Replay your coding agent sessions as a map and a timeline
Python agent-observabilityai-agentsclaudeclaude-codecodexcoding-agentscursordeveloper-toolsdevtoolsgithub-copilotkirollmobservabilityopencodeprivacypythonsession-replaytypescriptvisualization
fix(gemini): bound and harden the discovery scan
shubhook6d7ce90e2b4e
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 d17a336..9a7d8ae 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@@ -24,6 +24,7 @@ from agentplay._core.ingestion.coding_agent._sources._base import (MAX_SESSION_BYTES,OversizedSessionError,)+from agentplay.discover import MAX_SOURCE_BYTESfrom agentplay._core.ingestion.coding_agent._sources.local.parsers import (AgentType,detect_agent,@@ -37,6 +38,9 @@ from agentplay._core.ingestion.coding_agent._sources.local.parsers import (parse_kiro,parse_opencode,)+from agentplay._core.ingestion.coding_agent._sources.local.parsers.gemini import (+ _user_prompt as _gemini_user_prompt,+)from agentplay._core.ingestion.coding_agent.spans import DiscoveredSession, SpanDatalogger = logging.getLogger(__name__)@@ -1130,52 +1134,35 @@ def _gemini_header(head: bytes) -> dict | None:return None-# Injected as the first user message of every Gemini CLI session. Not a prompt.-# The same prefix `parsers.gemini._user_prompt` ignores.-_GEMINI_SESSION_CONTEXT_PREFIX = "<session_context>"---def _gemini_user_counts(content: object) -> bool:- """True when a `user` record carries prompt text, plus tool-result records.-- Empty text and the CLI's `<session_context>` block are ignored, the same- filter as `parsers.gemini._user_prompt` (`text` must be non-empty and not- that prefix). A tool-result record has no text parts and still counts.- """- if isinstance(content, str):- texts = [content]- elif isinstance(content, list):- texts = [- part["text"]- for part in content- if isinstance(part, dict) and isinstance(part.get("text"), str)- ]- else:- return True- if not texts:- return True- return any(text and not text.lstrip().startswith(_GEMINI_SESSION_CONTEXT_PREFIX) for text in texts)--def _gemini_has_messages(path: Path) -> bool:"""True when the file holds a real prompt or a `gemini` message.Streams one line at a time and stops at the first qualifying record, so a- prompt that sits past `_read_head` (after a multi-MB `<session_context>`- line) is still found. A file of only the header, that context block, or- empty user text is skipped at EOF, same as `_kiro_event_count == 0`.- The whole transcript is never held at once.+ prompt that sits past `_read_head` is still found. Reads at most+ ``MAX_SOURCE_BYTES``. A file of only the header or user content+ ``_user_prompt`` rejects is skipped at EOF. A ``RecursionError`` from a+ deeply nested record skips that line instead of aborting the index."""+ remaining = MAX_SOURCE_BYTESwith path.open("rb") as handle:- for line in handle:+ while remaining > 0:+ line = handle.readline(remaining)+ if not line:+ break+ remaining -= len(line)+ # `readline(n)` cuts a line at n bytes. A partial record is not JSON.+ if remaining == 0 and not line.endswith(b"\n"):+ breaktry:obj = json.loads(line)- except ValueError:+ except (ValueError, RecursionError):continueif not isinstance(obj, dict):continuekind = obj.get("type")- if kind == "gemini" or (kind == "user" and _gemini_user_counts(obj.get("content"))):+ if kind == "gemini" or (+ kind == "user" and _gemini_user_prompt(obj.get("content")) is not None+ ):return Truereturn False@@ -1946,6 +1933,12 @@ class LocalSource:if size == 0:self._record_discovery("gemini-cli", "empty_or_unreadable")return None+ # `build_map` refuses the same cap with SkipSession("too_large"). Skip+ # here, before any read, so discovery does not allocate the file.+ if size > MAX_SOURCE_BYTES:+ logger.debug("gemini-cli: %s exceeds the source byte cap; session skipped", jsonl_file)+ self._record_discovery("gemini-cli", "too_large")+ return Nonetry:head = _read_head(jsonl_file, stop_when=_agent_detected)except OSError:diff --git a/python/tests/core/test_gemini_parser.py b/python/tests/core/test_gemini_parser.pyindex 2465922..df2cc08 100644--- a/python/tests/core/test_gemini_parser.py+++ b/python/tests/core/test_gemini_parser.py@@ -21,6 +21,7 @@ import pytestfrom agentplay import builder, discoverfrom agentplay._core.code_authorship import extract_edit_evidence+from agentplay._core.ingestion.coding_agent._sources.local import source as local_sourcefrom agentplay._core.ingestion.coding_agent._sources.local.parsers import (AgentType,detect_agent,@@ -495,6 +496,94 @@ def test_prompt_past_the_head_is_indexed_and_empty_sessions_are_skipped(tmp_pathassert source.discovery_stats()["gemini-cli"]["skipped"]["empty_events"] == 2+def _chats(tmp_path: Path) -> Path:+ home = tmp_path / ".gemini"+ chats = home / "tmp" / "project" / "chats"+ chats.mkdir(parents=True)+ (chats.parent / ".project_root").write_text(FIXTURE_ROOT, encoding="utf-8")+ return chats+++def _user_record(msg_id: str, content: object) -> dict:+ return {"id": msg_id, "timestamp": "2026-10-23T07:02:00Z", "type": "user", "content": content}+++def test_non_prompt_user_content_is_skipped_as_empty_events(tmp_path):+ # Same shapes `_user_prompt` refuses: a non-text value, empty text, and+ # the CLI's context block. Each file is only that record.+ chats = _chats(tmp_path)+ context = "<session_context>\nCONTEXT-PLACEHOLDER\n</session_context>"+ cases = {+ "number": 5,+ "blank": "",+ "empty-part": [{"text": ""}],+ "context": [{"text": context}],+ }+ for session_id, content in cases.items():+ (chats / f"session-{session_id}.jsonl").write_bytes(+ _session(_user_record("u0", content), session_id=session_id)+ )+ source = LocalSource(claude_code_homes=[], codex_homes=[], gemini_homes=[chats.parents[2]])+ index = source._build_index()+ assert set(index) == set()+ assert source.discovery_stats()["gemini-cli"]["skipped"]["empty_events"] == len(cases)+++def test_deeply_nested_json_line_does_not_abort_discovery(tmp_path, monkeypatch):+ nested = b'{"a":' * 1200 + b"0" + b"}" * 1200+ try:+ json.loads(nested)+ except RecursionError:+ pass+ else:+ # Python 3.15 parses this depth. Older interpreters raise here, which+ # is the failure the scan has to survive, so reproduce it.+ real_loads = local_source.json.loads++ def loads(raw, *args, **kwargs):+ text = raw.decode("utf-8", "replace") if isinstance(raw, (bytes, bytearray)) else raw+ if isinstance(text, str) and text.startswith('{"a":' * 40):+ raise RecursionError("maximum recursion depth exceeded")+ return real_loads(raw, *args, **kwargs)++ monkeypatch.setattr(local_source.json, "loads", loads)++ chats = _chats(tmp_path)+ prompt = _user_record("u1", [{"text": "PROMPT-PLACEHOLDER-1"}])+ prompt_line = json.dumps(prompt).encode() + b"\n"+ header = json.dumps(+ {"sessionId": "nested-then-prompt", "projectHash": "h", "startTime": "2026-10-23T07:00:00Z", "kind": "main"}+ ).encode() + b"\n"+ (chats / "session-nested-then-prompt.jsonl").write_bytes(header + nested + b"\n" + prompt_line)+ only = header.replace(b"nested-then-prompt", b"nested-only")+ (chats / "session-nested-only.jsonl").write_bytes(only + nested + b"\n")++ source = LocalSource(claude_code_homes=[], codex_homes=[], gemini_homes=[chats.parents[2]])+ index = source._build_index()+ assert "local:gemini-cli:nested-then-prompt" in index+ assert "local:gemini-cli:nested-only" not in index+ assert source.discovery_stats()["gemini-cli"]["skipped"]["empty_events"] == 1+++def test_oversized_transcript_is_skipped_as_too_large(tmp_path, monkeypatch):+ # The real cap is 512MB. Lower it so the test file is over the cap without+ # writing one. The prompt sits at the start, so a scan that ignored the+ # size and stopped at the cap would still index this session.+ monkeypatch.setattr(local_source, "MAX_SOURCE_BYTES", 800)+ chats = _chats(tmp_path)+ prompt = _user_record("u1", [{"text": "PROMPT-PLACEHOLDER-1"}])+ (chats / "session-small.jsonl").write_bytes(_session(prompt, session_id="small"))+ huge = _session(prompt, {"id": "pad", "type": "info", "content": "x" * 2000}, session_id="huge")+ assert len(huge) > 800+ (chats / "session-huge.jsonl").write_bytes(huge)++ source = LocalSource(claude_code_homes=[], codex_homes=[], gemini_homes=[chats.parents[2]])+ index = source._build_index()+ assert "local:gemini-cli:small" in index+ assert "local:gemini-cli:huge" not in index+ assert source.discovery_stats()["gemini-cli"]["skipped"]["too_large"] == 1++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()