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 Cursor as a fourth agent target (#1457)

Raghav Chamadiya599277b3f9c2
diff --git a/README.md b/README.md
index 45ad39b06..550d4c145 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
-**Three agents wired end to end · two at the Full tier · every other MCP host one
+**Four agents wired end to end · two at the Full tier · every other MCP host one
paste away.**
<p>
@@ -379,6 +379,7 @@ paste away.**
<p>
<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" />
</p>
**Full** is every surface repowise has: MCP tools, skills, slash commands, a managed
@@ -390,8 +391,8 @@ computed from what each integration actually wires, so this list cannot claim a
the code does not have.
Everything else that speaks MCP is one snippet away. `repowise agents print-config
-claude-code` prints a stdio server entry to paste into Cursor, Cline, Windsurf, Zed,
-Gemini CLI or any other host that keys on `mcpServers`, and repowise writes nothing.
+claude-code` prints a stdio server entry to paste into Cline, Windsurf, Zed, Gemini
+CLI or any other host that keys on `mcpServers`, and repowise writes nothing.
Adding an agent takes **one descriptor file and one registry line**, with no changes to
the orchestrators. Full matrix and the contributor recipe:
diff --git a/docs/agent/INTEGRATIONS.md b/docs/agent/INTEGRATIONS.md
index 7758f0ee0..2a3ada540 100644
--- a/docs/agent/INTEGRATIONS.md
+++ b/docs/agent/INTEGRATIONS.md
@@ -28,12 +28,13 @@ for that agent.
| [Claude Code](https://docs.claude.com/en/docs/claude-code) | Full | Yes | Yes | Plugin | Plugin | Yes | Yes |
| [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 |
-Target ids for `--target=`: `claude-code`, `codex`, `vscode`.
+Target ids for `--target=`: `claude-code`, `codex`, `vscode`, `cursor`.
### What Good tier does not include
-VS Code sits at Good, and the honest version of that is worth stating
+VS Code and Cursor 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
@@ -53,14 +54,15 @@ the server entry and paste it into whatever config that host reads:
repowise agents print-config claude-code # prints, writes nothing
```
-That emits an `mcpServers` block, which is the shape Cursor, Cline, Windsurf,
-Zed and most others read. Ask for `vscode` instead when the host follows VS
-Code: that one keys on `servers` and adds a `type` field inside each entry, so
-it is not the same text with a different wrapper. Print the one that matches
-your host rather than editing either by hand. Hosts people ask about most,
-none of which repowise writes config for today:
+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:
-Cursor, Cline, Windsurf, Zed, Continue, Gemini CLI, OpenCode, JetBrains AI Assistant, Amp.
+Cline, Windsurf, Zed, Continue, Gemini CLI, OpenCode, 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/start/QUICKSTART.md b/docs/start/QUICKSTART.md
index 08e49dc4b..335c88115 100644
--- a/docs/start/QUICKSTART.md
+++ b/docs/start/QUICKSTART.md
@@ -125,13 +125,26 @@ args = ["mcp"]
[Codex integration](../agent/CODEX.md).
</details>
-<details><summary><b>Cursor, Cline, Windsurf, and other MCP clients</b></summary>
+<details><summary><b>Cursor</b></summary>
-Point the client at `repowise mcp`, run from the repo directory, over stdio:
+```bash
+repowise agents add --target=cursor
+```
+
+Writes project-local `.cursor/mcp.json` and a managed `.cursor/rules/repowise.mdc`.
+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>Cline, Windsurf, and other MCP clients</b></summary>
+
+Print the server entry and paste it into whatever config the host reads:
```bash
-repowise mcp --transport stdio
+repowise agents print-config claude-code
```
+
+Or point the client at `repowise mcp`, run from the repo directory, over stdio.
</details>
<details><summary><b>VS Code</b></summary>
diff --git a/packages/cli/src/repowise/cli/agent_targets/formats/__init__.py b/packages/cli/src/repowise/cli/agent_targets/formats/__init__.py
index 98fa5e32a..11fbbd816 100644
--- a/packages/cli/src/repowise/cli/agent_targets/formats/__init__.py
+++ b/packages/cli/src/repowise/cli/agent_targets/formats/__init__.py
@@ -4,5 +4,5 @@ Kept deliberately small and free of per-agent knowledge. The targets differ
enough — JSON versus TOML versus marker-delimited markdown, and different
idempotency markers within each — that a shared base class would force an
awkward shape on all of them; composition lets each take only the mechanics it
-needs. codegraph reached the same conclusion for the same reason.
+needs.
"""
diff --git a/packages/cli/src/repowise/cli/agent_targets/formats/marker_block.py b/packages/cli/src/repowise/cli/agent_targets/formats/marker_block.py
index b2affdbea..be7f14550 100644
--- a/packages/cli/src/repowise/cli/agent_targets/formats/marker_block.py
+++ b/packages/cli/src/repowise/cli/agent_targets/formats/marker_block.py
@@ -43,6 +43,11 @@ class BlockState(StrEnum):
DUPLICATED = "duplicated"
#: A start without its end, or an end without its start.
ORPHANED = "orphaned"
+ #: The file is there and we could not read it, so we do not know what is in
+ #: it. Distinct from :attr:`ABSENT_FILE` because the two lead to opposite
+ #: actions: an absent file is created, and a file whose contents are unknown
+ #: must be left strictly alone.
+ UNREADABLE = "unreadable"
@dataclass(frozen=True)
@@ -58,8 +63,19 @@ def inspect(path: Path, start: str, end: str) -> BlockInspection:
return BlockInspection(BlockState.ABSENT_FILE)
try:
content = path.read_text(encoding="utf-8")
- except OSError:
- return BlockInspection(BlockState.ABSENT_FILE)
+ except (OSError, ValueError):
+ # ``ValueError`` is here for ``UnicodeDecodeError``, which is a subclass
+ # of it and not of ``OSError``. A rule or instructions file saved in
+ # cp1252 is an ordinary thing to meet on Windows, and it used to escape
+ # this handler entirely and traceback out of ``install`` after other
+ # agents' configs had already been written.
+ #
+ # Reporting it as ABSENT_FILE, which is what an ``OSError`` used to get,
+ # is the worse half of the same bug: a decode failure does not stop the
+ # *write*, so ``upsert`` would have replaced a file it could not read.
+ # ``codex.py::_current_prompt_text`` catches the same pair for the same
+ # reason.
+ return BlockInspection(BlockState.UNREADABLE)
starts = content.count(start)
ends = content.count(end)
@@ -102,9 +118,10 @@ def upsert(
contain either, and the failure mode is a corrupted managed block or a
``bad escape`` crash at install time.
- **A malformed marker pair returns** :attr:`~..types.FileAction.KEPT` **and
- writes nothing.** Both malformed states mean a user edited across one of our
- markers, and for both, every available repair can destroy text:
+ **A malformed marker pair, or a file we could not read, returns**
+ :attr:`~..types.FileAction.KEPT` **and writes nothing.** The two malformed
+ states mean a user edited across one of our markers, and for both, every
+ available repair can destroy text:
* An **orphan** — a start with no end. Appending a fresh block leaves the
stray start above it, so the next run's non-greedy ``start.*?end`` spans
@@ -121,11 +138,15 @@ def upsert(
So both are refused, and the caller surfaces it as something to unpick by
hand. What this fixes relative to that hand-rolled writer is the *silence*:
an orphan used to report "unchanged" while the block was in fact absent.
+
+ :attr:`~.BlockState.UNREADABLE` is refused for a different reason. A decode
+ failure stops the read and not the write, so treating it as an absent file
+ would replace content we never saw.
"""
wrapped = f"{start}{body}{end}"
inspection = inspect(path, start, end)
- if inspection.state in (BlockState.ORPHANED, BlockState.DUPLICATED):
+ if inspection.state in (BlockState.ORPHANED, BlockState.DUPLICATED, BlockState.UNREADABLE):
return FileAction.KEPT
if inspection.state is BlockState.ABSENT_FILE:
@@ -169,13 +190,16 @@ def remove(path: Path, start: str, end: str, *, delete_if_only: str | None = Non
Returns True when something was removed.
"""
inspection = inspect(path, start, end)
- if inspection.state in (BlockState.ORPHANED, BlockState.DUPLICATED):
- return False
- if inspection.state in (BlockState.ABSENT_FILE, BlockState.ABSENT):
+ if inspection.state is not BlockState.PRESENT:
+ # PRESENT is the only state with a block to strip. Every other one is
+ # either nothing to do (absent) or something we must not touch (a
+ # malformed pair, a file we could not read), and enumerating the
+ # refusals by name let UNREADABLE fall through the gap when it was
+ # added.
return False
try:
existing = path.read_text(encoding="utf-8")
- except OSError:
+ except (OSError, ValueError):
return False
pattern = r"\n*" + re.escape(start) + r".*?" + re.escape(end) + r"\n?"
diff --git a/packages/cli/src/repowise/cli/agent_targets/formats/toml_merge.py b/packages/cli/src/repowise/cli/agent_targets/formats/toml_merge.py
index efbaca917..59acfad2f 100644
--- a/packages/cli/src/repowise/cli/agent_targets/formats/toml_merge.py
+++ b/packages/cli/src/repowise/cli/agent_targets/formats/toml_merge.py
@@ -2,9 +2,8 @@
Absorbed from ``mcp_config``. It is not a general TOML serializer and should
not become one: it handles the value types our tables actually contain, and
-raises on anything else rather than guessing at an encoding. codegraph made the
-same call for the same reason — 254 lines serving one target beats a dependency
-whose failure modes you inherit.
+raises on anything else rather than guessing at an encoding. A couple of hundred
+lines serving one target beats a dependency whose failure modes you inherit.
The merge strategy is regex table replacement over the *source text*, not a
parse-and-reserialize. That is what preserves the user's comments, key order and
diff --git a/packages/cli/src/repowise/cli/agent_targets/instructions.py b/packages/cli/src/repowise/cli/agent_targets/instructions.py
new file mode 100644
index 000000000..3374ac757
--- /dev/null
+++ b/packages/cli/src/repowise/cli/agent_targets/instructions.py
@@ -0,0 +1,38 @@
+"""The managed instruction block, shared by every host that reads one.
+
+Text only. No imports, and nothing that reads the filesystem, because this is
+reachable from ``codex_config`` which sits behind the self-heal path that runs on
+every CLI invocation.
+
+The block itself is written by :mod:`.formats.marker_block`; what lives here is
+the *content*, in one place. It used to live inside ``codex_config`` as a private
+constant, which was correct while ``AGENTS.md`` was the only file carrying it.
+Cursor's ``.cursor/rules/*.mdc`` is the second, and a second copy of this prose
+is how the plugin skills forked: the two drift a sentence at a time and nothing
+detects it.
+
+Hosts differ in how the block is *framed* — Codex appends it to a file the user
+owns, Cursor gets a file repowise creates outright with YAML frontmatter on top —
+so the framing stays with each target and only the body is shared.
+"""
+
+from __future__ import annotations
+
+#: Markers delimiting the section repowise owns. Everything outside them is the
+#: user's and round-trips byte for byte.
+DISTILL_MARKER_START = (
+ "<!-- REPOWISE_DISTILL:START — Do not edit below this line. Auto-generated by Repowise. -->"
+)
+DISTILL_MARKER_END = "<!-- REPOWISE_DISTILL:END -->"
+
+#: Heading inside the block. Also the probe for "this file already teaches
+#: distillation somewhere else", which is why it is a constant rather than
+#: inlined into the section text.
+DISTILL_SECTION_HEADING = "### Output Distillation"
+
+DISTILL_SECTION = f"""{DISTILL_SECTION_HEADING}
+
+- Prefer `repowise distill <cmd>` for noisy commands — test runs, builds, `git status`/`log`/`diff`, searches, file listings. It runs the command unchanged (exit code preserved) and prints a compact, errors-first rendering; every error line survives.
+- Output may contain a marker like `[repowise#a1b2c3d4e5f6: 230 lines omitted (~6.1k tokens); restore: repowise expand a1b2c3d4e5f6]`. The omitted content is fully preserved — run `repowise expand <ref>` to retrieve it, or `repowise expand <ref> -q <regex>` for just the matching lines.
+- Never re-run a command to see omitted output; expand the marker instead.
+- For structure-level questions about a large indexed file ("what's in here", "which function handles X"), `get_context(["path"], include=["skeleton"])` returns the file with bodies elided — every signature plus the bodies of the most central symbols — at a fraction of the cost of a full Read."""
diff --git a/packages/cli/src/repowise/cli/agent_targets/registry.py b/packages/cli/src/repowise/cli/agent_targets/registry.py
index 7c7d685c7..d83175988 100644
--- a/packages/cli/src/repowise/cli/agent_targets/registry.py
+++ b/packages/cli/src/repowise/cli/agent_targets/registry.py
@@ -9,10 +9,10 @@ mirroring the hook-adapter registry. Registration should cost nothing: a caller
resolving one target must not pay the import of every other, and this module is
reachable from ``init`` and ``doctor`` where startup time is visible.
-One deviation from codegraph, deliberate: their ``TargetId`` is a hand-written
-string union, so adding a target touches three files instead of two and the
-union can drift from the registry. Here the ids *are* the registry keys, so
-there is nothing to keep in sync.
+There is deliberately no hand-written ``TargetId`` union beside this map. A
+literal type listing the ids is the obvious companion and it is a third file to
+keep in sync, which means it can drift from the registry it describes. Here the
+ids *are* the registry keys, so there is nothing to synchronise.
"""
from __future__ import annotations
@@ -28,6 +28,7 @@ _TARGET_MODULES: dict[str, str] = {
"claude-code": "repowise.cli.agent_targets.targets.claude_code:TARGET",
"codex": "repowise.cli.agent_targets.targets.codex:TARGET",
"vscode": "repowise.cli.agent_targets.targets.vscode:TARGET",
+ "cursor": "repowise.cli.agent_targets.targets.cursor:TARGET",
}
#: Resolved when :meth:`resolve_target_flag` is asked for ``auto`` and nothing
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 886f7e379..38fcf3e4f 100644
--- a/packages/cli/src/repowise/cli/agent_targets/targets/codex.py
+++ b/packages/cli/src/repowise/cli/agent_targets/targets/codex.py
@@ -577,10 +577,25 @@ class CodexTarget:
if repo_path is None:
raise ValueError("project-scope uninstall needs a repo_path")
- removed = remove_agents_md_distill_section(repo_path)
+ instructions = instructions_path(repo_path)
+ if remove_agents_md_distill_section(repo_path):
+ result.record(instructions, FileAction.REMOVED)
+ return result
+
+ # The removal returns False for four different reasons, and reporting
+ # 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
+
+ state = inspect(instructions, DISTILL_MARKER_START, DISTILL_MARKER_END).state
result.record(
- instructions_path(repo_path),
- FileAction.REMOVED if removed else FileAction.NOT_FOUND,
+ instructions,
+ FileAction.NOT_FOUND
+ if state in (BlockState.ABSENT_FILE, BlockState.ABSENT)
+ else FileAction.KEPT,
)
return result
diff --git a/packages/cli/src/repowise/cli/agent_targets/targets/cursor.py b/packages/cli/src/repowise/cli/agent_targets/targets/cursor.py
new file mode 100644
index 000000000..49223f623
--- /dev/null
+++ b/packages/cli/src/repowise/cli/agent_targets/targets/cursor.py
@@ -0,0 +1,472 @@
+"""Cursor 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. Cursor exposes no hook protocol repowise can intercept tool calls
+through, and no transcript format to mine.
+
+Cursor is **not** a flag on the VS Code target despite the fork lineage. It does
+not read ``.vscode/mcp.json``; it reads ``.cursor/mcp.json``, and the two files
+disagree about their top-level key (``mcpServers`` against ``servers``). There is
+also no provider API for an extension to register a server through, which is what
+the VS Code extension uses.
+
+Two host facts this target is built on, both re-checked against Cursor's own
+documentation on 2026-08-12 rather than inherited:
+
+* ``.cursor/mcp.json`` keys servers under ``mcpServers`` and **requires** a
+ ``type`` field for stdio servers. That last part is the one worth pinning: it
+ is the single difference between this file and the repo-shared ``.mcp.json``,
+ and the shape most likely to be "simplified" back out.
+* ``.cursor/rules/*.mdc`` takes YAML frontmatter, and ``alwaysApply: true`` loads
+ the rule in every conversation with ``description`` and ``globs`` ignored. So
+ the frontmatter here is one key, matching the host's own minimal example,
+ rather than three of which two do nothing.
+
+**The working-directory quirk, and why it costs us nothing.** Cursor launches MCP
+subprocesses with a working directory that is not the workspace root, and does
+not pass ``rootUri`` in the MCP ``initialize`` call. A server that resolves its
+repo from ``cwd`` therefore looks at the wrong tree and reports "not indexed" on
+every call. repowise is unaffected only because its registration already carries
+the absolute repo path positionally (``repowise mcp <abs-path>``), which the
+shared generator has always emitted. That is a load-bearing accident, so
+``test_agent_targets`` pins it: if the generator ever drops the positional path,
+this target breaks in a way that looks like an indexing bug.
+
+**Project scope only.** Cursor does read ``~/.cursor/mcp.json``, but one global
+entry can only name one repo, and the workaround for that is a
+``${workspaceFolder}`` token repowise cannot verify Cursor expands inside an
+argument array. Writing a user-scope entry that silently points every workspace
+at one repo is worse than not writing one, and ``print_config`` covers the person
+who wants to paste it themselves.
+"""
+
+from __future__ import annotations
+
+import contextlib
+import json
+from pathlib import Path
+
+from ..types import (
+ Capability,
+ DoctorReport,
+ DoctorStatus,
+ FileAction,
+ FileWrite,
+ InstallMethod,
+ Registration,
+ Scope,
+ WriteResult,
+)
+
+ID = "cursor"
+DISPLAY_NAME = "Cursor"
+DOCS_URL = "https://cursor.com/docs/context/mcp"
+
+#: Config key gating this agent's managed rules file.
+PROJECT_FILE_ID = "cursor_rules"
+
+METHODS = (
+ InstallMethod(
+ id="direct",
+ provides=frozenset({Capability.MCP, Capability.INSTRUCTIONS}),
+ managed_by="repowise",
+ preferred=True,
+ ),
+)
+
+#: Frontmatter plus the note, written above the managed block when repowise
+#: creates the file. One key, because ``alwaysApply: true`` makes the host ignore
+#: ``description`` and ``globs``, and a key the host ignores is noise a reader has
+#: to evaluate.
+#:
+#: Paired with ``marker_block.remove(delete_if_only=...)`` so install then
+#: uninstall round-trips back to "no file" rather than leaving a stub carrying
+#: nothing but our own frontmatter — which would still read as repowise-managed
+#: to anyone who opened it.
+RULES_PREFIX = (
+ "---\n"
+ "alwaysApply: true\n"
+ "---\n"
+ "\n"
+ "<!-- Add your own Cursor rules above or below the Repowise section. "
+ "Repowise only updates the managed section between markers. -->\n"
+)
+
+
+class RemoteServerEntryError(ValueError):
+ """The stored ``repowise`` 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) -> bool:
+ """Whether a stored server entry describes a transport repowise did not write.
+
+ The entry's own ``type`` decides, and a bare ``url`` only counts when there
+ is no ``command`` beside it. Reading ``"url" in entry`` on its own, ahead of
+ the declared type, calls ``{"type": "stdio", "command": ..., "url": ...}``
+ remote and contradicts what the entry says about itself. A leftover ``url``
+ on a local entry is exactly the stale state ``agents add`` exists to
+ repoint, and treating it as remote wedged it shut against every command
+ that could have fixed it.
+ """
+ declared = entry.get("type")
+ if declared is not None:
+ return declared != "stdio"
+ return "url" in entry and "command" not in entry
+
+
+def mcp_config_path(repo_path: Path) -> Path:
+ return repo_path / ".cursor" / "mcp.json"
+
+
+def rules_path(repo_path: Path) -> Path:
+ return repo_path / ".cursor" / "rules" / "repowise.mdc"
+
+
+def server_entry(repo_path: Path) -> dict:
+ """The ``.cursor/mcp.json`` server entry.
+
+ Command and args come from the shared generator, so this resolves the same
+ server as the committed ``.mcp.json`` on every contributor's checkout. The
+ ``type`` field is added because Cursor documents it as required for stdio
+ servers; the repo-shared file does not carry one and does not need one.
+ """
+ from repowise.cli.mcp_config import generate_mcp_config
+
+ entry = generate_mcp_config(repo_path)["mcpServers"]["repowise"]
+ return {"type": "stdio", **entry}
+
+
+def write_mcp_config(repo_path: Path) -> FileWrite:
+ """Merge the repowise server into ``.cursor/mcp.json``.
+
+ Raises ``ValueError`` when the existing file is not strict JSON, so the
+ caller can skip rather than destroy it. Cursor does not document comment
+ support here, but the cost of being wrong is asymmetric: declining leaves a
+ working config untouched and prints what to add, while rewriting a file we
+ misparsed deletes whatever we could not read.
+ """
+ from ..formats.json_merge import (
+ load_json_object_or_value_error,
+ merge_server_entries,
+ write_json_config,
+ )
+
+ config_path = mcp_config_path(repo_path)
+ new_entry = {"repowise": server_entry(repo_path)}
+
+ if config_path.exists():
+ existing = load_json_object_or_value_error(config_path, "mcp.json")
+ servers = existing.get("mcpServers", {})
+ if not isinstance(servers, dict):
+ raise ValueError("mcp.json 'mcpServers' must be a JSON object")
+ servers = dict(servers)
+ stored = servers.get("repowise")
+ if isinstance(stored, dict) and _is_remote_entry(stored):
+ # ``merge_server_entries`` keeps every key the user added and lets
+ # the generated ones win, which is right for ``command`` and
+ # ``args`` and wrong for ``type``. Against a hand-wired remote
+ # server it forces ``type`` back to ``stdio`` 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 it broken rather than merely
+ # overwritten.
+ #
+ # A remote entry is a deliberate choice repowise did not make, so
+ # the honest answer is to leave it and say so.
+ raise RemoteServerEntryError("mcp.json 'repowise' is wired to a remote server")
+ merge_server_entries(servers, new_entry)
+ existing["mcpServers"] = servers
+ merged = existing
+ else:
+ config_path.parent.mkdir(parents=True, exist_ok=True)
+ merged = {"mcpServers": new_entry}
+
+ return FileWrite(path=config_path, action=write_json_config(config_path, merged))
+
+
+def write_rules_file(repo_path: Path) -> FileWrite:
+ """Upsert the managed block into ``.cursor/rules/repowise.mdc``.
+
+ The first caller of the marker-block helper against a file repowise creates
+ *outright*, frontmatter and all, rather than one the user already owns. The
+ helper covers that with ``new_file_prefix``, so the only thing this adds is
+ the directory: ``atomic_write_text`` deliberately creates no parents, and
+ ``.cursor/rules/`` will not exist on a machine that has never written a rule.
+ """
+ from ..formats import marker_block
+ from ..instructions import DISTILL_MARKER_END, DISTILL_MARKER_START, DISTILL_SECTION
+
+ config_path = rules_path(repo_path)
+ config_path.parent.mkdir(parents=True, exist_ok=True)
+ action = marker_block.upsert(
+ config_path,
+ f"\n{DISTILL_SECTION}\n",
+ DISTILL_MARKER_START,
+ DISTILL_MARKER_END,
+ new_file_prefix=RULES_PREFIX,
+ )
+ return FileWrite(path=config_path, action=action)
+
+
+def _remove_server_entry(config_path: Path) -> tuple[Path, FileAction]:
+ """Drop ``mcpServers.repowise``, preserving sibling servers."""
+ from ..formats.json_merge import load_json_object_or_value_error, write_json_config
+
+ if not config_path.exists():
+ return config_path, FileAction.NOT_FOUND
+ try:
+ existing = load_json_object_or_value_error(config_path, "mcp.json")
+ except ValueError:
+ # Same reason install declines: rewriting a file we could not parse
+ # destroys whatever we failed to read.
+ return config_path, FileAction.KEPT
+
+ servers = existing.get("mcpServers")
+ if not isinstance(servers, dict) or "repowise" not in servers:
+ return config_path, FileAction.NOT_FOUND
+ servers.pop("repowise")
+
+ # Drop the wrapper once it is empty, and the file once *it* is empty, so an
+ # install followed by an uninstall leaves no trace. A `.cursor/mcp.json`
+ # holding `{"mcpServers": {}}` is a file we created, that the user did not
+ # ask for, and that still reads as repowise having been here.
+ if not servers:
+ existing.pop("mcpServers", None)
+ if not existing:
+ try:
+ config_path.unlink()
+ except OSError:
+ # Suppressing this reported REMOVED for a file still holding our
+ # entry, which is a false success on the destructive verb and one
+ # a read-only bit is enough to cause. Falling through to the
+ # rewrite keeps the loud failure the previous code had, from the
+ # same `os.replace` it used.
+ write_json_config(config_path, existing)
+ return config_path, FileAction.REMOVED
+
+ write_json_config(config_path, existing)
+ return config_path, FileAction.REMOVED
+
+
+def _remove_rules_file(repo_path: Path) -> tuple[Path, FileAction]:
+ """Strip the managed block, deleting the file if it held nothing else."""
+ from ..formats import marker_block
+ from ..formats.marker_block import BlockState
+ from ..instructions import DISTILL_MARKER_END, DISTILL_MARKER_START
+
+ config_path = rules_path(repo_path)
+ if marker_block.remove(
+ config_path,
+ DISTILL_MARKER_START,
+ DISTILL_MARKER_END,
+ delete_if_only=RULES_PREFIX,
+ ):
+ return config_path, FileAction.REMOVED
+
+ # ``remove`` returns False for four different reasons, and they do not mean
+ # the same thing to a reader of the output. "There was nothing of ours here"
+ # is not-found; "there is a file we deliberately did not touch" is kept.
+ # Asking ``exists()`` conflates them, because a rules file with none of our
+ # markers in it exists and is not ours.
+ state = marker_block.inspect(config_path, DISTILL_MARKER_START, DISTILL_MARKER_END).state
+ if state in (BlockState.ABSENT_FILE, BlockState.ABSENT):
+ return config_path, FileAction.NOT_FOUND
+ return config_path, FileAction.KEPT
+
+
+def _prune_empty_dirs(repo_path: Path) -> None:
+ """Remove ``.cursor/rules`` and ``.cursor`` when uninstall emptied them.
+
+ ``write_rules_file`` creates both, so leaving them is the directory-shaped
+ version of the stub file ``delete_if_only`` exists to prevent. It also has a
+ second-order effect worth naming: :meth:`CursorTarget.is_present` reads
+ ``.cursor/`` as evidence the user has Cursor, so our own leftovers would
+ keep the agent pre-ticked in every later listing and checklist, for a repo
+ it had just been removed from.
+
+ **Only called when uninstall actually removed a file**, which is the part
+ that is not optional. "``rmdir`` refuses a non-empty directory, so an empty
+ one must be ours" is the same shape of wrong assumption this module keeps
+ meeting: a user who made ``.cursor/`` by hand and left it empty would have
+ had it deleted by a remove that found nothing of ours to remove.
+
+ The symlink guard is the second half. ``rmdir`` does refuse a non-empty
+ *directory*, and a Windows directory junction is not one: it is a reparse
+ point, so ``rmdir`` unlinks it happily however full the target is. The
+ target survives and the link does not, which is a repo whose ``.cursor``
+ stopped resolving.
+ """
+ for candidate in (rules_path(repo_path).parent, repo_path / ".cursor"):
+ if candidate.is_symlink():
+ continue
+ with contextlib.suppress(OSError):
+ candidate.rmdir()
+
+
+def detect(repo_path: Path | None = None) -> list[Registration]:
+ """Whether the workspace MCP config names repowise.
+
+ Project scope only, matching what this target writes. Returning nothing for
+ an unparseable file is deliberate: it may well be wired up, and reporting
+ "not configured" would be a guess.
+ """
+ if repo_path is None:
+ return []
+ config_path = mcp_config_path(repo_path)
+ if not config_path.exists():
+ return []
+ try:
+ data = json.loads(config_path.read_text(encoding="utf-8"))
+ except (OSError, ValueError):
+ # ``ValueError`` covers ``json.JSONDecodeError`` and, separately,
+ # ``UnicodeDecodeError`` from a file that is not UTF-8. Naming
+ # JSONDecodeError alone let the decode failure escape a probe whose
+ # whole contract is that it never raises, and detection runs on paths
+ # (``resolve_target_flag``) that do not catch for it.
+ return []
+ servers = data.get("mcpServers")
+ if not isinstance(servers, dict) or "repowise" not in servers:
+ return []
+ return [Registration(method="direct", scope=Scope.PROJECT, config_path=config_path)]
+
+
+class CursorTarget:
+ """Descriptor for Cursor. 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:
+ """Project scope only. See the module docstring for why not user scope."""
+ return scope is Scope.PROJECT
+
+ def is_present(self, repo_path: Path | None = None) -> bool:
+ """A ``.cursor/`` in the repo, the ``cursor`` shim on PATH, or ``~/.cursor``.
+
+ The repo-local check earns its place for the same reason VS Code's does:
+ ``.cursor/`` is committed and read by whoever opens the repo next, so a
+ workspace carrying one is worth configuring even from a machine where
+ the editor was never installed.
+ """
+ import shutil
+
+ if repo_path is not None and (repo_path / ".cursor").is_dir():
+ return True
+ if shutil.which("cursor") is not None:
+ return True
+ return (Path.home() / ".cursor").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 not Scope.PROJECT:
+ return result
+ if repo_path is None:
+ raise ValueError("project-scope install needs a repo_path")
+
+ try:
+ written = write_mcp_config(repo_path)
+ result.record(written.path, written.action)
+ except RemoteServerEntryError:
+ result.record(mcp_config_path(repo_path), FileAction.KEPT)
+ result.note(
+ '.cursor/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=cursor' first if you "
+ "want the local server instead."
+ )
+ # ``OSError`` alongside ``ValueError`` because the read and the parent
+ # ``mkdir`` both live in there, and neither is exotic: ``.cursor`` can be
+ # a plain file, and a config in a shared checkout can be unreadable.
+ # Nothing wraps ``install`` — ``agents add``, ``agents refresh`` and
+ # ``doctor --repair`` all call it bare — so an escape here aborts the run
+ # after other agents' configs have already been written, and prints a
+ # traceback instead of the summary that would have said so.
+ except (ValueError, OSError) as exc:
+ result.record(mcp_config_path(repo_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: the
+ # generated entry is built inside the guarded call, so an OSError
+ # resolving the repo path lands here too, and a note that flatly
+ # says "not valid JSON" would send the user to inspect a file that
+ # is fine.
+ result.note(
+ f".cursor/mcp.json left unchanged ({exc}). Add a "
+ '"repowise" server under "mcpServers" manually.'
+ )
+
+ try:
+ written = write_rules_file(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 text,
+ # so say which file needs unpicking instead of reporting a write.
+ result.note(
+ f"{rules_path(repo_path).name} 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):
+ result.record(rules_path(repo_path), FileAction.KEPT)
+ result.note(".cursor/rules/repowise.mdc could not be written.")
+
+ return result
+
+ def uninstall(self, scope: Scope, *, repo_path: Path | None = None) -> WriteResult:
+ """Remove the server entry and the rules file, because install writes both."""
+ result = WriteResult()
+ if scope is not Scope.PROJECT or repo_path is None:
+ return result
+ result.record(*_remove_server_entry(mcp_config_path(repo_path)))
+ result.record(*_remove_rules_file(repo_path))
+ if any(written.action is FileAction.REMOVED for written in result.files):
+ _prune_empty_dirs(repo_path)
+ return result
+
+ def print_config(self, scope: Scope, *, repo_path: Path | None = None) -> str:
+ return json.dumps(
+ {"mcpServers": {"repowise": server_entry(repo_path or Path.cwd())}}, indent=2
+ )
+
+ def describe_paths(self, scope: Scope, *, repo_path: Path | None = None) -> list[str]:
+ if scope is not Scope.PROJECT:
+ return []
+ repo = repo_path or Path.cwd()
+ return [str(mcp_config_path(repo)), str(rules_path(repo))]
+
+ def doctor(self) -> DoctorReport:
+ """Health is repo-scoped, so a bare call can only report the honest answer.
+
+ Same shape as VS Code's, and for the same reason: ``doctor()`` takes no
+ repo path, and there is nothing user-level this target writes. Reporting
+ ``OK`` would be a claim nothing checked.
+ """
+ return DoctorReport(
+ target_id=ID,
+ status=DoctorStatus.NOT_INSTALLED,
+ issues=("Cursor wiring is workspace-local; run this from a repo to check it.",),
+ fix_command="repowise agents add --target=cursor",
+ )
+
+
+TARGET = CursorTarget()
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 ed7ca5871..f346d2137 100644
--- a/packages/cli/src/repowise/cli/agent_targets/targets/vscode.py
+++ b/packages/cli/src/repowise/cli/agent_targets/targets/vscode.py
@@ -183,9 +183,14 @@ def detect(repo_path: Path | None = None) -> list[Registration]:
return []
try:
data = json.loads(config_path.read_text(encoding="utf-8"))
- except (OSError, json.JSONDecodeError):
+ except (OSError, ValueError):
# A JSONC workspace file is unparseable here but may well be wired up.
# Reporting "not configured" would be a guess, so report nothing.
+ #
+ # ``ValueError`` rather than ``json.JSONDecodeError`` so a file that is
+ # not UTF-8 lands here too. It is a ``UnicodeDecodeError``, which is a
+ # ``ValueError`` and not a ``JSONDecodeError``, so it used to escape a
+ # probe contracted never to raise.
return []
servers = data.get("servers")
if not isinstance(servers, dict) or "repowise" not in servers:
@@ -241,23 +246,32 @@ class VSCodeTarget:
if repo_path is None:
raise ValueError("project-scope install needs a repo_path")
+ # ``OSError`` alongside ``ValueError`` because the read and the parent
+ # ``mkdir`` both live inside these writers, and neither failure is
+ # exotic: ``.vscode`` can be a plain file, and a config in a shared
+ # checkout can be unreadable. Nothing wraps ``install`` — ``agents
+ # add``, ``agents refresh`` and ``doctor --repair`` all call it bare —
+ # so an escape aborts the run after other agents' configs have already
+ # been written, and prints a traceback instead of the summary naming
+ # them.
try:
written = write_mcp_config(repo_path)
result.record(written.path, written.action)
- except ValueError:
+ except (ValueError, OSError):
result.record(mcp_config_path(repo_path), FileAction.KEPT)
result.note(
- ".vscode/mcp.json left unchanged (not valid JSON; it may contain "
- 'comments). Add a "repowise" server under "servers" manually.'
+ ".vscode/mcp.json left unchanged (unreadable, or not valid JSON; it "
+ 'may contain comments). Add a "repowise" server under "servers" manually.'
)
try:
written = write_extensions_config(repo_path)
result.record(written.path, written.action)
- except ValueError:
+ except (ValueError, OSError):
result.record(extensions_config_path(repo_path), FileAction.KEPT)
result.note(
- ".vscode/extensions.json left unchanged (not valid JSON; it may "
- f'contain comments). Add "{EXTENSION_ID}" to "recommendations" manually.'
+ ".vscode/extensions.json left unchanged (unreadable, or not valid JSON; "
+ f'it may contain comments). Add "{EXTENSION_ID}" to "recommendations" '
+ "manually."
)
return result
diff --git a/packages/cli/src/repowise/cli/agent_targets/types.py b/packages/cli/src/repowise/cli/agent_targets/types.py
index c77dbef14..c86f82df4 100644
--- a/packages/cli/src/repowise/cli/agent_targets/types.py
+++ b/packages/cli/src/repowise/cli/agent_targets/types.py
@@ -57,16 +57,16 @@ class Scope(StrEnum):
class FileAction(StrEnum):
"""What an install or uninstall did to one file.
- Taken from codegraph's installer, which reports one of these per file and
- renders a log line from it. ``UNCHANGED`` is the one that earns its keep:
- it means the file was inspected and already held exactly what we would
- write, which is what makes a re-run byte-identical and stops an idempotent
+ One per file, which is what lets an installer render a real per-file log
+ instead of a summary. ``UNCHANGED`` is the value that earns its keep: it
+ means the file was inspected and already held exactly what we would write,
+ which is what makes a re-run byte-identical and stops an idempotent
re-install from printing a misleading "updated".
- (The plan called this a 7-value enum; codegraph ships six, and six is what
- the actions actually are. Its marker-block helper has a seventh internal
- ``appended`` state, but it is folded into ``updated`` before it reaches a
- result, so it is not an action a caller can observe.)
+ Six values, not seven. Appending a managed block to a file that did not
+ carry one looks like a distinct action and is not: it is folded into
+ ``UPDATED`` before it reaches a result, because from the caller's side the
+ file existed and now differs.
"""
CREATED = "created"
@@ -108,9 +108,9 @@ class Tier(StrEnum):
class DoctorStatus(StrEnum):
"""The four states a target's health can be in.
- Borrowed from tokenjuice's instruction doctor, which is better than
- codegraph's two-state version for one reason: ``STALE`` is distinct from
- ``BROKEN``. A hook whose matcher names a tool the host has since renamed is
+ Four rather than the obvious two, for one reason: ``STALE`` has to be
+ distinct from ``BROKEN``. A hook whose matcher names a tool the host has
+ since renamed is
installed, parses fine, and will never fire — reporting that as "ok" is how
it stays invisible, and reporting it as "broken" sends the user to fix a
file that is not damaged.
@@ -255,11 +255,12 @@ class AgentTarget(Protocol):
"""One agent repowise can wire up.
Implementations compose the helpers in :mod:`.formats` rather than
- inheriting from a base class. codegraph states the rationale and our own
- evidence agrees: Codex needs TOML plus a hooks JSON, VS Code needs two JSON
- files one of which may carry comments, and a future Cursor target needs a
- frontmattered rules file. A base class would need an override hook for each
- and would force that shape on every target that does not want it.
+ inheriting from a base class. The targets differ too much for one to fit:
+ Codex needs TOML plus a hooks JSON, VS Code needs two JSON files one of
+ which may carry comments, and Cursor needs a JSON config plus a rules file
+ with YAML frontmatter that repowise creates outright. A base class would
+ need an override hook for each and would force that shape on every target
+ that does not want it.
Every method must be safe to call when nothing was ever installed.
"""
@@ -387,6 +388,14 @@ class InstallLifecycle(Protocol):
stops a fourth agent from meaning a fourth prompt in a fourth module.
"""
+ #: The :class:`AgentTarget` id this integration writes for. Declared here
+ #: because the checklist reads it to answer "can ``init`` act on this
+ #: agent", which is a question the registry alone cannot: a target can be
+ #: registered without ``init`` having a writer for it. Two of the three
+ #: implementations already carried it; the third did not, and the gap was
+ #: invisible until something asked all of them at once.
+ integration_id: str
+
def write_project_files(
self, console_obj: object, repo_path: Path, options: object
) -> None:
diff --git a/packages/cli/src/repowise/cli/editor_integrations/claude.py b/packages/cli/src/repowise/cli/editor_integrations/claude.py
index c21242571..507f01dd2 100644
--- a/packages/cli/src/repowise/cli/editor_integrations/claude.py
+++ b/packages/cli/src/repowise/cli/editor_integrations/claude.py
@@ -19,7 +19,8 @@ class ClaudeCodeSetup:
class drives.
"""
- #: Read from the descriptor rather than restated, so the id has one home.
+ #: Read from the descriptor rather than restated, so the ids have one home.
+ integration_id = claude_target.ID
project_file_id = claude_target.PROJECT_FILE_ID
def write_project_files(
diff --git a/packages/cli/src/repowise/cli/editor_integrations/codex_config.py b/packages/cli/src/repowise/cli/editor_integrations/codex_config.py
index f0c9d83f5..700e9e03c 100644
--- a/packages/cli/src/repowise/cli/editor_integrations/codex_config.py
+++ b/packages/cli/src/repowise/cli/editor_integrations/codex_config.py
@@ -30,6 +30,13 @@ from pathlib import Path
# its own imports are stdlib only.
from repowise.cli.agent_adapters.codex import SHELL_TOOL_MATCHER
+# Text only, no imports of its own. It does pull in the ``agent_targets``
+# package ``__init__`` (which re-exports ``types``), measured at 3.2ms marginal
+# once this module is loaded. That is paid on the self-heal path this module
+# sits behind, which the version stamp in ``cli.self_heal`` already reduces to
+# once per release, and on paths that import ``agent_targets`` regardless.
+from repowise.cli.agent_targets import instructions
+
#: First Codex release whose PreToolUse hooks honor an ``updatedInput``
#: command rewrite; earlier builds report it as an unsupported hook output.
CODEX_REWRITE_MIN_VERSION: tuple[int, int] = (0, 137)
@@ -277,19 +284,13 @@ def _has_rewrite_hook(hook_list: list) -> bool:
# "Output Distillation" block.
# ---------------------------------------------------------------------------
-_DISTILL_MARKER_START = (
- "<!-- REPOWISE_DISTILL:START — Do not edit below this line. Auto-generated by Repowise. -->"
-)
-_DISTILL_MARKER_END = "<!-- REPOWISE_DISTILL:END -->"
-
-_DISTILL_SECTION_HEADING = "### Output Distillation"
-
-_DISTILL_SECTION = f"""{_DISTILL_SECTION_HEADING}
-
-- Prefer `repowise distill <cmd>` for noisy commands — test runs, builds, `git status`/`log`/`diff`, searches, file listings. It runs the command unchanged (exit code preserved) and prints a compact, errors-first rendering; every error line survives.
-- Output may contain a marker like `[repowise#a1b2c3d4e5f6: 230 lines omitted (~6.1k tokens); restore: repowise expand a1b2c3d4e5f6]`. The omitted content is fully preserved — run `repowise expand <ref>` to retrieve it, or `repowise expand <ref> -q <regex>` for just the matching lines.
-- Never re-run a command to see omitted output; expand the marker instead.
-- For structure-level questions about a large indexed file ("what's in here", "which function handles X"), `get_context(["path"], include=["skeleton"])` returns the file with bodies elided — every signature plus the bodies of the most central symbols — at a fraction of the cost of a full Read."""
+# The section text is shared with every other host that carries a managed
+# instruction block, so it has one home. The framing around it stays per host:
+# this one appends to a file the user owns.
+_DISTILL_MARKER_START = instructions.DISTILL_MARKER_START
+_DISTILL_MARKER_END = instructions.DISTILL_MARKER_END
+_DISTILL_SECTION_HEADING = instructions.DISTILL_SECTION_HEADING
+_DISTILL_SECTION = instructions.DISTILL_SECTION
_NEW_FILE_PLACEHOLDER = (
"# AGENTS.md\n\n"
@@ -337,7 +338,11 @@ def install_agents_md_distill_section(repo_path: Path) -> Path | None:
new_file_prefix=_NEW_FILE_PLACEHOLDER,
)
return None if action is FileAction.KEPT else target
- except OSError:
+ except (OSError, ValueError):
+ # ``ValueError`` for ``UnicodeDecodeError``: the read three lines above
+ # happens here rather than in the marker helper, so the helper's own
+ # refusal of an unreadable file never gets the chance to run and the
+ # decode escaped straight out of ``hook rewrite install``.
return None
@@ -363,5 +368,8 @@ def agents_md_distill_section_installed(repo_path: Path) -> bool:
target = _agents_md_path(repo_path)
try:
return target.exists() and _DISTILL_MARKER_START in target.read_text(encoding="utf-8")
- except OSError:
+ except (OSError, ValueError):
+ # Same reason as the installer above, on the path ``hook rewrite
+ # status`` calls. A file we cannot decode does not carry our section as
+ # far as anyone can tell, and a status probe must not raise.
return False
diff --git a/packages/cli/src/repowise/cli/editor_setup.py b/packages/cli/src/repowise/cli/editor_setup.py
index 78a0a327c..c0cd8aadb 100644
--- a/packages/cli/src/repowise/cli/editor_setup.py
+++ b/packages/cli/src/repowise/cli/editor_setup.py
@@ -224,7 +224,26 @@ def select_agents_interactively(
from repowise.cli.agent_targets.registry import default_selection, describe_agents
from repowise.cli.ui.agent_selection import AgentChoice, interactive_agent_select
+ # Offer only what this command can act on. The checklist is built from the
+ # agent registry and the writing is done by the setup integrations, and
+ # those are two lists: an agent can be registered (so it gets a matrix row,
+ # a ``--target`` id and a ``doctor`` row) without ``init`` having a writer
+ # for it. Showing the rest turns a ticked box into a silent no-op, which
+ # reads as success because every agent that *was* written prints a line.
+ #
+ # ``repowise agents add --target=<id>`` is the command for those, and the
+ # line below names it rather than leaving them invisible.
rows = describe_agents(repo_path)
+ installable = {integration.integration_id for integration in _resolve_integrations(None)}
+ deferred = [row for row in rows if row["id"] not in installable]
+ rows = [row for row in rows if row["id"] in installable]
+ for row in deferred:
+ if row["present"] or row["registrations"]:
+ console_obj.print(
+ f" [dim]{row['display_name']} detected. Set it up with "
+ f"[bold]repowise agents add --target={row['id']}[/bold][/dim]"
+ )
+
ticked = default_selection(rows)
for row in rows:
flagged = options.integration_overrides.get(row["id"])
diff --git a/packages/cli/src/repowise/cli/hooks.py b/packages/cli/src/repowise/cli/hooks.py
index b768fd3d9..9de084ab4 100644
--- a/packages/cli/src/repowise/cli/hooks.py
+++ b/packages/cli/src/repowise/cli/hooks.py
@@ -4,7 +4,7 @@ Installs/uninstalls a post-commit hook that runs ``repowise update`` in the
background after every commit, keeping the wiki in sync automatically.
The hook uses start/end markers so it can safely coexist with other hooks
-in the same file (e.g. lint hooks, graphify hooks).
+in the same file (a lint hook, another tool's index hook).
"""
from __future__ import annotations
diff --git a/scripts/gen_agent_matrix.py b/scripts/gen_agent_matrix.py
index 54c9ba94c..2a292ecf9 100644
--- a/scripts/gen_agent_matrix.py
+++ b/scripts/gen_agent_matrix.py
@@ -55,7 +55,6 @@ for _pkg in ("cli", "core", "server"):
#: that nothing here collides with a registered target, so promoting one of
#: these to a real integration and forgetting to delete the line is caught.
PASTE_CONFIG_HOSTS: tuple[str, ...] = (
- "Cursor",
"Cline",
"Windsurf",
"Zed",
@@ -267,6 +266,19 @@ def _matrix_table(rows: list[dict]) -> str:
return "\n".join(lines)
+def _join_names(names: list[str]) -> str:
+ """``A``, ``A and B``, ``A, B and C`` — a real list, at any length.
+
+ The first version of this handled one name and read as a grammar error at
+ two ("VS Code and Cursor sits at Good"), which is the shape of drift a
+ generated document is supposed to make impossible. Verb agreement is the
+ caller's, because only it knows whether the sentence needs one.
+ """
+ if len(names) < 3:
+ return " and ".join(names)
+ return ", ".join(names[:-1]) + f" and {names[-1]}"
+
+
def _tier_list() -> str:
return "\n".join(
f"- **{title}.** {body}" for title, body in (TIER_BLURBS[key] for key in TIER_BLURBS)
@@ -310,11 +322,11 @@ def render() -> str:
]
if good:
- names = " and ".join(good) if len(good) < 3 else ", ".join(good)
parts += [
"### What Good tier does not include",
"",
- f"{names} sits at Good, and the honest version of that is worth stating",
+ f"{_join_names(good)} {'sits' if len(good) == 1 else '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",
@@ -337,12 +349,13 @@ def render() -> str:
"repowise agents print-config claude-code # prints, writes nothing",
"```",
"",
- "That emits an `mcpServers` block, which is the shape Cursor, Cline, Windsurf,",
- "Zed and most others read. Ask for `vscode` instead when the host follows VS",
- "Code: that one keys on `servers` and adds a `type` field inside each entry, so",
- "it is not the same text with a different wrapper. Print the one that matches",
- "your host rather than editing either by hand. Hosts people ask about most,",
- "none of which repowise writes config for today:",
+ "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:",
"",
", ".join(PASTE_CONFIG_HOSTS) + ".",
"",
diff --git a/tests/unit/cli/test_agent_targets.py b/tests/unit/cli/test_agent_targets.py
index bbc2bc8d0..6bdfeaa4a 100644
--- a/tests/unit/cli/test_agent_targets.py
+++ b/tests/unit/cli/test_agent_targets.py
@@ -41,8 +41,13 @@ ALL_IDS = list_target_ids()
# ---------------------------------------------------------------------------
-def test_registry_exposes_the_three_shipped_targets() -> None:
- assert ALL_IDS == ["claude-code", "codex", "vscode"]
+def test_registry_exposes_the_shipped_targets() -> None:
+ """A frozen list, so adding a target is a deliberate edit rather than a side effect.
+
+ 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"]
@pytest.mark.parametrize("target_id", ALL_IDS)
@@ -70,9 +75,9 @@ def test_resolve_target_flag_handles_the_four_forms(tmp_path: Path) -> None:
def test_unknown_target_flag_names_the_known_ids(tmp_path: Path) -> None:
"""A typo must not silently resolve to nothing and report success."""
with pytest.raises(ValueError) as excinfo:
- resolve_target_flag("cursor,codex", tmp_path)
+ resolve_target_flag("emacs,codex", tmp_path)
message = str(excinfo.value)
- assert "cursor" in message
+ assert "emacs" in message
for target_id in ALL_IDS:
assert target_id in message
assert "auto" in message
@@ -118,6 +123,7 @@ def test_tiers_are_derived_from_the_adapters_a_target_names() -> None:
assert tier_of("claude-code") is Tier.FULL
assert tier_of("codex") is Tier.FULL
assert tier_of("vscode") is Tier.GOOD
+ assert tier_of("cursor") is Tier.GOOD
def test_a_target_cannot_reach_full_without_a_session_adapter() -> None:
@@ -230,6 +236,463 @@ def test_vscode_declines_user_scope() -> None:
assert not get_target("vscode").supports_scope(Scope.USER)
+def test_cursor_declines_user_scope() -> None:
+ """One global entry can only name one repo, so this target does not write one."""
+ assert get_target("cursor").supports_scope(Scope.PROJECT)
+ assert not get_target("cursor").supports_scope(Scope.USER)
+
+
+def test_cursor_writes_its_own_config_key_not_vs_codes() -> None:
+ """The two files disagree, and Cursor does not read ``.vscode/mcp.json``.
+
+ ``mcpServers`` against ``servers`` is the whole reason this is a separate
+ target rather than a flag on the VS Code one, so it is pinned rather than
+ left to the reader of the descriptor.
+ """
+ from repowise.cli.agent_targets.targets import cursor as cursor_target
+
+ repo = Path.cwd()
+ written = json.loads(cursor_target.TARGET.print_config(Scope.PROJECT, repo_path=repo))
+
+ assert set(written) == {"mcpServers"}
+ assert "repowise" in written["mcpServers"]
+ # Cursor documents ``type`` as required for stdio servers. It is the one
+ # field that differs from the repo-shared ``.mcp.json``, and the one most
+ # likely to be tidied away as redundant.
+ assert written["mcpServers"]["repowise"]["type"] == "stdio"
+
+
+def test_cursors_registration_carries_the_repo_path_positionally(tmp_path: Path) -> None:
+ """The load-bearing accident that makes Cursor work without a special case.
+
+ Cursor launches MCP subprocesses with a working directory that is not the
+ workspace root and passes no ``rootUri``, so a server resolving its repo from
+ ``cwd`` reads the wrong tree and reports "not indexed" on every call. repowise
+ is unaffected only because the shared generator emits the absolute repo path
+ as a positional argument. Nothing else forces that to stay true, and the
+ failure it would cause looks like an indexing bug rather than a config one.
+ """
+ from repowise.cli.agent_targets.targets import cursor as cursor_target
+
+ repo = tmp_path / "repo"
+ repo.mkdir()
+ args = cursor_target.server_entry(repo)["args"]
+
+ assert str(repo.resolve()).replace("\\", "/") in args
+
+
+def test_cursor_rules_file_round_trips_to_no_file(tmp_path: Path) -> None:
+ """Install then uninstall leaves no stub carrying only our own frontmatter.
+
+ A leftover ``.mdc`` holding nothing but ``alwaysApply: true`` still reads as
+ repowise-managed to whoever opens it, and Cursor would still load it on every
+ conversation.
+ """
+ from repowise.cli.agent_targets.targets import cursor as cursor_target
+
+ repo = tmp_path / "repo"
+ repo.mkdir()
+ rules = cursor_target.rules_path(repo)
+
+ cursor_target.TARGET.install(Scope.PROJECT, repo_path=repo)
+ assert rules.exists()
+ assert rules.read_text(encoding="utf-8").startswith("---\nalwaysApply: true\n---\n")
+
+ cursor_target.TARGET.uninstall(Scope.PROJECT, repo_path=repo)
+ assert not rules.exists()
+
+
+def test_cursor_reinstall_reports_unchanged(tmp_path: Path) -> None:
+ """Both files, so ``agents refresh`` on a settled repo reports no movement."""
+ from repowise.cli.agent_targets.targets import cursor as cursor_target
+
+ repo = tmp_path / "repo"
+ repo.mkdir()
+ first = cursor_target.TARGET.install(Scope.PROJECT, repo_path=repo)
+ assert first.changed
+
+ second = cursor_target.TARGET.install(Scope.PROJECT, repo_path=repo)
+
+ assert not second.changed
+ assert {f.action for f in second.files} == {FileAction.UNCHANGED}
+
+
+def test_cursor_keeps_a_sibling_server_and_a_user_env_block(tmp_path: Path) -> None:
+ """The merge is per server, and per key inside ours.
+
+ Same guarantee the other JSON targets give. A user who added an ``env`` block
+ to the repowise entry keeps it, and another tool's server is not our business.
+ """
+ from repowise.cli.agent_targets.targets import cursor as cursor_target
+
+ repo = tmp_path / "repo"
+ repo.mkdir()
+ config = cursor_target.mcp_config_path(repo)
+ config.parent.mkdir(parents=True)
+ config.write_text(
+ json.dumps(
+ {
+ "mcpServers": {
+ "other": {"command": "other-server"},
+ "repowise": {"command": "stale", "env": {"RUST_LOG": "debug"}},
+ }
+ },
+ indent=2,
+ ),
+ encoding="utf-8",
+ )
+
+ cursor_target.TARGET.install(Scope.PROJECT, repo_path=repo)
+
+ servers = json.loads(config.read_text(encoding="utf-8"))["mcpServers"]
+ assert servers["other"] == {"command": "other-server"}
+ assert servers["repowise"]["env"] == {"RUST_LOG": "debug"}
+ # ...while a generated key still wins, so a moved repo repoints.
+ assert servers["repowise"]["command"] != "stale"
+
+
+def test_cursor_declines_a_config_it_cannot_parse(tmp_path: Path) -> None:
+ """Declining beats rewriting: a file we misparsed loses whatever we could not read."""
+ from repowise.cli.agent_targets.targets import cursor as cursor_target
+
+ repo = tmp_path / "repo"
+ repo.mkdir()
+ config = cursor_target.mcp_config_path(repo)
+ config.parent.mkdir(parents=True)
+ original = '// a comment\n{ "mcpServers": {} }\n'
+ config.write_text(original, encoding="utf-8", newline="\n")
+
+ result = cursor_target.TARGET.install(Scope.PROJECT, repo_path=repo)
+
+ assert config.read_text(encoding="utf-8") == original
+ action = next(f.action for f in result.files if f.path == config)
+ assert action is FileAction.KEPT
+ assert any("mcp.json" in note for note in result.notes)
+
+
+def test_cursor_refuses_a_rules_file_with_malformed_markers(tmp_path: Path) -> None:
+ """The helper refuses; the target has to say so rather than report a write."""
+ from repowise.cli.agent_targets.targets import cursor as cursor_target
+
+ repo = tmp_path / "repo"
+ repo.mkdir()
+ rules = cursor_target.rules_path(repo)
+ rules.parent.mkdir(parents=True)
+ from repowise.cli.agent_targets.instructions import DISTILL_MARKER_START
+
+ original = f"---\nalwaysApply: true\n---\n\n{DISTILL_MARKER_START}\nI deleted the end.\n"
+ rules.write_text(original, encoding="utf-8", newline="\n")
+
+ result = cursor_target.TARGET.install(Scope.PROJECT, repo_path=repo)
+
+ assert rules.read_text(encoding="utf-8") == original
+ assert next(f.action for f in result.files if f.path == rules) is FileAction.KEPT
+ assert any("unpaired or duplicated" in note for note in result.notes)
+
+
+def test_cursor_leaves_a_rules_file_it_does_not_own(tmp_path: Path) -> None:
+ """Uninstall reports what it did not touch rather than deleting a user's rule.
+
+ ``.cursor/rules/repowise.mdc`` is a name a user could plausibly have written
+ themselves, and a marker-free file at that path is theirs. It reports
+ ``not-found`` rather than ``kept``: there was no block of ours to remove,
+ which is a different statement from "we deliberately left this alone", and
+ that second one is reserved for a file we could not safely touch.
+ """
+ from repowise.cli.agent_targets.targets import cursor as cursor_target
+
+ repo = tmp_path / "repo"
+ repo.mkdir()
+ rules = cursor_target.rules_path(repo)
+ rules.parent.mkdir(parents=True)
+ original = "---\nalwaysApply: true\n---\n\nMy own notes about repowise.\n"
+ rules.write_text(original, encoding="utf-8", newline="\n")
+
+ result = cursor_target.TARGET.uninstall(Scope.PROJECT, repo_path=repo)
+
+ assert rules.read_text(encoding="utf-8") == original
+ assert next(f.action for f in result.files if f.path == rules) is FileAction.NOT_FOUND
+
+
+def test_cursor_uninstall_leaves_no_directories_of_ours_behind(tmp_path: Path) -> None:
+ """The directory-shaped version of the stub file ``delete_if_only`` prevents.
+
+ It is not only tidiness. ``is_present`` reads ``.cursor/`` as evidence the
+ user has Cursor, so our own residue would keep the agent pre-ticked in every
+ later listing for a repo it had just been removed from.
+ """
+ from repowise.cli.agent_targets.targets import cursor as cursor_target
+
+ repo = tmp_path / "repo"
+ repo.mkdir()
+ cursor_target.TARGET.install(Scope.PROJECT, repo_path=repo)
+ assert (repo / ".cursor").is_dir()
+
+ cursor_target.TARGET.uninstall(Scope.PROJECT, repo_path=repo)
+
+ assert list(repo.iterdir()) == []
+
+
+def test_cursor_keeps_a_sibling_server_when_it_removes_ours(tmp_path: Path) -> None:
+ """Deleting the file is only right when the file held nothing else."""
+ from repowise.cli.agent_targets.targets import cursor as cursor_target
+
+ repo = tmp_path / "repo"
+ repo.mkdir()
+ cursor_target.TARGET.install(Scope.PROJECT, repo_path=repo)
+ config = cursor_target.mcp_config_path(repo)
+ data = json.loads(config.read_text(encoding="utf-8"))
+ data["mcpServers"]["other"] = {"command": "other-server"}
+ config.write_text(json.dumps(data, indent=2), encoding="utf-8")
+
+ cursor_target.TARGET.uninstall(Scope.PROJECT, repo_path=repo)
+
+ assert json.loads(config.read_text(encoding="utf-8")) == {
+ "mcpServers": {"other": {"command": "other-server"}}
+ }
+
+
+def test_cursor_declines_a_hand_wired_remote_server(tmp_path: Path) -> None:
+ """The third variant of the preserve-user-keys trap: the key that had to go stayed.
+
+ ``merge_server_entries`` lets generated keys win and keeps everything else,
+ which is right for ``command`` and ``args`` and wrong for ``type``. Against
+ an entry the user pointed at a remote server it forced ``type`` back to
+ ``stdio`` while faithfully preserving the ``url`` beside it, producing an
+ entry that was neither a valid local server nor a valid remote one.
+ """
+ from repowise.cli.agent_targets.targets import cursor as cursor_target
+
+ repo = tmp_path / "repo"
+ repo.mkdir()
+ config = cursor_target.mcp_config_path(repo)
+ config.parent.mkdir(parents=True)
+ remote = {"mcpServers": {"repowise": {"type": "http", "url": "https://example/mcp"}}}
+ config.write_text(json.dumps(remote, indent=2), encoding="utf-8", newline="\n")
+
+ result = cursor_target.TARGET.install(Scope.PROJECT, repo_path=repo)
+
+ assert json.loads(config.read_text(encoding="utf-8")) == remote
+ assert next(f.action for f in result.files if f.path == config) is FileAction.KEPT
+ assert any("remote server" in note for note in result.notes)
+
+
+def test_cursor_rules_file_that_is_not_utf8_is_refused_not_replaced(tmp_path: Path) -> None:
+ """The dangerous half of the decode bug, and the reason for ``UNREADABLE``.
+
+ A decode failure stops the *read* and not the write. Reporting an
+ undecodable file as absent, which is what an unreadable one used to get,
+ means ``upsert`` replaces a file it never saw. The crash was the visible
+ half; this is the one that loses data.
+
+ A cp1252 rules file is ordinary on Windows, not exotic.
+ """
+ from repowise.cli.agent_targets.targets import cursor as cursor_target
+
+ repo = tmp_path / "repo"
+ repo.mkdir()
+ path = cursor_target.rules_path(repo)
+ path.parent.mkdir(parents=True)
+ path.write_bytes("caf\xe9".encode("latin-1"))
+ before = path.read_bytes()
+
+ result = cursor_target.TARGET.install(Scope.PROJECT, repo_path=repo)
+ cursor_target.TARGET.uninstall(Scope.PROJECT, repo_path=repo)
+
+ assert path.read_bytes() == before
+ assert next(f.action for f in result.files if f.path == path) is FileAction.KEPT
+
+
+def test_cursor_detect_survives_a_config_that_is_not_utf8(tmp_path: Path) -> None:
+ """``detect`` is contracted never to raise, and ran on paths that do not catch.
+
+ ``UnicodeDecodeError`` is a ``ValueError`` and not a ``json.JSONDecodeError``,
+ so naming the latter let it through. ``resolve_target_flag`` calls detection
+ without a handler.
+ """
+ from repowise.cli.agent_targets.targets import cursor as cursor_target
+
+ repo = tmp_path / "repo"
+ repo.mkdir()
+ config = cursor_target.mcp_config_path(repo)
+ config.parent.mkdir(parents=True)
+ config.write_bytes("caf\xe9".encode("latin-1"))
+
+ assert cursor_target.TARGET.detect(repo) == []
+ assert resolve_target_flag("auto", repo) is not None
+
+
+def test_cursor_leaves_a_cursor_dir_it_did_not_create(tmp_path: Path) -> None:
+ """Pruning is gated on having removed something, not on the directory being empty.
+
+ "``rmdir`` refuses a non-empty directory, so an empty one must be ours" is
+ the same wrong assumption this module keeps meeting. A user who made
+ ``.cursor/`` by hand and left it empty had it deleted by a remove that found
+ nothing of ours to remove.
+ """
+ from repowise.cli.agent_targets.targets import cursor as cursor_target
+
+ repo = tmp_path / "repo"
+ repo.mkdir()
+ (repo / ".cursor").mkdir()
+
+ result = cursor_target.TARGET.uninstall(Scope.PROJECT, repo_path=repo)
+
+ assert (repo / ".cursor").is_dir()
+ assert not result.changed
+
+
+def test_cursor_install_repoints_a_stale_local_entry_carrying_a_url(tmp_path: Path) -> None:
+ """A local entry with a leftover ``url`` is stale, not remote.
+
+ Reading ``"url" in entry`` ahead of the declared type contradicted what the
+ entry says about itself, and wedged the exact state ``agents add`` exists to
+ repoint: every command that could have fixed it reached the same decline.
+ """
+ from repowise.cli.agent_targets.targets import cursor as cursor_target
+
+ repo = tmp_path / "repo"
+ repo.mkdir()
+ config = cursor_target.mcp_config_path(repo)
+ config.parent.mkdir(parents=True)
+ config.write_text(
+ json.dumps(
+ {
+ "mcpServers": {
+ "repowise": {"type": "stdio", "command": "stale", "url": "https://old"}
+ }
+ }
+ ),
+ encoding="utf-8",
+ )
+
+ cursor_target.TARGET.install(Scope.PROJECT, repo_path=repo)
+
+ entry = json.loads(config.read_text(encoding="utf-8"))["mcpServers"]["repowise"]
+ assert entry["command"] != "stale"
+ assert entry["type"] == "stdio"
+
+
+def test_cursor_does_not_claim_it_removed_a_file_it_could_not_delete(tmp_path: Path) -> None:
+ """A false success on the destructive verb, which a read-only bit was enough to cause.
+
+ Suppressing the ``unlink`` error reported ``removed`` for a file still
+ holding our entry. Falling through to the rewrite restores the loud failure
+ the previous code had.
+ """
+ from repowise.cli.agent_targets.targets import cursor as cursor_target
+
+ repo = tmp_path / "repo"
+ repo.mkdir()
+ cursor_target.TARGET.install(Scope.PROJECT, repo_path=repo)
+ config = cursor_target.mcp_config_path(repo)
+
+ real_unlink = Path.unlink
+
+ def _refuse(self, *args, **kwargs):
+ if self == config:
+ raise PermissionError("read-only")
+ return real_unlink(self, *args, **kwargs)
+
+ import unittest.mock
+
+ with unittest.mock.patch.object(Path, "unlink", _refuse):
+ cursor_target.TARGET.uninstall(Scope.PROJECT, repo_path=repo)
+
+ # Either the entry is gone or the command failed loudly. What it must not do
+ # is report "removed" over a file that still names us.
+ assert "repowise" not in json.loads(config.read_text(encoding="utf-8")).get("mcpServers", {})
+
+
+def test_codex_uninstall_separates_absent_from_left_alone(tmp_path: Path) -> None:
+ """The same conflation the Cursor rules file drew, one module over.
+
+ ``AGENTS.md`` is a file users write in, so "left alone" is the common answer
+ and reporting it as ``not-found`` says there was nothing of ours there.
+ """
+ from repowise.cli.agent_targets.instructions import DISTILL_MARKER_START
+ from repowise.cli.agent_targets.targets import codex as codex_target
+
+ repo = tmp_path / "repo"
+ repo.mkdir()
+ agents_md = repo / "AGENTS.md"
+
+ # Nothing of ours in it.
+ agents_md.write_text("# My notes\n", encoding="utf-8", newline="\n")
+ result = codex_target.TARGET.uninstall(Scope.PROJECT, repo_path=repo)
+ assert next(f.action for f in result.files if f.path == agents_md) is FileAction.NOT_FOUND
+
+ # A marker pair we must not touch.
+ agents_md.write_text(f"{DISTILL_MARKER_START}\nno end marker\n", encoding="utf-8", newline="\n")
+ result = codex_target.TARGET.uninstall(Scope.PROJECT, repo_path=repo)
+ assert next(f.action for f in result.files if f.path == agents_md) is FileAction.KEPT
+
+
+def test_codex_instructions_survive_a_file_that_is_not_utf8(tmp_path: Path) -> None:
+ """The marker helper refuses an unreadable file, but this path reads before calling it.
+
+ So the helper's refusal never got the chance to run, and the decode escaped
+ straight out of ``hook rewrite install`` and ``hook rewrite status``.
+ """
+ from repowise.cli.editor_integrations.codex_config import (
+ agents_md_distill_section_installed,
+ install_agents_md_distill_section,
+ )
+
+ repo = tmp_path / "repo"
+ repo.mkdir()
+ agents_md = repo / "AGENTS.md"
+ agents_md.write_bytes("caf\xe9".encode("latin-1"))
+ before = agents_md.read_bytes()
+
+ assert install_agents_md_distill_section(repo) is None
+ assert agents_md_distill_section_installed(repo) is False
+ assert agents_md.read_bytes() == before
+
+
+def test_vscode_install_survives_a_vscode_path_that_is_a_file(tmp_path: Path) -> None:
+ """The guard widened for Cursor belonged here too, one line above the one that moved."""
+ from repowise.cli.agent_targets.targets import vscode as vscode_target
+
+ repo = tmp_path / "repo"
+ repo.mkdir()
+ (repo / ".vscode").write_text("not a directory\n", encoding="utf-8")
+
+ result = vscode_target.TARGET.install(Scope.PROJECT, repo_path=repo)
+
+ assert (repo / ".vscode").is_file()
+ assert all(f.action is FileAction.KEPT for f in result.files)
+ assert result.notes
+
+
+def test_cursor_install_survives_a_cursor_path_that_is_a_file(tmp_path: Path) -> None:
+ """``.cursor`` as a plain file made ``mkdir`` raise straight out of ``install``."""
+ from repowise.cli.agent_targets.targets import cursor as cursor_target
+
+ repo = tmp_path / "repo"
+ repo.mkdir()
+ (repo / ".cursor").write_text("not a directory\n", encoding="utf-8")
+
+ result = cursor_target.TARGET.install(Scope.PROJECT, repo_path=repo)
+
+ assert (repo / ".cursor").is_file()
+ assert all(f.action is FileAction.KEPT for f in result.files)
+ assert result.notes
+
+
+def test_the_shared_instruction_body_has_one_home() -> None:
+ """Two hosts now carry the same managed block, and prose forks a sentence at a time.
+
+ That is exactly how the plugin skill sets drifted, so the second copy is an
+ import rather than a paste.
+ """
+ from repowise.cli.agent_targets import instructions
+ from repowise.cli.editor_integrations import codex_config
+
+ assert codex_config._DISTILL_SECTION is instructions.DISTILL_SECTION
+ assert codex_config._DISTILL_MARKER_START is instructions.DISTILL_MARKER_START
+
+
def test_claude_code_reports_plugin_and_direct_separately(tmp_path: Path, monkeypatch) -> None:
"""The duplicate-registration case the method axis exists for.
diff --git a/tests/unit/cli/test_agents_cmd.py b/tests/unit/cli/test_agents_cmd.py
index 75ed7f648..df41d7095 100644
--- a/tests/unit/cli/test_agents_cmd.py
+++ b/tests/unit/cli/test_agents_cmd.py
@@ -70,7 +70,12 @@ def test_bare_agents_lists_every_registered_target_as_a_table(repo: Path) -> Non
def test_bare_agents_lists_every_registered_target_as_json(repo: Path) -> None:
payload = _json(["agents"])
- assert [row["id"] for row in payload["agents"]] == ["claude-code", "codex", "vscode"]
+ assert [row["id"] for row in payload["agents"]] == [
+ "claude-code",
+ "codex",
+ "vscode",
+ "cursor",
+ ]
for row in payload["agents"]:
# The keys the table renders, so a dropped one is a broken table.
assert set(row) >= {"id", "tier", "present", "registrations", "method"}
@@ -347,6 +352,7 @@ def test_doctor_reports_one_row_per_agent_from_its_own_descriptor(repo: Path) ->
"Agent: claude-code",
"Agent: codex",
"Agent: vscode",
+ "Agent: cursor",
]
# Nothing is wired on a clean machine, and an agent you do not use is not a
# problem with your setup.
diff --git a/tests/unit/cli/test_editor_setup.py b/tests/unit/cli/test_editor_setup.py
index 4dbe79224..0c5c65c97 100644
--- a/tests/unit/cli/test_editor_setup.py
+++ b/tests/unit/cli/test_editor_setup.py
@@ -47,6 +47,10 @@ def test_register_editor_clients_skipped_when_env_set(monkeypatch) -> None:
registered: list[Path] = []
class FakeIntegration:
+ # ``InstallLifecycle`` declares this, and the checklist reads it to
+ # decide which agents ``init`` can act on.
+ integration_id = "fake"
+
def write_project_files(self, c: Any, p: Path, o: Any) -> None:
pass
@@ -79,6 +83,10 @@ def test_register_editor_clients_skipped_by_flag(monkeypatch) -> None:
registered: list[Path] = []
class FakeIntegration:
+ # ``InstallLifecycle`` declares this, and the checklist reads it to
+ # decide which agents ``init`` can act on.
+ integration_id = "fake"
+
def write_project_files(self, c: Any, p: Path, o: Any) -> None:
pass
@@ -437,8 +445,34 @@ def test_checklist_ticking_everything_disables_nothing(monkeypatch, tmp_path) ->
monkeypatch, tmp_path, lambda choices: {choice.id for choice in choices}
)
+ from repowise.cli.editor_integrations.defaults import get_default_editor_integrations
+
assert options.disabled_project_files == frozenset()
- assert options.integration_overrides == {"claude-code": True, "codex": True, "vscode": True}
+ # Derived from the *setup integrations*, not the target registry, and the
+ # difference is the point: the checklist offers what ``init`` can write, and
+ # a registered agent without a setup integration is not that. Restating the
+ # list here would make a fifth agent fail two tests for one reason.
+ assert options.integration_overrides == {
+ integration.integration_id: True for integration in get_default_editor_integrations()
+ }
+
+
+def test_checklist_offers_only_agents_init_can_write(monkeypatch, tmp_path) -> None:
+ """A ticked box that writes nothing reads as success, because the others print a line.
+
+ The checklist is built from the agent registry and the writing is done by
+ the setup integrations, and those are two lists. An agent can be registered
+ (matrix row, ``--target`` id, ``doctor`` row) without ``init`` having a
+ writer for it, and Cursor is the first one that is. It gets a pointer to the
+ command that does wire it, not a box that quietly does nothing.
+ """
+ from repowise.cli.editor_integrations.defaults import get_default_editor_integrations
+
+ _, choices = _select(monkeypatch, tmp_path, lambda c: {choice.id for choice in c})
+
+ offered = {choice.id for choice in choices}
+ assert offered == {i.integration_id for i in get_default_editor_integrations()}
+ assert "cursor" not in offered
def test_checklist_pre_ticks_an_agent_an_explicit_flag_asked_for(monkeypatch, tmp_path) -> None:
@@ -514,6 +548,10 @@ def test_write_editor_project_files_saves_common_mcp_before_integrations(
return repo_path / ".repowise" / "mcp.json"
class FakeIntegration:
+ # ``InstallLifecycle`` declares this, and the checklist reads it to
+ # decide which agents ``init`` can act on.
+ integration_id = "fake"
+
def write_project_files(
self,
console_obj: object,
@@ -555,6 +593,10 @@ def test_write_editor_project_files_uses_pre_resolved_options(
return repo_path / ".repowise" / "mcp.json"
class FakeIntegration:
+ # ``InstallLifecycle`` declares this, and the checklist reads it to
+ # decide which agents ``init`` can act on.
+ integration_id = "fake"
+
def write_project_files(
self,
console_obj: object,
@@ -620,6 +662,10 @@ def test_refresh_editor_project_files_delegates_to_integrations(tmp_path: Path)
calls: list[tuple[str, Path, frozenset[str]]] = []
class FakeIntegration:
+ # ``InstallLifecycle`` declares this, and the checklist reads it to
+ # decide which agents ``init`` can act on.
+ integration_id = "fake"
+
def refresh_project_files(
self,
console_obj: object,