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): SessionStart context block, safe-pipeline distill rewrites, doctor registration check (#743)
Raghav Chamadiyaa759cf20c2ff
diff --git a/docs/DISTILL.md b/docs/DISTILL.mdindex 86e9c445a..5e5cad244 100644--- a/docs/DISTILL.md+++ b/docs/DISTILL.md@@ -111,7 +111,12 @@ and restores your AGENTS.md byte-for-byte.The hook is deliberately conservative. It never rewrites:-- pipes, redirections, compound commands (`|`, `>`, `&&`, `;`, backticks, `$()`)+- redirections, compound commands (`>`, `&&`, `;`, backticks, `$()`) and+ almost all pipes. Two safe shapes are carved out: a trailing `2>&1`+ (distill merges stderr into its capture anyway), and, on macOS/Linux only,+ a single pipe into bare `head`/`tail`, which runs unchanged inside+ distill's own shell (`pytest -q | head -50` →+ `repowise distill "pytest -q | head -50"`)- watch/follow modes (`--watch`, `tail -f`, …)- anything on the trivial-command ignore-list, or already-prefixed commands- PowerShell-native constructs: `Verb-Noun` cmdlets, `& "path"` invocations,diff --git a/docs/USER_GUIDE.md b/docs/USER_GUIDE.mdindex caacbeb03..7b062f24e 100644--- a/docs/USER_GUIDE.md+++ b/docs/USER_GUIDE.md@@ -868,7 +868,8 @@ Claude Code hooks are written to `~/.claude/settings.json` automatically during| Hook type | Matcher | Action ||-----------|---------|--------|-| Claude `PostToolUse` | `Bash\|Grep\|Glob` | Check git freshness and add search rescue/triage context |+| Claude `SessionStart` | `startup\|resume\|clear` | Inject live index freshness (current / behind with a changed-file count / update in progress) and the core-tool trust rule |+| Claude `PostToolUse` | `Bash\|PowerShell\|Grep\|Glob\|Read\|Edit\|Write` | Check git freshness, add search rescue/triage context, and emit Read-intelligence notices || Codex `SessionStart` / `UserPromptSubmit` | lifecycle | Remind Codex to use Repowise MCP tools || Codex `PostToolUse` | `Bash`, `apply_patch\|Edit\|Write` | Check git/edit freshness |diff --git a/packages/cli/src/repowise/cli/commands/augment_cmd/command.py b/packages/cli/src/repowise/cli/commands/augment_cmd/command.pyindex f45e8ab29..2bac2af29 100644--- a/packages/cli/src/repowise/cli/commands/augment_cmd/command.py+++ b/packages/cli/src/repowise/cli/commands/augment_cmd/command.py@@ -23,6 +23,12 @@ asymmetric, durable value:Codex SessionStart/UserPromptSubmit: adds short repowise MCP usage guidance.+ SessionStart (Claude Code)+ * Emits a one-paragraph context block: whether the index is current,+ behind (with a changed-file count), or mid-update, plus the core-tool+ trust rule. CLAUDE.md stays static and cache-friendly; live freshness+ arrives here instead.+PostToolUse → Bash* After a successful git commit/merge/rebase/cherry-pick/pull, ifthe wiki HEAD has drifted from .repowise/state.json's last sync@@ -74,6 +80,7 @@ from .bash_staleness import _handle_bash_postfrom .codex import _handle_codex_context_event, _handle_post_edit_usefrom .read_state import _handle_read_post, _record_editfrom .search import _handle_search_post+from .session_start import _handle_claude_session_start_EDIT_TOOL_NAMES = {"apply_patch", "Edit", "Write"}@@ -118,6 +125,13 @@ def _run_augment(*, client: str | None = None) -> None:_emit_response(event, result)return+ if event == "SessionStart":+ # Claude Code lifecycle hook: live index-freshness + trust context.+ result = _handle_claude_session_start(cwd)+ if result:+ _emit_response(event, result)+ return+if event != "PostToolUse":returndiff --git a/packages/cli/src/repowise/cli/commands/augment_cmd/session_start.py b/packages/cli/src/repowise/cli/commands/augment_cmd/session_start.pynew file mode 100644index 000000000..2aa80be86--- /dev/null+++ b/packages/cli/src/repowise/cli/commands/augment_cmd/session_start.py@@ -0,0 +1,119 @@+"""Claude Code SessionStart: index freshness + tool-protocol context block.++The generated CLAUDE.md is static between reindexes; what it cannot carry is+whether the index is current *right now*. This handler closes that gap with a+short per-session block so the agent starts with calibrated trust instead of+discovering staleness mid-task:++ * index current → one line saying so, plus the core-tool pointer;+ * update running → positive "catching up" notice (never a stale scare);+ * index behind → indexed vs HEAD with a changed-file count, and the+ target-scoped trust rule (stale_warning only when a served file changed).++Deliberately no hotspot/health lines here: CLAUDE.md already carries those+statically, and this block is re-billed every session; freshness is the only+signal that must be live.++Same operational rules as the rest of augment: stdlib + git subprocess only,+any failure returns None, and a git failure never produces a false "current"+claim (it degrades to the freshness-free reminder).+"""++from __future__ import annotations++import json+from pathlib import Path++from ._shared import _find_repo_root+from .bash_staleness import _read_in_flight_marker++_CORE_TOOLS = "get_answer, get_context, get_symbol, search_codebase, get_risk"+++def _handle_claude_session_start(cwd: str) -> str | None:+ """Return the session context block, or None outside indexed repos."""+ repo_path = _find_repo_root(Path(cwd))+ if repo_path is None:+ return None+ try:+ state = json.loads((repo_path / ".repowise" / "state.json").read_text(encoding="utf-8"))+ except (OSError, json.JSONDecodeError):+ return None+ last_sync = state.get("last_sync_commit")+ if not isinstance(last_sync, str) or not last_sync:+ return None++ head = _git_head(repo_path)+ if head is None:+ return (+ "[repowise] This repository has a local codebase index. Prefer the "+ f"repowise MCP tools ({_CORE_TOOLS}) over raw file reads for locating "+ "and understanding code before you edit."+ )++ if head == last_sync:+ return (+ f"[repowise] Codebase index is current (HEAD {head[:8]}). The MCP tools "+ f"({_CORE_TOOLS}) serve content verified against this exact tree; prefer "+ "them over raw file reads for locating and understanding code before you edit."+ )++ in_flight = _read_in_flight_marker(repo_path)+ if in_flight is not None:+ elapsed = in_flight.get("elapsed_seconds")+ elapsed_str = (+ f"started {int(elapsed)}s ago" if isinstance(elapsed, (int, float)) else "running now"+ )+ return (+ f"[repowise] Index update in progress ({elapsed_str}), catching up to "+ f"{head[:8]}. The MCP tools remain reliable meanwhile; a response carries "+ "`stale_warning` only when a file it serves actually changed."+ )++ changed = _changed_file_count(repo_path, last_sync, head)+ drift = f" ({changed} files changed since)" if changed is not None else ""+ return (+ f"[repowise] Index is behind HEAD: indexed {last_sync[:8]}, now {head[:8]}{drift}. "+ f"The MCP tools ({_CORE_TOOLS}) stay reliable: a response carries `stale_warning` "+ "only when a file it serves actually changed, and silence means current. "+ "Run `repowise update` to resync."+ )+++def _git_head(repo_path: Path) -> str | None:+ """Live HEAD SHA, or None when git can't answer quickly."""+ import subprocess++ try:+ out = subprocess.run(+ ["git", "rev-parse", "HEAD"],+ cwd=str(repo_path),+ capture_output=True,+ text=True,+ timeout=5,+ stdin=subprocess.DEVNULL,+ )+ except Exception:+ return None+ head = out.stdout.strip()+ return head if out.returncode == 0 and head else None+++def _changed_file_count(repo_path: Path, indexed: str, live: str) -> int | None:+ """Files changed between the indexed commit and live HEAD, or None."""+ import subprocess++ try:+ out = subprocess.run(+ ["git", "diff", "--name-only", indexed, live],+ cwd=str(repo_path),+ capture_output=True,+ text=True,+ timeout=5,+ stdin=subprocess.DEVNULL,+ )+ except Exception:+ return None+ if out.returncode != 0:+ return None+ return sum(1 for line in out.stdout.splitlines() if line.strip())diff --git a/packages/cli/src/repowise/cli/commands/doctor_cmd/repo_checks.py b/packages/cli/src/repowise/cli/commands/doctor_cmd/repo_checks.pyindex fc211ad31..81d1c011b 100644--- a/packages/cli/src/repowise/cli/commands/doctor_cmd/repo_checks.py+++ b/packages/cli/src/repowise/cli/commands/doctor_cmd/repo_checks.py@@ -384,6 +384,10 @@ def _run_repo_checks(# 11. Distill — config block, omission store, rewrite hook (advisory)checks.extend(_distill_checks(repo_path))+ # 12. Claude Code MCP registration: wedged-path detection+ registration_check, registration_wedged = _claude_registration_check()+ checks.append(registration_check)+all_ok = all(c.ok for c in checks)if fmt != "table":@@ -503,12 +507,90 @@ def _run_repo_checks(repaired_count = run_async(_repair())console.print(f"[bold green]Repaired {repaired_count} entries.[/bold green]")- elif repair and not has_mismatches:+ elif repair and not has_mismatches and not registration_wedged:console.print("[green]Nothing to repair.[/green]")+ if repair and registration_wedged:+ from repowise.cli.editor_integrations.claude_config import register_with_claude_code++ fixed = register_with_claude_code(repo_path)+ if fixed:+ console.print(+ f"[bold green]Re-registered the Claude Code MCP entry ({fixed}).[/bold green]"+ )+ else:+ console.print(+ "[yellow]Could not re-register the Claude Code MCP entry; "+ "run `repowise init` to redo editor setup.[/yellow]"+ )+return all_ok, checks+def _claude_registration_check() -> tuple[DoctorCheck, bool]:+ """Detect a wedged Claude Code MCP registration (stale paths).++ The global ``~/.claude/settings.json`` entry can end up pointing at a+ directory that no longer exists (a moved repo, or a leaked temp path) or+ at a pinned command binary from a deleted venv; either way the MCP+ server silently fails to start in every Claude Code session. Returns+ ``(check, wedged)``; ``wedged`` drives the ``--repair`` re-registration.+ Absence of a registration is informational, never a failure.+ """+ name = "Claude Code MCP entry"+ try:+ import json as _json++ from repowise.cli.editor_integrations.claude_config import _claude_code_settings_path++ settings_path = _claude_code_settings_path()+ if not settings_path.exists():+ return _check(name, True, "not registered (repowise init registers it)"), False+ try:+ settings = _json.loads(settings_path.read_text(encoding="utf-8"))+ except (OSError, _json.JSONDecodeError):+ return _check(name, True, f"could not parse {settings_path}"), False+ servers = settings.get("mcpServers") if isinstance(settings, dict) else None+ entry = servers.get("repowise") if isinstance(servers, dict) else None+ if not isinstance(entry, dict):+ return _check(name, True, "not registered (repowise init registers it)"), False++ problems: list[str] = []+ command = entry.get("command")+ # Bare command names resolve via PATH at session start; only a pinned+ # absolute path can go stale.+ if (+ isinstance(command, str)+ and ("/" in command or "\\" in command)+ and not _DoctorPath(command).exists()+ ):+ problems.append(f"command not found: {command}")+ target = _registration_target(entry)+ if target is not None and not _DoctorPath(target).is_dir():+ problems.append(f"registered path missing: {target}")+ if problems:+ return _check(name, False, "; ".join(problems) + " (rerun with --repair)"), True+ return _check(name, True, target or "registered"), False+ except Exception as exc:+ return _check(name, True, f"Could not check: {exc}"), False+++def _registration_target(entry: dict) -> str | None:+ """The repo/workspace path a registration serves, or None if unrecognized.++ Registrations are shaped ``args: ["mcp", "<abs path>", "--transport",+ "stdio"]``; the target sits right after ``mcp``. Anything else (a flag+ in that slot, a hand-edited entry) returns None rather than guessing.+ """+ args = entry.get("args")+ if not isinstance(args, list) or args[:1] != ["mcp"] or len(args) < 2:+ return None+ target = args[1]+ if isinstance(target, str) and not target.startswith("-"):+ return target+ return None++def _distill_checks(repo_path: _DoctorPath) -> list[DoctorCheck]:"""Distill feature health: config validity, store sizing, rewrite hook.diff --git a/packages/cli/src/repowise/cli/editor_integrations/claude.py b/packages/cli/src/repowise/cli/editor_integrations/claude.pyindex 5d928edf9..18115f536 100644--- a/packages/cli/src/repowise/cli/editor_integrations/claude.py+++ b/packages/cli/src/repowise/cli/editor_integrations/claude.py@@ -63,12 +63,13 @@ class ClaudeCodeSetup:hooks = install_claude_code_hooks()if hooks:- console_obj.print(" [green]✓[/green] Claude Code hooks registered (PostToolUse)")+ console_obj.print(+ " [green]✓[/green] Claude Code hooks registered (PostToolUse, SessionStart)"+ )if enable_tool_search_in_claude_code():console_obj.print(- " [green]✓[/green] Claude Code tool-search enabled "- "(defers MCP tool schemas)"+ " [green]✓[/green] Claude Code tool-search enabled (defers MCP tool schemas)")def refresh_project_files(diff --git a/packages/cli/src/repowise/cli/editor_integrations/claude_config.py b/packages/cli/src/repowise/cli/editor_integrations/claude_config.pyindex 24efcf0b1..ebd7c5593 100644--- a/packages/cli/src/repowise/cli/editor_integrations/claude_config.py+++ b/packages/cli/src/repowise/cli/editor_integrations/claude_config.py@@ -141,12 +141,32 @@ _LEGACY_AUGMENT_MATCHERS = ("Bash|Grep|Glob|Read|Edit|Write",)+# SessionStart emits the live index-freshness / trust context block. `compact`+# is excluded on purpose: the block usually survives compaction in the summary,+# and re-emitting it there would double it up.+_SESSION_START_MATCHER = "startup|resume|clear"+++def _session_start_entry() -> dict:+ return {+ "matcher": _SESSION_START_MATCHER,+ "hooks": [+ {+ "type": "command",+ "command": "repowise-augment",+ "timeout": 10,+ "statusMessage": "Loading repowise context...",+ }+ ],+ }+def install_claude_code_hooks() -> Path | None:- """Register PostToolUse hooks in ~/.claude/settings.json.+ """Register PostToolUse + SessionStart hooks in ~/.claude/settings.json.PostToolUse detects git staleness, enriches Grep/Glob results, and emits- Read-intelligence notices. Existing user hooks are preserved.+ Read-intelligence notices; SessionStart injects the live index-freshness+ context block. Existing user hooks are preserved."""settings_path = _claude_code_settings_path()@@ -186,6 +206,11 @@ def install_claude_code_hooks() -> Path | None:if not _has_repowise_hook(post_hooks):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())+settings_path.write_text(json.dumps(existing, indent=2) + "\n", encoding="utf-8")return settings_pathexcept OSError:@@ -434,6 +459,19 @@ 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.+ if isinstance(post, list) and _has_repowise_hook(post):+ session = hooks.get("SessionStart")+ if session is None:+ hooks["SessionStart"] = [_session_start_entry()]+ changed = True+ elif isinstance(session, list) and not _has_repowise_hook(session):+ session.append(_session_start_entry())+ changed = True+if not changed:return Falsediff --git a/packages/cli/src/repowise/cli/rewrite_hook.py b/packages/cli/src/repowise/cli/rewrite_hook.pyindex a2b857f52..3472958df 100644--- a/packages/cli/src/repowise/cli/rewrite_hook.py+++ b/packages/cli/src/repowise/cli/rewrite_hook.py@@ -7,10 +7,11 @@ posture is ``allow``: a rewritten command runs without an approval prompt,uniformly across the main agent and every subagent. This is safe because``classify`` only ever rewrites a closed set of recognized command families(test/lint/build/git/search/listing/log) that survive the bailouts below —-no pipes, redirects, compound commands, substitution, or interactive-commands. The rewrite is therefore always ``repowise distill <one simple,-recognized command>``, never an arbitrary command smuggled behind the-wrapper, so auto-allowing it is not a permission escalation. Users who want+no redirects, compound commands, substitution, or interactive commands,+and the only pipe shape allowed is a single ``| head``/``| tail`` with no+quoting to break out of. The rewrite is therefore always ``repowise distill+<one simple, recognized command>``, never an arbitrary command smuggled+behind the wrapper, so auto-allowing it is not a permission escalation. Users who wantto review every rewrite can set ``permission: ask`` in``.repowise/config.yaml``; a family set to ``off`` is never rewritten.@@ -26,9 +27,12 @@ Hot-path discipline (this fires on EVERY Bash tool call):Bailouts — commands never rewritten:- - pipes / redirections / compound commands (``| > < && || ; &``),- substitution (backticks, ``$(``), multi-line commands: the wrapper- would change shell semantics;+ - redirections / compound commands (``> < && || ; &``), substitution+ (backticks, ``$(``), multi-line commands: the wrapper would change+ shell semantics. Two safe tails are carved out: a trailing ``2>&1``+ (distill merges stderr into its capture anyway) and, on POSIX hosts,+ a single pipe into bare ``head``/``tail``; the whole pipeline is+ then quoted so it runs inside distill's own shell, unchanged;- watch/follow modes (``--watch``, ``tail -f``): long-running,interactive by design;- the ignore-list of trivial or interactive commands (cd, echo, vim, …);@@ -184,6 +188,55 @@ IGNORED_FIRST_TOKENS = frozenset(# and `& "path\to.exe"` call-operator invocations._SHELL_SYNTAX_RE = re.compile(r"[|&;<>`\n]|\$\(")+# A stderr-merge suffix is the one redirection distill preserves for free:+# it captures both streams and interleaves them, so `cmd 2>&1` and+# `repowise distill cmd` (with the outer shell applying the now-vacuous+# 2>&1 to distill's own empty stderr) see the same bytes.+_STDERR_MERGE_RE = re.compile(r"\s+2>&1(?=\s|$)")++# The only pipe tails safe to run inside distill's shell: bare head/tail+# with at most a numeric count. Anything else (grep, awk, sort, xargs)+# passes through untouched.+_SAFE_PIPE_TAIL_RE = re.compile(r"^(?:head|tail)(?:\s+(?:-n\s*|-c\s*|-)\d+)?\s*$")++# Quoting the pipeline for distill's inner shell is only sound when nothing+# in it can be re-expanded or break the quoting on the second pass.+_PIPE_UNSAFE_CHARS = ('"', "'", "$", "\\")++# distill executes via the system shell (cmd.exe on Windows, where head/tail+# don't exist), so the safe-pipeline rewrite is POSIX-hosts-only. Module+# constant so tests can pin both platforms' behavior.+_POSIX_HOST = os.name == "posix"+++def _split_safe_tail(command: str) -> tuple[str, bool] | None:+ """Split *command* into (classifiable head, needs_inner_shell).++ Returns None when the command carries shell syntax the wrapper can't+ preserve. ``needs_inner_shell`` is True for the safe-pipeline shape+ (``cmd | head -N``): the caller must pass the whole command to+ ``repowise distill`` as one quoted token so the pipe executes inside+ distill's own shell rather than binding to the wrapper.+ """+ cmd = command.strip()+ # Classification always ignores stderr merges; `pytest 2>&1 | head`+ # still classifies as pytest.+ declawed = _STDERR_MERGE_RE.sub("", cmd)+ if not _SHELL_SYNTAX_RE.search(declawed):+ return declawed, False+ # One pipe into bare head/tail: run the pipeline inside distill.+ if not _POSIX_HOST:+ return None+ if any(ch in cmd for ch in _PIPE_UNSAFE_CHARS):+ return None+ head_part, sep, tail_part = declawed.partition("|")+ if not sep or _SHELL_SYNTAX_RE.search(head_part) or _SHELL_SYNTAX_RE.search(tail_part):+ return None+ if not _SAFE_PIPE_TAIL_RE.match(tail_part.strip()):+ return None+ return head_part.strip(), True++# Watch/follow modes are long-running; wrapping them buffers forever._WATCH_RE = re.compile(r"--watch(?:all)?\b|--looponfail\b|(?:^|\s)-f\b.*\.log\b|--follow\b")@@ -197,9 +250,17 @@ _DASHED_TOOL_TOKENS = frozenset({"golangci-lint"})def classify(command: str) -> str | None:"""Return the distill family for *command*, or None to pass through."""- if not command or _SHELL_SYNTAX_RE.search(command):+ if not command:return None- normalized = _normalize(command)+ split = _split_safe_tail(command)+ if split is None:+ return None+ return _classify_head(split[0])+++def _classify_head(head_command: str) -> str | None:+ """Family for an already syntax-vetted command (no bailout checks)."""+ normalized = _normalize(head_command)if not normalized or normalized.startswith("repowise"):return Nonefirst = normalized.split(None, 1)[0]@@ -304,12 +365,16 @@ def decide(*source* overrides the ledger tag for agents with their own surface(``hook-codex``); by default it derives from the shell dialect."""- family = classify(command)+ split = _split_safe_tail(command) if command else None+ if split is None:+ return None+ head_command, needs_inner_shell = split+ family = _classify_head(head_command)if family is None:return Noneif shell == "powershell":- first = _normalize(command).split(None, 1)[0]+ first = _normalize(head_command).split(None, 1)[0]if first in _PS_ALIAS_TOKENS:return None@@ -332,8 +397,13 @@ def decide(# --by source` can tell hook surfaces apart from direct CLI use.if source is None:source = "hook-powershell" if shell == "powershell" else "hook-bash"+ # A safe pipeline is passed as ONE quoted token so the pipe binds inside+ # distill's shell (distill re-runs a single token verbatim via shell=True)+ # instead of piping distill's own rendering. _split_safe_tail already+ # rejected commands containing quotes, so the wrap can't be broken out of.+ wrapped = f'"{command.strip()}"' if needs_inner_shell else command.strip()return RewriteResult(- command=f"repowise distill --source {source} {command.strip()}",+ command=f"repowise distill --source {source} {wrapped}",permission=permission,reason=(f"repowise distill: compact {family} rendering; full output stays "diff --git a/plugins/claude-code/CHANGELOG.md b/plugins/claude-code/CHANGELOG.mdindex 83ce4da99..a3408d76a 100644--- a/plugins/claude-code/CHANGELOG.md+++ b/plugins/claude-code/CHANGELOG.md@@ -2,6 +2,14 @@All notable changes to the Repowise Claude Code plugin are documented here.+## Unreleased++### Added+- Bundled `SessionStart` hook (`repowise-augment`, matcher `startup|resume|clear`):+ injects a short context block at session start with live index freshness+ (current / behind with a changed-file count / update in progress) and the+ core-tool trust rule, matching the CLI-installed hook.+## 0.27.0### Changeddiff --git a/plugins/claude-code/hooks/hooks.json b/plugins/claude-code/hooks/hooks.jsonindex bf9832e2a..a2adf1234 100644--- a/plugins/claude-code/hooks/hooks.json+++ b/plugins/claude-code/hooks/hooks.json@@ -1,5 +1,18 @@{"hooks": {+ "SessionStart": [+ {+ "matcher": "startup|resume|clear",+ "hooks": [+ {+ "type": "command",+ "command": "repowise-augment",+ "timeout": 10,+ "statusMessage": "Loading repowise context..."+ }+ ]+ }+ ],"PostToolUse": [{"matcher": "Bash|PowerShell|Grep|Glob|Read|Edit|Write",diff --git a/tests/unit/cli/conftest.py b/tests/unit/cli/conftest.pynew file mode 100644index 000000000..cc4e82925--- /dev/null+++ b/tests/unit/cli/conftest.py@@ -0,0 +1,27 @@+"""CLI test configuration.++CLI commands write user-level config as a side effect (``repowise init``+registers the MCP server and hooks in ``~/.claude/settings.json``, enables+tool search, and touches Claude Desktop / Codex config). A test that drives a+command end-to-end against a pytest tmp_path would therefore leak that temp+path into the developer's real settings, a wedged registration that breaks+every subsequent Claude Code session until repaired. The autouse fixture+below points "home" at a per-test temp directory so no CLI test can ever+touch real user-level config; tests that build their own fake home simply+patch over it.+"""++from __future__ import annotations++from pathlib import Path++import pytest++[email protected](autouse=True)+def _isolated_home(tmp_path_factory, monkeypatch):+ fake_home = tmp_path_factory.mktemp("home")+ monkeypatch.setenv("HOME", str(fake_home))+ monkeypatch.setenv("USERPROFILE", str(fake_home))+ monkeypatch.setattr(Path, "home", lambda: fake_home)+ return fake_homediff --git a/tests/unit/cli/test_augment_cmd.py b/tests/unit/cli/test_augment_cmd.pyindex 38e4af0da..b62967fab 100644--- a/tests/unit/cli/test_augment_cmd.py+++ b/tests/unit/cli/test_augment_cmd.py@@ -75,10 +75,15 @@ def test_codex_user_prompt_submit_payload_returns_mcp_context(assert "semantic search" in _hook_context(result.output)-def test_claude_lifecycle_payload_stays_silent_without_codex_client(- runner: CliRunner, tmp_path: Path+def test_claude_session_start_emits_freshness_context(+ runner: CliRunner, tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:_init_repowise_repo(tmp_path)+ # The dedup marker is keyed on (event, context); identical blocks across+ # fast test runs would suppress the emission, so bypass it here.+ monkeypatch.setattr(+ "repowise.cli.commands.augment_cmd.command._claim_emission", lambda e, c: True+ )result = _invoke_augment(runner,@@ -89,6 +94,26 @@ def test_claude_lifecycle_payload_stays_silent_without_codex_client(},)+ assert result.exit_code == 0+ # tmp_path is not a git repo, so the handler emits the freshness-free+ # reminder, never a false "current" claim.+ context = _hook_context(result.output)+ assert "MCP tools" in context+ assert "current" not in context+++def test_claude_user_prompt_submit_stays_silent(runner: CliRunner, tmp_path: Path) -> None:+ _init_repowise_repo(tmp_path)++ result = _invoke_augment(+ runner,+ {+ "hook_event_name": "UserPromptSubmit",+ "prompt": "Where is the auth flow?",+ "cwd": str(tmp_path),+ },+ )+assert result.exit_code == 0assert result.output == ""diff --git a/tests/unit/cli/test_augment_session_start.py b/tests/unit/cli/test_augment_session_start.pynew file mode 100644index 000000000..0de2a268e--- /dev/null+++ b/tests/unit/cli/test_augment_session_start.py@@ -0,0 +1,131 @@+"""Claude Code SessionStart context block: freshness states and gating.++The block's whole value is calibrated trust, so the contract under test is+which of the four states gets emitted (current / update-in-flight / behind /+git-unavailable) and that a git failure never produces a false "current"+claim. Outside an indexed repo the handler must stay silent.+"""++from __future__ import annotations++import json+from pathlib import Path++import pytest++from repowise.cli.commands.augment_cmd import session_start++_INDEXED = "1" * 40+_LIVE = "2" * 40+++def repo(tmp_path: Path) -> Path:+ (tmp_path / ".repowise").mkdir()+ (tmp_path / ".repowise" / "state.json").write_text(+ json.dumps({"last_sync_commit": _INDEXED}), encoding="utf-8"+ )+ return tmp_path+++def _handle(cwd: Path) -> str | None:+ return session_start._handle_claude_session_start(str(cwd))+++def test_current_index(repo, monkeypatch) -> None:+ monkeypatch.setattr(session_start, "_git_head", lambda p: _INDEXED)+ out = _handle(repo)+ assert out is not None+ assert "current" in out+ assert _INDEXED[:8] in out+ assert "get_answer" in out+++def test_behind_head_with_changed_count(repo, monkeypatch) -> None:+ monkeypatch.setattr(session_start, "_git_head", lambda p: _LIVE)+ monkeypatch.setattr(session_start, "_read_in_flight_marker", lambda p: None)+ monkeypatch.setattr(session_start, "_changed_file_count", lambda p, a, b: 12)+ out = _handle(repo)+ assert out is not None+ assert f"indexed {_INDEXED[:8]}, now {_LIVE[:8]}" in out+ assert "(12 files changed since)" in out+ assert "stale_warning" in out+ assert "repowise update" in out+++def test_behind_head_without_changed_count(repo, monkeypatch) -> None:+ monkeypatch.setattr(session_start, "_git_head", lambda p: _LIVE)+ monkeypatch.setattr(session_start, "_read_in_flight_marker", lambda p: None)+ monkeypatch.setattr(session_start, "_changed_file_count", lambda p, a, b: None)+ out = _handle(repo)+ assert out is not None+ assert "files changed" not in out+ assert "repowise update" in out+++def test_update_in_flight_gets_positive_notice(repo, monkeypatch) -> None:+ monkeypatch.setattr(session_start, "_git_head", lambda p: _LIVE)+ monkeypatch.setattr(+ session_start,+ "_read_in_flight_marker",+ lambda p: {"source": "lock", "target_commit": _LIVE, "elapsed_seconds": 34.2},+ )+ out = _handle(repo)+ assert out is not None+ assert "update in progress" in out+ assert "started 34s ago" in out+ # Positive notice, not a stale scare.+ assert "repowise update" not in out+++def test_git_failure_never_claims_current(repo, monkeypatch) -> None:+ monkeypatch.setattr(session_start, "_git_head", lambda p: None)+ out = _handle(repo)+ assert out is not None+ assert "current" not in out+ assert "MCP tools" in out+++def test_silent_outside_indexed_repo(tmp_path) -> None:+ assert _handle(tmp_path) is None+++def test_silent_without_state_json(tmp_path) -> None:+ (tmp_path / ".repowise").mkdir()+ assert _handle(tmp_path) is None+++def test_silent_without_last_sync_commit(tmp_path) -> None:+ (tmp_path / ".repowise").mkdir()+ (tmp_path / ".repowise" / "state.json").write_text("{}", encoding="utf-8")+ assert _handle(tmp_path) is None+++def test_changed_file_count_real_git(tmp_path) -> None:+ import subprocess++ def git(*args: str) -> str:+ return subprocess.run(+ ["git", "-C", str(tmp_path), *args],+ check=True,+ capture_output=True,+ text=True,+ ).stdout.strip()++ git("init", "-q")+ git("config", "user.email", "[email protected]")+ git("config", "user.name", "t")+ (tmp_path / "a.py").write_text("x = 1\n", encoding="utf-8")+ git("add", ".")+ git("commit", "-qm", "one")+ sha1 = git("rev-parse", "HEAD")+ (tmp_path / "b.py").write_text("y = 2\n", encoding="utf-8")+ (tmp_path / "c.py").write_text("z = 3\n", encoding="utf-8")+ git("add", ".")+ git("commit", "-qm", "two")+ sha2 = git("rev-parse", "HEAD")++ assert session_start._git_head(tmp_path) == sha2+ assert session_start._changed_file_count(tmp_path, sha1, sha2) == 2+ # An unresolvable SHA degrades to None (count omitted), never raises.+ assert session_start._changed_file_count(tmp_path, "f" * 40, sha2) is Nonediff --git a/tests/unit/cli/test_doctor_registration.py b/tests/unit/cli/test_doctor_registration.pynew file mode 100644index 000000000..aa47a08a8--- /dev/null+++ b/tests/unit/cli/test_doctor_registration.py@@ -0,0 +1,108 @@+"""Doctor's wedged Claude Code MCP registration detection.++A leaked or stale ``mcpServers.repowise`` entry in ``~/.claude/settings.json``+(a moved repo, a deleted venv's pinned binary, a temp path) silently breaks+the MCP server in every session. The check must flag exactly those cases and+treat "not registered" / "can't check" as informational, never a failure.++The autouse ``_isolated_home`` conftest fixture points ``Path.home()`` at a+temp dir, so these tests write their own settings.json freely.+"""++from __future__ import annotations++import json+from pathlib import Path++from repowise.cli.commands.doctor_cmd.repo_checks import (+ _claude_registration_check,+ _registration_target,+)+++def _write_settings(entry: dict) -> Path:+ settings_path = Path.home() / ".claude" / "settings.json"+ settings_path.parent.mkdir(parents=True, exist_ok=True)+ settings_path.write_text(json.dumps({"mcpServers": {"repowise": entry}}), encoding="utf-8")+ return settings_path+++def _entry(target: Path | str, command: str = "repowise") -> dict:+ return {+ "command": command,+ "args": ["mcp", str(target), "--transport", "stdio"],+ }+++def test_no_settings_file_is_informational() -> None:+ check, wedged = _claude_registration_check()+ assert check.ok is True+ assert wedged is False+ assert "not registered" in check.detail+++def test_not_registered_is_informational() -> None:+ settings_path = Path.home() / ".claude" / "settings.json"+ settings_path.parent.mkdir(parents=True, exist_ok=True)+ settings_path.write_text(json.dumps({"env": {}}), encoding="utf-8")+ check, wedged = _claude_registration_check()+ assert check.ok is True+ assert wedged is False+++def test_healthy_registration_passes(tmp_path: Path) -> None:+ _write_settings(_entry(tmp_path))+ check, wedged = _claude_registration_check()+ assert check.ok is True+ assert wedged is False+ assert str(tmp_path) in check.detail+++def test_missing_target_path_is_wedged(tmp_path: Path) -> None:+ # The shape found in the wild: a registration left pointing at a+ # long-deleted pytest temp directory.+ _write_settings(_entry(tmp_path / "pytest-1457" / "gone0"))+ check, wedged = _claude_registration_check()+ assert check.ok is False+ assert wedged is True+ assert "registered path missing" in check.detail+ assert "--repair" in check.detail+++def test_missing_pinned_command_is_wedged(tmp_path: Path) -> None:+ target = tmp_path / "repo"+ target.mkdir()+ _write_settings(_entry(target, command=str(tmp_path / "dead-venv" / "repowise.exe")))+ check, wedged = _claude_registration_check()+ assert check.ok is False+ assert wedged is True+ assert "command not found" in check.detail+++def test_bare_command_name_is_never_checked(tmp_path: Path) -> None:+ # Bare names resolve via PATH at session start; only pinned absolute+ # paths can go stale.+ target = tmp_path / "repo"+ target.mkdir()+ _write_settings(_entry(target, command="repowise"))+ check, wedged = _claude_registration_check()+ assert check.ok is True+ assert wedged is False+++def test_malformed_settings_is_informational() -> None:+ settings_path = Path.home() / ".claude" / "settings.json"+ settings_path.parent.mkdir(parents=True, exist_ok=True)+ settings_path.write_text("{ not json", encoding="utf-8")+ check, wedged = _claude_registration_check()+ assert check.ok is True+ assert wedged is False+++def test_registration_target_extraction(tmp_path: Path) -> None:+ assert _registration_target(_entry(tmp_path)) == str(tmp_path)+ # Unrecognized arg shapes → None, no false positives.+ assert _registration_target({"args": ["serve", str(tmp_path)]}) is None+ assert _registration_target({"args": "mcp"}) is None+ assert _registration_target({}) is None+ assert _registration_target({"args": ["mcp", "--transport", "stdio"]}) is Nonediff --git a/tests/unit/cli/test_helpers.py b/tests/unit/cli/test_helpers.pyindex b49d151ce..a24df828b 100644--- a/tests/unit/cli/test_helpers.py+++ b/tests/unit/cli/test_helpers.py@@ -78,7 +78,12 @@ class TestFindRepowiseRepoRoot:assert find_repowise_repo_root(nested) == root.resolve()- def test_returns_none_when_missing(self, tmp_path):+ def test_returns_none_when_missing(self, tmp_path, monkeypatch):+ # The walk stops at Path.home(); anchor "home" above the tmp dir so+ # the test can't escape into the real filesystem (the conftest's fake+ # home is a sibling temp dir, not an ancestor, so it never trips the+ # guard, and the developer's real ~/.repowise must stay invisible).+ monkeypatch.setattr(Path, "home", lambda: tmp_path.parent)assert find_repowise_repo_root(tmp_path) is Nonedef test_ignores_nested_git_dirs(self, tmp_path):diff --git a/tests/unit/cli/test_mcp_config.py b/tests/unit/cli/test_mcp_config.pyindex e238bbdbe..1adb9e2da 100644--- a/tests/unit/cli/test_mcp_config.py+++ b/tests/unit/cli/test_mcp_config.py@@ -391,11 +391,20 @@ def _post_repowise_entries(saved: dict) -> list:]+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", "")+ ]++def test_install_claude_code_hooks_creates_missing_file(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:- """Fresh install: only a PostToolUse entry is added. The new design- routes Bash + Grep + Glob through a single matcher; PreToolUse is+ """Fresh install: a PostToolUse entry plus the SessionStart context hook.+ Enrichment routes through a single PostToolUse matcher; PreToolUse isintentionally absent because it can't see actual result counts."""monkeypatch.setattr(Path, "home", lambda: tmp_path)@@ -407,6 +416,7 @@ def test_install_claude_code_hooks_creates_missing_file(assert _post_repowise_entries(saved) == [("Bash|PowerShell|Grep|Glob|Read|Edit|Write", "repowise-augment")]+ assert _session_start_repowise_entries(saved) == [("startup|resume|clear", "repowise-augment")]def test_install_claude_code_hooks_preserves_user_pretool_hooks(@@ -645,7 +655,15 @@ def test_migrate_claude_code_hooks_never_widens_user_matcher({"type": "command", "command": "my-linter"},],}- ]+ ],+ # SessionStart already present so its backfill (a separate+ # migration) can't mask the matcher no-op under test.+ "SessionStart": [+ {+ "matcher": "startup|resume|clear",+ "hooks": [{"type": "command", "command": "repowise-augment"}],+ }+ ],}}),@@ -705,7 +723,13 @@ def test_migrate_claude_code_hooks_noop_when_already_current("matcher": "Bash|PowerShell|Grep|Glob|Read|Edit|Write","hooks": [{"type": "command", "command": "repowise-augment"}],}- ]+ ],+ "SessionStart": [+ {+ "matcher": "startup|resume|clear",+ "hooks": [{"type": "command", "command": "repowise-augment"}],+ }+ ],}}original = json.dumps(payload, indent=2) + "\n"@@ -717,6 +741,97 @@ def test_migrate_claude_code_hooks_noop_when_already_current(assert settings_path.stat().st_mtime_ns == mtime_before+def test_migrate_claude_code_hooks_backfills_session_start(+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch+) -> None:+ """Installs that predate the SessionStart context hook get it added,+ gated on the augment PostToolUse hook being present (so migration never+ installs anything for a user who removed repowise hooks on purpose)."""+ 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": "Bash|PowerShell|Grep|Glob|Read|Edit|Write",+ "hooks": [{"type": "command", "command": "repowise-augment"}],+ }+ ]+ }+ }+ ),+ encoding="utf-8",+ )++ assert claude_config.migrate_claude_code_hooks() is True+ saved = json.loads(settings_path.read_text(encoding="utf-8"))+ assert _session_start_repowise_entries(saved) == [("startup|resume|clear", "repowise-augment")]+ # Idempotent on the second pass.+ assert claude_config.migrate_claude_code_hooks() is False+++def test_migrate_claude_code_hooks_no_session_start_without_augment(+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch+) -> None:+ """A settings.json with only user hooks never gains repowise entries."""+ 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": "Bash",+ "hooks": [{"type": "command", "command": "my-linter"}],+ }+ ]+ }+ }+ ),+ encoding="utf-8",+ )++ assert claude_config.migrate_claude_code_hooks() is False+ saved = json.loads(settings_path.read_text(encoding="utf-8"))+ assert "SessionStart" not in saved["hooks"]+++def test_migrate_claude_code_hooks_preserves_user_session_start(+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch+) -> None:+ """A user's own SessionStart 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": "Bash|PowerShell|Grep|Glob|Read|Edit|Write",+ "hooks": [{"type": "command", "command": "repowise-augment"}],+ }+ ],+ "SessionStart": [{"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"))+ session = saved["hooks"]["SessionStart"]+ assert session[0]["hooks"][0]["command"] == "echo mine"+ assert _session_start_repowise_entries(saved) == [("startup|resume|clear", "repowise-augment")]++def test_migrate_claude_code_hooks_silent_when_settings_missing(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:@@ -735,6 +850,26 @@ def test_migrate_claude_code_hooks_silent_on_malformed_json(assert claude_config.migrate_claude_code_hooks() is False+def test_plugin_hooks_json_mirrors_settings_entries(repo_root: Path) -> None:+ """The bundled plugin's hooks.json must match what init writes to+ settings.json; the emission dedup in augment assumes both surfaces+ fire the same command on the same events."""+ plugin = json.loads(+ (repo_root / "plugins" / "claude-code" / "hooks" / "hooks.json").read_text(encoding="utf-8")+ )+ hooks = plugin["hooks"]++ def rows(bucket: str) -> list:+ return [+ (entry.get("matcher"), h["command"])+ for entry in hooks.get(bucket, [])+ for h in entry["hooks"]+ ]++ assert rows("PostToolUse") == [(claude_config._AUGMENT_MATCHER, "repowise-augment")]+ assert rows("SessionStart") == [(claude_config._SESSION_START_MATCHER, "repowise-augment")]++def test_install_claude_code_hooks_rejects_invalid_existing_file(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:diff --git a/tests/unit/distill/test_rewrite_hook.py b/tests/unit/distill/test_rewrite_hook.pyindex ef8b9d86c..0557c5ac1 100644--- a/tests/unit/distill/test_rewrite_hook.py+++ b/tests/unit/distill/test_rewrite_hook.py@@ -93,7 +93,7 @@ class TestClassify:"python script.py","node server.js",# compound / pipes / redirections / substitution- "pytest | head -50",+ "pytest | grep FAIL","pytest && echo done","pytest || true","git status; ls",@@ -169,6 +169,86 @@ class TestClassify:assert _normalize(command) == normalize_command(command)+class TestSafeTails:+ """The two shell-syntax carve-outs: trailing ``2>&1`` and ``| head/tail``.++ ``2>&1`` is platform-neutral (distill merges stderr into its capture+ anyway). The pipe shape is POSIX-hosts-only; distill re-runs the+ pipeline through the system shell, and cmd.exe has no head/tail.+ """++ @pytest.fixture+ def posix_host(self, monkeypatch):+ monkeypatch.setattr(rewrite_hook, "_POSIX_HOST", True)++ @pytest.fixture+ def windows_host(self, monkeypatch):+ monkeypatch.setattr(rewrite_hook, "_POSIX_HOST", False)++ @pytest.mark.parametrize(+ ("command", "family"),+ [+ ("pytest -x 2>&1", "test_output"),+ ("git log --oneline -20 2>&1", "git_log"),+ ("npm run build 2>&1", "build_output"),+ ],+ )+ def test_stderr_merge_classifies_on_any_host(self, command, family, windows_host) -> None:+ assert classify(command) == family++ @pytest.mark.parametrize(+ ("command", "family"),+ [+ ("pytest | head -50", "test_output"),+ ("pytest tests/unit -q | head", "test_output"),+ ("git log --oneline | tail -20", "git_log"),+ ("git log --oneline | tail -n 20", "git_log"),+ ("cargo build 2>&1 | head -100", "build_output"),+ ],+ )+ def test_safe_pipe_classifies_on_posix(self, command, family, posix_host) -> None:+ assert classify(command) == family++ @pytest.mark.parametrize(+ "command",+ [+ "pytest | head -50",+ "cargo build 2>&1 | head -100",+ ],+ )+ def test_safe_pipe_passes_through_on_windows(self, command, windows_host) -> None:+ assert classify(command) is None++ @pytest.mark.parametrize(+ "command",+ [+ "pytest | grep FAIL", # tail not in the head/tail whitelist+ "pytest | head -50 | tail -2", # two pipes+ 'pytest -k "a b" | head', # quotes could break the wrap+ "pytest $ARGS | head", # expansion re-evaluated inside distill+ "pytest | head; ls", # compound after the pipe+ "pytest | head > out.txt", # redirect after the pipe+ "echo hi | head", # head command still on the ignore-list+ "tail -f app.log | head", # watch mode still bails+ ],+ )+ def test_unsafe_pipes_pass_through(self, command, posix_host) -> None:+ assert classify(command) is None++ def test_decide_keeps_stderr_merge_unquoted(self, repo) -> None:+ result = decide("pytest -x 2>&1", str(repo))+ assert result is not None+ assert result.command == "repowise distill --source hook-bash pytest -x 2>&1"++ def test_decide_quotes_safe_pipeline(self, repo, posix_host) -> None:+ result = decide("pytest tests/unit -q | head -50", str(repo))+ assert result is not None+ assert result.command == (+ 'repowise distill --source hook-bash "pytest tests/unit -q | head -50"'+ )+ assert result.permission == "allow"++# ---------------------------------------------------------------------------# decide() — repo gating + permission config# ---------------------------------------------------------------------------