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
perf(agent): slim the resident CLAUDE.md block and stop waking hooks on shell commands (#1382)
Raghav Chamadiya5a7a81e025ca
diff --git a/docs/agent/HOOKS.md b/docs/agent/HOOKS.mdindex 097910a1e..a238a21fa 100644--- a/docs/agent/HOOKS.md+++ b/docs/agent/HOOKS.md@@ -21,7 +21,7 @@ crashes or blocks your agent.|------|--------|--------------|----------|--------------|| **Post-commit auto-sync** | git | `repowise hook install` (or the `repowise init` prompt) | every `git commit` | Runs `repowise update` in the background so the wiki tracks your code || **SessionStart context** | Claude Code | `repowise init` | session `startup` / `resume` / `clear` | Live index-freshness line, core-tool trust rule, and the standing decisions relevant to this session |-| **PostToolUse enrichment** | Claude Code | `repowise init` | `Grep` / `Glob` / `Read` / `Edit` / `Write` / `Bash` / `PowerShell` / repowise MCP calls | Graph context on searches, git/edit freshness, read-intelligence notices, and edit-time "governed by" decision notices |+| **PostToolUse enrichment** | Claude Code | `repowise init` | `Grep` / `Glob` / `Read` / `Edit` / `Write` / repowise MCP calls | Graph context on searches, read-intelligence notices, and edit-time "governed by" decision notices || **Wrong-path rescue** | Claude Code | `repowise init` | a `Read` / `Edit` / `Write` / `Grep` / `Glob` / `NotebookEdit` that failed on a path this tree does not have | Names the file when exactly one indexed file carries that basename; silent otherwise || **Command-rewrite (distill)** | Claude Code | `repowise hook rewrite install` (opt-in) | `Bash` / `PowerShell` | Rewrites noisy commands to `repowise distill <cmd>`; auto-allowed by default, set `permission: ask` to approve each one || **Codex context + staleness** | Codex | `repowise init --codex` | SessionStart / UserPromptSubmit / edit / Bash | Reminds Codex to use the MCP tools and flags stale context after edits |@@ -97,8 +97,7 @@ competes at a flat base relevance.### PostToolUse, enrichment on every tool callOne hook covers several jobs, matched on-`Grep`, `Glob`, `Read`, `Edit`, `Write`, `Bash`, `PowerShell`, and repowise MCP-calls:+`Grep`, `Glob`, `Read`, `Edit`, `Write`, and repowise MCP calls:**Grep/Glob enrichment.** When Claude Code runs a broad or zero-result search,repowise appends focused context pulled straight from `wiki.db`:@@ -142,11 +141,6 @@ and Claude Code renders those results without a path prefix, so they are notparsed as a multi-file flood in the first place. And `files_with_matches` resultscarry no match text to replace: the file list is already a digest.-**Git/edit freshness.** After a successful `git commit`, `merge`, `rebase`,-`cherry-pick`, or `pull`, repowise compares `HEAD` against the last indexed commit-in `.repowise/state.json` and, if the wiki is behind, reminds the agent to run-`repowise update` so it never silently works from outdated docs.-**Read-intelligence.** On `Read` of an indexed file, repowise emits a per-filestale-read notice when the file changed after the session's previous read of it,and points at the cheaper `get_context(..., include=["skeleton"])` for@@ -290,9 +284,16 @@ not touch your global `~/.codex/config.toml`):- **SessionStart / UserPromptSubmit** → a short developer note reminding Codex touse the repowise MCP tools for architecture, search, risk, decisions, anddead-code analysis.-- **PostToolUse** (`Bash`, `apply_patch` / `Edit` / `Write`) → flags that indexed- context may be stale after edits or git operations, pointing at `repowise- update`.+- **PostToolUse** (the shell tool, and `apply_patch` / `Edit` / `Write`) → after+ a successful `git commit`, `merge`, `rebase`, `cherry-pick` or `pull`, compares+ `HEAD` against the last indexed commit and flags that indexed context may be+ stale, pointing at `repowise update`.++Codex names its shell tool `shell_command` on current releases and `Bash` on+older ones, so the matcher covers both. The Claude Code hook deliberately does+*not* watch shell commands: it has `Read` / `Grep` / `Glob` tools and a+SessionStart freshness line, so the shell adds cost without adding reach. Codex+has neither, which is why it keeps the surface.Full Codex setup: [CODEX.md](CODEX.md).@@ -332,7 +333,7 @@ and `.codex/hooks.json` (Codex when `--codex` is passed):| Client | Hook type | Matcher | Command ||--------|-----------|---------|---------|| Claude Code | `SessionStart` | `startup\|resume\|clear` | `repowise-augment` [^guard] |-| Claude Code | `PostToolUse` | `Bash\|PowerShell\|Grep\|Glob\|Read\|Edit\|Write\|mcp__.*[Rr]epowise.*__.*` | `repowise-augment` [^guard] |+| Claude Code | `PostToolUse` | `Grep\|Glob\|Read\|Edit\|Write\|mcp__.*[Rr]epowise.*__.*` | `repowise-augment` [^guard] || Claude Code | `PreToolUse` (opt-in) | `Bash\|PowerShell` | `repowise-rewrite` || Codex | `SessionStart` / `UserPromptSubmit` | lifecycle | context reminder || Codex | `PostToolUse` | `Bash`, `apply_patch\|Edit\|Write` | staleness check |diff --git a/packages/cli/src/repowise/cli/editor_integrations/claude_config.py b/packages/cli/src/repowise/cli/editor_integrations/claude_config.pyindex 95d0d6055..f4b3cddec 100644--- a/packages/cli/src/repowise/cli/editor_integrations/claude_config.py+++ b/packages/cli/src/repowise/cli/editor_integrations/claude_config.py@@ -209,17 +209,31 @@ def enable_tool_search_in_claude_code() -> Path | None:# Current augment PostToolUse matcher. Read/Edit/Write power the distill# read-intelligence layer (skeleton replacement + per-file stale-read notices);-# PowerShell is the Windows Claude Code shell tool (same payload shape as-# Bash); the mcp__ pattern feeds the read-after-served ledger (read_enrich)-# and matches the repowise MCP server under any registration name (local,-# plugin, hosted "Repowise"); legacy installs with the narrower matchers-# below are widened in place.-_AUGMENT_MATCHER = "Bash|PowerShell|Grep|Glob|Read|Edit|Write|mcp__.*[Rr]epowise.*__.*"+# the mcp__ pattern feeds the read-after-served ledger (read_enrich) and+# matches the repowise MCP server under any registration name (local, plugin,+# hosted "Repowise"). Installs carrying any matcher below are rewritten to this+# one in place, which is how both a widening and a narrowing reach an existing+# machine without a re-init.+#+# Bash and PowerShell are deliberately absent, on measurement: across one 287+# session corpus they were 51% of hook invocations and 0.7% of emissions, the+# emissions being a post-commit staleness reminder. The cost is process start,+# paid before repowise reads the payload, so no gate inside the handler can+# avoid it — the only lever is the matcher. Shell commands were also paying it+# twice, here and again for the ``repowise-rewrite`` PreToolUse hook.+# SessionStart already carries the freshness line, so what is given up is a+# mid-session commit going unflagged until the next session.+#+# Claude Code only. ``_handle_bash_post`` stays in the augment dispatcher:+# Codex has no Read/Grep/Glob tools and no SessionStart block, so the shell is+# the only surface a hook can reach it on.+_AUGMENT_MATCHER = "Grep|Glob|Read|Edit|Write|mcp__.*[Rr]epowise.*__.*"_LEGACY_AUGMENT_MATCHERS = ("Bash","Bash|Grep|Glob","Bash|Grep|Glob|Read|Edit|Write","Bash|PowerShell|Grep|Glob|Read|Edit|Write",+ "Bash|PowerShell|Grep|Glob|Read|Edit|Write|mcp__.*[Rr]epowise.*__.*",)# SessionStart emits the live index-freshness / trust context block. `compact`diff --git a/packages/cli/src/repowise/cli/hook_ledger.py b/packages/cli/src/repowise/cli/hook_ledger.pyindex 592e8cd36..5b55eda97 100644--- a/packages/cli/src/repowise/cli/hook_ledger.py+++ b/packages/cli/src/repowise/cli/hook_ledger.py@@ -202,8 +202,8 @@ def _record_hook_run("""Count one hook invocation and what it cost. Best-effort, never raises.Every invocation lands here, including the large majority that return- nothing: the matcher covers Read/Edit/Write/Grep/Glob/Bash/PowerShell and- the repowise MCP tools, and a silent run still pays the import cost. The+ nothing: the matcher covers Read/Edit/Write/Grep/Glob and the repowise MCP+ tools, and a silent run still pays the import cost. Theharness only writes a transcript record for hooks that *emitted*, sowithout this counter the silent invocations — the bulk of the bill — areinvisible. Aggregated per (session, event, tool) rather than one row perdiff --git a/packages/cli/src/repowise/cli/mcp_config.py b/packages/cli/src/repowise/cli/mcp_config.pyindex 51c6443e9..dce7d8b0e 100644--- a/packages/cli/src/repowise/cli/mcp_config.py+++ b/packages/cli/src/repowise/cli/mcp_config.py@@ -13,6 +13,8 @@ from pathlib import Pathimport click+from repowise.cli.agent_adapters.codex import SHELL_TOOL_MATCHER+def _looks_transient(path: Path) -> bool:"""True when *path* lives somewhere that won't survive (temp, uvx cache).@@ -138,7 +140,16 @@ def generate_codex_mcp_server_config(repo_path: Path) -> dict[str, object]:def generate_codex_hooks_config() -> dict[str, object]:- """Generate project-local Codex hooks for repowise context and freshness checks."""+ """Generate project-local Codex hooks for repowise context and freshness checks.++ The shell matcher is derived from the adapter rather than spelled here.+ Codex names its shell tool ``shell_command`` on current releases and+ ``Bash`` on older ones, and this function hardcoded ``"Bash"`` alone, so an+ install written by ``repowise init --codex`` registered a matcher that+ selects nothing on a current Codex. A hook whose matcher matches nothing is+ silent in exactly the way a working one is, which is why this survived the+ pass that fixed the same defect in the rewrite hook and the Codex plugin.+ """context_hook = {"type": "command",@@ -157,7 +168,7 @@ def generate_codex_hooks_config() -> dict[str, object]:"SessionStart": [{"matcher": "startup|resume|clear", "hooks": [context_hook]}],"UserPromptSubmit": [{"hooks": [context_hook]}],"PostToolUse": [- {"matcher": "Bash", "hooks": [freshness_hook]},+ {"matcher": SHELL_TOOL_MATCHER, "hooks": [freshness_hook]},{"matcher": "apply_patch|Edit|Write", "hooks": [freshness_hook]},],}diff --git a/packages/core/src/repowise/core/generation/editor_files/tool_table.py b/packages/core/src/repowise/core/generation/editor_files/tool_table.pyindex ea5196e52..3f57b3a59 100644--- a/packages/core/src/repowise/core/generation/editor_files/tool_table.py+++ b/packages/core/src/repowise/core/generation/editor_files/tool_table.py@@ -5,10 +5,27 @@ tool name so a drift test can assert every row names a registered MCP tool(and every default-surface tool has a row) — the table used to be hand-editedprose in the template and silently drifted from the live registry.-Row style: one entry per tool, 1-3 sentences, leading with when to call it.-The load-bearing response fields (symbol_bodies, verified, continuation,-directive, sources) stay named — they are what the trust protocol keys-on. Reference detail lives in docs/agent/MCP_TOOLS.md, not here.+Row style: one entry per tool, **one sentence plus at most one clause**,+leading with when to call it. The load-bearing response fields (symbol_bodies,+verified, continuation, directive, sources) stay named, because a row that+drops them costs the agent a round trip to discover them. Reference detail+lives in docs/agent/MCP_TOOLS.md, not here.++**Length is the constraint, not the feature list.** This table is resident in+the prompt prefix of every session in every repo repowise has indexed, so it is+re-read on every API call: measured at 50.4x on one corpus, which makes a+character here roughly fifty times more expensive than a character in a tool+response. It was 3,402 characters and bought a repowise MCP call before ~1.0%+of edits under Claude Code.++It is kept, and kept short, because the table is what reaches an agent under a+harness that defers MCP schemas. Claude Code defers, so an agent there must+issue a ``ToolSearch`` before a tool is even a candidate, and this table in+CLAUDE.md is the only description it sees until then. Codex loads the schemas+up front and needs the table least, but reads the same AGENTS.md block, so the+rows must stay accurate for both. Adding a sentence here is a real cost; spend+it in the tool's own schema description instead, which is paid only on use.+Budgets in ``tests/unit/server/mcp/test_tool_table_drift.py``."""from __future__ import annotations@@ -18,68 +35,48 @@ TOOL_TABLE_ROWS: dict[str, tuple[str, str]] = {"get_answer": ("get_answer(question)",'First call for any how / where / why question. `confidence: "high"` or '- '`grounding: "extracted"` is content-grounded — cite it directly. When the '- "question names an indexed symbol, `symbol_bodies` carries its full live body "- "(skip the `get_symbol` follow-up). Low confidence returns `best_guesses` with "- "one-line justifications plus `code_rationale` (rationale comments mined live "- "from candidate source).",+ '`grounding: "extracted"` is content-grounded, so cite it directly; '+ "`symbol_bodies` carries full live bodies.",),"get_context": ("get_context(targets=[...])",- "Triage card for files/modules/symbols: summary, signatures, `symbol_id`s, "- "`hotspot` bit. File targets auto-serve a `verified` skeleton (every signature "- "at a fraction of a full Read); `mostly_full` marks files where Read costs "- "little more. Batch targets in one call. Opt-in blocks: "- '`include=["callers"|"callees"|"ownership"|"decisions"|"metrics"]`.',+ "Triage card for files/modules/symbols, serving a `verified` skeleton for "+ 'file targets. Batch targets; `include=["callers"|"callees"|"decisions"|'+ '"metrics"]` for depth.',),"get_symbol": ("get_symbol(id)",- 'One verified body: `"path.py::Name"` (indexed symbol), `"path.py:140-180"` '- '(live range read), or `"repowise#<hex>"` (omission ref). Source arrives in '- "Read's numbered format — treat it as an already-performed Read. `truncated` "- "responses carry a `continuation` naming the exact next range; ambiguous ids "- "return every match in `candidates`. Index misses fall back to live-grep "- "`fallback_lines`.",+ "One verified body: `path.py::Name`, `path.py:140-180`, or `repowise#<hex>`. "+ "Arrives in Read's numbered format; a `truncated` response carries a "+ "`continuation`.",),"search_codebase": ("search_codebase(query)",- "Hybrid search, auto-routed by query shape: identifier → symbol hits (pipe "- "`symbol_id` into `get_symbol`), path → file pages, prose → wiki-semantic. "- "Force with `mode=symbol|path|concept|hybrid`. Concept hits carry a `sources` "- "list; a hit whose sources are `[fts]` only is a keyword match with no "- "semantic agreement — verify it.",+ "Hybrid search, auto-routed by query shape; force with "+ "`mode=symbol|path|concept|hybrid`. A hit whose `sources` are `[fts]` only "+ "has no semantic agreement, so verify it.",),"get_why": ("get_why(query, targets?)",- "Why the code is shaped this way: decision records with evidence and "- "supersession lineage, falling back to git archaeology and `code_rationale` "- "comments. Call before refactors or pattern divergences.",+ "Why the code is shaped this way: decision records, git archaeology, "+ "rationale comments. Call before a refactor or a pattern divergence.",),"get_risk": ("get_risk(targets, changed_files?)",- "What history says about touching these files: churn, owners, co-change "- "partners, blast radius. PR mode (`changed_files`) leads with a `directive` "- "block — read `will_break` / `missing_cochanges` / `missing_tests` / "- "`tests_to_run` first. `tests_to_run` is coverage-backed (the tests the "- "per-test map proves exercise the changed files); empty means unknown, "- "never no tests. To score a whole commit or diff range instead, use "- "`get_change_risk`.",+ "What history says about touching these files. PR mode (`changed_files`) "+ "leads with a `directive`: read `will_break` / `missing_cochanges` / "+ "`missing_tests` / `tests_to_run` first.",),"get_change_risk": ("get_change_risk(revspec, extensions?, exclude_patterns?)",- "Pre-merge defect score for a whole commit or `base..head` range, computed "- "from its diff shape on the live checkout (no index, no LLM). Lead with "- "`risk_percentile` (this change ranked against sampled recent commits), "- "summarized by `review_priority` and `classification`; `score` / "- "`probability` / `level` are the corpus-calibrated fallback. Distinct from "- "`get_risk`, which scores indexed files by path. A `warning` field flags an "- "empty diff (bad revspec or over-tight extension / exclusion filters).",+ "Defect score for a whole commit or `base..head` range, from its diff on the "+ "live checkout. Lead with `risk_percentile`. Scores a range; `get_risk` "+ "scores paths.",),"get_health": ("get_health(targets?, include?)",- "Health scores + findings on three dimensions (defect / maintainability / "- "performance). Self-check the files you touched before finishing; "- '`include=["biomarkers"|"refactoring"|"signals"]` for depth.',+ "Defect / maintainability / performance scores and findings. Self-check the "+ "files you touched before finishing.",),"get_dead_code": ("get_dead_code()",@@ -88,8 +85,8 @@ TOOL_TABLE_ROWS: dict[str, tuple[str, str]] = {),"get_overview": ("get_overview()",- "Architecture map + tool recipes. Call once, first, in an unfamiliar repo; "- "skip it after that.",+ "Architecture map. Call once, first, in an unfamiliar repo; skip it after "+ "that.",),}diff --git a/packages/core/src/repowise/core/generation/templates/agents_md.j2 b/packages/core/src/repowise/core/generation/templates/agents_md.j2index be3efa45f..21895c013 100644--- a/packages/core/src/repowise/core/generation/templates/agents_md.j2+++ b/packages/core/src/repowise/core/generation/templates/agents_md.j2@@ -2,27 +2,15 @@Indexed by [Repowise](https://repowise.dev). Last indexed: {{ data.indexed_at }}{% if data.indexed_commit %} (commit {{ data.indexed_commit }}){% endif %}{% if data.avg_confidence %}. Confidence: {{ (data.avg_confidence * 100) | int }}%.{% endif %}-The MCP tools below serve pre-verified docs, symbols, history, and health from that index. Every response carries `_meta` freshness fields; a `stale_warning` appears only when a file the response actually serves changed after indexing, so silence means current.-### How to work in this repo-- **Pre-edit phase** (locate, understand, assess) is where these tools win: `get_answer` for how/where/why, `search_codebase` to find, `get_context` for a file's map, `get_risk` before touching a hotspot.-- **Edit phase**: reading a file before you edit it is correct and expected. Use these tools to decide *which* files to read and edit, not to replace that read.-- **Noisy commands** (tests, builds, `git log`/`diff`, searches, listings): prefer `repowise distill <cmd>`, the same command with its exit code preserved and errors-first compact output. A `[repowise#<ref>: N lines omitted]` marker is fully recoverable via `repowise expand <ref>` (add `-q <regex>` to filter); never re-run the command to see omitted output.--### Trust protocol--- `verified: true` means the served bytes were checked against the live tree. Never follow it with a re-read of the same lines.-- `get_answer` at `confidence: "high"` or `grounding: "extracted"` is content-grounded: cite it directly. `symbol_bodies`, `quotes`, and `code_rationale` entries are live source, so use them instead of opening the file.-- The **only** re-read triggers: `bounds: "approximate"`, `_meta.stale_warning`, `search_method: "bm25"`, `confidence: "low"`. `index_behind: true` alone is informational; the served content is unaffected by the drift.-- Not valid reasons to re-read: "just to be safe", "to see full context" (use the skeleton or a range read), "the file might have changed" (`verified` already checked).-- For exhaustive literal sweeps (rename every call site) plain text search is unbeatable, so use it. Reach for `get_context(include=["callers"])` when you need the `callers_total`/`callers_truncated` honesty signal instead of a maybe-incomplete grep.+- **Trust the index.** `verified: true` means the bytes were checked against the live tree, so never re-read those lines. Re-read only on `bounds: "approximate"`, `_meta.stale_warning`, `search_method: "bm25"` or `confidence: "low"`; `index_behind: true` alone is informational.+- **Pre-edit, not instead-of-edit.** These tools decide *which* files to read and edit. Reading a file before you edit it is correct and expected.+- **Noisy commands** (tests, builds, `git log`/`diff`, searches, listings): prefer `repowise distill <cmd>`, the same command with its exit code preserved and errors-first output. A `[repowise#<ref>: N lines omitted]` marker is recoverable via `repowise expand <ref>` (add `-q <regex>` to filter); never re-run the command to see omitted output.### Tools{{ data.tool_table_md }}--**Compose them:** low-confidence `get_answer` then read `best_guesses[0].file`; `get_context` shows `hotspot: true` then `get_risk` before editing; `decision_records` titles then `get_why(targets=[...])`; PR review then `get_risk(targets, changed_files)` and read `directive` first. A `tombstone` error means the file moved, so follow `successor_paths`.{% if data.architecture_summary %}### Architecturediff --git a/packages/core/src/repowise/core/generation/templates/claude_md.j2 b/packages/core/src/repowise/core/generation/templates/claude_md.j2index bd8bc86fd..8bf5ba450 100644--- a/packages/core/src/repowise/core/generation/templates/claude_md.j2+++ b/packages/core/src/repowise/core/generation/templates/claude_md.j2@@ -2,27 +2,15 @@Indexed by [Repowise](https://repowise.dev). Last indexed: {{ data.indexed_at }}{% if data.indexed_commit %} (commit {{ data.indexed_commit }}){% endif %}{% if data.avg_confidence %}. Confidence: {{ (data.avg_confidence * 100) | int }}%.{% endif %}-The MCP tools below serve pre-verified docs, symbols, history, and health from that index. Every response carries `_meta` freshness fields; a `stale_warning` appears only when a file the response actually serves changed after indexing — silence means current.-### How to work in this repo-- **Pre-edit phase** (locate, understand, assess) is where these tools win: `get_answer` for how/where/why, `search_codebase` to find, `get_context` for a file's map, `get_risk` before touching a hotspot.-- **Edit phase**: Claude Code requires a raw Read of any file you will Edit — that Read is correct and expected. Use the tools to decide *which* files to read and edit, not to replace the edit-target Read.-- **Noisy commands** (tests, builds, `git log`/`diff`, searches, listings): prefer `repowise distill <cmd>` — same command, exit code preserved, errors-first compact output. A `[repowise#<ref>: N lines omitted]` marker is fully recoverable via `repowise expand <ref>` (add `-q <regex>` to filter); never re-run the command to see omitted output.--### Trust protocol--- `verified: true` → the served bytes were checked against the live tree. Never follow it with a Read of the same lines.-- `get_answer` at `confidence: "high"` or `grounding: "extracted"` is content-grounded: cite it directly. `symbol_bodies`, `quotes`, and `code_rationale` entries are live source — use them instead of opening the file.-- The **only** re-read triggers: `bounds: "approximate"`, `_meta.stale_warning`, `search_method: "bm25"`, `confidence: "low"`. `index_behind: true` alone is informational — the served content is unaffected by the drift.-- Not valid reasons to re-read: "just to be safe", "to see full context" (use the skeleton or a range read), "the file might have changed" (`verified` already checked).-- For exhaustive literal sweeps (rename every call site) plain `Grep` is unbeatable — use it. Reach for `get_context(include=["callers"])` when you need the `callers_total`/`callers_truncated` honesty signal instead of a maybe-incomplete grep.+- **Trust the index.** `verified: true` means the bytes were checked against the live tree, so never re-read those lines. Re-read only on `bounds: "approximate"`, `_meta.stale_warning`, `search_method: "bm25"` or `confidence: "low"`; `index_behind: true` alone is informational.+- **Pre-edit, not instead-of-edit.** These tools decide *which* files to read and edit. Claude Code requires a raw Read of any file you will Edit, and that Read is correct and expected.+- **Noisy commands** (tests, builds, `git log`/`diff`, searches, listings): prefer `repowise distill <cmd>` — same command, exit code preserved, errors-first output. A `[repowise#<ref>: N lines omitted]` marker is recoverable via `repowise expand <ref>` (add `-q <regex>` to filter); never re-run the command to see omitted output.### Tools{{ data.tool_table_md }}--**Compose them:** low-confidence `get_answer` → Read `best_guesses[0].file`; `get_context` shows `hotspot: true` → `get_risk` before editing; `decision_records` titles → `get_why(targets=[...])`; PR review → `get_risk(targets, changed_files)` and read `directive` first. A `tombstone` error means the file moved — follow `successor_paths`.{% if data.architecture_summary %}### Architecturediff --git a/packages/core/src/repowise/core/generation/templates/workspace_claude_md.j2 b/packages/core/src/repowise/core/generation/templates/workspace_claude_md.j2index 371888adb..f36893609 100644--- a/packages/core/src/repowise/core/generation/templates/workspace_claude_md.j2+++ b/packages/core/src/repowise/core/generation/templates/workspace_claude_md.j2@@ -54,10 +54,9 @@ Files that frequently change together across repos — consider reviewing both w### Repowise MCP Tools-These tools work across all repos in this workspace. Pass `repo="alias"` to scope, `repo="all"` for cross-repo queries, or omit for the default repo. Every response carries `_meta` freshness fields; a `stale_warning` appears only when a file the response actually serves changed after indexing — silence means current.+These tools work across all repos in this workspace. Pass `repo="alias"` to scope, `repo="all"` for cross-repo queries, or omit for the default repo.-{{ data.tool_table_md }}--**Workspace-specific:** `get_overview(repo="all")` returns cross-repo topology (co-changes, package deps, API contracts); `get_risk(changed_files=[...])` picks up cross-repo consumers automatically; `get_blast_radius` / `get_conformance` / `get_architecture` cover cross-repo impact, dependency-rule violations, and coupling.+- **Trust the index.** `verified: true` means the bytes were checked against the live tree, so never re-read those lines. Re-read only on `bounds: "approximate"`, `_meta.stale_warning`, `search_method: "bm25"` or `confidence: "low"`; `index_behind: true` alone is informational.+- **Workspace-specific:** `get_overview(repo="all")` returns cross-repo topology (co-changes, package deps, API contracts); `get_risk(changed_files=[...])` picks up cross-repo consumers automatically; `get_blast_radius` / `get_conformance` / `get_architecture` cover cross-repo impact, dependency-rule violations, and coupling.-**Verify when:** `bounds: "approximate"`, `_meta.stale_warning`, `search_method: "bm25"`, or `confidence: "low"`. `index_behind: true` alone is informational — the served content is unaffected. Otherwise trust the response.+{{ data.tool_table_md }}diff --git a/plugins/claude-code/DEVELOPER.md b/plugins/claude-code/DEVELOPER.mdindex 188dfdff2..a621d1357 100644--- a/plugins/claude-code/DEVELOPER.md+++ b/plugins/claude-code/DEVELOPER.md@@ -64,7 +64,7 @@ The `repowise` binary must be on PATH (`/repowise:init` installs it).**`hooks/hooks.json`** — Registers `SessionStart`(`startup|resume|clear` → `repowise-augment`) and `PostToolUse`-(`Bash|PowerShell|Grep|Glob|Read|Edit|Write|mcp__.*[Rr]epowise.*__.*` →+(`Grep|Glob|Read|Edit|Write|mcp__.*[Rr]epowise.*__.*` →`repowise-augment`) so context enrichment works as soon as the plugin isinstalled. This mirrors the hooks `repowise init` writes to`~/.claude/settings.json`; both firing is safe — see "Hook de-duplication".diff --git a/plugins/claude-code/README.md b/plugins/claude-code/README.mdindex eab9c5c4f..255f0b35d 100644--- a/plugins/claude-code/README.md+++ b/plugins/claude-code/README.md@@ -110,7 +110,7 @@ The plugin registers two hooks that run `repowise-augment`:- **`SessionStart`** (`startup|resume|clear`) — emits live index-freshness /trust context at session start.- **`PostToolUse`** after- `Bash|PowerShell|Grep|Glob|Read|Edit|Write|mcp__.*[Rr]epowise.*__.*` —+ `Grep|Glob|Read|Edit|Write|mcp__.*[Rr]epowise.*__.*` —stays silent unless it has something asymmetric to add (rescuing azero-result grep with the closest indexed symbol, ranking a flood ofmatches by graph centrality, flagging a stale read, or recordingdiff --git a/plugins/claude-code/hooks/hooks.json b/plugins/claude-code/hooks/hooks.jsonindex a2b717179..e0ffac121 100644--- a/plugins/claude-code/hooks/hooks.json+++ b/plugins/claude-code/hooks/hooks.json@@ -15,7 +15,7 @@],"PostToolUse": [{- "matcher": "Bash|PowerShell|Grep|Glob|Read|Edit|Write|mcp__.*[Rr]epowise.*__.*",+ "matcher": "Grep|Glob|Read|Edit|Write|mcp__.*[Rr]epowise.*__.*","hooks": [{"type": "command",diff --git a/tests/unit/cli/test_mcp_config.py b/tests/unit/cli/test_mcp_config.pyindex cd0e0c1dc..7c65f6fde 100644--- a/tests/unit/cli/test_mcp_config.py+++ b/tests/unit/cli/test_mcp_config.py@@ -10,6 +10,7 @@ import clickimport pytestfrom repowise.cli import mcp_config+from repowise.cli.agent_adapters import codex as codex_adapterfrom repowise.cli.editor_integrations import claude_config@@ -91,7 +92,12 @@ def test_generate_codex_hooks_config_uses_supported_events_only() -> None:assert set(hooks) == {"SessionStart", "UserPromptSubmit", "PostToolUse"}assert hooks["SessionStart"][0]["matcher"] == "startup|resume|clear"- assert hooks["PostToolUse"][0]["matcher"] == "Bash"+ # Derived from the adapter, never spelled here: Codex calls its shell tool+ # `shell_command` on current releases and `Bash` on older ones, and a+ # matcher naming only `Bash` selects nothing on a current Codex while+ # looking exactly like a working one.+ assert hooks["PostToolUse"][0]["matcher"] == codex_adapter.SHELL_TOOL_MATCHER+ assert "shell_command" in hooks["PostToolUse"][0]["matcher"]assert hooks["PostToolUse"][1]["matcher"] == "apply_patch|Edit|Write"assert [hook["timeout"]@@ -805,6 +811,65 @@ def test_migrate_claude_code_hooks_backfills_session_start(assert claude_config.migrate_claude_code_hooks() is False+def test_migrate_narrows_the_shell_tools_out_of_an_existing_install(+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch+) -> None:+ """Bash and PowerShell are dropped from an install that already has them.++ Every previous matcher change widened, so migration had only ever been+ exercised in that direction. This one narrows: shell tools were 51% of hook+ invocations and 0.7% of emissions, and the cost is interpreter start, which+ no gate inside the hook can avoid. An existing machine has to get the fix+ without a re-init, so the old wide matcher is in the legacy tuple.+ """+ 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": {+ "PostToolUse": [+ {+ "matcher": (+ "Bash|PowerShell|Grep|Glob|Read|Edit|Write"+ "|mcp__.*[Rr]epowise.*__.*"+ ),+ "hooks": [+ {+ "type": "command",+ "command": claude_config._AUGMENT_HOOK_COMMAND,+ }+ ],+ },+ # Somebody else's hook on the same event, carrying the+ # same matcher. Rewriting it would silently change a+ # tool the user pointed it at on purpose.+ {+ "matcher": (+ "Bash|PowerShell|Grep|Glob|Read|Edit|Write"+ "|mcp__.*[Rr]epowise.*__.*"+ ),+ "hooks": [{"type": "command", "command": "node theirs.js"}],+ },+ ]+ }+ }+ ),+ encoding="utf-8",+ )++ assert claude_config.migrate_claude_code_hooks() is True+ saved = json.loads(settings_path.read_text(encoding="utf-8"))+ entries = saved["hooks"]["PostToolUse"]+ assert entries[0]["matcher"] == claude_config._AUGMENT_MATCHER+ assert "Bash" not in entries[0]["matcher"]+ assert "PowerShell" not in entries[0]["matcher"]+ assert entries[1]["matcher"] == (+ "Bash|PowerShell|Grep|Glob|Read|Edit|Write|mcp__.*[Rr]epowise.*__.*"+ )++def test_migrate_backfills_the_failure_hook_for_older_installs(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:diff --git a/tests/unit/generation/test_kg_claude_md_onboarding.py b/tests/unit/generation/test_kg_claude_md_onboarding.pyindex 9b5f93152..54aa6f93e 100644--- a/tests/unit/generation/test_kg_claude_md_onboarding.py+++ b/tests/unit/generation/test_kg_claude_md_onboarding.py@@ -111,15 +111,22 @@ class TestClaudeMdKGSection:tmpl = jinja_env.get_template("claude_md.j2")rendered = tmpl.render(data=self._data())assert "### How to work in this repo" in rendered- assert "### Trust protocol" in rendered+ # The trust rule survives as a bullet rather than its own section. The+ # separate "### Trust protocol" heading was five bullets of protocol for+ # a response shape the agent sees rarely, and it was cut for size; the+ # load-bearing clause is what has to stay reachable.+ assert "`verified: true`" in rendered+ assert "never re-read those lines" in rendered# Pre-edit framing: the mandatory Read of edit targets is conceded.assert "raw Read of any file you will Edit" in rendered# The tool table renders from the single-source module.assert "| Tool | When and why |" in renderedassert "`get_answer(question)`" in rendered- # Protocol comes before the repo-facts data blocks.+ # Protocol comes before the repo-facts data blocks. Anchored on the+ # trust rule rather than on the first heading in the file, which would+ # be ordered correctly by construction and could not fail.if "Entry points" in rendered:- assert rendered.index("Trust protocol") < rendered.index("Entry points")+ assert rendered.index("`verified: true`") < rendered.index("Entry points")# ---------------------------------------------------------------------------diff --git a/tests/unit/server/mcp/test_tool_table_drift.py b/tests/unit/server/mcp/test_tool_table_drift.pyindex 8b7f3f8b9..f600e8cc1 100644--- a/tests/unit/server/mcp/test_tool_table_drift.py+++ b/tests/unit/server/mcp/test_tool_table_drift.py@@ -49,3 +49,43 @@ def test_render_produces_one_row_per_tool():assert md.startswith("| Tool | When and why |")# Header + separator + one line per row.assert len(md.splitlines()) == 2 + len(TOOL_TABLE_ROWS)+++#: Longest a single row's prose may be, and the mean across all rows. This table+#: is resident in the prompt prefix of every session in every indexed repo, so+#: it is re-read on every API call (measured at 50.4x on one corpus). It reached+#: 3,402 characters by one reasonable-looking sentence at a time and was cut to+#: ~1,850 in 2026-08; the budget exists so that regrowth is a decision somebody+#: makes on purpose rather than a drift nobody measures.+#:+#: **Both bounds are needed and the per-row one alone is not enough.** The drift+#: this guards against adds a 30 to 60 character sentence at a time, spread over+#: ten rows, which a per-row ceiling set above the current maximum absorbs+#: completely. The mean is what actually tracks the total, and it is expressed+#: as a mean rather than a total so that adding a tool does not fail the build.+#: Current values: max 179, mean ~145.+_MAX_ROW_CHARS = 200+_MAX_MEAN_ROW_CHARS = 165+++def test_no_row_outgrows_its_budget():+ oversized = {+ name: len(row)+ for name, (_signature, row) in TOOL_TABLE_ROWS.items()+ if len(row) > _MAX_ROW_CHARS+ }+ assert not oversized, (+ f"tool table rows over {_MAX_ROW_CHARS} chars: {oversized}. This text is "+ "resident in every session's prompt prefix; put reference detail in the "+ "tool's own schema description or docs/agent/MCP_TOOLS.md instead."+ )+++def test_the_table_as_a_whole_does_not_creep():+ lengths = [len(row) for _signature, row in TOOL_TABLE_ROWS.values()]+ mean = sum(lengths) / len(lengths)+ assert mean <= _MAX_MEAN_ROW_CHARS, (+ f"mean tool-table row is {mean:.0f} chars, over the {_MAX_MEAN_ROW_CHARS} "+ "budget. A sentence added to every row costs more than any single row "+ "ever will; this is the bound that catches that."+ )