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
fix(cli): report what a surface is actually doing, not what it once did (#1343)
Raghav Chamadiyad63a5fcb8e31
diff --git a/docs/reference/CLI_REFERENCE.md b/docs/reference/CLI_REFERENCE.mdindex 01225cebf..11a6083a0 100644--- a/docs/reference/CLI_REFERENCE.md+++ b/docs/reference/CLI_REFERENCE.md@@ -744,7 +744,7 @@ distill filters.|------|-------------|| `--by` | Grouping: `filter` (default), `day`, `source` || `--since` | Only count savings since this ISO date |-| `--model` | Pricing model for the dollar estimate (input-token rate; default `claude-sonnet-4-6`) |+| `--model` | Pricing model for the dollar estimate (input-token rate). Defaults to the model detected from this repo's most recent agent session, falling back to `claude-sonnet-4-6` || `--missed` | Report commands that looked distillable but weren't rewritten || `--missed-days` | Window in days for `--missed` (default 7.0) |diff --git a/packages/cli/src/repowise/cli/agent_adapters/base.py b/packages/cli/src/repowise/cli/agent_adapters/base.pyindex a8d7a0e49..b484ab57c 100644--- a/packages/cli/src/repowise/cli/agent_adapters/base.py+++ b/packages/cli/src/repowise/cli/agent_adapters/base.py@@ -47,6 +47,80 @@ class RewriteResult:self.reason = reason+class RewriteHookStatus:+ """What an installed rewrite hook will actually do.++ ``installed`` keys on the hook *command*, which is what makes an entry+ ours. ``unmatched`` answers the separate question the command cannot: of+ the tool names this agent runs commands with, which does the entry's+ matcher fail to select? An entry left behind by an upstream tool rename is+ registered and fires on some or none of them, and all three states read as+ "installed" until they are reported apart.+ """++ __slots__ = ("fires", "installed", "matcher", "unmatched")++ def __init__(+ self,+ installed: bool,+ matcher: str | None,+ unmatched: tuple[str, ...] = (),+ fires: bool = False,+ ) -> None:+ self.installed = installed+ #: The matcher as written in the agent's config; ``""`` when the entry+ #: carries none, which every agent here reads as match-all.+ self.matcher = matcher+ #: Shell tool names, sorted, that this matcher provably does not+ #: select. Empty when it selects all of them *and* when there is+ #: nothing to check against — an unknowable case must not read as a+ #: broken hook, because claiming a working hook is dead is the worse+ #: error of the two.+ self.unmatched = unmatched+ #: True unless the matcher selects *none* of them, which is a hook+ #: that runs for nothing at all. A matcher that selects some but not+ #: all still fires, and still misses ``unmatched``. Derived when+ #: nothing is unmatched, so a caller cannot accidentally construct an+ #: installed hook that misses nothing and claims not to fire.+ self.fires = fires or (installed and not unmatched)+++#: Characters that keep a matcher in the plain-list dialect. Anything outside+#: this set makes the agent read the matcher as a regular expression.+_PLAIN_MATCHER_CHARS = frozenset(+ "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789_- ,|"+)+++def unmatched_tool_names(matcher: str | None, names: frozenset[str]) -> tuple[str, ...]:+ """Which of *names* the matcher does not select, sorted.++ Two dialects, and getting the split wrong is the one failure that matters+ here — reporting a working hook dead is worse than missing a dead one, so+ every uncertain case resolves to "selected".++ A matcher of letters, digits, ``_``, ``-``, spaces, commas and ``|`` is a+ plain list of tool names, matched exactly. Anything else is a regular+ expression, and an **unanchored** one: ``Shell$`` selects ``PowerShell``.+ Anchoring it here would call that matcher inert while the agent happily+ fires on it. A pattern that will not compile falls back to the list+ reading. An absent matcher is match-all, and an agent that declares no+ tool names is no evidence at all; both answer with nothing missing.+ """+ import re++ if not matcher or not names:+ return ()+ if set(matcher) <= _PLAIN_MATCHER_CHARS:+ listed = {part.strip() for part in matcher.replace(",", "|").split("|")}+ return tuple(sorted(n for n in names if n not in listed))+ try:+ pattern = re.compile(matcher)+ except re.error:+ return tuple(sorted(n for n in names if n != matcher.strip()))+ return tuple(sorted(n for n in names if not pattern.search(n)))++class AgentAdapter(ABC):"""Everything agent-specific about the command-rewrite hook.@@ -66,6 +140,12 @@ class AgentAdapter(ABC):#: rather than silently escalating them to an unprompted rewrite.rewrite_permissions: ClassVar[frozenset[str]] = frozenset({"ask", "allow"})+ #: Tool names this agent uses to run a shell command. The installed hook's+ #: matcher is derived from this set and checked back against it, so an+ #: upstream rename cannot leave a matcher and a gate disagreeing in+ #: silence. Empty means the adapter declines to say.+ shell_tool_names: ClassVar[frozenset[str]] = frozenset()+@abstractmethoddef detect(self) -> bool:"""True when this agent appears to be installed for the current user."""@@ -93,3 +173,29 @@ class AgentAdapter(ABC):@abstractmethoddef rewrite_hook_installed(self) -> bool:"""True when the rewrite hook is currently registered."""++ def rewrite_hook_matcher(self) -> str | None:+ """The installed entry's tool matcher, or None when not installed.++ ``""`` means the entry carries no matcher. An adapter that cannot+ report one leaves this at None and gets the presence answer, which is+ what this method refines and is never worse than.+ """+ return None++ def rewrite_hook_status(self) -> RewriteHookStatus:+ """Whether the rewrite hook is registered *and* still points at a tool.++ One config read, not two: an adapter that can report a matcher answers+ presence with the same lookup, so the two can never disagree about a+ file being rewritten underneath them. Only an adapter that cannot+ report one falls back to the separate presence check.+ """+ matcher = self.rewrite_hook_matcher()+ if matcher is None:+ if not self.rewrite_hook_installed():+ return RewriteHookStatus(False, None)+ matcher = "" # installed, but this adapter cannot say on what+ unmatched = unmatched_tool_names(matcher, self.shell_tool_names)+ fires = not self.shell_tool_names or len(unmatched) < len(self.shell_tool_names)+ return RewriteHookStatus(True, matcher, unmatched, fires)diff --git a/packages/cli/src/repowise/cli/agent_adapters/claude_code.py b/packages/cli/src/repowise/cli/agent_adapters/claude_code.pyindex 0b28a3ec9..1afe14047 100644--- a/packages/cli/src/repowise/cli/agent_adapters/claude_code.py+++ b/packages/cli/src/repowise/cli/agent_adapters/claude_code.py@@ -20,9 +20,22 @@ if TYPE_CHECKING:from pathlib import Path+#: Every name Claude Code gives the tool that carries a shell command string.+#: ``PowerShell`` is the Windows one and has the same payload shape. Kept as a+#: set, and the installed matcher is derived from it below, for the reason the+#: Codex adapter states at length: a rename upstream is silent here, because a+#: gate that stops matching looks exactly like a hook with nothing to say.+SHELL_TOOL_NAMES: frozenset[str] = frozenset({"Bash", "PowerShell"})++#: The same set as a settings.json matcher. Derived rather than written twice.+SHELL_TOOL_MATCHER: str = "|".join(sorted(SHELL_TOOL_NAMES))++class ClaudeCodeAdapter(AgentAdapter):name: ClassVar[str] = "claude-code"+ shell_tool_names: ClassVar[frozenset[str]] = SHELL_TOOL_NAMES+def detect(self) -> bool:return os.path.isdir(os.path.expanduser("~/.claude"))@@ -36,7 +49,7 @@ class ClaudeCodeAdapter(AgentAdapter):if payload.get("hook_event_name") != "PreToolUse":return Nonetool_name = payload.get("tool_name")- if tool_name not in ("Bash", "PowerShell"):+ if tool_name not in SHELL_TOOL_NAMES:return Nonetool_input = payload.get("tool_input")command = tool_input.get("command") if isinstance(tool_input, dict) else None@@ -81,3 +94,10 @@ class ClaudeCodeAdapter(AgentAdapter):)return claude_code_rewrite_hook_installed()++ def rewrite_hook_matcher(self) -> str | None:+ from repowise.cli.editor_integrations.claude_config import (+ claude_code_rewrite_hook_matcher,+ )++ return claude_code_rewrite_hook_matcher()diff --git a/packages/cli/src/repowise/cli/agent_adapters/codex.py b/packages/cli/src/repowise/cli/agent_adapters/codex.pyindex 4e6b8a871..ab905d4b7 100644--- a/packages/cli/src/repowise/cli/agent_adapters/codex.py+++ b/packages/cli/src/repowise/cli/agent_adapters/codex.py@@ -61,6 +61,8 @@ SHELL_TOOL_MATCHER: str = "|".join(sorted(SHELL_TOOL_NAMES))class CodexAdapter(AgentAdapter):name: ClassVar[str] = "codex"+ shell_tool_names: ClassVar[frozenset[str]] = SHELL_TOOL_NAMES+#: No ask-with-mutation in the Codex hook protocol — see module docstring.rewrite_permissions: ClassVar[frozenset[str]] = frozenset({"allow"})@@ -133,3 +135,10 @@ class CodexAdapter(AgentAdapter):)return codex_rewrite_hook_installed()++ def rewrite_hook_matcher(self) -> str | None:+ from repowise.cli.editor_integrations.codex_config import (+ codex_rewrite_hook_matcher,+ )++ return codex_rewrite_hook_matcher()diff --git a/packages/cli/src/repowise/cli/commands/doctor_cmd/repo_checks.py b/packages/cli/src/repowise/cli/commands/doctor_cmd/repo_checks.pyindex 6deb712be..b2e1d1d5f 100644--- a/packages/cli/src/repowise/cli/commands/doctor_cmd/repo_checks.py+++ b/packages/cli/src/repowise/cli/commands/doctor_cmd/repo_checks.py@@ -780,7 +780,20 @@ def _distill_checks(repo_path: _DoctorPath) -> list[DoctorCheck]:codex = CodexAdapter()if codex.detect():surfaces.append(("codex", codex))- installed_names = [name for name, a in surfaces if a.rewrite_hook_installed()]+ # Registered and live are different questions: an entry whose matcher+ # predates a tool rename is registered and fires on some or none of+ # the agent's shell tools. Say which, rather than calling all three+ # "installed".+ installed_names = []+ for name, adapter in surfaces:+ status = adapter.rewrite_hook_status()+ if not status.installed:+ continue+ if not status.unmatched:+ installed_names.append(name)+ else:+ misses = ", ".join(status.unmatched)+ installed_names.append(f"{name} (matcher misses {misses})")if installed_names:commands_cfg = distill_cfg.get("commands") if isinstance(distill_cfg, dict) else Noneopted_out = isinstance(commands_cfg, dict) and commands_cfg.get("enabled") is Falsediff --git a/packages/cli/src/repowise/cli/commands/hook_cmd.py b/packages/cli/src/repowise/cli/commands/hook_cmd.pyindex 7594543d5..3e202513e 100644--- a/packages/cli/src/repowise/cli/commands/hook_cmd.py+++ b/packages/cli/src/repowise/cli/commands/hook_cmd.py@@ -128,6 +128,32 @@ def _target_repo_paths(target) -> list:return [target.repo_path] if (target.repo_path / ".repowise").is_dir() else []+def _print_rewrite_hook_status(label: str, status) -> None:+ """Report one agent's rewrite hook, separating registered from live.++ Presence keys on the hook command, so an entry whose matcher names a tool+ the agent has since renamed reads as "installed" while firing on nothing.+ A hook that matches nothing is silent in exactly the way a working one is,+ which is why this has to be said rather than inferred.+ """+ if not status.installed:+ console.print(f" [dim]✗[/dim] {label} rewrite hook: not installed")+ return+ if not status.unmatched:+ console.print(f" [green]✓[/green] {label} rewrite hook: installed")+ return+ missed = ", ".join(status.unmatched)+ state = "registered but inert" if not status.fires else "installed, matcher too narrow"+ console.print(f" [yellow]![/yellow] {label} rewrite hook: {state}")+ console.print(+ f" [dim]its matcher ({status.matcher!r}) does not select {missed}, so "+ f"commands {label} runs under {'that name' if len(status.unmatched) == 1 else 'those names'} "+ "pass through unrewritten. `repowise hook rewrite install` repoints a "+ "matcher it recognises as its own; a hand-narrowed one has to be "+ "widened by hand.[/dim]"+ )++def _codex_capability_note(version, supports) -> str:"""One honest line about what the local Codex build can actually do."""from repowise.cli.editor_integrations.codex_config import CODEX_REWRITE_MIN_VERSION@@ -341,11 +367,7 @@ def rewrite_status(path: str | None, workspace: bool, no_workspace: bool) -> Nonfrom repowise.cli.agent_adapters.claude_code import ClaudeCodeAdapterfrom repowise.cli.agent_adapters.codex import CodexAdapter- installed = ClaudeCodeAdapter().rewrite_hook_installed()- icon = "[green]✓[/green]" if installed else "[dim]✗[/dim]"- console.print(- f" {icon} claude-code rewrite hook: {'installed' if installed else 'not installed'}"- )+ _print_rewrite_hook_status("claude-code", ClaudeCodeAdapter().rewrite_hook_status())codex = CodexAdapter()if not codex.detect():@@ -360,11 +382,7 @@ def rewrite_status(path: str | None, workspace: bool, no_workspace: bool) -> Nonversion = codex_cli_version()supports = codex_supports_rewrite(version)- codex_installed = codex.rewrite_hook_installed()- icon = "[green]✓[/green]" if codex_installed else "[dim]✗[/dim]"- console.print(- f" {icon} codex rewrite hook: {'installed' if codex_installed else 'not installed'}"- )+ _print_rewrite_hook_status("codex", codex.rewrite_hook_status())console.print(f" [dim]{_codex_capability_note(version, supports)}[/dim]")target = _hook_target(path, workspace, no_workspace)@@ -547,7 +565,11 @@ def hook_stats(path: str | None, as_json: bool) -> None:"""import json as json_mod- from repowise.core.sessions.efficacy import CLASSIFIED_SURFACES, NO_ACTION_EXPECTED+ from repowise.core.sessions.efficacy import (+ CLASSIFIED_SURFACES,+ NO_ACTION_EXPECTED,+ RETIRED_CATEGORIES,+ )from repowise.core.sessions.staging import SessionStagingStore, default_store_pathtarget = resolve_command_target(path=path, workspace_flag=False, no_workspace_flag=True)@@ -570,6 +592,10 @@ def hook_stats(path: str | None, as_json: bool) -> None:returnif as_json:+ # The machine-readable twin carries the same lie the table did, so it+ # gets the same label rather than a footer nothing can parse.+ for row in rows:+ row["retired"] = (row["surface"], row["category"]) in RETIRED_CATEGORIESconsole.print_json(json_mod.dumps({"surfaces": rows, "runs": by_tool, "decision_feedback": feedback}))@@ -589,7 +615,13 @@ def hook_stats(path: str | None, as_json: bool) -> None:for row in rows:pair = (row["surface"], row["category"])classified = row["evaluated"]- if row["surface"] not in CLASSIFIED_SURFACES:+ retired = pair in RETIRED_CATEGORIES+ if retired:+ # A closed population. Its firings and cost are real history and+ # stay visible; its rate is not a rate, because the denominator+ # stopped growing when the emission was deleted.+ acted, rate = "-", "[dim]retired[/dim]"+ elif row["surface"] not in CLASSIFIED_SURFACES:# Decision rows are judged as followed-vs-contradicted against the# decision records, not as acted-on; read_enrich never emits.acted, rate = "-", "[dim]n/a[/dim]"@@ -603,19 +635,25 @@ def hook_stats(path: str | None, as_json: bool) -> None:colour = "green" if pct >= 20 else ("yellow" if pct >= 5 else "red")rate = f"[{colour}]{pct:.1f}%[/{colour}]"n = row["duration_ms_count"]+ # Dimming the whole row is what makes a retired surface legible at a+ # glance; the rate cell alone is too easy to read past.+ lo, hi = ("[dim]", "[/dim]") if retired else ("", "")+ label = f"{row['surface']}/{row['category']}" if row["category"] else row["surface"]table.add_row(- f"{row['surface']}/{row['category']}" if row["category"] else row["surface"],- str(row["firings"]),- str(row["sessions"]),- acted,+ f"{lo}{label}{hi}",+ f"{lo}{row['firings']}{hi}",+ f"{lo}{row['sessions']}{hi}",+ acted if acted == "-" else f"{lo}{acted}{hi}",rate,- f"~{row['chars'] // 4}t",- f"{row['duration_ms_total'] // n}" if n else "[dim]-[/dim]",+ f"{lo}~{row['chars'] // 4}t{hi}",+ f"{lo}{row['duration_ms_total'] // n}{hi}" if n else "[dim]-[/dim]",)console.print(table)console.print(- " [dim]rate is over classified firings only; 'n/a' marks a notice with no "- "action to take, and read/reread counts as respected-not-re-offended.[/dim]"+ " [dim]rate is over classified firings only, and 'n/a' marks a notice "+ "with no action to take. Dimmed 'retired' rows are history: the "+ "emission is gone, so the counts cannot grow and the rate is not "+ "adoption.[/dim]")# The decision surface's own verdict, which the acted-on rate above cannotdiff --git a/packages/cli/src/repowise/cli/commands/saved_cmd.py b/packages/cli/src/repowise/cli/commands/saved_cmd.pyindex 3756216f9..211efa0aa 100644--- a/packages/cli/src/repowise/cli/commands/saved_cmd.py+++ b/packages/cli/src/repowise/cli/commands/saved_cmd.py@@ -23,8 +23,9 @@ from rich.table import Tablefrom repowise.cli.helpers import console-#: Pricing model used for the dollar estimate. Saved tokens are input-side-#: tokens the coding agent never had to read, so the input rate applies.+#: Fallback pricing model for the dollar estimate. Saved tokens are input-side+#: tokens the coding agent never had to read, so the input rate applies. Used+#: only when no agent session can be detected — see :func:`_resolve_pricing`.DEFAULT_PRICING_MODEL = "claude-sonnet-4-6"@@ -47,10 +48,13 @@ DEFAULT_PRICING_MODEL = "claude-sonnet-4-6"@click.option("--model","pricing_model",- default=DEFAULT_PRICING_MODEL,- show_default=True,+ default=None,metavar="MODEL",- help="Pricing model for the dollar estimate (input-token rate).",+ help=(+ "Pricing model for the dollar estimate (input-token rate). Defaults to "+ "the model detected from this repo's most recent agent session, and "+ f"falls back to {DEFAULT_PRICING_MODEL} when there is none."+ ),)@click.option("--missed",@@ -70,7 +74,7 @@ def saved_command(path: str | None,group_by: str,since: str | None,- pricing_model: str,+ pricing_model: str | None,show_missed: bool,missed_days: float,) -> None:@@ -86,6 +90,7 @@ def saved_command(since_ts = _parse_since(since)start = Path(path).resolve() if path else Path.cwd()+ pricing_model, pricing_note = _resolve_pricing(start, pricing_model)if show_missed:_print_missed_report(start, missed_days, pricing_model)@@ -158,7 +163,7 @@ def saved_command(console.print(table)console.print(f" Estimated saved: [bold green]${usd:.4f}[/bold green] "- f"[dim](at ${rate:.2f}/M input tokens, {pricing_model}; "+ f"[dim](at ${rate:.2f}/M input tokens, {pricing_note}; "f"tokens are chars/4 estimates)[/dim]")console.print(f" [dim]Ledger: {db_path}[/dim]")@@ -411,20 +416,48 @@ def _render_missed_distill_table(console.print()+def _resolve_pricing(repo_root: Path, override: str | None) -> tuple[str, str]:+ """The model to price saved tokens at, and how it was arrived at.++ The Costs endpoint has always priced this ledger at the model detected from+ the repo's most recent agent session; this command assumed Sonnet. Same+ tokens, two dollar figures, on two surfaces a reader takes for one — and+ the assumed one understates an Opus session by two thirds. Detection is+ shared with the endpoint rather than reimplemented, and any failure lands+ on the documented default rather than an error.+ """+ if override:+ return override, override+ try:+ from repowise.core.distill.session_model import resolve_session_model++ resolved = resolve_session_model(repo_root)+ except Exception:+ return DEFAULT_PRICING_MODEL, f"{DEFAULT_PRICING_MODEL}, assumed"+ return resolved.model, f"{resolved.model}, {resolved.source}"++def _rewrite_hook_installed() -> bool:- """True when any agent surface has the rewrite hook wired up.+ """True when any agent surface has a rewrite hook that can actually fire.Mirrors the doctor check: Claude Code is always considered, Codex only- when it is actually present on the machine.+ when it is actually present on the machine. Registered is not enough — an+ entry whose matcher names a renamed tool fires on nothing, and telling+ someone their hook is installed is the one answer that hides why the rows+ below it are still there."""try:from repowise.cli.agent_adapters.claude_code import ClaudeCodeAdapterfrom repowise.cli.agent_adapters.codex import CodexAdapter- if ClaudeCodeAdapter().rewrite_hook_installed():+ def live(adapter) -> bool:+ status = adapter.rewrite_hook_status()+ return status.installed and not status.unmatched++ if live(ClaudeCodeAdapter()):return Truecodex = CodexAdapter()- return codex.detect() and codex.rewrite_hook_installed()+ return codex.detect() and live(codex)except Exception:return Falsediff --git a/packages/cli/src/repowise/cli/editor_integrations/claude_config.py b/packages/cli/src/repowise/cli/editor_integrations/claude_config.pyindex 6ef5f6bf2..95d0d6055 100644--- a/packages/cli/src/repowise/cli/editor_integrations/claude_config.py+++ b/packages/cli/src/repowise/cli/editor_integrations/claude_config.py@@ -6,6 +6,7 @@ import jsonimport sysfrom pathlib import Path+from repowise.cli.agent_adapters.claude_code import SHELL_TOOL_MATCHERfrom repowise.cli.mcp_config import (generate_mcp_config,load_existing_config,@@ -353,9 +354,12 @@ def install_claude_code_hooks() -> Path | None:_REWRITE_HOOK_COMMAND = "repowise-rewrite"-# Current rewrite PreToolUse matcher; PowerShell is the Windows Claude Code-# shell tool. Legacy Bash-only installs are widened in place.-_REWRITE_MATCHER = "Bash|PowerShell"+# Current rewrite PreToolUse matcher, derived from the adapter's own tool-name+# set so the installed matcher and the gate that reads the payload cannot+# drift apart. Legacy Bash-only installs are widened in place. Safe at module+# scope for the same reason the Codex twin is: the adapter imports this module+# lazily, and its own imports are stdlib only.+_REWRITE_MATCHER = SHELL_TOOL_MATCHER_LEGACY_REWRITE_MATCHERS = ("Bash",)@@ -486,26 +490,47 @@ def uninstall_claude_code_rewrite_hook() -> bool:def claude_code_rewrite_hook_installed() -> bool:"""True when the distill rewrite hook is registered in settings.json."""+ return claude_code_rewrite_hook_matcher() is not None+++def claude_code_rewrite_hook_matcher() -> str | None:+ """The matcher on the installed rewrite entry, or None when not installed.++ ``""`` is a real answer: an entry with no matcher at all. Presence and+ matcher say different things — an entry pointing at a tool name Claude+ Code no longer uses is registered and will never fire.+ """settings_path = _claude_code_settings_path()if not settings_path.exists():- return False+ return Nonetry:existing = load_existing_config(settings_path)except Exception:- return False+ return Nonehooks = existing.get("hooks")if not isinstance(hooks, dict):- return False+ return Nonepre_hooks = hooks.get("PreToolUse")- return isinstance(pre_hooks, list) and _has_rewrite_hook(pre_hooks)+ if not isinstance(pre_hooks, list):+ return None+ return _rewrite_matcher(pre_hooks)def _is_rewrite_hook(hook: dict) -> bool:return _REWRITE_HOOK_COMMAND in hook.get("command", "")+def _rewrite_matcher(hook_list: list) -> str | None:+ """Matcher of the first entry carrying our hook, or None if there is none."""+ for entry in hook_list:+ if any(_is_rewrite_hook(h) for h in entry.get("hooks", [])):+ matcher = entry.get("matcher")+ return matcher if isinstance(matcher, str) else ""+ return None++def _has_rewrite_hook(hook_list: list) -> bool:- return any(_is_rewrite_hook(h) for entry in hook_list for h in entry.get("hooks", []))+ return _rewrite_matcher(hook_list) is not Nonedef _strip_hooks(hook_list: list, predicate) -> bool:diff --git a/packages/cli/src/repowise/cli/editor_integrations/codex_config.py b/packages/cli/src/repowise/cli/editor_integrations/codex_config.pyindex 183e1c330..b7e2ab159 100644--- a/packages/cli/src/repowise/cli/editor_integrations/codex_config.py+++ b/packages/cli/src/repowise/cli/editor_integrations/codex_config.py@@ -226,28 +226,50 @@ def uninstall_codex_rewrite_hook() -> bool:def codex_rewrite_hook_installed() -> bool:"""True when the distill rewrite entry is registered in hooks.json."""+ return codex_rewrite_hook_matcher() is not None+++def codex_rewrite_hook_matcher() -> str | None:+ """The matcher on the installed rewrite entry, or None when not installed.++ ``""`` is a real answer: an entry with no matcher at all. The caller needs+ the matcher and not just its presence because the two say different+ things — an entry whose matcher names a tool Codex has since renamed is+ registered and will never fire.+ """from repowise.cli.mcp_config import load_existing_confighooks_path = _codex_hooks_path()if not hooks_path.exists():- return False+ return Nonetry:existing = load_existing_config(hooks_path)except Exception:- return False+ return Nonehooks = existing.get("hooks")if not isinstance(hooks, dict):- return False+ return Nonepre_hooks = hooks.get("PreToolUse")- return isinstance(pre_hooks, list) and _has_rewrite_hook(pre_hooks)+ if not isinstance(pre_hooks, list):+ return None+ return _rewrite_matcher(pre_hooks)def _is_rewrite_hook(hook: dict) -> bool:return _REWRITE_HOOK_COMMAND in hook.get("command", "")+def _rewrite_matcher(hook_list: list) -> str | None:+ """Matcher of the first entry carrying our hook, or None if there is none."""+ for entry in hook_list:+ if any(_is_rewrite_hook(h) for h in entry.get("hooks", [])):+ matcher = entry.get("matcher")+ return matcher if isinstance(matcher, str) else ""+ return None++def _has_rewrite_hook(hook_list: list) -> bool:- return any(_is_rewrite_hook(h) for entry in hook_list for h in entry.get("hooks", []))+ return _rewrite_matcher(hook_list) is not None# ---------------------------------------------------------------------------diff --git a/packages/core/src/repowise/core/sessions/efficacy.py b/packages/core/src/repowise/core/sessions/efficacy.pyindex 295707c95..d173f1a02 100644--- a/packages/core/src/repowise/core/sessions/efficacy.py+++ b/packages/core/src/repowise/core/sessions/efficacy.py@@ -145,6 +145,21 @@ NO_ACTION_EXPECTED = frozenset(})+#: (surface, category) pairs whose emission has been removed. The judges below+#: stay so a transcript backfill still settles the rows already in the corpus,+#: but nothing new lands here, and a rate over a closed population is not an+#: adoption rate — ``read``/``reread`` reads 100% and ``read``/``skeleton_nudge``+#: 0.2% off populations that stopped growing, and both are indistinguishable+#: from a live surface until they are labelled apart. Historical, not current.+RETIRED_CATEGORIES = frozenset(+ {+ # Retired in the read hook; see ``augment_cmd/read_state.py``.+ ("read", "reread"),+ # Retired on the emission side after the dose measurement.+ ("read", "skeleton_nudge"),+ }+)+#: Firings whose recommended outcome is a *non*-action, scored as compliance#: (did the agent avoid re-offending?) rather than adoption. Same ``acted``#: column, and ``repowise hook stats`` labels these "respected" so the two arediff --git a/tests/unit/cli/test_hook_stats_retired.py b/tests/unit/cli/test_hook_stats_retired.pynew file mode 100644index 000000000..70c135688--- /dev/null+++ b/tests/unit/cli/test_hook_stats_retired.py@@ -0,0 +1,102 @@+"""`repowise hook stats` must not report a retired surface as a live one.++Two of the ledger's rows are closed populations: their emission was deleted+and their judges were kept so a transcript backfill still settles the rows+already in the corpus. The table is data-driven off ``efficacy_rows()`` and+had no liveness concept, so ``read/reread`` rendered 100% and+``read/skeleton_nudge`` 0.2% off denominators that stopped growing — the same+number a working surface and a deleted one produce.+"""++from __future__ import annotations++import json++from click.testing import CliRunner++from repowise.cli.main import cli+from repowise.core.sessions.efficacy import RETIRED_CATEGORIES, ledger_key+from repowise.core.sessions.staging import SessionStagingStore+++def _seed(repo, surface: str, category: str, *, acted: bool) -> None:+ store = SessionStagingStore.open_default(repo)+ try:+ text = f"[repowise] {surface}/{category} emission"+ store.record_firing(+ session_id="sess-1",+ key=ledger_key(surface, category, text),+ surface=surface,+ category=category,+ chars=len(text),+ shown_at=1.0,+ duration_ms=50,+ acted=acted,+ )+ store.commit()+ finally:+ store.close()+++def _repo(tmp_path):+ repo = tmp_path / "repo"+ (repo / ".repowise" / "sessions").mkdir(parents=True)+ return repo+++def _run(repo, *args):+ return CliRunner().invoke(cli, ["hook", "stats", str(repo), *args])+++def test_retired_row_shows_retired_not_a_rate(tmp_path) -> None:+ repo = _repo(tmp_path)+ _seed(repo, "read", "reread", acted=True)+ result = _run(repo)+ assert result.exit_code == 0+ assert "retired" in result.output+ # 100% off a closed population is the exact claim this exists to stop.+ assert "100.0%" not in result.output+++def test_live_row_still_shows_its_rate(tmp_path) -> None:+ repo = _repo(tmp_path)+ _seed(repo, "search", "triage", acted=True)+ result = _run(repo)+ assert result.exit_code == 0+ assert "100.0%" in result.output+++def test_retired_and_live_rows_are_told_apart(tmp_path) -> None:+ repo = _repo(tmp_path)+ _seed(repo, "read", "skeleton_nudge", acted=True)+ _seed(repo, "search", "triage", acted=True)+ result = _run(repo)+ assert result.exit_code == 0+ assert "retired" in result.output+ assert "100.0%" in result.output, "the live row keeps its rate"+++def test_json_labels_retired_rows(tmp_path) -> None:+ # The machine-readable twin carried the same lie; a footer cannot reach it.+ repo = _repo(tmp_path)+ _seed(repo, "read", "reread", acted=True)+ _seed(repo, "search", "triage", acted=True)+ result = _run(repo, "--json")+ assert result.exit_code == 0+ payload = json.loads(result.output)+ by_pair = {(r["surface"], r["category"]): r["retired"] for r in payload["surfaces"]}+ assert by_pair[("read", "reread")] is True+ assert by_pair[("search", "triage")] is False+++def test_every_retired_pair_has_a_judge(tmp_path) -> None:+ """The set names retirements, not deletions.++ A pair listed here without a classifier would stop settling on backfill,+ which is the one thing keeping these rows worth showing at all.+ """+ from repowise.core.sessions.efficacy import _PATTERNS, COMPLIANCE_CATEGORIES++ emitted = {(surface, category) for surface, category, _ in _PATTERNS}+ for pair in RETIRED_CATEGORIES:+ assert pair in emitted or pair in COMPLIANCE_CATEGORIESdiff --git a/tests/unit/distill/test_agent_adapters.py b/tests/unit/distill/test_agent_adapters.pyindex fb8adbbf4..6561d5985 100644--- a/tests/unit/distill/test_agent_adapters.py+++ b/tests/unit/distill/test_agent_adapters.py@@ -12,8 +12,9 @@ import osimport pytest+from repowise.cli.agent_adapters import claude_code as claude_modulefrom repowise.cli.agent_adapters import codex as codex_module-from repowise.cli.agent_adapters.base import RewriteResult+from repowise.cli.agent_adapters.base import RewriteResult, unmatched_tool_namesfrom repowise.cli.agent_adapters.claude_code import ClaudeCodeAdapterfrom repowise.cli.agent_adapters.codex import SHELL_TOOL_MATCHER, CodexAdapterfrom repowise.cli.editor_integrations import claude_config, codex_config@@ -135,6 +136,17 @@ def _pre_hooks(settings_path) -> list:return _read(settings_path).get("hooks", {}).get("PreToolUse", [])+def _write_rewrite_entry(path, matcher: str, command: str) -> None:+ """Seed a config holding our rewrite hook under an arbitrary matcher.++ Both agents keep their PreToolUse entries in the same shape, so one+ helper seeds either settings.json or hooks.json.+ """+ path.parent.mkdir(parents=True, exist_ok=True)+ entry = {"matcher": matcher, "hooks": [{"type": "command", "command": command}]}+ path.write_text(json.dumps({"hooks": {"PreToolUse": [entry]}}), encoding="utf-8")++class TestRewriteHookInstall:def test_fresh_install(self, settings_path) -> None:assert install_claude_code_rewrite_hook() == settings_path@@ -268,6 +280,119 @@ class TestAdapterDelegation:assert adapter.rewrite_hook_installed() is False+class TestUnmatchedToolNames:+ """The predicate that separates a registered hook from a live one.++ A false alarm here is the worst outcome — it tells someone a working hook+ is dead — so the anchoring and dialect cases below are the load-bearing+ ones, not the happy path.+ """++ def test_alternation_covers_both(self) -> None:+ assert unmatched_tool_names("Bash|PowerShell", frozenset({"Bash", "PowerShell"})) == ()++ def test_regex_matchers_are_unanchored(self) -> None:+ # A matcher carrying a regex character is read as an *unanchored*+ # pattern, so `Shell$` genuinely selects `PowerShell`. Anchoring it+ # would report a firing hook as inert.+ names = frozenset({"Bash", "PowerShell"})+ assert unmatched_tool_names("Shell$", names) == ("Bash",)+ assert unmatched_tool_names("ash$", names) == ("PowerShell",)+ assert unmatched_tool_names(".*", names) == ()++ def test_plain_matcher_is_an_exact_list_not_a_substring(self) -> None:+ # The other half of the dialect: with no regex character in it, the+ # matcher is a list of names compared exactly, so a prefix selects+ # nothing.+ assert unmatched_tool_names("Bas", frozenset({"Bash"})) == ("Bash",)+ assert unmatched_tool_names("Bash, PowerShell", frozenset({"Bash", "PowerShell"})) == ()++ def test_narrowed_matcher_names_what_it_misses(self) -> None:+ assert unmatched_tool_names("Bash", frozenset({"Bash", "shell_command"})) == (+ "shell_command",+ )++ def test_stale_literal_misses_everything(self) -> None:+ assert unmatched_tool_names("Bash", frozenset({"shell_command"})) == ("shell_command",)++ def test_absent_matcher_is_match_all(self) -> None:+ assert unmatched_tool_names("", frozenset({"Bash"})) == ()+ assert unmatched_tool_names(None, frozenset({"Bash"})) == ()++ def test_uncompilable_pattern_falls_back_to_equality(self) -> None:+ assert unmatched_tool_names("Bash(", frozenset({"Bash("})) == ()+ assert unmatched_tool_names("Bash(", frozenset({"Bash"})) == ("Bash",)++ def test_adapter_declining_to_say_is_not_evidence(self) -> None:+ assert unmatched_tool_names("anything", frozenset()) == ()+++class TestRewriteHookStatus:+ """Registered and live are different questions, and both get answered.++ A hook that matches nothing is silent in exactly the way a working one is,+ so nothing catches a stale matcher unless the status surface reports it.+ """++ def test_not_installed(self, settings_path, adapter) -> None:+ status = adapter.rewrite_hook_status()+ assert status.installed is False+ assert status.matcher is None+ assert status.unmatched == ()++ def test_fresh_install_is_live(self, settings_path, adapter) -> None:+ install_claude_code_rewrite_hook()+ status = adapter.rewrite_hook_status()+ assert (status.installed, status.fires, status.unmatched) == (True, True, ())++ def test_stale_matcher_is_registered_but_inert(self, settings_path, adapter) -> None:+ # A matcher naming a tool Claude Code does not use: registered under+ # the presence check, and firing on nothing.+ _write_rewrite_entry(settings_path, "Shell", "repowise-rewrite")+ assert claude_code_rewrite_hook_installed() is True+ status = adapter.rewrite_hook_status()+ assert status.installed is True+ assert status.fires is False+ assert status.unmatched == ("Bash", "PowerShell")+ assert status.matcher == "Shell"++ def test_narrowed_matcher_fires_and_still_misses(self, settings_path, adapter) -> None:+ # The Windows half of the surface: a Bash-only entry rewrites nothing+ # a PowerShell agent runs, and reads as fully installed without this.+ _write_rewrite_entry(settings_path, "Bash", "repowise-rewrite")+ status = adapter.rewrite_hook_status()+ assert (status.installed, status.fires) == (True, True)+ assert status.unmatched == ("PowerShell",)++ def test_codex_stale_bash_matcher_is_narrowed(+ self, codex_hooks_path, codex_adapter+ ) -> None:+ # The exact install every Codex user held before the tool-name fix.+ # ``Bash`` stays in the gate because a live hook payload was never+ # captured, so the honest verdict is narrowed rather than dead: it+ # misses ``shell_command``, which is every shell call in 18 real+ # rollouts.+ _write_rewrite_entry(codex_hooks_path, "Bash", "repowise-rewrite --agent codex")+ status = codex_adapter.rewrite_hook_status()+ assert (status.installed, status.fires) == (True, True)+ assert status.unmatched == ("shell_command",)++ def test_codex_fresh_install_is_live(self, codex_hooks_path, codex_adapter) -> None:+ install_codex_rewrite_hook()+ status = codex_adapter.rewrite_hook_status()+ assert (status.installed, status.unmatched) == (True, ())++ def test_installed_matcher_selects_every_gated_tool_name(self) -> None:+ # The pin the Codex fix asked for, now held on both surfaces: the+ # matcher the installer writes and the gate that reads the payload+ # cannot drift apart without failing here.+ for names, matcher in (+ (claude_module.SHELL_TOOL_NAMES, claude_module.SHELL_TOOL_MATCHER),+ (codex_module.SHELL_TOOL_NAMES, codex_module.SHELL_TOOL_MATCHER),+ ):+ assert unmatched_tool_names(matcher, names) == ()++# ---------------------------------------------------------------------------# Codex adapter — payload parsing, rendering, posture limits# ---------------------------------------------------------------------------diff --git a/tests/unit/distill/test_config_and_doctor.py b/tests/unit/distill/test_config_and_doctor.pyindex 582066213..d502ad215 100644--- a/tests/unit/distill/test_config_and_doctor.py+++ b/tests/unit/distill/test_config_and_doctor.py@@ -143,10 +143,18 @@ def _isolate_codex(monkeypatch):@pytest.fixturedef no_real_hook(monkeypatch):- """Keep doctor away from the developer's real ~/.claude/settings.json."""+ """Keep doctor away from the developer's real ~/.claude/settings.json.++ Both entry points are stubbed on purpose. Patching the presence check+ alone worked only while nothing else read the file, and the matcher+ lookup does — leaving the isolation to depend on which of the two a+ caller happens to reach first is how a suite starts passing or failing+ on the machine that runs it.+ """from repowise.cli.agent_adapters.claude_code import ClaudeCodeAdaptermonkeypatch.setattr(ClaudeCodeAdapter, "rewrite_hook_installed", lambda self: False)+ monkeypatch.setattr(ClaudeCodeAdapter, "rewrite_hook_matcher", lambda self: None)def _rows(repo: Path) -> dict[str, tuple[bool, str]]:@@ -195,10 +203,22 @@ def test_doctor_store_over_cap_fails(repo: Path, no_real_hook) -> None:assert "over cap" in rows["Omission store"][1]+def _live_hook(monkeypatch, adapter_cls, unmatched: tuple[str, ...] = ()) -> None:+ """Report *adapter_cls*'s rewrite hook as installed, without reading $HOME.++ Patching only the presence check would leave the matcher lookup reading the+ developer's real settings, which makes the assertion depend on the machine.+ """+ from repowise.cli.agent_adapters.base import RewriteHookStatus++ status = RewriteHookStatus(True, "Bash|PowerShell", unmatched, True)+ monkeypatch.setattr(adapter_cls, "rewrite_hook_status", lambda self: status)++def test_doctor_hook_installed_with_repo_opt_out(repo: Path, monkeypatch) -> None:from repowise.cli.agent_adapters.claude_code import ClaudeCodeAdapter- monkeypatch.setattr(ClaudeCodeAdapter, "rewrite_hook_installed", lambda self: True)+ _live_hook(monkeypatch, ClaudeCodeAdapter)(repo / ".repowise" / "config.yaml").write_text("distill:\n commands:\n enabled: false\n", encoding="utf-8")@@ -210,13 +230,24 @@ def test_doctor_reports_codex_surface_when_installed(repo: Path, monkeypatch) ->from repowise.cli.agent_adapters.claude_code import ClaudeCodeAdapterfrom repowise.cli.agent_adapters.codex import CodexAdapter- monkeypatch.setattr(ClaudeCodeAdapter, "rewrite_hook_installed", lambda self: True)+ _live_hook(monkeypatch, ClaudeCodeAdapter)monkeypatch.setattr(CodexAdapter, "detect", lambda self: True)- monkeypatch.setattr(CodexAdapter, "rewrite_hook_installed", lambda self: True)+ _live_hook(monkeypatch, CodexAdapter)rows = _rows(repo)assert rows["Distill rewrite hook"][1] == "installed: claude-code, codex"+def test_doctor_names_what_a_narrowed_matcher_misses(repo: Path, monkeypatch) -> None:+ # An entry left behind by a tool rename is registered and rewrites only+ # some of what the agent runs. Reporting it as plain "installed" is the+ # answer that hides why nothing is being distilled.+ from repowise.cli.agent_adapters.claude_code import ClaudeCodeAdapter++ _live_hook(monkeypatch, ClaudeCodeAdapter, unmatched=("PowerShell",))+ rows = _rows(repo)+ assert rows["Distill rewrite hook"][1] == "installed: claude-code (matcher misses PowerShell)"++# ---------------------------------------------------------------------------# hook rewrite install/uninstall <-> init opt-out interplay# ---------------------------------------------------------------------------diff --git a/tests/unit/distill/test_saved_cmd.py b/tests/unit/distill/test_saved_cmd.pyindex bd16da064..b8e97a5e1 100644--- a/tests/unit/distill/test_saved_cmd.py+++ b/tests/unit/distill/test_saved_cmd.py@@ -148,11 +148,91 @@ def test_saved_dollar_estimate_uses_input_rate(repo_cwd: Path) -> None:)s.close()# claude-sonnet-4-6 input rate is $3.00/M -> exactly $3.00 for 1M saved.- result = CliRunner().invoke(saved_command, [])+ # Pinned explicitly: the rate is now detected, and a tmp repo happens to+ # have no session to detect, which is not something to assert by accident.+ result = CliRunner().invoke(saved_command, ["--model", "claude-sonnet-4-6"])assert result.exit_code == 0assert "$3.0000" in result.output+class TestPricingModelResolution:+ """Saved tokens must cost what the agent that saved them costs.++ The Costs endpoint has always priced this ledger at the detected session+ model while this command assumed Sonnet, so the same ledger produced two+ dollar figures — and the assumed one understates an Opus session by two+ thirds.+ """++ def test_explicit_model_wins(self, tmp_path: Path) -> None:+ model, note = saved_cmd._resolve_pricing(tmp_path, "gpt-5.4-nano")+ assert model == "gpt-5.4-nano"+ assert note == "gpt-5.4-nano"++ def test_detected_model_is_used_and_named(self, tmp_path: Path, monkeypatch) -> None:+ from repowise.core.distill import session_model++ detected = session_model.ResolvedModel(+ model="claude-opus-5",+ raw="claude-opus-5[1m]",+ agent="claude_code",+ source="detected from Claude Code session",+ )+ monkeypatch.setattr(session_model, "resolve_session_model", lambda *a, **k: detected)+ model, note = saved_cmd._resolve_pricing(tmp_path, None)+ assert model == "claude-opus-5"+ # The reader is told it was detected, not assumed.+ assert note == "claude-opus-5, detected from Claude Code session"++ def test_detection_failure_falls_back_rather_than_raising(+ self, tmp_path: Path, monkeypatch+ ) -> None:+ from repowise.core.distill import session_model++ def boom(*_a, **_k):+ raise RuntimeError("unreadable transcript")++ monkeypatch.setattr(session_model, "resolve_session_model", boom)+ model, note = saved_cmd._resolve_pricing(tmp_path, None)+ assert model == saved_cmd.DEFAULT_PRICING_MODEL+ assert "assumed" in note++ def test_the_fallback_matches_the_resolver_s_own_default(self) -> None:+ # Not asserted by running detection against a tmp path: that reads the+ # real ~/.codex, where a rollout carrying no cwd is kept on purpose,+ # so the assertion would pass or fail on whose machine ran it.+ # `test_session_model.py` owns detection, hermetically, with injected+ # roots. What belongs here is that the two defaults agree.+ from repowise.core.distill.session_model import DEFAULT_MODEL++ assert saved_cmd.DEFAULT_PRICING_MODEL == DEFAULT_MODEL++ def test_detected_rate_reaches_the_dollar_line(self, repo_cwd: Path, monkeypatch) -> None:+ from repowise.core.distill import session_model++ detected = session_model.ResolvedModel(+ model="claude-opus-5",+ raw="claude-opus-5",+ agent="claude_code",+ source="detected from Claude Code session",+ )+ monkeypatch.setattr(session_model, "resolve_session_model", lambda *a, **k: detected)+ s = _store(repo_cwd)+ s.record_saving(+ filter_name="test_output",+ source="cli",+ command="pytest",+ raw_tokens=1_000_000,+ distilled_tokens=0,+ )+ s.close()+ result = CliRunner().invoke(saved_command, [])+ assert result.exit_code == 0+ # Opus input is $5.00/M, not the $3.00 this command used to assume.+ assert "$5.0000" in result.output+ assert "claude-opus-5" in result.output++def test_saved_no_store_prints_hint(repo_cwd: Path) -> None:result = CliRunner().invoke(saved_command, [])assert result.exit_code == 0@@ -226,11 +306,16 @@ def test_missed_tip_names_the_opt_out_when_the_repo_declined(monkeypatch, tmp_padef test_rewrite_hook_installed_degrades_to_false(monkeypatch) -> None:- """A broken or absent adapter must not break `saved --missed`."""+ """A broken or absent adapter must not break `saved --missed`.++ Patches the status call rather than the presence check underneath it:+ that is the entry point now, and stubbing anything shallower would let+ this assertion fall through to the developer's real ~/.claude.+ """import repowise.cli.agent_adapters.claude_code as ccdef boom(self):raise RuntimeError("no adapter here")- monkeypatch.setattr(cc.ClaudeCodeAdapter, "rewrite_hook_installed", boom)+ monkeypatch.setattr(cc.ClaudeCodeAdapter, "rewrite_hook_status", boom)assert saved_cmd._rewrite_hook_installed() is False