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(init): ask before pointing the global MCP entry at this repo (#4246)

Raghav Chamadiya0bc2161876cd
diff --git a/packages/cli/src/repowise/cli/commands/init_cmd/_finish.py b/packages/cli/src/repowise/cli/commands/init_cmd/_finish.py
index f09a6441f..f904ba1bd 100644
--- a/packages/cli/src/repowise/cli/commands/init_cmd/_finish.py
+++ b/packages/cli/src/repowise/cli/commands/init_cmd/_finish.py
@@ -126,7 +126,15 @@ def save_run_config(run: InitRun) -> None:
def register_clients(run: InitRun) -> None:
"""Global client registration, then the workspace's distill verdict."""
- register_editor_clients(console, run.repo_path, no_editor_setup=not run.opts.editor_setup)
+ from repowise.cli.editor_integrations.global_mcp import confirm_global_mcp
+
+ if confirm_global_mcp(
+ console,
+ run.repo_path,
+ yes=run.opts.yes,
+ no_editor_setup=not run.opts.editor_setup,
+ ):
+ register_editor_clients(console, run.repo_path)
# Before the config fingerprint: left unwritten, the first update writes it,
# sees a fingerprint change and re-scores every file.
diff --git a/packages/cli/src/repowise/cli/commands/init_cmd/workspace.py b/packages/cli/src/repowise/cli/commands/init_cmd/workspace.py
index 4eef06a03..9799ebc35 100644
--- a/packages/cli/src/repowise/cli/commands/init_cmd/workspace.py
+++ b/packages/cli/src/repowise/cli/commands/init_cmd/workspace.py
@@ -889,7 +889,9 @@ def _workspace_init(
# A dry run writes nothing for any repo, so nothing at the workspace level.
if not dry_run:
- _save_workspace(ws_config, root, selected, totals.errors, editor_setup=editor_setup)
+ _save_workspace(
+ ws_config, root, selected, totals.errors, editor_setup=editor_setup, yes=yes
+ )
show_workspace_completion(
selected=selected,
@@ -933,7 +935,13 @@ def _select_workspace_repos(scan: Any, *, select_all: bool) -> tuple[list[Any],
def _save_workspace(
- ws_config: Any, root: Path, selected: list[Any], errors: list, *, editor_setup: bool
+ ws_config: Any,
+ root: Path,
+ selected: list[Any],
+ errors: list,
+ *,
+ editor_setup: bool,
+ yes: bool,
) -> None:
"""Save the indexed timestamps, run cross-repo analysis, register the primary."""
ws_config.save(root)
@@ -941,7 +949,10 @@ def _save_workspace(
primary_entry = ws_config.get_primary()
if primary_entry:
primary_path = (root / primary_entry.path).resolve()
- register_editor_clients(console, primary_path, no_editor_setup=not editor_setup)
+ from repowise.cli.editor_integrations.global_mcp import confirm_global_mcp
+
+ if confirm_global_mcp(console, primary_path, yes=yes, no_editor_setup=not editor_setup):
+ register_editor_clients(console, primary_path)
def _ask_workspace_mode(
diff --git a/packages/cli/src/repowise/cli/editor_integrations/claude.py b/packages/cli/src/repowise/cli/editor_integrations/claude.py
index 617e3b178..8867eb9b8 100644
--- a/packages/cli/src/repowise/cli/editor_integrations/claude.py
+++ b/packages/cli/src/repowise/cli/editor_integrations/claude.py
@@ -43,20 +43,15 @@ class ClaudeCodeSetup:
def register_client(self, console_obj: Any, repo_path: Path) -> None:
from repowise.cli.editor_integrations.claude_config import (
- describe_mcp_registration_change,
enable_tool_search_in_claude_code,
install_claude_code_hooks,
register_with_claude_code,
register_with_claude_desktop,
)
- from repowise.cli.ui.brand import OK, WARN
-
- # Read-only probe first: the merge below silently repoints the single
- # global "repowise" entry, so say so before it happens.
- clobber = describe_mcp_registration_change(repo_path)
- if clobber:
- console_obj.print(f" [{WARN}]![/] {clobber}")
+ from repowise.cli.ui.brand import OK
+ # Callers ask first (global_mcp.confirm_global_mcp): these writes
+ # repoint the single global "repowise" entry.
desktop = register_with_claude_desktop(repo_path)
if desktop:
console_obj.print(f" [{OK}]✓[/] Claude Desktop MCP registered ({desktop})")
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 c9cd6d2c5..becece17a 100644
--- a/packages/cli/src/repowise/cli/editor_integrations/claude_config.py
+++ b/packages/cli/src/repowise/cli/editor_integrations/claude_config.py
@@ -128,52 +128,6 @@ def _entry_repo_target(entry: dict) -> str | None:
return str(args[1])
-def describe_mcp_registration_change(repo_path: Path) -> str | None:
- """Warn when registering would repoint an existing ``repowise`` MCP entry.
-
- Both Claude configs hold a single ``repowise`` key, so an ``init`` from a
- second repo *replaces* the entry rather than adding one alongside it. That
- write is silent, and only surfaces later when the binary or repo it points
- at is gone and the MCP server stops loading. This is a read-only probe run
- before registration; it returns a one-line notice when the stored command
- or repo target differs from what is about to be written, else None.
- """
- new_entry = generate_mcp_config(
- _resolve_mcp_target(repo_path), command=resolve_repowise_command()
- )["mcpServers"]["repowise"]
- new_command = new_entry.get("command")
- new_target = _entry_repo_target(new_entry)
-
- for config_path in (_claude_code_settings_path(), _claude_desktop_config_path()):
- stored = _stored_repowise_entry(config_path)
- if stored is None:
- continue
- # Both fields are reported when both move, which is the usual shape of
- # the mistake: a second repo indexed by a second install. Naming only
- # one would hide half of what is about to change.
- changes = [
- (label, was, now)
- for label, was, now in (
- ("repo", _entry_repo_target(stored), new_target),
- ("command", stored.get("command"), new_command),
- )
- if was != now
- ]
- if not changes:
- continue
- fields = " and ".join(label for label, _was, _now in changes)
- lines = [f"Replacing the existing repowise MCP {fields} in {config_path}:"]
- for label, was, now in changes:
- # A hand-edited entry can be missing either field outright.
- lines.append(f" {label} was: {was if was is not None else '(not set)'}")
- lines.append(f" {label} now: {now}")
- lines.append(
- " There is one 'repowise' entry per config; pass --no-editor-setup to leave it alone."
- )
- return "\n".join(lines)
- return None
-
-
def enable_tool_search_in_claude_code() -> Path | None:
"""Set ``env.ENABLE_TOOL_SEARCH=true`` in ~/.claude/settings.json.
diff --git a/packages/cli/src/repowise/cli/editor_integrations/global_mcp.py b/packages/cli/src/repowise/cli/editor_integrations/global_mcp.py
new file mode 100644
index 000000000..d78253da2
--- /dev/null
+++ b/packages/cli/src/repowise/cli/editor_integrations/global_mcp.py
@@ -0,0 +1,180 @@
+"""Consent for repointing the one global ``repowise`` MCP entry.
+
+Claude Code (``~/.claude/settings.json``) and Claude Desktop each hold a
+single ``repowise`` server key, so registering from a new repo moves every
+agent session on the machine to it. :func:`read_global_mcp_target` is the
+read-only probe a start screen can show; :func:`confirm_global_mcp` is the one
+place init asks.
+"""
+
+from __future__ import annotations
+
+import json
+import logging
+import os
+import sys
+from dataclasses import dataclass
+from pathlib import Path
+from typing import Any
+
+import click
+
+from repowise.cli.editor_integrations import claude_config
+
+logger = logging.getLogger(__name__)
+
+NOT_SET = "not set"
+#: Re-runs the user-level writes a declined init skipped.
+REGISTER_LATER_COMMAND = "repowise agents add --target=claude-code --scope=user"
+
+
+@dataclass(frozen=True)
+class GlobalMcpEntry:
+ """One client's stored ``repowise`` entry."""
+
+ client: str
+ config_path: Path
+ target: str | None
+ command: str | None
+
+
+@dataclass(frozen=True)
+class GlobalMcpTarget:
+ """Where the global entry points now, and where registration would move it."""
+
+ new_target: str
+ new_command: str
+ entries: tuple[GlobalMcpEntry, ...]
+
+ @property
+ def repoints(self) -> bool:
+ """Whether any client would move to a different repo (or gain an entry)."""
+ return any(not _same_path(e.target, self.new_target) for e in self.entries)
+
+ @property
+ def command_changes(self) -> bool:
+ return any(e.command != self.new_command for e in self.entries if e.target)
+
+ def summary_lines(self) -> list[str]:
+ """``global entry now points at X, will point here`` for each distinct X."""
+ currents = {e.target or NOT_SET for e in self.entries}
+ if len(currents) <= 1:
+ clients = " and ".join(e.client for e in self.entries) or "Claude Code"
+ now = next(iter(currents), NOT_SET)
+ return [
+ f"Global repowise MCP entry ({clients}) now points at {now}, "
+ f"will point here: {self.new_target}"
+ ]
+ lines = [f"Global repowise MCP entry will point here: {self.new_target}"]
+ lines += [f" {e.client} now points at {e.target or NOT_SET}" for e in self.entries]
+ return lines
+
+
+def _same_path(a: str | None, b: str) -> bool:
+ if a is None:
+ return False
+ return os.path.normcase(os.path.normpath(a)) == os.path.normcase(os.path.normpath(b))
+
+
+def read_global_mcp_target(repo_path: Path) -> GlobalMcpTarget:
+ """Read-only: what each global config holds and what init would write.
+
+ Lists the clients registration would write: Claude Code always, Claude
+ Desktop only when installed, the same rule the writers apply.
+ """
+ new_entry = claude_config.generate_mcp_config(
+ claude_config._resolve_mcp_target(repo_path),
+ command=claude_config.resolve_repowise_command(),
+ )["mcpServers"]["repowise"]
+
+ configs: list[tuple[str, Path]] = [
+ ("Claude Code", claude_config._claude_code_settings_path())
+ ]
+ desktop = claude_config._claude_desktop_config_path()
+ if desktop is not None and desktop.parent.exists():
+ configs.append(("Claude Desktop", desktop))
+
+ entries = []
+ for client, path in configs:
+ stored = claude_config._stored_repowise_entry(path) or {}
+ entries.append(
+ GlobalMcpEntry(
+ client=client,
+ config_path=path,
+ target=claude_config._entry_repo_target(stored),
+ command=stored.get("command"),
+ )
+ )
+ return GlobalMcpTarget(
+ new_target=claude_config._entry_repo_target(new_entry) or "",
+ new_command=str(new_entry.get("command")),
+ entries=tuple(entries),
+ )
+
+
+def _probe(repo_path: Path) -> GlobalMcpTarget | None:
+ """The probe, or None when it fails. A failure never blocks registration."""
+ try:
+ return read_global_mcp_target(repo_path)
+ except (OSError, json.JSONDecodeError, ValueError, KeyError, TypeError) as exc:
+ logger.debug("global MCP probe failed for %s: %s", repo_path, exc)
+ return None
+
+
+def _print_command_move(console_obj: Any, target: GlobalMcpTarget) -> None:
+ if target.command_changes:
+ console_obj.print(
+ f" [dim]Global repowise MCP entry stays on {target.new_target}; "
+ f"its command moves to {target.new_command}.[/dim]"
+ )
+
+
+def _ask_to_repoint(console_obj: Any) -> bool:
+ """Prompt, default yes. Ctrl-C or EOF declines, like init's other offers."""
+ try:
+ agreed = click.confirm(" Point it here?", default=True)
+ except (click.Abort, EOFError):
+ agreed = False
+ if not agreed:
+ console_obj.print(
+ " [dim]Global Claude config left as is. Project files still connect "
+ f"agents opened in this repo. Run '{REGISTER_LATER_COMMAND}' to point "
+ "it here later.[/dim]"
+ )
+ return agreed
+
+
+def _repoint_consent(console_obj: Any, target: GlobalMcpTarget, *, yes: bool) -> bool:
+ """Print old and new; ask only when someone can answer."""
+ for line in target.summary_lines():
+ console_obj.print(f" {line}")
+ if yes or not sys.stdin.isatty():
+ return True
+ return _ask_to_repoint(console_obj)
+
+
+def confirm_global_mcp(
+ console_obj: Any,
+ repo_path: Path,
+ *,
+ yes: bool = False,
+ no_editor_setup: bool = False,
+) -> bool:
+ """Whether init may write user-level client config for *repo_path*.
+
+ Asks (default yes) only when the entry would move and someone can answer.
+ ``--yes`` and a non-terminal stdin keep registering, the documented
+ scripted path, but still print the old and new target. A decline leaves
+ every user-level file alone; project files are written either way.
+ """
+ from repowise.cli.editor_setup import is_editor_setup_disabled
+
+ if is_editor_setup_disabled(no_editor_setup):
+ return False
+ target = _probe(repo_path)
+ if target is None:
+ return True
+ if not target.repoints:
+ _print_command_move(console_obj, target)
+ return True
+ return _repoint_consent(console_obj, target, yes=yes)
diff --git a/tests/unit/cli/test_editor_setup.py b/tests/unit/cli/test_editor_setup.py
index cdffa881f..f783588eb 100644
--- a/tests/unit/cli/test_editor_setup.py
+++ b/tests/unit/cli/test_editor_setup.py
@@ -808,154 +808,6 @@ def test_write_editor_project_files_honors_agents_config_optout_when_codex_enabl
assert written == [tmp_path / ".codex" / "config.toml", tmp_path / ".codex" / "hooks.toml"]
-def _write_settings(path: Path, entry: dict) -> None:
- path.parent.mkdir(parents=True, exist_ok=True)
- path.write_text(json.dumps({"mcpServers": {"repowise": entry}}), encoding="utf-8")
-
-
-def test_describe_mcp_registration_change_warns_on_repoint(
- tmp_path: Path,
- monkeypatch: Any,
-) -> None:
- """A second init from another repo replaces the single 'repowise' entry.
-
- That write is silent and only surfaces later, when the repo or binary it
- points at is gone. The probe names both sides before the merge happens.
- """
- settings = tmp_path / "home" / ".claude" / "settings.json"
- other_repo = str((tmp_path / "other-repo").resolve()).replace("\\", "/")
- _write_settings(
- settings,
- {"command": "repowise", "args": ["mcp", other_repo, "--transport", "stdio"]},
- )
-
- monkeypatch.setattr(claude_config, "_claude_code_settings_path", lambda: settings)
- monkeypatch.setattr(claude_config, "_claude_desktop_config_path", lambda: None)
- monkeypatch.setattr(claude_config, "resolve_repowise_command", lambda: "repowise")
-
- this_repo = tmp_path / "this-repo"
- this_repo.mkdir()
- notice = claude_config.describe_mcp_registration_change(this_repo)
-
- assert notice is not None
- assert other_repo in notice
- assert str(this_repo.resolve()).replace("\\", "/") in notice
- assert "--no-editor-setup" in notice
-
-
-def test_describe_mcp_registration_change_silent_when_unchanged(
- tmp_path: Path,
- monkeypatch: Any,
-) -> None:
- """Re-running init on the same repo is not a clobber and stays quiet."""
- settings = tmp_path / "home" / ".claude" / "settings.json"
- repo = tmp_path / "repo"
- repo.mkdir()
- repo_arg = str(repo.resolve()).replace("\\", "/")
- _write_settings(
- settings,
- {"command": "repowise", "args": ["mcp", repo_arg, "--transport", "stdio"]},
- )
-
- monkeypatch.setattr(claude_config, "_claude_code_settings_path", lambda: settings)
- monkeypatch.setattr(claude_config, "_claude_desktop_config_path", lambda: None)
- monkeypatch.setattr(claude_config, "resolve_repowise_command", lambda: "repowise")
-
- assert claude_config.describe_mcp_registration_change(repo) is None
-
-
-def test_describe_mcp_registration_change_silent_on_first_run(
- tmp_path: Path,
- monkeypatch: Any,
-) -> None:
- """No stored entry means nothing is being replaced."""
- monkeypatch.setattr(
- claude_config, "_claude_code_settings_path", lambda: tmp_path / "missing.json"
- )
- monkeypatch.setattr(claude_config, "_claude_desktop_config_path", lambda: None)
- monkeypatch.setattr(claude_config, "resolve_repowise_command", lambda: "repowise")
-
- repo = tmp_path / "repo"
- repo.mkdir()
- assert claude_config.describe_mcp_registration_change(repo) is None
-
-
-def test_describe_mcp_registration_change_warns_on_command_repoint(
- tmp_path: Path,
- monkeypatch: Any,
-) -> None:
- """Same repo, different binary — the release-smoke-test case."""
- settings = tmp_path / "home" / ".claude" / "settings.json"
- repo = tmp_path / "repo"
- repo.mkdir()
- repo_arg = str(repo.resolve()).replace("\\", "/")
- _write_settings(
- settings,
- {
- "command": "C:/Users/dev/.venv/Scripts/repowise.exe",
- "args": ["mcp", repo_arg, "--transport", "stdio"],
- },
- )
-
- monkeypatch.setattr(claude_config, "_claude_code_settings_path", lambda: settings)
- monkeypatch.setattr(claude_config, "_claude_desktop_config_path", lambda: None)
- monkeypatch.setattr(
- claude_config, "resolve_repowise_command", lambda: "C:/tmp/throwaway/repowise.exe"
- )
-
- notice = claude_config.describe_mcp_registration_change(repo)
- assert notice is not None
- assert "C:/Users/dev/.venv/Scripts/repowise.exe" in notice
- assert "C:/tmp/throwaway/repowise.exe" in notice
-
-
-def test_describe_mcp_registration_change_reports_both_fields(
- tmp_path: Path,
- monkeypatch: Any,
-) -> None:
- """A new repo indexed by a new install moves both fields; name both."""
- settings = tmp_path / "home" / ".claude" / "settings.json"
- other = str((tmp_path / "other").resolve()).replace("\\", "/")
- _write_settings(
- settings,
- {"command": "old-repowise", "args": ["mcp", other, "--transport", "stdio"]},
- )
-
- monkeypatch.setattr(claude_config, "_claude_code_settings_path", lambda: settings)
- monkeypatch.setattr(claude_config, "_claude_desktop_config_path", lambda: None)
- monkeypatch.setattr(claude_config, "resolve_repowise_command", lambda: "new-repowise")
-
- repo = tmp_path / "repo"
- repo.mkdir()
- notice = claude_config.describe_mcp_registration_change(repo)
-
- assert notice is not None
- assert "repo and command" in notice
- assert "old-repowise" in notice and "new-repowise" in notice
- assert other in notice
-
-
-def test_describe_mcp_registration_change_handles_truncated_entry(
- tmp_path: Path,
- monkeypatch: Any,
-) -> None:
- """A hand-edited entry with no args must not print 'was: None'."""
- settings = tmp_path / "home" / ".claude" / "settings.json"
- _write_settings(settings, {"command": "repowise", "args": ["mcp"]})
-
- monkeypatch.setattr(claude_config, "_claude_code_settings_path", lambda: settings)
- monkeypatch.setattr(claude_config, "_claude_desktop_config_path", lambda: None)
- monkeypatch.setattr(claude_config, "resolve_repowise_command", lambda: "repowise")
-
- repo = tmp_path / "repo"
- repo.mkdir()
- notice = claude_config.describe_mcp_registration_change(repo)
-
- assert notice is not None
- assert "None" not in notice
- assert "(not set)" in notice
-
-
def test_codex_project_setup_writes_project_config_hooks_and_agents(
tmp_path: Path,
monkeypatch: Any,
diff --git a/tests/unit/cli/test_global_mcp_consent.py b/tests/unit/cli/test_global_mcp_consent.py
new file mode 100644
index 000000000..4e151662c
--- /dev/null
+++ b/tests/unit/cli/test_global_mcp_consent.py
@@ -0,0 +1,248 @@
+"""init asks before repointing the global ``repowise`` MCP entry.
+
+Every test runs against a fake home: the real ``~/.claude/settings.json`` and
+Claude Desktop config are never read or written.
+"""
+
+from __future__ import annotations
+
+import io
+import json
+from pathlib import Path
+from types import SimpleNamespace
+from typing import Any
+
+import click
+import pytest
+from rich.console import Console
+
+from repowise.cli.editor_integrations import claude_config, global_mcp
+
+_REAL_HOME = Path.home()
+
+
+class _Tty(io.StringIO):
+ def isatty(self) -> bool:
+ return True
+
+
+def _console() -> tuple[Console, io.StringIO]:
+ buf = io.StringIO()
+ return Console(file=buf, width=300, color_system=None), buf
+
+
+def _arg(path: Path) -> str:
+ return str(path.resolve()).replace("\\", "/")
+
+
+def _entry(target: str, command: str = "repowise") -> dict:
+ return {"command": command, "args": ["mcp", target, "--transport", "stdio"]}
+
+
+def _write(path: Path, entry: dict) -> None:
+ path.parent.mkdir(parents=True, exist_ok=True)
+ path.write_text(json.dumps({"mcpServers": {"repowise": entry}}), encoding="utf-8")
+
+
+def home(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> Path:
+ """A fake home holding both Claude configs' locations."""
+ fake = tmp_path / "home"
+ fake.mkdir()
+ monkeypatch.setattr(Path, "home", classmethod(lambda cls: fake))
+ monkeypatch.setenv("HOME", str(fake))
+ monkeypatch.setenv("USERPROFILE", str(fake))
+ monkeypatch.setenv("APPDATA", str(fake / "AppData" / "Roaming"))
+ monkeypatch.setattr(claude_config, "resolve_repowise_command", lambda: "repowise")
+ # tests/conftest.py turns editor setup off; this module is about it being on.
+ monkeypatch.delenv("REPOWISE_SKIP_EDITOR_SETUP", raising=False)
+ assert Path.home() != _REAL_HOME
+ return fake
+
+
+def _settings(home: Path) -> Path:
+ return home / ".claude" / "settings.json"
+
+
+def _desktop(home: Path, monkeypatch: pytest.MonkeyPatch) -> Path:
+ path = home / "Claude" / "claude_desktop_config.json"
+ path.parent.mkdir(parents=True, exist_ok=True)
+ monkeypatch.setattr(claude_config, "_claude_desktop_config_path", lambda: path)
+ return path
+
+
+def repo(tmp_path: Path) -> Path:
+ path = tmp_path / "repo"
+ path.mkdir()
+ return path
+
+
+def _no_prompt(*_a: Any, **_k: Any) -> bool:
+ raise AssertionError("must not prompt")
+
+
+def test_read_reports_not_set_on_first_run(home: Path, repo: Path, monkeypatch) -> None:
+ monkeypatch.setattr(claude_config, "_claude_desktop_config_path", lambda: None)
+ target = global_mcp.read_global_mcp_target(repo)
+
+ assert target.repoints
+ assert target.new_target == _arg(repo)
+ [line] = target.summary_lines()
+ assert "now points at not set" in line
+ assert line.endswith(f"will point here: {_arg(repo)}")
+
+
+def test_read_lists_desktop_only_when_installed(home: Path, repo: Path, monkeypatch) -> None:
+ monkeypatch.setattr(
+ claude_config, "_claude_desktop_config_path", lambda: home / "nope" / "c.json"
+ )
+ clients = [e.client for e in global_mcp.read_global_mcp_target(repo).entries]
+ assert clients == ["Claude Code"]
+
+
+def test_read_names_each_client_when_they_differ(home: Path, repo: Path, monkeypatch) -> None:
+ desktop = _desktop(home, monkeypatch)
+ _write(_settings(home), _entry("C:/a"))
+ _write(desktop, _entry("C:/b"))
+
+ lines = global_mcp.read_global_mcp_target(repo).summary_lines()
+ assert lines[0].endswith(f"will point here: {_arg(repo)}")
+ assert "Claude Code now points at C:/a" in lines[1]
+ assert "Claude Desktop now points at C:/b" in lines[2]
+
+
+def test_read_truncated_entry_reads_not_set(home: Path, repo: Path, monkeypatch) -> None:
+ monkeypatch.setattr(claude_config, "_claude_desktop_config_path", lambda: None)
+ _write(_settings(home), {"command": "repowise", "args": ["mcp"]})
+ [line] = global_mcp.read_global_mcp_target(repo).summary_lines()
+ assert "None" not in line and "not set" in line
+
+
+def test_same_target_is_quiet_and_never_asks(home: Path, repo: Path, monkeypatch) -> None:
+ monkeypatch.setattr(claude_config, "_claude_desktop_config_path", lambda: None)
+ _write(_settings(home), _entry(_arg(repo)))
+ monkeypatch.setattr("sys.stdin", _Tty())
+ monkeypatch.setattr(click, "confirm", _no_prompt)
+ console, buf = _console()
+
+ assert global_mcp.confirm_global_mcp(console, repo) is True
+ assert buf.getvalue() == ""
+
+
+def test_command_only_change_is_one_quiet_line(home: Path, repo: Path, monkeypatch) -> None:
+ monkeypatch.setattr(claude_config, "_claude_desktop_config_path", lambda: None)
+ _write(_settings(home), _entry(_arg(repo), command="C:/old/repowise.exe"))
+ monkeypatch.setattr("sys.stdin", _Tty())
+ monkeypatch.setattr(click, "confirm", _no_prompt)
+ console, buf = _console()
+
+ assert global_mcp.confirm_global_mcp(console, repo) is True
+ out = buf.getvalue().strip()
+ assert len(out.splitlines()) == 1 and "command moves to repowise" in out
+
+
[email protected]("yes", [True, False])
+def test_yes_or_no_terminal_registers_and_prints_old_and_new(
+ home: Path, repo: Path, monkeypatch, yes: bool
+) -> None:
+ monkeypatch.setattr(claude_config, "_claude_desktop_config_path", lambda: None)
+ _write(_settings(home), _entry("C:/elsewhere"))
+ monkeypatch.setattr("sys.stdin", _Tty() if yes else io.StringIO())
+ monkeypatch.setattr(click, "confirm", _no_prompt)
+ console, buf = _console()
+
+ assert global_mcp.confirm_global_mcp(console, repo, yes=yes) is True
+ out = buf.getvalue()
+ assert "now points at C:/elsewhere" in out and _arg(repo) in out
+
+
[email protected]("answer", [True, False])
+def test_interactive_asks_with_default_yes(
+ home: Path, repo: Path, monkeypatch, answer: bool
+) -> None:
+ monkeypatch.setattr(claude_config, "_claude_desktop_config_path", lambda: None)
+ monkeypatch.setattr("sys.stdin", _Tty())
+ asked: list[bool] = []
+
+ def confirm(_text: str, default: bool) -> bool:
+ asked.append(default)
+ return answer
+
+ monkeypatch.setattr(click, "confirm", confirm)
+ console, buf = _console()
+
+ assert global_mcp.confirm_global_mcp(console, repo) is answer
+ assert asked == [True]
+ assert ("left as is" in buf.getvalue()) is (not answer)
+
+
+def test_unanswerable_prompt_declines(home: Path, repo: Path, monkeypatch) -> None:
+ monkeypatch.setattr(claude_config, "_claude_desktop_config_path", lambda: None)
+ monkeypatch.setattr("sys.stdin", _Tty())
+
+ def abort(*_a: Any, **_k: Any) -> bool:
+ raise click.Abort()
+
+ monkeypatch.setattr(click, "confirm", abort)
+ console, _ = _console()
+ assert global_mcp.confirm_global_mcp(console, repo) is False
+
+
+def test_no_editor_setup_asks_and_prints_nothing(home: Path, repo: Path, monkeypatch) -> None:
+ monkeypatch.setenv("REPOWISE_SKIP_EDITOR_SETUP", "1")
+ monkeypatch.setattr("sys.stdin", _Tty())
+ monkeypatch.setattr(click, "confirm", _no_prompt)
+ console, buf = _console()
+ assert global_mcp.confirm_global_mcp(console, repo, no_editor_setup=True) is False
+ assert buf.getvalue() == ""
+
+
+def _run(repo: Path, *, yes: bool) -> SimpleNamespace:
+ return SimpleNamespace(repo_path=repo, opts=SimpleNamespace(yes=yes, editor_setup=True))
+
+
+def test_decline_leaves_global_configs_byte_identical(
+ home: Path, repo: Path, monkeypatch
+) -> None:
+ from repowise.cli.commands.init_cmd import _finish
+
+ desktop = _desktop(home, monkeypatch)
+ _write(_settings(home), _entry("C:/elsewhere"))
+ _write(desktop, _entry("C:/elsewhere"))
+ before = (_settings(home).read_bytes(), desktop.read_bytes())
+ monkeypatch.setattr("sys.stdin", _Tty())
+ monkeypatch.setattr(click, "confirm", lambda *_a, **_k: False)
+ monkeypatch.setattr(_finish, "console", _console()[0])
+
+ _finish.register_clients(_run(repo, yes=False))
+
+ assert (_settings(home).read_bytes(), desktop.read_bytes()) == before
+
+
+def test_yes_repoints_both_global_configs(home: Path, repo: Path, monkeypatch) -> None:
+ from repowise.cli.commands.init_cmd import _finish
+
+ desktop = _desktop(home, monkeypatch)
+ _write(_settings(home), _entry("C:/elsewhere"))
+ monkeypatch.setattr(click, "confirm", _no_prompt)
+ console, buf = _console()
+ monkeypatch.setattr(_finish, "console", console)
+
+ _finish.register_clients(_run(repo, yes=True))
+
+ for path in (_settings(home), desktop):
+ stored = json.loads(path.read_text(encoding="utf-8"))["mcpServers"]["repowise"]
+ assert stored["args"][1] == _arg(repo)
+ assert "now points at" in buf.getvalue()
+
+
+def test_probe_failure_never_blocks_registration(home: Path, repo: Path, monkeypatch) -> None:
+ def broken(_repo: Path) -> None:
+ raise OSError("unreadable")
+
+ monkeypatch.setattr(global_mcp, "read_global_mcp_target", broken)
+ monkeypatch.setattr(click, "confirm", _no_prompt)
+ console, buf = _console()
+ assert global_mcp.confirm_global_mcp(console, repo) is True
+ assert buf.getvalue() == ""