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): answer a failed path with the file the index says you meant (#1336)
Raghav Chamadiyac0161ddd6c91
diff --git a/docs/agent/HOOKS.md b/docs/agent/HOOKS.mdindex 72d6e0060..fa86866ee 100644--- a/docs/agent/HOOKS.md+++ b/docs/agent/HOOKS.md@@ -22,6 +22,7 @@ crashes or blocks your agent.| **Post-commit auto-sync** | git | `repowise hook install` (or the `repowise init` prompt) | every `git commit` | Runs `repowise update` in the background so the wiki tracks your code || **SessionStart context** | Claude Code | `repowise init` | session `startup` / `resume` / `clear` | Live index-freshness line, core-tool trust rule, and the standing decisions relevant to this session || **PostToolUse enrichment** | Claude Code | `repowise init` | `Grep` / `Glob` / `Read` / `Edit` / `Write` / `Bash` / `PowerShell` / repowise MCP calls | Graph context on searches, git/edit freshness, read-intelligence notices, and edit-time "governed by" decision notices |+| **Wrong-path rescue** | Claude Code | `repowise init` | a `Read` / `Edit` / `Write` / `Grep` / `Glob` / `NotebookEdit` that failed on a path this tree does not have | Names the file when exactly one indexed file carries that basename; silent otherwise || **Command-rewrite (distill)** | Claude Code | `repowise hook rewrite install` (opt-in) | `Bash` / `PowerShell` | Rewrites noisy commands to `repowise distill <cmd>`; auto-allowed by default, set `permission: ask` to approve each one || **Codex context + staleness** | Codex | `repowise init --codex` | SessionStart / UserPromptSubmit / edit / Bash | Reminds Codex to use the MCP tools and flags stale context after edits |@@ -186,6 +187,40 @@ behind "learns from your sessions" (see the [README](../../README.md) and---+## PostToolUseFailure, the wrong-path rescue++An agent that knows a file exists but guesses the wrong directory for it gets+back "Path does not exist" and burns a turn hunting. The index already knows+where that filename lives, so the failure is answerable at the moment it+happens:++```+[repowise] core/git_indexer/fix_events.py is not in this tree.+The only indexed fix_events.py is core/ingestion/git_indexer/fix_events.py+```++It speaks only when the basename resolves to **exactly one** indexed file that+is still on disk. Everything else is silence, and each case is a distinct way+to be confidently wrong:++- **An ambiguous basename.** Naming one of a dozen `registry.py` is worse than+ saying nothing, because the agent has no cheap way to tell a rescue from a+ fact.+- **A directory target.** "Which file did you mean" is not the question a+ missing directory asks.+- **A path in another checkout.** A sibling worktree has its own index; this+ one has no standing to answer for it.+- **A failure Claude Code already answered.** It prints its own "Did you mean"+ for some of these, and repeating it is worse than silence.+- **The path that just failed.** The index can hold a row for a file that is+ not on disk right now, and pointing back at the failed path is the worst+ thing this surface could say.++Measured over 435 sessions in this repo: 86 path-not-found failures on the file+tools, of which the rescue speaks to 18. The gap is the point.++---+## Command-rewrite hook (distill), opt-inMost of what an agent reads from a shell command is noise: 300 lines of passingdiff --git a/packages/cli/src/repowise/cli/commands/augment_cmd/command.py b/packages/cli/src/repowise/cli/commands/augment_cmd/command.pyindex cbe3bfbf5..240da0d65 100644--- a/packages/cli/src/repowise/cli/commands/augment_cmd/command.py+++ b/packages/cli/src/repowise/cli/commands/augment_cmd/command.py@@ -64,6 +64,13 @@ Codex SessionStart/UserPromptSubmit: adds short repowise MCP usage guidance.* After file edits, emit a short reminder that the indexed context maybe stale.+ PostToolUseFailure → Read / Edit / Write / Grep / Glob / NotebookEdit+ * Wrong-path rescue: the call failed because the path is not in this+ tree, and exactly one indexed file carries that basename. Names it.+ Silent on an ambiguous basename, a directory target, a path in another+ checkout, and on the failures where Claude Code already printed its+ own suggestion — the whole value here is that a rescue can be trusted.+There is intentionally NO PreToolUse handling. Earlier versions enrichedevery Grep/Glob unconditionally with importers/dependencies/symbols; inpractice this added noise on the >70% of searches where the agent had@@ -94,6 +101,7 @@ from .read_state import _handle_edit_post, _handle_read_post, _record_editfrom .search import _handle_search_postfrom .served_reads import _handle_mcp_read_post, _log_read_after_servedfrom .session_start import _handle_claude_session_start+from .wrong_path import _handle_tool_failure_EDIT_TOOL_NAMES = {"apply_patch", "Edit", "Write"}@@ -152,6 +160,27 @@ def _run_augment(*, client: str | None = None) -> None:_count_run(cwd, session_id, event, "", emitted=bool(result))return+ if event == "PostToolUseFailure":+ # A tool that just failed on a path this tree does not have is the one+ # moment the index can answer a question the agent actually asked.+ #+ # This event carries the failure in ``error`` and not in+ # ``tool_response``, which is PostToolUse-only, and it fires for a user+ # interrupt as well as for a real error. Both are load-bearing: reading+ # the wrong field is silence, and answering an interrupt is noise at+ # the moment the user asked for quiet.+ if payload.get("is_interrupt"):+ return+ session_id = payload.get("session_id", "")+ session_id = session_id if isinstance(session_id, str) else ""+ result = _handle_tool_failure(+ tool_name, tool_input, payload.get("error"), cwd, session_id=session_id+ )+ if result:+ _emit_response(event, result)+ _count_run(cwd, session_id, event, tool_name, emitted=bool(result))+ return+if event != "PostToolUse":returndiff --git a/packages/cli/src/repowise/cli/commands/augment_cmd/fast_lookup.py b/packages/cli/src/repowise/cli/commands/augment_cmd/fast_lookup.pyindex fbd09830a..d1d12190c 100644--- a/packages/cli/src/repowise/cli/commands/augment_cmd/fast_lookup.py+++ b/packages/cli/src/repowise/cli/commands/augment_cmd/fast_lookup.py@@ -100,6 +100,42 @@ def pagerank(return {node_id: pr or 0.0 for node_id, pr in rows if node_id}+def files_by_basename(+ conn: sqlite3.Connection, repository_id: str, basename: str, limit: int = 5+) -> list[str]:+ """Node ids of indexed files with this basename, newest-schema first.++ Capped rather than exhaustive: the caller only needs to tell one match from+ more-than-one, and the cap keeps a common name like ``__init__.py`` from+ materialising hundreds of rows to be counted and thrown away. The cap is+ above two on purpose — the caller still has to drop rows whose file is no+ longer on disk, and a cap of two lets one stale row hide the single live+ answer behind an apparent tie.++ ``LIKE`` with an explicit ``ESCAPE`` rather than ``GLOB``: a path is data,+ not a pattern, and ``GLOB`` would read a ``[`` in a filename as a character+ class. The exact-equality arm catches a file at the repository root, which+ has no leading separator to match, and is spelled case-insensitively to+ match the ``LIKE`` arm's own default rather than holding a root file to a+ stricter rule than a nested one.++ Filtering non-path nodes is left to the caller: ``node_type = 'file'`` also+ covers resolved external packages, and ``:`` is a legal character in a+ POSIX path, so excluding them in SQL would mean a colon test that can drop+ a real file and manufacture a false unique.+ """+ if not basename:+ return []+ rows = conn.execute(+ "SELECT node_id FROM graph_nodes "+ "WHERE repository_id = ? AND node_type = 'file' "+ "AND (lower(node_id) = lower(?) "+ f"OR node_id LIKE ? ESCAPE '{_LIKE_ESCAPE}') LIMIT ?",+ (repository_id, basename, f"%/{escape_like(basename)}", limit),+ ).fetchall()+ return [node_id for (node_id,) in rows if node_id]++def symbols_matching(conn: sqlite3.Connection, repository_id: str, paths: list[str], needle: str) -> list[tuple[str, str]]:diff --git a/packages/cli/src/repowise/cli/commands/augment_cmd/wrong_path.py b/packages/cli/src/repowise/cli/commands/augment_cmd/wrong_path.pynew file mode 100644index 000000000..ea58d54dd--- /dev/null+++ b/packages/cli/src/repowise/cli/commands/augment_cmd/wrong_path.py@@ -0,0 +1,220 @@+"""Rescue a tool call that failed on a path this tree does not have.++The agent guesses a plausible directory for a file it knows exists — the+package layout moved, or it inferred ``core/git_indexer/`` from a symbol name+when the file lives under ``core/ingestion/git_indexer/`` — and gets back+"Path does not exist". The index knows where that basename actually lives, so+the failure is answerable at the moment it happens.++Measured over 435 transcripts of this repo: 86 path-not-found failures on the+file tools, of which this predicate speaks to 18, across 16 sessions. The gap+is deliberate and every step of it is a rule below. Precision is the whole+product here — a confident wrong path costs more than silence, because the+agent has no cheap way to tell a rescue from a fact.++Everything runs on stdlib ``sqlite3`` through :mod:`fast_lookup`; no retrieval,+no ORM. The one query is a basename scan of the repo's file nodes.+"""++from __future__ import annotations++import re+from pathlib import Path++from ._shared import HookResult, _find_repo_root++#: Tools whose failure can name a path we could rescue. Bash and PowerShell+#: fail on paths too ("cd: no such file"), but their input is a command line+#: rather than a path argument, so extracting the intended path is a different+#: problem with a different error surface. Out of scope on purpose.+_PATH_TOOLS = frozenset({"Read", "Edit", "Write", "Grep", "Glob", "NotebookEdit"})++#: The two verbatim shapes a missing path takes, taken from the corpus rather+#: than from the docs. Grep/Glob name the path in the error; Read does not, and+#: its path has to come from ``tool_input``.+_PATH_MISSING = re.compile(+ r"<tool_use_error>Path does not exist: (?P<path>.+?)\. Note: your current"+)+_FILE_MISSING = re.compile(r"(?:^|\n)File does not exist\.")++#: Claude Code prints its own suggestion for some of these (10 of the 86). It+#: has already been said and saying it again is worse than silence.+_ALREADY_SUGGESTED = re.compile(r"Did you mean ", re.IGNORECASE)+++def _failed_path(tool_input: dict, error_text: str) -> str:+ """The path the tool tried and did not find, or "" if this is not that."""+ m = _PATH_MISSING.search(error_text)+ if m:+ return m.group("path").strip()+ if _FILE_MISSING.search(error_text):+ for field in ("file_path", "path", "notebook_path"):+ value = tool_input.get(field)+ if isinstance(value, str) and value.strip():+ return value.strip()+ return ""+++def _is_several_paths(attempted: str) -> bool:+ """True when one string carries more than one path.++ A search tool can be handed several paths at once and report them as one+ string, and the basename of whichever landed last is not what was asked+ for. Tested by counting whitespace-separated tokens that end in a file+ extension rather than by rejecting whitespace outright: a checkout under+ ``C:\\Users\\Foo Bar`` or ``OneDrive - Company`` puts a space in every+ absolute path, and rejecting those takes the surface's recall to zero for+ everyone who has one.+ """+ tokens = attempted.split()+ return sum(1 for token in tokens if Path(token).suffix) > 1+++def _repo_relative(repo_path: Path, attempted: str, cwd: Path) -> str | None:+ """*attempted* as a repo-relative POSIX path, or None if it is elsewhere.++ A sibling worktree or another checkout carries its own index, and this one+ has no standing to answer for it: 10 of the 86 failures name one, and the+ file they want is the *other* tree's copy.++ A relative path is joined to *cwd* and put through the same containment+ check rather than taken at face value. The agent's cwd is not always the+ repository root, so face value gets both halves wrong: ``../sibling/x.py``+ would read as an in-repo path and be answered with this tree's copy, and a+ cwd-relative path would be echoed back as though it were repo-relative.+ """+ path = Path(attempted)+ if not path.is_absolute():+ path = cwd / path+ try:+ return path.resolve().relative_to(repo_path.resolve()).as_posix()+ except (ValueError, OSError):+ return None+++def _resolve(repo_path: Path, relative: str) -> str | None:+ """The one indexed file with this basename, or None when that is not one.++ None covers every reason to stay quiet, and they are not the same reason:+ no index, no match, several matches, or a match that is no longer on disk.+ The ambiguous case is silence by decision — naming one of twelve+ ``registry.py`` confidently is the failure this surface exists to avoid.+ """+ from . import fast_lookup++ basename = relative.rsplit("/", 1)[-1]+ conn = fast_lookup.connect(repo_path)+ if conn is None:+ return None+ try:+ repo_id = fast_lookup.repo_id(conn, repo_path)+ if repo_id is None:+ return None+ matches = fast_lookup.files_by_basename(conn, repo_id, basename)+ except Exception:+ return None+ finally:+ conn.close()++ # ``node_type = 'file'`` also covers resolved external packages, spelled+ # ``external:pkg/mod``. They are not paths in this tree, and the on-disk+ # test below is what rules them out along with rows whose file has since+ # been deleted. Both filters run before the uniqueness test, so a stale row+ # cannot hide the single live answer behind an apparent tie.+ live = [m for m in matches if (repo_path / m).exists()]+ if len(live) != 1:+ return None+ resolved = live[0]+ if resolved.lower() == relative.lower():+ # The answer is the path that just failed. Reachable whenever the file+ # arrived between the failure and this hook, or the tool failed for a+ # reason other than the path being absent. "Did you mean the thing you+ # just tried" is the worst thing this surface could say, and 3 of the+ # 86 measured failures would have hit it.+ return None+ return resolved+++def _error_text(error: object) -> str:+ """The failure as text. ``error`` is a string today; this survives it not.++ Claude Code passes the rejection through verbatim, so the shape is the+ tool's rather than the harness's. A dict is unwrapped by the keys the+ tool-result blocks use; anything else is not something to guess at.+ """+ if isinstance(error, str):+ return error+ if isinstance(error, dict):+ for field in ("message", "text", "content", "error"):+ value = error.get(field)+ if isinstance(value, str) and value.strip():+ return value+ return ""+++def _handle_tool_failure(+ tool_name: str,+ tool_input: dict,+ error: object,+ cwd: str,+ *,+ session_id: str = "",+) -> HookResult:+ """Point a path-not-found failure at the file the index says it meant."""+ if tool_name not in _PATH_TOOLS or not isinstance(tool_input, dict):+ return HookResult()+ error_text = _error_text(error)+ if not error_text or _ALREADY_SUGGESTED.search(error_text):+ return HookResult()++ attempted = _failed_path(tool_input, error_text)+ if not attempted or _is_several_paths(attempted):+ return HookResult()++ repo_path = _find_repo_root(Path(cwd)) if cwd else None+ if repo_path is None:+ return HookResult()++ relative = _repo_relative(repo_path, attempted, Path(cwd))+ # A path with no extension is a directory, and "which file did you mean" is+ # not the question it asks. 20 of the 86, left for a surface that can+ # answer them properly.+ if not relative or not Path(relative).suffix:+ return HookResult()++ resolved = _resolve(repo_path, relative)+ if resolved is None:+ return HookResult()++ text = (+ f"[repowise] {relative} is not in this tree. "+ f"The only indexed {relative.rsplit('/', 1)[-1]} is {resolved}"+ )+ _log_wrong_path_firing(repo_path, session_id, text)+ return HookResult(context=text)+++def _log_wrong_path_firing(repo_path: Path, session_id: str, text: str) -> None:+ """Record the firing in the shared ledger; measurement only, never fatal.++ Same contract as the search surfaces: keyed on a hash of the emitted text+ so the transcript classifier can recompute the id from what the agent saw,+ and so one repeated rescue in a session logs once.+ """+ if not session_id:+ return+ try:+ from ._shared import _ledger_key+ from .ledger import _claim_ledger++ _claim_ledger(+ repo_path,+ session_id,+ _ledger_key("wrong_path", "rescue", text),+ node_id="",+ surface="wrong_path",+ category="rescue",+ chars=len(text),+ )+ except Exception:+ returndiff --git a/packages/cli/src/repowise/cli/commands/hook_cmd.py b/packages/cli/src/repowise/cli/commands/hook_cmd.pyindex 73524135c..7594543d5 100644--- a/packages/cli/src/repowise/cli/commands/hook_cmd.py+++ b/packages/cli/src/repowise/cli/commands/hook_cmd.py@@ -706,9 +706,10 @@ def hook_stats(path: str | None, as_json: bool) -> None:is_flag=True,default=False,help=(- "Clear the read/search/fix_history rows before replaying. Run this once "- "after upgrading: rows written under the older ledger keys cannot be "- "matched to a transcript firing and would be counted twice."+ "Clear every transcript-classified surface's rows before replaying. "+ "Run this once after upgrading: rows written under the older ledger "+ "keys cannot be matched to a transcript firing and would be counted "+ "twice. Decision rows are never touched."),)def hook_backfill(path: str | None, all_projects: bool, days: int | None, reset: bool) -> None:diff --git a/packages/cli/src/repowise/cli/editor_integrations/claude_config.py b/packages/cli/src/repowise/cli/editor_integrations/claude_config.pyindex d881b87d1..a89923b2b 100644--- a/packages/cli/src/repowise/cli/editor_integrations/claude_config.py+++ b/packages/cli/src/repowise/cli/editor_integrations/claude_config.py@@ -239,6 +239,13 @@ _AUGMENT_HOOK_COMMAND = ()+# PostToolUseFailure carries the wrong-path rescue. Narrower than+# _AUGMENT_MATCHER on purpose: only the tools that take a path argument can+# fail in the way this surface answers, and a Bash failure is a command line+# rather than a path, so matching it would wake the hook for nothing.+_FAILURE_MATCHER = "Read|Edit|Write|Grep|Glob|NotebookEdit"++def _session_start_entry() -> dict:return {"matcher": _SESSION_START_MATCHER,@@ -253,12 +260,44 @@ def _session_start_entry() -> dict:}+def _backfill_event(hooks: dict, event: str, entry_factory) -> bool:+ """Add this event's augment entry if the install predates it.++ Preserves a user's own hooks on the same event by appending rather than+ replacing, and is a no-op once a repowise entry is present, so migration+ stays idempotent across runs.+ """+ existing = hooks.get(event)+ if existing is None:+ hooks[event] = [entry_factory()]+ return True+ if isinstance(existing, list) and not _has_repowise_hook(existing):+ existing.append(entry_factory())+ return True+ return False+++def _failure_entry() -> dict:+ return {+ "matcher": _FAILURE_MATCHER,+ "hooks": [+ {+ "type": "command",+ "command": _AUGMENT_HOOK_COMMAND,+ "timeout": 10,+ "statusMessage": "Checking codebase context...",+ }+ ],+ }++def install_claude_code_hooks() -> Path | None:- """Register PostToolUse + SessionStart hooks in ~/.claude/settings.json.+ """Register the augment hooks in ~/.claude/settings.json.PostToolUse detects git staleness, enriches Grep/Glob results, and emitsRead-intelligence notices; SessionStart injects the live index-freshness- context block. Existing user hooks are preserved.+ context block; PostToolUseFailure carries the wrong-path rescue. Existing+ user hooks are preserved."""settings_path = _claude_code_settings_path()@@ -299,9 +338,12 @@ def install_claude_code_hooks() -> Path | None:post_hooks.append(post_hook_entry)# SessionStart: live index-freshness context at session start.- session_hooks = hooks.setdefault("SessionStart", [])- if not _has_repowise_hook(session_hooks):- session_hooks.append(_session_start_entry())+ # PostToolUseFailure: the wrong-path rescue.+ # Both go through the same helper as the self-heal, which leaves a+ # hand-written non-list value alone instead of iterating it into an+ # AttributeError the OSError handler below would not catch.+ _backfill_event(hooks, "SessionStart", _session_start_entry)+ _backfill_event(hooks, "PostToolUseFailure", _failure_entry)settings_path.write_text(json.dumps(existing, indent=2) + "\n", encoding="utf-8")return settings_path@@ -554,17 +596,14 @@ def migrate_claude_code_hooks() -> bool:if isinstance(post, list) and _migrate_legacy_hook(post):changed = True- # Users who installed before the SessionStart context hook existed have- # the augment PostToolUse entry but no SessionStart one; backfill it.- # Gated on the augment hook so migration never installs for someone who- # removed repowise hooks on purpose.+ # An install predating one of the later events has the augment PostToolUse+ # entry but not that event's; backfill each. Gated on the augment hook so+ # migration never installs for someone who removed repowise hooks on+ # purpose.if isinstance(post, list) and _has_repowise_hook(post):- session = hooks.get("SessionStart")- if session is None:- hooks["SessionStart"] = [_session_start_entry()]+ if _backfill_event(hooks, "SessionStart", _session_start_entry):changed = True- elif isinstance(session, list) and not _has_repowise_hook(session):- session.append(_session_start_entry())+ if _backfill_event(hooks, "PostToolUseFailure", _failure_entry):changed = Trueif not changed:diff --git a/packages/core/src/repowise/core/sessions/efficacy.py b/packages/core/src/repowise/core/sessions/efficacy.pyindex 85ab05007..ae20cb3d8 100644--- a/packages/core/src/repowise/core/sessions/efficacy.py+++ b/packages/core/src/repowise/core/sessions/efficacy.py@@ -92,7 +92,7 @@ AMBIGUOUS = "ranged_read"#: Surfaces this module judges. ``decision`` rows key on decision-record ids#: and are judged by the decision miner; ``read_enrich`` is a silent KPI with#: no emission to act on.-CLASSIFIED_SURFACES = ("read", "search", "fix_history")+CLASSIFIED_SURFACES = ("read", "search", "fix_history", "wrong_path")#: (surface, category) pairs that carry no recommended action, so an unacted#: firing is not a failure. Reported as a count, excluded from rates. The@@ -211,8 +211,27 @@ _PATTERNS: tuple[tuple[str, str, re.Pattern[str]], ...] = ("digest",re.compile(r"^\[repowise\] Search flood — compact digest"),),+ # Deliberately one line, so ``parse_emission`` — which harvests loose path+ # tokens from continuation lines only — cannot turn the attempted path into+ # a target. The resolved path is the last field and is captured to end of+ # line rather than as ``\S+``: an indexed path can contain a space, and+ # truncating it there both stores a node id that does not exist and leaves+ # a prefix short enough to substring-match almost anything.+ (+ "wrong_path",+ "rescue",+ re.compile(+ r"^\[repowise\] \S+ is not in this tree\. "+ r"The only indexed \S+ is (?P<target>.+)$"+ ),+ ),)+#: The attempted path from a wrong-path rescue, for the judge below. Read off+#: the emission rather than carried on :class:`Firing`, which has no field for+#: "what this firing was steering the agent away from".+_WRONG_PATH_ATTEMPTED = re.compile(r"^\[repowise\] (?P<attempted>\S+) is not in this tree\.")+#: A path-shaped token, for harvesting the file lists that follow a triage#: header or ride inside a digest body. Both separators are accepted: triage#: renders repo-relative POSIX node ids, but the digest groups whatever@@ -291,8 +310,16 @@ def parse_emission(text: str) -> list[Firing]:def _normalize(path: str) -> str:- """Repo-relative POSIX spelling, as the ledger's node ids use."""- return path.replace("\\\\", "/").replace("\\", "/").lstrip("./").rstrip(".,;:")+ """Repo-relative POSIX spelling, as the ledger's node ids use.++ ``removeprefix`` rather than ``lstrip``, which strips a character *set*:+ it turned ``.github/workflows/ci.yml`` into ``github/...``, storing a node+ id no repository has and widening the target to a substring that matches+ more than it should.+ """+ return (+ path.replace("\\\\", "/").replace("\\", "/").removeprefix("./").rstrip(".,;:")+ )# ---------------------------------------------------------------------------@@ -335,6 +362,7 @@ def classify(firing: Firing, following: list[tuple[str, str]]) -> Firing:("search", "rescue_wide"): _acted_rescue,("search", "digest"): _acted_target,("fix_history", "edit_notice"): _acted_fix_history,+ ("wrong_path", "rescue"): _acted_wrong_path,}.get((firing.surface, firing.category))if judge is None:firing.acted = None@@ -407,6 +435,23 @@ def _acted_target(firing: Firing, name: str, norm: str, raw: str) -> str:return ""+def _acted_wrong_path(firing: Firing, name: str, norm: str, raw: str) -> str:+ """Went where it pointed — and retrying the failed path is not that.++ ``_acted_target`` is an unanchored substring test, so it cannot be used+ here alone: whenever the attempted path *contains* the resolved one (the+ agent guessed an extra directory in front of a real file, which is half of+ this surface's corpus), a verbatim retry of the failed path matches the+ target and scores as compliance. Disqualifying the attempted path first is+ what keeps the rate about the rescue rather than about the mistake.+ """+ m = _WRONG_PATH_ATTEMPTED.match(firing.text)+ attempted = _normalize(m.group("attempted")) if m else ""+ if attempted and attempted in norm:+ return ""+ return _acted_target(firing, name, norm, raw)++def _acted_rescue(firing: Firing, name: str, norm: str, raw: str) -> str:"""The rescued file, or the symbol name it offered."""hit = _acted_target(firing, name, norm, raw)diff --git a/plugins/claude-code/hooks/hooks.json b/plugins/claude-code/hooks/hooks.jsonindex 960bea5c6..a2b717179 100644--- a/plugins/claude-code/hooks/hooks.json+++ b/plugins/claude-code/hooks/hooks.json@@ -25,6 +25,19 @@}]}+ ],+ "PostToolUseFailure": [+ {+ "matcher": "Read|Edit|Write|Grep|Glob|NotebookEdit",+ "hooks": [+ {+ "type": "command",+ "command": "if command -v repowise-augment >/dev/null 2>&1; then exec repowise-augment; fi",+ "timeout": 10,+ "statusMessage": "Checking codebase context..."+ }+ ]+ }]}}diff --git a/tests/unit/cli/test_augment_hook_perf.py b/tests/unit/cli/test_augment_hook_perf.pyindex 29effae44..aa65e1ed1 100644--- a/tests/unit/cli/test_augment_hook_perf.py+++ b/tests/unit/cli/test_augment_hook_perf.py@@ -278,6 +278,50 @@ def test_a_triage_that_queries_the_index_imports_nothing_heavy(tmp_path: Path) -assert out.stderr.strip() == "", f"a triage emission pulled in:\n{out.stderr}"+def test_a_wrong_path_rescue_imports_nothing_heavy(tmp_path: Path) -> None:+ """The failure surface reaches the index too, on the same cheap graph.++ Its basename lookup is the fourth caller of ``fast_lookup``; this is the+ guard that keeps it from reaching for the ORM the moment someone finds a+ query easier to write there. Like the triage guard, it can only pass by+ actually emitting.+ """+ repo = _indexed_search_repo(tmp_path)+ # The rescue only names a file it can still see on disk, so the indexed+ # node needs a real one behind it here.+ (repo / "src").mkdir(parents=True, exist_ok=True)+ (repo / "src" / "b.py").write_text("x", encoding="utf-8")+ attempted = repo / "src" / "nested" / "b.py"+ payload = {+ "hook_event_name": "PostToolUseFailure",+ "tool_name": "Read",+ "tool_input": {"file_path": str(attempted)},+ "error": (+ f"<tool_use_error>Path does not exist: {attempted}. "+ f"Note: your current working directory is {repo}.</tool_use_error>"+ ),+ "cwd": str(repo),+ "session_id": "perf",+ }+ code = (+ "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); "+ 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 "is not in this tree" in out.stdout, "the probe did not reach a rescue"+ assert out.stderr.strip() == "", f"a wrong-path rescue 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_wrong_path.py b/tests/unit/cli/test_augment_wrong_path.pynew file mode 100644index 000000000..774164e7f--- /dev/null+++ b/tests/unit/cli/test_augment_wrong_path.py@@ -0,0 +1,380 @@+"""The wrong-path rescue: what it says, and the eight ways it stays quiet.++Weighted towards silence on purpose. The surface's whole value is that a+rescue can be trusted, so every rule that drops a candidate has a test naming+the failure it prevents — measured against 435 transcripts of this repo, where+86 path-not-found failures on the file tools reduce to 18 this speaks to.+"""++from __future__ import annotations++import io+import json+import os+import sqlite3+import sys+import tempfile+from pathlib import Path+from unittest.mock import patch++from repowise.cli.commands.augment_cmd import _run_augment+from repowise.cli.commands.augment_cmd.wrong_path import _handle_tool_failure+++def _run_hook(payload: dict, tmp_path: Path) -> str:+ """Drive the real stdin/stdout entry point, so the dispatch is under test.++ ``TMPDIR`` is redirected because ``_emit_response`` dedupes identical+ emissions for 8 seconds through a marker in the *system* temp directory,+ keyed on the text alone. The rescue text is all repo-relative paths, so+ two runs of this test inside 8 seconds would collide with each other and+ the second would see silence.+ """+ out = io.StringIO()+ env = {v: str(tmp_path) for v in ("TMPDIR", "TEMP", "TMP")}+ with patch.dict(os.environ, env), patch.object(+ sys, "stdin", io.StringIO(json.dumps(payload))+ ), patch.object(sys, "stdout", out):+ tempfile.tempdir = None+ _run_augment(client=None)+ tempfile.tempdir = None+ return out.getvalue()++PATH_ERROR = (+ "<tool_use_error>Path does not exist: {path}. "+ "Note: your current working directory is {cwd}.</tool_use_error>"+)+FILE_ERROR = "File does not exist. Note: your current working directory is {cwd}"+++def _repo(tmp_path: Path, files: tuple[str, ...] = ()) -> Path:+ """A repo whose index knows *files*, and whose disk carries them too."""+ repo = tmp_path / "repo"+ (repo / ".repowise").mkdir(parents=True)+ con = sqlite3.connect(repo / ".repowise" / "wiki.db")+ con.execute("CREATE TABLE repositories (id TEXT, local_path TEXT)")+ con.execute("INSERT INTO repositories VALUES ('r1', ?)", (str(repo),))+ con.execute(+ "CREATE TABLE graph_nodes (repository_id TEXT, node_id TEXT, node_type TEXT, "+ "pagerank REAL)"+ )+ for node_id in files:+ con.execute("INSERT INTO graph_nodes VALUES ('r1', ?, 'file', 0.5)", (node_id,))+ on_disk = repo / node_id+ on_disk.parent.mkdir(parents=True, exist_ok=True)+ on_disk.write_text("x", encoding="utf-8")+ con.commit()+ con.close()+ return repo+++def _fire(repo: Path, attempted: str, *, tool: str = "Read", error: str | None = None):+ if error is None:+ error = PATH_ERROR.format(path=attempted, cwd=repo)+ return _handle_tool_failure(+ tool,+ {"file_path": attempted},+ error,+ str(repo),+ session_id="s1",+ )+++# --- the one thing it says -------------------------------------------------+++def test_names_the_only_file_carrying_that_basename(tmp_path: Path) -> None:+ """The measured shape: a real file, guessed under the wrong directory."""+ repo = _repo(tmp_path, ("core/ingestion/git_indexer/fix_events.py",))+ result = _fire(repo, str(repo / "core" / "git_indexer" / "fix_events.py"))+ assert result.context == (+ "[repowise] core/git_indexer/fix_events.py is not in this tree. "+ "The only indexed fix_events.py is core/ingestion/git_indexer/fix_events.py"+ )+++def test_a_relative_attempt_is_resolved_against_cwd(tmp_path: Path) -> None:+ """The tool resolved it against cwd, so the rescue has to as well."""+ repo = _repo(tmp_path, ("src/deep/config_loader.py",))+ result = _fire(repo, "src/config_loader.py")+ assert result.context is not None+ assert "src/deep/config_loader.py" in result.context+++def test_the_grep_error_shape_is_read_too(tmp_path: Path) -> None:+ """Grep names the path in the error; Read does not. Both must work."""+ repo = _repo(tmp_path, ("packages/ui/shared/table.tsx",))+ result = _handle_tool_failure(+ "Grep",+ {"pattern": "x", "path": str(repo / "packages" / "table.tsx")},+ PATH_ERROR.format(path=repo / "packages" / "table.tsx", cwd=repo),+ str(repo),+ session_id="s1",+ )+ assert result.context is not None+ assert "packages/ui/shared/table.tsx" in result.context+++def test_the_read_error_shape_takes_the_path_from_tool_input(tmp_path: Path) -> None:+ """"File does not exist." carries no path; tool_input is the only source."""+ repo = _repo(tmp_path, ("a/b/widget.py",))+ result = _fire(+ repo, str(repo / "a" / "widget.py"), error=FILE_ERROR.format(cwd=repo)+ )+ assert result.context is not None+ assert "a/b/widget.py" in result.context+++# --- and the ways it does not ---------------------------------------------+++def test_an_ambiguous_basename_stays_silent(tmp_path: Path) -> None:+ """Naming one of three registry.py confidently is the failure to avoid."""+ repo = _repo(tmp_path, ("a/registry.py", "b/registry.py", "c/registry.py"))+ assert not _fire(repo, str(repo / "core" / "registry.py"))+++def test_a_directory_target_stays_silent(tmp_path: Path) -> None:+ """"Which file did you mean" is not the question a directory asks."""+ repo = _repo(tmp_path, ("core/hooks/handler.py",))+ assert not _fire(repo, str(repo / "cli" / "hooks"))+++def test_a_path_in_another_checkout_stays_silent(tmp_path: Path) -> None:+ """A sibling worktree has its own index; this one cannot answer for it."""+ repo = _repo(tmp_path, ("packages/types/src/overview.ts",))+ other = tmp_path / "repowise-restyle" / "packages" / "types" / "overview.ts"+ assert not _fire(repo, str(other))+++def test_a_relative_escape_to_another_checkout_stays_silent(tmp_path: Path) -> None:+ """The same sibling, spelled relatively, must not slip past containment.++ A character-set ``lstrip("./")`` turned "../repowise-restyle/x.ts" into a+ path that looked repo-relative, and this tree answered for the other one.+ """+ repo = _repo(tmp_path, ("packages/types/src/overview.ts",))+ assert not _fire(repo, "../repowise-restyle/packages/types/overview.ts")+++def test_a_dot_directory_keeps_its_dot(tmp_path: Path) -> None:+ """".github/ci.yml" must not be echoed back as "github/ci.yml"."""+ repo = _repo(tmp_path, (".github/workflows/ci.yml",))+ result = _fire(repo, ".github/ci.yml")+ assert result.context is not None+ assert result.context.startswith("[repowise] .github/ci.yml is not in this tree.")+++def test_a_repo_under_a_path_with_spaces_still_rescues(tmp_path: Path) -> None:+ """A checkout under "Foo Bar" must not silence the surface entirely.++ Every absolute path in such a tree contains a space, so a blanket+ whitespace guard takes recall to zero rather than reducing it.+ """+ spaced = tmp_path / "Foo Bar"+ spaced.mkdir()+ repo = _repo(spaced, ("core/deep/fix_events.py",))+ result = _fire(repo, str(repo / "core" / "fix_events.py"))+ assert result.context is not None+ assert "core/deep/fix_events.py" in result.context+++def test_a_stale_row_does_not_hide_the_live_answer(tmp_path: Path) -> None:+ """Two indexed rows, one deleted, is still one live answer."""+ repo = _repo(tmp_path, ("core/deep/fix_events.py",))+ con = sqlite3.connect(repo / ".repowise" / "wiki.db")+ con.execute("INSERT INTO graph_nodes VALUES ('r1', 'old/fix_events.py', 'file', 0.5)")+ con.commit()+ con.close()+ result = _fire(repo, str(repo / "core" / "fix_events.py"))+ assert result.context is not None+ assert "core/deep/fix_events.py" in result.context+++def test_an_external_package_node_is_not_a_path(tmp_path: Path) -> None:+ """graph_nodes carries resolved external packages under node_type 'file'."""+ repo = _repo(tmp_path, ("src/real/config.py",))+ con = sqlite3.connect(repo / ".repowise" / "wiki.db")+ con.execute("INSERT INTO graph_nodes VALUES ('r1', 'external:vendor/config.py', 'file', 0.5)")+ con.commit()+ con.close()+ result = _fire(repo, str(repo / "src" / "config.py"))+ assert result.context is not None+ assert "src/real/config.py" in result.context+++def test_an_error_that_already_suggests_stays_silent(tmp_path: Path) -> None:+ """Claude Code printed its own answer; repeating it is worse than nothing."""+ repo = _repo(tmp_path, ("src/shared/responsive-table.tsx",))+ error = FILE_ERROR.format(cwd=repo) + " Did you mean responsive-table?"+ assert not _fire(repo, str(repo / "responsive-table.tsx"), error=error)+++def test_it_never_restates_the_path_that_just_failed(tmp_path: Path) -> None:+ """The index can hold a row for a file that is not on disk right now."""+ repo = _repo(tmp_path)+ con = sqlite3.connect(repo / ".repowise" / "wiki.db")+ con.execute("INSERT INTO graph_nodes VALUES ('r1', 'src/gone.py', 'file', 0.5)")+ con.commit()+ con.close()+ assert not _fire(repo, str(repo / "src" / "gone.py"))+++def test_an_indexed_row_with_no_file_on_disk_stays_silent(tmp_path: Path) -> None:+ """A stale row must not send the agent to a path that is also missing."""+ repo = _repo(tmp_path)+ con = sqlite3.connect(repo / ".repowise" / "wiki.db")+ con.execute("INSERT INTO graph_nodes VALUES ('r1', 'src/deep/gone.py', 'file', 0.5)")+ con.commit()+ con.close()+ assert not _fire(repo, str(repo / "src" / "gone.py"))+++def test_several_paths_in_one_grep_argument_stay_silent(tmp_path: Path) -> None:+ """The basename of whichever landed last is not what was asked for."""+ repo = _repo(tmp_path, ("tests/unit/cli/test_one.py",))+ both = f"{repo / 'tests' / 'test_two.py'} {repo / 'tests' / 'test_one.py'}"+ assert not _fire(repo, both, tool="Grep")+++def test_an_unresolvable_basename_stays_silent(tmp_path: Path) -> None:+ repo = _repo(tmp_path, ("src/other.py",))+ assert not _fire(repo, str(repo / "src" / "missing.py"))+++def test_a_bash_failure_is_not_this_surface(tmp_path: Path) -> None:+ """Its input is a command line, not a path; a different problem."""+ repo = _repo(tmp_path, ("src/deep/thing.py",))+ result = _handle_tool_failure(+ "Bash",+ {"command": "cat src/thing.py"},+ "Exit code 1\ncat: src/thing.py: No such file or directory",+ str(repo),+ session_id="s1",+ )+ assert not result+++def test_a_failure_that_is_not_about_a_path_stays_silent(tmp_path: Path) -> None:+ """Edit's commonest failure names no path at all."""+ repo = _repo(tmp_path, ("src/deep/thing.py",))+ result = _handle_tool_failure(+ "Edit",+ {"file_path": str(repo / "src" / "deep" / "thing.py")},+ "<tool_use_error>String to replace not found in file.\nString: foo",+ str(repo),+ session_id="s1",+ )+ assert not result+++def test_no_index_stays_silent(tmp_path: Path) -> None:+ """No wiki.db is the ordinary state of a repo that never ran init."""+ repo = tmp_path / "repo"+ (repo / ".repowise").mkdir(parents=True)+ assert not _fire(repo, str(repo / "src" / "thing.py"))+++def test_a_dict_error_is_unwrapped(tmp_path: Path) -> None:+ """The rejection comes through verbatim from the tool, not the harness."""+ repo = _repo(tmp_path, ("core/deep/fix_events.py",))+ attempted = str(repo / "core" / "fix_events.py")+ result = _handle_tool_failure(+ "Read",+ {"file_path": attempted},+ {"message": PATH_ERROR.format(path=attempted, cwd=repo)},+ str(repo),+ session_id="s1",+ )+ assert result.context is not None+++def test_an_error_shape_we_cannot_read_stays_silent(tmp_path: Path) -> None:+ repo = _repo(tmp_path, ("core/deep/fix_events.py",))+ assert not _handle_tool_failure(+ "Read",+ {"file_path": str(repo / "core" / "fix_events.py")},+ {"code": 42},+ str(repo),+ session_id="s1",+ )+++# --- the event, end to end -------------------------------------------------+++def test_the_hook_reads_the_error_field_not_tool_response(tmp_path: Path) -> None:+ """PostToolUseFailure carries ``error``; ``tool_response`` is PostToolUse+ only, and reading the wrong one is a surface that never fires."""+ repo = _repo(tmp_path, ("core/deep/fix_events.py",))+ attempted = str(repo / "core" / "fix_events.py")+ payload = {+ "hook_event_name": "PostToolUseFailure",+ "tool_name": "Read",+ "tool_input": {"file_path": attempted},+ "error": PATH_ERROR.format(path=attempted, cwd=repo),+ "cwd": str(repo),+ "session_id": "s1",+ }+ assert "is not in this tree" in _run_hook(payload, tmp_path)+++def test_an_interrupt_is_not_a_failure_to_rescue(tmp_path: Path) -> None:+ """The event fires when the user presses escape too. Answering that is+ noise at the exact moment someone asked for quiet."""+ repo = _repo(tmp_path, ("core/deep/fix_events.py",))+ attempted = str(repo / "core" / "fix_events.py")+ payload = {+ "hook_event_name": "PostToolUseFailure",+ "tool_name": "Read",+ "tool_input": {"file_path": attempted},+ "error": PATH_ERROR.format(path=attempted, cwd=repo),+ "is_interrupt": True,+ "cwd": str(repo),+ "session_id": "s1",+ }+ assert _run_hook(payload, tmp_path) == ""+++# --- the ledger ------------------------------------------------------------+++def test_a_firing_is_recorded_under_its_own_surface(tmp_path: Path) -> None:+ """A surface that cannot report an efficacy rate does not ship."""+ repo = _repo(tmp_path, ("core/deep/fix_events.py",))+ assert _fire(repo, str(repo / "core" / "fix_events.py"))+ con = sqlite3.connect(repo / ".repowise" / "sessions" / "sessions.db")+ rows = con.execute(+ "SELECT surface, category, chars FROM injections WHERE session_id = 's1'"+ ).fetchall()+ con.close()+ assert len(rows) == 1+ surface, category, chars = rows[0]+ assert (surface, category) == ("wrong_path", "rescue")+ assert chars > 0+++def test_the_same_rescue_twice_in_a_session_logs_once(tmp_path: Path) -> None:+ repo = _repo(tmp_path, ("core/deep/fix_events.py",))+ attempted = str(repo / "core" / "fix_events.py")+ assert _fire(repo, attempted)+ assert _fire(repo, attempted)+ con = sqlite3.connect(repo / ".repowise" / "sessions" / "sessions.db")+ (count,) = con.execute(+ "SELECT COUNT(*) FROM injections WHERE session_id = 's1'"+ ).fetchone()+ con.close()+ assert count == 1+++def test_no_session_id_still_rescues(tmp_path: Path) -> None:+ """Measurement is a sidecar; losing it must not cost the enrichment."""+ repo = _repo(tmp_path, ("core/deep/fix_events.py",))+ result = _handle_tool_failure(+ "Read",+ {"file_path": str(repo / "core" / "fix_events.py")},+ PATH_ERROR.format(path=repo / "core" / "fix_events.py", cwd=repo),+ str(repo),+ session_id="",+ )+ assert result.context is not Nonediff --git a/tests/unit/cli/test_claude_plugin.py b/tests/unit/cli/test_claude_plugin.pyindex 21ced1877..cdbcdfdeb 100644--- a/tests/unit/cli/test_claude_plugin.py+++ b/tests/unit/cli/test_claude_plugin.py@@ -57,6 +57,12 @@ def test_claude_plugin_hooks_match_installer() -> None:assert rows("PostToolUse") == [(claude_config._AUGMENT_MATCHER, command)]assert rows("SessionStart") == [(claude_config._SESSION_START_MATCHER, command)]+ assert rows("PostToolUseFailure") == [(claude_config._FAILURE_MATCHER, command)]++ # Every event the installer registers, and nothing else: a surface that+ # ships only to fresh CLI installs and not to the plugin is the failure+ # this guards, and it is invisible from either side alone.+ assert set(hooks) == {"PostToolUse", "SessionStart", "PostToolUseFailure"}commands = [hook["command"]@@ -64,7 +70,7 @@ def test_claude_plugin_hooks_match_installer() -> None:for entry in entriesfor hook in entry["hooks"]]- assert commands == [command] * 2+ assert commands == [command] * len(hooks)def _posix_bash() -> str | None:diff --git a/tests/unit/cli/test_mcp_config.py b/tests/unit/cli/test_mcp_config.pyindex 6c7b199c8..cd0e0c1dc 100644--- a/tests/unit/cli/test_mcp_config.py+++ b/tests/unit/cli/test_mcp_config.py@@ -382,22 +382,22 @@ def test_save_root_mcp_config_preserves_user_env_block(tmp_path: Path) -> None:# ----------------------------------------------------------------------------def _post_repowise_entries(saved: dict) -> list:+def _repowise_entries(saved: dict, event: str) -> list:+ """``(matcher, command)`` for the repowise hooks registered on *event*."""return [(entry.get("matcher"), h["command"])- for entry in saved["hooks"].get("PostToolUse", [])+ for entry in saved["hooks"].get(event, [])for h in entry["hooks"]if "repowise" in h.get("command", "")]+def _post_repowise_entries(saved: dict) -> list:+ return _repowise_entries(saved, "PostToolUse")++def _session_start_repowise_entries(saved: dict) -> list:- return [- (entry.get("matcher"), h["command"])- for entry in saved["hooks"].get("SessionStart", [])- for h in entry["hooks"]- if "repowise" in h.get("command", "")- ]+ return _repowise_entries(saved, "SessionStart")def test_install_claude_code_hooks_creates_missing_file(@@ -419,6 +419,17 @@ def test_install_claude_code_hooks_creates_missing_file(assert _session_start_repowise_entries(saved) == [("startup|resume|clear", claude_config._AUGMENT_HOOK_COMMAND)]+ assert _repowise_entries(saved, "PostToolUseFailure") == [+ (claude_config._FAILURE_MATCHER, claude_config._AUGMENT_HOOK_COMMAND)+ ]+++def test_the_failure_matcher_covers_only_tools_that_take_a_path() -> None:+ """A Bash failure is a command line, not a path, and would wake the hook+ for a question this surface cannot answer."""+ matched = set(claude_config._FAILURE_MATCHER.split("|"))+ assert matched == {"Read", "Edit", "Write", "Grep", "Glob", "NotebookEdit"}+ assert "Bash" not in matched and "PowerShell" not in matcheddef test_install_claude_code_hooks_preserves_user_pretool_hooks(@@ -664,8 +675,9 @@ def test_migrate_claude_code_hooks_never_widens_user_matcher(],}],- # SessionStart already present so its backfill (a separate- # migration) can't mask the matcher no-op under test.+ # SessionStart and PostToolUseFailure already present so+ # their backfills (separate migrations) can't mask the+ # matcher no-op under test."SessionStart": [{"matcher": "startup|resume|clear",@@ -677,6 +689,7 @@ def test_migrate_claude_code_hooks_never_widens_user_matcher(],}],+ "PostToolUseFailure": [claude_config._failure_entry()],}}),@@ -746,6 +759,7 @@ def test_migrate_claude_code_hooks_noop_when_already_current("hooks": [{"type": "command", "command": claude_config._AUGMENT_HOOK_COMMAND}],}],+ "PostToolUseFailure": [claude_config._failure_entry()],}}original = json.dumps(payload, indent=2) + "\n"@@ -791,6 +805,88 @@ def test_migrate_claude_code_hooks_backfills_session_start(assert claude_config.migrate_claude_code_hooks() is False+def test_migrate_backfills_the_failure_hook_for_older_installs(+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch+) -> None:+ """An install predating PostToolUseFailure gains it on self-heal.++ Without this the surface only ever reaches people who install fresh, which+ is the smaller half of the population and the harder one to notice.+ """+ monkeypatch.setattr(Path, "home", lambda: tmp_path)+ settings_path = tmp_path / ".claude" / "settings.json"+ settings_path.parent.mkdir(parents=True)+ settings_path.write_text(+ json.dumps(+ {+ "hooks": {+ "PostToolUse": [+ {+ "matcher": claude_config._AUGMENT_MATCHER,+ "hooks": [+ {+ "type": "command",+ "command": claude_config._AUGMENT_HOOK_COMMAND,+ }+ ],+ }+ ],+ "SessionStart": [claude_config._session_start_entry()],+ }+ }+ ),+ encoding="utf-8",+ )++ assert claude_config.migrate_claude_code_hooks() is True+ saved = json.loads(settings_path.read_text(encoding="utf-8"))+ assert _repowise_entries(saved, "PostToolUseFailure") == [+ (claude_config._FAILURE_MATCHER, claude_config._AUGMENT_HOOK_COMMAND)+ ]+ assert claude_config.migrate_claude_code_hooks() is False+++def test_migrate_preserves_a_user_failure_hook(+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch+) -> None:+ """A user's own PostToolUseFailure hook is kept; the repowise entry appends."""+ monkeypatch.setattr(Path, "home", lambda: tmp_path)+ settings_path = tmp_path / ".claude" / "settings.json"+ settings_path.parent.mkdir(parents=True)+ settings_path.write_text(+ json.dumps(+ {+ "hooks": {+ "PostToolUse": [+ {+ "matcher": claude_config._AUGMENT_MATCHER,+ "hooks": [+ {+ "type": "command",+ "command": claude_config._AUGMENT_HOOK_COMMAND,+ }+ ],+ }+ ],+ "SessionStart": [claude_config._session_start_entry()],+ "PostToolUseFailure": [+ {"hooks": [{"type": "command", "command": "echo mine"}]}+ ],+ }+ }+ ),+ encoding="utf-8",+ )++ assert claude_config.migrate_claude_code_hooks() is True+ saved = json.loads(settings_path.read_text(encoding="utf-8"))+ failure = saved["hooks"]["PostToolUseFailure"]+ assert failure[0]["hooks"][0]["command"] == "echo mine"+ assert _repowise_entries(saved, "PostToolUseFailure") == [+ (claude_config._FAILURE_MATCHER, claude_config._AUGMENT_HOOK_COMMAND)+ ]++def test_migrate_claude_code_hooks_no_session_start_without_augment(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:@@ -817,6 +913,7 @@ def test_migrate_claude_code_hooks_no_session_start_without_augment(assert claude_config.migrate_claude_code_hooks() is Falsesaved = json.loads(settings_path.read_text(encoding="utf-8"))assert "SessionStart" not in saved["hooks"]+ assert "PostToolUseFailure" not in saved["hooks"]def test_migrate_claude_code_hooks_preserves_user_session_start(diff --git a/tests/unit/sessions/test_efficacy.py b/tests/unit/sessions/test_efficacy.pyindex 8f04bf673..aaa58f9c5 100644--- a/tests/unit/sessions/test_efficacy.py+++ b/tests/unit/sessions/test_efficacy.py@@ -37,6 +37,10 @@ RESCUE = ("[repowise] No literal match for `parseYaml`. Closest indexed symbol: ""function `parse_yaml` in pkg/core/loader.py:12")+WRONG_PATH = (+ "[repowise] pkg/core/fix_events.py is not in this tree. "+ "The only indexed fix_events.py is pkg/core/ingestion/fix_events.py"+)TRIAGE_V2 = ("[repowise] 40+ matches for `parse_yaml` across 12 files. Most likely relevant, ""ranked over the files your search matched:\n"@@ -179,6 +183,65 @@ def test_rescue_counts_the_offered_symbol_as_well_as_the_file():assert firing.acted is True+def test_a_wrong_path_rescue_is_acted_on_by_going_where_it_pointed():+ (firing,) = parse_emission(WRONG_PATH)+ assert (firing.surface, firing.category) == ("wrong_path", "rescue")+ classify(firing, [_use("Read", file_path="/repo/pkg/core/ingestion/fix_events.py")])+ assert (firing.acted, firing.evidence) == (True, "touched_rank0")+++def test_retrying_the_path_that_failed_is_not_acting_on_the_rescue():+ """The attempted path shares the line with the answer and must not count.++ ``parse_emission`` harvests loose path tokens from continuation lines, so+ a rescue that ever grows a second line would silently start crediting the+ agent for repeating the mistake. One line, one captured target.+ """+ (firing,) = parse_emission(WRONG_PATH)+ assert firing.targets == ["pkg/core/ingestion/fix_events.py"]+ classify(firing, [_use("Read", file_path="/repo/pkg/core/fix_events.py")])+ assert firing.acted is False+++def test_a_retry_that_contains_the_answer_is_still_not_acting():+ """Half this surface's corpus is an extra directory in front of a real+ file, so the attempted path *contains* the resolved one. A substring judge+ scores a verbatim retry as compliance; this is the guard against that."""+ (firing,) = parse_emission(+ "[repowise] packages/docs/guide.md is not in this tree. "+ "The only indexed guide.md is docs/guide.md"+ )+ assert firing.targets == ["docs/guide.md"]+ classify(firing, [_use("Read", file_path="/repo/packages/docs/guide.md")])+ assert firing.acted is False+ # Going where it actually pointed still counts.+ (firing,) = parse_emission(+ "[repowise] packages/docs/guide.md is not in this tree. "+ "The only indexed guide.md is docs/guide.md"+ )+ classify(firing, [_use("Read", file_path="/repo/docs/guide.md")])+ assert firing.acted is True+++def test_a_resolved_path_containing_a_space_is_not_truncated():+ """An indexed path can contain a space; ``\\S+`` would keep "packages/My"+ and substring-match nearly every later tool call in that repo."""+ (firing,) = parse_emission(+ "[repowise] src/config.py is not in this tree. "+ "The only indexed config.py is packages/My App/config.py"+ )+ assert firing.targets == ["packages/My App/config.py"]+++def test_normalize_keeps_a_leading_dot_directory():+ """``lstrip("./")`` strips a character set and ate the dot."""+ (firing,) = parse_emission(+ "[repowise] ci.yml is not in this tree. "+ "The only indexed ci.yml is .github/workflows/ci.yml"+ )+ assert firing.targets == [".github/workflows/ci.yml"]++def test_fix_history_acted_on_a_test_run_or_a_history_look():for call, evidence in ((_use("Bash", command="pytest tests/unit/core"), "ran_test"),