#!/usr/bin/env python3 """Export Antigravity conversations to clean Markdown files and optionally push to Git.""" from __future__ import annotations import argparse import json import re import shutil import sqlite3 import subprocess from dataclasses import dataclass from datetime import datetime from pathlib import Path from typing import Any ANTIGRAVITY_DIR = Path.home() / ".gemini" / "antigravity" BRAIN_DIR = ANTIGRAVITY_DIR / "brain" SUMMARIES_DB = ANTIGRAVITY_DIR / "conversation_summaries.db" REPO_DIR = Path(__file__).resolve().parent USER_REQUEST_RE = re.compile(r"\s*(.*?)\s*", re.DOTALL) @dataclass class ConversationMeta: """Metadata loaded from conversation_summaries.db.""" conversation_id: str title: str last_modified_time: str workspace_uris: str parent_conversation_id: str def slugify(text: str, max_len: int = 50) -> str: """Create a filesystem-safe lowercase slug from a title.""" slug = re.sub(r"[^\w\s-]", "", text.lower(), flags=re.UNICODE) slug = re.sub(r"[-\s]+", "-", slug).strip("-_") return (slug[:max_len].rstrip("-_")) or "conversation" def load_summaries(db_path: Path) -> dict[str, ConversationMeta]: """Read conversation metadata from SQLite in read-only mode.""" if not db_path.exists(): return {} uri = f"file:{db_path}?mode=ro" conn = sqlite3.connect(uri, uri=True, timeout=5.0) try: rows = conn.execute( """ SELECT conversation_id, title, last_modified_time, workspace_uris, parent_conversation_id FROM conversation_summaries """ ).fetchall() finally: conn.close() return { row[0]: ConversationMeta( conversation_id=row[0], title=row[1] or "", last_modified_time=row[2] or "", workspace_uris=row[3] or "", parent_conversation_id=row[4] or "", ) for row in rows } def extract_user_text(raw: str) -> str: """Strip Antigravity XML wrappers from user input when present.""" match = USER_REQUEST_RE.search(raw) if match: return match.group(1).strip() return raw.strip() def format_timestamp(iso_str: str) -> str: """Format an ISO timestamp as YYYY-MM-DD HH:MM.""" if not iso_str: return "" try: dt = datetime.fromisoformat(iso_str.replace("Z", "+00:00")) return dt.strftime("%Y-%m-%d %H:%M") except ValueError: return iso_str[:16] def parse_transcript(transcript_path: Path) -> list[dict[str, str]]: """Extract user and assistant messages from transcript.jsonl.""" messages: list[dict[str, str]] = [] with transcript_path.open("r", encoding="utf-8", errors="replace") as handle: for line in handle: line = line.strip() if not line: continue try: entry: dict[str, Any] = json.loads(line) except json.JSONDecodeError: continue entry_type = entry.get("type", "") content = (entry.get("content") or "").strip() created_at = format_timestamp(entry.get("created_at", "")) if entry_type == "USER_INPUT" and content: text = extract_user_text(content) if text: messages.append({"role": "Utilisateur", "time": created_at, "text": text}) elif entry_type == "PLANNER_RESPONSE" and content: messages.append({"role": "Assistant", "time": created_at, "text": content}) return messages def copy_artifacts(conv_dir: Path, out_artifacts_dir: Path) -> list[str]: """Copy top-level Markdown artifacts for a conversation.""" md_files = sorted(p for p in conv_dir.glob("*.md") if p.is_file()) if not md_files: return [] out_artifacts_dir.mkdir(parents=True, exist_ok=True) copied: list[str] = [] for src in md_files: shutil.copy2(src, out_artifacts_dir / src.name) copied.append(src.name) return copied def export_all(include_subagents: bool = False) -> tuple[int, Path]: """Export all conversations and return (count, index_path).""" summaries = load_summaries(SUMMARIES_DB) convs_out = REPO_DIR / "conversations" artifacts_out = REPO_DIR / "artifacts" convs_out.mkdir(parents=True, exist_ok=True) index_entries: list[tuple[str, str, str, str, int]] = [] if not BRAIN_DIR.exists(): raise FileNotFoundError(f"Dossier introuvable : {BRAIN_DIR}") for conv_dir in sorted(BRAIN_DIR.iterdir()): if not conv_dir.is_dir(): continue conv_id = conv_dir.name meta = summaries.get(conv_id) if not include_subagents and meta and meta.parent_conversation_id: continue transcript_path = conv_dir / ".system_generated" / "logs" / "transcript.jsonl" if not transcript_path.exists(): continue messages = parse_transcript(transcript_path) if not messages: continue title = (meta.title if meta and meta.title else "").strip() if not title: first_user = next((m["text"] for m in messages if m["role"] == "Utilisateur"), "Sans titre") title = first_user.splitlines()[0][:80] date_str = "" if meta and meta.last_modified_time: date_str = meta.last_modified_time[:10] if not date_str: date_str = datetime.fromtimestamp(transcript_path.stat().st_mtime).strftime("%Y-%m-%d") short_id = conv_id.split("-")[0] filename = f"{date_str}_{slugify(title)}_{short_id}.md" target_file = convs_out / filename artifact_names = copy_artifacts(conv_dir, artifacts_out / short_id) lines = [ f"# {title}", "", f"- **ID** : `{conv_id}`", f"- **Date** : {date_str}", ] if meta and meta.workspace_uris and meta.workspace_uris != "[]": lines.append(f"- **Workspace** : `{meta.workspace_uris}`") if artifact_names: links = ", ".join(f"[{name}](../artifacts/{short_id}/{name})" for name in artifact_names) lines.append(f"- **Artefacts** : {links}") lines.extend(["", "---", ""]) for msg in messages: ts = f" *({msg['time']})*" if msg["time"] else "" lines.append(f"### {msg['role']}{ts}") lines.append("") lines.append(msg["text"]) lines.append("") lines.append("---") lines.append("") target_file.write_text("\n".join(lines), encoding="utf-8") index_entries.append((date_str, title, filename, short_id, len(messages))) index_entries.sort(key=lambda item: (item[0], item[2]), reverse=True) index_lines = [ "# Historique des conversations Antigravity", "", f"Total : **{len(index_entries)}** conversations exportées.", "", "| Date | Titre | Messages |", "| :--- | :--- | :---: |", ] for date_str, title, filename, _, msg_count in index_entries: safe_title = title.replace("|", "\\|") index_lines.append(f"| {date_str} | [{safe_title}](conversations/{filename}) | {msg_count} |") index_path = REPO_DIR / "INDEX.md" index_path.write_text("\n".join(index_lines) + "\n", encoding="utf-8") return len(index_entries), index_path def git_push() -> bool: """Commit and push changes if any exist. Returns True if a commit was pushed.""" subprocess.run(["git", "add", "-A"], cwd=REPO_DIR, check=True) status = subprocess.run( ["git", "status", "--porcelain"], cwd=REPO_DIR, check=True, capture_output=True, text=True, ) if not status.stdout.strip(): return False stamp = datetime.now().strftime("%Y-%m-%d %H:%M") subprocess.run( ["git", "commit", "-m", f"Sauvegarde conversations Antigravity ({stamp})"], cwd=REPO_DIR, check=True, ) subprocess.run(["git", "push", "-u", "origin", "HEAD"], cwd=REPO_DIR, check=True) return True def main() -> None: parser = argparse.ArgumentParser(description="Exporte les conversations Antigravity en Markdown.") parser.add_argument("--push", action="store_true", help="Commit et push automatiquement vers origin.") parser.add_argument( "--include-subagents", action="store_true", help="Inclure aussi les conversations internes des sous-agents.", ) args = parser.parse_args() count, index_path = export_all(include_subagents=args.include_subagents) print(f"Export terminé : {count} conversations -> {index_path}") if args.push: pushed = git_push() print("Push Gitea effectué." if pushed else "Aucun changement à pousser.") if __name__ == "__main__": main()