Codebase intelligence for AI and humans: code health scores, auto-generated docs, git analytics, dead code detection, and architectural decisions via MCP.
Python aicode-complexitycode-healthcode-intelligencecode-qualitydead-codedeveloper-toolsdocumentationgit-analyticsmcpopen-sourcepythonrefactoringstatic-analysistechnical-debt
Refactor CLI editor setup into integrations (#199)
Selene295e49aa36c61f
diff --git a/packages/cli/src/repowise/cli/augment_hook.py b/packages/cli/src/repowise/cli/augment_hook.pyindex 62a33c0de..ed1509381 100644--- a/packages/cli/src/repowise/cli/augment_hook.py+++ b/packages/cli/src/repowise/cli/augment_hook.py@@ -43,7 +43,7 @@ def main() -> None:# no-op on every subsequent fire. Wrapped so a write failure never# propagates back to the agent.try:- from repowise.cli.mcp_config import migrate_claude_code_hooks+ from repowise.cli.editor_integrations.claude_config import migrate_claude_code_hooksmigrate_claude_code_hooks()except BaseException:diff --git a/packages/cli/src/repowise/cli/commands/init_cmd.py b/packages/cli/src/repowise/cli/commands/init_cmd.pyindex 1b89ae093..66e662c94 100644--- a/packages/cli/src/repowise/cli/commands/init_cmd.py+++ b/packages/cli/src/repowise/cli/commands/init_cmd.py@@ -2,7 +2,6 @@from __future__ import annotations-import jsonimport osimport sysimport time@@ -14,6 +13,12 @@ from rich.progress import BarColumn, Progress, SpinnerColumn, TextColumn, TimeElfrom rich.table import Tablefrom repowise.cli.cost_estimator import build_generation_plan, estimate_cost+from repowise.cli.editor_integrations.defaults import get_default_disabled_project_files+from repowise.cli.editor_setup import (+ register_editor_clients,+ resolve_editor_setup_options,+ write_editor_project_files,+)from repowise.cli.helpers import (console,ensure_repowise_dir,@@ -148,92 +153,6 @@ def _resolve_embedder(embedder_flag: str | None) -> str:return "mock"-def _register_mcp_with_claude(console_obj: Any, repo_path: Path) -> None:- """Register the repowise MCP server and hooks with Claude Desktop and Claude Code."""- from repowise.cli.mcp_config import (- install_claude_code_hooks,- register_with_claude_code,- register_with_claude_desktop,- )-- desktop = register_with_claude_desktop(repo_path)- if desktop:- console_obj.print(f" [green]✓[/green] Claude Desktop MCP registered ({desktop})")-- code = register_with_claude_code(repo_path)- if code:- console_obj.print(f" [green]✓[/green] Claude Code MCP registered ({code})")-- hooks = install_claude_code_hooks()- if hooks:- console_obj.print(- f" [green]✓[/green] Claude Code hooks registered (PreToolUse + PostToolUse)"- )---def _maybe_generate_claude_md(- console_obj: Any,- repo_path: Path,- *,- no_claude_md: bool = False,-) -> None:- """Generate CLAUDE.md if enabled in config and not opted out."""- cfg = load_config(repo_path)- enabled = cfg.get("editor_files", {}).get("claude_md", True)- if no_claude_md:- # Persist opt-out so 'repowise update' respects it- ef_cfg = dict(cfg.get("editor_files", {}))- ef_cfg["claude_md"] = False- cfg["editor_files"] = ef_cfg- try:- import yaml # type: ignore[import-untyped]-- cfg_path = repo_path / ".repowise" / "config.yaml"- cfg_path.write_text(- yaml.dump(cfg, default_flow_style=False, sort_keys=False),- encoding="utf-8",- )- except ImportError:- pass- return- if not enabled:- return- try:- with console_obj.status(" Generating .claude/CLAUDE.md…", spinner="dots"):- run_async(_write_claude_md_async(repo_path))- console_obj.print(" [green]✓[/green] .claude/CLAUDE.md updated")- except Exception as exc:- console_obj.print(f" [yellow].claude/CLAUDE.md skipped: {exc}[/yellow]")---async def _write_claude_md_async(repo_path: Path) -> None:- """Fetch data from DB and write CLAUDE.md (async helper)."""- from repowise.cli.helpers import get_db_url_for_repo- from repowise.core.generation.editor_files import ClaudeMdGenerator, EditorFileDataFetcher- from repowise.core.persistence import (- create_engine,- create_session_factory,- get_session,- init_db,- )- from repowise.core.persistence.crud import get_repository_by_path-- url = get_db_url_for_repo(repo_path)- engine = create_engine(url)- await init_db(engine)- sf = create_session_factory(engine)- try:- async with get_session(sf) as session:- repo = await get_repository_by_path(session, str(repo_path))- if repo is None:- return # Not indexed yet — skip silently- fetcher = EditorFileDataFetcher(session, repo.id, repo_path)- data = await fetcher.fetch()- finally:- await engine.dispose()- ClaudeMdGenerator().write(repo_path, data)--# ---------------------------------------------------------------------------# Persistence — saves PipelineResult to SQLite# ---------------------------------------------------------------------------@@ -347,7 +266,7 @@ def _run_workspace_generation("""from repowise.cli.cost_estimator import build_generation_plan, estimate_costfrom repowise.cli.helpers import get_db_url_for_repo- from repowise.cli.ui import BRAND, RichProgressCallback+ from repowise.cli.ui import RichProgressCallbackfrom repowise.core.generation import GenerationConfigfrom repowise.core.generation.cost_tracker import CostTrackerfrom repowise.core.persistence import (@@ -540,7 +459,6 @@ def _workspace_init(from rich.progress import BarColumn, Progress, SpinnerColumn, TextColumn, TimeElapsedColumn- from repowise.cli.mcp_config import save_mcp_config, save_root_mcp_configfrom repowise.cli.ui import (BRAND,RichProgressCallback,@@ -661,6 +579,12 @@ def _workspace_init(# never has to guess why the web UI is missing pages for some repos.# Maps alias -> (generated_count, skip_reason | None)docs_outcomes: dict[str, tuple[int, str | None]] = {}+ editor_options = resolve_editor_setup_options(+ console,+ disabled_project_files=get_default_disabled_project_files(+ no_claude_md=no_claude_md,+ ),+ )for i, repo in enumerate(selected, 1):console.print(@@ -780,10 +704,12 @@ def _workspace_init(entry.indexed_at = datetime.now(timezone.utc).isoformat()entry.last_commit_at_index = head- # MCP config + CLAUDE.md per repo- save_mcp_config(repo.path)- save_root_mcp_config(repo.path)- _maybe_generate_claude_md(console, repo.path, no_claude_md=no_claude_md)+ # MCP config + editor setup files per repo+ write_editor_project_files(+ console,+ repo.path,+ options=editor_options,+ )# Persist provider/model config per-repo when doing full generationif not index_only and provider is not None:@@ -815,11 +741,11 @@ def _workspace_init(except Exception as exc:console.print(f" [yellow]⚠ Cross-repo analysis failed: {exc}[/yellow]")- # Step 6: Register MCP for primary repo with Claude+ # Step 6: Register primary repo with configured editor clientsprimary_entry = ws_config.get_primary()if primary_entry:primary_path = (root / primary_entry.path).resolve()- _register_mcp_with_claude(console, primary_path)+ register_editor_clients(console, primary_path)# Step 7: Completion summaryelapsed = time.monotonic() - start@@ -1025,7 +951,6 @@ def init_command(build_contextual_next_steps,format_elapsed,interactive_advanced_config,- interactive_claude_md_prompt,interactive_mode_select,interactive_provider_select,load_dotenv,@@ -1134,12 +1059,13 @@ def init_command(else:provider_name, model = interactive_provider_select(console, model, repo_path=repo_path)- # Ask about CLAUDE.md once, after mode selection, so full and advanced- # modes both honour the user's choice (issue #81). Skip when --no-claude-md- # was already passed on the CLI (the user has already opted out) and when- # the user picked index-only mode (no LLM generation runs anyway).- if not no_claude_md and not index_only:- no_claude_md = interactive_claude_md_prompt(console)+ editor_options = resolve_editor_setup_options(+ console,+ disabled_project_files=get_default_disabled_project_files(+ no_claude_md=no_claude_md,+ ),+ prompt_for_project_files=is_interactive and not index_only,+ )# Merge exclude_patterns from config.yaml and --exclude/-x flagsconfig = load_config(repo_path)@@ -1523,7 +1449,7 @@ def init_command(run_async(_persist_result(result, repo_path))console.print(" [green]✓[/green] Database updated")- # ---- Post-run: config, state, MCP, CLAUDE.md ----+ # ---- Post-run: config, state, MCP, editor project files ----if commit_limit is not None:cfg = load_config(repo_path)cfg["commit_limit"] = resolved_commit_limit@@ -1538,13 +1464,12 @@ def init_command(except ImportError:pass- from repowise.cli.mcp_config import save_mcp_config, save_root_mcp_config-- save_mcp_config(repo_path)- save_root_mcp_config(repo_path)- _register_mcp_with_claude(console, repo_path)-- _maybe_generate_claude_md(console, repo_path, no_claude_md=no_claude_md)+ write_editor_project_files(+ console,+ repo_path,+ options=editor_options,+ )+ register_editor_clients(console, repo_path)# ---- State (always) ----# Even in index-only mode we persist `last_sync_commit` so that adiff --git a/packages/cli/src/repowise/cli/commands/update_cmd.py b/packages/cli/src/repowise/cli/commands/update_cmd.pyindex ee854fd3b..2c7a68c79 100644--- a/packages/cli/src/repowise/cli/commands/update_cmd.py+++ b/packages/cli/src/repowise/cli/commands/update_cmd.py@@ -733,42 +733,13 @@ def update_command(run_async(_persist())- # ---- CLAUDE.md (best-effort) ----- cfg = load_config(repo_path)- if cfg.get("editor_files", {}).get("claude_md", True):- try:- from repowise.cli.helpers import get_db_url_for_repo- from repowise.core.generation.editor_files import (- ClaudeMdGenerator,- EditorFileDataFetcher,- )- from repowise.core.persistence import (- create_engine,- create_session_factory,- get_session,- init_db,- )- from repowise.core.persistence.crud import get_repository_by_path+ # ---- Editor project files (best-effort) ----+ try:+ from repowise.cli.editor_setup import refresh_editor_project_files- async def _update_claude_md() -> None:- url = get_db_url_for_repo(repo_path)- engine = create_engine(url)- await init_db(engine)- sf = create_session_factory(engine)- try:- async with get_session(sf) as session:- repo_rec = await get_repository_by_path(session, str(repo_path))- if repo_rec is None:- return- fetcher = EditorFileDataFetcher(session, repo_rec.id, repo_path)- data = await fetcher.fetch()- finally:- await engine.dispose()- ClaudeMdGenerator().write(repo_path, data)-- run_async(_update_claude_md())- except Exception:- pass # CLAUDE.md update must never fail the update command+ refresh_editor_project_files(console, repo_path)+ except Exception:+ pass # Editor project-file refresh must never fail the update command# Update statestate["last_sync_commit"] = headdiff --git a/packages/cli/src/repowise/cli/editor_integrations/__init__.py b/packages/cli/src/repowise/cli/editor_integrations/__init__.pynew file mode 100644index 000000000..d41b85ee6--- /dev/null+++ b/packages/cli/src/repowise/cli/editor_integrations/__init__.py@@ -0,0 +1 @@+"""Concrete AI editor setup integrations."""diff --git a/packages/cli/src/repowise/cli/editor_integrations/claude.py b/packages/cli/src/repowise/cli/editor_integrations/claude.pynew file mode 100644index 000000000..ced15ffc0--- /dev/null+++ b/packages/cli/src/repowise/cli/editor_integrations/claude.py@@ -0,0 +1,161 @@+"""Claude Code/Desktop setup integration."""++from __future__ import annotations++from pathlib import Path+from typing import Any++import click++from repowise.cli.editor_setup import EditorSetupOptions+from repowise.cli.helpers import get_db_url_for_repo, load_config, run_async+++class ClaudeCodeSetup:+ """Claude Code/Desktop setup integration preserving existing init behavior."""++ project_file_id = "claude_md"++ def configure_options(+ self,+ console_obj: Any,+ options: EditorSetupOptions,+ ) -> EditorSetupOptions:+ if (+ not options.prompt_for_project_files+ or self.project_file_id in options.disabled_project_files+ ):+ return options+ if _prompt_claude_md_enabled(console_obj):+ return options+ return options.with_disabled_project_file(self.project_file_id)++ def write_project_files(+ self,+ console_obj: Any,+ repo_path: Path,+ options: EditorSetupOptions,+ ) -> None:+ from repowise.cli.mcp_config import save_root_mcp_config++ save_root_mcp_config(repo_path)+ maybe_generate_claude_md(+ console_obj,+ repo_path,+ no_claude_md=self.project_file_id in options.disabled_project_files,+ )++ def register_client(self, console_obj: Any, repo_path: Path) -> None:+ from repowise.cli.editor_integrations.claude_config import (+ install_claude_code_hooks,+ register_with_claude_code,+ register_with_claude_desktop,+ )++ desktop = register_with_claude_desktop(repo_path)+ if desktop:+ console_obj.print(f" [green]✓[/green] Claude Desktop MCP registered ({desktop})")++ code = register_with_claude_code(repo_path)+ if code:+ console_obj.print(f" [green]✓[/green] Claude Code MCP registered ({code})")++ hooks = install_claude_code_hooks()+ if hooks:+ console_obj.print(+ " [green]✓[/green] Claude Code hooks registered (PreToolUse + PostToolUse)"+ )++ def refresh_project_files(+ self,+ console_obj: Any,+ repo_path: Path,+ options: EditorSetupOptions,+ ) -> None:+ if self.project_file_id in options.disabled_project_files:+ return+ if not _claude_md_enabled(repo_path):+ return+ run_async(_write_claude_md_async(repo_path))+++def _prompt_claude_md_enabled(console_obj: Any) -> bool:+ """Ask whether the Claude project instruction file should be generated."""++ from repowise.cli.ui import BRAND++ console_obj.print()+ console_obj.print(f" [{BRAND}]Editor Integration[/]")+ console_obj.print()+ return click.confirm(+ " Generate .claude/CLAUDE.md?",+ default=True,+ )+++def _claude_md_enabled(repo_path: Path) -> bool:+ cfg = load_config(repo_path)+ return bool(cfg.get("editor_files", {}).get("claude_md", True))+++def maybe_generate_claude_md(+ console_obj: Any,+ repo_path: Path,+ *,+ no_claude_md: bool = False,+) -> None:+ """Generate CLAUDE.md if enabled in config and not opted out."""++ cfg = load_config(repo_path)+ if no_claude_md:+ # Persist opt-out so 'repowise update' respects it.+ ef_cfg = dict(cfg.get("editor_files", {}))+ ef_cfg["claude_md"] = False+ cfg["editor_files"] = ef_cfg+ try:+ import yaml # type: ignore[import-untyped]++ cfg_path = repo_path / ".repowise" / "config.yaml"+ cfg_path.write_text(+ yaml.dump(cfg, default_flow_style=False, sort_keys=False),+ encoding="utf-8",+ )+ except ImportError:+ pass+ return+ if not _claude_md_enabled(repo_path):+ return+ try:+ with console_obj.status(" Generating .claude/CLAUDE.md…", spinner="dots"):+ run_async(_write_claude_md_async(repo_path))+ console_obj.print(" [green]✓[/green] .claude/CLAUDE.md updated")+ except Exception as exc:+ console_obj.print(f" [yellow].claude/CLAUDE.md skipped: {exc}[/yellow]")+++async def _write_claude_md_async(repo_path: Path) -> None:+ """Fetch indexed repo data and write CLAUDE.md."""++ from repowise.core.generation.editor_files import ClaudeMdGenerator, EditorFileDataFetcher+ from repowise.core.persistence import (+ create_engine,+ create_session_factory,+ get_session,+ init_db,+ )+ from repowise.core.persistence.crud import get_repository_by_path++ url = get_db_url_for_repo(repo_path)+ engine = create_engine(url)+ await init_db(engine)+ sf = create_session_factory(engine)+ try:+ async with get_session(sf) as session:+ repo = await get_repository_by_path(session, str(repo_path))+ if repo is None:+ return+ fetcher = EditorFileDataFetcher(session, repo.id, repo_path)+ data = await fetcher.fetch()+ finally:+ await engine.dispose()+ ClaudeMdGenerator().write(repo_path, data)diff --git a/packages/cli/src/repowise/cli/editor_integrations/claude_config.py b/packages/cli/src/repowise/cli/editor_integrations/claude_config.pynew file mode 100644index 000000000..8c2e462b9--- /dev/null+++ b/packages/cli/src/repowise/cli/editor_integrations/claude_config.py@@ -0,0 +1,196 @@+"""Claude Desktop and Claude Code MCP config helpers."""++from __future__ import annotations++import json+import sys+from pathlib import Path++from repowise.cli.mcp_config import (+ generate_mcp_config,+ load_existing_config,+ merge_mcp_entry,+)+++def _claude_desktop_config_path() -> Path | None:+ """Return the Claude Desktop config path for this OS, or None if unsupported."""+ if sys.platform == "darwin":+ return (+ Path.home()+ / "Library"+ / "Application Support"+ / "Claude"+ / "claude_desktop_config.json"+ )+ if sys.platform == "win32":+ appdata = Path.home() / "AppData" / "Roaming"+ return appdata / "Claude" / "claude_desktop_config.json"+ # Linux / other: Claude Desktop not officially supported yet+ return None+++def _claude_code_settings_path() -> Path:+ """Return the global Claude Code settings path (~/.claude/settings.json)."""+ return Path.home() / ".claude" / "settings.json"+++def register_with_claude_desktop(repo_path: Path) -> Path | None:+ """Add repowise MCP server to Claude Desktop's config.++ Returns the config path if successful, None if Claude Desktop is not+ present or the platform is unsupported.+ """+ config_path = _claude_desktop_config_path()+ if config_path is None:+ return None+ if not config_path.parent.exists():+ # Claude Desktop not installed+ return None+ entry = generate_mcp_config(repo_path)["mcpServers"]+ return config_path if merge_mcp_entry(config_path, entry) else None+++def register_with_claude_code(repo_path: Path) -> Path | None:+ """Add repowise MCP server to global Claude Code settings (~/.claude/settings.json).++ Returns the settings path if successful, None on failure.+ """+ settings_path = _claude_code_settings_path()+ entry = generate_mcp_config(repo_path)["mcpServers"]+ return settings_path if merge_mcp_entry(settings_path, entry) else None+++def install_claude_code_hooks() -> Path | None:+ """Register PostToolUse hooks in ~/.claude/settings.json.++ PostToolUse detects git staleness and can enrich Grep/Glob results when+ the hook output has useful extra context. Existing user hooks are preserved.+ """+ settings_path = _claude_code_settings_path()++ post_hook_entry = {+ "matcher": "Bash|Grep|Glob",+ "hooks": [+ {+ "type": "command",+ "command": "repowise-augment",+ "timeout": 10,+ "statusMessage": "Checking codebase context...",+ }+ ],+ }++ try:+ if settings_path.exists():+ existing = load_existing_config(settings_path)+ else:+ settings_path.parent.mkdir(parents=True, exist_ok=True)+ existing = {}++ hooks = existing.setdefault("hooks", {})++ # Drop any pre-existing repowise PreToolUse entry; the current design+ # routes everything through PostToolUse.+ pre_hooks = hooks.setdefault("PreToolUse", [])+ _strip_repowise_pretool(pre_hooks)+ if not pre_hooks:+ hooks.pop("PreToolUse", None)++ # PostToolUse: migrate legacy command + matcher, then add if missing.+ post_hooks = hooks.setdefault("PostToolUse", [])+ _migrate_legacy_hook(post_hooks)+ if not _has_repowise_hook(post_hooks):+ post_hooks.append(post_hook_entry)++ settings_path.write_text(json.dumps(existing, indent=2) + "\n", encoding="utf-8")+ return settings_path+ except OSError:+ return None+++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+++def _is_repowise_hook(hook: dict) -> bool:+ cmd = hook.get("command", "")+ return "repowise-augment" in cmd or "repowise augment" in cmd+++def _strip_repowise_pretool(hook_list: list) -> bool:+ """Remove repowise's PreToolUse entry from a hook bucket in place."""+ changed = False+ for entry in list(hook_list):+ kept = [h for h in entry.get("hooks", []) if not _is_repowise_hook(h)]+ if len(kept) != len(entry.get("hooks", [])):+ changed = True+ if kept:+ entry["hooks"] = kept+ else:+ hook_list.remove(entry)+ return changed+++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", "")+ if cmd == "repowise augment":+ hook["command"] = "repowise-augment"+ changed = True+ matcher = entry.get("matcher", "")+ only_repowise = entry.get("hooks") and all(+ _is_repowise_hook(h) for h in entry["hooks"]+ )+ if only_repowise and matcher == "Bash":+ entry["matcher"] = "Bash|Grep|Glob"+ changed = True+ return changed+++def migrate_claude_code_hooks() -> bool:+ """Self-healing migration of legacy Claude Code hook entries."""+ 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++ pre = hooks.get("PreToolUse")+ if isinstance(pre, list) and _strip_repowise_pretool(pre):+ changed = True+ if not pre:+ hooks.pop("PreToolUse", None)++ post = hooks.get("PostToolUse")+ if isinstance(post, list) and _migrate_legacy_hook(post):+ changed = True++ if not changed:+ return False++ try:+ settings_path.write_text(+ json.dumps(existing, indent=2) + "\n", encoding="utf-8"+ )+ except OSError:+ return False+ return Truediff --git a/packages/cli/src/repowise/cli/editor_integrations/defaults.py b/packages/cli/src/repowise/cli/editor_integrations/defaults.pynew file mode 100644index 000000000..e162baded--- /dev/null+++ b/packages/cli/src/repowise/cli/editor_integrations/defaults.py@@ -0,0 +1,22 @@+"""Default editor setup integration registry."""++from __future__ import annotations++from repowise.cli.editor_setup import EditorSetupIntegration++from .claude import ClaudeCodeSetup+++def get_default_editor_integrations() -> tuple[EditorSetupIntegration, ...]:+ """Return the editor integrations enabled by default today."""++ return (ClaudeCodeSetup(),)+++def get_default_disabled_project_files(*, no_claude_md: bool = False) -> tuple[str, ...]:+ """Map legacy CLI editor-file flags to integration-owned project file ids."""++ disabled: list[str] = []+ if no_claude_md:+ disabled.append(ClaudeCodeSetup.project_file_id)+ return tuple(disabled)diff --git a/packages/cli/src/repowise/cli/editor_setup.py b/packages/cli/src/repowise/cli/editor_setup.pynew file mode 100644index 000000000..509823a71--- /dev/null+++ b/packages/cli/src/repowise/cli/editor_setup.py@@ -0,0 +1,138 @@+"""AI editor setup orchestration for repowise init.++The indexing command should not know the details of each editor's config files,+global settings, or managed instruction files. This module keeps that product+setup layer behind a small integration interface; concrete editor integrations+live in ``repowise.cli.editor_integrations``.+"""++from __future__ import annotations++from collections.abc import Iterable+from dataclasses import dataclass, field+from pathlib import Path+from typing import Any, Protocol+++@dataclass(frozen=True)+class EditorSetupOptions:+ """Options shared across editor setup integrations."""++ disabled_project_files: frozenset[str] = field(default_factory=frozenset)+ prompt_for_project_files: bool = False++ def with_disabled_project_file(self, project_file_id: str) -> EditorSetupOptions:+ """Return options with one managed project file disabled."""++ return EditorSetupOptions(+ disabled_project_files=self.disabled_project_files | {project_file_id},+ prompt_for_project_files=self.prompt_for_project_files,+ )+++class EditorSetupIntegration(Protocol):+ """Setup hooks implemented by each AI editor integration."""++ def configure_options(+ self,+ console_obj: Any,+ options: EditorSetupOptions,+ ) -> EditorSetupOptions:+ """Let the integration prompt or adjust setup options before writing files."""+ ...++ def write_project_files(+ self,+ console_obj: Any,+ repo_path: Path,+ options: EditorSetupOptions,+ ) -> None:+ """Write project-local config or instruction files for this editor."""+ ...++ def register_client(self, console_obj: Any, repo_path: Path) -> None:+ """Register global or user-level client configuration for this editor."""+ ...++ def refresh_project_files(+ self,+ console_obj: Any,+ repo_path: Path,+ options: EditorSetupOptions,+ ) -> None:+ """Refresh managed project files after repository content changes."""+ ...+++def _resolve_integrations(+ integrations: tuple[EditorSetupIntegration, ...] | None,+) -> tuple[EditorSetupIntegration, ...]:+ if integrations is not None:+ return integrations+ from repowise.cli.editor_integrations.defaults import get_default_editor_integrations++ return get_default_editor_integrations()+++def resolve_editor_setup_options(+ console_obj: Any,+ *,+ disabled_project_files: Iterable[str] | None = None,+ prompt_for_project_files: bool = False,+ integrations: tuple[EditorSetupIntegration, ...] | None = None,+) -> EditorSetupOptions:+ """Build setup options, allowing integrations to own their prompts."""++ options = EditorSetupOptions(+ disabled_project_files=frozenset(disabled_project_files or ()),+ prompt_for_project_files=prompt_for_project_files,+ )+ for integration in _resolve_integrations(integrations):+ options = integration.configure_options(console_obj, options)+ return options+++def write_editor_project_files(+ console_obj: Any,+ repo_path: Path,+ *,+ options: EditorSetupOptions | None = None,+ disabled_project_files: Iterable[str] | None = None,+ integrations: tuple[EditorSetupIntegration, ...] | None = None,+) -> None:+ """Write common MCP config and project-local editor files."""++ from repowise.cli.mcp_config import save_mcp_config++ save_mcp_config(repo_path)+ resolved_options = options or EditorSetupOptions(+ disabled_project_files=frozenset(disabled_project_files or ()),+ )+ for integration in _resolve_integrations(integrations):+ integration.write_project_files(console_obj, repo_path, resolved_options)+++def register_editor_clients(+ console_obj: Any,+ repo_path: Path,+ *,+ integrations: tuple[EditorSetupIntegration, ...] | None = None,+) -> None:+ """Register editor clients with repowise MCP and hooks where supported."""++ for integration in _resolve_integrations(integrations):+ integration.register_client(console_obj, repo_path)+++def refresh_editor_project_files(+ console_obj: Any,+ repo_path: Path,+ *,+ options: EditorSetupOptions | None = None,+ integrations: tuple[EditorSetupIntegration, ...] | None = None,+) -> None:+ """Refresh editor-managed project files without rewriting common MCP config."""++ resolved_options = options or EditorSetupOptions()+ for integration in _resolve_integrations(integrations):+ integration.refresh_project_files(console_obj, repo_path, resolved_options)diff --git a/packages/cli/src/repowise/cli/main.py b/packages/cli/src/repowise/cli/main.pyindex 3641c1266..036297aed 100644--- a/packages/cli/src/repowise/cli/main.py+++ b/packages/cli/src/repowise/cli/main.py@@ -9,8 +9,8 @@ from repowise.cli.commands.augment_cmd import augment_commandfrom repowise.cli.commands.claude_md_cmd import claude_md_commandfrom repowise.cli.commands.costs_cmd import costs_commandfrom repowise.cli.commands.dead_code_cmd import dead_code_command-from repowise.cli.commands.delete_cmd import delete_commandfrom repowise.cli.commands.decision_cmd import decision_group+from repowise.cli.commands.delete_cmd import delete_commandfrom repowise.cli.commands.doctor_cmd import doctor_commandfrom repowise.cli.commands.export_cmd import export_commandfrom repowise.cli.commands.hook_cmd import hook_group@@ -37,7 +37,7 @@ def cli(ctx: click.Context) -> None:# every Grep/Glob/Bash) — `augment_hook.main` handles that case.if ctx.invoked_subcommand != "augment":try:- from repowise.cli.mcp_config import migrate_claude_code_hooks+ from repowise.cli.editor_integrations.claude_config import migrate_claude_code_hooksmigrate_claude_code_hooks()except Exception:diff --git a/packages/cli/src/repowise/cli/mcp_config.py b/packages/cli/src/repowise/cli/mcp_config.pyindex fc9335753..3f7db1ada 100644--- a/packages/cli/src/repowise/cli/mcp_config.py+++ b/packages/cli/src/repowise/cli/mcp_config.py@@ -1,36 +1,13 @@-"""Auto-generated MCP config for Claude Code, Claude Desktop, Cursor, and Cline."""+"""Generic MCP config helpers for repowise."""from __future__ import annotationsimport json-import sysfrom pathlib import Pathimport click-def _claude_desktop_config_path() -> Path | None:- """Return the Claude Desktop config path for this OS, or None if unsupported."""- if sys.platform == "darwin":- return (- Path.home()- / "Library"- / "Application Support"- / "Claude"- / "claude_desktop_config.json"- )- if sys.platform == "win32":- appdata = Path.home() / "AppData" / "Roaming"- return appdata / "Claude" / "claude_desktop_config.json"- # Linux / other: Claude Desktop not officially supported yet- return None---def _claude_code_settings_path() -> Path:- """Return the global Claude Code settings path (~/.claude/settings.json)."""- return Path.home() / ".claude" / "settings.json"--def generate_mcp_config(repo_path: Path) -> dict:"""Generate MCP config JSON for a repository.@@ -59,7 +36,7 @@ def save_mcp_config(repo_path: Path) -> Path:def save_root_mcp_config(repo_path: Path) -> Path:- """Write .mcp.json at repo root for Claude Code auto-discovery.+ """Write .mcp.json at repo root for MCP clients that support discovery.Merges the repowise server entry into any existing mcpServers blockso other MCP servers configured by the user are preserved.@@ -68,7 +45,7 @@ def save_root_mcp_config(repo_path: Path) -> Path:new_entry = generate_mcp_config(repo_path)["mcpServers"]if config_path.exists():- existing = _load_existing_config(config_path)+ existing = load_existing_config(config_path)servers = dict(existing.get("mcpServers", {}))servers.update(new_entry)existing["mcpServers"] = servers@@ -80,14 +57,14 @@ def save_root_mcp_config(repo_path: Path) -> Path:return config_path-def _merge_mcp_entry(config_path: Path, new_entry: dict) -> bool:+def merge_mcp_entry(config_path: Path, new_entry: dict) -> bool:"""Merge *new_entry* into the mcpServers block of *config_path*.Creates the file if it doesn't exist. Returns True on success."""try:if config_path.exists():- existing = _load_existing_config(config_path)+ existing = load_existing_config(config_path)else:config_path.parent.mkdir(parents=True, exist_ok=True)existing = {}@@ -101,7 +78,7 @@ def _merge_mcp_entry(config_path: Path, new_entry: dict) -> bool:return False-def _load_existing_config(config_path: Path) -> dict:+def load_existing_config(config_path: Path) -> dict:"""Load an existing JSON config without silently replacing bad content."""try:existing = json.loads(config_path.read_text(encoding="utf-8"))@@ -123,235 +100,6 @@ def _load_existing_config(config_path: Path) -> dict:return existing-def register_with_claude_desktop(repo_path: Path) -> Path | None:- """Add repowise MCP server to Claude Desktop's config.-- Returns the config path if successful, None if Claude Desktop is not- present or the platform is unsupported.- """- config_path = _claude_desktop_config_path()- if config_path is None:- return None- if not config_path.parent.exists():- # Claude Desktop not installed- return None- entry = generate_mcp_config(repo_path)["mcpServers"]- return config_path if _merge_mcp_entry(config_path, entry) else None---def register_with_claude_code(repo_path: Path) -> Path | None:- """Add repowise MCP server to global Claude Code settings (~/.claude/settings.json).-- Returns the settings path if successful, None on failure.- """- settings_path = _claude_code_settings_path()- entry = generate_mcp_config(repo_path)["mcpServers"]- return settings_path if _merge_mcp_entry(settings_path, entry) else None---def install_claude_code_hooks() -> Path | None:- """Register PreToolUse and PostToolUse hooks in ~/.claude/settings.json.-- PreToolUse: enriches Grep/Glob searches with graph context (importers,- symbols) from the local wiki.db.-- PostToolUse: detects git commits and notifies the agent when the wiki- is stale.-- Merges into existing hooks without clobbering user-defined entries.- Returns the settings path on success, None on failure.- """- settings_path = _claude_code_settings_path()-- # Single PostToolUse hook covers Bash (stale-wiki nudge) and Grep/Glob- # (zero-result rescue + big-result triage). PreToolUse enrichment was- # removed: PostToolUse can see the actual result count and is strictly- # more informed about whether enrichment will help.- post_hook_entry = {- "matcher": "Bash|Grep|Glob",- "hooks": [- {- "type": "command",- "command": "repowise-augment",- "timeout": 10,- "statusMessage": "Checking codebase context...",- }- ],- }-- try:- if settings_path.exists():- existing = _load_existing_config(settings_path)- else:- settings_path.parent.mkdir(parents=True, exist_ok=True)- existing = {}-- hooks = existing.setdefault("hooks", {})-- # Drop any pre-existing repowise PreToolUse entry — the new design- # routes everything through PostToolUse.- pre_hooks = hooks.setdefault("PreToolUse", [])- _strip_repowise_pretool(pre_hooks)- if not pre_hooks:- hooks.pop("PreToolUse", None)-- # PostToolUse: migrate legacy command + matcher, then add if missing.- post_hooks = hooks.setdefault("PostToolUse", [])- _migrate_legacy_hook(post_hooks)- if not _has_repowise_hook(post_hooks):- post_hooks.append(post_hook_entry)-- settings_path.write_text(json.dumps(existing, indent=2) + "\n", encoding="utf-8")- return settings_path- except OSError:- return None---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---def _is_repowise_hook(hook: dict) -> bool:- cmd = hook.get("command", "")- return "repowise-augment" in cmd or "repowise augment" in cmd---def _strip_repowise_pretool(hook_list: list) -> bool:- """Remove repowise's PreToolUse entry from a hook bucket in place.-- Pre-0.6.2 versions registered a PreToolUse Grep|Glob hook that- enriched every search unconditionally. The new design moves all- Grep/Glob enrichment into PostToolUse so the hook can see the- actual result count and stay silent on focused searches. Existing- users have a stale PreToolUse entry that needs to be removed- rather than rewritten — the function it served is now folded into- the PostToolUse handler.-- Returns True if anything was removed (caller may want to know).- """- changed = False- for entry in list(hook_list):- # Drop only repowise hooks within this entry; if that empties- # the entry, drop the entry too. User-defined sibling hooks in- # the same matcher block are preserved.- kept = [h for h in entry.get("hooks", []) if not _is_repowise_hook(h)]- if len(kept) != len(entry.get("hooks", [])):- changed = True- if kept:- entry["hooks"] = kept- else:- hook_list.remove(entry)- return changed---def _migrate_legacy_hook(hook_list: list) -> bool:- """In-place migration of legacy PostToolUse entries to current shape.-- Two layers of legacy:-- * Pre-0.6.1 used the ``repowise augment`` Click subcommand, which- crashes if any module in the full CLI fails to import (a single- missing dep nukes every Bash/Grep tool call). Rewrite to the- import-isolated ``repowise-augment`` console script.-- * Pre-0.6.2 used matcher ``"Bash"`` for the PostToolUse entry.- The new design folds Grep/Glob enrichment into the same hook,- so the matcher widens to ``"Bash|Grep|Glob"``.-- Idempotent: a hook already in the current shape is left alone.- Returns True if anything was changed.- """- changed = False- for entry in hook_list:- # Migrate command names.- for hook in entry.get("hooks", []):- cmd = hook.get("command", "")- if cmd == "repowise augment":- hook["command"] = "repowise-augment"- changed = True- # Widen matcher on entries that only carry a repowise hook.- matcher = entry.get("matcher", "")- only_repowise = entry.get("hooks") and all(- _is_repowise_hook(h) for h in entry["hooks"]- )- if only_repowise and matcher == "Bash":- entry["matcher"] = "Bash|Grep|Glob"- changed = True- return changed---def migrate_claude_code_hooks() -> bool:- """Self-healing migration of legacy hook entries in settings.json.-- Idempotent and silent — does nothing if the file is missing, malformed,- or already migrated. Writes settings.json only when a legacy entry- was actually rewritten or stripped.-- Two migrations are applied:-- 1. PostToolUse: legacy ``repowise augment`` command names are- rewritten to ``repowise-augment`` (pre-0.6.1), and the- matcher is widened from ``"Bash"`` to ``"Bash|Grep|Glob"``- (pre-0.6.2) so a single hook serves all three tool types.- 2. PreToolUse: any repowise-owned entry is removed entirely.- The new design moves Grep/Glob enrichment into PostToolUse,- which can see the actual result count.-- Called from both ``cli.main`` (so any ``repowise <command>`` after- upgrade self-heals) and ``augment_hook`` (so users whose only repowise- invocation is via the hook are also migrated on first successful fire).- Wrapped failures: a malformed settings.json or a permissions error- must never break the CLI or the hook.-- Returns True if a migration was performed.- """- 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-- # Strip stale PreToolUse repowise entry.- pre = hooks.get("PreToolUse")- if isinstance(pre, list):- if _strip_repowise_pretool(pre):- changed = True- if not pre:- hooks.pop("PreToolUse", None)-- # Migrate PostToolUse.- post = hooks.get("PostToolUse")- if isinstance(post, list):- if _migrate_legacy_hook(post):- changed = True-- if not changed:- return False-- try:- settings_path.write_text(- json.dumps(existing, indent=2) + "\n", encoding="utf-8"- )- except OSError:- return False- return True--def format_setup_instructions(repo_path: Path) -> str:"""Return human-readable setup instructions for MCP clients."""config = generate_mcp_config(repo_path)@@ -362,7 +110,7 @@ def format_setup_instructions(repo_path: Path) -> str:MCP Server Configuration========================-Claude Code: automatically configured via .mcp.json (no manual steps needed).+Project .mcp.json: automatically written for MCP clients that support repo-local discovery.Cursor (.cursor/mcp.json):{server_block}diff --git a/packages/cli/src/repowise/cli/ui.py b/packages/cli/src/repowise/cli/ui.pyindex 57b7064aa..7c23288a0 100644--- a/packages/cli/src/repowise/cli/ui.py+++ b/packages/cli/src/repowise/cli/ui.py@@ -627,9 +627,9 @@ def interactive_advanced_config(``concurrency``, ``exclude``, ``test_run``, ``embedder``,``include_submodules``.- The CLAUDE.md prompt is intentionally not asked here so that full and- advanced modes stay aligned: the caller asks once via- :func:`interactive_claude_md_prompt` after mode selection.+ Editor integration prompts are intentionally not asked here so that full and+ advanced modes stay aligned. Editor setup owns those prompts after mode+ selection."""console.print()console.print(@@ -800,23 +800,6 @@ def interactive_advanced_config(return result-def interactive_claude_md_prompt(console: Console) -> bool:- """Ask the user whether to generate ``.claude/CLAUDE.md``.-- Returns ``True`` when the user opts out (i.e. the value to assign to- ``no_claude_md``). Asked once after mode selection so that full mode and- advanced mode behave the same way and a user who answers ``n`` always has- that answer honoured (issue #81).- """- console.print()- console.print(f" [{BRAND}]Editor Integration[/]")- console.print()- return not click.confirm(- " Generate .claude/CLAUDE.md?",- default=True,- )--def _resolve_embedder_from_env() -> str:"""Auto-detect embedder from env vars (for advanced config default)."""if os.environ.get("GEMINI_API_KEY") or os.environ.get("GOOGLE_API_KEY"):diff --git a/tests/unit/cli/test_claude_md_prompt.py b/tests/unit/cli/test_claude_md_prompt.pyindex 1c57ed905..e97687ebb 100644--- a/tests/unit/cli/test_claude_md_prompt.py+++ b/tests/unit/cli/test_claude_md_prompt.py@@ -2,11 +2,9 @@The CLAUDE.md opt-out prompt used to live inside ``interactive_advanced_config``and was therefore skipped entirely in full mode, and the answer was not always-threaded back to the writer in every code path. These tests pin the new-behaviour: the dedicated ``interactive_claude_md_prompt`` helper returns-``True`` (i.e. ``no_claude_md=True``) when the user answers ``n`` and ``False``-when they answer ``y`` or accept the default, and the writer's gating function-honours that answer by early-returning before any file is written.+threaded back to the writer in every code path. These tests pin the current+behaviour: the Claude editor integration owns that prompt and feeds the+resulting project-file option into the writer."""from __future__ import annotations@@ -18,31 +16,45 @@ from unittest.mock import patchfrom click.testing import CliRunnerfrom rich.console import Console-from repowise.cli.commands.init_cmd import _maybe_generate_claude_md-from repowise.cli.ui import interactive_claude_md_prompt+from repowise.cli.editor_integrations import claude as claude_integration+from repowise.cli.editor_setup import EditorSetupOptionsdef _silent_console() -> Console:return Console(file=StringIO(), force_terminal=False)-def test_prompt_returns_true_when_user_says_no() -> None:+def test_prompt_disables_claude_md_when_user_says_no() -> None:runner = CliRunner()with runner.isolation(input="n\n"):- assert interactive_claude_md_prompt(_silent_console()) is True+ options = claude_integration.ClaudeCodeSetup().configure_options(+ _silent_console(),+ EditorSetupOptions(prompt_for_project_files=True),+ )+ assert "claude_md" in options.disabled_project_files-def test_prompt_returns_false_when_user_says_yes() -> None:++def test_prompt_keeps_claude_md_when_user_says_yes() -> None:runner = CliRunner()with runner.isolation(input="y\n"):- assert interactive_claude_md_prompt(_silent_console()) is False+ options = claude_integration.ClaudeCodeSetup().configure_options(+ _silent_console(),+ EditorSetupOptions(prompt_for_project_files=True),+ )++ assert "claude_md" not in options.disabled_project_files-def test_prompt_returns_false_on_default_enter() -> None:+def test_prompt_keeps_claude_md_on_default_enter() -> None:runner = CliRunner()with runner.isolation(input="\n"):- # default is "Yes", so empty input should produce no_claude_md=False- assert interactive_claude_md_prompt(_silent_console()) is False+ options = claude_integration.ClaudeCodeSetup().configure_options(+ _silent_console(),+ EditorSetupOptions(prompt_for_project_files=True),+ )++ assert "claude_md" not in options.disabled_project_filesdef test_maybe_generate_skips_write_when_user_opted_out(tmp_path: Path) -> None:@@ -53,7 +65,9 @@ def test_maybe_generate_skips_write_when_user_opted_out(tmp_path: Path) -> None:(tmp_path / ".repowise").mkdir()claude_dir = tmp_path / ".claude"- _maybe_generate_claude_md(_silent_console(), tmp_path, no_claude_md=True)+ claude_integration.maybe_generate_claude_md(+ _silent_console(), tmp_path, no_claude_md=True+ )# No .claude directory and no CLAUDE.md should have been created.assert not claude_dir.exists()@@ -77,9 +91,11 @@ def test_maybe_generate_skips_write_when_config_disabled(tmp_path: Path) -> None# Patch the writer to detect any unexpected call.with patch(- "repowise.cli.commands.init_cmd._write_claude_md_async"+ "repowise.cli.editor_integrations.claude._write_claude_md_async") as fake_write:- _maybe_generate_claude_md(_silent_console(), tmp_path, no_claude_md=False)+ claude_integration.maybe_generate_claude_md(+ _silent_console(), tmp_path, no_claude_md=False+ )fake_write.assert_not_called()assert not (tmp_path / ".claude" / "CLAUDE.md").exists()diff --git a/tests/unit/cli/test_commands.py b/tests/unit/cli/test_commands.pyindex 0da4bab5b..3456dec72 100644--- a/tests/unit/cli/test_commands.py+++ b/tests/unit/cli/test_commands.py@@ -102,9 +102,12 @@ class TestErrorCases:"""init with no provider configured should error."""monkeypatch.delenv("ANTHROPIC_API_KEY", raising=False)monkeypatch.delenv("OPENAI_API_KEY", raising=False)+ monkeypatch.delenv("OPENROUTER_API_KEY", raising=False)+ monkeypatch.delenv("DEEPSEEK_API_KEY", raising=False)monkeypatch.delenv("GOOGLE_API_KEY", raising=False)monkeypatch.delenv("GEMINI_API_KEY", raising=False)monkeypatch.delenv("OLLAMA_BASE_URL", raising=False)+ monkeypatch.delenv("LITELLM_API_KEY", raising=False)monkeypatch.delenv("REPOWISE_PROVIDER", raising=False)result = runner.invoke(cli, ["init", str(tmp_path)])assert result.exit_code != 0diff --git a/tests/unit/cli/test_editor_setup.py b/tests/unit/cli/test_editor_setup.pynew file mode 100644index 000000000..6b7499bfe--- /dev/null+++ b/tests/unit/cli/test_editor_setup.py@@ -0,0 +1,330 @@+from __future__ import annotations++import inspect+from io import StringIO+from pathlib import Path+from typing import Any++from rich.console import Console++from repowise.cli import mcp_config+from repowise.cli.commands import init_cmd, update_cmd+from repowise.cli.editor_integrations import claude as claude_integration+from repowise.cli.editor_integrations import claude_config+from repowise.cli.editor_integrations.claude import ClaudeCodeSetup+from repowise.cli.editor_integrations.defaults import get_default_disabled_project_files+from repowise.cli.editor_setup import (+ EditorSetupOptions,+ refresh_editor_project_files,+ resolve_editor_setup_options,+ write_editor_project_files,+)+++def _silent_console() -> Console:+ return Console(file=StringIO(), force_terminal=False)+++def test_resolve_editor_setup_options_delegates_to_integrations() -> None:+ calls: list[tuple[str, frozenset[str], bool]] = []++ class FakeIntegration:+ def configure_options(+ self,+ console_obj: object,+ options: EditorSetupOptions,+ ) -> EditorSetupOptions:+ calls.append(+ (+ "configure",+ options.disabled_project_files,+ options.prompt_for_project_files,+ )+ )+ return options.with_disabled_project_file("fake_instructions")++ options = resolve_editor_setup_options(+ _silent_console(),+ disabled_project_files={"cli_disabled"},+ prompt_for_project_files=True,+ integrations=(FakeIntegration(),), # type: ignore[arg-type]+ )++ assert calls == [("configure", frozenset({"cli_disabled"}), True)]+ assert options.disabled_project_files == frozenset({"cli_disabled", "fake_instructions"})+ assert options.prompt_for_project_files is True+++def test_default_disabled_project_files_maps_legacy_no_claude_flag() -> None:+ assert get_default_disabled_project_files() == ()+ assert get_default_disabled_project_files(no_claude_md=True) == ("claude_md",)+++def test_write_editor_project_files_saves_common_mcp_before_integrations(+ tmp_path: Path,+ monkeypatch: Any,+) -> None:+ calls: list[tuple[str, object, object | None]] = []++ def fake_save_mcp_config(repo_path: Path) -> Path:+ calls.append(("mcp", repo_path, None))+ return repo_path / ".repowise" / "mcp.json"++ class FakeIntegration:+ def write_project_files(+ self,+ console_obj: object,+ repo_path: Path,+ options: EditorSetupOptions,+ ) -> None:+ calls.append(("fake-project", repo_path, options.disabled_project_files))++ def register_client(self, console_obj: object, repo_path: Path) -> None:+ raise AssertionError("not used")++ monkeypatch.setattr(mcp_config, "save_mcp_config", fake_save_mcp_config)++ write_editor_project_files(+ _silent_console(),+ tmp_path,+ disabled_project_files={"fake_instructions"},+ integrations=(FakeIntegration(),),+ )++ assert calls == [+ ("mcp", tmp_path, None),+ ("fake-project", tmp_path, frozenset({"fake_instructions"})),+ ]+++def test_write_editor_project_files_uses_pre_resolved_options(+ tmp_path: Path,+ monkeypatch: Any,+) -> None:+ calls: list[tuple[str, Path, EditorSetupOptions]] = []+ options = EditorSetupOptions(+ disabled_project_files=frozenset({"resolved"}),+ prompt_for_project_files=True,+ )++ def fake_save_mcp_config(repo_path: Path) -> Path:+ calls.append(("mcp", repo_path, options))+ return repo_path / ".repowise" / "mcp.json"++ class FakeIntegration:+ def write_project_files(+ self,+ console_obj: object,+ repo_path: Path,+ received_options: EditorSetupOptions,+ ) -> None:+ calls.append(("fake-project", repo_path, received_options))++ monkeypatch.setattr(mcp_config, "save_mcp_config", fake_save_mcp_config)++ write_editor_project_files(+ _silent_console(),+ tmp_path,+ options=options,+ disabled_project_files={"ignored"},+ integrations=(FakeIntegration(),), # type: ignore[arg-type]+ )++ assert calls == [+ ("mcp", tmp_path, options),+ ("fake-project", tmp_path, options),+ ]+++def test_claude_project_setup_writes_root_mcp_and_claude_md(+ tmp_path: Path,+ monkeypatch: Any,+) -> None:+ calls: list[tuple[str, object, object | None]] = []++ def fake_save_root_mcp_config(repo_path: Path) -> Path:+ calls.append(("root-mcp", repo_path, None))+ return repo_path / ".mcp.json"++ def fake_maybe_generate_claude_md(+ console_obj: object,+ repo_path: Path,+ *,+ no_claude_md: bool = False,+ ) -> None:+ calls.append(("claude-md", repo_path, no_claude_md))++ monkeypatch.setattr(mcp_config, "save_root_mcp_config", fake_save_root_mcp_config)+ monkeypatch.setattr(+ claude_integration,+ "maybe_generate_claude_md",+ fake_maybe_generate_claude_md,+ )++ ClaudeCodeSetup().write_project_files(+ _silent_console(),+ tmp_path,+ EditorSetupOptions(disabled_project_files=frozenset({"claude_md"})),+ )++ assert calls == [+ ("root-mcp", tmp_path, None),+ ("claude-md", tmp_path, True),+ ]+++def test_refresh_editor_project_files_delegates_to_integrations(tmp_path: Path) -> None:+ calls: list[tuple[str, Path, frozenset[str]]] = []++ class FakeIntegration:+ def refresh_project_files(+ self,+ console_obj: object,+ repo_path: Path,+ options: EditorSetupOptions,+ ) -> None:+ calls.append(("refresh", repo_path, options.disabled_project_files))++ refresh_editor_project_files(+ _silent_console(),+ tmp_path,+ options=EditorSetupOptions(disabled_project_files=frozenset({"skip"})),+ integrations=(FakeIntegration(),), # type: ignore[arg-type]+ )++ assert calls == [("refresh", tmp_path, frozenset({"skip"}))]+++def test_claude_refresh_project_files_writes_when_enabled(+ tmp_path: Path,+ monkeypatch: Any,+) -> None:+ calls: list[Path] = []++ async def fake_write_claude_md(repo_path: Path) -> None:+ calls.append(repo_path)++ monkeypatch.setattr(+ claude_integration,+ "_write_claude_md_async",+ fake_write_claude_md,+ )++ ClaudeCodeSetup().refresh_project_files(+ _silent_console(),+ tmp_path,+ EditorSetupOptions(),+ )++ assert calls == [tmp_path]+++def test_claude_refresh_project_files_skips_when_config_disabled(+ tmp_path: Path,+ monkeypatch: Any,+) -> None:+ calls: list[Path] = []+ (tmp_path / ".repowise").mkdir()+ (tmp_path / ".repowise" / "config.yaml").write_text(+ "editor_files:\n claude_md: false\n",+ encoding="utf-8",+ )++ async def fake_write_claude_md(repo_path: Path) -> None:+ calls.append(repo_path)++ monkeypatch.setattr(+ claude_integration,+ "_write_claude_md_async",+ fake_write_claude_md,+ )++ ClaudeCodeSetup().refresh_project_files(+ _silent_console(),+ tmp_path,+ EditorSetupOptions(),+ )++ assert calls == []+++def test_claude_refresh_project_files_skips_when_options_disable_file(+ tmp_path: Path,+ monkeypatch: Any,+) -> None:+ calls: list[Path] = []++ async def fake_write_claude_md(repo_path: Path) -> None:+ calls.append(repo_path)++ monkeypatch.setattr(+ claude_integration,+ "_write_claude_md_async",+ fake_write_claude_md,+ )++ ClaudeCodeSetup().refresh_project_files(+ _silent_console(),+ tmp_path,+ EditorSetupOptions(disabled_project_files=frozenset({"claude_md"})),+ )++ assert calls == []+++def test_update_command_uses_editor_refresh_abstraction() -> None:+ source = inspect.getsource(update_cmd.update_command.callback)++ assert "refresh_editor_project_files" in source+ assert "ClaudeMdGenerator" not in source+ assert "EditorFileDataFetcher" not in source+ assert "claude_md" not in source+++def test_init_command_uses_editor_option_abstraction() -> None:+ source = inspect.getsource(init_cmd.init_command.callback) + inspect.getsource(+ init_cmd._workspace_init+ )++ assert "resolve_editor_setup_options" in source+ assert "write_editor_project_files" in source+ assert "interactive_claude_md_prompt" not in source+ assert 'disabled_project_files={"claude_md"}' not in source+++def test_claude_client_registration_uses_existing_claude_setup(+ tmp_path: Path,+ monkeypatch: Any,+) -> None:+ calls: list[tuple[str, Path]] = []++ def fake_desktop(repo_path: Path) -> Path:+ calls.append(("desktop", repo_path))+ return tmp_path / "claude_desktop_config.json"++ def fake_code(repo_path: Path) -> Path:+ calls.append(("code", repo_path))+ return tmp_path / ".claude" / "settings.json"++ def fake_hooks() -> Path:+ calls.append(("hooks", tmp_path))+ return tmp_path / ".claude" / "settings.json"++ monkeypatch.setattr(claude_config, "register_with_claude_desktop", fake_desktop)+ monkeypatch.setattr(claude_config, "register_with_claude_code", fake_code)+ monkeypatch.setattr(claude_config, "install_claude_code_hooks", fake_hooks)++ output = StringIO()+ console = Console(file=output, force_terminal=False)++ ClaudeCodeSetup().register_client(console, tmp_path)++ assert calls == [+ ("desktop", tmp_path),+ ("code", tmp_path),+ ("hooks", tmp_path),+ ]+ text = output.getvalue()+ assert "Claude Desktop MCP registered" in text+ assert "Claude Code MCP registered" in text+ assert "Claude Code hooks registered" in textdiff --git a/tests/unit/cli/test_mcp_config.py b/tests/unit/cli/test_mcp_config.pyindex 59238110e..4adfb6d75 100644--- a/tests/unit/cli/test_mcp_config.py+++ b/tests/unit/cli/test_mcp_config.py@@ -6,6 +6,7 @@ import clickimport pytestfrom repowise.cli import mcp_config+from repowise.cli.editor_integrations import claude_configdef _repowise_entry(repo_path: Path) -> dict:@@ -58,7 +59,7 @@ def test_save_root_mcp_config_rejects_invalid_existing_file(tmp_path: Path) -> Ndef test_merge_mcp_entry_creates_missing_file(tmp_path: Path) -> None:config_path = tmp_path / "settings.json"- assert mcp_config._merge_mcp_entry(config_path, _repowise_entry(tmp_path))+ assert mcp_config.merge_mcp_entry(config_path, _repowise_entry(tmp_path))saved = json.loads(config_path.read_text(encoding="utf-8"))assert "repowise" in saved["mcpServers"]@@ -76,7 +77,7 @@ def test_merge_mcp_entry_merges_valid_existing_file(tmp_path: Path) -> None:encoding="utf-8",)- assert mcp_config._merge_mcp_entry(config_path, _repowise_entry(tmp_path))+ assert mcp_config.merge_mcp_entry(config_path, _repowise_entry(tmp_path))saved = json.loads(config_path.read_text(encoding="utf-8"))assert saved["mcpServers"]["existing"] == {"command": "existing"}@@ -90,7 +91,7 @@ def test_merge_mcp_entry_rejects_invalid_existing_file(tmp_path: Path) -> None:config_path.write_text(original, encoding="utf-8")with pytest.raises(click.ClickException, match=re.escape(str(config_path))):- mcp_config._merge_mcp_entry(config_path, _repowise_entry(tmp_path))+ mcp_config.merge_mcp_entry(config_path, _repowise_entry(tmp_path))assert config_path.read_text(encoding="utf-8") == original@@ -117,7 +118,7 @@ def test_install_claude_code_hooks_creates_missing_file(intentionally absent because it can't see actual result counts."""monkeypatch.setattr(Path, "home", lambda: tmp_path)- settings_path = mcp_config.install_claude_code_hooks()+ settings_path = claude_config.install_claude_code_hooks()assert settings_path == tmp_path / ".claude" / "settings.json"saved = json.loads(settings_path.read_text(encoding="utf-8"))@@ -149,7 +150,7 @@ def test_install_claude_code_hooks_preserves_user_pretool_hooks(encoding="utf-8",)- assert mcp_config.install_claude_code_hooks() == settings_path+ assert claude_config.install_claude_code_hooks() == settings_pathsaved = json.loads(settings_path.read_text(encoding="utf-8"))assert saved["permissions"] == {"allow": ["Bash(git status:*)"]}@@ -201,7 +202,7 @@ def test_install_claude_code_hooks_migrates_pre_0_6_1_command(encoding="utf-8",)- assert mcp_config.install_claude_code_hooks() == settings_path+ assert claude_config.install_claude_code_hooks() == settings_pathsaved = json.loads(settings_path.read_text(encoding="utf-8"))assert "PreToolUse" not in saved["hooks"]@@ -243,7 +244,7 @@ def test_install_claude_code_hooks_migrates_pre_0_6_2_matcher(encoding="utf-8",)- assert mcp_config.install_claude_code_hooks() == settings_path+ assert claude_config.install_claude_code_hooks() == settings_pathsaved = json.loads(settings_path.read_text(encoding="utf-8"))assert "PreToolUse" not in saved["hooks"]@@ -255,9 +256,9 @@ def test_install_claude_code_hooks_idempotent_on_current_shape() -> None:"""Running install twice should leave settings.json in the same shape."""monkeypatch.setattr(Path, "home", lambda: tmp_path)- mcp_config.install_claude_code_hooks()+ claude_config.install_claude_code_hooks()first = (tmp_path / ".claude" / "settings.json").read_text(encoding="utf-8")- mcp_config.install_claude_code_hooks()+ claude_config.install_claude_code_hooks()second = (tmp_path / ".claude" / "settings.json").read_text(encoding="utf-8")assert first == second@@ -301,14 +302,14 @@ def test_migrate_claude_code_hooks_handles_full_legacy_payload(encoding="utf-8",)- assert mcp_config.migrate_claude_code_hooks() is True+ assert claude_config.migrate_claude_code_hooks() is Truesaved = json.loads(settings_path.read_text(encoding="utf-8"))assert "PreToolUse" not in saved["hooks"]assert _post_repowise_entries(saved) == [("Bash|Grep|Glob", "repowise-augment")]# Idempotent: a second run finds nothing to do.- assert mcp_config.migrate_claude_code_hooks() is False+ assert claude_config.migrate_claude_code_hooks() is Falsedef test_migrate_claude_code_hooks_preserves_user_sibling_hook(@@ -338,7 +339,7 @@ def test_migrate_claude_code_hooks_preserves_user_sibling_hook(encoding="utf-8",)- assert mcp_config.migrate_claude_code_hooks() is True+ assert claude_config.migrate_claude_code_hooks() is Truesaved = json.loads(settings_path.read_text(encoding="utf-8"))pre = saved["hooks"]["PreToolUse"]assert len(pre) == 1@@ -366,7 +367,7 @@ def test_migrate_claude_code_hooks_noop_when_already_current(settings_path.write_text(original, encoding="utf-8")mtime_before = settings_path.stat().st_mtime_ns- assert mcp_config.migrate_claude_code_hooks() is False+ assert claude_config.migrate_claude_code_hooks() is Falseassert settings_path.read_text(encoding="utf-8") == originalassert settings_path.stat().st_mtime_ns == mtime_before@@ -375,7 +376,7 @@ def test_migrate_claude_code_hooks_silent_when_settings_missing(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:monkeypatch.setattr(Path, "home", lambda: tmp_path)- assert mcp_config.migrate_claude_code_hooks() is False+ assert claude_config.migrate_claude_code_hooks() is Falsedef test_migrate_claude_code_hooks_silent_on_malformed_json(@@ -386,7 +387,7 @@ def test_migrate_claude_code_hooks_silent_on_malformed_json(settings_path.parent.mkdir(parents=True)settings_path.write_text("{ not json", encoding="utf-8")- assert mcp_config.migrate_claude_code_hooks() is False+ assert claude_config.migrate_claude_code_hooks() is Falsedef test_install_claude_code_hooks_rejects_invalid_existing_file(@@ -399,6 +400,6 @@ def test_install_claude_code_hooks_rejects_invalid_existing_file(settings_path.write_text(original, encoding="utf-8")with pytest.raises(click.ClickException, match=re.escape(str(settings_path))):- mcp_config.install_claude_code_hooks()+ claude_config.install_claude_code_hooks()assert settings_path.read_text(encoding="utf-8") == originaldiff --git a/tests/unit/server/test_mcp.py b/tests/unit/server/test_mcp.pyindex a35c84bae..9acf494f2 100644--- a/tests/unit/server/test_mcp.py+++ b/tests/unit/server/test_mcp.py@@ -1217,7 +1217,8 @@ def test_format_setup_instructions():from repowise.cli.mcp_config import format_setup_instructionsinstructions = format_setup_instructions(Path("/tmp/test-repo"))- assert "Claude Code" in instructions+ assert "Project .mcp.json" in instructions+ assert "Claude Code" not in instructionsassert "Cursor" in instructionsassert "Cline" in instructionsassert "repowise" in instructions