Skip to content

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

feat(cli): opt-in health gate on agent git commit and git push (#4371)

Raghav Chamadiya99a2f0af83e6
diff --git a/docs/agent/HOOKS.md b/docs/agent/HOOKS.md
index 3de24528f..18c99cef3 100644
--- a/docs/agent/HOOKS.md
+++ b/docs/agent/HOOKS.md
@@ -26,6 +26,7 @@ For the exact settings entries each install writes, see the
| **PostToolUse enrichment** | Claude Code | `repowise init` | `Grep` / `Glob` / `Read` / `Edit` / `Write` / repowise MCP calls | Graph context on searches, read notices, edit-time decision and bug-history notices |
| **Wrong-path rescue** | Claude Code | `repowise init` | a path tool call that failed on a path this tree does not have | Names the file when exactly one indexed file carries that basename; silent otherwise |
| **Coverage re-ingest** (opt-in) | Claude Code | `hooks.coverage_reingest: true`, then the next `repowise coverage add` / `init` / `update` | `Bash` / `PowerShell` | Re-ingests a fresh full-suite coverage report in the background |
+| **Health gate** (opt-in) | Claude Code | `repowise hook health-gate install` | `git commit` / `git push` via `Bash` / `PowerShell` | Runs `repowise health check` on what the command records and blocks it when the gate fails ([details](../start/CI.md#before-an-agent-commits-or-pushes)) |
| **Command rewrite (distill)** | Claude Code, Codex, Cursor | `repowise hook rewrite install`, or Yes at the `repowise init` prompt | `Bash` / `PowerShell` (Cursor: `Shell`) | Rewrites noisy commands to `repowise distill <cmd>` |
| **Codex context and staleness** | Codex | `repowise init --codex` | SessionStart, edits, shell | Reminds Codex to use the MCP tools and flags stale context after git operations |
diff --git a/docs/reference/CLI_REFERENCE.md b/docs/reference/CLI_REFERENCE.md
index d1d9af066..4f164b7dd 100644
--- a/docs/reference/CLI_REFERENCE.md
+++ b/docs/reference/CLI_REFERENCE.md
@@ -42,7 +42,7 @@ Grouped by task; `PATH` and flags are in each command's section.
status`](#repowise-hook-status), [`hook uninstall`](#repowise-hook-uninstall), [`hook stats`](#repowise-hook-stats),
[`hook backfill`](#repowise-hook-backfill), [`hook rewrite`](#repowise-hook-rewrite-installuninstallstatus), [`hook
read-skeleton|search-digest|read-reread`](#repowise-hook-read-skeletonsearch-digestread-reread),
- [`augment`](#repowise-augment)
+ [`hook health-gate`](#repowise-hook-health-gate-installuninstallstatus), [`augment`](#repowise-augment)
- **Server:** [`serve`](#repowise-serve-path), [`mcp`](#repowise-mcp-path)
- **Workspace:** [`workspace list`](#repowise-workspace-list), [`workspace add`](#repowise-workspace-add-path),
[`workspace remove`](#repowise-workspace-remove-alias), [`workspace scan`](#repowise-workspace-scan-path), [`workspace
@@ -1901,6 +1901,19 @@ repowise hook read-reread status -w
- No hook to install: `init`'s PostToolUse hook carries all three; these set the verdict in `.repowise/config.yaml` (`init` sets it from `--distill-hook`).
- `uninstall` returns whole results (the digest rides alongside again). `status` says on/off and, when off, points to `repowise saved`. With no `.repowise/` it asks for `repowise init`.
+### `repowise hook health-gate install|uninstall|status`
+
+Opt-in, off by default: Claude Code's `git commit` and `git push` in this repo run
+[`repowise health check`](#repowise-health-check-revspec) first and are denied when the gate fails (exit 1). Optional
+`PATH`, `-w`/`--no-workspace`.
+
+- `install` sets `hooks.health_gate: true` in `.repowise/config.yaml` and adds a PreToolUse entry to the repo's
+ `.claude/settings.local.json`; `uninstall` (and `hook uninstall`) removes both. `init` and `upgrade` never write either.
+- A commit is checked on the staged change, including `git add` earlier in the same command and `-a`; a push on
+ `@{u}...HEAD`, else the default branch's merge-base. `--amend`, pathspecs, merges in progress, other branches, tags,
+ `--delete`, and a `git add` after another command in the chain pass
+ unchecked, as does anything that keeps the check from finishing within 20 s.
+
## Utility Commands
### `repowise mcp [PATH]`
diff --git a/docs/reference/CONFIG.md b/docs/reference/CONFIG.md
index 0a76d23e4..bc246c08c 100644
--- a/docs/reference/CONFIG.md
+++ b/docs/reference/CONFIG.md
@@ -260,6 +260,7 @@ overrides a key for one session.
| `read_reread` | `false` | Serve an unchanged repeat Read as a short notice. |
| `search_digest` | `false` | Serve multi-file grep floods as a digest. |
| `coverage_reingest` | `false` | Re-ingest coverage after an agent's full test run, at a process start per shell command ([test intelligence](../layers/TEST_INTELLIGENCE.md)). |
+| `health_gate` | `false` | Block an agent's `git commit` / `git push` that fails `repowise health check`; set with `repowise hook health-gate install` ([CI](../start/CI.md#before-an-agent-commits-or-pushes)). |
**`read_skeleton`**
diff --git a/docs/reference/HOOKS_REFERENCE.md b/docs/reference/HOOKS_REFERENCE.md
index c223dbf2f..c3b59b4b6 100644
--- a/docs/reference/HOOKS_REFERENCE.md
+++ b/docs/reference/HOOKS_REFERENCE.md
@@ -13,6 +13,7 @@ hand. For what each hook does and when it fires, see [HOOKS.md](../agent/HOOKS.m
| Claude Code | `PreToolUse` (opt-in) | `Bash\|PowerShell` | `repowise-rewrite` | `~/.claude/settings.json` |
| Claude Code | `PostToolUse` (opt-in decision capture prompt) | `Bash\|PowerShell` | `repowise-augment` (guarded) | `~/.claude/settings.json` |
| Claude Code | `PostToolUse` and `PostToolUseFailure` (opt-in coverage re-ingest) | `Bash\|PowerShell` | `repowise-augment --coverage-only` (guarded) | the repo's `.claude/settings.local.json` |
+| Claude Code | `PreToolUse` (opt-in health gate) | `Bash\|PowerShell` | `repowise-augment --health-gate` (guarded) | the repo's `.claude/settings.local.json` |
| Codex | `PreToolUse` (opt-in) | the shell tool | `repowise-rewrite --agent codex` | `~/.codex/hooks.json` |
| Codex | `SessionStart` | `startup\|resume\|clear` | `repowise-augment --client codex` | the repo's `.codex/hooks.json` |
| Codex | `PostToolUse` | `Bash\|shell_command`, `apply_patch\|Edit\|Write` | `repowise-augment --client codex` | the repo's `.codex/hooks.json` |
@@ -24,8 +25,9 @@ Which switch turns each opt-in entry on:
| Command rewrite | `repowise hook rewrite install`, or Yes at the `repowise init` prompt |
| Decision capture prompt | `repowise decision config capture-prompt --on` ([decisions](../layers/DECISIONS.md)). The entry is per install, so one repo opting in adds a process start on shell calls for every repo on the machine; repos with the policy off return at once |
| Coverage re-ingest | `hooks.coverage_reingest: true` in `.repowise/config.yaml`, applied by the next `repowise coverage add`, `init` or `update` ([test intelligence](../layers/TEST_INTELLIGENCE.md)) |
+| Health gate | `repowise hook health-gate install`, which writes `hooks.health_gate: true` and the entry together |
-The Claude Code plugin does not carry the coverage re-ingest entries.
+The Claude Code plugin does not carry the coverage re-ingest or health-gate entries.
`repowise uninstall` removes them.
## The presence guard
diff --git a/docs/start/CI.md b/docs/start/CI.md
index aa2ea7a63..22671bffe 100644
--- a/docs/start/CI.md
+++ b/docs/start/CI.md
@@ -563,6 +563,15 @@ health-fail-at: medium
Findings that do not fail warn. On GitLab, set `REPOWISE_HEALTH: "true"`.
+### Before an agent commits or pushes
+
+`repowise hook health-gate install` runs the same check when Claude Code runs
+`git commit` (on the staged change) or `git push` (on `@{u}...HEAD`, else the
+default branch's merge-base) in this repo, and blocks the command when the gate
+fails. It is off by default, and `init` and `upgrade` never turn it on.
+Anything that stops the check from running within 20 s lets the command
+through; `repowise hook health-gate uninstall` turns it off.
+
## Gate on change risk
The [shared workflow](#github-actions) shows the input in use.
diff --git a/packages/cli/src/repowise/cli/agent_targets/targets/claude_code.py b/packages/cli/src/repowise/cli/agent_targets/targets/claude_code.py
index 24b344153..b2519b35f 100644
--- a/packages/cli/src/repowise/cli/agent_targets/targets/claude_code.py
+++ b/packages/cli/src/repowise/cli/agent_targets/targets/claude_code.py
@@ -473,10 +473,13 @@ class ClaudeCodeTarget:
from repowise.cli.editor_integrations.claude_config import (
claude_code_local_settings_path,
set_repo_coverage_hook,
+ set_repo_health_gate_hook,
)
- # The coverage re-ingest entries `coverage add` / init / update wrote.
- if set_repo_coverage_hook(repo_path, False) is not None:
+ # The coverage re-ingest entries `coverage add` / init / update wrote,
+ # and the health-gate entry `hook health-gate install` wrote.
+ coverage = set_repo_coverage_hook(repo_path, False)
+ if (set_repo_health_gate_hook(repo_path, False) or coverage) is not None:
result.record(claude_code_local_settings_path(repo_path), FileAction.REMOVED)
return result
diff --git a/packages/cli/src/repowise/cli/augment_hook.py b/packages/cli/src/repowise/cli/augment_hook.py
index 0083f36ae..ca4fffa57 100644
--- a/packages/cli/src/repowise/cli/augment_hook.py
+++ b/packages/cli/src/repowise/cli/augment_hook.py
@@ -43,16 +43,23 @@ def main() -> None:
response_stream = sys.stdout
with contextlib.redirect_stdout(sys.stderr):
try:
- from repowise.cli.commands.augment_cmd import _run_augment, command
-
- command._response_stream = response_stream
- try:
- _run_augment(
- client=_parse_client_arg(sys.argv[1:]),
- coverage_only="--coverage-only" in sys.argv,
- )
- finally:
- command._response_stream = None
+ if "--health-gate" in sys.argv[1:]:
+ # The opt-in PreToolUse gate: its own stdlib-only module, so a
+ # shell call that is not a commit or push pays no augment import.
+ from repowise.cli.health_gate_hook import run
+
+ run(sys.stdin, response_stream)
+ else:
+ from repowise.cli.commands.augment_cmd import _run_augment, command
+
+ command._response_stream = response_stream
+ try:
+ _run_augment(
+ client=_parse_client_arg(sys.argv[1:]),
+ coverage_only="--coverage-only" in sys.argv,
+ )
+ finally:
+ command._response_stream = None
except (SystemExit, KeyboardInterrupt):
raise
except BaseException:
diff --git a/packages/cli/src/repowise/cli/commands/hook_cmd.py b/packages/cli/src/repowise/cli/commands/hook_cmd.py
index 4349c12ce..c1058721f 100644
--- a/packages/cli/src/repowise/cli/commands/hook_cmd.py
+++ b/packages/cli/src/repowise/cli/commands/hook_cmd.py
@@ -101,11 +101,12 @@ def hook_install(path: str | None, workspace: bool, no_workspace: bool, security
help="Force single-repo mode even when invoked from a workspace.",
)
def hook_uninstall(path: str | None, workspace: bool, no_workspace: bool) -> None:
- """Remove everything repowise installed: the post-commit hook and the security block."""
+ """Remove everything repowise installed: the post-commit hook, the security block, the health gate."""
from repowise.cli.hooks import uninstall, uninstall_security
target = _hook_target(path, workspace, no_workspace)
_run_security_action(target, uninstall_security)
+ _apply_health_gate(target, enabled=False, quiet=True)
_run_post_commit_action(target, uninstall, action="uninstalled")
@@ -650,6 +651,86 @@ def read_reread_status(path: str | None, workspace: bool, no_workspace: bool) ->
)
+@hook_group.group("health-gate")
+def health_gate_group() -> None:
+ """Manage the opt-in health gate on agent commits and pushes (Claude Code).
+
+ When on, a `git commit` or `git push` that Claude Code runs in this repo
+ first runs `repowise health check` on what it would record (the staged
+ change, or the commits the push sends) and is blocked when the gate
+ fails. Anything that keeps the check from running lets the command
+ through. Off by default: `repowise init` and `upgrade` never turn it on.
+
+ `install` sets `hooks.health_gate: true` in .repowise/config.yaml and adds
+ a PreToolUse entry to the repo's .claude/settings.local.json; `uninstall`
+ removes both. Plain `git commit` in a terminal is not gated.
+ """
+
+
+@health_gate_group.command("install")
[email protected]("path", required=False, default=None)
[email protected]("--workspace", "-w", is_flag=True, default=False, help="Force workspace mode.")
[email protected]("--no-workspace", is_flag=True, default=False, help="Force single-repo mode.")
+def health_gate_install(path: str | None, workspace: bool, no_workspace: bool) -> None:
+ """Gate agent commits and pushes on `repowise health check` in this repo."""
+ _apply_health_gate(_hook_target(path, workspace, no_workspace), enabled=True)
+
+
+@health_gate_group.command("uninstall")
[email protected]("path", required=False, default=None)
[email protected]("--workspace", "-w", is_flag=True, default=False, help="Force workspace mode.")
[email protected]("--no-workspace", is_flag=True, default=False, help="Force single-repo mode.")
+def health_gate_uninstall(path: str | None, workspace: bool, no_workspace: bool) -> None:
+ """Stop gating agent commits and pushes in this repo."""
+ _apply_health_gate(_hook_target(path, workspace, no_workspace), enabled=False)
+
+
+def _apply_health_gate(target, *, enabled: bool, quiet: bool = False) -> None:
+ """Write ``hooks.health_gate`` and the repo-local Claude Code entry together.
+
+ *quiet* reports only repos where something was removed (``hook uninstall``).
+ """
+ from repowise.cli.commands.augment_cmd._shared import hook_flag_enabled
+ from repowise.cli.editor_integrations.claude_config import set_repo_health_gate_hook
+ from repowise.cli.helpers import save_hook_surface_enabled
+
+ repos = _target_repo_paths(target)
+ for repo_path in repos:
+ was_on = hook_flag_enabled(repo_path, "health_gate")
+ if enabled or was_on:
+ save_hook_surface_enabled(repo_path, "health_gate", enabled=enabled)
+ changed = set_repo_health_gate_hook(repo_path, enabled)
+ if quiet and not (was_on or changed):
+ continue
+ word = "[green]on[/green]" if enabled else "[yellow]off[/yellow]"
+ console.print(f" Health gate on agent commits and pushes: {word} ({repo_path})")
+ if not repos and not quiet:
+ console.print(" [yellow]No indexed repo here — run `repowise init` first.[/yellow]")
+
+
+@health_gate_group.command("status")
[email protected]("path", required=False, default=None)
[email protected]("--workspace", "-w", is_flag=True, default=False, help="Force workspace mode.")
[email protected]("--no-workspace", is_flag=True, default=False, help="Force single-repo mode.")
+def health_gate_status(path: str | None, workspace: bool, no_workspace: bool) -> None:
+ """Report whether agent commits and pushes are gated, and whether the entry is in place."""
+ from repowise.cli.commands.augment_cmd._shared import hook_flag_enabled
+ from repowise.cli.editor_integrations.claude_config import repo_health_gate_hook_installed
+
+ target = _hook_target(path, workspace, no_workspace)
+ for repo_path in _target_repo_paths(target):
+ on = hook_flag_enabled(repo_path, "health_gate")
+ entry = repo_health_gate_hook_installed(repo_path)
+ icon = "[green]✓[/green]" if on and entry else "[dim]✗[/dim]"
+ console.print(f" {icon} health gate: {'on' if on and entry else 'off'} ({repo_path})")
+ if on != entry:
+ missing = "the Claude Code entry" if on else "hooks.health_gate: true"
+ console.print(
+ f" [yellow]{missing} is missing, so nothing is gated; "
+ "`repowise hook health-gate install` sets both.[/yellow]"
+ )
+
+
@hook_group.group("search-digest")
def search_digest_group() -> None:
"""Manage digest-served searches (Claude Code).
diff --git a/packages/cli/src/repowise/cli/editor_integrations/claude_config.py b/packages/cli/src/repowise/cli/editor_integrations/claude_config.py
index becece17a..14deb525d 100644
--- a/packages/cli/src/repowise/cli/editor_integrations/claude_config.py
+++ b/packages/cli/src/repowise/cli/editor_integrations/claude_config.py
@@ -388,6 +388,26 @@ def _is_coverage_hook(hook: object) -> bool:
return "--coverage-only" in _hook_command(hook) and _is_repowise_hook(hook)
+def _health_gate_entry() -> dict:
+ from repowise.core.owned_paths import HEALTH_GATE_HOOK_COMMAND
+
+ return {
+ "matcher": SHELL_TOOL_MATCHER,
+ "hooks": [
+ {
+ "type": "command",
+ "command": HEALTH_GATE_HOOK_COMMAND,
+ # Above the gate's own 20 s budget, so the gate times out first and fails open.
+ "timeout": 30,
+ }
+ ],
+ }
+
+
+def _is_health_gate_hook(hook: object) -> bool:
+ return "--health-gate" in _hook_command(hook) and _is_repowise_hook(hook)
+
+
def claude_code_augment_installed() -> bool:
"""Whether ``~/.claude/settings.json`` carries the repowise augment hooks."""
path = _claude_code_settings_path()
@@ -409,9 +429,38 @@ def set_repo_coverage_hook(repo_path: Path, enabled: bool) -> Path | None:
settings files. Returns the file when it changed, else ``None``. A file
this leaves empty is removed.
"""
+ return _set_repo_local_hook(
+ repo_path, enabled, _COVERAGE_HOOK_EVENTS, _coverage_entry, _is_coverage_hook
+ )
+
+
+def set_repo_health_gate_hook(repo_path: Path, enabled: bool) -> Path | None:
+ """Add or remove the opt-in health-gate PreToolUse entry, as :func:`set_repo_coverage_hook`.
+
+ Repo-local for the same reason: only a repository that turned the gate on
+ pays a process start per shell call.
+ """
+ return _set_repo_local_hook(
+ repo_path, enabled, ("PreToolUse",), _health_gate_entry, _is_health_gate_hook
+ )
+
+
+def repo_health_gate_hook_installed(repo_path: Path) -> bool:
+ """Whether the repo's ``settings.local.json`` carries the health-gate entry."""
+ settings = _read_local_settings(claude_code_local_settings_path(repo_path), False)
+ hooks = settings.get("hooks") if isinstance(settings, dict) else None
+ entries = hooks.get("PreToolUse") if isinstance(hooks, dict) else None
+ if not isinstance(entries, list):
+ return False
+ return any(_is_health_gate_hook(h) for e in _own_entries(entries) for h in _hooks_of(e))
+
+
+def _set_repo_local_hook(
+ repo_path: Path, enabled: bool, events: tuple[str, ...], entry, is_ours
+) -> Path | None:
path = claude_code_local_settings_path(repo_path)
settings = _read_local_settings(path, enabled)
- if settings is None or not _apply_coverage_entries(settings, enabled):
+ if settings is None or not _apply_local_entries(settings, enabled, events, entry, is_ours):
return None
return _write_or_remove(path, settings)
@@ -426,33 +475,38 @@ def _read_local_settings(path: Path, enabled: bool) -> dict | None:
return None
-def _apply_coverage_entries(settings: dict, enabled: bool) -> bool:
+def _apply_local_entries(
+ settings: dict, enabled: bool, events: tuple[str, ...], entry, is_ours
+) -> bool:
"""Add or remove our entry under each event of *settings*, in place; whether it changed."""
hooks = settings.setdefault("hooks", {}) if enabled else settings.get("hooks")
if not isinstance(hooks, dict):
return False
changed = False
- for event in _COVERAGE_HOOK_EVENTS:
- changed = _apply_coverage_entry(hooks, event, enabled) or changed
+ for event in events:
+ changed = _apply_local_entry(hooks, event, enabled, entry, is_ours) or changed
if not hooks:
settings.pop("hooks", None)
return changed
-def _apply_coverage_entry(hooks: dict, event: str, enabled: bool) -> bool:
+def _own_entries(entries: list) -> list:
+ """Ours only inside a shell-matcher entry: the same command elsewhere is someone else's."""
+ return [e for e in entries if isinstance(e, dict) and e.get("matcher") == SHELL_TOOL_MATCHER]
+
+
+def _apply_local_entry(hooks: dict, event: str, enabled: bool, entry, is_ours) -> bool:
entries = hooks.setdefault(event, []) if enabled else hooks.get(event)
if not isinstance(entries, list):
return False
- # Ours only inside a shell-matcher entry: the same command under any other
- # matcher was written by someone else and is left alone.
- own = [e for e in entries if isinstance(e, dict) and e.get("matcher") == SHELL_TOOL_MATCHER]
- present = any(_is_coverage_hook(h) for e in own for h in _hooks_of(e))
+ own = _own_entries(entries)
+ present = any(is_ours(h) for e in own for h in _hooks_of(e))
changed = enabled != present
if changed and enabled:
- entries.append(_coverage_entry())
+ entries.append(entry())
elif changed:
kept = list(own)
- _strip_hooks(kept, _is_coverage_hook)
+ _strip_hooks(kept, is_ours)
dropped = [e for e in own if not any(e is k for k in kept)]
entries[:] = [e for e in entries if not any(e is d for d in dropped)]
if not entries:
diff --git a/packages/cli/src/repowise/cli/health_gate_hook.py b/packages/cli/src/repowise/cli/health_gate_hook.py
new file mode 100644
index 000000000..4915d6069
--- /dev/null
+++ b/packages/cli/src/repowise/cli/health_gate_hook.py
@@ -0,0 +1,478 @@
+"""PreToolUse shell hook: run ``repowise health check`` before an agent's ``git commit`` or ``git push``.
+
+Opt-in per repository and off by default. It acts only where
+``hooks.health_gate: true`` is set, which ``repowise hook health-gate install``
+writes together with the repo-local Claude Code entry; ``init``, ``upgrade``
+and the self-heal never write either.
+
+The verdict is the command's own: this runs ``repowise health check`` as a
+subprocess and blocks only on its exit 1 (the gate failed). Everything else
+fails open, with no output: exit 2, a crash, a timeout past
+:data:`BUDGET_SECONDS`, a command shape this cannot read, no git, no index.
+
+What is checked is what the command would record:
+
+* ``git commit``: the staged index against ``HEAD``, after replaying any
+ ``git add`` earlier in the same chain and ``-a``. It is built in a temporary
+ index and object directory, so the repository is not touched. ``--amend``,
+ pathspecs, ``--only``/``--include`` and interactive forms are not read.
+* ``git push``: ``@{u}...HEAD``, else the merge-base with the default branch
+ (the command's own default). A push of another branch, tags, ``--all``,
+ ``--mirror``, ``--delete`` or ``--dry-run`` is not read.
+
+Module scope is stdlib only: this fires on every shell call in an opted-in
+repository and returns on the first regex for everything that is not git. The
+config read (through the augment package) is paid only for a commit or push.
+"""
+
+from __future__ import annotations
+
+import json
+import os
+import re
+import shlex
+import shutil
+import subprocess
+import sys
+import tempfile
+import time
+from dataclasses import dataclass, replace
+from pathlib import Path
+from typing import TextIO
+
+#: Wall-clock budget for the whole gate; past it the command goes through.
+BUDGET_SECONDS = 20.0
+_GIT_TIMEOUT = 5.0
+#: Shown in the deny reason; more than this is counted, not listed.
+_MAX_LISTED = 5
+
+_QUICK_RE = re.compile(r"\bgit\b[\s\S]*\b(?:commit|push)\b")
+_OPERATORS = frozenset({"&&", "||", ";", "|", "&", "|&", ";;", "(", ")"})
+_REDIRECT_RE = re.compile(r"^[<>&]+$")
+#: Unquoted, these make the token stream misleading; the command is not read.
+_UNREAD_TOKENS = frozenset({"<<", "<<-", "<<<", "("})
+#: Commands that write nothing a commit could pick up.
+_INERT_COMMANDS = frozenset({"echo", "printf", "pwd", "true", ":", "cd"})
+#: :class:`GitCall` verb for any other command in the chain.
+SHELL_STEP = "(shell)"
+#: Global ``git`` options that take the next token as their value.
+_GIT_VALUE_OPTS = frozenset({"-C", "-c", "--git-dir", "--work-tree", "--namespace", "--config-env"})
+#: Global options that point git somewhere this hook does not follow.
+_GIT_OPAQUE_OPTS = frozenset({"--git-dir", "--work-tree", "--namespace", "--bare"})
+#: Verbs that may run earlier in the chain without changing what is committed or pushed.
+_READ_ONLY_VERBS = frozenset(
+ {"status", "diff", "log", "show", "fetch", "remote", "rev-parse", "ls-files", "describe"}
+)
+
+#: What may run before a commit in the same chain for its staged content to be read.
+_COMMIT_PRELUDE = _READ_ONLY_VERBS | {"add", SHELL_STEP}
+_OPERATION_HEADS = ("MERGE_HEAD", "CHERRY_PICK_HEAD", "REVERT_HEAD")
+
+_COMMIT_VALUE_SHORT = frozenset("mFCct")
+_COMMIT_VALUE_LONG = frozenset({
+ "--message", "--file", "--reuse-message", "--reedit-message", "--fixup", "--squash",
+ "--template", "--author", "--date", "--cleanup", "--trailer",
+})
+_COMMIT_UNREAD_LONG = frozenset({
+ "--amend", "--patch", "--interactive", "--only", "--include", "--dry-run",
+ "--pathspec-from-file", "--short", "--porcelain", "--long",
+})
+_COMMIT_UNREAD_SHORT = frozenset("poi")
+_ADD_UNREAD = frozenset({"-p", "--patch", "-i", "--interactive", "-e", "--edit", "-n", "--dry-run"})
+
+_PUSH_UNREAD = frozenset({
+ "--all", "--branches", "--mirror", "--tags", "--delete", "--dry-run", "--prune",
+})
+_PUSH_UNREAD_SHORT = frozenset("dn")
+_PUSH_VALUE = frozenset({"--repo", "-o", "--push-option", "--receive-pack", "--exec"})
+
+#: Identity for the throwaway snapshot commit, so an unset user.name cannot fail it.
+_SNAPSHOT_IDENTITY = {
+ "GIT_AUTHOR_NAME": "repowise", "GIT_AUTHOR_EMAIL": "repowise@localhost",
+ "GIT_COMMITTER_NAME": "repowise", "GIT_COMMITTER_EMAIL": "repowise@localhost",
+}
+
+
+@dataclass(frozen=True)
+class GitCall:
+ """One ``git`` invocation in a shell command, with the directory it runs in."""
+
+ verb: str
+ cwd: str
+ args: tuple[str, ...]
+ #: Pointed elsewhere (``--git-dir``, ``--work-tree``): not read.
+ opaque: bool = False
+
+
+def run(stdin: TextIO, out: TextIO) -> None:
+ """Read one PreToolUse payload from *stdin*; write a deny to *out* on a failed gate."""
+ try:
+ payload = json.loads(stdin.read() or "{}")
+ except ValueError:
+ return
+ reason = deny_reason(payload) if isinstance(payload, dict) else None
+ if reason:
+ out.write(json.dumps({"hookSpecificOutput": {
+ "hookEventName": "PreToolUse",
+ "permissionDecision": "deny",
+ "permissionDecisionReason": reason,
+ }}))
+ out.flush()
+
+
+def deny_reason(payload: dict) -> str | None:
+ """Why this shell call is blocked, or ``None`` to let it run (every unclear case)."""
+ from repowise.cli.agent_adapters.claude_code import SHELL_TOOL_NAMES
+
+ if payload.get("hook_event_name") != "PreToolUse":
+ return None
+ if payload.get("tool_name") not in SHELL_TOOL_NAMES:
+ return None
+ tool_input = payload.get("tool_input")
+ command = tool_input.get("command") if isinstance(tool_input, dict) else None
+ cwd = payload.get("cwd")
+ if not isinstance(command, str) or not _QUICK_RE.search(command) or not isinstance(cwd, str):
+ return None
+ try:
+ return gate(command, cwd)
+ except Exception:
+ # Fail open: a broken gate never blocks a commit.
+ return None
+
+
+def gate(command: str, cwd: str, *, budget: float = BUDGET_SECONDS) -> str | None:
+ """The deny reason for the first commit or push in *command* that fails the gate."""
+ calls = git_calls(command, cwd)
+ deadline = time.monotonic() + budget
+ for i, call in enumerate(calls):
+ if call.verb not in ("commit", "push") or call.opaque or not _enabled(call.cwd):
+ continue
+ check = _check_commit if call.verb == "commit" else _check_push
+ reason = check(call, calls[:i], deadline)
+ if reason:
+ return reason
+ return None
+
+
+def _enabled(cwd: str) -> bool:
+ from repowise.cli.commands.augment_cmd._shared import _find_repo_root, hook_flag_enabled
+
+ repo = _find_repo_root(Path(cwd))
+ return repo is not None and hook_flag_enabled(repo, "health_gate")
+
+
+# -- reading the command ------------------------------------------------------
+
+
+def git_calls(command: str, cwd: str) -> list[GitCall]:
+ """Every ``git`` call in *command*, in order; ``[]`` when it does not tokenize.
+
+ Any other command that could write files is kept as a :data:`SHELL_STEP`,
+ so a check knows the tree may change before the commit runs.
+ """
+ calls: list[GitCall] = []
+ here = cwd
+ for raw in _segments(command):
+ tokens, git_env = _unwrap(raw)
+ if len(tokens) >= 2 and tokens[0] == "cd":
+ here = os.path.join(here, os.path.expanduser(tokens[1]))
+ elif tokens and Path(tokens[0]).name.lower() in ("git", "git.exe"):
+ call = _git_call(tokens[1:], here)
+ if call is not None:
+ calls.append(replace(call, opaque=True) if git_env else call)
+ elif tokens and tokens[0] not in _INERT_COMMANDS:
+ calls.append(GitCall(SHELL_STEP, here, ()))
+ return calls
+
+
+def _segments(command: str) -> list[list[str]]:
+ """The simple commands in *command*, split on shell operators, redirections dropped."""
+ lexer = shlex.shlex(command.replace("\n", " ; "), posix=True, punctuation_chars=True)
+ lexer.whitespace_split = True
+ try:
+ tokens = list(lexer)
+ except ValueError:
+ return []
+ if _UNREAD_TOKENS & set(tokens):
+ return [] # a heredoc body or a subshell's ``cd`` would be misread
+ segments: list[list[str]] = [[]]
+ skip_next = False
+ for i, token in enumerate(tokens):
+ if skip_next:
+ skip_next = False
+ elif token in _OPERATORS:
+ segments.append([])
+ elif _REDIRECT_RE.match(token):
+ skip_next = True # the redirection's target
+ elif token in ("0", "1", "2") and i + 1 < len(tokens) and _REDIRECT_RE.match(tokens[i + 1]):
+ continue # the ``2`` of ``2>&1``
+ else:
+ segments[-1].append(token)
+ return [s for s in segments if s]
+
+
+def _unwrap(tokens: list[str]) -> tuple[list[str], bool]:
+ """*tokens* without leading ``VAR=value`` and the ``repowise distill`` wrapper.
+
+ The flag says a ``GIT_*`` assignment was among them (``GIT_DIR``,
+ ``GIT_INDEX_FILE``, ...): git then reads somewhere this hook does not.
+ """
+ git_env = False
+ while tokens and re.match(r"^\w+=", tokens[0]):
+ git_env = git_env or tokens[0].startswith("GIT_")
+ tokens = tokens[1:]
+ if tokens[:2] != ["repowise", "distill"]:
+ return tokens, git_env
+ rest = tokens[2:]
+ if rest[:1] == ["--source"]:
+ rest = rest[2:]
+ if len(rest) == 1: # the rewritten form quotes the whole command
+ segments = _segments(rest[0])
+ return _unwrap(segments[0]) if len(segments) == 1 else ([], git_env)
+ return rest, git_env
+
+
+def _git_call(args: list[str], cwd: str) -> GitCall | None:
+ """The verb, effective directory and arguments of one ``git ...`` command."""
+ opaque = False
+ i = 0
+ while i < len(args) and args[i].startswith("-"):
+ name = args[i].split("=", 1)[0]
+ opaque = opaque or name in _GIT_OPAQUE_OPTS
+ if args[i] in _GIT_VALUE_OPTS:
+ if i + 1 >= len(args):
+ return None
+ if args[i] == "-C":
+ cwd = os.path.join(cwd, os.path.expanduser(args[i + 1]))
+ i += 1
+ i += 1
+ if i >= len(args):
+ return None
+ return GitCall(args[i], cwd, tuple(args[i + 1:]), opaque)
+
+
+def commit_plan(args: tuple[str, ...]) -> str | None:
+ """``"staged"`` or ``"all"`` (``-a``) for a commit this can read; ``None`` otherwise."""
+ plan = "staged"
+ i = 0
+ while i < len(args):
+ arg = args[i]
+ i += 1
+ if arg == "--":
+ return None if args[i:] else plan
+ if arg.startswith("--"):
+ name = arg.split("=", 1)[0]
+ if name in _COMMIT_UNREAD_LONG:
+ return None
+ if name == "--all":
+ plan = "all"
+ elif name in _COMMIT_VALUE_LONG and "=" not in arg:
+ i += 1
+ continue
+ if not arg.startswith("-") or arg == "-":
+ return None # a pathspec: the commit is not the index
+ step = _short_cluster(arg[1:])
+ if step is None:
+ return None
+ all_flag, takes_next = step
+ plan = "all" if all_flag else plan
+ i += 1 if takes_next else 0
+ return plan
+
+
+def _short_cluster(flags: str) -> tuple[bool, bool] | None:
+ """``(has -a, value is the next token)`` for one ``-xyz`` cluster; ``None`` if unread."""
+ has_all = False
+ for j, ch in enumerate(flags):
+ if ch in _COMMIT_UNREAD_SHORT:
+ return None
+ has_all = has_all or ch == "a"
+ if ch in _COMMIT_VALUE_SHORT:
+ return has_all, j == len(flags) - 1
+ if ch in "Su": # optional value, attached only
+ break
+ return has_all, False
+
+
+def push_targets_head(args: tuple[str, ...], branch: str) -> bool:
+ """Whether this push sends the current branch and nothing else this cannot read."""
+ positional: list[str] = []
+ i = 0
+ while i < len(args):
+ arg = args[i]
+ i += 1
+ if arg.split("=", 1)[0] in _PUSH_UNREAD:
+ return False
+ if arg in _PUSH_VALUE:
+ i += 1
+ elif arg.startswith("--"):
+ continue
+ elif arg.startswith("-"):
+ if _PUSH_UNREAD_SHORT & set(arg[1:]):
+ return False
+ i += 1 if arg.endswith("o") else 0
+ else:
+ positional.append(arg)
+ allowed = {"HEAD", branch, f"refs/heads/{branch}"} - {""}
+ for ref in positional[1:]:
+ src, _, dst = ref.lstrip("+").partition(":")
+ # A push to another remote branch is judged against the wrong upstream.
+ if src not in allowed or (dst and dst not in allowed - {"HEAD"}):
+ return False
+ return True
+
+
+# -- checking -----------------------------------------------------------------
+
+
+def _check_commit(call: GitCall, before: list[GitCall], deadline: float) -> str | None:
+ plan = commit_plan(call.args)
+ root = _git(call.cwd, "rev-parse", "--show-toplevel")
+ if plan is None or not root or any(c.verb not in _COMMIT_PRELUDE for c in before):
+ return None
+ adds = [c for c in before if c.verb == "add" and not c.opaque]
+ if (adds or plan == "all") and any(c.verb == SHELL_STEP for c in before):
+ return None # that step may rewrite the files before they are staged
+ head = _git(root, "rev-parse", "--verify", "-q", "HEAD")
+ if not head or _mid_operation(root):
+ return None # the first commit, or a merge whose other side is not this change
+ with tempfile.TemporaryDirectory(prefix="repowise-gate-") as tmp:
+ env = _scratch_env(root, Path(tmp))
+ snapshot = _stage(root, head, plan, adds, env, deadline) if env is not None else None
+ if snapshot is None:
+ return None
+ env.pop("GIT_INDEX_FILE")
+ failing = _run_health_check(root, f"{head}..{snapshot}", env, deadline)
+ return _reason("commit", failing, None) if failing else None
+
+
+def _mid_operation(root: str) -> bool:
+ """A merge, cherry-pick or revert in progress: the commit carries another side's lines."""
+ return any(_git(root, "rev-parse", "-q", "--verify", ref) for ref in _OPERATION_HEADS)
+
+
+def _stage(
+ root: str, head: str, plan: str, adds: list[GitCall], env: dict, deadline: float
+) -> str | None:
+ """Replay the chain's ``git add`` (and ``-a``) on the scratch index; its snapshot commit."""
+ for add in adds:
+ if time.monotonic() > deadline:
+ return None
+ if _git(add.cwd, "rev-parse", "--show-toplevel") != root:
+ continue
+ if _ADD_UNREAD & set(add.args) or _git(add.cwd, "add", *add.args, env=env) is None:
+ return None
+ if plan == "all" and _git(root, "add", "-u", env=env) is None:
+ return None
+ return _snapshot(root, head, env)
+
+
+def _check_push(call: GitCall, before: list[GitCall], deadline: float) -> str | None:
+ root = _git(call.cwd, "rev-parse", "--show-toplevel")
+ # An earlier commit in the chain moves HEAD; its own check covers it.
+ if not root or any(c.verb not in _READ_ONLY_VERBS | {SHELL_STEP} for c in before):
+ return None
+ branch = _git(root, "symbolic-ref", "--short", "-q", "HEAD") or ""
+ if not push_targets_head(call.args, branch):
+ return None
+ head = _git(root, "rev-parse", "--verify", "-q", "HEAD")
+ upstream = _git(root, "rev-parse", "--verify", "-q", "@{u}")
+ if not head or head == upstream:
+ return None
+ revspec = f"{upstream}...{head}" if upstream else None
+ failing = _run_health_check(root, revspec, dict(os.environ), deadline)
+ shown = "@{u}...HEAD" if upstream else None
+ return _reason("push", failing, shown) if failing else None
+
+
+def _scratch_env(root: str, tmp: Path) -> dict[str, str] | None:
+ """An environment whose index and new objects live in *tmp*, reading the repo's objects."""
+ index = _git(root, "rev-parse", "--path-format=absolute", "--git-path", "index")
+ objects = _git(root, "rev-parse", "--path-format=absolute", "--git-path", "objects")
+ if not index or not objects or not Path(index).is_file():
+ return None
+ shutil.copyfile(index, tmp / "index")
+ (tmp / "objects").mkdir()
+ inherited = os.environ.get("GIT_ALTERNATE_OBJECT_DIRECTORIES")
+ try: # the repo's own alternates (``--reference`` / ``--shared`` clones)
+ own = (Path(objects) / "info" / "alternates").read_text(encoding="utf-8").split()
+ except OSError:
+ own = []
+ alternates = [objects, *(str(Path(objects) / a) for a in own), inherited]
+ return {
+ **os.environ,
+ **_SNAPSHOT_IDENTITY,
+ "GIT_INDEX_FILE": str(tmp / "index"),
+ "GIT_OBJECT_DIRECTORY": str(tmp / "objects"),
+ "GIT_ALTERNATE_OBJECT_DIRECTORIES": os.pathsep.join(filter(None, alternates)),
+ }
+
+
+def _snapshot(root: str, head: str, env: dict[str, str]) -> str | None:
+ """A commit of the scratch index on top of *head*; ``None`` when it equals *head*."""
+ tree = _git(root, "write-tree", env=env)
+ if not tree or tree == _git(root, "rev-parse", f"{head}^{{tree}}", env=env):
+ return None
+ return _git(root, "commit-tree", tree, "-p", head, "-m", "repowise health gate", env=env)
+
+
+def _run_health_check(
+ root: str, revspec: str | None, env: dict[str, str], deadline: float
+) -> list[dict]:
+ """The failing rows of ``repowise health check``; ``[]`` unless it exited 1 with them."""
+ remaining = deadline - time.monotonic()
+ if remaining <= 1:
+ return []
+ argv = [sys.executable, "-m", "repowise.cli.main", "health", "check"]
+ argv += [revspec] if revspec else []
+ argv += ["--path", root, "--format", "json"]
+ try:
+ proc = subprocess.run(
+ argv, cwd=root, env=env, capture_output=True, text=True, encoding="utf-8",
+ errors="replace", stdin=subprocess.DEVNULL, timeout=remaining, check=False,
+ )
+ except (OSError, subprocess.SubprocessError):
+ return []
+ if proc.returncode != 1:
+ return []
+ try:
+ failing = json.loads(proc.stdout)["gate"]["failing"]
+ except (ValueError, KeyError, TypeError):
+ return [] # exit 1 without the report is a crash, not a verdict
+ return [row for row in failing if isinstance(row, dict)] if isinstance(failing, list) else []
+
+
+def _reason(what: str, failing: list[dict], revspec: str | None) -> str:
+ """The short message the agent sees in place of the command's output."""
+ lines = [
+ f"repowise health gate: this {what} adds {len(failing)} health finding(s) that fail "
+ "the gate.",
+ ]
+ for row in failing[:_MAX_LISTED]:
+ where = str(row.get("file_path") or "?")
+ if row.get("line_number"):
+ where += f":{row['line_number']}"
+ lines.append(f" {where} {row.get('message', '')}")
+ if len(failing) > _MAX_LISTED:
+ lines.append(f" ... and {len(failing) - _MAX_LISTED} more")
+ report = ""
+ if what == "push":
+ report = f"; `repowise health check{' ' + revspec if revspec else ''}` shows the full report"
+ lines.append(
+ f"Fix them and {what} again{report}. The gate is opt-in for this repository: "
+ "`repowise hook health-gate uninstall` turns it off."
+ )
+ return "\n".join(lines)
+
+
+def _git(cwd: str, *args: str, env: dict[str, str] | None = None) -> str | None:
+ """``git`` stdout, stripped; ``None`` on any failure."""
+ try:
+ proc = subprocess.run(
+ ["git", "-C", cwd, *args], capture_output=True, text=True, encoding="utf-8",
+ errors="replace", stdin=subprocess.DEVNULL, env=env, timeout=_GIT_TIMEOUT,
+ check=False,
+ )
+ except (OSError, subprocess.SubprocessError):
+ return None
+ return proc.stdout.strip() if proc.returncode == 0 else None
diff --git a/packages/core/src/repowise/core/owned_paths.py b/packages/core/src/repowise/core/owned_paths.py
index 6f6d5fb7b..63f3ce81b 100644
--- a/packages/core/src/repowise/core/owned_paths.py
+++ b/packages/core/src/repowise/core/owned_paths.py
@@ -73,6 +73,11 @@ COVERAGE_HOOK_COMMAND = (
"if command -v repowise-augment >/dev/null 2>&1; "
"then exec repowise-augment --coverage-only; fi"
)
+#: The opt-in Claude Code health gate (PreToolUse), in ``.claude/settings.local.json``.
+HEALTH_GATE_HOOK_COMMAND = (
+ "if command -v repowise-augment >/dev/null 2>&1; "
+ "then exec repowise-augment --health-gate; fi"
+)
#: The Codex context and freshness hooks, in ``.codex/hooks.json``.
CODEX_HOOK_COMMAND = "repowise-augment --client codex"
#: What the cursor target writes above its block in a new rules file.
@@ -92,7 +97,7 @@ CURSOR_RULES_PREFIX = (
_DISTILL_TAG = "REPOWISE_DISTILL"
_COPILOT_OWNER_PAIR = ("<!-- REPOWISE_COPILOT_CLI:START -->", "<!-- REPOWISE_COPILOT_CLI:END -->")
-_HOOK_COMMANDS = (COVERAGE_HOOK_COMMAND, CODEX_HOOK_COMMAND)
+_HOOK_COMMANDS = (COVERAGE_HOOK_COMMAND, HEALTH_GATE_HOOK_COMMAND, CODEX_HOOK_COMMAND)
#: The server entry's key in every target's config (each target's ``SERVER_NAME``).
_SERVER_NAME = "repowise"
diff --git a/tests/unit/cli/test_health_gate_hook.py b/tests/unit/cli/test_health_gate_hook.py
new file mode 100644
index 000000000..cf330ffe5
--- /dev/null
+++ b/tests/unit/cli/test_health_gate_hook.py
@@ -0,0 +1,383 @@
+"""The opt-in PreToolUse health gate on agent ``git commit`` / ``git push``."""
+
+from __future__ import annotations
+
+import io
+import json
+import subprocess
+import sys
+from pathlib import Path
+
+import pytest
+from click.testing import CliRunner
+
+from repowise.cli import health_gate_hook as gate
+from repowise.cli.commands.hook_cmd import hook_group
+
+_NESTED = "def bad(x):\n" + "".join(
+ " " * (depth + 1) + f"if x > {depth}:\n" for depth in range(9)
+) + " " * 10 + "return x\n return 0\n"
+
+
+def _git(repo: Path, *args: str) -> str:
+ return subprocess.run(
+ ["git", "-C", str(repo), *args], capture_output=True, text=True, check=True
+ ).stdout.strip()
+
+
+def repo(tmp_path: Path) -> Path:
+ root = tmp_path / "repo"
+ root.mkdir()
+ _git(root, "init", "-q", "-b", "main")
+ _git(root, "config", "user.email", "[email protected]")
+ _git(root, "config", "user.name", "t")
+ (root / ".repowise").mkdir()
+ (root / "a.py").write_text("def ok():\n return 1\n", encoding="utf-8")
+ _git(root, "add", "a.py")
+ _git(root, "commit", "-qm", "base")
+ return root
+
+
+def _enable(repo: Path) -> None:
+ (repo / ".repowise" / "config.yaml").write_text("hooks:\n health_gate: true\n", "utf-8")
+
+
+def _payload(command: str, cwd: Path, tool: str = "Bash") -> dict:
+ return {
+ "hook_event_name": "PreToolUse",
+ "tool_name": tool,
+ "tool_input": {"command": command},
+ "cwd": str(cwd),
+ }
+
+
+def _no_health_check(monkeypatch) -> list:
+ """Record health-check calls instead of running them."""
+ calls: list = []
+ monkeypatch.setattr(
+ gate, "_run_health_check", lambda root, revspec, env, deadline: calls.append(revspec) or []
+ )
+ return calls
+
+
+# -- reading the command ------------------------------------------------------
+
+
+ ("command", "expected"),
+ [
+ ("git commit -m x", [("commit", "/r")]),
+ ("git add a.py && git commit -m 'a && b'", [("add", "/r"), ("commit", "/r")]),
+ ("git -C sub push", [("push", "sub")]),
+ ("cd sub && git commit -am x", [("commit", "sub")]),
+ ("FOO=1 git push origin HEAD 2>&1 | tail -5", [("push", "/r"), ("(shell)", "/r")]),
+ ('repowise distill "git push"', [("push", "/r")]),
+ ("echo git commit", []),
+ ("git log --grep commit", [("log", "/r")]),
+ ("git commit -m 'unbalanced", []),
+ ("cat <<EOF\ngit commit\nEOF", []),
+ ("(cd sub && git commit -m x)", []),
+ ("ruff check . && git commit -m x", [("(shell)", "/r"), ("commit", "/r")]),
+ ("echo hi && git commit -m x", [("commit", "/r")]),
+ ],
+)
+def test_git_calls_reads_verbs_and_directories(command, expected) -> None:
+ calls = gate.git_calls(command, "/r")
+ assert [(c.verb, Path(c.cwd).name if c.cwd != "/r" else "/r") for c in calls] == expected
+
+
+def test_git_dir_override_is_marked_opaque() -> None:
+ assert gate.git_calls("git --git-dir=x commit -m y", "/r")[0].opaque
+ assert gate.git_calls("GIT_INDEX_FILE=x git commit -m y", "/r")[0].opaque
+ assert not gate.git_calls("LANG=C git commit -m y", "/r")[0].opaque
+
+
+def test_a_quoted_heredoc_message_is_still_read() -> None:
+ command = "git commit -m \"$(cat <<'EOF'\nfix: x\n\nbody\nEOF\n)\""
+ assert [c.verb for c in gate.git_calls(command, "/r")] == ["commit"]
+
+
+ ("args", "plan"),
+ [
+ (("-m", "x"), "staged"),
+ (("-am", "x"), "all"),
+ (("--all", "--message", "x"), "all"),
+ (("-mx", "--no-verify"), "staged"),
+ (("--amend", "--no-edit"), None),
+ (("-m", "x", "a.py"), None),
+ (("-p",), None),
+ (("--only", "-m", "x"), None),
+ ],
+)
+def test_commit_plan(args, plan) -> None:
+ assert gate.commit_plan(args) == plan
+
+
+ ("args", "reads"),
+ [
+ ((), True),
+ (("-u", "origin", "HEAD"), True),
+ (("origin", "main"), True),
+ (("origin", "+main:main"), True),
+ (("origin", "other"), False),
+ (("--tags",), False),
+ (("origin", "--delete", "x"), False),
+ (("origin", ":main"), False),
+ (("--dry-run",), False),
+ (("origin", "HEAD:refs/heads/other"), False),
+ (("origin", "HEAD:main"), True),
+ ],
+)
+def test_push_targets_head(args, reads) -> None:
+ assert gate.push_targets_head(args, "main") is reads
+
+
+# -- off by default and failing open ------------------------------------------
+
+
+def test_off_without_the_config_key(repo, monkeypatch) -> None:
+ calls = _no_health_check(monkeypatch)
+ (repo / "b.py").write_text(_NESTED, encoding="utf-8")
+ _git(repo, "add", "b.py")
+ assert gate.deny_reason(_payload("git commit -m x", repo)) is None
+ assert calls == []
+
+
+def test_init_consent_never_turns_it_on() -> None:
+ from repowise.cli.helpers import HOOK_REPLACEMENT_SURFACES
+
+ assert "health_gate" not in HOOK_REPLACEMENT_SURFACES
+
+
+ "payload",
+ [
+ {"hook_event_name": "PostToolUse", "tool_name": "Bash", "tool_input": {"command": "git push"}},
+ {"hook_event_name": "PreToolUse", "tool_name": "Read", "tool_input": {"command": "git push"}},
+ {"hook_event_name": "PreToolUse", "tool_name": "Bash", "tool_input": {"command": ["git"]}},
+ {"hook_event_name": "PreToolUse", "tool_name": "Bash", "tool_input": {"command": "ls"}},
+ ],
+)
+def test_non_gated_payloads_pass(payload, tmp_path) -> None:
+ assert gate.deny_reason({**payload, "cwd": str(tmp_path)}) is None
+
+
+def test_bad_stdin_writes_nothing() -> None:
+ out = io.StringIO()
+ gate.run(io.StringIO("not json"), out)
+ gate.run(io.StringIO("[1]"), out)
+ assert out.getvalue() == ""
+
+
+def test_not_a_git_repository_passes(tmp_path, monkeypatch) -> None:
+ calls = _no_health_check(monkeypatch)
+ (tmp_path / ".repowise").mkdir()
+ _enable(tmp_path)
+ assert gate.deny_reason(_payload("git commit -m x", tmp_path)) is None
+ assert calls == []
+
+
[email protected]("returncode", [0, 2])
+def test_only_exit_1_blocks(repo, monkeypatch, returncode) -> None:
+ _enable(repo)
+ (repo / "b.py").write_text(_NESTED, encoding="utf-8")
+ _git(repo, "add", "b.py")
+ real_run = subprocess.run
+
+ def fake(argv, *args, **kwargs):
+ if argv[:3] == [sys.executable, "-m", "repowise.cli.main"]:
+ return subprocess.CompletedProcess(argv, returncode, '{"gate": {"failing": [{}]}}', "")
+ return real_run(argv, *args, **kwargs)
+
+ monkeypatch.setattr(gate.subprocess, "run", fake)
+ assert gate.deny_reason(_payload("git commit -m x", repo)) is None
+
+
+def test_timeout_and_crash_pass(repo, monkeypatch) -> None:
+ _enable(repo)
+ (repo / "b.py").write_text(_NESTED, encoding="utf-8")
+ _git(repo, "add", "b.py")
+ real_run = subprocess.run
+
+ def slow(argv, *args, **kwargs):
+ if argv[:3] == [sys.executable, "-m", "repowise.cli.main"]:
+ raise subprocess.TimeoutExpired(argv, kwargs.get("timeout"))
+ return real_run(argv, *args, **kwargs)
+
+ monkeypatch.setattr(gate.subprocess, "run", slow)
+ assert gate.deny_reason(_payload("git commit -m x", repo)) is None
+ monkeypatch.setattr(gate, "gate", lambda *a, **k: 1 / 0)
+ assert gate.deny_reason(_payload("git commit -m x", repo)) is None
+
+
+def test_an_exhausted_budget_skips_the_check(repo, monkeypatch) -> None:
+ _enable(repo)
+ (repo / "b.py").write_text(_NESTED, encoding="utf-8")
+ _git(repo, "add", "b.py")
+ assert gate.gate("git commit -m x", str(repo), budget=0) is None
+
+
+def test_unread_commit_forms_pass_without_a_check(repo, monkeypatch) -> None:
+ _enable(repo)
+ calls = _no_health_check(monkeypatch)
+ for command in (
+ "git commit --amend --no-edit",
+ "git commit -m x a.py",
+ "git rm a.py && git commit -m x",
+ "git commit -m x", # nothing staged
+ "npm run format && git add a.py && git commit -m x",
+ ):
+ assert gate.deny_reason(_payload(command, repo)) is None
+ assert calls == []
+
+
+# -- what is checked ----------------------------------------------------------
+
+
+def test_commit_checks_the_chain_s_adds_and_leaves_the_repo_alone(repo, monkeypatch) -> None:
+ _enable(repo)
+ calls = _no_health_check(monkeypatch)
+ (repo / "b.py").write_text(_NESTED, encoding="utf-8")
+ objects_before = _git(repo, "count-objects", "-v")
+ gate.deny_reason(_payload("git add b.py && git commit -m x", repo))
+ assert len(calls) == 1 and calls[0].startswith(_git(repo, "rev-parse", "HEAD") + "..")
+ # The snapshot lived in a scratch index and object store.
+ assert _git(repo, "diff", "--cached", "--name-only") == ""
+ assert _git(repo, "count-objects", "-v") == objects_before
+
+
+def test_commit_all_picks_up_tracked_edits(repo, monkeypatch) -> None:
+ _enable(repo)
+ calls = _no_health_check(monkeypatch)
+ (repo / "a.py").write_text(_NESTED, encoding="utf-8")
+ gate.deny_reason(_payload("git commit -m x", repo))
+ assert calls == [] # nothing staged
+ gate.deny_reason(_payload("git commit -am x", repo))
+ assert len(calls) == 1
+
+
+def test_push_compares_with_the_upstream(repo, monkeypatch) -> None:
+ _enable(repo)
+ calls = _no_health_check(monkeypatch)
+ base = _git(repo, "rev-parse", "HEAD")
+ _git(repo, "remote", "add", "origin", str(repo))
+ _git(repo, "update-ref", "refs/remotes/origin/main", base)
+ _git(repo, "branch", "-q", "--set-upstream-to=origin/main")
+ gate.deny_reason(_payload("git push", repo))
+ assert calls == [] # nothing to push
+ (repo / "b.py").write_text(_NESTED, encoding="utf-8")
+ _git(repo, "add", "b.py")
+ _git(repo, "commit", "-qm", "b")
+ gate.deny_reason(_payload("git push origin main", repo))
+ assert calls == [f"{base}...{_git(repo, 'rev-parse', 'HEAD')}"]
+ gate.deny_reason(_payload("git push origin other", repo))
+ assert len(calls) == 1
+
+
+def test_a_failing_commit_is_denied_with_its_findings(repo) -> None:
+ """End to end: the real ``repowise health check`` decides."""
+ _enable(repo)
+ (repo / "b.py").write_text(_NESTED, encoding="utf-8")
+ out = io.StringIO()
+ stdin = io.StringIO(json.dumps(_payload("git add b.py && git commit -m wip", repo)))
+ gate.run(stdin, out)
+ response = json.loads(out.getvalue())["hookSpecificOutput"]
+ assert response["hookEventName"] == "PreToolUse"
+ assert response["permissionDecision"] == "deny"
+ assert "b.py:1" in response["permissionDecisionReason"]
+ assert "repowise hook health-gate uninstall" in response["permissionDecisionReason"]
+
+
+def test_the_hook_entry_imports_nothing_heavy_for_other_commands(tmp_path) -> None:
+ probe = (
+ "import io, json, sys; "
+ f"sys.stdin = io.StringIO({json.dumps(json.dumps(_payload('ls -la', tmp_path)))}); "
+ "sys.argv = ['repowise-augment', '--health-gate']; "
+ "from repowise.cli.augment_hook import main\n"
+ "try:\n main()\nexcept SystemExit:\n pass\n"
+ "print(sorted(m for m in sys.modules if m.startswith("
+ "('repowise.cli.commands', 'repowise.core.analysis', 'sqlalchemy', 'structlog'))))"
+ )
+ out = subprocess.run(
+ [sys.executable, "-c", probe], capture_output=True, text=True, check=True
+ ).stdout
+ assert out.strip().splitlines()[-1] == "[]"
+
+
+# -- install / uninstall ------------------------------------------------------
+
+
+def _local(repo: Path) -> dict:
+ path = repo / ".claude" / "settings.local.json"
+ return json.loads(path.read_text(encoding="utf-8")) if path.exists() else {}
+
+
+def test_install_and_uninstall_write_and_remove_both_halves(repo) -> None:
+ from repowise.cli.commands.augment_cmd._shared import hook_flag_enabled
+
+ foreign = {"matcher": "Bash", "hooks": [{"type": "command", "command": "make lint"}]}
+ (repo / ".claude").mkdir()
+ (repo / ".claude" / "settings.local.json").write_text(
+ json.dumps({"hooks": {"PreToolUse": [foreign]}}), encoding="utf-8"
+ )
+ result = CliRunner().invoke(hook_group, ["health-gate", "install", str(repo)])
+ assert result.exit_code == 0, result.output
+ assert hook_flag_enabled(repo, "health_gate")
+ entries = _local(repo)["hooks"]["PreToolUse"]
+ assert entries[0] == foreign and "--health-gate" in entries[1]["hooks"][0]["command"]
+
+ status = CliRunner().invoke(hook_group, ["health-gate", "status", str(repo)])
+ assert "health gate: on" in status.output
+
+ CliRunner().invoke(hook_group, ["health-gate", "install", str(repo)])
+ assert len(_local(repo)["hooks"]["PreToolUse"]) == 2 # idempotent
+
+ result = CliRunner().invoke(hook_group, ["health-gate", "uninstall", str(repo)])
+ assert result.exit_code == 0, result.output
+ assert not hook_flag_enabled(repo, "health_gate")
+ assert _local(repo) == {"hooks": {"PreToolUse": [foreign]}}
+
+
+def test_hook_uninstall_removes_the_gate_too(repo) -> None:
+ CliRunner().invoke(hook_group, ["health-gate", "install", str(repo)])
+ result = CliRunner().invoke(hook_group, ["uninstall", str(repo)])
+ assert "Health gate on agent commits and pushes" in result.output
+ assert not (repo / ".claude" / "settings.local.json").exists()
+
+
+def test_project_uninstall_removes_the_entry(repo) -> None:
+ from repowise.cli.agent_targets.targets.claude_code import ClaudeCodeTarget
+ from repowise.cli.agent_targets.types import Scope
+
+ CliRunner().invoke(hook_group, ["health-gate", "install", str(repo)])
+ ClaudeCodeTarget().uninstall(Scope.PROJECT, repo_path=repo)
+ assert not (repo / ".claude" / "settings.local.json").exists()
+
+
+def test_the_entry_counts_as_repowise_s_own_edit() -> None:
+ from repowise.cli.editor_integrations.claude_config import _health_gate_entry
+ from repowise.core.owned_paths import only_repowise_differs
+
+ created = json.dumps({"hooks": {"PreToolUse": [_health_gate_entry()]}})
+ assert only_repowise_differs(".claude/settings.local.json", "", created)
+
+
+def test_a_merge_in_progress_passes_without_a_check(repo, monkeypatch) -> None:
+ _enable(repo)
+ calls = _no_health_check(monkeypatch)
+ (repo / "b.py").write_text(_NESTED, encoding="utf-8")
+ _git(repo, "add", "b.py")
+ (repo / ".git" / "MERGE_HEAD").write_text(_git(repo, "rev-parse", "HEAD") + "\n")
+ assert gate.deny_reason(_payload("git commit -m x", repo)) is None
+ assert calls == []
+
+
+def test_a_push_after_a_commit_in_the_chain_checks_only_the_commit(repo, monkeypatch) -> None:
+ _enable(repo)
+ calls = _no_health_check(monkeypatch)
+ (repo / "b.py").write_text(_NESTED, encoding="utf-8")
+ gate.deny_reason(_payload("git add b.py && git commit -m x && git push", repo))
+ assert len(calls) == 1 and ".." in calls[0] and "..." not in calls[0]