Skip to content

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

fix(hooks): the served skeleton never reached the agent, and the feature had no way in (#1278)

Raghav Chamadiyab5bf4651ab5e
diff --git a/docs/agent/HOOKS.md b/docs/agent/HOOKS.md
index 610b707ce..6dbbf0516 100644
--- a/docs/agent/HOOKS.md
+++ b/docs/agent/HOOKS.md
@@ -132,15 +132,19 @@ 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
+With `hooks.read_skeleton: true` in `.repowise/config.yaml` — which `repowise
+init` writes from the same yes/no as the rewrite hook, and which `repowise hook
+read-skeleton install | uninstall | status` toggles afterwards — 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.
+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
diff --git a/docs/reference/CONFIG.md b/docs/reference/CONFIG.md
index 566bff9ee..15ae425ce 100644
--- a/docs/reference/CONFIG.md
+++ b/docs/reference/CONFIG.md
@@ -255,11 +255,18 @@ hooks:
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.
+- **Written by the rewrite-hook question in `repowise init`.** Saying yes there
+ turns this on too; `--no-editor-setup` and `--no-distill-hook` turn it off
+ with everything else. There is no separate prompt, because that question
+ already asks the broader thing — letting repowise's hooks intervene in your
+ agent's tool calls — and rewriting a shell command is the larger
+ intervention of the two. To change your mind for one repo without re-running
+ init, use `repowise hook read-skeleton install | uninstall | status`.
+- **What it costs while off.** Every Read that *would* have been served as a
+ skeleton is measured anyway, and `repowise saved` reports the total under
+ "Not saved". That figure 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 wanted the whole file.
- `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"])`).
diff --git a/packages/cli/src/repowise/cli/commands/augment_cmd/_shared.py b/packages/cli/src/repowise/cli/commands/augment_cmd/_shared.py
index 7ee2ed541..d823b67fa 100644
--- a/packages/cli/src/repowise/cli/commands/augment_cmd/_shared.py
+++ b/packages/cli/src/repowise/cli/commands/augment_cmd/_shared.py
@@ -24,6 +24,12 @@ class HookResult(NamedTuple):
:func:`as_result` lifts their bare ``str | None`` into this shape and the
two-field response is assembled in exactly one place.
+ ``replacement`` is ``str | dict`` because Claude Code validates it against
+ the *replaced tool's own* output schema, not a common one: ``Bash`` takes a
+ string, ``Read`` takes ``{"type", "file": {...}}``. Handing Read a string
+ is rejected with ``does not match Read's output shape`` and the original
+ output is used — see :func:`read_skeleton.as_read_output`.
+
``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:
@@ -32,7 +38,7 @@ class HookResult(NamedTuple):
"""
context: str | None = None
- replacement: str | None = None
+ replacement: str | dict | None = None
on_emitted: Callable[[], None] | None = None
def __bool__(self) -> bool:
diff --git a/packages/cli/src/repowise/cli/commands/augment_cmd/command.py b/packages/cli/src/repowise/cli/commands/augment_cmd/command.py
index a209bd5b8..657e3a974 100644
--- a/packages/cli/src/repowise/cli/commands/augment_cmd/command.py
+++ b/packages/cli/src/repowise/cli/commands/augment_cmd/command.py
@@ -201,6 +201,12 @@ def _emit_response(event: str, result: HookResult | str) -> None:
can legitimately want both — a stale-read flag alongside a served
skeleton.
+ ``updatedToolOutput`` is typed by the tool being replaced, so it is
+ whatever the handler built (a string for Bash-shaped output, an object for
+ Read's) and is written through unchanged. Claude Code validates it and
+ falls back to the original output on a mismatch, so getting the shape
+ wrong fails *quietly* from the agent's side — the row still says served.
+
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
@@ -208,13 +214,18 @@ def _emit_response(event: str, result: HookResult | str) -> None:
enrichment block twice on a single tool event.
"""
result = as_result(result)
- if not _claim_emission(event, f"{result.context or ''}\x00{result.replacement or ''}"):
+ replacement = result.replacement
+ if replacement is None or isinstance(replacement, str):
+ dedup_mark = replacement or ""
+ else:
+ dedup_mark = json.dumps(replacement, sort_keys=True)
+ if not _claim_emission(event, f"{result.context or ''}\x00{dedup_mark}"):
return
- payload: dict[str, str] = {"hookEventName": event}
+ payload: dict[str, object] = {"hookEventName": event}
if result.context:
payload["additionalContext"] = result.context
- if result.replacement:
- payload["updatedToolOutput"] = result.replacement
+ if replacement:
+ payload["updatedToolOutput"] = replacement
sys.stdout.write(json.dumps({"hookSpecificOutput": payload}))
sys.stdout.flush()
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.py
index 60dab8101..eedd7e7c4 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
@@ -69,13 +69,16 @@ class Replacement:
call site would read as noise.
"""
- __slots__ = ("full_tokens", "rel", "skeleton_tokens", "text")
+ __slots__ = ("full_tokens", "payload", "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
+ #: Read-shaped wire payload wrapping :attr:`text`, filled in by the
+ #: caller once it has the Read's own ``tool_response`` to build from.
+ self.payload: dict | None = None
@property
def saved_tokens(self) -> int:
@@ -227,6 +230,33 @@ def skeleton_replacement(
)
+def as_read_output(tool_output: object, text: str) -> dict | None:
+ """Wrap *text* in the object shape Claude Code requires for a Read.
+
+ ``updatedToolOutput`` is validated against the schema of the tool being
+ replaced, not against a common one. Read's is
+ ``{"type": "text", "file": {"filePath", "content", "numLines",
+ "startLine", "totalLines"}}``, and handing it a bare string is rejected
+ with ``does not match Read's output shape`` — 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 the line counts move.
+
+ 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
+ file_block = tool_output.get("file")
+ if not isinstance(file_block, dict) or "content" not in file_block:
+ return None
+ lines = text.count("\n") + (0 if text.endswith("\n") else 1)
+ updated_file = {**file_block, "content": text, "numLines": lines, "startLine": 1}
+ return {**tool_output, "file": updated_file}
+
+
#: 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*$")
@@ -239,9 +269,12 @@ def _render(rel: str, result: SkeletonResult, total_lines: int) -> str:
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"
+ "There are two gutters. Ignore the outer one — Claude Code numbers the lines it "
+ "is handed, and it is counting skeleton lines. The inner gutter is this file's "
+ "real line numbers, and it is the one to Read against.\n"
+ "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}"
@@ -257,6 +290,14 @@ def _number(text: str, total_lines: int) -> str:
elision marker states the range it swallowed, so walking the rendered text
and jumping the counter at every marker reproduces the original numbering.
+ This *is* a second gutter, and deliberately. Claude Code renders the
+ ``content`` it is handed through its own ``cat -n``, numbering sequentially
+ from ``startLine`` — which for a skeleton counts skeleton lines, not file
+ lines, and cannot be switched off. So the choice is two gutters where the
+ inner one is right, or one gutter that is wrong. Item 5 already settled
+ that a wrong line number is worse than none; the header names both columns
+ so the outer one cannot be mistaken for the file's.
+
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.
@@ -320,6 +361,52 @@ 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
+
+
def record_saving(repo_path: Path, replacement: Replacement) -> None:
"""Bill this replacement to the savings ledger so ``repowise saved`` sees it.
diff --git a/packages/cli/src/repowise/cli/commands/augment_cmd/read_state.py b/packages/cli/src/repowise/cli/commands/augment_cmd/read_state.py
index 8cdd8ccf0..d996a2748 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
@@ -62,6 +62,10 @@ def _load_session_state(repo_path: Path, session_id: str) -> dict:
# 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": [],
+ # Files this session measured a *forgone* saving for — the
+ # counterfactual leg, which runs only while the feature is off.
+ # Doubles as its once-per-file gate.
+ "forgone": [],
# 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.
@@ -224,7 +228,7 @@ def _handle_read_post(
state["seq"] += 1
state["reads"][rel] = state["seq"]
- replacement = _skeleton_replacement(
+ replacement, forgone = _skeleton_replacement(
repo_path, rel, tool_input, tool_output, state, edited_since_read=edited_since_read
)
if replacement is not None:
@@ -236,28 +240,48 @@ def _handle_read_post(
fired.append(("skeleton_nudge", nudge))
persisted = _save_session_state(repo_path, state)
- if replacement is not None and not persisted:
+ if 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"]
+ if replacement is not None:
+ replacement = None
+ fired = [f for f in fired if f[0] != "skeleton_served"]
+ # The counterfactual's gates are the same list, so they fail the same
+ # way: without a durable `forgone` the once-per-file gate and the
+ # per-session cap both reset on the next event, and the same file is
+ # counted again and again. That inflates the very number the
+ # measurement exists to state honestly, and removes the ceiling on
+ # what it costs. No durable state, no measurement either.
+ forgone = None
for category, text in fired:
_log_read_firing(repo_path, session_id, category, rel, text)
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
- ),
+ replacement=replacement.payload if replacement is not None else None,
+ on_emitted=_bookkeeping(repo_path, replacement, forgone),
)
+def _bookkeeping(repo_path: Path, replacement, forgone):
+ """The ledger write this Read owes, to run after the response is emitted.
+
+ At most one of the two is ever set. Both are deferred for the same reason:
+ accounting must not sit between the agent and its tool result. The
+ counterfactual needs this more than the saving does, not less — it takes a
+ write lock on a database ``repowise distill`` also writes, and it does so
+ on a Read that is getting nothing back for the wait.
+ """
+ if replacement is not None:
+ return lambda: _record_skeleton_saving(repo_path, replacement)
+ if forgone is not None:
+ return lambda: _record_forgone_saving(repo_path, forgone)
+ return None
+
+
def _skeleton_replacement(
repo_path: Path,
rel: str,
@@ -267,14 +291,19 @@ def _skeleton_replacement(
*,
edited_since_read: bool,
):
- """The skeleton to serve in place of this Read, or None. Never raises.
+ """``(replacement, forgone)`` for this Read — at most one set. 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`.
+
+ The two legs share every gate above the flag on purpose: a counterfactual
+ computed under looser conditions than the thing it stands in for would be
+ measuring a different feature.
"""
try:
from .read_skeleton import (
+ as_read_output,
enabled,
is_unbounded_read,
skeleton_replacement,
@@ -282,28 +311,109 @@ def _skeleton_replacement(
)
if not is_unbounded_read(tool_input):
- return None
+ return None, None
if _read_output_line_count(tool_output) < _READ_NUDGE_MIN_LINES:
- return None
+ return None, 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
+ # `forgone` joins the once-per-file gate so that flipping the flag on
+ # mid-session cannot bill the same file to both ledgers — it would
+ # appear in the headline saving *and* be advertised as not saved, with
+ # identical token counts. Costs at most a deferred replacement: the
+ # file is served as a skeleton from the next session on.
+ if edited_since_read or rel in state["skeletonized"] or rel in state["forgone"]:
+ return None, None
+ if not enabled(repo_path):
+ return None, _measure_forgone(repo_path, rel, state)
+ if not supports_updated_output():
+ return None, None
replacement = skeleton_replacement(
repo_path,
rel,
min_ratio_gain=_READ_NUDGE_MAX_RATIO,
min_saved_tokens=_READ_NUDGE_MIN_SAVINGS,
)
+ if replacement is not None:
+ # Build the wire payload here, not at emit time: if this Read's
+ # tool_response is not the shape Read documents, the replacement
+ # would be rejected downstream and the agent would get the whole
+ # file *while* the ledger recorded a saving. No payload, no row.
+ payload = as_read_output(tool_output, replacement.text)
+ if payload is None:
+ return None, None
+ replacement.payload = payload
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
+ return None, None
if replacement is not None:
state["skeletonized"].append(rel)
- return replacement
+ return replacement, None
+
+
+#: Files per session the counterfactual will measure before it stops. The real
+#: path spends ~30ms and hands back thousands of tokens; this one spends the
+#: same and hands back nothing but a number, on the *common* case — every
+#: qualifying Read in a repo that has the feature off. A few dozen files is
+#: plenty to characterise a repo, and the cap is what keeps a measurement from
+#: costing more than the thing it is measuring.
+_MAX_FORGONE_PER_SESSION = 40
+
+
+def _measure_forgone(repo_path: Path, rel: str, state: dict) -> str | None:
+ """Claim a measurement slot for *rel*, or None. Computes nothing.
+
+ Runs only when the feature is off, which is the point: a repo that
+ declined can still see what declining costs, and item 5's own saving can
+ be characterised on real work before it is switched on anywhere.
+
+ **Nothing here is on the critical path, and that is deliberate.** The real
+ replacement has to build its skeleton before the response, because the
+ skeleton *is* the response. This one hands the agent nothing at all, so
+ making it wait — for an index query, a file read, a skeleton build and a
+ write lock on a database ``repowise distill`` also writes — would be
+ charging every qualifying Read in an opted-out repo for a number it will
+ never see. All of it is deferred to :func:`_forgone_saving`; the only
+ thing that must happen now is claiming the slot, because the claim has to
+ be in the state file the caller is about to write.
+
+ Claiming before knowing whether the file qualifies means a file that turns
+ out not to qualify still spends a slot. That is the conservative
+ direction: the cap exists to bound what measuring *costs*, and an attempt
+ costs whether or not it produces a row.
+
+ **This settles A1 and nothing else.** A1 asks whether the replacement is a
+ net win, and the numbers are exact — the same skeleton, the same token
+ counts the real path would have billed. A2 asks how often the agent has to
+ come back for the whole file, and nothing was replaced here, so nothing
+ was recovered and there is no recovery rate to read. A large forgone total
+ is not a pass; see the caveat ``repowise saved`` prints.
+ """
+ if len(state["forgone"]) >= _MAX_FORGONE_PER_SESSION:
+ return None
+ state["forgone"].append(rel)
+ return rel
+
+
+def _record_forgone_saving(repo_path: Path, rel: str) -> None:
+ """Build the skeleton nobody will see and record what it would have saved.
+
+ The whole measurement, run after the response is on its way. Never raises:
+ a counterfactual that broke a Read would be the worst possible trade.
+ """
+ try:
+ from .read_skeleton import record_forgone, skeleton_replacement
+
+ would_have = skeleton_replacement(
+ repo_path,
+ rel,
+ min_ratio_gain=_READ_NUDGE_MAX_RATIO,
+ min_saved_tokens=_READ_NUDGE_MIN_SAVINGS,
+ )
+ if would_have is not None:
+ record_forgone(repo_path, would_have)
+ except Exception:
+ return
def _log_skeleton_recovery(
diff --git a/packages/cli/src/repowise/cli/commands/hook_cmd.py b/packages/cli/src/repowise/cli/commands/hook_cmd.py
index 970255971..fb189901e 100644
--- a/packages/cli/src/repowise/cli/commands/hook_cmd.py
+++ b/packages/cli/src/repowise/cli/commands/hook_cmd.py
@@ -375,6 +375,81 @@ def rewrite_status(path: str | None, workspace: bool, no_workspace: bool) -> Non
console.print(f" {icon} AGENTS.md distill section: {state} ({repo_path})")
+@hook_group.group("read-skeleton")
+def read_skeleton_group() -> None:
+ """Manage skeleton-served Reads (Claude Code).
+
+ An unbounded Read of a large indexed file comes back as its skeleton —
+ signatures kept, bodies elided, every elided span carrying the line range
+ that reads it back. Reading the same file a second time returns it whole.
+
+ There is no hook to install: the PostToolUse hook `repowise init` already
+ set up carries this. What these commands move is the per-repo verdict
+ `hooks.read_skeleton` in .repowise/config.yaml, which `repowise init`
+ writes from the same answer as the rewrite hook. Use these to change your
+ mind about one repo without re-running init.
+ """
+
+
+@read_skeleton_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 read_skeleton_install(path: str | None, workspace: bool, no_workspace: bool) -> None:
+ """Serve large indexed Reads as skeletons in this repo."""
+ _set_read_skeleton(path, workspace, no_workspace, enabled=True)
+
+
+@read_skeleton_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 read_skeleton_uninstall(path: str | None, workspace: bool, no_workspace: bool) -> None:
+ """Stop replacing Reads in this repo; they come back whole."""
+ _set_read_skeleton(path, workspace, no_workspace, enabled=False)
+
+
+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
+
+ target = _hook_target(path, workspace, no_workspace)
+ word = "[green]on[/green]" if enabled else "[yellow]off[/yellow]"
+ touched = 0
+ 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})")
+ touched += 1
+ if not touched:
+ console.print(" [yellow]No indexed repo here — run `repowise init` first.[/yellow]")
+
+
+@read_skeleton_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 read_skeleton_status(path: str | None, workspace: bool, no_workspace: bool) -> None:
+ """Report whether Reads are being served as skeletons, and what it saved."""
+ from repowise.cli.commands.augment_cmd.read_skeleton import enabled as read_skeleton_enabled
+
+ target = _hook_target(path, workspace, no_workspace)
+ for repo_path in _target_repo_paths(target):
+ on = read_skeleton_enabled(repo_path)
+ icon = "[green]✓[/green]" if on else "[dim]✗[/dim]"
+ console.print(f" {icon} skeleton-served Reads: {'on' if on else 'off'} ({repo_path})")
+ if not on:
+ # The counterfactual is the whole point of measuring while off:
+ # a repo that declined can still see what declining costs it.
+ 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.py
index 8169ef074..0ab1f85a2 100644
--- a/packages/cli/src/repowise/cli/commands/init_cmd/_interactive.py
+++ b/packages/cli/src/repowise/cli/commands/init_cmd/_interactive.py
@@ -81,6 +81,14 @@ 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.
+ 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]"
+ )
try:
flag = click.confirm(" Install the Claude Code rewrite hook?", default=True)
except (click.Abort, EOFError):
@@ -111,16 +119,34 @@ def _record_distill_verdict(
*,
enabled: bool,
) -> None:
- """Persist ``distill.commands.enabled`` for every repo in this run."""
+ """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.
+
+ Read-skeleton shipped with no code path that wrote its key at all, which
+ left it reachable only by hand-editing YAML. That is not a discovery
+ problem: its gate needs 50 firings across 10 sessions to decide whether it
+ stays, and a feature nobody can turn on returns zero of them and settles
+ nothing.
+ """
- from repowise.cli.helpers import save_distill_commands_enabled
+ from repowise.cli.helpers import (
+ save_distill_commands_enabled,
+ save_hook_read_skeleton_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)
except Exception as exc: # init must not crash on a config write
console_obj.print(
- f" [yellow]Could not record distill verdict for {repo_path.name}: {exc}[/yellow]"
+ 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.py
index 8d2c85f16..490ab8ad9 100644
--- a/packages/cli/src/repowise/cli/commands/init_cmd/command.py
+++ b/packages/cli/src/repowise/cli/commands/init_cmd/command.py
@@ -523,8 +523,12 @@ def _run_generation_phase(
help=(
"Install the Claude Code command-rewrite hook that routes noisy "
"commands (tests, builds, git, searches) through `repowise distill` "
- "for compact output. Default: ask when interactive; skip otherwise. "
- "In workspace mode the verdict applies to every selected repo."
+ "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."
),
)
@click.option(
diff --git a/packages/cli/src/repowise/cli/commands/saved_cmd.py b/packages/cli/src/repowise/cli/commands/saved_cmd.py
index 72a87f38c..9de5c8731 100644
--- a/packages/cli/src/repowise/cli/commands/saved_cmd.py
+++ b/packages/cli/src/repowise/cli/commands/saved_cmd.py
@@ -112,6 +112,12 @@ def saved_command(
if since_ts is not None:
msg += f" since {since}"
console.print(f"[yellow]{msg}.[/yellow]")
+ # Before returning, not after. Declining the init prompt turns off
+ # distill rewrites *and* skeleton-served Reads in the same write, so
+ # the cohort the counterfactual exists to inform is exactly the cohort
+ # with zero distillation events — and returning here first would make
+ # its rows unreadable by the only command that reports them.
+ _print_forgone_read_skeleton_line(start, db_path, since_ts)
return
saved = summary["saved_tokens"]
@@ -158,9 +164,73 @@ def saved_command(
console.print(f" [dim]Ledger: {db_path}[/dim]")
_print_missed_summary_line(start, missed_days)
_print_reread_summary_line(start, missed_days)
+ _print_forgone_read_skeleton_line(start, db_path, since_ts)
console.print()
+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.
+
+ Read out of its own table rather than the savings ledger, and printed
+ below the total rather than inside it, because none of it happened.
+
+ The caveat is not decoration. This number is exactly half the question:
+ it says what the replacement would have taken off the bill, and it cannot
+ say what the agent would then have had to read back, because nothing was
+ replaced and so nothing was recovered. A repo can show a large figure here
+ and still be one where serving skeletons is a bad trade.
+ """
+ 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 _enabled
+ from repowise.cli.helpers import find_repowise_repo_root
+
+ repo_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:
+ 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]"
+ )
+ 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:
"""Best-effort missed-savings scan rooted at the enclosing repowise repo."""
try:
diff --git a/packages/cli/src/repowise/cli/helpers.py b/packages/cli/src/repowise/cli/helpers.py
index a4e22d37d..4704c70f7 100644
--- a/packages/cli/src/repowise/cli/helpers.py
+++ b/packages/cli/src/repowise/cli/helpers.py
@@ -602,6 +602,21 @@ 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``.
+
+ Same shape as :func:`save_distill_commands_enabled`, and written by the
+ same consent: the rewrite-hook prompt means "let repowise's hooks
+ intervene 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.
+ """
+ cfg = load_config(repo_path)
+ hooks = dict(cfg.get("hooks") or {})
+ hooks["read_skeleton"] = enabled
+ save_config_partial(repo_path, hooks=hooks)
+
+
def config_fingerprint(repo_path: Path) -> str:
"""SHA-256 hex of ``.repowise/config.yaml`` + ``health-rules.json`` content.
diff --git a/tests/unit/cli/test_augment_hook_perf.py b/tests/unit/cli/test_augment_hook_perf.py
index 139812de3..3e454dd4a 100644
--- a/tests/unit/cli/test_augment_hook_perf.py
+++ b/tests/unit/cli/test_augment_hook_perf.py
@@ -86,12 +86,27 @@ def test_the_self_heal_imports_nothing_heavy(tmp_path: Path) -> None:
def _read_payload_probe(repo: Path, rel: str) -> str:
- """Source that fires the PostToolUse Read hook against a real file."""
+ """Source that fires the PostToolUse Read hook against a real file.
+
+ ``tool_response`` is Read's real shape, ``content`` included: the
+ replacement is built from this object, so a probe that stubs it loses the
+ very path it claims to be timing.
+ """
+ source = (repo / rel).read_text(encoding="utf-8")
payload = {
"hook_event_name": "PostToolUse",
"tool_name": "Read",
"tool_input": {"file_path": str(repo / rel)},
- "tool_response": {"file": {"numLines": 400}},
+ "tool_response": {
+ "type": "text",
+ "file": {
+ "filePath": str(repo / rel),
+ "content": source,
+ "numLines": len(source.splitlines()),
+ "startLine": 1,
+ "totalLines": len(source.splitlines()),
+ },
+ },
"cwd": str(repo),
"session_id": "perf",
}
@@ -163,7 +178,14 @@ def test_a_read_that_serves_a_skeleton_imports_nothing_heavy(tmp_path: Path) ->
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."""
+ """Off by default has to be *cheap* by default, not merely quiet.
+
+ This is now the counterfactual's perf guard as well, and that is the more
+ demanding case: the measurement runs on Reads that are *not* being
+ replaced, so a repo with the feature off pays it on every qualifying read
+ and gets no tokens back. It has to stay on the same cheap import graph as
+ the path it stands in for.
+ """
repo, rel = _indexed_repo(tmp_path, opted_in=False)
code = (
_read_payload_probe(repo, rel)
@@ -180,6 +202,11 @@ def test_a_read_in_a_repo_that_did_not_opt_in_imports_nothing_heavy(tmp_path: Pa
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}"
+ # Guard the guard, same as the opted-in case: if the counterfactual stopped
+ # running, the import assertion above would pass by doing nothing at all.
+ state = json.loads((repo / ".repowise" / ".augment-session.json").read_text("utf-8"))
+ assert state["forgone"] == [rel], "the probe did not reach the counterfactual"
+
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."""
diff --git a/tests/unit/cli/test_augment_read_skeleton.py b/tests/unit/cli/test_augment_read_skeleton.py
index 353fc7466..758c5339c 100644
--- a/tests/unit/cli/test_augment_read_skeleton.py
+++ b/tests/unit/cli/test_augment_read_skeleton.py
@@ -99,18 +99,61 @@ def repo(tmp_path: Path, fake_home: Path) -> Path:
return root
+def _read_output(repo_path: Path, rel: str) -> dict:
+ """Read's real ``tool_response``, field for field.
+
+ Faithful on purpose. The first version of this helper sent
+ ``{"file": {"filePath", "numLines"}}`` — enough for the gates, missing
+ ``content``, and missing the ``type`` envelope — and every test passed
+ against a payload Claude Code never sends. The replacement is built *from*
+ this object, so a fixture that is not the real shape cannot catch a
+ response that is not the real shape, which is exactly what happened.
+ """
+ source = (repo_path / rel).read_text(encoding="utf-8")
+ return {
+ "type": "text",
+ "file": {
+ "filePath": str(repo_path / rel),
+ "content": source,
+ "numLines": len(source.splitlines()),
+ "startLine": 1,
+ "totalLines": len(source.splitlines()),
+ },
+ }
+
+
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())}},
+ _read_output(repo_path, rel),
str(repo_path),
session_id=_SESSION,
)
+def _read_and_settle(repo_path: Path, rel: str = "pkg/big.py", **tool_input):
+ """Fire the Read hook and run the bookkeeping the dispatcher defers.
+
+ Both ledger writes hang off ``on_emitted``, which the real dispatcher runs
+ only once the response is on its way to the agent, so a test that stops at
+ the return value sees no rows at all.
+ """
+ result = _read(repo_path, rel, **tool_input)
+ if result.on_emitted is not None:
+ result.on_emitted()
+ return result
+
+
+def _served(result) -> str | None:
+ """The skeleton text out of a Read replacement, or None if nothing served."""
+ replacement = result.replacement
+ if replacement is None:
+ return None
+ return replacement["file"]["content"]
+
+
def _edit(repo_path: Path, rel: str = "pkg/big.py"):
return _handle_post_tool_use(
"Edit",
@@ -127,13 +170,60 @@ def _edit(repo_path: Path, rel: str = "pkg/big.py"):
def test_an_unbounded_read_of_a_large_indexed_file_is_served_as_a_skeleton(repo: Path) -> None:
- result = _read(repo)
+ served = _served(_read(repo))
- assert result.replacement is not None
- assert "Serving the indexed skeleton of pkg/big.py" in result.replacement
+ assert served is not None
+ assert "Serving the indexed skeleton of pkg/big.py" in served
# 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
+ assert "def func_0(argument_one, argument_two):" in served
+ assert "value_20 = argument_one" not in served
+
+
+def test_the_replacement_is_shaped_like_a_read_result_not_a_string(repo: Path) -> None:
+ """Claude Code type-checks ``updatedToolOutput`` against the replaced tool.
+
+ Read's output is an object. Item 5 shipped emitting a bare string, which
+ Claude Code rejected with "does not match Read's output shape" — falling
+ back to the original file *silently*, exit 0 and no stderr, while the hook
+ went on recording a served row and a saving. Every firing was a no-op for
+ a release. This pins the shape so it cannot regress into a string again.
+ """
+ replacement = _read(repo).replacement
+
+ assert isinstance(replacement, dict), "a string here is rejected by the client"
+ assert replacement["type"] == "text"
+ file_block = replacement["file"]
+ # Exactly Read's own keys — carried through from the payload, not invented.
+ assert set(file_block) == {"filePath", "content", "numLines", "startLine", "totalLines"}
+ assert file_block["numLines"] == file_block["content"].count("\n")
+ assert file_block["totalLines"] == 1324, "the file's real length, not the skeleton's"
+
+
+def test_a_read_response_of_an_unexpected_shape_serves_nothing(repo: Path) -> None:
+ """No payload, no replacement — and critically, no saving row either.
+
+ The failure mode being ruled out is billing a saving for a replacement the
+ client then refuses, which is what made the string bug invisible.
+
+ The payload matters here. ``{"type": "text"}`` alone would be rejected by
+ the size gate (no ``numLines`` means a line count of 0) and never reach
+ the shape check at all — an assertion about the right thing on the wrong
+ code path, which is the same vacuum that let the original bug ship. This
+ one clears every gate above the shape check and fails only there. It is
+ also, deliberately, the exact fixture the old tests used.
+ """
+ from repowise.cli.commands.augment_cmd.command import _handle_post_tool_use
+
+ result = _handle_post_tool_use(
+ "Read",
+ {"file_path": str(repo / "pkg/big.py")},
+ {"file": {"numLines": 400}}, # passes the size gate, has no `content`
+ str(repo),
+ session_id="shape-probe",
+ )
+
+ assert result.replacement is None
+ assert result.on_emitted is None, "a rejected replacement must not bill a saving"
def test_every_elided_span_carries_its_line_range(repo: Path) -> None:
@@ -142,7 +232,7 @@ def test_every_elided_span_carries_its_line_range(repo: Path) -> None:
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
+ replacement = _served(_read(repo))
assert replacement is not None
markers = [ln.strip() for ln in replacement.splitlines() if ln.strip().startswith("...")]
@@ -157,7 +247,7 @@ def test_every_elided_span_carries_its_line_range(repo: Path) -> None:
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
+ replacement = _served(_read(repo))
assert replacement is not None
source = (repo / "pkg" / "big.py").read_text(encoding="utf-8").splitlines()
@@ -243,12 +333,19 @@ def test_a_verification_read_after_an_edit_is_left_alone(repo: Path) -> None:
"""
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}})
+ state = {"skeletonized": [], "forgone": []}
+ args = (
+ repo,
+ "pkg/big.py",
+ {"file_path": str(repo / "pkg/big.py")},
+ _read_output(repo, "pkg/big.py"),
+ )
- assert _skeleton_replacement(*args, state, edited_since_read=False) is not None
+ served, _ = _skeleton_replacement(*args, state, edited_since_read=False)
+ assert served is not None
state["skeletonized"].clear()
- assert _skeleton_replacement(*args, state, edited_since_read=True) is None
+ served, _ = _skeleton_replacement(*args, state, edited_since_read=True)
+ assert served is None
def test_an_edit_after_a_skeleton_is_warned_about_once(repo: Path) -> None:
@@ -330,8 +427,15 @@ def test_the_env_override_turns_it_on_without_a_config(repo: Path, monkeypatch)
(repo / ".repowise" / "config.yaml").unlink()
assert _read(repo).replacement is None
+ # A different file on purpose. `pkg/big.py` was just measured by the
+ # counterfactual, and a measured file is not replaced again this session —
+ # see test_a_file_is_never_billed_to_both_ledgers.
+ source = (repo / "pkg" / "big.py").read_text(encoding="utf-8")
+ (repo / "pkg" / "second.py").write_text(source, encoding="utf-8")
+ _write_index(repo, "pkg/second.py", source)
+
monkeypatch.setenv("REPOWISE_HOOK_READ_SKELETON", "1")
- assert _read(repo, rel="pkg/big.py").replacement is not None
+ assert _read(repo, rel="pkg/second.py").replacement is not None
def test_the_second_read_of_a_file_returns_it_whole(repo: Path) -> None:
@@ -478,6 +582,128 @@ def test_the_saving_is_billed_to_the_ledger_repowise_saved_reads(repo: Path) ->
assert 0 < distilled < raw
+# ---------------------------------------------------------------------------
+# The counterfactual: what the feature would have saved, while it is off
+# ---------------------------------------------------------------------------
+
+
+def _forgone_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 path, raw_tokens, distilled_tokens FROM forgone_savings"
+ ).fetchall()
+ except sqlite3.OperationalError:
+ return []
+ finally:
+ con.close()
+
+
+def repo_off(repo: Path) -> Path:
+ """The same repo with the feature explicitly declined."""
+ (repo / ".repowise" / "config.yaml").write_text(
+ "hooks:\n read_skeleton: false\n", encoding="utf-8"
+ )
+ from repowise.core.distill.store import OmissionStore
+
+ OmissionStore.open_default(repo).close()
+ return repo
+
+
+def test_a_repo_with_it_off_still_measures_what_it_would_have_saved(repo_off: Path) -> None:
+ """Otherwise the gate can never run: off means no data, and no data means
+ the flag stays off by inaction rather than by evidence."""
+ result = _read_and_settle(repo_off)
+
+ assert result.replacement is None, "measuring must not replace anything"
+ rows = _forgone_rows(repo_off)
+ assert len(rows) == 1
+ path, raw, distilled = rows[0]
+ assert path == "pkg/big.py"
+ assert 0 < distilled < raw
+
+
+def test_a_forgone_saving_is_kept_out_of_the_savings_ledger(repo_off: Path) -> None:
+ """`repowise saved` sums that table into a headline figure. Nothing here
+ happened, so adding it would inflate a real number with a hypothetical."""
+ _read_and_settle(repo_off)
+
+ assert _forgone_rows(repo_off)
+ assert not _savings_rows(repo_off)
+
+
+def test_the_counterfactual_measures_each_file_once(repo_off: Path) -> None:
+ for _ in range(4):
+ _read_and_settle(repo_off)
+
+ assert len(_forgone_rows(repo_off)) == 1
+
+
+def test_the_counterfactual_stops_at_the_per_session_cap(repo_off: Path) -> None:
+ """It runs on Reads that are *not* being replaced — the common case — so
+ an uncapped measurement would cost more than the feature it measures."""
+ from repowise.cli.commands.augment_cmd import read_state
+
+ source = (repo_off / "pkg" / "big.py").read_text(encoding="utf-8")
+ for i in range(read_state._MAX_FORGONE_PER_SESSION + 5):
+ rel = f"pkg/copy_{i}.py"
+ (repo_off / rel).write_text(source, encoding="utf-8")
+ _write_index(repo_off, rel, source)
+ _read_and_settle(repo_off, rel)
+
+ assert len(_forgone_rows(repo_off)) == read_state._MAX_FORGONE_PER_SESSION
+
+
+def test_a_file_is_never_billed_to_both_ledgers(repo_off: Path) -> None:
+ """Flipping the flag on mid-session must not count the same file twice.
+
+ Without the `forgone` entry in the once-per-file gate the same read is
+ recorded as saved *and* advertised as not-saved, with identical token
+ counts, in one session.
+ """
+ _read_and_settle(repo_off) # measured while off
+ (repo_off / ".repowise" / "config.yaml").write_text(
+ "hooks:\n read_skeleton: true\n", encoding="utf-8"
+ )
+ _read_and_settle(repo_off)
+
+ assert len(_forgone_rows(repo_off)) == 1
+ assert not _savings_rows(repo_off), "the same file was billed to both ledgers"
+
+
+def test_nothing_is_measured_when_the_session_state_cannot_persist(
+ repo_off: Path, monkeypatch
+) -> None:
+ """The cap and the once-per-file gate both live in that state file.
+
+ If it does not persist they reset on every event, so the same file is
+ counted over and over — inflating the one number this feature exists to
+ state honestly, and removing the ceiling on what measuring costs.
+ """
+ from repowise.cli.commands.augment_cmd import read_state
+
+ monkeypatch.setattr(read_state, "_save_session_state", lambda *a, **k: False)
+
+ for _ in range(6):
+ _read_and_settle(repo_off)
+
+ assert not _forgone_rows(repo_off)
+
+
+def test_no_omission_store_means_no_forgone_row_either(repo: Path) -> None:
+ """Same never-create-the-store rule as the real saving."""
+ (repo / ".repowise" / "config.yaml").write_text(
+ "hooks:\n read_skeleton: false\n", encoding="utf-8"
+ )
+ _read_and_settle(repo)
+
+ assert not (repo / ".repowise" / "omissions").exists()
+
+
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)
diff --git a/tests/unit/cli/test_editor_setup.py b/tests/unit/cli/test_editor_setup.py
index fa068c6ab..caff00590 100644
--- a/tests/unit/cli/test_editor_setup.py
+++ b/tests/unit/cli/test_editor_setup.py
@@ -6,6 +6,7 @@ from io import StringIO
from pathlib import Path
from typing import Any
+import pytest
from rich.console import Console
from repowise.cli import mcp_config
@@ -199,6 +200,60 @@ 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."""
+ import yaml
+
+ cfg = yaml.safe_load((repo_path / ".repowise" / "config.yaml").read_text("utf-8")) or {}
+ return (
+ ((cfg.get("distill") or {}).get("commands") or {}).get("enabled"),
+ (cfg.get("hooks") or {}).get("read_skeleton"),
+ )
+
+
[email protected]("answer", [True, False])
+def test_the_rewrite_hook_answer_decides_read_skeleton_too(
+ monkeypatch, tmp_path: Path, answer: bool
+) -> None:
+ """One question, both keys.
+
+ The prompt already means "repowise's hooks may intervene in my agent's
+ tool 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.
+
+ 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.
+ """
+ from repowise.cli.commands.init_cmd._interactive import offer_distill_rewrite_hook
+
+ (tmp_path / ".repowise").mkdir()
+ monkeypatch.setattr(
+ "repowise.cli.agent_adapters.claude_code.ClaudeCodeAdapter.install_rewrite_hook",
+ lambda self: tmp_path / "settings.json",
+ )
+
+ offer_distill_rewrite_hook(_silent_console(), [tmp_path], answer, yes=True)
+
+ assert _hook_verdicts(tmp_path) == (answer, 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
+ returns."""
+ from repowise.cli.commands.init_cmd._interactive import offer_distill_rewrite_hook
+
+ (tmp_path / ".repowise").mkdir()
+
+ offer_distill_rewrite_hook(
+ _silent_console(), [tmp_path], False, yes=True, no_editor_setup=True
+ )
+
+ assert _hook_verdicts(tmp_path) == (False, False)
+
+
def test_distill_offer_silent_when_undecided_and_setup_off(monkeypatch, tmp_path: Path) -> None:
"""No flag plus no editor setup means nothing to install and nothing to ask."""
from repowise.cli.commands.init_cmd._interactive import offer_distill_rewrite_hook