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): rewrite Cursor shell commands through a preToolUse hook (#3177)

Raghav Chamadiyaa70cd2ca2512
diff --git a/README.md b/README.md
index e6f49f133..f816a8d4c 100644
--- a/README.md
+++ b/README.md
@@ -547,8 +547,8 @@ paste away.**
**Full** is every surface Repowise has: MCP tools, skills, slash commands, a managed
instructions file, hook-level interception of tool calls, and transcript mining after
-the session. **Good** is MCP tools plus an instructions file or skills, without hooks
-or transcript mining. **Basic** is the MCP config alone. Anything else that speaks MCP is one snippet away:
+the session. **Good** is MCP tools plus an instructions file or skills, without transcript mining
+(hooks only where the matrix says). **Basic** is the MCP config alone. Anything else that speaks MCP is one snippet away:
`repowise agents print-config claude-code` prints a server entry for Cline, Windsurf,
Zed, Gemini CLI or any host that reads `mcpServers`.
[Integration matrix →](docs/agent/INTEGRATIONS.md)
diff --git a/docs/agent/DISTILL.md b/docs/agent/DISTILL.md
index 91edc6648..22d4cc11d 100644
--- a/docs/agent/DISTILL.md
+++ b/docs/agent/DISTILL.md
@@ -106,6 +106,12 @@ itself and to `repowise expand` markers instead of re-running commands. This
works on every Codex version. `uninstall` removes the section and restores your
`AGENTS.md` byte-for-byte.
+**Cursor.** When `~/.cursor` exists, `install` also adds a `preToolUse` entry
+(matcher `Shell`) to `~/.cursor/hooks.json`, beside any hooks you already have.
+Cursor's `preToolUse` honours `allow` and `deny` only, so as under Codex, rewrites
+fire only for families resolving to `permission: allow`. `repowise agents add
+--target=cursor --scope=user` writes the same entry.
+
The hook is conservative. It never rewrites:
- redirections and compound commands (`>`, `&&`, `;`, backticks, `$()`), and
diff --git a/docs/agent/HOOKS.md b/docs/agent/HOOKS.md
index 6041d39de..3de24528f 100644
--- a/docs/agent/HOOKS.md
+++ b/docs/agent/HOOKS.md
@@ -26,7 +26,7 @@ For the exact settings entries each install writes, see the
| **PostToolUse enrichment** | Claude Code | `repowise init` | `Grep` / `Glob` / `Read` / `Edit` / `Write` / repowise MCP calls | Graph context on searches, read notices, edit-time decision and bug-history notices |
| **Wrong-path rescue** | Claude Code | `repowise init` | a path tool call that failed on a path this tree does not have | Names the file when exactly one indexed file carries that basename; silent otherwise |
| **Coverage re-ingest** (opt-in) | Claude Code | `hooks.coverage_reingest: true`, then the next `repowise coverage add` / `init` / `update` | `Bash` / `PowerShell` | Re-ingests a fresh full-suite coverage report in the background |
-| **Command rewrite (distill)** | Claude Code, Codex | `repowise hook rewrite install`, or Yes at the `repowise init` prompt | `Bash` / `PowerShell` | Rewrites noisy commands to `repowise distill <cmd>` |
+| **Command rewrite (distill)** | Claude Code, Codex, Cursor | `repowise hook rewrite install`, or Yes at the `repowise init` prompt | `Bash` / `PowerShell` (Cursor: `Shell`) | Rewrites noisy commands to `repowise distill <cmd>` |
| **Codex context and staleness** | Codex | `repowise init --codex` | SessionStart, edits, shell | Reminds Codex to use the MCP tools and flags stale context after git operations |
Each agent hook records what it said and whether the agent acted on it. See
@@ -260,6 +260,7 @@ Flags and the `--reset` upgrade step: [CLI reference](../reference/CLI_REFERENCE
| Claude Code | `PostToolUse` and `PostToolUseFailure` (opt-in coverage re-ingest) | `Bash\|PowerShell` | the repo's `.claude/settings.local.json` |
| Codex | `SessionStart` | `startup\|resume\|clear` | the repo's `.codex/hooks.json` |
| Codex | `PostToolUse` | `Bash\|shell_command`, `apply_patch\|Edit\|Write` | the repo's `.codex/hooks.json` |
+| Cursor | `preToolUse` (opt-in rewrite) | `Shell` | `~/.cursor/hooks.json` |
The coverage re-ingest entries are written by the next `repowise coverage add`,
`init` or `update` once `hooks.coverage_reingest: true` is set, and removed when
diff --git a/docs/agent/INTEGRATIONS.md b/docs/agent/INTEGRATIONS.md
index 72e1fe000..ff24316b8 100644
--- a/docs/agent/INTEGRATIONS.md
+++ b/docs/agent/INTEGRATIONS.md
@@ -15,7 +15,7 @@ only by wiring instructions or skills beside MCP, so no document can claim
a depth the integration does not have.
- **Full.** MCP tools, a managed instructions file, skills, slash commands, hook-level interception of tool calls, and transcript mining after the fact. Every surface repowise has.
-- **Good.** MCP tools plus a managed instructions file or skills, so the agent is told when to reach for them. **No hook-level interception and no transcript mining.** The agent can ask repowise questions; repowise cannot see or annotate what the agent does in between.
+- **Good.** MCP tools plus a managed instructions file or skills, so the agent is told when to reach for them. **No transcript mining, and hooks only where the matrix says so.** The agent can ask repowise questions; repowise sees little or nothing of what it does in between.
- **Basic.** repowise writes the MCP server config and nothing else. The tools are there; no instructions file or skill tells the agent when to use them.
- **Paste-config.** `repowise agents print-config <id>` emits the MCP server snippet and we write nothing. Zero code and zero maintenance per host.
@@ -32,7 +32,7 @@ example). It is separate from the tier: it says nothing about the session.
| [Claude Code](https://docs.claude.com/en/docs/claude-code) | Full | Yes | Yes | Plugin | Plugin | Yes | Yes | Yes |
| [Codex CLI](https://developers.openai.com/codex/cli) | Full | Yes | Yes | Plugin | Yes | Yes | Yes | Yes |
| [VS Code](https://code.visualstudio.com/docs/copilot/chat/mcp-servers) | Good | Yes | No | No | No | Yes | No | No |
-| [Cursor](https://cursor.com/docs/context/mcp) | Good | Yes | No | No | No | Yes | No | No |
+| [Cursor](https://cursor.com/docs/context/mcp) | Good | Yes | Yes | No | No | Yes | No | No |
| [OpenCode](https://opencode.ai/docs/mcp-servers/) | Good | Yes | No | No | No | Yes | No | Yes |
| [Hermes](https://hermes-agent.nousresearch.com/docs/user-guide/features/mcp) | Good | Yes | No | No | No | Yes | No | No |
| [GitHub Copilot CLI](https://docs.github.com/en/copilot/reference/copilot-cli-reference/cli-command-reference) | Good | Yes | No | No | No | Yes | No | No |
@@ -49,6 +49,9 @@ call before it runs, never rewrites a noisy command, and never annotates
a result afterwards. Nor is there transcript mining, so nothing learns
from the session after it ends.
+The one exception is hooks: Cursor runs the distill command-rewrite hook,
+so noisy commands are rewritten there. Transcript mining is still absent.
+
That is a real integration and it is most of the value. It is not the
same product Full-tier agents get, and breadth that overclaims depth is
worse than narrower breadth.
diff --git a/packages/cli/src/repowise/cli/agent_adapters/__init__.py b/packages/cli/src/repowise/cli/agent_adapters/__init__.py
index 8d76dab93..8c7ba1dd4 100644
--- a/packages/cli/src/repowise/cli/agent_adapters/__init__.py
+++ b/packages/cli/src/repowise/cli/agent_adapters/__init__.py
@@ -28,6 +28,7 @@ from repowise.cli.agent_adapters.base import AgentAdapter, RewriteRequest, Rewri
_REGISTRY: dict[str, str] = {
"claude-code": "repowise.cli.agent_adapters.claude_code:ClaudeCodeAdapter",
"codex": "repowise.cli.agent_adapters.codex:CodexAdapter",
+ "cursor": "repowise.cli.agent_adapters.cursor:CursorAdapter",
}
#: What an unmarked payload is. Claude Code's hook config passes no marker,
diff --git a/packages/cli/src/repowise/cli/agent_adapters/cursor.py b/packages/cli/src/repowise/cli/agent_adapters/cursor.py
new file mode 100644
index 000000000..11c0b6d9b
--- /dev/null
+++ b/packages/cli/src/repowise/cli/agent_adapters/cursor.py
@@ -0,0 +1,240 @@
+"""Cursor adapter: the distill rewrite on ``preToolUse`` in ``~/.cursor/hooks.json``.
+
+Host quirks, all from https://cursor.com/docs/agent/hooks:
+
+- Only ``preToolUse`` documents ``updated_input``; ``beforeShellExecution`` cannot rewrite.
+- ``preToolUse`` does not enforce ``ask``, so only ``allow`` families rewrite.
+- ``updated_input`` is the input "to use instead", so the whole input is echoed back.
+- ``updated_mcp_tool_output`` is MCP-only, so no shell or file result is replaced.
+- Entries are flat ``{command, matcher, timeout}`` under ``{"version": 1, "hooks": ...}``.
+"""
+
+from __future__ import annotations
+
+import json
+import os
+from typing import TYPE_CHECKING, ClassVar
+
+from repowise.cli.agent_adapters.base import (
+ SHELL_POSIX,
+ SHELL_POWERSHELL,
+ AgentAdapter,
+ RewriteRequest,
+ RewriteResult,
+)
+
+if TYPE_CHECKING:
+ from pathlib import Path
+
+#: Cursor's one shell tool name in ``preToolUse`` payloads.
+SHELL_TOOL_NAMES: frozenset[str] = frozenset({"Shell"})
+
+#: The installed matcher, derived so it cannot disagree with the gate.
+SHELL_TOOL_MATCHER: str = "|".join(sorted(SHELL_TOOL_NAMES))
+
+_REWRITE_HOOK_COMMAND = "repowise-rewrite"
+_EVENT = "preToolUse"
+
+#: Bare command on PATH, as Claude Code's and Codex's entries are.
+_REWRITE_HOOK_ENTRY = {
+ "command": f"{_REWRITE_HOOK_COMMAND} --agent cursor",
+ "matcher": SHELL_TOOL_MATCHER,
+ "timeout": 5,
+}
+
+
+class CursorAdapter(AgentAdapter):
+ name: ClassVar[str] = "cursor"
+
+ savings_source: ClassVar[str | None] = "hook-cursor"
+
+ shell_tool_names: ClassVar[frozenset[str]] = SHELL_TOOL_NAMES
+
+ rewrite_permissions: ClassVar[frozenset[str]] = frozenset({"allow"})
+
+ replaces_tool_output: ClassVar[bool] = False
+
+ def __init__(self) -> None:
+ # Echoed back whole by render_response; one payload per hook process.
+ self._tool_input: dict = {}
+
+ def detect(self) -> bool:
+ return os.path.isdir(os.path.expanduser("~/.cursor"))
+
+ def parse_hook_payload(self, raw: str) -> RewriteRequest | None:
+ try:
+ payload = json.loads(raw)
+ except (json.JSONDecodeError, TypeError):
+ return None
+ if not isinstance(payload, dict):
+ return None
+ if payload.get("hook_event_name") != _EVENT:
+ return None
+ if payload.get("tool_name") not in SHELL_TOOL_NAMES:
+ return None
+ tool_input = payload.get("tool_input")
+ if not isinstance(tool_input, dict):
+ return None
+ command = tool_input.get("command")
+ if not isinstance(command, str) or not command.strip():
+ return None
+ self._tool_input = tool_input
+ cwd = next(
+ (
+ value
+ for value in (
+ tool_input.get("working_directory"),
+ payload.get("cwd"),
+ *(payload.get("workspace_roots") or [])[:1],
+ )
+ if isinstance(value, str) and value
+ ),
+ "",
+ )
+ session_id = payload.get("conversation_id")
+ return RewriteRequest(
+ command=command,
+ cwd=cwd,
+ session_id=session_id if isinstance(session_id, str) else "",
+ # The payload names no shell; PowerShell's extra bailouts are the safe side.
+ shell=SHELL_POWERSHELL if os.name == "nt" else SHELL_POSIX,
+ )
+
+ def render_response(self, result: RewriteResult) -> str:
+ # Only called for "allow" (rewrite_permissions); "ask" is not enforced.
+ return json.dumps(
+ {
+ "permission": result.permission,
+ "updated_input": {**self._tool_input, "command": result.command},
+ }
+ )
+
+ def install_rewrite_hook(self) -> Path | None:
+ return install_cursor_rewrite_hook()
+
+ def uninstall_rewrite_hook(self) -> bool:
+ return uninstall_cursor_rewrite_hook()
+
+ def rewrite_hook_installed(self) -> bool:
+ return cursor_rewrite_hook_matcher() is not None
+
+ def rewrite_hook_matcher(self) -> str | None:
+ return cursor_rewrite_hook_matcher()
+
+
+# ---------------------------------------------------------------------------
+# ~/.cursor/hooks.json: additive, idempotent, other entries untouched.
+# ---------------------------------------------------------------------------
+
+
+def user_hooks_path() -> Path:
+ from pathlib import Path # lazy: pathlib is too slow for the hook hot path
+
+ return Path.home() / ".cursor" / "hooks.json"
+
+
+def _is_rewrite_hook(entry: object) -> bool:
+ """Ours when the command's executable basename is ``repowise-rewrite``.
+
+ A substring test would claim a user's wrapper that merely mentions it.
+ """
+ if not isinstance(entry, dict):
+ return False
+ command = entry.get("command")
+ if not isinstance(command, str) or not command.strip():
+ return False
+ command = command.strip()
+ quoted = command[0] in "\"'"
+ exe = command[1:].split(command[0], 1)[0] if quoted else command.split(None, 1)[0]
+ name = exe.replace("\\", "/").rsplit("/", 1)[-1].lower()
+ return name.removesuffix(".exe") == _REWRITE_HOOK_COMMAND
+
+
+def _load(path: Path) -> dict:
+ from repowise.cli.mcp_config import load_existing_config
+
+ return load_existing_config(path)
+
+
+def _write(path: Path, doc: dict) -> None:
+ from repowise.cli.agent_targets.formats.json_merge import write_json_config
+
+ write_json_config(path, doc)
+
+
+def install_cursor_rewrite_hook() -> Path | None:
+ """Register the rewrite entry under ``preToolUse``; the path, or None on failure."""
+ path = user_hooks_path()
+ try:
+ if path.exists():
+ doc = _load(path)
+ else:
+ path.parent.mkdir(parents=True, exist_ok=True)
+ doc = {}
+ hooks = doc.setdefault("hooks", {})
+ entries = hooks.setdefault(_EVENT, [])
+ if not any(_is_rewrite_hook(entry) for entry in entries):
+ doc.setdefault("version", 1)
+ entries.append(dict(_REWRITE_HOOK_ENTRY))
+ _write(path, doc)
+ return path
+ except Exception:
+ # A malformed file or a failed write: report failure, never raise.
+ return None
+
+
+def uninstall_cursor_rewrite_hook() -> bool:
+ """Remove our entry from every event; True when the file changed."""
+ path = user_hooks_path()
+ if not path.exists():
+ return False
+ try:
+ doc = _load(path)
+ except Exception:
+ return False
+ hooks = doc.get("hooks")
+ if not isinstance(hooks, dict):
+ return False
+ changed = False
+ for event, entries in list(hooks.items()):
+ if not isinstance(entries, list):
+ continue
+ kept = [entry for entry in entries if not _is_rewrite_hook(entry)]
+ if len(kept) == len(entries):
+ continue
+ changed = True
+ if kept:
+ hooks[event] = kept
+ else:
+ hooks.pop(event)
+ if not changed:
+ return False
+ try:
+ # A file holding nothing but our entry was ours; leave no stub behind.
+ if not hooks and set(doc) <= {"version", "hooks"}:
+ path.unlink()
+ else:
+ _write(path, doc)
+ except OSError:
+ return False
+ return True
+
+
+def cursor_rewrite_hook_matcher() -> str | None:
+ """The installed entry's matcher, ``""`` for none, or None when absent."""
+ path = user_hooks_path()
+ if not path.exists():
+ return None
+ try:
+ doc = _load(path)
+ except Exception:
+ return None
+ hooks = doc.get("hooks")
+ entries = hooks.get(_EVENT) if isinstance(hooks, dict) else None
+ if not isinstance(entries, list):
+ return None
+ for entry in entries:
+ if _is_rewrite_hook(entry):
+ matcher = entry.get("matcher")
+ return matcher if isinstance(matcher, str) else ""
+ return None
diff --git a/packages/cli/src/repowise/cli/agent_targets/targets/cursor.py b/packages/cli/src/repowise/cli/agent_targets/targets/cursor.py
index 947ba0688..b4fb7067d 100644
--- a/packages/cli/src/repowise/cli/agent_targets/targets/cursor.py
+++ b/packages/cli/src/repowise/cli/agent_targets/targets/cursor.py
@@ -1,9 +1,8 @@
"""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.
+Good tier: it names a hook adapter (:mod:`repowise.cli.agent_adapters.cursor`,
+the ``preToolUse`` rewrite in ``~/.cursor/hooks.json``, the one user-scope write)
+but no transcript adapter, so :func:`derive_tier` cannot place it at Full.
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
@@ -33,7 +32,7 @@ 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
+**Project scope only, for MCP.** 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
@@ -72,7 +71,7 @@ PROJECT_FILE_ID = "cursor_rules"
METHODS = (
InstallMethod(
id="direct",
- provides=frozenset({Capability.MCP, Capability.INSTRUCTIONS}),
+ provides=frozenset({Capability.MCP, Capability.HOOKS, Capability.INSTRUCTIONS}),
managed_by="repowise",
preferred=True,
),
@@ -330,18 +329,53 @@ def _prune_empty_dirs(repo_path: Path) -> None:
candidate.rmdir()
+def _install_rewrite_hook(result: WriteResult) -> WriteResult:
+ """Merge the rewrite entry into ``~/.cursor/hooks.json``, observed not assumed."""
+ from repowise.cli.agent_adapters.cursor import install_cursor_rewrite_hook, user_hooks_path
+
+ from ..formats.observe import observed_action, read_bytes
+
+ hooks_path = user_hooks_path()
+ before = read_bytes(hooks_path)
+ if install_cursor_rewrite_hook():
+ result.record(hooks_path, observed_action(before, read_bytes(hooks_path)))
+ else:
+ result.record(hooks_path, FileAction.KEPT, "not valid JSON, or could not be written")
+ result.note(f"{hooks_path} left unchanged; fix it by hand and re-run.")
+ return result
+
+
+def cursor_rewrite_hook_present() -> bool:
+ """Our entry is registered, or the file is unreadable and still names it."""
+ from repowise.cli.agent_adapters.cursor import cursor_rewrite_hook_matcher, user_hooks_path
+
+ from ..formats.json_merge import is_damaged
+
+ if cursor_rewrite_hook_matcher() is not None:
+ return True
+ path = user_hooks_path()
+ try:
+ return is_damaged(path) and b"repowise-rewrite" in path.read_bytes()
+ except OSError:
+ return False
+
+
def detect(repo_path: Path | None = None) -> list[Registration]:
- """Whether the workspace MCP config names repowise.
+ """The user-scope rewrite hook, and 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.
+ Returning nothing for an unparseable file is deliberate: it may well be
+ wired up, and reporting "not configured" would be a guess.
"""
+ from repowise.cli.agent_adapters.cursor import cursor_rewrite_hook_matcher, user_hooks_path
+
+ found: list[Registration] = []
+ if cursor_rewrite_hook_matcher() is not None:
+ found.append(Registration(method="direct", scope=Scope.USER, config_path=user_hooks_path()))
if repo_path is None:
- return []
+ return found
config_path = mcp_config_path(repo_path)
if not config_path.exists():
- return []
+ return found
try:
data = json.loads(config_path.read_text(encoding="utf-8"))
except (OSError, ValueError):
@@ -350,11 +384,12 @@ def detect(repo_path: Path | None = None) -> list[Registration]:
# 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 []
+ return found
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)]
+ return found
+ found.append(Registration(method="direct", scope=Scope.PROJECT, config_path=config_path))
+ return found
class CursorTarget:
@@ -369,8 +404,8 @@ class CursorTarget:
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
+ """Both: user scope writes only the rewrite hook. See the module docstring."""
+ return True
def is_present(self, repo_path: Path | None = None) -> bool:
"""A ``.cursor/`` in the repo, the ``cursor`` shim on PATH, or ``~/.cursor``.
@@ -397,8 +432,8 @@ class CursorTarget:
repo_path: Path | None = None,
) -> WriteResult:
result = WriteResult()
- if scope is not Scope.PROJECT:
- return result
+ if scope is Scope.USER:
+ return _install_rewrite_hook(result)
if repo_path is None:
raise ValueError("project-scope install needs a repo_path")
@@ -462,9 +497,25 @@ class CursorTarget:
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."""
+ """Remove what install wrote at *scope*: the hook, or the server entry and rules."""
result = WriteResult()
- if scope is not Scope.PROJECT or repo_path is None:
+ if scope is Scope.USER:
+ from repowise.cli.agent_adapters.cursor import (
+ uninstall_cursor_rewrite_hook,
+ user_hooks_path,
+ )
+
+ removed = uninstall_cursor_rewrite_hook()
+ # Asked of the file, not the boolean, which is also False for "could
+ # not parse" and "write failed".
+ if cursor_rewrite_hook_present():
+ result.record(user_hooks_path(), FileAction.KEPT, "our rewrite hook is still there")
+ else:
+ result.record(
+ user_hooks_path(), FileAction.REMOVED if removed else FileAction.NOT_FOUND
+ )
+ return result
+ if repo_path is None:
return result
result.record(*_remove_server_entry(mcp_config_path(repo_path)))
result.record(*_remove_rules_file(repo_path))
@@ -478,24 +529,41 @@ class CursorTarget:
)
def describe_paths(self, scope: Scope, *, repo_path: Path | None = None) -> list[str]:
- if scope is not Scope.PROJECT:
- return []
+ if scope is Scope.USER:
+ from repowise.cli.agent_adapters.cursor import user_hooks_path
+
+ return [str(user_hooks_path())]
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.
+ """Health of the one user-level surface, the rewrite hook.
- 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.
+ The MCP config and rules file are workspace-local and ``doctor()`` takes
+ no repo path, so they are not judged here.
"""
- 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",
- )
+ from repowise.cli.agent_adapters.cursor import cursor_rewrite_hook_matcher, user_hooks_path
+
+ from ..formats.json_merge import is_damaged
+
+ hooks = user_hooks_path()
+ fix = "repowise agents add --target=cursor --scope=user"
+ if is_damaged(hooks):
+ return DoctorReport(
+ target_id=ID,
+ status=DoctorStatus.BROKEN,
+ issues=(f"{hooks} is not valid JSON, so Cursor loads none of its hooks.",),
+ fix_command=fix,
+ repairable=False,
+ )
+ if cursor_rewrite_hook_matcher() is None:
+ return DoctorReport(
+ target_id=ID,
+ status=DoctorStatus.NOT_INSTALLED,
+ issues=("The distill rewrite hook is not installed for Cursor.",),
+ fix_command=fix,
+ )
+ return DoctorReport(target_id=ID, status=DoctorStatus.OK)
TARGET = CursorTarget()
diff --git a/packages/cli/src/repowise/cli/commands/doctor_cmd/repo_checks.py b/packages/cli/src/repowise/cli/commands/doctor_cmd/repo_checks.py
index 05c9265ed..df1da3ce3 100644
--- a/packages/cli/src/repowise/cli/commands/doctor_cmd/repo_checks.py
+++ b/packages/cli/src/repowise/cli/commands/doctor_cmd/repo_checks.py
@@ -1234,6 +1234,11 @@ def _distill_checks(repo_path: _DoctorPath) -> list[DoctorCheck]:
codex = CodexAdapter()
if codex.detect():
surfaces.append(("codex", codex))
+ from repowise.cli.agent_adapters.cursor import CursorAdapter
+
+ cursor = CursorAdapter()
+ if cursor.detect():
+ surfaces.append(("cursor", cursor))
# Registered and live are different questions: an entry whose matcher
# predates a tool rename is registered and fires on some or none of
# the agent's shell tools. Say which, rather than calling all three
diff --git a/packages/cli/src/repowise/cli/commands/hook_cmd.py b/packages/cli/src/repowise/cli/commands/hook_cmd.py
index e70c8c5a6..4349c12ce 100644
--- a/packages/cli/src/repowise/cli/commands/hook_cmd.py
+++ b/packages/cli/src/repowise/cli/commands/hook_cmd.py
@@ -313,6 +313,25 @@ def rewrite_install(
save_distill_commands_enabled(target.repo_path, enabled=True)
_install_codex_surfaces(target)
+ _install_cursor_hook()
+
+
+def _install_cursor_hook() -> None:
+ """Cursor side of ``rewrite install``; skipped when there is no ``~/.cursor``."""
+ from repowise.cli.agent_adapters.cursor import CursorAdapter
+
+ cursor = CursorAdapter()
+ if not cursor.detect():
+ return
+ cursor_path = cursor.install_rewrite_hook()
+ if cursor_path:
+ console.print(f"Cursor rewrite hook: [green]installed[/green] ({cursor_path})")
+ console.print(
+ " [dim]Cursor does not enforce `ask` on preToolUse, so only families "
+ "set to `permission: allow` are rewritten there.[/dim]"
+ )
+ else:
+ console.print("Cursor rewrite hook: [red]install failed[/red]")
def _install_codex_surfaces(target) -> None:
@@ -400,6 +419,15 @@ def rewrite_uninstall(path: str | None, workspace: bool, no_workspace: bool) ->
f"Codex rewrite hook: {'[green]removed[/green]' if codex_removed else 'not installed'}"
)
+ from repowise.cli.agent_adapters.cursor import CursorAdapter
+
+ cursor = CursorAdapter()
+ if cursor.detect():
+ cursor_removed = cursor.uninstall_rewrite_hook()
+ console.print(
+ f"Cursor rewrite hook: {'[green]removed[/green]' if cursor_removed else 'not installed'}"
+ )
+
target = _hook_target(path, workspace, no_workspace)
for repo_path in _target_repo_paths(target):
if remove_agents_md_distill_section(repo_path):
@@ -440,6 +468,12 @@ def rewrite_status(path: str | None, workspace: bool, no_workspace: bool) -> Non
_print_rewrite_hook_status("claude-code", ClaudeCodeAdapter().rewrite_hook_status())
+ from repowise.cli.agent_adapters.cursor import CursorAdapter
+
+ cursor = CursorAdapter()
+ if cursor.detect():
+ _print_rewrite_hook_status("cursor", cursor.rewrite_hook_status())
+
codex = CodexAdapter()
if not codex.detect():
console.print(" [dim]✗[/dim] codex: not detected (no ~/.codex)")
diff --git a/packages/cli/src/repowise/cli/commands/saved_cmd.py b/packages/cli/src/repowise/cli/commands/saved_cmd.py
index 9002c2e4d..b2f091eba 100644
--- a/packages/cli/src/repowise/cli/commands/saved_cmd.py
+++ b/packages/cli/src/repowise/cli/commands/saved_cmd.py
@@ -707,8 +707,8 @@ def _resolve_pricing(repo_root: Path, override: str | None) -> tuple[str, str]:
def _rewrite_hook_installed() -> bool:
"""True when any agent surface has a rewrite hook that can actually fire.
- Mirrors the doctor check: Claude Code is always considered, Codex only
- when it is actually present on the machine. Registered is not enough — an
+ Mirrors the doctor check: Claude Code is always considered, Codex and
+ Cursor only when actually present on the machine. Registered is not enough — an
entry whose matcher names a renamed tool fires on nothing, and telling
someone their hook is installed is the one answer that hides why the rows
below it are still there.
@@ -723,8 +723,9 @@ def _rewrite_hook_installed() -> bool:
if live(ClaudeCodeAdapter()):
return True
- codex = CodexAdapter()
- return codex.detect() and live(codex)
+ from repowise.cli.agent_adapters.cursor import CursorAdapter
+
+ return any(a.detect() and live(a) for a in (CodexAdapter(), CursorAdapter()))
except Exception:
return False
diff --git a/packages/cli/src/repowise/cli/editor_setup.py b/packages/cli/src/repowise/cli/editor_setup.py
index 26bd8c31e..1a8c118e4 100644
--- a/packages/cli/src/repowise/cli/editor_setup.py
+++ b/packages/cli/src/repowise/cli/editor_setup.py
@@ -108,18 +108,17 @@ def detect_editor_setup_outcome(
pass
# The distill rewrite hook is per-agent. Treat it as present when any agent
- # surface has it (Claude Code always, Codex only when detected), mirroring
+ # surface has it (Claude Code always, Codex and Cursor only when detected), mirroring
# `repowise hook rewrite status`, so a Codex-only user who set it up on
# Codex is never nagged to install it again.
rewrite = False
try:
from repowise.cli.agent_adapters.claude_code import ClaudeCodeAdapter
from repowise.cli.agent_adapters.codex import CodexAdapter
+ from repowise.cli.agent_adapters.cursor import CursorAdapter
surfaces = [ClaudeCodeAdapter()]
- codex = CodexAdapter()
- if codex.detect():
- surfaces.append(codex)
+ surfaces += [a for a in (CodexAdapter(), CursorAdapter()) if a.detect()]
rewrite = any(surface.rewrite_hook_installed() for surface in surfaces)
except Exception:
pass
diff --git a/packages/core/src/repowise/core/agents/identity.py b/packages/core/src/repowise/core/agents/identity.py
index fff656025..b302d6d04 100644
--- a/packages/core/src/repowise/core/agents/identity.py
+++ b/packages/core/src/repowise/core/agents/identity.py
@@ -197,7 +197,12 @@ CODEX = AgentIdentity(
indexing_provider="codex_cli",
)
VSCODE = AgentIdentity(slug="vscode", display_name="VS Code", executable="code")
-CURSOR = AgentIdentity(slug="cursor", display_name="Cursor", executable="cursor")
+CURSOR = AgentIdentity(
+ slug="cursor",
+ display_name="Cursor",
+ hook_adapter="cursor",
+ executable="cursor",
+)
OPENCODE = AgentIdentity(
slug="opencode",
display_name="OpenCode",
diff --git a/scripts/gen_agent_matrix.py b/scripts/gen_agent_matrix.py
index e26e278d7..cee60bfc9 100644
--- a/scripts/gen_agent_matrix.py
+++ b/scripts/gen_agent_matrix.py
@@ -74,9 +74,9 @@ TIER_BLURBS: dict[str, tuple[str, str]] = {
"good": (
"Good",
"MCP tools plus a managed instructions file or skills, so the agent is "
- "told when to reach for them. **No hook-level interception and no "
- "transcript mining.** The agent can ask repowise questions; repowise "
- "cannot see or annotate what the agent does in between.",
+ "told when to reach for them. **No transcript mining, and hooks only "
+ "where the matrix says so.** The agent can ask repowise questions; "
+ "repowise sees little or nothing of what it does in between.",
),
"basic": (
"Basic",
@@ -292,6 +292,7 @@ def render() -> str:
counts = tool_counts()
ids = ", ".join(f"`{row['id']}`" for row in rows)
good = [row["display_name"] for row in rows if row["tier"] == "good"]
+ hooked = [row["display_name"] for row in rows if row["tier"] == "good" and row["hook_adapter"]]
basic = [row["display_name"] for row in rows if row["tier"] == "basic"]
parts = [
@@ -339,6 +340,15 @@ def render() -> str:
"a result afterwards. Nor is there transcript mining, so nothing learns",
"from the session after it ends.",
"",
+ ]
+ if hooked:
+ parts += [
+ f"The one exception is hooks: {_join_names(hooked)} "
+ f"{'runs' if len(hooked) == 1 else 'run'} the distill command-rewrite hook,",
+ "so noisy commands are rewritten there. Transcript mining is still absent.",
+ "",
+ ]
+ parts += [
"That is a real integration and it is most of the value. It is not the",
"same product Full-tier agents get, and breadth that overclaims depth is",
"worse than narrower breadth.",
diff --git a/tests/unit/cli/test_agent_targets.py b/tests/unit/cli/test_agent_targets.py
index 54847c9a1..6f79eb556 100644
--- a/tests/unit/cli/test_agent_targets.py
+++ b/tests/unit/cli/test_agent_targets.py
@@ -25,6 +25,7 @@ from repowise.cli.agent_targets.registry import (
)
from repowise.cli.agent_targets.types import (
AgentTarget,
+ DoctorStatus,
FileAction,
Scope,
Tier,
@@ -278,10 +279,37 @@ 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_user_scope_writes_only_the_rewrite_hook(
+ _isolated_home: Path, cursor_hooks_json: Path
+) -> None:
+ """User scope is the hook in ``~/.cursor/hooks.json``; never a global MCP entry."""
+ from repowise.cli.agent_targets.targets import cursor as cursor_target
+
+ target = get_target("cursor")
+ hooks = cursor_hooks_json
+ assert target.doctor().status is DoctorStatus.NOT_INSTALLED
+
+ first = target.install(Scope.USER)
+ assert [(f.path, f.action) for f in first.files] == [(hooks, FileAction.CREATED)]
+ assert not (_isolated_home / ".cursor" / "mcp.json").exists()
+ assert target.install(Scope.USER).files[0].action is FileAction.UNCHANGED
+ assert [r.scope for r in cursor_target.detect(None)] == [Scope.USER]
+ assert target.doctor().status is DoctorStatus.OK
+
+ removed = target.uninstall(Scope.USER)
+ assert [(f.path, f.action) for f in removed.files] == [(hooks, FileAction.REMOVED)]
+ assert cursor_target.detect(None) == []
+ assert target.uninstall(Scope.USER).files[0].action is FileAction.NOT_FOUND
+
+
+def test_cursor_user_scope_keeps_a_hooks_file_it_cannot_parse(cursor_hooks_json: Path) -> None:
+ target = get_target("cursor")
+ hooks = cursor_hooks_json
+ hooks.write_text('{"hooks": {"preToolUse": [{"command": "repowise-rewrite"', encoding="utf-8")
+
+ assert target.install(Scope.USER).files[0].action is FileAction.KEPT
+ assert target.uninstall(Scope.USER).files[0].action is FileAction.KEPT
+ assert target.doctor().status is DoctorStatus.BROKEN
def test_cursor_writes_its_own_config_key_not_vs_codes() -> None:
diff --git a/tests/unit/conftest.py b/tests/unit/conftest.py
new file mode 100644
index 000000000..d602bdafd
--- /dev/null
+++ b/tests/unit/conftest.py
@@ -0,0 +1,20 @@
+"""Guards shared by every unit test."""
+
+from __future__ import annotations
+
+import pytest
+
+
[email protected](autouse=True)
+def cursor_hooks_json(tmp_path_factory, monkeypatch):
+ """Keep every test off the developer's real ``~/.cursor/hooks.json``.
+
+ Rewrite-hook install paths run wherever ``~/.cursor`` exists, and not every
+ suite isolates ``$HOME``. Tests that want Cursor present patch ``detect``.
+ """
+ from repowise.cli.agent_adapters import cursor
+
+ hooks = tmp_path_factory.mktemp("cursor") / "hooks.json"
+ monkeypatch.setattr(cursor, "user_hooks_path", lambda: hooks)
+ monkeypatch.setattr(cursor.CursorAdapter, "detect", lambda self: False)
+ return hooks
diff --git a/tests/unit/distill/test_cursor_hook_adapter.py b/tests/unit/distill/test_cursor_hook_adapter.py
new file mode 100644
index 000000000..309514f76
--- /dev/null
+++ b/tests/unit/distill/test_cursor_hook_adapter.py
@@ -0,0 +1,230 @@
+"""Cursor hook adapter: ``preToolUse`` payloads, responses and ``hooks.json``.
+
+Payloads are synthetic, shaped after https://cursor.com/docs/agent/hooks.
+"""
+
+from __future__ import annotations
+
+import io
+import json
+import sys
+
+import pytest
+
+from repowise.cli import rewrite_hook
+from repowise.cli.agent_adapters import adapter_for
+from repowise.cli.agent_adapters import cursor as cursor_module
+from repowise.cli.agent_adapters.base import SHELL_POSIX, SHELL_POWERSHELL, RewriteResult
+from repowise.cli.agent_adapters.cursor import (
+ CursorAdapter,
+ cursor_rewrite_hook_matcher,
+ install_cursor_rewrite_hook,
+ uninstall_cursor_rewrite_hook,
+)
+
+
+def _payload(command: str = "pytest -x", **overrides) -> dict:
+ base = {
+ "conversation_id": "conv-1",
+ "generation_id": "gen-1",
+ "model": "some-model",
+ "hook_event_name": "preToolUse",
+ "cursor_version": "2.0.0",
+ "workspace_roots": ["/work/root"],
+ "user_email": None,
+ "transcript_path": None,
+ "tool_name": "Shell",
+ "tool_input": {"command": command, "working_directory": "/work/repo"},
+ "tool_use_id": "abc123",
+ "cwd": "/work/cwd",
+ }
+ base.update(overrides)
+ return base
+
+
+def adapter() -> CursorAdapter:
+ return CursorAdapter()
+
+
+class TestParsePayload:
+ def test_shell_pre_tool_use(self, adapter, monkeypatch) -> None:
+ monkeypatch.setattr(cursor_module.os, "name", "posix")
+ request = adapter.parse_hook_payload(json.dumps(_payload()))
+ assert request is not None
+ assert request.command == "pytest -x"
+ assert request.cwd == "/work/repo"
+ assert request.session_id == "conv-1"
+ assert request.shell == SHELL_POSIX
+
+ def test_windows_is_powershell(self, adapter, monkeypatch) -> None:
+ monkeypatch.setattr(cursor_module.os, "name", "nt")
+ request = adapter.parse_hook_payload(json.dumps(_payload()))
+ assert request is not None and request.shell == SHELL_POWERSHELL
+
+ def test_cwd_falls_back_to_cwd_then_workspace_root(self, adapter) -> None:
+ no_wd = _payload(tool_input={"command": "pytest"})
+ assert adapter.parse_hook_payload(json.dumps(no_wd)).cwd == "/work/cwd"
+ no_wd.pop("cwd")
+ assert adapter.parse_hook_payload(json.dumps(no_wd)).cwd == "/work/root"
+
+ @pytest.mark.parametrize(
+ "mutation",
+ [
+ {"hook_event_name": "beforeShellExecution"},
+ {"hook_event_name": "postToolUse"},
+ {"hook_event_name": "PreToolUse"},
+ {"tool_name": "Read"},
+ {"tool_name": "MCP:get_context"},
+ {"tool_input": {"command": " "}},
+ {"tool_input": "pytest"},
+ ],
+ )
+ def test_rejects_other_shapes(self, adapter, mutation) -> None:
+ assert adapter.parse_hook_payload(json.dumps(_payload(**mutation))) is None
+
+ @pytest.mark.parametrize("raw", ["", "{", "[]", "null", "7"])
+ def test_malformed_input_never_raises(self, adapter, raw) -> None:
+ assert adapter.parse_hook_payload(raw) is None
+
+
+class TestRenderResponse:
+ def test_echoes_the_whole_input_with_the_command_replaced(self, adapter) -> None:
+ adapter.parse_hook_payload(json.dumps(_payload()))
+ out = json.loads(
+ adapter.render_response(RewriteResult("repowise distill pytest -x", "allow", "r"))
+ )
+ assert out == {
+ "permission": "allow",
+ "updated_input": {
+ "command": "repowise distill pytest -x",
+ "working_directory": "/work/repo",
+ },
+ }
+
+ def test_capabilities(self, adapter) -> None:
+ assert adapter.rewrite_permissions == frozenset({"allow"})
+ assert adapter.replaces_tool_output is False
+ assert adapter.shell_tool_names == frozenset({"Shell"})
+ assert isinstance(adapter_for("cursor"), CursorAdapter)
+
+
+def _run_main(monkeypatch, payload: dict) -> str:
+ stdout = io.StringIO()
+ monkeypatch.setattr(sys, "stdin", io.StringIO(json.dumps(payload)))
+ monkeypatch.setattr(sys, "stdout", stdout)
+ monkeypatch.setattr(sys, "argv", ["repowise-rewrite", "--agent", "cursor"])
+ with pytest.raises(SystemExit):
+ rewrite_hook.main()
+ return stdout.getvalue()
+
+
+class TestMain:
+ def test_default_allow_rewrites(self, monkeypatch, tmp_path) -> None:
+ (tmp_path / ".repowise").mkdir()
+ payload = _payload(tool_input={"command": "pytest -x", "working_directory": str(tmp_path)})
+ out = json.loads(_run_main(monkeypatch, payload))
+ assert out["permission"] == "allow"
+ assert out["updated_input"]["command"] == "repowise distill --source hook-cursor pytest -x"
+ assert out["updated_input"]["working_directory"] == str(tmp_path)
+
+ def test_ask_passes_through(self, monkeypatch, tmp_path) -> None:
+ # preToolUse does not enforce "ask", so an ask family runs unrewritten.
+ (tmp_path / ".repowise").mkdir()
+ (tmp_path / ".repowise" / "config.yaml").write_text(
+ "distill:\n commands:\n permission: ask\n", encoding="utf-8"
+ )
+ payload = _payload(tool_input={"command": "pytest -x", "working_directory": str(tmp_path)})
+ assert _run_main(monkeypatch, payload) == ""
+
+
+class TestHooksJson:
+ def test_fresh_install(self, cursor_hooks_json) -> None:
+ assert install_cursor_rewrite_hook() == cursor_hooks_json
+ doc = json.loads(cursor_hooks_json.read_text(encoding="utf-8"))
+ assert doc == {
+ "hooks": {
+ "preToolUse": [
+ {"command": "repowise-rewrite --agent cursor", "matcher": "Shell", "timeout": 5}
+ ]
+ },
+ "version": 1,
+ }
+ assert cursor_rewrite_hook_matcher() == "Shell"
+ assert CursorAdapter().rewrite_hook_status().fires
+
+ def test_idempotent(self, cursor_hooks_json) -> None:
+ install_cursor_rewrite_hook()
+ before = cursor_hooks_json.read_bytes()
+ install_cursor_rewrite_hook()
+ assert cursor_hooks_json.read_bytes() == before
+
+ def test_coexists_with_user_hooks(self, cursor_hooks_json) -> None:
+ user = {
+ "version": 1,
+ "hooks": {
+ "preToolUse": [{"command": "./hooks/guard.sh", "matcher": "Shell"}],
+ "afterFileEdit": [{"command": "./hooks/format.sh"}],
+ },
+ }
+ cursor_hooks_json.write_text(json.dumps(user), encoding="utf-8")
+ install_cursor_rewrite_hook()
+ doc = json.loads(cursor_hooks_json.read_text(encoding="utf-8"))
+ assert doc["hooks"]["preToolUse"][0] == {"command": "./hooks/guard.sh", "matcher": "Shell"}
+ assert len(doc["hooks"]["preToolUse"]) == 2
+
+ assert uninstall_cursor_rewrite_hook() is True
+ assert json.loads(cursor_hooks_json.read_text(encoding="utf-8")) == user
+
+ def test_uninstall_of_our_only_entry_removes_the_file(self, cursor_hooks_json) -> None:
+ install_cursor_rewrite_hook()
+ assert uninstall_cursor_rewrite_hook() is True
+ assert not cursor_hooks_json.exists()
+ assert uninstall_cursor_rewrite_hook() is False
+
+ def test_malformed_file_is_left_alone(self, cursor_hooks_json) -> None:
+ cursor_hooks_json.write_text("{not json", encoding="utf-8")
+ assert install_cursor_rewrite_hook() is None
+ assert uninstall_cursor_rewrite_hook() is False
+ assert cursor_hooks_json.read_text(encoding="utf-8") == "{not json"
+
+
+def test_rewrite_install_covers_cursor_when_detected(cursor_hooks_json, monkeypatch) -> None:
+ from repowise.cli.commands.hook_cmd import _install_cursor_hook
+
+ _install_cursor_hook()
+ assert not cursor_hooks_json.exists() # no ~/.cursor, nothing written
+
+ monkeypatch.setattr(CursorAdapter, "detect", lambda self: True)
+ _install_cursor_hook()
+ assert cursor_rewrite_hook_matcher() == "Shell"
+
+
+ ("command", "ours"),
+ [
+ ("repowise-rewrite --agent cursor", True),
+ ("repowise-rewrite", True),
+ (r"C:\venv\Scripts\repowise-rewrite.exe --agent cursor", True),
+ (r'"C:\Program Files\rw\repowise-rewrite.exe" --agent cursor', True),
+ ("/usr/local/bin/repowise-rewrite --agent cursor", True),
+ ("./hooks/my-repowise-rewrite-wrapper.sh", False),
+ ("bash -c 'repowise-rewrite --agent cursor'", False),
+ ("node hooks/guard.js repowise-rewrite", False),
+ ],
+)
+def test_ownership_is_the_executable_basename(command: str, ours: bool) -> None:
+ assert cursor_module._is_rewrite_hook({"command": command}) is ours
+
+
+def test_uninstall_leaves_a_user_wrapper_that_mentions_us(cursor_hooks_json) -> None:
+ wrapper = {"command": "./hooks/repowise-rewrite-wrapper.sh", "matcher": "Shell"}
+ cursor_hooks_json.write_text(
+ json.dumps({"version": 1, "hooks": {"preToolUse": [wrapper]}}), encoding="utf-8"
+ )
+ assert cursor_rewrite_hook_matcher() is None
+ assert uninstall_cursor_rewrite_hook() is False
+ install_cursor_rewrite_hook()
+ assert uninstall_cursor_rewrite_hook() is True
+ doc = json.loads(cursor_hooks_json.read_text(encoding="utf-8"))
+ assert doc["hooks"]["preToolUse"] == [wrapper]