Compress tool outputs, logs, files, and RAG chunks before they reach the LLM. 20% fewer tokens for coding agents, 60-95% fewer tokens for JSON, same answers. Library, proxy, MCP server.
Python agentaianthropicclaude-codecompressioncontext-engineeringcontext-windowcursorfastapilangchainllmmcpopenaiprompt-engineeringproxypythonragtoken-optimizationtokenstypescript
fix(learn): support opencode v2 session schema in learn scanner (#4199)
Javier Leónc05466a469c8
diff --git a/headroom/learn/plugins/opencode.py b/headroom/learn/plugins/opencode.pyindex 9bc53fb80..3684179ae 100644--- a/headroom/learn/plugins/opencode.py+++ b/headroom/learn/plugins/opencode.py@@ -5,22 +5,15 @@ Reads conversation data from the OpenCode SQLite database at``~/.local/share/opencode/opencode-local.db``. Set``HEADROOM_OPENCODE_DB`` to force a specific database path.-OpenCode stores messages and tool parts in two tables:-- ``message``: one row per turn (user/assistant), with JSON ``data``-- ``part``: one row per content part; tool parts have ``data.type == "tool"``--A tool part looks like::-- {- "type": "tool",- "tool": "bash",- "callID": "toolu_01...",- "state": {- "status": "completed" | "error",- "input": { ... },- "output": "..."- }- }+Supports both schemas:+- Legacy (opencode v1): ``message`` + ``part`` tables, where tool parts look+ like ``{"type": "tool", "tool": "bash", "callID": ..., "state":+ {"status": ..., "input": {...}, "output": "..."}}``.+- Current (opencode v2, >= 2026-03): ``session_v2`` + ``session_message``+ tables, where each message row holds JSON ``data`` with a ``content`` list+ and tool entries look like ``{"type": "tool", "id": ..., "name": "bash",+ "state": {"status": ..., "input": {...}, "content": [{"type": "text",+ "text": "..."}], "error": {...}}}``.``headroom learn opencode`` mines these for errors and writes corrections tothe project's ``AGENTS.md`` file (OpenCode's native rules file).@@ -58,6 +51,79 @@ _OPENCODE_DB_CANDIDATES = ("opencode-local.db", "opencode.db")_ERROR_STATUSES = {"error", "failed", "aborted"}+def _tables(conn: sqlite3.Connection) -> set[str]:+ try:+ cur = conn.cursor()+ cur.execute("SELECT name FROM sqlite_master WHERE type='table'")+ return {r[0] for r in cur.fetchall()}+ except sqlite3.Error:+ return set()+++def _session_table(tables: set[str]) -> str | None:+ # Prefer the v2 schema used by current opencode releases, fall back to+ # the legacy table name.+ if "session_v2" in tables:+ return "session_v2"+ if "session" in tables:+ return "session"+ return None+++def _worktree_key(value: str | Path) -> str:+ """Normalize a worktree path for cross-platform database matching.++ opencode stores Windows worktrees with POSIX separators (``C:/Users/...``)+ while ``str(Path(...))`` renders them with backslashes on Windows. Compare+ both spellings, and fold case for drive-letter/UNC paths because Windows+ filesystems are case-insensitive. POSIX paths stay case-sensitive.+ """+ path = str(value).replace("\\", "/")+ if path.startswith("//") or (len(path) >= 2 and path[1] == ":"):+ path = path.casefold()+ return path.rstrip("/") or "/"+++def _extract_output(state: dict) -> str:+ """Extract human-readable tool output from either schema shape.++ Combines all available sources: the legacy ``state.output`` string, the+ v2 ``state.content`` text blocks, and ``state.error`` details. The error+ is always included when present — even alongside content blocks — so a+ failed call keeps its failure message for error classification.+ """+ parts: list[str] = []+ # Legacy shape: state.output is a plain string.+ if isinstance(state.get("output"), str) and state.get("output"):+ parts.append(str(state.get("output") or ""))+ # Current shape: state.content is a list of {type, text} blocks.+ content = state.get("content")+ if isinstance(content, list) and content:+ for item in content:+ if not isinstance(item, dict):+ parts.append(str(item))+ continue+ t = item.get("text")+ if isinstance(t, str) and t:+ parts.append(t)+ elif item.get("type") != "text":+ parts.append(json.dumps(item)[:500])+ elif content is not None and not isinstance(content, list):+ parts.append(str(content))+ # Error shape: state.error = {type, message}. Surface it as output so+ # error classification sees the message even when content is empty —+ # or when content holds only pre-failure progress output.+ err = state.get("error")+ if isinstance(err, dict) and err:+ etype = str(err.get("type") or "error")+ msg = str(err.get("message") or "")+ combined = f"{etype}: {msg}".strip(": ").strip()+ parts.append(combined if combined else json.dumps(err)[:2000])+ elif isinstance(err, str) and err:+ parts.append(err)+ return "\n".join(p for p in parts if p)++class OpenCodePlugin(LearnPlugin, ConversationScanner):"""Read OpenCode sessions from the SQLite database.@@ -111,14 +177,28 @@ class OpenCodePlugin(LearnPlugin, ConversationScanner):return []try:+ tables = _tables(conn)+ sess_tbl = _session_table(tables)+ if sess_tbl is None:+ logger.warning("OpenCode DB %s has no session table", self._db_path)+ return []cursor = conn.cursor()- cursor.execute(- "SELECT p.id, p.name, p.worktree "- "FROM project p "- "WHERE EXISTS (SELECT 1 FROM session s WHERE s.project_id = p.id)"- )+ try:+ cursor.execute(+ f"SELECT p.id, p.name, p.worktree "+ f"FROM project p "+ f"WHERE EXISTS (SELECT 1 FROM {sess_tbl} s WHERE s.project_id = p.id)"+ )+ rows = cursor.fetchall()+ except sqlite3.OperationalError:+ cursor.execute(+ f"SELECT p.id, NULL, p.worktree "+ f"FROM project p "+ f"WHERE EXISTS (SELECT 1 FROM {sess_tbl} s WHERE s.project_id = p.id)"+ )+ rows = cursor.fetchall()projects: list[ProjectInfo] = []- for row in cursor.fetchall():+ for row in rows:proj_id, proj_name, worktree = rowworktree_path = Path(worktree) if worktree else Path("~").expanduser()agents_md = worktree_path / "AGENTS.md"@@ -130,6 +210,9 @@ class OpenCodePlugin(LearnPlugin, ConversationScanner):context_file=agents_md if path_exists(agents_md) else None,))+ except sqlite3.Error as exc:+ logger.warning("Cannot discover OpenCode projects: %s", exc)+ return []finally:conn.close()@@ -161,27 +244,40 @@ class OpenCodePlugin(LearnPlugin, ConversationScanner):self, conn: sqlite3.Connection, project: ProjectInfo) -> list[SessionData]:cursor = conn.cursor()+ tables = _tables(conn)+ sess_tbl = _session_table(tables)+ if sess_tbl is None:+ return []- # Find the project ID from the worktree path.- cursor.execute(- "SELECT id FROM project WHERE worktree = ?",- (str(project.project_path),),- )- row = cursor.fetchone()- if row is None:+ cursor.execute("SELECT id, worktree FROM project")+ target_worktree = _worktree_key(project.project_path)+ project_db_id: str | None = None+ for proj_id, worktree in cursor.fetchall():+ if isinstance(worktree, str) and _worktree_key(worktree) == target_worktree:+ project_db_id = proj_id+ break+ if project_db_id is None:return []- project_db_id: str = row[0]- # Get all sessions for this project.cursor.execute(- "SELECT id, time_created FROM session WHERE project_id = ? ORDER BY time_created DESC LIMIT 200",+ f"SELECT id, time_created FROM {sess_tbl} WHERE project_id = ? ORDER BY time_created DESC LIMIT 200",(project_db_id,),)session_rows = cursor.fetchall()sessions: list[SessionData] = []+ # The message layout follows the session schema: v2 sessions live in+ # session_message, legacy ones in part/message. Resolve once per scan+ # instead of per session (up to 200 sqlite_master lookups per project).+ prefer_v2 = sess_tbl == "session_v2"for session_id, time_created in session_rows:- session = self._scan_session(conn, session_id, time_created)+ try:+ session = self._scan_session(+ conn, session_id, time_created, tables=tables, prefer_v2=prefer_v2+ )+ except sqlite3.Error as exc:+ logger.warning("Cannot scan OpenCode session %s: %s", session_id, exc)+ continueif session is not None and session.tool_calls:sessions.append(session)@@ -215,10 +311,132 @@ class OpenCodePlugin(LearnPlugin, ConversationScanner):conn: sqlite3.Connection,session_id: str,time_created: int | None,+ tables: set[str] | None = None,+ prefer_v2: bool = True,+ ) -> SessionData | None:+ """Scan one session, trying the matching message layout first.++ ``prefer_v2`` follows the session schema the ID was discovered from.+ When the preferred layout yields no tool calls (partially migrated+ databases can hold both families), the other layout is tried before+ giving up, so mixed-schema sessions don't silently lose their calls.+ """+ if tables is None:+ tables = _tables(conn)+ attempts = []+ if "session_message" in tables:+ attempts.append((True, self._scan_session_v2))+ if "part" in tables and "message" in tables:+ attempts.append((False, self._scan_session_legacy))+ if not attempts:+ logger.warning("OpenCode DB has neither session_message nor part/message tables")+ return None+ attempts.sort(key=lambda attempt: attempt[0] != prefer_v2)+ for _, scan in attempts:+ session = scan(conn, session_id, time_created)+ if session is not None and session.tool_calls:+ return session+ return None++ def _scan_session_v2(+ self,+ conn: sqlite3.Connection,+ session_id: str,+ time_created: int | None,+ ) -> SessionData | None:+ cursor = conn.cursor()++ cursor.execute(+ "SELECT data, time_created FROM session_message "+ "WHERE session_id = ? AND data LIKE '%\"type\"%tool%' "+ "ORDER BY seq",+ (session_id,),+ )+ rows = cursor.fetchall()++ tool_calls: list[ToolCall] = []+ events: list[SessionEvent] = []+ idx = 0+ for data_raw, msg_time in rows:+ try:+ data = json.loads(data_raw)+ except (json.JSONDecodeError, TypeError):+ continue+ # data_raw is TEXT; a stored "null"/"[]" parses to a non-dict.+ if not isinstance(data, dict):+ continue+ content = data.get("content")+ if not isinstance(content, list):+ continue++ for item in content:+ if not isinstance(item, dict) or item.get("type") != "tool":+ continue+ raw_tool_name = str(item.get("name") or item.get("tool") or "unknown")+ tool_name = (+ "Bash"+ if raw_tool_name.lower() == "bash"+ else normalize_tool_name(raw_tool_name)+ )+ call_id = str(item.get("id") or item.get("callID") or f"oc_{session_id}_{idx}")+ state_raw = item.get("state")+ state: dict = state_raw if isinstance(state_raw, dict) else {}+ status = str(state.get("status") or "unknown")+ input_raw = state.get("input")+ input_data: dict = input_raw if isinstance(input_raw, dict) else {}+ output: str = _extract_output(state)++ if output == "...output truncated..." or output.startswith("...output truncated"):+ truncated_ref = (+ state.get("outputRef")+ or state.get("outputFile")+ or state.get("outputRefFile")+ )+ if truncated_ref:+ try:+ output = Path(str(truncated_ref)).read_text(errors="replace")+ except OSError:+ pass++ is_error = status in _ERROR_STATUSES or is_error_content(output)+ error_cat = classify_error(output) if is_error else ErrorCategory.UNKNOWN++ tc = ToolCall(+ name=tool_name,+ tool_call_id=call_id,+ input_data=input_data,+ output=output,+ is_error=is_error,+ error_category=error_cat,+ msg_index=idx,+ output_bytes=len(output.encode()),+ )+ tool_calls.append(tc)+ part_ts = str(msg_time) if msg_time is not None else None+ events.append(+ SessionEvent(type="tool_call", msg_index=idx, timestamp=part_ts, tool_call=tc)+ )+ idx += 1++ if not tool_calls:+ return None++ ts = _to_datetime(time_created)+ return SessionData(+ session_id=session_id,+ tool_calls=tool_calls,+ events=events,+ timestamp=ts,+ )++ def _scan_session_legacy(+ self,+ conn: sqlite3.Connection,+ session_id: str,+ time_created: int | None,) -> SessionData | None:cursor = conn.cursor()- # Get all tool parts for this session ordered by creation time.cursor.execute("""SELECT p.data, p.time_created@@ -244,19 +462,18 @@ class OpenCodePlugin(LearnPlugin, ConversationScanner):if data.get("type") != "tool":continue- raw_tool_name = str(data.get("tool") or "unknown")+ raw_tool_name = str(data.get("tool") or data.get("name") or "unknown")tool_name = ("Bash" if raw_tool_name.lower() == "bash" else normalize_tool_name(raw_tool_name))- call_id = str(data.get("callID") or f"oc_{session_id}_{idx}")+ call_id = str(data.get("callID") or data.get("id") or f"oc_{session_id}_{idx}")state_raw = data.get("state")state: dict = state_raw if isinstance(state_raw, dict) else {}status = str(state.get("status") or "unknown")input_raw = state.get("input")input_data: dict = input_raw if isinstance(input_raw, dict) else {}- output: str = str(state.get("output") or "")+ output: str = _extract_output(state)- # Detect truncated output pointer.if output == "...output truncated..." or output.startswith("...output truncated"):truncated_ref = state.get("outputRef") or state.get("outputFile")if truncated_ref:@@ -287,13 +504,7 @@ class OpenCodePlugin(LearnPlugin, ConversationScanner):if not tool_calls:return None- ts: datetime | None = None- if time_created is not None:- try:- ts = datetime.fromtimestamp(time_created / 1000, tz=timezone.utc)- except (OSError, OverflowError, ValueError):- pass-+ ts = _to_datetime(time_created)return SessionData(session_id=session_id,tool_calls=tool_calls,@@ -302,5 +513,14 @@ class OpenCodePlugin(LearnPlugin, ConversationScanner):)+def _to_datetime(time_created: int | None) -> datetime | None:+ if time_created is None:+ return None+ try:+ return datetime.fromtimestamp(time_created / 1000, tz=timezone.utc)+ except (OSError, OverflowError, ValueError, TypeError):+ return None++# Module-level instance — auto-discovered by the learn plugin registry.plugin = OpenCodePlugin()diff --git a/tests/test_learn/test_opencode_scanner.py b/tests/test_learn/test_opencode_scanner.pyindex 8f30f22eb..182f00c8f 100644--- a/tests/test_learn/test_opencode_scanner.py+++ b/tests/test_learn/test_opencode_scanner.py@@ -333,3 +333,432 @@ def test_opencode_plugin_is_discovered_by_registry() -> None:assert "opencode" in get_registry()finally:reset_registry()+++def _create_opencode_db_v2(+ db_path: Path,+ project_path: Path,+ *,+ project_id: str = "project-v2",+ project_name: str | None = None,+ session_id: str = "session-v2",+ worktree: str | None = None,+) -> None:+ """Build a minimal opencode v2 database (session_v2 + session_message).++ Mirrors the schema shipped by current opencode releases: each+ ``session_message`` row holds JSON ``data`` with a ``content`` list, and+ tool entries carry ``name``/``id`` plus a ``state`` dict with+ ``status``/``input``/``content`` (or ``error`` on failure).+ """+ conn = sqlite3.connect(db_path)+ try:+ conn.executescript(+ """+ CREATE TABLE project (+ id TEXT PRIMARY KEY,+ worktree TEXT NOT NULL,+ name TEXT+ );+ CREATE TABLE session_v2 (+ id TEXT PRIMARY KEY,+ project_id TEXT NOT NULL,+ time_created INTEGER NOT NULL+ );+ CREATE TABLE session_message (+ id TEXT PRIMARY KEY,+ session_id TEXT NOT NULL,+ type TEXT NOT NULL,+ seq INTEGER NOT NULL,+ time_created INTEGER NOT NULL,+ time_updated INTEGER NOT NULL,+ data TEXT NOT NULL+ );+ """+ )++ # NOTE: compact separators mirror production storage (no spaces), which+ # the scanner's LIKE prefilter matches.+ def _dump(obj: object) -> str:+ return json.dumps(obj, separators=(",", ":"))++ conn.execute(+ "INSERT INTO project (id, worktree, name) VALUES (?, ?, ?)",+ (project_id, worktree if worktree is not None else str(project_path), project_name),+ )+ conn.execute(+ "INSERT INTO session_v2 (id, project_id, time_created) VALUES (?, ?, ?)",+ (session_id, project_id, 1_700_000_000_000),+ )+ conn.execute(+ "INSERT INTO session_message (id, session_id, type, seq, time_created, time_updated, data)"+ " VALUES (?, ?, ?, ?, ?, ?, ?)",+ (+ "message-v2-1",+ session_id,+ "assistant",+ 5,+ 1_700_000_000_001,+ 1_700_000_000_002,+ _dump(+ {+ "content": [+ {+ "type": "tool",+ "id": "call-v2-1",+ "name": "read",+ "state": {+ "status": "completed",+ "input": {"path": "/repo/main.py"},+ "content": [{"type": "text", "text": "print('hi')\n"}],+ "metadata": {"truncated": False},+ },+ },+ {+ "type": "tool",+ "id": "call-v2-2",+ "name": "bash",+ "state": {+ "status": "error",+ "input": {"command": "pytest"},+ "error": {+ "type": "tool.execution",+ "message": "Error: command failed with exit code 1",+ },+ },+ },+ ]+ }+ ),+ ),+ )+ conn.commit()+ finally:+ conn.close()+++def test_opencode_plugin_v2_schema_discovers_projects_and_scans_tool_calls(+ tmp_path: Path,+) -> None:+ project_path = tmp_path / "repo-v2"+ _write_agents_file(project_path)+ db_path = tmp_path / "opencode-v2.db"+ _create_opencode_db_v2(db_path, project_path, project_name="V2Project")++ plugin = OpenCodePlugin(db_path=db_path)++ projects = plugin.discover_projects()+ assert len(projects) == 1+ assert projects[0].name == "V2Project"+ assert projects[0].project_path == project_path++ sessions = plugin.scan_project(projects[0])+ assert len(sessions) == 1+ assert sessions[0].session_id == "session-v2"+ assert len(sessions[0].tool_calls) == 2++ ok_call, err_call = sessions[0].tool_calls+ assert ok_call.name == "read"+ assert ok_call.is_error is False+ assert "print('hi')" in ok_call.output+ assert err_call.name == "Bash"+ assert err_call.tool_call_id == "call-v2-2"+ assert err_call.is_error is True+ assert err_call.error_category == ErrorCategory.RUNTIME_ERROR+++def test_opencode_plugin_v2_forward_slash_windows_worktree_scans_calls(+ tmp_path: Path,+) -> None:+ # opencode stores Windows worktrees with forward slashes, while+ # str(Path(worktree)) renders them with backslashes on Windows. Scanning+ # must match both spellings instead of silently returning zero sessions.+ db_path = tmp_path / "opencode-v2-windows.db"+ _create_opencode_db_v2(+ db_path,+ Path("C:/Users/runner/project"),+ project_name="WindowsProject",+ worktree="C:/Users/runner/project",+ )++ plugin = OpenCodePlugin(db_path=db_path)+ projects = plugin.discover_projects()+ assert len(projects) == 1++ # Simulate discovery on Windows: Path() renders the stored worktree with+ # native separators (and may normalize the drive-letter case).+ projects[0].project_path = Path(r"c:\users\runner\project")++ sessions = plugin.scan_project(projects[0])+ assert len(sessions) == 1+ assert [call.tool_call_id for call in sessions[0].tool_calls] == [+ "call-v2-1",+ "call-v2-2",+ ]+ assert sessions[0].tool_calls[1].is_error is True+++def test_opencode_plugin_v2_null_project_name_falls_back_to_worktree(+ tmp_path: Path,+) -> None:+ # Current opencode releases leave project.name NULL; discovery must fall+ # back to the worktree basename instead of crashing or emitting an empty name.+ project_path = tmp_path / "fallback-repo"+ project_path.mkdir()+ db_path = tmp_path / "opencode-v2-null.db"+ _create_opencode_db_v2(db_path, project_path, project_name=None)++ plugin = OpenCodePlugin(db_path=db_path)++ projects = plugin.discover_projects()+ assert len(projects) == 1+ assert projects[0].name == "fallback-repo"+ assert projects[0].context_file is None++ sessions = plugin.scan_project(projects[0])+ assert len(sessions) == 1+++def test_opencode_plugin_v2_missing_name_column_still_discovers(+ tmp_path: Path,+) -> None:+ # Very old databases lack project.name entirely; discovery must use the+ # missing-column fallback instead of raising OperationalError.+ project_path = tmp_path / "nocol-repo"+ project_path.mkdir()+ db_path = tmp_path / "opencode-v2-nocol.db"+ conn = sqlite3.connect(db_path)+ try:+ conn.executescript(+ """+ CREATE TABLE project (id TEXT PRIMARY KEY, worktree TEXT NOT NULL);+ CREATE TABLE session_v2 (+ id TEXT PRIMARY KEY,+ project_id TEXT NOT NULL,+ time_created INTEGER NOT NULL+ );+ """+ )+ conn.execute(+ "INSERT INTO project (id, worktree) VALUES (?, ?)",+ ("project-nocol", str(project_path)),+ )+ conn.execute(+ "INSERT INTO session_v2 (id, project_id, time_created) VALUES (?, ?, ?)",+ ("session-nocol", "project-nocol", 1_700_000_000_000),+ )+ conn.commit()+ finally:+ conn.close()++ plugin = OpenCodePlugin(db_path=db_path)++ projects = plugin.discover_projects()+ assert len(projects) == 1+ assert projects[0].name == "nocol-repo"+++def test_opencode_plugin_v2_failure_keeps_error_message_alongside_content(+ tmp_path: Path,+) -> None:+ # A failed tool carrying both progress output and error details must keep+ # the error text so classification sees the failure, not just the output.+ project_path = tmp_path / "repo-v2-mixed"+ project_path.mkdir()+ db_path = tmp_path / "opencode-v2-mixed.db"+ conn = sqlite3.connect(db_path)+ try:+ conn.executescript(+ """+ CREATE TABLE project (id TEXT PRIMARY KEY, worktree TEXT NOT NULL, name TEXT);+ CREATE TABLE session_v2 (+ id TEXT PRIMARY KEY,+ project_id TEXT NOT NULL,+ time_created INTEGER NOT NULL+ );+ CREATE TABLE session_message (+ id TEXT PRIMARY KEY,+ session_id TEXT NOT NULL,+ type TEXT NOT NULL,+ seq INTEGER NOT NULL,+ time_created INTEGER NOT NULL,+ time_updated INTEGER NOT NULL,+ data TEXT NOT NULL+ );+ """+ )+ conn.execute(+ "INSERT INTO project (id, worktree, name) VALUES (?, ?, ?)",+ ("project-mixed", str(project_path), "Mixed"),+ )+ conn.execute(+ "INSERT INTO session_v2 (id, project_id, time_created) VALUES (?, ?, ?)",+ ("session-mixed", "project-mixed", 1_700_000_000_000),+ )+ conn.execute(+ "INSERT INTO session_message (id, session_id, type, seq, time_created, time_updated, data)"+ " VALUES (?, ?, ?, ?, ?, ?, ?)",+ (+ "message-mixed-1",+ "session-mixed",+ "assistant",+ 5,+ 1_700_000_000_001,+ 1_700_000_000_002,+ json.dumps(+ {+ "content": [+ {+ "type": "tool",+ "id": "call-mixed-1",+ "name": "bash",+ "state": {+ "status": "error",+ "input": {"command": "pytest"},+ "content": [{"type": "text", "text": "starting tests"}],+ "error": {+ "type": "tool.execution",+ "message": "ENOENT: missing fixture",+ },+ },+ }+ ]+ },+ separators=(",", ":"),+ ),+ ),+ )+ conn.commit()+ finally:+ conn.close()++ plugin = OpenCodePlugin(db_path=db_path)+ projects = plugin.discover_projects()+ sessions = plugin.scan_project(projects[0])++ assert len(sessions) == 1+ call = sessions[0].tool_calls[0]+ assert call.is_error is True+ assert "starting tests" in call.output+ assert "ENOENT: missing fixture" in call.output+ assert call.error_category == ErrorCategory.FILE_NOT_FOUND+++def test_opencode_plugin_v2_skips_non_dict_message_data(+ tmp_path: Path,+) -> None:+ # Stored "null"/"[]" payloads parse to non-dicts; they must be skipped,+ # not abort the session scan.+ project_path = tmp_path / "repo-v2-nulldata"+ project_path.mkdir()+ db_path = tmp_path / "opencode-v2-nulldata.db"+ _create_opencode_db_v2(db_path, project_path, project_name="NullData")+ conn = sqlite3.connect(db_path)+ try:+ for msg_id, payload in (("junk-1", "null"), ("junk-2", "[]")):+ conn.execute(+ "INSERT INTO session_message (id, session_id, type, seq, time_created, time_updated, data)"+ " VALUES (?, ?, ?, ?, ?, ?, ?)",+ (+ msg_id,+ "session-v2",+ "assistant",+ 1,+ 1_700_000_000_000,+ 1_700_000_000_000,+ payload,+ ),+ )+ conn.commit()+ finally:+ conn.close()++ plugin = OpenCodePlugin(db_path=db_path)+ projects = plugin.discover_projects()+ sessions = plugin.scan_project(projects[0])++ assert len(sessions) == 1+ assert len(sessions[0].tool_calls) == 2+++def test_opencode_plugin_mixed_schema_falls_back_to_legacy_tables(+ tmp_path: Path,+) -> None:+ # A partially migrated database can hold a v2 session whose tool calls+ # still live in the legacy part/message tables; the scanner must fall+ # back instead of reporting the session empty.+ project_path = tmp_path / "repo-mixed-schema"+ project_path.mkdir()+ db_path = tmp_path / "opencode-mixed-schema.db"+ conn = sqlite3.connect(db_path)+ try:+ conn.executescript(+ """+ CREATE TABLE project (id TEXT PRIMARY KEY, worktree TEXT NOT NULL, name TEXT);+ CREATE TABLE session_v2 (+ id TEXT PRIMARY KEY,+ project_id TEXT NOT NULL,+ time_created INTEGER NOT NULL+ );+ CREATE TABLE session_message (+ id TEXT PRIMARY KEY,+ session_id TEXT NOT NULL,+ type TEXT NOT NULL,+ seq INTEGER NOT NULL,+ time_created INTEGER NOT NULL,+ time_updated INTEGER NOT NULL,+ data TEXT NOT NULL+ );+ CREATE TABLE message (id TEXT PRIMARY KEY, session_id TEXT);+ CREATE TABLE part (+ id TEXT PRIMARY KEY,+ message_id TEXT,+ data TEXT,+ time_created INTEGER+ );+ """+ )+ conn.execute(+ "INSERT INTO project (id, worktree, name) VALUES (?, ?, ?)",+ ("project-ms", str(project_path), "MixedSchema"),+ )+ conn.execute(+ "INSERT INTO session_v2 (id, project_id, time_created) VALUES (?, ?, ?)",+ ("session-ms", "project-ms", 1_700_000_000_000),+ )+ conn.execute(+ "INSERT INTO message (id, session_id) VALUES (?, ?)",+ ("message-ms-1", "session-ms"),+ )+ conn.execute(+ "INSERT INTO part (id, message_id, data, time_created) VALUES (?, ?, ?, ?)",+ (+ "part-ms-1",+ "message-ms-1",+ json.dumps(+ {+ "type": "tool",+ "tool": "bash",+ "callID": "call-ms-1",+ "state": {+ "status": "error",+ "input": {"command": "pytest"},+ "output": "Error: command failed with exit code 1",+ },+ }+ ),+ 1_700_000_000_001,+ ),+ )+ conn.commit()+ finally:+ conn.close()++ plugin = OpenCodePlugin(db_path=db_path)+ projects = plugin.discover_projects()+ assert len(projects) == 1+ sessions = plugin.scan_project(projects[0])++ assert len(sessions) == 1+ assert sessions[0].tool_calls[0].tool_call_id == "call-ms-1"+ assert sessions[0].tool_calls[0].is_error is True