| 1 | """Subprocess contract tests for the silent multi-harness brief capture hook.""" |
| 2 | |
| 3 | from __future__ import annotations |
| 4 | |
| 5 | import json |
| 6 | import os |
| 7 | import stat |
| 8 | import subprocess |
| 9 | import sys |
| 10 | from pathlib import Path |
| 11 | |
| 12 | import pytest |
| 13 | |
| 14 | |
| 15 | REPO_ROOT = Path(__file__).resolve().parents[1] |
| 16 | HOOK_SCRIPT = REPO_ROOT / "skills" / "last30days" / "scripts" / "capture_brief_hook.py" |
| 17 | |
| 18 | SAMPLE_BRIEF = """🌐 last30days · Anthropic · Oct 22 to Nov 21, 2026 · v4.5.0 |
| 19 | |
| 20 | ## What I learned |
| 21 | |
| 22 | Anthropic developer threads focus on tool reliability and agent workflows. |
| 23 | |
| 24 | ```text |
| 25 | --- |
| 26 | ✅ All agents reported back! |
| 27 | ├─ 🟠 Reddit: 12 threads │ 48 comments |
| 28 | └─ 🗓️ Oct 22 to Nov 21, 2026 |
| 29 | --- |
| 30 | ``` |
| 31 | |
| 32 | --- |
| 33 | I'm now an expert on Anthropic. Want to explore pricing or competitors? Just ask. |
| 34 | """ |
| 35 | |
| 36 | |
| 37 | def _run_hook( |
| 38 | payload: str | dict[str, object], |
| 39 | *, |
| 40 | save_dir: Path | str | None, |
| 41 | extra_env: dict[str, str] | None = None, |
| 42 | ) -> subprocess.CompletedProcess[str]: |
| 43 | env = os.environ.copy() |
| 44 | env.pop("LAST30DAYS_AUTO_CAPTURE", None) |
| 45 | env.pop("LAST30DAYS_HOOK_DEBUG", None) |
| 46 | if save_dir is not None: |
| 47 | env["LAST30DAYS_MEMORY_DIR"] = str(save_dir) |
| 48 | if extra_env: |
| 49 | env.update(extra_env) |
| 50 | stdin_data = json.dumps(payload) if isinstance(payload, dict) else payload |
| 51 | return subprocess.run( |
| 52 | [sys.executable, str(HOOK_SCRIPT)], |
| 53 | input=stdin_data, |
| 54 | text=True, |
| 55 | capture_output=True, |
| 56 | env=env, |
| 57 | timeout=10, |
| 58 | check=False, |
| 59 | ) |
| 60 | |
| 61 | |
| 62 | @pytest.mark.parametrize( |
| 63 | ("harness", "payload"), |
| 64 | [ |
| 65 | ( |
| 66 | "claude", |
| 67 | { |
| 68 | "hook_event_name": "Stop", |
| 69 | "session_id": "s-1", |
| 70 | "stop_hook_active": False, |
| 71 | "last_assistant_message": SAMPLE_BRIEF, |
| 72 | }, |
| 73 | ), |
| 74 | ( |
| 75 | "codex", |
| 76 | { |
| 77 | "hook_event_name": "Stop", |
| 78 | "turn_id": "t-1", |
| 79 | "stop_hook_active": False, |
| 80 | "last_assistant_message": SAMPLE_BRIEF, |
| 81 | }, |
| 82 | ), |
| 83 | ( |
| 84 | "gemini", |
| 85 | { |
| 86 | "hook_event_name": "AfterAgent", |
| 87 | "session_id": "g-1", |
| 88 | "stop_hook_active": False, |
| 89 | "prompt_response": SAMPLE_BRIEF, |
| 90 | }, |
| 91 | ), |
| 92 | ( |
| 93 | "cursor", |
| 94 | { |
| 95 | "hook_event_name": "afterAgentResponse", |
| 96 | "conversation_id": "c-1", |
| 97 | "text": SAMPLE_BRIEF, |
| 98 | }, |
| 99 | ), |
| 100 | ( |
| 101 | "grok", |
| 102 | { |
| 103 | "hookEventName": "Stop", |
| 104 | "sessionId": "x-1", |
| 105 | "last_assistant_message": SAMPLE_BRIEF, |
| 106 | }, |
| 107 | ), |
| 108 | ], |
| 109 | ) |
| 110 | def test_hook_captures_finished_brief_across_inline_harnesses(tmp_path, harness, payload): |
| 111 | result = _run_hook(payload, save_dir=tmp_path) |
| 112 | |
| 113 | assert result.returncode == 0, f"{harness}: {result.stderr}" |
| 114 | assert result.stdout.strip() == "{}" |
| 115 | assert result.stderr == "" |
| 116 | |
| 117 | saved = tmp_path / "finished" / "anthropic-2026-11-21.md" |
| 118 | assert saved.is_file(), f"{harness} did not write brief" |
| 119 | text = saved.read_text(encoding="utf-8") |
| 120 | assert text.startswith("🌐 last30days · Anthropic · Oct 22 to Nov 21, 2026 · v4.5.0") |
| 121 | assert "I'm now an expert" not in text |
| 122 | |
| 123 | |
| 124 | def test_hook_resolves_antigravity_untruncated_transcript_full(tmp_path): |
| 125 | logs_dir = tmp_path / "brain" / "conv-1" / ".system_generated" / "logs" |
| 126 | logs_dir.mkdir(parents=True) |
| 127 | compact = logs_dir / "transcript.jsonl" |
| 128 | full = logs_dir / "transcript_full.jsonl" |
| 129 | |
| 130 | # Compact transcript truncates content before the closing footer. |
| 131 | compact.write_text( |
| 132 | json.dumps( |
| 133 | { |
| 134 | "type": "PLANNER_RESPONSE", |
| 135 | "step_index": 7, |
| 136 | "content": SAMPLE_BRIEF[:120], |
| 137 | "truncated_fields": ["content"], |
| 138 | } |
| 139 | ) |
| 140 | + "\n", |
| 141 | encoding="utf-8", |
| 142 | ) |
| 143 | full.write_text( |
| 144 | json.dumps( |
| 145 | { |
| 146 | "type": "PLANNER_RESPONSE", |
| 147 | "step_index": 7, |
| 148 | "content": SAMPLE_BRIEF, |
| 149 | } |
| 150 | ) |
| 151 | + "\n", |
| 152 | encoding="utf-8", |
| 153 | ) |
| 154 | |
| 155 | save_dir = tmp_path / "memory" |
| 156 | payload = { |
| 157 | "hookEventName": "Stop", |
| 158 | "conversationId": "conv-1", |
| 159 | "transcriptPath": str(compact), |
| 160 | "terminationReason": "NO_TOOL_CALL", |
| 161 | "continuationActive": False, |
| 162 | } |
| 163 | result = _run_hook(payload, save_dir=save_dir) |
| 164 | |
| 165 | assert result.returncode == 0 |
| 166 | assert result.stdout.strip() == "{}" |
| 167 | assert result.stderr == "" |
| 168 | saved = save_dir / "finished" / "anthropic-2026-11-21.md" |
| 169 | assert saved.is_file() |
| 170 | assert "All agents reported back!" in saved.read_text(encoding="utf-8") |
| 171 | |
| 172 | |
| 173 | def test_hook_reads_claude_transcript_fallback_when_inline_missing(tmp_path): |
| 174 | transcript = tmp_path / "session.jsonl" |
| 175 | transcript.write_text( |
| 176 | json.dumps( |
| 177 | { |
| 178 | "type": "assistant", |
| 179 | "message": { |
| 180 | "role": "assistant", |
| 181 | "content": [{"type": "text", "text": SAMPLE_BRIEF}], |
| 182 | }, |
| 183 | } |
| 184 | ) |
| 185 | + "\n", |
| 186 | encoding="utf-8", |
| 187 | ) |
| 188 | save_dir = tmp_path / "memory" |
| 189 | result = _run_hook( |
| 190 | {"hook_event_name": "Stop", "transcript_path": str(transcript)}, |
| 191 | save_dir=save_dir, |
| 192 | ) |
| 193 | |
| 194 | assert result.returncode == 0 |
| 195 | assert result.stdout.strip() == "{}" |
| 196 | assert (save_dir / "finished" / "anthropic-2026-11-21.md").is_file() |
| 197 | |
| 198 | |
| 199 | @pytest.mark.parametrize( |
| 200 | ("payload", "save_dir_override", "extra_env"), |
| 201 | [ |
| 202 | ({"hook_event_name": "Stop", "last_assistant_message": "Fixed the unit test."}, None, None), |
| 203 | ({"hook_event_name": "Stop", "stop_hook_active": True, "last_assistant_message": SAMPLE_BRIEF}, None, None), |
| 204 | ({"hookEventName": "Stop", "continuationActive": True, "last_assistant_message": SAMPLE_BRIEF}, None, None), |
| 205 | ({"hookEventName": "Stop", "terminationReason": "USER_CANCELED", "last_assistant_message": SAMPLE_BRIEF}, None, None), |
| 206 | ({"hook_event_name": "stop", "status": "aborted", "text": SAMPLE_BRIEF}, None, None), |
| 207 | ({"hook_event_name": "Stop", "last_assistant_message": SAMPLE_BRIEF}, "", None), |
| 208 | ({"hook_event_name": "Stop", "last_assistant_message": SAMPLE_BRIEF}, None, {"LAST30DAYS_AUTO_CAPTURE": "0"}), |
| 209 | ], |
| 210 | ) |
| 211 | def test_hook_fast_silent_noop_on_guards_and_disabled_config( |
| 212 | tmp_path, payload, save_dir_override, extra_env |
| 213 | ): |
| 214 | target_dir = tmp_path / "should_not_exist" |
| 215 | effective_save_dir = save_dir_override if save_dir_override is not None else target_dir |
| 216 | result = _run_hook(payload, save_dir=effective_save_dir, extra_env=extra_env) |
| 217 | |
| 218 | assert result.returncode == 0 |
| 219 | assert result.stdout.strip() == "{}" |
| 220 | assert result.stderr == "" |
| 221 | assert not target_dir.exists() |
| 222 | |
| 223 | |
| 224 | def test_hook_swallows_errors_silently_unless_debug_enabled(tmp_path): |
| 225 | # Malformed stdin JSON |
| 226 | bad_json = _run_hook("{not valid json", save_dir=tmp_path) |
| 227 | assert bad_json.returncode == 0 |
| 228 | assert bad_json.stdout.strip() == "{}" |
| 229 | assert bad_json.stderr == "" |
| 230 | |
| 231 | # Empty stdin |
| 232 | empty = _run_hook("", save_dir=tmp_path) |
| 233 | assert empty.returncode == 0 |
| 234 | assert empty.stdout.strip() == "{}" |
| 235 | assert empty.stderr == "" |
| 236 | |
| 237 | # Missing transcript path |
| 238 | missing = _run_hook( |
| 239 | {"hook_event_name": "Stop", "transcript_path": str(tmp_path / "missing.jsonl")}, |
| 240 | save_dir=tmp_path, |
| 241 | ) |
| 242 | assert missing.returncode == 0 |
| 243 | assert missing.stdout.strip() == "{}" |
| 244 | assert missing.stderr == "" |
| 245 | |
| 246 | # Unwritable save path: silent by default, logs only when debug enabled. |
| 247 | blocker = tmp_path / "not_a_dir" |
| 248 | blocker.write_text("file", encoding="utf-8") |
| 249 | silent_fail = _run_hook( |
| 250 | {"hook_event_name": "Stop", "last_assistant_message": SAMPLE_BRIEF}, |
| 251 | save_dir=blocker, |
| 252 | ) |
| 253 | assert silent_fail.returncode == 0 |
| 254 | assert silent_fail.stdout.strip() == "{}" |
| 255 | assert silent_fail.stderr == "" |
| 256 | |
| 257 | debug_fail = _run_hook( |
| 258 | {"hook_event_name": "Stop", "last_assistant_message": SAMPLE_BRIEF}, |
| 259 | save_dir=blocker, |
| 260 | extra_env={"LAST30DAYS_HOOK_DEBUG": "1"}, |
| 261 | ) |
| 262 | assert debug_fail.returncode == 0 |
| 263 | assert debug_fail.stdout.strip() == "{}" |
| 264 | assert "capture_brief_hook" in debug_fail.stderr |
| 265 |