Skip to content

Self-evolving Context Database for AI Agents. Unify Agent Memory, Knowledge RAG and Skills.

fix(server,plugin): readable OV session id + MCP store role_id (#1895)

t0sakiacec33bb5ff2
diff --git a/docs/en/agent-integrations/02-claude-code.md b/docs/en/agent-integrations/02-claude-code.md
index c54e4470d..e31da85b0 100644
--- a/docs/en/agent-integrations/02-claude-code.md
+++ b/docs/en/agent-integrations/02-claude-code.md
@@ -172,6 +172,15 @@ This plugin **complements** Claude Code's native memory system, it doesn't repla
`auto-capture` strips `<openviking-context>`, `<system-reminder>`, `<relevant-memories>`, and `[Subagent Context]` blocks before pushing to OV — without this, the recall context the plugin injects this turn would be captured back as part of the user's message next turn.
+### OV session ID derivation
+
+The OV session ID embeds the CC `session_id` verbatim, so you can map between the two by eye:
+
+- Parent: `cc-<ccSessionId>`, e.g. `cc-7d978bb3-cd9c-4ac6-828d-20965d66b783`
+- Subagent: `cc-<ccSessionId>__agent-<agentId>`, e.g. `cc-7d978bb3-cd9c-4ac6-828d-20965d66b783__agent-abc123`
+
+`~/.openviking/state/last-capture.json` shows the live `cc_session_id` and `ov_session_id` for the current session; the CC side's session ID is also the filename of `~/.claude/projects/<encoded-cwd>/<session_id>.jsonl`.
+
## Troubleshooting
| Symptom | Cause | Fix |
diff --git a/docs/zh/agent-integrations/02-claude-code.md b/docs/zh/agent-integrations/02-claude-code.md
index b098c68a8..02b3b9d91 100644
--- a/docs/zh/agent-integrations/02-claude-code.md
+++ b/docs/zh/agent-integrations/02-claude-code.md
@@ -172,6 +172,15 @@ hook 脚本把每轮的小快照写到 `~/.openviking/state/`;statusline 脚
`auto-capture` 在推送到 OV 前会剥离 `<openviking-context>`、`<system-reminder>`、`<relevant-memories>`、`[Subagent Context]` 等区块——否则插件本轮注入的召回上下文会作为下一轮"用户消息"被回灌进去,形成自污染。
+### OV session id 派生
+
+OV 端的 session id 直接包含 CC 的 `session_id`,方便肉眼对账:
+
+- 主 session:`cc-<ccSessionId>`,例如 `cc-7d978bb3-cd9c-4ac6-828d-20965d66b783`
+- subagent:`cc-<ccSessionId>__agent-<agentId>`,例如 `cc-7d978bb3-cd9c-4ac6-828d-20965d66b783__agent-abc123`
+
+可在 `~/.openviking/state/last-capture.json` 看到当前 session 的 `cc_session_id` 和 `ov_session_id` 对应关系;CC 这边的 session id 也是 `~/.claude/projects/<encoded-cwd>/<session_id>.jsonl` 的文件名。
+
## 故障排查
| 现象 | 原因 | 修复 |
diff --git a/examples/claude-code-memory-plugin/scripts/lib/ov-session.mjs b/examples/claude-code-memory-plugin/scripts/lib/ov-session.mjs
index 546f36eba..cf828df84 100644
--- a/examples/claude-code-memory-plugin/scripts/lib/ov-session.mjs
+++ b/examples/claude-code-memory-plugin/scripts/lib/ov-session.mjs
@@ -6,6 +6,13 @@
* This replaces the old one-shot session model (create → add → extract → delete)
* with a persistent session that lets OV's own commit/extract pipeline run.
*
+ * Format:
+ * parent: cc-<ccSessionId>
+ * subagent: cc-<ccSessionId>__agent-<agentId>
+ *
+ * The CC session_id is preserved verbatim so the OV id is human-readable and
+ * the parent/subagent lineage is visible at a glance.
+ *
* Works with endpoints in openviking/server/routers/sessions.py:
* - POST /api/v1/sessions/{id}/messages (auto_create=true by default)
* - POST /api/v1/sessions/{id}/commit
@@ -13,10 +20,7 @@
* - GET /api/v1/sessions/{id}/context?token_budget=N
*/
-import { createHash } from "node:crypto";
-
const OV_SESSION_PREFIX = "cc-";
-const OV_SESSION_HASH_LEN = 16;
/**
* Glob → RegExp. Minimal implementation: supports `*` (any chars except /),
@@ -58,15 +62,19 @@ export function isBypassed(cfg, { sessionId, cwd } = {}) {
/**
* Derive a stable OV session ID from a CC session_id.
- * Optionally mix in an extra suffix (e.g. subagent agent_id) for isolation.
+ *
+ * Optionally append a suffix (e.g. subagent agent_id) for isolation. The suffix
+ * is normalized: `:` → `-` (so `agent:abc123` → `agent-abc123`) and any
+ * characters outside [A-Za-z0-9._-] become `-`. Result: `cc-<uuid>__<suffix>`.
*/
export function deriveOvSessionId(ccSessionId, suffix = "") {
if (!ccSessionId || typeof ccSessionId !== "string") {
throw new Error("deriveOvSessionId requires a non-empty ccSessionId");
}
- const material = suffix ? `${ccSessionId}\x1f${suffix}` : ccSessionId;
- const hash = createHash("sha256").update(material).digest("hex").slice(0, OV_SESSION_HASH_LEN);
- return `${OV_SESSION_PREFIX}${hash}`;
+ const base = `${OV_SESSION_PREFIX}${ccSessionId}`;
+ if (!suffix) return base;
+ const normalized = String(suffix).replace(/:/g, "-").replace(/[^A-Za-z0-9._-]/g, "-");
+ return `${base}__${normalized}`;
}
/**
diff --git a/examples/claude-code-memory-plugin/scripts/subagent-start.mjs b/examples/claude-code-memory-plugin/scripts/subagent-start.mjs
index f2dca08aa..93e8d3b8a 100644
--- a/examples/claude-code-memory-plugin/scripts/subagent-start.mjs
+++ b/examples/claude-code-memory-plugin/scripts/subagent-start.mjs
@@ -76,8 +76,8 @@ async function main() {
return;
}
- // Isolated ovSessionId: mix agent_id into the hash so the subagent has
- // its own OV session distinct from the parent.
+ // Isolated ovSessionId: append agent_id so the subagent has its own OV
+ // session distinct from the parent (cc-<ccid>__agent-<agentid>).
const ovSessionId = deriveOvSessionId(sessionId, `agent:${agentId}`);
const ovAgentId = `${cfg.agentId || "claude-code"}_${agentType}`;
diff --git a/openviking/server/identity.py b/openviking/server/identity.py
index 48ea2bc49..90b0607d7 100644
--- a/openviking/server/identity.py
+++ b/openviking/server/identity.py
@@ -74,10 +74,30 @@ class RequestContext:
def account_id(self) -> str:
return self.user.account_id
+ def resolve_role_id(self, message_role: str, override: Optional[str] = None) -> Optional[str]:
+ """Resolve the role_id for a message, with fallback to ctx identity.
+
+ `message_role` is the message-level role ("user" / "assistant"), distinct
+ from `RequestContext.role` (the authz role).
+
+ - If `override` is truthy, returns it as-is (caller-supplied wins).
+ - For message_role="user", falls back to `user.user_id`.
+ - For message_role="assistant", falls back to `user.agent_id`.
+ - Any other message_role returns None when no override is given.
+ """
+ if override:
+ return override
+ if message_role == "user":
+ return self.user.user_id
+ if message_role == "assistant":
+ return self.user.agent_id
+ return None
+
@dataclass
class ToolContext:
"""Tool-level context, containing request context and additional tool-specific information."""
+
viking_fs: VikingFS
request_ctx: RequestContext
default_search_uris: List[str] = field(default_factory=list)
diff --git a/openviking/server/mcp_endpoint.py b/openviking/server/mcp_endpoint.py
index 4599576a7..40b28cf58 100644
--- a/openviking/server/mcp_endpoint.py
+++ b/openviking/server/mcp_endpoint.py
@@ -234,7 +234,11 @@ async def store(messages: list[StoreMessage]) -> str:
session = await service.sessions.get(session_id, ctx, auto_create=True)
for msg in messages:
if msg.content:
- session.add_message(msg.role, [TextPart(text=msg.content)])
+ session.add_message(
+ msg.role,
+ [TextPart(text=msg.content)],
+ role_id=ctx.resolve_role_id(msg.role),
+ )
await service.sessions.commit_async(session_id, ctx)
return f"Stored {len(messages)} message(s) and committed for memory extraction."
diff --git a/openviking/server/routers/sessions.py b/openviking/server/routers/sessions.py
index 829727876..65d1cc8d2 100644
--- a/openviking/server/routers/sessions.py
+++ b/openviking/server/routers/sessions.py
@@ -106,21 +106,6 @@ def _request_auth_mode(request: Request) -> AuthMode:
return AuthMode.API_KEY
-def _resolve_message_role_id(
- http_request: Request,
- request: AddMessageRequest,
- ctx: RequestContext,
-) -> Optional[str]:
- if request.role not in {"user", "assistant"}:
- return request.role_id
-
- role_id = request.role_id
- if not role_id:
- role_id = ctx.user.user_id if request.role == "user" else ctx.user.agent_id
-
- return role_id
-
-
@router.post("")
async def create_session(
request: Optional[CreateSessionRequest] = None,
@@ -286,7 +271,6 @@ async def extract_session(
@router.post("/{session_id}/messages")
async def add_message(
request: AddMessageRequest,
- http_request: Request,
session_id: str = Path(..., description="Session ID"),
_ctx: RequestContext = Depends(get_request_context),
):
@@ -307,7 +291,7 @@ async def add_message(
"""
service = get_service()
session = await service.sessions.get(session_id, _ctx, auto_create=True)
- role_id = _resolve_message_role_id(http_request, request, _ctx)
+ role_id = _ctx.resolve_role_id(request.role, request.role_id)
if request.parts is not None:
parts = [part_from_dict(p) for p in request.parts]
diff --git a/tests/server/test_api_sessions.py b/tests/server/test_api_sessions.py
index 1d26fafdb..8b842118b 100644
--- a/tests/server/test_api_sessions.py
+++ b/tests/server/test_api_sessions.py
@@ -118,17 +118,11 @@ async def _call_add_message_route(
*,
ctx: RequestContext,
payload: dict,
- auth_mode: str = "api_key",
- api_key_manager=None,
session_id: str = "test-session",
):
monkeypatch.setattr(sessions_router, "get_service", lambda: service)
return await sessions_router.add_message(
request=sessions_router.AddMessageRequest.model_validate(payload),
- http_request=_session_route_request(
- auth_mode=auth_mode,
- api_key_manager=api_key_manager,
- ),
session_id=session_id,
_ctx=ctx,
)
@@ -279,7 +273,6 @@ async def test_add_message_trusted_request_allows_explicit_role_id(service, monk
monkeypatch,
ctx=ctx,
payload=_message_request("assistant", content="hello trusted", role_id="assistant-b"),
- auth_mode="trusted",
session_id=session_id,
)
@@ -307,7 +300,6 @@ async def test_add_message_admin_request_allows_registered_user_role_id(service,
monkeypatch,
ctx=ctx,
payload=_message_request("user", content="hello admin", role_id="alice"),
- api_key_manager=manager,
session_id=session_id,
)
@@ -375,7 +367,6 @@ async def test_add_message_admin_request_allows_unregistered_user_role_id(servic
monkeypatch,
ctx=ctx,
payload=_message_request("user", content="hello invalid", role_id="ghost"),
- api_key_manager=manager,
session_id="invalid-user-role-id",
)
diff --git a/tests/server/test_mcp_endpoint.py b/tests/server/test_mcp_endpoint.py
index dd72febcf..984d09539 100644
--- a/tests/server/test_mcp_endpoint.py
+++ b/tests/server/test_mcp_endpoint.py
@@ -24,7 +24,7 @@ from openviking.server.mcp_endpoint import (
search,
store,
)
-from openviking.server.mcp_endpoint import list_dir as list_tool
+from openviking.server.mcp_endpoint import ls as list_tool
from openviking_cli.exceptions import UnauthenticatedError
from openviking_cli.session.user_id import UserIdentifier
@@ -170,6 +170,39 @@ async def test_store_batch_messages(service):
assert "2 message" in result
+async def test_store_populates_role_id_from_ctx(service, monkeypatch):
+ """Regression: MCP store used to persist role_id=None because it skipped the
+ HTTP router's fallback resolver. With ctx.resolve_role_id, user msgs should
+ get user.user_id and assistant msgs should get user.agent_id.
+
+ We capture role_id at the add_message boundary instead of reading it back from
+ storage, because store() commits the session synchronously and committed
+ messages move out of session.messages into archive files.
+ """
+ from openviking.session.session import Session
+
+ captured: list[tuple[str, str | None]] = []
+ original = Session.add_message
+
+ def _spy(self, role, parts, role_id=None, created_at=None):
+ captured.append((role, role_id))
+ return original(self, role, parts, role_id=role_id, created_at=created_at)
+
+ monkeypatch.setattr(Session, "add_message", _spy)
+
+ await store(
+ messages=[
+ StoreMessage(role="user", content="user msg"),
+ StoreMessage(role="assistant", content="assistant msg"),
+ ]
+ )
+
+ assert captured == [
+ ("user", DEFAULT_CTX.user.user_id),
+ ("assistant", DEFAULT_CTX.user.agent_id),
+ ]
+
+
# ---------------------------------------------------------------------------
# add_resource tool
# ---------------------------------------------------------------------------