Skip to content

Codebase intelligence for AI and humans: code health scores, auto-generated docs, git analytics, dead code detection, and architectural decisions via MCP.

feat(distill): seamless rewrite permissions + re-read savings (#559)

Raghav Chamadiya322b3a4053b9
diff --git a/packages/cli/src/repowise/cli/agent_adapters/base.py b/packages/cli/src/repowise/cli/agent_adapters/base.py
index cb79b7f46..a8d7a0e49 100644
--- a/packages/cli/src/repowise/cli/agent_adapters/base.py
+++ b/packages/cli/src/repowise/cli/agent_adapters/base.py
@@ -39,9 +39,9 @@ class RewriteResult:
#: The replacement command (e.g. ``repowise distill pytest -x``).
self.command = command
#: ``"ask"`` surfaces the rewritten command for user approval;
- #: ``"allow"`` executes it without a prompt. Never auto-allow unless
- #: the user opted in per command family — a silently mutated command
- #: is a permission escalation.
+ #: ``"allow"`` executes it without a prompt (the default — see the
+ #: ``rewrite_hook`` module docstring for why auto-allowing a
+ #: bailout-filtered ``repowise distill`` wrap is not an escalation).
self.permission = permission
#: One-line human explanation shown in the agent's permission UI.
self.reason = reason
diff --git a/packages/cli/src/repowise/cli/commands/augment_cmd.py b/packages/cli/src/repowise/cli/commands/augment_cmd.py
index 2f21dd23c..4c65991a1 100644
--- a/packages/cli/src/repowise/cli/commands/augment_cmd.py
+++ b/packages/cli/src/repowise/cli/commands/augment_cmd.py
@@ -856,6 +856,7 @@ def _load_session_state(repo_path: Path, session_id: str) -> dict:
"edits": {},
"nudged": [],
"stale_notified": [],
+ "reread_notified": [],
}
try:
state = json.loads(_session_state_path(repo_path).read_text(encoding="utf-8"))
@@ -931,18 +932,37 @@ def _handle_read_post(
# reasoning still anchored on the pre-edit excerpt.
last_read = state["reads"].get(rel)
last_edit = state["edits"].get(rel)
- if (
- last_read is not None
- and last_edit is not None
- and last_read < last_edit
- and rel not in state["stale_notified"]
- ):
+ edited_since_read = last_read is not None and last_edit is not None and last_read < last_edit
+ if edited_since_read and rel not in state["stale_notified"]:
state["stale_notified"].append(rel)
notices.append(
f"[repowise] {rel} changed (Edit/Write) after your previous read of it — "
"excerpts from before that edit are stale."
)
+ # Re-read: already read this session, unchanged since (the read→edit→read
+ # case is the stale notice above), and this is a full re-read of a
+ # non-trivial file — the content is still in context, so re-reading the
+ # whole file just re-bills it. A targeted range re-read is the behavior
+ # we'd recommend, so it is deliberately not flagged; the line floor (the
+ # skeleton nudge's) keeps small files from generating noise.
+ partial_read = isinstance(tool_input, dict) and (
+ tool_input.get("offset") is not None or tool_input.get("limit") is not None
+ )
+ if (
+ last_read is not None
+ and not edited_since_read
+ and not partial_read
+ and rel not in state["reread_notified"]
+ and _read_output_line_count(tool_output) >= _READ_NUDGE_MIN_LINES
+ ):
+ state["reread_notified"].append(rel)
+ notices.append(
+ f"[repowise] You already read {rel} this session and it is unchanged — "
+ "its content is still in context. For a specific symbol use "
+ f'get_symbol("{rel}::Name") or a line-range read instead of re-reading the file.'
+ )
+
state["seq"] += 1
state["reads"][rel] = state["seq"]
diff --git a/packages/cli/src/repowise/cli/commands/hook_cmd.py b/packages/cli/src/repowise/cli/commands/hook_cmd.py
index 28564c052..dd1257053 100644
--- a/packages/cli/src/repowise/cli/commands/hook_cmd.py
+++ b/packages/cli/src/repowise/cli/commands/hook_cmd.py
@@ -167,8 +167,9 @@ def _codex_capability_note(version, supports) -> str:
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)."
+ "commands. Only needed if you set `permission: ask` in "
+ ".repowise/config.yaml; the default `allow` posture rewrites without "
+ "a prompt and needs no allow rule."
),
)
def rewrite_install(
@@ -182,8 +183,6 @@ def rewrite_install(
otherwise — since a prior ``repowise init`` opt-out may have gated
repos off.
"""
- import sys
-
from repowise.cli.agent_adapters.claude_code import ClaudeCodeAdapter
from repowise.cli.helpers import save_distill_commands_enabled
@@ -196,23 +195,18 @@ def rewrite_install(
console.print(f"Rewrite hook: [green]installed[/green] ({hook_path})")
console.print(
" [dim]Per-repo behavior is configured under `distill.commands` "
- "in .repowise/config.yaml (permission: ask | allow).[/dim]"
+ "in .repowise/config.yaml (permission: allow | ask).[/dim]"
+ )
+ console.print(
+ " [dim]Rewrites run without a prompt by default (for the main agent "
+ "and subagents alike); set `permission: ask` to review each one.[/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,
- )
+ # The default `allow` posture rewrites without a prompt, so no allowlist
+ # entry is needed. Seeding `Bash(repowise distill:*)` only helps users who
+ # set `permission: ask` and want their existing allowlist (e.g.
+ # `Bash(git diff:*)`) to keep matching the rewritten string — honor it
+ # only when explicitly requested via --allow-rule.
if allow_rule:
from repowise.cli.editor_integrations.claude_config import (
add_claude_code_distill_allow_rules,
diff --git a/packages/cli/src/repowise/cli/commands/saved_cmd.py b/packages/cli/src/repowise/cli/commands/saved_cmd.py
index fafc63b25..898dd719d 100644
--- a/packages/cli/src/repowise/cli/commands/saved_cmd.py
+++ b/packages/cli/src/repowise/cli/commands/saved_cmd.py
@@ -155,6 +155,7 @@ def saved_command(
)
console.print(f" [dim]Ledger: {db_path}[/dim]")
_print_missed_summary_line(start, missed_days)
+ _print_reread_summary_line(start, missed_days)
console.print()
@@ -182,16 +183,51 @@ def _print_missed_summary_line(start: Path, days: float) -> None:
)
-def _print_missed_report(start: Path, days: float, pricing_model: str) -> None:
- report = _missed_report(start, days)
+def _reread_report(start: Path, days: float) -> dict | None:
+ """Best-effort wasteful-re-read scan rooted at the enclosing repowise repo."""
+ try:
+ from repowise.cli.helpers import find_repowise_repo_root
+ from repowise.core.distill.missed_mcp import scan_missed_mcp_savings
+
+ repo_root = find_repowise_repo_root(start) or start
+ return scan_missed_mcp_savings(repo_root, days=days)
+ except Exception:
+ return None
+
+
+def _print_reread_summary_line(start: Path, days: float) -> None:
+ """One re-read-waste line under the main report; silent when empty."""
+ report = _reread_report(start, days)
if not report or not report["events"]:
+ return
+ console.print(
+ f" Re-reads: [yellow]~{report['est_saved_tokens']:,} tokens[/yellow] across "
+ f"{report['events']} full re-reads of unchanged files in the last {days:g} days "
+ f"[dim](repowise saved --missed)[/dim]"
+ )
+
+
+def _print_missed_report(start: Path, days: float, pricing_model: str) -> None:
+ missed = _missed_report(start, days)
+ reread = _reread_report(start, days)
+ has_missed = bool(missed and missed["events"])
+ has_reread = bool(reread and reread["events"])
+
+ if not has_missed and not has_reread:
console.print(
f"[yellow]No missed savings found in the last {days:g} days.[/yellow] "
- "Either every distillable command already ran through 'repowise distill', "
- "or no agent transcripts cover this repo."
+ "Either every distillable command already ran through 'repowise distill' "
+ "and no files were needlessly re-read, or no agent transcripts cover this repo."
)
return
+ if has_missed:
+ _render_missed_distill_table(missed, days, pricing_model)
+ if has_reread:
+ _render_reread_table(reread, days, pricing_model)
+
+
+def _render_missed_distill_table(report: dict, days: float, pricing_model: str) -> None:
usd, rate = _estimate_usd(report["est_saved_tokens"], pricing_model)
table = Table(
title=f"Missed distill savings - last {days:g} days",
@@ -233,6 +269,49 @@ def _print_missed_report(start: Path, days: float, pricing_model: str) -> None:
console.print()
+def _render_reread_table(report: dict, days: float, pricing_model: str) -> None:
+ usd, rate = _estimate_usd(report["est_saved_tokens"], pricing_model)
+ table = Table(
+ title=f"Missed MCP savings (file re-reads) - last {days:g} days",
+ border_style="dim",
+ show_footer=True,
+ caption=(
+ "Full re-reads of unchanged files a targeted get_symbol / range read "
+ "would have replaced; estimates credit a conservative half of each "
+ "re-read. Scanned from local Claude Code transcripts - nothing leaves "
+ "this machine."
+ ),
+ )
+ table.add_column("File", style="cyan", footer="[bold]TOTAL[/bold]")
+ table.add_column("Re-reads", justify="right", footer=str(report["events"]))
+ table.add_column("Raw Tokens", justify="right", footer=f"{report['raw_tokens']:,}")
+ table.add_column(
+ "Est. Foregone",
+ justify="right",
+ footer=f"[bold yellow]{report['est_saved_tokens']:,}[/bold yellow]",
+ )
+ for rel, stats in list(report["per_file"].items())[:15]:
+ table.add_row(
+ rel,
+ str(stats["events"]),
+ f"{stats['raw_tokens']:,}",
+ f"[yellow]{stats['est_saved_tokens']:,}[/yellow]",
+ )
+
+ console.print()
+ console.print(table)
+ console.print(
+ f" Estimated foregone: [bold yellow]${usd:.4f}[/bold yellow] "
+ f"[dim](at ${rate:.2f}/M input tokens, {pricing_model}; "
+ f"tokens are chars/4 estimates)[/dim]"
+ )
+ console.print(
+ ' [dim]Tip: for a known symbol use get_symbol("file::Name") or a '
+ "line-range read instead of re-reading the whole file.[/dim]"
+ )
+ console.print()
+
+
def _parse_since(value: str | None) -> float | None:
"""ISO date string -> Unix timestamp, or None."""
if value is None:
diff --git a/packages/cli/src/repowise/cli/editor_integrations/claude.py b/packages/cli/src/repowise/cli/editor_integrations/claude.py
index ba7219886..5d928edf9 100644
--- a/packages/cli/src/repowise/cli/editor_integrations/claude.py
+++ b/packages/cli/src/repowise/cli/editor_integrations/claude.py
@@ -47,6 +47,7 @@ class ClaudeCodeSetup:
def register_client(self, console_obj: Any, repo_path: Path) -> None:
from repowise.cli.editor_integrations.claude_config import (
+ enable_tool_search_in_claude_code,
install_claude_code_hooks,
register_with_claude_code,
register_with_claude_desktop,
@@ -64,6 +65,12 @@ class ClaudeCodeSetup:
if hooks:
console_obj.print(" [green]✓[/green] Claude Code hooks registered (PostToolUse)")
+ if enable_tool_search_in_claude_code():
+ console_obj.print(
+ " [green]✓[/green] Claude Code tool-search enabled "
+ "(defers MCP tool schemas)"
+ )
+
def refresh_project_files(
self,
console_obj: Any,
diff --git a/packages/cli/src/repowise/cli/editor_integrations/claude_config.py b/packages/cli/src/repowise/cli/editor_integrations/claude_config.py
index 3137e325c..24efcf0b1 100644
--- a/packages/cli/src/repowise/cli/editor_integrations/claude_config.py
+++ b/packages/cli/src/repowise/cli/editor_integrations/claude_config.py
@@ -96,6 +96,39 @@ def register_with_claude_code(repo_path: Path) -> Path | None:
return settings_path if merge_mcp_entry(settings_path, entry) else None
+def enable_tool_search_in_claude_code() -> Path | None:
+ """Set ``env.ENABLE_TOOL_SEARCH=true`` in ~/.claude/settings.json.
+
+ Claude Code defers MCP tool schemas (loads them on demand via tool search)
+ when this is on, so repowise's tools don't sit in every session's standing
+ context. The behavior is client-default in newer builds but flips off in
+ some configs, so we pin it explicitly. Idempotent and non-destructive: an
+ existing ``ENABLE_TOOL_SEARCH`` value the user set (including a deliberate
+ ``false``) is left untouched, and other ``env`` keys are preserved.
+
+ Returns the settings path when it newly sets the key, else None (already
+ set, or a write failure — both non-fatal to ``init``).
+ """
+ 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 = {}
+ env = existing.get("env")
+ if not isinstance(env, dict):
+ env = {}
+ if "ENABLE_TOOL_SEARCH" in env:
+ return None
+ env["ENABLE_TOOL_SEARCH"] = "true"
+ existing["env"] = env
+ settings_path.write_text(json.dumps(existing, indent=2) + "\n", encoding="utf-8")
+ return settings_path
+ except (OSError, ValueError):
+ return None
+
+
# Current augment PostToolUse matcher. Read/Edit/Write power the distill
# read-intelligence layer (skeleton nudges + per-file stale-read notices);
# PowerShell is the Windows Claude Code shell tool (same payload shape as
diff --git a/packages/cli/src/repowise/cli/rewrite_hook.py b/packages/cli/src/repowise/cli/rewrite_hook.py
index bc547dfd0..a2b857f52 100644
--- a/packages/cli/src/repowise/cli/rewrite_hook.py
+++ b/packages/cli/src/repowise/cli/rewrite_hook.py
@@ -2,10 +2,17 @@
Fires before every shell command an AI agent runs and decides whether to
rewrite it to ``repowise distill <command>`` so the agent sees a compact,
-errors-first rendering instead of the raw flood. The hook only *proposes*
-the rewrite — the default permission posture is ``ask``, so the user
-approves the modified command unless they opted into auto-allow per
-command family in ``.repowise/config.yaml``.
+errors-first rendering instead of the raw flood. The default permission
+posture is ``allow``: a rewritten command runs without an approval prompt,
+uniformly across the main agent and every subagent. This is safe because
+``classify`` only ever rewrites a closed set of recognized command families
+(test/lint/build/git/search/listing/log) that survive the bailouts below —
+no pipes, redirects, compound commands, substitution, or interactive
+commands. The rewrite is therefore always ``repowise distill <one simple,
+recognized command>``, never an arbitrary command smuggled behind the
+wrapper, so auto-allowing it is not a permission escalation. Users who want
+to review every rewrite can set ``permission: ask`` in
+``.repowise/config.yaml``; a family set to ``off`` is never rewritten.
Hot-path discipline (this fires on EVERY Bash tool call):
@@ -239,9 +246,12 @@ def _load_commands_config(repo_root: str) -> tuple[bool, str, dict]:
"""Return (enabled, default_permission, per-family overrides).
Missing file, missing yaml, malformed yaml → permissive defaults with
- ``ask`` (the hook is only installed for users who opted in).
+ ``allow`` (the hook is only installed for users who opted in, and a
+ rewrite is always a bailout-filtered ``repowise distill`` wrap — see the
+ module docstring for why auto-allow is safe). Set ``permission: ask`` to
+ restore per-rewrite approval prompts.
"""
- enabled, permission, families = True, "ask", {}
+ enabled, permission, families = True, "allow", {}
config_path = os.path.join(repo_root, ".repowise", "config.yaml")
try:
with open(config_path, encoding="utf-8") as fh:
diff --git a/packages/core/src/repowise/core/distill/missed_mcp.py b/packages/core/src/repowise/core/distill/missed_mcp.py
new file mode 100644
index 000000000..f2ced44a6
--- /dev/null
+++ b/packages/core/src/repowise/core/distill/missed_mcp.py
@@ -0,0 +1,271 @@
+"""Missed MCP savings — what did repeated file reads waste?
+
+The sibling :mod:`repowise.core.distill.missed` accounts for *shell commands*
+a distill filter would have compressed. This module covers the other big
+exploration sink: an agent reading the **same file** more than once in a
+session. The first read puts the file in context; a later *full* re-read of
+the unchanged file re-bills the whole thing, when a targeted ``get_symbol``
+or a line-range read would have returned a fraction.
+
+It scans the same Claude Code transcript JSONL
+(``~/.claude/projects/<munged-cwd>/*.jsonl``) as the missed-savings scan,
+tracks per-file read and edit order within each session, and credits a
+conservative fraction of each wasteful re-read's tokens as foregone savings.
+
+Read-only and best-effort by the same contract as
+:mod:`repowise.core.distill.missed`: malformed lines, unreadable files, or an
+absent transcript directory produce an empty report, never an error.
+
+Privacy: everything stays local. Reads are taken from the user's own
+transcript directory on this machine; nothing leaves it.
+
+What counts as a wasteful re-read (high precision on purpose):
+
+ - the file was already read earlier this session;
+ - no Edit/Write/MultiEdit to it landed after that prior read (an edit makes
+ a re-read justified — the content changed);
+ - the current read is a *full* read (no ``offset``/``limit``). A targeted
+ range re-read is the behavior we recommend, so it is never counted.
+"""
+
+from __future__ import annotations
+
+import json
+import os.path
+import time
+from pathlib import Path
+from typing import Any
+
+from repowise.core.distill.budget import estimate_tokens
+from repowise.core.distill.missed import _parse_ts, transcript_dir_for
+
+#: Default scan window, in days. Matches the missed-savings scan.
+DEFAULT_WINDOW_DAYS = 7.0
+
+#: Conservative fraction of a re-read's tokens credited as saveable. A full
+#: re-read of an unchanged file is largely redundant (the content is already
+#: in context), but a ``get_symbol`` replacement still returns the one symbol
+#: the agent wanted, so we undersell rather than claim the whole read back.
+REREAD_FLOOR = 0.5
+
+#: Mirrors the engine's net-positive floor: a re-read this small would not be
+#: worth flagging even if avoided.
+_MIN_EST_TOKENS = 40
+
+_MUTATING_TOOLS = ("Edit", "Write", "MultiEdit", "NotebookEdit")
+
+
+def empty_report(days: float = DEFAULT_WINDOW_DAYS) -> dict[str, Any]:
+ return {
+ "events": 0,
+ "raw_tokens": 0,
+ "est_saved_tokens": 0,
+ "per_file": {},
+ "window_days": days,
+ }
+
+
+def scan_missed_mcp_savings(
+ repo_root: Path,
+ *,
+ days: float = DEFAULT_WINDOW_DAYS,
+ now: float | None = None,
+ projects_root: Path | None = None,
+) -> dict[str, Any]:
+ """Aggregate foregone savings from wasteful file re-reads in transcripts.
+
+ Returns totals plus a per-file breakdown; any failure degrades to an
+ empty report.
+ """
+ try:
+ return _scan(Path(repo_root).resolve(), days, now, projects_root)
+ except Exception:
+ return empty_report(days)
+
+
+def _scan(
+ repo_root: Path, days: float, now: float | None, projects_root: Path | None
+) -> dict[str, Any]:
+ transcripts = transcript_dir_for(repo_root, projects_root)
+ report = empty_report(days)
+ if not transcripts.is_dir():
+ return report
+
+ cutoff = (now if now is not None else time.time()) - days * 86400.0
+ repo_prefix = str(repo_root).lower().rstrip("\\/")
+ per_file: dict[str, dict[str, int]] = {}
+
+ for path in sorted(transcripts.glob("*.jsonl")):
+ try:
+ if path.stat().st_mtime < cutoff:
+ continue # untouched since the window opened
+ _scan_file(path, cutoff, repo_prefix, repo_root, per_file)
+ except OSError:
+ continue
+
+ for stats in per_file.values():
+ report["events"] += stats["events"]
+ report["raw_tokens"] += stats["raw_tokens"]
+ report["est_saved_tokens"] += stats["est_saved_tokens"]
+ report["per_file"] = dict(sorted(per_file.items(), key=lambda kv: -kv[1]["est_saved_tokens"]))
+ return report
+
+
+def _rel(file_path: str, repo_root: Path) -> str:
+ """Repo-relative POSIX display path; falls back to the raw path off-root."""
+ try:
+ rel = os.path.relpath(file_path, str(repo_root))
+ except (ValueError, OSError):
+ return file_path
+ if rel.startswith(".."):
+ return file_path
+ return rel.replace("\\", "/")
+
+
+def _scan_file(
+ path: Path,
+ cutoff: float,
+ repo_prefix: str,
+ repo_root: Path,
+ per_file: dict[str, dict[str, int]],
+) -> None:
+ """Replay one session transcript, crediting wasteful re-reads.
+
+ State is per file (transcript): each ``*.jsonl`` is one session, so read
+ and edit history never leaks across sessions.
+ """
+ seq = 0
+ #: Read tool_use id -> (file_path, is_partial, seq_at_use), awaiting result.
+ pending: dict[str, tuple[str, bool, int]] = {}
+ last_read_seq: dict[str, int] = {}
+ last_edit_seq: dict[str, int] = {}
+
+ with path.open(encoding="utf-8", errors="replace") as fh:
+ for raw in fh:
+ if '"tool_use"' in raw:
+ seq = _collect_tool_use(raw, cutoff, repo_prefix, seq, pending, last_edit_seq)
+ elif pending and '"tool_result"' in raw:
+ _collect_result(raw, pending, last_read_seq, last_edit_seq, repo_root, per_file)
+
+
+def _collect_tool_use(
+ raw: str,
+ cutoff: float,
+ repo_prefix: str,
+ seq: int,
+ pending: dict[str, tuple[str, bool, int]],
+ last_edit_seq: dict[str, int],
+) -> int:
+ """Record Read tool_use ids (awaiting result) and Edit ordering. Returns seq."""
+ try:
+ entry = json.loads(raw)
+ except ValueError:
+ return seq
+ if entry.get("type") != "assistant":
+ return seq
+ ts = _parse_ts(entry.get("timestamp"))
+ if ts is not None and ts < cutoff:
+ return seq
+ cwd = str(entry.get("cwd") or "").lower().rstrip("\\/")
+ if not cwd.startswith(repo_prefix):
+ return seq
+ content = (entry.get("message") or {}).get("content")
+ if not isinstance(content, list):
+ return seq
+
+ seq += 1
+ for block in content:
+ if not isinstance(block, dict) or block.get("type") != "tool_use":
+ continue
+ name = block.get("name")
+ tool_input = block.get("input")
+ if not isinstance(tool_input, dict):
+ continue
+ file_path = tool_input.get("file_path") or tool_input.get("path")
+ if not isinstance(file_path, str) or not file_path.strip():
+ continue
+ if name == "Read":
+ partial = tool_input.get("offset") is not None or tool_input.get("limit") is not None
+ block_id = block.get("id")
+ if isinstance(block_id, str):
+ pending[block_id] = (file_path, partial, seq)
+ elif name in _MUTATING_TOOLS:
+ last_edit_seq[file_path] = seq
+ return seq
+
+
+def _collect_result(
+ raw: str,
+ pending: dict[str, tuple[str, bool, int]],
+ last_read_seq: dict[str, int],
+ last_edit_seq: dict[str, int],
+ repo_root: Path,
+ per_file: dict[str, dict[str, int]],
+) -> None:
+ try:
+ entry = json.loads(raw)
+ except ValueError:
+ return
+ content = (entry.get("message") or {}).get("content")
+ if not isinstance(content, list):
+ return
+ block_id = next(
+ (
+ b.get("tool_use_id")
+ for b in content
+ if isinstance(b, dict) and b.get("type") == "tool_result"
+ ),
+ None,
+ )
+ record = pending.pop(block_id, None) if isinstance(block_id, str) else None
+ if record is None:
+ return
+ file_path, partial, read_seq = record
+
+ prior_read = last_read_seq.get(file_path)
+ # A wasteful re-read: read before, no edit landed at or after that prior
+ # read, and this is a full read. An edit sharing the prior read's turn
+ # (same seq) counts as "edited since" and justifies the re-read, so the
+ # comparison is strict. Record this read's order regardless so the next
+ # re-read compares against the latest read.
+ is_waste = (
+ prior_read is not None and not partial and last_edit_seq.get(file_path, -1) < prior_read
+ )
+ last_read_seq[file_path] = read_seq
+ if not is_waste:
+ return
+
+ output = _read_output_text(entry.get("toolUseResult"))
+ if not output:
+ return
+ raw_tokens = estimate_tokens(output)
+ est = int(raw_tokens * REREAD_FLOOR)
+ if est < _MIN_EST_TOKENS:
+ return
+
+ key = _rel(file_path, repo_root)
+ stats = per_file.setdefault(key, {"events": 0, "raw_tokens": 0, "est_saved_tokens": 0})
+ stats["events"] += 1
+ stats["raw_tokens"] += raw_tokens
+ stats["est_saved_tokens"] += est
+
+
+def _read_output_text(result: Any) -> str:
+ """File content from a Read ``toolUseResult``, tolerating shape drift.
+
+ Claude Code serializes a Read result as ``{"type": "text", "file":
+ {"content": "...", ...}}``; older or partial shapes may carry a plain
+ string. Anything else yields an empty string (skipped).
+ """
+ if isinstance(result, str):
+ return result
+ if isinstance(result, dict):
+ file_block = result.get("file")
+ if isinstance(file_block, dict):
+ content = file_block.get("content")
+ if isinstance(content, str):
+ return content
+ content = result.get("content")
+ if isinstance(content, str):
+ return content
+ return ""
diff --git a/packages/server/src/repowise/server/routers/costs.py b/packages/server/src/repowise/server/routers/costs.py
index be3b3e2df..d3c775eea 100644
--- a/packages/server/src/repowise/server/routers/costs.py
+++ b/packages/server/src/repowise/server/routers/costs.py
@@ -174,8 +174,10 @@ async def get_distill_savings(
# Missed savings: best-effort scan of local agent transcripts; the module
# degrades to an empty report on any failure, never raises.
from repowise.core.distill.missed import scan_missed_savings
+ from repowise.core.distill.missed_mcp import scan_missed_mcp_savings
missed = scan_missed_savings(Path(repo.local_path))
+ reread = scan_missed_mcp_savings(Path(repo.local_path))
# Price at the coding agent's actual model — saved tokens are input tokens
# that agent never had to read. Detection is best-effort (sonnet default).
@@ -209,4 +211,6 @@ async def get_distill_savings(
missed_events=missed["events"],
missed_tokens_est=missed["est_saved_tokens"],
missed_window_days=missed["window_days"],
+ reread_events=reread["events"],
+ reread_tokens_est=reread["est_saved_tokens"],
)
diff --git a/packages/server/src/repowise/server/schemas/ui_helpers.py b/packages/server/src/repowise/server/schemas/ui_helpers.py
index 42cbedb5f..6402ef644 100644
--- a/packages/server/src/repowise/server/schemas/ui_helpers.py
+++ b/packages/server/src/repowise/server/schemas/ui_helpers.py
@@ -98,3 +98,7 @@ class DistillSavingsResponse(BaseModel):
missed_events: int = 0
missed_tokens_est: int = 0
missed_window_days: float = 0.0
+ # Missed MCP savings — full re-reads of unchanged files a targeted
+ # get_symbol / range read would have replaced, same transcript scan.
+ reread_events: int = 0
+ reread_tokens_est: int = 0
diff --git a/packages/ui/src/costs/distill-savings-card.tsx b/packages/ui/src/costs/distill-savings-card.tsx
index 7461ecbfd..67d076fc8 100644
--- a/packages/ui/src/costs/distill-savings-card.tsx
+++ b/packages/ui/src/costs/distill-savings-card.tsx
@@ -41,6 +41,9 @@ export interface DistillSavingsData {
missed_events?: number;
missed_tokens_est?: number;
missed_window_days?: number;
+ /** Full re-reads of unchanged files a targeted get_symbol would have replaced. */
+ reread_events?: number;
+ reread_tokens_est?: number;
}
export interface DistillSavingsCardProps {
@@ -110,6 +113,7 @@ export function DistillSavingsCard({ data }: DistillSavingsCardProps) {
const priced = agentLabel(data.pricing_agent) || data.pricing_model;
const detected = data.pricing_source && data.pricing_source !== "default";
const missed = (data.missed_tokens_est ?? 0) > 0;
+ const reread = (data.reread_tokens_est ?? 0) > 0;
// Prefer the counterfactual framing ("N queries answered") when any MCP call
// recorded a real saving; fall back to the truncation-drop count otherwise.
@@ -240,6 +244,21 @@ export function DistillSavingsCard({ data }: DistillSavingsCardProps) {
</a>
)}
+ {/* Re-read waste → MCP opportunity CTA */}
+ {reread && (
+ <div className="mt-3 flex items-center gap-3 rounded-lg border border-[var(--color-warning)]/30 bg-[var(--color-warning)]/5 px-3 py-2.5">
+ <Zap className="h-4 w-4 shrink-0 text-[var(--color-warning)]" />
+ <div className="text-xs text-[var(--color-text-secondary)]">
+ <span className="font-medium text-[var(--color-warning)]">
+ Save ~{formatTokens(data.reread_tokens_est ?? 0)} more
+ </span>{" "}
+ — {(data.reread_events ?? 0).toLocaleString()} full re-read
+ {(data.reread_events ?? 0) === 1 ? "" : "s"} of unchanged files a targeted{" "}
+ <code>get_symbol</code> would have replaced.
+ </div>
+ </div>
+ )}
+
<p className="mt-3 text-xs leading-snug text-[var(--color-text-tertiary)]">
Distill counts <code>repowise distill</code> command/hook savings; MCP counts the raw
file exploration each tool answer replaced (plus any over-budget content trimmed). Saved
diff --git a/tests/unit/cli/test_editor_setup.py b/tests/unit/cli/test_editor_setup.py
index bc50eeeec..fea689ba9 100644
--- a/tests/unit/cli/test_editor_setup.py
+++ b/tests/unit/cli/test_editor_setup.py
@@ -1,6 +1,7 @@
from __future__ import annotations
import inspect
+import json
from io import StringIO
from pathlib import Path
from typing import Any
@@ -608,9 +609,14 @@ def test_claude_client_registration_uses_existing_claude_setup(
calls.append(("hooks", tmp_path))
return tmp_path / ".claude" / "settings.json"
+ def fake_tool_search() -> Path:
+ calls.append(("tool_search", tmp_path))
+ return tmp_path / ".claude" / "settings.json"
+
monkeypatch.setattr(claude_config, "register_with_claude_desktop", fake_desktop)
monkeypatch.setattr(claude_config, "register_with_claude_code", fake_code)
monkeypatch.setattr(claude_config, "install_claude_code_hooks", fake_hooks)
+ monkeypatch.setattr(claude_config, "enable_tool_search_in_claude_code", fake_tool_search)
output = StringIO()
console = Console(file=output, force_terminal=False)
@@ -621,8 +627,44 @@ def test_claude_client_registration_uses_existing_claude_setup(
("desktop", tmp_path),
("code", tmp_path),
("hooks", tmp_path),
+ ("tool_search", tmp_path),
]
text = output.getvalue()
assert "Claude Desktop MCP registered" in text
assert "Claude Code MCP registered" in text
assert "Claude Code hooks registered" in text
+ assert "tool-search enabled" in text
+
+
+def test_enable_tool_search_sets_env_idempotently(tmp_path: Path, monkeypatch: Any) -> None:
+ settings = tmp_path / ".claude" / "settings.json"
+ monkeypatch.setattr(claude_config, "_claude_code_settings_path", lambda: settings)
+
+ # First call creates the env block and sets the flag.
+ assert claude_config.enable_tool_search_in_claude_code() == settings
+ data = json.loads(settings.read_text(encoding="utf-8"))
+ assert data["env"]["ENABLE_TOOL_SEARCH"] == "true"
+
+ # Idempotent: a second call leaves it set but reports nothing new to do.
+ assert claude_config.enable_tool_search_in_claude_code() is None
+
+ # A user's explicit value is never overwritten.
+ settings.write_text(json.dumps({"env": {"ENABLE_TOOL_SEARCH": "false"}}), encoding="utf-8")
+ assert claude_config.enable_tool_search_in_claude_code() is None
+ data = json.loads(settings.read_text(encoding="utf-8"))
+ assert data["env"]["ENABLE_TOOL_SEARCH"] == "false"
+
+
+def test_enable_tool_search_preserves_existing_settings(tmp_path: Path, monkeypatch: Any) -> None:
+ settings = tmp_path / ".claude" / "settings.json"
+ settings.parent.mkdir(parents=True, exist_ok=True)
+ settings.write_text(
+ json.dumps({"env": {"FOO": "bar"}, "mcpServers": {"repowise": {}}}),
+ encoding="utf-8",
+ )
+ monkeypatch.setattr(claude_config, "_claude_code_settings_path", lambda: settings)
+
+ assert claude_config.enable_tool_search_in_claude_code() == settings
+ data = json.loads(settings.read_text(encoding="utf-8"))
+ assert data["env"] == {"FOO": "bar", "ENABLE_TOOL_SEARCH": "true"}
+ assert data["mcpServers"] == {"repowise": {}}
diff --git a/tests/unit/distill/test_allow_rule.py b/tests/unit/distill/test_allow_rule.py
index afb0fe270..a7e1e55a1 100644
--- a/tests/unit/distill/test_allow_rule.py
+++ b/tests/unit/distill/test_allow_rule.py
@@ -113,8 +113,9 @@ class TestRewriteInstallFlag:
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.
+ def test_default_adds_no_rule(self, repo, settings_path) -> None:
+ # The default `allow` posture rewrites without a prompt, so install
+ # seeds no allowlist entry unless --allow-rule is passed explicitly.
result = self._invoke(["rewrite", "install", str(repo)])
assert result.exit_code == 0, result.output
data = json.loads(settings_path.read_text(encoding="utf-8"))
diff --git a/tests/unit/distill/test_missed_mcp.py b/tests/unit/distill/test_missed_mcp.py
new file mode 100644
index 000000000..3b4501422
--- /dev/null
+++ b/tests/unit/distill/test_missed_mcp.py
@@ -0,0 +1,305 @@
+"""Missed MCP savings — wasteful file re-read detection over transcripts.
+
+Transcript lines follow the Claude Code JSONL shape: an assistant entry with
+``message.content[]`` ``tool_use`` blocks plus top-level ``cwd``/``timestamp``,
+and a paired user entry carrying ``message.content[].tool_result`` plus a
+top-level ``toolUseResult`` (for Read: ``{"type": "text", "file": {...}}``).
+"""
+
+from __future__ import annotations
+
+import json
+import time
+from datetime import UTC, datetime
+from pathlib import Path
+
+import pytest
+from click.testing import CliRunner
+
+from repowise.cli.commands.saved_cmd import saved_command
+from repowise.core.distill.budget import estimate_tokens
+from repowise.core.distill.missed import transcript_dir_for
+from repowise.core.distill.missed_mcp import REREAD_FLOOR, scan_missed_mcp_savings
+
+NOW = time.time()
+
+#: Big enough that half its tokens clear the net-positive floor (40).
+BIG_CONTENT = "x = 1 # padding padding padding\n" * 120
+
+
+def _iso(ts: float) -> str:
+ return datetime.fromtimestamp(ts, tz=UTC).strftime("%Y-%m-%dT%H:%M:%S.%fZ")
+
+
+def _read_pair(
+ file_path: str,
+ content: str,
+ *,
+ cwd: str,
+ block_id: str,
+ ts: float = NOW,
+ offset: int | None = None,
+ limit: int | None = None,
+) -> list[dict]:
+ tool_input: dict = {"file_path": file_path}
+ if offset is not None:
+ tool_input["offset"] = offset
+ if limit is not None:
+ tool_input["limit"] = limit
+ return [
+ {
+ "type": "assistant",
+ "cwd": cwd,
+ "timestamp": _iso(ts),
+ "message": {
+ "role": "assistant",
+ "content": [
+ {"type": "tool_use", "id": block_id, "name": "Read", "input": tool_input}
+ ],
+ },
+ },
+ {
+ "type": "user",
+ "cwd": cwd,
+ "timestamp": _iso(ts + 1),
+ "message": {
+ "role": "user",
+ "content": [{"type": "tool_result", "tool_use_id": block_id, "content": "..."}],
+ },
+ "toolUseResult": {
+ "type": "text",
+ "file": {
+ "filePath": file_path,
+ "content": content,
+ "numLines": content.count("\n"),
+ },
+ },
+ },
+ ]
+
+
+def _edit_entry(file_path: str, *, cwd: str, ts: float = NOW, tool: str = "Edit") -> dict:
+ return {
+ "type": "assistant",
+ "cwd": cwd,
+ "timestamp": _iso(ts),
+ "message": {
+ "role": "assistant",
+ "content": [
+ {"type": "tool_use", "id": "ed1", "name": tool, "input": {"file_path": file_path}}
+ ],
+ },
+ }
+
+
+def repo(tmp_path: Path) -> Path:
+ root = tmp_path / "myrepo"
+ (root / ".repowise").mkdir(parents=True)
+ return root
+
+
+def projects(tmp_path: Path, repo: Path) -> Path:
+ root = tmp_path / "projects"
+ transcript_dir_for(repo, root).mkdir(parents=True)
+ return root
+
+
+def _write_session(projects: Path, repo: Path, entries: list[dict], name: str = "s1") -> Path:
+ path = transcript_dir_for(repo, projects) / f"{name}.jsonl"
+ path.write_text("\n".join(json.dumps(e) for e in entries) + "\n", encoding="utf-8")
+ return path
+
+
+def test_full_reread_of_unchanged_file_counted(repo: Path, projects: Path) -> None:
+ f = str(repo / "a.py")
+ entries = _read_pair(f, BIG_CONTENT, cwd=str(repo), block_id="r1") + _read_pair(
+ f, BIG_CONTENT, cwd=str(repo), block_id="r2"
+ )
+ _write_session(projects, repo, entries)
+ report = scan_missed_mcp_savings(repo, projects_root=projects, now=NOW + 10)
+ assert report["events"] == 1
+ raw = estimate_tokens(BIG_CONTENT)
+ assert report["per_file"]["a.py"]["raw_tokens"] == raw
+ assert report["est_saved_tokens"] == int(raw * REREAD_FLOOR)
+
+
+def test_single_read_not_counted(repo: Path, projects: Path) -> None:
+ f = str(repo / "a.py")
+ _write_session(projects, repo, _read_pair(f, BIG_CONTENT, cwd=str(repo), block_id="r1"))
+ report = scan_missed_mcp_savings(repo, projects_root=projects, now=NOW + 10)
+ assert report["events"] == 0
+
+
+def test_partial_reread_not_counted(repo: Path, projects: Path) -> None:
+ f = str(repo / "a.py")
+ entries = _read_pair(f, BIG_CONTENT, cwd=str(repo), block_id="r1") + _read_pair(
+ f, BIG_CONTENT, cwd=str(repo), block_id="r2", offset=10, limit=20
+ )
+ _write_session(projects, repo, entries)
+ report = scan_missed_mcp_savings(repo, projects_root=projects, now=NOW + 10)
+ assert report["events"] == 0
+
+
+def test_edit_between_reads_is_not_waste(repo: Path, projects: Path) -> None:
+ f = str(repo / "a.py")
+ entries = [
+ *_read_pair(f, BIG_CONTENT, cwd=str(repo), block_id="r1"),
+ _edit_entry(f, cwd=str(repo)),
+ *_read_pair(f, BIG_CONTENT, cwd=str(repo), block_id="r2"),
+ ]
+ _write_session(projects, repo, entries)
+ report = scan_missed_mcp_savings(repo, projects_root=projects, now=NOW + 10)
+ assert report["events"] == 0
+
+
+def test_three_full_reads_count_two(repo: Path, projects: Path) -> None:
+ f = str(repo / "a.py")
+ entries = (
+ _read_pair(f, BIG_CONTENT, cwd=str(repo), block_id="r1")
+ + _read_pair(f, BIG_CONTENT, cwd=str(repo), block_id="r2")
+ + _read_pair(f, BIG_CONTENT, cwd=str(repo), block_id="r3")
+ )
+ _write_session(projects, repo, entries)
+ report = scan_missed_mcp_savings(repo, projects_root=projects, now=NOW + 10)
+ assert report["events"] == 2
+
+
+def test_tiny_reread_below_floor_skipped(repo: Path, projects: Path) -> None:
+ f = str(repo / "a.py")
+ entries = _read_pair(f, "ok\n", cwd=str(repo), block_id="r1") + _read_pair(
+ f, "ok\n", cwd=str(repo), block_id="r2"
+ )
+ _write_session(projects, repo, entries)
+ report = scan_missed_mcp_savings(repo, projects_root=projects, now=NOW + 10)
+ assert report["events"] == 0
+
+
+def test_other_cwd_skipped(repo: Path, projects: Path) -> None:
+ f = str(repo / "a.py")
+ entries = _read_pair(f, BIG_CONTENT, cwd=r"C:\elsewhere", block_id="r1") + _read_pair(
+ f, BIG_CONTENT, cwd=r"C:\elsewhere", block_id="r2"
+ )
+ _write_session(projects, repo, entries)
+ report = scan_missed_mcp_savings(repo, projects_root=projects, now=NOW + 10)
+ assert report["events"] == 0
+
+
+def test_distinct_files_isolated(repo: Path, projects: Path) -> None:
+ a, b = str(repo / "a.py"), str(repo / "b.py")
+ entries = _read_pair(a, BIG_CONTENT, cwd=str(repo), block_id="r1") + _read_pair(
+ b, BIG_CONTENT, cwd=str(repo), block_id="r2"
+ )
+ _write_session(projects, repo, entries)
+ report = scan_missed_mcp_savings(repo, projects_root=projects, now=NOW + 10)
+ assert report["events"] == 0
+
+
+def test_old_entries_outside_window_skipped(repo: Path, projects: Path) -> None:
+ f = str(repo / "a.py")
+ entries = _read_pair(f, BIG_CONTENT, cwd=str(repo), block_id="r1", ts=NOW - 10 * 86400) + (
+ _read_pair(f, BIG_CONTENT, cwd=str(repo), block_id="r2", ts=NOW - 10 * 86400)
+ )
+ path = _write_session(projects, repo, entries)
+ import os
+
+ os.utime(path, (NOW, NOW)) # fresh mtime so only the per-entry gate applies
+ report = scan_missed_mcp_savings(repo, projects_root=projects, days=7, now=NOW)
+ assert report["events"] == 0
+
+
+def test_new_session_forgets_history(repo: Path, projects: Path) -> None:
+ f = str(repo / "a.py")
+ _write_session(
+ projects, repo, _read_pair(f, BIG_CONTENT, cwd=str(repo), block_id="r1"), name="s1"
+ )
+ _write_session(
+ projects, repo, _read_pair(f, BIG_CONTENT, cwd=str(repo), block_id="r2"), name="s2"
+ )
+ report = scan_missed_mcp_savings(repo, projects_root=projects, now=NOW + 10)
+ assert report["events"] == 0
+
+
+def test_malformed_lines_tolerated(repo: Path, projects: Path) -> None:
+ good = _read_pair(str(repo / "a.py"), BIG_CONTENT, cwd=str(repo), block_id="r1") + _read_pair(
+ str(repo / "a.py"), BIG_CONTENT, cwd=str(repo), block_id="r2"
+ )
+ path = transcript_dir_for(repo, projects) / "s1.jsonl"
+ path.write_text(
+ '{"tool_use" broken\n' + "\n".join(json.dumps(e) for e in good) + "\n", encoding="utf-8"
+ )
+ report = scan_missed_mcp_savings(repo, projects_root=projects, now=NOW + 10)
+ assert report["events"] == 1
+
+
+def test_edit_in_same_turn_as_read_is_not_waste(repo: Path, projects: Path) -> None:
+ # A Read and an Edit emitted in the SAME assistant turn share a seq; the
+ # edit counts as "edited since", so a later re-read is justified, not waste.
+ f = str(repo / "a.py")
+ combo = {
+ "type": "assistant",
+ "cwd": str(repo),
+ "timestamp": _iso(NOW),
+ "message": {
+ "role": "assistant",
+ "content": [
+ {"type": "tool_use", "id": "r1", "name": "Read", "input": {"file_path": f}},
+ {"type": "tool_use", "id": "ed", "name": "Edit", "input": {"file_path": f}},
+ ],
+ },
+ }
+ combo_result = {
+ "type": "user",
+ "cwd": str(repo),
+ "timestamp": _iso(NOW + 1),
+ "message": {
+ "role": "user",
+ "content": [{"type": "tool_result", "tool_use_id": "r1", "content": "..."}],
+ },
+ "toolUseResult": {"type": "text", "file": {"filePath": f, "content": BIG_CONTENT}},
+ }
+ entries = [combo, combo_result, *_read_pair(f, BIG_CONTENT, cwd=str(repo), block_id="r2")]
+ _write_session(projects, repo, entries)
+ report = scan_missed_mcp_savings(repo, projects_root=projects, now=NOW + 10)
+ assert report["events"] == 0
+
+
+def test_read_output_text_shapes() -> None:
+ from repowise.core.distill.missed_mcp import _read_output_text
+
+ assert _read_output_text("plain string") == "plain string"
+ assert _read_output_text({"type": "text", "file": {"content": "c"}}) == "c"
+ assert _read_output_text({"content": "fallback"}) == "fallback"
+ assert _read_output_text({"file": {"numLines": 3}}) == ""
+ assert _read_output_text(None) == ""
+
+
+def test_absent_transcript_dir_is_empty_report(repo: Path, tmp_path: Path) -> None:
+ report = scan_missed_mcp_savings(repo, projects_root=tmp_path / "nowhere")
+ assert report == {
+ "events": 0,
+ "raw_tokens": 0,
+ "est_saved_tokens": 0,
+ "per_file": {},
+ "window_days": 7.0,
+ }
+
+
+# -- CLI surface --------------------------------------------------------------
+
+
+def test_saved_missed_shows_reread_table(repo: Path, projects: Path, monkeypatch) -> None:
+ f = str(repo / "a.py")
+ entries = _read_pair(f, BIG_CONTENT, cwd=str(repo), block_id="r1") + _read_pair(
+ f, BIG_CONTENT, cwd=str(repo), block_id="r2"
+ )
+ _write_session(projects, repo, entries)
+ monkeypatch.setattr(
+ "repowise.core.distill.missed_mcp.transcript_dir_for",
+ lambda root, projects_root=None: transcript_dir_for(root, projects),
+ )
+ result = CliRunner().invoke(saved_command, ["--missed", str(repo)])
+ assert result.exit_code == 0
+ assert "file re-reads" in result.output
+ assert "Estimated foregone" in result.output
diff --git a/tests/unit/distill/test_read_intelligence.py b/tests/unit/distill/test_read_intelligence.py
index 82ea54a5e..aa98d3eae 100644
--- a/tests/unit/distill/test_read_intelligence.py
+++ b/tests/unit/distill/test_read_intelligence.py
@@ -87,12 +87,18 @@ class TestSkeletonNudge:
_write_big_file(repo, "src/big.py")
_index_file(repo, "src/big.py", [(10, 60), (70, 150), (160, 195)])
- assert _read_event(repo, "src/big.py") is not None
- # Identical payload, same session: silent.
+ first = _read_event(repo, "src/big.py")
+ assert first is not None and 'include=["skeleton"]' in first
+ # Second read of the same big file surfaces a re-read notice (content
+ # already in context), not a second skeleton pointer.
+ second = _read_event(repo, "src/big.py")
+ assert second is not None and 'include=["skeleton"]' not in second
+ assert "already read" in second
+ # Third read: both the skeleton and re-read notices are once-per-file.
assert _read_event(repo, "src/big.py") is None
- assert _read_event(repo, "src/big.py") is None
- # A new session resets the claim.
- assert _read_event(repo, "src/big.py", session="session-2") is not None
+ # A new session resets the claim — skeleton pointer fires again.
+ third_session = _read_event(repo, "src/big.py", session="session-2")
+ assert third_session is not None and 'include=["skeleton"]' in third_session
def test_silent_below_line_threshold(self, repo: Path) -> None:
_write_big_file(repo, "src/big.py")
@@ -205,6 +211,53 @@ class TestStaleReadNotice:
assert state["edits"] == {}
+class TestRereadNotice:
+ def test_full_reread_of_unchanged_file_is_flagged(self, repo: Path) -> None:
+ _write_big_file(repo, "a.py", lines=200)
+ assert _read_event(repo, "a.py", num_lines=150) is None # first read
+ notice = _read_event(repo, "a.py", num_lines=150)
+ assert notice is not None
+ assert "a.py" in notice and "already read" in notice
+ assert "get_symbol" in notice
+
+ def test_notice_is_once_per_file_per_session(self, repo: Path) -> None:
+ _write_big_file(repo, "a.py", lines=200)
+ _read_event(repo, "a.py", num_lines=150)
+ assert _read_event(repo, "a.py", num_lines=150) is not None
+ assert _read_event(repo, "a.py", num_lines=150) is None
+
+ def test_partial_reread_is_not_flagged(self, repo: Path) -> None:
+ # A targeted range re-read is the behavior we recommend; never nag it.
+ _write_big_file(repo, "a.py", lines=200)
+ _read_event(repo, "a.py", num_lines=150)
+ result = _handle_post_tool_use(
+ "Read",
+ {"file_path": str(repo / "a.py"), "offset": 40, "limit": 30},
+ {"file": {"numLines": 30}},
+ str(repo),
+ session_id=SESSION,
+ )
+ assert result is None
+
+ def test_small_file_reread_is_not_flagged(self, repo: Path) -> None:
+ _write_big_file(repo, "a.py", lines=10)
+ assert _read_event(repo, "a.py", num_lines=10) is None
+ assert _read_event(repo, "a.py", num_lines=10) is None
+
+ def test_edit_between_reads_is_stale_not_reread(self, repo: Path) -> None:
+ _write_big_file(repo, "a.py", lines=200)
+ _read_event(repo, "a.py", num_lines=150)
+ _edit_event(repo, "a.py")
+ notice = _read_event(repo, "a.py", num_lines=150)
+ assert notice is not None and "stale" in notice
+ assert "already read" not in notice
+
+ def test_new_session_forgets_history(self, repo: Path) -> None:
+ _write_big_file(repo, "a.py", lines=200)
+ _read_event(repo, "a.py", num_lines=150)
+ assert _read_event(repo, "a.py", num_lines=150, session="other") is None
+
+
class TestSessionState:
def test_state_file_lives_under_repowise(self, repo: Path) -> None:
_write_big_file(repo, "a.py", lines=10)
diff --git a/tests/unit/distill/test_rewrite_hook.py b/tests/unit/distill/test_rewrite_hook.py
index a06bb4192..ef8b9d86c 100644
--- a/tests/unit/distill/test_rewrite_hook.py
+++ b/tests/unit/distill/test_rewrite_hook.py
@@ -187,11 +187,11 @@ def _write_config(repo, distill_block) -> None:
class TestDecide:
- def test_default_is_ask(self, repo) -> None:
+ def test_default_is_allow(self, repo) -> None:
result = decide("pytest -x", str(repo))
assert result is not None
assert result.command == "repowise distill --source hook-bash pytest -x"
- assert result.permission == "ask"
+ assert result.permission == "allow"
assert "repowise expand" in result.reason
def test_no_repowise_dir_passes_through(self, tmp_path) -> None:
@@ -218,11 +218,17 @@ class TestDecide:
_write_config(repo, {"commands": {"permission": "allow"}})
assert decide("git status", str(repo)).permission == "allow"
- def test_family_allow_overrides_ask(self, repo) -> None:
- _write_config(repo, {"commands": {"families": {"git_status": "allow"}}})
+ def test_family_setting_overrides_default(self, repo) -> None:
+ # A per-family `ask` overrides the default `allow`; an unlisted family
+ # keeps the default.
+ _write_config(repo, {"commands": {"families": {"test_output": "ask"}}})
assert decide("git status", str(repo)).permission == "allow"
assert decide("pytest -x", str(repo)).permission == "ask"
+ def test_global_ask_posture(self, repo) -> None:
+ _write_config(repo, {"commands": {"permission": "ask"}})
+ assert decide("git status", str(repo)).permission == "ask"
+
def test_family_off_disables_one_family(self, repo) -> None:
_write_config(repo, {"commands": {"families": {"git_diff": "off"}}})
assert decide("git diff main", str(repo)) is None
@@ -232,12 +238,12 @@ class TestDecide:
_write_config(repo, {"commands": {"families": {"git_diff": "deny"}}})
assert decide("git diff main", str(repo)) is None
- def test_malformed_config_defaults_to_ask(self, repo) -> None:
+ def test_malformed_config_defaults_to_allow(self, repo) -> None:
(repo / ".repowise" / "config.yaml").write_text(
"distill: [not, a, mapping", encoding="utf-8"
)
result = decide("pytest -x", str(repo))
- assert result is not None and result.permission == "ask"
+ assert result is not None and result.permission == "allow"
class TestDecidePowerShell:
@@ -274,7 +280,7 @@ class TestDecidePowerShell:
result = decide(command, str(repo), shell="powershell")
assert result is not None
assert result.command == f"repowise distill --source hook-powershell {command}"
- assert result.permission == "ask"
+ assert result.permission == "allow"
# ---------------------------------------------------------------------------
@@ -313,7 +319,7 @@ class TestMain:
response = json.loads(out)
hso = response["hookSpecificOutput"]
assert hso["hookEventName"] == "PreToolUse"
- assert hso["permissionDecision"] == "ask"
+ assert hso["permissionDecision"] == "allow"
assert hso["updatedInput"] == {"command": "repowise distill --source hook-bash pytest -x"}
assert hso["permissionDecisionReason"]
@@ -329,7 +335,7 @@ class TestMain:
assert hso["updatedInput"] == {
"command": "repowise distill --source hook-powershell git status"
}
- assert hso["permissionDecision"] == "ask"
+ assert hso["permissionDecision"] == "allow"
def test_powershell_alias_passes_through(self, monkeypatch, repo) -> None:
assert _run_main(monkeypatch, _payload("ls -la", str(repo), tool_name="PowerShell")) == ""
@@ -354,10 +360,21 @@ class TestMainCodex:
"""
def test_ask_family_passes_through(self, monkeypatch, repo) -> None:
- # Default posture is ask → Codex gets nothing, command runs raw.
+ # An explicit `ask` posture → Codex has no ask-with-mutation, so the
+ # command runs raw instead of silently escalating to an unprompted
+ # rewrite.
+ _write_config(repo, {"commands": {"permission": "ask"}})
out = _run_main(monkeypatch, _payload("pytest -x", str(repo)), argv=["--agent", "codex"])
assert out == ""
+ def test_default_allow_rewrites_for_codex(self, monkeypatch, repo) -> None:
+ # The default `allow` posture is honorable by Codex, so a plain repo
+ # rewrites without any config.
+ out = _run_main(monkeypatch, _payload("pytest -x", str(repo)), argv=["--agent", "codex"])
+ hso = json.loads(out)["hookSpecificOutput"]
+ assert hso["permissionDecision"] == "allow"
+ assert hso["updatedInput"] == {"command": "repowise distill --source hook-codex pytest -x"}
+
def test_allow_family_rewrites(self, monkeypatch, repo) -> None:
_write_config(repo, {"commands": {"families": {"test_output": "allow"}}})
out = _run_main(monkeypatch, _payload("pytest -x", str(repo)), argv=["--agent", "codex"])
@@ -379,4 +396,4 @@ class TestMainCodex:
def test_unknown_agent_falls_back_to_claude_code(self, monkeypatch, repo) -> None:
out = _run_main(monkeypatch, _payload("pytest -x", str(repo)), argv=["--agent", "weird"])
- assert json.loads(out)["hookSpecificOutput"]["permissionDecision"] == "ask"
+ assert json.loads(out)["hookSpecificOutput"]["permissionDecision"] == "allow"