| 1 | #!/usr/bin/env python3 |
| 2 | """Silent post-turn lifecycle hook that archives completed last30days chat briefs. |
| 3 | |
| 4 | Designed to run across local agent harnesses (Claude Code, Antigravity, Gemini |
| 5 | CLI, Codex CLI, Cursor, and Grok Build CLI) with zero chat output and negligible |
| 6 | latency on non-brief turns. Only Python standard library modules are imported on |
| 7 | startup; engine modules load lazily when a completed brief is detected. |
| 8 | """ |
| 9 | |
| 10 | from __future__ import annotations |
| 11 | |
| 12 | import json |
| 13 | import os |
| 14 | import sys |
| 15 | from datetime import date, datetime |
| 16 | from pathlib import Path |
| 17 | |
| 18 | |
| 19 | _MAX_STDIN_BYTES = 4 * 1024 * 1024 |
| 20 | _MAX_TRANSCRIPT_TAIL_BYTES = 256 * 1024 |
| 21 | _MAX_JSON_TRANSCRIPT_BYTES = 4 * 1024 * 1024 |
| 22 | |
| 23 | _DISABLED_VALUES = frozenset({"0", "false", "no", "off"}) |
| 24 | _ABORTED_STATUSES = frozenset({"aborted", "error", "cancelled", "canceled"}) |
| 25 | _ABORTED_TERMINATION_REASONS = frozenset( |
| 26 | { |
| 27 | "USER_CANCELED", |
| 28 | "ERROR", |
| 29 | "MAX_INVOCATIONS", |
| 30 | "MAX_FORCED_INVOCATIONS", |
| 31 | "MAX_TOKEN_BUDGET_EXCEEDED", |
| 32 | } |
| 33 | ) |
| 34 | |
| 35 | |
| 36 | def _debug_enabled() -> bool: |
| 37 | return os.environ.get("LAST30DAYS_HOOK_DEBUG", "").strip().lower() in { |
| 38 | "1", |
| 39 | "true", |
| 40 | "yes", |
| 41 | "on", |
| 42 | } |
| 43 | |
| 44 | |
| 45 | def _debug_log(message: str) -> None: |
| 46 | if _debug_enabled(): |
| 47 | sys.stderr.write(f"[capture_brief_hook] {message}\n") |
| 48 | |
| 49 | |
| 50 | def _auto_capture_disabled() -> bool: |
| 51 | return os.environ.get("LAST30DAYS_AUTO_CAPTURE", "").strip().lower() in _DISABLED_VALUES |
| 52 | |
| 53 | |
| 54 | def _read_stdin_payload() -> dict[str, object] | None: |
| 55 | raw = sys.stdin.read(_MAX_STDIN_BYTES + 1) |
| 56 | if not raw or len(raw) > _MAX_STDIN_BYTES: |
| 57 | return None |
| 58 | data = json.loads(raw) |
| 59 | return data if isinstance(data, dict) else None |
| 60 | |
| 61 | |
| 62 | def _should_skip_payload(payload: dict[str, object]) -> bool: |
| 63 | if payload.get("stop_hook_active") is True: |
| 64 | return True |
| 65 | if payload.get("continuationActive") is True: |
| 66 | return True |
| 67 | status = str(payload.get("status") or "").strip().lower() |
| 68 | if status in _ABORTED_STATUSES: |
| 69 | return True |
| 70 | reason = str(payload.get("terminationReason") or "").strip().upper() |
| 71 | if reason in _ABORTED_TERMINATION_REASONS: |
| 72 | return True |
| 73 | return False |
| 74 | |
| 75 | |
| 76 | def _extract_inline_text(payload: dict[str, object]) -> str: |
| 77 | for key in ("last_assistant_message", "prompt_response", "text"): |
| 78 | value = payload.get(key) |
| 79 | if isinstance(value, str) and value.strip(): |
| 80 | return value |
| 81 | return "" |
| 82 | |
| 83 | |
| 84 | def _resolve_transcript_path(payload: dict[str, object]) -> Path | None: |
| 85 | raw_path = payload.get("transcript_path") or payload.get("transcriptPath") |
| 86 | if not isinstance(raw_path, str) or not raw_path.strip(): |
| 87 | return None |
| 88 | path = Path(raw_path).expanduser() |
| 89 | # Antigravity compact transcripts truncate fields >4 KB; prefer sibling full log. |
| 90 | if path.name == "transcript.jsonl": |
| 91 | full_sibling = path.with_name("transcript_full.jsonl") |
| 92 | if full_sibling.is_file(): |
| 93 | return full_sibling |
| 94 | return path if path.is_file() else None |
| 95 | |
| 96 | |
| 97 | def _read_tail_text(path: Path, max_bytes: int) -> str: |
| 98 | size = path.stat().st_size |
| 99 | with path.open("rb") as handle: |
| 100 | if size > max_bytes: |
| 101 | handle.seek(size - max_bytes) |
| 102 | handle.readline() # discard partial leading line |
| 103 | chunk = handle.read(max_bytes) |
| 104 | return chunk.decode("utf-8", errors="replace") |
| 105 | |
| 106 | |
| 107 | def _assistant_text_from_jsonl_record(record: dict[str, object]) -> str: |
| 108 | record_type = record.get("type") |
| 109 | |
| 110 | # Antigravity transcript.jsonl / transcript_full.jsonl |
| 111 | if record_type == "PLANNER_RESPONSE": |
| 112 | content = record.get("content") |
| 113 | return content if isinstance(content, str) else "" |
| 114 | |
| 115 | # Claude Code transcript JSONL |
| 116 | if record_type == "assistant": |
| 117 | message = record.get("message") |
| 118 | if isinstance(message, dict): |
| 119 | return _flatten_content(message.get("content")) |
| 120 | |
| 121 | # Codex CLI rollout JSONL |
| 122 | if record_type == "response_item": |
| 123 | pl = record.get("payload") |
| 124 | if isinstance(pl, dict) and pl.get("role") == "assistant": |
| 125 | return _flatten_content(pl.get("content")) |
| 126 | if record_type == "event_msg": |
| 127 | pl = record.get("payload") |
| 128 | if isinstance(pl, dict) and pl.get("type") == "agent_message": |
| 129 | msg = pl.get("message") |
| 130 | return msg if isinstance(msg, str) else "" |
| 131 | |
| 132 | # Generic role-based JSONL fallback |
| 133 | if record.get("role") in {"assistant", "model"}: |
| 134 | return _flatten_content(record.get("content") or record.get("text")) |
| 135 | return "" |
| 136 | |
| 137 | |
| 138 | def _flatten_content(content: object) -> str: |
| 139 | if isinstance(content, str): |
| 140 | return content |
| 141 | if isinstance(content, list): |
| 142 | parts: list[str] = [] |
| 143 | for item in content: |
| 144 | if isinstance(item, str): |
| 145 | parts.append(item) |
| 146 | elif isinstance(item, dict): |
| 147 | item_type = item.get("type") |
| 148 | if item_type in {None, "text", "output_text"}: |
| 149 | text = item.get("text") |
| 150 | if isinstance(text, str): |
| 151 | parts.append(text) |
| 152 | return "\n".join(parts) |
| 153 | return "" |
| 154 | |
| 155 | |
| 156 | def _extract_transcript_text(path: Path) -> str: |
| 157 | if path.suffix.lower() == ".json": |
| 158 | if path.stat().st_size > _MAX_JSON_TRANSCRIPT_BYTES: |
| 159 | return "" |
| 160 | data = json.loads(path.read_text(encoding="utf-8", errors="replace")) |
| 161 | messages = data.get("messages") if isinstance(data, dict) else None |
| 162 | if isinstance(messages, list): |
| 163 | for entry in reversed(messages): |
| 164 | if not isinstance(entry, dict): |
| 165 | continue |
| 166 | role = str(entry.get("type") or entry.get("role") or "").lower() |
| 167 | if role in {"gemini", "model", "assistant"}: |
| 168 | text = _flatten_content(entry.get("content") or entry.get("text")) |
| 169 | if text.strip(): |
| 170 | return text |
| 171 | return "" |
| 172 | |
| 173 | tail = _read_tail_text(path, _MAX_TRANSCRIPT_TAIL_BYTES) |
| 174 | for line in reversed(tail.splitlines()): |
| 175 | stripped = line.strip() |
| 176 | if not stripped: |
| 177 | continue |
| 178 | try: |
| 179 | record = json.loads(stripped) |
| 180 | except json.JSONDecodeError: |
| 181 | continue |
| 182 | if not isinstance(record, dict): |
| 183 | continue |
| 184 | text = _assistant_text_from_jsonl_record(record) |
| 185 | if text.strip(): |
| 186 | return text |
| 187 | return "" |
| 188 | |
| 189 | |
| 190 | def _fallback_date_from_payload(payload: dict[str, object]) -> date | None: |
| 191 | raw = payload.get("timestamp") |
| 192 | if not isinstance(raw, str) or len(raw) < 10: |
| 193 | return None |
| 194 | try: |
| 195 | return datetime.strptime(raw[:10], "%Y-%m-%d").date() |
| 196 | except ValueError: |
| 197 | return None |
| 198 | |
| 199 | |
| 200 | def _run_capture() -> None: |
| 201 | if _auto_capture_disabled(): |
| 202 | return |
| 203 | payload = _read_stdin_payload() |
| 204 | if payload is None or _should_skip_payload(payload): |
| 205 | return |
| 206 | |
| 207 | text = _extract_inline_text(payload) |
| 208 | if not text: |
| 209 | transcript = _resolve_transcript_path(payload) |
| 210 | if transcript is not None: |
| 211 | text = _extract_transcript_text(transcript) |
| 212 | |
| 213 | if not text or "All agents reported back!" not in text or "last30days" not in text: |
| 214 | return |
| 215 | |
| 216 | scripts_dir = str(Path(__file__).resolve().parent) |
| 217 | if scripts_dir not in sys.path: |
| 218 | sys.path.insert(0, scripts_dir) |
| 219 | |
| 220 | from lib import brief_capture, env |
| 221 | |
| 222 | if os.environ.get("LAST30DAYS_AUTO_CAPTURE") is None: |
| 223 | file_env, project_env, _ = env._load_config_files(env.ConfigLoadPolicy()) |
| 224 | cfg_val = project_env.get("LAST30DAYS_AUTO_CAPTURE") |
| 225 | if cfg_val is None: |
| 226 | cfg_val = file_env.get("LAST30DAYS_AUTO_CAPTURE") |
| 227 | if isinstance(cfg_val, str) and cfg_val.strip().lower() in _DISABLED_VALUES: |
| 228 | return |
| 229 | |
| 230 | save_dir = env.resolve_memory_dir() |
| 231 | if not save_dir: |
| 232 | return |
| 233 | |
| 234 | brief = brief_capture.extract_finished_brief( |
| 235 | text, |
| 236 | fallback_date=_fallback_date_from_payload(payload), |
| 237 | ) |
| 238 | if brief is None: |
| 239 | return |
| 240 | |
| 241 | outcome = brief_capture.save_finished_brief(brief, save_dir) |
| 242 | if outcome.status == "saved": |
| 243 | try: |
| 244 | from lib import library_index |
| 245 | |
| 246 | save_root = Path(save_dir).expanduser().resolve() |
| 247 | db_path = library_index.saved_report_index_path(save_root) |
| 248 | library_index.index_entry( |
| 249 | outcome.path, |
| 250 | db_path=db_path, |
| 251 | source_format="finished-brief", |
| 252 | ) |
| 253 | except Exception as exc: |
| 254 | _debug_log(f"index_entry skipped ({type(exc).__name__}: {exc})") |
| 255 | |
| 256 | |
| 257 | def main() -> int: |
| 258 | try: |
| 259 | _run_capture() |
| 260 | except Exception as exc: |
| 261 | _debug_log(f"{type(exc).__name__}: {exc}") |
| 262 | sys.stdout.write("{}\n") |
| 263 | sys.stdout.flush() |
| 264 | return 0 |
| 265 | |
| 266 | |
| 267 | if __name__ == "__main__": |
| 268 | raise SystemExit(main()) |
| 269 |