| 1 | """Detect, normalize, and atomically persist finished last30days chat briefs.""" |
| 2 | |
| 3 | from __future__ import annotations |
| 4 | |
| 5 | import contextlib |
| 6 | import errno |
| 7 | import hashlib |
| 8 | import os |
| 9 | import re |
| 10 | import tempfile |
| 11 | from dataclasses import dataclass |
| 12 | from datetime import date, datetime |
| 13 | from pathlib import Path |
| 14 | from typing import Iterator |
| 15 | |
| 16 | from . import html_render, library |
| 17 | |
| 18 | |
| 19 | FINISHED_SUBDIR = "finished" |
| 20 | _LOCK_FILENAME = ".capture.lock" |
| 21 | |
| 22 | _BADGE_LINE = library._BADGE_LINE |
| 23 | _RAW_DUMP_MARKERS = ( |
| 24 | "<!-- EVIDENCE FOR SYNTHESIS", |
| 25 | "# END OF last30days CANONICAL OUTPUT", |
| 26 | ) |
| 27 | _SYNCED_DATE = library._BADGE_SYNCED_DATE |
| 28 | _VERSION_TOKEN = re.compile(r"\bv(\d+\.\d+(?:\.\d+)*(?:[-+][A-Za-z0-9._-]+)?)\b") |
| 29 | _FIRST_HEADING = re.compile(r"^#{1,2}\s+(.+?)\s*$", re.MULTILINE) |
| 30 | _RAW_SAVED_PATH = re.compile(r"Raw results saved to\s+([^\r\n]+?\.md)\s*$", re.MULTILINE) |
| 31 | _RAW_STEM_PREFIX = re.compile(r"^(.+?)-raw(?:-[^\r\n]+)?$") |
| 32 | _TOPIC_META_COMMENT = library._TOPIC_META_COMMENT |
| 33 | |
| 34 | |
| 35 | @dataclass(frozen=True, slots=True) |
| 36 | class CapturedBrief: |
| 37 | """Normalized finished brief ready to persist to the local research library.""" |
| 38 | |
| 39 | topic: str |
| 40 | slug: str |
| 41 | published_date: date |
| 42 | version: str |
| 43 | content: str |
| 44 | content_hash: str |
| 45 | is_private: bool |
| 46 | |
| 47 | |
| 48 | @dataclass(frozen=True, slots=True) |
| 49 | class SaveResult: |
| 50 | """Outcome of persisting a captured finished brief.""" |
| 51 | |
| 52 | status: str # "saved" | "duplicate" |
| 53 | path: Path |
| 54 | brief: CapturedBrief |
| 55 | |
| 56 | |
| 57 | def has_private_corpus(markdown: str) -> bool: |
| 58 | """Return whether a brief contains local-corpus content or citations.""" |
| 59 | return library.has_private_corpus(markdown) |
| 60 | |
| 61 | |
| 62 | def normalize_brief_text(content: str) -> str: |
| 63 | """Normalize line endings and trailing whitespace for stable hashing and storage.""" |
| 64 | normalized = content.replace("\r\n", "\n").replace("\r", "\n").strip() |
| 65 | return normalized + "\n" |
| 66 | |
| 67 | |
| 68 | def content_hash(content: str) -> str: |
| 69 | """Return SHA-256 hex digest of normalized brief content.""" |
| 70 | return hashlib.sha256(normalize_brief_text(content).encode("utf-8")).hexdigest() |
| 71 | |
| 72 | |
| 73 | def _topic_from_raw_footer(body: str) -> tuple[str, str]: |
| 74 | """Recover full untruncated (topic, slug) from the footer's saved raw path if available.""" |
| 75 | match = _RAW_SAVED_PATH.search(body) |
| 76 | if match is None: |
| 77 | return "", "" |
| 78 | raw_str = match.group(1).strip().strip("`\"'") |
| 79 | if not raw_str: |
| 80 | return "", "" |
| 81 | raw_path = Path(raw_str).expanduser() |
| 82 | # Read only the header of an existing local raw report to recover exact topic text. |
| 83 | try: |
| 84 | if raw_path.is_file(): |
| 85 | with raw_path.open("r", encoding="utf-8", errors="replace") as handle: |
| 86 | head = handle.read(1024) |
| 87 | title = library._REPORT_TITLE.search(head) |
| 88 | if title: |
| 89 | full_topic = library._clean_inline(title.group(1)) |
| 90 | if full_topic: |
| 91 | return full_topic, library.slugify(full_topic) |
| 92 | except OSError: |
| 93 | pass |
| 94 | # Fallback when the raw file is gone: recover full slug from its filename stem. |
| 95 | stem_match = _RAW_STEM_PREFIX.match(raw_path.stem) |
| 96 | if stem_match: |
| 97 | recovered_slug = library.slugify(stem_match.group(1)) |
| 98 | if recovered_slug: |
| 99 | return "", recovered_slug |
| 100 | return "", "" |
| 101 | |
| 102 | |
| 103 | def _looks_truncated_topic(topic: str) -> bool: |
| 104 | stripped = topic.strip() |
| 105 | return stripped.endswith("...") or stripped.endswith("…") |
| 106 | |
| 107 | |
| 108 | def _inject_topic_comment(content: str, badge_line: str, full_topic: str) -> str: |
| 109 | if _TOPIC_META_COMMENT.search(content): |
| 110 | return content |
| 111 | safe_topic = full_topic.replace("-->", "- - >").replace("\n", " ").strip() |
| 112 | if not safe_topic: |
| 113 | return content |
| 114 | marker = f"<!-- last30days-topic: {safe_topic} -->" |
| 115 | if content.startswith(badge_line + "\n"): |
| 116 | return badge_line + "\n" + marker + "\n" + content[len(badge_line) + 1 :] |
| 117 | return marker + "\n" + content |
| 118 | |
| 119 | |
| 120 | def parse_badge_metadata( |
| 121 | badge_line: str, |
| 122 | body: str, |
| 123 | *, |
| 124 | fallback_date: date | None = None, |
| 125 | ) -> tuple[str, str, date, str]: |
| 126 | """Extract (topic, slug, published_date, version) from a brief badge and body.""" |
| 127 | version_match = _VERSION_TOKEN.search(badge_line) |
| 128 | version = version_match.group(1) if version_match else "" |
| 129 | |
| 130 | parts = [part.strip() for part in badge_line.split("·") if part.strip()] |
| 131 | badge_topic = "" |
| 132 | published: date | None = None |
| 133 | |
| 134 | if synced := _SYNCED_DATE.search(badge_line): |
| 135 | published = _safe_iso_date(synced.group(1)) |
| 136 | else: |
| 137 | for segment in parts[1:]: |
| 138 | if published is None: |
| 139 | parsed = _parse_date_segment(segment) |
| 140 | if parsed is not None: |
| 141 | published = parsed |
| 142 | continue |
| 143 | if not badge_topic and not _is_meta_segment(segment): |
| 144 | badge_topic = segment |
| 145 | |
| 146 | raw_topic, raw_slug = _topic_from_raw_footer(body) |
| 147 | |
| 148 | if raw_topic: |
| 149 | topic = raw_topic |
| 150 | slug = raw_slug or library.slugify(topic) |
| 151 | elif badge_topic and not _looks_truncated_topic(badge_topic): |
| 152 | topic = badge_topic |
| 153 | slug = library.slugify(topic) |
| 154 | elif badge_topic and _looks_truncated_topic(badge_topic): |
| 155 | topic = badge_topic |
| 156 | slug = raw_slug or library.slugify(topic) |
| 157 | else: |
| 158 | topic = _topic_from_body(body) or "last30days" |
| 159 | slug = raw_slug or library.slugify(topic) |
| 160 | |
| 161 | if published is None: |
| 162 | published = _parse_date_segment(body) or fallback_date or date.today() |
| 163 | |
| 164 | return topic, slug, published, version |
| 165 | |
| 166 | |
| 167 | def extract_finished_brief( |
| 168 | text: str, |
| 169 | *, |
| 170 | fallback_date: date | None = None, |
| 171 | ) -> CapturedBrief | None: |
| 172 | """Extract a completed last30days brief from an assistant response, or None.""" |
| 173 | if not text or "All agents reported back!" not in text or "last30days" not in text: |
| 174 | return None |
| 175 | if any(marker in text for marker in _RAW_DUMP_MARKERS): |
| 176 | return None |
| 177 | |
| 178 | normalized = text.replace("\r\n", "\n").replace("\r", "\n") |
| 179 | badge_match = _BADGE_LINE.search(normalized) |
| 180 | if badge_match is None: |
| 181 | return None |
| 182 | |
| 183 | footer_match = html_render.FENCED_ENGINE_FOOTER_PATTERN.search( |
| 184 | normalized, pos=badge_match.end() |
| 185 | ) |
| 186 | if footer_match is None: |
| 187 | return None |
| 188 | |
| 189 | slice_text = normalized[badge_match.start() : footer_match.end()] |
| 190 | slice_text = html_render.INVITATION_PATTERN.sub("", slice_text) |
| 191 | final_content = normalize_brief_text(slice_text) |
| 192 | |
| 193 | badge_line = badge_match.group(0).strip() |
| 194 | body_after_badge = final_content[len(badge_line) :] |
| 195 | topic, slug, published, version = parse_badge_metadata( |
| 196 | badge_line, |
| 197 | body_after_badge, |
| 198 | fallback_date=fallback_date, |
| 199 | ) |
| 200 | |
| 201 | # Carry the complete topic in an HTML comment whenever the badge truncated |
| 202 | # or omitted it, so library scanning and raw-report supersession match the |
| 203 | # full query identity instead of a 60-char prefix. |
| 204 | badge_topic_only, _ = library._parse_badge_line(badge_line) |
| 205 | if topic and topic != badge_topic_only: |
| 206 | final_content = normalize_brief_text( |
| 207 | _inject_topic_comment(final_content, badge_line, topic) |
| 208 | ) |
| 209 | |
| 210 | return CapturedBrief( |
| 211 | topic=topic, |
| 212 | slug=slug, |
| 213 | published_date=published, |
| 214 | version=version, |
| 215 | content=final_content, |
| 216 | content_hash=content_hash(final_content), |
| 217 | is_private=has_private_corpus(final_content), |
| 218 | ) |
| 219 | |
| 220 | |
| 221 | @contextlib.contextmanager |
| 222 | def _finished_dir_lock(finished_dir: Path) -> Iterator[None]: |
| 223 | """Serialize duplicate checks and exclusive filename allocation across processes.""" |
| 224 | lock_path = finished_dir / _LOCK_FILENAME |
| 225 | fd = os.open(lock_path, os.O_CREAT | os.O_RDWR, 0o600) |
| 226 | try: |
| 227 | if os.name == "posix": |
| 228 | import fcntl |
| 229 | |
| 230 | fcntl.flock(fd, fcntl.LOCK_EX) |
| 231 | else: |
| 232 | import msvcrt |
| 233 | |
| 234 | msvcrt.locking(fd, msvcrt.LK_LOCK, 1) |
| 235 | try: |
| 236 | yield |
| 237 | finally: |
| 238 | if os.name == "posix": |
| 239 | import fcntl |
| 240 | |
| 241 | fcntl.flock(fd, fcntl.LOCK_UN) |
| 242 | else: |
| 243 | import msvcrt |
| 244 | |
| 245 | msvcrt.locking(fd, msvcrt.LK_UNLCK, 1) |
| 246 | finally: |
| 247 | os.close(fd) |
| 248 | |
| 249 | |
| 250 | def save_finished_brief(brief: CapturedBrief, save_dir: Path | str) -> SaveResult: |
| 251 | """Exclusively write a finished brief into <save_dir>/finished/, deduping by hash.""" |
| 252 | base_dir = Path(save_dir).expanduser() |
| 253 | finished_dir = base_dir / FINISHED_SUBDIR |
| 254 | _ensure_finished_dir(finished_dir, private=brief.is_private) |
| 255 | |
| 256 | stem_prefix = f"{library.filename_slug(brief.slug)}-{brief.published_date.isoformat()}" |
| 257 | candidates = [finished_dir / f"{stem_prefix}.md"] |
| 258 | candidates.extend(finished_dir / f"{stem_prefix}-{idx}.md" for idx in range(2, 100)) |
| 259 | # Briefs saved before filenames were shortened kept the full slug. Check |
| 260 | # those names too so re-saving one is still reported as a duplicate. |
| 261 | legacy_prefix = f"{brief.slug}-{brief.published_date.isoformat()}" |
| 262 | legacy = [] |
| 263 | if legacy_prefix != stem_prefix: |
| 264 | legacy = [finished_dir / f"{legacy_prefix}.md"] |
| 265 | legacy.extend(finished_dir / f"{legacy_prefix}-{idx}.md" for idx in range(2, 100)) |
| 266 | |
| 267 | with _finished_dir_lock(finished_dir): |
| 268 | for existing in [*legacy, *candidates]: |
| 269 | try: |
| 270 | if not existing.exists(): |
| 271 | continue |
| 272 | except OSError: |
| 273 | continue |
| 274 | try: |
| 275 | existing_text = existing.read_text(encoding="utf-8") |
| 276 | except (OSError, UnicodeDecodeError): |
| 277 | continue |
| 278 | if content_hash(existing_text) == brief.content_hash: |
| 279 | return SaveResult(status="duplicate", path=existing, brief=brief) |
| 280 | |
| 281 | for candidate in candidates: |
| 282 | if _write_exclusive(candidate, brief.content, private=brief.is_private): |
| 283 | return SaveResult(status="saved", path=candidate, brief=brief) |
| 284 | |
| 285 | raise RuntimeError( |
| 286 | f"save_finished_brief: could not allocate unique filename for {stem_prefix} in {finished_dir}" |
| 287 | ) |
| 288 | |
| 289 | |
| 290 | def _ensure_finished_dir(path: Path, *, private: bool) -> None: |
| 291 | path.mkdir(parents=True, exist_ok=True) |
| 292 | if private and os.name == "posix": |
| 293 | path.chmod(0o700) |
| 294 | |
| 295 | |
| 296 | def _write_exclusive(path: Path, content: str, *, private: bool) -> bool: |
| 297 | """Write full content to a hidden temp file, then link to ``path`` without overwriting. |
| 298 | |
| 299 | Readers scanning ``*.md`` never observe a partial file, and concurrent |
| 300 | writers cannot clobber an existing ``path`` because ``os.link`` fails with |
| 301 | ``FileExistsError`` if the target already exists. |
| 302 | """ |
| 303 | mode = 0o600 if private else 0o644 |
| 304 | staged_fd, staged_name = tempfile.mkstemp( |
| 305 | dir=path.parent, |
| 306 | prefix=f".{path.name}.", |
| 307 | suffix=".tmp", |
| 308 | ) |
| 309 | staged_path = Path(staged_name) |
| 310 | try: |
| 311 | if os.name == "posix": |
| 312 | os.fchmod(staged_fd, mode) |
| 313 | with os.fdopen(staged_fd, "wb") as handle: |
| 314 | handle.write(content.encode("utf-8")) |
| 315 | handle.flush() |
| 316 | try: |
| 317 | os.link(staged_path, path) |
| 318 | return True |
| 319 | except FileExistsError: |
| 320 | return False |
| 321 | except OSError as exc: |
| 322 | # Filesystems without hard-link support (e.g. some FUSE/FAT mounts): |
| 323 | # caller already holds _finished_dir_lock, so re-check before rename. |
| 324 | if exc.errno not in { |
| 325 | errno.EPERM, |
| 326 | errno.ENOTSUP, |
| 327 | errno.EOPNOTSUPP, |
| 328 | errno.EXDEV, |
| 329 | errno.EINVAL, |
| 330 | }: |
| 331 | raise |
| 332 | if path.exists(): |
| 333 | return False |
| 334 | os.replace(staged_path, path) |
| 335 | return True |
| 336 | finally: |
| 337 | staged_path.unlink(missing_ok=True) |
| 338 | |
| 339 | |
| 340 | def _is_meta_segment(segment: str) -> bool: |
| 341 | lowered = segment.lower() |
| 342 | if _VERSION_TOKEN.fullmatch(segment): |
| 343 | return True |
| 344 | if lowered in {"quick", "default", "deep", "cached"}: |
| 345 | return True |
| 346 | return _SYNCED_DATE.search(segment) is not None |
| 347 | |
| 348 | |
| 349 | def _topic_from_body(body: str) -> str: |
| 350 | for match in _FIRST_HEADING.finditer(body): |
| 351 | raw_heading = library._COMPARISON_TITLE_SUFFIX.sub("", match.group(1)) |
| 352 | heading = library._clean_inline(raw_heading) |
| 353 | lowered = heading.lower() |
| 354 | if not heading or lowered in {"what i learned", "key patterns", "from your files"}: |
| 355 | continue |
| 356 | if lowered.startswith("what i learned about "): |
| 357 | return heading[len("what i learned about ") :].strip() |
| 358 | return heading |
| 359 | return "" |
| 360 | |
| 361 | |
| 362 | def _parse_date_segment(text: str) -> date | None: |
| 363 | return library._parse_badge_date(text) |
| 364 | |
| 365 | |
| 366 | def _safe_iso_date(value: str) -> date | None: |
| 367 | try: |
| 368 | return datetime.strptime(value, "%Y-%m-%d").date() |
| 369 | except ValueError: |
| 370 | return None |
| 371 |