Skip to main content Switch to mobile version hookbrake 0.3.0 Runtime circuit-breaker, PostToolUse secret vault, output compactor, and session waste auditor for AI coding agents.
pip install hookbrake Copy PIP instructions
Guardrails for AI coding agents: stops runaway retry loops, redacts secrets in tool output, blocks a short list of destructive commands, and trims noisy test and diff output.
Why HookBrake exists
Autonomous coding agents (Claude Code, OpenAI Codex CLI, Gemini CLI, Cursor) regularly hit four failure modes at the tool-execution boundary:
Zero-progress retry loops: An agent runs the same failing pytest command or re-reads the exact same unchanged file 5 times in a row, burning quota without changing a single byte on disk.
Test/lockfile context flooding: A single pytest traceback dump, cargo test run, or git diff package-lock.json injects 30,000+ chars into context, forcing premature compaction loops.
Secrets leaking via tool stdout: PreToolUse command checks miss secrets printed at runtime (cat output, verbose env traces, debug HTTP responses), writing raw tokens straight into cloud LLM context and .jsonl transcripts.
Silent cache invalidations: One volatile prefix change breaks prompt caching across turns, multiplying input costs invisibly.
HookBrake offers a retroactive audit of past sessions (hookbrake audit) and real-time hook interception (hookbrake hook) in one pure-stdlib Python CLI with no external dependencies. Speed is measured by the benchmark script below and varies by machine.
Gemini CLI compatibility. Google states that since June 18, 2026 "Login with Google" no longer works for Gemini CLI on consumer accounts (Gemini Code Assist for individuals, Google AI Pro, Google AI Ultra), which are directed to Antigravity CLI. Standard and Enterprise subscriptions follow a separate schedule (Google notice, announcement of 2026-05-19). HookBrake's Gemini adapter targets Gemini CLI hooks only. It has not been run against a live Gemini CLI, and there is no Antigravity CLI adapter.
1. Audit your existing local sessions first (read-only)
Before enabling any hook, measure how much waste happened in your past Claude Code, Codex CLI, or Gemini CLI transcripts:
pip install hookbrake hookbrake audit Illustrative output (numbers are an example, not a measurement):
=== HookBrake Session Waste Audit === Sessions scanned: 14 Tool calls scanned: 612 Oversized outputs: 19 Compaction savings: 184,320 chars (~46,080 tokens) Secrets exposed: 2 Breakdown: {'GITHUB_PAT': 1, 'OPENAI_KEY': 1} Stalled loops detected: 5 - Bash repeated 4x in session-a18f.jsonl Cache-break events: 3 - Turn 19 (session-a18f.jsonl): cache_read dropped 42,100 -> 1,800 while cache_creation spiked to 41,200 2. Install hooks for your coding agent
# Claude Code (~/.claude/settings.json) hookbrake install --claude # Gemini CLI (~/.gemini/settings.json) and Cursor (~/.cursor/hooks.json) hookbrake install --claude --gemini --cursor (Backups are automatically saved to *.hookbrake.bak. Remove cleanly anytime with hookbrake install --claude --uninstall.)
What Happens at Runtime
PreToolUse — Git-Aware Loop Breaker & Firewall
Real TDD vs. Thrashing: HookBrake hashes (tool_name, args, git_state_hash) in SQLite (~/.hookbrake/state.db), including mtime/size of dirty files. Editing code and re-running pytest is allowed; re-running the identical failing command 3 times with zero file edits trips the breaker (exit code 2) and prompts the agent to change strategy.
Read-thrash & Ping-Pong detection: Catches repeated reads of unchanged files and alternating A -> B -> A -> B non-edit cycles.
Blast-radius & exfiltration rules: Pattern rules that deny common forms of rm -rf on /, ~, $HOME and wildcards, curl | bash, git push --force main|master, .env/SSH key reads, and edits to hook config files. They are regex rules, not a shell parser or a sandbox; see Limits below. Commands longer than 5000 characters are denied with an explicit reason rather than checked.
Test-integrity check: Warns (or hard-blocks with --strict-tests) if an agent writes @pytest.mark.skip, it.skip, assert True, or except Exception: pass into test files.
PostToolUse — Secret Vault & Lossless-Pointer Diet
Secret Redactor: Scrubs OpenAI, Anthropic, AWS, GitHub PAT, PyPI, Stripe, Slack, Google API keys, Bearer tokens, and PEM private keys into deterministic
Structured Output Compactor: Collapses lockfile hunks (package-lock.json, poetry.lock, uv.lock, Cargo.lock) inside git diff while leaving source code diffs untouched.
Strips verbose passing test dots/lines from pytest, unittest, jest, cargo test, and go test while preserving failing assertions and tracebacks.
Saves the complete untouched log to ~/.hookbrake/artifacts/
hookbrake audit [path] [--agent all|claude|codex|gemini] [--json] hookbrake wrap --
For agents or scripts without native PreToolUse / PostToolUse hooks (such as Codex pipelines or CI test runners), wrap any command directly:
hookbrake wrap -- pytest -q HookBrake applies the firewall and git-aware loop breaker to the command line it is given before running it (not to what the wrapped program does internally), scrubs leaked secrets from stdout/stderr, and compacts passing noise while preserving failure tracebacks and saving the raw log to ~/.hookbrake/artifacts/.
Configuration (hookbrake.toml)
Optional overrides in project root (hookbrake.toml) or ~/.hookbrake/config.toml:
max_identical_retries = 3 max_unchanged_rereads = 3 max_ping_pong_cycles = 4 compact_threshold_chars = 4000 redact_secrets = true block_destructive_commands = true block_exfiltration = true check_test_tampering = true strict_tests = false strict_policy = false # opt-in, see Modes below Modes
Redaction patterns cover the listed command forms only; unquoted passwords with spaces, PASSWORD: some words lines and other tools are not covered. Strict mode is pattern-based and can still be wrong: git clean -n, git restore --staged and env | grep NAME are allowed, but a SQL DROP mentioned inside echo is denied and environment dumps built through shell loops or other languages are not caught. A repository config can turn strict mode on but never off.
Reproducible Benchmarks
These numbers are character reductions on synthetic logs. They do not measure agent accuracy or total token savings, and they have not been measured on real agent sessions. Compaction is lossy and bounded: output over the threshold is cut to about 4,000 characters, so it cannot keep unlimited detail. It keeps the first 3 and last 8 lines and lines that look like failures or warnings (a fixed list of markers such as error, FAILED, panic, Exception, npm ERR!). When many tests fail it lists every failing test id in log order (shortened to the bare id if needed), and when even that does not fit it lists as many as fit from both ends and prints "N lines that look like failures; listing X, the rest are only in the raw log". Measured at the default 4,000-character threshold: with short pytest ids every failing test id and the "N failed" line are kept up to about 90 failures; with long ids (about 110 characters, with the assertion message) about 30; Go, unittest and jest ids were all kept up to 100 in the reviewer's sweep. Above that, ids are shortened to the bare test id and then listed as many as fit, with a count of how many are only in the raw log. A single very long line keeps its start plus windows around its first, middle and last marker (or start, middle and end if it has no marker), so a cause that sits between those windows can still be lost. Lockfile diffs are collapsed by exact file name (package-lock.json, yarn.lock, ...). Anything else that matches no marker is dropped from the middle. When run by the hooks, hookbrake wrap or compact --save-artifacts, HookBrake saves the full raw log to ~/.hookbrake/artifacts/.
Run python benchmarks/run_benchmarks.py from the repository root to reproduce these measurements on synthetic logs (first recorded by the author on Python 3.14.7, Windows; re-run on Linux with Python 3.10.12 with the same compaction ratios, 19/19, 0/5, 8/8, 4/4 and 500/500 results, but different latencies):
Secret Redactor: In the project's own test cases it caught 19/19 listed secret formats (AWS AKIA/ASIA/Secret, OpenAI, Anthropic, GitHub PAT, Slack webhook, SendGrid, npm, Docker PAT, Vercel, Supabase, Google OAuth, Stripe webhook, HuggingFace, JWT, DB URL passwords with @, Basic/Bearer auth) with 0/5 false positives on the sample prose and identifiers. Unlisted or unprefixed secret formats are not detected.
Firewall: In the project's own test cases it blocked 8/8 bypass attempts (bash -c "rm -rf /", PowerShell Remove-Item, flag-after-branch force-push, +main, python -c open('.env'), <.env, Windows backslash exfil) while allowing 4/4 safe commands (e.g. --force-with-lease, feature/main-fix, .env.example). These are example cases, not a guarantee against all bypasses.
SQLite Concurrency: 500/500 barrier-synchronized calls across 10 parallel threads recorded with 0 lock errors.
HookBrake is a guardrail, not a sandbox. A hook only sees tool calls the agent routes through it. Real containment needs the tool's own sandbox, a container or a restricted account.
The firewall and redactor are pattern rules. Commands built through command substitution, eval, encoding or other tools (for example find -delete) can get past them.
Some routine but risky commands are allowed by default, for example git reset --hard, git clean -fd, terraform destroy and printenv; the opt-in strict_policy setting denies them (see Modes). rm -rf on top-level system directories such as /usr or /etc is denied by default.
Commands over 5000 characters are denied, including large heredocs, while command blocking is on. The limit is not configurable.
Identical read-only git inspection commands are blocked on the 20th identical call in a row; any other command repeated 3 times in an unchanged working tree is counted as a retry loop.
The advisory MCP server (hookbrake mcp) only answers check and redact requests; it does not enforce anything.
The retry-loop, compaction and redaction behaviour described above is design intent covered by the unit tests and a synthetic behaviour matrix in tests/, not a measured result on real sessions.
The hook adapters follow each tool's documented hook format but have not been run in live Claude Code, Gemini CLI, Cursor or Codex CLI sessions by the maintainers, and hook behaviour can differ between tool versions (for example, hooks may not fire for subagent tool calls in some Claude Code versions).
Secrets already in logs, prompts or git history are not removed.
Released: Nov 28, 2026
Author: Aprameya Acharya
Both files in this release have provenance metadata.
View provenance details
MIT View SPDX License List
claude-code codex gemini-cli cursor ai-agents circuit-breaker hooks secret-redaction prompt-caching context-optimization
Development Status 4 - Beta
Intended Audience Developers
Programming Language Python :: 3
Software Development :: Quality Assurance
Software Development :: Testing
Release files for hookbrake 0.3.0
For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.
Source distribution (sdist)
Built distribution (wheel)
Total release size: 140.1 kB
Release files / hookbrake-0.3.0.tar.gz
Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.
PyPI Publish Attestation
PyPI verified that this artifact, at this checksum, originated from the publisher listed below.
Signed by GitHub Actions, verified by PyPI on Nov 28, 2026.
Release files / hookbrake-0.3.0-py3-none-any.whl
Security for hookbrake 0.3.0
Both files in this release have been uploaded with provenance metadata.
With provenance hookbrake-0.3.0.tar.gz Nov 28, 2026
With provenance hookbrake-0.3.0-py3-none-any.whl Nov 28, 2026
Attestation for hookbrake-0.3.0.tar.gz
Attestation for hookbrake-0.3.0-py3-none-any.whl
A note on package security
PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.
To learn more about protecting yourself from malicious actors, visit our package security documentation.
Release history Release notifications | RSS feed
Nov 28, 2026 2 release files Full provenance
Nov 28, 2026 2 release files No provenance
"PyPI", "Python Package Index", and the blocks logos are registered trademarks of the Python Software Foundation.
© 2026 Python Software Foundation
Deployed from fc0d8e6











