Codebase intelligence for AI and humans: code health scores, auto-generated docs, git analytics, dead code detection, and architectural decisions via MCP.
Python aicode-complexitycode-healthcode-intelligencecode-qualitydead-codedeveloper-toolsdocumentationgit-analyticsmcpopen-sourcepythonrefactoringstatic-analysistechnical-debt
feat(hooks): the search flood is served as its digest, not ranked beside it (#1283)
Raghav Chamadiyabbd4b4531e43
diff --git a/docs/agent/HOOKS.md b/docs/agent/HOOKS.mdindex 6dbbf0516..72d6e0060 100644--- a/docs/agent/HOOKS.md+++ b/docs/agent/HOOKS.md@@ -122,6 +122,25 @@ what it depends on, and that it is a hotspot, without a separate MCP call:Git: HOTSPOT, bus-factor=1, owner=RaghavChamadiya```+**Search-flood digests.** A grep that returns 50+ matches also gets a compact+per-file digest: every matched file with its match count and two anchor line+numbers, ranked by graph centrality when the index can rank them, and an explicit+`(N more files, M matches)` tail for anything past the top ten.++With `hooks.search_digest: true` in `.repowise/config.yaml`, written by the same+yes/no as the rewrite hook, and toggled afterwards with `repowise hook+search-digest install | uninstall | status`, that digest *replaces* the raw+match list rather than riding alongside it. Re-run the search scoped to a file it+names, or read those lines directly, to see any match in full. Savings appear in+`repowise saved` under the `search_digest` filter, and a repo with it off still+gets the counterfactual number.++Two cases are deliberately left alone. A **single-file context grep** (`-C`,+`-A`, `-B`) is never digested: that context is exactly what the agent asked for,+and Claude Code renders those results without a path prefix, so they are not+parsed as a multi-file flood in the first place. And `files_with_matches` results+carry no match text to replace: the file list is already a digest.+**Git/edit freshness.** After a successful `git commit`, `merge`, `rebase`,`cherry-pick`, or `pull`, repowise compares `HEAD` against the last indexed commitin `.repowise/state.json` and, if the wiki is behind, reminds the agent to run@@ -146,9 +165,7 @@ filter. In a repo that has it off, the same Reads are still *measured*, and`repowise saved` reports what they would have saved — a number about size only,never about whether the agent could work from a skeleton.-This is the only hook that replaces a tool result rather than adding to it, which-is why it ships opt-in and why the skeleton always says what it removed. One-consequence is worth knowing: a Read the agent saw only as a skeleton still+One consequence is worth knowing: a Read the agent saw only as a skeleton stillsatisfies Claude Code's read-before-edit precondition, so an `Edit` (especiallywith `replace_all`) or a `Write` could touch bodies it never saw. Editing such afile raises a one-line warning, once per file, until the file is read in full.diff --git a/packages/cli/src/repowise/cli/commands/augment_cmd/_shared.py b/packages/cli/src/repowise/cli/commands/augment_cmd/_shared.pyindex d823b67fa..b0f9d7131 100644--- a/packages/cli/src/repowise/cli/commands/augment_cmd/_shared.py+++ b/packages/cli/src/repowise/cli/commands/augment_cmd/_shared.py@@ -122,6 +122,152 @@ def _extract_output_text(tool_output: object) -> str:return ""+#: Hard ceiling on an ``updatedToolOutput`` string. Undocumented but observed;+#: a replacement that does not fit is skipped rather than cut, because the+#: elision markers that make an omission recoverable live at the end.+MAX_OUTPUT_CHARS = 10_000+++def hook_flag_enabled(repo_path: Path, flag: str) -> bool:+ """True when ``hooks.<flag>`` is on for this repo. Fails closed.++ Every hook surface that *replaces* a tool result is opt-in behind one of+ these, and they are all written by the single init consent (see+ :func:`repowise.cli.helpers.save_hook_surface_enabled`). The env override+ is ``REPOWISE_HOOK_<FLAG>``, upper-cased, for a one-session A/B.++ Deliberately not :func:`repowise.core.repo_config.load_repo_config`: that+ import is not free and this runs before the gates that would justify it.+ Same open-plus-lazy-yaml shape as ``rewrite_hook._load_commands_config``,+ with the opposite default: that one fails open because distilling is on by+ default, these fail closed because replacing a tool result is not.+ """+ import os++ override = os.environ.get(f"REPOWISE_HOOK_{flag.upper()}")+ if override is not None:+ return override.strip().lower() in ("1", "true", "yes", "on")+ try:+ text = (repo_path / ".repowise" / "config.yaml").read_text(encoding="utf-8")+ except (OSError, ValueError):+ # ValueError covers UnicodeDecodeError: a config with a latin-1 byte in+ # it means "cannot tell", which for an opt-in means no.+ return False+ # Substring pre-check before the yaml import: a repo that has a config but+ # not this key is the common case, and it should not pay ~70ms to learn so.+ # The parse below is still what decides; this only rules out.+ if flag not in text:+ return False+ try:+ import yaml++ data = yaml.safe_load(text) or {}+ hooks = data.get("hooks")+ return bool(isinstance(hooks, dict) and hooks.get(flag) is True)+ except Exception:+ return False+++#: The counterfactual's own table. Deliberately *not* the ``savings`` ledger:+#: every row there is an event that happened, and ``repowise saved`` sums them+#: into a headline figure that is already published. A forgone saving did not+#: happen, and adding it to that sum would inflate a real number with a+#: hypothetical one, the precise misreading the caveat exists to prevent.+_FORGONE_TABLE_SQL = (+ "CREATE TABLE IF NOT EXISTS forgone_savings ("+ "created_at REAL NOT NULL, source TEXT NOT NULL, path TEXT NOT NULL, "+ "raw_tokens INTEGER NOT NULL, distilled_tokens INTEGER NOT NULL)"+)+++def _omission_db(repo_path: Path) -> Path | None:+ """The omission store, or None when this repo has not opted into one.++ Path spelled out rather than imported: the constants live in+ ``distill.store``, which imports structlog: 250ms to learn that a repo+ without an omission store has no omission store. Kept in sync by+ ``test_the_omission_store_path_matches_distills``.+ """+ db_path = repo_path / ".repowise" / "omissions" / "omissions.db"+ return db_path if db_path.exists() else None+++def record_saving(+ repo_path: Path,+ *,+ source: str,+ filter_name: str,+ command: str,+ raw_tokens: int,+ distilled_tokens: int,+) -> None:+ """Bill one replacement to the savings ledger so ``repowise saved`` sees it.++ Never creates the omission store: its absence means this repo has not+ opted into distill bookkeeping, and a hook is not the place to decide+ otherwise. Any failure is swallowed, because accounting must not cost the agent an+ enrichment that is already computed.+ """+ db_path = _omission_db(repo_path)+ if db_path is None:+ return+ try:+ import sqlite3++ from repowise.core.distill.tracking import record_saving as _record++ con = sqlite3.connect(str(db_path), timeout=2)+ try:+ _record(+ con,+ filter_name=filter_name,+ source=source,+ command=command,+ raw_tokens=raw_tokens,+ distilled_tokens=distilled_tokens,+ )+ finally:+ con.close()+ except Exception:+ return+++def record_forgone(+ repo_path: Path,+ *,+ source: str,+ path: str,+ raw_tokens: int,+ distilled_tokens: int,+) -> None:+ """Record a saving this repo *would* have made, had the surface been on.++ Same never-create-the-store rule as :func:`record_saving`, into the+ separate ``forgone_savings`` table so a hypothetical can never be summed+ into the published figure.+ """+ db_path = _omission_db(repo_path)+ if db_path is None:+ return+ try:+ import sqlite3++ con = sqlite3.connect(str(db_path), timeout=2)+ try:+ con.execute(_FORGONE_TABLE_SQL)+ con.execute(+ "INSERT INTO forgone_savings "+ "(created_at, source, path, raw_tokens, distilled_tokens) "+ "VALUES (?, ?, ?, ?, ?)",+ (time.time(), source, path, raw_tokens, distilled_tokens),+ )+ con.commit()+ finally:+ con.close()+ except Exception:+ return++def _relativize(file_path: str, repo_path: Path) -> str | None:"""Repo-relative POSIX path for *file_path*, or None when outside it."""try:diff --git a/packages/cli/src/repowise/cli/commands/augment_cmd/command.py b/packages/cli/src/repowise/cli/commands/augment_cmd/command.pyindex 657e3a974..af480ec81 100644--- a/packages/cli/src/repowise/cli/commands/augment_cmd/command.py+++ b/packages/cli/src/repowise/cli/commands/augment_cmd/command.py@@ -10,6 +10,11 @@ returns *nothing* most of the time, and only speaks up when there isasymmetric, durable value:PostToolUse → Grep / Glob+ * Flood digest: a multi-file grep flood is served as a compact+ per-file digest via updatedToolOutput, with match counts and anchor+ line numbers per file, with the dropped tail named. Opt-in+ (hooks.search_digest), default off, Claude Code only. Falls back+ to appending the same digest beside the flood, as it always did.* Zero-result rescue: grep returned 0 hits but the wiki has asemantic match (FTS on docs, fuzzy symbol match, decision recordmention). Surfaces the closest hit so the agent doesn't burn@@ -40,8 +45,7 @@ Codex SessionStart/UserPromptSubmit: adds short repowise MCP usage guidance.* Skeleton replacement: an unbounded Read of a large indexed file isserved as its skeleton via updatedToolOutput, elision markers and1-indexed line ranges intact, once per file per session. Opt-in- (hooks.read_skeleton), default off. This is the only handler that- changes what a tool returned rather than adding to it.+ (hooks.read_skeleton), default off.* Skeleton nudge: the fallback when the replacement does not apply —a one-line pointer at get_context(include=["skeleton"]) with a cheapbounds-arithmetic estimate.@@ -289,9 +293,10 @@ def _handle_post_tool_use() -> HookResult:"""Dispatch PostToolUse events from Claude or Codex.- Every branch but Read yields plain additional context, so they keep- returning ``str | None`` and :func:`as_result` lifts them here — the- two-field shape exists in one place rather than in eight.+ Read and Grep/Glob can replace the tool result, so they return a+ :class:`HookResult` themselves; every other branch yields plain additional+ context and keeps returning ``str | None``, which :func:`as_result` lifts+ here, so the two-field shape exists in one place rather than in eight."""# The edit-tool freshness notice is a Codex-only lifecycle hook, gated on# the Codex client so the widened Claude matcher (Read|Edit|Write) can't@@ -314,8 +319,10 @@ def _handle_post_tool_use(# stdout/stderr response shape as Bash — one handler covers both.return as_result(_handle_bash_post(tool_input, tool_output, cwd))if tool_name in ("Grep", "Glob"):- return as_result(- _handle_search_post(tool_name, tool_input, tool_output, cwd, session_id)+ # ``client`` reaches this one because the flood digest can *replace*+ # the tool output, and only Claude Code's protocol can honour that.+ return _handle_search_post(+ tool_name, tool_input, tool_output, cwd, session_id, client=client)if tool_name.startswith("mcp__") and "repowise" in tool_name.lower():# Served-content bookkeeping for the read-after-served KPI. Neverdiff --git a/packages/cli/src/repowise/cli/commands/augment_cmd/read_skeleton.py b/packages/cli/src/repowise/cli/commands/augment_cmd/read_skeleton.pyindex eedd7e7c4..4ca76c461 100644--- a/packages/cli/src/repowise/cli/commands/augment_cmd/read_skeleton.py+++ b/packages/cli/src/repowise/cli/commands/augment_cmd/read_skeleton.py@@ -41,6 +41,10 @@ import sqlite3from pathlib import Pathfrom typing import TYPE_CHECKING+from ._shared import MAX_OUTPUT_CHARS, hook_flag_enabled+from ._shared import record_forgone as _record_forgone+from ._shared import record_saving as _record_saving+if TYPE_CHECKING: # pragma: no cover - the hook path imports these lazilyfrom repowise.core.distill.skeleton import SkeletonResult, SkeletonSymbol@@ -49,10 +53,10 @@ if TYPE_CHECKING: # pragma: no cover - the hook path imports these lazily#: fall back to the nudge (see :func:`supports_updated_output`)._MIN_CLIENT_VERSION = (2, 1, 218)-#: Hard ceiling on the replacement string. Undocumented but observed; a-#: skeleton that does not fit is skipped rather than cut, because the tail-#: elision markers are what make the omission recoverable.-_MAX_OUTPUT_CHARS = 10_000+#: Hard ceiling on the replacement string; shared with every other replacing+#: surface. A skeleton that does not fit is skipped rather than cut, because+#: the tail elision markers are what make the omission recoverable.+_MAX_OUTPUT_CHARS = MAX_OUTPUT_CHARS#: Savings-ledger identity, so ``repowise saved`` can name this surface._SAVINGS_SOURCE = "hook-read"@@ -93,34 +97,11 @@ class Replacement:def enabled(repo_path: Path) -> bool:"""True when this repo opted into read replacement. Fails closed.- Deliberately not :func:`repowise.core.repo_config.load_repo_config`: that- import is not free and this runs before the gates that would justify it.- Same open-plus-lazy-yaml shape as ``rewrite_hook._load_commands_config``,- with the opposite default — that one fails open because distilling is on- by default, this one fails closed because replacing a Read is not.+ Thin alias over the shared reader so the two replacing surfaces cannot+ drift on how they read their flag. See :func:`_shared.hook_flag_enabled`+ for the fail-closed rationale and the env override."""- override = os.environ.get("REPOWISE_HOOK_READ_SKELETON")- if override is not None:- return override.strip().lower() in ("1", "true", "yes", "on")- try:- text = (repo_path / ".repowise" / "config.yaml").read_text(encoding="utf-8")- except (OSError, ValueError):- # ValueError covers UnicodeDecodeError: a config with a latin-1 byte- # in it means "cannot tell", which for an opt-in means no.- return False- # Substring pre-check before the yaml import: a repo that has a config but- # not this key is the common case, and it should not pay ~70ms to learn so.- # The parse below is still what decides — this only rules out.- if _CONFIG_FLAG not in text:- return False- try:- import yaml-- data = yaml.safe_load(text) or {}- hooks = data.get("hooks")- return bool(isinstance(hooks, dict) and hooks.get(_CONFIG_FLAG) is True)- except Exception:- return False+ return hook_flag_enabled(repo_path, _CONFIG_FLAG)def supports_updated_output() -> bool:@@ -361,81 +342,24 @@ def _indexed_symbols(db_path: Path, rel: str) -> list[SkeletonSymbol]:# ----------------------------------------------------------------------------#: The counterfactual's own table. Deliberately *not* the ``savings`` ledger:-#: every row there is an event that happened, and ``repowise saved`` sums them-#: into a headline figure that is already published. A forgone saving did not-#: happen, and adding it to that sum would inflate a real number with a-#: hypothetical one — the precise misreading the caveat exists to prevent.-_FORGONE_TABLE_SQL = (- "CREATE TABLE IF NOT EXISTS forgone_savings ("- "created_at REAL NOT NULL, source TEXT NOT NULL, path TEXT NOT NULL, "- "raw_tokens INTEGER NOT NULL, distilled_tokens INTEGER NOT NULL)"-)--def record_forgone(repo_path: Path, replacement: Replacement) -> None:- """Record a saving this repo *would* have made, had the feature been on.-- Same never-create-the-store rule as :func:`record_saving`, and the same- reason for spelling the path out rather than importing it.- """- db_path = repo_path / ".repowise" / "omissions" / "omissions.db"- if not db_path.exists():- return- try:- import time-- con = sqlite3.connect(str(db_path), timeout=2)- try:- con.execute(_FORGONE_TABLE_SQL)- con.execute(- "INSERT INTO forgone_savings "- "(created_at, source, path, raw_tokens, distilled_tokens) "- "VALUES (?, ?, ?, ?, ?)",- (- time.time(),- _SAVINGS_SOURCE,- replacement.rel,- replacement.full_tokens,- replacement.skeleton_tokens,- ),- )- con.commit()- finally:- con.close()- except Exception:- return+ """Record a saving this repo *would* have made, had the feature been on."""+ _record_forgone(+ repo_path,+ source=_SAVINGS_SOURCE,+ path=replacement.rel,+ raw_tokens=replacement.full_tokens,+ distilled_tokens=replacement.skeleton_tokens,+ )def record_saving(repo_path: Path, replacement: Replacement) -> None:- """Bill this replacement to the savings ledger so ``repowise saved`` sees it.-- Never creates the omission store: its absence means this repo has not- opted into distill bookkeeping, and a hook is not the place to decide- otherwise. Any failure is swallowed — accounting must not cost the agent- an enrichment that is already computed.- """- # Path spelled out rather than imported: the constants live in- # distill.store, which imports structlog — 250ms to learn that a repo- # without an omission store has no omission store. Kept in sync by- # test_the_omission_store_path_matches_distills.- db_path = repo_path / ".repowise" / "omissions" / "omissions.db"- if not db_path.exists():- return- try:- from repowise.core.distill.tracking import record_saving as _record-- con = sqlite3.connect(str(db_path), timeout=2)- try:- _record(- con,- filter_name=_SAVINGS_FILTER,- source=_SAVINGS_SOURCE,- command=replacement.rel,- raw_tokens=replacement.full_tokens,- distilled_tokens=replacement.skeleton_tokens,- )- finally:- con.close()- except Exception:- return+ """Bill this replacement to the savings ledger so ``repowise saved`` sees it."""+ _record_saving(+ repo_path,+ source=_SAVINGS_SOURCE,+ filter_name=_SAVINGS_FILTER,+ command=replacement.rel,+ raw_tokens=replacement.full_tokens,+ distilled_tokens=replacement.skeleton_tokens,+ )diff --git a/packages/cli/src/repowise/cli/commands/augment_cmd/search.py b/packages/cli/src/repowise/cli/commands/augment_cmd/search.pyindex 38397c806..4c9919902 100644--- a/packages/cli/src/repowise/cli/commands/augment_cmd/search.py+++ b/packages/cli/src/repowise/cli/commands/augment_cmd/search.py@@ -4,7 +4,7 @@ from __future__ import annotationsfrom pathlib import Path-from ._shared import _extract_output_text, _find_repo_root+from ._shared import HookResult, _extract_output_text, _find_repo_root# NOTE: repowise.core.persistence.sql is imported inside _rescue/_triage, not# here. At module scope it costs ~790ms on every single hook invocation — it@@ -30,18 +30,19 @@ def _handle_search_post(tool_output: object,cwd: str,session_id: str = "",-) -> str | None:+ client: str | None = None,+) -> HookResult:"""Decide whether to enrich a Grep/Glob result and how."""repo_path = _find_repo_root(Path(cwd))if repo_path is None:- return None+ return HookResult()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 None+ return HookResult()output_text = _extract_output_text(tool_output)# A genuine flood gets a compact per-file digest regardless of what the@@ -49,18 +50,26 @@ def _handle_search_post(if result_count >= _DIGEST_THRESHOLD:digest = _grep_flood_digest(repo_path, output_text)if digest:- _log_search_firing(repo_path, session_id, "digest", digest)- return digest- # Unparseable output (e.g. Glob path lists): fall through to triage.+ return _digest_result(+ repo_path,+ tool_input,+ tool_output,+ output_text,+ digest,+ session_id,+ client=client,+ )+ # Unparseable output (e.g. Glob path lists, or a single-file context+ # grep, see search_digest): fall through to triage.pattern = tool_input.get("pattern")if not isinstance(pattern, str) or not pattern.strip():- return None+ return HookResult()# Path-style lookups don't benefit from semantic enrichment — the agent# is reading literal locations, not exploring a concept.if _looks_like_path_lookup(pattern):- return None+ return HookResult()# Decision tree. The skip case is the most common — that's by design.if result_count == 0:@@ -70,19 +79,109 @@ def _handle_search_post(# 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 None+ return HookResult()mode = "rescue"elif result_count >= _TRIAGE_THRESHOLD:mode = "triage"else:- return None+ return HookResult()import asyncioenrichment = asyncio.run(_search_enrich(repo_path, pattern, mode, result_count))if enrichment:_log_search_firing(repo_path, session_id, mode, enrichment)- return enrichment+ return HookResult(context=enrichment or None)+++def _digest_result(+ repo_path: Path,+ tool_input: dict,+ tool_output: object,+ output_text: str,+ digest: str,+ session_id: str,+ *,+ client: str | None,+) -> HookResult:+ """Serve the digest in place of the flood, or append it as before.++ Two ledger categories on purpose. A *served* digest and an *appended* one+ are different products. One costs the agent tokens to gain a ranking, the+ other saves them, and pooling both under ``digest`` would average a cost+ and a saving into a number that describes neither. ``digest_served`` is+ scored as no-action-expected for the same structural reason+ ``skeleton_served`` is: its text leaves as ``updatedToolOutput`` and never+ appears in the transcript the classifier reads.+ """+ replacement, forgone = _digest_replacement(+ repo_path, tool_input, tool_output, output_text, digest, client=client+ )+ if replacement is not None:+ _log_search_firing(repo_path, session_id, "digest_served", replacement.text)+ from .search_digest import record_saving++ return HookResult(+ replacement=replacement.payload,+ on_emitted=lambda: record_saving(repo_path, replacement),+ )++ _log_search_firing(repo_path, session_id, "digest", digest)+ if forgone is not None:+ from .search_digest import record_forgone++ return HookResult(+ context=digest,+ on_emitted=lambda: record_forgone(repo_path, forgone),+ )+ return HookResult(context=digest)+++def _digest_replacement(+ repo_path: Path,+ tool_input: dict,+ tool_output: object,+ output_text: str,+ digest: str,+ *,+ client: str | None,+):+ """``(replacement, forgone)`` for this flood; at most one set. Never raises.++ The two legs share every gate but the flag, on purpose: a counterfactual+ computed under looser conditions than the thing it stands in for would be+ measuring a different feature. So a repo with the surface off still learns+ what it would have saved, and one whose client cannot honour a replacement+ is told nothing, because for that client there was nothing to forgo.+ """+ try:+ from .read_skeleton import supports_updated_output+ from .search_digest import (+ as_grep_output,+ digest_replacement,+ enabled,+ replaces_tool_output,+ )++ if not supports_updated_output() or not replaces_tool_output(client):+ return None, None+ pattern = tool_input.get("pattern") if isinstance(tool_input, dict) else None+ candidate = digest_replacement(+ pattern if isinstance(pattern, str) else "", output_text, digest+ )+ if candidate is None:+ return None, None+ if not enabled(repo_path):+ return None, candidate+ candidate.payload = as_grep_output(tool_output, candidate.text)+ if candidate.payload is None:+ # Not a shape we can legally replace (files_with_matches, Glob).+ # The digest still appends, and nothing was forgone: with the flag+ # on we would have reached exactly here.+ return None, None+ return candidate, None+ except Exception:+ return None, Nonedef _log_search_firing(diff --git a/packages/cli/src/repowise/cli/commands/augment_cmd/search_digest.py b/packages/cli/src/repowise/cli/commands/augment_cmd/search_digest.pynew file mode 100644index 000000000..39bd0f3d7--- /dev/null+++ b/packages/cli/src/repowise/cli/commands/augment_cmd/search_digest.py@@ -0,0 +1,203 @@+"""PostToolUse Grep → serve the compact digest instead of the match flood.++The flood digest has always been the most expensive thing this hook says:+across the efficacy ledger it fired 37 times for ~17.6k tokens, and it *added*+every one of them **next to** the flood the agent had already been billed for.+Ranking a flood you also keep is a lens, not a saving. This module replaces the+flood with the digest instead, the same trade ``repowise distill`` makes for+shell output and :mod:`read_skeleton` now makes for Reads.++**Not a silent truncation.** :func:`render_search_digest` names every file, its+match count, two anchored line numbers per file, and an explicit+``(N more files, M matches)`` tail. The agent can see what was dropped and+re-run scoped to any file it names. The header says so.++What this deliberately does **not** touch, measured over real transcripts:++* **Single-file context greps** (``-C``/``-A``/``-B``) are the most common+ flood by a distance: 20 of 22 in the sample. Claude Code renders them with+ no path prefix, so :func:`group_search_matches` declines them and no digest+ is built. That is the right answer for the wrong reason: the agent asked for+ that context by name, and compressing it would be taking back what it+ requested. Left alone on purpose.+* **``files_with_matches`` and Glob**, whose payloads carry no ``content`` at+ all. There is nothing to replace, and the file list is already a digest.++So the population here is genuinely multi-file floods. On those the measured+digest is 0.30 of the flood, ~1,183 tokens saved per firing, none near the+output cap.++Gates, cheapest first (:func:`digest_replacement`):++1. **The client can honour a replacement.** Codex's hook protocol has no+ output-replacement field (see :func:`replaces_tool_output`).+2. **Opted in**: ``hooks.search_digest``, written by the same init consent as+ ``hooks.read_skeleton``. Fails closed.+3. **The client build supports ``updatedToolOutput``** (shared version probe).+4. **Grep content mode**, with a ``content`` string to stand in for.+5. **Worth it**: digest well under the flood, and the saving clears a floor.+6. **Under the output cap**, whole.++Operational rules are the rest of augment's: stdlib on the way in, no network,+any failure degrades to returning None and the agent sees its Grep untouched.+"""++from __future__ import annotations++from pathlib import Path++from ._shared import MAX_OUTPUT_CHARS, hook_flag_enabled+from ._shared import record_forgone as _record_forgone+from ._shared import record_saving as _record_saving++#: Savings-ledger identity, so ``repowise saved`` can name this surface.+_SAVINGS_SOURCE = "hook-search"+_SAVINGS_FILTER = "search_digest"++_CONFIG_FLAG = "search_digest"++#: The digest must be at most this fraction of the flood it replaces. Mirrors+#: ``read_state._READ_NUDGE_MAX_RATIO``: below half, replacing is a saving;+#: above it, it is a detour with extra steps.+_MAX_RATIO = 0.5++#: Floor on tokens saved. Lower than the Read surface's 1500 because a flood is+#: a smaller object than a whole file. The measured median saving on real+#: multi-file floods is ~1,183 tokens, which a 1500 floor would reject+#: outright. Set under the measurement, not over it.+_MIN_SAVED_TOKENS = 400+++class DigestReplacement:+ """A digest ready to stand in for a Grep flood, and its ledger facts."""++ __slots__ = ("digest_tokens", "flood_tokens", "pattern", "payload", "text")++ def __init__(self, *, pattern: str, text: str, flood_tokens: int, digest_tokens: int) -> None:+ self.pattern = pattern+ self.text = text+ self.flood_tokens = flood_tokens+ self.digest_tokens = digest_tokens+ #: Grep-shaped wire payload wrapping :attr:`text`, filled in by the+ #: caller once it has the Grep's own ``tool_response`` to build from.+ self.payload: dict | None = None++ @property+ def saved_tokens(self) -> int:+ return max(0, self.flood_tokens - self.digest_tokens)+++def enabled(repo_path: Path) -> bool:+ """True when this repo opted into flood replacement. Fails closed."""+ return hook_flag_enabled(repo_path, _CONFIG_FLAG)+++def replaces_tool_output(client: str | None) -> bool:+ """True when *client*'s hook protocol can honour ``updatedToolOutput``.++ Only Claude Code can. Codex's hook contract carries a context string and+ nothing else, so a replacement handed to it is dropped on the floor, and+ dropped *silently*, which is the failure that let the Read surface record+ ``skeleton_served`` rows for two commits while every agent saw the original+ file. A capability that is checked is worth more than one that is assumed,+ even while Codex registers no Grep matcher to reach this with.++ This is the narrow version of what ``AgentAdapter`` already does for the+ rewrite hook via ``rewrite_permissions`` (plan item 18 folds augment into+ that ABC properly). Unknown clients are treated as Claude Code, matching+ every other handler here: ``--client`` is passed only by Codex's own+ lifecycle hooks.+ """+ return client != "codex"+++def as_grep_output(tool_output: object, text: str) -> dict | None:+ """Wrap *text* in the object shape Claude Code requires for a Grep.++ ``updatedToolOutput`` is validated against the schema of the tool being+ replaced, not against a common one. Grep's content mode is+ ``{"mode": "content", "content", "numLines", "numFiles", "filenames",+ "totalLines"}``, and handing it a bare string is rejected, after which the+ *original* output goes to the agent while the hook still records a served+ row. That failure is invisible from inside the hook (exit 0, no stderr),+ which is why this builds from the payload's own ``tool_response`` rather+ than constructing the envelope from scratch: unknown or future keys are+ carried through untouched and only ``content`` and its line count move.++ ``totalLines`` and ``numFiles`` are deliberately left alone. They describe+ the search, not the rendering of it, and they stay true after the swap. The digest's own+ header restates both anyway.++ Returns None when the payload is not the shape we think it is, which+ degrades to no replacement rather than to a rejected one.+ """+ if not isinstance(tool_output, dict):+ return None+ if tool_output.get("mode") != "content":+ # files_with_matches / Glob carry no content to stand in for.+ return None+ if not isinstance(tool_output.get("content"), str):+ return None+ lines = text.count("\n") + (0 if text.endswith("\n") else 1)+ return {**tool_output, "content": text, "numLines": lines}+++def digest_replacement(+ pattern: str, flood_text: str, digest_body: str+) -> DigestReplacement | None:+ """A replacement for this flood, or None when it is not worth making.++ *digest_body* is what :func:`search._grep_flood_digest` already rendered. This decides whether serving it in place of *flood_text* is a saving, and+ never re-renders it. Callers own the cheaper gates above.+ """+ text = _render(digest_body)+ if len(text) > MAX_OUTPUT_CHARS:+ # A cut digest loses its trailing "N more files" line, which is the+ # part that makes the omission visible. Skip rather than truncate.+ return None+ flood_tokens = max(1, len(flood_text) // 4)+ digest_tokens = max(1, len(text) // 4)+ if digest_tokens > flood_tokens * _MAX_RATIO:+ return None+ if flood_tokens - digest_tokens < _MIN_SAVED_TOKENS:+ return None+ return DigestReplacement(+ pattern=pattern,+ text=text,+ flood_tokens=flood_tokens,+ digest_tokens=digest_tokens,+ )+++def _render(digest_body: str) -> str:+ """Header plus digest; the header is the reversibility contract."""+ return (+ "[repowise] Serving a compact digest of this search in place of the raw "+ "matches. Every matched file is named below with its match count and "+ "anchor line numbers; re-run the search scoped to one of them, or read "+ "the lines directly, to see any match in full.\n"+ f"{digest_body}"+ )+++def record_saving(repo_path: Path, replacement: DigestReplacement) -> None:+ """Bill this replacement to the savings ledger so ``repowise saved`` sees it."""+ _record_saving(+ repo_path,+ source=_SAVINGS_SOURCE,+ filter_name=_SAVINGS_FILTER,+ command=replacement.pattern,+ raw_tokens=replacement.flood_tokens,+ distilled_tokens=replacement.digest_tokens,+ )+++def record_forgone(repo_path: Path, replacement: DigestReplacement) -> None:+ """Record a saving this repo *would* have made, had the surface been on."""+ _record_forgone(+ repo_path,+ source=_SAVINGS_SOURCE,+ path=replacement.pattern,+ raw_tokens=replacement.flood_tokens,+ distilled_tokens=replacement.digest_tokens,+ )diff --git a/packages/cli/src/repowise/cli/commands/hook_cmd.py b/packages/cli/src/repowise/cli/commands/hook_cmd.pyindex fb189901e..bfcf57b33 100644--- a/packages/cli/src/repowise/cli/commands/hook_cmd.py+++ b/packages/cli/src/repowise/cli/commands/hook_cmd.py@@ -413,7 +413,22 @@ def _set_read_skeleton(path: str | None, workspace: bool, no_workspace: bool, *, enabled: bool) -> None:"""Write ``hooks.read_skeleton`` for the target repo or workspace."""- from repowise.cli.helpers import save_hook_read_skeleton_enabled+ _set_hook_surface(+ path, workspace, no_workspace, surface="read_skeleton", label="Skeleton-served Reads", enabled=enabled+ )+++def _set_hook_surface(+ path: str | None,+ workspace: bool,+ no_workspace: bool,+ *,+ surface: str,+ label: str,+ enabled: bool,+) -> None:+ """Write ``hooks.<surface>`` for the target repo or workspace."""+ from repowise.cli.helpers import save_hook_surface_enabledtarget = _hook_target(path, workspace, no_workspace)word = "[green]on[/green]" if enabled else "[yellow]off[/yellow]"@@ -421,8 +436,8 @@ def _set_read_skeleton(for repo_path in _target_repo_paths(target):if not (repo_path / ".repowise").is_dir():continue- save_hook_read_skeleton_enabled(repo_path, enabled=enabled)- console.print(f" Skeleton-served Reads: {word} ({repo_path})")+ save_hook_surface_enabled(repo_path, surface, enabled=enabled)+ console.print(f" {label}: {word} ({repo_path})")touched += 1if not touched:console.print(" [yellow]No indexed repo here — run `repowise init` first.[/yellow]")@@ -450,6 +465,68 @@ def read_skeleton_status(path: str | None, workspace: bool, no_workspace: bool))+@hook_group.group("search-digest")+def search_digest_group() -> None:+ """Manage digest-served searches (Claude Code).++ A grep that floods across many files comes back as a compact per-file+ digest: every file named with its match count and anchor line numbers,+ and the dropped tail counted, instead of the raw match list. Re-run the+ search scoped to a file to see its matches in full.++ Single-file context greps (`-C`/`-A`/`-B`) are never touched: that context+ is what the agent asked for.++ Like `read-skeleton`, there is no hook to install. This moves the per-repo+ verdict `hooks.search_digest`, which `repowise init` writes from the same+ answer as the rewrite hook.+ """+++@search_digest_group.command("install")[email protected]("path", required=False, default=None)[email protected]("--workspace", "-w", is_flag=True, default=False, help="Force workspace mode.")[email protected]("--no-workspace", is_flag=True, default=False, help="Force single-repo mode.")+def search_digest_install(path: str | None, workspace: bool, no_workspace: bool) -> None:+ """Serve multi-file grep floods as digests in this repo."""+ _set_hook_surface(+ path, workspace, no_workspace,+ surface="search_digest", label="Digest-served searches", enabled=True,+ )+++@search_digest_group.command("uninstall")[email protected]("path", required=False, default=None)[email protected]("--workspace", "-w", is_flag=True, default=False, help="Force workspace mode.")[email protected]("--no-workspace", is_flag=True, default=False, help="Force single-repo mode.")+def search_digest_uninstall(path: str | None, workspace: bool, no_workspace: bool) -> None:+ """Stop replacing search floods in this repo; the digest goes back to riding alongside."""+ _set_hook_surface(+ path, workspace, no_workspace,+ surface="search_digest", label="Digest-served searches", enabled=False,+ )+++@search_digest_group.command("status")[email protected]("path", required=False, default=None)[email protected]("--workspace", "-w", is_flag=True, default=False, help="Force workspace mode.")[email protected]("--no-workspace", is_flag=True, default=False, help="Force single-repo mode.")+def search_digest_status(path: str | None, workspace: bool, no_workspace: bool) -> None:+ """Report whether search floods are being served as digests."""+ from repowise.cli.commands.augment_cmd.search_digest import enabled as search_digest_enabled++ target = _hook_target(path, workspace, no_workspace)+ for repo_path in _target_repo_paths(target):+ on = search_digest_enabled(repo_path)+ icon = "[green]✓[/green]" if on else "[dim]✗[/dim]"+ console.print(f" {icon} digest-served searches: {'on' if on else 'off'} ({repo_path})")+ if not on:+ console.print(+ " [dim]`repowise saved` shows what this would have saved "+ "if it were on.[/dim]"+ )++@hook_group.command("stats")@click.argument("path", required=False, default=None)@click.option(diff --git a/packages/cli/src/repowise/cli/commands/init_cmd/_interactive.py b/packages/cli/src/repowise/cli/commands/init_cmd/_interactive.pyindex 0ab1f85a2..183774585 100644--- a/packages/cli/src/repowise/cli/commands/init_cmd/_interactive.py+++ b/packages/cli/src/repowise/cli/commands/init_cmd/_interactive.py@@ -81,13 +81,16 @@ def offer_distill_rewrite_hook("recognized command; set `permission: ask` in .repowise/config.yaml to ""approve each one. Raw output stays recoverable via `repowise expand`.[/dim]")- # Named here because a yes turns it on. The question stays one question- # — this is the same consent, and the thing being consented to is- # "hooks may compact what your agent sees", not two separate features.+ # Named here because a yes turns them on. The question stays one+ # question: this is the same consent, and the thing being consented to+ # is "hooks may compact what your agent sees", not three features.+ # Every surface a yes covers has to be named, or it is not consent.console_obj.print(- " [dim]Also serves an unbounded Read of a large indexed file as its "- "skeleton, with every elided span line-numbered so the agent can read "- "any of it back. Toggle later with `repowise hook read-skeleton`.[/dim]"+ " [dim]Also shrinks two big tool results, both reversible: a "+ "whole-file Read comes back as a skeleton, and a grep matching many "+ "files comes back as a per-file summary. Each names the line numbers "+ "to get the rest. Toggle later: `repowise hook read-skeleton`, "+ "`repowise hook search-digest`.[/dim]")try:flag = click.confirm(" Install the Claude Code rewrite hook?", default=True)@@ -121,29 +124,33 @@ def _record_distill_verdict() -> None:"""Persist the hook-intervention verdict for every repo in this run.- Two keys, one answer. ``distill.commands.enabled`` gates rewriting a Bash- command into ``repowise distill``; ``hooks.read_skeleton`` gates serving an- unbounded Read of a large indexed file as its skeleton. Both are the same- consent — "repowise's hooks may intervene in my agent's tool calls" — and- the one the user was asked is the broader of the two, so a second prompt- would be asking permission we already have.+ Several keys, one answer. ``distill.commands.enabled`` gates rewriting a+ Bash command into ``repowise distill``; ``hooks.read_skeleton`` gates+ serving an unbounded Read of a large indexed file as its skeleton;+ ``hooks.search_digest`` gates serving a multi-file grep flood as its+ compact digest. All are the same consent, "repowise's hooks may intervene+ in my agent's tool calls", and the one the user was asked is the broadest+ of them, so a second prompt would be asking permission we already have.Read-skeleton shipped with no code path that wrote its key at all, whichleft it reachable only by hand-editing YAML. That is not a discoveryproblem: its gate needs 50 firings across 10 sessions to decide whether itstays, and a feature nobody can turn on returns zero of them and settles- nothing.+ nothing. Every replacing surface added since rides this same verdict for+ that reason."""from repowise.cli.helpers import (+ HOOK_REPLACEMENT_SURFACES,save_distill_commands_enabled,- save_hook_read_skeleton_enabled,+ save_hook_surface_enabled,)for repo_path in repo_paths:try:save_distill_commands_enabled(repo_path, enabled=enabled)- save_hook_read_skeleton_enabled(repo_path, enabled=enabled)+ for surface in HOOK_REPLACEMENT_SURFACES:+ save_hook_surface_enabled(repo_path, surface, enabled=enabled)except Exception as exc: # init must not crash on a config writeconsole_obj.print(f" [yellow]Could not record hook verdict for {repo_path.name}: {exc}[/yellow]"diff --git a/packages/cli/src/repowise/cli/commands/init_cmd/command.py b/packages/cli/src/repowise/cli/commands/init_cmd/command.pyindex 490ab8ad9..64a266ec1 100644--- a/packages/cli/src/repowise/cli/commands/init_cmd/command.py+++ b/packages/cli/src/repowise/cli/commands/init_cmd/command.py@@ -521,14 +521,13 @@ def _run_generation_phase("distill_hook",default=None,help=(- "Install the Claude Code command-rewrite hook that routes noisy "- "commands (tests, builds, git, searches) through `repowise distill` "- "for compact output, and serve an unbounded Read of a large indexed "- "file as its skeleton (`hooks.read_skeleton`). Both are the same "- "consent — repowise's hooks may compact what your agent sees — and "- "this flag decides both, without a prompt. Default: ask when "- "interactive; skip otherwise. In workspace mode the verdict applies "- "to every selected repo."+ "Let repowise's hooks compact what your agent sees. Noisy commands "+ "(tests, builds, git, searches) run through `repowise distill`; a "+ "whole-file Read comes back as a skeleton (`hooks.read_skeleton`); a "+ "grep matching many files comes back as a per-file digest "+ "(`hooks.search_digest`). One consent, and this flag decides all three "+ "without a prompt. Default: ask when interactive, skip otherwise. In "+ "workspace mode the verdict applies to every selected repo."),)@click.option(diff --git a/packages/cli/src/repowise/cli/commands/saved_cmd.py b/packages/cli/src/repowise/cli/commands/saved_cmd.pyindex 9de5c8731..85101a332 100644--- a/packages/cli/src/repowise/cli/commands/saved_cmd.py+++ b/packages/cli/src/repowise/cli/commands/saved_cmd.py@@ -168,8 +168,31 @@ def saved_command(console.print()+#: One entry per replacing hook surface: the savings-ledger source that tags+#: its forgone rows, how to read its on/off verdict, and how to name it. The+#: source filter is load-bearing: every surface writes into the one+#: ``forgone_savings`` table, so an unfiltered sum would report a search+#: saving as a Read one.+_FORGONE_SURFACES = (+ (+ "hook-read",+ "read_skeleton",+ "skeleton-served Reads",+ "file",+ "repowise hook read-skeleton install",+ ),+ (+ "hook-search",+ "search_digest",+ "digest-served searches",+ "search",+ "repowise hook search-digest install",+ ),+)++def _print_forgone_read_skeleton_line(start: Path, db_path: Path, since_ts: float | None) -> None:- """What skeleton-served Reads would have saved, for repos that have it off.+ """What each replacing surface would have saved, for repos that have it off.Read out of its own table rather than the savings ledger, and printedbelow the total rather than inside it, because none of it happened.@@ -182,53 +205,57 @@ def _print_forgone_read_skeleton_line(start: Path, db_path: Path, since_ts: floa"""import sqlite3- try:- con = sqlite3.connect(f"file:{db_path.as_posix()}?mode=ro", uri=True, timeout=2)- try:- where, params = "", ()- if since_ts is not None:- where, params = " WHERE created_at >= ?", (since_ts,)- files, raw, distilled = con.execute(- "SELECT COUNT(DISTINCT path), COALESCE(SUM(raw_tokens),0), "- f"COALESCE(SUM(distilled_tokens),0) FROM forgone_savings{where}",- params,- ).fetchone()- finally:- con.close()- except sqlite3.Error:- return # no such table: this repo never measured, which is not an error- if not files:- return-- # Rows outlive the setting that produced them, and nothing prunes them, so- # the state has to be read rather than inferred from their presence — or a- # repo that measured for a week and then turned the feature on gets told- # forever that it is off and should turn it on.- from repowise.cli.commands.augment_cmd.read_skeleton import enabled as _enabledfrom repowise.cli.helpers import find_repowise_repo_rootrepo_root = find_repowise_repo_root(start) or start- still_off = not _enabled(repo_root)-- if still_off:- console.print(- f" [dim]Not saved:[/dim] skeleton-served Reads are [yellow]off[/yellow] here — "- f"{files:,} file{'' if files == 1 else 's'} would have cost "- f"[bold]{raw - distilled:,}[/bold] fewer tokens ({raw:,} → {distilled:,}). "- f"[dim]Turn on with `repowise hook read-skeleton install`.[/dim]"- )- else:+ printed = False+ for source, flag, label, noun, install_cmd in _FORGONE_SURFACES:+ try:+ con = sqlite3.connect(f"file:{db_path.as_posix()}?mode=ro", uri=True, timeout=2)+ try:+ where, params = " WHERE source = ?", (source,)+ if since_ts is not None:+ where, params = " WHERE source = ? AND created_at >= ?", (source, since_ts)+ items, raw, distilled = con.execute(+ "SELECT COUNT(DISTINCT path), COALESCE(SUM(raw_tokens),0), "+ f"COALESCE(SUM(distilled_tokens),0) FROM forgone_savings{where}",+ params,+ ).fetchone()+ finally:+ con.close()+ except sqlite3.Error:+ return # no such table: this repo never measured, which is not an error+ if not items:+ continue++ # Rows outlive the setting that produced them, and nothing prunes them,+ # so the state has to be read rather than inferred from their presence,+ # or a repo that measured for a week and then turned the feature on gets+ # told forever that it is off and should turn it on.+ from repowise.cli.commands.augment_cmd._shared import hook_flag_enabled++ printed = True+ plural = "" if items == 1 else "s"+ if not hook_flag_enabled(repo_root, flag):+ console.print(+ f" [dim]Not saved:[/dim] {label} are [yellow]off[/yellow] here: "+ f"{items:,} {noun}{plural} would have cost "+ f"[bold]{raw - distilled:,}[/bold] fewer tokens ({raw:,} → {distilled:,}). "+ f"[dim]Turn on with `{install_cmd}`.[/dim]"+ )+ else:+ console.print(+ f" [dim]Measured before {label} was turned on:[/dim] {items:,} "+ f"{noun}{plural} would have cost "+ f"[bold]{raw - distilled:,}[/bold] fewer tokens ({raw:,} → {distilled:,}). "+ "[dim]Savings since then are in the table above.[/dim]"+ )+ if printed:console.print(- f" [dim]Measured before it was turned on:[/dim] {files:,} "- f"file{'' if files == 1 else 's'} would have cost "- f"[bold]{raw - distilled:,}[/bold] fewer tokens ({raw:,} → {distilled:,}). "- "[dim]Savings since then are in the table above.[/dim]"+ " [dim]This is what the replacement would have taken off the bill, and only "+ "that: nothing was replaced, so nothing was read back, so it says nothing "+ "about how often the agent would have needed the whole thing anyway.[/dim]")- console.print(- " [dim]This is what the replacement would have taken off the bill, and only "- "that: nothing was replaced, so nothing was read back, so it says nothing "- "about how often the agent would have needed the whole file anyway.[/dim]"- )def _missed_report(start: Path, days: float) -> dict | None:diff --git a/packages/cli/src/repowise/cli/helpers.py b/packages/cli/src/repowise/cli/helpers.pyindex 4704c70f7..db74cdc2b 100644--- a/packages/cli/src/repowise/cli/helpers.py+++ b/packages/cli/src/repowise/cli/helpers.py@@ -602,18 +602,25 @@ def save_distill_commands_enabled(repo_path: Path, *, enabled: bool) -> None:save_config_partial(repo_path, distill=distill)-def save_hook_read_skeleton_enabled(repo_path: Path, *, enabled: bool) -> None:- """Deep-merge ``hooks.read_skeleton`` into ``.repowise/config.yaml``.+#: The hook surfaces that *replace* a tool result rather than adding to it.+#: One consent turns them all on; each has its own ``repowise hook <name>``+#: toggle afterwards, so a surface that turns out to be wrong can be dropped+#: without taking the others with it.+HOOK_REPLACEMENT_SURFACES = ("read_skeleton", "search_digest")+++def save_hook_surface_enabled(repo_path: Path, surface: str, *, enabled: bool) -> None:+ """Deep-merge ``hooks.<surface>`` into ``.repowise/config.yaml``.Same shape as :func:`save_distill_commands_enabled`, and written by thesame consent: the rewrite-hook prompt means "let repowise's hooksintervene in your agent's tool calls", and rewriting a Bash command is a- larger intervention than serving a Read as its skeleton, not a smaller- one. There is deliberately no second question.+ larger intervention than serving a Read as its skeleton or a search as its+ digest, not a smaller one. There is deliberately no second question."""cfg = load_config(repo_path)hooks = dict(cfg.get("hooks") or {})- hooks["read_skeleton"] = enabled+ hooks[surface] = enabledsave_config_partial(repo_path, hooks=hooks)diff --git a/packages/core/src/repowise/core/sessions/efficacy.py b/packages/core/src/repowise/core/sessions/efficacy.pyindex 591dd6d54..5d8ac17dc 100644--- a/packages/core/src/repowise/core/sessions/efficacy.py+++ b/packages/core/src/repowise/core/sessions/efficacy.py@@ -34,6 +34,7 @@ read stale_read n/a — a warning, not a pointersearch triage a named file is touchedsearch rescue the named file or symbol is touchedsearch digest a file the digest ranked is touched+search digest_served n/a, the hook already did it (see below)fix_history edit_notice a test is run, or the file's history is inspected============= =============== ==================================================@@ -42,13 +43,15 @@ range of a file you just read in full is ordinary edit-prep and cannot beattributed to the nudge. It is tracked separately as:data:`AMBIGUOUS` evidence so the generous bound stays reportable.-The skeleton *replacement* rows (``skeleton_served`` and its two recovery-categories) are structurally unlike the rest: their text goes out as+The *replacement* rows (``skeleton_served`` and its two recovery categories,+and ``digest_served``) are structurally unlike the rest: their text goes out as``updatedToolOutput``, so it never appears as a transcript``hook_additional_context`` line and this module's pattern pass will neversee it. That is fine and deliberate — the hook writes those rows directly andGate A is a ratio of row counts, not a question about what the agent did-next. There is no action to look for, because the hook took it.+next. There is no action to look for, because the hook took it. What those+surfaces return is measured in the savings ledger instead, not as an adoption+rate.Surfaces with no recommended action (``stale_read``) and surfaces that emitnothing at all (``read_enrich``'s read-after-served KPI) are never marked@@ -97,6 +100,11 @@ NO_ACTION_EXPECTED = frozenset(("read", "skeleton_served"),("read", "skeleton_recovered_full"),("read", "skeleton_ranged"),+ # A *served* flood digest, for the same structural reason: it leaves as+ # updatedToolOutput, so the pattern pass below can never see it. The+ # appended ``search``/``digest`` rows are still scored normally, and the+ # two are kept apart so a cost and a saving are never averaged.+ ("search", "digest_served"),})diff --git a/tests/unit/cli/test_augment_read_skeleton.py b/tests/unit/cli/test_augment_read_skeleton.pyindex 758c5339c..a89996402 100644--- a/tests/unit/cli/test_augment_read_skeleton.py+++ b/tests/unit/cli/test_augment_read_skeleton.py@@ -272,11 +272,15 @@ def test_numbering_is_dropped_rather_than_guessed_when_it_cannot_reconcile() ->def test_the_omission_store_path_matches_distills(repo: Path) -> None:- """The path is spelled out to dodge a 250ms structlog import; keep it true."""- from repowise.cli.commands.augment_cmd import read_skeleton+ """The path is spelled out to dodge a 250ms structlog import; keep it true.++ Lives in ``_shared`` now that both replacing surfaces bill savings through+ the same two writers: one copy of the literal, one guard over it.+ """+ from repowise.cli.commands.augment_cmd import _sharedfrom repowise.core.distill.store import OMISSIONS_DB_FILENAME, OMISSIONS_DIRNAME- source = Path(read_skeleton.__file__).read_text(encoding="utf-8")+ source = Path(_shared.__file__).read_text(encoding="utf-8")assert f'".repowise" / "{OMISSIONS_DIRNAME}" / "{OMISSIONS_DB_FILENAME}"' in sourcediff --git a/tests/unit/cli/test_augment_search.py b/tests/unit/cli/test_augment_search.pyindex 28a3d80dc..77bc841e1 100644--- a/tests/unit/cli/test_augment_search.py+++ b/tests/unit/cli/test_augment_search.py@@ -310,12 +310,19 @@ def repowise_cwd(tmp_path):def _call(tool_name, pattern, output_text, cwd):+ """The appended-context leg of the handler, as a plain string or None.++ ``_handle_search_post`` returns a ``HookResult`` since the flood digest can+ replace the tool output; every test below this line is about what the hook+ *says*, so they read the context field and the replacement leg gets its own+ class.+ """return _handle_search_post(tool_name=tool_name,tool_input={"pattern": pattern},tool_output={"output": output_text},cwd=str(cwd),- )+ ).contextclass TestDecisionTree:@@ -332,7 +339,7 @@ class TestDecisionTree:tool_input={"pattern": ""},tool_output={"output": "anything"},cwd=str(repowise_cwd),- )+ ).contextis None)enrich.assert_not_called()@@ -384,7 +391,7 @@ class TestDecisionTree:tool_output=GREP_FILES_MODE,cwd=str(repowise_cwd),)- assert result is None+ assert not resultenrich.assert_not_called()@pytest.mark.parametrize(@@ -404,7 +411,7 @@ class TestDecisionTree:tool_output=tool_output,cwd=str(repowise_cwd),)- assert result is None+ assert not resultenrich.assert_not_called()@pytest.mark.parametrize(@@ -425,7 +432,7 @@ class TestDecisionTree:tool_output=GREP_FILES_MODE_ZERO,cwd=str(repowise_cwd),)- assert result is None+ assert not resultenrich.assert_not_called()def test_triage_mode_on_flood(self, repowise_cwd) -> None:diff --git a/tests/unit/cli/test_augment_search_digest.py b/tests/unit/cli/test_augment_search_digest.pynew file mode 100644index 000000000..3aac5a9d6--- /dev/null+++ b/tests/unit/cli/test_augment_search_digest.py@@ -0,0 +1,200 @@+"""Tests for serving a grep flood as its digest (``updatedToolOutput``).++The Read surface shipped this same mechanism twice before it worked: once+emitting a bare string against Read's object schema, which Claude Code rejected+silently while the ledger went on recording served rows, and once behind a flag+no code path could write. Both failures were invisible to a test that only+checked "did the handler return something". So the tests here pin the *wire+shape* and the *capability gate*, not just the decision.+"""++from __future__ import annotations++from unittest.mock import patch++import pytest++from repowise.cli.commands import augment_cmd+from repowise.cli.commands.augment_cmd import search_digest+from repowise.cli.commands.augment_cmd.search import _handle_search_post++# A real multi-file flood: 60 matches over 6 files, the shape `group_search_matches`+# parses. Mirrors the captured `mode: "content"` payload exactly.+_FLOOD_TEXT = "\n".join(+ f"packages/core/src/repowise/core/mod{i % 6}.py:{100 + i}: result = compute_value(x, y) # match {i}"+ for i in range(60)+)++GREP_CONTENT_FLOOD = {+ "mode": "content",+ "numFiles": 6,+ "filenames": [],+ "content": _FLOOD_TEXT,+ "numLines": 60,+ "totalLines": 60,+}+++def repo(tmp_path):+ (tmp_path / ".repowise").mkdir()+ return tmp_path+++def opted_in(repo):+ (repo / ".repowise" / "config.yaml").write_text(+ "hooks:\n search_digest: true\n", encoding="utf-8"+ )+ return repo+++def _fire(cwd, tool_output=None, client=None, pattern="compute_value"):+ return _handle_search_post(+ tool_name="Grep",+ tool_input={"pattern": pattern},+ tool_output=tool_output if tool_output is not None else dict(GREP_CONTENT_FLOOD),+ cwd=str(cwd),+ client=client,+ )+++class TestReplacementWireShape:+ """What Claude Code will actually accept for a Grep."""++ def test_replacement_is_grep_shaped_not_a_bare_string(self, opted_in) -> None:+ result = _fire(opted_in)+ assert result.replacement is not None, "the flood should have been replaced"+ assert isinstance(result.replacement, dict), (+ "updatedToolOutput is validated against Grep's own schema; a bare "+ "string is rejected silently and the agent sees the original flood"+ )+ assert result.replacement["mode"] == "content"+ assert "content" in result.replacement++ def test_replacement_carries_unknown_keys_through(self, opted_in) -> None:+ payload = dict(GREP_CONTENT_FLOOD, appliedLimit=60, someFutureKey="keep me")+ result = _fire(opted_in, tool_output=payload)+ assert result.replacement["appliedLimit"] == 60+ assert result.replacement["someFutureKey"] == "keep me"++ def test_numlines_matches_the_served_content(self, opted_in) -> None:+ result = _fire(opted_in)+ content = result.replacement["content"]+ assert result.replacement["numLines"] == content.count("\n") + 1++ def test_served_content_is_the_digest_and_names_its_files(self, opted_in) -> None:+ content = _fire(opted_in).replacement["content"]+ assert "[repowise]" in content+ assert "mod0.py" in content+ # The reversibility contract: counts and anchor line numbers survive.+ assert "matches)" in content+ assert "L1" in content++ def test_the_digest_does_not_also_ride_along_as_context(self, opted_in) -> None:+ """Replacing and appending the same text would bill it twice."""+ result = _fire(opted_in)+ assert result.context is None+++class TestCapabilityGate:+ def test_codex_never_gets_a_replacement(self, opted_in) -> None:+ """Codex's hook protocol has no updatedToolOutput field.++ Sending one would be dropped on the floor while the ledger recorded a+ served row: the exact failure the Read surface shipped twice.+ """+ result = _fire(opted_in, client="codex")+ assert result.replacement is None+ assert result.context is not None, "Codex still gets the digest, appended"+ assert "matches in" in result.context++ def test_unknown_client_is_treated_as_claude(self, opted_in) -> None:+ assert _fire(opted_in, client=None).replacement is not None++ def test_old_client_build_falls_back_to_appending(self, opted_in) -> None:+ with patch.object(+ augment_cmd.search_digest, "replaces_tool_output", return_value=True+ ), patch(+ "repowise.cli.commands.augment_cmd.read_skeleton.supports_updated_output",+ return_value=False,+ ):+ result = _fire(opted_in)+ assert result.replacement is None+ assert result.context is not None+++class TestOptIn:+ def test_off_by_default_the_digest_still_appends(self, repo) -> None:+ result = _fire(repo)+ assert result.replacement is None+ assert result.context is not None++ def test_env_override_enables_it(self, repo, monkeypatch) -> None:+ monkeypatch.setenv("REPOWISE_HOOK_SEARCH_DIGEST", "1")+ assert _fire(repo).replacement is not None++ def test_env_override_disables_it(self, opted_in, monkeypatch) -> None:+ monkeypatch.setenv("REPOWISE_HOOK_SEARCH_DIGEST", "0")+ assert _fire(opted_in).replacement is None+++class TestWorthItGates:+ def test_files_with_matches_is_never_replaced(self, opted_in) -> None:+ """No content field to stand in for, and the file list is already a digest."""+ payload = {+ "mode": "files_with_matches",+ "filenames": [f"src/mod{i}.py" for i in range(60)],+ "numFiles": 60,+ "totalFiles": 60,+ }+ assert _fire(opted_in, tool_output=payload).replacement is None++ def test_a_flood_of_one_line_matches_saves_too_little_to_replace(self, opted_in) -> None:+ """60 one-character matches: the digest is no smaller than the flood."""+ text = "\n".join(f"src/mod{i}.py:{i}:x" for i in range(60))+ payload = dict(GREP_CONTENT_FLOOD, content=text)+ result = _fire(opted_in, tool_output=payload)+ assert result.replacement is None, "replacing here would be a detour, not a saving"+ assert result.context is not None, "the digest still appends, as it always did"++ def test_an_oversized_digest_is_skipped_not_truncated(self) -> None:+ """A cut digest loses the tail that says what was dropped."""+ oversized = "y" * (search_digest.MAX_OUTPUT_CHARS + 1000)+ assert search_digest.digest_replacement("p", "z" * 500_000, oversized) is None++ def test_a_digest_that_is_not_much_smaller_is_not_served(self) -> None:+ assert search_digest.digest_replacement("p", "z" * 4000, "y" * 3000) is None++ def test_a_digest_well_under_the_flood_is_served(self) -> None:+ made = search_digest.digest_replacement("p", "z" * 8000, "y" * 2000)+ assert made is not None+ assert made.saved_tokens > 0+++class TestAsGrepOutput:+ def test_rejects_non_content_modes(self) -> None:+ assert search_digest.as_grep_output({"mode": "files_with_matches"}, "x") is None+ assert search_digest.as_grep_output({"filenames": []}, "x") is None++ def test_rejects_non_dict(self) -> None:+ assert search_digest.as_grep_output("a string", "x") is None+ assert search_digest.as_grep_output(None, "x") is None++ def test_rejects_content_mode_without_content(self) -> None:+ assert search_digest.as_grep_output({"mode": "content", "numLines": 3}, "x") is None++ def test_leaves_search_facts_alone(self) -> None:+ out = search_digest.as_grep_output(dict(GREP_CONTENT_FLOOD), "one\ntwo")+ assert out["totalLines"] == GREP_CONTENT_FLOOD["totalLines"]+ assert out["numFiles"] == GREP_CONTENT_FLOOD["numFiles"]+ assert out["numLines"] == 2+++class TestReplacesToolOutput:+ @pytest.mark.parametrize("client", [None, "claude", "claude-code"])+ def test_clients_that_can_replace(self, client) -> None:+ assert search_digest.replaces_tool_output(client) is True++ def test_codex_cannot(self) -> None:+ assert search_digest.replaces_tool_output("codex") is Falsediff --git a/tests/unit/cli/test_editor_setup.py b/tests/unit/cli/test_editor_setup.pyindex caff00590..1af4bd64e 100644--- a/tests/unit/cli/test_editor_setup.py+++ b/tests/unit/cli/test_editor_setup.py@@ -200,31 +200,83 @@ def test_distill_optout_recorded_despite_no_editor_setup(monkeypatch, tmp_path:assert verdicts == [False]-def _hook_verdicts(repo_path: Path) -> tuple[object, object]:- """``(distill.commands.enabled, hooks.read_skeleton)`` as written to disk."""+def test_the_consent_names_every_surface_a_yes_turns_on(monkeypatch, tmp_path: Path) -> None:+ """One question, but it has to say what it covers.++ A yes here writes every ``hooks.<surface>`` key, so a surface added without+ a line in this prompt is one the user enabled without being told. That is+ not a hypothetical: read-skeleton shipped undisclosed, and search-digest+ was added to the same consent while the prompt still named only Reads.+ The `repowise hook <name>` toggle stands in for the surface, since it is+ the string a user can act on.+ """+ from repowise.cli.commands.init_cmd._interactive import offer_distill_rewrite_hook+ from repowise.cli.helpers import HOOK_REPLACEMENT_SURFACES++ _patch_distill_offer(monkeypatch)+ monkeypatch.setattr("sys.stdin.isatty", lambda: True)+ monkeypatch.setattr("click.confirm", lambda *a, **k: False)++ console = _silent_console()+ offer_distill_rewrite_hook(console, [tmp_path], None)+ # Collapsed: rich wraps to the console width, so a phrase this asserts on+ # can arrive split across two lines.+ shown = " ".join(console.file.getvalue().split())++ for surface in HOOK_REPLACEMENT_SURFACES:+ toggle = f"repowise hook {surface.replace('_', '-')}"+ assert toggle in shown, f"the consent prompt never mentions {toggle}"+++def test_the_distill_hook_flag_names_every_surface_it_decides() -> None:+ """``--distill-hook`` sets all of them with no prompt at all, so its help+ text is the only disclosure that path has."""+ from repowise.cli.commands.init_cmd.command import init_command+ from repowise.cli.helpers import HOOK_REPLACEMENT_SURFACES++ (option,) = [o for o in init_command.params if o.name == "distill_hook"]+ for surface in HOOK_REPLACEMENT_SURFACES:+ assert surface in option.help, f"--distill-hook help never mentions {surface}"+++def _hook_verdicts(repo_path: Path) -> tuple[object, ...]:+ """``distill.commands.enabled`` then every ``hooks.<surface>``, from disk.++ Built from ``HOOK_REPLACEMENT_SURFACES`` rather than a literal list, so a+ surface added without a writer fails these tests instead of shipping+ unreachable, which is exactly how read-skeleton shipped.+ """import yaml+ from repowise.cli.helpers import HOOK_REPLACEMENT_SURFACES+cfg = yaml.safe_load((repo_path / ".repowise" / "config.yaml").read_text("utf-8")) or {}+ hooks = cfg.get("hooks") or {}return (((cfg.get("distill") or {}).get("commands") or {}).get("enabled"),- (cfg.get("hooks") or {}).get("read_skeleton"),+ *(hooks.get(surface) for surface in HOOK_REPLACEMENT_SURFACES),)+def _all_same(verdicts: tuple[object, ...], answer: bool) -> bool:+ return verdicts == (answer,) * len(verdicts)++@pytest.mark.parametrize("answer", [True, False])-def test_the_rewrite_hook_answer_decides_read_skeleton_too(+def test_the_rewrite_hook_answer_decides_every_replacing_surface(monkeypatch, tmp_path: Path, answer: bool) -> None:- """One question, both keys.+ """One question, every key.The prompt already means "repowise's hooks may intervene in my agent'stool calls", and rewriting a Bash command into `repowise distill` is a- larger intervention than serving a Read as its skeleton, not a smaller- one — so a second prompt would be asking for permission already given.+ larger intervention than serving a Read as its skeleton or a search as its+ digest, not a smaller one, so a second prompt would be asking for+ permission already given.- The concrete thing this pins is that read-skeleton has *a* writer at all.- It shipped with none, reachable only by hand-editing YAML, which left its- gate needing 50 firings it could never collect.+ The concrete thing this pins is that each replacing surface has *a* writer+ at all. Read-skeleton shipped with none, reachable only by hand-editing+ YAML, which left its gate needing 50 firings it could never collect."""from repowise.cli.commands.init_cmd._interactive import offer_distill_rewrite_hook@@ -236,12 +288,12 @@ def test_the_rewrite_hook_answer_decides_read_skeleton_too(offer_distill_rewrite_hook(_silent_console(), [tmp_path], answer, yes=True)- assert _hook_verdicts(tmp_path) == (answer, answer)+ assert _all_same(_hook_verdicts(tmp_path), answer)-def test_no_editor_setup_turns_off_read_skeleton_as_well(monkeypatch, tmp_path: Path) -> None:- """One flag, one meaning: no hooks. An opt-out that left read-skeleton on- would be `--no-editor-setup` still letting a hook rewrite what Read+def test_no_editor_setup_turns_off_every_replacing_surface(monkeypatch, tmp_path: Path) -> None:+ """One flag, one meaning: no hooks. An opt-out that left one of these on+ would be `--no-editor-setup` still letting a hook rewrite what a toolreturns."""from repowise.cli.commands.init_cmd._interactive import offer_distill_rewrite_hook@@ -251,7 +303,7 @@ def test_no_editor_setup_turns_off_read_skeleton_as_well(monkeypatch, tmp_path:_silent_console(), [tmp_path], False, yes=True, no_editor_setup=True)- assert _hook_verdicts(tmp_path) == (False, False)+ assert _all_same(_hook_verdicts(tmp_path), False)def test_distill_offer_silent_when_undecided_and_setup_off(monkeypatch, tmp_path: Path) -> None: