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(distill): Grep-rescue correctness, PowerShell hook coverage, nudge floor, allowlist seeding (#389)
Raghav Chamadiyaf0b55d7757d7
diff --git a/docs/DISTILL.md b/docs/DISTILL.mdindex ce47db804..e9504ecff 100644--- a/docs/DISTILL.md+++ b/docs/DISTILL.md@@ -81,13 +81,42 @@ repowise hook rewrite statusrepowise hook rewrite uninstall # removes only the repowise entry```+The hook covers both Claude Code shell tools — Bash and, on Windows,+PowerShell. Existing installs are widened automatically on the next+`install`/`init`.+The hook is deliberately conservative. It never rewrites:- pipes, redirections, compound commands (`|`, `>`, `&&`, `;`, backticks, `$()`)- watch/follow modes (`--watch`, `tail -f`, …)- anything on the trivial-command ignore-list, or already-prefixed commands+- PowerShell-native constructs: `Verb-Noun` cmdlets, `& "path"` invocations,+ backtick continuations — and, from PowerShell, alias tokens (`ls`, `cat`,+ `find`, …) that don't mean what their unix namesakes mean- commands in repos that have not opted into repowise (no `.repowise/` upward)+**The allowlist trap.** A rewrite changes the command string, so a Claude Code+permission rule you already had — say `Bash(git diff:*)` — no longer matches+the rewritten `repowise distill git diff …`, and the permission prompt comes+back for commands you had already allowed. The fix is one extra allow rule+covering the distill prefix:++```jsonc+// ~/.claude/settings.json+"permissions": {+ "allow": [+ "Bash(repowise distill:*)",+ "PowerShell(repowise distill:*)"+ ]+}+```++`repowise hook rewrite install` offers to add these for you (or pass+`--allow-rule` / `--no-allow-rule` to decide non-interactively). The default+posture stays `ask` — the rule only stops *double*-asking for commands you've+already vetted; `repowise distill` runs the wrapped command unchanged and+never widens what it can do.+Per-repo behavior is configured under `distill.commands` in`.repowise/config.yaml` — see [Configuration](#configuration). Declining the`repowise init` prompt writes `distill.commands.enabled: false`, so a hookdiff --git a/packages/cli/src/repowise/cli/agent_adapters/base.py b/packages/cli/src/repowise/cli/agent_adapters/base.pyindex f0a87ae7f..4e2bde960 100644--- a/packages/cli/src/repowise/cli/agent_adapters/base.py+++ b/packages/cli/src/repowise/cli/agent_adapters/base.py@@ -18,11 +18,16 @@ if TYPE_CHECKING:class RewriteRequest:"""Agent-agnostic view of one shell command an agent is about to run."""- __slots__ = ("command", "cwd")+ __slots__ = ("command", "cwd", "shell")- def __init__(self, command: str, cwd: str) -> None:+ def __init__(self, command: str, cwd: str, shell: str = "posix") -> None:self.command = commandself.cwd = cwd+ #: ``"posix"`` or ``"powershell"`` — which shell dialect the agent+ #: will run the command under. PowerShell commands get extra+ #: classifier bailouts (PS aliases like ``ls`` don't survive a+ #: subprocess wrap through the system shell).+ self.shell = shellclass RewriteResult:diff --git a/packages/cli/src/repowise/cli/agent_adapters/claude_code.py b/packages/cli/src/repowise/cli/agent_adapters/claude_code.pyindex 51fe623f4..0b28a3ec9 100644--- a/packages/cli/src/repowise/cli/agent_adapters/claude_code.py+++ b/packages/cli/src/repowise/cli/agent_adapters/claude_code.py@@ -35,14 +35,19 @@ class ClaudeCodeAdapter(AgentAdapter):return Noneif payload.get("hook_event_name") != "PreToolUse":return None- if payload.get("tool_name") != "Bash":+ tool_name = payload.get("tool_name")+ if tool_name not in ("Bash", "PowerShell"):return Nonetool_input = payload.get("tool_input")command = tool_input.get("command") if isinstance(tool_input, dict) else Noneif not isinstance(command, str) or not command.strip():return Nonecwd = payload.get("cwd")- return RewriteRequest(command=command, cwd=cwd if isinstance(cwd, str) else "")+ return RewriteRequest(+ command=command,+ cwd=cwd if isinstance(cwd, str) else "",+ shell="powershell" if tool_name == "PowerShell" else "posix",+ )def render_response(self, result: RewriteResult) -> str:return json.dumps(diff --git a/packages/cli/src/repowise/cli/commands/augment_cmd.py b/packages/cli/src/repowise/cli/commands/augment_cmd.pyindex 23ac740cf..2f21dd23c 100644--- a/packages/cli/src/repowise/cli/commands/augment_cmd.py+++ b/packages/cli/src/repowise/cli/commands/augment_cmd.py@@ -79,7 +79,8 @@ _RESCUE_TOP_N = 2_DIGEST_THRESHOLD = 50 # grep result lines before the full compact digest_DIGEST_TOP_FILES = 10_READ_NUDGE_MIN_LINES = 100 # Read output lines before a skeleton nudge-_READ_NUDGE_MIN_TOKENS = 800 # full-file tokens below which a nudge is noise+_READ_NUDGE_MIN_TOKENS = 3000 # full-file tokens below which a nudge is noise+_READ_NUDGE_MIN_SAVINGS = 1500 # estimated tokens saved must clear this_READ_NUDGE_MAX_RATIO = 0.5 # skeleton must be at most this fraction of full@@ -248,8 +249,13 @@ def _handle_search_post(if repo_path is None:return None+ result_count = _search_result_count(tool_output)+ if result_count is None:+ # Unknown/unextractable response shape. Skipping is the only safe+ # answer — treating it as zero results would fire a "no match"+ # rescue under a Grep that actually succeeded.+ return Noneoutput_text = _extract_output_text(tool_output)- result_count = _count_search_results(output_text)# A genuine flood gets a compact per-file digest regardless of what the# pattern looks like — it summarizes the actual results, not the concept.@@ -270,6 +276,13 @@ def _handle_search_post(# Decision tree. The skip case is the most common — that's by design.if result_count == 0:+ # Rescue relevance guards. A regex pattern loses its structure in the+ # symbol-lookup sanitizer (`distill|savings` → `distillsavings`), so+ # any "closest symbol" answer would be luck, not signal. And a grep+ # scoped to one non-code file is a config-key check, not a symbol+ # hunt — the wiki has nothing useful to add to either.+ if _looks_like_regex(pattern) or _targets_single_non_code_file(tool_input):+ return Nonemode = "rescue"elif result_count >= _TRIAGE_THRESHOLD:mode = "triage"@@ -422,13 +435,60 @@ def _looks_like_path_lookup(pattern: str) -> bool:return lower.endswith(exts)+def _looks_like_regex(pattern: str) -> bool:+ """Heuristic: pattern uses regex syntax, not a literal symbol name.++ Flags unescaped alternation/class/group openers and the common regex+ idioms (``\\b``, ``.*``, ``.+``) that agents reach for. Escaped literals+ (``\\[``, ``\\|``) stay eligible for rescue.+ """+ import re++ return re.search(r"(?<!\\)[|\[(]|\\b|\.[*+]", pattern) is not None+++# Extensions where a zero-match grep is a config/doc lookup, not a missed+# symbol — rescue would answer a question the agent isn't asking.+_NON_CODE_SUFFIXES = (+ ".yaml",+ ".yml",+ ".json",+ ".jsonc",+ ".toml",+ ".ini",+ ".cfg",+ ".md",+ ".rst",+ ".txt",+ ".lock",+ ".env",+)+++def _targets_single_non_code_file(tool_input: dict) -> bool:+ """True when the Grep was scoped to one non-code file (path or glob)."""+ if not isinstance(tool_input, dict):+ return False+ path = tool_input.get("path")+ if isinstance(path, str) and path.lower().rstrip("/\\").endswith(_NON_CODE_SUFFIXES):+ return True+ glob = tool_input.get("glob")+ return (+ isinstance(glob, str)+ and "*" not in glob+ and "?" not in glob+ and glob.lower().endswith(_NON_CODE_SUFFIXES)+ )++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.+ Claude Code's hook payload shape varies by tool: Bash/PowerShell+ surface ``stdout``/``stderr``, Grep surfaces a structured dict+ (``mode``/``content``/``filenames``), Glob a bare ``filenames`` list.+ We only need a string we can count newlines in, so we accept any of+ the shapes captured from real hook payloads."""if isinstance(tool_output, str):return tool_output@@ -436,7 +496,7 @@ def _extract_output_text(tool_output: object) -> str:return ""for key in ("output", "result", "content", "stdout", "text"):val = tool_output.get(key)- if isinstance(val, str):+ if isinstance(val, str) and val:return valif isinstance(val, list):# Some shapes wrap content as [{"type": "text", "text": "..."}].@@ -450,9 +510,61 @@ def _extract_output_text(tool_output: object) -> str:parts.append(t)if parts:return "\n".join(parts)+ # Grep files_with_matches / Glob: a list of paths, one per line.+ filenames = tool_output.get("filenames")+ if isinstance(filenames, list):+ parts = [f for f in filenames if isinstance(f, str)]+ if parts:+ return "\n".join(parts)return ""+def _search_result_count(tool_output: object) -> int | None:+ """Result count for a Grep/Glob tool_response, or None when unknowable.++ Claude Code's Grep responses are structured dicts whose shape varies by+ output mode (all captured from real PostToolUse payloads):++ content {"mode": "content", "content": str, "numLines": int, ...}+ files_with_matches {"mode": "files_with_matches", "filenames": [...], "numFiles": int}+ count {"mode": "count", "content": str, "numMatches": int, ...}+ Glob {"filenames": [...], "numFiles": int, "truncated": bool}++ Structured counts are trusted as-is — including a genuine zero. For+ anything else we fall back to counting extracted text lines, where a+ zero can only come from an explicit no-match sentinel. An empty or+ unrecognized response returns None: the caller must SKIP, never rescue,+ on a shape we don't positively understand.+ """+ if isinstance(tool_output, dict):+ mode = tool_output.get("mode")+ filenames = tool_output.get("filenames")+ if mode == "files_with_matches" or (+ mode is None and isinstance(filenames, list) and "numFiles" in tool_output+ ):+ num_files = tool_output.get("numFiles")+ if isinstance(num_files, int):+ return num_files+ return len(filenames) if isinstance(filenames, list) else None+ if mode in ("content", "count"):+ count_key = "numLines" if mode == "content" else "numMatches"+ count = tool_output.get(count_key)+ if isinstance(count, int):+ return count+ content = tool_output.get("content")+ if isinstance(content, str):+ return _count_search_results(content) if content.strip() else 0+ return None+ if isinstance(mode, str):+ # A future Grep output mode we don't know — refuse to guess.+ return None++ output_text = _extract_output_text(tool_output)+ if not output_text.strip():+ return None+ return _count_search_results(output_text)++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():@@ -888,6 +1000,10 @@ def _skeleton_nudge(repo_path: Path, rel: str, tool_output: object, state: dict)skeleton_tokens = estimate_skeleton_tokens(bounds, file_size_bytes=size)if skeleton_tokens > full_tokens * _READ_NUDGE_MAX_RATIO:return None+ # A nudge is only worth the agent's attention when acting on it buys a+ # real saving — a few hundred tokens on a mid-size file is noise.+ if full_tokens - skeleton_tokens < _READ_NUDGE_MIN_SAVINGS:+ return Nonestate["nudged"].append(rel)return (@@ -955,7 +1071,9 @@ def _handle_post_tool_use(return Noneif tool_name == "Read":return _handle_read_post(tool_input, tool_output, cwd, session_id)- if tool_name == "Bash":+ if tool_name in ("Bash", "PowerShell"):+ # The PowerShell tool (Windows Claude Code) surfaces the same+ # stdout/stderr response shape as Bash — one handler covers both.return _handle_bash_post(tool_input, tool_output, cwd)if tool_name in ("Grep", "Glob"):return _handle_search_post(tool_name, tool_input, tool_output, cwd)diff --git a/packages/cli/src/repowise/cli/commands/hook_cmd.py b/packages/cli/src/repowise/cli/commands/hook_cmd.pyindex 1c114df01..8d1135c6a 100644--- a/packages/cli/src/repowise/cli/commands/hook_cmd.py+++ b/packages/cli/src/repowise/cli/commands/hook_cmd.py@@ -123,7 +123,19 @@ def rewrite_group() -> None:default=False,help="Force single-repo mode even when invoked from a workspace.",)-def rewrite_install(path: str | None, workspace: bool, no_workspace: bool) -> None:+ "--allow-rule/--no-allow-rule",+ "allow_rule",+ default=None,+ help=(+ "Seed a Claude Code permission allow rule for `repowise distill` "+ "commands so existing allowlist entries keep working after rewrites. "+ "Prompts when omitted (interactive only)."+ ),+)+def rewrite_install(+ path: str | None, workspace: bool, no_workspace: bool, allow_rule: bool | None+) -> None:"""Install the rewrite hook into ~/.claude/settings.json.The hook itself is user-level (one install covers every repo); this@@ -132,6 +144,8 @@ def rewrite_install(path: str | None, workspace: bool, no_workspace: bool) -> Nootherwise — since a prior ``repowise init`` opt-out may have gatedrepos off."""+ import sys+from repowise.cli.agent_adapters.claude_code import ClaudeCodeAdapterfrom repowise.cli.helpers import save_distill_commands_enabled@@ -147,6 +161,31 @@ def rewrite_install(path: str | None, workspace: bool, no_workspace: bool) -> No"in .repowise/config.yaml (permission: ask | allow).[/dim]")+ # A rewrite changes the command string, so a user's existing allowlist+ # entry (e.g. `Bash(git diff:*)`) no longer matches the rewritten+ # `repowise distill git diff …` — every rewrite asks again. Offer to+ # seed an allow rule for the distill prefix; strictly opt-in, the hook+ # posture itself stays `ask`.+ if allow_rule is None and sys.stdin.isatty():+ console.print(+ " [dim]Rewritten commands no longer match your existing Claude Code "+ "allowlist entries (e.g. `Bash(git diff:*)`), so they prompt again.[/dim]"+ )+ allow_rule = click.confirm(+ " Add a permission allow rule for `repowise distill` commands?",+ default=False,+ )+ if allow_rule:+ from repowise.cli.editor_integrations.claude_config import (+ add_claude_code_distill_allow_rules,+ )++ settings = add_claude_code_distill_allow_rules()+ if settings:+ console.print(f" [green]✓[/green] Allow rule added ({settings})")+ else:+ console.print(" [yellow]Could not update permission rules.[/yellow]")+if target.is_workspace:assert target.ws_root is not None and target.ws_config is not Nonefor entry in target.ws_config.repos:diff --git a/packages/cli/src/repowise/cli/editor_integrations/claude_config.py b/packages/cli/src/repowise/cli/editor_integrations/claude_config.pyindex a95c49e66..3137e325c 100644--- a/packages/cli/src/repowise/cli/editor_integrations/claude_config.py+++ b/packages/cli/src/repowise/cli/editor_integrations/claude_config.py@@ -98,9 +98,15 @@ def register_with_claude_code(repo_path: Path) -> Path | None:# Current augment PostToolUse matcher. Read/Edit/Write power the distill# read-intelligence layer (skeleton nudges + per-file stale-read notices);-# legacy installs with the narrower matchers below are widened in place.-_AUGMENT_MATCHER = "Bash|Grep|Glob|Read|Edit|Write"-_LEGACY_AUGMENT_MATCHERS = ("Bash", "Bash|Grep|Glob")+# PowerShell is the Windows Claude Code shell tool (same payload shape as+# Bash); legacy installs with the narrower matchers below are widened in+# place.+_AUGMENT_MATCHER = "Bash|PowerShell|Grep|Glob|Read|Edit|Write"+_LEGACY_AUGMENT_MATCHERS = (+ "Bash",+ "Bash|Grep|Glob",+ "Bash|Grep|Glob|Read|Edit|Write",+)def install_claude_code_hooks() -> Path | None:@@ -155,16 +161,21 @@ 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"+_LEGACY_REWRITE_MATCHERS = ("Bash",)+def install_claude_code_rewrite_hook() -> Path | None:- """Register the opt-in distill PreToolUse rewrite hook (Bash matcher).+ """Register the opt-in distill PreToolUse rewrite hook (shell matcher).Idempotent; preserves user hooks and the augment PostToolUse entry.Returns the settings path on success, None on failure."""settings_path = _claude_code_settings_path()pre_hook_entry = {- "matcher": "Bash",+ "matcher": _REWRITE_MATCHER,"hooks": [{"type": "command",@@ -184,14 +195,73 @@ def install_claude_code_rewrite_hook() -> Path | None:hooks = existing.setdefault("hooks", {})pre_hooks = hooks.setdefault("PreToolUse", [])+ changed = _migrate_legacy_rewrite_matcher(pre_hooks)if not _has_rewrite_hook(pre_hooks):pre_hooks.append(pre_hook_entry)+ changed = True+ if changed:settings_path.write_text(json.dumps(existing, indent=2) + "\n", encoding="utf-8")return settings_pathexcept OSError:return None+# Permission allow rules for rewritten commands. A rewrite changes the+# command string, so the user's existing allowlist entries (e.g.+# ``Bash(git diff:*)``) stop matching the rewritten ``repowise distill …``+# and every approved family starts prompting again. One rule per shell tool+# covers the distill prefix; `repowise distill` runs the wrapped command+# unchanged, so the rule never widens what a command can do.+DISTILL_ALLOW_RULES = (+ "Bash(repowise distill:*)",+ "PowerShell(repowise distill:*)",+)+++def add_claude_code_distill_allow_rules() -> Path | None:+ """Append the distill allow rules to ``permissions.allow`` (idempotent).++ Returns the settings path on success, None when settings.json exists but+ can't be read or written. Strictly additive — user rules are untouched.+ """+ settings_path = _claude_code_settings_path()+ try:+ if settings_path.exists():+ existing = load_existing_config(settings_path)+ else:+ settings_path.parent.mkdir(parents=True, exist_ok=True)+ existing = {}+ except Exception:+ return None++ permissions = existing.setdefault("permissions", {})+ if not isinstance(permissions, dict):+ return None+ allow = permissions.setdefault("allow", [])+ if not isinstance(allow, list):+ return None++ missing = [rule for rule in DISTILL_ALLOW_RULES if rule not in allow]+ if missing:+ allow.extend(missing)+ try:+ settings_path.write_text(json.dumps(existing, indent=2) + "\n", encoding="utf-8")+ except OSError:+ return None+ return settings_path+++def _migrate_legacy_rewrite_matcher(hook_list: list) -> bool:+ """Widen legacy rewrite-hook matchers in place (``Bash`` → current)."""+ changed = False+ for entry in hook_list:+ only_rewrite = entry.get("hooks") and all(_is_rewrite_hook(h) for h in entry["hooks"])+ if only_rewrite and entry.get("matcher", "") in _LEGACY_REWRITE_MATCHERS:+ entry["matcher"] = _REWRITE_MATCHER+ changed = True+ return changed++def uninstall_claude_code_rewrite_hook() -> bool:"""Remove the distill rewrite hook; True when something was removed."""settings_path = _claude_code_settings_path()@@ -319,10 +389,13 @@ def migrate_claude_code_hooks() -> bool:changed = Falsepre = hooks.get("PreToolUse")- if isinstance(pre, list) and _strip_repowise_pretool(pre):- changed = True- if not pre:- hooks.pop("PreToolUse", None)+ if isinstance(pre, list):+ if _strip_repowise_pretool(pre):+ changed = True+ if not pre:+ hooks.pop("PreToolUse", None)+ if _migrate_legacy_rewrite_matcher(pre):+ changed = Truepost = hooks.get("PostToolUse")if isinstance(post, list) and _migrate_legacy_hook(post):diff --git a/packages/cli/src/repowise/cli/rewrite_hook.py b/packages/cli/src/repowise/cli/rewrite_hook.pyindex 017617475..a8f8520f8 100644--- a/packages/cli/src/repowise/cli/rewrite_hook.py+++ b/packages/cli/src/repowise/cli/rewrite_hook.py@@ -159,11 +159,20 @@ IGNORED_FIRST_TOKENS = frozenset(# Shell syntax that changes meaning if the command is wrapped: pipes,# redirections, chaining, backgrounding, substitution, heredocs, newlines.+# The same characters cover PowerShell's equivalents: `;` separators,+# backtick line-continuation/escapes, `$(...)` subexpressions, pipelines,+# and `& "path\to.exe"` call-operator invocations._SHELL_SYNTAX_RE = re.compile(r"[|&;<>`\n]|\$\(")# Watch/follow modes are long-running; wrapping them buffers forever._WATCH_RE = re.compile(r"--watch(?:all)?\b|--looponfail\b|(?:^|\s)-f\b.*\.log\b|--follow\b")+# PowerShell cmdlets all follow the Verb-Noun shape (Get-ChildItem,+# Select-Object, ForEach-Object, …). None of the distill families start+# with a dashed token, so a Verb-Noun first token is a safe fast bail —+# PS-native pipelines and object output don't survive wrapping anyway.+_PS_CMDLET_RE = re.compile(r"^[a-z]+-[a-z]")+def classify(command: str) -> str | None:"""Return the distill family for *command*, or None to pass through."""@@ -173,7 +182,7 @@ def classify(command: str) -> str | None:if not normalized or normalized.startswith("repowise"):return Nonefirst = normalized.split(None, 1)[0]- if first in IGNORED_FIRST_TOKENS:+ if first in IGNORED_FIRST_TOKENS or _PS_CMDLET_RE.match(first):return Noneif _WATCH_RE.search(normalized):return None@@ -251,12 +260,27 @@ def _load_commands_config(repo_root: str) -> tuple[bool, str, dict]:return enabled, permission, families-def decide(command: str, cwd: str) -> RewriteResult | None:+# First tokens that are PowerShell aliases or unix-flavored lookalikes+# (``ls`` → Get-ChildItem, ``cat`` → Get-Content, Windows ``find``/``tree``+# differ from their unix namesakes). Wrapping them through ``repowise+# distill``'s system-shell subprocess would change — or break — what runs,+# so PowerShell-sourced commands starting with these always pass through.+_PS_ALIAS_TOKENS = frozenset(+ {"ls", "dir", "cat", "type", "find", "fd", "tail", "head", "tree", "grep", "egrep", "fgrep"}+)+++def decide(command: str, cwd: str, shell: str = "posix") -> RewriteResult | None:"""Full decision: classification + bailouts + per-repo permission config."""family = classify(command)if family is None:return None+ if shell == "powershell":+ first = _normalize(command).split(None, 1)[0]+ if first in _PS_ALIAS_TOKENS:+ return None+# Only act inside repos that opted into repowise; the hook is installed# globally, but a repo without .repowise/ gets untouched commands.repo_root = _find_repo_root(cwd)@@ -289,7 +313,7 @@ def main() -> None:adapter = ClaudeCodeAdapter()request = adapter.parse_hook_payload(sys.stdin.read())if request is not None:- result = decide(request.command, request.cwd)+ result = decide(request.command, request.cwd, request.shell)if result is not None:sys.stdout.write(adapter.render_response(result))sys.stdout.flush()diff --git a/tests/unit/cli/test_augment_search.py b/tests/unit/cli/test_augment_search.pyindex ffc2fe536..e9fbdae36 100644--- a/tests/unit/cli/test_augment_search.py+++ b/tests/unit/cli/test_augment_search.py@@ -20,9 +20,69 @@ from repowise.cli.commands.augment_cmd import (_extract_output_text,_handle_search_post,_looks_like_path_lookup,+ _looks_like_regex,_name_variants,+ _search_result_count,+ _targets_single_non_code_file,)+# ---------------------------------------------------------------------------+# Grep/Glob tool_response fixtures — captured from real Claude Code+# PostToolUse payloads (transcript toolUseResult entries), trimmed to the+# fields the tool emits. The dict *shapes* are the contract under test.+# ---------------------------------------------------------------------------++GREP_FILES_MODE = {+ "mode": "files_with_matches",+ "filenames": [+ "packages\\web\\src\\lib\\api\\costs.ts",+ "packages\\web\\src\\app\\repos\\[id]\\costs\\page.tsx",+ ],+ "numFiles": 2,+}++GREP_FILES_MODE_ZERO = {"mode": "files_with_matches", "filenames": [], "numFiles": 0}++GREP_CONTENT_MODE = {+ "mode": "content",+ "numFiles": 0,+ "filenames": [],+ "content": "src/a.py:10:def parse_yaml():\nsrc/b.py:42:parse_yaml()",+ "numLines": 2,+}++GREP_CONTENT_MODE_ZERO = {+ "mode": "content",+ "numFiles": 0,+ "filenames": [],+ "content": "",+ "numLines": 0,+}++GREP_COUNT_MODE = {+ "mode": "count",+ "numFiles": 5,+ "filenames": [],+ "content": (+ "app\\services\\dodo_service.py:5\n"+ "app\\services\\admin_notifications.py:6\n"+ "app\\services\\embedding_service.py:13\n"+ "app\\services\\account_export_service.py:12\n"+ "app\\services\\github_app_service.py:9"+ ),+ "numMatches": 45,+ "appliedLimit": 5,+}++GLOB_RESPONSE = {+ "filenames": ["src\\a.py", "src\\b.py"],+ "durationMs": 12,+ "numFiles": 2,+ "truncated": False,+}++GLOB_RESPONSE_ZERO = {"filenames": [], "durationMs": 9769, "numFiles": 0, "truncated": False}+# ---------------------------------------------------------------------------# Pure helpers# ---------------------------------------------------------------------------@@ -82,6 +142,114 @@ class TestExtractOutputText:assert _extract_output_text(42) == ""assert _extract_output_text({"unrelated": "value"}) == ""+ def test_files_mode_joins_filenames(self) -> None:+ text = _extract_output_text(GREP_FILES_MODE)+ assert text.splitlines() == GREP_FILES_MODE["filenames"]++ def test_content_mode_returns_content(self) -> None:+ assert _extract_output_text(GREP_CONTENT_MODE) == GREP_CONTENT_MODE["content"]++ def test_glob_response_joins_filenames(self) -> None:+ assert _extract_output_text(GLOB_RESPONSE) == "src\\a.py\nsrc\\b.py"+++class TestSearchResultCount:+ """Counting against the captured tool_response shapes, mode by mode."""++ def test_files_mode_counts_files(self) -> None:+ assert _search_result_count(GREP_FILES_MODE) == 2++ def test_files_mode_zero_is_a_true_zero(self) -> None:+ assert _search_result_count(GREP_FILES_MODE_ZERO) == 0++ def test_content_mode_counts_lines(self) -> None:+ assert _search_result_count(GREP_CONTENT_MODE) == 2++ def test_content_mode_zero_is_a_true_zero(self) -> None:+ assert _search_result_count(GREP_CONTENT_MODE_ZERO) == 0++ def test_count_mode_counts_matches(self) -> None:+ assert _search_result_count(GREP_COUNT_MODE) == 45++ def test_glob_counts_files(self) -> None:+ assert _search_result_count(GLOB_RESPONSE) == 2+ assert _search_result_count(GLOB_RESPONSE_ZERO) == 0++ def test_unknown_future_mode_is_unknown(self) -> None:+ assert _search_result_count({"mode": "summary", "summary": "3 hits"}) is None++ def test_unknown_shape_is_unknown_not_zero(self) -> None:+ assert _search_result_count({"unrelated": "value"}) is None+ assert _search_result_count(None) is None+ assert _search_result_count("") is None+ assert _search_result_count(" \n") is None++ def test_plain_text_counts_lines(self) -> None:+ assert _search_result_count("src/a.py:1: hit\nsrc/b.py:2: hit") == 2++ def test_text_zero_requires_a_sentinel(self) -> None:+ assert _search_result_count({"output": "No matches found"}) == 0+ assert _search_result_count("Found 0 files") == 0+++class TestLooksLikeRegex:+ @pytest.mark.parametrize(+ "pattern",+ [+ "distill|savings",+ "def (parse|load)_yaml",+ r"\bparse_yaml\b",+ "parse.*yaml",+ "parse.+yaml",+ "[Pp]arse_yaml",+ "log(ger)?",+ ],+ )+ def test_regex_patterns_flag(self, pattern: str) -> None:+ assert _looks_like_regex(pattern) is True++ @pytest.mark.parametrize(+ "pattern",+ [+ "parse_yaml",+ "GraphBuilder",+ "use cache",+ r"escaped \| pipe",+ r"escaped \[ bracket",+ "v1.2", # dot without a quantifier is fine+ ],+ )+ def test_literal_patterns_do_not_flag(self, pattern: str) -> None:+ assert _looks_like_regex(pattern) is False+++class TestTargetsSingleNonCodeFile:+ @pytest.mark.parametrize(+ "tool_input",+ [+ {"pattern": "x", "path": "config/settings.yaml"},+ {"pattern": "x", "path": "package.json"},+ {"pattern": "x", "path": "README.md"},+ {"pattern": "x", "path": "pyproject.toml"},+ {"pattern": "x", "glob": "uv.lock"},+ ],+ )+ def test_single_non_code_targets(self, tool_input: dict) -> None:+ assert _targets_single_non_code_file(tool_input) is True++ @pytest.mark.parametrize(+ "tool_input",+ [+ {"pattern": "x"}, # repo-wide grep+ {"pattern": "x", "path": "src/auth/service.py"}, # code file+ {"pattern": "x", "path": "packages/core"}, # directory scope+ {"pattern": "x", "glob": "**/*.yaml"}, # many files+ {"pattern": "x", "glob": "*.json"},+ ],+ )+ def test_everything_else_stays_eligible(self, tool_input: dict) -> None:+ assert _targets_single_non_code_file(tool_input) is False+class TestCountSearchResults:def test_empty(self) -> None:@@ -182,29 +350,91 @@ class TestDecisionTree:assert _call("Grep", "auth", output, repowise_cwd) is Noneenrich.assert_not_called()- def test_rescue_mode_on_zero_results(self, repowise_cwd) -> None:- """0 lines + concept query → rescue mode."""+ @pytest.mark.parametrize(+ "tool_output",+ [+ GREP_FILES_MODE_ZERO,+ GREP_CONTENT_MODE_ZERO,+ {"output": "No matches found"},+ ],+ )+ def test_rescue_mode_on_true_zero_results(self, repowise_cwd, tool_output) -> None:+ """A positively-identified zero + concept query → rescue mode."""sentinel = object()- with patch.object(- augment_cmd, "_search_enrich", return_value=sentinel- ) as enrich:+ 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)+ _handle_search_post(+ tool_name="Grep",+ tool_input={"pattern": "parse_yaml"},+ tool_output=tool_output,+ cwd=str(repowise_cwd),+ )(call_args,) = enrich.call_args_listkwargs = call_args.kwargs or {}args = call_args.argsmode = kwargs.get("mode") if "mode" in kwargs else args[2]assert mode == "rescue"+ def test_no_rescue_for_successful_files_mode_grep(self, repowise_cwd) -> None:+ """The live bug: files_with_matches results must never read as zero."""+ with patch.object(augment_cmd, "_search_enrich") as enrich:+ result = _handle_search_post(+ tool_name="Grep",+ tool_input={"pattern": "distill_savings"},+ tool_output=GREP_FILES_MODE,+ cwd=str(repowise_cwd),+ )+ assert result is None+ enrich.assert_not_called()++ @pytest.mark.parametrize(+ "tool_output",+ [+ {"mode": "summary", "summary": "3 hits"}, # future Grep mode+ {"unrelated": "value"},+ {"output": ""}, # empty extraction is NOT a zero signal+ "",+ ],+ )+ def test_unknown_shape_skips_never_rescues(self, repowise_cwd, tool_output) -> None:+ with patch.object(augment_cmd, "_search_enrich") as enrich:+ result = _handle_search_post(+ tool_name="Grep",+ tool_input={"pattern": "parse_yaml"},+ tool_output=tool_output,+ cwd=str(repowise_cwd),+ )+ assert result is None+ enrich.assert_not_called()++ @pytest.mark.parametrize(+ "tool_input",+ [+ {"pattern": "distill|savings"}, # regex alternation, sanitizer-mangled+ {"pattern": r"\bdistill\b"},+ {"pattern": "default_model", "path": "config/settings.yaml"},+ {"pattern": "permission", "glob": "package.json"},+ ],+ )+ def test_zero_match_rescue_skipped_when_irrelevant(self, repowise_cwd, tool_input) -> None:+ """Regex patterns and single non-code-file scopes never rescue."""+ with patch.object(augment_cmd, "_search_enrich") as enrich:+ result = _handle_search_post(+ tool_name="Grep",+ tool_input=tool_input,+ tool_output=GREP_FILES_MODE_ZERO,+ cwd=str(repowise_cwd),+ )+ assert result is None+ enrich.assert_not_called()+def test_triage_mode_on_flood(self, repowise_cwd) -> None:""">= _TRIAGE_THRESHOLD lines → triage mode."""from repowise.cli.commands.augment_cmd import _TRIAGE_THRESHOLDbig = "\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.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]diff --git a/tests/unit/cli/test_augment_staleness.py b/tests/unit/cli/test_augment_staleness.pyindex 3cf2f5843..4998100e6 100644--- a/tests/unit/cli/test_augment_staleness.py+++ b/tests/unit/cli/test_augment_staleness.py@@ -23,8 +23,18 @@ def repo(tmp_path):"""A minimal git repo with a `.repowise/state.json`."""subprocess.run(["git", "init", "-q"], cwd=tmp_path, check=True)subprocess.run(- ["git", "-c", "user.email=t@t", "-c", "user.name=t",- "commit", "--allow-empty", "-m", "init", "-q"],+ [+ "git",+ "-c",+ "user.email=t@t",+ "-c",+ "user.name=t",+ "commit",+ "--allow-empty",+ "-m",+ "init",+ "-q",+ ],cwd=tmp_path,check=True,)@@ -39,16 +49,24 @@ def repo(tmp_path):def _state(repo_path: Path, **fields) -> None:- (repo_path / ".repowise" / "state.json").write_text(- json.dumps(fields), encoding="utf-8"- )+ (repo_path / ".repowise" / "state.json").write_text(json.dumps(fields), encoding="utf-8")def _commit(repo_path: Path) -> str:"""Make an empty commit and return the new HEAD."""subprocess.run(- ["git", "-c", "user.email=t@t", "-c", "user.name=t",- "commit", "--allow-empty", "-m", "next", "-q"],+ [+ "git",+ "-c",+ "user.email=t@t",+ "-c",+ "user.name=t",+ "commit",+ "--allow-empty",+ "-m",+ "next",+ "-q",+ ],cwd=repo_path,check=True,)@@ -108,11 +126,13 @@ class TestUpdateLockSuppression:# A live PID: read_update_lock now probes liveness, so a fabricated# dead PID would (correctly) be treated as a crashed update.(repo_path / ".repowise" / ".update.lock").write_text(- json.dumps({- "pid": os.getpid(),- "target_commit": new_head,- "started_at": time.time(),- }),+ json.dumps(+ {+ "pid": os.getpid(),+ "target_commit": new_head,+ "started_at": time.time(),+ }+ ),encoding="utf-8",)@@ -136,11 +156,13 @@ class TestUpdateLockSuppression:proc = subprocess.Popen([sys.executable, "-c", "pass"])proc.wait(timeout=30)(repo_path / ".repowise" / ".update.lock").write_text(- json.dumps({- "pid": proc.pid,- "target_commit": "x",- "started_at": time.time(),- }),+ json.dumps(+ {+ "pid": proc.pid,+ "target_commit": "x",+ "started_at": time.time(),+ }+ ),encoding="utf-8",)@@ -175,11 +197,13 @@ class TestUpdateLockSuppression:import time(repo_path / ".repowise" / ".update.lock").write_text(- json.dumps({- "pid": os.getpid(), # live owner — see liveness probe note above- "target_commit": head, # old HEAD, not the current one- "started_at": time.time(),- }),+ json.dumps(+ {+ "pid": os.getpid(), # live owner — see liveness probe note above+ "target_commit": head, # old HEAD, not the current one+ "started_at": time.time(),+ }+ ),encoding="utf-8",)@@ -251,6 +275,52 @@ class TestPerHeadDedupe:assert msg is not None+class TestPowerShellDispatch:+ """The PowerShell tool surfaces the same stdout/stderr response shape as+ Bash (captured from real PostToolUse payloads) and must take the same+ staleness path."""++ def test_powershell_git_commit_warns(self, repo):+ from repowise.cli.commands.augment_cmd import _handle_post_tool_use++ repo_path, head = repo+ _state(repo_path, last_sync_commit=head, docs_enabled=True)+ new_head = _commit(repo_path)++ msg = _handle_post_tool_use(+ "PowerShell",+ {"command": "git commit -m 'x'"},+ # Captured PowerShell tool_response shape — same keys as Bash.+ {"stdout": "[main 1234abcd] x", "stderr": "", "interrupted": False, "isImage": False},+ str(repo_path),+ session_id="s",+ )+ assert msg is not None+ assert "Wiki is stale" in msg+ assert new_head[:8] in msg++ def test_powershell_failed_command_is_silent(self, repo):+ from repowise.cli.commands.augment_cmd import _handle_post_tool_use++ repo_path, head = repo+ _state(repo_path, last_sync_commit=head, docs_enabled=True)+ _commit(repo_path)++ msg = _handle_post_tool_use(+ "PowerShell",+ {"command": "git commit -m 'x'"},+ {+ "stdout": "",+ "stderr": "fatal: nothing to commit",+ "interrupted": False,+ "isImage": False,+ },+ str(repo_path),+ session_id="s",+ )+ assert msg is None++class TestDocsEnabledWording:def test_says_index_when_docs_disabled(self, repo):repo_path, head = repodiff --git a/tests/unit/cli/test_mcp_config.py b/tests/unit/cli/test_mcp_config.pyindex 9bc2ac81e..e238bbdbe 100644--- a/tests/unit/cli/test_mcp_config.py+++ b/tests/unit/cli/test_mcp_config.py@@ -404,7 +404,9 @@ def test_install_claude_code_hooks_creates_missing_file(assert settings_path == tmp_path / ".claude" / "settings.json"saved = json.loads(settings_path.read_text(encoding="utf-8"))assert "PreToolUse" not in saved["hooks"]- assert _post_repowise_entries(saved) == [("Bash|Grep|Glob|Read|Edit|Write", "repowise-augment")]+ assert _post_repowise_entries(saved) == [+ ("Bash|PowerShell|Grep|Glob|Read|Edit|Write", "repowise-augment")+ ]def test_install_claude_code_hooks_preserves_user_pretool_hooks(@@ -439,7 +441,9 @@ def test_install_claude_code_hooks_preserves_user_pretool_hooks(assert saved["hooks"]["PreToolUse"][0]["matcher"] == "Read"assert saved["hooks"]["PreToolUse"][0]["hooks"][0]["command"] == "echo read"# PostToolUse now has the repowise hook.- assert _post_repowise_entries(saved) == [("Bash|Grep|Glob|Read|Edit|Write", "repowise-augment")]+ assert _post_repowise_entries(saved) == [+ ("Bash|PowerShell|Grep|Glob|Read|Edit|Write", "repowise-augment")+ ]# ---------------------------------------------------------------------------@@ -483,7 +487,9 @@ def test_install_claude_code_hooks_migrates_pre_0_6_1_command(saved = json.loads(settings_path.read_text(encoding="utf-8"))assert "PreToolUse" not in saved["hooks"]- assert _post_repowise_entries(saved) == [("Bash|Grep|Glob|Read|Edit|Write", "repowise-augment")]+ assert _post_repowise_entries(saved) == [+ ("Bash|PowerShell|Grep|Glob|Read|Edit|Write", "repowise-augment")+ ]def test_install_claude_code_hooks_migrates_pre_0_6_2_matcher(@@ -521,7 +527,9 @@ def test_install_claude_code_hooks_migrates_pre_0_6_2_matcher(saved = json.loads(settings_path.read_text(encoding="utf-8"))assert "PreToolUse" not in saved["hooks"]- assert _post_repowise_entries(saved) == [("Bash|Grep|Glob|Read|Edit|Write", "repowise-augment")]+ assert _post_repowise_entries(saved) == [+ ("Bash|PowerShell|Grep|Glob|Read|Edit|Write", "repowise-augment")+ ]def test_install_claude_code_hooks_idempotent_on_current_shape(@@ -575,17 +583,23 @@ def test_migrate_claude_code_hooks_handles_full_legacy_payload(saved = json.loads(settings_path.read_text(encoding="utf-8"))assert "PreToolUse" not in saved["hooks"]- assert _post_repowise_entries(saved) == [("Bash|Grep|Glob|Read|Edit|Write", "repowise-augment")]+ assert _post_repowise_entries(saved) == [+ ("Bash|PowerShell|Grep|Glob|Read|Edit|Write", "repowise-augment")+ ]# Idempotent: a second run finds nothing to do.assert claude_config.migrate_claude_code_hooks() is False-def test_migrate_claude_code_hooks_widens_grep_glob_matcher(- tmp_path: Path, monkeypatch: pytest.MonkeyPatch+ "legacy_matcher",+ ["Bash|Grep|Glob", "Bash|Grep|Glob|Read|Edit|Write"],+)+def test_migrate_claude_code_hooks_widens_legacy_matchers(+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch, legacy_matcher: str) -> None:- """Pre-read-intelligence installs used matcher ``Bash|Grep|Glob``;- migration widens it to include Read/Edit/Write."""+ """Pre-read-intelligence installs used ``Bash|Grep|Glob``; pre-PowerShell+ installs lacked the PowerShell tool. Both widen to the current matcher."""monkeypatch.setattr(Path, "home", lambda: tmp_path)settings_path = tmp_path / ".claude" / "settings.json"settings_path.parent.mkdir(parents=True)@@ -595,7 +609,7 @@ def test_migrate_claude_code_hooks_widens_grep_glob_matcher("hooks": {"PostToolUse": [{- "matcher": "Bash|Grep|Glob",+ "matcher": legacy_matcher,"hooks": [{"type": "command", "command": "repowise-augment"}],}]@@ -607,7 +621,9 @@ def test_migrate_claude_code_hooks_widens_grep_glob_matcher(assert claude_config.migrate_claude_code_hooks() is Truesaved = json.loads(settings_path.read_text(encoding="utf-8"))- assert _post_repowise_entries(saved) == [("Bash|Grep|Glob|Read|Edit|Write", "repowise-augment")]+ assert _post_repowise_entries(saved) == [+ ("Bash|PowerShell|Grep|Glob|Read|Edit|Write", "repowise-augment")+ ]def test_migrate_claude_code_hooks_never_widens_user_matcher(@@ -686,7 +702,7 @@ def test_migrate_claude_code_hooks_noop_when_already_current("hooks": {"PostToolUse": [{- "matcher": "Bash|Grep|Glob|Read|Edit|Write",+ "matcher": "Bash|PowerShell|Grep|Glob|Read|Edit|Write","hooks": [{"type": "command", "command": "repowise-augment"}],}]diff --git a/tests/unit/distill/test_agent_adapters.py b/tests/unit/distill/test_agent_adapters.pyindex 6bb1d763c..ca6fbe246 100644--- a/tests/unit/distill/test_agent_adapters.py+++ b/tests/unit/distill/test_agent_adapters.py@@ -42,6 +42,21 @@ class TestParsePayload:assert req is not Noneassert req.command == "pytest -x"assert req.cwd == "/repo"+ assert req.shell == "posix"++ def test_valid_powershell_payload(self, adapter) -> None:+ raw = json.dumps(+ {+ "hook_event_name": "PreToolUse",+ "tool_name": "PowerShell",+ "tool_input": {"command": "git status"},+ "cwd": "C:\\repo",+ }+ )+ req = adapter.parse_hook_payload(raw)+ assert req is not None+ assert req.command == "git status"+ assert req.shell == "powershell"@pytest.mark.parametrize("mutation",@@ -113,7 +128,7 @@ class TestRewriteHookInstall:assert install_claude_code_rewrite_hook() == settings_pathentries = _pre_hooks(settings_path)assert len(entries) == 1- assert entries[0]["matcher"] == "Bash"+ assert entries[0]["matcher"] == "Bash|PowerShell"hook = entries[0]["hooks"][0]assert hook["command"] == "repowise-rewrite"assert hook["type"] == "command"@@ -124,6 +139,42 @@ class TestRewriteHookInstall:install_claude_code_rewrite_hook()assert len(_pre_hooks(settings_path)) == 1+ def test_install_widens_legacy_bash_matcher(self, settings_path) -> None:+ settings_path.parent.mkdir(parents=True, exist_ok=True)+ legacy = {+ "matcher": "Bash",+ "hooks": [{"type": "command", "command": "repowise-rewrite", "timeout": 5}],+ }+ settings_path.write_text(json.dumps({"hooks": {"PreToolUse": [legacy]}}), encoding="utf-8")+ install_claude_code_rewrite_hook()+ entries = _pre_hooks(settings_path)+ assert len(entries) == 1+ assert entries[0]["matcher"] == "Bash|PowerShell"++ def test_install_leaves_user_bash_matcher_alone(self, settings_path) -> None:+ settings_path.parent.mkdir(parents=True, exist_ok=True)+ user_entry = {+ "matcher": "Bash",+ "hooks": [{"type": "command", "command": "my-validator"}],+ }+ settings_path.write_text(+ json.dumps({"hooks": {"PreToolUse": [user_entry]}}), encoding="utf-8"+ )+ install_claude_code_rewrite_hook()+ entries = _pre_hooks(settings_path)+ assert entries[0]["matcher"] == "Bash" # user entry untouched+ assert entries[1]["matcher"] == "Bash|PowerShell"++ def test_migrate_widens_legacy_rewrite_matcher(self, settings_path) -> None:+ settings_path.parent.mkdir(parents=True, exist_ok=True)+ legacy = {+ "matcher": "Bash",+ "hooks": [{"type": "command", "command": "repowise-rewrite", "timeout": 5}],+ }+ settings_path.write_text(json.dumps({"hooks": {"PreToolUse": [legacy]}}), encoding="utf-8")+ assert migrate_claude_code_hooks() is True+ assert _pre_hooks(settings_path)[0]["matcher"] == "Bash|PowerShell"+def test_preserves_user_pretool_hooks(self, settings_path) -> None:settings_path.parent.mkdir(parents=True, exist_ok=True)user_entry = {diff --git a/tests/unit/distill/test_allow_rule.py b/tests/unit/distill/test_allow_rule.pynew file mode 100644index 000000000..afb0fe270--- /dev/null+++ b/tests/unit/distill/test_allow_rule.py@@ -0,0 +1,121 @@+"""Permission allow-rule seeding for distilled commands.++A rewrite changes the command string, so the user's existing Claude Code+allowlist entries (``Bash(git diff:*)``) stop matching the rewritten+``repowise distill git diff …``. ``repowise hook rewrite install`` offers+to seed one allow rule per shell tool covering the distill prefix; these+tests pin the settings.json mechanics — additive, idempotent, never+touching user rules — and the CLI flag plumbing.+"""++from __future__ import annotations++import json++import pytest++from repowise.cli.editor_integrations import claude_config+from repowise.cli.editor_integrations.claude_config import (+ DISTILL_ALLOW_RULES,+ add_claude_code_distill_allow_rules,+)+++def settings_path(tmp_path, monkeypatch):+ path = tmp_path / ".claude" / "settings.json"+ monkeypatch.setattr(claude_config, "_claude_code_settings_path", lambda: path)+ return path+++def _allow(settings_path) -> list:+ data = json.loads(settings_path.read_text(encoding="utf-8"))+ return data.get("permissions", {}).get("allow", [])+++class TestAddDistillAllowRules:+ def test_creates_missing_file(self, settings_path) -> None:+ assert add_claude_code_distill_allow_rules() == settings_path+ assert _allow(settings_path) == list(DISTILL_ALLOW_RULES)++ def test_rules_cover_both_shell_tools(self) -> None:+ assert "Bash(repowise distill:*)" in DISTILL_ALLOW_RULES+ assert "PowerShell(repowise distill:*)" in DISTILL_ALLOW_RULES++ def test_idempotent(self, settings_path) -> None:+ add_claude_code_distill_allow_rules()+ before = settings_path.read_text(encoding="utf-8")+ add_claude_code_distill_allow_rules()+ assert settings_path.read_text(encoding="utf-8") == before++ def test_preserves_existing_user_rules(self, settings_path) -> None:+ settings_path.parent.mkdir(parents=True, exist_ok=True)+ settings_path.write_text(+ json.dumps(+ {+ "permissions": {"allow": ["Bash(git status:*)"], "deny": ["WebFetch"]},+ "hooks": {},+ }+ ),+ encoding="utf-8",+ )+ add_claude_code_distill_allow_rules()+ allow = _allow(settings_path)+ assert allow[0] == "Bash(git status:*)"+ for rule in DISTILL_ALLOW_RULES:+ assert rule in allow+ data = json.loads(settings_path.read_text(encoding="utf-8"))+ assert data["permissions"]["deny"] == ["WebFetch"]++ def test_partial_presence_adds_only_missing(self, settings_path) -> None:+ settings_path.parent.mkdir(parents=True, exist_ok=True)+ settings_path.write_text(+ json.dumps({"permissions": {"allow": ["Bash(repowise distill:*)"]}}),+ encoding="utf-8",+ )+ add_claude_code_distill_allow_rules()+ allow = _allow(settings_path)+ assert allow.count("Bash(repowise distill:*)") == 1+ assert "PowerShell(repowise distill:*)" in allow++ def test_malformed_settings_returns_none(self, settings_path) -> None:+ settings_path.parent.mkdir(parents=True, exist_ok=True)+ settings_path.write_text("{not json", encoding="utf-8")+ assert add_claude_code_distill_allow_rules() is None+++class TestRewriteInstallFlag:+ """--allow-rule / --no-allow-rule plumbing on `hook rewrite install`."""++ @pytest.fixture+ def repo(self, tmp_path, monkeypatch):+ (tmp_path / ".repowise").mkdir()+ monkeypatch.chdir(tmp_path)+ return tmp_path++ def _invoke(self, args):+ from click.testing import CliRunner++ from repowise.cli.commands.hook_cmd import hook_group++ return CliRunner().invoke(hook_group, args)++ def test_allow_rule_flag_seeds_rules(self, repo, settings_path) -> None:+ result = self._invoke(["rewrite", "install", "--allow-rule", str(repo)])+ assert result.exit_code == 0, result.output+ assert "Allow rule added" in result.output+ for rule in DISTILL_ALLOW_RULES:+ assert rule in _allow(settings_path)++ def test_no_allow_rule_flag_skips(self, repo, settings_path) -> None:+ result = self._invoke(["rewrite", "install", "--no-allow-rule", str(repo)])+ assert result.exit_code == 0, result.output+ data = json.loads(settings_path.read_text(encoding="utf-8"))+ assert "permissions" not in data++ def test_default_is_no_rule_when_not_interactive(self, repo, settings_path) -> None:+ # CliRunner stdin is not a tty — the prompt is skipped, no rule added.+ result = self._invoke(["rewrite", "install", str(repo)])+ assert result.exit_code == 0, result.output+ data = json.loads(settings_path.read_text(encoding="utf-8"))+ assert "permissions" not in datadiff --git a/tests/unit/distill/test_read_intelligence.py b/tests/unit/distill/test_read_intelligence.pyindex b05ddd120..82ea54a5e 100644--- a/tests/unit/distill/test_read_intelligence.py+++ b/tests/unit/distill/test_read_intelligence.py@@ -44,7 +44,8 @@ def _index_file(repo: Path, rel: str, bounds: list[tuple[int, int]]) -> None:con.close()-def _write_big_file(repo: Path, rel: str, lines: int = 200) -> Path:+def _write_big_file(repo: Path, rel: str, lines: int = 600) -> Path:+ """Default size clears the nudge's full-file token floor (~3k tokens)."""path = repo / relpath.parent.mkdir(parents=True, exist_ok=True)path.write_text("\n".join(f"x{n} = {n} # padding padding" for n in range(lines)) + "\n")@@ -127,6 +128,21 @@ class TestSkeletonNudge:_index_file(repo, "src/small.py", [(1, 30)])assert _read_event(repo, "src/small.py") is None+ def test_silent_below_token_floor(self, repo: Path) -> None:+ # The live noise case: a ~1.5k-token file with a perfectly valid+ # skeleton (~600 tokens saved) is a hint nobody should act on.+ _write_big_file(repo, "src/mid.py", lines=200)+ _index_file(repo, "src/mid.py", [(10, 60), (70, 150), (160, 195)])+ assert _read_event(repo, "src/mid.py") is None++ def test_fires_above_token_floor_with_real_savings(self, repo: Path) -> None:+ # Same shape as the noise case, just genuinely large: ≥3k full-file+ # tokens with ≥1.5k estimated savings.+ _write_big_file(repo, "src/big.py", lines=600)+ _index_file(repo, "src/big.py", [(10, 60), (70, 150), (160, 195)])+ result = _read_event(repo, "src/big.py")+ assert result is not None and 'include=["skeleton"]' in result+class TestStaleReadNotice:def test_edit_then_reread_flags_staleness(self, repo: Path) -> None:diff --git a/tests/unit/distill/test_rewrite_hook.py b/tests/unit/distill/test_rewrite_hook.pyindex a69d3fadc..dda283121 100644--- a/tests/unit/distill/test_rewrite_hook.py+++ b/tests/unit/distill/test_rewrite_hook.py@@ -101,6 +101,18 @@ class TestClassify:"pytest --looponfail","tail -f app.log","kubectl logs --follow pod",+ # PowerShell: compound/continuation/substitution/call operator+ "git status; git log --oneline -5",+ "git log --oneline `\n -20",+ "git diff $(git merge-base main HEAD)",+ '& "C:\\Program Files\\Git\\bin\\git.exe" status',+ "$env:FOO='1'; pytest -x",+ # PowerShell: Verb-Noun cmdlets+ "Get-ChildItem -Recurse",+ "Get-Content app.log -Tail 100",+ "Select-Object -First 5",+ "ForEach-Object name",+ "Test-Path .repowise",# already repowise"repowise distill pytest -x","repowise update",@@ -216,6 +228,43 @@ class TestDecide:assert result is not None and result.permission == "ask"+class TestDecidePowerShell:+ """shell="powershell" — PS aliases never rewritten, neutral commands are."""++ @pytest.mark.parametrize(+ "command",+ [+ "ls", # Get-ChildItem alias; not the unix binary+ "cat server.log", # Get-Content alias+ "tail -n 100 app.log",+ "find . -name '*.py'", # Windows find.exe differs+ "tree src", # tree.com differs+ "grep -rn auth .",+ ],+ )+ def test_ps_alias_tokens_pass_through(self, repo, command) -> None:+ assert decide(command, str(repo), shell="powershell") is None+ # The same command from a POSIX shell still rewrites.+ assert decide(command, str(repo), shell="posix") is not None++ @pytest.mark.parametrize(+ "command",+ [+ "git status",+ "git log --oneline -20",+ "pytest tests/unit -q",+ r".venv\Scripts\pytest.exe -q",+ "npm run build",+ "cargo test",+ ],+ )+ def test_shell_neutral_commands_rewrite(self, repo, command) -> None:+ result = decide(command, str(repo), shell="powershell")+ assert result is not None+ assert result.command == f"repowise distill {command}"+ assert result.permission == "ask"++# ---------------------------------------------------------------------------# End-to-end: PreToolUse payload in, hookSpecificOutput JSON out# ---------------------------------------------------------------------------@@ -258,9 +307,18 @@ class TestMain:def test_passthrough_emits_nothing(self, monkeypatch, repo) -> None:assert _run_main(monkeypatch, _payload("cd src", str(repo))) == ""- def test_non_bash_tool_ignored(self, monkeypatch, repo) -> None:+ def test_non_shell_tool_ignored(self, monkeypatch, repo) -> None:assert _run_main(monkeypatch, _payload("pytest", str(repo), tool_name="Grep")) == ""+ def test_powershell_tool_rewrites(self, monkeypatch, repo) -> None:+ out = _run_main(monkeypatch, _payload("git status", str(repo), tool_name="PowerShell"))+ hso = json.loads(out)["hookSpecificOutput"]+ assert hso["updatedInput"] == {"command": "repowise distill git status"}+ assert hso["permissionDecision"] == "ask"++ def test_powershell_alias_passes_through(self, monkeypatch, repo) -> None:+ assert _run_main(monkeypatch, _payload("ls -la", str(repo), tool_name="PowerShell")) == ""+def test_post_tool_use_ignored(self, monkeypatch, repo) -> None:payload = _payload("pytest", str(repo), hook_event_name="PostToolUse")assert _run_main(monkeypatch, payload) == ""