"""Unit tests for the opencode telemetry plugin TTFF log parser.""" from __future__ import annotations from pathlib import Path from investibook.core.agent_runtime import parse_plugin_ttff def _write_log(workspace_dir: Path, lines: list[str]) -> None: opencode_dir = workspace_dir / ".opencode" opencode_dir.mkdir(parents=True, exist_ok=True) (opencode_dir / "telemetry.log").write_text("\n".join(lines) + "\n") def test_parse_plugin_ttff_first_occurrence_per_phase(tmp_path: Path) -> None: _write_log(tmp_path, [ "[2026-05-04T21:00:00.000Z] Plugin initialized", "[2026-05-04T21:00:01.000Z] TTFF session=ses_a phase=chat.message since_start_ms=0 since_last_ms=0", "[2026-05-04T21:00:01.060Z] TTFF session=ses_a phase=system.transform since_start_ms=60 since_last_ms=60", "[2026-05-04T21:00:01.062Z] TTFF session=ses_a phase=chat.params since_start_ms=62 since_last_ms=2", # second turn — must be ignored, first occurrence per phase wins. "[2026-05-04T21:00:30.000Z] TTFF session=ses_a phase=chat.message since_start_ms=0 since_last_ms=0", "[2026-05-04T21:00:30.080Z] TTFF session=ses_a phase=system.transform since_start_ms=80 since_last_ms=80", ]) out = parse_plugin_ttff(tmp_path, "ses_a") assert out == { "chat.message": 0, "system.transform": 60, "chat.params": 62, } def test_parse_plugin_ttff_filters_by_session_id(tmp_path: Path) -> None: _write_log(tmp_path, [ "[t] TTFF session=ses_a phase=chat.message since_start_ms=0 since_last_ms=0", "[t] TTFF session=ses_b phase=chat.message since_start_ms=5 since_last_ms=5", "[t] TTFF session=ses_b phase=chat.params since_start_ms=70 since_last_ms=65", ]) assert parse_plugin_ttff(tmp_path, "ses_b") == { "chat.message": 5, "chat.params": 70, } def test_parse_plugin_ttff_returns_none_when_log_missing(tmp_path: Path) -> None: # No .opencode/telemetry.log file at all. assert parse_plugin_ttff(tmp_path, "ses_a") is None def test_parse_plugin_ttff_returns_none_when_no_match(tmp_path: Path) -> None: _write_log(tmp_path, [ "[t] Recorded: builtin/read (5ms) - no description", "[t] TTFF session=ses_a phase=chat.message since_start_ms=0 since_last_ms=0", ]) assert parse_plugin_ttff(tmp_path, "ses_NOT_PRESENT") is None