Replay your coding agent sessions as a map and a timeline
Python agent-observabilityai-agentsclaudeclaude-codecodexcoding-agentscursordeveloper-toolsdevtoolsgithub-copilotkirollmobservabilityopencodeprivacypythonsession-replaytypescriptvisualization
feat: add Gemini CLI parser (closes #21)
shubhook7ee2e3863e65
diff --git a/README.md b/README.mdindex 8528c9f..c31d0e1 100644--- a/README.md+++ b/README.md@@ -9,7 +9,7 @@<a href="https://github.com/Entelligence-AI/agentplay/stargazers"><img alt="GitHub stars" src="https://img.shields.io/github/stars/Entelligence-AI/agentplay?style=social"></a></p>-**See what your coding agent actually did. Replay every session as a map and a timeline: what it read, what it edited, what failed, and what it shipped. Local, open source, works across Claude Code, Codex, Cursor, Copilot, OpenCode and Kiro.**+**See what your coding agent actually did. Replay every session as a map and a timeline: what it read, what it edited, what failed, and what it shipped. Local, open source, works across Claude Code, Codex, Cursor, Copilot, OpenCode, Kiro and Gemini CLI.**```bashuvx agentplay@@ -140,6 +140,7 @@ Every view is a URL, so a link to a moment in a session reopens it for anyone wh| **GitHub Copilot in VS Code** | VS Code `User/workspaceStorage/*/chatSessions` | main lane only | per turn, where recorded | Code, Code Insiders, VSCodium || **OpenCode** | `~/.local/share/opencode/opencode.db` | main lane only | per turn | SQLite, decoded locally || **Kiro** | `~/.kiro/sessions/*/*` | main lane only | per turn, where recorded | Sub-executions merged into the session |+| **Gemini CLI** | `~/.gemini/tmp/*/chats/session-*.jsonl` | main lane only | per turn | The project folder is read from the CLI's `.project_root` file |"Main lane only" means the session's own tool calls are all there, but subagent work is not split out into separate lanes on the map.@@ -273,6 +274,7 @@ All configuration is through environment variables. The examples in this README| `AGENTPLAY_COPILOT_VSCODE_HOMES` | VS Code `User` dirs | Copilot in VS Code || `AGENTPLAY_OPENCODE_HOMES` | `$XDG_DATA_HOME/opencode` | OpenCode data dirs || `AGENTPLAY_KIRO_HOMES` | `~/.kiro` | Kiro homes |+| `AGENTPLAY_GEMINI_HOMES` | `~/.gemini` | Gemini CLI homes || `AGENTPLAY_HMAC_KEY` | unset | key for `--path-mode hashed` || `DO_NOT_TRACK`, `AGENTPLAY_NO_NETWORK` | unset | set either to turn off the email signup and its one network call || `AGENTPLAY_SIGNUP_URL` | built in | where the signup sends an email (for testing; see [docs/signup-endpoint.md](docs/signup-endpoint.md)) |@@ -302,7 +304,7 @@ Test suites:Contributions are very welcome, and you don't need to know the whole codebase to make one. The most valuable are:-1. **A parser for another agent**: Gemini CLI, Amp, Cline, Roo, Windsurf or Aider. Each is one file plus a few registration lines; [CONTRIBUTING.md](CONTRIBUTING.md#adding-an-agent) walks through it step by step, and [`codex.py`](python/src/agentplay/_core/ingestion/coding_agent/_sources/local/parsers/codex.py) is a good one to copy.+1. **A parser for another agent**: Amp, Cline, Roo, Windsurf or Aider. Each is one file plus a few registration lines; [CONTRIBUTING.md](CONTRIBUTING.md#adding-an-agent) walks through it step by step, and [`codex.py`](python/src/agentplay/_core/ingestion/coding_agent/_sources/local/parsers/codex.py) is a good one to copy.2. **Fixture transcripts** for an agent version that broke parsing, with personal content removed. Open a [parser bug](https://github.com/Entelligence-AI/agentplay/issues/new?template=bug_report.yml) and attach one.3. **Viewer improvements** that make a session easier to read. The viewer runs on demo data with `pnpm dev` in `viewer/`, no sessions needed.4. **Docs and install fixes**, especially for Windows and WSL.diff --git a/python/src/agentplay/_core/ingestion/coding_agent/_sources/local/parsers/__init__.py b/python/src/agentplay/_core/ingestion/coding_agent/_sources/local/parsers/__init__.pyindex 202a0d3..559071f 100644--- a/python/src/agentplay/_core/ingestion/coding_agent/_sources/local/parsers/__init__.py+++ b/python/src/agentplay/_core/ingestion/coding_agent/_sources/local/parsers/__init__.py@@ -14,6 +14,8 @@ returns the agent type by sniffing for marker lines:directly.- Cursor: synthesized header line with `type="cursor_store_session"`.- Kiro: synthesized header line with `type="kiro_session"`.+- Gemini CLI: header line with `sessionId` + `projectHash` and no `type`, or a+ `type="gemini"` message (`~/.gemini/tmp/<project>/chats/session-*.jsonl`).- opencode: materialized records carrying a `message` object and a `parts` list.Each parser exposes `parse_X(data, trace_id, user_id=None,@@ -40,6 +42,7 @@ from agentplay._core.ingestion.coding_agent._sources.local.parsers.cursor_agent_from agentplay._core.ingestion.coding_agent._sources.local.parsers.cursor_store import (parse_cursor_store,)+from agentplay._core.ingestion.coding_agent._sources.local.parsers.gemini import parse_geminifrom agentplay._core.ingestion.coding_agent._sources.local.parsers.kiro import parse_kirofrom agentplay._core.ingestion.coding_agent._sources.local.parsers.opencode import parse_opencode@@ -52,6 +55,7 @@ __all__ = ["parse_copilot_vscode","parse_cursor_agent_transcript","parse_cursor_store",+ "parse_gemini","parse_kiro","parse_opencode",]diff --git a/python/src/agentplay/_core/ingestion/coding_agent/_sources/local/parsers/base.py b/python/src/agentplay/_core/ingestion/coding_agent/_sources/local/parsers/base.pyindex b280d0d..aabd8e0 100644--- a/python/src/agentplay/_core/ingestion/coding_agent/_sources/local/parsers/base.py+++ b/python/src/agentplay/_core/ingestion/coding_agent/_sources/local/parsers/base.py@@ -24,6 +24,7 @@ class AgentType(StrEnum):OPENCODE = "opencode"CURSOR = "cursor"KIRO = "kiro"+ GEMINI_CLI = "gemini-cli"def detect_agent(data: bytes) -> AgentType | None:@@ -71,6 +72,19 @@ def detect_agent(data: bytes) -> AgentType | None:if line_type == "kiro_session":return AgentType.KIRO+ # Gemini CLI: the first line is a header with `sessionId`, a+ # `projectHash` string and NO `type` (Claude Code's records all carry+ # one), and messages are typed `user` / `gemini`. `gemini` is a type no+ # other agent emits, so it identifies a file whose header was cut off.+ if (+ "type" not in obj+ and isinstance(obj.get("sessionId"), str)+ and isinstance(obj.get("projectHash"), str)+ ):+ return AgentType.GEMINI_CLI+ if line_type == "gemini" and isinstance(obj.get("id"), str):+ return AgentType.GEMINI_CLI+# Codex: session_meta with codex originator.if line_type == "session_meta":payload = obj.get("payload")diff --git a/python/src/agentplay/_core/ingestion/coding_agent/_sources/local/parsers/gemini.py b/python/src/agentplay/_core/ingestion/coding_agent/_sources/local/parsers/gemini.pynew file mode 100644index 0000000..ceda4b0--- /dev/null+++ b/python/src/agentplay/_core/ingestion/coding_agent/_sources/local/parsers/gemini.py@@ -0,0 +1,401 @@+"""Parse Gemini CLI session JSONL into the universal SpanData shape.++Gemini CLI writes one file per session at+``~/.gemini/tmp/<project-slug>/chats/session-<date>-<short-id>.jsonl``. The+shape below was read from real Gemini CLI 0.65 sessions:++ {"sessionId": ..., "projectHash": <sha256 of the project root>,+ "startTime": <ISO>, "lastUpdated": <ISO>, "kind": "main"}+ {"id": ..., "timestamp": <ISO>, "type": "user", "content": [{"text": ...}]}+ {"$set": {"lastUpdated": <ISO>}}+ {"id": ..., "timestamp": <ISO>, "type": "gemini", "content": <text>,+ "thoughts": [...], "model": ..., "tokens": {"input", "output", "cached",+ "thoughts", "tool", "total"}, "toolCalls": [...]}+ {"id": ..., "timestamp": <ISO>, "type": "user",+ "content": [{"functionResponse": {...}}]}++# Records are rewritten, not appended once++The recorder appends a record each time it updates a message, so one message+`id` can appear more than once: a `gemini` message is written first without+`toolCalls` and again once the calls are attached, with the same `tokens`.+The last copy of each id wins, kept at the position of its first copy, so a+request's tokens are counted once.++# Turn boundaries++A `user` message carrying text opens a turn. The CLI injects a+`<session_context>` block as the first `user` message of every session; it is+not a prompt and opens no turn. `user` messages that only carry+`functionResponse` parts are tool results, which the matching `toolCalls`+entry already holds in `result`.++# Tool failures++A tool call records `status` (`success` | `error` | `cancelled`). The shell+tool reports `success` even when the command fails, and appends an+`Exit Code: <n>` line to its output only when n is non-zero (and a `Signal:`+line only when a signal ended the process). Those lines are the failure+signal for shell calls.++# Tokens++`input` includes `cached`; `thoughts` and `tool` are counted apart from+`output` and `input` (`total` = input + output + thoughts + tool). Thinking+tokens bill as output, so completion = output + thoughts.+"""++from __future__ import annotations++from datetime import UTC, datetime+import json+import logging+import re++from agentplay._core.code_authorship import extract_edit_evidence+from agentplay._core.ingestion.coding_agent._sources._jsonl_utils import (+ as_count,+ parse_jsonl_records,+ safe_parse_dt,+ source_attrs,+)+from agentplay._core.ingestion.coding_agent.spans import SpanData, TraceData, model_id_or_none+from agentplay._core.ingestion.coding_agent.tool_taxonomy import aliases_for++logger = logging.getLogger(__name__)++# input.value / output.value truncation, matching every other local parser.+_TRUNCATE = 2000++# Raw -> canonical tool names live in the shared table (tool_taxonomy.py).+_TOOL_ALIASES: dict[str, str] = aliases_for("gemini-cli")++_MESSAGE_TYPES = ("user", "gemini", "info", "warning", "error")++_SESSION_CONTEXT_PREFIX = "<session_context>"++_SHELL_TOOL = "run_shell_command"++# Full-line matches: the command's own output comes first in the result text,+# so the LAST match is the CLI's label, never a line the program printed.+_RE_EXIT_CODE = re.compile(r"^Exit Code: (-?\d+)\s*$", re.MULTILINE)+_RE_SIGNAL = re.compile(r"^Signal: (\S+)\s*$", re.MULTILINE)+++def parse_gemini(+ data: bytes,+ trace_id: str,+ user_id: str | None = None,+ project_name: str | None = None,+) -> tuple[TraceData, list[SpanData]]:+ """Parse a Gemini CLI session JSONL file into a span tree.++ Args:+ data: raw JSONL bytes of one `session-*.jsonl` file.+ trace_id: the source-prefixed session id (e.g. `local:gemini-cli:<id>`).+ user_id: identifier to stash on the root span's `user.id`.+ project_name: project name resolved by `LocalSource` (from the+ project's `.project_root`). The transcript itself records only a+ hash of the project path, so there is nothing to derive here.++ Returns:+ `(trace, all_spans)`; empty spans when the file holds no messages.+ """+ records = parse_jsonl_records(data)+ header: dict = next(+ (r for r in records if isinstance(r.get("sessionId"), str) and "type" not in r), {}+ )+ messages = _messages(records)+ if not messages:+ now = datetime.now(UTC)+ return TraceData(trace_id=trace_id, start_time=now, end_time=now), []++ times = [+ t+ for t in (+ safe_parse_dt(header.get("startTime")),+ *(safe_parse_dt(m.get("timestamp")) for m in messages),+ *(safe_parse_dt(tc.get("timestamp")) for m in messages for tc in _tool_calls(m)),+ )+ if t is not None+ ]+ session_start = min(times) if times else datetime.now(UTC)+ session_end = max(times) if times else session_start++ root_id = f"{trace_id}:root"+ all_spans: list[SpanData] = []+ turn: dict | None = None+ turn_num = 0+ session_model = ""++ def _open_turn(msg: dict, prompt: str) -> dict:+ nonlocal turn_num+ turn_num += 1+ ts = safe_parse_dt(msg.get("timestamp")) or session_start+ return {+ "span_id": f"{trace_id}:turn:{turn_num}",+ "num": turn_num,+ "_src": msg,+ "prompt": prompt,+ "start": ts,+ "end": ts,+ "output": [],+ "prompt_tokens": 0,+ "completion_tokens": 0,+ "reasoning_tokens": 0,+ "cache_read": 0,+ "cost_events": [],+ "model": "",+ "tools": [],+ }++ def _close_turn() -> None:+ if turn is not None:+ all_spans.append(_turn_span(trace_id, root_id, turn))+ all_spans.extend(turn["tools"])++ for msg in messages:+ mtype = msg.get("type")+ ts = safe_parse_dt(msg.get("timestamp"))++ if mtype == "user":+ prompt = _user_prompt(msg.get("content"))+ if prompt is not None:+ _close_turn()+ turn = _open_turn(msg, prompt)+ continue+ elif mtype == "gemini":+ if turn is None:+ # Model activity before any prompt still needs a turn to live+ # under (same fallback as kiro.py / cursor_store.py).+ turn = _open_turn(msg, "")+ model = model_id_or_none(msg.get("model")) or ""+ if model:+ turn["model"] = model+ session_model = model+ text = msg.get("content")+ if isinstance(text, str) and text:+ turn["output"].append(text)+ _add_usage(turn, msg, model)+ for index, call in enumerate(_tool_calls(msg)):+ turn["tools"].append(_tool_span(trace_id, turn, msg, call, index))++ if turn is not None and ts is not None and ts > turn["end"]:+ turn["end"] = ts+ _close_turn()++ root_span = SpanData(+ span_id=root_id,+ trace_id=trace_id,+ parent_id=None,+ name="Session",+ span_kind="CHAIN",+ status_code="OK",+ start_time=session_start,+ end_time=session_end,+ attributes={+ "user.id": user_id or "",+ "llm.model_name": session_model,+ "session.id": trace_id,+ "project.name": project_name or "",+ "harness.agent_session_id": header.get("sessionId") or "",+ # The transcript does not record the CLI version.+ "harness.agent_version": "",+ },+ )+ all_spans.insert(0, root_span)+ trace = TraceData(+ trace_id=trace_id,+ start_time=session_start,+ end_time=session_end,+ spans=all_spans,+ )+ return trace, all_spans+++def _messages(records: list[dict]) -> list[dict]:+ """Conversation messages in order, keeping the last copy of each `id`."""+ latest: dict[str, dict] = {}+ for record in records:+ msg_id = record.get("id")+ if isinstance(msg_id, str) and msg_id and record.get("type") in _MESSAGE_TYPES:+ # dict keeps first-insertion order; reassigning keeps the position.+ latest[msg_id] = record+ return list(latest.values())+++def _tool_calls(msg: dict) -> list[dict]:+ calls = msg.get("toolCalls")+ return [c for c in calls if isinstance(c, dict)] if isinstance(calls, list) else []+++def _user_prompt(content: object) -> str | None:+ """The prompt text of a `user` message, or None when it opens no turn.++ None for tool-result messages (only `functionResponse` parts) and for the+ CLI's own `<session_context>` injection.+ """+ if isinstance(content, str):+ parts = [content]+ elif isinstance(content, list):+ parts = [+ p["text"] for p in content if isinstance(p, dict) and isinstance(p.get("text"), str)+ ]+ else:+ return None+ texts = [t for t in parts if t and not t.lstrip().startswith(_SESSION_CONTEXT_PREFIX)]+ if not texts:+ return None+ return "\n".join(texts)+++def _add_usage(turn: dict, msg: dict, model: str) -> None:+ """Fold one `gemini` message's token record into its turn."""+ tokens = msg.get("tokens")+ if not isinstance(tokens, dict):+ return+ prompt = as_count(tokens.get("input")) + as_count(tokens.get("tool"))+ cache_read = min(as_count(tokens.get("cached")), prompt)+ thoughts = as_count(tokens.get("thoughts"))+ completion = as_count(tokens.get("output")) + thoughts+ if not prompt and not completion:+ return+ turn["prompt_tokens"] += prompt+ turn["completion_tokens"] += completion+ turn["reasoning_tokens"] += thoughts+ turn["cache_read"] += cache_read+ turn["cost_events"].append(+ {+ "timestamp": msg.get("timestamp") or "",+ "request_id": None,+ "message_id": f"gemini:{msg.get('id')}",+ "model": model,+ "input_tokens": prompt - cache_read,+ "cache_read_tokens": cache_read,+ "cache_write_5m_tokens": 0,+ "cache_write_1h_tokens": 0,+ "output_tokens": completion,+ "reasoning_tokens": thoughts,+ "usage_basis": "message_tokens",+ **source_attrs(msg),+ }+ )+++def _turn_span(trace_id: str, root_id: str, turn: dict) -> SpanData:+ prompt = turn["prompt_tokens"]+ cache_read = turn["cache_read"]+ span = SpanData(+ span_id=turn["span_id"],+ trace_id=trace_id,+ parent_id=root_id,+ name=f"Turn {turn['num']}",+ span_kind="CHAIN",+ status_code="OK",+ start_time=turn["start"],+ end_time=turn["end"],+ attributes={+ "input.value": turn["prompt"][:_TRUNCATE],+ "output.value": "\n".join(turn["output"])[:_TRUNCATE],+ # The transcript records no working directory; LocalSource stamps+ # the project root it read from `.project_root`.+ "cwd": "",+ "llm.token_count.prompt": prompt,+ "llm.token_count.completion": turn["completion_tokens"],+ # Subset of completion, not additive. Display-only.+ "llm.token_count.reasoning": turn["reasoning_tokens"],+ "llm.token_count.cache_read": cache_read,+ "llm.token_count.cache_write": 0,+ "llm.token_count.input_fresh": max(0, prompt - cache_read),+ "llm.cost_events": turn["cost_events"],+ "llm.model_name": turn["model"],+ },+ )+ span.attributes.update(source_attrs(turn["_src"]))+ return span+++def _tool_span(trace_id: str, turn: dict, msg: dict, call: dict, index: int) -> SpanData:+ raw_name = call.get("name")+ raw_name = raw_name if isinstance(raw_name, str) and raw_name else "unknown"+ tool_name = _TOOL_ALIASES.get(raw_name, raw_name)++ args = call.get("args")+ input_value = json.dumps(args) if isinstance(args, dict) else "{}"+ response = _response(call)+ output_value = _output_text(response)++ status = call.get("status")+ if status in ("error", "cancelled") or (status == "success" and _failed(raw_name, response)):+ status_code = "ERROR"+ elif status == "success":+ status_code = "OK"+ else:+ status_code = "UNSET"++ start = safe_parse_dt(msg.get("timestamp")) or turn["start"]+ end = safe_parse_dt(call.get("timestamp")) or start+ if end < start:+ end = start++ call_id = call.get("id")+ if not isinstance(call_id, str) or not call_id:+ call_id = f"{msg.get('id')}:{index}"+ span = SpanData(+ span_id=f"{trace_id}:tool:{call_id}",+ trace_id=trace_id,+ parent_id=turn["span_id"],+ name=tool_name,+ span_kind="CHAIN",+ status_code=status_code,+ start_time=start,+ end_time=end,+ attributes={+ "tool.name": tool_name,+ "cwd": "",+ "input.value": input_value[:_TRUNCATE],+ "output.value": output_value[:_TRUNCATE],+ "code.edit_evidence": extract_edit_evidence(+ tool_name, input_value, successful=status_code == "OK"+ ),+ },+ )+ span.attributes.update(source_attrs(msg))+ return span+++def _response(call: dict) -> dict:+ """The `functionResponse.response` object of a tool call's result."""+ result = call.get("result")+ for part in result if isinstance(result, list) else []:+ if isinstance(part, dict):+ fr = part.get("functionResponse")+ if isinstance(fr, dict) and isinstance(fr.get("response"), dict):+ return fr["response"]+ return {}+++def _output_text(response: dict) -> str:+ output = response.get("output")+ if isinstance(output, str):+ return output+ return json.dumps(response) if response else ""+++def _failed(raw_name: str, response: dict) -> bool:+ """Failure evidence inside a result the CLI marked `success`."""+ if response.get("error"):+ return True+ if raw_name != _SHELL_TOOL:+ return False+ output = response.get("output")+ if not isinstance(output, str):+ return False+ codes = _RE_EXIT_CODE.findall(output)+ if codes and codes[-1] != "0":+ return True+ signals = _RE_SIGNAL.findall(output)+ return bool(signals and signals[-1] not in ("(none)", "0"))+++__all__ = ["parse_gemini"]diff --git a/python/src/agentplay/_core/ingestion/coding_agent/_sources/local/source.py b/python/src/agentplay/_core/ingestion/coding_agent/_sources/local/source.pyindex 045bff5..bd6afc2 100644--- a/python/src/agentplay/_core/ingestion/coding_agent/_sources/local/source.py+++ b/python/src/agentplay/_core/ingestion/coding_agent/_sources/local/source.py@@ -1,4 +1,4 @@-"""Local filesystem source — walks ~/.claude / ~/.codex / Copilot dirs.+"""Local filesystem source — walks ~/.claude / ~/.codex / ~/.gemini / Copilot dirs.Indexes JSONL session files under per-agent homes, detects the agentfrom the file head, and emits the universal `SpanData` shape via the@@ -33,6 +33,7 @@ from agentplay._core.ingestion.coding_agent._sources.local.parsers import (parse_copilot_vscode,parse_cursor_agent_transcript,parse_cursor_store,+ parse_gemini,parse_kiro,parse_opencode,)@@ -1117,6 +1118,56 @@ def _copilot_vscode_json_session_id(head: bytes) -> tuple[str | None, bool]:return session_id, isinstance(requests, list) and len(requests) > 0+def _gemini_header(head: bytes) -> dict | None:+ """The Gemini CLI session header: the first record with `sessionId` and no `type`."""+ for line in head.split(b"\n"):+ try:+ obj = json.loads(line)+ except ValueError: # blank, truncated, or split mid-character+ continue+ if isinstance(obj, dict) and "type" not in obj and isinstance(obj.get("sessionId"), str):+ return obj+ return None+++def _gemini_has_messages(head: bytes) -> bool:+ """True when the head holds a `user` or `gemini` message, not only the header.++ A session that was opened and closed without a prompt is just the header+ line; it has nothing to map, same as `_kiro_event_count == 0`.+ """+ for line in head.split(b"\n"):+ try:+ obj = json.loads(line)+ except ValueError:+ continue+ if isinstance(obj, dict) and obj.get("type") in ("user", "gemini"):+ return True+ return False+++def _cwd_from_gemini_project(jsonl_file: Path, header: dict | None) -> str | None:+ """The project root of a Gemini CLI session.++ The transcript stores only `projectHash` (sha256 of the project root). The+ CLI writes the root itself to `.project_root` in the project folder+ (`<home>/tmp/<slug>/.project_root`, two levels above `chats/<file>`).+ When the header carries a hash, the root must hash to it, so a stale or+ copied `.project_root` can't name the wrong project.+ """+ try:+ root = (jsonl_file.parent.parent / ".project_root").read_text(encoding="utf-8").strip()+ except (OSError, UnicodeDecodeError):+ return None+ if not root:+ return None+ expected = (header or {}).get("projectHash")+ if isinstance(expected, str) and expected:+ if hashlib.sha256(root.encode("utf-8")).hexdigest() != expected:+ return None+ return root++def _project_from_cwd(cwd: str) -> str | None:"""Project name from the transcript's cwd.@@ -1243,6 +1294,7 @@ class LocalSource:kiro_homes: list[Path] | None = None,copilot_homes: list[Path] | None = None,copilot_vscode_homes: list[Path] | None = None,+ gemini_homes: list[Path] | None = None,) -> None:self.claude_code_homes = claude_code_homesself.codex_homes = codex_homes@@ -1274,6 +1326,11 @@ class LocalSource:# `globalStorage/emptyWindowChatSessions/`), so this also gets the# whole-home rglob treatment, over both `.jsonl` and `.json`.self.copilot_vscode_homes = copilot_vscode_homes or []+ # Gemini CLI writes a real per-session JSONL itself:+ # `<home>/tmp/<project-slug>/chats/session-*.jsonl`. The session id+ # comes from the header's `sessionId`, the cwd from the project+ # folder's `.project_root` (see `_cwd_from_gemini_project`).+ self.gemini_homes = gemini_homes or []# Per-home identity stamp (`<home>/_manifest/*.json`). It carries a# user_uuid/email/github_username used to detect duplicated sessions# that belong to different owners. Missing manifest → empty dict.@@ -1297,6 +1354,7 @@ class LocalSource:*self.kiro_homes,*self.copilot_homes,*self.copilot_vscode_homes,+ *self.gemini_homes,):identity = _load_manifest_identity(home)if identity is not None:@@ -1501,6 +1559,18 @@ class LocalSource:if ref:_index_put(index, ref[0], ref[1], newest)+ # Gemini CLI: `<home>/tmp/<project-slug>/chats/session-*.jsonl`.+ # `detect_agent` sniffs the header, so a stray `.jsonl` is skipped.+ for home in self.gemini_homes:+ tmp_dir = home / "tmp"+ if not tmp_dir.is_dir():+ logger.debug("Skipping non-existent path: %s", tmp_dir)+ continue+ for jsonl_file in tmp_dir.glob("*/chats/session-*.jsonl"):+ ref = self._index_gemini_file(jsonl_file, home=home)+ if ref:+ _index_put(index, ref[0], ref[1], newest)+_carry_collision_mtimes(index, newest)self._file_index = indexlogger.info(@@ -1512,7 +1582,8 @@ class LocalSource:+ len(self.cursor_store_homes)+ len(self.kiro_homes)+ len(self.copilot_homes)- + len(self.copilot_vscode_homes),+ + len(self.copilot_vscode_homes)+ + len(self.gemini_homes),)return index@@ -1826,6 +1897,63 @@ class LocalSource:home=home,)+ def _index_gemini_file(+ self,+ jsonl_file: Path,+ *,+ home: Path,+ ) -> tuple[str, _FileRef] | None:+ """Index one Gemini CLI session JSONL."""+ if not jsonl_file.is_file():+ # See _index_cc_file's identical guard: a directory/broken symlink+ # is never tallied, only a genuinely empty real file is.+ return None+ size = jsonl_file.stat().st_size+ if size == 0:+ self._record_discovery("gemini-cli", "empty_or_unreadable")+ return None+ try:+ head = _read_head(jsonl_file, stop_when=_agent_detected)+ except OSError:+ self._record_discovery("gemini-cli", "empty_or_unreadable")+ return None++ agent = detect_agent(head)+ if agent is None:+ logger.warning(+ "agent detection failed for %s (%d bytes); session skipped",+ jsonl_file,+ size,+ )+ self._record_discovery("gemini-cli", "detection_failed")+ return None+ if agent != AgentType.GEMINI_CLI:+ self._record_discovery("gemini-cli", "different_agent")+ return None++ if not _gemini_has_messages(head):+ logger.debug("gemini-cli: %s has no messages; session skipped", jsonl_file)+ self._record_discovery("gemini-cli", "empty_events")+ return None++ header = _gemini_header(head)+ native_id = (header or {}).get("sessionId") or jsonl_file.stem+ session_id = f"local:{agent}:{native_id}"+ mtime = datetime.fromtimestamp(jsonl_file.stat().st_mtime, tz=UTC)++ cwd = _cwd_from_gemini_project(jsonl_file, header)+ project_name = _project_from_cwd(cwd) if cwd else None++ self._record_discovery("gemini-cli", "indexed")+ return session_id, _FileRef(+ path=jsonl_file,+ agent=agent,+ mtime=mtime,+ project_name=project_name,+ cwd=cwd,+ home=home,+ )+def _index_copilot_file(self,jsonl_file: Path,@@ -2237,6 +2365,7 @@ class LocalSource:AgentType.OPENCODE: parse_opencode,AgentType.CURSOR: parse_cursor_store,AgentType.KIRO: parse_kiro,+ AgentType.GEMINI_CLI: parse_gemini,}# Cursor's `agent-transcripts` narrative shares the `cursor` agent label@@ -2255,6 +2384,12 @@ class LocalSource:user_id=user_id,project_name=ref.project_name,)+ if ref.agent == AgentType.GEMINI_CLI and ref.cwd:+ # Gemini CLI's transcript records no cwd; the indexer read the+ # project root from `.project_root`. Every call ran there.+ for span in spans:+ if span.parent_id is not None and not span.attributes.get("cwd"):+ span.attributes["cwd"] = ref.cwdbranch, branches = self._branch_history[session_id]root = next((span for span in spans if span.parent_id is None), None)if root is not None:diff --git a/python/src/agentplay/_core/ingestion/coding_agent/tool_taxonomy.py b/python/src/agentplay/_core/ingestion/coding_agent/tool_taxonomy.pyindex fa029aa..7f1c640 100644--- a/python/src/agentplay/_core/ingestion/coding_agent/tool_taxonomy.py+++ b/python/src/agentplay/_core/ingestion/coding_agent/tool_taxonomy.py@@ -224,8 +224,31 @@ _COPILOT_VSCODE: dict[str, str] = {"runSubagent": "Task",}+# Gemini CLI's built-in tool names. `read_file`, `replace`, `write_file` and+# `run_shell_command` were seen in real Gemini CLI 0.65 sessions; the rest are+# the `*_TOOL_NAME` constants in the same release's bundle. `replace` is an+# in-place old_string/new_string edit and `write_file` writes the whole file,+# the same Edit/Write split as Copilot's `edit` vs `create`. Meta tools+# (`update_topic`, `ask_user`, `enter_plan_mode`, `tracker_*`, `activate_skill`,+# ...) and MCP tools (`mcp_<server>_<tool>`) pass through unaliased.+_GEMINI_CLI: dict[str, str] = {+ "run_shell_command": "Bash",+ "read_file": "Read",+ "read_many_files": "Read",+ "replace": "Edit",+ "write_file": "Write",+ "grep_search": "Grep",+ "glob": "Glob",+ "list_directory": "ListDir",+ "web_fetch": "WebFetch",+ "google_web_search": "WebSearch",+ "write_todos": "TodoWrite",+ "invoke_agent": "Task",+}+TOOL_ALIASES: dict[str, dict[str, str]] = {"codex": _CODEX,+ "gemini-cli": _GEMINI_CLI,"cursor": _CURSOR,"copilot": _COPILOT,"copilot-vscode": _COPILOT_VSCODE,diff --git a/python/src/agentplay/discover.py b/python/src/agentplay/discover.pyindex d7cf7b3..e021db5 100644--- a/python/src/agentplay/discover.py+++ b/python/src/agentplay/discover.py@@ -13,6 +13,7 @@ Cursor ``~/.cursor`` agent transcripts, ``chats/*/store.db``, decodIDE ``state.vscdb``OpenCode ``~/.local/share/opencode/opencode.db`` decodedKiro ``~/.kiro/sessions`` decoded+Gemini CLI ``~/.gemini/tmp/*/chats/session-*.jsonl`` file================= ===================================================== ==========="Decoded" agents keep sessions in a database; :mod:`agentplay.materialize`@@ -42,7 +43,7 @@ from ._util import capturedlogger = logging.getLogger("agentplay.discover")-AGENTS = ("claude-code", "codex", "cursor", "copilot", "copilot-vscode", "opencode", "kiro")+AGENTS = ("claude-code", "codex", "cursor", "copilot", "copilot-vscode", "opencode", "kiro", "gemini-cli")# Transcripts above this size are skipped rather than parsed (a 20k-event map cap# applies anyway; this keeps one pathological file from stalling a run).@@ -84,6 +85,7 @@ class Homes:copilot_vscode: list[Path]opencode: list[Path]kiro: list[Path]+ gemini_cli: list[Path]@classmethoddef default(cls) -> Homes:@@ -96,6 +98,7 @@ class Homes:copilot_vscode=_homes_from_env("AGENTPLAY_COPILOT_VSCODE_HOMES", _vscode_user_dirs()),opencode=_homes_from_env("AGENTPLAY_OPENCODE_HOMES", _opencode_data_dirs()),kiro=_homes_from_env("AGENTPLAY_KIRO_HOMES", ["~/.kiro"]),+ gemini_cli=_homes_from_env("AGENTPLAY_GEMINI_HOMES", ["~/.gemini"]),)def present(self) -> dict[str, list[Path]]:@@ -109,6 +112,7 @@ class Homes:("copilot-vscode", self.copilot_vscode),("opencode", self.opencode),("kiro", self.kiro),+ ("gemini-cli", self.gemini_cli),):found = [p for p in paths if p.is_dir()]if found:@@ -188,6 +192,7 @@ def local_source(homes: Homes, agents: set[str]) -> Any:kiro_homes=pick("kiro", _cache_dirs("kiro")),copilot_homes=pick("copilot", homes.copilot),copilot_vscode_homes=pick("copilot-vscode", homes.copilot_vscode),+ gemini_homes=pick("gemini-cli", homes.gemini_cli),)diff --git a/python/tests/core/fixtures/gemini/edit_and_run.jsonl b/python/tests/core/fixtures/gemini/edit_and_run.jsonlnew file mode 100644index 0000000..16d838a--- /dev/null+++ b/python/tests/core/fixtures/gemini/edit_and_run.jsonl@@ -0,0 +1,22 @@+{"sessionId":"00000000-0000-4000-8000-000000000001","projectHash":"0000000000000000000000000000000000000000000000000000000000000000","startTime":"2026-10-23T07:33:51.276Z","lastUpdated":"2026-10-23T07:33:51.276Z","kind":"main"}+{"id":"msg-0001","timestamp":"2026-10-23T07:33:51.276Z","type":"user","content":[{"text":"<session_context>\nCONTEXT-PLACEHOLDER\n</session_context>"}]}+{"$set":{"lastUpdated":"2026-10-23T07:33:51.276Z"}}+{"id":"msg-0002","timestamp":"2026-10-23T07:33:51.282Z","type":"user","content":[{"text":"PROMPT-PLACEHOLDER-1"}]}+{"$set":{"lastUpdated":"2026-10-23T07:33:51.282Z"}}+{"id":"msg-0003","timestamp":"2026-10-23T07:33:54.690Z","type":"gemini","content":"","thoughts":[{"subject":"THOUGHT-SUBJECT-PLACEHOLDER","description":"THOUGHT-PLACEHOLDER","timestamp":"2026-10-23T07:33:54.690Z"}],"tokens":{"input":10933,"output":56,"cached":8404,"thoughts":345,"tool":0,"total":11334},"model":"gemini-3.6-flash"}+{"$set":{"lastUpdated":"2026-10-23T07:33:54.691Z"}}+{"id":"msg-0003","timestamp":"2026-10-23T07:33:54.690Z","type":"gemini","content":"","thoughts":[{"subject":"THOUGHT-SUBJECT-PLACEHOLDER","description":"THOUGHT-PLACEHOLDER","timestamp":"2026-10-23T07:33:54.690Z"}],"tokens":{"input":10933,"output":56,"cached":8404,"thoughts":345,"tool":0,"total":11334},"model":"gemini-3.6-flash","toolCalls":[{"id":"call-0001","name":"update_topic","args":{"strategic_intent":"STRATEGIC_INTENT-PLACEHOLDER"},"result":[{"functionResponse":{"id":"call-0001","name":"update_topic","response":{"output":"TOOL-OUTPUT-PLACEHOLDER"}}}],"status":"success","timestamp":"2026-10-23T07:33:54.698Z","resultDisplay":"RESULTDISPLAY-PLACEHOLDER","description":"DESCRIPTION-PLACEHOLDER","displayName":"Update Topic Context","renderOutputAsMarkdown":true},{"id":"call-0002","name":"read_file","args":{"file_path":"/Users/dev/project/file_1.js"},"result":[{"functionResponse":{"id":"call-0002","name":"read_file","response":{"output":"TOOL-OUTPUT-PLACEHOLDER"}}}],"status":"success","timestamp":"2026-10-23T07:33:54.698Z","resultDisplay":"RESULTDISPLAY-PLACEHOLDER","description":"DESCRIPTION-PLACEHOLDER","displayName":"ReadFile","renderOutputAsMarkdown":true}]}+{"id":"msg-0004","timestamp":"2026-10-23T07:33:54.699Z","type":"user","content":[{"functionResponse":{"id":"call-0001","name":"update_topic","response":{"output":"TOOL-OUTPUT-PLACEHOLDER"}}},{"functionResponse":{"id":"call-0002","name":"read_file","response":{"output":"TOOL-OUTPUT-PLACEHOLDER"}}}]}+{"$set":{"lastUpdated":"2026-10-23T07:33:54.699Z"}}+{"id":"msg-0005","timestamp":"2026-10-23T07:34:00.157Z","type":"gemini","content":"","thoughts":[{"subject":"THOUGHT-SUBJECT-PLACEHOLDER","description":"THOUGHT-PLACEHOLDER","timestamp":"2026-10-23T07:34:00.157Z"},{"subject":"THOUGHT-SUBJECT-PLACEHOLDER","description":"THOUGHT-PLACEHOLDER","timestamp":"2026-10-23T07:34:00.157Z"},{"subject":"THOUGHT-SUBJECT-PLACEHOLDER","description":"THOUGHT-PLACEHOLDER","timestamp":"2026-10-23T07:34:00.157Z"}],"tokens":{"input":11436,"output":121,"cached":8890,"thoughts":761,"tool":0,"total":12318},"model":"gemini-3.6-flash"}+{"$set":{"lastUpdated":"2026-10-23T07:34:00.158Z"}}+{"id":"msg-0005","timestamp":"2026-10-23T07:34:00.157Z","type":"gemini","content":"","thoughts":[{"subject":"THOUGHT-SUBJECT-PLACEHOLDER","description":"THOUGHT-PLACEHOLDER","timestamp":"2026-10-23T07:34:00.157Z"},{"subject":"THOUGHT-SUBJECT-PLACEHOLDER","description":"THOUGHT-PLACEHOLDER","timestamp":"2026-10-23T07:34:00.157Z"},{"subject":"THOUGHT-SUBJECT-PLACEHOLDER","description":"THOUGHT-PLACEHOLDER","timestamp":"2026-10-23T07:34:00.157Z"}],"tokens":{"input":11436,"output":121,"cached":8890,"thoughts":761,"tool":0,"total":12318},"model":"gemini-3.6-flash","toolCalls":[{"id":"call-0003","name":"write_file","args":{"content":"CONTENT-PLACEHOLDER","file_path":"/Users/dev/project/file_1.js"},"result":[{"functionResponse":{"id":"call-0003","name":"write_file","response":{"output":"TOOL-OUTPUT-PLACEHOLDER"}}}],"status":"success","timestamp":"2026-10-23T07:34:00.172Z","resultDisplay":{"fileDiff":"FILEDIFF-PLACEHOLDER","fileName":"FILENAME-PLACEHOLDER","filePath":"/Users/dev/project/file_2.js","originalContent":"ORIGINALCONTENT-PLACEHOLDER","newContent":"NEWCONTENT-PLACEHOLDER","diffStat":{"model_added_lines":5,"model_removed_lines":0,"model_added_chars":112,"model_removed_chars":0,"user_added_lines":0,"user_removed_lines":0,"user_added_chars":0,"user_removed_chars":0},"isNewFile":false,"isBuildFile":false},"description":"DESCRIPTION-PLACEHOLDER","displayName":"WriteFile","renderOutputAsMarkdown":true}]}+{"id":"msg-0006","timestamp":"2026-10-23T07:34:00.173Z","type":"user","content":[{"functionResponse":{"id":"call-0003","name":"write_file","response":{"output":"TOOL-OUTPUT-PLACEHOLDER"}}}]}+{"$set":{"lastUpdated":"2026-10-23T07:34:00.173Z"}}+{"id":"msg-0007","timestamp":"2026-10-23T07:34:02.654Z","type":"gemini","content":"MODEL-TEXT-PLACEHOLDER-1","thoughts":[],"tokens":{"input":12459,"output":58,"cached":9406,"thoughts":55,"tool":0,"total":12572},"model":"gemini-3.6-flash"}+{"$set":{"lastUpdated":"2026-10-23T07:34:02.655Z"}}+{"id":"msg-0007","timestamp":"2026-10-23T07:34:02.654Z","type":"gemini","content":"MODEL-TEXT-PLACEHOLDER-1","thoughts":[],"tokens":{"input":12459,"output":58,"cached":9406,"thoughts":55,"tool":0,"total":12572},"model":"gemini-3.6-flash","toolCalls":[{"id":"call-0004","name":"run_shell_command","args":{"command":"node ARG-1","description":"DESCRIPTION-PLACEHOLDER"},"result":[{"functionResponse":{"id":"call-0004","name":"run_shell_command","response":{"output":"Output: OUTPUT-PLACEHOLDER\nProcess Group PGID: 4242"}}}],"status":"success","timestamp":"2026-10-23T07:34:02.740Z","resultDisplay":"RESULTDISPLAY-PLACEHOLDER","description":"DESCRIPTION-PLACEHOLDER","displayName":"Shell","renderOutputAsMarkdown":false}]}+{"id":"msg-0008","timestamp":"2026-10-23T07:34:02.741Z","type":"user","content":[{"functionResponse":{"id":"call-0004","name":"run_shell_command","response":{"output":"Output: OUTPUT-PLACEHOLDER\nProcess Group PGID: 4242"}}}]}+{"$set":{"lastUpdated":"2026-10-23T07:34:02.741Z"}}+{"id":"msg-0009","timestamp":"2026-10-23T07:35:08.419Z","type":"gemini","content":"MODEL-TEXT-PLACEHOLDER-2","thoughts":[],"tokens":{"input":12625,"output":41,"cached":10422,"thoughts":105,"tool":0,"total":12771},"model":"gemini-3.6-flash"}+{"$set":{"lastUpdated":"2026-10-23T07:35:08.421Z"}}diff --git a/python/tests/core/fixtures/gemini/failed_shell.jsonl b/python/tests/core/fixtures/gemini/failed_shell.jsonlnew file mode 100644index 0000000..54f668d--- /dev/null+++ b/python/tests/core/fixtures/gemini/failed_shell.jsonl@@ -0,0 +1,17 @@+{"sessionId":"00000000-0000-4000-8000-000000000001","projectHash":"0000000000000000000000000000000000000000000000000000000000000000","startTime":"2026-10-23T07:35:09.633Z","lastUpdated":"2026-10-23T07:35:09.633Z","kind":"main"}+{"id":"msg-0001","timestamp":"2026-10-23T07:35:09.634Z","type":"user","content":[{"text":"<session_context>\nCONTEXT-PLACEHOLDER\n</session_context>"}]}+{"$set":{"lastUpdated":"2026-10-23T07:35:09.634Z"}}+{"id":"msg-0002","timestamp":"2026-10-23T07:35:09.640Z","type":"user","content":[{"text":"PROMPT-PLACEHOLDER-1"}]}+{"$set":{"lastUpdated":"2026-10-23T07:35:09.640Z"}}+{"id":"msg-0003","timestamp":"2026-10-23T07:35:13.890Z","type":"gemini","content":"","thoughts":[{"subject":"THOUGHT-SUBJECT-PLACEHOLDER","description":"THOUGHT-PLACEHOLDER","timestamp":"2026-10-23T07:35:13.890Z"},{"subject":"THOUGHT-SUBJECT-PLACEHOLDER","description":"THOUGHT-PLACEHOLDER","timestamp":"2026-10-23T07:35:13.890Z"}],"tokens":{"input":10922,"output":39,"cached":0,"thoughts":506,"tool":0,"total":11467},"model":"gemini-3.6-flash"}+{"$set":{"lastUpdated":"2026-10-23T07:35:13.890Z"}}+{"id":"msg-0003","timestamp":"2026-10-23T07:35:13.890Z","type":"gemini","content":"","thoughts":[{"subject":"THOUGHT-SUBJECT-PLACEHOLDER","description":"THOUGHT-PLACEHOLDER","timestamp":"2026-10-23T07:35:13.890Z"},{"subject":"THOUGHT-SUBJECT-PLACEHOLDER","description":"THOUGHT-PLACEHOLDER","timestamp":"2026-10-23T07:35:13.890Z"}],"tokens":{"input":10922,"output":39,"cached":0,"thoughts":506,"tool":0,"total":11467},"model":"gemini-3.6-flash","toolCalls":[{"id":"call-0001","name":"run_shell_command","args":{"description":"DESCRIPTION-PLACEHOLDER","command":"node ARG-1"},"result":[{"functionResponse":{"id":"call-0001","name":"run_shell_command","response":{"output":"Output: OUTPUT-PLACEHOLDER\nError: ERROR-PLACEHOLDER\nExit Code: 1\nProcess Group PGID: 4242"}}}],"status":"success","timestamp":"2026-10-23T07:35:13.969Z","resultDisplay":"RESULTDISPLAY-PLACEHOLDER","description":"DESCRIPTION-PLACEHOLDER","displayName":"Shell","renderOutputAsMarkdown":false}]}+{"id":"msg-0004","timestamp":"2026-10-23T07:35:13.970Z","type":"user","content":[{"functionResponse":{"id":"call-0001","name":"run_shell_command","response":{"output":"Output: OUTPUT-PLACEHOLDER\nError: ERROR-PLACEHOLDER\nExit Code: 1\nProcess Group PGID: 4242"}}}]}+{"$set":{"lastUpdated":"2026-10-23T07:35:13.970Z"}}+{"id":"msg-0005","timestamp":"2026-10-23T07:35:17.048Z","type":"gemini","content":"","thoughts":[],"tokens":{"input":11802,"output":35,"cached":8888,"thoughts":33,"tool":0,"total":11870},"model":"gemini-3.6-flash"}+{"$set":{"lastUpdated":"2026-10-23T07:35:17.049Z"}}+{"id":"msg-0005","timestamp":"2026-10-23T07:35:17.048Z","type":"gemini","content":"","thoughts":[],"tokens":{"input":11802,"output":35,"cached":8888,"thoughts":33,"tool":0,"total":11870},"model":"gemini-3.6-flash","toolCalls":[{"id":"call-0002","name":"run_shell_command","args":{"description":"DESCRIPTION-PLACEHOLDER","command":"node ARG-2"},"result":[{"functionResponse":{"id":"call-0002","name":"run_shell_command","response":{"output":"Output: OUTPUT-PLACEHOLDER\nProcess Group PGID: 4242"}}}],"status":"success","timestamp":"2026-10-23T07:35:17.124Z","resultDisplay":"RESULTDISPLAY-PLACEHOLDER","description":"DESCRIPTION-PLACEHOLDER","displayName":"Shell","renderOutputAsMarkdown":false}]}+{"id":"msg-0006","timestamp":"2026-10-23T07:35:17.125Z","type":"user","content":[{"functionResponse":{"id":"call-0002","name":"run_shell_command","response":{"output":"Output: OUTPUT-PLACEHOLDER\nProcess Group PGID: 4242"}}}]}+{"$set":{"lastUpdated":"2026-10-23T07:35:17.125Z"}}+{"id":"msg-0007","timestamp":"2026-10-23T07:35:21.370Z","type":"gemini","content":"MODEL-TEXT-PLACEHOLDER-1","thoughts":[],"tokens":{"input":11923,"output":50,"cached":9763,"thoughts":86,"tool":0,"total":12059},"model":"gemini-3.6-flash"}+{"$set":{"lastUpdated":"2026-10-23T07:35:21.371Z"}}diff --git a/python/tests/core/fixtures/gemini/read_explain.jsonl b/python/tests/core/fixtures/gemini/read_explain.jsonlnew file mode 100644index 0000000..f655233--- /dev/null+++ b/python/tests/core/fixtures/gemini/read_explain.jsonl@@ -0,0 +1,12 @@+{"sessionId":"00000000-0000-4000-8000-000000000001","projectHash":"0000000000000000000000000000000000000000000000000000000000000000","startTime":"2026-10-23T07:15:15.796Z","lastUpdated":"2026-10-23T07:15:15.796Z","kind":"main"}+{"id":"msg-0001","timestamp":"2026-10-23T07:15:15.796Z","type":"user","content":[{"text":"<session_context>\nCONTEXT-PLACEHOLDER\n</session_context>"}]}+{"$set":{"lastUpdated":"2026-10-23T07:15:15.797Z"}}+{"id":"msg-0002","timestamp":"2026-10-23T07:15:15.803Z","type":"user","content":[{"text":"PROMPT-PLACEHOLDER-1"}]}+{"$set":{"lastUpdated":"2026-10-23T07:15:15.803Z"}}+{"id":"msg-0003","timestamp":"2026-10-23T07:15:19.066Z","type":"gemini","content":"","thoughts":[],"tokens":{"input":10033,"output":108,"cached":0,"thoughts":0,"tool":0,"total":10141},"model":"gemini-3-flash-preview"}+{"$set":{"lastUpdated":"2026-10-23T07:15:19.067Z"}}+{"id":"msg-0003","timestamp":"2026-10-23T07:15:19.066Z","type":"gemini","content":"","thoughts":[],"tokens":{"input":10033,"output":108,"cached":0,"thoughts":0,"tool":0,"total":10141},"model":"gemini-3-flash-preview","toolCalls":[{"id":"call-0001","name":"update_topic","args":{"summary":"SUMMARY-PLACEHOLDER","strategic_intent":"STRATEGIC_INTENT-PLACEHOLDER","title":"TITLE-PLACEHOLDER"},"result":[{"functionResponse":{"id":"call-0001","name":"update_topic","response":{"output":"TOOL-OUTPUT-PLACEHOLDER"}}}],"status":"success","timestamp":"2026-10-23T07:15:19.075Z","resultDisplay":"RESULTDISPLAY-PLACEHOLDER","description":"DESCRIPTION-PLACEHOLDER","displayName":"Update Topic Context","renderOutputAsMarkdown":true},{"id":"call-0002","name":"read_file","args":{"file_path":"/Users/dev/project/file_1.js"},"result":[{"functionResponse":{"id":"call-0002","name":"read_file","response":{"output":"TOOL-OUTPUT-PLACEHOLDER"}}}],"status":"success","timestamp":"2026-10-23T07:15:19.075Z","resultDisplay":"RESULTDISPLAY-PLACEHOLDER","description":"DESCRIPTION-PLACEHOLDER","displayName":"ReadFile","renderOutputAsMarkdown":true},{"id":"call-0003","name":"read_file","args":{"file_path":"/Users/dev/project/file_2.js"},"result":[{"functionResponse":{"id":"call-0003","name":"read_file","response":{"output":"TOOL-OUTPUT-PLACEHOLDER"}}}],"status":"success","timestamp":"2026-10-23T07:15:19.075Z","resultDisplay":"RESULTDISPLAY-PLACEHOLDER","description":"DESCRIPTION-PLACEHOLDER","displayName":"ReadFile","renderOutputAsMarkdown":true}]}+{"id":"msg-0004","timestamp":"2026-10-23T07:15:19.077Z","type":"user","content":[{"functionResponse":{"id":"call-0001","name":"update_topic","response":{"output":"TOOL-OUTPUT-PLACEHOLDER"}}},{"functionResponse":{"id":"call-0002","name":"read_file","response":{"output":"TOOL-OUTPUT-PLACEHOLDER"}}},{"functionResponse":{"id":"call-0003","name":"read_file","response":{"output":"TOOL-OUTPUT-PLACEHOLDER"}}}]}+{"$set":{"lastUpdated":"2026-10-23T07:15:19.077Z"}}+{"id":"msg-0005","timestamp":"2026-10-23T07:15:20.695Z","type":"gemini","content":"MODEL-TEXT-PLACEHOLDER-1","thoughts":[],"tokens":{"input":10311,"output":42,"cached":8119,"thoughts":0,"tool":0,"total":10353},"model":"gemini-3-flash-preview"}+{"$set":{"lastUpdated":"2026-10-23T07:15:20.696Z"}}diff --git a/python/tests/core/test_gemini_parser.py b/python/tests/core/test_gemini_parser.pynew file mode 100644index 0000000..5947e4a--- /dev/null+++ b/python/tests/core/test_gemini_parser.py@@ -0,0 +1,339 @@+"""Gemini CLI parser, detection and discovery.++The fixtures under ``fixtures/gemini/`` are three real Gemini CLI 0.65 sessions+with every prompt, reply, thought, path, file content, description, tool+output and command argument replaced by a placeholder. What survives is the+structure: record shapes, ids (renumbered), timestamps, token counts, model,+tool names and statuses, and the shell result labels with their exit code.++* ``read_explain``: reads two files and explains the project.+* ``edit_and_run``: reads a file, rewrites it, runs it.+* ``failed_shell``: runs a missing file (exit code 1), then recovers.+"""++from __future__ import annotations++import hashlib+import json+from pathlib import Path++import pytest++from agentplay import builder, discover+from agentplay._core.ingestion.coding_agent._sources.local.parsers import (+ AgentType,+ detect_agent,+ parse_gemini,+)+from agentplay._core.ingestion.coding_agent._sources.local.source import LocalSource++FIXTURES = Path(__file__).parent / "fixtures" / "gemini"+FIXTURE_ROOT = "/Users/dev/project"+# The fixtures carry a zeroed `projectHash`; tests that need the indexer to+# accept `.project_root` stamp in the hash of FIXTURE_ROOT.+ZERO_HASH = "0" * 64+++def _fixture(name: str) -> bytes:+ return (FIXTURES / f"{name}.jsonl").read_bytes()+++def _parse(name: str):+ _, spans = parse_gemini(_fixture(name), f"local:gemini-cli:{name}")+ return spans+++def _turns(spans):+ return [s for s in spans if s.name.startswith("Turn ")]+++def _tools(spans):+ return [s for s in spans if ":tool:" in s.span_id]+++def _records(name: str) -> list[dict]:+ return [json.loads(line) for line in _fixture(name).splitlines() if line.strip()]+++def _unique_gemini_tokens(name: str) -> list[dict]:+ """The token record of each distinct `gemini` message id (last copy wins)."""+ latest: dict[str, dict] = {}+ for rec in _records(name):+ if rec.get("type") == "gemini":+ latest[rec["id"]] = rec+ return [m["tokens"] for m in latest.values() if "tokens" in m]++[email protected]("name", ["read_explain", "edit_and_run", "failed_shell"])+def test_fixture_is_detected_as_gemini_cli(name):+ assert detect_agent(_fixture(name)) == AgentType.GEMINI_CLI+++def test_claude_code_records_are_not_claimed_as_gemini():+ line = {"type": "user", "sessionId": "s1", "message": {"role": "user", "content": "hi"}}+ assert detect_agent(json.dumps(line).encode()) == AgentType.CLAUDE_CODE+++def test_message_without_header_is_still_detected():+ line = {"id": "g1", "timestamp": "2026-10-23T07:00:00Z", "type": "gemini", "content": ""}+ assert detect_agent(json.dumps(line).encode()) == AgentType.GEMINI_CLI+++ ("name", "tools"),+ [+ ("read_explain", ["update_topic", "Read", "Read"]),+ ("edit_and_run", ["update_topic", "Read", "Write", "Bash"]),+ ("failed_shell", ["Bash", "Bash"]),+ ],+)+def test_turn_and_tool_counts(name, tools):+ spans = _parse(name)+ assert spans[0].name == "Session" and spans[0].parent_id is None+ turns = _turns(spans)+ # One prompt per session; the CLI's `<session_context>` message is not a turn.+ assert len(turns) == 1+ assert turns[0].attributes["input.value"] == "PROMPT-PLACEHOLDER-1"+ assert [s.name for s in _tools(spans)] == tools+ assert all(s.parent_id == turns[0].span_id for s in _tools(spans))+ assert all(s.attributes["tool.name"] == s.name for s in _tools(spans))+++def test_failed_shell_call_is_an_error_and_the_retry_is_not():+ failed, retry = _tools(_parse("failed_shell"))+ # The CLI records `status: success` for both; the exit code is the signal.+ assert failed.status_code == "ERROR"+ assert retry.status_code == "OK"+ assert failed.attributes["code.edit_evidence"]["status"] == "not_successful"+++def test_successful_sessions_have_no_errors():+ for name in ("read_explain", "edit_and_run"):+ assert {s.status_code for s in _tools(_parse(name))} == {"OK"}+++def test_write_records_edit_evidence():+ write = next(s for s in _tools(_parse("edit_and_run")) if s.name == "Write")+ assert json.loads(write.attributes["input.value"])["file_path"] == f"{FIXTURE_ROOT}/file_1.js"+ assert write.attributes["code.edit_evidence"]["status"] != "not_successful"++[email protected]("name", ["read_explain", "edit_and_run", "failed_shell"])+def test_tokens_are_counted_once_per_request(name):+ turn = _turns(_parse(name))[0].attributes+ tokens = _unique_gemini_tokens(name)+ prompt = sum(t["input"] + t["tool"] for t in tokens)+ cached = sum(t["cached"] for t in tokens)+ completion = sum(t["output"] + t["thoughts"] for t in tokens)+ assert turn["llm.token_count.prompt"] == prompt+ assert turn["llm.token_count.cache_read"] == cached+ assert turn["llm.token_count.input_fresh"] == prompt - cached+ assert turn["llm.token_count.completion"] == completion+ assert turn["llm.token_count.reasoning"] == sum(t["thoughts"] for t in tokens)+ assert len(turn["llm.cost_events"]) == len(tokens)+++def test_model_and_session_id():+ root = _parse("failed_shell")[0].attributes+ assert root["llm.model_name"] == "gemini-3.6-flash"+ assert root["harness.agent_session_id"] == "00000000-0000-4000-8000-000000000001"+ assert _parse("read_explain")[0].attributes["llm.model_name"] == "gemini-3-flash-preview"+++def _session(*records: dict) -> bytes:+ header = {"sessionId": "s1", "projectHash": "h", "startTime": "2026-10-23T07:00:00Z", "kind": "main"}+ return b"".join(json.dumps(r).encode() + b"\n" for r in (header, *records))+++def _call(name: str, status: str, response: dict | None = None, **args) -> dict:+ return {+ "id": f"c-{name}-{status}",+ "name": name,+ "args": args,+ "result": [{"functionResponse": {"id": "x", "name": name, "response": response or {"output": "ok"}}}],+ "status": status,+ "timestamp": "2026-10-23T07:00:02Z",+ }+++def test_status_mapping_for_other_tools():+ prompt = {"id": "u1", "timestamp": "2026-10-23T07:00:00Z", "type": "user", "content": [{"text": "go"}]}+ reply = {+ "id": "g1",+ "timestamp": "2026-10-23T07:00:01Z",+ "type": "gemini",+ "content": "",+ "toolCalls": [+ _call("replace", "success", file_path="/p/a.py", old_string="a\n", new_string="b\n"),+ _call("read_file", "error", file_path="/p/missing.py"),+ _call("write_file", "cancelled", file_path="/p/b.py", content="x"),+ _call("grep_search", "success", {"error": "bad pattern"}, pattern="x"),+ _call("run_shell_command", "success", {"output": "Output: (empty)\nSignal: 15"}, command="sleep 9"),+ _call("mcp_server_tool", "success"),+ ],+ }+ tools = _tools(parse_gemini(_session(prompt, reply), "t")[1])+ assert [(s.name, s.status_code) for s in tools] == [+ ("Edit", "OK"),+ ("Read", "ERROR"),+ ("Write", "ERROR"),+ ("Grep", "ERROR"),+ ("Bash", "ERROR"),+ ("mcp_server_tool", "OK"),+ ]+++def test_exit_code_printed_by_the_program_is_not_the_verdict():+ output = "Output: Exit Code: 3\nProcess Group PGID: 1"+ prompt = {"id": "u1", "timestamp": "2026-10-23T07:00:00Z", "type": "user", "content": [{"text": "go"}]}+ reply = {+ "id": "g1",+ "timestamp": "2026-10-23T07:00:01Z",+ "type": "gemini",+ "toolCalls": [_call("run_shell_command", "success", {"output": output}, command="cat log")],+ }+ (tool,) = _tools(parse_gemini(_session(prompt, reply), "t")[1])+ assert tool.status_code == "OK"+++ "data",+ [+ b"",+ b"not json at all\n",+ b"[1, 2]\nnull\n",+ _session(), # header only: a session opened and closed with no prompt+ _session({"$set": {"lastUpdated": "2026-10-23T07:00:09Z"}}),+ _session({"id": "u1", "type": "user", "content": 5, "timestamp": "nope"}),+ _session({"id": "g1", "type": "gemini", "toolCalls": None, "tokens": "many", "model": 3}),+ _session({"id": "g1", "type": "gemini", "toolCalls": [{"name": None, "args": [], "result": "x"}]}),+ ],+)+def test_malformed_or_empty_input_does_not_crash(data):+ trace, spans = parse_gemini(data, "t")+ assert trace.trace_id == "t"+ assert isinstance(spans, list)+++def test_empty_input_yields_no_spans():+ assert parse_gemini(b"", "t")[1] == []+ assert parse_gemini(_session(), "t")[1] == []+++def _map(name: str) -> dict:+ _, spans = parse_gemini(_fixture(name), f"local:gemini-cli:{name}")+ for span in spans:+ if span.parent_id is not None:+ span.attributes["cwd"] = FIXTURE_ROOT+ return builder.build_map_from_spans(spans, session_id=f"local:gemini-cli:{name}", agent_tool="gemini-cli")+++def _fixture_strings(name: str) -> set[str]:+ out: set[str] = set()++ def walk(value):+ if isinstance(value, dict):+ for v in value.values():+ walk(v)+ elif isinstance(value, list):+ for v in value:+ walk(v)+ elif isinstance(value, str):+ out.add(value)++ for rec in _records(name):+ walk(rec)+ return out+++# Strings the map may carry: identifiers the redaction contract allows (model+# and tool names), the CLI's own labels, and values with no free text.+_ALLOWED = {"main", "user", "gemini", "success", "", "gemini-3.6-flash", "gemini-3-flash-preview"}++[email protected]("name", ["read_explain", "edit_and_run", "failed_shell"])+def test_built_map_never_leaks_fixture_text(name):+ doc = _map(name)+ raw = json.dumps(doc)+ for text in _fixture_strings(name):+ if text in _ALLOWED or "PLACEHOLDER" not in text and "ARG-" not in text:+ continue+ # Every placeholder stands for prompt text, model output, a thought, a+ # file's contents, a tool description or output, or a command argument.+ assert text not in raw, text+ # Outside a git repository a path collapses to a bucket label, so neither+ # the absolute path nor the file name may appear.+ for part in ("PLACEHOLDER", "ARG-1", "ARG-2", "session_context", FIXTURE_ROOT, "file_1", "file_2"):+ assert part not in raw, part+ assert doc["session"]["agentTool"] == "gemini-cli"+++def test_built_map_classifies_reads_edits_shell_and_the_failure():+ def kinds(name: str) -> list[tuple]:+ return [(e["kind"], e.get("verb"), e.get("err")) for e in _map(name)["events"] if e.get("tool")]++ assert kinds("read_explain") == [("tool", None, False), ("read", None, False), ("read", None, False)]+ assert kinds("edit_and_run")[1:] == [("read", None, False), ("edit", None, False), ("exec", "node", False)]+ assert kinds("failed_shell") == [("exec", "node", True), ("exec", "node", False)]+ failed = _map("failed_shell")+ assert failed["totals"]["errors"] == 1+ assert failed["session"]["models"] == ["gemini-3.6-flash"]+++def _with_project_hash(data: bytes, root: str) -> bytes:+ """A fixture whose header hashes `root`, as the CLI writes it."""+ real = hashlib.sha256(root.encode("utf-8")).hexdigest()+ return data.replace(ZERO_HASH.encode(), real.encode(), 1)+++def _gemini_home(tmp_path: Path, root: str = FIXTURE_ROOT) -> Path:+ home = tmp_path / ".gemini"+ project = home / "tmp" / "project"+ (project / "chats").mkdir(parents=True)+ (project / ".project_root").write_text(root, encoding="utf-8")+ for name in ("read_explain", "edit_and_run", "failed_shell"):+ (project / "chats" / f"session-2026-10-23T07-00-{name}.jsonl").write_bytes(+ _with_project_hash(_fixture(name), FIXTURE_ROOT)+ )+ (project / "chats" / "session-2026-10-23T07-01-empty.jsonl").write_bytes(_session())+ (project / "logs.json").write_text("[]", encoding="utf-8")+ return home+++def test_local_source_indexes_gemini_sessions(tmp_path):+ source = LocalSource(claude_code_homes=[], codex_homes=[], gemini_homes=[_gemini_home(tmp_path)])+ index = source._build_index()+ # The three fixtures share one renumbered session id; the largest copy wins.+ assert list(index) == ["local:gemini-cli:00000000-0000-4000-8000-000000000001"]+ stats = source.discovery_stats()["gemini-cli"]+ assert stats["skipped"] == {"empty_events": 1}+ sid = next(iter(index))+ assert source.get_cwd(sid) == FIXTURE_ROOT+ assert source.get_project_name(sid) == "project"+ spans = source.get_spans_by_session(sid)+ assert {s.attributes["cwd"] for s in spans if s.parent_id is not None} == {FIXTURE_ROOT}+++def test_project_root_that_does_not_match_the_hash_is_ignored(tmp_path):+ home = _gemini_home(tmp_path, root="/Users/dev/other")+ source = LocalSource(claude_code_homes=[], codex_homes=[], gemini_homes=[home])+ sid = next(iter(source._build_index()))+ assert source.get_cwd(sid) is None+ # The header still hashes FIXTURE_ROOT, so the mismatch is what rejects it.+ header = json.loads(_with_project_hash(_fixture("read_explain"), FIXTURE_ROOT).splitlines()[0])+ assert header["projectHash"] == hashlib.sha256(FIXTURE_ROOT.encode()).hexdigest()++[email protected]("name", ["read_explain", "edit_and_run", "failed_shell"])+def test_fixtures_carry_no_real_project_hash(name):+ assert _records(name)[0]["projectHash"] == ZERO_HASH+++def test_discovery_lists_gemini_cli_with_env_override(tmp_path, monkeypatch):+ assert "gemini-cli" in discover.AGENTS+ monkeypatch.setenv("AGENTPLAY_GEMINI_HOMES", str(tmp_path))+ homes = discover.Homes.default()+ assert homes.gemini_cli == [tmp_path]+ assert homes.present()["gemini-cli"] == [tmp_path]+ monkeypatch.delenv("AGENTPLAY_GEMINI_HOMES")+ assert discover.Homes.default().gemini_cli == [Path.home() / ".gemini"]diff --git a/python/tests/core/test_parser_robustness.py b/python/tests/core/test_parser_robustness.pyindex e4e29ff..35dafc5 100644--- a/python/tests/core/test_parser_robustness.py+++ b/python/tests/core/test_parser_robustness.py@@ -27,6 +27,7 @@ from agentplay._core.ingestion.coding_agent._sources.local.parsers import (parse_copilot_vscode,parse_cursor_agent_transcript,parse_cursor_store,+ parse_gemini,parse_kiro,parse_opencode,)@@ -286,6 +287,36 @@ def _opencode() -> list[dict]:]+def _gemini() -> list[dict]:+ shell = {+ "id": "c1",+ "name": "run_shell_command",+ "args": {"command": "ls", "description": "list"},+ "result": [{"functionResponse": {"id": "c1", "name": "run_shell_command", "response": {"output": "Output: x"}}}],+ "status": "success",+ "timestamp": TS.format(2),+ }+ reply = {+ "id": "g1",+ "timestamp": TS.format(1),+ "type": "gemini",+ "content": "",+ "thoughts": [{"subject": "s", "description": "d", "timestamp": TS.format(1)}],+ "tokens": {"input": 10, "output": 5, "cached": 2, "thoughts": 1, "tool": 0, "total": 16},+ "model": "gemini-3.6-flash",+ }+ return [+ {"sessionId": "s1", "projectHash": "h", "startTime": TS.format(0), "lastUpdated": TS.format(3), "kind": "main"},+ {"id": "u0", "timestamp": TS.format(0), "type": "user", "content": [{"text": "<session_context>x</session_context>"}]},+ {"id": "u1", "timestamp": TS.format(0), "type": "user", "content": [{"text": "list files"}]},+ {"$set": {"lastUpdated": TS.format(1)}},+ reply,+ {**reply, "toolCalls": [shell]},+ {"id": "u2", "timestamp": TS.format(2), "type": "user", "content": [shell["result"][0]]},+ {"id": "g2", "timestamp": TS.format(3), "type": "gemini", "content": "done", "model": "gemini-3.6-flash"},+ ]++PARSERS = {"claude_code": (parse_claude_code, _claude),"codex": (parse_codex, _codex),@@ -293,6 +324,7 @@ PARSERS = {"copilot_vscode": (parse_copilot_vscode, _copilot_vscode),"cursor_store": (parse_cursor_store, _cursor_store),"cursor_agent": (parse_cursor_agent_transcript, _cursor_agent),+ "gemini": (parse_gemini, _gemini),"kiro": (parse_kiro, _kiro),"opencode": (parse_opencode, _opencode),}diff --git a/python/tests/core/test_tool_taxonomy.py b/python/tests/core/test_tool_taxonomy.pyindex 5596410..cd57e17 100644--- a/python/tests/core/test_tool_taxonomy.py+++ b/python/tests/core/test_tool_taxonomy.py@@ -14,6 +14,7 @@ from agentplay._core.ingestion.coding_agent._sources.local.parsers import (copilot,cursor_agent_transcript,cursor_store,+ gemini,kiro,opencode,)@@ -26,6 +27,7 @@ from agentplay._core.ingestion.coding_agent._sources.local.parsers import ((cursor_store, "cursor"),(cursor_agent_transcript, "cursor"),(copilot, "copilot"),+ (gemini, "gemini-cli"),(kiro, "kiro"),(opencode, "opencode"),],@@ -45,6 +47,10 @@ def test_every_parser_reads_the_shared_table(module, agent) -> None:("cursor", "Subagent", "Task"),("copilot", "str_replace_editor", "Edit"),("copilot", "view", "Read"),+ ("gemini-cli", "run_shell_command", "Bash"),+ ("gemini-cli", "read_file", "Read"),+ ("gemini-cli", "replace", "Edit"),+ ("gemini-cli", "write_file", "Write"),("kiro", "execute_bash", "Bash"),("opencode", "todowrite", "TodoWrite"),],@@ -63,12 +69,14 @@ def test_unknown_and_claude_names_pass_through() -> None:def test_table_sizes_are_pinned() -> None:# These counts are pinned; a changed count means a row was added or dropped on purpose -- update here.- # copilot-vscode's 12 rows are pinned against real tool names.+ # copilot-vscode's 12 rows are pinned against real tool names; gemini-cli's+ # 12 against real sessions plus the 0.65 bundle's tool-name constants.assert {a: len(t) for a, t in tt.TOOL_ALIASES.items()} == {"codex": 7,"cursor": 26,"copilot": 23,"copilot-vscode": 12,+ "gemini-cli": 12,"kiro": 12,"opencode": 14,}