| 1 | """Tests for cross-harness brief-capture hook installation, removal, and doctor status.""" |
| 2 | |
| 3 | from __future__ import annotations |
| 4 | |
| 5 | import json |
| 6 | import os |
| 7 | import subprocess |
| 8 | import sys |
| 9 | from pathlib import Path |
| 10 | |
| 11 | import pytest |
| 12 | |
| 13 | from lib import doctor, hook_installer |
| 14 | |
| 15 | |
| 16 | REPO_ROOT = Path(__file__).resolve().parents[1] |
| 17 | CLI_SCRIPT = REPO_ROOT / "skills" / "last30days" / "scripts" / "last30days.py" |
| 18 | |
| 19 | |
| 20 | def _run_cli( |
| 21 | *args: str, |
| 22 | home: Path, |
| 23 | extra_env: dict[str, str] | None = None, |
| 24 | ) -> subprocess.CompletedProcess[str]: |
| 25 | env = os.environ.copy() |
| 26 | env["HOME"] = str(home) |
| 27 | env["LAST30DAYS_MEMORY_DIR"] = str(home / "Documents" / "Last30Days") |
| 28 | env.pop("LAST30DAYS_HOST", None) |
| 29 | if extra_env: |
| 30 | env.update(extra_env) |
| 31 | return subprocess.run( |
| 32 | [sys.executable, str(CLI_SCRIPT), *args], |
| 33 | cwd=REPO_ROOT, |
| 34 | text=True, |
| 35 | capture_output=True, |
| 36 | env=env, |
| 37 | timeout=15, |
| 38 | check=False, |
| 39 | ) |
| 40 | |
| 41 | |
| 42 | @pytest.mark.parametrize("harness", hook_installer.SUPPORTED_HARNESSES) |
| 43 | def test_install_idempotent_and_uninstall_preserves_existing_hooks(tmp_path, harness): |
| 44 | script = tmp_path / "capture_brief_hook.py" |
| 45 | script.write_text("#!/usr/bin/env python3\n", encoding="utf-8") |
| 46 | |
| 47 | # Seed pre-existing user configuration with an unrelated hook. |
| 48 | if harness == "claude": |
| 49 | cfg = tmp_path / ".claude" / "settings.json" |
| 50 | cfg.parent.mkdir(parents=True) |
| 51 | cfg.write_text( |
| 52 | json.dumps( |
| 53 | { |
| 54 | "theme": "dark", |
| 55 | "hooks": { |
| 56 | "Stop": [ |
| 57 | {"hooks": [{"type": "command", "command": "echo keep-me"}]} |
| 58 | ] |
| 59 | }, |
| 60 | } |
| 61 | ), |
| 62 | encoding="utf-8", |
| 63 | ) |
| 64 | elif harness == "antigravity": |
| 65 | cfg = tmp_path / ".agents" / "hooks.json" |
| 66 | cfg.parent.mkdir(parents=True) |
| 67 | cfg.write_text( |
| 68 | json.dumps( |
| 69 | { |
| 70 | "user-lint": { |
| 71 | "Stop": [{"type": "command", "command": "echo keep-me"}] |
| 72 | } |
| 73 | } |
| 74 | ), |
| 75 | encoding="utf-8", |
| 76 | ) |
| 77 | elif harness == "gemini": |
| 78 | cfg = tmp_path / ".gemini" / "settings.json" |
| 79 | cfg.parent.mkdir(parents=True) |
| 80 | cfg.write_text( |
| 81 | json.dumps( |
| 82 | { |
| 83 | "hooks": { |
| 84 | "AfterAgent": [ |
| 85 | { |
| 86 | "matcher": "*", |
| 87 | "hooks": [ |
| 88 | { |
| 89 | "name": "user-hook", |
| 90 | "type": "command", |
| 91 | "command": "echo keep-me", |
| 92 | "timeout": 3000, |
| 93 | } |
| 94 | ], |
| 95 | } |
| 96 | ] |
| 97 | } |
| 98 | } |
| 99 | ), |
| 100 | encoding="utf-8", |
| 101 | ) |
| 102 | elif harness == "codex": |
| 103 | cfg = tmp_path / ".codex" / "hooks.json" |
| 104 | cfg.parent.mkdir(parents=True) |
| 105 | cfg.write_text( |
| 106 | json.dumps( |
| 107 | { |
| 108 | "hooks": { |
| 109 | "Stop": [ |
| 110 | {"hooks": [{"type": "command", "command": "echo keep-me"}]} |
| 111 | ] |
| 112 | } |
| 113 | } |
| 114 | ), |
| 115 | encoding="utf-8", |
| 116 | ) |
| 117 | elif harness == "cursor": |
| 118 | cfg = tmp_path / ".cursor" / "hooks.json" |
| 119 | cfg.parent.mkdir(parents=True) |
| 120 | cfg.write_text( |
| 121 | json.dumps( |
| 122 | { |
| 123 | "version": 1, |
| 124 | "hooks": { |
| 125 | "afterAgentResponse": [{"command": "echo keep-me"}] |
| 126 | }, |
| 127 | } |
| 128 | ), |
| 129 | encoding="utf-8", |
| 130 | ) |
| 131 | elif harness == "grok": |
| 132 | cfg = tmp_path / ".grok" / "hooks" / "user-other.json" |
| 133 | cfg.parent.mkdir(parents=True) |
| 134 | cfg.write_text('{"hooks":{"Stop":[]}}\n', encoding="utf-8") |
| 135 | |
| 136 | first = hook_installer.install_hooks(harness, home=tmp_path, script_path=script) |
| 137 | assert first["ok"] is True |
| 138 | assert first["results"][harness]["status"] == "installed" |
| 139 | if harness == "codex": |
| 140 | assert "/hooks" in first["results"][harness].get("note", "") |
| 141 | |
| 142 | # Second install must be idempotent (no duplicate entries). |
| 143 | second = hook_installer.install_hooks(harness, home=tmp_path, script_path=script) |
| 144 | assert second["ok"] is True |
| 145 | assert second["results"][harness]["status"] == "already-installed" |
| 146 | |
| 147 | status = hook_installer.hook_status(home=tmp_path) |
| 148 | assert status[harness]["status"] == "installed" |
| 149 | |
| 150 | # Verify schema details & preservation of user entries. |
| 151 | if harness == "gemini": |
| 152 | data = json.loads((tmp_path / ".gemini" / "settings.json").read_text(encoding="utf-8")) |
| 153 | entries = data["hooks"]["AfterAgent"] |
| 154 | assert len(entries) == 2 |
| 155 | assert entries[1]["hooks"][0]["timeout"] == 5000 |
| 156 | elif harness == "antigravity": |
| 157 | data = json.loads((tmp_path / ".agents" / "hooks.json").read_text(encoding="utf-8")) |
| 158 | assert "user-lint" in data |
| 159 | assert "last30days-brief-capture" in data |
| 160 | assert "Stop" in data["last30days-brief-capture"] |
| 161 | elif harness == "cursor": |
| 162 | data = json.loads((tmp_path / ".cursor" / "hooks.json").read_text(encoding="utf-8")) |
| 163 | assert data["version"] == 1 |
| 164 | assert len(data["hooks"]["afterAgentResponse"]) == 2 |
| 165 | elif harness == "grok": |
| 166 | assert (tmp_path / ".grok" / "hooks" / "last30days-brief-capture.json").is_file() |
| 167 | assert (tmp_path / ".grok" / "hooks" / "user-other.json").is_file() |
| 168 | |
| 169 | # Uninstall removes only last30days hook while preserving existing user config. |
| 170 | removed = hook_installer.uninstall_hooks(harness, home=tmp_path) |
| 171 | assert removed["ok"] is True |
| 172 | assert removed["results"][harness]["status"] == "removed" |
| 173 | assert hook_installer.hook_status(home=tmp_path)[harness]["status"] == "not-installed" |
| 174 | |
| 175 | if harness == "claude": |
| 176 | data = json.loads((tmp_path / ".claude" / "settings.json").read_text(encoding="utf-8")) |
| 177 | assert data["theme"] == "dark" |
| 178 | assert len(data["hooks"]["Stop"]) == 1 |
| 179 | elif harness == "antigravity": |
| 180 | data = json.loads((tmp_path / ".agents" / "hooks.json").read_text(encoding="utf-8")) |
| 181 | assert "user-lint" in data |
| 182 | assert "last30days-brief-capture" not in data |
| 183 | elif harness == "grok": |
| 184 | assert not (tmp_path / ".grok" / "hooks" / "last30days-brief-capture.json").exists() |
| 185 | assert (tmp_path / ".grok" / "hooks" / "user-other.json").is_file() |
| 186 | |
| 187 | |
| 188 | def test_cli_setup_install_and_uninstall_hooks_all_and_validation(tmp_path): |
| 189 | (tmp_path / ".claude").mkdir() |
| 190 | (tmp_path / ".cursor").mkdir() |
| 191 | |
| 192 | # Bare --install-hooks (no value) installs for all detected local harnesses. |
| 193 | res = _run_cli("setup", "--install-hooks", home=tmp_path) |
| 194 | assert res.returncode == 0, res.stderr |
| 195 | payload = json.loads(res.stdout) |
| 196 | assert payload["ok"] is True |
| 197 | assert set(payload["results"].keys()) == {"claude", "cursor"} |
| 198 | assert not (tmp_path / ".codex").exists() |
| 199 | |
| 200 | # Reject unknown host. |
| 201 | bad = _run_cli("setup", "--install-hooks", "unknown-host", home=tmp_path) |
| 202 | assert bad.returncode == 2 |
| 203 | |
| 204 | # Reject mutually exclusive flags. |
| 205 | both = _run_cli("setup", "--install-hooks", "--uninstall-hooks", home=tmp_path) |
| 206 | assert both.returncode == 2 |
| 207 | |
| 208 | # Bare --uninstall-hooks cleans up cleanly. |
| 209 | unres = _run_cli("setup", "--uninstall-hooks", home=tmp_path) |
| 210 | assert unres.returncode == 0, unres.stderr |
| 211 | assert json.loads(unres.stdout)["results"]["claude"]["status"] == "removed" |
| 212 | |
| 213 | |
| 214 | def test_cli_setup_install_hooks_refuses_hosted_grok_bot_honestly(tmp_path): |
| 215 | res = _run_cli( |
| 216 | "setup", |
| 217 | "--install-hooks", |
| 218 | home=tmp_path, |
| 219 | extra_env={"LAST30DAYS_HOST": "grok-bot"}, |
| 220 | ) |
| 221 | assert res.returncode == 0 |
| 222 | payload = json.loads(res.stdout) |
| 223 | assert payload["ok"] is False |
| 224 | assert payload["unsupported_host"] == "grok-bot" |
| 225 | assert "no local" in payload["message"].lower() |
| 226 | assert not (tmp_path / ".claude").exists() |
| 227 | |
| 228 | explicit = _run_cli("setup", "--install-hooks", "grok-bot", home=tmp_path) |
| 229 | assert explicit.returncode == 0 |
| 230 | assert json.loads(explicit.stdout)["unsupported_host"] == "grok-bot" |
| 231 | |
| 232 | |
| 233 | def test_doctor_reports_brief_capture_hooks_and_finished_count_read_only(tmp_path, monkeypatch): |
| 234 | monkeypatch.setenv("HOME", str(tmp_path)) |
| 235 | memory_dir = tmp_path / "Documents" / "Last30Days" |
| 236 | finished = memory_dir / "finished" |
| 237 | finished.mkdir(parents=True) |
| 238 | (finished / "anthropic-2026-11-21.md").write_text("# stub\n", encoding="utf-8") |
| 239 | hook_installer.install_hooks("cursor", home=tmp_path) |
| 240 | |
| 241 | report = doctor.build_report({"LAST30DAYS_MEMORY_DIR": str(memory_dir)}) |
| 242 | hooks_info = report.get("brief_capture_hooks") |
| 243 | assert isinstance(hooks_info, dict) |
| 244 | assert hooks_info["finished_briefs"] == 1 |
| 245 | assert hooks_info["harnesses"]["cursor"]["status"] == "installed" |
| 246 | assert hooks_info["harnesses"]["codex"]["status"] == "not-installed" |
| 247 | |
| 248 | |
| 249 | def test_shared_group_reinstall_and_uninstall_preserve_sibling_handlers(tmp_path): |
| 250 | script = tmp_path / "new_dir" / "capture_brief_hook.py" |
| 251 | script.parent.mkdir(parents=True) |
| 252 | script.write_text("#!/usr/bin/env python3\n", encoding="utf-8") |
| 253 | |
| 254 | cfg = tmp_path / ".gemini" / "settings.json" |
| 255 | cfg.parent.mkdir(parents=True) |
| 256 | cfg.write_text( |
| 257 | json.dumps( |
| 258 | { |
| 259 | "hooks": { |
| 260 | "AfterAgent": [ |
| 261 | { |
| 262 | "matcher": "custom-matcher", |
| 263 | "hooks": [ |
| 264 | {"name": "keep-sibling", "type": "command", "command": "echo keep-me", "timeout": 1000}, |
| 265 | {"name": "last30days-brief-capture", "type": "command", "command": 'python3 "/old/capture_brief_hook.py"', "timeout": 5000}, |
| 266 | ], |
| 267 | } |
| 268 | ] |
| 269 | } |
| 270 | } |
| 271 | ), |
| 272 | encoding="utf-8", |
| 273 | ) |
| 274 | |
| 275 | updated = hook_installer.install_hooks("gemini", home=tmp_path, script_path=script) |
| 276 | assert updated["results"]["gemini"]["status"] == "updated" |
| 277 | data = json.loads(cfg.read_text(encoding="utf-8")) |
| 278 | group = data["hooks"]["AfterAgent"][0] |
| 279 | assert group["matcher"] == "custom-matcher" |
| 280 | assert [h["command"] for h in group["hooks"]] == [ |
| 281 | "echo keep-me", |
| 282 | f'python3 "{script.resolve()}"', |
| 283 | ] |
| 284 | |
| 285 | removed = hook_installer.uninstall_hooks("gemini", home=tmp_path) |
| 286 | assert removed["results"]["gemini"]["status"] == "removed" |
| 287 | data_after = json.loads(cfg.read_text(encoding="utf-8")) |
| 288 | assert len(data_after["hooks"]["AfterAgent"]) == 1 |
| 289 | assert data_after["hooks"]["AfterAgent"][0]["matcher"] == "custom-matcher" |
| 290 | assert data_after["hooks"]["AfterAgent"][0]["hooks"] == [ |
| 291 | {"name": "keep-sibling", "type": "command", "command": "echo keep-me", "timeout": 1000} |
| 292 | ] |
| 293 | |
| 294 | |
| 295 | def test_doctor_does_not_claim_inactive_claude_plugin_hook_is_active(tmp_path, monkeypatch): |
| 296 | monkeypatch.setenv("HOME", str(tmp_path)) |
| 297 | monkeypatch.delenv("CLAUDE_PLUGIN_ROOT", raising=False) |
| 298 | status = hook_installer.hook_status(home=tmp_path) |
| 299 | assert status["claude"]["status"] == "not-installed" |
| 300 | assert status["claude"].get("plugin_bundled_available") is True |
| 301 | |
| 302 | report = doctor.build_report({"LAST30DAYS_MEMORY_DIR": str(tmp_path / "memory")}) |
| 303 | rendered = doctor.render_text(report) |
| 304 | assert "none active" in rendered |
| 305 | assert "setup --install-hooks" in rendered |
| 306 | |
| 307 | # When CLAUDE_PLUGIN_ROOT points to the active plugin root, status is plugin-active. |
| 308 | monkeypatch.setenv("CLAUDE_PLUGIN_ROOT", str(REPO_ROOT)) |
| 309 | assert hook_installer.hook_status(home=tmp_path)["claude"]["status"] == "plugin-active" |
| 310 | |
| 311 |