Self-evolving Context Database for AI Agents. Unify Agent Memory, Knowledge RAG and Skills.
Python agent-contextagent-memoryagent-pluginsagentic-ragcontext-databasedsh-pluginknowledge-basememorymemory-managementself-evolvingvector-database
feat(ingest): add a MiMo / MiMoCode log source (#5130)
zhangxin80c59f13eb1e
diff --git a/docs/en/agent-integrations/09-log-ingestion.md b/docs/en/agent-integrations/09-log-ingestion.mdindex a0a84d404..5a31dfa4d 100644--- a/docs/en/agent-integrations/09-log-ingestion.md+++ b/docs/en/agent-integrations/09-log-ingestion.md@@ -1,6 +1,6 @@# Import Local Agent Logs (openviking-server ingest)-`openviking-server ingest` parses the conversation logs that AI coding / agent harnesses (Claude Code, Codex, WorkBuddy, OpenCode, Hermes, OpenClaw) already leave on your machine, then "replays" them through OpenViking's existing session pipeline (`create session → batch add messages → commit`, where commit triggers memory extraction). This turns both your historical and newly written conversations into long-term memory. It complements the per-harness memory plugins: a plugin captures **while a conversation is happening**, whereas this tool is for **importing existing logs** and **watching for new logs offline** — no plugin required and no change to the harness itself.+`openviking-server ingest` parses the conversation logs that AI coding / agent harnesses (Claude Code, Codex, WorkBuddy, OpenCode, MiMo, Hermes, OpenClaw) already leave on your machine, then "replays" them through OpenViking's existing session pipeline (`create session → batch add messages → commit`, where commit triggers memory extraction). This turns both your historical and newly written conversations into long-term memory. It complements the per-harness memory plugins: a plugin captures **while a conversation is happening**, whereas this tool is for **importing existing logs** and **watching for new logs offline** — no plugin required and no change to the harness itself.Key difference from the plugins: this tool is an OpenViking **client**. It runs where the logs live and points at a local or remote server via the SDK, and it is **off by default** — installing OpenViking does not silently scan your local files.@@ -24,6 +24,7 @@ The feature is doubly disabled and must be turned on explicitly:| `hermes` | Supported | `~/.hermes/sessions/*.jsonl` | group-chat agent; user peer = original username || `openclaw` | Supported | `~/.openclaw/agents/*/sessions/*.jsonl` | group-chat agent; user peer = original username || `opencode` | Experimental | `~/.local/share/opencode/opencode.db` | SQLite, polled by `(time, id)`; the legacy file-store is not supported |+| `mimo` | Experimental | `~/.local/share/mimocode/mimocode.db` | SQLite, polled by `(time, id)`; skips `part.synthetic` text and `agent_id != main` || `cursor` | Deferred | `~/Library/Application Support/Cursor/User/**/state.vscdb` | undocumented, version-unstable KV blobs; not yet implemented |> "harness" (agent framework) here means a whole tool like Claude Code or Codex — distinct from OpenViking's "tool" (tool-call) concept.@@ -45,6 +46,7 @@ Add an `ingest` section to `ov.conf`, listing the harnesses to import and their"codex": { "enabled": true, "mode": "backfill" },"workbuddy": { "enabled": true, "mode": "both" },"opencode": { "enabled": false, "mode": "watch", "experimental": true },+ "mimo": { "enabled": false, "mode": "watch", "experimental": true },"hermes": { "enabled": false, "mode": "both", "user_field": "sender" },"openclaw": { "enabled": false, "mode": "both", "user_field": "sender" }}diff --git a/docs/zh/agent-integrations/09-log-ingestion.md b/docs/zh/agent-integrations/09-log-ingestion.mdindex 4e4d01902..2556f231c 100644--- a/docs/zh/agent-integrations/09-log-ingestion.md+++ b/docs/zh/agent-integrations/09-log-ingestion.md@@ -1,6 +1,6 @@# 导入本地 Agent 日志(openviking-server ingest)-`openviking-server ingest` 把你本地已有的 AI 编码 / agent harness 的对话日志(Claude Code、Codex、WorkBuddy、OpenCode、Hermes、OpenClaw)解析成标准消息,再通过 OpenViking 既有的会话管线“重放”进去(`创建会话 → 批量追加消息 → 提交`,提交时触发记忆抽取),从而把这些历史与新增对话沉淀为长期记忆。它与各 harness 的“记忆插件”互补:插件在对话**进行时**实时挂载捕获,而本工具用于**导入既有日志**与**离线监听新增日志**,无需插件、也无需改动对应 harness。+`openviking-server ingest` 把你本地已有的 AI 编码 / agent harness 的对话日志(Claude Code、Codex、WorkBuddy、OpenCode、MiMo、Hermes、OpenClaw)解析成标准消息,再通过 OpenViking 既有的会话管线“重放”进去(`创建会话 → 批量追加消息 → 提交`,提交时触发记忆抽取),从而把这些历史与新增对话沉淀为长期记忆。它与各 harness 的“记忆插件”互补:插件在对话**进行时**实时挂载捕获,而本工具用于**导入既有日志**与**离线监听新增日志**,无需插件、也无需改动对应 harness。与插件方案的关键区别:本工具是 OpenViking 的**客户端**,跑在日志所在的机器上,通过 SDK 指向本地或远端 server;它默认**完全关闭**,不会“装上就扫你本地文件”。@@ -24,6 +24,7 @@| `hermes` | 支持 | `~/.hermes/sessions/*.jsonl` | 群聊 agent,user 取原始用户名 || `openclaw` | 支持 | `~/.openclaw/agents/*/sessions/*.jsonl` | 群聊 agent,user 取原始用户名 || `opencode` | 实验性 | `~/.local/share/opencode/opencode.db` | SQLite,按 `(time, id)` 轮询;旧版文件存储暂不支持 |+| `mimo` | 实验性 | `~/.local/share/mimocode/mimocode.db` | SQLite,按 `(time, id)` 轮询;跳过 `part.synthetic` 文本与 `agent_id != main` || `cursor` | 暂缓 | `~/Library/Application Support/Cursor/User/**/state.vscdb` | 无文档、随版本漂移的 KV blob,暂未实现 |> 这里的 harness(agent 框架)指 CC / Codex 等整套工具,区别于 OpenViking 里“tool(工具调用)”的概念。@@ -45,6 +46,7 @@"codex": { "enabled": true, "mode": "backfill" },"workbuddy": { "enabled": true, "mode": "both" },"opencode": { "enabled": false, "mode": "watch", "experimental": true },+ "mimo": { "enabled": false, "mode": "watch", "experimental": true },"hermes": { "enabled": false, "mode": "both", "user_field": "sender" },"openclaw": { "enabled": false, "mode": "both", "user_field": "sender" }}diff --git a/openviking/ingest/sources/__init__.py b/openviking/ingest/sources/__init__.pyindex c006a80f8..dd4d4dde4 100644--- a/openviking/ingest/sources/__init__.py+++ b/openviking/ingest/sources/__init__.py@@ -8,9 +8,19 @@ from openviking.ingest.sources import ( # noqa: F401codex,cursor,hermes,+ mimo,openclaw,opencode,workbuddy,)-__all__ = ["claude_code", "codex", "cursor", "hermes", "opencode", "openclaw", "workbuddy"]+__all__ = [+ "claude_code",+ "codex",+ "cursor",+ "hermes",+ "mimo",+ "opencode",+ "openclaw",+ "workbuddy",+]diff --git a/openviking/ingest/sources/base.py b/openviking/ingest/sources/base.pyindex 0125ef023..254e35bb7 100644--- a/openviking/ingest/sources/base.py+++ b/openviking/ingest/sources/base.py@@ -3,7 +3,7 @@"""Log-source abstraction: one ABC + two intermediates so a new harness is a thin subclass.- ``JsonlLogSource`` — append-only JSONL (Claude Code, Codex, Hermes, OpenClaw); byte-offset cursor.-- ``SqliteLogSource`` — relational SQLite (OpenCode); (time, id) cursor, polled read-only.+- ``SqliteLogSource`` — relational SQLite (OpenCode, MiMo); (time, id) cursor, polled read-only."""from __future__ import annotationsdiff --git a/openviking/ingest/sources/mimo.py b/openviking/ingest/sources/mimo.pynew file mode 100644index 000000000..f92842a7a--- /dev/null+++ b/openviking/ingest/sources/mimo.py@@ -0,0 +1,165 @@+# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.+# SPDX-License-Identifier: AGPL-3.0+"""Xiaomi MiMo Desktop / MiMoCode adapter — EXPERIMENTAL.++Logs: ``~/.local/share/mimocode/mimocode.db`` (SQLite, WAL). Schema::++ session(id, title, directory, version, time_created, …)+ message(id, session_id, agent_id, time_created, data JSON{role, modelID,+ providerID, time{created,completed}, finish, system, …})+ part(id, message_id, session_id, time_created, data JSON{type, text,+ synthetic, …})++``message.time_created`` is epoch **milliseconds**. Conversation text lives in+``part`` rows with ``type == "text"``. Tool / reasoning / step parts are skipped.++Host pollution that must not become memory:++* ``message.data.system`` holds the full system prompt on every user turn.+* ``part.synthetic == true`` marks injected context (runtime notes, tool lists,+ skill bodies) written as ``type=text``.+* residual ``<system-reminder>…</system-reminder>`` may remain in a+ non-synthetic text block.++Cursor is ``(time_created, id)`` over ``message`` (same model as ``opencode``).+Only ``agent_id = 'main'`` rows are read. An assistant row is complete only when+``time.completed`` or ``finish`` is set, so late-arriving parts are not skipped.+"""++from __future__ import annotations++import json+import re+import sqlite3+from pathlib import Path+from typing import Any, Dict, List++from openviking.ingest.models import NormalizedMessage, SessionRef, iso_from_epoch_ms+from openviking.ingest.registry import register_source+from openviking.ingest.sources.base import NotSupportedError, SqliteLogSource++_REMINDER_RE = re.compile(r"<system-reminder\b[^>]*>.*?</system-reminder>", re.S | re.I)+++def _clean_text(raw: str) -> str:+ return _REMINDER_RE.sub("", raw).strip()+++@register_source("mimo")+class MiMoSource(SqliteLogSource):+ def default_paths(self) -> List[Path]:+ return [Path.home() / ".local" / "share" / "mimocode" / "mimocode.db"]++ def db_path(self) -> Path:+ roots = self.roots()+ if not roots:+ return self.default_paths()[0]+ path = roots[0].expanduser()+ return path / "mimocode.db" if path.is_dir() else path++ def discover_sessions(self):+ db = self.db_path()+ if not db.exists():+ raise NotSupportedError(f"mimo: database not found at {db}")+ conn = self._connect()+ try:+ rows = conn.execute(+ "SELECT id, title, directory, version, time_created "+ "FROM session ORDER BY time_created"+ ).fetchall()+ finally:+ conn.close()+ for row in rows:+ yield SessionRef(+ harness=self.name,+ native_session_id=row["id"],+ locator=row["id"],+ title=row["title"],+ started_at=iso_from_epoch_ms(row["time_created"]),+ meta={+ "cwd": row["directory"],+ "version": row["version"],+ "platform": "mimo",+ },+ )++ def fetch_rows(self, conn, ref: SessionRef, cursor, limit: int) -> List[sqlite3.Row]:+ time_at = cursor.value.get("time", 0)+ last_id = cursor.value.get("id", "")+ return conn.execute(+ "SELECT id, agent_id, time_created, data FROM message "+ "WHERE session_id = ? AND agent_id = 'main' "+ "AND (time_created > ? OR (time_created = ? AND id > ?)) "+ "ORDER BY time_created, id LIMIT ?",+ (ref.locator, time_at, time_at, last_id, limit),+ ).fetchall()++ def row_complete(self, conn, row) -> bool:+ try:+ data = json.loads(row["data"])+ except (ValueError, TypeError):+ return True+ if data.get("role") == "user":+ return True+ time_obj = data.get("time") or {}+ if isinstance(time_obj, dict) and time_obj.get("completed"):+ return True+ return bool(data.get("finish"))++ def rows_to_messages(self, conn, ref: SessionRef, rows) -> List[NormalizedMessage]:+ out: List[NormalizedMessage] = []+ cwd = ref.meta.get("cwd")+ for row in rows:+ try:+ data = json.loads(row["data"])+ except (ValueError, TypeError):+ continue+ role = data.get("role")+ if role not in ("user", "assistant"):+ continue++ text = self._reassemble_text(conn, row["id"], user=(role == "user"))+ if not text:+ continue++ if role == "assistant":+ peer = self.assistant_peer(data.get("modelID"), data.get("providerID"))+ else:+ peer = self.user_peer(cwd=cwd)++ out.append(+ NormalizedMessage(+ role=role,+ text=text,+ created_at=iso_from_epoch_ms(row["time_created"]),+ peer_id=peer,+ meta={+ "model": data.get("modelID"),+ "provider": data.get("providerID"),+ "cwd": cwd,+ },+ )+ )+ return out++ @staticmethod+ def _reassemble_text(conn, message_id: str, *, user: bool) -> str:+ parts = conn.execute(+ "SELECT data FROM part WHERE message_id = ? ORDER BY time_created, id",+ (message_id,),+ ).fetchall()+ chunks: List[str] = []+ for part in parts:+ try:+ payload: Dict[str, Any] = json.loads(part["data"])+ except (ValueError, TypeError):+ continue+ if payload.get("type") != "text" or payload.get("synthetic"):+ continue+ text = payload.get("text")+ if not isinstance(text, str) or not text.strip():+ continue+ cleaned = _clean_text(text) if user else text.strip()+ if cleaned:+ chunks.append(cleaned)+ return "\n".join(chunks).strip()diff --git a/tests/ingest/test_parsers.py b/tests/ingest/test_parsers.pyindex acf984f99..861b882a3 100644--- a/tests/ingest/test_parsers.py+++ b/tests/ingest/test_parsers.py@@ -8,6 +8,7 @@ import sqlite3from openviking.ingest.sources.claude_code import ClaudeCodeSourcefrom openviking.ingest.sources.codex import CodexSourcefrom openviking.ingest.sources.hermes import HermesSource+from openviking.ingest.sources.mimo import MiMoSourcefrom openviking.ingest.sources.openclaw import OpenClawSourcefrom openviking.ingest.sources.opencode import OpenCodeSourcefrom openviking.ingest.sources.workbuddy import WorkBuddySource, user_turn_text@@ -172,6 +173,8 @@ def test_codex_forked_rollout_file_gets_its_own_session_id(tmp_path):for sid, ref in refs.items():msgs, _ = src.read_messages(ref, first[sid])assert msgs == [], f"{sid} re-read its rollout file on the second sweep"++def _workbuddy_turn(role, text, ts_ms, model=None):record = {"id": f"m-{ts_ms}",@@ -425,3 +428,115 @@ def test_opencode_text_from_part_table(tmp_path):# cursor advanced; re-read returns nothing newmsgs2, _ = src.read_messages(refs[0], cursor)assert msgs2 == []+++def test_mimo_skips_synthetic_parts_and_system_prompt(tmp_path):+ db = tmp_path / "mimocode.db"+ conn = sqlite3.connect(str(db))+ conn.executescript(+ """+ CREATE TABLE session (+ id TEXT, title TEXT, directory TEXT, version TEXT, time_created INT+ );+ CREATE TABLE message (+ id TEXT, session_id TEXT, agent_id TEXT, time_created INT, data TEXT+ );+ CREATE TABLE part (+ id TEXT, message_id TEXT, session_id TEXT, time_created INT, data TEXT+ );+ """+ )+ conn.execute(+ "INSERT INTO session VALUES (?,?,?,?,?)",+ ("ses_1", "demo", str(tmp_path), "desktop-test", 1000),+ )+ # message.data.system is the host system prompt — must never be message text+ conn.execute(+ "INSERT INTO message VALUES (?,?,?,?,?)",+ (+ "msg_u",+ "ses_1",+ "main",+ 1773044814194,+ json.dumps({"role": "user", "system": "You are MiMo agent..."}),+ ),+ )+ conn.execute(+ "INSERT INTO message VALUES (?,?,?,?,?)",+ (+ "msg_side",+ "ses_1",+ "side",+ 1773044815000,+ json.dumps({"role": "assistant", "finish": "stop"}),+ ),+ )+ conn.execute(+ "INSERT INTO message VALUES (?,?,?,?,?)",+ (+ "msg_a",+ "ses_1",+ "main",+ 1773044819959,+ json.dumps(+ {+ "role": "assistant",+ "modelID": "mimo-x-pro-preview",+ "providerID": "xiaomi",+ "finish": "stop",+ }+ ),+ ),+ )+ conn.execute(+ "INSERT INTO part VALUES (?,?,?,?,?)",+ (+ "p_syn",+ "msg_u",+ "ses_1",+ 1,+ json.dumps(+ {+ "type": "text",+ "text": "<system-reminder>runtime</system-reminder>",+ "synthetic": True,+ }+ ),+ ),+ )+ conn.execute(+ "INSERT INTO part VALUES (?,?,?,?,?)",+ (+ "p_u",+ "msg_u",+ "ses_1",+ 2,+ json.dumps(+ {+ "type": "text",+ "text": "<system-reminder>note</system-reminder>hello mimo",+ }+ ),+ ),+ )+ conn.execute(+ "INSERT INTO part VALUES (?,?,?,?,?)",+ ("p_tool", "msg_a", "ses_1", 1, json.dumps({"type": "tool", "tool": "bash"})),+ )+ conn.execute(+ "INSERT INTO part VALUES (?,?,?,?,?)",+ ("p_a", "msg_a", "ses_1", 2, json.dumps({"type": "text", "text": "world"})),+ )+ conn.commit()+ conn.close()++ src = MiMoSource(_cfg(db), fallback_user="tester")+ refs = list(src.discover_sessions())+ assert len(refs) == 1+ assert refs[0].title == "demo"+ msgs, cursor = src.read_messages(refs[0], None)+ # sidechain row ignored; synthetic part dropped; reminder stripped+ assert [(m.role, m.text) for m in msgs] == [("user", "hello mimo"), ("assistant", "world")]+ assert msgs[1].peer_id == "mimo__xiaomi__mimo-x-pro-preview"+ msgs2, _ = src.read_messages(refs[0], cursor)+ assert msgs2 == []