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 Read hook serves the skeleton instead of recommending it (#1275)
Raghav Chamadiyac29220fe8513
diff --git a/docs/agent/HOOKS.md b/docs/agent/HOOKS.mdindex 192b54ca7..610b707ce 100644--- a/docs/agent/HOOKS.md+++ b/docs/agent/HOOKS.md@@ -127,10 +127,27 @@ what it depends on, and that it is a hotspot, without a separate MCP call:in `.repowise/state.json` and, if the wiki is behind, reminds the agent to run`repowise update` so it never silently works from outdated docs.-**Read-intelligence.** On `Read` of an indexed file, repowise can nudge the agent-toward the cheaper `get_context(..., include=["skeleton"])` for structure-level-questions, and emit a per-file stale-read notice when the file changed after-indexing.+**Read-intelligence.** On `Read` of an indexed file, repowise emits a per-file+stale-read notice when the file changed after the session's previous read of it,+and points at the cheaper `get_context(..., include=["skeleton"])` for+structure-level questions.++With `hooks.read_skeleton: true` in `.repowise/config.yaml` (**off by default**,+see [CONFIG.md](../reference/CONFIG.md)), that pointer becomes an action: an+unbounded `Read` of a large indexed file returns the file's *skeleton* instead of+the file, once per file per session. Signatures stay, keeping their real line+numbers; bodies collapse to `... N lines (a-b)` markers carrying 1-indexed ranges,+so the agent can range-read any elided span back — the same reversibility contract+`repowise distill` makes for shell output. Reading the file again with no range+returns it whole. Savings appear in `repowise saved` under the `read_skeleton`+filter.++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+satisfies Claude Code's read-before-edit precondition, so an `Edit` (especially+with `replace_all`) or a `Write` could touch bodies it never saw. Editing such a+file raises a one-line warning, once per file, until the file is read in full.**Edit-time "governed by" decisions.** When the agent edits a file governed by anarchitectural decision (via `decision_node_links`), it gets a one-line noticediff --git a/docs/reference/CONFIG.md b/docs/reference/CONFIG.mdindex 42556772b..0d0f9e082 100644--- a/docs/reference/CONFIG.md+++ b/docs/reference/CONFIG.md@@ -237,6 +237,31 @@ distill:`commands.enabled: false`, so a rewrite hook installed globally from anotherrepo stays inert in this one.+### The `hooks:` block++Opt-in behaviour for the agent hooks ([HOOKS.md](../agent/HOOKS.md)). Absent+means every key below is off.++```yaml+hooks:+ read_skeleton: false # serve large indexed files as skeletons+```++- `read_skeleton` lets the PostToolUse Read hook return the *skeleton* of a+ file instead of the file, for an unbounded Read of a large indexed file, once+ per file per session. Signatures stay; bodies become `... N lines (a-b)`+ markers carrying 1-indexed ranges, so any elided span can be pulled back with+ a ranged Read — and reading the file a second time returns it whole.+ Savings land in `repowise saved` under the `read_skeleton` filter.+- **Default off, deliberately.** This is the only hook that changes what a tool+ returned rather than adding to it, and it is being measured against a+ pass/fail threshold set before it was built. Turn it on if you want the+ token saving now; leave it off if you want the agent to see exactly what it+ asked for.+- `REPOWISE_HOOK_READ_SKELETON=1` overrides the file for one session.+ Requires Claude Code 2.1.218+ (older clients silently fall back to the+ one-line pointer at `get_context(include=["skeleton"])`).+### The `mcp:` blockControls which tools the MCP server advertises. The default surface is curateddiff --git a/packages/cli/src/repowise/cli/commands/augment_cmd/_shared.py b/packages/cli/src/repowise/cli/commands/augment_cmd/_shared.pyindex a6f6f36e9..7ee2ed541 100644--- a/packages/cli/src/repowise/cli/commands/augment_cmd/_shared.py+++ b/packages/cli/src/repowise/cli/commands/augment_cmd/_shared.py@@ -9,8 +9,41 @@ from __future__ import annotationsimport tempfileimport time+from collections.abc import Callablefrom functools import lru_cachefrom pathlib import Path+from typing import NamedTuple+++class HookResult(NamedTuple):+ """What one PostToolUse handler wants the hook to do.++ ``context`` is appended to what the agent sees (``additionalContext``);+ ``replacement`` *replaces* the tool result outright+ (``updatedToolOutput``). Most handlers only ever set ``context``, so+ :func:`as_result` lifts their bare ``str | None`` into this shape and the+ two-field response is assembled in exactly one place.++ ``on_emitted`` is bookkeeping the handler wants done *after* the response+ reaches the agent — savings accounting, counters. Anything here is off the+ critical path by construction, which is the only way to keep it honest:+ a docstring promising "this runs after the response" is not enforcement,+ and the first version of this got it wrong.+ """++ context: str | None = None+ replacement: str | None = None+ on_emitted: Callable[[], None] | None = None++ def __bool__(self) -> bool:+ return bool(self.context or self.replacement)+++def as_result(value: HookResult | str | None) -> HookResult:+ """Normalize a handler return into a :class:`HookResult`."""+ if isinstance(value, HookResult):+ return value+ return HookResult(context=value or None)#: Wall clock at the first moment repowise code runs in this hook process.#: Every ledger row carries the elapsed time to its own write, which is thediff --git a/packages/cli/src/repowise/cli/commands/augment_cmd/command.py b/packages/cli/src/repowise/cli/commands/augment_cmd/command.pyindex cce956c99..a209bd5b8 100644--- a/packages/cli/src/repowise/cli/commands/augment_cmd/command.py+++ b/packages/cli/src/repowise/cli/commands/augment_cmd/command.py@@ -37,10 +37,14 @@ Codex SessionStart/UserPromptSubmit: adds short repowise MCP usage guidance.already warned for this HEAD, emit a one-line stale-wiki notice.PostToolUse → Read- * Skeleton nudge: a large Read of an indexed file gets a one-line- pointer at the skeleton surface (get_context include=["skeleton"]),- with a cheap bounds-arithmetic estimate of the saving. Once per file- per session.+ * Skeleton replacement: an unbounded Read of a large indexed file is+ served as its skeleton via updatedToolOutput, elision markers and+ 1-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.+ * Skeleton nudge: the fallback when the replacement does not apply —+ a one-line pointer at get_context(include=["skeleton"]) with a cheap+ bounds-arithmetic estimate.* Stale-read notice: when this file was Edited/Written after thesession's previous Read of it, flag that earlier excerpts are stale.Once per file per session, never blocking.@@ -79,6 +83,7 @@ from pathlib import Pathimport click+from ._shared import HookResult, as_resultfrom .bash_staleness import _handle_bash_postfrom .codex import _handle_codex_context_event, _handle_post_edit_usefrom .read_state import _handle_edit_post, _handle_read_post, _record_edit@@ -159,6 +164,11 @@ def _run_augment(*, client: str | None = None) -> None:)if result:_emit_response(event, result)+ if result.on_emitted is not None:+ # Post-response bookkeeping, for the same reason _count_run is below:+ # the agent must not wait on accounting.+ with contextlib.suppress(Exception):+ result.on_emitted()_count_run(cwd, session_id, event, tool_name, emitted=bool(result))@@ -182,24 +192,30 @@ def _count_run(cwd: str, session_id: str, event: str, tool: str, *, emitted: booreturn-def _emit_response(event: str, context: str) -> None:+def _emit_response(event: str, result: HookResult | str) -> None:"""Write the hook JSON response to stdout.+ Two fields, and they are not alternatives: ``additionalContext`` is+ appended to what the agent sees, ``updatedToolOutput`` replaces the tool+ result outright. Claude Code accepts both together, and the Read surface+ can legitimately want both — a stale-read flag alongside a served+ skeleton.+Suppressed when an identical emission was just produced (see:func:`_claim_emission`) so two concurrently-registered repowise hooks —one bundled in the Claude Code plugin, one written to``~/.claude/settings.json`` by ``repowise init`` — can't echo the sameenrichment block twice on a single tool event."""- if not _claim_emission(event, context):+ result = as_result(result)+ if not _claim_emission(event, f"{result.context or ''}\x00{result.replacement or ''}"):return- response = {- "hookSpecificOutput": {- "hookEventName": event,- "additionalContext": context,- }- }- sys.stdout.write(json.dumps(response))+ payload: dict[str, str] = {"hookEventName": event}+ if result.context:+ payload["additionalContext"] = result.context+ if result.replacement:+ payload["updatedToolOutput"] = result.replacement+ sys.stdout.write(json.dumps({"hookSpecificOutput": payload}))sys.stdout.flush()@@ -259,8 +275,13 @@ def _handle_post_tool_use(*,client: str | None = None,session_id: str = "",-) -> str | None:- """Dispatch PostToolUse events from Claude or Codex."""+) -> 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.+ """# 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# emit Codex-flavored banners to Claude Code users. Both clients record@@ -269,10 +290,10 @@ def _handle_post_tool_use(if tool_name in _EDIT_TOOL_NAMES:if client == "codex":_record_edit(tool_input, cwd, session_id)- return _handle_post_edit_use(- cwd, session_id=session_id, tool_input=tool_input+ return as_result(+ _handle_post_edit_use(cwd, session_id=session_id, tool_input=tool_input))- return _handle_edit_post(tool_input, cwd, session_id)+ return as_result(_handle_edit_post(tool_input, cwd, session_id))if tool_name == "Read":# Read-after-served KPI: logged to the ledger, never spoken about._log_read_after_served(tool_input, tool_output, cwd, session_id)@@ -280,12 +301,14 @@ def _handle_post_tool_use(if tool_name in ("Bash", "PowerShell"):# The PowerShell tool (Windows Claude Code) surfaces the same# stdout/stderr response shape as Bash — one handler covers both.- return _handle_bash_post(tool_input, tool_output, cwd)+ return as_result(_handle_bash_post(tool_input, tool_output, cwd))if tool_name in ("Grep", "Glob"):- return _handle_search_post(tool_name, tool_input, tool_output, cwd, session_id)+ return as_result(+ _handle_search_post(tool_name, tool_input, tool_output, cwd, session_id)+ )if tool_name.startswith("mcp__") and "repowise" in tool_name.lower():# Served-content bookkeeping for the read-after-served KPI. Never# emits — measurement only._handle_mcp_read_post(tool_output, cwd, session_id)- return None- return None+ return HookResult()+ return HookResult()diff --git a/packages/cli/src/repowise/cli/commands/augment_cmd/read_skeleton.py b/packages/cli/src/repowise/cli/commands/augment_cmd/read_skeleton.pynew file mode 100644index 000000000..60dab8101--- /dev/null+++ b/packages/cli/src/repowise/cli/commands/augment_cmd/read_skeleton.py@@ -0,0 +1,354 @@+"""PostToolUse Read → serve the indexed skeleton instead of the whole file.++The skeleton *nudge* — a one-line pointer at ``get_context(include=+["skeleton"])`` — fired 502 times across 185 sessions and was acted on once.+It did not fail on content. It failed by asking the agent to do something the+hook could do itself. This module does it instead: when every gate below+clears, the hook returns ``updatedToolOutput`` and the agent's Read of a large+indexed file arrives as its skeleton.++**This is not a silent truncation.** ``build_skeleton`` marks every elided+span with its 1-indexed line range, so the agent can see exactly what was+removed and range-read any of it back — the same contract ``repowise distill``+makes for shell output and the omission store makes for truncated MCP+responses. Reads were the last unfiltered surface. Reading the file a second+time returns it whole; the header says so.++Gates, cheapest first (:func:`skeleton_replacement`):++1. **Unbounded read only.** A ranged Read is already a targeted question.+2. **Above the size floor** the nudge already used.+3. **Opted in.** ``hooks.read_skeleton: true`` in ``.repowise/config.yaml``,+ default off. Read with a lazy ``yaml`` import and fail-closed.+4. **Not a verification re-read.** A Read that follows an Edit of the same+ file wants fidelity, not structure.+5. **Once per file per session.** The second Read is the escape hatch.+6. **Indexed**, with symbol bounds persisted.+7. **Worth it** — skeleton well under full, and the saving clears the floor.+8. **Under the output cap**, whole. A truncated skeleton would lose its+ trailing elision ranges, which is the part that makes this reversible.++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 Read untouched.+"""++from __future__ import annotations++import json+import os+import re+import sqlite3+from pathlib import Path+from typing import TYPE_CHECKING++if TYPE_CHECKING: # pragma: no cover - the hook path imports these lazily+ from repowise.core.distill.skeleton import SkeletonResult, SkeletonSymbol++#: Claude Code release that introduced ``updatedToolOutput``. Older clients+#: ignore the field, which would silently drop the enrichment, so on those we+#: 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++#: Savings-ledger identity, so ``repowise saved`` can name this surface.+_SAVINGS_SOURCE = "hook-read"+_SAVINGS_FILTER = "read_skeleton"++_CONFIG_FLAG = "read_skeleton"+++class Replacement:+ """A skeleton ready to be served in place of a Read, and its ledger facts.++ A tiny value object rather than a tuple: the caller records a saving, logs+ a ledger row and emits the text, and three positional elements at that+ call site would read as noise.+ """++ __slots__ = ("full_tokens", "rel", "skeleton_tokens", "text")++ def __init__(self, *, rel: str, text: str, full_tokens: int, skeleton_tokens: int) -> None:+ self.rel = rel+ self.text = text+ self.full_tokens = full_tokens+ self.skeleton_tokens = skeleton_tokens++ @property+ def saved_tokens(self) -> int:+ return max(0, self.full_tokens - self.skeleton_tokens)+++# ---------------------------------------------------------------------------+# Gates+# ---------------------------------------------------------------------------+++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.+ """+ 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+++def supports_updated_output() -> bool:+ """True when the Claude Code client can honour ``updatedToolOutput``.++ There is no version in the hook payload and no version env var, and+ ``claude --version`` is a ~1s subprocess this path cannot afford. The one+ cheap on-disk signal is the updater's own record, so we read that and+ **fail open** — an unsupported client ignores the unknown field, which+ costs a skipped enrichment, never a broken Read.+ """+ override = os.environ.get("REPOWISE_HOOK_UPDATED_OUTPUT")+ if override is not None:+ return override.strip().lower() in ("1", "true", "yes", "on")+ version = _recorded_client_version()+ return version is None or version >= _MIN_CLIENT_VERSION+++def _recorded_client_version() -> tuple[int, ...] | None:+ """Installed Claude Code version per ``~/.claude/.last-update-result.json``.++ Best effort by construction: the file only exists once the updater has run+ at least once, and its ``version_to`` is null on a failed update — in which+ case ``version_from`` is what is still installed.+ """+ try:+ raw = (Path.home() / ".claude" / ".last-update-result.json").read_text(encoding="utf-8")+ data = json.loads(raw)+ except (OSError, ValueError, RuntimeError):+ return None+ if not isinstance(data, dict):+ return None+ for key in ("version_to", "version_from"):+ value = data.get(key)+ if isinstance(value, str) and value:+ parts = value.split(".")+ if all(p.isdigit() for p in parts) and parts:+ return tuple(int(p) for p in parts)+ return None+++def is_unbounded_read(tool_input: dict) -> bool:+ """True for a Read with neither offset nor limit — the whole file."""+ if not isinstance(tool_input, dict):+ return False+ return tool_input.get("offset") is None and tool_input.get("limit") is None+++# ---------------------------------------------------------------------------+# Building the replacement+# ---------------------------------------------------------------------------+++def skeleton_replacement(+ repo_path: Path,+ rel: str,+ *,+ min_ratio_gain: float,+ min_saved_tokens: int,+) -> Replacement | None:+ """Render *rel*'s skeleton, or None when any content gate fails.++ Callers own the cheap gates (see the module docstring); by the time this+ runs we have already decided the Read is a candidate, so it may pay for+ the index query and the render (~1ms — pure line slicing, no parser).+ """+ symbols = _indexed_symbols(repo_path / ".repowise" / "wiki.db", rel)+ if not symbols:+ return None+ try:+ source = (repo_path / rel).read_text(encoding="utf-8", errors="replace")+ except OSError:+ return None+ if not source.strip():+ return None++ from repowise.core.distill.skeleton import build_skeleton++ total_lines = len(source.splitlines())+ # "smart" over "signatures" for the docstring summary line it keeps under+ # each signature. Its body-budget machinery is inert here on purpose: no+ # PageRank is persisted on wiki_symbols, so every importance is 0.0 and no+ # body is ever kept. That is the intended output — a map, not an excerpt.+ result = build_skeleton(source, symbols, mode="smart")+ if result.mode == "raw": # no usable bounds — the index cannot help here+ return None+ if result.skeleton_tokens > result.full_tokens * min_ratio_gain:+ return None+ if result.full_tokens - result.skeleton_tokens < min_saved_tokens:+ return None++ text = _render(rel, result, total_lines)+ if len(text) > _MAX_OUTPUT_CHARS:+ # Without this retry the cap scales backwards: the biggest files, which+ # have the most to save, are the ones whose signatures alone overflow+ # it. Signatures-only drops the docstring summaries and usually fits.+ result = build_skeleton(source, symbols, mode="signatures")+ text = _render(rel, result, total_lines)+ if len(text) > _MAX_OUTPUT_CHARS:+ return None+ return Replacement(+ rel=rel,+ text=text,+ full_tokens=result.full_tokens,+ # The header is part of what the agent is billed for.+ skeleton_tokens=max(1, len(text) // 4),+ )+++#: The elision marker ``_render`` in distill.skeleton emits: indent, then+#: ``... N lines (start-end)``, 1-indexed and inclusive.+_ELISION_RE = re.compile(r"^\s*\.\.\. \d+ lines \((\d+)-(\d+)\)\s*$")+++def _render(rel: str, result: SkeletonResult, total_lines: int) -> str:+ """Header plus numbered skeleton — the header is the reversibility contract."""+ body = _number(result.text, total_lines)+ return (+ f"[repowise] Serving the indexed skeleton of {rel} in place of the full file "+ f"(~{result.skeleton_tokens} tokens vs ~{result.full_tokens}; "+ f"{result.symbol_count} symbols).\n"+ "Kept lines carry their real line numbers. Every `... N lines (a-b)` marker is "+ "an elided span: Read this file with that offset/limit to pull it back, or Read "+ "it again with no range to get the whole file.\n"+ "You have NOT seen the bodies. Do not Edit, Write, or conclude what this file "+ "does or does not contain from a skeleton — read the range first.\n\n"+ f"{body}"+ )+++def _number(text: str, total_lines: int) -> str:+ """Restore Read's line-number gutter on the kept lines.++ Claude Code's Read returns ``cat -n`` output, and dropping the gutter would+ leave the agent knowing line numbers only for the spans it *cannot* see —+ exactly backwards. The numbers are recoverable without the source: each+ elision marker states the range it swallowed, so walking the rendered text+ and jumping the counter at every marker reproduces the original numbering.++ Self-checking: if the walk does not land on the file's real line count the+ reconstruction is wrong somewhere, and a wrong number is worse than none,+ so the text is returned unnumbered instead.+ """+ out: list[str] = []+ line_no = 1+ for line in text.splitlines():+ match = _ELISION_RE.match(line)+ if match:+ out.append(line)+ line_no = int(match.group(2)) + 1+ continue+ out.append(f"{line_no:6d}\t{line}")+ line_no += 1+ if line_no - 1 != total_lines:+ return text+ return "\n".join(out) + "\n"+++def _indexed_symbols(db_path: Path, rel: str) -> list[SkeletonSymbol]:+ """Persisted symbol rows for one file as ``SkeletonSymbol``s, or [].++ Read-only stdlib sqlite3 for the same reason+ :func:`read_state._file_symbol_bounds` uses it: the hook path must not pay+ the sqlalchemy import to read five columns.+ """+ if not db_path.exists():+ return []+ try:+ con = sqlite3.connect(f"file:{db_path.as_posix()}?mode=ro", uri=True, timeout=1)+ try:+ rows = con.execute(+ "SELECT name, kind, start_line, end_line, signature "+ "FROM wiki_symbols WHERE file_path = ?",+ (rel,),+ ).fetchall()+ finally:+ con.close()+ except sqlite3.Error:+ return []+ if not rows:+ return []++ from repowise.core.distill.skeleton import SkeletonSymbol++ return [+ SkeletonSymbol(+ name=name,+ kind=kind,+ start_line=start,+ end_line=end,+ signature=signature or "",+ )+ for name, kind, start, end, signature in rows+ if isinstance(start, int) and isinstance(end, int) and start > 0+ ]+++# ---------------------------------------------------------------------------+# Savings ledger+# ---------------------------------------------------------------------------+++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:+ returndiff --git a/packages/cli/src/repowise/cli/commands/augment_cmd/read_state.py b/packages/cli/src/repowise/cli/commands/augment_cmd/read_state.pyindex aeba9d338..8cdd8ccf0 100644--- a/packages/cli/src/repowise/cli/commands/augment_cmd/read_state.py+++ b/packages/cli/src/repowise/cli/commands/augment_cmd/read_state.py@@ -1,27 +1,38 @@"""PostToolUse Read/Edit/Write per-session read intelligence.A small JSON state file under .repowise/ tracks which files this agent-session has Read and Edited, keyed by the hook payload's session_id. Two+session has Read and Edited, keyed by the hook payload's session_id. Threebehaviors ride on it:* Stale-read notice — a Read of a file whose previous Read predates arecorded Edit/Write gets a one-line "earlier excerpts are stale" flag.- * Skeleton nudge — a large Read of an indexed file gets a pointer at- get_context(include=["skeleton"]) with a bounds-arithmetic estimate.+ * Skeleton replacement — an unbounded Read of a large indexed file is+ *served as* its skeleton via ``updatedToolOutput``, once per file per+ session, when the repo opted in. Gates and rationale live in+ :mod:`read_skeleton`; this module owns only the session-state gates.+ * Skeleton nudge — the fallback when the replacement does not apply: a+ one-line pointer at get_context(include=["skeleton"]) with a+ bounds-arithmetic estimate. Measured at 0.2%, and on the way out — it+ survives only to cover clients that cannot honour a replacement.Rate limiting is the state file itself (per-file, per-session lists), NOTthe _claim_emission temp marker — that TTL-based dedup only suppresses thetwo concurrently-registered hooks racing on one tool event, which stillapplies on top. A new session_id resets the state.++The re-read notice lived here too, and was retired: it scored 100%+"respected" only because agents rarely read the same file a third time, so+it was measuring the base rate and changing nothing. The case it argued —+"you already have this, take a range instead" — is now handled by doing it+rather than saying it."""from __future__ import annotations-import contextlibimport jsonfrom pathlib import Path-from ._shared import _extract_output_text, _find_repo_root, _relativize+from ._shared import HookResult, _extract_output_text, _find_repo_root, _relativize_READ_NUDGE_MIN_LINES = 100 # Read output lines before a skeleton nudge_READ_NUDGE_MIN_TOKENS = 3000 # full-file tokens below which a nudge is noise@@ -48,7 +59,14 @@ def _load_session_state(repo_path: Path, session_id: str) -> dict:"edits": {},"nudged": [],"stale_notified": [],- "reread_notified": [],+ # Files served as a skeleton this session. Doubles as the once-per-+ # file gate and as the "did the agent come back for it" marker.+ "skeletonized": [],+ # Skeletonized files the agent later read in full, and files whose+ # edit-from-a-skeleton warning has already fired. Both exist to keep+ # that warning to exactly the window where it is true.+ "read_whole": [],+ "skeleton_edit_warned": [],"decisions_shown": [],# File ranges served by repowise MCP responses this session, kept for# the read-after-served KPI (see read_enrich; rel -> [[start, end]]).@@ -66,15 +84,23 @@ def _load_session_state(repo_path: Path, session_id: str) -> dict:return state-def _save_session_state(repo_path: Path, state: dict) -> None:- """Persist session state; trims unbounded growth, never raises."""+def _save_session_state(repo_path: Path, state: dict) -> bool:+ """Persist session state; trims unbounded growth, never raises.++ Returns whether the write landed. Most callers can ignore that — a lost+ notice-dedup entry costs a repeated notice. The skeleton replacement+ cannot: its once-per-file gate *is* this file, so it checks.+ """for key in ("reads", "edits"):entries = state.get(key, {})if len(entries) > 500:keep = sorted(entries, key=entries.get, reverse=True)[:400]state[key] = {k: entries[k] for k in keep}- with contextlib.suppress(OSError, TypeError, ValueError):+ try:_session_state_path(repo_path).write_text(json.dumps(state), encoding="utf-8")+ except (OSError, TypeError, ValueError):+ return False+ return Truedef _record_edit(tool_input: dict, cwd: str, session_id: str) -> None:@@ -112,6 +138,9 @@ def _handle_edit_post(state["edits"][rel] = state["seq"]notices: list[str] = []+ skeleton_warning = _edit_from_skeleton_notice(rel, state)+ if skeleton_warning:+ notices.append(skeleton_warning)if with_decisions:from .decision_inject import _edit_decision_notice, _edit_fix_history_notice@@ -130,22 +159,47 @@ def _handle_edit_post(return "\n".join(notices) or None+def _edit_from_skeleton_notice(rel: str, state: dict) -> str | None:+ """Flag an edit to a file this session has only ever seen as a skeleton.++ The replacement satisfies Claude Code's read-before-edit precondition with+ a Read whose *content* the agent never saw, and that cuts the wrong way in+ three places the header alone cannot reach: an ``Edit`` with+ ``replace_all`` rewrites occurrences inside elided spans, a ``Write``+ reconstructs the file from signatures and destroys every body, and+ "does this file do X?" gets answered from a map. Once per file per+ session, and it stops as soon as the agent reads the file for real —+ which is what makes it a guard rather than a drumbeat.+ """+ if rel not in state["skeletonized"]:+ return None+ if rel in state["read_whole"] or rel in state["skeleton_edit_warned"]:+ return None+ state["skeleton_edit_warned"].append(rel)+ return (+ f"[repowise] You have only seen {rel} as a skeleton this session — its bodies "+ "were elided. Read the range you are changing (or the whole file) before "+ "trusting an exact-match edit, a rewrite, or a conclusion about what this "+ "file contains."+ )++def _handle_read_post(tool_input: dict,tool_output: object,cwd: str,session_id: str,-) -> str | None:- """Stale-read notice + skeleton nudge for a completed Read."""+) -> HookResult:+ """Stale-read notice, then either a skeleton replacement or the nudge."""file_path = tool_input.get("file_path") if isinstance(tool_input, dict) else Noneif not isinstance(file_path, str) or not file_path.strip():- return None+ return HookResult()repo_path = _find_repo_root(Path(cwd))if repo_path is None:- return None+ return HookResult()rel = _relativize(file_path, repo_path)if rel is None:- return None+ return HookResult()state = _load_session_state(repo_path, session_id)notices: list[str] = []@@ -165,42 +219,127 @@ def _handle_read_post()fired.append(("stale_read", notices[-1]))- # 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.'- )- fired.append(("reread", notices[-1]))+ _log_skeleton_recovery(repo_path, rel, tool_input, state, fired)state["seq"] += 1state["reads"][rel] = state["seq"]- nudge = _skeleton_nudge(repo_path, rel, tool_output, state)- if nudge:- notices.append(nudge)- fired.append(("skeleton_nudge", nudge))+ replacement = _skeleton_replacement(+ repo_path, rel, tool_input, tool_output, state, edited_since_read=edited_since_read+ )+ if replacement is not None:+ fired.append(("skeleton_served", replacement.text))+ else:+ nudge = _skeleton_nudge(repo_path, rel, tool_output, state)+ if nudge:+ notices.append(nudge)+ fired.append(("skeleton_nudge", nudge))++ persisted = _save_session_state(repo_path, state)+ if replacement is not None and not persisted:+ # The "read it again and you get it whole" escape hatch is the+ # `skeletonized` list, and the list is that state file. If it did not+ # persist — read-only checkout, full disk — the promise in the header+ # would have no ceiling: every unbounded Read would return a skeleton+ # and none would return the file. No durable state, no replacement.+ replacement = None+ fired = [f for f in fired if f[0] != "skeleton_served"]- _save_session_state(repo_path, state)for category, text in fired:_log_read_firing(repo_path, session_id, category, rel, text)- return "\n".join(notices) if notices else None+ return HookResult(+ context="\n".join(notices) if notices else None,+ replacement=replacement.text if replacement is not None else None,+ on_emitted=(+ (lambda r=replacement: _record_skeleton_saving(repo_path, r))+ if replacement is not None+ else None+ ),+ )+++def _skeleton_replacement(+ repo_path: Path,+ rel: str,+ tool_input: dict,+ tool_output: object,+ state: dict,+ *,+ edited_since_read: bool,+):+ """The skeleton to serve in place of this Read, or None. Never raises.++ Ordered cheapest-gate-first so a Read that cannot qualify — which is+ almost all of them — costs a handful of dict lookups and no import. The+ gates themselves are documented in :mod:`read_skeleton`.+ """+ try:+ from .read_skeleton import (+ enabled,+ is_unbounded_read,+ skeleton_replacement,+ supports_updated_output,+ )++ if not is_unbounded_read(tool_input):+ return None+ if _read_output_line_count(tool_output) < _READ_NUDGE_MIN_LINES:+ return None+ # A verification re-read after an edit needs fidelity, not structure.+ if edited_since_read or rel in state["skeletonized"]:+ return None+ if not enabled(repo_path) or not supports_updated_output():+ return None+ replacement = skeleton_replacement(+ repo_path,+ rel,+ min_ratio_gain=_READ_NUDGE_MAX_RATIO,+ min_saved_tokens=_READ_NUDGE_MIN_SAVINGS,+ )+ except Exception:+ # Everything is inside the try, gates included. A malformed config or+ # a stale index must cost this one enrichment, never the stale-read+ # notice and the ledger row that the rest of this handler owes.+ return None+ if replacement is not None:+ state["skeletonized"].append(rel)+ return replacement+++def _log_skeleton_recovery(+ repo_path: Path,+ rel: str,+ tool_input: dict,+ state: dict,+ fired: list[tuple[str, str]],+) -> None:+ """Note that the agent came back for a file we served as a skeleton.++ Gate A's two numbers live here. A *ranged* return is the elision contract+ working as designed; a *full* return is the replacement having been wrong+ about what the agent needed, and is what the gate caps. Both are+ measurement rows — neither is ever spoken about.++ The requested window rides in the row text on purpose. Ledger keys hash+ that text, so a full recovery (stable text) dedups to one row per file+ while each distinct ranged recovery gets its own — which is what Gate A's+ A1 needs, since it charges every recovery back against the saving and+ cannot do that from a count of files.+ """+ if rel not in state["skeletonized"]:+ return+ from .read_skeleton import is_unbounded_read++ if is_unbounded_read(tool_input):+ # The gate above already declined to replace this one, so the agent is+ # getting the real file — it has now genuinely seen it.+ if rel not in state["read_whole"]:+ state["read_whole"].append(rel)+ fired.append(("skeleton_recovered_full", f"skeleton_recovered_full:{rel}"))+ return+ offset = tool_input.get("offset")+ limit = tool_input.get("limit")+ fired.append(("skeleton_ranged", f"skeleton_ranged:{rel}:{offset}:{limit}"))def _log_read_firing(@@ -230,6 +369,21 @@ def _log_read_firing()+def _record_skeleton_saving(repo_path: Path, replacement) -> None:+ """Bill a served skeleton to the savings ledger. Never fails the hook.++ After the response is decided, for the same reason :func:`_count_run` is:+ the agent must not wait on bookkeeping, and a broken ledger must not cost+ an enrichment that is already computed.+ """+ try:+ from .read_skeleton import record_saving++ record_saving(repo_path, replacement)+ except Exception:+ return++def _read_output_line_count(tool_output: object) -> int:"""Line count of a Read result across the hook payload shapes we see."""if isinstance(tool_output, dict):diff --git a/packages/cli/src/repowise/cli/commands/saved_cmd.py b/packages/cli/src/repowise/cli/commands/saved_cmd.pyindex b980cc176..72a87f38c 100644--- a/packages/cli/src/repowise/cli/commands/saved_cmd.py+++ b/packages/cli/src/repowise/cli/commands/saved_cmd.py@@ -123,8 +123,10 @@ def saved_command(border_style="dim",show_footer=True,caption=(- "Covers the 'repowise distill' command/hook path plus MCP "- "counterfactual savings (mcp:<tool>); group by source to split them."+ "Covers the 'repowise distill' command/hook path, MCP "+ "counterfactual savings (mcp:<tool>), and the Read hook serving a "+ "skeleton in place of a whole file (read_skeleton / hook-read); "+ "group by source to split them."),)table.add_column(group_by.capitalize(), style="cyan", footer="[bold]TOTAL[/bold]")diff --git a/packages/core/src/repowise/core/distill/__init__.py b/packages/core/src/repowise/core/distill/__init__.pyindex 75fae76b1..19c006b01 100644--- a/packages/core/src/repowise/core/distill/__init__.py+++ b/packages/core/src/repowise/core/distill/__init__.py@@ -1,31 +1,32 @@"""Distill — index-aware compaction of noisy command output.-The engine orchestrates the pure pieces (router -> filter) around the-stateful ones (omission store, savings ledger) and owns the safety-guarantees the filters rely on:--- **fallback-to-raw**: any filter exception, storage failure, or- non-improvement returns the original output untouched;-- **reversibility**: the full raw output is persisted before a marker is- emitted, so ``repowise expand <ref>`` always round-trips;-- **net-positive only**: distilled text (marker included) must actually be- smaller than the raw output, with a small floor so trivial wins don't- litter markers everywhere.+This package `__init__` is a **lazy re-export shim** and imports nothing at+module scope. The public names below resolve on first attribute access via+PEP 562 ``__getattr__``, so ``from repowise.core.distill import+distill_output`` still works and costs the same as before, while importing a+sibling submodule costs only that submodule.++Why it matters: a package ``__init__`` runs on *any* submodule import, so the+engine's graph (structlog, the filter registry, the omission store) used to be+charged to ``import repowise.core.distill.skeleton`` — 556ms, paid by the+PostToolUse Read hook on every fire that reached the skeleton path. Same bug+class as ``search.py``'s ``persistence.sql`` and ``claude_config.py``'s+``core.workspace.config``; this is the shape that stops it recurring here.++The engine itself lives in :mod:`repowise.core.distill.engine`."""from __future__ import annotations-import contextlib-from dataclasses import dataclass-from pathlib import Path--import structlog+from typing import TYPE_CHECKING, Any-from repowise.core.distill.budget import estimate_tokens, savings_pct-from repowise.core.distill.markers import parse_marker_refs, render_marker-from repowise.core.distill.registry import filter_registry-from repowise.core.distill.router import normalize_command, select_filter-from repowise.core.distill.store import OmissionStore+if TYPE_CHECKING: # pragma: no cover - import-time typing only+ from repowise.core.distill.budget import estimate_tokens, savings_pct+ from repowise.core.distill.engine import DistillResult, distill_output+ from repowise.core.distill.markers import parse_marker_refs, render_marker+ from repowise.core.distill.registry import filter_registry+ from repowise.core.distill.router import normalize_command, select_filter+ from repowise.core.distill.store import OmissionStore__all__ = ["DistillResult",@@ -40,109 +41,33 @@ __all__ = ["select_filter",]-logger = structlog.get_logger(__name__)--#: Distillation must save at least this many tokens to be worth a marker.-MIN_SAVED_TOKENS = 40---@dataclass(frozen=True)-class DistillResult:- """Outcome of one distillation attempt."""-- text: str- distilled: bool- filter_name: str | None- ref: str | None- raw_tokens: int- distilled_tokens: int-- @property- def savings_pct(self) -> float:- return savings_pct(self.raw_tokens, self.distilled_tokens)---def distill_output(- output: str,- *,- command: str = "",- exit_code: int = 0,- source: str = "cli",- store: OmissionStore | None = None,- store_start: Path | None = None,- disabled_filters: tuple[str, ...] = (),-) -> DistillResult:- """Distill *output*, falling back to the raw text on any failure.-- When *store* is None one is opened at the default sidecar location for- *store_start* (default: cwd) and closed before returning.- """- raw_tokens = estimate_tokens(output)- raw = DistillResult(- text=output,- distilled=False,- filter_name=None,- ref=None,- raw_tokens=raw_tokens,- distilled_tokens=raw_tokens,- )-- try:- chosen = select_filter(command, output, disabled=disabled_filters)- except Exception:- logger.debug("distill filter selection failed", exc_info=True)- return raw- if chosen is None:- return raw- if len(output.splitlines()) < chosen.min_lines:- return raw-- try:- kept = chosen.distill(output, command=command, exit_code=exit_code)- except Exception:- logger.debug("distill filter failed; falling back to raw", filter=chosen.name)- return raw-- kept_tokens = estimate_tokens(kept)- omitted_lines = max(0, len(output.splitlines()) - len(kept.splitlines()))-- owns_store = store is None- try:- if owns_store:- store = OmissionStore.open_default(store_start)- ref = store.put(- output,- source=f"{source}:{chosen.name}",- original_tokens=raw_tokens,- kept_tokens=kept_tokens,- )- marker = render_marker(ref, omitted_lines, max(0, raw_tokens - kept_tokens))- text = kept.rstrip("\n") + "\n\n" + marker + "\n"- distilled_tokens = estimate_tokens(text)- # Net-positive guarantee, marker included.- if distilled_tokens >= raw_tokens - MIN_SAVED_TOKENS:- return raw- store.record_saving(- filter_name=chosen.name,- source=source,- command=command or None,- raw_tokens=raw_tokens,- distilled_tokens=distilled_tokens,- )- return DistillResult(- text=text,- distilled=True,- filter_name=chosen.name,- ref=ref,- raw_tokens=raw_tokens,- distilled_tokens=distilled_tokens,- )- except Exception:- # Raw output is never recoverable without a successful store write,- # so a storage failure means we must not drop anything.- logger.debug("omission store unavailable; falling back to raw", exc_info=True)- return raw- finally:- if owns_store and store is not None:- with contextlib.suppress(Exception):- store.close()+#: Public name -> defining submodule. The single source of truth for both+#: ``__getattr__`` and ``__dir__``; ``__all__`` above is asserted against it.+_EXPORTS: dict[str, str] = {+ "DistillResult": "engine",+ "OmissionStore": "store",+ "distill_output": "engine",+ "estimate_tokens": "budget",+ "filter_registry": "registry",+ "normalize_command": "router",+ "parse_marker_refs": "markers",+ "render_marker": "markers",+ "savings_pct": "budget",+ "select_filter": "router",+}+++def __getattr__(name: str) -> Any:+ """Resolve a public export on first access, importing only its module."""+ module = _EXPORTS.get(name)+ if module is None:+ raise AttributeError(f"module {__name__!r} has no attribute {name!r}")+ from importlib import import_module++ value = getattr(import_module(f"{__name__}.{module}"), name)+ globals()[name] = value # cache: subsequent accesses skip __getattr__+ return value+++def __dir__() -> list[str]:+ return sorted(__all__)diff --git a/packages/core/src/repowise/core/distill/budget.py b/packages/core/src/repowise/core/distill/budget.pyindex 41a55f344..61097c6c1 100644--- a/packages/core/src/repowise/core/distill/budget.py+++ b/packages/core/src/repowise/core/distill/budget.py@@ -1,16 +1,25 @@-"""Token estimation for distill — thin façade over the shared heuristic.+"""Token estimation for distill — the shared 4-chars-per-token heuristic.-Reuses the generation-side 4-chars-per-token estimator so every repowise-subsystem reports savings on the same scale. No tiktoken dependency.+Every repowise subsystem reports savings on this one scale, and no subsystem+carries a tiktoken dependency to do it.++The estimator *lives* here, and ``generation.context.token_budget`` re-exports+it, rather than the other way round. Deliberate: distill is a leaf utility+with no package-level graph, while ``generation.context``'s ``__init__`` pulls+the assembler → the ingestion models → networkx (538ms). Importing four lines+of arithmetic must not cost that, on the hook path or anywhere else."""from __future__ import annotations-from repowise.core.generation.context.token_budget import estimate_tokens-__all__ = ["estimate_tokens", "savings_pct"]+def estimate_tokens(text: str) -> int:+ """Estimate token count using the 4-chars-per-token heuristic."""+ return len(text) // 4++def savings_pct(raw_tokens: int, distilled_tokens: int) -> float:"""Percentage of tokens saved by distillation (0.0 when nothing saved)."""if raw_tokens <= 0:diff --git a/packages/core/src/repowise/core/distill/engine.py b/packages/core/src/repowise/core/distill/engine.pynew file mode 100644index 000000000..6b58e1764--- /dev/null+++ b/packages/core/src/repowise/core/distill/engine.py@@ -0,0 +1,139 @@+"""Distill's engine — the orchestration around the pure filter pieces.++Lives here rather than in ``distill/__init__.py`` so that importing any+*other* distill submodule (notably :mod:`repowise.core.distill.skeleton`, on+the PostToolUse Read hook path) does not run the engine's import graph.+``__init__`` re-exports everything below lazily; see its docstring.++The engine owns the safety guarantees the filters rely on:++- **fallback-to-raw**: any filter exception, storage failure, or+ non-improvement returns the original output untouched;+- **reversibility**: the full raw output is persisted before a marker is+ emitted, so ``repowise expand <ref>`` always round-trips;+- **net-positive only**: distilled text (marker included) must actually be+ smaller than the raw output, with a small floor so trivial wins don't+ litter markers everywhere.+"""++from __future__ import annotations++import contextlib+from dataclasses import dataclass+from pathlib import Path++import structlog++from repowise.core.distill.budget import estimate_tokens, savings_pct+from repowise.core.distill.markers import render_marker+from repowise.core.distill.router import select_filter+from repowise.core.distill.store import OmissionStore++__all__ = ["MIN_SAVED_TOKENS", "DistillResult", "distill_output"]++logger = structlog.get_logger(__name__)++#: Distillation must save at least this many tokens to be worth a marker.+MIN_SAVED_TOKENS = 40+++@dataclass(frozen=True)+class DistillResult:+ """Outcome of one distillation attempt."""++ text: str+ distilled: bool+ filter_name: str | None+ ref: str | None+ raw_tokens: int+ distilled_tokens: int++ @property+ def savings_pct(self) -> float:+ return savings_pct(self.raw_tokens, self.distilled_tokens)+++def distill_output(+ output: str,+ *,+ command: str = "",+ exit_code: int = 0,+ source: str = "cli",+ store: OmissionStore | None = None,+ store_start: Path | None = None,+ disabled_filters: tuple[str, ...] = (),+) -> DistillResult:+ """Distill *output*, falling back to the raw text on any failure.++ When *store* is None one is opened at the default sidecar location for+ *store_start* (default: cwd) and closed before returning.+ """+ raw_tokens = estimate_tokens(output)+ raw = DistillResult(+ text=output,+ distilled=False,+ filter_name=None,+ ref=None,+ raw_tokens=raw_tokens,+ distilled_tokens=raw_tokens,+ )++ try:+ chosen = select_filter(command, output, disabled=disabled_filters)+ except Exception:+ logger.debug("distill filter selection failed", exc_info=True)+ return raw+ if chosen is None:+ return raw+ if len(output.splitlines()) < chosen.min_lines:+ return raw++ try:+ kept = chosen.distill(output, command=command, exit_code=exit_code)+ except Exception:+ logger.debug("distill filter failed; falling back to raw", filter=chosen.name)+ return raw++ kept_tokens = estimate_tokens(kept)+ omitted_lines = max(0, len(output.splitlines()) - len(kept.splitlines()))++ owns_store = store is None+ try:+ if owns_store:+ store = OmissionStore.open_default(store_start)+ ref = store.put(+ output,+ source=f"{source}:{chosen.name}",+ original_tokens=raw_tokens,+ kept_tokens=kept_tokens,+ )+ marker = render_marker(ref, omitted_lines, max(0, raw_tokens - kept_tokens))+ text = kept.rstrip("\n") + "\n\n" + marker + "\n"+ distilled_tokens = estimate_tokens(text)+ # Net-positive guarantee, marker included.+ if distilled_tokens >= raw_tokens - MIN_SAVED_TOKENS:+ return raw+ store.record_saving(+ filter_name=chosen.name,+ source=source,+ command=command or None,+ raw_tokens=raw_tokens,+ distilled_tokens=distilled_tokens,+ )+ return DistillResult(+ text=text,+ distilled=True,+ filter_name=chosen.name,+ ref=ref,+ raw_tokens=raw_tokens,+ distilled_tokens=distilled_tokens,+ )+ except Exception:+ # Raw output is never recoverable without a successful store write,+ # so a storage failure means we must not drop anything.+ logger.debug("omission store unavailable; falling back to raw", exc_info=True)+ return raw+ finally:+ if owns_store and store is not None:+ with contextlib.suppress(Exception):+ store.close()diff --git a/packages/core/src/repowise/core/generation/context/token_budget.py b/packages/core/src/repowise/core/generation/context/token_budget.pyindex 74cb147a8..4ec2f03a3 100644--- a/packages/core/src/repowise/core/generation/context/token_budget.py+++ b/packages/core/src/repowise/core/generation/context/token_budget.py@@ -10,12 +10,11 @@ from __future__ import annotationsfrom collections.abc import Callable, Iterablefrom typing import Any, TypeVar-T = TypeVar("T")-+# Re-exported, not redefined: the estimator lives in the distill leaf module+# so that importing it never drags this package's assembler graph along.+from repowise.core.distill.budget import estimate_tokens-def estimate_tokens(text: str) -> int:- """Estimate token count using the 4-chars-per-token heuristic."""- return len(text) // 4+T = TypeVar("T")def trim_to_budget(text: str, remaining: int) -> str:diff --git a/packages/core/src/repowise/core/sessions/efficacy.py b/packages/core/src/repowise/core/sessions/efficacy.pyindex c0d538601..591dd6d54 100644--- a/packages/core/src/repowise/core/sessions/efficacy.py+++ b/packages/core/src/repowise/core/sessions/efficacy.py@@ -29,7 +29,7 @@ What counts as acting, per surfacesurface category acted when, within the window============= =============== ==================================================read skeleton_nudge a skeleton/structure call on the named file-read reread *respected*: the file is not re-read in full again+read skeleton_served n/a — the hook already did it (see below)read stale_read n/a — a warning, not a pointersearch triage a named file is touchedsearch rescue the named file or symbol is touched@@ -42,6 +42,14 @@ 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+``updatedToolOutput``, so it never appears as a transcript+``hook_additional_context`` line and this module's pattern pass will never+see it. That is fine and deliberate — the hook writes those rows directly and+Gate 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.+Surfaces with no recommended action (``stale_read``) and surfaces that emitnothing at all (``read_enrich``'s read-after-served KPI) are never markedacted and are excluded from action rates rather than counted as failures.@@ -79,12 +87,27 @@ CLASSIFIED_SURFACES = ("read", "search", "fix_history")#: firing is not a failure. Reported as a count, excluded from rates. The#: stale-read notice belongs here because the behavior it asks for — stop#: reasoning from a pre-edit excerpt — leaves no trace in the transcript.-NO_ACTION_EXPECTED = frozenset({("read", "stale_read"), ("read_enrich", "read_after_served")})+NO_ACTION_EXPECTED = frozenset(+ {+ ("read", "stale_read"),+ ("read_enrich", "read_after_served"),+ # The skeleton replacement and its two recovery counters. Nothing is+ # asked of the agent, so an unacted row is not a failure — these are+ # Gate A's numerator and denominator, not an adoption rate.+ ("read", "skeleton_served"),+ ("read", "skeleton_recovered_full"),+ ("read", "skeleton_ranged"),+ }+)#: Firings whose recommended outcome is a *non*-action, scored as compliance#: (did the agent avoid re-offending?) rather than adoption. Same ``acted``#: column, and ``repowise hook stats`` labels these "respected" so the two are#: never read as the same measurement.+#:+#: ``read``/``reread`` is retired — the notice no longer fires (see+#: ``augment_cmd/read_state.py``). The classifier stays so historical rows and+#: transcript backfills still settle correctly; nothing new lands here.COMPLIANCE_CATEGORIES = frozenset({("read", "reread")})diff --git a/tests/unit/cli/test_augment_hook_perf.py b/tests/unit/cli/test_augment_hook_perf.pyindex ccce24075..139812de3 100644--- a/tests/unit/cli/test_augment_hook_perf.py+++ b/tests/unit/cli/test_augment_hook_perf.py@@ -14,7 +14,9 @@ same job for the ``repowise-rewrite`` PreToolUse hook.from __future__ import annotations+import jsonimport os+import sqlite3import subprocessimport sysfrom pathlib import Path@@ -26,6 +28,9 @@ _HEAVY_PREFIXES = ("networkx","scipy","sqlalchemy",+ # 216ms, and it hid behind the others: the Read path reached it through+ # distill.store's module scope while every other guard here still passed.+ "structlog","repowise.core.workspace","repowise.core.ingestion","repowise.core.pipeline",@@ -80,6 +85,102 @@ def test_the_self_heal_imports_nothing_heavy(tmp_path: Path) -> None:assert heavy == "", f"the hook self-heal pulled in:\n{heavy}"+def _read_payload_probe(repo: Path, rel: str) -> str:+ """Source that fires the PostToolUse Read hook against a real file."""+ payload = {+ "hook_event_name": "PostToolUse",+ "tool_name": "Read",+ "tool_input": {"file_path": str(repo / rel)},+ "tool_response": {"file": {"numLines": 400}},+ "cwd": str(repo),+ "session_id": "perf",+ }+ return (+ "import sys, json, io; "+ f"sys.stdin = io.StringIO({json.dumps(payload)!r}); "+ "from repowise.cli.commands.augment_cmd import _run_augment; "+ "_run_augment(client=None); "+ )+++def _indexed_repo(tmp_path: Path, *, opted_in: bool) -> tuple[Path, str]:+ """A repo the Read hook will take all the way to the skeleton path."""+ repo = tmp_path / "repo"+ (repo / ".repowise").mkdir(parents=True)+ rel = "big.py"+ lines = []+ for i in range(60):+ lines.append(f"def func_{i}(a, b):")+ lines.extend(f" x{j} = a + b + {j}" for j in range(20))+ lines.append("")+ source = "\n".join(lines)+ (repo / rel).write_text(source, encoding="utf-8")++ con = sqlite3.connect(repo / ".repowise" / "wiki.db")+ con.execute(+ "CREATE TABLE wiki_symbols (file_path TEXT, name TEXT, kind TEXT, "+ "signature TEXT, start_line INTEGER, end_line INTEGER)"+ )+ for i in range(60):+ start = i * 22 + 1+ con.execute(+ "INSERT INTO wiki_symbols VALUES (?, ?, ?, ?, ?, ?)",+ (rel, f"func_{i}", "function", f"def func_{i}(a, b)", start, start + 20),+ )+ con.commit()+ con.close()++ if opted_in:+ (repo / ".repowise" / "config.yaml").write_text(+ "hooks:\n read_skeleton: true\n", encoding="utf-8"+ )+ return repo, rel+++def test_a_read_that_serves_a_skeleton_imports_nothing_heavy(tmp_path: Path) -> None:+ """The Read hook's most expensive path, guarded at its most expensive.++ ``repowise.core.distill.skeleton`` used to cost 556ms to import — not for+ anything in the skeleton, but because a package ``__init__`` runs on any+ submodule import and ``budget.py`` reached into ``generation.context`` for+ a four-line heuristic. Both are fixed; this is what keeps them fixed.+ """+ repo, rel = _indexed_repo(tmp_path, opted_in=True)+ env = _fake_home(tmp_path)+ env["REPOWISE_HOOK_UPDATED_OUTPUT"] = "1"+ code = (+ _read_payload_probe(repo, rel)+ + f"heavy = sorted(m for m in sys.modules if m.startswith({_HEAVY_PREFIXES!r})); "+ "print('\\n'.join(heavy), file=sys.stderr)"+ )+ out = subprocess.run(+ [sys.executable, "-c", code], capture_output=True, text=True, check=True, env=env+ )+ # Guard the guard: a gate that silently stopped firing would pass an+ # import-graph assertion trivially, which is how this test would rot.+ assert "updatedToolOutput" in out.stdout, "the probe did not reach the skeleton path"+ assert out.stderr.strip() == "", f"a skeleton-serving Read pulled in:\n{out.stderr}"+++def test_a_read_in_a_repo_that_did_not_opt_in_imports_nothing_heavy(tmp_path: Path) -> None:+ """Off by default has to be *cheap* by default, not merely quiet."""+ repo, rel = _indexed_repo(tmp_path, opted_in=False)+ code = (+ _read_payload_probe(repo, rel)+ + f"heavy = sorted(m for m in sys.modules if m.startswith({_HEAVY_PREFIXES!r})); "+ "print('\\n'.join(heavy), file=sys.stderr)"+ )+ out = subprocess.run(+ [sys.executable, "-c", code],+ capture_output=True,+ text=True,+ check=True,+ env=_fake_home(tmp_path),+ )+ assert "updatedToolOutput" not in out.stdout, "an opted-out repo had its Read replaced"+ assert out.stderr.strip() == "", f"an opted-out Read pulled in:\n{out.stderr}"++def test_a_silent_invocation_imports_nothing_heavy(tmp_path: Path) -> None:"""A payload the hook has nothing to say about must stay on the cheap path."""code = (diff --git a/tests/unit/cli/test_augment_read_skeleton.py b/tests/unit/cli/test_augment_read_skeleton.pynew file mode 100644index 000000000..353fc7466--- /dev/null+++ b/tests/unit/cli/test_augment_read_skeleton.py@@ -0,0 +1,497 @@+"""The PostToolUse Read hook serving a skeleton instead of the whole file.++Two things are under test and they are not the same thing:++1. **The gates.** Every one of them must be able to say no on its own, and+ the default must be no. A hook that replaces what a tool returned is the+ most invasive thing in this codebase; the tests below are ordered as an+ argument that it fires only when it should.+2. **The contract.** A replacement that does not carry its elision ranges is+ a silent truncation, which is the one outcome that would make this worse+ than the nudge it replaces. That is asserted directly, not implied.+"""++from __future__ import annotations++import json+import sqlite3+from pathlib import Path++import pytest++from repowise.cli.commands.augment_cmd import _handle_post_tool_use+from repowise.cli.commands.augment_cmd.read_skeleton import (+ _MAX_OUTPUT_CHARS,+ _recorded_client_version,+ enabled,+ is_unbounded_read,+ supports_updated_output,+)++_SESSION = "sess-1"+++def _source(bodies: int = 30, body_lines: int = 40) -> str:+ """A Python file big enough to clear every size floor."""+ out = ['"""Module docstring."""', "", "import os", "import sys", ""]+ for i in range(bodies):+ out.append(f"def func_{i}(argument_one, argument_two):")+ out.append(f' """Summary line for func_{i}."""')+ out.extend(f" value_{j} = argument_one + argument_two + {j}" for j in range(body_lines))+ out.append(f" return value_{body_lines - 1}")+ out.append("")+ return "\n".join(out)+++def _write_index(repo_path: Path, rel: str, source: str) -> None:+ """Persist wiki_symbols rows the way the indexer would."""+ db = repo_path / ".repowise" / "wiki.db"+ con = sqlite3.connect(db)+ con.execute(+ "CREATE TABLE IF NOT EXISTS wiki_symbols ("+ "file_path TEXT, name TEXT, kind TEXT, signature TEXT, "+ "start_line INTEGER, end_line INTEGER)"+ )+ lines = source.splitlines()+ for idx, line in enumerate(lines, start=1):+ if not line.startswith("def "):+ continue+ end = idx+ while end < len(lines) and (lines[end].startswith(" ") or not lines[end].strip()):+ end += 1+ name = line[4 : line.index("(")]+ con.execute(+ "INSERT INTO wiki_symbols VALUES (?, ?, ?, ?, ?, ?)",+ (rel, name, "function", line.rstrip(":"), idx, end),+ )+ con.commit()+ con.close()+++def fake_home(_isolated_home: Path) -> Path:+ """The client-version probe reads ``~/.claude``, never the developer's.++ ``tests/unit/cli/conftest.py`` already redirects HOME *and* patches+ ``Path.home`` itself for every test in this package — so this aliases that+ rather than setting the env vars again, which the patch would ignore. It+ lives outside ``tmp_path``, which also keeps it clear of+ ``_find_repo_root``, whose walk refuses to treat ``$HOME`` as a repo.+ """+ return _isolated_home+++def repo(tmp_path: Path, fake_home: Path) -> Path:+ """An opted-in indexed repo with one large indexed file."""+ from repowise.cli.commands.augment_cmd._shared import _find_repo_root++ _find_repo_root.cache_clear()+ root = tmp_path / "repo"+ (root / ".repowise").mkdir(parents=True)+ (root / "pkg").mkdir()+ source = _source()+ (root / "pkg" / "big.py").write_text(source, encoding="utf-8")+ _write_index(root, "pkg/big.py", source)+ (root / ".repowise" / "config.yaml").write_text(+ "hooks:\n read_skeleton: true\n", encoding="utf-8"+ )+ return root+++def _read(repo_path: Path, rel: str = "pkg/big.py", **tool_input):+ """Fire the PostToolUse Read hook as Claude Code would."""+ source = (repo_path / rel).read_text(encoding="utf-8")+ return _handle_post_tool_use(+ "Read",+ {"file_path": str(repo_path / rel), **tool_input},+ {"file": {"filePath": str(repo_path / rel), "numLines": len(source.splitlines())}},+ str(repo_path),+ session_id=_SESSION,+ )+++def _edit(repo_path: Path, rel: str = "pkg/big.py"):+ return _handle_post_tool_use(+ "Edit",+ {"file_path": str(repo_path / rel)},+ {},+ str(repo_path),+ session_id=_SESSION,+ )+++# ---------------------------------------------------------------------------+# The contract+# ---------------------------------------------------------------------------+++def test_an_unbounded_read_of_a_large_indexed_file_is_served_as_a_skeleton(repo: Path) -> None:+ result = _read(repo)++ assert result.replacement is not None+ assert "Serving the indexed skeleton of pkg/big.py" in result.replacement+ # Signatures survive; bodies do not.+ assert "def func_0(argument_one, argument_two):" in result.replacement+ assert "value_20 = argument_one" not in result.replacement+++def test_every_elided_span_carries_its_line_range(repo: Path) -> None:+ """The whole justification for replacing a Read rather than nudging.++ Without ranges this is a silent truncation and the agent has no way back+ to what was removed. Same contract distill makes for shell output.+ """+ replacement = _read(repo).replacement+ assert replacement is not None++ markers = [ln.strip() for ln in replacement.splitlines() if ln.strip().startswith("...")]+ assert markers, "a skeleton with no elision markers elided nothing"+ for marker in markers:+ # "... N lines (a-b)" — 1-indexed, inclusive, both bounds present.+ assert "lines (" in marker and "-" in marker.split("lines (")[1]++ assert "Read it again with no range to get the whole file" in replacement+++def test_kept_lines_carry_their_real_line_numbers(repo: Path) -> None:+ """Read returns ``cat -n``; dropping the gutter would leave the agent+ knowing line numbers only for the spans it cannot see."""+ replacement = _read(repo).replacement+ assert replacement is not None+ source = (repo / "pkg" / "big.py").read_text(encoding="utf-8").splitlines()++ numbered = 0+ for line in replacement.splitlines():+ if "\t" not in line or not line[:6].strip().isdigit():+ continue+ gutter, _, text = line.partition("\t")+ assert source[int(gutter) - 1] == text, f"line {gutter} does not match the file"+ numbered += 1+ assert numbered > 10, "almost nothing was numbered"+++def test_numbering_is_dropped_rather_than_guessed_when_it_cannot_reconcile() -> None:+ """A wrong line number is worse than none."""+ from repowise.cli.commands.augment_cmd.read_skeleton import _number++ text = "def a():\n ... 5 lines (2-6)\ndef b():\n"+ assert _number(text, total_lines=7).splitlines()[0].startswith(" 1\t")+ # Same text, but the file is not that long — reconstruction is unsound.+ assert _number(text, total_lines=99) == text+++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+ from repowise.core.distill.store import OMISSIONS_DB_FILENAME, OMISSIONS_DIRNAME++ source = Path(read_skeleton.__file__).read_text(encoding="utf-8")+ assert f'".repowise" / "{OMISSIONS_DIRNAME}" / "{OMISSIONS_DB_FILENAME}"' in source+++def test_the_replacement_is_smaller_than_what_it_replaced(repo: Path) -> None:+ replacement = _read(repo).replacement+ assert replacement is not None+ full = (repo / "pkg" / "big.py").read_text(encoding="utf-8")+ assert len(replacement) < len(full) / 2+++def test_it_never_exceeds_the_output_cap(repo: Path) -> None:+ replacement = _read(repo).replacement+ assert replacement is not None+ assert len(replacement) <= _MAX_OUTPUT_CHARS+++def test_a_skeleton_too_large_for_the_cap_is_skipped_not_truncated(repo: Path) -> None:+ """Cutting a skeleton would drop its trailing ranges — so we do not cut."""+ source = _source(bodies=400, body_lines=8)+ (repo / "pkg" / "big.py").write_text(source, encoding="utf-8")+ (repo / ".repowise" / "wiki.db").unlink()+ _write_index(repo, "pkg/big.py", source)++ assert _read(repo).replacement is None+++# ---------------------------------------------------------------------------+# The gates — each one alone must be able to say no+# ---------------------------------------------------------------------------+++def test_it_is_off_unless_the_repo_opted_in(repo: Path) -> None:+ (repo / ".repowise" / "config.yaml").write_text("hooks:\n read_skeleton: false\n", "utf-8")+ assert _read(repo).replacement is None++ (repo / ".repowise" / "config.yaml").unlink()+ assert _read(repo).replacement is None+ assert enabled(repo) is False+++def test_a_ranged_read_is_left_alone(repo: Path) -> None:+ """A bounded Read is already a targeted question; answer it as asked."""+ assert _read(repo, offset=10, limit=40).replacement is None+ assert _read(repo, limit=40).replacement is None+++def test_a_verification_read_after_an_edit_is_left_alone(repo: Path) -> None:+ """Re-reading what you just edited needs fidelity, not structure.++ Tested on the gate directly. Going through ``_handle_post_tool_use`` would+ prove nothing: the first read has to serve a skeleton to set up the edit,+ and that puts the file in ``skeletonized``, so the once-per-file gate+ would return None whether or not the edit gate existed at all.+ """+ from repowise.cli.commands.augment_cmd.read_state import _skeleton_replacement++ state = {"skeletonized": []}+ args = (repo, "pkg/big.py", {"file_path": str(repo / "pkg/big.py")}, {"file": {"numLines": 400}})++ assert _skeleton_replacement(*args, state, edited_since_read=False) is not None+ state["skeletonized"].clear()+ assert _skeleton_replacement(*args, state, edited_since_read=True) is None+++def test_an_edit_after_a_skeleton_is_warned_about_once(repo: Path) -> None:+ """The replacement satisfies read-before-edit with content never shown."""+ assert _read(repo).replacement is not None++ first = _edit(repo)+ assert "only seen pkg/big.py as a skeleton" in (first.context or "")+ # Once per file — a warning on every edit would be a drumbeat.+ assert "as a skeleton" not in (_edit(repo).context or "")+++def test_the_edit_warning_stops_once_the_file_is_read_in_full(repo: Path) -> None:+ """It is a guard for a true statement, not a permanent label."""+ assert _read(repo).replacement is not None+ assert _read(repo).replacement is None # the escape hatch: file returned whole+ assert "as a skeleton" not in (_edit(repo).context or "")+++def test_a_config_that_is_not_utf8_costs_only_this_enrichment(repo: Path) -> None:+ """A gate that raises must not take the rest of the Read handler with it."""+ (repo / ".repowise" / "config.yaml").write_bytes(b"hooks:\n read_skeleton: true # caf\xe9\n")++ _read(repo)+ _edit(repo)+ result = _read(repo)+ assert result.replacement is None+ # The stale-read notice and the session state still work.+ assert "changed (Edit/Write) after your previous read" in (result.context or "")+++def test_no_durable_state_means_no_replacement(+ repo: Path, monkeypatch: pytest.MonkeyPatch+) -> None:+ """The escape hatch is the state file; without it the promise has no ceiling."""+ from repowise.cli.commands.augment_cmd import read_state++ monkeypatch.setattr(read_state, "_save_session_state", lambda *a, **k: False)+ assert _read(repo).replacement is None+++def _reindex(repo_path: Path, rel: str, source: str) -> None:+ (repo_path / rel).write_text(source, encoding="utf-8")+ (repo_path / ".repowise" / "wiki.db").unlink()+ _write_index(repo_path, rel, source)+++def test_a_skeleton_that_is_not_enough_smaller_is_left_alone(repo: Path) -> None:+ """Long, indexed, and above every size floor — but nothing to elide.++ Bodies of two lines fall under the render rule that keeps short runs+ verbatim, so the "skeleton" is the file. Replacing a Read with itself is+ strictly worse than leaving it alone: same tokens, plus a header.+ """+ _reindex(repo, "pkg/big.py", _source(bodies=300, body_lines=1))+ assert _read(repo).replacement is None+++def test_a_skeleton_that_saves_too_few_tokens_is_left_alone(repo: Path) -> None:+ """A real proportional win on a file too small for it to be worth anything."""+ _reindex(repo, "pkg/big.py", _source(bodies=6, body_lines=15))+ result = _read(repo)+ assert result.replacement is None+ # And it is the token floor doing it, not the line floor above.+ assert len((repo / "pkg" / "big.py").read_text("utf-8").splitlines()) > 100+++def test_a_stale_index_pointing_past_the_end_of_the_file_is_left_alone(repo: Path) -> None:+ """Bounds from before the file shrank: build_skeleton degrades to raw."""+ (repo / "pkg" / "big.py").write_text("\n".join(f"line_{i} = {i}" for i in range(150)), "utf-8")+ con = sqlite3.connect(repo / ".repowise" / "wiki.db")+ con.execute("UPDATE wiki_symbols SET start_line = start_line + 100000")+ con.commit()+ con.close()+ assert _read(repo).replacement is None+++def test_the_env_override_turns_it_on_without_a_config(repo: Path, monkeypatch) -> None:+ (repo / ".repowise" / "config.yaml").unlink()+ assert _read(repo).replacement is None++ monkeypatch.setenv("REPOWISE_HOOK_READ_SKELETON", "1")+ assert _read(repo, rel="pkg/big.py").replacement is not None+++def test_the_second_read_of_a_file_returns_it_whole(repo: Path) -> None:+ """The escape hatch the header promises has to actually exist."""+ assert _read(repo).replacement is not None+ assert _read(repo).replacement is None+++def test_a_small_file_is_left_alone(repo: Path) -> None:+ source = "def tiny():\n return 1\n"+ (repo / "pkg" / "small.py").write_text(source, encoding="utf-8")+ _write_index(repo, "pkg/small.py", source)+ assert _read(repo, rel="pkg/small.py").replacement is None+++def test_an_unindexed_file_is_left_alone(repo: Path) -> None:+ (repo / "pkg" / "other.py").write_text(_source(), encoding="utf-8")+ assert _read(repo, rel="pkg/other.py").replacement is None+++def test_no_index_at_all_is_left_alone(repo: Path) -> None:+ (repo / ".repowise" / "wiki.db").unlink()+ assert _read(repo).replacement is None+++def test_an_unsupported_client_falls_back_to_the_nudge(+ repo: Path, monkeypatch: pytest.MonkeyPatch+) -> None:+ """Older clients ignore updatedToolOutput — emitting it would lose the win."""+ monkeypatch.setenv("REPOWISE_HOOK_UPDATED_OUTPUT", "0")+ result = _read(repo)+ assert result.replacement is None+ assert "A skeleton of pkg/big.py is ~" in (result.context or "")+++# ---------------------------------------------------------------------------+# Client-version probe+# ---------------------------------------------------------------------------+++def test_the_version_probe_fails_open_when_it_cannot_tell(fake_home: Path) -> None:+ """No record on disk means "assume modern": the cost of being wrong is a+ skipped enrichment, never a broken Read."""+ assert _recorded_client_version() is None+ assert supports_updated_output() is True+++ ("record", "expected"),+ [+ ({"version_to": "2.1.220", "version_from": "2.1.219"}, True),+ ({"version_to": None, "version_from": "2.1.220"}, True),+ ({"version_to": None, "version_from": "2.1.100"}, False),+ ({"version_to": "2.0.9", "version_from": "2.0.8"}, False),+ ({"version_to": "not-a-version"}, True), # unparseable → fail open+ ({}, True),+ ],+)+def test_the_version_probe_reads_the_updater_record(+ fake_home: Path, record: dict, expected: bool+) -> None:+ claude = fake_home / ".claude"+ claude.mkdir(exist_ok=True)+ (claude / ".last-update-result.json").write_text(json.dumps(record), encoding="utf-8")+ assert supports_updated_output() is expected+++def test_a_corrupt_updater_record_fails_open(fake_home: Path) -> None:+ claude = fake_home / ".claude"+ claude.mkdir(exist_ok=True)+ (claude / ".last-update-result.json").write_text("{not json", encoding="utf-8")+ assert supports_updated_output() is True+++def test_is_unbounded_read() -> None:+ assert is_unbounded_read({"file_path": "a.py"}) is True+ assert is_unbounded_read({"file_path": "a.py", "offset": 1}) is False+ assert is_unbounded_read({"file_path": "a.py", "limit": 1}) is False+ assert is_unbounded_read("not a dict") is False+++# ---------------------------------------------------------------------------+# Measurement — Gate A's numerator and denominator+# ---------------------------------------------------------------------------+++def _ledger_categories(repo_path: Path) -> list[str]:+ db = repo_path / ".repowise" / "sessions" / "sessions.db"+ if not db.exists():+ return []+ con = sqlite3.connect(db)+ try:+ return [+ row[0]+ for row in con.execute(+ "SELECT category FROM injections WHERE surface = 'read' ORDER BY rowid"+ )+ ]+ finally:+ con.close()+++def test_a_served_skeleton_and_its_recoveries_are_logged(repo: Path) -> None:+ _read(repo) # served+ _read(repo, offset=10, limit=20) # ranged recovery — the contract working+ _read(repo) # full recovery — the replacement was wrong++ categories = _ledger_categories(repo)+ assert "skeleton_served" in categories+ assert "skeleton_ranged" in categories+ assert "skeleton_recovered_full" in categories+++def _savings_rows(repo_path: Path) -> list[tuple]:+ db = repo_path / ".repowise" / "omissions" / "omissions.db"+ if not db.exists():+ return []+ con = sqlite3.connect(db)+ try:+ return con.execute(+ "SELECT filter, source, raw_tokens, distilled_tokens FROM savings"+ ).fetchall()+ finally:+ con.close()+++def test_the_saving_is_billed_to_the_ledger_repowise_saved_reads(repo: Path) -> None:+ from repowise.core.distill.store import OmissionStore++ store = OmissionStore.open_default(repo)+ store.close()++ result = _read(repo)+ # Accounting is deferred to `on_emitted`, which the hook runs only after+ # the response is on its way to the agent. Nothing bills before then.+ assert not _savings_rows(repo)+ assert result.on_emitted is not None+ result.on_emitted()++ rows = _savings_rows(repo)+ assert len(rows) == 1+ filter_name, source, raw, distilled = rows[0]+ assert (filter_name, source) == ("read_skeleton", "hook-read")+ assert 0 < distilled < raw+++def test_no_omission_store_means_no_store_is_created(repo: Path) -> None:+ """A hook is not the place to opt a repo into distill bookkeeping."""+ _read(repo)+ assert not (repo / ".repowise" / "omissions").exists()+++# ---------------------------------------------------------------------------+# The retired re-read notice+# ---------------------------------------------------------------------------+++def test_the_reread_notice_no_longer_fires(repo: Path) -> None:+ """Item 7: it scored 100% "respected" by measuring the base rate."""+ (repo / ".repowise" / "config.yaml").write_text("hooks:\n read_skeleton: false\n", "utf-8")+ for _ in range(3):+ result = _read(repo)+ assert "You already read" not in (result.context or "")diff --git a/tests/unit/cli/test_augment_staleness.py b/tests/unit/cli/test_augment_staleness.pyindex cc2da5cdc..d35edadca 100644--- a/tests/unit/cli/test_augment_staleness.py+++ b/tests/unit/cli/test_augment_staleness.py@@ -298,9 +298,11 @@ class TestPowerShellDispatch:str(repo_path),session_id="s",)- assert msg is not None- assert "Wiki is stale" in msg- assert new_head[:8] in msg+ assert msg.context is not None+ assert "Wiki is stale" in msg.context+ assert new_head[:8] in msg.context+ # Only the Read surface ever replaces a tool result.+ assert msg.replacement is Nonedef test_powershell_failed_command_is_silent(self, repo):from repowise.cli.commands.augment_cmd import _handle_post_tool_use@@ -321,7 +323,7 @@ class TestPowerShellDispatch:str(repo_path),session_id="s",)- assert msg is None+ assert not msgclass TestDocsEnabledWording:diff --git a/tests/unit/distill/test_read_intelligence.py b/tests/unit/distill/test_read_intelligence.pyindex aa98d3eae..8cafc5925 100644--- a/tests/unit/distill/test_read_intelligence.py+++ b/tests/unit/distill/test_read_intelligence.py@@ -3,6 +3,11 @@Exercises the augment handlers directly (the `_handle_post_tool_use`dispatch layer), below `_emit_response`'s cross-process dedup, so theper-session state file is the only rate limiter under test.++Scope: the *additional context* half of the Read surface — what the hook says+alongside a tool result. The half that replaces a tool result outright lives+in `tests/unit/cli/test_augment_read_skeleton.py`; the helpers below read+`HookResult.context` so a replacement can never be mistaken for a notice here."""from __future__ import annotations@@ -52,22 +57,31 @@ def _write_big_file(repo: Path, rel: str, lines: int = 600) -> Path:return path+def _post(tool: str, **kwargs) -> str | None:+ """Dispatch a PostToolUse event and return only what the agent is *told*.++ Every assertion in this module is about ``additionalContext``. Unwrapping+ here keeps a stray ``updatedToolOutput`` from reading as a notice.+ """+ return _handle_post_tool_use(tool, **kwargs).context++def _read_event(repo: Path, rel: str, num_lines: int = 150, session: str = SESSION):- return _handle_post_tool_use(+ return _post("Read",- {"file_path": str(repo / rel)},- {"file": {"numLines": num_lines}},- str(repo),+ tool_input={"file_path": str(repo / rel)},+ tool_output={"file": {"numLines": num_lines}},+ cwd=str(repo),session_id=session,)def _edit_event(repo: Path, rel: str, tool: str = "Edit", session: str = SESSION):- return _handle_post_tool_use(+ return _post(tool,- {"file_path": str(repo / rel)},- {"success": True},- str(repo),+ tool_input={"file_path": str(repo / rel)},+ tool_output={"success": True},+ cwd=str(repo),session_id=session,)@@ -89,12 +103,8 @@ class TestSkeletonNudge: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.+ # Every subsequent read of the same file this session is silent.+ assert _read_event(repo, "src/big.py") is Noneassert _read_event(repo, "src/big.py") is None# A new session resets the claim — skeleton pointer fires again.third_session = _read_event(repo, "src/big.py", session="session-2")@@ -117,11 +127,11 @@ class TestSkeletonNudge:def test_silent_outside_any_repowise_repo(self, tmp_path: Path) -> None:plain = tmp_path / "plain"_write_big_file(plain, "src/big.py")- result = _handle_post_tool_use(+ result = _post("Read",- {"file_path": str(plain / "src/big.py")},- {"file": {"numLines": 150}},- str(plain),+ tool_input={"file_path": str(plain / "src/big.py")},+ tool_output={"file": {"numLines": 150}},+ cwd=str(plain),session_id=SESSION,)assert result is None@@ -199,11 +209,11 @@ class TestStaleReadNotice:def test_edit_outside_repo_records_nothing(self, repo: Path, tmp_path: Path) -> None:outside = tmp_path.parent / "elsewhere.py"- result = _handle_post_tool_use(+ result = _post("Edit",- {"file_path": str(outside)},- {"success": True},- str(repo),+ tool_input={"file_path": str(outside)},+ tool_output={"success": True},+ cwd=str(repo),session_id=SESSION,)assert result is None@@ -211,40 +221,21 @@ 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+class TestRetiredRereadNotice:+ """The re-read notice was deleted; these keep it deleted.- 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+ It scored 100% "respected" only because agents rarely read the same file a+ third time — it was measuring the base rate. The case it argued is now+ handled by serving a skeleton instead of saying so.+ """- def test_partial_reread_is_not_flagged(self, repo: Path) -> None:- # A targeted range re-read is the behavior we recommend; never nag it.+ def test_a_full_reread_of_an_unchanged_file_says_nothing(self, repo: Path) -> None:_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+ for _ in range(3):+ assert _read_event(repo, "a.py", num_lines=150) is None- def test_edit_between_reads_is_stale_not_reread(self, repo: Path) -> None:+ def test_an_edit_between_reads_still_flags_staleness(self, repo: Path) -> None:+ """The notice that survived, and the one that did not, in one place."""_write_big_file(repo, "a.py", lines=200)_read_event(repo, "a.py", num_lines=150)_edit_event(repo, "a.py")@@ -252,11 +243,6 @@ class TestRereadNotice:assert notice is not None and "stale" in noticeassert "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:@@ -293,11 +279,11 @@ class TestSessionState:def test_codex_edit_banner_still_fires_and_records(self, repo: Path) -> None:(repo / ".repowise" / "state.json").write_text("{}", encoding="utf-8")- result = _handle_post_tool_use(+ result = _post("Edit",- {"file_path": str(repo / "a.py")},- {"success": True},- str(repo),+ tool_input={"file_path": str(repo / "a.py")},+ tool_output={"success": True},+ cwd=str(repo),client="codex",session_id=SESSION,)