Metadata-Version: 2.4
Name: hookbrake
Version: 0.1.0
Summary: Runtime circuit-breaker, PostToolUse secret vault, output compactor, and session waste auditor for AI coding agents.
Author: Aprameya Acharya
License-Expression: MIT
Project-URL: Homepage, https://github.com/appu2712/hookbrake
Project-URL: Repository, https://github.com/appu2712/hookbrake
Project-URL: Issues, https://github.com/appu2712/hookbrake/issues
Keywords: claude-code,codex,gemini-cli,cursor,ai-agents,circuit-breaker,hooks,secret-redaction,prompt-caching,context-optimization
Classifier: Development Status :: 4 - Beta
Classifier: Intended Audience :: Developers
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.10
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3.13
Classifier: Programming Language :: Python :: 3.14
Classifier: Topic :: Software Development :: Quality Assurance
Classifier: Topic :: Software Development :: Testing
Classifier: Topic :: Security
Requires-Python: >=3.10
Description-Content-Type: text/markdown
License-File: LICENSE
Dynamic: license-file

# HookBrake

**Git-aware loop circuit-breaker, `PostToolUse` secret vault, lossless-pointer test/diff compactor, and local session waste auditor for AI coding agents.**

[![CI](https://github.com/appu2712/hookbrake/actions/workflows/ci.yml/badge.svg)](https://github.com/appu2712/hookbrake/actions/workflows/ci.yml)
[![License: MIT](https://img.shields.io/badge/License-MIT-green.svg)](https://opensource.org/licenses/MIT)
[![Python 3.10+](https://img.shields.io/badge/python-3.10%2B-blue.svg)](https://www.python.org/downloads/)

---

## Why HookBrake exists

Autonomous coding agents (**Claude Code**, **OpenAI Codex CLI**, **Gemini CLI**, **Cursor**) regularly hit four failure modes at the tool-execution boundary:

1. **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.
2. **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.
3. **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.
4. **Silent cache invalidations**: One volatile prefix change breaks prompt caching across turns, multiplying input costs invisibly.

Instead of shipping another static token counter or regex one-liner, **HookBrake** handles both **retroactive proof** (`hookbrake audit`) and **real-time runtime interception** (`hookbrake hook`) in one pure-stdlib Python CLI (`<30ms` per hook call, zero external dependencies).

---

## Quickstart

### 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:

```bash
pip install -e .
hookbrake audit
```

```text
=== 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

```bash
# 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**: Blocks `rm -rf /|~`, `curl | bash`, `git push --force main|master`, `.env`/SSH key exfiltration, and tampering with hook config files.
* **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 `<REDACTED:TYPE:sha6>` markers *before* tool output enters LLM context.
* **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/<sha>.log` and appends the exact path so nothing is lost.

---

## CLI Commands

```bash
hookbrake audit [path] [--agent all|claude|codex|gemini] [--json]
hookbrake compact <file|-> [--threshold 4000] [--save-artifacts] [--json]
hookbrake redact <file|-> [--json]
hookbrake install [--claude] [--gemini] [--cursor] [--uninstall]
hookbrake stats [--json]
```

## Configuration (`hookbrake.toml`)

Optional overrides in project root (`hookbrake.toml`) or `~/.hookbrake/config.toml`:

```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
```

## How HookBrake Compares

| Focus | Existing Single-Purpose Scripts | HookBrake |
| :--- | :--- | :--- |
| **Loop Detection** | Naive consecutive command counting | SQLite + `git status`/mtime state fingerprint (allows real TDD edits) |
| **PostToolUse Diet** | Truncation cuts off bottom tracebacks | Lockfile-aware + test-failure-preserving + raw log artifact pointer |
| **Secret Safety** | Blocks `cat .env` in `PreToolUse` only | Scrubs leaked tokens inside runtime tool stdout in `PostToolUse` |
| **Harness Scope** | Single agent (usually Claude-only) | Normalized adapters for Claude Code, Gemini CLI, Cursor, generic JSON |
| **Audit Before Install** | Separate log viewer script | Built-in `hookbrake audit` across Claude, Codex, and Gemini logs |

---

## License

[MIT](LICENSE)
