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
feat(hooks): smart PostToolUse enrichment for Grep/Glob, drop noisy PreToolUse (#162)
Raghav Chamadiya0febbd040636
diff --git a/README.md b/README.mdindex 693511519..0e325e28a 100644--- a/README.md+++ b/README.md@@ -11,7 +11,7 @@ Four intelligence layers. Seven MCP tools. Multi-repo workspaces. Auto-sync hook[](https://modelcontextprotocol.io)[](https://github.com/repowise-dev/repowise)-[**Explore real codebases →**](https://www.repowise.dev/explore) · [**Hosted for teams →**](https://www.repowise.dev/#contact) · [**Docs**](https://repowise-dev.github.io) · [**Discord**](https://discord.gg/cQVpuDB6rh) · [**Contact**](mailto:[email protected])+[**Explore real codebases →**](https://www.repowise.dev/explore) · [**Hosted for teams →**](https://www.repowise.dev/#contact) · [**Docs**](https://docs.repowise.dev) · [**Discord**](https://discord.gg/cQVpuDB6rh) · [**Contact**](mailto:[email protected])---diff --git a/packages/cli/src/repowise/cli/commands/augment_cmd.py b/packages/cli/src/repowise/cli/commands/augment_cmd.pyindex 413b6cba5..a6d749b43 100644--- a/packages/cli/src/repowise/cli/commands/augment_cmd.py+++ b/packages/cli/src/repowise/cli/commands/augment_cmd.py@@ -1,18 +1,44 @@"""``repowise augment`` — hook-driven context enrichment for AI coding agents.-Reads a Claude Code hook payload from stdin (JSON), queries the local wiki.db-for graph context (importers, symbols), and writes enriched context back to-stdout as the hook response.--PreToolUse: enriches Grep/Glob calls with up to 3 related files, their key-symbols, importers, and dependencies.--PostToolUse: detects git commits and notifies the agent when the wiki is stale.--Design goals:- - Cold start < 500ms (lazy imports, minimal work)- - Graceful failure: any error → exit 0 with empty output- - No LLM calls, no network — pure local SQLite queries+Reads a Claude Code hook payload from stdin (JSON) and writes targeted+enrichment back as a PostToolUse hook response.++Design philosophy: an enrichment hook is only valuable when it tells the+agent something the raw tool output didn't. Anything else is noise the+agent has to scroll past. So the hook fires on every Grep/Glob/Bash but+returns *nothing* most of the time, and only speaks up when there is+asymmetric, durable value:++ PostToolUse → Grep / Glob+ * Zero-result rescue: grep returned 0 hits but the wiki has a+ semantic match (FTS on docs, fuzzy symbol match, decision record+ mention). Surfaces the closest hit so the agent doesn't burn+ another round on a synonym.+ * Triage on flood: grep returned a large unfocused result set+ (>=_TRIAGE_THRESHOLD lines). Surfaces the top 3 files by+ PageRank so the agent can prioritise. The raw matches are still+ visible — this is just a ranking lens.+ * Skip otherwise: a focused result set means the agent already+ found what it wanted; further graph context is just noise.++ PostToolUse → Bash+ * After a successful git commit/merge/rebase/cherry-pick/pull, if+ the wiki HEAD has drifted from .repowise/state.json's last sync+ commit AND no `repowise update` is in flight AND we haven't+ already warned for this HEAD, emit a one-line stale-wiki notice.++There is intentionally NO PreToolUse handling. Earlier versions enriched+every Grep/Glob unconditionally with importers/dependencies/symbols; in+practice this added noise on the >70% of searches where the agent had+already located what it wanted. PostToolUse is strictly more informed —+it can see the actual result count — and is the only entry point now.++Operational invariants:+ * No LLM calls, no network. Pure local SQLite + Python.+ * Cold start budget: well under the 10s hook timeout. Heavy imports+ (sqlalchemy, asyncio) are deferred until we actually have work.+ * Graceful failure: any unexpected error exits 0 with empty stdout+ so a repowise problem never surfaces in the agent transcript."""from __future__ import annotations@@ -22,6 +48,13 @@ import sysimport click+# Tunables — fixed thresholds keep the fire pattern predictable across+# repos. If these ever need to vary, derive them from indexed-row counts+# rather than exposing knobs (every knob is a way for the hook to drift).+_TRIAGE_THRESHOLD = 15 # grep result lines before we surface a ranking+_TRIAGE_TOP_N = 3+_RESCUE_TOP_N = 2+@click.command("augment")def augment_command() -> None:@@ -36,7 +69,7 @@ def augment_command() -> None:def _run_augment() -> None:- """Main entry point — reads stdin, dispatches to pre/post handler."""+ """Main entry point — reads stdin, dispatches to the post handler."""raw = sys.stdin.read()if not raw.strip():return@@ -47,20 +80,27 @@ def _run_augment() -> None:returnevent = payload.get("hook_event_name", "")+ if event != "PostToolUse":+ return+tool_name = payload.get("tool_name", "")tool_input = payload.get("tool_input", {})+ tool_output = (+ payload.get("tool_output")+ or payload.get("tool_response")+ or {}+ )cwd = payload.get("cwd", "")- if event == "PreToolUse" and tool_name in ("Grep", "Glob"):- result = _handle_pre_tool_use(tool_name, tool_input, cwd)- if result:- _emit_response(event, result)+ if tool_name == "Bash":+ result = _handle_bash_post(tool_input, tool_output, cwd)+ elif tool_name in ("Grep", "Glob"):+ result = _handle_search_post(tool_name, tool_input, tool_output, cwd)+ else:+ result = None- elif event == "PostToolUse" and tool_name == "Bash":- tool_output = payload.get("tool_output", {})- result = _handle_post_tool_use(tool_input, tool_output, cwd)- if result:- _emit_response(event, result)+ if result:+ _emit_response(event, result)def _emit_response(event: str, context: str) -> None:@@ -76,21 +116,24 @@ def _emit_response(event: str, context: str) -> None:# ----------------------------------------------------------------------------# PreToolUse — enrich search/grep/glob with graph context+# PostToolUse — Grep / Glob: smart enrichment# ----------------------------------------------------------------------------def _extract_search_pattern(tool_name: str, tool_input: dict) -> str | None:- """Extract the search pattern from the tool input."""- if tool_name in ("Grep", "Glob"):- return tool_input.get("pattern")- return None-+def _handle_search_post(+ tool_name: str,+ tool_input: dict,+ tool_output: object,+ cwd: str,+) -> str | None:+ """Decide whether to enrich a Grep/Glob result and how."""+ pattern = tool_input.get("pattern")+ if not isinstance(pattern, str) or not pattern.strip():+ return None-def _handle_pre_tool_use(tool_name: str, tool_input: dict, cwd: str) -> str | None:- """Query the wiki DB for graph context related to the search pattern."""- pattern = _extract_search_pattern(tool_name, tool_input)- if not pattern:+ # Path-style lookups don't benefit from semantic enrichment — the agent+ # is reading literal locations, not exploring a concept.+ if _looks_like_path_lookup(pattern):return Nonefrom pathlib import Path@@ -99,27 +142,115 @@ def _handle_pre_tool_use(tool_name: str, tool_input: dict, cwd: str) -> str | Noif repo_path is None:return None+ output_text = _extract_output_text(tool_output)+ result_count = _count_search_results(output_text)++ # Decision tree. The skip case is the most common — that's by design.+ if result_count == 0:+ mode = "rescue"+ elif result_count >= _TRIAGE_THRESHOLD:+ mode = "triage"+ else:+ return None+import asyncio- return asyncio.run(_query_graph_context(repo_path, pattern))+ return asyncio.run(_search_enrich(repo_path, pattern, mode, result_count))+++def _looks_like_path_lookup(pattern: str) -> bool:+ """Heuristic: pattern is a literal file path, not a search concept.+ Path-style queries that should skip enrichment:+ - Contains a directory separator (``/`` or ``\\``).+ - Ends with a known source extension (``.py``, ``.ts``, ``.tsx``,+ ``.js``, ``.jsx``, ``.go``, ``.rs``, ``.java``, ``.kt``, etc.).+ - Looks like a glob over files (``*.py``, ``**/*.ts``).-async def _query_graph_context(repo_path: "Path", pattern: str) -> str | None:- """Multi-signal search + graph enrichment.+ These are agents looking up specific files; semantic enrichment of+ such queries duplicates information the result already provides.+ """+ if "/" in pattern or "\\" in pattern:+ return True+ lower = pattern.lower().rstrip()+ _EXTS = (+ ".py", ".pyi", ".ts", ".tsx", ".js", ".jsx", ".mjs", ".cjs",+ ".go", ".rs", ".java", ".kt", ".kts", ".scala", ".rb", ".php",+ ".cs", ".swift", ".cpp", ".cc", ".c", ".h", ".hpp", ".lua",+ ".sql", ".yaml", ".yml", ".toml", ".json", ".md",+ )+ return lower.endswith(_EXTS)- Phase 1 — find relevant files via three signals (merged, deduped):- a) Symbol name match (wiki_symbols.name LIKE pattern)- b) File path match (graph_nodes.node_id LIKE pattern)- c) FTS on wiki page content (fallback for conceptual queries)- Results ranked by how many signals matched, then by PageRank.- Phase 2 — enrich top 3 files with symbols, importers, dependencies.+def _extract_output_text(tool_output: object) -> str:+ """Pull the textual portion of a Claude Code tool_output, defensively.++ Claude Code's hook payload shape varies a little by tool: Bash+ surfaces ``stdout``/``stderr``, Grep/Glob surface ``output`` or+ ``tool_response``. We only need a string we can count newlines in,+ so we accept any of the common shapes."""+ if isinstance(tool_output, str):+ return tool_output+ if not isinstance(tool_output, dict):+ return ""+ for key in ("output", "result", "content", "stdout", "text"):+ val = tool_output.get(key)+ if isinstance(val, str):+ return val+ if isinstance(val, list):+ # Some shapes wrap content as [{"type": "text", "text": "..."}].+ parts = []+ for item in val:+ if isinstance(item, str):+ parts.append(item)+ elif isinstance(item, dict):+ t = item.get("text") or item.get("content")+ if isinstance(t, str):+ parts.append(t)+ if parts:+ return "\n".join(parts)+ return ""+++def _count_search_results(output_text: str) -> int:+ """Count tool-result lines, treating Grep/Glob 'no match' as zero."""+ if not output_text or not output_text.strip():+ return 0+ stripped = output_text.strip()+ # Common no-match sentinels emitted by Claude Code's Grep/Glob tool.+ _ZERO_MARKERS = (+ "no matches found",+ "no files found",+ "no files matched",+ "found 0 files",+ "found 0 matches",+ )+ head = stripped.lower().splitlines()[0] if stripped else ""+ if any(marker in head for marker in _ZERO_MARKERS):+ return 0+ # Strip a "Found N files\n" / "Found N matches\n" header if present —+ # the count we want is the actual result lines, not the banner.+ lines = [ln for ln in stripped.splitlines() if ln.strip()]+ if lines and lines[0].lower().startswith("found "):+ lines = lines[1:]+ return len(lines)+++async def _search_enrich(+ repo_path: "object",+ pattern: str,+ mode: str,+ result_count: int,+) -> str | None:+ """Run the rescue or triage query against the wiki and format output."""import re+ from pathlib import Path+ from sqlalchemy import select+from repowise.core.persistence import (FullTextSearch,- GraphEdge,GraphNode,WikiSymbol,create_engine,@@ -128,8 +259,8 @@ async def _query_graph_context(repo_path: "Path", pattern: str) -> str | None:)from repowise.core.persistence.crud import get_repository_by_pathfrom repowise.core.persistence.database import resolve_db_url- from sqlalchemy import select+ repo_path = Path(repo_path)db_path = repo_path / ".repowise" / "wiki.db"if not db_path.exists():return None@@ -145,160 +276,206 @@ async def _query_graph_context(repo_path: "Path", pattern: str) -> str | None:return Nonerepo_id = repo.id- # Clean pattern for SQL LIKE — strip regex syntax- clean = re.sub(r"[^\w/._-]", "", pattern)-- # Track how many signals each file matched + its PageRank- file_scores: dict[str, float] = {} # path -> score- file_ranks: dict[str, float] = {} # path -> pagerank-- # Signal 1: symbol name match — most precise- if clean:- sym_stmt = (- select(WikiSymbol.file_path)- .where(- WikiSymbol.repository_id == repo_id,- WikiSymbol.name.like(f"%{clean}%"),- )- .distinct()- .limit(5)+ clean = re.sub(r"[^\w./_-]", "", pattern).strip("./")++ if mode == "rescue":+ return await _rescue(+ session, engine, repo_id, pattern, clean)- sym_result = await session.execute(sym_stmt)- for (fp,) in sym_result.all():- file_scores[fp] = file_scores.get(fp, 0) + 2.0-- # Signal 2: file path match- if clean:- path_stmt = (- select(GraphNode.node_id, GraphNode.pagerank)- .where(- GraphNode.repository_id == repo_id,- GraphNode.node_type == "file",- GraphNode.node_id.like(f"%{clean}%"),- )- .order_by(GraphNode.pagerank.desc())- .limit(5)+ if mode == "triage":+ return await _triage(+ session, repo_id, pattern, clean, result_count)- path_result = await session.execute(path_stmt)- for node_id, pr in path_result.all():- file_scores[node_id] = file_scores.get(node_id, 0) + 1.5- file_ranks[node_id] = pr-- # Signal 3: FTS on wiki content — broadest, lowest weight- fts = FullTextSearch(engine)- try:- fts_results = await fts.search(pattern, limit=5)- except Exception:- fts_results = []-- for r in fts_results:- target = getattr(r, "target_path", None) or ""- page_type = getattr(r, "page_type", "")- if page_type and page_type not in (- "file", "file_page", "infra_page", "api_contract",- ):- continue- if "::" in target:- target = target.split("::")[0]- if target:- file_scores[target] = file_scores.get(target, 0) + 1.0-- if not file_scores:- return None+ return None+ finally:+ await engine.dispose()- # Fetch PageRank for files we don't have it for yet- missing_pr = [fp for fp in file_scores if fp not in file_ranks]- if missing_pr:- pr_stmt = select(GraphNode.node_id, GraphNode.pagerank).where(- GraphNode.repository_id == repo_id,- GraphNode.node_type == "file",- GraphNode.node_id.in_(missing_pr),- )- pr_result = await session.execute(pr_stmt)- for node_id, pr in pr_result.all():- file_ranks[node_id] = pr-- # Rank: primary by signal score, secondary by PageRank- ranked = sorted(- file_scores.keys(),- key=lambda fp: (file_scores[fp], file_ranks.get(fp, 0)),- reverse=True,- )- file_paths = ranked[:3]- # Phase 2: enrich with symbols, importers, dependencies+async def _rescue(+ session,+ engine,+ repo_id: int,+ pattern: str,+ clean: str,+) -> str | None:+ """Zero-result rescue: grep missed but the wiki has a semantic hit.- # Importers: who uses these files? (limit 3 per file)- importers_stmt = select(GraphEdge).where(- GraphEdge.repository_id == repo_id,- GraphEdge.target_node_id.in_(file_paths),- GraphEdge.edge_type == "imports",- )- importers_result = await session.execute(importers_stmt)- importers_by_file: dict[str, list[str]] = {}- for edge in importers_result.scalars().all():- lst = importers_by_file.setdefault(edge.target_node_id, [])- if len(lst) < 3:- lst.append(edge.source_node_id)-- # Dependencies: what does this file use? (limit 2 per file)- deps_stmt = select(GraphEdge).where(- GraphEdge.repository_id == repo_id,- GraphEdge.source_node_id.in_(file_paths),- GraphEdge.edge_type == "imports",- )- deps_result = await session.execute(deps_stmt)- deps_by_file: dict[str, list[str]] = {}- for edge in deps_result.scalars().all():- lst = deps_by_file.setdefault(edge.source_node_id, [])- if len(lst) < 2:- lst.append(edge.target_node_id)-- # Symbols: key symbols (limit 3 per file)- symbols_stmt = (- select(WikiSymbol)- .where(- WikiSymbol.repository_id == repo_id,- WikiSymbol.file_path.in_(file_paths),- )- .order_by(WikiSymbol.start_line)+ Looks for the closest match in three places, in priority order:++ 1. Fuzzy symbol name match — handles snake_case ↔ camelCase ↔+ PascalCase drift. ``parse_yaml`` finds ``parseYaml`` /+ ``ParseYaml`` / ``yaml_parser``.+ 2. FTS on wiki page content — handles conceptual misses where+ the agent grepped for a synonym ("session" but the codebase+ calls it "context").+ 3. Skip — if neither signal hits, we have nothing useful to add.++ Output is a single line so it can't be confused with a real result.+ """+ from sqlalchemy import or_, select++ from repowise.core.persistence import (+ FullTextSearch,+ GraphNode,+ WikiSymbol,+ )++ if not clean:+ return None++ # Build a small set of token variants. Cheap; helps catch case-style+ # drift without a heavy similarity index.+ variants = _name_variants(clean)+ like_clauses = [WikiSymbol.name.ilike(f"%{v}%") for v in variants]+ sym_stmt = (+ select(WikiSymbol.name, WikiSymbol.kind, WikiSymbol.file_path, WikiSymbol.start_line)+ .where(WikiSymbol.repository_id == repo_id, or_(*like_clauses))+ .limit(_RESCUE_TOP_N)+ )+ rows = (await session.execute(sym_stmt)).all()+ if rows:+ # Rank: prefer exact-token-equal matches; then shortest name (most+ # specific). All ties broken by file path lex order for stability.+ def _rank(row):+ name = (row[0] or "").lower()+ exact = name in {v.lower() for v in variants}+ return (not exact, len(name), row[2] or "")++ rows = sorted(rows, key=_rank)[:_RESCUE_TOP_N]+ first = rows[0]+ line = f":{first[3]}" if first[3] else ""+ extras = ""+ if len(rows) > 1:+ extras = f" (+{len(rows) - 1} more)"+ return (+ f"[repowise] No literal match for `{pattern}`. Closest indexed symbol: "+ f"{first[1]} `{first[0]}` in {first[2]}{line}{extras}"+ )++ # Fall back to FTS on wiki content. Only return if the FTS row actually+ # points at a code page (file/module/api), not a generic doc page.+ fts = FullTextSearch(engine)+ try:+ fts_rows = await fts.search(pattern, limit=3)+ except Exception:+ fts_rows = []+ for r in fts_rows:+ target = getattr(r, "target_path", None) or ""+ page_type = getattr(r, "page_type", "") or ""+ if "::" in target:+ target = target.split("::")[0]+ if target and page_type in ("file", "file_page", "module_page", "api_contract", "infra_page"):+ return (+ f"[repowise] No literal match for `{pattern}`. "+ f"Wiki suggests `{target}` ({page_type}).")- symbols_result = await session.execute(symbols_stmt)- symbols_by_file: dict[str, list] = {}- for sym in symbols_result.scalars().all():- lst = symbols_by_file.setdefault(sym.file_path, [])- if len(lst) < 3:- lst.append(sym)+ return None- # Phase 3: Format- lines = [f"[repowise] {len(file_paths)} related file(s) found:\n"]- for fp in file_paths:- lines.append(f" {fp}")+async def _triage(+ session,+ repo_id: int,+ pattern: str,+ clean: str,+ result_count: int,+) -> str | None:+ """Big-result triage: surface top files by PageRank.- syms = symbols_by_file.get(fp, [])- if syms:- sym_strs = [f"{s.kind}:{s.name}" for s in syms]- lines.append(f" Symbols: {', '.join(sym_strs)}")+ The grep result set has too many lines for the agent to scan+ efficiently. Without overriding the agent's literal results, we+ point at the top _TRIAGE_TOP_N files (by structural centrality)+ that contain the pattern in either symbol or path.- imps = importers_by_file.get(fp, [])- if imps:- lines.append(f" Imported by: {', '.join(imps)}")+ Output is one line plus an enumerated list. Three lines max.+ """+ from sqlalchemy import or_, select- deps = deps_by_file.get(fp, [])- if deps:- lines.append(f" Uses: {', '.join(deps)}")+ from repowise.core.persistence import GraphNode, WikiSymbol- lines.append("")+ if not clean:+ return None- return "\n".join(lines)+ # Files that contain a symbol whose name matches, or whose own path+ # matches. Either way we can rank by PageRank from graph_nodes.+ sym_files_stmt = (+ select(WikiSymbol.file_path)+ .where(+ WikiSymbol.repository_id == repo_id,+ WikiSymbol.name.ilike(f"%{clean}%"),+ )+ .distinct()+ .limit(50)+ )+ sym_files = {r[0] for r in (await session.execute(sym_files_stmt)).all() if r[0]}++ path_stmt = (+ select(GraphNode.node_id)+ .where(+ GraphNode.repository_id == repo_id,+ GraphNode.node_type == "file",+ GraphNode.node_id.ilike(f"%{clean}%"),+ )+ .limit(50)+ )+ path_files = {r[0] for r in (await session.execute(path_stmt)).all() if r[0]}- finally:- await engine.dispose()+ candidates = sym_files | path_files+ if not candidates:+ return None++ pr_stmt = select(GraphNode.node_id, GraphNode.pagerank).where(+ GraphNode.repository_id == repo_id,+ GraphNode.node_type == "file",+ GraphNode.node_id.in_(candidates),+ )+ pr_rows = (await session.execute(pr_stmt)).all()+ if not pr_rows:+ return None++ ranked = sorted(pr_rows, key=lambda r: (r[1] or 0.0), reverse=True)[:_TRIAGE_TOP_N]+ if not ranked:+ return None++ header = (+ f"[repowise] {result_count}+ matches for `{pattern}`. "+ f"Top files by graph centrality:"+ )+ lines = [header] + [f" {row[0]}" for row in ranked]+ return "\n".join(lines)+++def _name_variants(token: str) -> list[str]:+ """Generate snake_case ↔ camelCase ↔ PascalCase variants for fuzzy match.++ Cheap to compute, and catches the most common naming-drift class+ that causes literal grep to miss what the wiki has indexed.+ """+ import re++ token = token.strip("_-./")+ if not token:+ return []+ seen: list[str] = []+ candidates = {token, token.lower(), token.upper()}+ # snake_case → camelCase / PascalCase+ if "_" in token:+ parts = [p for p in token.split("_") if p]+ if parts:+ candidates.add("".join(p.capitalize() for p in parts))+ candidates.add(parts[0].lower() + "".join(p.capitalize() for p in parts[1:]))+ # camelCase / PascalCase → snake_case+ snake = re.sub(r"(?<!^)(?=[A-Z])", "_", token).lower()+ if snake != token.lower():+ candidates.add(snake)+ # Dedup while preserving insertion order roughly.+ for c in candidates:+ if c and c not in seen:+ seen.append(c)+ return seen# ----------------------------------------------------------------------------# PostToolUse — detect git commits and flag stale wiki+# PostToolUse — Bash: stale-wiki detection after git commits# ---------------------------------------------------------------------------_GIT_COMMIT_PATTERNS = (@@ -310,20 +487,23 @@ _GIT_COMMIT_PATTERNS = ()-def _handle_post_tool_use(tool_input: dict, tool_output: dict, cwd: str) -> str | None:+def _handle_bash_post(tool_input: dict, tool_output: object, cwd: str) -> str | None:"""After a successful git commit, check if the wiki needs updating."""- # Only act on successful commands- exit_code = tool_output.get("exit_code")- if exit_code is None:- # Try stdout-based detection (some hook formats differ)- stdout = tool_output.get("stdout", "")- if "error" in stdout.lower() or "fatal" in stdout.lower():+ if isinstance(tool_output, dict):+ exit_code = tool_output.get("exit_code")+ if exit_code is None:+ stdout = tool_output.get("stdout", "")+ if isinstance(stdout, str) and (+ "error" in stdout.lower() or "fatal" in stdout.lower()+ ):+ return None+ elif exit_code != 0:return None- elif exit_code != 0:- return Nonecmd = tool_input.get("command", "")- if not any(p in cmd for p in _GIT_COMMIT_PATTERNS):+ if not isinstance(cmd, str) or not any(+ p in cmd for p in _GIT_COMMIT_PATTERNS+ ):return Nonefrom pathlib import Path@@ -345,7 +525,6 @@ def _handle_post_tool_use(tool_input: dict, tool_output: dict, cwd: str) -> strif not last_sync:return None- # Compare HEAD against last synctry:import subprocess@@ -362,16 +541,9 @@ def _handle_post_tool_use(tool_input: dict, tool_output: dict, cwd: str) -> strif head == last_sync:return None- # Suppress while a `repowise update` is in flight — the post-commit- # hook typically kicks one off in the background, and warning the- # agent that the wiki is stale right after the commit is just noise.if _update_in_flight(repo_path, head):return None- # Once-per-HEAD dedupe: every tool call after a commit would otherwise- # repeat the same staleness warning until an update completes (which- # may never happen if the user's hook is misconfigured). Cache the- # already-warned HEAD so the message fires once per stale state.if _already_warned(repo_path, head):return None_record_warning(repo_path, head)@@ -385,18 +557,12 @@ def _handle_post_tool_use(tool_input: dict, tool_output: dict, cwd: str) -> str)-def _update_in_flight(repo_path: "Path", head: str) -> bool:- """Return True if a recent `repowise update` is still running.-- Reads ``.repowise/.update.lock`` written by ``update_command``. A lock- is considered live if it was written within the last 30 minutes; older- entries are treated as crashed runs and ignored. If the lock's target- commit matches HEAD, the update will land us in sync — suppress the- warning either way.- """+def _update_in_flight(repo_path: "object", head: str) -> bool:+ """Return True if a recent ``repowise update`` is still running."""import time+ from pathlib import Path- lock_path = repo_path / ".repowise" / ".update.lock"+ lock_path = Path(repo_path) / ".repowise" / ".update.lock"if not lock_path.exists():return Falsetry:@@ -413,15 +579,13 @@ def _update_in_flight(repo_path: "Path", head: str) -> bool:target = payload.get("target_commit")if target and target == head:return True- # Lock is live but for a different (presumably older) commit. The- # in-flight update will at least narrow the gap; one more tool call- # later will re-evaluate. Suppress for now.return True-def _already_warned(repo_path: "Path", head: str) -> bool:- """Check the per-HEAD warning marker, written by ``_record_warning``."""- marker = repo_path / ".repowise" / ".augment-warned"+def _already_warned(repo_path: "object", head: str) -> bool:+ from pathlib import Path++ marker = Path(repo_path) / ".repowise" / ".augment-warned"if not marker.exists():return Falsetry:@@ -430,9 +594,10 @@ def _already_warned(repo_path: "Path", head: str) -> bool:return False-def _record_warning(repo_path: "Path", head: str) -> None:- """Persist that we have warned about staleness at *head*. Best-effort."""- marker = repo_path / ".repowise" / ".augment-warned"+def _record_warning(repo_path: "object", head: str) -> None:+ from pathlib import Path++ marker = Path(repo_path) / ".repowise" / ".augment-warned"try:marker.write_text(head, encoding="utf-8")except OSError:@@ -444,12 +609,12 @@ def _record_warning(repo_path: "Path", head: str) -> None:# ----------------------------------------------------------------------------def _find_repo_root(cwd: "Path") -> "Path | None":- """Walk up from cwd to find a directory with .repowise/."""+def _find_repo_root(cwd: "object") -> "object | None":+ """Walk up from cwd to find a directory with ``.repowise/``."""from pathlib import Pathcurrent = Path(cwd).resolve()- for _ in range(20): # safety limit+ for _ in range(20):if (current / ".repowise").is_dir():return currentparent = current.parentdiff --git a/packages/cli/src/repowise/cli/mcp_config.py b/packages/cli/src/repowise/cli/mcp_config.pyindex 0b12a8e1d..fc9335753 100644--- a/packages/cli/src/repowise/cli/mcp_config.py+++ b/packages/cli/src/repowise/cli/mcp_config.py@@ -163,26 +163,18 @@ def install_claude_code_hooks() -> Path | None:"""settings_path = _claude_code_settings_path()- pre_hook_entry = {- "matcher": "Grep|Glob",- "hooks": [- {- "type": "command",- "command": "repowise-augment",- "timeout": 10,- "statusMessage": "Enriching with codebase context...",- }- ],- }-+ # 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",+ "matcher": "Bash|Grep|Glob","hooks": [{"type": "command","command": "repowise-augment","timeout": 10,- "statusMessage": "Checking wiki freshness...",+ "statusMessage": "Checking codebase context...",}],}@@ -196,13 +188,14 @@ def install_claude_code_hooks() -> Path | None:hooks = existing.setdefault("hooks", {})- # Merge PreToolUse — migrate legacy entries, then add if missing+ # Drop any pre-existing repowise PreToolUse entry — the new design+ # routes everything through PostToolUse.pre_hooks = hooks.setdefault("PreToolUse", [])- _migrate_legacy_hook(pre_hooks)- if not _has_repowise_hook(pre_hooks):- pre_hooks.append(pre_hook_entry)+ _strip_repowise_pretool(pre_hooks)+ if not pre_hooks:+ hooks.pop("PreToolUse", None)- # Merge PostToolUse — migrate legacy entries, then add if missing+ # 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):@@ -224,33 +217,91 @@ def _has_repowise_hook(hook_list: list) -> bool: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:- """Rewrite legacy ``repowise augment`` commands to ``repowise-augment``.+ """In-place migration of legacy PostToolUse entries to current shape.++ Two layers of legacy:- 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.+ * 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.- Returns True if any entry was changed.+ * 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 = Falsefor 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 = Truereturn changeddef migrate_claude_code_hooks() -> bool:- """Self-healing migration of pre-0.6.1 hook entries in settings.json.+ """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- ``repowise augment`` entry was actually rewritten to ``repowise-augment``.+ 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>`` afterupgrade self-heals) and ``augment_hook`` (so users whose only repowise@@ -267,8 +318,6 @@ def migrate_claude_code_hooks() -> bool: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 Falsehooks = existing.get("hooks")@@ -276,11 +325,20 @@ def migrate_claude_code_hooks() -> bool:return Falsechanged = False- for key in ("PreToolUse", "PostToolUse"):- bucket = hooks.get(key)- if isinstance(bucket, list):- if _migrate_legacy_hook(bucket):- changed = True++ # 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 = Trueif not changed:return Falsediff --git a/tests/unit/cli/test_augment_search.py b/tests/unit/cli/test_augment_search.pynew file mode 100644index 000000000..8130879e2--- /dev/null+++ b/tests/unit/cli/test_augment_search.py@@ -0,0 +1,215 @@+"""Tests for the PostToolUse Grep/Glob smart-enrichment decision tree.++The hook is designed to be silent on the common case (focused search+already returned what the agent wanted) and only speak up when it can+add information the raw result didn't carry. These tests pin the+boundary cases of the decision tree without hitting the wiki — the+``_search_enrich`` async path is mocked because it requires a real+wiki.db, and is exercised end-to-end in integration tests instead.+"""++from __future__ import annotations++from unittest.mock import patch++import pytest++from repowise.cli.commands import augment_cmd+from repowise.cli.commands.augment_cmd import (+ _count_search_results,+ _extract_output_text,+ _handle_search_post,+ _looks_like_path_lookup,+ _name_variants,+)+++# ---------------------------------------------------------------------------+# Pure helpers+# ---------------------------------------------------------------------------+++class TestLooksLikePathLookup:+ @pytest.mark.parametrize(+ "pattern",+ [+ "src/auth/service.py",+ "packages/web/src",+ "*.py",+ "**/*.tsx",+ "init_cmd.py",+ "README.md",+ r"C:\Users\ragha\Desktop\repowise",+ ],+ )+ def test_path_style_skips(self, pattern: str) -> None:+ assert _looks_like_path_lookup(pattern) is True++ @pytest.mark.parametrize(+ "pattern",+ [+ "parse_yaml",+ "GraphBuilder",+ "auth",+ "session",+ "use cache",+ "fooBar",+ ],+ )+ def test_concept_queries_do_not_skip(self, pattern: str) -> None:+ assert _looks_like_path_lookup(pattern) is False+++class TestExtractOutputText:+ def test_string_passthrough(self) -> None:+ assert _extract_output_text("hello\nworld") == "hello\nworld"++ def test_dict_with_output_key(self) -> None:+ assert _extract_output_text({"output": "x\ny"}) == "x\ny"++ def test_dict_with_stdout_key(self) -> None:+ assert _extract_output_text({"stdout": "z"}) == "z"++ def test_dict_with_text_list(self) -> None:+ assert (+ _extract_output_text(+ {"content": [{"type": "text", "text": "a"}, {"type": "text", "text": "b"}]}+ )+ == "a\nb"+ )++ def test_unrecognised_shape(self) -> None:+ assert _extract_output_text(None) == ""+ assert _extract_output_text(42) == ""+ assert _extract_output_text({"unrelated": "value"}) == ""+++class TestCountSearchResults:+ def test_empty(self) -> None:+ assert _count_search_results("") == 0+ assert _count_search_results(" \n ") == 0++ @pytest.mark.parametrize(+ "text",+ [+ "No matches found",+ "no files found",+ "Found 0 files",+ "Found 0 matches",+ ],+ )+ def test_zero_markers(self, text: str) -> None:+ assert _count_search_results(text) == 0++ def test_strips_found_header(self) -> None:+ text = "Found 3 files\nfile1.py\nfile2.py\nfile3.py"+ assert _count_search_results(text) == 3++ def test_counts_nonempty_lines(self) -> None:+ text = "src/a.py\n\nsrc/b.py\n \nsrc/c.py"+ assert _count_search_results(text) == 3+++class TestNameVariants:+ def test_snake_to_camel(self) -> None:+ v = _name_variants("parse_yaml")+ assert "parse_yaml" in v+ assert any(x.lower() == "parseyaml" for x in v)+ assert "parseYaml" in v++ def test_camel_to_snake(self) -> None:+ v = _name_variants("parseYaml")+ assert any(x == "parse_yaml" for x in v)++ def test_pascal_to_snake(self) -> None:+ v = _name_variants("ParseYaml")+ assert any(x == "parse_yaml" for x in v)++ def test_empty_input(self) -> None:+ assert _name_variants("") == []+ assert _name_variants("___") == []+++# ---------------------------------------------------------------------------+# Decision tree — the gating logic before any wiki query runs+# ---------------------------------------------------------------------------+++def repowise_cwd(tmp_path):+ """A cwd with a ``.repowise`` directory so ``_find_repo_root`` succeeds."""+ (tmp_path / ".repowise").mkdir()+ return tmp_path+++def _call(tool_name, pattern, output_text, cwd):+ return _handle_search_post(+ tool_name=tool_name,+ tool_input={"pattern": pattern},+ tool_output={"output": output_text},+ cwd=str(cwd),+ )+++class TestDecisionTree:+ def test_skip_when_pattern_is_path(self, repowise_cwd) -> None:+ with patch.object(augment_cmd, "_search_enrich") as enrich:+ assert _call("Grep", "src/foo.py", "src/foo.py:1: x", repowise_cwd) is None+ enrich.assert_not_called()++ def test_skip_when_no_pattern(self, repowise_cwd) -> None:+ with patch.object(augment_cmd, "_search_enrich") as enrich:+ assert (+ _handle_search_post(+ tool_name="Grep",+ tool_input={"pattern": ""},+ tool_output={"output": "anything"},+ cwd=str(repowise_cwd),+ )+ is None+ )+ enrich.assert_not_called()++ def test_skip_when_outside_repowise_repo(self, tmp_path) -> None:+ # No .repowise dir: silently skip without invoking the enrich path.+ with patch.object(augment_cmd, "_search_enrich") as enrich:+ assert _call("Grep", "auth", "src/a.py:1: hit", tmp_path) is None+ enrich.assert_not_called()++ def test_skip_on_focused_result_set(self, repowise_cwd) -> None:+ """1–14 lines = focused: agent has what it wanted, hook stays silent."""+ output = "\n".join(f"src/file{i}.py:1: hit" for i in range(5))+ with patch.object(augment_cmd, "_search_enrich") as enrich:+ assert _call("Grep", "auth", output, repowise_cwd) is None+ enrich.assert_not_called()++ def test_rescue_mode_on_zero_results(self, repowise_cwd) -> None:+ """0 lines + concept query → rescue mode."""+ sentinel = object()+ with patch.object(+ augment_cmd, "_search_enrich", return_value=sentinel+ ) as enrich:+ with patch("asyncio.run", side_effect=lambda coro: (coro.close(), sentinel)[1]):+ _call("Grep", "parse_yaml", "", repowise_cwd)+ (call_args,) = enrich.call_args_list+ kwargs = call_args.kwargs or {}+ args = call_args.args+ mode = kwargs.get("mode") if "mode" in kwargs else args[2]+ assert mode == "rescue"++ def test_triage_mode_on_flood(self, repowise_cwd) -> None:+ """>= _TRIAGE_THRESHOLD lines → triage mode."""+ from repowise.cli.commands.augment_cmd import _TRIAGE_THRESHOLD++ big = "\n".join(f"src/file{i}.py:1: hit" for i in range(_TRIAGE_THRESHOLD + 5))+ sentinel = object()+ with patch.object(+ augment_cmd, "_search_enrich", return_value=sentinel+ ) as enrich:+ with patch("asyncio.run", side_effect=lambda coro: (coro.close(), sentinel)[1]):+ _call("Grep", "auth", big, repowise_cwd)+ call_args = enrich.call_args_list[0]+ args = call_args.args+ kwargs = call_args.kwargs or {}+ mode = kwargs.get("mode") if "mode" in kwargs else args[2]+ assert mode == "triage"diff --git a/tests/unit/cli/test_augment_staleness.py b/tests/unit/cli/test_augment_staleness.pyindex 265075790..64f034a32 100644--- a/tests/unit/cli/test_augment_staleness.py+++ b/tests/unit/cli/test_augment_staleness.py@@ -15,7 +15,7 @@ from pathlib import Pathimport pytest-from repowise.cli.commands.augment_cmd import _handle_post_tool_use+from repowise.cli.commands.augment_cmd import _handle_bash_post@pytest.fixture@@ -61,7 +61,7 @@ def _commit(repo_path: Path) -> str:def _post(repo_path: Path):- return _handle_post_tool_use(+ return _handle_bash_post(tool_input={"command": "git commit -m 'x'"},tool_output={"exit_code": 0},cwd=str(repo_path),diff --git a/tests/unit/cli/test_mcp_config.py b/tests/unit/cli/test_mcp_config.pyindex d0e71a395..59238110e 100644--- a/tests/unit/cli/test_mcp_config.py+++ b/tests/unit/cli/test_mcp_config.py@@ -12,6 +12,11 @@ def _repowise_entry(repo_path: Path) -> dict:return mcp_config.generate_mcp_config(repo_path)["mcpServers"]+# ---------------------------------------------------------------------------+# Root .mcp.json+# ---------------------------------------------------------------------------++def test_save_root_mcp_config_creates_missing_file(tmp_path: Path) -> None:config_path = mcp_config.save_root_mcp_config(tmp_path)@@ -90,22 +95,40 @@ def test_merge_mcp_entry_rejects_invalid_existing_file(tmp_path: Path) -> None:assert config_path.read_text(encoding="utf-8") == original+# ---------------------------------------------------------------------------+# install_claude_code_hooks — fresh installs+# ---------------------------------------------------------------------------+++def _post_repowise_entries(saved: dict) -> list:+ return [+ (entry.get("matcher"), h["command"])+ for entry in saved["hooks"].get("PostToolUse", [])+ for h in entry["hooks"]+ if "repowise" in h.get("command", "")+ ]++def test_install_claude_code_hooks_creates_missing_file(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:+ """Fresh install: only a PostToolUse entry is added. The new design+ routes Bash + Grep + Glob through a single matcher; PreToolUse is+ 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()assert settings_path == tmp_path / ".claude" / "settings.json"saved = json.loads(settings_path.read_text(encoding="utf-8"))- assert "PreToolUse" in saved["hooks"]- assert "PostToolUse" in saved["hooks"]+ assert "PreToolUse" not in saved["hooks"]+ assert _post_repowise_entries(saved) == [("Bash|Grep|Glob", "repowise-augment")]-def test_install_claude_code_hooks_merges_valid_existing_file(+def test_install_claude_code_hooks_preserves_user_pretool_hooks(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:+ """User-defined PreToolUse hooks (non-repowise) are never touched."""monkeypatch.setattr(Path, "home", lambda: tmp_path)settings_path = tmp_path / ".claude" / "settings.json"settings_path.parent.mkdir(parents=True)@@ -130,21 +153,25 @@ def test_install_claude_code_hooks_merges_valid_existing_file(saved = json.loads(settings_path.read_text(encoding="utf-8"))assert saved["permissions"] == {"allow": ["Bash(git status:*)"]}+ # User's PreToolUse Read hook stays intact.assert saved["hooks"]["PreToolUse"][0]["matcher"] == "Read"- assert any(- hook["command"] == "repowise-augment"- for entry in saved["hooks"]["PreToolUse"]- for hook in entry["hooks"]- )- assert "PostToolUse" in saved["hooks"]+ assert saved["hooks"]["PreToolUse"][0]["hooks"][0]["command"] == "echo read"+ # PostToolUse now has the repowise hook.+ assert _post_repowise_entries(saved) == [("Bash|Grep|Glob", "repowise-augment")]+++# ---------------------------------------------------------------------------+# install_claude_code_hooks — migrating existing repowise installs+# ----------------------------------------------------------------------------def test_install_claude_code_hooks_migrates_legacy_command(+def test_install_claude_code_hooks_migrates_pre_0_6_1_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."""+ """Pre-0.6.1 entries used the legacy ``repowise augment`` Click command.+ Installer should drop the PreToolUse repowise entry entirely (the new+ design moves enrichment to PostToolUse) and rewrite + widen the+ PostToolUse entry to ``Bash|Grep|Glob`` with ``repowise-augment``."""monkeypatch.setattr(Path, "home", lambda: tmp_path)settings_path = tmp_path / ".claude" / "settings.json"settings_path.parent.mkdir(parents=True)@@ -177,25 +204,74 @@ def test_install_claude_code_hooks_migrates_legacy_command(assert mcp_config.install_claude_code_hooks() == settings_pathsaved = 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"]+ assert "PreToolUse" not in saved["hooks"]+ assert _post_repowise_entries(saved) == [("Bash|Grep|Glob", "repowise-augment")]+++def test_install_claude_code_hooks_migrates_pre_0_6_2_matcher(+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch+) -> None:+ """0.6.1 entries had ``repowise-augment`` already but kept matcher=Bash.+ The matcher should widen to ``Bash|Grep|Glob`` so the same hook covers+ Grep/Glob enrichment too."""+ 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"))+ assert "PreToolUse" not in saved["hooks"]+ assert _post_repowise_entries(saved) == [("Bash|Grep|Glob", "repowise-augment")]+++def test_install_claude_code_hooks_idempotent_on_current_shape(+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch+) -> 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()+ first = (tmp_path / ".claude" / "settings.json").read_text(encoding="utf-8")+ mcp_config.install_claude_code_hooks()+ second = (tmp_path / ".claude" / "settings.json").read_text(encoding="utf-8")+ assert first == second-def test_migrate_claude_code_hooks_rewrites_legacy_command(+# ---------------------------------------------------------------------------+# migrate_claude_code_hooks — self-heal path+# ---------------------------------------------------------------------------+++def test_migrate_claude_code_hooks_handles_full_legacy_payload(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."""+ """Self-heal on a pre-0.6.1 settings.json: drop PreToolUse repowise+ entry, migrate command + matcher on PostToolUse, write back."""monkeypatch.setattr(Path, "home", lambda: tmp_path)settings_path = tmp_path / ".claude" / "settings.json"settings_path.parent.mkdir(parents=True)@@ -228,35 +304,59 @@ def test_migrate_claude_code_hooks_rewrites_legacy_command(assert mcp_config.migrate_claude_code_hooks() is Truesaved = 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"]+ assert "PreToolUse" not in saved["hooks"]+ assert _post_repowise_entries(saved) == [("Bash|Grep|Glob", "repowise-augment")]- # Idempotent: a second run finds nothing to do and returns False.+ # Idempotent: a second run finds nothing to do.assert mcp_config.migrate_claude_code_hooks() is False-def test_migrate_claude_code_hooks_noop_when_already_migrated(+def test_migrate_claude_code_hooks_preserves_user_sibling_hook(+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch+) -> None:+ """A PreToolUse entry with a user-defined sibling hook in the same+ matcher block should keep the sibling and only drop the repowise hook."""+ 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"},+ {"type": "command", "command": "echo hi"},+ ],+ }+ ],+ }+ }+ ),+ encoding="utf-8",+ )++ assert mcp_config.migrate_claude_code_hooks() is True+ saved = json.loads(settings_path.read_text(encoding="utf-8"))+ pre = saved["hooks"]["PreToolUse"]+ assert len(pre) == 1+ assert [h["command"] for h in pre[0]["hooks"]] == ["echo hi"]+++def test_migrate_claude_code_hooks_noop_when_already_current(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:- """Must not rewrite settings.json when the new command is already in place."""+ """No write when settings.json is already in the current shape."""monkeypatch.setattr(Path, "home", lambda: tmp_path)settings_path = tmp_path / ".claude" / "settings.json"settings_path.parent.mkdir(parents=True)payload = {"hooks": {- "PreToolUse": [+ "PostToolUse": [{- "matcher": "Grep|Glob",+ "matcher": "Bash|Grep|Glob","hooks": [{"type": "command", "command": "repowise-augment"}],}]@@ -267,7 +367,6 @@ def test_migrate_claude_code_hooks_noop_when_already_migrated(mtime_before = settings_path.stat().st_mtime_nsassert 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") == originalassert settings_path.stat().st_mtime_ns == mtime_before@@ -276,15 +375,12 @@ 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 Falsedef 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)