| 1 | """Install, remove, and inspect silent brief-capture hooks across local agent harnesses.""" |
| 2 | |
| 3 | from __future__ import annotations |
| 4 | |
| 5 | import json |
| 6 | import os |
| 7 | import tempfile |
| 8 | from pathlib import Path |
| 9 | from typing import Any |
| 10 | |
| 11 | from . import env |
| 12 | |
| 13 | |
| 14 | SUPPORTED_HARNESSES: tuple[str, ...] = ( |
| 15 | "claude", |
| 16 | "antigravity", |
| 17 | "gemini", |
| 18 | "codex", |
| 19 | "cursor", |
| 20 | "grok", |
| 21 | ) |
| 22 | HOOK_MARKER = "capture_brief_hook.py" |
| 23 | ANTIGRAVITY_HOOK_NAME = "last30days-brief-capture" |
| 24 | GEMINI_HOOK_NAME = "last30days-brief-capture" |
| 25 | GROK_HOOK_FILENAME = "last30days-brief-capture.json" |
| 26 | |
| 27 | _HOST_DIRS: dict[str, str] = { |
| 28 | "claude": ".claude", |
| 29 | "antigravity": ".agents", |
| 30 | "gemini": ".gemini", |
| 31 | "codex": ".codex", |
| 32 | "cursor": ".cursor", |
| 33 | "grok": ".grok", |
| 34 | } |
| 35 | |
| 36 | _GROK_BOT_MESSAGE = ( |
| 37 | "Hosted Grok Bot has no local filesystem or hook runtime, so local " |
| 38 | "brief-capture hooks cannot be installed there." |
| 39 | ) |
| 40 | |
| 41 | |
| 42 | def hook_script_path() -> Path: |
| 43 | """Return the canonical absolute path to capture_brief_hook.py.""" |
| 44 | return (Path(__file__).resolve().parents[1] / HOOK_MARKER).resolve() |
| 45 | |
| 46 | |
| 47 | def _home_dir(home: Path | str | None) -> Path: |
| 48 | return Path(home).expanduser() if home is not None else Path.home() |
| 49 | |
| 50 | |
| 51 | def _config_path(harness: str, home: Path) -> Path: |
| 52 | if harness == "claude": |
| 53 | return home / ".claude" / "settings.json" |
| 54 | if harness == "antigravity": |
| 55 | return home / ".agents" / "hooks.json" |
| 56 | if harness == "gemini": |
| 57 | return home / ".gemini" / "settings.json" |
| 58 | if harness == "codex": |
| 59 | return home / ".codex" / "hooks.json" |
| 60 | if harness == "cursor": |
| 61 | return home / ".cursor" / "hooks.json" |
| 62 | if harness == "grok": |
| 63 | return home / ".grok" / "hooks" / GROK_HOOK_FILENAME |
| 64 | raise ValueError(f"unknown harness: {harness}") |
| 65 | |
| 66 | |
| 67 | def detect_local_harnesses(*, home: Path | str | None = None) -> list[str]: |
| 68 | """Return supported local harnesses whose config root directory already exists.""" |
| 69 | base = _home_dir(home) |
| 70 | return [name for name in SUPPORTED_HARNESSES if (base / _HOST_DIRS[name]).is_dir()] |
| 71 | |
| 72 | |
| 73 | def _command_string(script: Path) -> str: |
| 74 | return f'python3 "{script}"' |
| 75 | |
| 76 | |
| 77 | def _read_json_object(path: Path) -> dict[str, Any]: |
| 78 | if not path.is_file(): |
| 79 | return {} |
| 80 | raw = path.read_text(encoding="utf-8").strip() |
| 81 | if not raw: |
| 82 | return {} |
| 83 | data = json.loads(raw) |
| 84 | if not isinstance(data, dict): |
| 85 | raise ValueError(f"{path} does not contain a JSON object") |
| 86 | return data |
| 87 | |
| 88 | |
| 89 | def _write_json_atomic(path: Path, data: dict[str, Any]) -> None: |
| 90 | path.parent.mkdir(parents=True, exist_ok=True) |
| 91 | rendered = json.dumps(data, indent=2) + "\n" |
| 92 | staged = tempfile.NamedTemporaryFile( |
| 93 | mode="w", |
| 94 | encoding="utf-8", |
| 95 | dir=path.parent, |
| 96 | prefix=f".{path.name}.", |
| 97 | delete=False, |
| 98 | ) |
| 99 | try: |
| 100 | with staged: |
| 101 | staged.write(rendered) |
| 102 | os.replace(staged.name, path) |
| 103 | finally: |
| 104 | Path(staged.name).unlink(missing_ok=True) |
| 105 | |
| 106 | |
| 107 | def _handler_has_marker(handler: object) -> bool: |
| 108 | return isinstance(handler, dict) and HOOK_MARKER in str(handler.get("command") or "") |
| 109 | |
| 110 | |
| 111 | def _group_has_marker(group: object) -> bool: |
| 112 | if _handler_has_marker(group): |
| 113 | return True |
| 114 | if not isinstance(group, dict): |
| 115 | return False |
| 116 | handlers = group.get("hooks") |
| 117 | if isinstance(handlers, list): |
| 118 | return any(_handler_has_marker(handler) for handler in handlers) |
| 119 | return False |
| 120 | |
| 121 | |
| 122 | def _install_grouped_event( |
| 123 | path: Path, |
| 124 | *, |
| 125 | event: str, |
| 126 | new_handler: dict[str, Any], |
| 127 | new_group: dict[str, Any] | None = None, |
| 128 | extra_top: dict[str, Any] | None = None, |
| 129 | ) -> str: |
| 130 | """Install or update ONLY the matching handler while preserving sibling handlers and group settings.""" |
| 131 | data = _read_json_object(path) |
| 132 | if extra_top: |
| 133 | for key, value in extra_top.items(): |
| 134 | data.setdefault(key, value) |
| 135 | hooks = data.get("hooks") |
| 136 | if not isinstance(hooks, dict): |
| 137 | hooks = {} |
| 138 | data["hooks"] = hooks |
| 139 | groups = hooks.get(event) |
| 140 | if not isinstance(groups, list): |
| 141 | groups = [] |
| 142 | hooks[event] = groups |
| 143 | |
| 144 | for idx, existing in enumerate(groups): |
| 145 | if _handler_has_marker(existing): |
| 146 | if existing == new_handler: |
| 147 | return "already-installed" |
| 148 | groups[idx] = new_handler |
| 149 | _write_json_atomic(path, data) |
| 150 | return "updated" |
| 151 | if isinstance(existing, dict) and isinstance(existing.get("hooks"), list): |
| 152 | child_hooks = existing["hooks"] |
| 153 | for h_idx, handler in enumerate(child_hooks): |
| 154 | if _handler_has_marker(handler): |
| 155 | if handler == new_handler: |
| 156 | return "already-installed" |
| 157 | child_hooks[h_idx] = new_handler |
| 158 | _write_json_atomic(path, data) |
| 159 | return "updated" |
| 160 | |
| 161 | groups.append(new_group if new_group is not None else new_handler) |
| 162 | _write_json_atomic(path, data) |
| 163 | return "installed" |
| 164 | |
| 165 | |
| 166 | def _uninstall_grouped_event(path: Path, *, event: str) -> str: |
| 167 | """Remove ONLY the matching handler, keeping sibling handlers and group metadata intact.""" |
| 168 | if not path.is_file(): |
| 169 | return "not-installed" |
| 170 | data = _read_json_object(path) |
| 171 | hooks = data.get("hooks") |
| 172 | if not isinstance(hooks, dict): |
| 173 | return "not-installed" |
| 174 | groups = hooks.get(event) |
| 175 | if not isinstance(groups, list): |
| 176 | return "not-installed" |
| 177 | |
| 178 | changed = False |
| 179 | kept_groups: list[Any] = [] |
| 180 | for entry in groups: |
| 181 | if _handler_has_marker(entry): |
| 182 | changed = True |
| 183 | continue |
| 184 | if isinstance(entry, dict) and isinstance(entry.get("hooks"), list): |
| 185 | orig_handlers = entry["hooks"] |
| 186 | kept_handlers = [h for h in orig_handlers if not _handler_has_marker(h)] |
| 187 | if len(kept_handlers) != len(orig_handlers): |
| 188 | changed = True |
| 189 | if kept_handlers: |
| 190 | updated_group = dict(entry) |
| 191 | updated_group["hooks"] = kept_handlers |
| 192 | kept_groups.append(updated_group) |
| 193 | continue |
| 194 | kept_groups.append(entry) |
| 195 | |
| 196 | if not changed: |
| 197 | return "not-installed" |
| 198 | hooks[event] = kept_groups |
| 199 | _write_json_atomic(path, data) |
| 200 | return "removed" |
| 201 | |
| 202 | |
| 203 | def _install_one(harness: str, home: Path, script: Path) -> dict[str, Any]: |
| 204 | path = _config_path(harness, home) |
| 205 | command = _command_string(script) |
| 206 | note = "" |
| 207 | |
| 208 | if harness in {"claude", "codex"}: |
| 209 | handler = {"type": "command", "command": command, "timeout": 5} |
| 210 | group = {"hooks": [handler]} |
| 211 | status = _install_grouped_event(path, event="Stop", new_handler=handler, new_group=group) |
| 212 | if harness == "codex": |
| 213 | note = "Run /hooks inside Codex CLI to trust the newly installed hook." |
| 214 | elif harness == "gemini": |
| 215 | handler = { |
| 216 | "name": GEMINI_HOOK_NAME, |
| 217 | "type": "command", |
| 218 | "command": command, |
| 219 | "timeout": 5000, |
| 220 | } |
| 221 | group = {"matcher": "*", "hooks": [handler]} |
| 222 | status = _install_grouped_event(path, event="AfterAgent", new_handler=handler, new_group=group) |
| 223 | elif harness == "cursor": |
| 224 | handler = {"command": command} |
| 225 | status = _install_grouped_event( |
| 226 | path, |
| 227 | event="afterAgentResponse", |
| 228 | new_handler=handler, |
| 229 | new_group=None, |
| 230 | extra_top={"version": 1}, |
| 231 | ) |
| 232 | elif harness == "antigravity": |
| 233 | data = _read_json_object(path) |
| 234 | entry = {"Stop": [{"type": "command", "command": command, "timeout": 5}]} |
| 235 | existing = data.get(ANTIGRAVITY_HOOK_NAME) |
| 236 | if existing == entry: |
| 237 | status = "already-installed" |
| 238 | else: |
| 239 | status = "updated" if existing is not None else "installed" |
| 240 | data[ANTIGRAVITY_HOOK_NAME] = entry |
| 241 | _write_json_atomic(path, data) |
| 242 | elif harness == "grok": |
| 243 | desired = { |
| 244 | "hooks": { |
| 245 | "Stop": [ |
| 246 | {"hooks": [{"type": "command", "command": command, "timeout": 5}]} |
| 247 | ] |
| 248 | } |
| 249 | } |
| 250 | if path.is_file() and _read_json_object(path) == desired: |
| 251 | status = "already-installed" |
| 252 | else: |
| 253 | status = "updated" if path.is_file() else "installed" |
| 254 | _write_json_atomic(path, desired) |
| 255 | else: |
| 256 | raise ValueError(f"unknown harness: {harness}") |
| 257 | |
| 258 | result: dict[str, Any] = {"status": status, "path": str(path)} |
| 259 | if note: |
| 260 | result["note"] = note |
| 261 | return result |
| 262 | |
| 263 | |
| 264 | def _uninstall_one(harness: str, home: Path) -> dict[str, Any]: |
| 265 | path = _config_path(harness, home) |
| 266 | if harness in {"claude", "codex"}: |
| 267 | status = _uninstall_grouped_event(path, event="Stop") |
| 268 | elif harness == "gemini": |
| 269 | status = _uninstall_grouped_event(path, event="AfterAgent") |
| 270 | elif harness == "cursor": |
| 271 | status = _uninstall_grouped_event(path, event="afterAgentResponse") |
| 272 | elif harness == "antigravity": |
| 273 | if not path.is_file(): |
| 274 | status = "not-installed" |
| 275 | else: |
| 276 | data = _read_json_object(path) |
| 277 | if ANTIGRAVITY_HOOK_NAME not in data: |
| 278 | status = "not-installed" |
| 279 | else: |
| 280 | del data[ANTIGRAVITY_HOOK_NAME] |
| 281 | _write_json_atomic(path, data) |
| 282 | status = "removed" |
| 283 | elif harness == "grok": |
| 284 | if path.is_file(): |
| 285 | path.unlink() |
| 286 | status = "removed" |
| 287 | else: |
| 288 | status = "not-installed" |
| 289 | else: |
| 290 | raise ValueError(f"unknown harness: {harness}") |
| 291 | return {"status": status, "path": str(path)} |
| 292 | |
| 293 | |
| 294 | def _resolve_targets(target: str, home: Path) -> list[str]: |
| 295 | normalized = target.strip().lower() or "all" |
| 296 | if normalized == "all": |
| 297 | return detect_local_harnesses(home=home) |
| 298 | if normalized in SUPPORTED_HARNESSES: |
| 299 | return [normalized] |
| 300 | raise ValueError( |
| 301 | f"unknown harness '{target}'; supported harnesses are {', '.join(SUPPORTED_HARNESSES)}, all" |
| 302 | ) |
| 303 | |
| 304 | |
| 305 | def _is_hosted_grok_bot(target: str, host_env: str | None) -> bool: |
| 306 | resolved_host = ( |
| 307 | host_env if host_env is not None else os.environ.get(env.X_HOST_VAR, "") |
| 308 | ).strip() |
| 309 | if env.x_policy({env.X_HOST_VAR: resolved_host}).official_only: |
| 310 | return True |
| 311 | return target.strip().lower() == env.GROK_BOT_HOST |
| 312 | |
| 313 | |
| 314 | def install_hooks( |
| 315 | target: str = "all", |
| 316 | *, |
| 317 | home: Path | str | None = None, |
| 318 | host_env: str | None = None, |
| 319 | script_path: Path | None = None, |
| 320 | ) -> dict[str, Any]: |
| 321 | """Install silent brief-capture hooks for one or all detected local harnesses.""" |
| 322 | if _is_hosted_grok_bot(target, host_env): |
| 323 | return { |
| 324 | "ok": False, |
| 325 | "unsupported_host": env.GROK_BOT_HOST, |
| 326 | "message": _GROK_BOT_MESSAGE, |
| 327 | "results": {}, |
| 328 | } |
| 329 | |
| 330 | base = _home_dir(home) |
| 331 | targets = _resolve_targets(target, base) |
| 332 | script = (script_path or hook_script_path()).resolve() |
| 333 | results = {name: _install_one(name, base, script) for name in targets} |
| 334 | return {"ok": True, "script": str(script), "results": results} |
| 335 | |
| 336 | |
| 337 | def uninstall_hooks( |
| 338 | target: str = "all", |
| 339 | *, |
| 340 | home: Path | str | None = None, |
| 341 | host_env: str | None = None, |
| 342 | ) -> dict[str, Any]: |
| 343 | """Remove silent brief-capture hooks for one or all detected local harnesses.""" |
| 344 | if _is_hosted_grok_bot(target, host_env): |
| 345 | return { |
| 346 | "ok": False, |
| 347 | "unsupported_host": env.GROK_BOT_HOST, |
| 348 | "message": _GROK_BOT_MESSAGE, |
| 349 | "results": {}, |
| 350 | } |
| 351 | |
| 352 | base = _home_dir(home) |
| 353 | targets = _resolve_targets(target, base) |
| 354 | results = {name: _uninstall_one(name, base) for name in targets} |
| 355 | return {"ok": True, "results": results} |
| 356 | |
| 357 | |
| 358 | def _is_installed(harness: str, home: Path) -> bool: |
| 359 | path = _config_path(harness, home) |
| 360 | if not path.is_file(): |
| 361 | return False |
| 362 | try: |
| 363 | data = _read_json_object(path) |
| 364 | except (OSError, ValueError, json.JSONDecodeError): |
| 365 | return False |
| 366 | if harness == "antigravity": |
| 367 | entry = data.get(ANTIGRAVITY_HOOK_NAME) |
| 368 | return isinstance(entry, dict) and HOOK_MARKER in json.dumps(entry) |
| 369 | if harness == "grok": |
| 370 | return HOOK_MARKER in json.dumps(data) |
| 371 | hooks = data.get("hooks") |
| 372 | if not isinstance(hooks, dict): |
| 373 | return False |
| 374 | event = { |
| 375 | "claude": "Stop", |
| 376 | "codex": "Stop", |
| 377 | "gemini": "AfterAgent", |
| 378 | "cursor": "afterAgentResponse", |
| 379 | }[harness] |
| 380 | groups = hooks.get(event) |
| 381 | return isinstance(groups, list) and any(_group_has_marker(g) for g in groups) |
| 382 | |
| 383 | |
| 384 | def hook_status(*, home: Path | str | None = None) -> dict[str, dict[str, Any]]: |
| 385 | """Read-only inspection of brief-capture hook installation per local harness.""" |
| 386 | base = _home_dir(home) |
| 387 | out: dict[str, dict[str, Any]] = {} |
| 388 | plugin_root_env = os.environ.get("CLAUDE_PLUGIN_ROOT", "").strip() |
| 389 | plugin_active = bool( |
| 390 | plugin_root_env |
| 391 | and (Path(plugin_root_env).expanduser() / ".claude-plugin" / "hooks.json").is_file() |
| 392 | ) |
| 393 | repo_bundled = ( |
| 394 | Path(__file__).resolve().parents[4] / ".claude-plugin" / "hooks.json" |
| 395 | ).is_file() |
| 396 | |
| 397 | for harness in SUPPORTED_HARNESSES: |
| 398 | path = _config_path(harness, home=base) |
| 399 | installed = _is_installed(harness, base) |
| 400 | if installed: |
| 401 | status = "installed" |
| 402 | elif harness == "claude" and plugin_active: |
| 403 | status = "plugin-active" |
| 404 | else: |
| 405 | status = "not-installed" |
| 406 | entry: dict[str, Any] = {"status": status, "path": str(path)} |
| 407 | if harness == "claude" and repo_bundled and not installed and not plugin_active: |
| 408 | entry["plugin_bundled_available"] = True |
| 409 | out[harness] = entry |
| 410 | return out |
| 411 |