| 1 | """Offline transcript scanner that backfills completed last30days chat briefs.""" |
| 2 | |
| 3 | from __future__ import annotations |
| 4 | |
| 5 | import json |
| 6 | from dataclasses import dataclass |
| 7 | from datetime import date, datetime |
| 8 | from pathlib import Path |
| 9 | from typing import Iterator |
| 10 | |
| 11 | from . import brief_capture |
| 12 | |
| 13 | |
| 14 | HARVEST_SOURCES: tuple[str, ...] = ( |
| 15 | "claude", |
| 16 | "codex", |
| 17 | "antigravity", |
| 18 | "gemini", |
| 19 | "cursor", |
| 20 | ) |
| 21 | VALID_SOURCE_FLAGS: tuple[str, ...] = ("auto", "all", *HARVEST_SOURCES) |
| 22 | _FOOTER_MARKER_BYTES = b"All agents reported back!" |
| 23 | |
| 24 | |
| 25 | @dataclass(frozen=True, slots=True) |
| 26 | class HarvestResult: |
| 27 | """Summary of an offline transcript backfill pass.""" |
| 28 | |
| 29 | scanned_files: int |
| 30 | matched_briefs: int |
| 31 | saved: int |
| 32 | duplicates: int |
| 33 | saved_paths: tuple[Path, ...] |
| 34 | notes: tuple[str, ...] |
| 35 | dry_run: bool |
| 36 | |
| 37 | |
| 38 | def _home_dir(home: Path | str | None) -> Path: |
| 39 | return Path(home).expanduser() if home is not None else Path.home() |
| 40 | |
| 41 | |
| 42 | def _discover_source_files(source: str, home: Path) -> list[Path]: |
| 43 | if source == "claude": |
| 44 | root = home / ".claude" / "projects" |
| 45 | return sorted(root.rglob("*.jsonl")) if root.is_dir() else [] |
| 46 | if source == "codex": |
| 47 | root = home / ".codex" / "sessions" |
| 48 | return sorted(root.rglob("*.jsonl")) if root.is_dir() else [] |
| 49 | if source == "antigravity": |
| 50 | seen_dirs: set[Path] = set() |
| 51 | found: list[Path] = [] |
| 52 | roots = [ |
| 53 | home / ".t3" / "userdata" / "providers" / "antigravity", |
| 54 | home / ".gemini", |
| 55 | ] |
| 56 | for root in roots: |
| 57 | if not root.is_dir(): |
| 58 | continue |
| 59 | for full_log in sorted(root.rglob("transcript_full.jsonl")): |
| 60 | seen_dirs.add(full_log.parent) |
| 61 | found.append(full_log) |
| 62 | for compact_log in sorted(root.rglob("transcript.jsonl")): |
| 63 | if compact_log.parent not in seen_dirs: |
| 64 | found.append(compact_log) |
| 65 | return found |
| 66 | if source == "gemini": |
| 67 | root = home / ".gemini" / "tmp" |
| 68 | return sorted(root.rglob("session-*.json")) if root.is_dir() else [] |
| 69 | if source == "cursor": |
| 70 | root = home / ".cursor" / "transcripts" |
| 71 | return sorted(root.rglob("*.jsonl")) if root.is_dir() else [] |
| 72 | raise ValueError(f"unknown harvest source: {source}") |
| 73 | |
| 74 | |
| 75 | def _file_contains_marker(path: Path) -> bool: |
| 76 | try: |
| 77 | with path.open("rb") as handle: |
| 78 | overlap = b"" |
| 79 | while True: |
| 80 | chunk = handle.read(65536) |
| 81 | if not chunk: |
| 82 | return False |
| 83 | if _FOOTER_MARKER_BYTES in overlap + chunk: |
| 84 | return True |
| 85 | overlap = chunk[-len(_FOOTER_MARKER_BYTES) :] |
| 86 | except OSError: |
| 87 | return False |
| 88 | |
| 89 | |
| 90 | def _flatten_content(content: object) -> str: |
| 91 | if isinstance(content, str): |
| 92 | return content |
| 93 | if isinstance(content, list): |
| 94 | parts: list[str] = [] |
| 95 | for item in content: |
| 96 | if isinstance(item, str): |
| 97 | parts.append(item) |
| 98 | elif isinstance(item, dict) and item.get("type") in {None, "text", "output_text"}: |
| 99 | text = item.get("text") |
| 100 | if isinstance(text, str): |
| 101 | parts.append(text) |
| 102 | return "\n".join(parts) |
| 103 | return "" |
| 104 | |
| 105 | |
| 106 | def _parse_iso_date(value: object) -> date | None: |
| 107 | if not isinstance(value, str) or len(value) < 10: |
| 108 | return None |
| 109 | try: |
| 110 | return datetime.strptime(value[:10], "%Y-%m-%d").date() |
| 111 | except ValueError: |
| 112 | return None |
| 113 | |
| 114 | |
| 115 | def _iter_assistant_texts(source: str, path: Path) -> Iterator[tuple[str, date | None]]: |
| 116 | if path.suffix.lower() == ".json": |
| 117 | data = json.loads(path.read_text(encoding="utf-8", errors="replace")) |
| 118 | messages = data.get("messages") if isinstance(data, dict) else None |
| 119 | if isinstance(messages, list): |
| 120 | for entry in messages: |
| 121 | if not isinstance(entry, dict): |
| 122 | continue |
| 123 | role = str(entry.get("type") or entry.get("role") or "").lower() |
| 124 | if role in {"gemini", "model", "assistant"}: |
| 125 | text = _flatten_content(entry.get("content") or entry.get("text")) |
| 126 | if text: |
| 127 | yield text, _parse_iso_date(entry.get("timestamp")) |
| 128 | return |
| 129 | |
| 130 | with path.open("r", encoding="utf-8", errors="replace") as handle: |
| 131 | for line in handle: |
| 132 | if "All agents reported back!" not in line: |
| 133 | continue |
| 134 | try: |
| 135 | record = json.loads(line) |
| 136 | except json.JSONDecodeError: |
| 137 | continue |
| 138 | if not isinstance(record, dict): |
| 139 | continue |
| 140 | |
| 141 | fallback = _parse_iso_date(record.get("timestamp") or record.get("created_at")) |
| 142 | rec_type = record.get("type") |
| 143 | text = "" |
| 144 | if source == "claude" and rec_type == "assistant": |
| 145 | msg = record.get("message") |
| 146 | if isinstance(msg, dict): |
| 147 | text = _flatten_content(msg.get("content")) |
| 148 | elif source == "codex": |
| 149 | pl = record.get("payload") |
| 150 | if rec_type == "response_item" and isinstance(pl, dict) and pl.get("role") == "assistant": |
| 151 | text = _flatten_content(pl.get("content")) |
| 152 | elif rec_type == "event_msg" and isinstance(pl, dict) and pl.get("type") == "agent_message": |
| 153 | msg_text = pl.get("message") |
| 154 | text = msg_text if isinstance(msg_text, str) else "" |
| 155 | elif source == "antigravity" and rec_type == "PLANNER_RESPONSE": |
| 156 | content = record.get("content") |
| 157 | text = content if isinstance(content, str) else "" |
| 158 | elif record.get("role") in {"assistant", "model"}: |
| 159 | text = _flatten_content(record.get("content") or record.get("text")) |
| 160 | |
| 161 | if text: |
| 162 | yield text, fallback |
| 163 | |
| 164 | |
| 165 | def _existing_hashes_for(save_dir: Path, slug: str, published_date: date) -> set[str]: |
| 166 | finished_dir = save_dir / brief_capture.FINISHED_SUBDIR |
| 167 | if not finished_dir.is_dir(): |
| 168 | return set() |
| 169 | prefix = f"{slug}-{published_date.isoformat()}" |
| 170 | hashes: set[str] = set() |
| 171 | for path in finished_dir.glob(f"{prefix}*.md"): |
| 172 | try: |
| 173 | hashes.add(brief_capture.content_hash(path.read_text(encoding="utf-8"))) |
| 174 | except (OSError, UnicodeDecodeError): |
| 175 | continue |
| 176 | return hashes |
| 177 | |
| 178 | |
| 179 | def harvest_transcripts( |
| 180 | *, |
| 181 | save_dir: Path | str, |
| 182 | source: str = "auto", |
| 183 | since: date | None = None, |
| 184 | dry_run: bool = False, |
| 185 | home: Path | str | None = None, |
| 186 | ) -> HarvestResult: |
| 187 | """Scan local harness transcripts offline and archive finished briefs.""" |
| 188 | normalized = source.strip().lower() or "auto" |
| 189 | if normalized not in VALID_SOURCE_FLAGS: |
| 190 | raise ValueError( |
| 191 | f"unsupported --source '{source}'; expected one of {', '.join(VALID_SOURCE_FLAGS)}" |
| 192 | ) |
| 193 | |
| 194 | selected_sources = HARVEST_SOURCES if normalized in {"auto", "all"} else (normalized,) |
| 195 | base_home = _home_dir(home) |
| 196 | target_dir = Path(save_dir).expanduser() |
| 197 | |
| 198 | scanned_files = 0 |
| 199 | matched_briefs = 0 |
| 200 | saved = 0 |
| 201 | duplicates = 0 |
| 202 | saved_paths: list[Path] = [] |
| 203 | notes: list[str] = [] |
| 204 | dry_run_seen_hashes: set[str] = set() |
| 205 | |
| 206 | for src in selected_sources: |
| 207 | files = _discover_source_files(src, base_home) |
| 208 | for path in files: |
| 209 | scanned_files += 1 |
| 210 | try: |
| 211 | mtime_date = datetime.fromtimestamp(path.stat().st_mtime).date() |
| 212 | except OSError as exc: |
| 213 | notes.append(f"Skipped {path}: {exc}") |
| 214 | continue |
| 215 | if since is not None and mtime_date < since: |
| 216 | continue |
| 217 | if not _file_contains_marker(path): |
| 218 | continue |
| 219 | |
| 220 | try: |
| 221 | candidates = list(_iter_assistant_texts(src, path)) |
| 222 | except (OSError, ValueError, json.JSONDecodeError) as exc: |
| 223 | notes.append(f"Skipped {path}: {exc}") |
| 224 | continue |
| 225 | |
| 226 | for text, fallback_date in candidates: |
| 227 | brief = brief_capture.extract_finished_brief( |
| 228 | text, |
| 229 | fallback_date=fallback_date or mtime_date, |
| 230 | ) |
| 231 | if brief is None: |
| 232 | continue |
| 233 | if since is not None and brief.published_date < since: |
| 234 | continue |
| 235 | matched_briefs += 1 |
| 236 | if dry_run: |
| 237 | existing_hashes = _existing_hashes_for( |
| 238 | target_dir, brief.slug, brief.published_date |
| 239 | ) |
| 240 | if ( |
| 241 | brief.content_hash in existing_hashes |
| 242 | or brief.content_hash in dry_run_seen_hashes |
| 243 | ): |
| 244 | duplicates += 1 |
| 245 | else: |
| 246 | dry_run_seen_hashes.add(brief.content_hash) |
| 247 | saved += 1 |
| 248 | else: |
| 249 | outcome = brief_capture.save_finished_brief(brief, target_dir) |
| 250 | if outcome.status == "saved": |
| 251 | saved += 1 |
| 252 | saved_paths.append(outcome.path) |
| 253 | else: |
| 254 | duplicates += 1 |
| 255 | |
| 256 | return HarvestResult( |
| 257 | scanned_files=scanned_files, |
| 258 | matched_briefs=matched_briefs, |
| 259 | saved=saved, |
| 260 | duplicates=duplicates, |
| 261 | saved_paths=tuple(saved_paths), |
| 262 | notes=tuple(notes), |
| 263 | dry_run=dry_run, |
| 264 | ) |
| 265 |