diff --git a/claude_code_log/providers/agy.py b/claude_code_log/providers/agy.py index 1426608f..26283de3 100644 --- a/claude_code_log/providers/agy.py +++ b/claude_code_log/providers/agy.py @@ -1,12 +1,19 @@ """Antigravity CLI (agy) session provider.""" +from collections import deque import json import logging import re from pathlib import Path from typing import Any, Iterator, Optional, cast -from claude_code_log.models import TranscriptEntry +from claude_code_log.models import ( + AssistantTranscriptEntry, + SystemTranscriptEntry, + ToolResultContent, + TranscriptEntry, + UsageInfo, +) from .base import ( BaseProvider, @@ -14,11 +21,79 @@ extract_text, file_mtime_iso, make_assistant_entry, + make_thinking_entry, + make_tool_result_entry, + make_tool_use_entry, make_user_entry, ) logger = logging.getLogger(__name__) +_DEFAULT_MODEL = "antigravity" +_TOOL_ERROR_STATUSES = frozenset({"ERROR", "CANCELED", "INVALID"}) + + +def _as_optional_int(value: Any) -> Optional[int]: + """Return an int token count, rejecting booleans and non-integers.""" + if isinstance(value, int) and not isinstance(value, bool): + return value + return None + + +def _reject_json_constant(token: str) -> Any: + """Reject non-standard JSON constants (NaN, Infinity, -Infinity).""" + raise ValueError(f"Non-standard JSON constant: {token}") + + +def _decode_arg_value(value: Any) -> Any: + """Decode Antigravity's JSON-encoded scalar/container argument strings. + + Antigravity transcripts serialize each tool argument value as a JSON string + (e.g. ``Path: '"/tmp/a.py"'``, ``StartLine: '1'``). Decoding valid JSON + values recovers clean native types for tool renderers while leaving plain, + non-standard (NaN/Infinity), or truncated strings intact. + """ + if not isinstance(value, str): + return value + stripped = value.strip() + if not stripped: + return value + try: + return json.loads(stripped, parse_constant=_reject_json_constant) + except (json.JSONDecodeError, ValueError): + return value + + +def _decode_tool_args(args_raw: Any) -> dict[str, Any]: + if not isinstance(args_raw, dict): + return {} + raw_dict = cast(dict[str, Any], args_raw) + return {str(k): _decode_arg_value(v) for k, v in raw_dict.items()} + + +def _make_system_entry( + session_id: str, + uuid: str, + timestamp: str, + content: str, + *, + level: str = "info", + parent_uuid: Optional[str] = None, +) -> SystemTranscriptEntry: + return SystemTranscriptEntry( + type="system", + parentUuid=parent_uuid, + isSidechain=False, + userType="external", + cwd="", + sessionId=session_id, + version="", + uuid=uuid, + timestamp=timestamp, + content=content, + level=level, + ) + class AgyProvider(BaseProvider): def get_provider_name(self) -> str: @@ -43,10 +118,8 @@ def discover_sessions(self) -> Iterator[SessionInfo]: for session_dir in sorted(brain_dir.iterdir()): if not session_dir.is_dir(): continue - transcript_file = ( - session_dir / ".system_generated" / "logs" / "transcript.jsonl" - ) - if not transcript_file.exists(): + transcript_file = self._resolve_transcript_file(session_dir) + if transcript_file is None: continue yield SessionInfo( provider="agy", @@ -64,21 +137,17 @@ def load_session( if data_dir is None: raise ValueError("Antigravity CLI data directory not found") - transcript_file = ( - data_dir - / "brain" - / session_id - / ".system_generated" - / "logs" - / "transcript.jsonl" - ) - if not transcript_file.exists(): + session_dir = data_dir / "brain" / session_id + transcript_file = self._resolve_transcript_file(session_dir) + if transcript_file is None: + expected = session_dir / ".system_generated" / "logs" / "transcript.jsonl" raise FileNotFoundError( - f"Transcript for session {session_id} not found at {transcript_file}" + f"Transcript for session {session_id} not found at {expected}" ) prev_uuid: Optional[str] = None message_count = 0 + pending_tool_calls: deque[tuple[str, str]] = deque() with open(transcript_file, "r", encoding="utf-8") as f: for line in f: @@ -97,7 +166,11 @@ def load_session( if isinstance(raw_entry, dict): entry = cast(dict[str, Any], raw_entry) for transcript_entry in self._parse_entry( - entry, session_id, message_count, prev_uuid + entry, + session_id, + message_count, + prev_uuid, + pending_tool_calls, ): if max_messages is not None and message_count >= max_messages: return @@ -112,34 +185,60 @@ def _parse_entry( session_id: str, index: int, parent_uuid: Optional[str], + pending_tool_calls: deque[tuple[str, str]], ) -> Iterator[TranscriptEntry]: - entry_type = str(entry.get("type", "")) - timestamp = str(entry.get("created_at", "")) - content = entry.get("content", "") + entry_type = str(entry.get("type") or "") + timestamp = str(entry.get("created_at") or "") + raw_content = entry.get("content") + content: Any = "" if raw_content is None else raw_content if entry_type == "USER_INPUT": + pending_tool_calls.clear() yield from self._parse_user_input( content, session_id, index, timestamp, parent_uuid ) elif entry_type == "PLANNER_RESPONSE": yield from self._parse_planner_response( - entry, content, session_id, index, timestamp, parent_uuid + entry, + content, + session_id, + index, + timestamp, + parent_uuid, + pending_tool_calls, ) elif entry_type == "CHECKPOINT": + pending_tool_calls.clear() yield from self._parse_checkpoint( content, session_id, index, timestamp, parent_uuid ) + elif entry_type == "SYSTEM_MESSAGE": + yield from self._parse_system_message( + content, session_id, index, timestamp, parent_uuid + ) + + elif entry_type == "ERROR_MESSAGE": + yield from self._parse_error_message( + entry, content, session_id, index, timestamp, parent_uuid + ) + elif entry_type == "LIST_DIRECTORY": - yield from self._make_tool_entry( - "list_dir", content, session_id, index, timestamp, parent_uuid + yield from self._make_legacy_tool_pair( + "list_dir", {}, content, session_id, index, timestamp, parent_uuid ) elif entry_type == "GENERIC": yield from self._parse_generic( - content, session_id, index, timestamp, parent_uuid + entry, + content, + session_id, + index, + timestamp, + parent_uuid, + pending_tool_calls, ) elif entry_type == "RUN_COMMAND": @@ -185,22 +284,71 @@ def _parse_planner_response( index: int, timestamp: str, parent_uuid: Optional[str], + pending_tool_calls: deque[tuple[str, str]], ) -> Iterator[TranscriptEntry]: + model = self._extract_model(raw_entry) + usage = self._extract_usage(raw_entry) + thinking_raw = raw_entry.get("thinking") + thinking = thinking_raw.strip() if isinstance(thinking_raw, str) else "" text = content if isinstance(content, str) else json.dumps(content) - tool_calls_raw = raw_entry.get("tool_calls", []) - tool_calls = self._coerce_tool_calls(tool_calls_raw) + tool_calls = self._coerce_tool_calls(raw_entry.get("tool_calls", [])) - if tool_calls: - yield from self._parse_tool_calls( - tool_calls, text, session_id, index, timestamp, parent_uuid + emitted: list[AssistantTranscriptEntry] = [] + last_uuid = parent_uuid + + # A new planner turn supersedes any unclosed tool calls from earlier turns. + pending_tool_calls.clear() + + if thinking: + uid = f"agy-{session_id}-{index}-thinking" + thinking_entry = make_thinking_entry( + session_id, uid, timestamp, model, thinking ) + thinking_entry.parentUuid = last_uuid + last_uuid = uid + emitted.append(thinking_entry) + + if tool_calls: + for tc_index, tc in enumerate(tool_calls): + name = str(tc.get("name", "unknown")) + decoded_args = _decode_tool_args(tc.get("args")) + tool_id = f"agy-{session_id}-{index}-{tc_index}-{name}" + tool_entry = make_tool_use_entry( + session_id, + tool_id, + timestamp, + model, + tool_id, + name, + decoded_args, + ) + tool_entry.parentUuid = last_uuid + last_uuid = tool_id + pending_tool_calls.append((tool_id, name)) + emitted.append(tool_entry) + + if text and not text.startswith("[tool:"): + uid = f"agy-{session_id}-{index}-response" + text_entry = make_assistant_entry( + session_id, uid, timestamp, model, text + ) + text_entry.parentUuid = last_uuid + last_uuid = uid + emitted.append(text_entry) elif text: uid = f"agy-{session_id}-{index}" - entry = make_assistant_entry( - session_id, uid, timestamp, "antigravity", text - ) - entry.parentUuid = parent_uuid - yield entry + text_entry = make_assistant_entry(session_id, uid, timestamp, model, text) + text_entry.parentUuid = last_uuid + last_uuid = uid + emitted.append(text_entry) + + # Attach token usage to exactly one entry per PLANNER_RESPONSE so + # session totals are accurate without double counting. Choosing the + # final entry puts usage on the visible assistant text when present. + if usage is not None and emitted: + emitted[-1].message.usage = usage + + yield from emitted def _parse_checkpoint( self, @@ -210,30 +358,104 @@ def _parse_checkpoint( timestamp: str, parent_uuid: Optional[str], ) -> Iterator[TranscriptEntry]: - """CHECKPOINT entries are compaction summaries — render as system context.""" + """CHECKPOINT entries are compaction summaries — render as system info.""" text = content if isinstance(content, str) else json.dumps(content) if text: uid = f"agy-{session_id}-{index}" - entry = make_assistant_entry( - session_id, uid, timestamp, "antigravity", f"[checkpoint]\n{text}" + yield _make_system_entry( + session_id, + uid, + timestamp, + f"[checkpoint]\n{text}", + level="info", + parent_uuid=parent_uuid, + ) + + def _parse_system_message( + self, + content: Any, + session_id: str, + index: int, + timestamp: str, + parent_uuid: Optional[str], + ) -> Iterator[TranscriptEntry]: + """SYSTEM_MESSAGE entries are harness notices injected into the loop.""" + text = extract_text(content).strip() + if text: + uid = f"agy-{session_id}-{index}" + yield _make_system_entry( + session_id, + uid, + timestamp, + text, + level="info", + parent_uuid=parent_uuid, + ) + + def _parse_error_message( + self, + raw_entry: dict[str, Any], + content: Any, + session_id: str, + index: int, + timestamp: str, + parent_uuid: Optional[str], + ) -> Iterator[TranscriptEntry]: + """ERROR_MESSAGE entries record API/transport errors in the `error` field.""" + error_raw = raw_entry.get("error") + text = ( + extract_text(error_raw).strip() + if error_raw is not None + else extract_text(content).strip() + ) + if text: + uid = f"agy-{session_id}-{index}" + yield _make_system_entry( + session_id, + uid, + timestamp, + text, + level="error", + parent_uuid=parent_uuid, ) - entry.parentUuid = parent_uuid - yield entry def _parse_generic( self, + raw_entry: dict[str, Any], content: Any, session_id: str, index: int, timestamp: str, parent_uuid: Optional[str], + pending_tool_calls: deque[tuple[str, str]], ) -> Iterator[TranscriptEntry]: - """GENERIC entries are uncategorized model output.""" + """GENERIC entries carry tool execution results for preceding tool_calls. + + Antigravity emits one GENERIC record per tool call in FIFO order. When + a matching pending tool_call exists, emit a structured ToolResultContent + so depth filtering (`--depth assistant`) and tool pairing work properly. + Fall back to plain assistant text only for orphaned GENERIC records. + """ text = extract_text(content) + if pending_tool_calls: + tool_use_id, _tool_name = pending_tool_calls.popleft() + uid = f"agy-{session_id}-{index}" + result_entry = make_tool_result_entry( + session_id, uid, timestamp, tool_use_id, text + ) + result_entry.parentUuid = parent_uuid + status = str(raw_entry.get("status", "")).upper() + if status in _TOOL_ERROR_STATUSES: + first_item = result_entry.message.content[0] + if isinstance(first_item, ToolResultContent): + first_item.is_error = True + yield result_entry + return + if text: uid = f"agy-{session_id}-{index}" entry = make_assistant_entry( - session_id, uid, timestamp, "antigravity", text + session_id, uid, timestamp, _DEFAULT_MODEL, text ) entry.parentUuid = parent_uuid yield entry @@ -247,16 +469,18 @@ def _parse_run_command( timestamp: str, parent_uuid: Optional[str], ) -> Iterator[TranscriptEntry]: - """RUN_COMMAND entries are shell command executions.""" - command = str(raw_entry.get("command", "")) - text = content if isinstance(content, str) else json.dumps(content) - display = ( - f"[run_command: {command}]\n{text}" if command else f"[run_command]\n{text}" + """RUN_COMMAND entries are legacy shell command executions.""" + command = str(raw_entry.get("command") or "") + tool_input: dict[str, Any] = {"command": command} if command else {} + yield from self._make_legacy_tool_pair( + "run_command", + tool_input, + content, + session_id, + index, + timestamp, + parent_uuid, ) - uid = f"agy-{session_id}-{index}" - entry = make_assistant_entry(session_id, uid, timestamp, "antigravity", display) - entry.parentUuid = parent_uuid - yield entry def _parse_view_file( self, @@ -267,16 +491,12 @@ def _parse_view_file( timestamp: str, parent_uuid: Optional[str], ) -> Iterator[TranscriptEntry]: - """VIEW_FILE entries are file reads.""" - file_path = str(raw_entry.get("file_path", raw_entry.get("path", ""))) - text = content if isinstance(content, str) else json.dumps(content) - display = ( - f"[view_file: {file_path}]\n{text}" if file_path else f"[view_file]\n{text}" + """VIEW_FILE entries are legacy file reads.""" + file_path = str(raw_entry.get("file_path") or raw_entry.get("path") or "") + tool_input: dict[str, Any] = {"file_path": file_path} if file_path else {} + yield from self._make_legacy_tool_pair( + "view_file", tool_input, content, session_id, index, timestamp, parent_uuid ) - uid = f"agy-{session_id}-{index}" - entry = make_assistant_entry(session_id, uid, timestamp, "antigravity", display) - entry.parentUuid = parent_uuid - yield entry def _parse_code_action( self, @@ -287,22 +507,30 @@ def _parse_code_action( timestamp: str, parent_uuid: Optional[str], ) -> Iterator[TranscriptEntry]: - """CODE_ACTION entries are code modifications (edits, writes).""" - action = str(raw_entry.get("action", "")) - file_path = str(raw_entry.get("file_path", raw_entry.get("path", ""))) - text = content if isinstance(content, str) else json.dumps(content) - label = f"[code_action: {action} {file_path}]".strip() - display = f"{label}\n{text}" if text else label - uid = f"agy-{session_id}-{index}" - entry = make_assistant_entry(session_id, uid, timestamp, "antigravity", display) - entry.parentUuid = parent_uuid - yield entry + """CODE_ACTION entries are legacy code modifications (edits, writes).""" + action = str(raw_entry.get("action") or "") + file_path = str(raw_entry.get("file_path") or raw_entry.get("path") or "") + tool_input: dict[str, Any] = {} + if action: + tool_input["action"] = action + if file_path: + tool_input["file_path"] = file_path + yield from self._make_legacy_tool_pair( + "code_action", + tool_input, + content, + session_id, + index, + timestamp, + parent_uuid, + ) # -- Helpers -- - def _make_tool_entry( + def _make_legacy_tool_pair( self, tool_name: str, + tool_input: dict[str, Any], content: Any, session_id: str, index: int, @@ -310,53 +538,46 @@ def _make_tool_entry( parent_uuid: Optional[str], ) -> Iterator[TranscriptEntry]: text = content if isinstance(content, str) else json.dumps(content) - if text: - uid = f"agy-{session_id}-{index}" - entry = make_assistant_entry( - session_id, - uid, - timestamp, - "antigravity", - f"[tool: {tool_name}]\n{text}", - ) - entry.parentUuid = parent_uuid - yield entry - - def _parse_tool_calls( - self, - tool_calls: list[dict[str, Any]], - fallback_text: str, - session_id: str, - index: int, - timestamp: str, - parent_uuid: Optional[str], - ) -> Iterator[TranscriptEntry]: - last_uuid = parent_uuid - - for tc_index, tc in enumerate(tool_calls): - name = str(tc.get("name", "unknown")) - args_raw = tc.get("args", {}) - args: dict[str, Any] = ( - cast(dict[str, Any], args_raw) if isinstance(args_raw, dict) else {} - ) - args_str = json.dumps(args, indent=2) if args else "" - text = f"[tool: {name}]\n{args_str}" if args_str else f"[tool: {name}]" - uid = f"agy-{session_id}-{index}-{tc_index}-{name}" - entry = make_assistant_entry( - session_id, uid, timestamp, "antigravity", text - ) - entry.parentUuid = last_uuid - last_uuid = uid - yield entry + if not tool_input and not text: + return + tool_id = f"agy-{session_id}-{index}-{tool_name}" + use_entry = make_tool_use_entry( + session_id, + tool_id, + timestamp, + _DEFAULT_MODEL, + tool_id, + tool_name, + tool_input, + ) + use_entry.parentUuid = parent_uuid + yield use_entry - # Emit the response text after tool calls, chained to the last tool - if fallback_text and not fallback_text.startswith("[tool:"): - uid = f"agy-{session_id}-{index}-response" - entry = make_assistant_entry( - session_id, uid, timestamp, "antigravity", fallback_text + if text: + res_uid = f"{tool_id}-result" + res_entry = make_tool_result_entry( + session_id, res_uid, timestamp, tool_id, text ) - entry.parentUuid = last_uuid - yield entry + res_entry.parentUuid = tool_id + yield res_entry + + def _extract_model(self, raw_entry: dict[str, Any]) -> str: + model = raw_entry.get("model") + if isinstance(model, str) and model.strip(): + return model.strip() + return _DEFAULT_MODEL + + def _extract_usage(self, raw_entry: dict[str, Any]) -> Optional[UsageInfo]: + input_tokens = _as_optional_int(raw_entry.get("input_tokens")) + output_tokens = _as_optional_int(raw_entry.get("output_tokens")) + cache_read_tokens = _as_optional_int(raw_entry.get("cache_read_tokens")) + if input_tokens is None and output_tokens is None and cache_read_tokens is None: + return None + return UsageInfo( + input_tokens=input_tokens, + output_tokens=output_tokens, + cache_read_input_tokens=cache_read_tokens, + ) def _coerce_tool_calls(self, tool_calls_raw: Any) -> list[dict[str, Any]]: result: list[dict[str, Any]] = [] @@ -377,5 +598,14 @@ def _extract_user_request(self, content: str) -> str: return match.group(1).strip() return content.strip() if content else "" + def _resolve_transcript_file(self, session_dir: Path) -> Optional[Path]: + """Prefer untruncated ``transcript_full.jsonl`` when present.""" + logs_dir = session_dir / ".system_generated" / "logs" + for filename in ("transcript_full.jsonl", "transcript.jsonl"): + candidate = logs_dir / filename + if candidate.exists(): + return candidate + return None + def _is_valid_session_id(self, session_id: str) -> bool: return bool(re.fullmatch(r"[a-f0-9\-]+", session_id)) diff --git a/test/test_agy_provider.py b/test/test_agy_provider.py new file mode 100644 index 00000000..6bd29120 --- /dev/null +++ b/test/test_agy_provider.py @@ -0,0 +1,394 @@ +"""Tests for structured Antigravity CLI (agy) provider parsing and depth filtering.""" + +from __future__ import annotations + +import json +from pathlib import Path +from typing import Any + +import pytest + +from claude_code_log.markdown import MarkdownRenderer +from claude_code_log.models import ( + AssistantTranscriptEntry, + RenderingDepth, + SystemTranscriptEntry, + TextContent, + ThinkingContent, + ToolResultContent, + ToolUseContent, + UserTranscriptEntry, +) +from claude_code_log.providers.agy import AgyProvider + + +def _make_agy_provider( + tmp_path: Path, + monkeypatch: pytest.MonkeyPatch, + records: list[dict[str, Any]], + session_id: str = "abcd-1234", +) -> AgyProvider: + root = tmp_path / "agy" + logs = root / "brain" / session_id / ".system_generated" / "logs" + logs.mkdir(parents=True) + (logs / "transcript.jsonl").write_text( + "\n".join(json.dumps(record) for record in records) + "\n", + encoding="utf-8", + ) + provider = AgyProvider() + monkeypatch.setattr(provider, "get_data_dir", lambda: root) + return provider + + +def test_agy_pairs_parallel_tool_calls_with_generic_results_and_decodes_args( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + records = [ + { + "type": "USER_INPUT", + "created_at": "2026-12-05T10:00:00Z", + "content": "Check status", + }, + { + "type": "PLANNER_RESPONSE", + "created_at": "2026-12-05T10:00:01Z", + "model": "gemini-4-neon-xhigh", + "thinking": "Need to read config and run check.", + "input_tokens": 1200, + "cache_read_tokens": 800, + "output_tokens": 150, + "tool_calls": [ + { + "name": "read_file", + "args": { + "Path": '"/home/ubuntu/code/README.md"', + "StartLine": "1", + "EndLine": "50", + }, + }, + { + "name": "run_command", + "args": { + "CommandLine": '"git status"', + "Truncated": '"unterminated ', + }, + }, + ], + }, + { + "type": "GENERIC", + "status": "DONE", + "created_at": "2026-12-05T10:00:02Z", + "content": "README_BODY_CONTENT", + }, + { + "type": "GENERIC", + "status": "ERROR", + "created_at": "2026-12-05T10:00:03Z", + "content": "fatal: not a git repository", + }, + { + "type": "PLANNER_RESPONSE", + "created_at": "2026-12-05T10:00:04Z", + "model": "gemini-4-neon-xhigh", + "input_tokens": 300, + "cache_read_tokens": 1500, + "output_tokens": 80, + "content": "Everything looks good except git is not initialized.", + }, + ] + + provider = _make_agy_provider(tmp_path, monkeypatch, records) + entries = list(provider.load_session("abcd-1234")) + + # Expected sequence: + # 0: user input + # 1: thinking + # 2: tool_use (read_file) + # 3: tool_use (run_command, carries usage for first PLANNER_RESPONSE) + # 4: tool_result (for read_file) + # 5: tool_result (for run_command, is_error=True) + # 6: assistant text (carries usage for second PLANNER_RESPONSE) + assert len(entries) == 7 + assert isinstance(entries[0], UserTranscriptEntry) + assert isinstance(entries[1], AssistantTranscriptEntry) + assert isinstance(entries[1].message.content[0], ThinkingContent) + assert entries[1].message.model == "gemini-4-neon-xhigh" + assert entries[1].message.usage is None + + assert isinstance(entries[2], AssistantTranscriptEntry) + tool_use_1 = entries[2].message.content[0] + assert isinstance(tool_use_1, ToolUseContent) + assert tool_use_1.name == "read_file" + assert tool_use_1.input == { + "Path": "/home/ubuntu/code/README.md", + "StartLine": 1, + "EndLine": 50, + } + assert entries[2].message.usage is None + + assert isinstance(entries[3], AssistantTranscriptEntry) + tool_use_2 = entries[3].message.content[0] + assert isinstance(tool_use_2, ToolUseContent) + assert tool_use_2.name == "run_command" + assert tool_use_2.input["CommandLine"] == "git status" + assert tool_use_2.input["Truncated"] == '"unterminated ' + assert entries[3].message.usage is not None + assert entries[3].message.usage.input_tokens == 1200 + assert entries[3].message.usage.cache_read_input_tokens == 800 + assert entries[3].message.usage.output_tokens == 150 + + assert isinstance(entries[4], UserTranscriptEntry) + tool_res_1 = entries[4].message.content[0] + assert isinstance(tool_res_1, ToolResultContent) + assert tool_res_1.tool_use_id == tool_use_1.id + assert tool_res_1.content == "README_BODY_CONTENT" + assert tool_res_1.is_error is None + + assert isinstance(entries[5], UserTranscriptEntry) + tool_res_2 = entries[5].message.content[0] + assert isinstance(tool_res_2, ToolResultContent) + assert tool_res_2.tool_use_id == tool_use_2.id + assert tool_res_2.content == "fatal: not a git repository" + assert tool_res_2.is_error is True + + assert isinstance(entries[6], AssistantTranscriptEntry) + assert isinstance(entries[6].message.content[0], TextContent) + assert entries[6].message.usage is not None + assert entries[6].message.usage.input_tokens == 300 + assert entries[6].message.usage.cache_read_input_tokens == 1500 + assert entries[6].message.usage.output_tokens == 80 + + # Linear parentUuid chaining must remain unbroken across all emitted entries + assert [getattr(e, "parentUuid") for e in entries] == [ + None, + *[getattr(e, "uuid") for e in entries[:-1]], + ] + + +def test_agy_system_checkpoint_error_and_markdown_depth_filtering( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + records = [ + { + "type": "USER_INPUT", + "created_at": "2026-12-05T10:00:00Z", + "content": "Explain the fix", + }, + { + "type": "PLANNER_RESPONSE", + "created_at": "2026-12-05T10:00:01Z", + "model": "gemini-4-neon-xhigh", + "thinking": "INTERNAL_THINKING_MARKER", + "tool_calls": [ + { + "name": "run_command", + "args": {"CommandLine": '"echo TOOL_CMD_MARKER"'}, + } + ], + }, + { + "type": "GENERIC", + "status": "DONE", + "created_at": "2026-12-05T10:00:02Z", + "content": "TOOL_STDOUT_MARKER", + }, + { + "type": "SYSTEM_MESSAGE", + "created_at": "2026-12-05T10:00:03Z", + "content": "SYSTEM_NOTICE_MARKER", + }, + { + "type": "ERROR_MESSAGE", + "created_at": "2026-12-05T10:00:04Z", + "error": "API_ERROR_MARKER", + }, + { + "type": "CHECKPOINT", + "created_at": "2026-12-05T10:00:05Z", + "content": "CHECKPOINT_SUMMARY_MARKER", + }, + { + "type": "PLANNER_RESPONSE", + "created_at": "2026-12-05T10:00:06Z", + "model": "gemini-4-neon-xhigh", + "content": "FINAL_ANSWER_MARKER", + }, + ] + + provider = _make_agy_provider(tmp_path, monkeypatch, records) + entries = list(provider.load_session("abcd-1234")) + + system_entries = [e for e in entries if isinstance(e, SystemTranscriptEntry)] + assert len(system_entries) == 3 + assert [(e.level, e.content) for e in system_entries] == [ + ("info", "SYSTEM_NOTICE_MARKER"), + ("error", "API_ERROR_MARKER"), + ("info", "[checkpoint]\nCHECKPOINT_SUMMARY_MARKER"), + ] + + def _render(depth: RenderingDepth) -> str: + renderer = MarkdownRenderer(no_timestamps=True) + renderer.depth = depth + return renderer.generate(entries, "Agy Depth Test") + + md_assistant = _render(RenderingDepth.ASSISTANT) + assert "Explain the fix" in md_assistant + assert "FINAL_ANSWER_MARKER" in md_assistant + assert "TOOL_CMD_MARKER" not in md_assistant + assert "TOOL_STDOUT_MARKER" not in md_assistant + assert "INTERNAL_THINKING_MARKER" not in md_assistant + assert "SYSTEM_NOTICE_MARKER" not in md_assistant + assert "API_ERROR_MARKER" not in md_assistant + assert "CHECKPOINT_SUMMARY_MARKER" not in md_assistant + + md_tool = _render(RenderingDepth.TOOL) + assert "TOOL_CMD_MARKER" in md_tool + assert "TOOL_STDOUT_MARKER" in md_tool + assert "INTERNAL_THINKING_MARKER" in md_tool + assert "SYSTEM_NOTICE_MARKER" not in md_tool + assert "API_ERROR_MARKER" not in md_tool + assert "CHECKPOINT_SUMMARY_MARKER" not in md_tool + + md_hook = _render(RenderingDepth.HOOK) + assert "SYSTEM_NOTICE_MARKER" in md_hook + assert "API_ERROR_MARKER" in md_hook + assert "CHECKPOINT_SUMMARY_MARKER" in md_hook + + +def test_agy_orphaned_generic_and_legacy_tool_entries( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + records = [ + { + "type": "GENERIC", + "created_at": "2026-12-05T10:00:00Z", + "content": "Orphaned generic note", + }, + { + "type": "RUN_COMMAND", + "created_at": "2026-12-05T10:00:01Z", + "command": "ls -la", + "content": "file.txt", + }, + { + "type": "VIEW_FILE", + "created_at": "2026-12-05T10:00:02Z", + "file_path": "/tmp/a.py", + "content": "print(1)", + }, + { + "type": "CODE_ACTION", + "created_at": "2026-12-05T10:00:03Z", + "action": "edit", + "file_path": "/tmp/a.py", + "content": "ok", + }, + ] + + provider = _make_agy_provider(tmp_path, monkeypatch, records) + entries = list(provider.load_session("abcd-1234")) + + # 1 fallback assistant entry + 3 legacy (tool_use, tool_result) pairs = 7 entries + assert len(entries) == 7 + assert isinstance(entries[0], AssistantTranscriptEntry) + assert isinstance(entries[0].message.content[0], TextContent) + assert entries[0].message.content[0].text == "Orphaned generic note" + + for use_idx, expected_name in ( + (1, "run_command"), + (3, "view_file"), + (5, "code_action"), + ): + use_entry = entries[use_idx] + res_entry = entries[use_idx + 1] + assert isinstance(use_entry, AssistantTranscriptEntry) + assert isinstance(res_entry, UserTranscriptEntry) + use_item = use_entry.message.content[0] + res_item = res_entry.message.content[0] + assert isinstance(use_item, ToolUseContent) + assert isinstance(res_item, ToolResultContent) + assert use_item.name == expected_name + assert res_item.tool_use_id == use_item.id + + +def test_agy_prefers_transcript_full_when_present( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + compact_records = [ + { + "type": "PLANNER_RESPONSE", + "created_at": "2026-12-05T10:00:00Z", + "content": "Truncated ", + } + ] + full_records = [ + { + "type": "PLANNER_RESPONSE", + "created_at": "2026-12-05T10:00:00Z", + "content": "Full untruncated assistant answer", + } + ] + provider = _make_agy_provider(tmp_path, monkeypatch, compact_records) + logs = tmp_path / "agy" / "brain" / "abcd-1234" / ".system_generated" / "logs" + (logs / "transcript_full.jsonl").write_text( + "\n".join(json.dumps(r) for r in full_records) + "\n", + encoding="utf-8", + ) + + entries = list(provider.load_session("abcd-1234")) + assert len(entries) == 1 + assert isinstance(entries[0], AssistantTranscriptEntry) + assert isinstance(entries[0].message.content[0], TextContent) + assert entries[0].message.content[0].text == "Full untruncated assistant answer" + + +def test_agy_edge_cases_null_content_nan_args_and_stale_tool_queue( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + records = [ + # Explicit null content should be skipped rather than becoming literal "None" + {"type": "USER_INPUT", "created_at": "2026-12-05T10:00:00Z", "content": None}, + { + "type": "SYSTEM_MESSAGE", + "created_at": "2026-12-05T10:00:01Z", + "content": None, + }, + {"type": "LIST_DIRECTORY", "created_at": "2026-12-05T10:00:02Z", "content": ""}, + # Non-standard JSON constants (NaN/Infinity) must remain strings + { + "type": "PLANNER_RESPONSE", + "created_at": "2026-12-05T10:00:03Z", + "tool_calls": [ + {"name": "calc", "args": {"a": "NaN", "b": "Infinity", "c": "42"}} + ], + }, + # A text-only PLANNER_RESPONSE supersedes any unclosed pending tool call + { + "type": "PLANNER_RESPONSE", + "created_at": "2026-12-05T10:00:04Z", + "content": "Recovered without tool result", + }, + # Subsequent GENERIC must NOT pair with the stale tool call from the earlier turn + { + "type": "GENERIC", + "created_at": "2026-12-05T10:00:05Z", + "content": "Late orphan note", + }, + ] + provider = _make_agy_provider(tmp_path, monkeypatch, records) + entries = list(provider.load_session("abcd-1234")) + + assert len(entries) == 3 + assert isinstance(entries[0], AssistantTranscriptEntry) + tool_use = entries[0].message.content[0] + assert isinstance(tool_use, ToolUseContent) + assert tool_use.input == {"a": "NaN", "b": "Infinity", "c": 42} + + assert isinstance(entries[1], AssistantTranscriptEntry) + assert isinstance(entries[1].message.content[0], TextContent) + assert entries[1].message.content[0].text == "Recovered without tool result" + + assert isinstance(entries[2], AssistantTranscriptEntry) + assert isinstance(entries[2].message.content[0], TextContent) + assert entries[2].message.content[0].text == "Late orphan note"