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.

fix(hooks): isolate Claude Code augment hook + self-heal legacy entries on upgrade (#160)

Raghav Chamadiya40882e414406
diff --git a/docs/CHANGELOG.md b/docs/CHANGELOG.md
index c3fe1fd54..1a7aae806 100644
--- a/docs/CHANGELOG.md
+++ b/docs/CHANGELOG.md
@@ -9,6 +9,15 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
---
+## [Unreleased]
+
+### Fixed
+- **Claude Code hook crashes when the active venv is broken.** PreToolUse (`Grep`/`Glob`) and PostToolUse (`Bash`) hooks invoked the full `repowise augment` Click command, whose import chain pulls `cli.main` → `init_cmd` → `cost_estimator` → `core.ingestion.graph` → `networkx`/`scipy`. A single missing dependency in the user's environment caused every tool call to surface an `ImportError` traceback and non-zero exit, because the in-handler `try/except` could not catch failures during module loading. Hooks are now wired to a new `repowise-augment` console script (`repowise.cli.augment_hook:main`) that imports only the augment handler — module-level imports are stdlib-only — and wraps the entire run, including the lazy import of the handler, in a last-ditch `except BaseException` so any failure exits 0 silently.
+
+ Existing users upgrading from any prior version are migrated automatically: every `repowise <command>` invocation runs an idempotent self-heal that rewrites `repowise augment` to `repowise-augment` in `~/.claude/settings.json` on first run after upgrade, and the hook entry point itself performs the same rewrite on first successful firing. No manual edit, no `repowise init`, no extra command needed — `pip install -U repowise` is sufficient.
+
+---
+
## [0.6.0] — 2026-05-09
### Added
diff --git a/docs/USER_GUIDE.md b/docs/USER_GUIDE.md
index 5a114f7a7..644a091da 100644
--- a/docs/USER_GUIDE.md
+++ b/docs/USER_GUIDE.md
@@ -843,12 +843,13 @@ Hooks are written to `~/.claude/settings.json` automatically during `repowise in
| `PreToolUse` | `Grep\|Glob` | Query `wiki.db` and prepend graph context to the result |
| `PostToolUse` | `Bash` | Check for git operations and notify if wiki is stale |
-Both hooks call the `repowise augment` CLI command internally. Hooks are designed for graceful failure — any error results in a silent exit so a repowise issue never breaks the agent.
+Both hooks call the `repowise-augment` console script — a standalone, import-isolated entry point that does not load the full `repowise` CLI. This keeps cold start under the 500ms target and ensures a broken environment (missing optional dep, corrupt DB, etc.) never crashes the agent: any failure exits 0 silently. The equivalent `repowise augment` Click subcommand still exists for manual debugging.
### CLI command
```bash
-repowise augment # Not meant to be called manually — invoked by Claude Code hooks
+repowise-augment # Not meant to be called manually — invoked by Claude Code hooks
+repowise augment # Equivalent Click subcommand, useful for manual debugging
```
### Sample enrichment output
diff --git a/packages/cli/src/repowise/cli/augment_hook.py b/packages/cli/src/repowise/cli/augment_hook.py
new file mode 100644
index 000000000..62a33c0de
--- /dev/null
+++ b/packages/cli/src/repowise/cli/augment_hook.py
@@ -0,0 +1,56 @@
+"""Standalone entry point for the Claude Code ``repowise-augment`` hook.
+
+Hooks must never crash the agent. The full ``repowise`` CLI imports the
+entire command surface — including ``init_cmd`` → ``cost_estimator`` →
+``core.ingestion.graph``, which pulls in ``networkx``, ``scipy``, and other
+heavy dependencies. A single missing dep (or any other import-time failure
+in any subcommand) would otherwise propagate as a non-zero exit on every
+``Grep``/``Glob``/``Bash`` tool call, spamming the agent transcript with
+tracebacks.
+
+This entry point is wired as a separate ``[project.scripts]`` console script
+so:
+
+ - It does not transitively import any subcommand modules — only the
+ handler in ``commands.augment_cmd``, which itself only imports
+ ``json``/``sys``/``click`` at module scope (heavy queries are lazy).
+ - The entire body, including the import, is wrapped in a last-ditch
+ ``except BaseException`` so any failure (broken venv, corrupt DB,
+ even ``ImportError``) exits 0 silently with no output.
+
+The Click command ``repowise augment`` still works for manual debugging;
+hook installers should write ``repowise-augment`` instead.
+"""
+
+from __future__ import annotations
+
+import sys
+
+
+def main() -> None:
+ try:
+ from repowise.cli.commands.augment_cmd import _run_augment
+
+ _run_augment()
+ except (SystemExit, KeyboardInterrupt):
+ raise
+ except BaseException:
+ pass
+
+ # Best-effort self-heal for users whose only repowise invocation is
+ # through this hook. Idempotent: rewrites settings.json only when a
+ # legacy `repowise augment` entry is still present, then becomes a
+ # 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
+
+ migrate_claude_code_hooks()
+ except BaseException:
+ pass
+
+ sys.exit(0)
+
+
+if __name__ == "__main__":
+ main()
diff --git a/packages/cli/src/repowise/cli/main.py b/packages/cli/src/repowise/cli/main.py
index bea98610f..2925eae89 100644
--- a/packages/cli/src/repowise/cli/main.py
+++ b/packages/cli/src/repowise/cli/main.py
@@ -26,8 +26,21 @@ from repowise.cli.commands.workspace_cmd import workspace_group
@click.group()
@click.version_option(version=__version__, prog_name="repowise")
-def cli() -> None:
+def cli(ctx: click.Context) -> None:
"""repowise -- codebase intelligence for developers and AI."""
+ # Self-heal: migrate any legacy `repowise augment` Claude Code hooks
+ # to the import-isolated `repowise-augment` console script. Cheap,
+ # silent, idempotent — only writes when there is something to change.
+ # Skipped when invoked as the augment subcommand itself (hot path on
+ # 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
+
+ migrate_claude_code_hooks()
+ except Exception:
+ pass
cli.add_command(augment_command)
diff --git a/packages/cli/src/repowise/cli/mcp_config.py b/packages/cli/src/repowise/cli/mcp_config.py
index ee9d8b7a1..0b12a8e1d 100644
--- a/packages/cli/src/repowise/cli/mcp_config.py
+++ b/packages/cli/src/repowise/cli/mcp_config.py
@@ -168,7 +168,7 @@ def install_claude_code_hooks() -> Path | None:
"hooks": [
{
"type": "command",
- "command": "repowise augment",
+ "command": "repowise-augment",
"timeout": 10,
"statusMessage": "Enriching with codebase context...",
}
@@ -180,7 +180,7 @@ def install_claude_code_hooks() -> Path | None:
"hooks": [
{
"type": "command",
- "command": "repowise augment",
+ "command": "repowise-augment",
"timeout": 10,
"statusMessage": "Checking wiki freshness...",
}
@@ -196,13 +196,15 @@ def install_claude_code_hooks() -> Path | None:
hooks = existing.setdefault("hooks", {})
- # Merge PreToolUse — avoid duplicates
+ # Merge PreToolUse — migrate legacy entries, then add if missing
pre_hooks = hooks.setdefault("PreToolUse", [])
+ _migrate_legacy_hook(pre_hooks)
if not _has_repowise_hook(pre_hooks):
pre_hooks.append(pre_hook_entry)
- # Merge PostToolUse — avoid duplicates
+ # Merge PostToolUse — migrate legacy entries, 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)
@@ -213,15 +215,85 @@ def install_claude_code_hooks() -> Path | None:
def _has_repowise_hook(hook_list: list) -> bool:
- """Check if a repowise augment hook is already registered."""
+ """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:
+ if "repowise-augment" in cmd or "repowise augment" in cmd:
return True
return False
+def _migrate_legacy_hook(hook_list: list) -> bool:
+ """Rewrite legacy ``repowise augment`` commands to ``repowise-augment``.
+
+ Pre-0.6.1 installs registered ``repowise augment``, which goes through
+ the full Click CLI and crashes on any import failure (e.g. missing
+ ``networkx`` in the active venv) — exiting non-zero on every tool call.
+ The standalone ``repowise-augment`` console script is import-isolated
+ and crash-safe; rewrite in place so existing users get the fix.
+
+ Returns True if any entry was changed.
+ """
+ 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
+ return changed
+
+
+def migrate_claude_code_hooks() -> bool:
+ """Self-healing migration of pre-0.6.1 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
+ ``repowise augment`` entry was actually rewritten to ``repowise-augment``.
+
+ 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:
+ # Malformed JSON, etc. — bail silently; the user will see this on
+ # their next `repowise init`, where it raises a ClickException.
+ return False
+
+ hooks = existing.get("hooks")
+ if not isinstance(hooks, dict):
+ return False
+
+ changed = False
+ for key in ("PreToolUse", "PostToolUse"):
+ bucket = hooks.get(key)
+ if isinstance(bucket, list):
+ if _migrate_legacy_hook(bucket):
+ 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)
diff --git a/pyproject.toml b/pyproject.toml
index 56f9fd6f0..b399a1083 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -111,6 +111,7 @@ dev = [
[project.scripts]
repowise = "repowise.cli.main:cli"
+repowise-augment = "repowise.cli.augment_hook:main"
[project.urls]
Homepage = "https://github.com/repowise-dev/repowise"
diff --git a/tests/unit/cli/test_mcp_config.py b/tests/unit/cli/test_mcp_config.py
index f0b1cedc5..d0e71a395 100644
--- a/tests/unit/cli/test_mcp_config.py
+++ b/tests/unit/cli/test_mcp_config.py
@@ -132,13 +132,167 @@ def test_install_claude_code_hooks_merges_valid_existing_file(
assert saved["permissions"] == {"allow": ["Bash(git status:*)"]}
assert saved["hooks"]["PreToolUse"][0]["matcher"] == "Read"
assert any(
- hook["command"] == "repowise augment"
+ hook["command"] == "repowise-augment"
for entry in saved["hooks"]["PreToolUse"]
for hook in entry["hooks"]
)
assert "PostToolUse" in saved["hooks"]
+def test_install_claude_code_hooks_migrates_legacy_command(
+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ """Pre-0.6.1 installs wrote ``repowise augment`` (the Click CLI), which
+ crashes whenever any subcommand fails to import. The installer should
+ rewrite in place to the import-isolated ``repowise-augment`` script."""
+ monkeypatch.setattr(Path, "home", lambda: tmp_path)
+ settings_path = tmp_path / ".claude" / "settings.json"
+ settings_path.parent.mkdir(parents=True)
+ settings_path.write_text(
+ json.dumps(
+ {
+ "hooks": {
+ "PreToolUse": [
+ {
+ "matcher": "Grep|Glob",
+ "hooks": [
+ {"type": "command", "command": "repowise augment"}
+ ],
+ }
+ ],
+ "PostToolUse": [
+ {
+ "matcher": "Bash",
+ "hooks": [
+ {"type": "command", "command": "repowise augment"}
+ ],
+ }
+ ],
+ }
+ }
+ ),
+ encoding="utf-8",
+ )
+
+ assert mcp_config.install_claude_code_hooks() == settings_path
+
+ saved = json.loads(settings_path.read_text(encoding="utf-8"))
+ pre_cmds = [
+ h["command"]
+ for entry in saved["hooks"]["PreToolUse"]
+ for h in entry["hooks"]
+ ]
+ post_cmds = [
+ h["command"]
+ for entry in saved["hooks"]["PostToolUse"]
+ for h in entry["hooks"]
+ ]
+ assert pre_cmds == ["repowise-augment"]
+ assert post_cmds == ["repowise-augment"]
+
+
+def test_migrate_claude_code_hooks_rewrites_legacy_command(
+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ """Self-heal path: any `repowise <cmd>` after upgrade should rewrite a
+ legacy ``repowise augment`` entry to ``repowise-augment`` in place."""
+ monkeypatch.setattr(Path, "home", lambda: tmp_path)
+ settings_path = tmp_path / ".claude" / "settings.json"
+ settings_path.parent.mkdir(parents=True)
+ settings_path.write_text(
+ json.dumps(
+ {
+ "hooks": {
+ "PreToolUse": [
+ {
+ "matcher": "Grep|Glob",
+ "hooks": [
+ {"type": "command", "command": "repowise augment"}
+ ],
+ }
+ ],
+ "PostToolUse": [
+ {
+ "matcher": "Bash",
+ "hooks": [
+ {"type": "command", "command": "repowise augment"}
+ ],
+ }
+ ],
+ }
+ }
+ ),
+ encoding="utf-8",
+ )
+
+ assert mcp_config.migrate_claude_code_hooks() is True
+
+ saved = json.loads(settings_path.read_text(encoding="utf-8"))
+ pre_cmds = [
+ h["command"]
+ for entry in saved["hooks"]["PreToolUse"]
+ for h in entry["hooks"]
+ ]
+ post_cmds = [
+ h["command"]
+ for entry in saved["hooks"]["PostToolUse"]
+ for h in entry["hooks"]
+ ]
+ assert pre_cmds == ["repowise-augment"]
+ assert post_cmds == ["repowise-augment"]
+
+ # Idempotent: a second run finds nothing to do and returns False.
+ assert mcp_config.migrate_claude_code_hooks() is False
+
+
+def test_migrate_claude_code_hooks_noop_when_already_migrated(
+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ """Must not rewrite settings.json when the new command is already in place."""
+ monkeypatch.setattr(Path, "home", lambda: tmp_path)
+ settings_path = tmp_path / ".claude" / "settings.json"
+ settings_path.parent.mkdir(parents=True)
+ payload = {
+ "hooks": {
+ "PreToolUse": [
+ {
+ "matcher": "Grep|Glob",
+ "hooks": [{"type": "command", "command": "repowise-augment"}],
+ }
+ ]
+ }
+ }
+ original = json.dumps(payload, indent=2) + "\n"
+ 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
+ # File untouched — same content, same mtime (the function returned before write).
+ assert settings_path.read_text(encoding="utf-8") == original
+ assert settings_path.stat().st_mtime_ns == mtime_before
+
+
+def test_migrate_claude_code_hooks_silent_when_settings_missing(
+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ monkeypatch.setattr(Path, "home", lambda: tmp_path)
+ # No ~/.claude/settings.json at all.
+ assert mcp_config.migrate_claude_code_hooks() is False
+
+
+def test_migrate_claude_code_hooks_silent_on_malformed_json(
+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ """A malformed settings.json must not raise — the user sees the error
+ on their next `repowise init`, not via a self-heal pass."""
+ monkeypatch.setattr(Path, "home", lambda: tmp_path)
+ settings_path = tmp_path / ".claude" / "settings.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
+
+
def test_install_claude_code_hooks_rejects_invalid_existing_file(
tmp_path: Path, monkeypatch: pytest.MonkeyPatch
) -> None: