hookbrake 0.1.0__py3-none-any.whl

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.
hookbrake/__init__.py ADDED
@@ -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
+ ]
hookbrake/adapters.py ADDED
@@ -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)
hookbrake/audit.py ADDED
@@ -0,0 +1,284 @@
1
+ """Retroactive local session auditor for Claude Code, Codex CLI, and Gemini CLI logs."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import hashlib
6
+ import json
7
+ from dataclasses import asdict, dataclass, field
8
+ from pathlib import Path
9
+ from typing import Any, Dict, List, Optional, Tuple
10
+
11
+ from .compactor import compact_output
12
+ from .config import HookBrakeConfig
13
+ from .redactor import redact_secrets
14
+
15
+ _WRITE_NAMES = {"write", "edit", "multiedit", "apply_patch", "replace_file_content", "write_to_file"}
16
+
17
+
18
+ @dataclass
19
+ class CacheBreakFinding:
20
+ session_file: str
21
+ turn_index: int
22
+ reason: str
23
+ detail: str
24
+
25
+
26
+ @dataclass
27
+ class LoopFinding:
28
+ session_file: str
29
+ tool_name: str
30
+ repeats: int
31
+ estimated_wasted_chars: int
32
+
33
+
34
+ @dataclass
35
+ class AuditReport:
36
+ sessions_scanned: int = 0
37
+ tool_calls_scanned: int = 0
38
+ oversized_outputs: int = 0
39
+ original_output_chars: int = 0
40
+ compacted_chars_saved: int = 0
41
+ estimated_tokens_saved: int = 0
42
+ secrets_exposed: int = 0
43
+ secret_types: Dict[str, int] = field(default_factory=dict)
44
+ stalled_loops: List[LoopFinding] = field(default_factory=list)
45
+ cache_breaks: List[CacheBreakFinding] = field(default_factory=list)
46
+
47
+ def to_dict(self) -> Dict[str, Any]:
48
+ return asdict(self)
49
+
50
+
51
+ def discover_session_files(agent: str = "all", target_path: Optional[Path] = None) -> List[Tuple[str, Path]]:
52
+ """Discover local JSONL session logs across Claude Code, Codex CLI, and Gemini CLI."""
53
+ found: List[Tuple[str, Path]] = []
54
+ if target_path is not None:
55
+ if target_path.is_file():
56
+ return [(agent if agent != "all" else "auto", target_path)]
57
+ if target_path.is_dir():
58
+ for p in sorted(target_path.rglob("*.jsonl")):
59
+ found.append((agent if agent != "all" else "auto", p))
60
+ return found
61
+ return []
62
+
63
+ home = Path.home()
64
+ if agent in ("all", "claude"):
65
+ claude_dir = home / ".claude" / "projects"
66
+ if claude_dir.is_dir():
67
+ for p in sorted(claude_dir.rglob("*.jsonl")):
68
+ found.append(("claude", p))
69
+ if agent in ("all", "codex"):
70
+ codex_dir = home / ".codex" / "sessions"
71
+ if codex_dir.is_dir():
72
+ for p in sorted(codex_dir.rglob("*.jsonl")):
73
+ found.append(("codex", p))
74
+ if agent in ("all", "gemini"):
75
+ gemini_dir = home / ".gemini"
76
+ if gemini_dir.is_dir():
77
+ for p in sorted(gemini_dir.rglob("*.jsonl")):
78
+ found.append(("gemini", p))
79
+ return found
80
+
81
+
82
+ def _extract_claude_events(records: List[Dict[str, Any]]) -> Tuple[List[Dict[str, Any]], List[Tuple[int, str]]]:
83
+ """Extract normalized tool interactions and prompt prefixes/cache telemetry from Claude JSONL."""
84
+ calls: List[Dict[str, Any]] = []
85
+ cache_breaks: List[Tuple[int, str]] = []
86
+ prev_cache_read = 0
87
+ turn_idx = 0
88
+
89
+ for rec in records:
90
+ msg = rec.get("message")
91
+ if not isinstance(msg, dict):
92
+ continue
93
+ role = msg.get("role") or rec.get("type")
94
+ usage = msg.get("usage")
95
+ if isinstance(usage, dict):
96
+ turn_idx += 1
97
+ c_read = int(usage.get("cache_read_input_tokens") or 0)
98
+ c_create = int(usage.get("cache_creation_input_tokens") or 0)
99
+ if prev_cache_read > 2000 and c_read < (prev_cache_read * 0.25) and c_create > 1000:
100
+ cache_breaks.append(
101
+ (
102
+ turn_idx,
103
+ f"cache_read dropped {prev_cache_read:,} -> {c_read:,} while cache_creation spiked to {c_create:,}",
104
+ )
105
+ )
106
+ prev_cache_read = c_read
107
+
108
+ content = msg.get("content")
109
+ if not isinstance(content, list):
110
+ continue
111
+ for block in content:
112
+ if not isinstance(block, dict):
113
+ continue
114
+ btype = block.get("type")
115
+ if btype == "tool_use":
116
+ calls.append(
117
+ {
118
+ "kind": "call",
119
+ "name": str(block.get("name") or "unknown"),
120
+ "input": block.get("input") or {},
121
+ }
122
+ )
123
+ elif btype == "tool_result":
124
+ raw_out = block.get("content")
125
+ if isinstance(raw_out, list):
126
+ text = "\n".join(str(x.get("text", "")) for x in raw_out if isinstance(x, dict))
127
+ else:
128
+ text = str(raw_out or "")
129
+ calls.append({"kind": "result", "output": text})
130
+ return calls, cache_breaks
131
+
132
+
133
+ def _extract_codex_events(records: List[Dict[str, Any]]) -> Tuple[List[Dict[str, Any]], List[Tuple[int, str]]]:
134
+ """Extract tool interactions and prefix-break checks from Codex rollout JSONL logs."""
135
+ calls: List[Dict[str, Any]] = []
136
+ cache_breaks: List[Tuple[int, str]] = []
137
+ prev_prefix: Optional[str] = None
138
+ turn_idx = 0
139
+
140
+ for rec in records:
141
+ rtype = rec.get("type")
142
+ payload = rec.get("payload") if isinstance(rec.get("payload"), dict) else rec
143
+ # Check prefix continuity if system/instructions block appears repeatedly
144
+ if rtype == "session_meta" or rec.get("role") == "system":
145
+ turn_idx += 1
146
+ sys_txt = json.dumps(payload, sort_keys=True)
147
+ if prev_prefix is not None and sys_txt != prev_prefix:
148
+ div_pos = next((i for i, (a, b) in enumerate(zip(prev_prefix, sys_txt)) if a != b), min(len(prev_prefix), len(sys_txt)))
149
+ cache_breaks.append((turn_idx, f"System/prefix diverged at byte {div_pos}: '{sys_txt[max(0, div_pos-15):div_pos+35]}'"))
150
+ prev_prefix = sys_txt
151
+
152
+ item_type = payload.get("type") if isinstance(payload, dict) else None
153
+ if item_type in ("function_call", "local_shell_call") or "tool_name" in payload:
154
+ calls.append(
155
+ {
156
+ "kind": "call",
157
+ "name": str(payload.get("name") or payload.get("tool_name") or item_type),
158
+ "input": payload.get("arguments") or payload.get("action") or payload.get("tool_input") or {},
159
+ }
160
+ )
161
+ elif item_type in ("function_call_output", "local_shell_call_output") or "output" in payload:
162
+ calls.append({"kind": "result", "output": str(payload.get("output") or "")})
163
+
164
+ return calls, cache_breaks
165
+
166
+
167
+ def _first_diff_line(a: str, b: str) -> str:
168
+ for idx, (la, lb) in enumerate(zip(a.splitlines(), b.splitlines()), start=1):
169
+ if la != lb:
170
+ return f"line {idx}: '{la[:40]}' -> '{lb[:40]}'"
171
+ return "prefix length changed"
172
+
173
+
174
+ def _audit_single_file(path: Path, agent_hint: str, config: HookBrakeConfig, report: AuditReport) -> None:
175
+ records: List[Dict[str, Any]] = []
176
+ try:
177
+ with path.open("r", encoding="utf-8", errors="replace") as fh:
178
+ for line in fh:
179
+ line = line.strip()
180
+ if not line:
181
+ continue
182
+ try:
183
+ obj = json.loads(line)
184
+ if isinstance(obj, dict):
185
+ records.append(obj)
186
+ except json.JSONDecodeError:
187
+ continue
188
+ except OSError:
189
+ return
190
+
191
+ if not records:
192
+ return
193
+
194
+ report.sessions_scanned += 1
195
+
196
+ # Auto-detect log shape
197
+ sample = records[0]
198
+ if agent_hint == "codex" or "payload" in sample or sample.get("type") in ("session_meta", "response_item"):
199
+ events, breaks = _extract_codex_events(records)
200
+ else:
201
+ events, breaks = _extract_claude_events(records)
202
+ if not events:
203
+ events, breaks = _extract_codex_events(records)
204
+
205
+ for turn_idx, detail in breaks:
206
+ report.cache_breaks.append(
207
+ CacheBreakFinding(
208
+ session_file=str(path),
209
+ turn_index=turn_idx,
210
+ reason="prompt_cache_break",
211
+ detail=detail,
212
+ )
213
+ )
214
+
215
+ # Walk calls and results to find loops, bloat, and exposed secrets
216
+ last_call_sig: Optional[Tuple[str, str]] = None
217
+ streak = 0
218
+ streak_chars = 0
219
+ prev_out_len = 0
220
+
221
+ for ev in events:
222
+ if ev["kind"] == "call":
223
+ report.tool_calls_scanned += 1
224
+ tname = ev["name"]
225
+ args_str = json.dumps(ev["input"], sort_keys=True, default=str)
226
+ sig = (tname.lower(), hashlib.sha256(args_str.encode("utf-8")).hexdigest()[:12])
227
+
228
+ if tname.lower() in _WRITE_NAMES:
229
+ # An edit resets zero-progress streak
230
+ if streak >= config.max_identical_retries and last_call_sig is not None:
231
+ report.stalled_loops.append(
232
+ LoopFinding(str(path), last_call_sig[0], streak, streak_chars)
233
+ )
234
+ last_call_sig = None
235
+ streak = 0
236
+ streak_chars = 0
237
+ elif sig == last_call_sig:
238
+ streak += 1
239
+ streak_chars += len(args_str) + prev_out_len
240
+ else:
241
+ if streak >= config.max_identical_retries and last_call_sig is not None:
242
+ report.stalled_loops.append(
243
+ LoopFinding(str(path), last_call_sig[0], streak, streak_chars)
244
+ )
245
+ last_call_sig = sig
246
+ streak = 1
247
+ streak_chars = 0
248
+ elif ev["kind"] == "result":
249
+ out_txt = ev["output"]
250
+ prev_out_len = len(out_txt)
251
+ report.original_output_chars += len(out_txt)
252
+
253
+ # Check secrets
254
+ red = redact_secrets(out_txt)
255
+ if red.count > 0:
256
+ report.secrets_exposed += red.count
257
+ for kind in red.types_found:
258
+ report.secret_types[kind] = report.secret_types.get(kind, 0) + 1
259
+
260
+ # Check compaction savings (pure in-memory, artifacts_dir=None)
261
+ comp = compact_output(out_txt, threshold_chars=config.compact_threshold_chars, artifacts_dir=None)
262
+ if comp.was_compacted:
263
+ report.oversized_outputs += 1
264
+ report.compacted_chars_saved += comp.chars_saved
265
+ report.estimated_tokens_saved += comp.chars_saved // 4
266
+
267
+ if streak >= config.max_identical_retries and last_call_sig is not None:
268
+ report.stalled_loops.append(
269
+ LoopFinding(str(path), last_call_sig[0], streak, streak_chars)
270
+ )
271
+
272
+
273
+ def audit_sessions(
274
+ agent: str = "all",
275
+ target_path: Optional[Path] = None,
276
+ config: Optional[HookBrakeConfig] = None,
277
+ ) -> AuditReport:
278
+ """Audit historical local coding-agent sessions for loop waste, bloat, cache breaks, and exposed secrets."""
279
+ cfg = config or HookBrakeConfig()
280
+ report = AuditReport()
281
+ files = discover_session_files(agent=agent, target_path=target_path)
282
+ for agent_hint, fp in files:
283
+ _audit_single_file(fp, agent_hint, cfg, report)
284
+ return report
@@ -0,0 +1,156 @@
1
+ """Git-aware stateful circuit-breaker to stop stalled zero-progress agent loops."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import hashlib
6
+ import json
7
+ import re
8
+ from dataclasses import dataclass
9
+ from typing import Tuple
10
+
11
+ from .adapters import HookEvent
12
+ from .config import HookBrakeConfig
13
+ from .state import StateStore, compute_git_state_hash
14
+
15
+ _READ_TOOLS = {"read", "read_file", "view_file"}
16
+ _WRITE_TOOLS = {"write", "edit", "multiedit", "write_to_file", "replace_file_content", "multi_replace_file_content"}
17
+
18
+
19
+ @dataclass
20
+ class LoopDecision:
21
+ allowed: bool
22
+ reason: str = ""
23
+ loop_type: str = ""
24
+ target_key: str = ""
25
+
26
+
27
+ def _normalize_target_key(event: HookEvent) -> str:
28
+ tool = event.tool_name.strip()
29
+ inp = event.tool_input
30
+ if "command" in inp or "CommandLine" in inp:
31
+ cmd = str(inp.get("command") or inp.get("CommandLine") or "").strip()
32
+ cmd = re.sub(r"\s+", " ", cmd)
33
+ return f"{tool}:{cmd[:80]}"
34
+ for k in ("file_path", "path", "TargetFile", "target_file", "query", "pattern"):
35
+ if k in inp and inp[k]:
36
+ return f"{tool}:{str(inp[k])[:80]}"
37
+ return tool
38
+
39
+
40
+ def _hash_args(tool_name: str, tool_input: dict) -> str:
41
+ canonical = json.dumps({"tool": tool_name.lower(), "input": tool_input}, sort_keys=True, default=str)
42
+ return hashlib.sha256(canonical.encode("utf-8")).hexdigest()[:16]
43
+
44
+
45
+ def evaluate_pre_tool_loop(
46
+ event: HookEvent,
47
+ store: StateStore,
48
+ config: HookBrakeConfig,
49
+ git_hash: str | None = None,
50
+ ) -> Tuple[LoopDecision, str, str, str]:
51
+ """
52
+ Evaluate whether the incoming PreToolUse call continues a stalled loop.
53
+ Returns (LoopDecision, args_hash, git_hash, target_key).
54
+ """
55
+ resolved_git = git_hash if git_hash is not None else compute_git_state_hash(event.cwd)
56
+ args_hash = _hash_args(event.tool_name, event.tool_input)
57
+ target_key = _normalize_target_key(event)
58
+ tool_lower = event.tool_name.strip().lower()
59
+
60
+ recent = store.recent_calls(event.session_id, limit=12)
61
+
62
+ # 1. Consecutive identical retry loop in the same working-tree state
63
+ consec_same = 0
64
+ for rec in reversed(recent):
65
+ if rec.tool_name.lower() == tool_lower and rec.args_hash == args_hash and rec.git_hash == resolved_git:
66
+ consec_same += 1
67
+ else:
68
+ break
69
+
70
+ if consec_same >= max(1, config.max_identical_retries - 1):
71
+ return (
72
+ LoopDecision(
73
+ allowed=False,
74
+ loop_type="identical_retry_loop",
75
+ target_key=target_key,
76
+ reason=(
77
+ f"[hookbrake:loop-breaker] Blocked {target_key}: executed {consec_same + 1} identical times "
78
+ f"with zero workspace changes (git_state={resolved_git}). "
79
+ "Change your approach or inspect a different file before retrying."
80
+ ),
81
+ ),
82
+ args_hash,
83
+ resolved_git,
84
+ target_key,
85
+ )
86
+
87
+ # 2. Unchanged file read-thrash (even when interleaved with other tool calls)
88
+ if tool_lower in _READ_TOOLS:
89
+ same_reads = sum(
90
+ 1
91
+ for rec in recent
92
+ if rec.tool_name.lower() in _READ_TOOLS and rec.args_hash == args_hash and rec.git_hash == resolved_git
93
+ )
94
+ if same_reads >= max(1, config.max_unchanged_rereads - 1):
95
+ return (
96
+ LoopDecision(
97
+ allowed=False,
98
+ loop_type="read_thrash",
99
+ target_key=target_key,
100
+ reason=(
101
+ f"[hookbrake:read-thrash] Blocked {target_key}: file has already been read {same_reads} times "
102
+ f"in this session without modification (git_state={resolved_git}). Use prior context."
103
+ ),
104
+ ),
105
+ args_hash,
106
+ resolved_git,
107
+ target_key,
108
+ )
109
+
110
+ # 3. A <-> B ping-pong cycle across unchanged workspace (excluding intentional file edits)
111
+ if tool_lower not in _WRITE_TOOLS and len(recent) >= config.max_ping_pong_cycles - 1:
112
+ window = recent[-(config.max_ping_pong_cycles - 1) :]
113
+ # Pattern: [B, A, B] followed by incoming A -> A <-> B cycle in same git state
114
+ if (
115
+ len(window) >= 3
116
+ and window[-2].args_hash == args_hash
117
+ and window[-1].args_hash != args_hash
118
+ and len({r.args_hash for r in window[-3:]}) == 2
119
+ and len({r.git_hash for r in window[-3:]} | {resolved_git}) == 1
120
+ ):
121
+ return (
122
+ LoopDecision(
123
+ allowed=False,
124
+ loop_type="ping_pong_cycle",
125
+ target_key=target_key,
126
+ reason=(
127
+ f"[hookbrake:ping-pong] Blocked alternating A<->B cycle involving {target_key} "
128
+ f"with unchanged git state ({resolved_git}). Summarize findings and break the cycle."
129
+ ),
130
+ ),
131
+ args_hash,
132
+ resolved_git,
133
+ target_key,
134
+ )
135
+
136
+ return LoopDecision(allowed=True, target_key=target_key), args_hash, resolved_git, target_key
137
+
138
+
139
+ def check_loop_breaker(event: HookEvent, store: StateStore, config: HookBrakeConfig) -> LoopDecision:
140
+ """Check loop state and record allowed calls in the StateStore."""
141
+ decision, args_hash, git_hash, target_key = evaluate_pre_tool_loop(event, store, config)
142
+ if decision.allowed:
143
+ store.record_call(
144
+ session_id=event.session_id,
145
+ tool_name=event.tool_name,
146
+ args_hash=args_hash,
147
+ git_hash=git_hash,
148
+ target_key=target_key,
149
+ )
150
+ else:
151
+ store.record_metric(
152
+ session_id=event.session_id,
153
+ event_type="loop_blocked",
154
+ reason=decision.loop_type,
155
+ )
156
+ return decision