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.

Auto-configure MCP and write .claude/CLAUDE.md during repowise init (#7)

Swati Ahuja9718d28d5926
diff --git a/packages/cli/src/repowise/cli/commands/claude_md_cmd.py b/packages/cli/src/repowise/cli/commands/claude_md_cmd.py
index e085a686c..cf6f3567c 100644
--- a/packages/cli/src/repowise/cli/commands/claude_md_cmd.py
+++ b/packages/cli/src/repowise/cli/commands/claude_md_cmd.py
@@ -20,7 +20,7 @@ from repowise.cli.helpers import (
"output_path",
default=None,
metavar="FILE",
- help="Write to a custom path (default: CLAUDE.md in the repo root).",
+ help="Write to a custom path (default: .claude/CLAUDE.md).",
)
@click.option(
"--stdout",
@@ -99,5 +99,5 @@ async def _generate(
written.rename(dest)
written = dest
- click.echo(f"CLAUDE.md updated: {written}")
+ click.echo(f".claude/CLAUDE.md updated: {written}")
return None
diff --git a/packages/cli/src/repowise/cli/commands/init_cmd.py b/packages/cli/src/repowise/cli/commands/init_cmd.py
index a50cafbc6..9b4711bda 100644
--- a/packages/cli/src/repowise/cli/commands/init_cmd.py
+++ b/packages/cli/src/repowise/cli/commands/init_cmd.py
@@ -56,11 +56,11 @@ def _maybe_generate_claude_md(
if not enabled:
return
try:
- with console_obj.status(" Generating CLAUDE.md…", spinner="dots"):
+ with console_obj.status(" Generating .claude/CLAUDE.md…", spinner="dots"):
run_async(_write_claude_md_async(repo_path))
- console_obj.print(" [green]✓[/green] CLAUDE.md updated")
+ console_obj.print(" [green]✓[/green] .claude/CLAUDE.md updated")
except Exception as exc:
- console_obj.print(f" [yellow]CLAUDE.md skipped: {exc}[/yellow]")
+ console_obj.print(f" [yellow].claude/CLAUDE.md skipped: {exc}[/yellow]")
async def _write_claude_md_async(repo_path: Path) -> None:
@@ -717,11 +717,12 @@ def init_command(
pass # No yaml — commit_limit will use default next time
# MCP config
- from repowise.cli.mcp_config import save_mcp_config
+ from repowise.cli.mcp_config import save_mcp_config, save_root_mcp_config
save_mcp_config(repo_path)
+ save_root_mcp_config(repo_path)
- # CLAUDE.md (index-only: structural data is available)
+ # .claude/CLAUDE.md (index-only: structural data is available)
_maybe_generate_claude_md(console, repo_path, no_claude_md=no_claude_md)
elapsed = time.monotonic() - start
@@ -1070,9 +1071,14 @@ def init_command(
)
# ---- Completion ----
- from repowise.cli.mcp_config import format_setup_instructions, save_mcp_config
+ from repowise.cli.mcp_config import (
+ format_setup_instructions,
+ save_mcp_config,
+ save_root_mcp_config,
+ )
save_mcp_config(repo_path)
+ save_root_mcp_config(repo_path)
elapsed = time.monotonic() - start
diff --git a/packages/cli/src/repowise/cli/mcp_config.py b/packages/cli/src/repowise/cli/mcp_config.py
index da4fc2557..89c9328f6 100644
--- a/packages/cli/src/repowise/cli/mcp_config.py
+++ b/packages/cli/src/repowise/cli/mcp_config.py
@@ -33,6 +33,31 @@ def save_mcp_config(repo_path: Path) -> Path:
return config_path
+def save_root_mcp_config(repo_path: Path) -> Path:
+ """Write .mcp.json at repo root for Claude Code auto-discovery.
+
+ Merges the repowise server entry into any existing mcpServers block
+ so other MCP servers configured by the user are preserved.
+ """
+ config_path = repo_path / ".mcp.json"
+ new_entry = generate_mcp_config(repo_path)["mcpServers"]
+
+ if config_path.exists():
+ try:
+ existing = json.loads(config_path.read_text(encoding="utf-8"))
+ except (json.JSONDecodeError, OSError):
+ existing = {}
+ servers = dict(existing.get("mcpServers", {}))
+ servers.update(new_entry)
+ existing["mcpServers"] = servers
+ merged = existing
+ else:
+ merged = {"mcpServers": new_entry}
+
+ config_path.write_text(json.dumps(merged, indent=2) + "\n", encoding="utf-8")
+ return config_path
+
+
def format_setup_instructions(repo_path: Path) -> str:
"""Return human-readable setup instructions for MCP clients."""
config = generate_mcp_config(repo_path)
@@ -43,12 +68,7 @@ def format_setup_instructions(repo_path: Path) -> str:
MCP Server Configuration
========================
-Add the following to your editor's MCP config:
-
-Claude Code (~/.claude.json or ~/.claude/claude.json):
- "mcpServers": {{
- "repowise": {server_block}
- }}
+Claude Code: automatically configured via .mcp.json (no manual steps needed).
Cursor (.cursor/mcp.json):
{server_block}
diff --git a/packages/core/src/repowise/core/generation/editor_files/claude_md.py b/packages/core/src/repowise/core/generation/editor_files/claude_md.py
index 7502aa571..76233ca15 100644
--- a/packages/core/src/repowise/core/generation/editor_files/claude_md.py
+++ b/packages/core/src/repowise/core/generation/editor_files/claude_md.py
@@ -1,13 +1,17 @@
-"""ClaudeMdGenerator — generates and maintains CLAUDE.md for a repository."""
+"""ClaudeMdGenerator — generates and maintains .claude/CLAUDE.md for a repository."""
from __future__ import annotations
+from pathlib import Path
+
from .base import BaseEditorFileGenerator
+from .data import EditorFileData
class ClaudeMdGenerator(BaseEditorFileGenerator):
- """Generates and maintains the CLAUDE.md file.
+ """Generates and maintains .claude/CLAUDE.md.
+ Writes to <repo_path>/.claude/CLAUDE.md so Claude Code auto-discovers it.
The file has two sections:
- User section (above the REPOWISE markers): never touched by Repowise.
- Repowise section (between markers): auto-generated from indexed data.
@@ -23,3 +27,14 @@ class ClaudeMdGenerator(BaseEditorFileGenerator):
"<!-- Examples: coding style rules, test commands, "
"workflow preferences, constraints -->\n"
)
+
+ def write(self, repo_path: Path, data: EditorFileData) -> Path:
+ """Write to <repo_path>/.claude/CLAUDE.md, creating the directory if needed."""
+ dot_claude = repo_path / ".claude"
+ dot_claude.mkdir(parents=True, exist_ok=True)
+ return super().write(dot_claude, data)
+
+ def render_full(self, repo_path: Path, data: EditorFileData) -> str:
+ """Preview what .claude/CLAUDE.md would contain without writing."""
+ dot_claude = repo_path / ".claude"
+ return super().render_full(dot_claude, data)
diff --git a/packages/core/src/repowise/core/generation/templates/claude_md.j2 b/packages/core/src/repowise/core/generation/templates/claude_md.j2
index d6560780b..9f1111194 100644
--- a/packages/core/src/repowise/core/generation/templates/claude_md.j2
+++ b/packages/core/src/repowise/core/generation/templates/claude_md.j2
@@ -1,6 +1,10 @@
-## Codebase Intelligence — {{ data.repo_name }} (Repowise)
+## IMPORTANT: Codebase Intelligence Instructions for {{ data.repo_name }}
+
+> **CRITICAL**: This repository is indexed by [Repowise](https://repowise.dev).
+> You MUST use the repowise MCP tools below instead of reading raw source files.
+> They deliver richer context — documentation, ownership, history, decisions —
+> in a single call. Raw `read_file` calls are a last resort only.
-This project is indexed by [Repowise](https://repowise.dev) — a codebase intelligence layer.
Last indexed: {{ data.indexed_at }}{% if data.avg_confidence %}. Confidence: {{ (data.avg_confidence * 100) | int }}%.{% endif %}
{% if data.architecture_summary %}
@@ -46,29 +50,35 @@ Last indexed: {{ data.indexed_at }}{% if data.avg_confidence %}. Confidence: {{
### Repowise MCP Tools
-This project has a Repowise MCP server configured. Use these tools to understand the codebase before reading raw source files — they provide richer context including documentation, ownership, history, and architectural decisions.
+This project has a Repowise MCP server configured. **ALWAYS use these tools before reading source files** — they provide documentation, ownership, architectural decisions, and risk signals in a single call.
-**Recommended workflow:**
+**MANDATORY workflow:**
-1. Starting a new task? Call `get_overview()` first to understand the architecture.
-2. Before reading/modifying files, call `get_context(targets=["path/to/file.py"])` — faster and richer than reading source directly.
-3. Before making changes, call `get_risk(targets=["path/to/file.py"])` to understand impact and hotspot status.
-4. Don't know where something lives? Call `search_codebase(query="authentication flow")`.
-5. Need to understand why code is structured a certain way? Call `get_why(query="why JWT over sessions")`.
-6. Need to understand how two modules connect? Call `get_dependency_path(source="src/auth", target="src/db")`.
-7. Before cleanup tasks, call `get_dead_code()` to find confirmed unused code.
-8. For documentation or diagrams, call `get_architecture_diagram(scope="src/auth")`.
+1. **ALWAYS start with `get_overview()`** on any new task to orient yourself.
+2. **MUST call `get_context(targets=["path/to/file.py"])`** before reading or editing any file — faster and richer than reading source directly.
+3. **MUST call `get_risk(targets=["path/to/file.py"])`** before making changes — especially for hotspot files.
+4. Don't know where something lives? Call `search_codebase(query="authentication flow")` — prefer over grep/find.
+5. Need to understand why code is structured a certain way? **MUST call `get_why(query="why JWT over sessions")`** before any architectural change.
+6. **After completing any code changes**, **MUST call `update_decision_records(action="list")`** to review existing decisions, then:
+ - Call `update_decision_records(action="create", title="...", decision="...", rationale="...", affected_files=[...])` to record any new architectural decisions you made.
+ - Call `update_decision_records(action="update", decision_id="...", ...)` to update existing decisions affected by your changes.
+ - Call `update_decision_records(action="update_status", decision_id="...", status="deprecated")` if your changes invalidate an existing decision.
+ **This is not optional** — keeping decision records current is a required part of every coding task.
+7. Need to understand how two modules connect? Call `get_dependency_path(source="src/auth", target="src/db")`.
+8. Before cleanup tasks, call `get_dead_code()` to find confirmed unused code.
+9. For documentation or diagrams, call `get_architecture_diagram(scope="src/auth")`.
-| Tool | When to use |
-|------|------------|
-| `get_overview()` | First call on unfamiliar codebase or new task |
-| `get_context(targets=[...])` | Before reading or modifying specific files/symbols |
-| `get_risk(targets=[...])` | Before changing files — assess blast radius |
-| `get_why(query="...")` | Before architectural changes — find decisions |
-| `search_codebase(query="...")` | Don't know where something lives |
-| `get_dependency_path(source=..., target=...)` | Understand connections between modules |
-| `get_dead_code()` | Before cleanup or refactoring |
-| `get_architecture_diagram(scope=...)` | Need a visual of the structure |
+| Tool | WHEN you MUST use it |
+|------|----------------------|
+| `get_overview()` | **FIRST call on every new task** |
+| `get_context(targets=[...])` | **Before reading or modifying any file** |
+| `get_risk(targets=[...])` | Before changing files — REQUIRED for hotspots |
+| `get_why(query="...")` | Before architectural changes — REQUIRED |
+| `update_decision_records(action=...)` | **After every coding task** — record and update decisions |
+| `search_codebase(query="...")` | When locating code — prefer over grep/find |
+| `get_dependency_path(source=..., target=...)` | When tracing module connections |
+| `get_dead_code()` | Before any cleanup or removal |
+| `get_architecture_diagram(scope=...)` | For visual structure or documentation |
{% if data.decisions or data.build_commands %}
### Codebase Conventions
diff --git a/packages/server/src/repowise/server/routers/claude_md.py b/packages/server/src/repowise/server/routers/claude_md.py
index 1276079b3..342302521 100644
--- a/packages/server/src/repowise/server/routers/claude_md.py
+++ b/packages/server/src/repowise/server/routers/claude_md.py
@@ -50,7 +50,7 @@ async def generate_claude_md(
repo_id: str,
session: AsyncSession = Depends(get_db_session), # noqa: B008
) -> dict:
- """Regenerate CLAUDE.md and write it to the repository root.
+ """Regenerate .claude/CLAUDE.md and write it to the repository.
Returns the generated content. Runs synchronously (fast — no LLM calls).
"""
diff --git a/tests/unit/cli/test_commands.py b/tests/unit/cli/test_commands.py
index ccce1f1c4..532d0987b 100644
--- a/tests/unit/cli/test_commands.py
+++ b/tests/unit/cli/test_commands.py
@@ -99,6 +99,8 @@ 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("GOOGLE_API_KEY", raising=False)
+ monkeypatch.delenv("GEMINI_API_KEY", raising=False)
monkeypatch.delenv("OLLAMA_BASE_URL", raising=False)
monkeypatch.delenv("REPOWISE_PROVIDER", raising=False)
result = runner.invoke(cli, ["init", str(tmp_path)])