hookbrake 0.1.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Aprameya Acharya
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,146 @@
1
+ Metadata-Version: 2.4
2
+ Name: hookbrake
3
+ Version: 0.1.0
4
+ Summary: Runtime circuit-breaker, PostToolUse secret vault, output compactor, and session waste auditor for AI coding agents.
5
+ Author: Aprameya Acharya
6
+ License-Expression: MIT
7
+ Project-URL: Homepage, https://github.com/appu2712/hookbrake
8
+ Project-URL: Repository, https://github.com/appu2712/hookbrake
9
+ Project-URL: Issues, https://github.com/appu2712/hookbrake/issues
10
+ Keywords: claude-code,codex,gemini-cli,cursor,ai-agents,circuit-breaker,hooks,secret-redaction,prompt-caching,context-optimization
11
+ Classifier: Development Status :: 4 - Beta
12
+ Classifier: Intended Audience :: Developers
13
+ Classifier: Programming Language :: Python :: 3
14
+ Classifier: Programming Language :: Python :: 3.10
15
+ Classifier: Programming Language :: Python :: 3.11
16
+ Classifier: Programming Language :: Python :: 3.12
17
+ Classifier: Programming Language :: Python :: 3.13
18
+ Classifier: Programming Language :: Python :: 3.14
19
+ Classifier: Topic :: Software Development :: Quality Assurance
20
+ Classifier: Topic :: Software Development :: Testing
21
+ Classifier: Topic :: Security
22
+ Requires-Python: >=3.10
23
+ Description-Content-Type: text/markdown
24
+ License-File: LICENSE
25
+ Dynamic: license-file
26
+
27
+ # HookBrake
28
+
29
+ **Git-aware loop circuit-breaker, `PostToolUse` secret vault, lossless-pointer test/diff compactor, and local session waste auditor for AI coding agents.**
30
+
31
+ [![CI](https://github.com/appu2712/hookbrake/actions/workflows/ci.yml/badge.svg)](https://github.com/appu2712/hookbrake/actions/workflows/ci.yml)
32
+ [![License: MIT](https://img.shields.io/badge/License-MIT-green.svg)](https://opensource.org/licenses/MIT)
33
+ [![Python 3.10+](https://img.shields.io/badge/python-3.10%2B-blue.svg)](https://www.python.org/downloads/)
34
+
35
+ ---
36
+
37
+ ## Why HookBrake exists
38
+
39
+ Autonomous coding agents (**Claude Code**, **OpenAI Codex CLI**, **Gemini CLI**, **Cursor**) regularly hit four failure modes at the tool-execution boundary:
40
+
41
+ 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.
42
+ 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.
43
+ 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.
44
+ 4. **Silent cache invalidations**: One volatile prefix change breaks prompt caching across turns, multiplying input costs invisibly.
45
+
46
+ 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).
47
+
48
+ ---
49
+
50
+ ## Quickstart
51
+
52
+ ### 1. Audit your existing local sessions first (read-only)
53
+
54
+ Before enabling any hook, measure how much waste happened in your past Claude Code, Codex CLI, or Gemini CLI transcripts:
55
+
56
+ ```bash
57
+ pip install -e .
58
+ hookbrake audit
59
+ ```
60
+
61
+ ```text
62
+ === HookBrake Session Waste Audit ===
63
+ Sessions scanned: 14
64
+ Tool calls scanned: 612
65
+ Oversized outputs: 19
66
+ Compaction savings: 184,320 chars (~46,080 tokens)
67
+ Secrets exposed: 2
68
+ Breakdown: {'GITHUB_PAT': 1, 'OPENAI_KEY': 1}
69
+ Stalled loops detected: 5
70
+ - Bash repeated 4x in session-a18f.jsonl
71
+ Cache-break events: 3
72
+ - Turn 19 (session-a18f.jsonl): cache_read dropped 42,100 -> 1,800 while cache_creation spiked to 41,200
73
+ ```
74
+
75
+ ### 2. Install hooks for your coding agent
76
+
77
+ ```bash
78
+ # Claude Code (~/.claude/settings.json)
79
+ hookbrake install --claude
80
+
81
+ # Gemini CLI (~/.gemini/settings.json) and Cursor (~/.cursor/hooks.json)
82
+ hookbrake install --claude --gemini --cursor
83
+ ```
84
+
85
+ *(Backups are automatically saved to `*.hookbrake.bak`. Remove cleanly anytime with `hookbrake install --claude --uninstall`.)*
86
+
87
+ ---
88
+
89
+ ## What Happens at Runtime
90
+
91
+ ### `PreToolUse` — Git-Aware Loop Breaker & Firewall
92
+ * **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.
93
+ * **Read-thrash & Ping-Pong detection**: Catches repeated reads of unchanged files and alternating `A -> B -> A -> B` non-edit cycles.
94
+ * **Blast-radius & exfiltration rules**: Blocks `rm -rf /|~`, `curl | bash`, `git push --force main|master`, `.env`/SSH key exfiltration, and tampering with hook config files.
95
+ * **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.
96
+
97
+ ### `PostToolUse` — Secret Vault & Lossless-Pointer Diet
98
+ * **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.
99
+ * **Structured Output Compactor**:
100
+ * Collapses lockfile hunks (`package-lock.json`, `poetry.lock`, `uv.lock`, `Cargo.lock`) inside `git diff` while leaving source code diffs untouched.
101
+ * Strips verbose passing test dots/lines from `pytest`, `unittest`, `jest`, `cargo test`, and `go test` while preserving failing assertions and tracebacks.
102
+ * Saves the complete untouched log to `~/.hookbrake/artifacts/<sha>.log` and appends the exact path so nothing is lost.
103
+
104
+ ---
105
+
106
+ ## CLI Commands
107
+
108
+ ```bash
109
+ hookbrake audit [path] [--agent all|claude|codex|gemini] [--json]
110
+ hookbrake compact <file|-> [--threshold 4000] [--save-artifacts] [--json]
111
+ hookbrake redact <file|-> [--json]
112
+ hookbrake install [--claude] [--gemini] [--cursor] [--uninstall]
113
+ hookbrake stats [--json]
114
+ ```
115
+
116
+ ## Configuration (`hookbrake.toml`)
117
+
118
+ Optional overrides in project root (`hookbrake.toml`) or `~/.hookbrake/config.toml`:
119
+
120
+ ```toml
121
+ max_identical_retries = 3
122
+ max_unchanged_rereads = 3
123
+ max_ping_pong_cycles = 4
124
+ compact_threshold_chars = 4000
125
+ redact_secrets = true
126
+ block_destructive_commands = true
127
+ block_exfiltration = true
128
+ check_test_tampering = true
129
+ strict_tests = false
130
+ ```
131
+
132
+ ## How HookBrake Compares
133
+
134
+ | Focus | Existing Single-Purpose Scripts | HookBrake |
135
+ | :--- | :--- | :--- |
136
+ | **Loop Detection** | Naive consecutive command counting | SQLite + `git status`/mtime state fingerprint (allows real TDD edits) |
137
+ | **PostToolUse Diet** | Truncation cuts off bottom tracebacks | Lockfile-aware + test-failure-preserving + raw log artifact pointer |
138
+ | **Secret Safety** | Blocks `cat .env` in `PreToolUse` only | Scrubs leaked tokens inside runtime tool stdout in `PostToolUse` |
139
+ | **Harness Scope** | Single agent (usually Claude-only) | Normalized adapters for Claude Code, Gemini CLI, Cursor, generic JSON |
140
+ | **Audit Before Install** | Separate log viewer script | Built-in `hookbrake audit` across Claude, Codex, and Gemini logs |
141
+
142
+ ---
143
+
144
+ ## License
145
+
146
+ [MIT](LICENSE)
@@ -0,0 +1,120 @@
1
+ # HookBrake
2
+
3
+ **Git-aware loop circuit-breaker, `PostToolUse` secret vault, lossless-pointer test/diff compactor, and local session waste auditor for AI coding agents.**
4
+
5
+ [![CI](https://github.com/appu2712/hookbrake/actions/workflows/ci.yml/badge.svg)](https://github.com/appu2712/hookbrake/actions/workflows/ci.yml)
6
+ [![License: MIT](https://img.shields.io/badge/License-MIT-green.svg)](https://opensource.org/licenses/MIT)
7
+ [![Python 3.10+](https://img.shields.io/badge/python-3.10%2B-blue.svg)](https://www.python.org/downloads/)
8
+
9
+ ---
10
+
11
+ ## Why HookBrake exists
12
+
13
+ Autonomous coding agents (**Claude Code**, **OpenAI Codex CLI**, **Gemini CLI**, **Cursor**) regularly hit four failure modes at the tool-execution boundary:
14
+
15
+ 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.
16
+ 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.
17
+ 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.
18
+ 4. **Silent cache invalidations**: One volatile prefix change breaks prompt caching across turns, multiplying input costs invisibly.
19
+
20
+ 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).
21
+
22
+ ---
23
+
24
+ ## Quickstart
25
+
26
+ ### 1. Audit your existing local sessions first (read-only)
27
+
28
+ Before enabling any hook, measure how much waste happened in your past Claude Code, Codex CLI, or Gemini CLI transcripts:
29
+
30
+ ```bash
31
+ pip install -e .
32
+ hookbrake audit
33
+ ```
34
+
35
+ ```text
36
+ === HookBrake Session Waste Audit ===
37
+ Sessions scanned: 14
38
+ Tool calls scanned: 612
39
+ Oversized outputs: 19
40
+ Compaction savings: 184,320 chars (~46,080 tokens)
41
+ Secrets exposed: 2
42
+ Breakdown: {'GITHUB_PAT': 1, 'OPENAI_KEY': 1}
43
+ Stalled loops detected: 5
44
+ - Bash repeated 4x in session-a18f.jsonl
45
+ Cache-break events: 3
46
+ - Turn 19 (session-a18f.jsonl): cache_read dropped 42,100 -> 1,800 while cache_creation spiked to 41,200
47
+ ```
48
+
49
+ ### 2. Install hooks for your coding agent
50
+
51
+ ```bash
52
+ # Claude Code (~/.claude/settings.json)
53
+ hookbrake install --claude
54
+
55
+ # Gemini CLI (~/.gemini/settings.json) and Cursor (~/.cursor/hooks.json)
56
+ hookbrake install --claude --gemini --cursor
57
+ ```
58
+
59
+ *(Backups are automatically saved to `*.hookbrake.bak`. Remove cleanly anytime with `hookbrake install --claude --uninstall`.)*
60
+
61
+ ---
62
+
63
+ ## What Happens at Runtime
64
+
65
+ ### `PreToolUse` — Git-Aware Loop Breaker & Firewall
66
+ * **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.
67
+ * **Read-thrash & Ping-Pong detection**: Catches repeated reads of unchanged files and alternating `A -> B -> A -> B` non-edit cycles.
68
+ * **Blast-radius & exfiltration rules**: Blocks `rm -rf /|~`, `curl | bash`, `git push --force main|master`, `.env`/SSH key exfiltration, and tampering with hook config files.
69
+ * **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.
70
+
71
+ ### `PostToolUse` — Secret Vault & Lossless-Pointer Diet
72
+ * **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.
73
+ * **Structured Output Compactor**:
74
+ * Collapses lockfile hunks (`package-lock.json`, `poetry.lock`, `uv.lock`, `Cargo.lock`) inside `git diff` while leaving source code diffs untouched.
75
+ * Strips verbose passing test dots/lines from `pytest`, `unittest`, `jest`, `cargo test`, and `go test` while preserving failing assertions and tracebacks.
76
+ * Saves the complete untouched log to `~/.hookbrake/artifacts/<sha>.log` and appends the exact path so nothing is lost.
77
+
78
+ ---
79
+
80
+ ## CLI Commands
81
+
82
+ ```bash
83
+ hookbrake audit [path] [--agent all|claude|codex|gemini] [--json]
84
+ hookbrake compact <file|-> [--threshold 4000] [--save-artifacts] [--json]
85
+ hookbrake redact <file|-> [--json]
86
+ hookbrake install [--claude] [--gemini] [--cursor] [--uninstall]
87
+ hookbrake stats [--json]
88
+ ```
89
+
90
+ ## Configuration (`hookbrake.toml`)
91
+
92
+ Optional overrides in project root (`hookbrake.toml`) or `~/.hookbrake/config.toml`:
93
+
94
+ ```toml
95
+ max_identical_retries = 3
96
+ max_unchanged_rereads = 3
97
+ max_ping_pong_cycles = 4
98
+ compact_threshold_chars = 4000
99
+ redact_secrets = true
100
+ block_destructive_commands = true
101
+ block_exfiltration = true
102
+ check_test_tampering = true
103
+ strict_tests = false
104
+ ```
105
+
106
+ ## How HookBrake Compares
107
+
108
+ | Focus | Existing Single-Purpose Scripts | HookBrake |
109
+ | :--- | :--- | :--- |
110
+ | **Loop Detection** | Naive consecutive command counting | SQLite + `git status`/mtime state fingerprint (allows real TDD edits) |
111
+ | **PostToolUse Diet** | Truncation cuts off bottom tracebacks | Lockfile-aware + test-failure-preserving + raw log artifact pointer |
112
+ | **Secret Safety** | Blocks `cat .env` in `PreToolUse` only | Scrubs leaked tokens inside runtime tool stdout in `PostToolUse` |
113
+ | **Harness Scope** | Single agent (usually Claude-only) | Normalized adapters for Claude Code, Gemini CLI, Cursor, generic JSON |
114
+ | **Audit Before Install** | Separate log viewer script | Built-in `hookbrake audit` across Claude, Codex, and Gemini logs |
115
+
116
+ ---
117
+
118
+ ## License
119
+
120
+ [MIT](LICENSE)
@@ -0,0 +1,51 @@
1
+ [build-system]
2
+ requires = ["setuptools>=77.0"]
3
+ build-backend = "setuptools.build_meta"
4
+
5
+ [project]
6
+ name = "hookbrake"
7
+ version = "0.1.0"
8
+ authors = [
9
+ { name = "Aprameya Acharya" }
10
+ ]
11
+ description = "Runtime circuit-breaker, PostToolUse secret vault, output compactor, and session waste auditor for AI coding agents."
12
+ readme = "README.md"
13
+ requires-python = ">=3.10"
14
+ license = "MIT"
15
+ keywords = [
16
+ "claude-code",
17
+ "codex",
18
+ "gemini-cli",
19
+ "cursor",
20
+ "ai-agents",
21
+ "circuit-breaker",
22
+ "hooks",
23
+ "secret-redaction",
24
+ "prompt-caching",
25
+ "context-optimization"
26
+ ]
27
+ classifiers = [
28
+ "Development Status :: 4 - Beta",
29
+ "Intended Audience :: Developers",
30
+ "Programming Language :: Python :: 3",
31
+ "Programming Language :: Python :: 3.10",
32
+ "Programming Language :: Python :: 3.11",
33
+ "Programming Language :: Python :: 3.12",
34
+ "Programming Language :: Python :: 3.13",
35
+ "Programming Language :: Python :: 3.14",
36
+ "Topic :: Software Development :: Quality Assurance",
37
+ "Topic :: Software Development :: Testing",
38
+ "Topic :: Security"
39
+ ]
40
+ dependencies = []
41
+
42
+ [project.urls]
43
+ Homepage = "https://github.com/appu2712/hookbrake"
44
+ Repository = "https://github.com/appu2712/hookbrake"
45
+ Issues = "https://github.com/appu2712/hookbrake/issues"
46
+
47
+ [project.scripts]
48
+ hookbrake = "hookbrake.cli:main"
49
+
50
+ [tool.setuptools.packages.find]
51
+ where = ["src"]
@@ -0,0 +1,4 @@
1
+ [egg_info]
2
+ tag_build =
3
+ tag_date = 0
4
+
@@ -0,0 +1,34 @@
1
+ """
2
+ HookBrake: Runtime circuit-breaker, secret redactor, output compactor,
3
+ and session waste auditor for AI coding agents.
4
+ """
5
+
6
+ __version__ = "0.1.0"
7
+
8
+ from .config import HookBrakeConfig, load_config
9
+ from .adapters import HookEvent, HarnessType, parse_hook_event, format_hook_decision
10
+ from .firewall import FirewallResult, check_pre_tool_firewall
11
+ from .circuit_breaker import LoopDecision, check_loop_breaker
12
+ from .redactor import RedactionResult, redact_secrets
13
+ from .compactor import CompactionResult, compact_output
14
+ from .audit import AuditReport, audit_sessions
15
+
16
+ __all__ = [
17
+ "__version__",
18
+ "HookBrakeConfig",
19
+ "load_config",
20
+ "HookEvent",
21
+ "HarnessType",
22
+ "parse_hook_event",
23
+ "format_hook_decision",
24
+ "FirewallResult",
25
+ "check_pre_tool_firewall",
26
+ "LoopDecision",
27
+ "check_loop_breaker",
28
+ "RedactionResult",
29
+ "redact_secrets",
30
+ "CompactionResult",
31
+ "compact_output",
32
+ "AuditReport",
33
+ "audit_sessions",
34
+ ]
@@ -0,0 +1,206 @@
1
+ """Cross-harness stdin/stdout JSON hook protocol normalization."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import json
6
+ import os
7
+ from dataclasses import dataclass, field
8
+ from enum import Enum
9
+ from typing import Any, Dict, Optional, Tuple
10
+
11
+
12
+ class HarnessType(str, Enum):
13
+ CLAUDE = "claude"
14
+ GEMINI = "gemini"
15
+ CURSOR = "cursor"
16
+ GENERIC = "generic"
17
+
18
+
19
+ @dataclass
20
+ class HookEvent:
21
+ """Normalized representation of a coding-agent PreToolUse / PostToolUse hook event."""
22
+
23
+ harness: HarnessType
24
+ phase: str # "pre_tool" or "post_tool"
25
+ session_id: str
26
+ tool_name: str
27
+ tool_input: Dict[str, Any] = field(default_factory=dict)
28
+ tool_output: str = ""
29
+ is_error: bool = False
30
+ cwd: str = ""
31
+ raw: Dict[str, Any] = field(default_factory=dict)
32
+
33
+
34
+ def _extract_output_text(response: Any) -> Tuple[str, bool]:
35
+ """Extract normalized stdout/text output and error flag from heterogeneous tool responses."""
36
+ if response is None:
37
+ return "", False
38
+ if isinstance(response, str):
39
+ return response, False
40
+ if isinstance(response, dict):
41
+ is_err = bool(response.get("isError") or response.get("is_error"))
42
+ exit_code = response.get("exitCode", response.get("exit_code"))
43
+ if isinstance(exit_code, int) and exit_code != 0:
44
+ is_err = True
45
+ parts = []
46
+ for key in ("stdout", "output", "text", "result"):
47
+ val = response.get(key)
48
+ if isinstance(val, str) and val:
49
+ parts.append(val)
50
+ stderr_val = response.get("stderr")
51
+ if isinstance(stderr_val, str) and stderr_val:
52
+ parts.append(stderr_val)
53
+ is_err = is_err or ("error" in stderr_val.lower() or "traceback" in stderr_val.lower())
54
+ if not parts and isinstance(response.get("content"), list):
55
+ for block in response["content"]:
56
+ if isinstance(block, dict) and isinstance(block.get("text"), str):
57
+ parts.append(block["text"])
58
+ if parts:
59
+ return "\n".join(parts), is_err
60
+ return json.dumps(response), is_err
61
+ return str(response), False
62
+
63
+
64
+ def _detect_harness(data: Dict[str, Any], hint: str = "auto") -> HarnessType:
65
+ if hint and hint != "auto":
66
+ return HarnessType(hint.lower())
67
+ ev = str(data.get("hook_event_name") or data.get("event") or "")
68
+ if ev in ("PreToolUse", "PostToolUse"):
69
+ return HarnessType.CLAUDE
70
+ if ev in ("BeforeTool", "AfterTool"):
71
+ return HarnessType.GEMINI
72
+ if "cursor_version" in data or ev in (
73
+ "beforeShellExecution",
74
+ "afterShellExecution",
75
+ "beforeMCPExecution",
76
+ "afterMCPExecution",
77
+ ):
78
+ return HarnessType.CURSOR
79
+ if "tool_name" in data and "session_id" in data:
80
+ return HarnessType.CLAUDE
81
+ return HarnessType.GENERIC
82
+
83
+
84
+ def parse_hook_event(raw_json: str, harness_hint: str = "auto") -> HookEvent:
85
+ """Parse raw JSON hook input from Claude Code, Gemini CLI, Cursor, or generic runners."""
86
+ data = json.loads(raw_json) if raw_json.strip() else {}
87
+ harness = _detect_harness(data, hint=harness_hint)
88
+ ev_name = str(data.get("hook_event_name") or data.get("event") or data.get("phase") or "")
89
+
90
+ # Determine phase
91
+ ev_lower = ev_name.lower()
92
+ if any(k in ev_lower for k in ("post", "after")):
93
+ phase = "post_tool"
94
+ elif any(k in ev_lower for k in ("pre", "before")):
95
+ phase = "pre_tool"
96
+ elif "tool_response" in data or "output" in data or "result" in data:
97
+ phase = "post_tool"
98
+ else:
99
+ phase = "pre_tool"
100
+
101
+ # Extract tool name and input
102
+ tool_name = str(data.get("tool_name") or data.get("tool") or "")
103
+ tool_input = data.get("tool_input") or data.get("input") or {}
104
+ if not isinstance(tool_input, dict):
105
+ tool_input = {"raw": tool_input}
106
+
107
+ if harness == HarnessType.CURSOR and not tool_name:
108
+ if "command" in data:
109
+ tool_name = "Bash"
110
+ tool_input = {"command": data["command"], **tool_input}
111
+ elif "mcp_tool_name" in data:
112
+ tool_name = str(data["mcp_tool_name"])
113
+
114
+ raw_resp = data.get("tool_response")
115
+ if raw_resp is None:
116
+ raw_resp = data.get("output") if "output" in data else data.get("result")
117
+ output_text, is_err = _extract_output_text(raw_resp)
118
+
119
+ session_id = str(
120
+ data.get("session_id")
121
+ or data.get("conversation_id")
122
+ or os.environ.get("HOOKBRAKE_SESSION_ID")
123
+ or "default"
124
+ )
125
+ cwd = str(data.get("cwd") or os.getcwd())
126
+
127
+ return HookEvent(
128
+ harness=harness,
129
+ phase=phase,
130
+ session_id=session_id,
131
+ tool_name=tool_name or "unknown",
132
+ tool_input=tool_input,
133
+ tool_output=output_text,
134
+ is_error=is_err,
135
+ cwd=cwd,
136
+ raw=data,
137
+ )
138
+
139
+
140
+ def format_hook_decision(
141
+ event: HookEvent,
142
+ decision: str,
143
+ reason: str = "",
144
+ modified_output: Optional[str] = None,
145
+ warning: str = "",
146
+ ) -> Tuple[int, str]:
147
+ """
148
+ Format a normalized decision ('allow', 'deny', 'warn') into the target harness JSON contract.
149
+ Returns (process_exit_code, stdout_payload).
150
+ """
151
+ if event.phase == "pre_tool":
152
+ if decision == "deny":
153
+ if event.harness == HarnessType.CLAUDE:
154
+ payload = {
155
+ "hookSpecificOutput": {
156
+ "hookEventName": "PreToolUse",
157
+ "permissionDecision": "deny",
158
+ "permissionDecisionReason": reason,
159
+ }
160
+ }
161
+ elif event.harness == HarnessType.GEMINI:
162
+ payload = {"decision": "deny", "reason": reason}
163
+ elif event.harness == HarnessType.CURSOR:
164
+ payload = {"permission": "deny", "userMessage": reason, "agentMessage": reason}
165
+ else:
166
+ payload = {"decision": "deny", "reason": reason}
167
+ return 2, json.dumps(payload)
168
+
169
+ if warning:
170
+ if event.harness == HarnessType.CLAUDE:
171
+ return 0, json.dumps(
172
+ {
173
+ "hookSpecificOutput": {
174
+ "hookEventName": "PreToolUse",
175
+ "permissionDecision": "allow",
176
+ "additionalContext": warning,
177
+ }
178
+ }
179
+ )
180
+ return 0, json.dumps({"decision": "allow", "warning": warning})
181
+ return 0, ""
182
+
183
+ # post_tool phase
184
+ payload: Dict[str, Any] = {}
185
+ notes = [p for p in (warning, reason) if p]
186
+ if event.harness == HarnessType.CLAUDE:
187
+ hook_out: Dict[str, Any] = {"hookEventName": "PostToolUse"}
188
+ if notes:
189
+ hook_out["additionalContext"] = "\n".join(notes)
190
+ payload["hookSpecificOutput"] = hook_out
191
+ if modified_output is not None:
192
+ payload["updatedMCPToolOutput"] = modified_output
193
+ elif event.harness == HarnessType.GEMINI:
194
+ if modified_output is not None:
195
+ payload["modifiedResponse"] = modified_output
196
+ if notes:
197
+ payload["systemMessage"] = "\n".join(notes)
198
+ else:
199
+ if modified_output is not None:
200
+ payload["modified_output"] = modified_output
201
+ if notes:
202
+ payload["warning"] = "\n".join(notes)
203
+
204
+ if not payload:
205
+ return 0, ""
206
+ return 0, json.dumps(payload)