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(cli): shared hook efficacy ledger + read-after-served adoption KPI (#777)
Raghav Chamadiyad57ff2c890eb
diff --git a/packages/cli/src/repowise/cli/commands/augment_cmd/command.py b/packages/cli/src/repowise/cli/commands/augment_cmd/command.pyindex 97193ebde..e39fc93c1 100644--- a/packages/cli/src/repowise/cli/commands/augment_cmd/command.py+++ b/packages/cli/src/repowise/cli/commands/augment_cmd/command.py@@ -83,6 +83,7 @@ from .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_editfrom .search import _handle_search_post+from .served_reads import _handle_mcp_read_post, _log_read_after_servedfrom .session_start import _handle_claude_session_start_EDIT_TOOL_NAMES = {"apply_patch", "Edit", "Write"}@@ -246,11 +247,18 @@ def _handle_post_tool_use(return _handle_post_edit_use(cwd)return _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)return _handle_read_post(tool_input, tool_output, cwd, session_id)if tool_name in ("Bash", "PowerShell"):# The PowerShell tool (Windows Claude Code) surfaces the same# stdout/stderr response shape as Bash — one handler covers both.return _handle_bash_post(tool_input, tool_output, cwd)if tool_name in ("Grep", "Glob"):- return _handle_search_post(tool_name, tool_input, tool_output, cwd)+ return _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 Nonereturn Nonediff --git a/packages/cli/src/repowise/cli/commands/augment_cmd/decision_inject.py b/packages/cli/src/repowise/cli/commands/augment_cmd/decision_inject.pyindex 97f51fa52..0eacc6995 100644--- a/packages/cli/src/repowise/cli/commands/augment_cmd/decision_inject.py+++ b/packages/cli/src/repowise/cli/commands/augment_cmd/decision_inject.py@@ -547,9 +547,20 @@ _INJECTIONS_TABLE_SQL = ("session_id TEXT NOT NULL, decision_id TEXT NOT NULL, ""node_id TEXT NOT NULL DEFAULT '', shown_at REAL NOT NULL, ""evaluated INTEGER NOT NULL DEFAULT 0, "+ "surface TEXT NOT NULL DEFAULT '', "+ "category TEXT NOT NULL DEFAULT '', "+ "chars INTEGER NOT NULL DEFAULT 0, ""PRIMARY KEY (session_id, decision_id))")+#: Mirror of core.sessions.staging.INJECTIONS_LEDGER_COLUMNS — the hook path+#: must not import repowise.core, so the migration is duplicated verbatim.+_LEDGER_COLUMNS = (+ ("surface", "TEXT NOT NULL DEFAULT ''"),+ ("category", "TEXT NOT NULL DEFAULT ''"),+ ("chars", "INTEGER NOT NULL DEFAULT 0"),+)+def _open_injections(repo_path: Path) -> sqlite3.Connection | None:db_path = repo_path / ".repowise" / "sessions" / "sessions.db"@@ -559,6 +570,10 @@ def _open_injections(repo_path: Path) -> sqlite3.Connection | None:conn.execute("PRAGMA journal_mode=WAL")conn.execute("PRAGMA busy_timeout=1000")conn.execute(_INJECTIONS_TABLE_SQL)+ existing = {row[1] for row in conn.execute("PRAGMA table_info(injections)")}+ for name, decl in _LEDGER_COLUMNS:+ if name not in existing:+ conn.execute(f"ALTER TABLE injections ADD COLUMN {name} {decl}")return connexcept (sqlite3.Error, OSError):return None@@ -581,8 +596,9 @@ def _record_injections(try:now = time.time()conn.executemany(- "INSERT OR IGNORE INTO injections (session_id, decision_id, node_id, shown_at) "- "VALUES (?, ?, ?, ?)",+ "INSERT OR IGNORE INTO injections "+ "(session_id, decision_id, node_id, shown_at, surface, category) "+ "VALUES (?, ?, ?, ?, 'decision', 'session_start')",[(session_id, did, node_id, now) for did in decision_ids],)conn.commit()@@ -592,6 +608,48 @@ def _record_injections(conn.close()+def _claim_ledger(+ repo_path: Path,+ session_id: str,+ key: str,+ *,+ node_id: str,+ surface: str,+ category: str,+ chars: int,+) -> tuple[bool, int]:+ """Atomically claim one non-decision ledger emission.++ Generic twin of :func:`_claim_injection` for the read/search enrichment+ surfaces: *key* replaces the decision id in the primary key, so INSERT OR+ IGNORE is the once-per-session-per-key gate. Returns ``(claimed,+ surface_injection_count)`` where the count covers only rows that actually+ carried text (``chars > 0``) on *surface* — pure measurement rows must not+ eat into an injection cap. Fail-closed: any error reports unclaimed.+ """+ conn = _open_injections(repo_path)+ if conn is None:+ return False, 0+ try:+ cur = conn.execute(+ "INSERT OR IGNORE INTO injections "+ "(session_id, decision_id, node_id, shown_at, surface, category, chars) "+ "VALUES (?, ?, ?, ?, ?, ?, ?)",+ (session_id, key, node_id, time.time(), surface, category, chars),+ )+ claimed = cur.rowcount > 0+ count = conn.execute(+ "SELECT COUNT(*) FROM injections WHERE session_id = ? AND surface = ? AND chars > 0",+ (session_id, surface),+ ).fetchone()[0]+ conn.commit()+ return claimed, int(count)+ except sqlite3.Error:+ return False, 0+ finally:+ conn.close()++def _claim_injection(repo_path: Path, session_id: str, decision_id: str, node_id: str) -> tuple[bool, int]:@@ -608,13 +666,17 @@ def _claim_injection(return False, 0try:cur = conn.execute(- "INSERT OR IGNORE INTO injections (session_id, decision_id, node_id, shown_at) "- "VALUES (?, ?, ?, ?)",+ "INSERT OR IGNORE INTO injections "+ "(session_id, decision_id, node_id, shown_at, surface, category) "+ "VALUES (?, ?, ?, ?, 'decision', 'edit_notice')",(session_id, decision_id, node_id, time.time()),)claimed = cur.rowcount > 0+ # Surface-scoped: read/search enrichment rows also carry a node_id and+ # must not eat into the edit-notice cap.count = conn.execute(- "SELECT COUNT(*) FROM injections WHERE session_id = ? AND node_id != ''",+ "SELECT COUNT(*) FROM injections WHERE session_id = ? AND node_id != '' "+ "AND surface IN ('', 'decision')",(session_id,),).fetchone()[0]conn.commit()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.pyindex f1ddb5019..e6d842178 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@@ -50,6 +50,9 @@ def _load_session_state(repo_path: Path, session_id: str) -> dict:"stale_notified": [],"reread_notified": [],"decisions_shown": [],+ # File ranges served by repowise MCP responses this session, kept for+ # the read-after-served KPI (see read_enrich; rel -> [[start, end]]).+ "served": {},}try:state = json.loads(_session_state_path(repo_path).read_text(encoding="utf-8"))diff --git a/packages/cli/src/repowise/cli/commands/augment_cmd/search.py b/packages/cli/src/repowise/cli/commands/augment_cmd/search.pyindex 6f14629b0..b727636b8 100644--- a/packages/cli/src/repowise/cli/commands/augment_cmd/search.py+++ b/packages/cli/src/repowise/cli/commands/augment_cmd/search.py@@ -21,6 +21,7 @@ def _handle_search_post(tool_input: dict,tool_output: object,cwd: str,+ session_id: str = "",) -> str | None:"""Decide whether to enrich a Grep/Glob result and how."""repo_path = _find_repo_root(Path(cwd))@@ -40,6 +41,7 @@ def _handle_search_post(if result_count >= _DIGEST_THRESHOLD:digest = _grep_flood_digest(repo_path, output_text)if digest:+ _log_search_firing(repo_path, session_id, "digest", output_text, digest)return digest# Unparseable output (e.g. Glob path lists): fall through to triage.@@ -69,7 +71,38 @@ def _handle_search_post(import asyncio- return asyncio.run(_search_enrich(repo_path, pattern, mode, result_count))+ enrichment = asyncio.run(_search_enrich(repo_path, pattern, mode, result_count))+ if enrichment:+ _log_search_firing(repo_path, session_id, mode, pattern, enrichment)+ return enrichment+++def _log_search_firing(+ repo_path: Path, session_id: str, category: str, keyed_on: str, text: str+) -> None:+ """Record one search enrichment in the shared ledger; measurement only.++ All hook surfaces share the sessions.db efficacy ledger so the miner can+ classify used vs ignored firings in one pass. Keyed on the category plus a+ content hash — the same rescue repeated in one session logs once. Never+ changes what the agent sees; any failure is silent.+ """+ if not session_id:+ return+ import hashlib++ from .decision_inject import _claim_ledger++ digest = hashlib.sha1(keyed_on.encode("utf-8", "replace")).hexdigest()[:12]+ _claim_ledger(+ repo_path,+ session_id,+ f"search:{category}:{digest}",+ node_id="",+ surface="search",+ category=category,+ chars=len(text),+ )def _grep_flood_digest(repo_path: Path, output_text: str) -> str | None:diff --git a/packages/cli/src/repowise/cli/commands/augment_cmd/served_reads.py b/packages/cli/src/repowise/cli/commands/augment_cmd/served_reads.pynew file mode 100644index 000000000..8981169fd--- /dev/null+++ b/packages/cli/src/repowise/cli/commands/augment_cmd/served_reads.py@@ -0,0 +1,213 @@+"""Read-after-served tracking: the MCP adoption KPI, measured at the hook.++When a repowise MCP response has already served the content of a file (a+get_symbol body, a range read, get_answer's symbol_bodies/quotes) and the+agent later Reads that same content anyway, that Read is the single most+diagnostic adoption signal we have: served-then-read means the MCP answer+did not land. This module measures it and deliberately injects NOTHING —+nagging at that moment would burn trust for zero benefit.++Two hooks feed it:++ * PostToolUse on repowise MCP tools — record which file line-ranges the+ response actually served (source bytes only; skeletons and signatures+ don't count, a Read after those is expected).+ * PostToolUse on Read — when the served ranges cover most of the Read+ window, log one ``read_after_served`` row per file per session into the+ shared sessions.db ledger (chars=0: measurement, never an injection).++Same operational rules as the rest of augment: stdlib-only on the hook path,+unknown tool-output shapes are skipped rather than guessed, and any failure+degrades to silence.+"""++from __future__ import annotations++import json+from pathlib import Path++from ._shared import _find_repo_root, _relativize+from .decision_inject import _claim_ledger++_SERVED_COVERAGE = 0.8 # served share of a Read window that counts as covered+_MAX_SERVED_FILES = 50 # served-range bookkeeping caps (state-file hygiene)+_MAX_SERVED_RANGES = 40++_SURFACE = "read_enrich"+++# ---------------------------------------------------------------------------+# Read side: coverage check + ledger row+# ---------------------------------------------------------------------------+++def _log_read_after_served(+ tool_input: dict,+ tool_output: object,+ cwd: str,+ session_id: str,+) -> None:+ """Log a Read whose window the MCP tools already served. Emits nothing."""+ if not session_id:+ return+ file_path = tool_input.get("file_path") if isinstance(tool_input, dict) else None+ if not isinstance(file_path, str) or not file_path.strip():+ return+ repo_path = _find_repo_root(Path(cwd))+ if repo_path is None:+ return+ rel = _relativize(file_path, repo_path)+ if rel is None:+ return+ window = _read_window(tool_input, tool_output)+ if window is None:+ # Unknown/unextractable Read response shape — skip, never guess.+ return+ start, end = window+ if _served_covers(repo_path, session_id, rel, start, end):+ _claim_ledger(+ repo_path,+ session_id,+ f"{_SURFACE}:read_after_served:{rel}",+ node_id=rel,+ surface=_SURFACE,+ category="read_after_served",+ chars=0,+ )+++def _read_window(tool_input: dict, tool_output: object) -> tuple[int, int] | None:+ """(start_line, end_line) of a Read, or None when unknowable."""+ from .read_state import _read_output_line_count++ lines = _read_output_line_count(tool_output)+ if lines <= 0:+ return None+ offset = tool_input.get("offset")+ start = offset if isinstance(offset, int) and offset > 0 else 1+ return start, start + lines - 1+++def _served_covers(repo_path: Path, session_id: str, rel: str, start: int, end: int) -> bool:+ """True when served ranges cover >= _SERVED_COVERAGE of the Read window."""+ from .read_state import _load_session_state++ state = _load_session_state(repo_path, session_id)+ served = state.get("served")+ ranges = served.get(rel) if isinstance(served, dict) else None+ if not isinstance(ranges, list) or end < start:+ return False+ spans: list[tuple[int, int]] = []+ for r in ranges:+ if not (isinstance(r, list) and len(r) == 2):+ continue+ s, e = r+ if isinstance(s, int) and isinstance(e, int) and s <= end and e >= start:+ spans.append((max(s, start), min(e, end)))+ covered = 0+ cursor = start - 1+ for s, e in sorted(spans):+ s = max(s, cursor + 1)+ if e > cursor:+ covered += e - s + 1+ cursor = e+ return covered / (end - start + 1) >= _SERVED_COVERAGE+++# ---------------------------------------------------------------------------+# MCP side: served-content bookkeeping+# ---------------------------------------------------------------------------+++def _handle_mcp_read_post(tool_output: object, cwd: str, session_id: str) -> None:+ """Record file ranges a repowise MCP response served.++ Best-effort bookkeeping in the per-session state file — a lost update+ undercounts the KPI, never spams the agent. Emits nothing.+ """+ if not session_id:+ return+ repo_path = _find_repo_root(Path(cwd))+ if repo_path is None:+ return+ ranges = _served_ranges(tool_output)+ if not ranges:+ return++ from .read_state import _load_session_state, _save_session_state++ state = _load_session_state(repo_path, session_id)+ served = state.setdefault("served", {})+ for rel, start, end in ranges:+ if rel not in served and len(served) >= _MAX_SERVED_FILES:+ continue+ entries = served.setdefault(rel, [])+ if [start, end] not in entries and len(entries) < _MAX_SERVED_RANGES:+ entries.append([start, end])+ _save_session_state(repo_path, state)+++def _served_ranges(tool_output: object) -> list[tuple[str, int, int]]:+ """(rel_path, start_line, end_line) spans whose source text was served.++ Only the response fields known to carry actual source bytes are read:+ get_symbol's top-level/candidates bodies (file + start_line/end_line ++ source) and get_answer's symbol_bodies/quotes (path + lines). Skeletons+ and signatures don't count — a Read after those is expected, not an+ adoption failure. Unknown shapes yield nothing.+ """+ payload = _mcp_payload(tool_output)+ if not isinstance(payload, dict):+ return []+ if isinstance(payload.get("result"), dict):+ payload = payload["result"]++ out: list[tuple[str, int, int]] = []++ def _add(path: object, start: object, end: object) -> None:+ if (+ isinstance(path, str)+ and path+ and isinstance(start, int)+ and isinstance(end, int)+ and 0 < start <= end+ ):+ out.append((path.replace("\\", "/"), start, end))++ def _body(entry: dict) -> None:+ if entry.get("source") or entry.get("content"):+ _add(entry.get("file"), entry.get("start_line"), entry.get("end_line"))++ _body(payload)+ for entry in payload.get("candidates") or []:+ if isinstance(entry, dict):+ _body(entry)+ for key in ("symbol_bodies", "quotes"):+ for entry in payload.get(key) or []:+ if isinstance(entry, dict) and (entry.get("source") or entry.get("quote")):+ lines = entry.get("lines")+ if isinstance(lines, list) and len(lines) == 2:+ _add(entry.get("path"), lines[0], lines[1])+ return out+++def _mcp_payload(tool_output: object) -> dict | None:+ """The response JSON dict from any of the MCP hook payload shapes."""+ if isinstance(tool_output, dict):+ return tool_output+ text = None+ if isinstance(tool_output, str):+ text = tool_output+ elif isinstance(tool_output, list):+ # Content-block list: [{"type": "text", "text": "{...}"}]+ for item in tool_output:+ if isinstance(item, dict) and isinstance(item.get("text"), str):+ text = item["text"]+ break+ if not text:+ return None+ try:+ parsed = json.loads(text)+ except (ValueError, TypeError):+ return None+ return parsed if isinstance(parsed, dict) else Nonediff --git a/packages/cli/src/repowise/cli/editor_integrations/claude_config.py b/packages/cli/src/repowise/cli/editor_integrations/claude_config.pyindex ebd7c5593..e082d6f53 100644--- a/packages/cli/src/repowise/cli/editor_integrations/claude_config.py+++ b/packages/cli/src/repowise/cli/editor_integrations/claude_config.py@@ -132,13 +132,16 @@ def enable_tool_search_in_claude_code() -> Path | None:# Current augment PostToolUse matcher. Read/Edit/Write power the distill# read-intelligence layer (skeleton nudges + per-file stale-read notices);# PowerShell is the Windows Claude Code shell tool (same payload shape as-# Bash); legacy installs with the narrower matchers below are widened in-# place.-_AUGMENT_MATCHER = "Bash|PowerShell|Grep|Glob|Read|Edit|Write"+# Bash); the mcp__ pattern feeds the read-after-served ledger (read_enrich)+# and matches the repowise MCP server under any registration name (local,+# plugin, hosted "Repowise"); legacy installs with the narrower matchers+# below are widened in place.+_AUGMENT_MATCHER = "Bash|PowerShell|Grep|Glob|Read|Edit|Write|mcp__.*[Rr]epowise.*__.*"_LEGACY_AUGMENT_MATCHERS = ("Bash","Bash|Grep|Glob","Bash|Grep|Glob|Read|Edit|Write",+ "Bash|PowerShell|Grep|Glob|Read|Edit|Write",)# SessionStart emits the live index-freshness / trust context block. `compact`diff --git a/packages/core/src/repowise/core/sessions/staging.py b/packages/core/src/repowise/core/sessions/staging.pyindex 6ea2cd935..0f9dc414c 100644--- a/packages/core/src/repowise/core/sessions/staging.py+++ b/packages/core/src/repowise/core/sessions/staging.py@@ -79,12 +79,34 @@ CREATE TABLE IF NOT EXISTS injections (node_id TEXT NOT NULL DEFAULT '',shown_at REAL NOT NULL,evaluated INTEGER NOT NULL DEFAULT 0,+ surface TEXT NOT NULL DEFAULT '',+ category TEXT NOT NULL DEFAULT '',+ chars INTEGER NOT NULL DEFAULT 0,PRIMARY KEY (session_id, decision_id));CREATE INDEX IF NOT EXISTS idx_raw_pending ON raw_candidates(structured_key)WHERE structured_key IS NULL;"""+#: Columns added to ``injections`` after PR4 shipped the table (the ledger now+#: records every hook surface, not just decision injections). Kept in one place+#: so the hook-side writer (augment's stdlib-sqlite3 opener) and this reader+#: apply the identical migration to sidecars created by either side first.+INJECTIONS_LEDGER_COLUMNS = (+ ("surface", "TEXT NOT NULL DEFAULT ''"),+ ("category", "TEXT NOT NULL DEFAULT ''"),+ ("chars", "INTEGER NOT NULL DEFAULT 0"),+)+++def _migrate_injections_columns(conn: sqlite3.Connection) -> None:+ """Best-effort ALTER for sidecars created before the ledger columns."""+ existing = {row[1] for row in conn.execute("PRAGMA table_info(injections)")}+ for name, decl in INJECTIONS_LEDGER_COLUMNS:+ if name not in existing:+ conn.execute(f"ALTER TABLE injections ADD COLUMN {name} {decl}")++_NON_ALNUM_RE = re.compile(r"[^a-z0-9\s]")_WS_RE = re.compile(r"\s+")@@ -150,6 +172,7 @@ class SessionStagingStore:self._conn.execute("PRAGMA synchronous=NORMAL")self._conn.execute("PRAGMA busy_timeout=5000")self._conn.executescript(_SCHEMA)+ _migrate_injections_columns(self._conn)self._conn.commit()self.cursors = _DbCursors(self._conn)@@ -338,10 +361,17 @@ class SessionStagingStore:def unevaluated_injections(self, *, before: float) -> list[dict[str, Any]]:"""Shown-decision rows not yet judged, old enough that the showing- session has plausibly moved past the guidance (see *before*)."""+ session has plausibly moved past the guidance (see *before*).++ Scoped to the decision surface: the ledger also records read/search+ enrichments whose ids are not decision_records keys, and the follow-up+ classifier for those rides a separate mining pass. Pre-column rows+ (surface '') are all decision injections.+ """rows = self._conn.execute("SELECT session_id, decision_id, node_id, shown_at FROM injections "- "WHERE evaluated = 0 AND shown_at < ? ORDER BY shown_at ASC",+ "WHERE evaluated = 0 AND shown_at < ? AND surface IN ('', 'decision') "+ "ORDER BY shown_at ASC",(before,),).fetchall()return [diff --git a/plugins/claude-code/hooks/hooks.json b/plugins/claude-code/hooks/hooks.jsonindex a2adf1234..9745a47db 100644--- a/plugins/claude-code/hooks/hooks.json+++ b/plugins/claude-code/hooks/hooks.json@@ -15,7 +15,7 @@],"PostToolUse": [{- "matcher": "Bash|PowerShell|Grep|Glob|Read|Edit|Write",+ "matcher": "Bash|PowerShell|Grep|Glob|Read|Edit|Write|mcp__.*[Rr]epowise.*__.*","hooks": [{"type": "command",diff --git a/tests/unit/cli/test_augment_served_reads.py b/tests/unit/cli/test_augment_served_reads.pynew file mode 100644index 000000000..322f517a5--- /dev/null+++ b/tests/unit/cli/test_augment_served_reads.py@@ -0,0 +1,249 @@+"""Read-after-served KPI tracking + the shared hook efficacy ledger.++The contract under test: repowise MCP responses' served line-ranges are+tracked per session, a Read substantially covered by them logs exactly one+measurement row (chars=0, never an injection), unknown tool-output shapes are+skipped rather than guessed, and the extended ledger migrates legacy sidecars+on both the hook side and the staging-store side.+"""++from __future__ import annotations++import json+import sqlite3+from pathlib import Path++from repowise.cli.commands.augment_cmd import served_reads+from repowise.cli.commands.augment_cmd.decision_inject import _claim_ledger+from repowise.cli.commands.augment_cmd.search import _log_search_firing++_TARGET = "src/core/models.py"+++def _repo(tmp_path: Path) -> Path:+ (tmp_path / ".repowise").mkdir(parents=True, exist_ok=True)+ return tmp_path+++def _full_read(num_lines: int = 60, rel: str = _TARGET) -> tuple[dict, dict]:+ return (+ {"file_path": rel},+ {"file": {"numLines": num_lines, "content": "x\n" * num_lines}},+ )+++def _log_read(repo_root: Path, tool_input: dict, tool_output: dict, session_id="sess-1"):+ tool_input = {**tool_input, "file_path": str(repo_root / tool_input["file_path"])}+ served_reads._log_read_after_served(tool_input, tool_output, str(repo_root), session_id)+++def _serve(repo_root: Path, start: int, end: int, session_id="sess-1", rel=_TARGET) -> None:+ payload = {+ "result": {+ "symbol_id": f"{rel}:{start}-{end}",+ "file": rel,+ "start_line": start,+ "end_line": end,+ "source": " 1\tx",+ }+ }+ served_reads._handle_mcp_read_post(+ [{"type": "text", "text": json.dumps(payload)}], str(repo_root), session_id+ )+++def _ledger_rows(repo_root: Path) -> list[tuple]:+ db = repo_root / ".repowise" / "sessions" / "sessions.db"+ if not db.exists():+ return []+ con = sqlite3.connect(db)+ try:+ return con.execute(+ "SELECT session_id, decision_id, surface, category, chars FROM injections"+ ).fetchall()+ finally:+ con.close()+++# ---------------------------------------------------------------------------+# Read-after-served+# ---------------------------------------------------------------------------+++def test_covered_read_logs_one_measurement_row(tmp_path):+ repo = _repo(tmp_path)+ _serve(repo, 1, 60)++ _log_read(repo, *_full_read(num_lines=60))+ _log_read(repo, *_full_read(num_lines=60)) # once per file per session++ rows = _ledger_rows(repo)+ assert rows == [+ (+ "sess-1",+ f"read_enrich:read_after_served:{_TARGET}",+ "read_enrich",+ "read_after_served",+ 0,+ )+ ]+++def test_partially_served_read_is_not_logged(tmp_path):+ repo = _repo(tmp_path)+ _serve(repo, 1, 30) # 50% of the window: below the coverage bar+ _log_read(repo, *_full_read(num_lines=60))+ assert _ledger_rows(repo) == []+++def test_served_ranges_union_counts(tmp_path):+ repo = _repo(tmp_path)+ # Two disjoint serves covering 50/60 lines = 83% >= 80%.+ _serve(repo, 1, 30)+ _serve(repo, 41, 60)+ _log_read(repo, *_full_read(num_lines=60))+ assert any(r[3] == "read_after_served" for r in _ledger_rows(repo))+++def test_partial_read_window_uses_offset(tmp_path):+ repo = _repo(tmp_path)+ _serve(repo, 100, 200)+ tool_input = {"file_path": str(repo / _TARGET), "offset": 110, "limit": 50}+ tool_output = {"file": {"numLines": 50, "content": "x\n" * 50}}+ served_reads._log_read_after_served(tool_input, tool_output, str(repo), "sess-1")+ assert any(r[3] == "read_after_served" for r in _ledger_rows(repo))+++def test_unread_or_unknown_shapes_never_log(tmp_path):+ repo = _repo(tmp_path)+ _serve(repo, 1, 60)+ tool_input, _ = _full_read()+ # Unknown Read output shape: refuse to guess a window.+ _log_read(repo, tool_input, {"unexpected": True})+ # No session id: no dedup key, no row.+ _log_read(repo, *_full_read(num_lines=60), session_id="")+ assert _ledger_rows(repo) == []+++def test_mcp_unknown_shapes_record_nothing(tmp_path):+ repo = _repo(tmp_path)+ served_reads._handle_mcp_read_post({"weird": 1}, str(repo), "sess-1")+ served_reads._handle_mcp_read_post("not json", str(repo), "sess-1")+ served_reads._handle_mcp_read_post(None, str(repo), "sess-1")+ state_path = repo / ".repowise" / ".augment-session.json"+ if state_path.exists():+ state = json.loads(state_path.read_text(encoding="utf-8"))+ assert not state.get("served")+++def test_served_ranges_parser_shapes():+ get_symbol = {+ "result": {+ "file": "a.py",+ "start_line": 10,+ "end_line": 40,+ "source": "src",+ "candidates": [+ {"file": "b.py", "start_line": 1, "end_line": 5, "source": "s"},+ {"file": "c.py", "start_line": 1, "end_line": 5}, # no source: skip+ ],+ }+ }+ assert served_reads._served_ranges(get_symbol) == [("a.py", 10, 40), ("b.py", 1, 5)]++ answer = {+ "result": {+ "symbol_bodies": [{"path": "d\\e.py", "lines": [5, 25], "source": "s"}],+ "quotes": [{"path": "f.py", "lines": [1, 3], "quote": "q"}],+ }+ }+ assert served_reads._served_ranges(answer) == [("d/e.py", 5, 25), ("f.py", 1, 3)]++ assert served_reads._served_ranges({"result": {"answer": "prose only"}}) == []+ assert served_reads._served_ranges([{"type": "text", "text": "{broken"}]) == []+++# ---------------------------------------------------------------------------+# Shared ledger: search-surface logging + migration+# ---------------------------------------------------------------------------+++def test_search_firing_logs_to_ledger(tmp_path):+ repo = _repo(tmp_path)+ _log_search_firing(repo, "sess-1", "rescue", "parse_yaml", "[repowise] rescue text")+ _log_search_firing(repo, "sess-1", "rescue", "parse_yaml", "[repowise] rescue text") # dedup+ _log_search_firing(repo, "", "rescue", "parse_yaml", "text") # no session id: skipped++ rows = _ledger_rows(repo)+ assert len(rows) == 1+ session_id, key, surface, category, chars = rows[0]+ assert (session_id, surface, category) == ("sess-1", "search", "rescue")+ assert key.startswith("search:rescue:")+ assert chars == len("[repowise] rescue text")+++def test_claim_ledger_migrates_legacy_sidecar(tmp_path):+ repo = _repo(tmp_path)+ db_path = repo / ".repowise" / "sessions" / "sessions.db"+ db_path.parent.mkdir(parents=True, exist_ok=True)+ con = sqlite3.connect(db_path)+ con.execute(+ "CREATE TABLE injections (session_id TEXT NOT NULL, decision_id TEXT NOT NULL, "+ "node_id TEXT NOT NULL DEFAULT '', shown_at REAL NOT NULL, "+ "evaluated INTEGER NOT NULL DEFAULT 0, PRIMARY KEY (session_id, decision_id))"+ )+ con.execute("INSERT INTO injections (session_id, decision_id, shown_at) VALUES ('s', 'd', 1.0)")+ con.commit()+ con.close()++ claimed, count = _claim_ledger(+ repo,+ "sess-1",+ "read_enrich:read_after_served:x.py",+ node_id="x.py",+ surface="read_enrich",+ category="read_after_served",+ chars=0,+ )++ assert claimed is True+ assert count == 0 # chars=0 measurement rows never count as injections+ rows = _ledger_rows(repo)+ assert ("s", "d", "", "", 0) in rows # legacy row got the defaults+ assert (+ "sess-1",+ "read_enrich:read_after_served:x.py",+ "read_enrich",+ "read_after_served",+ 0,+ ) in rows+++def test_staging_store_migrates_legacy_sidecar(tmp_path):+ from repowise.core.sessions.staging import SessionStagingStore++ db_path = tmp_path / "sessions.db"+ con = sqlite3.connect(db_path)+ con.execute(+ "CREATE TABLE injections (session_id TEXT NOT NULL, decision_id TEXT NOT NULL, "+ "node_id TEXT NOT NULL DEFAULT '', shown_at REAL NOT NULL, "+ "evaluated INTEGER NOT NULL DEFAULT 0, PRIMARY KEY (session_id, decision_id))"+ )+ con.commit()+ con.close()++ with SessionStagingStore(db_path) as store:+ cols = {row[1] for row in store._conn.execute("PRAGMA table_info(injections)")}+ assert {"surface", "category", "chars"} <= cols+ # Decision-surface reader ignores non-decision rows.+ store._conn.execute(+ "INSERT INTO injections (session_id, decision_id, shown_at, surface) "+ "VALUES ('s1', 'read_enrich:read_after_served:x.py', 1.0, 'read_enrich')"+ )+ store._conn.execute(+ "INSERT INTO injections (session_id, decision_id, shown_at, surface) "+ "VALUES ('s1', 'd-legacy', 1.0, '')"+ )+ store.commit()+ pending = store.unevaluated_injections(before=2.0)+ assert [p["decision_id"] for p in pending] == ["d-legacy"]