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(cli): add repowise uninstall, and make every removal path honest (#1467)

Raghav Chamadiyac4e08a74e5f1
diff --git a/README.md b/README.md
index c3a50585d..7b092bb14 100644
--- a/README.md
+++ b/README.md
@@ -781,6 +781,7 @@ repowise distill pytest # compact, errors-first, reversible command output
repowise saved # tokens and dollars saved by distillation
repowise workspace add # multi-repo workspace management
repowise doctor # check setup, API keys, index drift
+repowise uninstall # remove what repowise wrote, and say what it left
```
Every command and flag: **[docs/reference/CLI_REFERENCE.md](docs/reference/CLI_REFERENCE.md)** ·
diff --git a/docs/agent/CODEX.md b/docs/agent/CODEX.md
index fe897f037..ccff49cc3 100644
--- a/docs/agent/CODEX.md
+++ b/docs/agent/CODEX.md
@@ -120,7 +120,7 @@ The plugin does not carry these, and cannot: a Codex plugin manifest has no slot
repowise agents add --target=codex
```
-That writes one `repowise-*.md` per command, and `repowise agents remove --target=codex` takes them back out. Invoke them as `/prompts:repowise-risk`, `/prompts:repowise-ask` and so on. They are rendered from the same `plugins/shared/` source as the Claude Code plugin's commands, so the two hosts cannot drift.
+That writes one `repowise-*.md` per command, and `repowise agents remove --target=codex` takes them back out, along with `.codex/config.toml`, `.codex/hooks.json` and the managed block in `AGENTS.md`. To remove every agent at once, see [`repowise uninstall`](../reference/CLI_REFERENCE.md#repowise-uninstall-path). Invoke them as `/prompts:repowise-risk`, `/prompts:repowise-ask` and so on. They are rendered from the same `plugins/shared/` source as the Claude Code plugin's commands, so the two hosts cannot drift.
Note this is the mirror image of Claude Code, where the commands come from the plugin and `repowise init` never writes any.
diff --git a/docs/agent/HERMES.md b/docs/agent/HERMES.md
index 9d8ae6788..b9cb6bfb6 100644
--- a/docs/agent/HERMES.md
+++ b/docs/agent/HERMES.md
@@ -17,7 +17,9 @@ them, but no hook-level interception and no transcript mining. See the
[support matrix](INTEGRATIONS.md) for what that means in full.
Remove it with `repowise agents remove --target=hermes`, and check it with
-`repowise agents` or `repowise doctor`.
+`repowise agents` or `repowise doctor`. To remove every agent at once, along
+with the index and anything else repowise has written, see
+[`repowise uninstall`](../reference/CLI_REFERENCE.md#repowise-uninstall-path).
## What each scope writes
diff --git a/docs/agent/OPENCODE.md b/docs/agent/OPENCODE.md
index d9c515333..0d912d92e 100644
--- a/docs/agent/OPENCODE.md
+++ b/docs/agent/OPENCODE.md
@@ -39,7 +39,9 @@ Two things worth knowing:
of them leaves the section in place while another is still wired, and says so.
Remove it with `repowise agents remove --target=opencode`, and check it with
-`repowise agents` or `repowise doctor`.
+`repowise agents` or `repowise doctor`. To remove every agent at once, along
+with the index and anything else repowise has written, see
+[`repowise uninstall`](../reference/CLI_REFERENCE.md#repowise-uninstall-path).
## Prerequisites
diff --git a/docs/reference/CLI_REFERENCE.md b/docs/reference/CLI_REFERENCE.md
index 571040157..fe34bedf7 100644
--- a/docs/reference/CLI_REFERENCE.md
+++ b/docs/reference/CLI_REFERENCE.md
@@ -2,7 +2,7 @@
Complete reference for all `repowise` commands. For a guided introduction, see the [Quickstart](../start/QUICKSTART.md).
-Command list (in registration order): `augment`, `init`, `delete`, `generate-claude-md`, `costs`, `update`, `generate`, `dead-code`, `health`, `risk`, `decision`, `coverage`, `impacted-tests`, `search`, `distill`, `expand`, `saved`, `security`, `corrections`, `export`, `hook`, `status`, `doctor`, `watch`, `serve`, `mcp`, `reindex`, `restyle`, `wiki-styles`, `whats-new`, `telemetry`, `login`, `logout`, `whoami`, `workspace`. Two more ship as separate console scripts, not subcommands: `repowise-augment`, `repowise-rewrite` (both hook entry points, not meant to be run by hand).
+Command list (in registration order): `augment`, `init`, `delete`, `generate-claude-md`, `costs`, `update`, `generate`, `dead-code`, `health`, `risk`, `decision`, `coverage`, `impacted-tests`, `search`, `ask`, `context`, `symbol`, `why`, `distill`, `expand`, `saved`, `security`, `corrections`, `export`, `hook`, `agents`, `uninstall`, `status`, `doctor`, `watch`, `serve`, `mcp`, `reindex`, `restyle`, `wiki-styles`, `whats-new`, `telemetry`, `login`, `logout`, `whoami`, `workspace`. Two more ship as separate console scripts, not subcommands: `repowise-augment`, `repowise-rewrite` (both hook entry points, not meant to be run by hand).
**Do you need an LLM key?** Most commands are pure index/analysis and never call an LLM. `init` never requires a key: without one it renders the wiki from structure. It calls an LLM only when a provider is resolvable or `--prose` is passed. The exceptions: `update` (unless `--index-only` or `--no-docs`), `generate`, `restyle`, `watch` (when it regenerates a page), `health --generate-code`, and `workspace add --docs`. Everything else, `search`, `dead-code`, `health`, `risk`, `impacted-tests`, `decision`, `coverage`, `security`, `export`, `mcp`, `reindex`, `doctor`, and so on, works index-only, with no provider configured.
@@ -1442,6 +1442,61 @@ repowise delete <repo-id> --force # delete a specific repo's index, no pr
---
+### `repowise uninstall [PATH]`
+
+Remove what repowise has written, and report everything it did not remove and
+why. Wider than `repowise delete`, which removes one repository's rows from the
+index database and no files at all.
+
+Four groups, chosen independently:
+
+| Group | What it covers |
+|------|-------------|
+| `agents` | Every wired agent, both scopes, through each target's own uninstall |
+| `repo-files` | The managed blocks in `.claude/CLAUDE.md` and `AGENTS.md` |
+| `index` | The repo's `.repowise/` directory |
+| `global` | `~/.repowise/`: login, caches, telemetry preference |
+
+With a terminal and no flags it prints the inventory and asks. Otherwise say
+what you want removed:
+
+| Flag | Description |
+|------|-------------|
+| `--all` | Everything, including the index and machine-wide state |
+| `--keep-index` | The reinstall case: agent wiring and generated blocks only |
+| `--dry-run` | Print the plan and change nothing |
+| `--format table\|json` | `json` reports the plan, every path and what happened to it |
+
+**There is no `--yes`.** On every other command it means "run the default", and
+a partial uninstall is not a safe default, so the scope is named instead. With
+no terminal and no scope flag the command prints the inventory, removes nothing
+and exits non-zero.
+
+The index and machine-wide state are never pre-selected. The index is expensive
+to rebuild, and `~/.repowise/` is shared by every repo on the machine, which a
+command running inside one of them cannot see.
+
+Exit codes: `0` everything selected is gone, `1` a removal failed, `3` a removal
+was refused and something remains, `4` no scope was given and nobody could be
+asked. Each refusal prints its reason on the row.
+
+Two things it never touches: the package, which belongs to pip, uv or pipx, and
+the Claude Code plugin, which only `/plugin uninstall` can remove. It prints the
+right command for each.
+
+```bash
+repowise uninstall # show what is there, then ask
+repowise uninstall --all # everything, including index and login
+repowise uninstall --keep-index # drop the wiring, keep the index
+repowise uninstall --all --dry-run # what --all would do, changing nothing
+repowise uninstall --all --format json # the same, machine-readable
+```
+
+To remove a single agent rather than all of them, use
+[`repowise agents remove --target=<id>`](../agent/INTEGRATIONS.md).
+
+---
+
### `repowise augment`
Hook-driven context enrichment engine. Not meant to be called manually, invoked by Claude Code and Codex hooks installed during `repowise init`. Claude Code uses it for search-result enrichment, stale-wiki checks, and decision injection: session start gets the standing decisions relevant to the session's working set (relevance-ranked, hard token cap, silent when nothing clears the floor), and editing a governed file gets a one-line "governed by" notice once per session per decision. Codex uses it for `SessionStart`, `UserPromptSubmit`, and `PostToolUse` lifecycle guidance. Shown decisions are recorded in `.repowise/sessions/sessions.db` so the next `repowise update` can judge whether the guidance was followed or contradicted and adjust decision staleness.
diff --git a/docs/start/QUICKSTART.md b/docs/start/QUICKSTART.md
index 61865e6db..6713a8e20 100644
--- a/docs/start/QUICKSTART.md
+++ b/docs/start/QUICKSTART.md
@@ -349,6 +349,19 @@ repowise doctor --repair # fixes what it safely can
repowise status # what is indexed, and how stale it is
```
+## Taking it back out
+
+```bash
+repowise uninstall # list what repowise wrote, then ask what to remove
+repowise uninstall --all # everything: wiring, index, and machine-wide state
+repowise uninstall --dry-run # the same list, changing nothing
+```
+
+It reports every path it removed and every path it left, with the reason on the
+row. The index is not selected by default, because rebuilding it is the one
+expensive thing here. Full flags in the
+[CLI Reference](../reference/CLI_REFERENCE.md#repowise-uninstall-path).
+
## Environment variables
None of these are required. Every one of them is only needed for a model-written
diff --git a/docs/start/USER_GUIDE.md b/docs/start/USER_GUIDE.md
index 26db592dc..d4857af89 100644
--- a/docs/start/USER_GUIDE.md
+++ b/docs/start/USER_GUIDE.md
@@ -195,6 +195,7 @@ Grouped by what you are trying to do. Every flag for every command lives in the
| `repowise costs` | What indexing has cost you, by provider and operation. |
| `repowise generate-claude-md` | Regenerate `CLAUDE.md` / `AGENTS.md` on demand. |
| `repowise telemetry disable` | Turn off anonymous usage telemetry. |
+| `repowise uninstall` | Remove what repowise wrote from this repo, and optionally this machine. It lists everything first, and says what it left and why. |
---
diff --git a/packages/cli/src/repowise/cli/_instrumented_group.py b/packages/cli/src/repowise/cli/_instrumented_group.py
index cc956c845..3977ca080 100644
--- a/packages/cli/src/repowise/cli/_instrumented_group.py
+++ b/packages/cli/src/repowise/cli/_instrumented_group.py
@@ -102,7 +102,22 @@ class InstrumentedGroup(click.Group):
def invoke(self, ctx: click.Context):
from repowise.cli.platform import telemetry
- telemetry.maybe_show_notice()
+ # Not for ``uninstall``. Reading the consent state resolves
+ # ``~/.repowise/``, and that resolution creates the directory even on a
+ # pure read, so this ran before any command code and put back the
+ # directory the previous ``uninstall --all`` had deleted. The command
+ # then reported machine-wide state ``removed`` on every run, forever.
+ #
+ # Two other writes to the same directory had to be stopped for the same
+ # reason (the spool on the way out, the self-heal stamp in ``main``).
+ # This is the earliest of the three, which is why it survived them.
+ # Read from the unparsed args, not from ``ctx.invoked_subcommand``:
+ # Click sets that inside ``MultiCommand.invoke``, which is the call we
+ # are wrapping, so up here it is still None for every command and the
+ # guard silently never fired.
+ pending = getattr(ctx, "protected_args", None) or ctx.args
+ if not pending or pending[0] != "uninstall":
+ telemetry.maybe_show_notice()
# The unparsed tail (subcommand + its args) is captured now, before
# ``super().invoke`` may consume it.
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 be7f14550..95c424867 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
@@ -57,6 +57,40 @@ class BlockInspection:
body: str | None = None
+#: Why a refused state was refused, in the words the user needs to fix it.
+#: Lives here rather than at each call site so the six targets cannot drift into
+#: six descriptions of the same refusal.
+_REFUSALS = {
+ BlockState.ORPHANED: (
+ "one of our two markers is missing, so the block's end is unknowable; "
+ "delete the leftover marker by hand"
+ ),
+ BlockState.DUPLICATED: (
+ "more than one managed block is present, so removing them could take "
+ "text written between them; reconcile them by hand"
+ ),
+ BlockState.UNREADABLE: "the file could not be read, so its contents are unknown",
+ # Reachable, despite looking like it should not be. ``remove`` returns False
+ # on a write error with the block still in place, and every caller
+ # re-inspects afterwards, so a permission error on a real block lands here.
+ # It used to fall through to the "unexpected block state" branch and reach
+ # the user as the word "present".
+ BlockState.PRESENT: "the file could not be written, so our block is still in it",
+}
+
+
+def refusal_reason(state: BlockState) -> str:
+ """The one-line reason a ``KEPT`` row should carry for a refused *state*.
+
+ Deliberately total: every state gets a sentence rather than ``None``, so no
+ row can reach a user with an empty reason. ``PRESENT`` is in the table and
+ is reachable, because :func:`remove` returns False with the block untouched
+ when the write fails. Callers should read that state as a failure rather
+ than a refusal; the sentence here says so.
+ """
+ return _REFUSALS.get(state, f"unexpected block state {state.value}")
+
+
def inspect(path: Path, start: str, end: str) -> BlockInspection:
"""Report what *path* holds for the ``start``/``end`` marker pair."""
if not path.exists():
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 59acfad2f..8b010ea0a 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
@@ -131,6 +131,167 @@ def replace_table(existing_text: str, table_name: str, block: str) -> str:
return f"{merged_text}\n\n{block}\n" if merged_text else f"{block}\n"
+#: A line that is blank, or holds nothing but a comment.
+#:
+#: TOML has no way to say who a trailing comment belongs to. A run of them
+#: between our table and whatever follows could be annotating either. On the
+#: destructive verb the tie has to break towards the user, so these lines are
+#: never part of what we remove.
+_TRAILING_NOISE = re.compile(r"^[ \t]*(#.*)?$")
+
+
+def remove_table(existing_text: str, table_name: str) -> str:
+ """Strip *table_name* from *existing_text*, keeping every comment.
+
+ Shares :func:`replace_table`'s regex for finding the table, and then does
+ something that function does not: **peels the trailing comments and blank
+ lines back off the match before deleting it.**
+
+ That step is the whole function. The shared pattern runs to the next table
+ header, and ``\\s`` does not match a ``#``, so a comment line never ends the
+ span. On the merge path the consequence is a lost comment. On this path it
+ was far worse: everything from our header to the next live header was
+ consumed, so a file whose remainder was a commented-out server and the
+ user's notes came back empty, and the caller read empty as "this file was
+ ours" and deleted it. An empty parse is not an empty file, and an emptiness
+ test is worthless when the thing being tested has already eaten the
+ evidence.
+
+ Comments *inside* the table, annotating our own keys, go with it. Only the
+ trailing run is preserved, because only the trailing run can belong to
+ something else.
+
+ The bare ``[table.name]`` spelling is still the only one recognised, so a
+ table written as a quoted key or nested inline under its parent survives
+ silently. Callers must re-parse the result and confirm the key is gone
+ rather than trusting the returned text.
+ """
+ table_re = re.compile(
+ r"(?ms)^\s*\[" + re.escape(table_name) + r"\]\s*\n.*?(?=^\s*\[|\Z)",
+ )
+
+ def _keep_trailing_noise(match: re.Match[str]) -> str:
+ lines = match.group(0).splitlines(keepends=True)
+ cut = len(lines)
+ while cut > 0 and _TRAILING_NOISE.match(lines[cut - 1].rstrip("\r\n")):
+ cut -= 1
+ return "".join(lines[cut:])
+
+ remaining = table_re.sub(_keep_trailing_noise, existing_text)
+ if not remaining.strip():
+ return ""
+ # The file's own ending, not the platform's: this is a config the user owns
+ # and a rewritten last line is a diff on every Windows checkout.
+ newline = "\r\n" if "\r\n" in existing_text else "\n"
+ return remaining.rstrip("\r\n \t") + newline
+
+
+def remove_key_line(existing_text: str, table_name: str, key: str) -> str:
+ """Delete one ``key = ...`` line from *table_name*, leaving the rest alone.
+
+ The surgical alternative to upserting the table without the key, and the
+ right tool whenever the table is the user's rather than ours.
+ ``[features]`` is Codex's own, and re-rendering it to drop one key had two
+ failure modes that a single-line delete simply does not have: the narrow
+ serializer raises on any value type it cannot encode, so a user with
+ ``retries = [1, 2, 3]`` got a ``TypeError`` mid-uninstall; and
+ :func:`replace_table` rebuilds the table from the parsed dict, so every
+ comment inside it was dropped and the whole table moved to the end of the
+ file.
+
+ Only a single-line ``key = value`` is removed. A value continued across
+ lines is left entirely in place, and the caller sees that when it re-parses
+ and finds the key still there.
+
+ That refusal is the load-bearing part. Deleting the first line of
+
+ .. code-block:: toml
+
+ hooks = [
+ "a",
+ ]
+
+ orphans the rest into ``[features]\\n "a",\\n]``, which is not TOML at all.
+ The caller's own validation then raised, from a helper whose message says
+ "no changes were written", by which point the server table had been written
+ out of the file and the hooks file deleted. A removal that cannot see where
+ a value ends must decline rather than cut at the first newline.
+ """
+ table_re = re.compile(
+ r"(?ms)^\s*\[" + re.escape(table_name) + r"\]\s*\n.*?(?=^\s*\[|\Z)",
+ )
+ key_re = re.compile(r"(?m)^[ \t]*" + re.escape(key) + r"[ \t]*=([^\n]*)\r?\n?")
+
+ def _drop(match: re.Match[str]) -> str:
+ head, _, body = match.group(0).partition("\n")
+ found = key_re.search(body)
+ if found is None or not _value_is_complete(found.group(1)):
+ return match.group(0)
+ # A line reading ``hooks = true`` inside an earlier key's multi-line
+ # string is text, not a key. Cutting it silently edited the user's
+ # value and left a file that still parsed, so nothing downstream
+ # noticed. An odd number of triple quotes before the match means we are
+ # inside one.
+ before = body[: found.start()]
+ if before.count('"""') % 2 or before.count("'''") % 2:
+ return match.group(0)
+ return f"{head}\n{before}{body[found.end() :]}"
+
+ return table_re.sub(_drop, existing_text, count=1)
+
+
+def _value_is_complete(value: str) -> bool:
+ """Whether *value* is a whole TOML value rather than the head of one.
+
+ Counts brackets and braces outside of strings, and refuses an unterminated
+ string or a multi-line basic string opener. Deliberately conservative: any
+ shape it is unsure about is reported incomplete, because the only cost of a
+ false negative is a key left in place and reported honestly, while a false
+ positive writes a file that no longer parses.
+ """
+ if '"""' in value or "'''" in value:
+ return False
+ depth = 0
+ quote: str | None = None
+ escaped = False
+ for char in value:
+ if quote is not None:
+ if escaped:
+ escaped = False
+ elif char == "\\" and quote == '"':
+ escaped = True
+ elif char == quote:
+ quote = None
+ continue
+ if char in "\"'":
+ quote = char
+ elif char in "[{":
+ depth += 1
+ elif char in "]}":
+ depth -= 1
+ elif char == "#":
+ break
+ return quote is None and depth == 0
+
+
+def table_is_bare(existing_text: str, table_name: str) -> bool:
+ """True when *table_name* holds no keys and no comments, only its header.
+
+ The safe precondition for removing a table wholesale: nothing of the user's
+ is inside it, so nothing of the user's can be lost with it.
+ """
+ table_re = re.compile(
+ r"(?ms)^\s*\[" + re.escape(table_name) + r"\]\s*\n(.*?)(?=^\s*\[|\Z)",
+ )
+ match = table_re.search(existing_text)
+ if match is None:
+ return False
+ return all(
+ _TRAILING_NOISE.match(line.rstrip("\r\n")) and not line.strip().startswith("#")
+ for line in match.group(1).splitlines()
+ )
+
+
def write_if_changed(
config_path: Path,
merged_text: str,
diff --git a/packages/cli/src/repowise/cli/agent_targets/targets/claude_code.py b/packages/cli/src/repowise/cli/agent_targets/targets/claude_code.py
index a32057200..4b28d9195 100644
--- a/packages/cli/src/repowise/cli/agent_targets/targets/claude_code.py
+++ b/packages/cli/src/repowise/cli/agent_targets/targets/claude_code.py
@@ -139,6 +139,47 @@ def write_project_mcp_config(repo_path: Path) -> FileWrite:
return FileWrite(path=config_path, action=write_json_config(config_path, merged))
+def _remove_project_mcp_entry(config_path: Path) -> tuple[Path, FileAction, str | None]:
+ """Drop ``mcpServers.repowise`` from the repo-root ``.mcp.json``.
+
+ The file is repo-shared and usually committed, which cuts both ways: other
+ contributors' servers must survive, and a stub left behind lands in everyone
+ else's diff. So the wrapper goes when it empties and the file goes with it.
+
+ Deleting on an empty parse is sound here only because the parse is strict
+ JSON: a file carrying comments raises above and is kept untouched, so
+ anything reaching the prune genuinely held nothing but our entry.
+ """
+ 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, None
+ try:
+ existing = load_json_object_or_value_error(config_path, ".mcp.json")
+ except ValueError:
+ return (
+ config_path,
+ FileAction.KEPT,
+ "not strict JSON, so removing our entry would drop comments",
+ )
+
+ servers = existing.get("mcpServers")
+ if not isinstance(servers, dict) or "repowise" not in servers:
+ return config_path, FileAction.NOT_FOUND, None
+ servers.pop("repowise")
+ if not servers:
+ existing.pop("mcpServers", None)
+ if not existing:
+ try:
+ config_path.unlink()
+ except OSError:
+ write_json_config(config_path, existing)
+ return config_path, FileAction.REMOVED, None
+
+ write_json_config(config_path, existing)
+ return config_path, FileAction.REMOVED, None
+
+
# ---------------------------------------------------------------------------
# Detection
# ---------------------------------------------------------------------------
@@ -378,24 +419,68 @@ class ClaudeCodeTarget:
return result
def uninstall(self, scope: Scope, *, repo_path: Path | None = None) -> WriteResult:
- """Remove the distill rewrite hook; leave sibling user hooks intact.
-
- Scoped narrowly on purpose. Tearing the augment hooks and the MCP
- registration out is not something any command asks for today, and a
- half-written uninstall is worse than none — the surface grows in
- Phase 2 alongside the command that needs it.
+ """Remove everything the direct install path wrote, and nothing else.
+
+ Three things, where this used to remove one. The rewrite hook, the
+ augment hooks and the MCP registration were all written by ``install``
+ and all survived ``uninstall``, so removing this target left Claude Code
+ launching our server and spawning our hooks for a repo it had just been
+ unwired from. At project scope it left ``.mcp.json`` untouched entirely
+ and reported ``KEPT`` about a file it had never looked at.
+
+ What stays out of reach is the plugin. ``~/.claude/plugins`` is
+ host-owned, documented at the top of this module as ours to read and
+ never to write, and only ``/plugin uninstall`` can remove it. The
+ caller surfaces that line rather than us writing the manifest.
"""
from repowise.cli.editor_integrations.claude_config import (
+ claude_code_leftover_reason,
+ claude_desktop_leftover_reason,
+ uninstall_claude_code_augment_hooks,
+ uninstall_claude_code_mcp_entry,
uninstall_claude_code_rewrite_hook,
+ uninstall_claude_desktop_mcp_entry,
)
result = WriteResult()
- settings = settings_path()
if scope is not Scope.USER:
- result.record(settings, FileAction.KEPT)
+ if repo_path is None:
+ raise ValueError("project-scope uninstall needs a repo_path")
+ result.record(*_remove_project_mcp_entry(project_mcp_config_path(repo_path)))
return result
+
+ settings = settings_path()
+ # Each returns True only when it changed the file, so the aggregate is a
+ # real answer rather than "we tried three things". Not short-circuited:
+ # `or` would skip the later removals whenever an earlier one succeeded.
removed = uninstall_claude_code_rewrite_hook()
- result.record(settings, FileAction.REMOVED if removed else FileAction.NOT_FOUND)
+ removed = uninstall_claude_code_augment_hooks() or removed
+ removed = uninstall_claude_code_mcp_entry() or removed
+ # The Desktop config too, because `install` writes it and `detect` reads
+ # it. Leaving it made a removed Claude Code still look wired, so the
+ # next `doctor --repair` reinstalled everything this had just removed.
+ #
+ # Its own row, with its own probe. Folding its reason into the
+ # settings.json row named one file and described another.
+ desktop_removed = uninstall_claude_desktop_mcp_entry()
+ desktop = desktop_config_path()
+ if desktop is not None:
+ desktop_leftover = claude_desktop_leftover_reason()
+ if desktop_leftover is not None:
+ result.record(desktop, FileAction.KEPT, desktop_leftover)
+ elif desktop_removed:
+ result.record(desktop, FileAction.REMOVED)
+ removed = desktop_removed or removed
+
+ # Asked of the file, not inferred from the three booleans. Each of them
+ # returns False for "nothing of ours was here", "could not parse" and
+ # "the write failed" alike, and reporting the last two as not-found is a
+ # claim that we looked and the file was clean.
+ leftover = claude_code_leftover_reason()
+ if leftover is not None:
+ result.record(settings, FileAction.KEPT, leftover)
+ else:
+ result.record(settings, FileAction.REMOVED if removed else FileAction.NOT_FOUND)
return result
def print_config(self, scope: Scope, *, repo_path: Path | None = None) -> str:
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 b193077bf..75c4fe831 100644
--- a/packages/cli/src/repowise/cli/agent_targets/targets/codex.py
+++ b/packages/cli/src/repowise/cli/agent_targets/targets/codex.py
@@ -32,6 +32,8 @@ Two quirks preserved from the existing implementation, both load-bearing:
from __future__ import annotations
+import json
+import tomllib
from pathlib import Path
from ..types import (
@@ -292,6 +294,336 @@ def write_hooks_config(repo_path: Path) -> tuple[FileWrite, FileWrite]:
return FileWrite(path=hooks_path, action=action), enable_hooks_feature(repo_path)
+def remove_hooks_config(repo_path: Path) -> FileWrite:
+ """Strip our hook entries from ``.codex/hooks.json``, sparing the user's.
+
+ A two-pass prune, not a file delete: drop our commands from each matcher
+ group, drop a group we emptied, drop an event left with no groups, drop the
+ ``hooks`` key once it holds nothing, and unlink the file only when the whole
+ document is empty. A user who added their own hook to the same event keeps
+ it, and keeps the event.
+
+ The ownership test is :func:`_is_augment_hook`, the same predicate install
+ uses to decide a matcher already carries our entry. It matches on the
+ command string rather than on the entry's shape, which is sound here for a
+ reason worth stating: the string it looks for is a repowise executable, so a
+ hook carrying it is a repowise hook whoever typed it, and leaving one behind
+ after an uninstall would spawn a process for a tool that is no longer wired.
+ """
+ from ..formats.json_merge import load_json_object_or_value_error, write_json_config
+
+ hooks_path = project_hooks_path(repo_path)
+ if not hooks_path.exists():
+ return FileWrite(path=hooks_path, action=FileAction.NOT_FOUND)
+ try:
+ existing = load_json_object_or_value_error(hooks_path, "hooks.json")
+ except ValueError:
+ return FileWrite(
+ path=hooks_path,
+ action=FileAction.KEPT,
+ reason="not strict JSON, so removing our entries would drop comments",
+ )
+
+ hooks = existing.get("hooks")
+ if not isinstance(hooks, dict):
+ return FileWrite(path=hooks_path, action=FileAction.NOT_FOUND)
+
+ changed = False
+ for event, entries in list(hooks.items()):
+ if not isinstance(entries, list):
+ continue
+ # An event that was already empty is not something we emptied, and
+ # popping it reported REMOVED over a file holding none of our hooks
+ # while quietly deleting a key the user had written.
+ if not entries:
+ continue
+ surviving: list[object] = []
+ for entry in entries:
+ if not isinstance(entry, dict) or not isinstance(entry.get("hooks"), list):
+ surviving.append(entry)
+ continue
+ inner = entry["hooks"]
+ remaining = [h for h in inner if not (isinstance(h, dict) and _is_augment_hook(h))]
+ if len(remaining) == len(inner):
+ surviving.append(entry)
+ continue
+ changed = True
+ # A group that held only our hook goes with it. A group the user
+ # also wrote in keeps everything except ours.
+ if remaining:
+ entry["hooks"] = remaining
+ surviving.append(entry)
+ if surviving:
+ hooks[event] = surviving
+ else:
+ hooks.pop(event)
+ changed = True
+
+ if not changed:
+ return FileWrite(path=hooks_path, action=FileAction.NOT_FOUND)
+ if not hooks:
+ existing.pop("hooks", None)
+
+ if not existing:
+ try:
+ hooks_path.unlink()
+ except OSError:
+ # Falling through to the rewrite rather than swallowing: reporting
+ # REMOVED over a file we failed to delete is the false success this
+ # track has already shipped once.
+ write_json_config(hooks_path, existing)
+ return FileWrite(path=hooks_path, action=FileAction.REMOVED)
+
+ write_json_config(hooks_path, existing)
+ return FileWrite(path=hooks_path, action=FileAction.REMOVED)
+
+
+def remove_server_config(repo_path: Path, *, drop_hooks_feature: bool) -> FileWrite:
+ """Strip ``[mcp_servers.repowise]``, and the hooks feature when it is ours to drop.
+
+ *drop_hooks_feature* is decided by the caller from what the hooks file looks
+ like afterwards. ``features.hooks`` is Codex's global switch, not a repowise
+ key: turning it off while the user still has hooks of their own in
+ ``.codex/hooks.json`` would silently disable them. So it goes only when
+ nothing is left for it to enable.
+
+ Both removals are re-parsed and re-checked rather than trusted.
+ :func:`~..formats.toml_merge.remove_table` works by regex over the source
+ text, which is what preserves the user's comments everywhere else in the
+ file, and which is also why a table spelled some other legal way slips past
+ it. A silent miss on the destructive verb reads as a successful uninstall
+ over a file that still launches our server.
+ """
+ import click
+
+ from ..formats.toml_merge import (
+ ensure_valid_toml,
+ load_toml_document,
+ remove_key_line,
+ remove_table,
+ require_table,
+ table_is_bare,
+ )
+
+ config_path = project_config_path(repo_path)
+ if not config_path.exists():
+ return FileWrite(path=config_path, action=FileAction.NOT_FOUND)
+
+ existing_text = config_path.read_text(encoding="utf-8")
+ doc = load_toml_document(config_path, existing_text)
+
+ servers = require_table(doc, "mcp_servers", config_path, "mcp_servers")
+ has_server = isinstance(servers, dict) and "repowise" in servers
+ features = require_table(doc, "features", config_path, "features") or {}
+ has_feature = drop_hooks_feature and "hooks" in features
+
+ if not has_server and not has_feature:
+ return FileWrite(path=config_path, action=FileAction.NOT_FOUND)
+
+ # The two edits are applied and validated **independently**, and that is the
+ # whole shape of this function. Accumulating both into one string and
+ # gating the write on "did either fail" meant a `features.hooks` value the
+ # line remover declines to cut (a multi-line array, Codex's own key, nothing
+ # to do with us) threw away a perfectly good removal of
+ # `[mcp_servers.repowise]` as well, and blamed it on "the repowise entry
+ # uses a key spelling this remover cannot match" when the repowise entry
+ # was fine. Codex went on launching our MCP server.
+ def _attempt(text: str, edit, gone) -> tuple[str, bool]:
+ """Apply *edit*, keep it only if it parses and *gone* says the key went."""
+ candidate = edit(text)
+ try:
+ parsed = ensure_valid_toml(candidate, config_path) if candidate.strip() else {}
+ except click.ClickException:
+ return text, False
+ return (candidate, True) if gone(parsed) else (text, False)
+
+ merged_text = existing_text
+ server_refused = feature_refused = False
+
+ if has_server:
+ merged_text, ok = _attempt(
+ merged_text,
+ lambda text: remove_table(text, "mcp_servers.repowise"),
+ lambda doc: "repowise" not in (doc.get("mcp_servers") or {}),
+ )
+ server_refused = not ok
+
+ if has_feature:
+ # One line, not a re-render. ``[features]`` is Codex's table, so
+ # rebuilding it from the parse would drop the user's comments inside it
+ # and raise outright on any value the narrow serializer cannot encode.
+ def _drop_feature(text: str) -> str:
+ text = remove_key_line(text, "features", "hooks")
+ return remove_table(text, "features") if table_is_bare(text, "features") else text
+
+ merged_text, ok = _attempt(
+ merged_text,
+ _drop_feature,
+ lambda doc: "hooks" not in (doc.get("features") or {}),
+ )
+ feature_refused = not ok
+
+ # Keyed on whether anything actually moved, not on which flag is set. The
+ # earlier spelling asked `server_refused and ...`, which is never true when
+ # there was no server table to remove, so a lone declined `features.hooks`
+ # fell through, wrote the file back byte-identical, skipped a re-check
+ # gated on `has_server`, and reported REMOVED with no reason. Three runs in
+ # a row said `removed` over an unchanged file, and run 2 of the ordinary
+ # flow lands in exactly that shape.
+ changed = (has_server and not server_refused) or (has_feature and not feature_refused)
+ if not changed:
+ return FileWrite(
+ path=config_path,
+ action=FileAction.KEPT,
+ reason=(
+ "the repowise entry uses a key spelling this remover cannot match; "
+ "delete it by hand"
+ )
+ if server_refused
+ else "features.hooks holds a value this remover cannot cut; delete it by hand",
+ )
+
+ try:
+ if not merged_text.strip():
+ try:
+ config_path.unlink()
+ except OSError:
+ config_path.write_text(merged_text, encoding="utf-8")
+ else:
+ config_path.write_text(merged_text, encoding="utf-8")
+ except OSError as exc:
+ # Escaping here reached `agents remove`, which wraps nothing, as a
+ # traceback part-way through a batch.
+ return FileWrite(path=config_path, action=FileAction.FAILED, reason=str(exc))
+
+ # Proven from disk, never from ``merged_doc``: a check fed a value derived
+ # from our own output cannot fail, which is exactly how ``agents remove``
+ # came to report REMOVED over a file that still held the entry. Each key is
+ # re-checked only where the edit was actually applied, so a deliberate
+ # decline is not reported as a failed write.
+ if config_path.exists():
+ try:
+ written = tomllib.loads(config_path.read_text(encoding="utf-8"))
+ except (OSError, ValueError, tomllib.TOMLDecodeError):
+ written = {}
+ left_server = has_server and not server_refused
+ left_server = left_server and "repowise" in (written.get("mcp_servers") or {})
+ left_feature = has_feature and not feature_refused
+ left_feature = left_feature and "hooks" in (written.get("features") or {})
+ if left_server or left_feature:
+ return FileWrite(
+ path=config_path,
+ action=FileAction.KEPT,
+ reason="the entry was still present after the write",
+ )
+
+ # Something went, and something else was declined. Both halves belong in
+ # the report: a bare REMOVED here would be true of the server table and
+ # silently false of the flag.
+ if feature_refused:
+ return FileWrite(
+ path=config_path,
+ action=FileAction.REMOVED,
+ reason="features.hooks was left in place; its value is one this remover cannot cut",
+ )
+ if server_refused:
+ return FileWrite(
+ path=config_path,
+ action=FileAction.REMOVED,
+ reason="the repowise server entry was left in place; delete it by hand",
+ )
+ return FileWrite(path=config_path, action=FileAction.REMOVED)
+
+
+def _config_parse_refusal(repo_path: Path) -> str | None:
+ """Why ``config.toml`` cannot be edited, or ``None`` when it can.
+
+ Asked before anything is removed, so a file we cannot read stops the run
+ cleanly at the start rather than raising out of the middle of it. The merge
+ path is right to raise: it is called from `install`, where aborting leaves
+ the file untouched. Removal is called from a batch that has already deleted
+ things by the time it gets here.
+ """
+ config_path = project_config_path(repo_path)
+ if not config_path.exists():
+ return None
+ try:
+ doc = tomllib.loads(config_path.read_text(encoding="utf-8"))
+ except (OSError, ValueError, tomllib.TOMLDecodeError):
+ return "the file is not valid TOML, so editing it would lose whatever we misread"
+ for key in ("mcp_servers", "features"):
+ value = doc.get(key)
+ if value is not None and not isinstance(value, dict):
+ return f"[{key}] is not a table in this file, so our entry cannot be located"
+ return None
+
+
+def _user_hooks_leftover_reason() -> str | None:
+ """Why ``~/.codex/hooks.json`` still has us in it, read from disk. None when clean."""
+ path = user_hooks_path()
+ if not path.exists():
+ return None
+ try:
+ doc = json.loads(path.read_text(encoding="utf-8"))
+ except (OSError, ValueError):
+ try:
+ if b"repowise" not in path.read_bytes().lower():
+ return None
+ except OSError:
+ return None
+ return "the file could not be read and still mentions repowise"
+ hooks = doc.get("hooks") if isinstance(doc, dict) else None
+ if not isinstance(hooks, dict):
+ return None
+ for entries in hooks.values():
+ if not isinstance(entries, list):
+ continue
+ for entry in entries:
+ if not isinstance(entry, dict) or not isinstance(entry.get("hooks"), list):
+ continue
+ for hook in entry["hooks"]:
+ if isinstance(hook, dict) and "repowise" in str(hook.get("command", "")):
+ return "one of our hooks was still present after the write"
+ return None
+
+
+def _hooks_file_has_entries(hooks_path: Path) -> bool:
+ """Whether ``hooks.json`` still holds any hook at all.
+
+ Read from disk rather than inferred from what the removal returned, and
+ deliberately broader than "has a `hooks` key with something in it": a file
+ we cannot parse might hold anything, and switching off the feature that runs
+ it would be a guess about somebody else's file.
+ """
+ if not hooks_path.exists():
+ return False
+ try:
+ doc = json.loads(hooks_path.read_text(encoding="utf-8"))
+ except (OSError, ValueError):
+ return True
+ hooks = doc.get("hooks") if isinstance(doc, dict) else None
+ # A file with no hooks left but other keys still in it is the user's file,
+ # and still not a reason to keep the feature switched on.
+ return isinstance(hooks, dict) and any(entries for entries in hooks.values())
+
+
+def prune_project_dir(repo_path: Path) -> None:
+ """Remove ``.codex/`` once uninstall emptied it, and never otherwise.
+
+ ``rmdir`` rather than a recursive delete, so a directory holding anything at
+ all, ours or the user's, is left exactly as it is. The symlink guard is the
+ one Cursor already carries: following a junction out of the repo to delete
+ something is not a risk worth a tidy directory.
+ """
+ directory = project_config_path(repo_path).parent
+ if directory.is_symlink() or not directory.is_dir():
+ return
+ try:
+ directory.rmdir()
+ except OSError:
+ return
+
+
#: Namespace for every prompt this target writes. ``~/.codex/prompts`` is a flat
#: global directory shared with every other tool the user has installed, so the
#: prefix is what keeps our filenames from colliding with theirs.
@@ -371,7 +703,13 @@ def write_prompts() -> list[FileWrite]:
directory.mkdir(parents=True, exist_ok=True)
atomic_write_text(path, text, newline="\n")
except OSError:
- writes.append(FileWrite(path=path, action=FileAction.KEPT))
+ writes.append(
+ FileWrite(
+ path=path,
+ action=FileAction.KEPT,
+ reason="could not be written (permission, or a directory in its place)",
+ )
+ )
continue
writes.append(
FileWrite(path=path, action=FileAction.UPDATED if existed else FileAction.CREATED)
@@ -398,9 +736,18 @@ def remove_prompts() -> list[FileWrite]:
removed: list[FileWrite] = []
for name, _text in bundled_prompts():
path = directory / name
+ existed = path.exists()
try:
path.unlink()
- except OSError:
+ except OSError as exc:
+ # Reported rather than skipped. Producing no row at all for a file
+ # we could not delete meant the caller saw no leftover, so
+ # `repowise uninstall` printed "everything selected is gone" and
+ # exited zero over a prompt still sitting in the user's directory.
+ if existed:
+ removed.append(
+ FileWrite(path=path, action=FileAction.FAILED, reason=str(exc))
+ )
continue
removed.append(FileWrite(path=path, action=FileAction.REMOVED))
return removed
@@ -555,7 +902,7 @@ class CodexTarget:
# separate directory, and a Codex build too old for PreToolUse rewriting
# still reads slash commands perfectly well.
for written in write_prompts():
- result.record(written.path, written.action)
+ result.record(written.path, written.action, written.reason)
return result
def uninstall(self, scope: Scope, *, repo_path: Path | None = None) -> WriteResult:
@@ -567,12 +914,21 @@ class CodexTarget:
result = WriteResult()
if scope is Scope.USER:
removed = uninstall_codex_rewrite_hook()
- result.record(
- user_hooks_path(),
- FileAction.REMOVED if removed else FileAction.NOT_FOUND,
- )
+ # Asked of the file rather than inferred from the boolean, for the
+ # same reason Claude Code's user scope is: that return is False for
+ # "nothing of ours was here", "could not parse" and "the write
+ # failed" alike, and calling the last two not-found claims we looked
+ # and the file was clean.
+ leftover = _user_hooks_leftover_reason()
+ if leftover is not None:
+ result.record(user_hooks_path(), FileAction.KEPT, leftover)
+ else:
+ result.record(
+ user_hooks_path(),
+ FileAction.REMOVED if removed else FileAction.NOT_FOUND,
+ )
for deleted in remove_prompts():
- result.record(deleted.path, deleted.action)
+ result.record(deleted.path, deleted.action, deleted.reason)
return result
if repo_path is None:
@@ -596,14 +952,55 @@ class CodexTarget:
# added most recently leaves the identical bug in its siblings, which is
# how this class of defect has kept surviving a review round on this
# track.
+ # The two config files install writes go first, and unconditionally.
+ # They used to be left behind entirely: `describe_paths` listed them as
+ # ours, install wrote both, and uninstall touched neither, so a removed
+ # Codex kept launching our MCP server and spawning our hooks. `.codex/`
+ # is gitignored in most repos, so `git status` showed nothing either.
+ # Computed up front so the config decision is made against the file as
+ # the user left it. It gates the config edit below, not the hooks
+ # removal: the two files are independent, and a config we cannot read is
+ # no reason to leave our hooks running.
+ hooks_path = project_hooks_path(repo_path)
+ parse_refusal = _config_parse_refusal(repo_path)
+
+ # Hooks first, then one pass over config.toml. Two passes over the same
+ # file put two rows for one path in the report, which is contradictory
+ # the moment they disagree.
+ hooks_write = remove_hooks_config(repo_path)
+ result.record(hooks_write.path, hooks_write.action, hooks_write.reason)
+
+ if parse_refusal is not None:
+ result.record(project_config_path(repo_path), FileAction.KEPT, parse_refusal)
+ else:
+ # `features.hooks` is Codex's global switch, so it goes only once
+ # nothing is left for it to enable. Read from the file as it stands
+ # now, not inferred from what the removal returned: an `unlink` that
+ # failed and fell back to a rewrite reports REMOVED over a file that
+ # still exists.
+ keep_feature = _hooks_file_has_entries(hooks_path)
+ server_write = remove_server_config(repo_path, drop_hooks_feature=not keep_feature)
+ result.record(server_write.path, server_write.action, server_write.reason)
+ if keep_feature:
+ result.note(
+ f"{project_config_path(repo_path)}: features.hooks left enabled because "
+ f"{hooks_path} still holds hooks that are not ours."
+ )
+ # Only when something of ours actually went, matching Cursor. Pruning
+ # unconditionally deleted a `.codex/` that happened to be empty and that
+ # this uninstall had just reported finding nothing in.
+ if any(written.action is FileAction.REMOVED for written in result.files):
+ prune_project_dir(repo_path)
+
owners = other_managers_of(instructions, exclude=ID, scope=scope, repo_path=repo_path)
block_state = inspect(instructions, DISTILL_MARKER_START, DISTILL_MARKER_END).state
if owners and block_state is BlockState.PRESENT:
- result.record(instructions, FileAction.KEPT)
- result.note(
- f"{instructions} kept: {' and '.join(owners)} still reads the same "
- "managed block. Remove that agent too if you want the block gone."
+ reason = (
+ f"{' and '.join(owners)} still reads the same managed block; "
+ "remove that agent too if you want the block gone"
)
+ result.record(instructions, FileAction.KEPT, reason)
+ result.note(f"{instructions} kept: {reason}.")
return result
if remove_agents_md_distill_section(repo_path):
@@ -618,12 +1015,15 @@ class CodexTarget:
# than reusing ``block_state``: the removal above runs in between and
# the whole question here is what the file looks like after it.
state = inspect(instructions, DISTILL_MARKER_START, DISTILL_MARKER_END).state
- result.record(
- instructions,
- FileAction.NOT_FOUND
- if state in (BlockState.ABSENT_FILE, BlockState.ABSENT)
- else FileAction.KEPT,
- )
+ if state in (BlockState.ABSENT_FILE, BlockState.ABSENT):
+ result.record(instructions, FileAction.NOT_FOUND)
+ else:
+ from ..formats.marker_block import refusal_reason
+
+ # PRESENT here means the write failed, not that we declined: the
+ # shared-ownership refusal returned earlier.
+ action = FileAction.FAILED if state is BlockState.PRESENT else FileAction.KEPT
+ result.record(instructions, action, refusal_reason(state))
return result
def print_config(self, scope: Scope, *, repo_path: Path | None = None) -> str:
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 49223f623..2bfa38d7a 100644
--- a/packages/cli/src/repowise/cli/agent_targets/targets/cursor.py
+++ b/packages/cli/src/repowise/cli/agent_targets/targets/cursor.py
@@ -214,22 +214,26 @@ def write_rules_file(repo_path: Path) -> FileWrite:
return FileWrite(path=config_path, action=action)
-def _remove_server_entry(config_path: Path) -> tuple[Path, FileAction]:
+def _remove_server_entry(config_path: Path) -> tuple[Path, FileAction, str | None]:
"""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
+ return config_path, FileAction.NOT_FOUND, None
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
+ return (
+ config_path,
+ FileAction.KEPT,
+ "not strict JSON, so removing our entry would drop comments",
+ )
servers = existing.get("mcpServers")
if not isinstance(servers, dict) or "repowise" not in servers:
- return config_path, FileAction.NOT_FOUND
+ return config_path, FileAction.NOT_FOUND, None
servers.pop("repowise")
# Drop the wrapper once it is empty, and the file once *it* is empty, so an
@@ -248,13 +252,13 @@ def _remove_server_entry(config_path: Path) -> tuple[Path, FileAction]:
# 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
+ return config_path, FileAction.REMOVED, None
write_json_config(config_path, existing)
- return config_path, FileAction.REMOVED
+ return config_path, FileAction.REMOVED, None
-def _remove_rules_file(repo_path: Path) -> tuple[Path, FileAction]:
+def _remove_rules_file(repo_path: Path) -> tuple[Path, FileAction, str | None]:
"""Strip the managed block, deleting the file if it held nothing else."""
from ..formats import marker_block
from ..formats.marker_block import BlockState
@@ -267,7 +271,7 @@ def _remove_rules_file(repo_path: Path) -> tuple[Path, FileAction]:
DISTILL_MARKER_END,
delete_if_only=RULES_PREFIX,
):
- return config_path, FileAction.REMOVED
+ return config_path, FileAction.REMOVED, None
# ``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"
@@ -276,8 +280,22 @@ def _remove_rules_file(repo_path: Path) -> tuple[Path, FileAction]:
# 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
+ return config_path, FileAction.NOT_FOUND, None
+ if state is BlockState.PRESENT:
+ # Still exactly where it was, so the write failed rather than us
+ # declining. This target has no shared-ownership case, so there is no
+ # other way to reach PRESENT here.
+ return config_path, FileAction.FAILED, marker_block.refusal_reason(state)
+ return config_path, FileAction.KEPT, marker_block.refusal_reason(state)
+
+
+def _rules_refusal_reason(config_path: Path) -> str:
+ """Why the rules file was left alone, in the words needed to unpick it."""
+ from ..formats import marker_block
+ from ..instructions import DISTILL_MARKER_END, DISTILL_MARKER_START
+
+ state = marker_block.inspect(config_path, DISTILL_MARKER_START, DISTILL_MARKER_END).state
+ return marker_block.refusal_reason(state)
def _prune_empty_dirs(repo_path: Path) -> None:
@@ -387,7 +405,11 @@ class CursorTarget:
written = write_mcp_config(repo_path)
result.record(written.path, written.action)
except RemoteServerEntryError:
- result.record(mcp_config_path(repo_path), FileAction.KEPT)
+ result.record(
+ mcp_config_path(repo_path),
+ FileAction.KEPT,
+ 'its "repowise" entry names a remote server',
+ )
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 "
@@ -402,7 +424,9 @@ class CursorTarget:
# 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)
+ result.record(
+ mcp_config_path(repo_path), FileAction.KEPT, f"could not be rewritten ({exc})"
+ )
# 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
@@ -416,7 +440,11 @@ class CursorTarget:
try:
written = write_rules_file(repo_path)
- result.record(written.path, written.action)
+ result.record(
+ written.path,
+ written.action,
+ _rules_refusal_reason(written.path) if written.action is FileAction.KEPT else None,
+ )
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,
@@ -427,7 +455,7 @@ class CursorTarget:
"hand and re-run."
)
except (OSError, ValueError):
- result.record(rules_path(repo_path), FileAction.KEPT)
+ result.record(rules_path(repo_path), FileAction.KEPT, "could not be written")
result.note(".cursor/rules/repowise.mdc could not be written.")
return result
diff --git a/packages/cli/src/repowise/cli/agent_targets/targets/hermes.py b/packages/cli/src/repowise/cli/agent_targets/targets/hermes.py
index c4965ebe9..5770456a7 100644
--- a/packages/cli/src/repowise/cli/agent_targets/targets/hermes.py
+++ b/packages/cli/src/repowise/cli/agent_targets/targets/hermes.py
@@ -486,7 +486,7 @@ def write_instructions(repo_path: Path) -> FileWrite:
return FileWrite(path=path, action=action)
-def _remove_server_entry() -> tuple[Path, FileAction]:
+def _remove_server_entry() -> tuple[Path, FileAction, str | None]:
"""Drop ``mcp_servers.repowise`` and any allowlist entry naming it.
Both edits again land in one file and one write.
@@ -516,20 +516,20 @@ def _remove_server_entry() -> tuple[Path, FileAction]:
try:
raw = _read_text(path)
except (OSError, ValueError):
- return path, FileAction.KEPT
+ return path, FileAction.KEPT, "the file could not be read, so its contents are unknown"
if raw is None:
- return path, FileAction.NOT_FOUND
+ return path, FileAction.NOT_FOUND, None
bom, newline, existing_text = _prepare(raw)
try:
existing_doc = yaml_merge.load_mapping(existing_text or "")
except (OSError, ValueError):
# Same reason install declines: rewriting a file we could not read
# destroys whatever we failed to read.
- return path, FileAction.KEPT
+ return path, FileAction.KEPT, "the file is not valid YAML, so rewriting it would lose text"
servers = existing_doc.get(MCP_KEY)
if not isinstance(servers, dict) or SERVER_NAME not in servers:
- return path, FileAction.NOT_FOUND
+ return path, FileAction.NOT_FOUND, None
merged_text, section = yaml_merge.remove_child(existing_text, MCP_KEY, SERVER_NAME)
@@ -554,7 +554,11 @@ def _remove_server_entry() -> tuple[Path, FileAction]:
# A splice that did not produce the intended document must not be
# written, and on the destructive verb that is worth reporting as
# "left alone" rather than as a removal that did not happen.
- return path, FileAction.KEPT
+ return (
+ path,
+ FileAction.KEPT,
+ "removing our entry from this file's shape would have changed something else in it",
+ )
merged_text = bom + merged_text
if not merged_text.strip() and _is_sole_occupant(path):
@@ -567,10 +571,10 @@ def _remove_server_entry() -> tuple[Path, FileAction]:
yaml_merge.write_if_changed(
path, merged_text, intended, existing_doc, newline=newline
)
- return path, FileAction.REMOVED
+ return path, FileAction.REMOVED, None
yaml_merge.write_if_changed(path, merged_text, intended, existing_doc, newline=newline)
- return path, FileAction.REMOVED
+ return path, FileAction.REMOVED, None
def _prune_allowlist(text: str, intended: dict) -> str:
@@ -684,6 +688,27 @@ def _remove_instructions(scope: Scope, repo_path: Path) -> tuple[Path, FileActio
return path, FileAction.KEPT, []
+def _instructions_outcome(owners: list[str], path: Path) -> tuple[FileAction, str]:
+ """What a non-removal of ``AGENTS.md`` actually was, and how to say it.
+
+ Shared ownership is a deliberate refusal and stays ``KEPT``; so is a
+ malformed marker pair. The block still in place with no other owner means
+ the write failed, which is ``FAILED`` and a different exit code.
+ """
+ from ..formats import marker_block
+ from ..formats.marker_block import BlockState
+ from ..instructions import DISTILL_MARKER_END, DISTILL_MARKER_START
+
+ if owners:
+ return FileAction.KEPT, (
+ f"{' and '.join(owners)} still reads the same managed block; "
+ "remove that agent too if you want the block gone"
+ )
+ state = marker_block.inspect(path, DISTILL_MARKER_START, DISTILL_MARKER_END).state
+ action = FileAction.FAILED if state is BlockState.PRESENT else FileAction.KEPT
+ return action, marker_block.refusal_reason(state)
+
+
def _reads_repowise() -> bool:
"""Whether the user config registers the repowise MCP server."""
path = config_path()
@@ -841,7 +866,11 @@ class HermesTarget:
written = write_mcp_config()
result.record(written.path, written.action)
except RemoteServerEntryError:
- result.record(path, FileAction.KEPT)
+ result.record(
+ path,
+ FileAction.KEPT,
+ f'its "{SERVER_NAME}" entry names a remote server',
+ )
result.note(
f'{path} left unchanged: its "{SERVER_NAME}" entry names a remote '
"server, and Hermes prefers a URL over a command even when both are "
@@ -851,7 +880,7 @@ class HermesTarget:
)
return
except (ValueError, OSError) as exc:
- result.record(path, FileAction.KEPT)
+ result.record(path, FileAction.KEPT, f"could not be rewritten ({exc})")
# The reason is carried rather than asserted: this guard is wide
# enough to catch things that are not a bad config file at all, and
# a note that flatly said "not valid YAML" would send the user to
@@ -892,7 +921,13 @@ class HermesTarget:
def _install_project(self, result: WriteResult, repo_path: Path) -> None:
try:
written = write_instructions(repo_path)
- result.record(written.path, written.action)
+ result.record(
+ written.path,
+ written.action,
+ _instructions_outcome([], written.path)[1]
+ if written.action is FileAction.KEPT
+ else None,
+ )
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
@@ -904,7 +939,9 @@ class HermesTarget:
"read. Fix it by hand and re-run."
)
except (OSError, ValueError) as exc:
- result.record(instructions_path(repo_path), FileAction.KEPT)
+ result.record(
+ instructions_path(repo_path), FileAction.KEPT, f"could not be written ({exc})"
+ )
result.note(f"AGENTS.md could not be written ({exc}).")
def uninstall(self, scope: Scope, *, repo_path: Path | None = None) -> WriteResult:
@@ -914,20 +951,20 @@ class HermesTarget:
raise ValueError("project-scope uninstall needs a repo_path")
if scope is Scope.USER:
- path, action = _remove_server_entry()
- result.record(path, action)
+ path, action, reason = _remove_server_entry()
+ result.record(path, action, reason)
if action is FileAction.REMOVED:
_prune_home()
return result
assert repo_path is not None # narrowed by the guard above
instructions, action, owners = _remove_instructions(scope, repo_path)
- result.record(instructions, action)
+ reason = None
+ if action is FileAction.KEPT:
+ action, reason = _instructions_outcome(owners, instructions)
+ result.record(instructions, action, reason)
if owners:
- result.note(
- f"{instructions} kept: {' and '.join(owners)} still reads the same "
- "managed block. Remove that agent too if you want the block gone."
- )
+ result.note(f"{instructions} kept: {reason}.")
return result
def print_config(self, scope: Scope, *, repo_path: Path | None = None) -> str:
diff --git a/packages/cli/src/repowise/cli/agent_targets/targets/opencode.py b/packages/cli/src/repowise/cli/agent_targets/targets/opencode.py
index 5bae41e98..dee7b995c 100644
--- a/packages/cli/src/repowise/cli/agent_targets/targets/opencode.py
+++ b/packages/cli/src/repowise/cli/agent_targets/targets/opencode.py
@@ -343,7 +343,7 @@ def write_instructions(scope: Scope, repo_path: Path | None = None) -> FileWrite
return FileWrite(path=path, action=action)
-def _remove_server_entry(path: Path) -> tuple[Path, FileAction]:
+def _remove_server_entry(path: Path) -> tuple[Path, FileAction, str | None]:
"""Drop ``mcp.repowise``, preserving sibling servers.
Rounds the install trip back to nothing: the ``mcp`` wrapper goes once it is
@@ -359,17 +359,21 @@ def _remove_server_entry(path: Path) -> tuple[Path, FileAction]:
from ..formats.json_merge import load_json_object_or_value_error, write_json_config
if not path.exists():
- return path, FileAction.NOT_FOUND
+ return path, FileAction.NOT_FOUND, None
try:
existing = load_json_object_or_value_error(path, path.name)
except (OSError, ValueError):
# Same reason install declines: rewriting a file we could not parse
# destroys whatever we failed to read.
- return path, FileAction.KEPT
+ return (
+ path,
+ FileAction.KEPT,
+ "not strict JSON, so removing our entry would drop comments",
+ )
servers = existing.get("mcp")
if not isinstance(servers, dict) or SERVER_NAME not in servers:
- return path, FileAction.NOT_FOUND
+ return path, FileAction.NOT_FOUND, None
servers.pop(SERVER_NAME)
if not servers:
@@ -384,10 +388,10 @@ def _remove_server_entry(path: Path) -> tuple[Path, FileAction]:
# Falling through to the rewrite keeps the failure loud, from the
# same ``os.replace`` the write path uses.
write_json_config(path, existing)
- return path, FileAction.REMOVED
+ return path, FileAction.REMOVED, None
write_json_config(path, existing)
- return path, FileAction.REMOVED
+ return path, FileAction.REMOVED, None
def _remove_instructions(
@@ -447,6 +451,29 @@ def _remove_instructions(
return path, FileAction.KEPT, []
+def _instructions_outcome(owners: list[str], path: Path) -> tuple[FileAction, str]:
+ """What a non-removal of ``AGENTS.md`` actually was, and how to say it.
+
+ Three genuinely different outcomes reach one action, and they want opposite
+ things from the user. Shared ownership is a deliberate refusal and stays
+ ``KEPT``. A malformed marker pair is also a refusal. But the block still
+ sitting there *with no other owner* means the write failed, which is a
+ ``FAILED`` and a different exit code, not a decision we made.
+ """
+ from ..formats import marker_block
+ from ..formats.marker_block import BlockState
+ from ..instructions import DISTILL_MARKER_END, DISTILL_MARKER_START
+
+ if owners:
+ return FileAction.KEPT, (
+ f"{' and '.join(owners)} still reads the same managed block; "
+ "remove that agent too if you want the block gone"
+ )
+ state = marker_block.inspect(path, DISTILL_MARKER_START, DISTILL_MARKER_END).state
+ action = FileAction.FAILED if state is BlockState.PRESENT else FileAction.KEPT
+ return action, marker_block.refusal_reason(state)
+
+
def _prune_user_dir() -> None:
"""Remove ``<config>/opencode`` when a user-scope uninstall emptied it.
@@ -612,7 +639,11 @@ class OpenCodeTarget:
result.record(written.path, written.action)
except RemoteServerEntryError:
path = write_target_path(scope, repo_path)
- result.record(path, FileAction.KEPT)
+ result.record(
+ path,
+ FileAction.KEPT,
+ 'its "repowise" entry names a remote server',
+ )
result.note(
f'{path.name} left unchanged: its "repowise" entry names a remote server, '
"and converting it in place would leave an entry that is neither. Run "
@@ -624,7 +655,7 @@ class OpenCodeTarget:
# name the file the write actually aimed at, which is the one
# already holding our entry when there is one.
path = write_target_path(scope, repo_path)
- result.record(path, FileAction.KEPT)
+ result.record(path, FileAction.KEPT, f"could not be rewritten ({exc})")
# The reason is carried rather than asserted: this guard is wide
# enough to catch things that are not a bad config file at all, and
# a note that flatly said "not valid JSON" would send the user to
@@ -639,7 +670,13 @@ class OpenCodeTarget:
try:
written = write_instructions(scope, repo_path)
- result.record(written.path, written.action)
+ result.record(
+ written.path,
+ written.action,
+ _instructions_outcome([], written.path)[1]
+ if written.action is FileAction.KEPT
+ else None,
+ )
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
@@ -651,7 +688,11 @@ class OpenCodeTarget:
"Fix it by hand and re-run."
)
except (OSError, ValueError) as exc:
- result.record(instructions_path(scope, repo_path), FileAction.KEPT)
+ result.record(
+ instructions_path(scope, repo_path),
+ FileAction.KEPT,
+ f"could not be written ({exc})",
+ )
result.note(f"AGENTS.md could not be written ({exc}).")
return result
@@ -673,17 +714,17 @@ class OpenCodeTarget:
# the *next* iteration reports anything.
preferred = config_path(scope, repo_path)
for candidate in config_paths(scope, repo_path):
- path, action = _remove_server_entry(candidate)
+ path, action, reason = _remove_server_entry(candidate)
if action is not FileAction.NOT_FOUND or path == preferred:
- result.record(path, action)
+ result.record(path, action, reason)
instructions, action, owners = _remove_instructions(scope, repo_path)
- result.record(instructions, action)
+ reason = None
+ if action is FileAction.KEPT:
+ action, reason = _instructions_outcome(owners, instructions)
+ result.record(instructions, action, reason)
if owners:
- result.note(
- f"{instructions} kept: {' and '.join(owners)} still reads the same "
- "managed block. Remove that agent too if you want the block gone."
- )
+ result.note(f"{instructions} kept: {reason}.")
if scope is Scope.USER and any(
written.action is FileAction.REMOVED for written in result.files
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 3d02a23ea..fde8061cb 100644
--- a/packages/cli/src/repowise/cli/agent_targets/targets/vscode.py
+++ b/packages/cli/src/repowise/cli/agent_targets/targets/vscode.py
@@ -140,44 +140,96 @@ def write_extensions_config(repo_path: Path) -> FileWrite:
return FileWrite(path=config_path, action=write_json_config(config_path, merged))
-def _remove_server_entry(config_path: Path) -> tuple[Path, FileAction]:
+def _remove_server_entry(config_path: Path) -> tuple[Path, FileAction, str | None]:
"""Drop ``servers.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
+ return config_path, FileAction.NOT_FOUND, None
try:
existing = load_json_object_or_value_error(config_path, "mcp.json")
except ValueError:
# Same reason install declines: it is far more likely to be JSONC than
# damaged, and rewriting it would silently delete the user's comments.
- return config_path, FileAction.KEPT
+ return config_path, FileAction.KEPT, "not strict JSON, so removing our entry would drop comments"
servers = existing.get("servers")
if not isinstance(servers, dict) or "repowise" not in servers:
- return config_path, FileAction.NOT_FOUND
+ return config_path, FileAction.NOT_FOUND, None
servers.pop("repowise")
+
+ # Prune the wrapper and then the file, matching Cursor. Deleting on an empty
+ # *parse* is only sound because the parse above is strict JSON: a file that
+ # got here cannot have held comments, so an empty object really is an empty
+ # file. The YAML and TOML targets must not copy this shortcut, and do not.
+ if not servers:
+ existing.pop("servers", None)
+ if not existing:
+ try:
+ config_path.unlink()
+ except OSError:
+ # Swallowing this would report REMOVED over a file that still holds
+ # our entry. Fall through to the rewrite so the failure stays loud,
+ # from the same os.replace the previous code used.
+ write_json_config(config_path, existing)
+ return config_path, FileAction.REMOVED, None
+
write_json_config(config_path, existing)
- return config_path, FileAction.REMOVED
+ return config_path, FileAction.REMOVED, None
-def _remove_extension_recommendation(config_path: Path) -> tuple[Path, FileAction]:
+def _remove_extension_recommendation(config_path: Path) -> tuple[Path, FileAction, str | None]:
"""Drop our id from ``recommendations``, preserving everyone else's."""
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
+ return config_path, FileAction.NOT_FOUND, None
try:
existing = load_json_object_or_value_error(config_path, "extensions.json")
except ValueError:
- return config_path, FileAction.KEPT
+ return (
+ config_path,
+ FileAction.KEPT,
+ "not strict JSON, so removing our entry would drop comments",
+ )
recommendations = existing.get("recommendations")
if not isinstance(recommendations, list) or EXTENSION_ID not in recommendations:
- return config_path, FileAction.NOT_FOUND
- existing["recommendations"] = [r for r in recommendations if r != EXTENSION_ID]
+ return config_path, FileAction.NOT_FOUND, None
+ remaining = [r for r in recommendations if r != EXTENSION_ID]
+
+ # Same prune, same justification. `extensions.json` holding an empty
+ # recommendations array is a file we created and the user never asked for.
+ if remaining:
+ existing["recommendations"] = remaining
+ else:
+ existing.pop("recommendations", None)
+ if not existing:
+ try:
+ config_path.unlink()
+ except OSError:
+ write_json_config(config_path, existing)
+ return config_path, FileAction.REMOVED, None
+
write_json_config(config_path, existing)
- return config_path, FileAction.REMOVED
+ return config_path, FileAction.REMOVED, None
+
+
+def _prune_project_dir(repo_path: Path) -> None:
+ """Remove ``.vscode/`` once uninstall emptied it, and never otherwise.
+
+ ``rmdir`` rather than a recursive delete, so a directory still holding
+ anything at all, ours or the user's ``settings.json``, is left exactly as it
+ is. The symlink guard is Cursor's: following a junction to delete something
+ outside the repo is not a risk worth a tidy directory.
+ """
+ directory = mcp_config_path(repo_path).parent
+ if directory.is_symlink() or not directory.is_dir():
+ return
+ try:
+ directory.rmdir()
+ except OSError:
+ return
def detect(repo_path: Path | None = None) -> list[Registration]:
@@ -271,7 +323,11 @@ class VSCodeTarget:
# Before the broader handler below, which it would otherwise reach
# as a ``ValueError`` and be described as an unreadable file. It is
# a perfectly readable file holding a deliberate choice.
- result.record(mcp_config_path(repo_path), FileAction.KEPT)
+ result.record(
+ mcp_config_path(repo_path),
+ FileAction.KEPT,
+ 'its "repowise" entry names a remote server',
+ )
result.note(
'.vscode/mcp.json left unchanged: its "repowise" entry names a remote '
"server, and converting it in place would leave an entry that is "
@@ -279,7 +335,11 @@ class VSCodeTarget:
"want the local server instead."
)
except (ValueError, OSError):
- result.record(mcp_config_path(repo_path), FileAction.KEPT)
+ result.record(
+ mcp_config_path(repo_path),
+ FileAction.KEPT,
+ "unreadable, or not strict JSON, so rewriting it would lose text",
+ )
result.note(
".vscode/mcp.json left unchanged (unreadable, or not valid JSON; it "
'may contain comments). Add a "repowise" server under "servers" manually.'
@@ -288,7 +348,11 @@ class VSCodeTarget:
written = write_extensions_config(repo_path)
result.record(written.path, written.action)
except (ValueError, OSError):
- result.record(extensions_config_path(repo_path), FileAction.KEPT)
+ result.record(
+ extensions_config_path(repo_path),
+ FileAction.KEPT,
+ "unreadable, or not strict JSON, so rewriting it would lose text",
+ )
result.note(
".vscode/extensions.json left unchanged (unreadable, or not valid JSON; "
f'it may contain comments). Add "{EXTENSION_ID}" to "recommendations" '
@@ -310,6 +374,11 @@ class VSCodeTarget:
return result
result.record(*_remove_server_entry(mcp_config_path(repo_path)))
result.record(*_remove_extension_recommendation(extensions_config_path(repo_path)))
+ # Only when something of ours actually went, matching Cursor. Pruning
+ # unconditionally deleted a `.vscode/` that happened to be empty and
+ # that this uninstall had just reported finding nothing in.
+ if any(written.action is FileAction.REMOVED for written in result.files):
+ _prune_project_dir(repo_path)
return result
def print_config(self, scope: Scope, *, repo_path: Path | None = None) -> str:
diff --git a/packages/cli/src/repowise/cli/agent_targets/types.py b/packages/cli/src/repowise/cli/agent_targets/types.py
index c86f82df4..b6dafd124 100644
--- a/packages/cli/src/repowise/cli/agent_targets/types.py
+++ b/packages/cli/src/repowise/cli/agent_targets/types.py
@@ -75,6 +75,12 @@ class FileAction(StrEnum):
REMOVED = "removed"
NOT_FOUND = "not-found"
KEPT = "kept"
+ #: We tried and could not. Distinct from ``KEPT``, which is a decision, and
+ #: the distinction only earns its keep on the destructive verb: "I chose not
+ #: to touch this" and "I failed to remove this" look identical in a report
+ #: that has one value for both, and they need opposite things from the user.
+ #: Only ``repowise uninstall`` produces it today.
+ FAILED = "failed"
class Capability(StrEnum):
@@ -169,10 +175,18 @@ class Registration:
@dataclass(frozen=True)
class FileWrite:
- """What happened to one file."""
+ """What happened to one file.
+
+ *reason* exists for one action in particular. ``KEPT`` on its own is
+ indistinguishable from a bug: the user asked for a file to go, it is still
+ there, and the row says nothing about whether that was a deliberate refusal
+ or a silent failure. Every ``KEPT`` carries one. The other actions speak for
+ themselves and leave it ``None``.
+ """
path: Path
action: FileAction
+ reason: str | None = None
@dataclass
@@ -189,8 +203,8 @@ class WriteResult:
#: One-line notes surfaced verbatim, e.g. "Restart the editor to apply."
notes: list[str] = field(default_factory=list)
- def record(self, path: Path, action: FileAction) -> None:
- self.files.append(FileWrite(path=path, action=action))
+ def record(self, path: Path, action: FileAction, reason: str | None = None) -> None:
+ self.files.append(FileWrite(path=path, action=action, reason=reason))
def note(self, message: str) -> None:
self.notes.append(message)
@@ -212,7 +226,10 @@ class WriteResult:
checks the projection alone.
"""
return {
- "files": [{"path": str(f.path), "action": f.action.value} for f in self.files],
+ "files": [
+ {"path": str(f.path), "action": f.action.value, "reason": f.reason}
+ for f in self.files
+ ],
"notes": list(self.notes),
}
diff --git a/packages/cli/src/repowise/cli/commands/agents_cmd.py b/packages/cli/src/repowise/cli/commands/agents_cmd.py
index 51cb96cf9..137179740 100644
--- a/packages/cli/src/repowise/cli/commands/agents_cmd.py
+++ b/packages/cli/src/repowise/cli/commands/agents_cmd.py
@@ -32,6 +32,7 @@ from typing import Any
import click
from repowise.cli.agent_targets.registry import default_selection, describe_agents
+from repowise.cli.agent_targets.types import FileAction
from repowise.cli.helpers import console, resolve_command_target
from repowise.cli.output import emit_json, format_option, notice_console
@@ -282,7 +283,18 @@ def _render_writes(payload: dict) -> None:
for agent in payload["agents"]:
for scope, write in agent["writes"].items():
for entry in write["files"]:
- table.add_row(agent["id"], scope, entry["action"], entry["path"])
+ # The reason rides on the row rather than in the notes block
+ # below the table. A bare "kept" is indistinguishable from a
+ # bug: the user asked for a file to go, it is still there, and
+ # the row says nothing about whether that was deliberate. Only
+ # three targets ever emitted a note, so for the other three the
+ # answer was invisible.
+ file_cell = entry["path"]
+ if entry.get("reason"):
+ file_cell = f"{entry['path']}\n[dim]{entry['reason']}[/dim]"
+ elif entry["action"] == FileAction.KEPT.value:
+ file_cell = f"{entry['path']}\n[dim]no reason recorded[/dim]"
+ table.add_row(agent["id"], scope, entry["action"], file_cell)
# Every skip gets its own row. Folding them into one "skipped" line
# per agent hid the reason whenever a second scope had written
# something, which is the common case rather than the edge one.
diff --git a/packages/cli/src/repowise/cli/commands/uninstall_cmd.py b/packages/cli/src/repowise/cli/commands/uninstall_cmd.py
new file mode 100644
index 000000000..db6dfbcc1
--- /dev/null
+++ b/packages/cli/src/repowise/cli/commands/uninstall_cmd.py
@@ -0,0 +1,382 @@
+"""``repowise uninstall`` — remove repowise from this repo and this machine.
+
+Two motives brought this command about and they look opposed: convenience for a
+reinstall wants the index kept, and a trust signal wants everything gone. They
+are not opposed, because **the trust signal is the report, not the deletion.**
+A command that enumerates every path repowise has ever written, removes what was
+chosen, and states exactly what it left and why is completely honest even when it
+leaves the index. Completeness of the inventory is the claim; which boxes start
+ticked is a separate knob.
+
+**There is no ``--yes``.** Everywhere else in this CLI that flag means "run the
+default without asking", and there is no safe meaning for it here. If it ran the
+default set, someone who typed it to uninstall would get a partial uninstall. If
+it removed everything, it would mean something different from ``agents add -y``
+and ``init --yes``, and that difference is discoverable only by losing an index.
+So the non-interactive path names its own scope, and naming the scope is the
+consent: ``--all`` or ``--keep-index``. The flag is still accepted, purely to
+fail with a sentence saying which one to use, because a helpful error beats a
+surprising deletion.
+
+**Consent is never inferred from a tty probe.** ``isatty`` lies on Windows, and
+the two ways to be wrong are not symmetric: guessing "interactive" hangs, and
+guessing "not interactive" deletes without asking. With no terminal and no scope
+flag this prints the inventory, removes nothing, and exits non-zero.
+"""
+
+from __future__ import annotations
+
+import sys
+from pathlib import Path
+
+import click
+
+from repowise.cli.agent_targets.types import FileAction
+from repowise.cli.helpers import console, resolve_command_target
+from repowise.cli.output import emit_json, format_option
+from repowise.cli.uninstall import build_plan, execute
+from repowise.cli.uninstall.inventory import ALL_GROUPS, DEFAULT_GROUPS, Group, Plan
+from repowise.cli.uninstall.runner import EXIT_NEEDS_SCOPE, Outcome
+
+_ACTION_STYLE = {
+ FileAction.REMOVED.value: "green",
+ FileAction.NOT_FOUND.value: "dim",
+ FileAction.KEPT.value: "yellow",
+ FileAction.FAILED.value: "red",
+}
+
+
+def _resolve_repo(path: str | None) -> Path:
+ """Resolve the repo, and deliberately skip the update notice.
+
+ Every other command calls ``target.notice`` here. This one must not, for two
+ reasons. Advertising an upgrade to someone uninstalling is the wrong thing
+ to say. And the notice caches its result in
+ ``~/.repowise/update-check.json``, which recreates the very directory a
+ previous ``--all`` run deleted, so the *second* run would find machine-wide
+ state, report it removed again, and never converge.
+ """
+ target = resolve_command_target(path=path, workspace_flag=False, no_workspace_flag=True)
+ assert target.repo_path is not None
+ return target.repo_path
+
+
+def _group_choices(plan: Plan, preticked: frozenset[Group]) -> list:
+ """One checklist row per group that has something on disk.
+
+ Groups with nothing present are left out of the prompt rather than shown
+ ticked and inert: a checklist offering to delete four things when three of
+ them do not exist teaches the user not to read it. They still appear in the
+ printed inventory as not-found, which is where "we looked here" belongs.
+ """
+ from repowise.cli.ui.agent_selection import AgentChoice
+
+ labels = {
+ Group.AGENTS: ("Agent configuration", "every wired agent, both scopes"),
+ Group.REPO_FILES: ("Generated blocks", "the managed sections in CLAUDE.md and AGENTS.md"),
+ Group.INDEX: ("Repo index", "rebuilding it costs a full re-index"),
+ Group.GLOBAL: ("Machine-wide state", "login, caches, telemetry preference"),
+ }
+ choices = []
+ for group in plan.groups_present():
+ name, detail = labels[group]
+ size = sum(item.size or 0 for item in plan.for_groups(frozenset({group})))
+ if size:
+ detail = f"{detail}, {_human_size(size)}"
+ choices.append(
+ AgentChoice(id=group.value, display_name=name, detail=detail, enabled=group in preticked)
+ )
+ return choices
+
+
+def _human_size(size: float) -> str:
+ for unit in ("B", "KB", "MB", "GB"):
+ if size < 1024 or unit == "GB":
+ return f"{size:.0f} {unit}" if unit == "B" else f"{size:.1f} {unit}"
+ size /= 1024.0
+ raise AssertionError("unreachable: the GB arm always returns")
+
+
+def _render_plan(plan: Plan, groups: frozenset[Group], *, heading: str) -> None:
+ from rich.table import Table
+
+ table = Table(title=heading)
+ table.add_column("Group", style="cyan")
+ table.add_column("Path")
+ table.add_column("Note")
+
+ for group in Group:
+ for item in plan.for_groups(frozenset({group})):
+ if group not in groups:
+ note = "[dim]not selected[/dim]"
+ elif item.blocked:
+ note = f"[yellow]{item.blocked}[/yellow]"
+ elif not item.exists:
+ note = "[dim]not found[/dim]"
+ else:
+ note = _human_size(item.size) if item.size else ""
+ table.add_row(group.value, str(item.path), note)
+ console.print(table)
+
+
+def _render_outcome(outcome: Outcome) -> None:
+ from rich.table import Table
+
+ table = Table(title="Uninstall")
+ table.add_column("Group", style="cyan")
+ table.add_column("Action")
+ table.add_column("Path")
+
+ for result in outcome.results:
+ style = _ACTION_STYLE.get(result.action.value, "")
+ action = f"[{style}]{result.action.value}[/{style}]" if style else result.action.value
+ cell = str(result.path)
+ if result.reason:
+ cell = f"{cell}\n[dim]{result.reason}[/dim]"
+ elif result.action is FileAction.KEPT:
+ cell = f"{cell}\n[dim]no reason recorded[/dim]"
+ table.add_row(result.group.value, action, cell)
+
+ # Printed even when every row is not-found. A trust command that prints
+ # nothing on a clean machine has proven nothing about where it looked.
+ console.print(table)
+
+
+def _print_advisories(plan: Plan, outcome: Outcome | None) -> None:
+ for note in outcome.notes if outcome else []:
+ console.print(f" [yellow]{note}[/yellow]")
+ for line in plan.advisories:
+ console.print(f" [dim]{line}[/dim]")
+
+
[email protected]("uninstall")
[email protected]("path", required=False, default=None)
+ "--all",
+ "remove_all",
+ is_flag=True,
+ help="Remove everything, including the repo index and machine-wide state.",
+)
+ "--keep-index",
+ is_flag=True,
+ help=(
+ "The reinstall case: remove agent wiring and the generated blocks, "
+ "keeping the repo index and machine-wide state (login, caches)."
+ ),
+)
+ "--dry-run",
+ is_flag=True,
+ help="Print the plan and change nothing.",
+)
+ "--yes",
+ "-y",
+ "yes",
+ is_flag=True,
+ hidden=True,
+ help="Not a flag on this command. Say --all or --keep-index instead.",
+)
+@format_option(help="Output format. json reports the plan, every path and what happened to it.")
+def uninstall_command(
+ ctx: click.Context,
+ path: str | None,
+ remove_all: bool,
+ keep_index: bool,
+ dry_run: bool,
+ yes: bool,
+ fmt: str,
+) -> None:
+ """Remove repowise from this repo, and optionally from this machine.
+
+ With a terminal and no flags this shows what repowise has written and asks
+ what to remove. Non-interactively, say what you want removed:
+
+ \b
+ repowise uninstall --all everything
+ repowise uninstall --keep-index everything except the index
+
+ The package itself and the Claude Code plugin are owned by their installers,
+ not by us. The report names the command for each.
+ """
+ # Before anything else, including the argument checks, because the cost of
+ # being late is silent and permanent. Telemetry spools to
+ # ``~/.repowise/telemetry-spool.jsonl`` and consent state lives in
+ # ``~/.repowise/platform.json``, and both are written on the way out of a
+ # command. Without this, ``uninstall --all`` deleted the directory, reported
+ # it removed truthfully, and then our own process recreated it holding a
+ # fresh anonymous id and a spool file. The report was accurate at the moment
+ # it was printed and wrong by the time the shell prompt came back.
+ #
+ # An env var rather than a config write, because the config lives in the
+ # directory we are about to delete.
+ import os
+
+ os.environ["REPOWISE_TELEMETRY_DISABLED"] = "1"
+
+ if remove_all and keep_index:
+ raise click.UsageError("--all and --keep-index say opposite things. Pick one.")
+ if yes:
+ raise click.UsageError(
+ "uninstall has no --yes: on every other command it means 'run the default', "
+ "and a partial uninstall is not a safe default. Say what to remove: "
+ "--all, or --keep-index to keep the repo index."
+ )
+
+ repo_path = _resolve_repo(path)
+ plan = build_plan(repo_path)
+
+ if remove_all:
+ groups = ALL_GROUPS
+ elif keep_index:
+ # The reinstall case, so it keeps machine-wide state too. Reading
+ # ``--keep-index`` as "everything except the index" would take the
+ # user's login and the shared embedder key on the way past, which is
+ # precisely what someone about to reinstall does not want. It also
+ # gives the command a property worth having on its own: machine-wide
+ # state goes only when the user names it, by ``--all`` or by ticking it.
+ groups = frozenset(DEFAULT_GROUPS)
+ elif dry_run:
+ # Only when no scope flag was given: there is nothing to honour and
+ # nobody to ask, so show everything. This sits *after* `--keep-index`
+ # on purpose. Ahead of it, `--keep-index --dry-run` reported that the
+ # index and the login would go, which is the opposite of what the real
+ # run does and exactly the pre-flight a cautious user leans on.
+ groups = ALL_GROUPS
+ else:
+ groups = _ask(plan, ctx, fmt)
+
+ if dry_run:
+ _emit_dry_run(plan, groups, fmt)
+ return
+
+ outcome = execute(plan, groups)
+ if fmt == "json":
+ emit_json(
+ {
+ "action": "uninstall",
+ "dry_run": False,
+ "repo": str(repo_path),
+ "groups": sorted(group.value for group in groups),
+ "plan": plan.as_dict(),
+ **outcome.as_dict(),
+ }
+ )
+ else:
+ _render_outcome(outcome)
+ _print_advisories(plan, outcome)
+ if outcome.complete:
+ console.print("[green]Everything selected is gone.[/green]")
+ else:
+ console.print(
+ f"[yellow]{len(outcome.leftovers)} path(s) still here. "
+ "See the reason on each row.[/yellow]"
+ )
+ ctx.exit(outcome.exit_code)
+
+
+def _emit_dry_run(plan: Plan, groups: frozenset[Group], fmt: str) -> None:
+ """The plan, and nothing else.
+
+ Deliberately the same plan object a real run executes, projected the same
+ way, so the two cannot describe different work. ``--dry-run`` is not a
+ separate code path that has to be kept in step with the real one.
+ """
+ if fmt == "json":
+ emit_json(
+ {
+ "action": "uninstall",
+ "dry_run": True,
+ "repo": str(plan.repo_path),
+ "groups": sorted(group.value for group in groups),
+ "plan": plan.as_dict(),
+ }
+ )
+ return
+ _render_plan(plan, groups, heading="Uninstall plan (dry run, nothing was changed)")
+ _print_advisories(plan, None)
+
+
+def _ask(plan: Plan, ctx: click.Context, fmt: str) -> frozenset[Group]:
+ """The interactive path, and its two refusals.
+
+ Refuses in both directions rather than guessing. With no terminal, or with
+ ``--format json``, there is nobody to answer and the command will not pick a
+ destructive default on their behalf. And when the prompt itself comes back
+ unanswerable, this aborts where ``agents add`` carries on with the ticked
+ set: that fallback is right for adding and wrong for anything that deletes.
+ """
+ from repowise.cli.ui.agent_selection import interactive_agent_select
+
+ interactive = fmt != "json"
+ try:
+ interactive = interactive and sys.stdin.isatty()
+ except Exception:
+ interactive = False
+
+ if not interactive:
+ if fmt == "json":
+ # A rich table here printed box-drawing characters onto the same
+ # stream as the payload, so `--format json` with no scope flag
+ # produced output no parser could read. The refusal is data too.
+ emit_json(
+ {
+ "action": "uninstall",
+ "dry_run": True,
+ "repo": str(plan.repo_path),
+ "groups": [],
+ "plan": plan.as_dict(),
+ "error": "uninstall needs a scope: pass --all or --keep-index",
+ }
+ )
+ ctx.exit(EXIT_NEEDS_SCOPE)
+ _render_plan(
+ plan,
+ ALL_GROUPS,
+ heading="Nothing was removed. This is what repowise has written.",
+ )
+ _print_advisories(plan, None)
+ console.print(
+ "[yellow]Say what to remove: --all, or --keep-index to keep the repo index. "
+ "Add --dry-run to see this again without being asked.[/yellow]"
+ )
+ ctx.exit(EXIT_NEEDS_SCOPE)
+
+ _render_plan(plan, ALL_GROUPS, heading="What repowise has written")
+ _print_advisories(plan, None)
+
+ choices = _group_choices(plan, DEFAULT_GROUPS)
+ if not choices:
+ console.print("[dim]Nothing of ours is here.[/dim]")
+ ctx.exit(0)
+
+ chosen = interactive_agent_select(
+ console,
+ choices,
+ title="[bold]Uninstall:[/bold] remove which of these?",
+ hint="Enter to accept the ticked set, or numbers to toggle (1,3), 'all', 'none'.",
+ prompt=" Remove",
+ )
+ if chosen is None:
+ console.print("[yellow]Could not read an answer, so nothing was removed.[/yellow]")
+ ctx.exit(EXIT_NEEDS_SCOPE)
+ if not chosen:
+ console.print("[dim]Nothing selected, so nothing was removed.[/dim]")
+ ctx.exit(0)
+
+ groups = frozenset(Group(value) for value in chosen)
+
+ # A second, explicit yes. The checklist has a fallback this command must not
+ # inherit: unparseable input keeps the ticked set and carries on, which is
+ # right for `agents add` and means `asdf` deletes things here. A typed
+ # confirmation turns every ambiguous answer into a definite one, and
+ # defaults to no.
+ console.print()
+ for group in sorted(groups, key=list(Group).index):
+ console.print(f" [red]remove[/red] {group.value}")
+ if not click.confirm("Remove these?", default=False):
+ console.print("[dim]Nothing was removed.[/dim]")
+ ctx.exit(0)
+ return groups
diff --git a/packages/cli/src/repowise/cli/editor_integrations/claude_config.py b/packages/cli/src/repowise/cli/editor_integrations/claude_config.py
index f4b3cddec..b9c2c5845 100644
--- a/packages/cli/src/repowise/cli/editor_integrations/claude_config.py
+++ b/packages/cli/src/repowise/cli/editor_integrations/claude_config.py
@@ -465,7 +465,8 @@ def _migrate_legacy_rewrite_matcher(hook_list: list) -> bool:
"""Widen legacy rewrite-hook matchers in place (``Bash`` → current)."""
changed = False
for entry in hook_list:
- only_rewrite = entry.get("hooks") and all(_is_rewrite_hook(h) for h in entry["hooks"])
+ hooks = _hooks_of(entry)
+ only_rewrite = hooks and all(_is_rewrite_hook(h) for h in hooks)
if only_rewrite and entry.get("matcher", "") in _LEGACY_REWRITE_MATCHERS:
entry["matcher"] = _REWRITE_MATCHER
changed = True
@@ -485,18 +486,230 @@ def uninstall_claude_code_rewrite_hook() -> bool:
hooks = existing.get("hooks")
if not isinstance(hooks, dict):
return False
- pre_hooks = hooks.get("PreToolUse")
- if not isinstance(pre_hooks, list):
+
+ # Every event, not just ``PreToolUse``. We only ever write this hook there,
+ # but ``claude_code_leftover_reason`` looks for it everywhere, so a hand-moved
+ # or legacy entry under another event was found by the probe and unreachable
+ # by the remover: an uninstall that reported KEPT forever and never
+ # converged however many times it was run.
+ changed = False
+ for event, entries in list(hooks.items()):
+ if not isinstance(entries, list) or not entries:
+ continue
+ if _strip_hooks(entries, _is_rewrite_hook):
+ changed = True
+ if not entries:
+ hooks.pop(event, None)
+ if not changed:
return False
+ if not hooks:
+ existing.pop("hooks", None)
- changed = _strip_hooks(pre_hooks, _is_rewrite_hook)
+ return _write_settings(settings_path, existing)
+
+
+def uninstall_claude_code_augment_hooks() -> bool:
+ """Remove every repowise augment hook from settings.json, across all events.
+
+ The sibling of :func:`uninstall_claude_code_rewrite_hook`, and deliberately
+ a separate function: the rewrite hook is one opt-in entry under one event,
+ while the augment hooks are installed across ``SessionStart``,
+ ``PostToolUse`` and ``PostToolUseFailure``. Sweeping every event with the
+ same predicate is what keeps a future fourth event from being missed here
+ while ``install_claude_code_hooks`` grows one.
+
+ Prunes as it goes, in the same order the file nests: our command out of an
+ entry, an entry we emptied out of its event, an event we emptied out of
+ ``hooks``, and ``hooks`` itself once nothing is left. Every hook the user
+ wrote survives, including hooks under the same event as ours.
+ """
+ settings_path = _claude_code_settings_path()
+ if not settings_path.exists():
+ return False
+ try:
+ existing = load_existing_config(settings_path)
+ except Exception:
+ return False
+
+ hooks = existing.get("hooks")
+ if not isinstance(hooks, dict):
+ return False
+
+ changed = False
+ for event, entries in list(hooks.items()):
+ if not isinstance(entries, list) or not entries:
+ # An event that was already empty is not one we emptied. Popping it
+ # unconditionally deleted a key the user had written and counted as
+ # a removal in a file holding none of our hooks.
+ continue
+ if _strip_hooks(entries, _is_repowise_hook):
+ changed = True
+ if not entries:
+ hooks.pop(event, None)
if not changed:
return False
- if not pre_hooks:
- hooks.pop("PreToolUse", None)
+ if not hooks:
+ existing.pop("hooks", None)
+ return _write_settings(settings_path, existing)
+
+
+def uninstall_claude_code_mcp_entry() -> bool:
+ """Drop ``mcpServers.repowise`` from settings.json, sparing sibling servers.
+
+ Keyed on our exact server name, never on a prefix or on the entry's shape.
+ The wrapper goes when it empties; the file never does. ``settings.json`` is
+ the user's, it long predates us, and an empty object there is still their
+ file rather than a stub we left.
+ """
+ settings_path = _claude_code_settings_path()
+ if not settings_path.exists():
+ return False
try:
- settings_path.write_text(json.dumps(existing, indent=2) + "\n", encoding="utf-8")
+ existing = load_existing_config(settings_path)
+ except Exception:
+ return False
+
+ servers = existing.get("mcpServers")
+ if not isinstance(servers, dict) or "repowise" not in servers:
+ return False
+ servers.pop("repowise")
+ if not servers:
+ existing.pop("mcpServers", None)
+
+ return _write_settings(settings_path, existing)
+
+
+def uninstall_claude_desktop_mcp_entry() -> bool:
+ """Drop ``mcpServers.repowise`` from Claude Desktop's config.
+
+ The sibling of :func:`uninstall_claude_code_mcp_entry`, and easy to miss
+ because the two live in different files on different platforms.
+ ``install`` writes both (:func:`register_with_claude_desktop` and
+ :func:`register_with_claude_code`), and leaving this one behind did more
+ than leave a stale entry: ``detect`` reads it, so a removed Claude Code
+ still reported a user-scope registration, ``refresh_wired_agents`` counted
+ it as wired, and the next ``repowise doctor --repair`` silently reinstalled
+ everything the uninstall had just removed.
+ """
+ config_path = _claude_desktop_config_path()
+ if config_path is None or not config_path.exists():
+ return False
+ try:
+ existing = load_existing_config(config_path)
+ except Exception:
+ return False
+
+ servers = existing.get("mcpServers")
+ if not isinstance(servers, dict) or "repowise" not in servers:
+ return False
+ servers.pop("repowise")
+ if not servers:
+ existing.pop("mcpServers", None)
+
+ return _write_settings(config_path, existing)
+
+
+def claude_code_leftover_reason() -> str | None:
+ """Why settings.json still has repowise in it, read from disk. None when clean.
+
+ The three uninstall helpers each return ``False`` for four different
+ outcomes: nothing of ours was there, the file would not parse, the write
+ raised, and the file does not exist. Collapsing those into "not found" told
+ a user with an unparseable ``settings.json`` that we had looked and found
+ nothing of ours, while our MCP registration and our hooks sat in it. That
+ answer then fed the exit code, so the command printed "everything selected
+ is gone" and exited zero over a file it had failed to touch.
+
+ Scoped to ``settings.json`` alone. The Desktop config has its own probe and
+ its own row: folding it in here produced a row whose path column named
+ ``settings.json`` and whose reason talked about the Desktop config, over a
+ settings file that was perfectly clean.
+ """
+ settings_path = _claude_code_settings_path()
+ if not settings_path.exists():
+ return None
+ try:
+ existing = load_existing_config(settings_path)
+ except Exception:
+ # Unreadable and unparseable are the cases this function exists for. We
+ # cannot say what is in there, and "we cannot say" is not "it is clean".
+ return "the file could not be read, so whether our entries are gone is unknown"
+
+ servers = existing.get("mcpServers")
+ if isinstance(servers, dict) and "repowise" in servers:
+ return "our MCP registration was still present after the write"
+
+ hooks = existing.get("hooks")
+ if isinstance(hooks, dict):
+ for entries in hooks.values():
+ if not isinstance(entries, list):
+ continue
+ for entry in entries:
+ if not isinstance(entry, dict) or not isinstance(entry.get("hooks"), list):
+ continue
+ for hook in entry["hooks"]:
+ if isinstance(hook, dict) and (
+ _is_repowise_hook(hook) or _is_rewrite_hook(hook)
+ ):
+ return "one of our hooks was still present after the write"
+ return None
+
+
+def claude_desktop_leftover_reason() -> str | None:
+ """Whether Claude Desktop's config still names us. None when clean or absent."""
+ config_path = _claude_desktop_config_path()
+ if config_path is None or not config_path.exists():
+ return None
+ try:
+ existing = load_existing_config(config_path)
+ except Exception:
+ # Unparseable is not the same as ours. A JSONC Claude Desktop config is
+ # ordinary, and reporting every one of them as a leftover made a clean
+ # machine print "N path(s) still here" and exit 3 forever, because the
+ # remover returns False on the same file and nothing ever converges.
+ # So ask the bytes whether we are even mentioned.
+ try:
+ if b"repowise" not in config_path.read_bytes().lower():
+ return None
+ except OSError:
+ return None
+ return (
+ "the Claude Desktop config could not be read and still mentions repowise, "
+ "so whether our entry is gone is unknown"
+ )
+ servers = existing.get("mcpServers")
+ if isinstance(servers, dict) and "repowise" in servers:
+ return "our entry was still in the Claude Desktop config after the write"
+ return None
+
+
+def _write_settings(settings_path: Path, existing: dict) -> bool:
+ """Write ``settings.json`` atomically. False when the write did not happen.
+
+ Atomic because a single ``uninstall`` now performs three of these in a row
+ on a long-lived file the user owns, and a truncated ``settings.json`` costs
+ them every hook and every MCP server they have, not just ours.
+
+ ``newline=None`` deliberately, which is the platform translation every other
+ writer of this file already takes. Pinning it to ``\\n`` would have made an
+ uninstall silently rewrite a Windows user's entire settings file from CRLF
+ to LF, so the one command that is supposed to leave less behind would have
+ touched every line of it.
+ """
+ from repowise.core.fsutils import atomic_write_text
+
+ payload = json.dumps(existing, indent=2) + "\n"
+ try:
+ if settings_path.is_symlink():
+ # Write through the link, not over it. The atomic path is a
+ # temp-file rename, which would replace a dotfile manager's symlink
+ # with a regular file and quietly detach settings.json from the
+ # repo the user keeps it in. Losing atomicity on this one shape is
+ # the smaller harm.
+ settings_path.write_text(payload, encoding="utf-8")
+ else:
+ atomic_write_text(settings_path, payload, newline=None)
except OSError:
return False
return True
@@ -530,14 +743,44 @@ def claude_code_rewrite_hook_matcher() -> str | None:
return _rewrite_matcher(pre_hooks)
+def _hooks_of(entry: object) -> list:
+ """The hook list on *entry*, or empty for any shape that is not one.
+
+ The read helpers used this as ``entry.get("hooks", [])``, which assumes the
+ entry is a dict and the value is iterable. Both assumptions are about a file
+ the user owns, and the write half already stopped making them.
+ """
+ if not isinstance(entry, dict):
+ return []
+ hooks = entry.get("hooks")
+ return hooks if isinstance(hooks, list) else []
+
+
+def _hook_command(hook: object) -> str:
+ """The command string on *hook*, or ``""`` for any shape that is not one.
+
+ The predicates below index this rather than ``hook.get("command", "")``.
+ The isinstance guards in :func:`_strip_hooks` cover the entry and the list
+ but not the value the predicate reaches into, so a ``"command": 7`` in a
+ file we did not write still raised ``TypeError`` out of the middle of an
+ uninstall, after an earlier removal had already rewritten the file. That
+ became reachable across every event once the rewrite-hook sweep stopped
+ being confined to ``PreToolUse``.
+ """
+ if not isinstance(hook, dict):
+ return ""
+ command = hook.get("command")
+ return command if isinstance(command, str) else ""
+
+
def _is_rewrite_hook(hook: dict) -> bool:
- return _REWRITE_HOOK_COMMAND in hook.get("command", "")
+ return _REWRITE_HOOK_COMMAND in _hook_command(hook)
def _rewrite_matcher(hook_list: list) -> str | None:
"""Matcher of the first entry carrying our hook, or None if there is none."""
for entry in hook_list:
- if any(_is_rewrite_hook(h) for h in entry.get("hooks", [])):
+ if any(_is_rewrite_hook(h) for h in _hooks_of(entry)):
matcher = entry.get("matcher")
return matcher if isinstance(matcher, str) else ""
return None
@@ -548,11 +791,24 @@ def _has_rewrite_hook(hook_list: list) -> bool:
def _strip_hooks(hook_list: list, predicate) -> bool:
- """Remove hooks matching *predicate* from a hook bucket in place."""
+ """Remove hooks matching *predicate* from a hook bucket in place.
+
+ Every shape is guarded, which it did not used to need. This only ever ran
+ over ``PreToolUse``, an event repowise writes and therefore knows the shape
+ of. :func:`uninstall_claude_code_augment_hooks` now sweeps **every** event in
+ the user's ``settings.json``, so one string or one null anywhere in a file
+ we did not write used to raise ``AttributeError`` out of the middle of an
+ uninstall, after an earlier removal had already rewritten the file.
+ """
changed = False
for entry in list(hook_list):
- kept = [h for h in entry.get("hooks", []) if not predicate(h)]
- if len(kept) != len(entry.get("hooks", [])):
+ if not isinstance(entry, dict):
+ continue
+ inner = entry.get("hooks")
+ if not isinstance(inner, list):
+ continue
+ kept = [h for h in inner if not (isinstance(h, dict) and predicate(h))]
+ if len(kept) != len(inner):
changed = True
if kept:
entry["hooks"] = kept
@@ -563,16 +819,13 @@ def _strip_hooks(hook_list: list, predicate) -> bool:
def _has_repowise_hook(hook_list: list) -> bool:
"""Check if a repowise hook is already registered, current or legacy."""
- for entry in hook_list:
- for hook in entry.get("hooks", []):
- cmd = hook.get("command", "")
- if "repowise-augment" in cmd or "repowise augment" in cmd:
- return True
- return False
+ return any(
+ any(_is_repowise_hook(hook) for hook in _hooks_of(entry)) for entry in hook_list
+ )
def _is_repowise_hook(hook: dict) -> bool:
- cmd = hook.get("command", "")
+ cmd = _hook_command(hook)
return "repowise-augment" in cmd or "repowise augment" in cmd
@@ -589,16 +842,19 @@ def _migrate_legacy_hook(hook_list: list) -> bool:
"""In-place migration of legacy PostToolUse entries to current shape."""
changed = False
for entry in hook_list:
- for hook in entry.get("hooks", []):
- cmd = hook.get("command", "")
+ for hook in _hooks_of(entry):
+ cmd = _hook_command(hook)
# Both the old subcommand form and the unguarded console script
# migrate to the guarded command, so an install predating the guard
# stops emitting "command not found" without needing a re-init.
if cmd in ("repowise augment", "repowise-augment"):
hook["command"] = _AUGMENT_HOOK_COMMAND
changed = True
+ if not isinstance(entry, dict):
+ continue
matcher = entry.get("matcher", "")
- only_repowise = entry.get("hooks") and all(_is_repowise_hook(h) for h in entry["hooks"])
+ entry_hooks = _hooks_of(entry)
+ only_repowise = entry_hooks and all(_is_repowise_hook(h) for h in entry_hooks)
if only_repowise and matcher in _LEGACY_AUGMENT_MATCHERS:
entry["matcher"] = _AUGMENT_MATCHER
changed = True
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 700e9e03c..84e1d5d2a 100644
--- a/packages/cli/src/repowise/cli/editor_integrations/codex_config.py
+++ b/packages/cli/src/repowise/cli/editor_integrations/codex_config.py
@@ -206,23 +206,36 @@ def uninstall_codex_rewrite_hook() -> bool:
hooks = existing.get("hooks")
if not isinstance(hooks, dict):
return False
- pre_hooks = hooks.get("PreToolUse")
- if not isinstance(pre_hooks, list):
- return False
+ # Every event and every shape, matching the Claude Code half. Sweeping only
+ # ``PreToolUse`` while the leftover probe scans every event made a hook the
+ # user had moved an unclearable KEPT: reported forever, removable never. And
+ # indexing ``entry.get("hooks", [])`` raw raised ``AttributeError`` on a bare
+ # string in a file we did not write, which escapes ``agents remove`` (it
+ # wraps nothing) as a traceback part-way through a batch.
changed = False
- for entry in list(pre_hooks):
- kept = [h for h in entry.get("hooks", []) if not _is_rewrite_hook(h)]
- if len(kept) != len(entry.get("hooks", [])):
- changed = True
- if kept:
- entry["hooks"] = kept
- else:
- pre_hooks.remove(entry)
+ for event, entries in list(hooks.items()):
+ if not isinstance(entries, list) or not entries:
+ continue
+ for entry in list(entries):
+ if not isinstance(entry, dict):
+ continue
+ inner = entry.get("hooks")
+ if not isinstance(inner, list):
+ continue
+ kept = [h for h in inner if not (isinstance(h, dict) and _is_rewrite_hook(h))]
+ if len(kept) != len(inner):
+ changed = True
+ if kept:
+ entry["hooks"] = kept
+ else:
+ entries.remove(entry)
+ if not entries:
+ hooks.pop(event, None)
if not changed:
return False
- if not pre_hooks:
- hooks.pop("PreToolUse", None)
+ if not hooks:
+ existing.pop("hooks", None)
try:
hooks_path.write_text(json.dumps(existing, indent=2) + "\n", encoding="utf-8")
@@ -262,14 +275,25 @@ def codex_rewrite_hook_matcher() -> str | None:
return _rewrite_matcher(pre_hooks)
-def _is_rewrite_hook(hook: dict) -> bool:
- return _REWRITE_HOOK_COMMAND in hook.get("command", "")
+def _is_rewrite_hook(hook: object) -> bool:
+ """True when *hook* is our rewrite entry. Any other shape is False.
+
+ Guarded rather than assumed, for the same reason the Claude Code side is:
+ this reads a file the user owns, so ``"command": 7`` is a shape to answer
+ rather than to raise on.
+ """
+ if not isinstance(hook, dict):
+ return False
+ command = hook.get("command")
+ return isinstance(command, str) and _REWRITE_HOOK_COMMAND in command
def _rewrite_matcher(hook_list: list) -> str | None:
"""Matcher of the first entry carrying our hook, or None if there is none."""
for entry in hook_list:
- if any(_is_rewrite_hook(h) for h in entry.get("hooks", [])):
+ if not isinstance(entry, dict):
+ continue
+ if any(_is_rewrite_hook(h) for h in entry.get("hooks") or []):
matcher = entry.get("matcher")
return matcher if isinstance(matcher, str) else ""
return None
diff --git a/packages/cli/src/repowise/cli/main.py b/packages/cli/src/repowise/cli/main.py
index aa1d68914..2613dcb18 100644
--- a/packages/cli/src/repowise/cli/main.py
+++ b/packages/cli/src/repowise/cli/main.py
@@ -20,7 +20,13 @@ def cli(ctx: click.Context) -> None:
# Skipped when invoked as the augment subcommand itself (hook hot path) —
# `augment_hook.main` handles that case. See `self_heal` for why the call
# site stays here.
- if ctx.invoked_subcommand != "augment":
+ #
+ # Also skipped for `uninstall`, where repairing agent hook entries is the
+ # opposite of what the user asked for, and where the migration stamp lands
+ # in `~/.repowise/` — the directory that command may be about to delete.
+ # Without this, a second `uninstall --all` found and removed a stamp its own
+ # startup had just written, and the command never converged.
+ if ctx.invoked_subcommand not in ("augment", "uninstall"):
try:
from repowise.cli.self_heal import run_editor_migrations
@@ -66,6 +72,7 @@ _OSS_COMMANDS: tuple[tuple[str, str], ...] = (
("export", "export_cmd:export_command"),
("hook", "hook_cmd:hook_group"),
("agents", "agents_cmd:agents_group"),
+ ("uninstall", "uninstall_cmd:uninstall_command"),
("status", "status_cmd:status_command"),
("doctor", "doctor_cmd:doctor_command"),
("watch", "watch_cmd:watch_command"),
diff --git a/packages/cli/src/repowise/cli/ui/agent_selection.py b/packages/cli/src/repowise/cli/ui/agent_selection.py
index b3cf3d5d6..36943e211 100644
--- a/packages/cli/src/repowise/cli/ui/agent_selection.py
+++ b/packages/cli/src/repowise/cli/ui/agent_selection.py
@@ -35,9 +35,19 @@ class AgentChoice:
enabled: bool
+#: The wording for the case this prompt was written for, adding agents.
+_ADD_TITLE = "[bold]Agent integrations:[/bold] write project config and instruction files for?"
+_ADD_HINT = "Enter to accept, or numbers to toggle (1,3), 'all', 'none'."
+_ADD_PROMPT = " Set up"
+
+
def interactive_agent_select(
console_obj: Any,
choices: list[AgentChoice],
+ *,
+ title: str | None = None,
+ hint: str | None = None,
+ prompt: str | None = None,
) -> set[str] | None:
"""Ask which agents to set up. Returns the chosen ids, or None.
@@ -62,9 +72,11 @@ def interactive_agent_select(
# scope: it is what the three per-agent prompts it replaced controlled.
# The global MCP registration is a separate step and unticking a box here
# does not withdraw it, so the question must not imply that it does.
- console_obj.print(
- "[bold]Agent integrations:[/bold] write project config and instruction files for?"
- )
+ #
+ # Overridable because `repowise uninstall` reuses this widget, and asking
+ # "write project config and instruction files for?" above a row that reads
+ # "Machine-wide state" is the wrong verb in the one place it matters most.
+ console_obj.print(title or _ADD_TITLE)
for index, choice in enumerate(choices, 1):
# ``\[`` escapes the bracket for rich. Unescaped, ``[x]`` is valid
# markup and gets eaten as a style tag while ``[ ]`` is not and
@@ -75,10 +87,12 @@ def interactive_agent_select(
console_obj.print(
f" {box} [{BRAND_STYLE}][{index}][/] {choice.display_name}{detail}"
)
- console_obj.print(" [dim]Enter to accept, or numbers to toggle (1,3), 'all', 'none'.[/dim]")
+ console_obj.print(f" [dim]{hint or _ADD_HINT}[/dim]")
try:
- raw = Prompt.ask(" Set up", default="", show_default=False, console=console_obj)
+ raw = Prompt.ask(
+ prompt or _ADD_PROMPT, default="", show_default=False, console=console_obj
+ )
except EOFError:
return None
diff --git a/packages/cli/src/repowise/cli/uninstall/__init__.py b/packages/cli/src/repowise/cli/uninstall/__init__.py
new file mode 100644
index 000000000..9e4ad69c6
--- /dev/null
+++ b/packages/cli/src/repowise/cli/uninstall/__init__.py
@@ -0,0 +1,13 @@
+"""What repowise has written, and what removing it would take.
+
+Split from the command for one reason: the plan has to be computable without
+writing anything. ``--dry-run`` is then the plan printed and nothing else, and a
+real run is the same plan executed, so the two cannot describe different work.
+"""
+
+from __future__ import annotations
+
+from .inventory import Group, Item, Plan, build_plan
+from .runner import execute
+
+__all__ = ["Group", "Item", "Plan", "build_plan", "execute"]
diff --git a/packages/cli/src/repowise/cli/uninstall/generated_files.py b/packages/cli/src/repowise/cli/uninstall/generated_files.py
new file mode 100644
index 000000000..22522c7d2
--- /dev/null
+++ b/packages/cli/src/repowise/cli/uninstall/generated_files.py
@@ -0,0 +1,110 @@
+"""Removal for the two managed blocks the *generators* write.
+
+Neither had a removal path anywhere in the CLI before this module. The pipeline
+writes a ``REPOWISE`` block into ``.claude/CLAUDE.md`` and a ``REPOWISE_AGENTS``
+block into ``AGENTS.md``; ``BaseEditorFileGenerator`` exposes ``render``,
+``write`` and ``render_full`` and nothing that takes either back out, and no
+agent target's ``uninstall`` names either path. So both survived
+``agents remove --target=all`` and every other command we ship.
+
+**``AGENTS.md`` holds two different repowise blocks and they are not
+interchangeable.** The generator's is fenced by ``REPOWISE_AGENTS``; the one
+codex, opencode and hermes share is fenced by ``REPOWISE_DISTILL``. Only the
+second has multiple managers, so only the second consults
+``registry.other_managers_of``. Routing this one through that guard would ask
+whether another *agent* still needs a block written by the *indexer*, which is a
+question about the wrong file. Anything here that treats "the repowise block in
+AGENTS.md" as one concept is already wrong.
+
+The removal itself is ``marker_block.remove``, the hardened one the targets use:
+it refuses an orphaned or duplicated pair rather than guessing at a repair, and
+it deletes the file only when the remaining raw text is blank.
+
+This lives in the CLI rather than beside the generators because the marker
+implementation does, and the import direction runs cli into core. A second
+marker remover in core, with its own idea of what a malformed pair means, is
+exactly the duplication that produced this track's worst bugs.
+"""
+
+from __future__ import annotations
+
+from dataclasses import dataclass
+from pathlib import Path
+
+from repowise.cli.agent_targets.formats import marker_block
+from repowise.cli.agent_targets.formats.marker_block import BlockState
+from repowise.cli.agent_targets.types import FileAction
+
+
+@dataclass(frozen=True)
+class GeneratedBlock:
+ """One managed block, named by where it lives and how it is fenced."""
+
+ #: Stable id used in the plan and in ``--format json``.
+ id: str
+ #: Path relative to the repo root.
+ relative_path: str
+ marker_tag: str
+
+ def path(self, repo_path: Path) -> Path:
+ return repo_path / self.relative_path
+
+ @property
+ def start(self) -> str:
+ from repowise.core.generation.editor_files.base import BaseEditorFileGenerator
+
+ return BaseEditorFileGenerator.MARKER_START_FMT.format(tag=self.marker_tag)
+
+ @property
+ def end(self) -> str:
+ from repowise.core.generation.editor_files.base import BaseEditorFileGenerator
+
+ return BaseEditorFileGenerator.MARKER_END_FMT.format(tag=self.marker_tag)
+
+
+#: Derived from the generator classes rather than retyped, so a generator that
+#: renames its file or its tag cannot leave this list quietly pointing at a path
+#: that no longer exists.
+def generated_blocks() -> tuple[GeneratedBlock, ...]:
+ from repowise.core.generation.editor_files.agents_md import AgentsMdGenerator
+ from repowise.core.generation.editor_files.claude_md import ClaudeMdGenerator
+
+ return (
+ GeneratedBlock(
+ id="claude-md",
+ relative_path=f".claude/{ClaudeMdGenerator.filename}",
+ marker_tag=ClaudeMdGenerator.marker_tag,
+ ),
+ GeneratedBlock(
+ id="agents-md",
+ relative_path=AgentsMdGenerator.filename,
+ marker_tag=AgentsMdGenerator.marker_tag,
+ ),
+ )
+
+
+def inspect_block(block: GeneratedBlock, repo_path: Path) -> BlockState:
+ """What *block* currently is in *repo_path*, without writing."""
+ return marker_block.inspect(block.path(repo_path), block.start, block.end).state
+
+
+def remove_block(block: GeneratedBlock, repo_path: Path) -> tuple[Path, FileAction, str | None]:
+ """Strip *block* from its file, or say why it was left alone.
+
+ The state is re-inspected after the removal rather than reused from before
+ it, because the whole question here is what the file looks like afterwards.
+ """
+ path = block.path(repo_path)
+ if marker_block.remove(path, block.start, block.end):
+ return path, FileAction.REMOVED, None
+
+ state = marker_block.inspect(path, block.start, block.end).state
+ if state in (BlockState.ABSENT_FILE, BlockState.ABSENT):
+ return path, FileAction.NOT_FOUND, None
+ if state is BlockState.PRESENT:
+ # The block is still exactly where it was, which means the write failed
+ # rather than that we declined. Those need opposite things from the
+ # user, and they also want different exit codes: this is a failure (1),
+ # not a leftover (3).
+ return path, FileAction.FAILED, marker_block.refusal_reason(state)
+ return path, FileAction.KEPT, marker_block.refusal_reason(state)
diff --git a/packages/cli/src/repowise/cli/uninstall/inventory.py b/packages/cli/src/repowise/cli/uninstall/inventory.py
new file mode 100644
index 000000000..c15b4089c
--- /dev/null
+++ b/packages/cli/src/repowise/cli/uninstall/inventory.py
@@ -0,0 +1,468 @@
+"""The full inventory of what repowise has written, computed without writing.
+
+This module is the trust claim. The deletion is not: a command that removes
+everything and says nothing is less honest than one that removes half and names
+the other half. So the plan enumerates every path in every group, present or
+not, and carries for each either the action a run would take or the reason it
+would not. ``--dry-run`` prints this and stops; a real run executes exactly it.
+
+Nothing here opens a file for writing or creates a directory.
+"""
+
+from __future__ import annotations
+
+import os
+from dataclasses import dataclass, field
+from enum import StrEnum
+from pathlib import Path
+
+
+class Group(StrEnum):
+ """The four things a user can independently choose to remove.
+
+ Deliberately not the two scopes the ``agents`` command uses. Project and
+ user are *locations*; these are *kinds*, and they cross-cut. Agent wiring
+ exists at both locations and a user removing it means both.
+ """
+
+ #: All six agent targets, both scopes, through their own ``uninstall()``.
+ AGENTS = "agents"
+ #: The managed blocks the generators write into the repo's own files.
+ REPO_FILES = "repo-files"
+ #: The repo's ``.repowise/`` directory.
+ INDEX = "index"
+ #: ``~/.repowise/``, which is machine-wide.
+ GLOBAL = "global"
+
+
+#: Ticked when the user just presses enter.
+#:
+#: The index is out, and so is machine-wide state, for two different reasons.
+#:
+#: The index is out because the cost is asymmetric in one direction. Someone
+#: leaving who misses the box loses a directory the report just named; someone
+#: reinstalling who misses it loses a full reindex. One keystroke either way.
+#:
+#: Machine-wide state is out because ``~/.repowise/`` holds no registry of the
+#: repos on this machine, so a command running inside one repo cannot see the
+#: other repos it would break by deleting a login or the shared embedder key.
+#: ``--all`` ticks both, because that is the user naming them.
+DEFAULT_GROUPS = frozenset({Group.AGENTS, Group.REPO_FILES})
+
+ALL_GROUPS = frozenset(Group)
+
+
+@dataclass(frozen=True)
+class Item:
+ """One path, and what would happen to it.
+
+ *blocked* is the field that keeps the output honest. A path we will not
+ touch is still listed, with the reason on the row, because a trust command
+ that silently omits what it declined has told the user nothing about it.
+ """
+
+ group: Group
+ path: Path
+ #: Short label for the row, e.g. "Claude Code (user)" or "index".
+ label: str
+ exists: bool
+ #: Bytes on disk where cheap to compute, else ``None``.
+ size: int | None = None
+ #: Why this path will not be touched, or ``None`` when it will be.
+ blocked: str | None = None
+ #: For the agents group: the target id whose ``uninstall`` owns this path.
+ target_id: str | None = None
+ #: For the agents group: ``"project"`` or ``"user"``. Carried as data
+ #: because the runner needs it, and recovering it by matching on the end of
+ #: the display label meant any wording change silently reclassified every
+ #: user-scope path as project scope.
+ scope: str | None = None
+
+ def as_dict(self) -> dict:
+ return {
+ "group": self.group.value,
+ "path": str(self.path),
+ "label": self.label,
+ "exists": self.exists,
+ "size": self.size,
+ "blocked": self.blocked,
+ "target_id": self.target_id,
+ "scope": self.scope,
+ }
+
+
+@dataclass
+class Plan:
+ """Everything the command knows before it does anything."""
+
+ repo_path: Path
+ items: list[Item] = field(default_factory=list)
+ #: Lines that are true regardless of what the user picks: the package, the
+ #: plugin, hand-pasted config, a detected workspace.
+ advisories: list[str] = field(default_factory=list)
+
+ def for_groups(self, groups: frozenset[Group]) -> list[Item]:
+ return [item for item in self.items if item.group in groups]
+
+ def groups_present(self) -> list[Group]:
+ """Groups with something to report, in declaration order.
+
+ ``blocked`` counts as something to report even when ``exists`` is False.
+ A generated block with an orphaned marker pair is exactly that shape,
+ and keying on ``exists`` alone dropped its whole group out of the
+ checklist, so the one case that most needs the user's attention was the
+ one the prompt did not mention.
+ """
+ found = {item.group for item in self.items if item.exists or item.blocked}
+ return [group for group in Group if group in found]
+
+ def as_dict(self) -> dict:
+ return {
+ "repo": str(self.repo_path),
+ "items": [item.as_dict() for item in self.items],
+ "advisories": list(self.advisories),
+ }
+
+
+def _size_of(path: Path) -> int | None:
+ """Bytes at *path*, walking a directory. ``None`` when it cannot be read.
+
+ Best-effort by design: this number decorates a row, and a permission error
+ partway through a tree must not stop the command that is about to offer to
+ delete it.
+
+ Through ``fs_walk.iter_glob`` rather than ``Path.rglob``, which the walk
+ guard in ``tests/unit/ingestion/test_fs_walk.py`` insists on and which this
+ code earns twice over: a bare ``rglob`` follows junction cycles, and this
+ walks two directories a user is free to have relocated. The pruning can
+ under-count a size by skipping a ``node_modules``-shaped name inside our own
+ directory, which is a rounding error on a figure that decorates a row.
+ """
+ from repowise.core.fs_walk import iter_glob
+
+ try:
+ if path.is_file():
+ return path.stat().st_size
+ if not path.is_dir():
+ return None
+ total = 0
+ for entry in iter_glob(path, "*"):
+ try:
+ if entry.is_file() and not entry.is_symlink():
+ total += entry.stat().st_size
+ except OSError:
+ continue
+ return total
+ except OSError:
+ return None
+
+
+def _index_blocked(repo_path: Path) -> str | None:
+ """Why the index cannot be deleted right now, or ``None``.
+
+ Two live-process checks, both cheap, both about deleting a directory out
+ from under something that is currently reading and writing it.
+ """
+ from repowise.cli.helpers import get_repowise_dir
+
+ try:
+ from repowise.core.update_lock import read_update_lock
+
+ if read_update_lock(repo_path) is not None:
+ return "an update is running for this repo; wait for it to finish"
+ except Exception:
+ # A lock helper that raises must not stop the inventory from being
+ # printed. Not knowing whether an update holds the lock is a worse
+ # answer than "no", but printing nothing at all is worse than both.
+ pass
+
+ lock = get_repowise_dir(repo_path) / "serve.lock.json"
+ if _serve_lock_is_live(lock):
+ return "'repowise serve' is running for this repo; stop it first"
+ return None
+
+
+def _serve_lock_is_live(lock: Path) -> bool:
+ """Whether ``serve.lock.json`` names a process that still exists.
+
+ A stale lock is the common case: ``serve`` only removes a lock it owns, so
+ a killed server leaves one behind forever. Treating a stale lock as live
+ would make the index permanently undeletable, which is a worse failure than
+ the one this guard prevents.
+ """
+ import json
+
+ if not lock.exists():
+ return False
+ try:
+ payload = json.loads(lock.read_text(encoding="utf-8"))
+ except (OSError, ValueError):
+ return False
+ pid = payload.get("pid")
+ if not isinstance(pid, int):
+ return False
+ try:
+ from repowise.core.procutils import pid_alive
+
+ return bool(pid_alive(pid))
+ except Exception:
+ # Without a liveness probe, assume it is stale rather than blocking the
+ # user out of their own directory on the strength of a leftover file.
+ return False
+
+
+#: Read in chunks rather than whole, with an overlap so the marker cannot be
+#: split across a boundary. A size cap that skipped large files outright would
+#: reintroduce the very miss this function exists to close, on the one input we
+#: cannot bound: a user's own ``settings.json`` or ``AGENTS.md``.
+_PROBE_CHUNK = 1 << 20
+_MARKER = b"repowise"
+
+#: How many entries of a described directory to look at. One of the eighteen
+#: described paths is a directory and it holds eighteen small files.
+_PROBE_DIR_ENTRIES = 200
+
+
+def _mentions_repowise(path: Path) -> bool:
+ """Whether *path* names us, read as bytes.
+
+ Bytes rather than text, and a substring rather than a parse. The whole
+ reason this exists is the file the parser could not read, so anything that
+ goes through a parser reintroduces the hole it is closing.
+
+ The asymmetry is deliberate. A false positive costs one row that reports
+ not-found and one target's uninstall running with nothing to remove. A false
+ negative leaves a live registration behind and says nothing, which is the
+ failure this command exists to prevent.
+
+ **Directories are searched, not skipped.** Exactly one of the eighteen paths
+ the six targets describe is a directory, ``~/.codex/prompts``, and it is the
+ only evidence that Codex user scope is wired when the hooks file is JSONC or
+ absent. Answering False for it left eighteen prompt files on disk under
+ "everything selected is gone".
+ """
+ try:
+ if path.is_dir():
+ # Unsorted, so a directory with more entries than the cap does not
+ # depend on where `repowise-` falls alphabetically. `~/.codex/prompts`
+ # is documented as a flat global directory shared with every other
+ # tool the user has installed, so it can be large.
+ #
+ # `os.fsencode` rather than `str.encode`, which raises
+ # `UnicodeEncodeError` on a filename holding lone surrogates. That is
+ # a `ValueError`, not an `OSError`, so it would escape the handler
+ # below and out of `build_plan`.
+ for index, child in enumerate(path.iterdir()):
+ if index >= _PROBE_DIR_ENTRIES:
+ return False
+ if _MARKER in os.fsencode(child.name).lower():
+ return True
+ return False
+ if not path.is_file():
+ return False
+ with path.open("rb") as handle:
+ tail = b""
+ while chunk := handle.read(_PROBE_CHUNK):
+ if _MARKER in (tail + chunk).lower():
+ return True
+ tail = chunk[-len(_MARKER) :]
+ return False
+ except OSError:
+ return False
+
+
+def _agent_items(repo_path: Path) -> list[Item]:
+ """Every path the currently wired agents manage, per target and scope.
+
+ Sourced from each target's own ``describe_paths`` rather than a list kept
+ here, so a target that starts writing a fourth file appears in the plan
+ without this module being edited.
+
+ **A scope counts as wired if ``detect`` says so, or if one of its files
+ mentions us.** Both halves are needed and each was learned by getting it
+ wrong.
+
+ Detection alone is not enough: a ``.vscode/mcp.json`` with a comment in it
+ is JSONC, which VS Code accepts and our strict parse refuses, so ``detect``
+ returned nothing, the file never entered the inventory, and the command
+ removed a live MCP registration from nowhere while printing "everything
+ selected is gone". Any target whose ``detect`` raises had the same hole.
+
+ Existence alone is far worse. Only three of the eighteen paths the six
+ targets describe are repowise-exclusive. The rest are files that exist for
+ anyone who has ever run the host at all: ``~/.claude/settings.json``,
+ ``~/.codex/hooks.json``, ``.vscode/extensions.json``, ``AGENTS.md``,
+ ``.mcp.json``. Keying on existence listed every one of them in a repo where
+ repowise had never been installed, pre-ticked the agent group, and had the
+ runner call ``uninstall`` for scopes detection never found.
+
+ So the fallback is a text probe rather than a stat: does a file we would
+ touch actually name us. That is the same shape as OpenCode's own JSONC
+ fallback, it cannot be fooled by a host the user merely happens to have, and
+ it cannot miss a file that genuinely holds our entry.
+ """
+ from repowise.cli.agent_targets.registry import all_targets
+ from repowise.cli.agent_targets.types import Scope
+
+ items: list[Item] = []
+ for target in all_targets():
+ try:
+ registrations = target.detect(repo_path)
+ except Exception:
+ registrations = []
+ wired_scopes = {registration.scope for registration in registrations}
+ for scope in (Scope.PROJECT, Scope.USER):
+ if not target.supports_scope(scope):
+ continue
+ try:
+ paths = [Path(raw) for raw in target.describe_paths(scope, repo_path=repo_path)]
+ except Exception:
+ continue
+ if scope not in wired_scopes and not any(_mentions_repowise(path) for path in paths):
+ continue
+ for path in paths:
+ items.append(
+ Item(
+ group=Group.AGENTS,
+ path=path,
+ scope=scope.value,
+ label=f"{target.display_name} ({scope.value})",
+ exists=path.exists(),
+ target_id=target.id,
+ )
+ )
+ return items
+
+
+def _repo_file_items(repo_path: Path) -> list[Item]:
+ from repowise.cli.agent_targets.formats.marker_block import BlockState, refusal_reason
+
+ from .generated_files import generated_blocks, inspect_block
+
+ items: list[Item] = []
+ for block in generated_blocks():
+ path = block.path(repo_path)
+ state = inspect_block(block, repo_path)
+ blocked = (
+ refusal_reason(state)
+ if state in (BlockState.ORPHANED, BlockState.DUPLICATED, BlockState.UNREADABLE)
+ else None
+ )
+ items.append(
+ Item(
+ group=Group.REPO_FILES,
+ path=path,
+ label=f"{block.marker_tag} block",
+ exists=state is BlockState.PRESENT,
+ size=_size_of(path),
+ blocked=blocked,
+ )
+ )
+ return items
+
+
+def _global_items() -> list[Item]:
+ """``~/.repowise/`` as one row, with the two consequences named.
+
+ One row rather than a file each: the directory is ours end to end, its name
+ is ours, and deleting it needs no content inspection. What it does need is
+ for the two costs to be visible before the box is ticked, which is what the
+ label carries.
+ """
+ # Built from ``Path.home()`` rather than by calling ``user_global_dir()``,
+ # which creates the directory as a side effect of resolving it. Taking the
+ # inventory must not bring into existence the thing it is reporting on, and
+ # under ``--dry-run`` that would be a write from a command that promised
+ # none.
+ try:
+ root = Path.home() / ".repowise"
+ except (OSError, RuntimeError):
+ return []
+ return [
+ Item(
+ group=Group.GLOBAL,
+ path=root,
+ label="machine-wide state (login, caches, telemetry preference)",
+ exists=root.exists(),
+ size=_size_of(root),
+ )
+ ]
+
+
+def _advisories(repo_path: Path) -> list[str]:
+ """Lines that are true whatever the user picks."""
+ lines: list[str] = []
+
+ lines.append(f"The package itself is not ours to remove. Run: {_package_uninstall_hint()}")
+
+ from repowise.cli.agent_targets.targets.claude_code import (
+ PLUGIN_KEY,
+ plugin_manifest_path,
+ )
+
+ if plugin_manifest_path().exists():
+ try:
+ import json
+
+ manifest = json.loads(plugin_manifest_path().read_text(encoding="utf-8"))
+ except (OSError, ValueError):
+ manifest = None
+ if manifest is not None and PLUGIN_KEY in str(manifest):
+ lines.append(
+ "The Claude Code plugin is host-owned and repowise cannot remove it. "
+ f"In Claude Code, run: /plugin uninstall {PLUGIN_KEY}"
+ )
+
+ lines.append(
+ "Hosts you configured by hand from 'repowise agents print-config' are not "
+ "visible to us and were not touched."
+ )
+
+ from repowise.core.workspace.config import WORKSPACE_CONFIG_FILENAME
+
+ if (repo_path / WORKSPACE_CONFIG_FILENAME).exists():
+ lines.append(
+ f"{WORKSPACE_CONFIG_FILENAME} is here, and this command is single-repo. "
+ "Workspace-level files were not touched."
+ )
+ return lines
+
+
+def _package_uninstall_hint() -> str:
+ """The uninstall line for however repowise was actually installed.
+
+ Detected rather than assumed. Telling a pipx user to run ``pip uninstall``
+ hands them a command that reports success and removes nothing.
+ """
+ import sys
+
+ executable = Path(sys.executable).resolve()
+ parts = {part.lower() for part in executable.parts}
+ if "pipx" in parts:
+ return "pipx uninstall repowise"
+ if "uv" in parts or (executable.parent / "uv.exe").exists() or (executable.parent / "uv").exists():
+ return "uv tool uninstall repowise"
+ return "pip uninstall repowise"
+
+
+def build_plan(repo_path: Path) -> Plan:
+ """Enumerate everything, touching nothing."""
+ from repowise.cli.helpers import get_repowise_dir
+
+ index_path = get_repowise_dir(repo_path)
+ plan = Plan(repo_path=repo_path)
+ plan.items.extend(_agent_items(repo_path))
+ plan.items.extend(_repo_file_items(repo_path))
+ plan.items.append(
+ Item(
+ group=Group.INDEX,
+ path=index_path,
+ label="index (rebuilding it costs a full re-index)",
+ exists=index_path.exists(),
+ size=_size_of(index_path),
+ blocked=_index_blocked(repo_path) if index_path.exists() else None,
+ )
+ )
+ plan.items.extend(_global_items())
+ plan.advisories.extend(_advisories(repo_path))
+ return plan
diff --git a/packages/cli/src/repowise/cli/uninstall/runner.py b/packages/cli/src/repowise/cli/uninstall/runner.py
new file mode 100644
index 000000000..b6e48b24b
--- /dev/null
+++ b/packages/cli/src/repowise/cli/uninstall/runner.py
@@ -0,0 +1,281 @@
+"""Executing a plan, and reporting what actually happened.
+
+Composes the six targets' own ``uninstall()`` rather than reimplementing any
+removal. Two implementations of the same removal, drifting apart, is the shape
+of every expensive bug on this track, and a command whose whole job is removing
+more would be the worst place to add a second one.
+"""
+
+from __future__ import annotations
+
+import shutil
+from dataclasses import dataclass, field
+from pathlib import Path
+
+from repowise.cli.agent_targets.types import FileAction
+
+from .inventory import Group, Item, Plan
+
+#: Ran fine, everything chosen is gone.
+EXIT_CLEAN = 0
+#: A removal failed.
+EXIT_FAILED = 1
+#: Ran fine, and something the user chose is still there. Not an error: it is
+#: the honest answer to "is it all gone", and folding it into zero would make
+#: the trust claim unverifiable from a script.
+#:
+#: Three rather than the obvious two, because Click already spends 2 on
+#: ``UsageError``. Sharing it would leave a script unable to tell "I removed
+#: what I could and something remains" from "you typed the command wrong",
+#: which is precisely the distinction these codes exist to carry.
+EXIT_LEFTOVERS = 3
+#: Nothing was removed because no scope was named and nobody could be asked.
+EXIT_NEEDS_SCOPE = 4
+
+
+@dataclass(frozen=True)
+class Result:
+ """What happened to one path."""
+
+ group: Group
+ path: Path
+ action: FileAction
+ label: str
+ reason: str | None = None
+
+ def as_dict(self) -> dict:
+ return {
+ "group": self.group.value,
+ "path": str(self.path),
+ "action": self.action.value,
+ "label": self.label,
+ "reason": self.reason,
+ }
+
+
+@dataclass
+class Outcome:
+ results: list[Result] = field(default_factory=list)
+ notes: list[str] = field(default_factory=list)
+
+ @property
+ def leftovers(self) -> list[Result]:
+ """Everything the user asked to remove that is still there."""
+ return [r for r in self.results if r.action in (FileAction.KEPT, FileAction.FAILED)]
+
+ @property
+ def exit_code(self) -> int:
+ if any(r.action is FileAction.FAILED for r in self.results):
+ return EXIT_FAILED
+ if any(r.action is FileAction.KEPT for r in self.results):
+ return EXIT_LEFTOVERS
+ return EXIT_CLEAN
+
+ @property
+ def complete(self) -> bool:
+ return not self.leftovers
+
+ def as_dict(self) -> dict:
+ return {
+ "results": [r.as_dict() for r in self.results],
+ "notes": list(self.notes),
+ "complete": self.complete,
+ "leftovers": [r.as_dict() for r in self.leftovers],
+ }
+
+
+def _remove_agents(repo_path: Path, plan: Plan) -> tuple[list[Result], list[str]]:
+ """Run every wired target's own uninstall, in one batch.
+
+ The batch matters. ``registry.removing`` tells the shared-file guard which
+ targets are on their way out, so three agents managing ``AGENTS.md`` do not
+ each keep the block for the other two and leave it behind. Removing them one
+ command at a time genuinely does leave the block, which is a documented
+ limitation of the guard rather than something to work around here.
+ """
+ from repowise.cli.agent_targets.registry import all_targets, get_target, removing
+ from repowise.cli.agent_targets.types import Scope
+
+ wired: dict[str, set[Scope]] = {}
+ for item in plan.for_groups(frozenset({Group.AGENTS})):
+ if item.target_id is None or item.scope is None:
+ continue
+ wired.setdefault(item.target_id, set()).add(Scope(item.scope))
+
+ results: list[Result] = []
+ notes: list[str] = []
+ if not wired:
+ return results, notes
+
+ ordered = [target.id for target in all_targets() if target.id in wired]
+ with removing(ordered):
+ for target_id in ordered:
+ target = get_target(target_id)
+ for scope in (Scope.PROJECT, Scope.USER):
+ if scope not in wired[target_id]:
+ continue
+ try:
+ write = target.uninstall(scope, repo_path=repo_path)
+ except Exception as exc:
+ # One target that raises must not abort the other five, and
+ # must not be reported as a removal that happened. `init`
+ # learned this the expensive way: an unguarded call aborted
+ # a run part-way through with other agents already written.
+ results.append(
+ Result(
+ group=Group.AGENTS,
+ path=repo_path,
+ action=FileAction.FAILED,
+ label=f"{target.display_name} ({scope.value})",
+ reason=str(exc),
+ )
+ )
+ continue
+ notes.extend(write.notes)
+ for written in write.files:
+ results.append(
+ Result(
+ group=Group.AGENTS,
+ path=written.path,
+ action=written.action,
+ label=f"{target.display_name} ({scope.value})",
+ reason=written.reason,
+ )
+ )
+ return results, notes
+
+
+def _remove_repo_files(repo_path: Path, plan: Plan) -> list[Result]:
+ from .generated_files import generated_blocks, remove_block
+
+ by_path = {item.path: item for item in plan.for_groups(frozenset({Group.REPO_FILES}))}
+ results: list[Result] = []
+ for block in generated_blocks():
+ item = by_path.get(block.path(repo_path))
+ label = item.label if item else block.marker_tag
+ if item is not None and item.blocked:
+ results.append(
+ Result(
+ group=Group.REPO_FILES,
+ path=item.path,
+ action=FileAction.KEPT,
+ label=label,
+ reason=item.blocked,
+ )
+ )
+ continue
+ path, action, reason = remove_block(block, repo_path)
+ results.append(
+ Result(group=Group.REPO_FILES, path=path, action=action, label=label, reason=reason)
+ )
+ return results
+
+
+def _is_link(path: Path) -> bool:
+ """Symlink or Windows junction.
+
+ ``is_symlink()`` alone is not enough and this is the platform we ship on:
+ a junction, which is how a Windows user relocates a directory, reports
+ ``is_symlink() == False``. ``rmtree`` happens to refuse both, so the guard
+ was not the thing keeping the target safe; it was only deciding whether the
+ row said "refused because it is a link" or "failed" with a message about
+ symbolic links that named neither the junction nor what to do.
+ """
+ import os
+
+ if path.is_symlink():
+ return True
+ isjunction = getattr(os.path, "isjunction", None)
+ if isjunction is None:
+ return False
+ try:
+ return bool(isjunction(path))
+ except OSError:
+ return False
+
+
+def _remove_tree(item: Item) -> Result:
+ """Delete a directory whose name is ours, and refuse anything else.
+
+ Ownership is the path, not the contents. ``.repowise/`` and ``~/.repowise/``
+ are named by us and created by us, so removing them needs no inspection of
+ what is inside and therefore has no invariant to get wrong. That is the only
+ tier of ownership on which this command deletes a whole tree.
+
+ A symlink is refused rather than followed. Deleting through a junction
+ reaches somewhere this command never enumerated and never showed the user.
+ """
+ if item.blocked:
+ return Result(
+ group=item.group,
+ path=item.path,
+ action=FileAction.KEPT,
+ label=item.label,
+ reason=item.blocked,
+ )
+ if not item.path.exists():
+ return Result(
+ group=item.group, path=item.path, action=FileAction.NOT_FOUND, label=item.label
+ )
+ if _is_link(item.path):
+ return Result(
+ group=item.group,
+ path=item.path,
+ action=FileAction.KEPT,
+ label=item.label,
+ reason="this is a symlink or junction, and following it would delete something "
+ "outside the tree this command enumerated",
+ )
+ try:
+ shutil.rmtree(item.path)
+ except OSError as exc:
+ return Result(
+ group=item.group,
+ path=item.path,
+ action=FileAction.FAILED,
+ label=item.label,
+ reason=str(exc),
+ )
+ # Proven from disk rather than from the absence of an exception. `rmtree`
+ # can return having left files behind on Windows when something holds a
+ # handle, and reporting REMOVED over a directory that is still there is the
+ # false success this track has already shipped once.
+ if item.path.exists():
+ return Result(
+ group=item.group,
+ path=item.path,
+ action=FileAction.FAILED,
+ label=item.label,
+ reason="the directory was still present after the delete",
+ )
+ return Result(group=item.group, path=item.path, action=FileAction.REMOVED, label=item.label)
+
+
+def execute(plan: Plan, groups: frozenset[Group]) -> Outcome:
+ """Carry out *plan*, restricted to *groups*."""
+ outcome = Outcome()
+
+ if Group.AGENTS in groups:
+ results, notes = _remove_agents(plan.repo_path, plan)
+ outcome.results.extend(results)
+ outcome.notes.extend(notes)
+
+ if Group.REPO_FILES in groups:
+ outcome.results.extend(_remove_repo_files(plan.repo_path, plan))
+
+ # After the agent and repo-file passes, never before: both write into the
+ # repo, and `.repowise/` holds the config that `describe_paths` consults.
+ for group in (Group.INDEX, Group.GLOBAL):
+ if group not in groups:
+ continue
+ for item in plan.for_groups(frozenset({group})):
+ outcome.results.append(_remove_tree(item))
+
+ if Group.GLOBAL in groups and any(
+ r.group is Group.GLOBAL and r.action is FileAction.REMOVED for r in outcome.results
+ ):
+ outcome.notes.append(
+ "Machine-wide state is gone, including your telemetry preference and your "
+ "anonymous id. A future install will ask about telemetry again."
+ )
+ return outcome
diff --git a/tests/unit/cli/test_agent_targets.py b/tests/unit/cli/test_agent_targets.py
index f4d84d8b7..ef10c3aa7 100644
--- a/tests/unit/cli/test_agent_targets.py
+++ b/tests/unit/cli/test_agent_targets.py
@@ -2394,26 +2394,54 @@ def test_hermes_and_codex_do_not_strip_the_shared_block_from_each_other(
Driven through both targets rather than by calling the helper by hand, so
deleting either side's guard fails this.
+
+ One scenario per direction, each on its own repo. Chaining them used to work
+ on a single repo and no longer does, for a reason worth recording: Codex's
+ project uninstall now removes ``.codex/config.toml``, so a removed Codex
+ stops being detected as wired. Before that, its leftover config kept
+ answering "still an owner" long after it had been removed, and the second
+ half of a chained test was really asserting on that leftover. The block
+ surviving both agents' removal was the bug, not the contract.
"""
- repo = tmp_path / "repo"
- repo.mkdir()
hermes_target = get_target("hermes")
codex_target = get_target("codex")
-
- codex_target.install(Scope.PROJECT, repo_path=repo)
hermes_target.install(Scope.USER)
- hermes_target.install(Scope.PROJECT, repo_path=repo)
- removed_codex = codex_target.uninstall(Scope.PROJECT, repo_path=repo)
- assert FileAction.KEPT in [written.action for written in removed_codex.files]
+ # Codex removed while Hermes is still wired.
+ codex_first = tmp_path / "codex-first"
+ codex_first.mkdir()
+ codex_target.install(Scope.PROJECT, repo_path=codex_first)
+ hermes_target.install(Scope.PROJECT, repo_path=codex_first)
+ removed_codex = codex_target.uninstall(Scope.PROJECT, repo_path=codex_first)
+ kept_codex = [w for w in removed_codex.files if w.action is FileAction.KEPT]
+ assert kept_codex
+ assert any("Hermes" in (w.reason or "") for w in kept_codex)
assert any("Hermes" in note for note in removed_codex.notes)
-
- removed_hermes = hermes_target.uninstall(Scope.PROJECT, repo_path=repo)
- assert FileAction.KEPT in [written.action for written in removed_hermes.files]
+ assert "REPOWISE_DISTILL:START" in (codex_first / "AGENTS.md").read_text(encoding="utf-8")
+
+ # Hermes removed while Codex is still wired.
+ hermes_first = tmp_path / "hermes-first"
+ hermes_first.mkdir()
+ codex_target.install(Scope.PROJECT, repo_path=hermes_first)
+ hermes_target.install(Scope.PROJECT, repo_path=hermes_first)
+ removed_hermes = hermes_target.uninstall(Scope.PROJECT, repo_path=hermes_first)
+ kept_hermes = [w for w in removed_hermes.files if w.action is FileAction.KEPT]
+ assert kept_hermes
+ assert any("Codex" in (w.reason or "") for w in kept_hermes)
assert any("Codex" in note for note in removed_hermes.notes)
-
- # The block is still there, which is the whole point.
- assert "REPOWISE_DISTILL:START" in (repo / "AGENTS.md").read_text(encoding="utf-8")
+ assert "REPOWISE_DISTILL:START" in (hermes_first / "AGENTS.md").read_text(encoding="utf-8")
+
+ # Removing the second agent in a *separate* invocation does not free the
+ # block, and that is a known limitation rather than an accident. Hermes's
+ # project-scope detection reads the very block that was kept for Codex, so
+ # a Hermes removed a command ago still answers "still an owner" and Codex
+ # keeps the block for it. `registry.removing` breaks exactly this cycle, but
+ # only within one command: `agents remove --target=codex,hermes` and
+ # `repowise uninstall` both batch and both clear the block. Pinned here so
+ # the behaviour is a recorded decision rather than a surprise.
+ second = codex_target.uninstall(Scope.PROJECT, repo_path=hermes_first)
+ assert FileAction.KEPT in [w.action for w in second.files]
+ assert "REPOWISE_DISTILL:START" in (hermes_first / "AGENTS.md").read_text(encoding="utf-8")
def test_hermes_batch_removal_does_not_deadlock_on_the_shared_block(
diff --git a/tests/unit/cli/test_agents_cmd.py b/tests/unit/cli/test_agents_cmd.py
index 88715d8cb..1a02b033d 100644
--- a/tests/unit/cli/test_agents_cmd.py
+++ b/tests/unit/cli/test_agents_cmd.py
@@ -233,8 +233,11 @@ def test_remove_takes_the_entry_out_and_reports_it_both_ways(repo: Path) -> None
assert payload["action"] == "remove"
assert payload["agents"][0]["writes"]["project"]["files"][0]["action"] == "removed"
- config = json.loads((repo / ".vscode" / "mcp.json").read_text(encoding="utf-8"))
- assert "repowise" not in config["servers"]
+ # The file goes with the entry when it held nothing else. It used to be left
+ # as a `{"servers": {}}` stub: a file repowise created, that the user never
+ # asked for, that still reads as repowise having been here, and that re-armed
+ # `is_present` for a repo it had just been removed from.
+ assert not (repo / ".vscode" / "mcp.json").exists()
output = _run(["agents", "remove", str(repo), "--target", "vscode"]).output
assert "not-found" in output
@@ -305,7 +308,8 @@ def test_remove_takes_the_extension_recommendation_with_it(repo: Path) -> None:
written = {f["path"]: f["action"] for f in payload["agents"][0]["writes"]["project"]["files"]}
assert written[str(extensions)] == "removed"
- assert json.loads(extensions.read_text(encoding="utf-8"))["recommendations"] == []
+ # Same prune as mcp.json: an empty recommendations array is a stub, not a file.
+ assert not extensions.exists()
def test_refresh_on_a_clean_repo_says_nothing_is_wired(repo: Path) -> None:
diff --git a/tests/unit/cli/test_lazy_commands.py b/tests/unit/cli/test_lazy_commands.py
index 4a6c0dc7a..66791737b 100644
--- a/tests/unit/cli/test_lazy_commands.py
+++ b/tests/unit/cli/test_lazy_commands.py
@@ -38,7 +38,7 @@ _EXPECTED_NAMES = frozenset(
"export", "generate", "generate-claude-md", "health", "hook",
"impacted-tests", "init", "login", "logout", "mcp", "reindex", "restyle",
"risk", "saved", "search", "security", "serve", "status", "symbol",
- "telemetry", "update", "watch", "whats-new", "whoami", "why",
+ "telemetry", "uninstall", "update", "watch", "whats-new", "whoami", "why",
"wiki-styles", "workspace",
}
) # fmt: skip
diff --git a/tests/unit/cli/test_toml_removal.py b/tests/unit/cli/test_toml_removal.py
new file mode 100644
index 000000000..3365c3256
--- /dev/null
+++ b/tests/unit/cli/test_toml_removal.py
@@ -0,0 +1,385 @@
+"""Removing a TOML table without taking the user's comments with it.
+
+Every test here is a regression. The first implementation of ``remove_table``
+shared ``replace_table``'s regex, whose terminating lookahead is ``(?=^\\s*\\[|\\Z)``
+and whose ``\\s`` does not match ``#``. So a comment line never ended the span,
+everything from our header to the next live header was consumed, and a
+``.codex/config.toml`` whose remainder was the user's commented-out server came
+back empty. The caller read empty as "this file was ours" and deleted it, then
+removed ``.codex/`` behind it, and reported a clean ``removed``. The directory is
+gitignored in most repos, so nothing showed it.
+
+That is two of this track's named historical bugs at once: deleting a section
+that still held a commented-out server, and treating an empty parse as an empty
+file. It is worse than the second, because the regex had already eaten the
+evidence before the emptiness test ran.
+"""
+
+from __future__ import annotations
+
+from pathlib import Path
+
+import pytest
+
+from repowise.cli.agent_targets.formats.toml_merge import (
+ remove_key_line,
+ remove_table,
+ table_is_bare,
+)
+from repowise.cli.agent_targets.targets.codex import (
+ project_config_path,
+ remove_server_config,
+)
+from repowise.cli.agent_targets.types import FileAction
+
+
+def _write(repo: Path, text: str) -> Path:
+ path = project_config_path(repo)
+ path.parent.mkdir(parents=True, exist_ok=True)
+ path.write_text(text, encoding="utf-8")
+ return path
+
+
+# ---------------------------------------------------------------------------
+# remove_table
+# ---------------------------------------------------------------------------
+
+
+def test_a_commented_out_server_after_our_table_survives() -> None:
+ text = (
+ '[mcp_servers.repowise]\ncommand = "repowise"\n\n'
+ '# [mcp_servers.other]\n# command = "other-server"\n'
+ )
+ remaining = remove_table(text, "mcp_servers.repowise")
+
+ assert "mcp_servers.other" in remaining
+ assert "other-server" in remaining
+ assert "repowise" not in remaining
+
+
+def test_the_users_prose_comments_after_our_table_survive() -> None:
+ text = (
+ '[mcp_servers.repowise]\ncommand = "repowise"\n\n'
+ "# my notes about codex\n# remember sandbox mode\n"
+ )
+ remaining = remove_table(text, "mcp_servers.repowise")
+
+ assert "my notes about codex" in remaining
+ assert "remember sandbox mode" in remaining
+
+
+def test_a_warning_comment_before_a_live_sibling_survives() -> None:
+ text = (
+ '[mcp_servers.repowise]\ncommand = "repowise"\n\n'
+ "# this one talks to prod, do not remove\n"
+ '[mcp_servers.prod]\ncommand = "p"\n'
+ )
+ remaining = remove_table(text, "mcp_servers.repowise")
+
+ assert "do not remove" in remaining
+ assert "[mcp_servers.prod]" in remaining
+
+
+def test_comments_annotating_our_own_keys_go_with_the_table() -> None:
+ """Only the *trailing* run is ambiguous. Comments inside the table are ours."""
+ text = (
+ "[mcp_servers.repowise]\n# generated by repowise\n"
+ 'command = "repowise"\n[mcp_servers.prod]\nc = 1\n'
+ )
+ remaining = remove_table(text, "mcp_servers.repowise")
+
+ assert "generated by repowise" not in remaining
+ assert "[mcp_servers.prod]" in remaining
+
+
+def test_a_file_holding_only_our_table_really_does_empty() -> None:
+ assert remove_table('[mcp_servers.repowise]\ncommand = "repowise"\n', "mcp_servers.repowise") == ""
+
+
+def test_a_sibling_with_our_name_as_a_prefix_is_untouched() -> None:
+ text = '[mcp_servers.repowiseX]\ncommand = "x"\n'
+ assert remove_table(text, "mcp_servers.repowise") == text
+
+
+def test_crlf_endings_are_not_mixed_on_the_last_line() -> None:
+ text = '[mcp_servers.repowise]\r\nc = 1\r\n[mcp_servers.b]\r\nc = 2\r\n'
+ remaining = remove_table(text, "mcp_servers.repowise")
+
+ assert "\n" not in remaining.replace("\r\n", "")
+
+
+# ---------------------------------------------------------------------------
+# remove_key_line and table_is_bare
+# ---------------------------------------------------------------------------
+
+
+def test_dropping_one_key_keeps_the_rest_of_the_table_verbatim() -> None:
+ text = "[features]\n# why this is on\nhooks = true\nretries = [1, 2, 3]\n"
+ remaining = remove_key_line(text, "features", "hooks")
+
+ assert "hooks = true" not in remaining
+ assert "retries = [1, 2, 3]" in remaining
+ assert "why this is on" in remaining
+
+
+def test_a_multi_line_value_is_declined_rather_than_cut_at_the_newline() -> None:
+ """Cutting the first line orphans the rest into text that is not TOML.
+
+ The caller's own validation then raised, from a helper whose message reads
+ "no changes were written", over a file already rewritten and a hooks file
+ already deleted.
+ """
+ text = '[features]\nhooks = [\n "a",\n "b",\n]\nother = 1\n'
+ assert remove_key_line(text, "features", "hooks") == text
+
+
+def test_a_single_line_collection_value_is_still_removed() -> None:
+ text = "[features]\nhooks = [1, 2]\nother = 1\n"
+ remaining = remove_key_line(text, "features", "hooks")
+
+ assert "hooks" not in remaining
+ assert "other = 1" in remaining
+
+
+def test_a_bracket_inside_a_string_does_not_look_like_a_continuation() -> None:
+ text = '[features]\nhooks = "a [ b"\nother = 1\n'
+ assert "hooks" not in remove_key_line(text, "features", "hooks")
+
+
+ ("value", "complete"),
+ [
+ ('"plain"', True),
+ ("true", True),
+ ("[1, 2]", True),
+ ("{ a = 1 }", True),
+ ('"a # b"', True),
+ ('"a [ b"', True),
+ ('"a \\" b"', True),
+ ("42 # a trailing comment", True),
+ ("[", False),
+ ("{", False),
+ ("[1,", False),
+ ('"unterminated', False),
+ ('"""', False),
+ ("'''", False),
+ ],
+)
+def test_value_completeness_is_judged_per_shape(value: str, complete: bool) -> None:
+ """The guard itself, not merely the behaviour given a guard exists.
+
+ Without this, deleting `_value_is_complete` outright left the suite green:
+ the surrounding tests all pass whether or not the multi-line refusal is
+ reached, because the caller catches the resulting validation failure.
+ """
+ from repowise.cli.agent_targets.formats.toml_merge import _value_is_complete
+
+ assert _value_is_complete(value) is complete
+
+
+def test_a_key_line_inside_a_multi_line_string_is_not_a_key() -> None:
+ """It is text in someone else's value, and cutting it edited that value."""
+ text = '[features]\nbanner = """\nhooks = true\n"""\nother = 1\n'
+ assert remove_key_line(text, "features", "hooks") == text
+
+
+def test_a_key_that_merely_shares_a_prefix_is_left_alone() -> None:
+ text = "[features]\nhooks_extra = 1\n"
+ assert remove_key_line(text, "features", "hooks") == text
+
+
+def test_a_feature_value_we_cannot_cut_does_not_abandon_the_server_removal(
+ tmp_path: Path,
+) -> None:
+ """The two edits are independent, and coupling them was the worse bug.
+
+ Accumulating both into one string and gating the write on "did either fail"
+ meant a multi-line ``features.hooks`` (Codex's own key, nothing to do with
+ us) threw away a clean removal of ``[mcp_servers.repowise]`` and blamed it
+ on the repowise entry using an unmatched key spelling. Codex went on
+ launching our MCP server while the report said ``kept``.
+ """
+ import tomllib
+
+ from repowise.cli.agent_targets.registry import get_target
+ from repowise.cli.agent_targets.types import Scope
+
+ repo = tmp_path / "repo"
+ repo.mkdir()
+ config = _write(
+ repo,
+ '[mcp_servers.repowise]\ncommand = "repowise"\n'
+ '[features]\nhooks = [\n "a",\n]\nother = 1\n',
+ )
+ hooks = repo / ".codex" / "hooks.json"
+ hooks.write_text(
+ '{"hooks": {"SessionStart": [{"hooks": [{"command": "repowise-augment"}]}]}}',
+ encoding="utf-8",
+ )
+
+ get_target("codex").uninstall(Scope.PROJECT, repo_path=repo)
+
+ body = config.read_text(encoding="utf-8")
+ tomllib.loads(body)
+ # The server entry is gone even though the feature line could not be cut.
+ assert "mcp_servers.repowise" not in body
+ # And the value we declined to cut is untouched, in full.
+ assert "other = 1" in body
+ assert '"a",' in body
+
+
+def test_one_row_per_file(tmp_path: Path) -> None:
+ """Two passes over config.toml put two rows for one path in the report."""
+ from repowise.cli.agent_targets.registry import get_target
+ from repowise.cli.agent_targets.types import Scope
+
+ repo = tmp_path / "repo"
+ repo.mkdir()
+ _write(repo, '[mcp_servers.repowise]\ncommand = "repowise"\n[features]\nhooks = true\n')
+
+ result = get_target("codex").uninstall(Scope.PROJECT, repo_path=repo)
+
+ paths = [w.path for w in result.files]
+ assert len(paths) == len(set(paths)), paths
+
+
+def test_a_table_holding_a_comment_is_not_bare() -> None:
+ assert not table_is_bare("[features]\n# a note\n", "features")
+ assert table_is_bare("[features]\n\n", "features")
+
+
+# ---------------------------------------------------------------------------
+# through the target
+# ---------------------------------------------------------------------------
+
+
+def test_uninstall_does_not_delete_a_config_holding_the_users_comments(tmp_path: Path) -> None:
+ """The end-to-end form of the critical bug."""
+ repo = tmp_path / "repo"
+ repo.mkdir()
+ path = _write(
+ repo,
+ '[mcp_servers.repowise]\ncommand = "repowise"\n\n'
+ '# [mcp_servers.other]\n# command = "other-server"\n',
+ )
+
+ write = remove_server_config(repo, drop_hooks_feature=False)
+
+ assert write.action is FileAction.REMOVED
+ assert path.exists(), "the file held the user's commented-out server and was deleted"
+ body = path.read_text(encoding="utf-8")
+ assert "other-server" in body
+ assert "mcp_servers.repowise" not in body
+
+
+def test_uninstall_still_deletes_a_config_that_was_only_ours(tmp_path: Path) -> None:
+ repo = tmp_path / "repo"
+ repo.mkdir()
+ path = _write(repo, '[mcp_servers.repowise]\ncommand = "repowise"\n')
+
+ write = remove_server_config(repo, drop_hooks_feature=False)
+
+ assert write.action is FileAction.REMOVED
+ assert not path.exists()
+
+
+def test_an_unencodable_value_in_the_users_features_table_does_not_raise(tmp_path: Path) -> None:
+ """``[features]`` is Codex's table, so it is dropped a line at a time, not re-rendered."""
+ repo = tmp_path / "repo"
+ repo.mkdir()
+ path = _write(
+ repo,
+ '[mcp_servers.repowise]\ncommand = "repowise"\n[features]\nhooks = true\nretries = [1, 2, 3]\n',
+ )
+
+ write = remove_server_config(repo, drop_hooks_feature=True)
+
+ assert write.action is FileAction.REMOVED
+ body = path.read_text(encoding="utf-8")
+ assert "hooks = true" not in body
+ assert "retries = [1, 2, 3]" in body
+
+
+def test_an_array_of_tables_spelling_is_refused_rather_than_missed(tmp_path: Path) -> None:
+ repo = tmp_path / "repo"
+ repo.mkdir()
+ _write(repo, '[[mcp_servers.repowise]]\ncommand = "repowise"\n')
+
+ write = remove_server_config(repo, drop_hooks_feature=False)
+
+ assert write.action is FileAction.KEPT
+ assert write.reason
+
+
+def test_an_unparseable_config_declines_instead_of_raising(tmp_path: Path) -> None:
+ """It used to raise out of the middle of a batch, after deleting hooks.json.
+
+ ``agents remove --target=all`` reaches codex second of six, so the abort
+ took the other four targets with it, and the exception's own text said "no
+ changes were written" over a hooks file that had already gone.
+ """
+ repo = tmp_path / "repo"
+ repo.mkdir()
+ config = _write(repo, "bad = = toml [[[\n")
+ hooks = repo / ".codex" / "hooks.json"
+ hooks.write_text(
+ '{"hooks": {"SessionStart": [{"hooks": [{"command": "repowise-augment"}]}]}}',
+ encoding="utf-8",
+ )
+
+ from repowise.cli.agent_targets.registry import get_target
+ from repowise.cli.agent_targets.types import Scope
+
+ result = get_target("codex").uninstall(Scope.PROJECT, repo_path=repo)
+
+ kept = [w for w in result.files if w.action is FileAction.KEPT and w.path == config]
+ assert kept and kept[0].reason
+ assert config.read_text(encoding="utf-8") == "bad = = toml [[[\n"
+
+
+def test_an_empty_codex_dir_holding_nothing_of_ours_is_not_deleted(tmp_path: Path) -> None:
+ """Pruning ran unconditionally, so it removed a directory it never wrote in."""
+ from repowise.cli.agent_targets.registry import get_target
+ from repowise.cli.agent_targets.types import Scope
+
+ repo = tmp_path / "repo"
+ repo.mkdir()
+ (repo / ".codex").mkdir()
+
+ result = get_target("codex").uninstall(Scope.PROJECT, repo_path=repo)
+
+ assert all(w.action is not FileAction.REMOVED for w in result.files)
+ assert (repo / ".codex").exists()
+
+
+def test_an_empty_vscode_dir_holding_nothing_of_ours_is_not_deleted(tmp_path: Path) -> None:
+ from repowise.cli.agent_targets.registry import get_target
+ from repowise.cli.agent_targets.types import Scope
+
+ repo = tmp_path / "repo"
+ repo.mkdir()
+ (repo / ".vscode").mkdir()
+
+ get_target("vscode").uninstall(Scope.PROJECT, repo_path=repo)
+
+ assert (repo / ".vscode").exists()
+
+
+ "text",
+ [
+ '[mcp_servers.repowise]\ncommand = "repowise"\n[mcp_servers.repowise.env]\nA = "1"\n',
+ '[mcp_servers.repowise] # trailing comment\ncommand = "repowise"\n',
+ ],
+)
+def test_a_spelling_the_remover_cannot_match_is_kept_with_a_reason(
+ tmp_path: Path, text: str
+) -> None:
+ repo = tmp_path / "repo"
+ repo.mkdir()
+ _write(repo, text)
+
+ write = remove_server_config(repo, drop_hooks_feature=False)
+
+ assert write.action is FileAction.KEPT
+ assert write.reason
diff --git a/tests/unit/cli/test_uninstall_cmd.py b/tests/unit/cli/test_uninstall_cmd.py
new file mode 100644
index 000000000..72537eab5
--- /dev/null
+++ b/tests/unit/cli/test_uninstall_cmd.py
@@ -0,0 +1,610 @@
+"""``repowise uninstall``, driven end to end through ``CliRunner``.
+
+Through the command rather than by calling the helpers, deliberately. This track
+has already shipped a fix whose test called ``registry.removing()`` by hand and
+stayed green when the entire CLI half of the fix was deleted. A removal command
+is the last place to accept that.
+
+The home directory is redirected twice over, and both layers matter. The
+autouse ``_isolated_home`` fixture in ``tests/unit/cli/conftest.py`` covers
+every test in this file including the ones that take only ``tmp_path``; the
+``repo`` fixture below re-points ``HOME``/``USERPROFILE``/``Path.home`` at a
+second temp dir for the tests that use it. The command can delete
+``~/.repowise`` and rewrite ``~/.claude``, and a review of this work already
+destroyed a real machine's agent wiring by running the runner without a
+redirect, so neither layer is optional.
+"""
+
+from __future__ import annotations
+
+import json
+from pathlib import Path
+
+import pytest
+from click.testing import CliRunner
+
+from repowise.cli.main import cli
+
+
+def repo(tmp_path_factory, monkeypatch) -> Path:
+ home = tmp_path_factory.mktemp("uninstall_home")
+ repo_path = tmp_path_factory.mktemp("uninstall_repo")
+
+ monkeypatch.setenv("HOME", str(home))
+ monkeypatch.setenv("USERPROFILE", str(home))
+ monkeypatch.setenv("HOMEDRIVE", home.drive or "")
+ monkeypatch.setenv("HOMEPATH", str(home)[len(home.drive) :])
+ monkeypatch.setattr(Path, "home", lambda: home)
+ monkeypatch.delenv("REPOWISE_SKIP_EDITOR_SETUP", raising=False)
+
+ (repo_path / ".repowise").mkdir()
+ (repo_path / ".repowise" / "wiki.db").write_text("not really a database", encoding="utf-8")
+ monkeypatch.chdir(repo_path)
+ return repo_path
+
+
+def _invoke(args: list[str]):
+ return CliRunner().invoke(cli, args, catch_exceptions=False)
+
+
+def _payload(args: list[str]) -> dict:
+ result = _invoke([*args, "--format", "json"])
+ return json.loads(result.output)
+
+
+def _wire_everything(repo: Path) -> None:
+ """All six targets, not four.
+
+ ``test_every_kept_row_carries_a_reason`` claimed to cover every target while
+ hermes and opencode were absent from the scenario entirely, so reverting the
+ reason wiring in either left it green.
+ """
+ CliRunner().invoke(
+ cli,
+ [
+ "agents",
+ "add",
+ str(repo),
+ "--target",
+ "claude-code,codex,vscode,cursor,opencode,hermes",
+ "-y",
+ ],
+ catch_exceptions=False,
+ )
+
+
+def _write_generated_blocks(repo: Path) -> tuple[Path, Path]:
+ """The two blocks the generators write, with the user's own prose around them."""
+ from repowise.core.generation.editor_files.agents_md import AgentsMdGenerator
+ from repowise.core.generation.editor_files.base import BaseEditorFileGenerator
+
+ def fenced(tag: str) -> str:
+ start = BaseEditorFileGenerator.MARKER_START_FMT.format(tag=tag)
+ end = BaseEditorFileGenerator.MARKER_END_FMT.format(tag=tag)
+ return f"{start}\ngenerated body\n{end}"
+
+ claude = repo / ".claude" / "CLAUDE.md"
+ claude.parent.mkdir(parents=True, exist_ok=True)
+ claude.write_text(f"# CLAUDE.md\n\nmy own notes\n\n{fenced('REPOWISE')}\n", encoding="utf-8")
+
+ agents = repo / AgentsMdGenerator.filename
+ agents.write_text(
+ f"# AGENTS.md\n\nmy own notes\n\n{fenced('REPOWISE_AGENTS')}\n", encoding="utf-8"
+ )
+ return claude, agents
+
+
+# ---------------------------------------------------------------------------
+# The flags, and the one that does not exist
+# ---------------------------------------------------------------------------
+
+
+def test_yes_is_refused_with_the_flag_to_use_instead(repo: Path) -> None:
+ """``--yes`` means 'run the default' everywhere else, and there is no safe default here."""
+ result = _invoke(["uninstall", str(repo), "--yes"])
+ assert result.exit_code != 0
+ assert "--all" in result.output
+ assert "--keep-index" in result.output
+ assert (repo / ".repowise").exists()
+
+
+def test_all_and_keep_index_together_are_refused(repo: Path) -> None:
+ result = _invoke(["uninstall", str(repo), "--all", "--keep-index"])
+ assert result.exit_code != 0
+ assert (repo / ".repowise").exists()
+
+
+def test_no_terminal_and_no_scope_flag_removes_nothing_and_exits_non_zero(repo: Path) -> None:
+ """Consent is never inferred from a tty probe, in either direction."""
+ _wire_everything(repo)
+ result = _invoke(["uninstall", str(repo)])
+
+ assert result.exit_code != 0
+ assert (repo / ".repowise").exists()
+ assert (repo / ".mcp.json").exists()
+ # It still says where it looked, which is the half that makes the refusal useful.
+ assert str(repo / ".repowise") in result.output
+ assert "--all" in result.output
+
+
+# ---------------------------------------------------------------------------
+# dry run
+# ---------------------------------------------------------------------------
+
+
+def test_dry_run_changes_nothing_at_all(repo: Path) -> None:
+ _wire_everything(repo)
+ _write_generated_blocks(repo)
+ before = sorted(str(p.relative_to(repo)) for p in repo.rglob("*"))
+
+ result = _invoke(["uninstall", str(repo), "--all", "--dry-run"])
+
+ assert result.exit_code == 0
+ assert sorted(str(p.relative_to(repo)) for p in repo.rglob("*")) == before
+
+
+def test_dry_run_names_every_path_the_real_run_touches(repo: Path) -> None:
+ """The claim worth testing is plan-against-results, not plan-against-plan.
+
+ An earlier version of this test compared ``dry["plan"]`` to ``real["plan"]``,
+ which are two calls to the same pure function over the same tree. It would
+ have stayed green if ``execute`` had ignored the plan completely.
+ """
+ _wire_everything(repo)
+ _write_generated_blocks(repo)
+
+ dry = _payload(["uninstall", str(repo), "--all", "--dry-run"])
+ real = _payload(["uninstall", str(repo), "--all"])
+
+ assert dry["dry_run"] is True
+ assert real["dry_run"] is False
+ assert dry["groups"] == real["groups"]
+
+ planned = {Path(item["path"]) for item in dry["plan"]["items"]}
+ touched = [
+ Path(result["path"])
+ for result in real["results"]
+ if result["action"] in ("removed", "failed")
+ ]
+ # At or under an announced path. The plan names `~/.codex/prompts` once
+ # while the report names the eighteen files inside it, and a user shown the
+ # directory has been told about its contents. What must never happen is a
+ # removal somewhere the plan did not mention at all.
+ unannounced = [
+ path
+ for path in touched
+ if path not in planned and not any(parent in planned for parent in path.parents)
+ ]
+ assert not unannounced, f"removed paths the dry run never named: {sorted(unannounced)}"
+
+
+def test_dry_run_honours_the_scope_flag_it_was_given(repo: Path) -> None:
+ """The pre-flight has to describe the run it is a pre-flight for.
+
+ With the dry-run branch ahead of ``--keep-index``, this reported that the
+ index and the machine-wide login would go, which is the opposite of what
+ ``--keep-index`` actually does.
+ """
+ _wire_everything(repo)
+
+ kept = _payload(["uninstall", str(repo), "--keep-index", "--dry-run"])
+ everything = _payload(["uninstall", str(repo), "--all", "--dry-run"])
+
+ assert "index" not in kept["groups"]
+ assert "global" not in kept["groups"]
+ assert "index" in everything["groups"]
+ assert kept["groups"] != everything["groups"]
+
+
+def test_a_repo_that_never_had_repowise_reports_no_agent_wiring(tmp_path: Path) -> None:
+ """Existence is not evidence, and most of these files belong to the host.
+
+ Only three of the eighteen paths the six targets describe are ours alone.
+ Keying the inventory on existence listed every Claude Code, Codex and Cursor
+ user's own config as ours, pre-ticked the agent group in a repo where
+ repowise had never run, and had the runner call user-scope uninstalls for
+ scopes detection never found.
+ """
+ from repowise.cli.uninstall import build_plan
+ from repowise.cli.uninstall.inventory import Group
+
+ stranger = tmp_path / "stranger"
+ (stranger / ".vscode").mkdir(parents=True)
+ (stranger / ".vscode" / "extensions.json").write_text(
+ '{"recommendations": ["ms-python.python"]}', encoding="utf-8"
+ )
+ (stranger / "AGENTS.md").write_text("# AGENTS.md\n\nmy own notes\n", encoding="utf-8")
+ (stranger / ".mcp.json").write_text(
+ '{"mcpServers": {"someone-else": {"command": "x"}}}', encoding="utf-8"
+ )
+
+ plan = build_plan(stranger)
+
+ assert plan.for_groups(frozenset({Group.AGENTS})) == []
+ assert Group.AGENTS not in plan.groups_present()
+
+
+def test_a_config_naming_us_is_found_even_when_it_cannot_be_parsed(tmp_path: Path) -> None:
+ """The other half of the same rule: the probe is bytes, not a parse.
+
+ The sibling file is what makes this discriminate. Under the old existence
+ check both files were listed, so asserting only on the first one passed
+ either way; it pinned the previous round's behaviour, not this one's.
+ """
+ from repowise.cli.uninstall import build_plan
+ from repowise.cli.uninstall.inventory import Group
+
+ repo = tmp_path / "jsonc"
+ (repo / ".vscode").mkdir(parents=True)
+ config = repo / ".vscode" / "mcp.json"
+ config.write_text(
+ '{\n // a comment VS Code accepts and our parser does not\n'
+ ' "servers": {"repowise": {}}\n}\n',
+ encoding="utf-8",
+ )
+ # Present, ours by path, and naming someone else entirely.
+ stranger = repo / ".cursor" / "mcp.json"
+ stranger.parent.mkdir(parents=True)
+ stranger.write_text('{"mcpServers": {"someone-else": {}}}', encoding="utf-8")
+
+ listed = {item.path for item in build_plan(repo).for_groups(frozenset({Group.AGENTS}))}
+
+ assert config in listed
+ assert stranger not in listed
+
+
+def test_codex_user_scope_is_found_from_the_prompts_directory_alone(tmp_path: Path) -> None:
+ """Install writes the prompts unconditionally; detection reads only the hook.
+
+ A directory answering False to the probe left all eighteen prompt files on
+ disk under "everything selected is gone".
+ """
+ from repowise.cli.uninstall import build_plan
+ from repowise.cli.uninstall.inventory import Group
+
+ prompts = Path.home() / ".codex" / "prompts"
+ prompts.mkdir(parents=True, exist_ok=True)
+ (prompts / "repowise-ask.md").write_text("body", encoding="utf-8")
+ # JSONC, so `detect` cannot see the hook even if one is there.
+ hooks = Path.home() / ".codex" / "hooks.json"
+ hooks.write_text("{\n // a comment\n}\n", encoding="utf-8")
+
+ listed = {item.path for item in build_plan(tmp_path).for_groups(frozenset({Group.AGENTS}))}
+
+ assert prompts in listed
+
+
+def test_a_bare_dry_run_needs_no_scope_flag(repo: Path) -> None:
+ """It asks nobody anything, so it must not route through the prompt."""
+ _wire_everything(repo)
+ result = _invoke(["uninstall", str(repo), "--dry-run"])
+
+ assert result.exit_code == 0
+ assert (repo / ".mcp.json").exists()
+
+
+def test_json_output_is_parseable_when_no_scope_was_given(repo: Path) -> None:
+ """A rich table on the payload's own stream is output no parser can read."""
+ result = _invoke(["uninstall", str(repo), "--format", "json"])
+
+ assert result.exit_code != 0
+ payload = json.loads(result.output)
+ assert payload["groups"] == []
+ assert "--all" in payload["error"]
+
+
+# ---------------------------------------------------------------------------
+# what it removes
+# ---------------------------------------------------------------------------
+
+
+def test_all_removes_the_wiring_the_index_and_the_generated_blocks(repo: Path) -> None:
+ _wire_everything(repo)
+ claude, agents = _write_generated_blocks(repo)
+ assert (repo / ".mcp.json").exists()
+
+ result = _invoke(["uninstall", str(repo), "--all"])
+
+ assert not (repo / ".repowise").exists()
+ assert not (repo / ".mcp.json").exists()
+ assert not (repo / ".vscode").exists()
+ assert not (repo / ".codex").exists()
+ assert "REPOWISE:START" not in claude.read_text(encoding="utf-8")
+ assert "REPOWISE_AGENTS:START" not in agents.read_text(encoding="utf-8")
+ assert result.exit_code == 0
+
+
+def test_the_users_own_prose_survives_the_block_removal(repo: Path) -> None:
+ """The whole reason these are marker-fenced rather than whole files."""
+ claude, agents = _write_generated_blocks(repo)
+
+ _invoke(["uninstall", str(repo), "--all"])
+
+ assert "my own notes" in claude.read_text(encoding="utf-8")
+ assert "my own notes" in agents.read_text(encoding="utf-8")
+
+
+def test_keep_index_leaves_the_index_and_takes_everything_else(repo: Path) -> None:
+ _wire_everything(repo)
+ _write_generated_blocks(repo)
+
+ result = _invoke(["uninstall", str(repo), "--keep-index"])
+
+ assert (repo / ".repowise" / "wiki.db").exists()
+ assert not (repo / ".mcp.json").exists()
+ assert result.exit_code == 0
+
+
+def test_machine_wide_state_is_never_pre_selected() -> None:
+ """It goes only when the user names it, because we cannot see the other repos."""
+ from repowise.cli.uninstall.inventory import DEFAULT_GROUPS, Group
+
+ assert Group.GLOBAL not in DEFAULT_GROUPS
+ assert Group.INDEX not in DEFAULT_GROUPS
+
+
+def test_global_state_goes_only_when_asked_and_says_what_that_cost(repo: Path) -> None:
+ global_dir = Path.home() / ".repowise"
+ global_dir.mkdir(parents=True, exist_ok=True)
+ (global_dir / "platform.json").write_text('{"telemetry_enabled": false}', encoding="utf-8")
+
+ kept = _invoke(["uninstall", str(repo), "--keep-index"])
+ assert global_dir.exists(), kept.output
+
+ result = _invoke(["uninstall", str(repo), "--all"])
+ assert not global_dir.exists()
+ assert "telemetry" in result.output
+
+
+# ---------------------------------------------------------------------------
+# honesty
+# ---------------------------------------------------------------------------
+
+
+def test_a_second_run_reports_not_found_and_never_reports_removed(
+ repo: Path, monkeypatch
+) -> None:
+ """Two real shell commands, not two invocations sharing one process.
+
+ The env var the command sets to stop telemetry recreating ``~/.repowise``
+ persists in-process, so without clearing it between runs this test suppressed
+ the very recreation it was meant to catch, and passed over three separate
+ live bugs.
+ """
+ _wire_everything(repo)
+ _write_generated_blocks(repo)
+ _invoke(["uninstall", str(repo), "--all"])
+ monkeypatch.delenv("REPOWISE_TELEMETRY_DISABLED", raising=False)
+
+ payload = _payload(["uninstall", str(repo), "--all"])
+
+ actions = {result["action"] for result in payload["results"]}
+ assert "removed" not in actions, f"not idempotent: {payload['results']}"
+ assert actions <= {"not-found", "kept"}
+
+
+def test_machine_wide_state_stays_gone_across_processes(repo: Path, monkeypatch) -> None:
+ """Three separate code paths recreated it at startup or shutdown."""
+ global_dir = Path.home() / ".repowise"
+ global_dir.mkdir(parents=True, exist_ok=True)
+ (global_dir / "platform.json").write_text("{}", encoding="utf-8")
+
+ _invoke(["uninstall", str(repo), "--all"])
+ monkeypatch.delenv("REPOWISE_TELEMETRY_DISABLED", raising=False)
+ assert not global_dir.exists()
+
+ _invoke(["uninstall", str(repo), "--all"])
+ assert not global_dir.exists(), "our own process put it back"
+
+
+def test_the_inventory_is_printed_even_when_nothing_is_there(repo: Path) -> None:
+ """A trust command that prints nothing on a clean machine has proven nothing."""
+ result = _invoke(["uninstall", str(repo), "--all", "--dry-run"])
+
+ assert str(repo / ".repowise") in result.output
+ assert "pip uninstall repowise" in result.output or "uninstall repowise" in result.output
+
+
+def test_a_malformed_marker_pair_is_refused_and_the_row_says_why(repo: Path) -> None:
+ """An orphaned marker means the block's end is unknowable. Refuse, do not guess."""
+ from repowise.core.generation.editor_files.base import BaseEditorFileGenerator
+
+ start = BaseEditorFileGenerator.MARKER_START_FMT.format(tag="REPOWISE_AGENTS")
+ agents = repo / "AGENTS.md"
+ agents.write_text(f"# AGENTS.md\n\n{start}\ngenerated body\n\nmy own notes\n", encoding="utf-8")
+
+ payload = _payload(["uninstall", str(repo), "--all"])
+
+ # By group as well as path: `AGENTS.md` now legitimately appears twice, once
+ # for the generated block and once per agent that manages the distill block.
+ rows = [
+ r for r in payload["results"] if r["path"] == str(agents) and r["group"] == "repo-files"
+ ]
+ assert rows and rows[0]["action"] == "kept", payload["results"]
+ assert rows[0]["reason"]
+ assert "my own notes" in agents.read_text(encoding="utf-8")
+
+
+def test_a_refusal_exits_distinctly_from_a_misinvocation(repo: Path) -> None:
+ """Ran fine and something is still here is not the same answer as all gone.
+
+ And not the same answer as "you typed it wrong" either, which is why this is
+ 3 and not 2: Click already spends 2 on ``UsageError``, so sharing it left a
+ script unable to tell a leftover from a bad command line.
+ """
+ from repowise.cli.uninstall.runner import EXIT_LEFTOVERS
+ from repowise.core.generation.editor_files.base import BaseEditorFileGenerator
+
+ start = BaseEditorFileGenerator.MARKER_START_FMT.format(tag="REPOWISE_AGENTS")
+ (repo / "AGENTS.md").write_text(f"{start}\nbody\n", encoding="utf-8")
+
+ result = _invoke(["uninstall", str(repo), "--all"])
+ assert result.exit_code == EXIT_LEFTOVERS
+
+ misinvoked = _invoke(["uninstall", str(repo), "--all", "--keep-index"])
+ assert misinvoked.exit_code != EXIT_LEFTOVERS
+
+ payload = _payload(["uninstall", str(repo), "--all"])
+ assert payload["complete"] is False
+ assert payload["leftovers"]
+
+
+def test_every_kept_row_carries_a_reason(repo: Path) -> None:
+ """A bare 'kept' is indistinguishable from a bug.
+
+ Arranged so that several different targets refuse, not just one. The earlier
+ version produced exactly one ``kept`` row, from the generated-block path, so
+ reverting the reason wiring in any of the five agent targets left it green.
+ """
+ from repowise.core.generation.editor_files.base import BaseEditorFileGenerator
+
+ _wire_everything(repo)
+
+ # An orphaned DISTILL marker, so the three AGENTS.md managers each refuse
+ # rather than reporting not-found. Overwriting the file wholesale, as an
+ # earlier version did, deleted that block and left opencode and hermes
+ # emitting zero kept rows, so reverting their reason wiring stayed green
+ # while the docstring claimed otherwise.
+ generated = BaseEditorFileGenerator.MARKER_START_FMT.format(tag="REPOWISE_AGENTS")
+ distill_start = "<!-- REPOWISE_DISTILL:START — Do not edit below this line. Auto-generated by Repowise. -->"
+ (repo / "AGENTS.md").write_text(
+ f"# AGENTS.md\n\n{generated}\nbody\n\n{distill_start}\nbody\n", encoding="utf-8"
+ )
+ # JSONC, which these hosts accept and our strict parse refuses.
+ (repo / ".vscode" / "mcp.json").write_text(
+ '{\n // a comment\n "servers": {"repowise": {}}\n}\n', encoding="utf-8"
+ )
+ (repo / ".cursor" / "mcp.json").write_text(
+ '{\n // a comment\n "mcpServers": {"repowise": {}}\n}\n', encoding="utf-8"
+ )
+ (repo / ".codex" / "config.toml").write_text("bad = = toml [[[\n", encoding="utf-8")
+
+ payload = _payload(["uninstall", str(repo), "--all"])
+
+ kept = [r for r in payload["results"] if r["action"] == "kept"]
+ labels = {r["label"] for r in kept}
+ assert len({r["group"] for r in kept}) > 1, kept
+ # Every target that can refuse here does, so a reverted reason in any one of
+ # them turns this red rather than only the three that happened to be wired.
+ for expected in ("OpenCode", "Hermes", "Codex", "Cursor", "VS Code"):
+ assert any(expected in label for label in labels), (expected, sorted(labels))
+ assert all(r["reason"] for r in kept), [r for r in kept if not r["reason"]]
+
+
+def test_a_config_we_cannot_parse_is_named_rather_than_missed(repo: Path) -> None:
+ """Detection cannot read JSONC, and a file we cannot detect is still ours.
+
+ Without the path-existence fallback in the inventory, this file never
+ entered the plan at all: the command removed nothing, said nothing about it,
+ and printed that everything selected was gone.
+ """
+ _wire_everything(repo)
+ config = repo / ".vscode" / "mcp.json"
+ config.write_text(
+ '{\n // repowise, via a comment VS Code accepts\n "servers": {"repowise": {}}\n}\n',
+ encoding="utf-8",
+ )
+
+ result = _invoke(["uninstall", str(repo), "--all"])
+ payload = _payload(["uninstall", str(repo), "--all"])
+
+ assert str(config) in {r["path"] for r in payload["results"]}
+ assert result.exit_code != 0
+ assert "Everything selected is gone" not in result.output
+
+
+def test_a_malformed_settings_file_does_not_abort_the_run(repo: Path) -> None:
+ """Sweeping every event means meeting shapes we never wrote.
+
+ Nothing pinned this: reverting the isinstance guards in ``_strip_hooks``
+ wholesale left 249 tests green, while a ``"command": 7`` anywhere in the
+ user's settings raised ``TypeError`` out of the middle of an uninstall,
+ after an earlier removal had already rewritten the file.
+ """
+ _wire_everything(repo)
+ settings = Path.home() / ".claude" / "settings.json"
+ doc = json.loads(settings.read_text(encoding="utf-8"))
+ doc.setdefault("hooks", {})["Stop"] = [
+ "a bare string",
+ {"hooks": "not a list"},
+ {"hooks": [{"type": "command", "command": 7}, None]},
+ ]
+ settings.write_text(json.dumps(doc), encoding="utf-8")
+
+ result = _invoke(["uninstall", str(repo), "--all"])
+
+ assert result.exit_code in (0, 3), result.output
+ survived = json.loads(settings.read_text(encoding="utf-8"))
+ assert "a bare string" in survived["hooks"]["Stop"]
+
+
+def test_a_live_update_lock_blocks_the_index_and_names_the_reason(repo: Path) -> None:
+ from repowise.core.update_lock import try_acquire_update_lock
+
+ # ``None`` means acquired; a payload means someone else holds it.
+ assert try_acquire_update_lock(repo, None) is None
+
+ payload = _payload(["uninstall", str(repo), "--all"])
+
+ rows = [r for r in payload["results"] if r["group"] == "index"]
+ assert rows and rows[0]["action"] == "kept"
+ assert "update" in (rows[0]["reason"] or "")
+ assert (repo / ".repowise").exists()
+
+
+def test_the_package_and_the_plugin_are_named_rather_than_touched(repo: Path) -> None:
+ payload = _payload(["uninstall", str(repo), "--all", "--dry-run"])
+
+ advisories = " ".join(payload["plan"]["advisories"])
+ assert "uninstall repowise" in advisories
+ assert "print-config" in advisories
+
+
+# ---------------------------------------------------------------------------
+# the shared file
+# ---------------------------------------------------------------------------
+
+
+def test_a_batch_removal_clears_the_shared_agents_block(repo: Path) -> None:
+ """Three targets manage the distill block; removing them together frees it."""
+ CliRunner().invoke(
+ cli,
+ ["agents", "add", str(repo), "--target", "codex,opencode,hermes", "-y"],
+ catch_exceptions=False,
+ )
+ agents = repo / "AGENTS.md"
+ assert "REPOWISE_DISTILL:START" in agents.read_text(encoding="utf-8")
+
+ _invoke(["uninstall", str(repo), "--all"])
+
+ assert not agents.exists() or "REPOWISE_DISTILL:START" not in agents.read_text(encoding="utf-8")
+
+
+def test_the_two_agents_md_blocks_are_removed_independently(repo: Path) -> None:
+ """``AGENTS.md`` holds two different repowise blocks and they are not one concept.
+
+ OpenCode rather than Codex, because Codex's project install does not write
+ ``AGENTS.md`` while its uninstall removes it. That asymmetry is pre-existing
+ and recorded in the progress log; this test needs an agent that actually
+ writes the distill block.
+ """
+ CliRunner().invoke(
+ cli, ["agents", "add", str(repo), "--target", "opencode", "-y"], catch_exceptions=False
+ )
+ agents = repo / "AGENTS.md"
+ body = agents.read_text(encoding="utf-8")
+ assert "REPOWISE_DISTILL:START" in body
+
+ from repowise.core.generation.editor_files.base import BaseEditorFileGenerator
+
+ start = BaseEditorFileGenerator.MARKER_START_FMT.format(tag="REPOWISE_AGENTS")
+ end = BaseEditorFileGenerator.MARKER_END_FMT.format(tag="REPOWISE_AGENTS")
+ agents.write_text(f"{body}\n{start}\nindexer body\n{end}\n", encoding="utf-8")
+
+ # `--keep-index` is agents + repo-files, so both blocks are in scope and
+ # both must go. The point is that they are found by different removers.
+ _invoke(["uninstall", str(repo), "--keep-index"])
+ remaining = agents.read_text(encoding="utf-8") if agents.exists() else ""
+ assert "REPOWISE_AGENTS:START" not in remaining
+ assert "REPOWISE_DISTILL:START" not in remaining