Skip to content

Replay your coding agent sessions as a map and a timeline

fix(gemini): keep file paths under truncation, skip context-only sessions

shubhook846fc781181f
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.py
index 07bcace..7f80fe9 100644
--- 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.py
@@ -80,6 +80,14 @@ _SESSION_CONTEXT_PREFIX = "<session_context>"
_SHELL_TOOL = "run_shell_command"
+# Path arguments, `file_path` first. `input.value` keeps 2,000 characters, and
+# Gemini records `content` ahead of `file_path` on `write_file`, so a large
+# write used to lose the path. `dir_path` is the directory argument on
+# list/search/shell. The rest are keys edit evidence and the CLI's own path
+# helper already accept. Hoisting them does not change the argument values
+# `extract_edit_evidence` reads.
+_PATH_KEYS = ("file_path", "dir_path", "path", "absolute_path", "filePath")
+
# The labels the CLI may append after `Output: ...`, last first. The result is
# read from its last line upward, each label at most once and only in this
# order, so a label line inside the program's output ends the scan.
@@ -330,7 +338,7 @@ def _tool_span(trace_id: str, turn: dict, msg: dict, call: dict, index: int) ->
tool_name = _TOOL_ALIASES.get(raw_name, raw_name)
args = call.get("args")
- input_value = json.dumps(args) if isinstance(args, dict) else "{}"
+ input_value = json.dumps(_path_keys_first(args)) if isinstance(args, dict) else "{}"
response = _response(call)
output_value = _output_text(response)
@@ -373,6 +381,13 @@ def _tool_span(trace_id: str, turn: dict, msg: dict, call: dict, index: int) ->
return span
+def _path_keys_first(args: dict) -> dict:
+ """A copy of `args` with path keys emitted before everything else."""
+ first = {key: args[key] for key in _PATH_KEYS if key in args}
+ rest = {key: value for key, value in args.items() if key not in first}
+ return {**first, **rest}
+
+
def _response(call: dict) -> dict:
"""The `functionResponse.response` object of a tool call's result."""
result = call.get("result")
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.py
index bd6afc2..73901a6 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
@@ -1130,18 +1130,49 @@ 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 unless every text part is the CLI's synthetic `<session_context>`.
+
+ A tool-result `user` record has no text parts and still counts. A record
+ that is only the context block does not: the parser opens no turn for it.
+ """
+ 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(not text.lstrip().startswith(_GEMINI_SESSION_CONTEXT_PREFIX) for text in texts)
+
+
def _gemini_has_messages(head: bytes) -> bool:
- """True when the head holds a `user` or `gemini` message, not only the header.
+ """True when the head holds a real prompt or a `gemini` message.
- 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`.
+ A session opened and closed without a prompt is the header plus the CLI's
+ `<session_context>` user record. That record is not a turn, so the file
+ has nothing to map and is an `empty_events` skip, same as a header-only
+ file and `_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"):
+ if not isinstance(obj, dict):
+ continue
+ kind = obj.get("type")
+ if kind == "gemini" or (kind == "user" and _gemini_user_counts(obj.get("content"))):
return True
return False
diff --git a/python/tests/core/test_gemini_parser.py b/python/tests/core/test_gemini_parser.py
index b3827f3..dd9693a 100644
--- a/python/tests/core/test_gemini_parser.py
+++ b/python/tests/core/test_gemini_parser.py
@@ -20,12 +20,14 @@ from pathlib import Path
import pytest
from agentplay import builder, discover
+from agentplay._core.code_authorship import extract_edit_evidence
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
+from agentplay._core.ingestion.coding_agent.file_paths import extract_file_path
FIXTURES = Path(__file__).parent / "fixtures" / "gemini"
FIXTURE_ROOT = "/Users/dev/project"
@@ -118,6 +120,43 @@ def test_write_records_edit_evidence():
assert write.attributes["code.edit_evidence"]["status"] != "not_successful"
+def test_path_keys_survive_truncation_and_edit_evidence_keeps_the_full_write():
+ # Gemini records `content` before `file_path`. A write larger than the
+ # 2,000-character input cap used to shear the path off the retained prefix.
+ content = "kept-line\n" + ("x" * 4000)
+ file_path = f"{FIXTURE_ROOT}/file_1.js"
+ dir_path = FIXTURE_ROOT
+ args = {
+ "content": content,
+ "instruction": "y" * 500,
+ "dir_path": dir_path,
+ "file_path": file_path,
+ }
+ 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": [
+ {
+ "id": "c-write",
+ "name": "write_file",
+ "args": args,
+ "result": [{"functionResponse": {"id": "x", "name": "write_file", "response": {"output": "ok"}}}],
+ "status": "success",
+ "timestamp": "2026-10-23T07:00:02Z",
+ }
+ ],
+ }
+ (tool,) = _tools(parse_gemini(_session(prompt, reply), "t")[1])
+ recorded = tool.attributes["input.value"]
+ assert len(recorded) <= 2000
+ assert recorded.startswith('{"file_path":')
+ assert extract_file_path(recorded) == file_path
+ assert f'"dir_path": {json.dumps(dir_path)}' in recorded
+ assert tool.attributes["code.edit_evidence"] == extract_edit_evidence("Write", args, successful=True)
+
+
@pytest.mark.parametrize("name", ["read_explain", "edit_and_run", "failed_shell"])
def test_tokens_are_counted_once_per_request(name):
turn = _turns(_parse(name))[0].attributes
@@ -140,8 +179,13 @@ def test_model_and_session_id():
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"}
+def _session(*records: dict, session_id: str = "s1") -> bytes:
+ header = {
+ "sessionId": session_id,
+ "projectHash": "h",
+ "startTime": "2026-10-23T07:00:00Z",
+ "kind": "main",
+ }
return b"".join(json.dumps(r).encode() + b"\n" for r in (header, *records))
@@ -341,6 +385,52 @@ def _gemini_home(tmp_path: Path, root: str = FIXTURE_ROOT) -> Path:
return home
+def _context_user(msg_id: str, *texts: str) -> dict:
+ return {
+ "id": msg_id,
+ "timestamp": "2026-10-23T07:02:00Z",
+ "type": "user",
+ "content": [{"text": text} for text in texts],
+ }
+
+
+def test_context_only_session_is_skipped_as_empty_events(tmp_path):
+ home = _gemini_home(tmp_path)
+ chats = home / "tmp" / "project" / "chats"
+ context = "<session_context>\nCONTEXT-PLACEHOLDER\n</session_context>"
+ (chats / "session-context-only.jsonl").write_bytes(
+ _session(_context_user("u0", context), session_id="context-only")
+ )
+ # A context block plus a real prompt is a session. So is model output
+ # that arrived with no prompt of its own.
+ (chats / "session-context-plus-prompt.jsonl").write_bytes(
+ _session(
+ _context_user("u1", context, "PROMPT-PLACEHOLDER-1"),
+ session_id="context-plus-prompt",
+ )
+ )
+ (chats / "session-context-and-model.jsonl").write_bytes(
+ _session(
+ _context_user("u2", context),
+ {
+ "id": "g1",
+ "timestamp": "2026-10-23T07:03:01Z",
+ "type": "gemini",
+ "content": "MODEL-TEXT-PLACEHOLDER",
+ "model": "gemini-3-flash-preview",
+ },
+ session_id="context-and-model",
+ )
+ )
+ source = LocalSource(claude_code_homes=[], codex_homes=[], gemini_homes=[home])
+ index = source._build_index()
+ assert "local:gemini-cli:context-only" not in index
+ assert "local:gemini-cli:context-plus-prompt" in index
+ assert "local:gemini-cli:context-and-model" in index
+ # Header-only file from `_gemini_home`, plus the context-only session.
+ assert source.discovery_stats()["gemini-cli"]["skipped"]["empty_events"] == 2
+
+
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()