Skip to content

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

feat(uri)!: remove uid-less current-user shorthand in favor of viking://~ (#4196)

t0sakia83b81715ba2
diff --git a/agent-plugins/skills/openviking-memory/SKILL.md b/agent-plugins/skills/openviking-memory/SKILL.md
index 4de53f514..6a22f6840 100644
--- a/agent-plugins/skills/openviking-memory/SKILL.md
+++ b/agent-plugins/skills/openviking-memory/SKILL.md
@@ -31,7 +31,7 @@ memory. Do not fabricate tool calls or fall back to raw HTTP.
`limit` around 5-10. Use `search` when deeper intent analysis helps, or use
`search` with `mode="context"` for a server-assembled, token-budgeted
context block. In list mode, scope with `target_uri` when you know where to look, e.g.
- `viking://user/memories/experiences` for prior task experience.
+ `viking://~/memories/experiences` for prior task experience.
4. Judge results by task and environment fit, not title similarity. `read` the
one to three exact file URIs likely to change how you execute. Ignore
sidecar files such as `.abstract.md`, `.overview.md`, and
@@ -56,7 +56,7 @@ session:
says "remember this", states a lasting preference or decision, or when a
hard-won lesson (root cause, working procedure, environment quirk) emerges.
- `write(uri, content)` / `edit` — when you need an exact document at a known
- location, such as curated notes under `viking://user/` or shared reference
+ location, such as curated notes under `viking://~/` (your own user root) or shared reference
material under `viking://resources/`. Prefer `edit` over rewriting whole
files. If neither tool is registered, fall back to `remember`.
- `add_resource` — to import external documents or URLs as searchable
@@ -72,7 +72,7 @@ transcript dumps — store conclusions, not scrollback.
User asks to fix a failing deployment:
1. `find` with query `deployment image pull failure private registry`,
- `target_uri: "viking://user/memories/experiences"`.
+ `target_uri: "viking://~/memories/experiences"`.
2. `read` the most relevant experience URI; check its assumptions against the
current cluster before applying its steps.
3. Fix the issue, verify the live result.
diff --git a/benchmark/tau2/llm/scripts/run_eval.py b/benchmark/tau2/llm/scripts/run_eval.py
index 2454a9f0f..ed47b39df 100755
--- a/benchmark/tau2/llm/scripts/run_eval.py
+++ b/benchmark/tau2/llm/scripts/run_eval.py
@@ -200,7 +200,7 @@ def _memory_corpus_dir(config: dict[str, Any], configured_run_id: str, corpus_ke
def _search_uri(search_memory_type: str) -> str:
- return f"viking://user/memories/{search_memory_type}"
+ return f"viking://~/memories/{search_memory_type}"
def _train_transcript_format(strategy: dict[str, Any]) -> str:
diff --git a/benchmark/tau2/train/rollout_executor.py b/benchmark/tau2/train/rollout_executor.py
index a3b10f696..85fc50d55 100644
--- a/benchmark/tau2/train/rollout_executor.py
+++ b/benchmark/tau2/train/rollout_executor.py
@@ -69,7 +69,7 @@ def make_tau2_rollout_executor(
default=True,
),
retrieval_mode=str(opts.get("retrieval_mode") or "first_user_prewrite"),
- search_uri=str(opts.get("search_uri") or "viking://user/memories/experiences"),
+ search_uri=str(opts.get("search_uri") or "viking://~/memories/experiences"),
retrieval_top_k=int(opts.get("retrieval_top_k") or 4),
first_user_retrieval_top_k=_optional_int(opts.get("first_user_retrieval_top_k")),
first_user_inject_top_k=_optional_int(opts.get("first_user_inject_top_k")),
diff --git a/benchmark/tau2/train/rollout_executor_native.py b/benchmark/tau2/train/rollout_executor_native.py
index 38109ca23..8cb89f410 100644
--- a/benchmark/tau2/train/rollout_executor_native.py
+++ b/benchmark/tau2/train/rollout_executor_native.py
@@ -80,7 +80,7 @@ class NativeTau2RolloutExecutor:
concurrency: int = 20
seed: int = 300
retrieval_mode: str = "first_user_prewrite"
- search_uri: str = "viking://user/memories/experiences"
+ search_uri: str = "viking://~/memories/experiences"
retrieval_top_k: int = 4
first_user_retrieval_top_k: int | None = None
first_user_inject_top_k: int | None = None
diff --git a/bot/README.md b/bot/README.md
index 479dbeddd..4d93dc529 100644
--- a/bot/README.md
+++ b/bot/README.md
@@ -13,6 +13,11 @@ VikingBot is the multi-channel AI agent built into OpenViking. You can use it di
## Installation
+> **OpenViking Server requirement**: VikingBot addresses the caller's own context space through the
+> `viking://~` home alias (for example `viking://~/memories/`), so it requires a server with
+> `viking://~` support. The uid-less shorthand `viking://user/memories` is no longer emitted and is
+> rejected by newer servers.
+
### Install from PyPI
```bash
diff --git a/bot/README_CN.md b/bot/README_CN.md
index bba7db007..50b588bd7 100644
--- a/bot/README_CN.md
+++ b/bot/README_CN.md
@@ -13,6 +13,8 @@ VikingBot 是 OpenViking 内置的多渠道 AI Agent。它可以在命令行中
## 安装
+> **OpenViking Server 要求**:VikingBot 通过 `viking://~` Home 别名访问调用方自己的上下文空间(例如 `viking://~/memories/`),因此需要一个支持 `viking://~` 的 Server。不带 uid 的旧写法 `viking://user/memories` 已不再产生,且会被新版 Server 拒绝。
+
### 从 PyPI 安装
```bash
diff --git a/bot/tests/test_compile.py b/bot/tests/test_compile.py
index 0b36fb8c9..5e424e504 100644
--- a/bot/tests/test_compile.py
+++ b/bot/tests/test_compile.py
@@ -2142,7 +2142,7 @@ async def test_submit_tool_reads_explicit_workspace_file_and_rejects_memory_file
memory_tool = SubmitWikiBundleTool(
source_ids={"src_1"},
catalog_uris=set(),
- target_uri="viking://user/memories/preferences/wiki",
+ target_uri="viking://user/alice/memories/preferences/wiki",
limits=CompileLimits(),
)
rejected = await memory_tool.execute(
diff --git a/bot/tests/test_openviking_api_key_type.py b/bot/tests/test_openviking_api_key_type.py
index 402c81326..10bb4ea9a 100644
--- a/bot/tests/test_openviking_api_key_type.py
+++ b/bot/tests/test_openviking_api_key_type.py
@@ -223,14 +223,14 @@ def test_openviking_config_api_key_type_empty_values_are_inferred():
assert config.api_key == "root-key"
-def test_user_key_current_memory_targets_use_current_user_shorthand(monkeypatch):
+def test_user_key_current_memory_targets_use_home_alias(monkeypatch):
monkeypatch.setattr(ov_server_module, "load_config", lambda: _make_config("user"))
client = VikingClient()
assert client.build_current_memory_target_uris(peer_ids=["sender-1"]) == [
- "viking://user/memories/",
- "viking://user/peers/sender-1/memories/",
+ "viking://~/memories/",
+ "viking://~/peers/sender-1/memories/",
]
@@ -947,7 +947,7 @@ def test_viking_client_request_connection_uses_active_identity(monkeypatch):
assert client.agent_id == "web-playground"
assert client._namespace_policy_loaded is True
assert client.should_sender_fanout() is False
- assert client._memory_target_uri(None) == "viking://user/memories/"
+ assert client._memory_target_uri(None) == "viking://~/memories/"
assert first.kwargs == {
"url": "http://ov.local",
"api_key": "anonymous-key",
@@ -1097,7 +1097,7 @@ async def test_request_connection_search_memory_uses_request_client_only(monkeyp
assert result == {"user_memory": [], "agent_memory": []}
first = _DummyHTTPClient.instances[0]
assert len(first.find_calls) == 2
- assert first.find_calls[0][1]["target_uri"] == "viking://user/memories/"
+ assert first.find_calls[0][1]["target_uri"] == "viking://~/memories/"
assert first.find_calls[1][1]["target_uri"] == "viking://agent/web-playground/memories/"
@@ -1974,8 +1974,8 @@ async def test_search_memory_peer_ids_use_explicit_peer_uris(monkeypatch):
await client.search_memory("hello", peer_ids=["sender-1", "sender-2"], limit=5)
assert calls == [
- ("hello", "viking://user/peers/sender-1/memories/", 5),
- ("hello", "viking://user/peers/sender-2/memories/", 5),
+ ("hello", "viking://~/peers/sender-1/memories/", 5),
+ ("hello", "viking://~/peers/sender-2/memories/", 5),
]
@@ -2130,7 +2130,7 @@ async def test_viking_memory_type_quota_actor_scope_keeps_per_type_limits(tmp_pa
actor_peer_id = "sender-1"
def _current_peer_memory_target_uri(self, peer_id):
- return f"viking://user/peers/{peer_id}/memories/"
+ return f"viking://~/peers/{peer_id}/memories/"
async def find(self, *, query, target_uri, context_type=None, limit):
calls.append(
@@ -2145,7 +2145,7 @@ async def test_viking_memory_type_quota_actor_scope_keeps_per_type_limits(tmp_pa
return {
"memories": [
{
- "uri": "viking://user/peers/sender-1/memories/events/e1.md",
+ "uri": "viking://user/default/peers/sender-1/memories/events/e1.md",
"abstract": "event",
"score": 0.9,
},
@@ -2165,19 +2165,19 @@ async def test_viking_memory_type_quota_actor_scope_keeps_per_type_limits(tmp_pa
assert calls == [
{
"query": "hello",
- "target_uri": "viking://user/peers/sender-1/memories/events/",
+ "target_uri": "viking://~/peers/sender-1/memories/events/",
"context_type": "memory",
"limit": 1,
},
{
"query": "hello",
- "target_uri": "viking://user/peers/sender-1/memories/entities/",
+ "target_uri": "viking://~/peers/sender-1/memories/entities/",
"context_type": "memory",
"limit": 1,
},
{
"query": "hello",
- "target_uri": "viking://user/peers/sender-1/memories/preferences/",
+ "target_uri": "viking://~/peers/sender-1/memories/preferences/",
"context_type": "memory",
"limit": 1,
},
@@ -2232,7 +2232,7 @@ async def test_viking_memory_context_uses_target_peer_actor_for_additional_peer_
self.actor_peer_id = actor_peer_id
def _current_peer_memory_target_uri(self, peer_id):
- return f"viking://user/peers/{peer_id}/memories/"
+ return f"viking://~/peers/{peer_id}/memories/"
async def find(self, *, query, target_uri, context_type=None, limit):
if target_uri.endswith("/events/"):
@@ -2240,7 +2240,8 @@ async def test_viking_memory_context_uses_target_peer_actor_for_additional_peer_
"memories": [
{
"uri": (
- f"viking://user/peers/{self.actor_peer_id}/memories/events/e1.md"
+ "viking://user/default/peers/"
+ f"{self.actor_peer_id}/memories/events/e1.md"
),
"score": 0.9,
}
@@ -2281,8 +2282,8 @@ async def test_viking_memory_context_uses_target_peer_actor_for_additional_peer_
assert create_actor_ids == ["sender-1", "speaker-a", "speaker-a"]
assert read_calls == [
- ("sender-1", "viking://user/peers/sender-1/memories/events/e1.md", "read"),
- ("speaker-a", "viking://user/peers/speaker-a/memories/events/e1.md", "read"),
+ ("sender-1", "viking://user/default/peers/sender-1/memories/events/e1.md", "read"),
+ ("speaker-a", "viking://user/default/peers/speaker-a/memories/events/e1.md", "read"),
]
assert closed == ["speaker-a", "speaker-a", "sender-1"]
assert "content via sender-1" in result
@@ -2590,11 +2591,11 @@ async def test_openviking_search_user_key_mode_uses_current_user_namespace(monke
assert "sender-1/memories" in result
assert calls == [
("viking://resources/", None),
- ("viking://user/memories/", None),
- ("viking://user/skills/", None),
- ("viking://user/peers/sender-0/memories/", None),
- ("viking://user/peers/sender-1/memories/", None),
- ("viking://user/peers/sender-2/memories/", None),
+ ("viking://~/memories/", None),
+ ("viking://~/skills/", None),
+ ("viking://~/peers/sender-0/memories/", None),
+ ("viking://~/peers/sender-1/memories/", None),
+ ("viking://~/peers/sender-2/memories/", None),
]
@@ -2610,17 +2611,19 @@ async def test_openviking_search_actor_client_expands_current_peer_scope(monkeyp
return True
def _memory_target_uri(self, _user_id=None):
- return "viking://user/memories/"
+ return "viking://~/memories/"
def build_current_memory_target_uris(self, *, peer_ids=None, include_self=True):
- uris = ["viking://user/memories/"] if include_self else []
- uris.extend(f"viking://user/peers/{peer_id}/memories/" for peer_id in peer_ids or [])
+ uris = ["viking://~/memories/"] if include_self else []
+ uris.extend(f"viking://~/peers/{peer_id}/memories/" for peer_id in peer_ids or [])
return uris
async def search(self, query, target_uri=None, limit=20, user_id=None):
calls.append((target_uri, user_id))
return {
- "memories": [{"uri": "viking://user/peers/sender-0/memories/a.md", "score": 0.9}]
+ "memories": [
+ {"uri": "viking://user/default/peers/sender-0/memories/a.md", "score": 0.9}
+ ]
}
async def close(self):
@@ -2641,11 +2644,11 @@ async def test_openviking_search_actor_client_expands_current_peer_scope(monkeyp
assert "sender-0/memories" in result
assert calls == [
("viking://resources/", None),
- ("viking://user/memories/", None),
- ("viking://user/skills/", None),
- ("viking://user/peers/sender-0/memories/", None),
- ("viking://user/peers/sender-1/memories/", None),
- ("viking://user/peers/sender-2/memories/", None),
+ ("viking://~/memories/", None),
+ ("viking://~/skills/", None),
+ ("viking://~/peers/sender-0/memories/", None),
+ ("viking://~/peers/sender-1/memories/", None),
+ ("viking://~/peers/sender-2/memories/", None),
("close", None),
]
@@ -2677,10 +2680,10 @@ async def test_openviking_grep_default_memory_expands_current_peer(monkeypatch):
class _FakeClient:
def _memory_target_uri(self, _user_id=None):
- return "viking://user/memories/"
+ return "viking://~/memories/"
def build_current_memory_target_uris(self, *, peer_ids=None, include_self=True):
- uris = ["viking://user/memories/"] if include_self else []
+ uris = ["viking://~/memories/"] if include_self else []
uris.extend(
f"viking://user/default/peers/{peer_id}/memories/" for peer_id in peer_ids or []
)
@@ -2697,12 +2700,12 @@ async def test_openviking_grep_default_memory_expands_current_peer(monkeypatch):
await tool.execute(
SimpleNamespace(workspace_id="workspace", sender_id="sender-0"),
- uri="viking://user/memories/",
+ uri="viking://~/memories/",
pattern="hello",
)
assert calls == [
- ("viking://user/memories/", "hello", False, None),
+ ("viking://~/memories/", "hello", False, None),
("viking://user/default/peers/sender-0/memories/", "hello", False, None),
]
@@ -2714,10 +2717,10 @@ async def test_openviking_list_default_memory_expands_current_peer(monkeypatch):
class _FakeClient:
def _memory_target_uri(self, _user_id=None):
- return "viking://user/memories/"
+ return "viking://~/memories/"
def build_current_memory_target_uris(self, *, peer_ids=None, include_self=True):
- uris = ["viking://user/memories/"] if include_self else []
+ uris = ["viking://~/memories/"] if include_self else []
uris.extend(
f"viking://user/default/peers/{peer_id}/memories/" for peer_id in peer_ids or []
)
@@ -2733,12 +2736,14 @@ async def test_openviking_list_default_memory_expands_current_peer(monkeypatch):
monkeypatch.setattr(tool, "_get_client", _fake_get_client)
await tool.execute(
+ # Legacy uid-less spelling: still recognized as "the default memory target" so
+ # stored configs / LLM output keep working, but expanded to the ~ home alias.
SimpleNamespace(workspace_id="workspace", sender_id="sender-0"),
uri="viking://user/memories/",
)
assert calls == [
- ("viking://user/memories/", False),
+ ("viking://~/memories/", False),
("viking://user/default/peers/sender-0/memories/", False),
]
@@ -2750,10 +2755,10 @@ async def test_openviking_glob_root_adds_current_peer_memory(monkeypatch):
class _FakeClient:
def _memory_target_uri(self, _user_id=None):
- return "viking://user/memories/"
+ return "viking://~/memories/"
def build_current_memory_target_uris(self, *, peer_ids=None, include_self=True):
- uris = ["viking://user/memories/"] if include_self else []
+ uris = ["viking://~/memories/"] if include_self else []
uris.extend(
f"viking://user/default/peers/{peer_id}/memories/" for peer_id in peer_ids or []
)
@@ -2775,8 +2780,8 @@ async def test_openviking_glob_root_adds_current_peer_memory(monkeypatch):
assert calls == [
("*.md", "viking://resources/"),
- ("*.md", "viking://user/memories/"),
- ("*.md", "viking://user/skills/"),
+ ("*.md", "viking://~/memories/"),
+ ("*.md", "viking://~/skills/"),
("*.md", "viking://user/default/peers/sender-0/memories/"),
]
diff --git a/bot/vikingbot/agent/tools/ov_file.py b/bot/vikingbot/agent/tools/ov_file.py
index 7460ad48c..cd0196926 100644
--- a/bot/vikingbot/agent/tools/ov_file.py
+++ b/bot/vikingbot/agent/tools/ov_file.py
@@ -119,7 +119,10 @@ class OVFileTool(Tool, ABC):
def _is_default_memory_uri(self, client: VikingClient, uri: str | None) -> bool:
normalized = self._normalize_uri(uri)
- if normalized in {"", "viking://user/memories"}:
+ # ``viking://user/memories`` is the legacy spelling of the current-user default
+ # target; it is still accepted here because it survives in stored bot configs and
+ # LLM output. New emissions always use the ``viking://~`` home alias.
+ if normalized in {"", "viking://user/memories", "viking://~/memories"}:
return True
try:
return normalized == self._normalize_uri(client._memory_target_uri(None))
@@ -127,7 +130,7 @@ class OVFileTool(Tool, ABC):
return False
def _is_default_root_uri(self, uri: str | None) -> bool:
- return self._normalize_uri(uri) in {"", "viking://", "viking://user"}
+ return self._normalize_uri(uri) in {"", "viking://", "viking://user", "viking://~"}
def _peer_memory_uris(
self,
@@ -150,7 +153,7 @@ class OVFileTool(Tool, ABC):
memory_uri = self._current_memory_uri(client).rstrip("/")
if memory_uri.endswith("/memories"):
return f"{memory_uri[: -len('/memories')]}/skills/"
- return "viking://user/skills/"
+ return "viking://~/skills/"
def _fs_retrieval_uris(
self,
@@ -182,7 +185,7 @@ class OVFileTool(Tool, ABC):
uris = builder(peer_ids=self._memory_peer_ids(tool_context))
if uris:
return uris
- return [uri or "viking://user/memories/"]
+ return [uri or "viking://~/memories/"]
class VikingListTool(OVFileTool):
@@ -459,7 +462,7 @@ class VikingSearchTool(OVFileTool):
skill_uri = (
f"{memory_uri.rstrip('/')[: -len('/memories')]}/skills/"
if memory_uri.rstrip("/").endswith("/memories")
- else "viking://user/skills/"
+ else "viking://~/skills/"
)
search_targets.extend([(memory_uri, user_id), (skill_uri, user_id)])
else:
@@ -486,7 +489,7 @@ class VikingSearchTool(OVFileTool):
):
target_uris = self._dedupe_strings(
[
- "viking://user/memories/",
+ "viking://~/memories/",
*self._peer_memory_uris(client, tool_context, peer_ids=peer_ids),
]
)
diff --git a/bot/vikingbot/openviking_mount/README.md b/bot/vikingbot/openviking_mount/README.md
index 2ce2a304a..4bc4feb0e 100644
--- a/bot/vikingbot/openviking_mount/README.md
+++ b/bot/vikingbot/openviking_mount/README.md
@@ -175,7 +175,7 @@ OpenViking URI 本地路径
------------------- ------------------
viking://resources/foo -> {mount_point}/resources/foo
viking://session/bar -> {mount_point}/session/bar
-viking://user/baz -> {mount_point}/user/baz
+viking://user/<uid>/baz -> {mount_point}/user/<uid>/baz
```
## 测试
diff --git a/bot/vikingbot/openviking_mount/ov_server.py b/bot/vikingbot/openviking_mount/ov_server.py
index c4858d245..30c30926a 100644
--- a/bot/vikingbot/openviking_mount/ov_server.py
+++ b/bot/vikingbot/openviking_mount/ov_server.py
@@ -397,7 +397,7 @@ class VikingClient:
user_space = self._user_space_fragment(user_id)
if user_space:
return f"viking://user/{user_space}/memories/"
- return "viking://user/memories/"
+ return "viking://~/memories/"
def _owner_user_id_for_uri(self, uri: Optional[str]) -> Optional[str]:
if not self._is_root_key_mode():
@@ -408,6 +408,11 @@ class VikingClient:
return None
if len(parts) < 2 or parts[0] != "user":
return None
+ # Mirrors the server's reserved user-space segment set. We keep the duplicated
+ # allowlist so legacy ``viking://user/<reserved>/...`` URIs (still present in stored
+ # bot configs and occasionally produced by LLM output) are not misrouted to a user
+ # named e.g. "memories" while running in root-key mode. Home-alias URIs
+ # (``viking://~/...``) never reach this branch and return None naturally.
if parts[1] in {"memories", "resources", "skills", "peers", "privacy", "sessions"}:
return None
owner_user_id = parts[1]
@@ -435,7 +440,7 @@ class VikingClient:
if not normalized_peer_id:
raise ValueError("peer_id is required for peer memory target")
if self._is_user_key_mode() or self._has_request_connection():
- return f"viking://user/peers/{normalized_peer_id}/memories/"
+ return f"viking://~/peers/{normalized_peer_id}/memories/"
user_space = self._current_user_space_fragment()
if not user_space:
raise ValueError("peer memory target requires current user_id")
@@ -739,7 +744,7 @@ class VikingClient:
"""读取用户 profile。"""
effective_user_id = self._effective_user_id(user_id)
if not effective_user_id:
- return await self.read_content(uri="viking://user/memories/profile.md", level="read")
+ return await self.read_content(uri="viking://~/memories/profile.md", level="read")
uri = f"{self._memory_target_uri(effective_user_id)}profile.md"
result = await self.read_content(uri=uri, level="read", user_id=effective_user_id)
diff --git a/bot/vikingbot/tests/unit/test_openviking_peer_identity.py b/bot/vikingbot/tests/unit/test_openviking_peer_identity.py
index feed35b6e..7e0c652fd 100644
--- a/bot/vikingbot/tests/unit/test_openviking_peer_identity.py
+++ b/bot/vikingbot/tests/unit/test_openviking_peer_identity.py
@@ -219,7 +219,7 @@ async def test_read_peer_profile_uses_current_user_peer_alias(monkeypatch):
profile = await client.read_peer_profile("telegram:alice")
assert profile == "Alice profile"
- assert calls == [(f"viking://user/peers/{TELEGRAM_ALICE_PEER_ID}/memories/profile.md", "read")]
+ assert calls == [(f"viking://~/peers/{TELEGRAM_ALICE_PEER_ID}/memories/profile.md", "read")]
@pytest.mark.asyncio
@@ -255,7 +255,7 @@ async def test_read_user_profile_uses_current_user_self_alias_for_user_key(monke
profile = await client.read_user_profile("sender-is-peer")
assert profile == "Self profile"
- assert calls == [("viking://user/memories/profile.md", "read")]
+ assert calls == [("viking://~/memories/profile.md", "read")]
@pytest.mark.asyncio
@@ -470,7 +470,7 @@ async def test_search_with_peer_id_uses_peer_target_uri_without_forwarding_peer_
assert calls == [
{
"query": "hello",
- "target_uri": f"viking://user/peers/{TELEGRAM_ALICE_PEER_ID}/memories/",
+ "target_uri": f"viking://~/peers/{TELEGRAM_ALICE_PEER_ID}/memories/",
"limit": 3,
}
]
diff --git a/docs/en/agent-integrations/16-capability-reference.md b/docs/en/agent-integrations/16-capability-reference.md
index a73f540a7..897d118f6 100644
--- a/docs/en/agent-integrations/16-capability-reference.md
+++ b/docs/en/agent-integrations/16-capability-reference.md
@@ -229,7 +229,7 @@ Recall for the JS-family harnesses is managed through a three-level degradation
1. **Context face**: Calls `POST /api/v1/search/search` with `mode:"context"` and `purpose:"coding"`. Its core design principle is "declare intent only, leave the mechanism to the server." Parameters like `quotas`, `max_tokens`, `query_expansion`, and `rewrite_max_bullets` are transmitted only if explicitly configured by the user (indicated by a sentinel field); otherwise, server defaults are applied.
2. **Legacy `/recall`**: If the context face request returns a 400 or 422 error and the response body contains marker fields like `extra`, `mode`, or `unexpected`, the server is identified as an older version. A 6-hour negative cache is then written locally to `~/.openviking/state/context-face.json`. Because this is a machine-wide shared file, once one harness flags it, every JS-family harness on that machine will bypass the context face stage. The call then degrades to the deprecated `/api/v1/search/recall` endpoint. If `peer_scope` is rejected, it retries once without that parameter.
-3. **Raw find fallback**: Concurrently requests `viking://user/memories` and `viking://user/skills` by calling `POST /search/find` twice. (Note: resources are deliberately excluded from automatic recall; resource documents are fetched by the model invoking `search` itself). The client then re-ranks the results locally (using weight rules: leaf +0.12, time intent +0.10, preference intent +0.08, and lexical overlap ≤0.2), deduplicates them, and fills up to the client token budget. The `recallTokenBudget`, `recallMaxContentChars`, and `recallPreferAbstract` configurations take effect *only* at this level. Under the context face, the injection budget is dictated by the server's `max_tokens` (which defaults to 1600).
+3. **Raw find fallback**: Concurrently requests `viking://~/memories` and `viking://~/skills` by calling `POST /search/find` twice. (Note: resources are deliberately excluded from automatic recall; resource documents are fetched by the model invoking `search` itself). The client then re-ranks the results locally (using weight rules: leaf +0.12, time intent +0.10, preference intent +0.08, and lexical overlap ≤0.2), deduplicates them, and fills up to the client token budget. The `recallTokenBudget`, `recallMaxContentChars`, and `recallPreferAbstract` configurations take effect *only* at this level. Under the context face, the injection budget is dictated by the server's `max_tokens` (which defaults to 1600).
On the server side, `session_id` handling diverges into two distinct execution paths:
@@ -578,7 +578,7 @@ Each card serves as a quick-reference entry point. It records only the facts and
- **Integration docs**: [Hermes Agent](./05-hermes.md)
- **Form**: Implemented as a MemoryProvider bundled directly with Hermes (a single-file Python implementation of 3725 lines, shipped alongside Hermes). It connects directly via `httpx`, eliminating the need for additional plugin installations. It provides 6 tools and over 10 lifecycle hooks (including `prefetch`, `sync_turn`, `on_session_end`, `on_session_switch`, and `on_memory_write`). The baseline is release `e12626b3` (equivalent to brew 2026.7.7.2).
- **Highlights**: Boasts the most comprehensive resource-ingestion surface: `viking_add_resource` supports HTTP, Git, SSH, `file://`, temporary uploads of local files, and zip-packing local directories for upload (automatically skipping symlinks and out-of-tree files). The `viking_remember` tool writes memory files directly, bypassing session commits or extractions. A local server can be initialized on demand; if the configured local endpoint is unreachable, it is automatically launched via `subprocess.Popen openviking-server`. It supports retries with an injected trusted identity. Commits are guaranteed to complete whether triggered by a normal exit, Ctrl+C, SIGTERM, or SIGHUP ([§3.3.3](#_3-3-3-shutdown-method-×-harness-outcome-matrix)).
-- **Behavior**: During recall, only the preferred `search/search` path carries a session ID and routes to path B (`mode="deep"`). Conversely, the `auto` and `fast` modes call `/find` without a session ID ([§3.2.2](#_3-2-2-decision-matrix)). The `queue_prefetch` hook is implemented synchronously without warm-up. Subagents configured with `skip_memory=True` will not interact with OpenViking ([§3.3.5](#_3-3-5-subagent-session-comparison)). This integration lacks profile injection, a status line, and slash commands. Commits strictly follow a "keep 0" policy; if the queue drain does not finish cleanly, the commit is skipped for that round. Additionally, the in-process queue is never written to disk. Session IDs follow the `%Y%m%d_%H%M%S_<hex6>` format. Recall parameters are strictly defined: 6 results, a 0.15 threshold, a 4000-character budget, and a 4-second total timeout. Memory URIs are formatted as `viking://user/peers/{agent}/memories/{subdir}/mem_<uuid12>.md`. The shutdown sequence incorporates a 1.5-second SIGTERM grace period alongside a 30-second exit watchdog. Finally, a complementary path (`openviking-server ingest hermes`) enables offline replays, though this is disabled by default ([§7](#_7-appendix-non-coding-integrations-at-a-glance) E).
+- **Behavior**: During recall, only the preferred `search/search` path carries a session ID and routes to path B (`mode="deep"`). Conversely, the `auto` and `fast` modes call `/find` without a session ID ([§3.2.2](#_3-2-2-decision-matrix)). The `queue_prefetch` hook is implemented synchronously without warm-up. Subagents configured with `skip_memory=True` will not interact with OpenViking ([§3.3.5](#_3-3-5-subagent-session-comparison)). This integration lacks profile injection, a status line, and slash commands. Commits strictly follow a "keep 0" policy; if the queue drain does not finish cleanly, the commit is skipped for that round. Additionally, the in-process queue is never written to disk. Session IDs follow the `%Y%m%d_%H%M%S_<hex6>` format. Recall parameters are strictly defined: 6 results, a 0.15 threshold, a 4000-character budget, and a 4-second total timeout. Memory URIs are formatted as `viking://~/peers/{agent}/memories/{subdir}/mem_<uuid12>.md`. The shutdown sequence incorporates a 1.5-second SIGTERM grace period alongside a 30-second exit watchdog. Finally, a complementary path (`openviking-server ingest hermes`) enables offline replays, though this is disabled by default ([§7](#_7-appendix-non-coding-integrations-at-a-glance) E).
- **Config**: Configured through `OPENVIKING_ENDPOINT` (not `_URL`), 8 `OPENVIKING_RECALL_*` environment variables, and `config.yaml`. In `use_ovcli_config` mode, the corresponding variables in `.env` are cleared.
- **Dimension index**: tool surface [§1.1](#_1-1-active-tool-surface-agentic-calls) | recall [§3.2](#_3-2-automatic-recall-and-injection) | commit [§3.3.2](#_3-3-2-regular-commit-triggers)/[§3.3.3](#_3-3-3-shutdown-method-×-harness-outcome-matrix) | deletion [§3.5](#_3-5-type-boundaries-for-writes-and-deletes).
## ov CLI
diff --git a/docs/en/api/02-resources.md b/docs/en/api/02-resources.md
index 3904a196c..066ab69c4 100644
--- a/docs/en/api/02-resources.md
+++ b/docs/en/api/02-resources.md
@@ -185,7 +185,7 @@ This endpoint is the core entry point for resource management, supporting adding
**Additional Notes**:
- `to` and `parent` cannot be specified together. Use `create_parent=true` with `parent` when the parent directory should be created automatically.
- If both `to` and `parent` are omitted, the server may use the current user's `add_targets.resource_uri` override, then `server.user_config_defaults.add_targets.resource_uri`. If neither is set, legacy target resolution is unchanged.
-- Resource targets may use public `viking://resources/...`, current-user shorthand `viking://user/resources/...`, explicit user `viking://user/{user_id}/resources/...`, or peer `viking://user/{user_id}/peers/{peer_id}/resources/...` paths. Current-user shorthand is canonicalized with the authenticated request identity.
+- Resource targets may use public `viking://resources/...`, the home alias `viking://~/resources/...`, explicit user `viking://user/{user_id}/resources/...`, or peer `viking://user/{user_id}/peers/{peer_id}/resources/...` paths. The home alias is expanded to the canonical path using the authenticated request identity; the uid-less spelling `viking://user/resources/...` is rejected with an error pointing at `viking://~/resources/...`.
- `user_id` and `peer_id` path segments must be safe single-segment identifiers, for example `alice` or `web-visitor-alice`. Values with path separators, `.`, `..`, `:`, or `+` are rejected.
- `path` and `temp_file_id` cannot be specified together
- Raw HTTP calls for local files require first uploading via [temp_upload](#temp_upload) to obtain `temp_file_id`
@@ -293,7 +293,7 @@ curl -X POST http://localhost:1933/api/v1/resources \
-H "X-API-Key: your-key" \
-d "{
\"temp_file_id\": \"$TEMP_FILE_ID\",
- \"parent\": \"viking://user/resources/docs\",
+ \"parent\": \"viking://~/resources/docs\",
\"create_parent\": true
}"
@@ -374,7 +374,7 @@ result = client.add_resource(
# Add to the current user's private resource root
result = client.add_resource(
"./documents/guide.md",
- parent="viking://user/resources/docs",
+ parent="viking://~/resources/docs",
create_parent=True,
)
@@ -481,7 +481,7 @@ ov add-resource https://example.feishu.cn/docx/doc_token \
ov add-resource ./documents/guide.md --parent viking://resources/docs
# Add under the current user's private resource root
-ov add-resource ./documents/guide.md --parent viking://user/resources/docs
+ov add-resource ./documents/guide.md --parent viking://~/resources/docs
# Add under a specific peer's private resource root
ov add-resource ./documents/guide.md \
diff --git a/docs/en/api/04-skills.md b/docs/en/api/04-skills.md
index fa2db26a3..3c041ac63 100644
--- a/docs/en/api/04-skills.md
+++ b/docs/en/api/04-skills.md
@@ -14,9 +14,10 @@ OpenViking supports multiple skill definition formats:
### Skill Storage Structure
-Skills are stored under the current user's skills root. The short URI
-`viking://user/skills/` resolves to `viking://user/{user_id}/skills/` for the
-authenticated request:
+Skills are stored under the current user's skills root. The home alias
+`viking://~/skills/` expands to `viking://user/{user_id}/skills/` for the
+authenticated request (the uid-less spelling `viking://user/skills/` is no longer
+accepted):
```
viking://user/{user_id}/skills/
@@ -189,7 +190,7 @@ Skills are a special type of resource that define actions or tools agents can pe
- **Targeting**:
- Skills are always user-scoped. `add_skill` does not accept `to`, `parent`, or `root_uri`.
- Peer-scoped skill roots are not supported; actor peer filtering only applies to peer memories/resources, not peer skills.
- - Use `viking://user/skills/...` as current-user shorthand when listing, reading, deleting, or searching skills.
+ - Use the home alias `viking://~/skills/...` to address your own skills when listing, reading, deleting, or searching. The uid-less `viking://user/skills/...` spelling returns an error with a corrective hint.
- **Supported data formats**:
1. **Dict (Skill format)**: Includes `name`, `description`, `content`, etc.
diff --git a/docs/en/api/05-sessions.md b/docs/en/api/05-sessions.md
index cf6b60034..fabfce738 100644
--- a/docs/en/api/05-sessions.md
+++ b/docs/en/api/05-sessions.md
@@ -1049,7 +1049,7 @@ ContextPart(
ToolPart(
tool_id="call_123",
tool_name="search_web",
- skill_uri="viking://user/skills/search-web/",
+ skill_uri="viking://~/skills/search-web/",
tool_input={"query": "OAuth best practices"},
tool_output="",
tool_status="pending" # "pending", "running", "completed", "error"
@@ -1354,7 +1354,7 @@ curl -X POST http://localhost:1933/api/v1/sessions/a1b2c3d4/used \
curl -X POST http://localhost:1933/api/v1/sessions/a1b2c3d4/used \
-H "Content-Type: application/json" \
-H "X-API-Key: your-key" \
- -d '{"skill": {"uri": "viking://user/skills/search-web/", "input": {"query": "OAuth"}, "output": "Results...", "success": true}}'
+ -d '{"skill": {"uri": "viking://~/skills/search-web/", "input": {"query": "OAuth"}, "output": "Results...", "success": true}}'
```
**Response Example**
diff --git a/docs/en/api/06-retrieval.md b/docs/en/api/06-retrieval.md
index 690d5ba2e..c70253f25 100644
--- a/docs/en/api/06-retrieval.md
+++ b/docs/en/api/06-retrieval.md
@@ -72,7 +72,7 @@ The `find()` method performs pure vector similarity search for simple query scen
**Target resolution notes**:
- With empty `target_uri`, non-ROOT retrieval searches the current user root (`viking://user/{user}`) and shared `viking://resources`.
- To filter the current user's peer collection to one peer for filesystem and retrieval operations, send `X-OpenViking-Actor-Peer: <peer_id>` or construct the SDK/CLI client with `actor_peer_id`. See [Multi-Tenant: Peer Collection Filter](../concepts/11-multi-tenant.md#peer-restricted-view).
-- Current-user shorthand target URIs such as `viking://user/memories`, `viking://user/resources`, and `viking://user/skills` are canonicalized from the authenticated request identity.
+- Home-alias target URIs such as `viking://~/memories`, `viking://~/resources`, and `viking://~/skills` are expanded to the canonical path from the authenticated request identity. The uid-less spelling `viking://user/memories` (and the same shape for `resources`, `skills`, `peers`, `privacy`, `sessions`) is rejected with an error pointing at the `viking://~/...` form.
**Image search notes**:
- Image queries use the image vector as the query and search L2 resource leaf nodes in the target scope by default. Results are not limited to image files; multimodal embedding decides similarity between the query image and text/image resources.
@@ -231,13 +231,13 @@ results = client.find(
# Search only in user memories
results = client.find(
"preferences",
- target_uri="viking://user/memories"
+ target_uri="viking://~/memories"
)
# Search only in current-user resources
results = client.find(
"private docs",
- target_uri="viking://user/resources"
+ target_uri="viking://~/resources"
)
# Search with the peer collection filtered to one peer
@@ -251,7 +251,7 @@ peer_results = peer_client.find("invoice follow-up")
# Search only in skills
results = client.find(
"web search",
- target_uri="viking://user/skills"
+ target_uri="viking://~/skills"
)
# Search in specific project
diff --git a/docs/en/api/08-admin.md b/docs/en/api/08-admin.md
index ce9600555..9c2b6ca9f 100644
--- a/docs/en/api/08-admin.md
+++ b/docs/en/api/08-admin.md
@@ -185,8 +185,9 @@ Create a new workspace with its first admin user.
- In `trusted` mode, `user_key` is omitted from the response
- Omit `seed` for the default random API key. Treat seed values as secret material; short seeds can make the key guessable.
- Account-level namespace isolation settings are no longer supported. User memory uses user-scoped namespaces, and one-to-many external participants are represented with `peer_id`.
-- `user_config.add_targets.resource_uri` must be a writable resource directory URI: `viking://resources` or `viking://resources/...`, `viking://user/resources` or `viking://user/resources/...`, `viking://user/{user_id}/resources` or `viking://user/{user_id}/resources/...`, or `viking://user/{user_id}/peers/{peer_id}/resources` or `viking://user/{user_id}/peers/{peer_id}/resources/...`.
-- `user_config.add_targets.skill_uri` must be `viking://user/skills` or `viking://agent/skills`. Explicit `viking://user/{user_id}/skills` is not accepted in v1.
+- `user_config.add_targets.resource_uri` must be a writable resource directory URI: `viking://resources` or `viking://resources/...`, `viking://~/resources` or `viking://~/resources/...`, `viking://user/{user_id}/resources` or `viking://user/{user_id}/resources/...`, or `viking://user/{user_id}/peers/{peer_id}/resources` or `viking://user/{user_id}/peers/{peer_id}/resources/...`.
+- `user_config.add_targets.skill_uri` must be `viking://~/skills` or `viking://agent/skills`. Explicit `viking://user/{user_id}/skills` is not accepted in v1.
+- Legacy spellings `viking://user/resources[/...]` and `viking://user/skills` are still accepted here and normalized to the `viking://~/...` form (the server logs an info message). Everywhere else, the uid-less spelling is rejected at the request boundary — write new configs with `viking://~/...`.
#### 3. Usage Examples
@@ -261,8 +262,8 @@ result = client.admin_create_account(
"alice",
user_config={
"add_targets": {
- "resource_uri": "viking://user/resources",
- "skill_uri": "viking://user/skills",
+ "resource_uri": "viking://~/resources",
+ "skill_uri": "viking://~/skills",
}
},
)
@@ -288,8 +289,8 @@ result, err = client.AdminCreateAccountWithOptions(ctx, "acme-private", "alice",
Seed: &seed,
UserConfig: map[string]any{
"add_targets": map[string]any{
- "resource_uri": "viking://user/resources",
- "skill_uri": "viking://user/skills",
+ "resource_uri": "viking://~/resources",
+ "skill_uri": "viking://~/skills",
},
},
})
@@ -303,7 +304,7 @@ ov --sudo admin create-account acme --admin alice
ov --sudo admin create-account acme --admin alice --seed alice-seed
ov --sudo admin create-account acme-private --admin alice \
- --user-config-json '{"add_targets":{"resource_uri":"viking://user/resources","skill_uri":"viking://user/skills"}}'
+ --user-config-json '{"add_targets":{"resource_uri":"viking://~/resources","skill_uri":"viking://~/skills"}}'
```
**Response Example**
@@ -534,8 +535,9 @@ Register a new user in a workspace.
- Omit `seed` for the default random API key. Treat seed values as secret material; short seeds can make the key guessable.
- ADMIN can only register users in their own account
- The `"root"` role cannot be minted through user registration
-- `user_config.add_targets.resource_uri` must be a writable resource directory URI: `viking://resources` or `viking://resources/...`, `viking://user/resources` or `viking://user/resources/...`, `viking://user/{user_id}/resources` or `viking://user/{user_id}/resources/...`, or `viking://user/{user_id}/peers/{peer_id}/resources` or `viking://user/{user_id}/peers/{peer_id}/resources/...`.
-- `user_config.add_targets.skill_uri` must be `viking://user/skills` or `viking://agent/skills`. Explicit `viking://user/{user_id}/skills` is not accepted in v1.
+- `user_config.add_targets.resource_uri` must be a writable resource directory URI: `viking://resources` or `viking://resources/...`, `viking://~/resources` or `viking://~/resources/...`, `viking://user/{user_id}/resources` or `viking://user/{user_id}/resources/...`, or `viking://user/{user_id}/peers/{peer_id}/resources` or `viking://user/{user_id}/peers/{peer_id}/resources/...`.
+- `user_config.add_targets.skill_uri` must be `viking://~/skills` or `viking://agent/skills`. Explicit `viking://user/{user_id}/skills` is not accepted in v1.
+- Legacy spellings `viking://user/resources[/...]` and `viking://user/skills` are still accepted here and normalized to the `viking://~/...` form (the server logs an info message). Everywhere else, the uid-less spelling is rejected at the request boundary — write new configs with `viking://~/...`.
#### 3. Usage Examples
@@ -572,7 +574,7 @@ result = client.admin_register_user(
"acme",
"bob-private",
role="user",
- user_config={"add_targets": {"resource_uri": "viking://user/resources/project-a"}},
+ user_config={"add_targets": {"resource_uri": "viking://~/resources/project-a"}},
)
```
@@ -595,7 +597,7 @@ seed := "bob-seed"
result, err = client.AdminRegisterUserWithOptions(ctx, "acme", "bob-private", "user", &openviking.AdminRegisterUserOptions{
Seed: &seed,
UserConfig: map[string]any{
- "add_targets": map[string]any{"resource_uri": "viking://user/resources/project-a"},
+ "add_targets": map[string]any{"resource_uri": "viking://~/resources/project-a"},
},
})
```
@@ -611,7 +613,7 @@ ov admin register-user acme bob --role user --seed bob-seed
ov --sudo admin register-user acme bob --role user
ov admin register-user acme bob-private --role user \
- --user-config-json '{"add_targets":{"resource_uri":"viking://user/resources/project-a"}}'
+ --user-config-json '{"add_targets":{"resource_uri":"viking://~/resources/project-a"}}'
```
**Response Example**
diff --git a/docs/en/concepts/02-context-types.md b/docs/en/concepts/02-context-types.md
index 1a680c355..b675a22df 100644
--- a/docs/en/concepts/02-context-types.md
+++ b/docs/en/concepts/02-context-types.md
@@ -56,17 +56,17 @@ Memories are durable knowledge learned from interactions and task execution. The
| Type | Default location | Description |
|------|------------------|-------------|
-| **profile** | `user/memories/profile.md` | Basic user information |
-| **preferences** | `user/memories/preferences/` | User preferences organized by topic |
-| **entities** | `user/memories/entities/` | Knowledge about people, projects, organizations, and other entities |
-| **events** | `user/memories/events/` | Decisions, milestones, and other event records |
-| **identity** | `user/memories/identity.md` | Assistant name, persona, temperament, and self-introduction |
-| **soul** | `user/memories/soul.md` | Assistant principles, boundaries, style, and continuity |
-| **cases** | `user/memories/cases/` | Task cases used for training and evaluation |
-| **trajectories** | `user/memories/trajectories/` | Reusable task-execution trajectories |
-| **experiences** | `user/memories/experiences/` | Reusable experience distilled from execution outcomes |
-
-The `user/...` entries above are current-user short paths. The server resolves them to `viking://user/{user_id}/...`. When the memory policy permits Peer memory, supported types may instead be written under `viking://user/{user_id}/peers/{peer_id}/memories/...`. Applications can extend or adjust memory types with custom templates.
+| **profile** | `~/memories/profile.md` | Basic user information |
+| **preferences** | `~/memories/preferences/` | User preferences organized by topic |
+| **entities** | `~/memories/entities/` | Knowledge about people, projects, organizations, and other entities |
+| **events** | `~/memories/events/` | Decisions, milestones, and other event records |
+| **identity** | `~/memories/identity.md` | Assistant name, persona, temperament, and self-introduction |
+| **soul** | `~/memories/soul.md` | Assistant principles, boundaries, style, and continuity |
+| **cases** | `~/memories/cases/` | Task cases used for training and evaluation |
+| **trajectories** | `~/memories/trajectories/` | Reusable task-execution trajectories |
+| **experiences** | `~/memories/experiences/` | Reusable experience distilled from execution outcomes |
+
+The `~/...` entries above use the home alias `viking://~`, which the server expands to `viking://user/{user_id}/...` for the authenticated caller. When the memory policy permits Peer memory, supported types may instead be written under `viking://user/{user_id}/peers/{peer_id}/memories/...`. Applications can extend or adjust memory types with custom templates.
The schema-defined `memories/tools/` and `memories/skills/` types are disabled. They are separate from standalone Skills stored under `viking://user/{user_id}/skills/{skill_name}/SKILL.md`, which remain supported.
@@ -82,7 +82,7 @@ task = await client.get_task(commit["task_id"]) # Poll until task["status"] ==
# Search memories
results = await client.find(
"UI preferences",
- target_uri="viking://user/memories/"
+ target_uri="viking://~/memories/"
)
```
@@ -99,7 +99,7 @@ Skills are capabilities that Agents can invoke, belonging to the **AgentDefinedC
### Storage Location
```
-viking://user/skills/{skill-name}/ # Default storage path
+viking://~/skills/{skill-name}/ # Default storage path
├── .abstract.md # L0: Short description
├── .overview.md # L1: Directory overview (after generation)
├── SKILL.md # L2: Skill definition
@@ -126,7 +126,7 @@ AgentDefinedContextType includes the following subtypes, all stored under the `v
### Usage
```python
-# Add skill (defaults to viking://user/skills/)
+# Add skill (defaults to viking://~/skills/)
await client.add_skill({
"name": "search-web",
"description": "Search the web for information",
@@ -139,7 +139,7 @@ ov skills add search-web -p viking://agent/skills
# Search user skills
results = await client.find(
"web search",
- target_uri="viking://user/skills/"
+ target_uri="viking://~/skills/"
)
# Search global agent skills
diff --git a/docs/en/concepts/04-viking-uri.md b/docs/en/concepts/04-viking-uri.md
index c42698d27..e0d664888 100644
--- a/docs/en/concepts/04-viking-uri.md
+++ b/docs/en/concepts/04-viking-uri.md
@@ -50,6 +50,9 @@ each caller.
user and admin callers; root-role and unauthenticated contexts, along with places that
demand an already-canonical URI (internal storage paths, background tasks), reject the
alias instead of guessing a user.
+- Replaces the removed uid-less shorthand: `viking://user/<segment>/...` for `memories`,
+ `resources`, `skills`, `peers`, `privacy`, and `sessions` is rejected at USER/ADMIN
+ request boundaries with an error that names the `viking://~/...` replacement.
## Initial Directory Structure
@@ -99,25 +102,27 @@ viking://resources/my-project/docs/api.md # Specific file
### User Data
```
-viking://user/ # User root
-viking://user/memories/ # All user memories
-viking://user/memories/preferences/ # User preferences
-viking://user/memories/preferences/coding # Specific preference
-viking://user/memories/entities/ # Entity memories
-viking://user/memories/events/ # Event memories
-viking://user/resources/ # Current user's resources
-viking://user/resources/docs/ # Current user's resource directory
+viking://user/ # Container of all user spaces (a user key lists only its own)
+viking://~/ # Your own user root (expands to viking://user/{user_id}/)
+viking://~/memories/ # All your memories
+viking://~/memories/preferences/ # Your preferences
+viking://~/memories/preferences/coding # Specific preference
+viking://~/memories/entities/ # Entity memories
+viking://~/memories/events/ # Event memories
+viking://~/resources/ # Your private resources
+viking://~/resources/docs/ # Your private resource directory
+viking://user/{user_id}/memories/ # Explicit user path (your own id; other ids need admin/root)
```
### User Skills and Peer Content
```
-viking://user/skills/ # Current user's skills
-viking://user/skills/search-web # Specific skill
-viking://user/memories/ # Current user's memories
-viking://user/memories/cases/ # Task cases used for training and evaluation
-viking://user/memories/trajectories/ # Reusable task-execution trajectories
-viking://user/memories/experiences/ # Experience distilled from execution outcomes
+viking://~/skills/ # Your skills
+viking://~/skills/search-web # Specific skill
+viking://~/memories/ # Your memories
+viking://~/memories/cases/ # Task cases used for training and evaluation
+viking://~/memories/trajectories/ # Reusable task-execution trajectories
+viking://~/memories/experiences/ # Experience distilled from execution outcomes
viking://user/{user_id}/peers/{peer_id}/memories/
viking://user/{user_id}/peers/{peer_id}/resources/
```
@@ -136,9 +141,16 @@ viking://agent/payments/ap2/ # Payment configuration (pla
without agent_id isolation. Legacy (0.3.x) data under `viking://agent/...` remains accessible
via a read-only compatibility entry, but new data should be written according to the new directory semantics.
-The short `viking://user/...` form is relative to the current request identity.
-OpenViking expands it internally to explicit namespace paths such as
-`viking://user/{user_id}/...` before storage and retrieval.
+The home alias `viking://~/...` is relative to the current request identity. OpenViking
+expands it internally to the explicit namespace path `viking://user/{user_id}/...` before
+storage and retrieval, and responses echo the expanded form.
+
+The older uid-less spelling — `viking://user/memories/...` and the same shape for
+`resources`, `skills`, `peers`, `privacy`, and `sessions` — is no longer accepted at the
+request boundary. Such requests fail with an error that points at the `viking://~/...`
+replacement. `viking://user` itself is the container of user spaces, not a shortcut to
+your own root: listing it with a user key shows only your own space.
+
Identity path segments such as `{user_id}` and `{peer_id}` must be safe single
segments, for example `alice` or `web-visitor-alice`.
@@ -149,7 +161,7 @@ viking://user/{user_id}/sessions/{session_id}/ # Session root
viking://user/{user_id}/sessions/{session_id}/messages # Session messages
viking://user/{user_id}/sessions/{session_id}/tools # Tool executions
viking://user/{user_id}/sessions/{session_id}/history # Archived history
-viking://user/sessions/{session_id}/ # Current-user short form
+viking://~/sessions/{session_id}/ # Your own session, via the home alias
```
`viking://session/{session_id}` is accepted as a backward-compatible alias for
@@ -305,22 +317,22 @@ results = client.find(
target_uri="viking://resources/"
)
-# Search only in current-user resources
+# Search only in your own resources
results = client.find(
"private project notes",
- target_uri="viking://user/resources/"
+ target_uri="viking://~/resources/"
)
-# Search only in user memories
+# Search only in your own memories
results = client.find(
"coding preferences",
- target_uri="viking://user/memories/"
+ target_uri="viking://~/memories/"
)
-# Search only in user skills
+# Search only in your own skills
results = client.find(
"web search",
- target_uri="viking://user/skills/"
+ target_uri="viking://~/skills/"
)
# Search only in global agent skills
@@ -375,11 +387,11 @@ Each directory may contain special files:
# Add resources to the shared account resource scope
await client.add_resource(url, to="viking://resources/project/")
-# Add private resources to the current user's resource root
-await client.add_resource(path, parent="viking://user/resources/project/")
+# Add private resources to your own resource root
+await client.add_resource(path, parent="viking://~/resources/project/")
-# Skills are added to the current user's skills root by default
-await client.add_skill(skill) # canonical root: viking://user/skills/
+# Skills are added to your own skills root by default
+await client.add_skill(skill) # default root: viking://~/skills/
# Write to the global agent skills root (public/shared) via -p override
ov skills add xxx -p viking://agent/skills/
diff --git a/docs/en/concepts/05-storage.md b/docs/en/concepts/05-storage.md
index 39805cf5d..2f5efd38a 100644
--- a/docs/en/concepts/05-storage.md
+++ b/docs/en/concepts/05-storage.md
@@ -41,8 +41,8 @@ VikingFS is the unified URI abstraction layer that hides underlying storage deta
```
viking://resources/docs/auth → /local/{account_id}/resources/docs/auth
-viking://user/memories → /local/{account_id}/user/{user_id}/memories
-viking://user/skills → /local/{account_id}/user/{user_id}/skills
+viking://~/memories → /local/{account_id}/user/{user_id}/memories
+viking://~/skills → /local/{account_id}/user/{user_id}/skills
```
### Core API
diff --git a/docs/en/concepts/06-extraction.md b/docs/en/concepts/06-extraction.md
index bf168da73..38b67c7e2 100644
--- a/docs/en/concepts/06-extraction.md
+++ b/docs/en/concepts/06-extraction.md
@@ -168,7 +168,7 @@ This routing applies to short and long code files alike.
| Phase | Resource | Memory | Skill |
|-------|----------|--------|-------|
| **Parser** | Common flow | Common flow | Common flow |
-| **Base URI** | `viking://resources` | `viking://user/memories` | `viking://user/skills` |
+| **Base URI** | `viking://resources` | `viking://~/memories` | `viking://~/skills` |
| **TreeBuilder scope** | resources | user | user |
| **SemanticMsg type** | resource | memory | skill |
@@ -193,7 +193,7 @@ await client.add_skill({
"content": "# search-web\\n..."
})
-# Flow: Direct write to viking://user/skills/{name}/ → SemanticQueue
+# Flow: Direct write to viking://~/skills/{name}/ → SemanticQueue
```
### Memory Extraction
diff --git a/docs/en/concepts/07-retrieval.md b/docs/en/concepts/07-retrieval.md
index 6464c1b89..d21a7ba4a 100644
--- a/docs/en/concepts/07-retrieval.md
+++ b/docs/en/concepts/07-retrieval.md
@@ -92,9 +92,9 @@ Step 5: Convert to MatchedContext
| context_type | Root Directories |
|--------------|------------------|
-| MEMORY | `viking://user/memories` |
+| MEMORY | `viking://~/memories` |
| RESOURCE | `viking://resources` |
-| SKILL | `viking://user/skills` |
+| SKILL | `viking://~/skills` |
### Recursive Search Algorithm
diff --git a/docs/en/concepts/08-session.md b/docs/en/concepts/08-session.md
index cdc7cd1d1..f08130a9a 100644
--- a/docs/en/concepts/08-session.md
+++ b/docs/en/concepts/08-session.md
@@ -35,7 +35,7 @@ session.add_message(
"assistant",
[
TextPart("Here's how..."),
- ContextPart(uri="viking://user/memories/profile.md"),
+ ContextPart(uri="viking://~/memories/profile.md"),
]
)
@@ -52,11 +52,11 @@ session.add_message(
```python
# Record used contexts
-session.used(contexts=["viking://user/memories/profile.md"])
+session.used(contexts=["viking://~/memories/profile.md"])
# Record used skill
session.used(skill={
- "uri": "viking://user/skills/code-search",
+ "uri": "viking://~/skills/code-search",
"input": "search config",
"output": "found 3 files",
"success": True
@@ -242,7 +242,7 @@ viking://user/{user_id}/sessions/{session_id}/
└── tools/
└── {tool_id}/tool.json
-viking://user/memories/
+viking://~/memories/
├── profile.md
├── identity.md
├── soul.md
@@ -254,11 +254,12 @@ viking://user/memories/
└── experiences/
```
-`viking://user/sessions/{session_id}` is accepted as a short form relative to
-the current request user and is canonicalized to
-`viking://user/{user_id}/sessions/{session_id}`. The old
-`viking://session/{session_id}` form is accepted as a backward-compatible alias
-for the same current-user session path and is not a separate storage root.
+`viking://~/sessions/{session_id}` uses the home alias and is expanded to
+`viking://user/{user_id}/sessions/{session_id}` for the authenticated caller.
+The uid-less spelling `viking://user/sessions/{session_id}` is no longer accepted
+and returns an error pointing at the `viking://~/...` form. The old
+`viking://session/{session_id}` form is still accepted as a backward-compatible
+alias for the same session path and is not a separate storage root.
## Related Documents
diff --git a/docs/en/concepts/13-privacy.md b/docs/en/concepts/13-privacy.md
index 119e54827..f9e886f5d 100644
--- a/docs/en/concepts/13-privacy.md
+++ b/docs/en/concepts/13-privacy.md
@@ -93,7 +93,7 @@ fs.read(uri)
Current matching is suffix-based: `/skills/{name}/SKILL.md`, so it supports user-scoped skill paths such as:
-- `viking://user/skills/{name}/SKILL.md`
+- `viking://~/skills/{name}/SKILL.md`
- `viking://user/{user_id}/skills/{name}/SKILL.md`
### restore Rules
diff --git a/docs/en/faq/faq.md b/docs/en/faq/faq.md
index 555c51c83..87ac93b25 100644
--- a/docs/en/faq/faq.md
+++ b/docs/en/faq/faq.md
@@ -353,7 +353,7 @@ This strategy finds semantically matching fragments while understanding the comp
4. **View extracted memories**
```python
- memories = await client.find("", target_uri="viking://user/memories/")
+ memories = await client.find("", target_uri="viking://~/memories/")
```
### Performance issues
diff --git a/docs/en/guides/01-configuration.md b/docs/en/guides/01-configuration.md
index 2e885ce3b..54fe00144 100644
--- a/docs/en/guides/01-configuration.md
+++ b/docs/en/guides/01-configuration.md
@@ -1561,8 +1561,8 @@ When running OpenViking as an HTTP service, add a `server` section to `ov.conf`:
},
"user_config_defaults": {
"add_targets": {
- "resource_uri": "viking://user/resources",
- "skill_uri": "viking://user/skills"
+ "resource_uri": "viking://~/resources",
+ "skill_uri": "viking://~/skills"
},
"memory_policy": {
"memory_types": ["profile", "preferences", "events", "entities", "experiences"]
@@ -1588,8 +1588,8 @@ When running OpenViking as an HTTP service, add a `server` section to `ov.conf`:
| `temp_upload.default_mode` | str | Server-side default for `POST /api/v1/resources/temp_upload` when the client does not send `upload_mode`: `"local"` (per-instance disk, current single-node behavior) or `"shared"` (distributed shared store usable across replicas). New shared uploads are stored in internal `viking://upload/<created_at_ms>-<uuid>/content` and `meta` objects, and can be consumed repeatedly for `ttl_seconds`. | `"local"` |
| `temp_upload.shared_max_size_bytes` | int | Maximum size accepted in `shared` mode, in bytes. Requests above this size are rejected before object-store write. | `536870912` (512 MiB) |
| `temp_upload.ttl_seconds` | int | Retention time shared by local and shared temporary uploads, in seconds. Each upload cleans files older than this for its mode; shared cleanup uses one upload-root listing, parses creation time from each first-level directory name, and recursively removes expired directories without filesystem modification times. Set to `0` to disable automatic cleanup. | `43200` (12 hours) |
-| `user_config_defaults.add_targets.resource_uri` | str | Deployment default resource add directory used when `add_resource` omits both `to` and `parent`. `viking://user/...` resolves per request user. | `null` |
-| `user_config_defaults.add_targets.skill_uri` | str | Deployment default skill add root used when `add_skill` omits `target_uri`. Only `viking://user/skills` and `viking://agent/skills` are accepted. | `null` |
+| `user_config_defaults.add_targets.resource_uri` | str | Deployment default resource add directory used when `add_resource` omits both `to` and `parent`. `viking://~/...` resolves per request user. | `null` |
+| `user_config_defaults.add_targets.skill_uri` | str | Deployment default skill add root used when `add_skill` omits `target_uri`. Only `viking://~/skills` and `viking://agent/skills` are accepted. | `null` |
| `user_config_defaults.memory_policy` | object | Deployment default memory extraction policy used when neither the Session nor the User has an explicit policy. | `null` |
| `agent_evolution.enabled` | bool | Instance-wide Agent Evolution switch. When enabled, session commits may generate or update cases, trajectories, and experiences according to the session `memory_policy`. When disabled, production of these memory types stops for every account and user. Existing memories remain readable and searchable. | `false` |
@@ -1642,8 +1642,9 @@ Each line has the following form:
Supported add target URIs:
-- `resource_uri` is used as the default `add_resource` parent directory, equivalent to `parent=<uri>, create_parent=true`. It must be a writable resource directory URI for the request user. Supported forms are `viking://resources` or `viking://resources/...`, `viking://user/resources` or `viking://user/resources/...`, `viking://user/{user_id}/resources` or `viking://user/{user_id}/resources/...`, and `viking://user/{user_id}/peers/{peer_id}/resources` or `viking://user/{user_id}/peers/{peer_id}/resources/...`. The `viking://user/...` shorthand resolves per request user.
-- `skill_uri` is used as the default `add_skill` target root. In v1, only `viking://user/skills` and `viking://agent/skills` are accepted; explicit `viking://user/{user_id}/skills` is not accepted.
+- `resource_uri` is used as the default `add_resource` parent directory, equivalent to `parent=<uri>, create_parent=true`. It must be a writable resource directory URI for the request user. Supported forms are `viking://resources` or `viking://resources/...`, `viking://~/resources` or `viking://~/resources/...`, `viking://user/{user_id}/resources` or `viking://user/{user_id}/resources/...`, and `viking://user/{user_id}/peers/{peer_id}/resources` or `viking://user/{user_id}/peers/{peer_id}/resources/...`. The `viking://~/...` home alias resolves per request user.
+- `skill_uri` is used as the default `add_skill` target root. In v1, only `viking://~/skills` and `viking://agent/skills` are accepted; explicit `viking://user/{user_id}/skills` is not accepted.
+- Legacy spellings: `viking://user/resources` and `viking://user/skills` written in earlier configs are auto-normalized to `viking://~/resources` and `viking://~/skills` when the config is loaded, and the server logs an info message. Prefer the `viking://~/...` form in new configs — outside `add_targets`, the uid-less spelling is rejected at the request boundary.
For startup and deployment details see [Deployment](./03-deployment.md), for authentication see [Authentication](./04-authentication.md).
diff --git a/docs/en/guides/06-mcp-integration.md b/docs/en/guides/06-mcp-integration.md
index d9b716521..145b91c5a 100644
--- a/docs/en/guides/06-mcp-integration.md
+++ b/docs/en/guides/06-mcp-integration.md
@@ -149,16 +149,16 @@ Once connected, OpenViking exposes 15 tools:
| `forget` | Delete any `viking://` URI (use `search` to find it first; pass `recursive=true` to delete a directory) | `uri`, `recursive` (optional) |
| `health` | Check OpenViking service health | none |
-For MCP tools, `viking://user` is the authenticated user's workspace. For example,
-`viking://user/notes/todo.md` resolves to
-`viking://user/<current-user>/notes/todo.md`, regardless of the file name or
-extension. Canonical URIs containing that exact current user id are also accepted;
-MCP does not use this shorthand for cross-user access.
-
-`viking://~` is a separate, universal alias for the caller's user root: it expands to
-`viking://user/<current-user>` on every control plane (REST API, `ov` CLI, SDKs, and
-MCP alike), and responses always echo the expanded canonical URI. The
-`viking://user/<path>` shorthand above stays MCP-only. See
+To address your own workspace from an MCP tool, use the home alias `viking://~`. It
+expands to `viking://user/<current-user>` on every control plane (REST API, `ov` CLI,
+SDKs, and MCP alike), so `viking://~/notes/todo.md` resolves to
+`viking://user/<current-user>/notes/todo.md`. Responses always echo the expanded
+canonical URI, and those canonical URIs are accepted as tool input as well.
+
+The uid-less spelling `viking://user/<segment>/...` (`memories`, `resources`, `skills`,
+`peers`, `privacy`, `sessions`) is no longer accepted; such calls fail with an error that
+points at the `viking://~/...` replacement. `viking://user` on its own is the container of
+user spaces, not a shortcut to yours. See
[Viking URI](../concepts/04-viking-uri.md) for details.
> **Note**: MCP exposes the minimum closure for watch management (`list_watches` + `cancel_watch`). Pause / resume / trigger and the unified `update` verb are intentionally not exposed here — use the REST `/api/v1/watches/*` endpoints or the `ov task watch` CLI for those operations.
diff --git a/docs/zh/agent-integrations/16-capability-reference.md b/docs/zh/agent-integrations/16-capability-reference.md
index 18214393d..1282cdc4d 100644
--- a/docs/zh/agent-integrations/16-capability-reference.md
+++ b/docs/zh/agent-integrations/16-capability-reference.md
@@ -232,7 +232,7 @@ JS 系 harness 的召回逻辑均由 `recall-core.mjs` 中的三级降级链处
1. **context face**:调用 `POST /api/v1/search/search`,参数设定为 `mode:"context"` 且 `purpose:"coding"`。其核心设计原则为"只声明意图,机制交服务端":对于 `quotas`/`max_tokens`/`query_expansion`/`rewrite_max_bullets` 等参数,仅在用户显式配置时(带有 configured 哨兵字段)才会发送,否则直接采用服务端的默认设定。
2. **legacy `/recall`**:若 context face 请求返回 400/422 错误,且响应报文包含 `extra`/`mode`/`unexpected` 等特征字段,则判定对接了旧版服务端。此时会在本地写入 6 小时的负缓存(路径为 `~/.openviking/state/context-face.json`,该文件全机共享,一旦被任一 harness 标记,同机所有 JS 系 harness 均会跳过 context face 阶段)。随后降级调用已弃用的 `/api/v1/search/recall` 接口;若 `peer_scope` 被拒,则去掉该参数重试一次。
-3. **raw find 兜底**:并发请求 `viking://user/memories` 与 `viking://user/skills`,调用两次 `POST /search/find`(注意:resources 被刻意排除在自动召回之外,资源类文档由模型主动调用 `search` 获取)。客户端收到结果后进行本地重排(权重规则为:leaf +0.12 / 时间意图 +0.10 / 偏好意图 +0.08 / 词面重叠 ≤0.2)、去重,最后按客户端 token 预算装填。`recallTokenBudget`、`recallMaxContentChars` 与 `recallPreferAbstract` 三个旋钮只在这一级生效;而在 context face 下,注入预算由服务端 `max_tokens`(默认 1600)决定。
+3. **raw find 兜底**:并发请求 `viking://~/memories` 与 `viking://~/skills`,调用两次 `POST /search/find`(注意:resources 被刻意排除在自动召回之外,资源类文档由模型主动调用 `search` 获取)。客户端收到结果后进行本地重排(权重规则为:leaf +0.12 / 时间意图 +0.10 / 偏好意图 +0.08 / 词面重叠 ≤0.2)、去重,最后按客户端 token 预算装填。`recallTokenBudget`、`recallMaxContentChars` 与 `recallPreferAbstract` 三个旋钮只在这一级生效;而在 context face 下,注入预算由服务端 `max_tokens`(默认 1600)决定。
服务端在处理 session_id 时,分为两条截然不同的执行路径:
@@ -560,7 +560,7 @@ MCP `write` / REST `content/write` 的三道 guard(`content_write.py`):可
- **集成文档**:[Hermes Agent](./05-hermes.md)
- **形态**:Hermes bundled MemoryProvider(Python 单文件实现,共 3725 行,随 Hermes 一同发布)。通过 `httpx` 直连,无需额外安装插件。提供 6 工具及 10+ 生命周期 hook(prefetch/sync_turn/on_session_end/on_session_switch/on_memory_write/…)。基线为发行版 `e12626b3`(= brew 2026.7.7.2)。
- **能力亮点**:具备最全面的资源摄取面——`viking_add_resource` 支持 HTTP、Git、SSH、`file://`、本地文件 temp_upload 以及本地目录 zip 打包上传(跳过 symlink + 越界文件);`viking_remember` 直写记忆文件(不依赖 session commit/抽取);支持本地服务端自启(当 endpoint 位于本地且不可达时,通过 `subprocess.Popen openviking-server` 拉起);支持 trusted 补身份重试;无论正常退出还是接收到 Ctrl+C、SIGTERM、SIGHUP 信号,均能保证完成 commit(详见 [§3.3.3](#_3-3-3-关闭方式-×-harness-终局矩阵))。
-- **行为要点**:在召回上,仅有 `search/search` 的首选路径携带 session_id 并落到路径 B(`mode="deep"`;而 `auto`/`fast` 走 `/find` 且不带 session_id,详见 [§3.2.2](#_3-2-2-判定矩阵))。`queue_prefetch` 为同步实现,无预热;subagent 传入 `skip_memory=True` 时不接 OV(详见 [§3.3.5](#_3-3-5-subagent-会话对照))。无 profile 注入/statusline/slash;commit 恒 keep 0,drain 不净则本次不 commit;进程内队列不落盘。session id 格式为 `%Y%m%d_%H%M%S_<hex6>`。召回参数:6 条/阈值 0.15/字符预算 4000/总超时 4s。记忆 URI 为 `viking://user/peers/{agent}/memories/{subdir}/mem_<uuid12>.md`。退出机制包含 SIGTERM grace 1.5s 与退出看门狗 30s。互补路径支持 `openviking-server ingest hermes`(离线重放,默认关,详见 [§7](#_7-附录-非-coding-集成速览) E)。
+- **行为要点**:在召回上,仅有 `search/search` 的首选路径携带 session_id 并落到路径 B(`mode="deep"`;而 `auto`/`fast` 走 `/find` 且不带 session_id,详见 [§3.2.2](#_3-2-2-判定矩阵))。`queue_prefetch` 为同步实现,无预热;subagent 传入 `skip_memory=True` 时不接 OV(详见 [§3.3.5](#_3-3-5-subagent-会话对照))。无 profile 注入/statusline/slash;commit 恒 keep 0,drain 不净则本次不 commit;进程内队列不落盘。session id 格式为 `%Y%m%d_%H%M%S_<hex6>`。召回参数:6 条/阈值 0.15/字符预算 4000/总超时 4s。记忆 URI 为 `viking://~/peers/{agent}/memories/{subdir}/mem_<uuid12>.md`。退出机制包含 SIGTERM grace 1.5s 与退出看门狗 30s。互补路径支持 `openviking-server ingest hermes`(离线重放,默认关,详见 [§7](#_7-附录-非-coding-集成速览) E)。
- **配置**:通过 `OPENVIKING_ENDPOINT`(非 `_URL`)、8 个 `OPENVIKING_RECALL_*` env 以及 `config.yaml` 进行配置。在 `use_ovcli_config` 模式下,系统会清空 `.env` 里的对应变量。
- **维度索引**:工具面 [§1.1](#_1-1-主动工具面-agentic-调用能力) |召回 [§3.2](#_3-2-自动召回与注入) |commit [§3.3.2](#_3-3-2-常规-commit-触发条件)/[§3.3.3](#_3-3-3-关闭方式-×-harness-终局矩阵) |删除 [§3.5](#_3-5-写入与删除的类型边界)。
diff --git a/docs/zh/api/02-resources.md b/docs/zh/api/02-resources.md
index 3ca4925e4..cd3194408 100644
--- a/docs/zh/api/02-resources.md
+++ b/docs/zh/api/02-resources.md
@@ -180,7 +180,7 @@ URL/文件 Parser TreeBuilder AGFS Summarizer/Vector
**补充说明**:
- `to` 和 `parent` 不能同时使用;如果使用 `parent` 且希望父目录不存在时自动创建,请传 `create_parent=true`。指定 `to` 且目标已存在时,触发增量更新。
- 如果同时省略 `to` 和 `parent`,服务端会先尝试使用当前用户的 `add_targets.resource_uri` 覆盖配置,再使用 `server.user_config_defaults.add_targets.resource_uri`。两者都没有配置时,保持旧的目标解析行为。
-- 资源目标可以使用公共 `viking://resources/...`、当前用户短写 `viking://user/resources/...`、显式用户 `viking://user/{user_id}/resources/...`,或 peer 级 `viking://user/{user_id}/peers/{peer_id}/resources/...`。当前用户短写会按请求身份 canonicalize。
+- 资源目标可以使用公共 `viking://resources/...`、家目录别名 `viking://~/resources/...`、显式用户 `viking://user/{user_id}/resources/...`,或 peer 级 `viking://user/{user_id}/peers/{peer_id}/resources/...`。家目录别名会按请求身份展开为 canonical 路径;无 uid 的写法 `viking://user/resources/...` 会被拒绝,并提示改用 `viking://~/resources/...`。
- `user_id` 和 `peer_id` 路径片段必须是安全的单段标识,例如 `alice` 或 `web-visitor-alice`。包含路径分隔符、`.`、`..`、`:` 或 `+` 的值会被拒绝。
- `path` 和 `temp_file_id` 不能同时指定,上传本地文件需要先通过 [temp_upload](#temp_upload) 上传获取 `temp_file_id`,在 SDK 和 CLI 中已经封装好。
- `tags` 会在资源解析后、向量记录写入时同步写入底层向量库。`add_resource(tags=...)` 不返回 `tags_result`;需要验证时,可在 `/api/v1/search/find` 或 `/api/v1/search/search` 中传相同 `tags` 过滤召回。
@@ -286,7 +286,7 @@ curl -X POST http://localhost:1933/api/v1/resources \
-H "X-API-Key: your-key" \
-d "{
\"temp_file_id\": \"$TEMP_FILE_ID\",
- \"parent\": \"viking://user/resources/docs\",
+ \"parent\": \"viking://~/resources/docs\",
\"create_parent\": true
}"
@@ -379,7 +379,7 @@ result = client.add_resource(
## 添加到当前用户私有资源根
result = client.add_resource(
"./documents/guide.md",
- parent="viking://user/resources/docs",
+ parent="viking://~/resources/docs",
create_parent=True,
)
@@ -486,7 +486,7 @@ ov add-resource https://example.feishu.cn/docx/doc_token \
ov add-resource ./documents/guide.md --parent viking://resources/docs
# 添加到当前用户私有资源根
-ov add-resource ./documents/guide.md --parent viking://user/resources/docs
+ov add-resource ./documents/guide.md --parent viking://~/resources/docs
# 添加到指定 peer 的私有资源根
ov add-resource ./documents/guide.md \
diff --git a/docs/zh/api/04-skills.md b/docs/zh/api/04-skills.md
index e79645793..b01cd9401 100644
--- a/docs/zh/api/04-skills.md
+++ b/docs/zh/api/04-skills.md
@@ -14,8 +14,8 @@ OpenViking 支持多种技能定义格式:
### 技能存储结构
-技能存储在当前用户的 skills 根。短 URI `viking://user/skills/` 会按认证请求身份解析为
-`viking://user/{user_id}/skills/`:
+技能存储在当前用户的 skills 根。家目录别名 `viking://~/skills/` 会按认证请求身份展开为
+`viking://user/{user_id}/skills/`(无 uid 的写法 `viking://user/skills/` 不再被接受):
```
viking://user/{user_id}/skills/
@@ -189,7 +189,7 @@ This tool wraps the MCP tool `search-web`. Call this when the user needs functio
- **目标规则**:
- Skills 始终是 user-scoped;`add_skill` 不接受 `to`、`parent` 或 `root_uri`。
- 不支持 peer-scoped skill 根;actor peer 过滤只作用于 peer memories/resources,不作用于 peer skills。
- - 列出、读取、删除或搜索技能时,可以使用 `viking://user/skills/...` 作为当前用户短写。
+ - 列出、读取、删除或搜索技能时,使用家目录别名 `viking://~/skills/...` 访问自己的技能;无 uid 的 `viking://user/skills/...` 写法会报错并提示正确写法。
- **支持的数据格式**:
1. **字典(技能格式)**:包含 `name`、`description`、`content` 等字段
diff --git a/docs/zh/api/05-sessions.md b/docs/zh/api/05-sessions.md
index 2e7bef1c7..ac552fa58 100644
--- a/docs/zh/api/05-sessions.md
+++ b/docs/zh/api/05-sessions.md
@@ -1043,7 +1043,7 @@ ContextPart(
ToolPart(
tool_id="call_123",
tool_name="search_web",
- skill_uri="viking://user/skills/search-web/",
+ skill_uri="viking://~/skills/search-web/",
tool_input={"query": "OAuth best practices"},
tool_output="",
tool_status="pending" # "pending"、"running"、"completed"、"error"
@@ -1326,7 +1326,7 @@ curl -X POST http://localhost:1933/api/v1/sessions/a1b2c3d4/used \
curl -X POST http://localhost:1933/api/v1/sessions/a1b2c3d4/used \
-H "Content-Type: application/json" \
-H "X-API-Key: your-key" \
- -d '{"skill": {"uri": "viking://user/skills/search-web/", "input": {"query": "OAuth"}, "output": "Results...", "success": true}}'
+ -d '{"skill": {"uri": "viking://~/skills/search-web/", "input": {"query": "OAuth"}, "output": "Results...", "success": true}}'
```
**响应示例**
diff --git a/docs/zh/api/06-retrieval.md b/docs/zh/api/06-retrieval.md
index d983a102f..89afb4179 100644
--- a/docs/zh/api/06-retrieval.md
+++ b/docs/zh/api/06-retrieval.md
@@ -73,7 +73,7 @@ OpenViking 提供多种检索方法,包括简单的向量相似度搜索、带
**目标解析说明**:
- `target_uri` 为空时,非 ROOT 检索默认搜索当前用户根 `viking://user/{user}` 和公共 `viking://resources`。
- 如需在文件系统和检索操作中把当前用户的 peer 集合过滤到某一个 peer,发送 `X-OpenViking-Actor-Peer: <peer_id>`,或用 SDK/CLI client 的 `actor_peer_id` 初始化。见 [多租户:Peer 集合过滤](../concepts/11-multi-tenant.md#peer-restricted-view)。
-- `viking://user/memories`、`viking://user/resources`、`viking://user/skills` 等当前用户短写 target URI 会按认证请求身份 canonicalize。
+- `viking://~/memories`、`viking://~/resources`、`viking://~/skills` 等家目录别名 target URI 会按认证请求身份展开为 canonical 路径。无 uid 的写法 `viking://user/memories`(以及 `resources`、`skills`、`peers`、`privacy`、`sessions` 的同类写法)会被拒绝,并提示改用 `viking://~/...`。
**图片搜索说明**:
- 图片查询会以图片向量作为 query,默认检索目标范围内的 L2 resource 叶子节点;结果不限于图片文件,图片与文本/图片资源的相似度由 multimodal embedding 模型决定。
@@ -232,13 +232,13 @@ results = client.find(
# 仅在用户记忆中搜索
results = client.find(
"preferences",
- target_uri="viking://user/memories"
+ target_uri="viking://~/memories"
)
# 仅在当前用户资源中搜索
results = client.find(
"private docs",
- target_uri="viking://user/resources"
+ target_uri="viking://~/resources"
)
# 检索时把 peer 集合过滤到一个 peer
@@ -252,7 +252,7 @@ peer_results = peer_client.find("invoice follow-up")
# 仅在技能中搜索
results = client.find(
"web search",
- target_uri="viking://user/skills"
+ target_uri="viking://~/skills"
)
# 在特定项目中搜索
diff --git a/docs/zh/api/08-admin.md b/docs/zh/api/08-admin.md
index 420ab9aaa..453593433 100644
--- a/docs/zh/api/08-admin.md
+++ b/docs/zh/api/08-admin.md
@@ -179,8 +179,9 @@ User override 并重新继承上述默认值,请 PATCH `{"memory_policy": null
- 在 `trusted` 模式下,响应中不会包含 `user_key` 字段
- 省略 `seed` 时使用默认随机 API Key。seed 应视为密钥材料;过短的 seed 会让 key 更容易被猜测。
- 不再支持 account 级 namespace 隔离配置。用户记忆使用 user-scoped namespace,一对多外部参与者通过 `peer_id` 表达。
-- `user_config.add_targets.resource_uri` 必须是可写资源目录 URI:`viking://resources` 或 `viking://resources/...`、`viking://user/resources` 或 `viking://user/resources/...`、`viking://user/{user_id}/resources` 或 `viking://user/{user_id}/resources/...`、`viking://user/{user_id}/peers/{peer_id}/resources` 或 `viking://user/{user_id}/peers/{peer_id}/resources/...`。
-- `user_config.add_targets.skill_uri` 只能是 `viking://user/skills` 或 `viking://agent/skills`。v1 不支持显式写成 `viking://user/{user_id}/skills`。
+- `user_config.add_targets.resource_uri` 必须是可写资源目录 URI:`viking://resources` 或 `viking://resources/...`、`viking://~/resources` 或 `viking://~/resources/...`、`viking://user/{user_id}/resources` 或 `viking://user/{user_id}/resources/...`、`viking://user/{user_id}/peers/{peer_id}/resources` 或 `viking://user/{user_id}/peers/{peer_id}/resources/...`。
+- `user_config.add_targets.skill_uri` 只能是 `viking://~/skills` 或 `viking://agent/skills`。v1 不支持显式写成 `viking://user/{user_id}/skills`。
+- 旧写法兼容:`viking://user/resources[/...]` 和 `viking://user/skills` 在这里仍会被接受,并归一化为 `viking://~/...` 形式(服务端会打印一条 info 日志)。在其他位置,无 uid 的写法会在请求入口被拒绝——新配置请直接写 `viking://~/...`。
#### 3. 使用示例
@@ -255,8 +256,8 @@ result = client.admin_create_account(
"alice",
user_config={
"add_targets": {
- "resource_uri": "viking://user/resources",
- "skill_uri": "viking://user/skills",
+ "resource_uri": "viking://~/resources",
+ "skill_uri": "viking://~/skills",
}
},
)
@@ -282,8 +283,8 @@ result, err = client.AdminCreateAccountWithOptions(ctx, "acme-private", "alice",
Seed: &seed,
UserConfig: map[string]any{
"add_targets": map[string]any{
- "resource_uri": "viking://user/resources",
- "skill_uri": "viking://user/skills",
+ "resource_uri": "viking://~/resources",
+ "skill_uri": "viking://~/skills",
},
},
})
@@ -297,7 +298,7 @@ ov --sudo admin create-account acme --admin alice
ov --sudo admin create-account acme --admin alice --seed alice-seed
ov --sudo admin create-account acme-private --admin alice \
- --user-config-json '{"add_targets":{"resource_uri":"viking://user/resources","skill_uri":"viking://user/skills"}}'
+ --user-config-json '{"add_targets":{"resource_uri":"viking://~/resources","skill_uri":"viking://~/skills"}}'
```
**响应示例**
@@ -526,8 +527,9 @@ ov --sudo admin delete-account acme
- 省略 `seed` 时使用默认随机 API Key。seed 应视为密钥材料;过短的 seed 会让 key 更容易被猜测。
- ADMIN 只能在自己所属的 account 中注册用户
- 无法通过用户注册接口直接创建 `"root"` 角色
-- `user_config.add_targets.resource_uri` 必须是可写资源目录 URI:`viking://resources` 或 `viking://resources/...`、`viking://user/resources` 或 `viking://user/resources/...`、`viking://user/{user_id}/resources` 或 `viking://user/{user_id}/resources/...`、`viking://user/{user_id}/peers/{peer_id}/resources` 或 `viking://user/{user_id}/peers/{peer_id}/resources/...`。
-- `user_config.add_targets.skill_uri` 只能是 `viking://user/skills` 或 `viking://agent/skills`。v1 不支持显式写成 `viking://user/{user_id}/skills`。
+- `user_config.add_targets.resource_uri` 必须是可写资源目录 URI:`viking://resources` 或 `viking://resources/...`、`viking://~/resources` 或 `viking://~/resources/...`、`viking://user/{user_id}/resources` 或 `viking://user/{user_id}/resources/...`、`viking://user/{user_id}/peers/{peer_id}/resources` 或 `viking://user/{user_id}/peers/{peer_id}/resources/...`。
+- `user_config.add_targets.skill_uri` 只能是 `viking://~/skills` 或 `viking://agent/skills`。v1 不支持显式写成 `viking://user/{user_id}/skills`。
+- 旧写法兼容:`viking://user/resources[/...]` 和 `viking://user/skills` 在这里仍会被接受,并归一化为 `viking://~/...` 形式(服务端会打印一条 info 日志)。在其他位置,无 uid 的写法会在请求入口被拒绝——新配置请直接写 `viking://~/...`。
#### 3. 使用示例
@@ -564,7 +566,7 @@ result = client.admin_register_user(
"acme",
"bob-private",
role="user",
- user_config={"add_targets": {"resource_uri": "viking://user/resources/project-a"}},
+ user_config={"add_targets": {"resource_uri": "viking://~/resources/project-a"}},
)
```
@@ -587,7 +589,7 @@ seed := "bob-seed"
result, err = client.AdminRegisterUserWithOptions(ctx, "acme", "bob-private", "user", &openviking.AdminRegisterUserOptions{
Seed: &seed,
UserConfig: map[string]any{
- "add_targets": map[string]any{"resource_uri": "viking://user/resources/project-a"},
+ "add_targets": map[string]any{"resource_uri": "viking://~/resources/project-a"},
},
})
```
@@ -603,7 +605,7 @@ ov admin register-user acme bob --role user --seed bob-seed
ov --sudo admin register-user acme bob --role user
ov admin register-user acme bob-private --role user \
- --user-config-json '{"add_targets":{"resource_uri":"viking://user/resources/project-a"}}'
+ --user-config-json '{"add_targets":{"resource_uri":"viking://~/resources/project-a"}}'
```
**响应示例**
diff --git a/docs/zh/concepts/02-context-types.md b/docs/zh/concepts/02-context-types.md
index 819f986f3..751a86382 100644
--- a/docs/zh/concepts/02-context-types.md
+++ b/docs/zh/concepts/02-context-types.md
@@ -56,17 +56,17 @@ results = client.find(
| 类型 | 默认位置 | 说明 |
|------|----------|------|
-| **profile** | `user/memories/profile.md` | 用户基本信息 |
-| **preferences** | `user/memories/preferences/` | 按主题组织的用户偏好 |
-| **entities** | `user/memories/entities/` | 人物、项目、组织等实体知识 |
-| **events** | `user/memories/events/` | 决策、里程碑等事件记录 |
-| **identity** | `user/memories/identity.md` | 助手的名称、形象、气质和自我介绍 |
-| **soul** | `user/memories/soul.md` | 助手的核心原则、边界、风格和连续性 |
-| **cases** | `user/memories/cases/` | 用于训练和评估的任务案例 |
-| **trajectories** | `user/memories/trajectories/` | 可复用的任务执行轨迹 |
-| **experiences** | `user/memories/experiences/` | 从执行结果中提炼的可复用经验 |
-
-表中的 `user/...` 是当前用户短路径,服务端会将其解析为 `viking://user/{user_id}/...`。当记忆策略允许 Peer 记忆时,支持 Peer 的类型会写入 `viking://user/{user_id}/peers/{peer_id}/memories/...`。记忆类型可通过自定义模板扩展或调整。
+| **profile** | `~/memories/profile.md` | 用户基本信息 |
+| **preferences** | `~/memories/preferences/` | 按主题组织的用户偏好 |
+| **entities** | `~/memories/entities/` | 人物、项目、组织等实体知识 |
+| **events** | `~/memories/events/` | 决策、里程碑等事件记录 |
+| **identity** | `~/memories/identity.md` | 助手的名称、形象、气质和自我介绍 |
+| **soul** | `~/memories/soul.md` | 助手的核心原则、边界、风格和连续性 |
+| **cases** | `~/memories/cases/` | 用于训练和评估的任务案例 |
+| **trajectories** | `~/memories/trajectories/` | 可复用的任务执行轨迹 |
+| **experiences** | `~/memories/experiences/` | 从执行结果中提炼的可复用经验 |
+
+表中的 `~/...` 使用家目录别名 `viking://~`,服务端会按认证身份将其展开为 `viking://user/{user_id}/...`。当记忆策略允许 Peer 记忆时,支持 Peer 的类型会写入 `viking://user/{user_id}/peers/{peer_id}/memories/...`。记忆类型可通过自定义模板扩展或调整。
Schema 定义的 `memories/tools/` 和 `memories/skills/` 类型已禁用。它们与存放在 `viking://user/{user_id}/skills/{skill_name}/SKILL.md` 下的独立 Skill 不同,后者仍然保留并受支持。
@@ -82,7 +82,7 @@ task = await client.get_task(commit["task_id"]) # 轮询直到 task["status"] =
# 搜索记忆
results = await client.find(
"用户界面偏好",
- target_uri="viking://user/memories/"
+ target_uri="viking://~/memories/"
)
```
@@ -99,7 +99,7 @@ results = await client.find(
### 存储位置
```
-viking://user/skills/{skill-name}/ # 默认存储路径
+viking://~/skills/{skill-name}/ # 默认存储路径
├── .abstract.md # L0: 简短描述
├── .overview.md # L1: 目录概览(生成后)
├── SKILL.md # L2: 技能定义
@@ -126,7 +126,7 @@ AgentDefinedContextType 包含以下子类型,均存储于 `viking://agent/`
### 使用
```python
-# 添加技能(默认写入 viking://user/skills/)
+# 添加技能(默认写入 viking://~/skills/)
await client.add_skill({
"name": "search-web",
"description": "搜索网络获取信息",
@@ -139,7 +139,7 @@ ov skills add search-web -p viking://agent/skills
# 搜索用户技能
results = await client.find(
"网络搜索",
- target_uri="viking://user/skills/"
+ target_uri="viking://~/skills/"
)
# 搜索全局 agent 技能
diff --git a/docs/zh/concepts/04-viking-uri.md b/docs/zh/concepts/04-viking-uri.md
index e11eeefae..298e70d71 100644
--- a/docs/zh/concepts/04-viking-uri.md
+++ b/docs/zh/concepts/04-viking-uri.md
@@ -42,6 +42,9 @@ viking://{scope}/{path}
- 需要认证用户身份。展开发生在 user / admin 调用方的请求入口;root 角色与未认证上下文,
以及要求 URI 已是 canonical 形式的场景(内部存储路径、后台任务),会直接拒绝该别名,
而不会猜测用户。
+- 取代已移除的无 uid 短写:`memories`、`resources`、`skills`、`peers`、`privacy`、`sessions`
+ 的 `viking://user/<segment>/...` 写法会在 USER / ADMIN 请求入口被拒绝,错误信息中会给出
+ `viking://~/...` 的替代写法。
## 初始目录
@@ -91,32 +94,39 @@ viking://resources/my-project/docs/api.md # 具体文件
### 用户数据
```
-viking://user/ # 用户根目录
-viking://user/memories/ # 所有用户记忆
-viking://user/memories/preferences/ # 用户偏好
-viking://user/memories/preferences/coding # 具体偏好
-viking://user/memories/entities/ # 实体记忆
-viking://user/memories/events/ # 事件记忆
-viking://user/resources/ # 当前用户资源
-viking://user/resources/docs/ # 当前用户资源目录
+viking://user/ # 所有用户空间的容器(user key 只能列出自己的空间)
+viking://~/ # 自己的用户根目录(展开为 viking://user/{user_id}/)
+viking://~/memories/ # 自己的所有记忆
+viking://~/memories/preferences/ # 用户偏好
+viking://~/memories/preferences/coding # 具体偏好
+viking://~/memories/entities/ # 实体记忆
+viking://~/memories/events/ # 事件记忆
+viking://~/resources/ # 自己的私有资源
+viking://~/resources/docs/ # 自己的私有资源目录
+viking://user/{user_id}/memories/ # 显式用户路径(可写自己的 id;访问他人需 admin/root)
```
### 用户技能和 peer 内容
```
-viking://user/skills/ # 当前用户的技能
-viking://user/skills/search-web # 某个技能
-viking://user/memories/ # 当前用户的记忆
-viking://user/memories/cases/ # 用于训练和评估的任务案例
-viking://user/memories/trajectories/ # 可复用的任务执行轨迹
-viking://user/memories/experiences/ # 从执行结果中提炼的经验
+viking://~/skills/ # 自己的技能
+viking://~/skills/search-web # 某个技能
+viking://~/memories/ # 自己的记忆
+viking://~/memories/cases/ # 用于训练和评估的任务案例
+viking://~/memories/trajectories/ # 可复用的任务执行轨迹
+viking://~/memories/experiences/ # 从执行结果中提炼的经验
viking://user/{user_id}/peers/{peer_id}/memories/
viking://user/{user_id}/peers/{peer_id}/resources/
```
-上面的 `viking://user/...` 短路径会按当前请求身份解析。
-OpenViking 会在存储和检索前将它展开为显式命名空间路径,例如
-`viking://user/{user_id}/...`。
+家目录别名 `viking://~/...` 会按当前请求身份解析。OpenViking 会在存储和检索前将它
+展开为显式命名空间路径 `viking://user/{user_id}/...`,响应中始终回显展开后的形式。
+
+旧的无 uid 写法——`viking://user/memories/...` 以及 `resources`、`skills`、`peers`、
+`privacy`、`sessions` 的同类写法——在请求入口不再被接受,这类请求会报错,并在错误信息中
+提示改用 `viking://~/...`。`viking://user` 本身是所有用户空间的容器,而不是自己根目录的
+快捷方式:使用 user key 列出它时只会看到自己的空间。
+
`{user_id}` 和 `{peer_id}` 等身份路径片段必须是安全的单段标识,例如
`alice` 或 `web-visitor-alice`。
@@ -141,7 +151,7 @@ viking://user/{user_id}/sessions/{session_id}/ # 会话根目录
viking://user/{user_id}/sessions/{session_id}/messages # 会话消息
viking://user/{user_id}/sessions/{session_id}/tools # 工具执行
viking://user/{user_id}/sessions/{session_id}/history # 归档历史
-viking://user/sessions/{session_id}/ # 当前用户短路径
+viking://~/sessions/{session_id}/ # 自己的会话(家目录别名写法)
```
`viking://session/{session_id}` 会作为当前用户 session 路径的向后兼容别名被接受。
@@ -295,22 +305,22 @@ results = client.find(
target_uri="viking://resources/"
)
-# 仅在当前用户资源中搜索
+# 仅在自己的资源中搜索
results = client.find(
"私有项目笔记",
- target_uri="viking://user/resources/"
+ target_uri="viking://~/resources/"
)
-# 仅在用户记忆中搜索
+# 仅在自己的记忆中搜索
results = client.find(
"编码偏好",
- target_uri="viking://user/memories/"
+ target_uri="viking://~/memories/"
)
-# 仅在技能中搜索
+# 仅在自己的技能中搜索
results = client.find(
"网络搜索",
- target_uri="viking://user/skills/"
+ target_uri="viking://~/skills/"
)
```
@@ -359,11 +369,11 @@ overview = await client.overview("viking://resources/docs/")
# 添加到 account 共享资源作用域
await client.add_resource(url, to="viking://resources/project/")
-# 添加到当前用户私有资源根
-await client.add_resource(path, parent="viking://user/resources/project/")
+# 添加到自己的私有资源根
+await client.add_resource(path, parent="viking://~/resources/project/")
-# 技能默认添加到当前用户技能根
-await client.add_skill(skill) # canonical root: viking://user/skills/
+# 技能默认添加到自己的技能根
+await client.add_skill(skill) # 默认根目录:viking://~/skills/
# 通过 -p 指定写入全局 agent 技能根(公开共享)
ov skills add xxx -p viking://agent/skills/
diff --git a/docs/zh/concepts/05-storage.md b/docs/zh/concepts/05-storage.md
index 8dcf96e24..1b649f3b5 100644
--- a/docs/zh/concepts/05-storage.md
+++ b/docs/zh/concepts/05-storage.md
@@ -40,8 +40,8 @@ VikingFS 是统一的 URI 抽象层,屏蔽底层存储细节。
```
viking://resources/docs/auth → /local/{account_id}/resources/docs/auth
-viking://user/memories → /local/{account_id}/user/{user_id}/memories
-viking://user/skills → /local/{account_id}/user/{user_id}/skills
+viking://~/memories → /local/{account_id}/user/{user_id}/memories
+viking://~/skills → /local/{account_id}/user/{user_id}/skills
```
### 核心 API
diff --git a/docs/zh/concepts/06-extraction.md b/docs/zh/concepts/06-extraction.md
index 60acb47df..c14418c51 100644
--- a/docs/zh/concepts/06-extraction.md
+++ b/docs/zh/concepts/06-extraction.md
@@ -167,7 +167,7 @@ L0/L1 是目录级 sidecar,不是 per-file sidecar。生成父目录摘要时
| 环节 | Resource | Memory | Skill |
|------|----------|--------|-------|
| **Parser** | 通用流程 | 通用流程 | 通用流程 |
-| **基础 URI** | `viking://resources` | `viking://user/memories` | `viking://user/skills` |
+| **基础 URI** | `viking://resources` | `viking://~/memories` | `viking://~/skills` |
| **TreeBuilder scope** | resources | user | user |
| **SemanticMsg type** | resource | memory | skill |
@@ -192,7 +192,7 @@ await client.add_skill({
"content": "# search-web\\n..."
})
-# 流程: 直接写入 viking://user/skills/{name}/ → SemanticQueue
+# 流程: 直接写入 viking://~/skills/{name}/ → SemanticQueue
```
### 记忆提取
diff --git a/docs/zh/concepts/07-retrieval.md b/docs/zh/concepts/07-retrieval.md
index d33b4745c..a2b64ae33 100644
--- a/docs/zh/concepts/07-retrieval.md
+++ b/docs/zh/concepts/07-retrieval.md
@@ -92,9 +92,9 @@ Step 5: 转换为 MatchedContext
| context_type | 根目录 |
|--------------|--------|
-| MEMORY | `viking://user/memories` |
+| MEMORY | `viking://~/memories` |
| RESOURCE | `viking://resources` |
-| SKILL | `viking://user/skills` |
+| SKILL | `viking://~/skills` |
### 递归搜索算法
diff --git a/docs/zh/concepts/08-session.md b/docs/zh/concepts/08-session.md
index 052684b01..f910a56f8 100644
--- a/docs/zh/concepts/08-session.md
+++ b/docs/zh/concepts/08-session.md
@@ -35,7 +35,7 @@ session.add_message(
"assistant",
[
TextPart("Here's how..."),
- ContextPart(uri="viking://user/memories/profile.md"),
+ ContextPart(uri="viking://~/memories/profile.md"),
]
)
@@ -52,11 +52,11 @@ session.add_message(
```python
# 记录使用的上下文
-session.used(contexts=["viking://user/memories/profile.md"])
+session.used(contexts=["viking://~/memories/profile.md"])
# 记录使用的技能
session.used(skill={
- "uri": "viking://user/skills/code-search",
+ "uri": "viking://~/skills/code-search",
"input": "search config",
"output": "found 3 files",
"success": True
@@ -242,7 +242,7 @@ viking://user/{user_id}/sessions/{session_id}/
└── tools/
└── {tool_id}/tool.json
-viking://user/memories/
+viking://~/memories/
├── profile.md
├── identity.md
├── soul.md
@@ -254,10 +254,11 @@ viking://user/memories/
└── experiences/
```
-`viking://user/sessions/{session_id}` 是相对当前请求用户的短路径,服务端会将其
-规范化为 `viking://user/{user_id}/sessions/{session_id}`。
-`viking://session/{session_id}` 会作为同一个当前用户 session 路径的向后兼容别名
-被接受,不是独立的存储根。
+`viking://~/sessions/{session_id}` 使用家目录别名,服务端会按认证身份将其展开为
+`viking://user/{user_id}/sessions/{session_id}`。无 uid 的写法
+`viking://user/sessions/{session_id}` 不再被接受,请求会报错并提示改用 `viking://~/...`。
+`viking://session/{session_id}` 仍会作为同一个 session 路径的向后兼容别名被接受,
+不是独立的存储根。
## 相关文档
diff --git a/docs/zh/concepts/13-privacy.md b/docs/zh/concepts/13-privacy.md
index 56a18233e..6ac465003 100644
--- a/docs/zh/concepts/13-privacy.md
+++ b/docs/zh/concepts/13-privacy.md
@@ -93,7 +93,7 @@ fs.read(uri)
当前支持通过后缀识别 Skill:`/skills/{name}/SKILL.md`,可兼容 user-scoped skill 路径,例如:
-- `viking://user/skills/{name}/SKILL.md`
+- `viking://~/skills/{name}/SKILL.md`
- `viking://user/{user_id}/skills/{name}/SKILL.md`
### restore 规则
diff --git a/docs/zh/faq/faq.md b/docs/zh/faq/faq.md
index 6cc27d47a..bcb7c06ed 100644
--- a/docs/zh/faq/faq.md
+++ b/docs/zh/faq/faq.md
@@ -346,7 +346,7 @@ OpenViking 使用分数传播机制:
4. **查看提取的记忆**
```python
- memories = await client.find("", target_uri="viking://user/memories/")
+ memories = await client.find("", target_uri="viking://~/memories/")
```
### 性能问题
diff --git a/docs/zh/guides/01-configuration.md b/docs/zh/guides/01-configuration.md
index 34f5ebb0e..4c589392a 100644
--- a/docs/zh/guides/01-configuration.md
+++ b/docs/zh/guides/01-configuration.md
@@ -1643,8 +1643,8 @@ openviking add-resource ./docs --exclude "*.tmp"
},
"user_config_defaults": {
"add_targets": {
- "resource_uri": "viking://user/resources",
- "skill_uri": "viking://user/skills"
+ "resource_uri": "viking://~/resources",
+ "skill_uri": "viking://~/skills"
},
"memory_policy": {
"memory_types": ["profile", "preferences", "events", "entities", "experiences"]
@@ -1670,8 +1670,8 @@ openviking add-resource ./docs --exclude "*.tmp"
| `temp_upload.default_mode` | str | `POST /api/v1/resources/temp_upload` 的服务端默认模式(客户端未显式传 `upload_mode` 时使用):`"local"`(仅当前实例本地磁盘,单机默认行为)或 `"shared"`(分布式共享存储,多副本部署可跨实例消费)。新的 shared 上传会固定写入内部 `viking://upload/<created_at_ms>-<uuid>/content` 和 `meta` 对象,在 `ttl_seconds` 指定的时间内可重复消费。 | `"local"` |
| `temp_upload.shared_max_size_bytes` | int | `shared` 模式下接受的最大文件大小(字节)。超过此阈值的请求会在写入对象存储之前被拒绝。 | `536870912`(512 MiB) |
| `temp_upload.ttl_seconds` | int | local 和 shared 临时上传文件共用的保留时间(秒)。每次对应模式的上传会清理超过此时间的文件;shared 只需一次上传根目录列举,从每个一级目录名解析创建时间,并递归删除过期目录,不依赖文件系统修改时间;设为 `0` 时禁用自动清理。 | `43200`(12 小时) |
-| `user_config_defaults.add_targets.resource_uri` | str | `add_resource` 未传 `to` 和 `parent` 时使用的部署级默认资源添加目录。`viking://user/...` 会按请求用户解析。 | `null` |
-| `user_config_defaults.add_targets.skill_uri` | str | `add_skill` 未传 `target_uri` 时使用的部署级默认技能添加根目录。仅允许 `viking://user/skills` 和 `viking://agent/skills`。 | `null` |
+| `user_config_defaults.add_targets.resource_uri` | str | `add_resource` 未传 `to` 和 `parent` 时使用的部署级默认资源添加目录。`viking://~/...` 会按请求用户解析。 | `null` |
+| `user_config_defaults.add_targets.skill_uri` | str | `add_skill` 未传 `target_uri` 时使用的部署级默认技能添加根目录。仅允许 `viking://~/skills` 和 `viking://agent/skills`。 | `null` |
| `user_config_defaults.memory_policy` | object | Session 和 User 都未显式配置策略时使用的部署级默认记忆抽取策略。 | `null` |
| `agent_evolution.enabled` | bool | 实例级 Agent 进化开关。开启时,session commit 可按 session `memory_policy` 生成或更新 cases、trajectories 和 experiences;关闭时,所有账号和用户均停止生产这三类记忆。已有记忆仍可读取和检索。 | `false` |
@@ -1723,8 +1723,9 @@ openviking add-resource ./docs --exclude "*.tmp"
支持的 add target URI:
-- `resource_uri` 作为 `add_resource` 的默认父目录使用,等价于 `parent=<uri>, create_parent=true`。它必须是当前请求用户可写的 resource 目录 URI,支持 `viking://resources` 或 `viking://resources/...`、`viking://user/resources` 或 `viking://user/resources/...`、`viking://user/{user_id}/resources` 或 `viking://user/{user_id}/resources/...`、`viking://user/{user_id}/peers/{peer_id}/resources` 或 `viking://user/{user_id}/peers/{peer_id}/resources/...`。`viking://user/...` 短写会按请求用户解析。
-- `skill_uri` 作为 `add_skill` 的默认目标根目录使用。v1 只允许 `viking://user/skills` 和 `viking://agent/skills`;不支持显式写成 `viking://user/{user_id}/skills`。
+- `resource_uri` 作为 `add_resource` 的默认父目录使用,等价于 `parent=<uri>, create_parent=true`。它必须是当前请求用户可写的 resource 目录 URI,支持 `viking://resources` 或 `viking://resources/...`、`viking://~/resources` 或 `viking://~/resources/...`、`viking://user/{user_id}/resources` 或 `viking://user/{user_id}/resources/...`、`viking://user/{user_id}/peers/{peer_id}/resources` 或 `viking://user/{user_id}/peers/{peer_id}/resources/...`。`viking://~/...` 家目录别名会按请求用户解析。
+- `skill_uri` 作为 `add_skill` 的默认目标根目录使用。v1 只允许 `viking://~/skills` 和 `viking://agent/skills`;不支持显式写成 `viking://user/{user_id}/skills`。
+- 旧写法兼容:早期配置中的 `viking://user/resources` 和 `viking://user/skills` 会在配置加载时自动归一化为 `viking://~/resources` 和 `viking://~/skills`,并打印一条 info 日志。新配置请直接使用 `viking://~/...`;在 `add_targets` 之外,无 uid 的写法会在请求入口被拒绝。
启动方式和部署详情见 [服务部署](./03-deployment.md),认证详情见 [认证](./04-authentication.md)。
diff --git a/docs/zh/guides/06-mcp-integration.md b/docs/zh/guides/06-mcp-integration.md
index bd3e24037..8d6cdd405 100644
--- a/docs/zh/guides/06-mcp-integration.md
+++ b/docs/zh/guides/06-mcp-integration.md
@@ -141,14 +141,14 @@ claude mcp add --transport http openviking \
| `forget` | 删除任意 `viking://` URI(先用 `search` 查找;删除目录需 `recursive=true`) | `uri`, `recursive`(可选) |
| `health` | 检查 OpenViking 服务健康状态 | 无 |
-在 MCP 工具中,`viking://user` 表示当前认证用户的工作区。例如,
-`viking://user/notes/todo.md` 会解析成
-`viking://user/<当前用户>/notes/todo.md`,不依赖文件名或扩展名判断。工具返回的、
-包含当前用户 ID 的 canonical URI 也可以直接使用;这套简写不用于跨用户访问。
-
-`viking://~` 是另一个通用别名,表示调用方的用户根目录:它在所有控制面(REST API、`ov` CLI、
-SDK 和 MCP)上都会展开为 `viking://user/<当前用户>`,且响应始终回显展开后的 canonical URI。
-上面的 `viking://user/<path>` 简写则仍是 MCP 专属。详见
+在 MCP 工具中访问自己的工作区,请使用家目录别名 `viking://~`。它在所有控制面
+(REST API、`ov` CLI、SDK 和 MCP)上都会展开为 `viking://user/<当前用户>`,因此
+`viking://~/notes/todo.md` 会解析成 `viking://user/<当前用户>/notes/todo.md`。
+响应始终回显展开后的 canonical URI,这些 canonical URI 也可以直接作为工具入参使用。
+
+无 uid 的写法 `viking://user/<segment>/...`(`memories`、`resources`、`skills`、`peers`、
+`privacy`、`sessions`)不再被接受,这类调用会报错并提示改用 `viking://~/...`。
+`viking://user` 本身是所有用户空间的容器,而不是自己空间的快捷方式。详见
[Viking URI](../concepts/04-viking-uri.md)。
> **注**:MCP 仅暴露 watch 管理的最小闭包(`list_watches` + `cancel_watch`)。pause / resume / trigger 和统一的 `update` 动作刻意不在此处暴露,请通过 REST `/api/v1/watches/*` 接口或 `ov task watch` CLI 使用上述操作。
diff --git a/examples/basic-usage/README.md b/examples/basic-usage/README.md
index 694ab12cd..d8c576205 100644
--- a/examples/basic-usage/README.md
+++ b/examples/basic-usage/README.md
@@ -131,8 +131,8 @@ content = client.read("viking://resources/my-project/README.md")
This same URI model applies to memories and skills as well:
- `viking://resources/`
-- `viking://user/memories/`
-- `viking://user/skills/`
+- `viking://~/memories/`
+- `viking://~/skills/`
### Retrieval
@@ -192,7 +192,7 @@ After commit, you can retrieve those memories through normal search APIs:
```python
memories = client.find(
query="user programming preferences",
- target_uri="viking://user/memories/",
+ target_uri="viking://~/memories/",
)
```
diff --git a/examples/basic-usage/README_CN.md b/examples/basic-usage/README_CN.md
index 149217396..d072e7fc8 100644
--- a/examples/basic-usage/README_CN.md
+++ b/examples/basic-usage/README_CN.md
@@ -132,8 +132,8 @@ content = client.read("viking://resources/my-project/README.md")
同样的 URI 模型也适用于记忆和技能:
- `viking://resources/`
-- `viking://user/memories/`
-- `viking://user/skills/`
+- `viking://~/memories/`
+- `viking://~/skills/`
### 检索
@@ -193,7 +193,7 @@ client.commit_session(session_id)
```python
memories = client.find(
query="用户编程偏好",
- target_uri="viking://user/memories/",
+ target_uri="viking://~/memories/",
)
```
diff --git a/examples/claude-code-memory-plugin/README.md b/examples/claude-code-memory-plugin/README.md
index 9f9253fbd..af7d82e09 100644
--- a/examples/claude-code-memory-plugin/README.md
+++ b/examples/claude-code-memory-plugin/README.md
@@ -2,6 +2,10 @@
Long-term semantic memory for Claude Code, powered by [OpenViking](https://github.com/volcengine/OpenViking). Recall happens automatically before every prompt, capture happens automatically after every turn — no MCP tool calls required from the model.
+> **Requires an OpenViking server with `viking://~` home-alias support.** Recall targets the
+> caller's own context space through `viking://~/memories` and `viking://~/skills`; the uid-less
+> `viking://user/memories` shorthand is rejected by newer servers.
+
> Installable straight from the repo's marketplace catalog — no separate distribution repo. See [Manual setup](#manual-setup) for the two-command remote install.
## Quick Start
diff --git a/examples/claude-code-memory-plugin/scripts/auto-recall.mjs b/examples/claude-code-memory-plugin/scripts/auto-recall.mjs
index 13c563a0c..de0a62524 100644
--- a/examples/claude-code-memory-plugin/scripts/auto-recall.mjs
+++ b/examples/claude-code-memory-plugin/scripts/auto-recall.mjs
@@ -153,6 +153,11 @@ async function resolveUserSpace(actorPeerId = "") {
async function resolveTargetUri(targetUri, actorPeerId = "") {
const trimmed = targetUri.trim().replace(/\/+$/, "");
+ // viking://~ is the home alias: the server expands it to the caller's own user
+ // space, so it needs no client-side rewrite.
+ if (trimmed === "viking://~" || trimmed.startsWith("viking://~/")) return trimmed;
+ // Legacy compat: uid-less viking://user/<reserved> URIs may still sit in plugin
+ // configs. Newer servers reject them, so rewrite to an explicit-uid URI here.
const m = trimmed.match(/^viking:\/\/user(?:\/(.*))?$/);
if (!m) return trimmed;
const rawRest = (m[1] ?? "").trim();
@@ -170,8 +175,8 @@ async function resolveTargetUri(targetUri, actorPeerId = "") {
// ---------------------------------------------------------------------------
const SOURCES = [
- { type: "memory", uri: "viking://user/memories", bucket: "memories" },
- { type: "skill", uri: "viking://user/skills", bucket: "skills" },
+ { type: "memory", uri: "viking://~/memories", bucket: "memories" },
+ { type: "skill", uri: "viking://~/skills", bucket: "skills" },
];
async function searchOneSource(query, source, limit, actorPeerId = "") {
diff --git a/examples/claude-code-memory-plugin/scripts/debug-recall.mjs b/examples/claude-code-memory-plugin/scripts/debug-recall.mjs
index fd7203e10..f48367009 100755
--- a/examples/claude-code-memory-plugin/scripts/debug-recall.mjs
+++ b/examples/claude-code-memory-plugin/scripts/debug-recall.mjs
@@ -264,7 +264,7 @@ async function searchScope(queryText, targetUri, limit) {
async function searchUserScope(queryText, limit) {
console.log(`${C.dim}Searching user scope...${C.reset}`);
- const userMems = await searchScope(queryText, "viking://user/memories", limit);
+ const userMems = await searchScope(queryText, "viking://~/memories", limit);
const uriSet = new Set();
return {
@@ -349,7 +349,7 @@ async function main() {
const { userMems, combined } = await searchUserScope(query, candidateLimit);
console.log();
- printSearchResults("User scope (viking://user/memories)", userMems);
+ printSearchResults("User scope (viking://~/memories)", userMems);
console.log();
dim(` Combined (deduplicated): ${combined.length} result${combined.length === 1 ? "" : "s"}`);
diff --git a/examples/claude-code-memory-plugin/scripts/shared/recall-core.mjs b/examples/claude-code-memory-plugin/scripts/shared/recall-core.mjs
index 83d444f26..bff58bc83 100644
--- a/examples/claude-code-memory-plugin/scripts/shared/recall-core.mjs
+++ b/examples/claude-code-memory-plugin/scripts/shared/recall-core.mjs
@@ -14,8 +14,8 @@ const STOPWORDS = new Set([
]);
const USER_RESERVED_DIRS = new Set(["memories", "skills"]);
const SOURCES = [
- { type: "memory", uri: "viking://user/memories", bucket: "memories" },
- { type: "skill", uri: "viking://user/skills", bucket: "skills" },
+ { type: "memory", uri: "viking://~/memories", bucket: "memories" },
+ { type: "skill", uri: "viking://~/skills", bucket: "skills" },
];
const DEFAULT_CONTEXT_LIMIT = 10;
const DEFAULT_CONTEXT_MAX_TOKENS = 1600;
@@ -272,6 +272,11 @@ async function resolveUserSpace(fetchJSON, actorPeerId = "") {
async function resolveTargetUri(fetchJSON, targetUri, actorPeerId = "") {
const trimmed = targetUri.trim().replace(/\/+$/, "");
+ // viking://~ is the home alias: the server expands it to the caller's own user
+ // space, so it needs no client-side rewrite.
+ if (trimmed === "viking://~" || trimmed.startsWith("viking://~/")) return trimmed;
+ // Legacy compat: uid-less viking://user/<reserved> URIs may still sit in plugin
+ // configs. Newer servers reject them, so rewrite to an explicit-uid URI here.
const m = trimmed.match(/^viking:\/\/user(?:\/(.*))?$/);
if (!m) return trimmed;
const rawRest = (m[1] ?? "").trim();
diff --git a/examples/claude-code-memory-plugin/scripts/skill-experience.mjs b/examples/claude-code-memory-plugin/scripts/skill-experience.mjs
index 2ee3ceaa6..eff2e58fa 100644
--- a/examples/claude-code-memory-plugin/scripts/skill-experience.mjs
+++ b/examples/claude-code-memory-plugin/scripts/skill-experience.mjs
@@ -100,7 +100,7 @@ async function findExperiences(query) {
method: "POST",
body: JSON.stringify({
query,
- target_uri: "viking://user/memories/experiences",
+ target_uri: "viking://~/memories/experiences",
context_type: "memory",
limit: cfg.skillExperienceLimit,
score_threshold: cfg.scoreThreshold,
diff --git a/examples/claude-code-memory-plugin/scripts/skill-experience.test.mjs b/examples/claude-code-memory-plugin/scripts/skill-experience.test.mjs
index ccfef9c7c..520a232d0 100644
--- a/examples/claude-code-memory-plugin/scripts/skill-experience.test.mjs
+++ b/examples/claude-code-memory-plugin/scripts/skill-experience.test.mjs
@@ -166,7 +166,7 @@ test("skill experience hook injects matching experience memories", async () => {
});
assert.equal(requests.length, 1);
- assert.equal(requests[0].target_uri, "viking://user/memories/experiences");
+ assert.equal(requests[0].target_uri, "viking://~/memories/experiences");
assert.equal(requests[0].limit, 3);
} finally {
await rm(tmp, { recursive: true, force: true });
diff --git a/examples/claude-code-memory-plugin/skills/ov-experience-memory/SKILL.md b/examples/claude-code-memory-plugin/skills/ov-experience-memory/SKILL.md
index 9472bff01..c70110027 100644
--- a/examples/claude-code-memory-plugin/skills/ov-experience-memory/SKILL.md
+++ b/examples/claude-code-memory-plugin/skills/ov-experience-memory/SKILL.md
@@ -50,7 +50,7 @@ context or deeper intent analysis is useful.
3. Search only the current user's Experience root:
```text
- viking://user/memories/experiences
+ viking://~/memories/experiences
```
For tools using MCP-style parameters, set `target_uri` to this root. For
diff --git a/examples/codex-memory-plugin/README.md b/examples/codex-memory-plugin/README.md
index 849eab33d..88670017b 100644
--- a/examples/codex-memory-plugin/README.md
+++ b/examples/codex-memory-plugin/README.md
@@ -3,6 +3,10 @@
Long-term semantic memory for [Codex](https://developers.openai.com/codex), powered by [OpenViking](https://github.com/volcengine/OpenViking).
TraeCode CLI 2.0 supports the same plugin format; use the shared installer's dedicated `--harness trae-cli` entry.
+> **Requires an OpenViking server with `viking://~` home-alias support.** Recall targets the
+> caller's own context space through `viking://~/memories` and `viking://~/skills`; the uid-less
+> `viking://user/memories` shorthand is rejected by newer servers.
+
This is the Codex counterpart to [`claude-code-memory-plugin`](../claude-code-memory-plugin). It hooks Codex's lifecycle to:
- **Session-start profile injection** on `startup`, `clear`, and `resume`: load `profile.md` plus abstract-annotated indexes of `preferences/` and `entities/` through the shared CJK-aware profile builder.
@@ -200,7 +204,7 @@ On `startup` or `clear`, the script:
On any /commit failure (OV unreachable, non-2xx, timeout) we **preserve state** (don't `clearState`) so the next sweep can retry.
-On `resume`, the script skips commit/sweep. It still injects the profile block. If local state has no live `ovSessionId`, it also reads `/api/v1/sessions/{cx-session-id}/context` and combines the latest committed archive overview into the same `SessionStart` output. The archive block includes a `viking://user/sessions/{cx-session-id}/history/` URI and tells the model to use the OpenViking MCP `read`/`search` tools for exact prior commands, file paths, tool outputs, or messages. Set `OPENVIKING_RESUME_ARCHIVE_INJECT=0` to disable the archive half without disabling profile injection.
+On `resume`, the script skips commit/sweep. It still injects the profile block. If local state has no live `ovSessionId`, it also reads `/api/v1/sessions/{cx-session-id}/context` and combines the latest committed archive overview into the same `SessionStart` output. The archive block includes a `viking://~/sessions/{cx-session-id}/history/` URI and tells the model to use the OpenViking MCP `read`/`search` tools for exact prior commands, file paths, tool outputs, or messages. Set `OPENVIKING_RESUME_ARCHIVE_INJECT=0` to disable the archive half without disabling profile injection.
### Auto-recall (every UserPromptSubmit)
diff --git a/examples/codex-memory-plugin/scripts/auto-recall.mjs b/examples/codex-memory-plugin/scripts/auto-recall.mjs
index 2fd0d9360..8bab6cce7 100644
--- a/examples/codex-memory-plugin/scripts/auto-recall.mjs
+++ b/examples/codex-memory-plugin/scripts/auto-recall.mjs
@@ -240,13 +240,13 @@ async function searchScope(query, targetUri, limit, bucket = "memories", session
// Candidate target URIs for a bucket, most-specific first. In trusted mode a
// user's memories live under viking://user/<user>/<bucket>; in api_key mode the
-// server canonicalizes the generic viking://user/<bucket> to the authenticated
-// user. Trying the user-scoped path first with the generic path as a fallback
-// recalls correctly in both modes. De-duped so a missing/blank user never
-// doubles the request count.
+// configured user may be unknown, so the viking://~ home alias lets the server
+// resolve the authenticated caller's own space. Trying the user-scoped path
+// first with the home alias as a fallback recalls correctly in both modes.
+// De-duped so a missing/blank user never doubles the request count.
function userScopedTargets(kind) {
const suffix = kind.replace(/^\/+/, "");
- const targets = [`viking://user/${suffix}`];
+ const targets = [`viking://~/${suffix}`];
if (cfg.user) {
targets.unshift(`viking://user/${cfg.user}/${suffix}`);
}
diff --git a/examples/codex-memory-plugin/scripts/session-start-commit.mjs b/examples/codex-memory-plugin/scripts/session-start-commit.mjs
index 7e1634455..111ef731b 100644
--- a/examples/codex-memory-plugin/scripts/session-start-commit.mjs
+++ b/examples/codex-memory-plugin/scripts/session-start-commit.mjs
@@ -134,7 +134,7 @@ function truncateText(text, maxChars) {
function formatResumeArchiveContext(ovSessionId, context) {
const overview = String(context?.latest_archive_overview || "").trim();
if (!overview) return "";
- const archiveUri = `viking://user/sessions/${ovSessionId}/history/`;
+ const archiveUri = `viking://~/sessions/${ovSessionId}/history/`;
const body = truncateText(overview, cfg.resumeArchiveMaxChars);
return [
"OpenViking session archive digest:",
diff --git a/examples/codex-memory-plugin/scripts/shared/recall-core.mjs b/examples/codex-memory-plugin/scripts/shared/recall-core.mjs
index 83d444f26..bff58bc83 100644
--- a/examples/codex-memory-plugin/scripts/shared/recall-core.mjs
+++ b/examples/codex-memory-plugin/scripts/shared/recall-core.mjs
@@ -14,8 +14,8 @@ const STOPWORDS = new Set([
]);
const USER_RESERVED_DIRS = new Set(["memories", "skills"]);
const SOURCES = [
- { type: "memory", uri: "viking://user/memories", bucket: "memories" },
- { type: "skill", uri: "viking://user/skills", bucket: "skills" },
+ { type: "memory", uri: "viking://~/memories", bucket: "memories" },
+ { type: "skill", uri: "viking://~/skills", bucket: "skills" },
];
const DEFAULT_CONTEXT_LIMIT = 10;
const DEFAULT_CONTEXT_MAX_TOKENS = 1600;
@@ -272,6 +272,11 @@ async function resolveUserSpace(fetchJSON, actorPeerId = "") {
async function resolveTargetUri(fetchJSON, targetUri, actorPeerId = "") {
const trimmed = targetUri.trim().replace(/\/+$/, "");
+ // viking://~ is the home alias: the server expands it to the caller's own user
+ // space, so it needs no client-side rewrite.
+ if (trimmed === "viking://~" || trimmed.startsWith("viking://~/")) return trimmed;
+ // Legacy compat: uid-less viking://user/<reserved> URIs may still sit in plugin
+ // configs. Newer servers reject them, so rewrite to an explicit-uid URI here.
const m = trimmed.match(/^viking:\/\/user(?:\/(.*))?$/);
if (!m) return trimmed;
const rawRest = (m[1] ?? "").trim();
diff --git a/examples/codex-memory-plugin/skills/ov-experience-memory/SKILL.md b/examples/codex-memory-plugin/skills/ov-experience-memory/SKILL.md
index 9472bff01..c70110027 100644
--- a/examples/codex-memory-plugin/skills/ov-experience-memory/SKILL.md
+++ b/examples/codex-memory-plugin/skills/ov-experience-memory/SKILL.md
@@ -50,7 +50,7 @@ context or deeper intent analysis is useful.
3. Search only the current user's Experience root:
```text
- viking://user/memories/experiences
+ viking://~/memories/experiences
```
For tools using MCP-style parameters, set `target_uri` to this root. For
diff --git a/examples/compile/graph-show/llm-wiki/wiki_graph.py b/examples/compile/graph-show/llm-wiki/wiki_graph.py
index 05683c340..8c03fa78e 100755
--- a/examples/compile/graph-show/llm-wiki/wiki_graph.py
+++ b/examples/compile/graph-show/llm-wiki/wiki_graph.py
@@ -13,7 +13,7 @@ arguments, OPENVIKING_* environment variables, then ~/.openviking/ovcli.conf.
Examples:
python wiki_graph.py viking://resources/my-wiki
python wiki_graph.py \
- viking://resources/wiki-a viking://user/resources/wiki-b \
+ viking://resources/wiki-a viking://~/resources/wiki-b \
--output llm-wiki-graph.html --title "团队知识图谱"
python wiki_graph.py viking://resources/my-wiki \
--url http://localhost:1933 --api-key "$OPENVIKING_API_KEY"
diff --git a/examples/dsh-memory-plugin/README.md b/examples/dsh-memory-plugin/README.md
index 911cb7942..6f28624dc 100644
--- a/examples/dsh-memory-plugin/README.md
+++ b/examples/dsh-memory-plugin/README.md
@@ -2,6 +2,10 @@
An installable DeepSeek Harness bundle that adds OpenViking auto-recall, session capture, `viking://` URI protection, and the OpenViking MCP tool surface.
+> **Requires an OpenViking server with `viking://~` home-alias support.** Recall targets the
+> caller's own context space through `viking://~/memories` and `viking://~/skills`; the uid-less
+> `viking://user/memories` shorthand is rejected by newer servers.
+
Published as [`@openviking/dsh-memory-plugin`](https://www.npmjs.com/package/@openviking/dsh-memory-plugin).
## Install
diff --git a/examples/dsh-memory-plugin/shared/recall-core.mjs b/examples/dsh-memory-plugin/shared/recall-core.mjs
index 83d444f26..bff58bc83 100644
--- a/examples/dsh-memory-plugin/shared/recall-core.mjs
+++ b/examples/dsh-memory-plugin/shared/recall-core.mjs
@@ -14,8 +14,8 @@ const STOPWORDS = new Set([
]);
const USER_RESERVED_DIRS = new Set(["memories", "skills"]);
const SOURCES = [
- { type: "memory", uri: "viking://user/memories", bucket: "memories" },
- { type: "skill", uri: "viking://user/skills", bucket: "skills" },
+ { type: "memory", uri: "viking://~/memories", bucket: "memories" },
+ { type: "skill", uri: "viking://~/skills", bucket: "skills" },
];
const DEFAULT_CONTEXT_LIMIT = 10;
const DEFAULT_CONTEXT_MAX_TOKENS = 1600;
@@ -272,6 +272,11 @@ async function resolveUserSpace(fetchJSON, actorPeerId = "") {
async function resolveTargetUri(fetchJSON, targetUri, actorPeerId = "") {
const trimmed = targetUri.trim().replace(/\/+$/, "");
+ // viking://~ is the home alias: the server expands it to the caller's own user
+ // space, so it needs no client-side rewrite.
+ if (trimmed === "viking://~" || trimmed.startsWith("viking://~/")) return trimmed;
+ // Legacy compat: uid-less viking://user/<reserved> URIs may still sit in plugin
+ // configs. Newer servers reject them, so rewrite to an explicit-uid URI here.
const m = trimmed.match(/^viking:\/\/user(?:\/(.*))?$/);
if (!m) return trimmed;
const rawRest = (m[1] ?? "").trim();
diff --git a/examples/langchain-langgraph/langchain/rag/quick_app.py b/examples/langchain-langgraph/langchain/rag/quick_app.py
index 068b725f3..ec7e82bfd 100644
--- a/examples/langchain-langgraph/langchain/rag/quick_app.py
+++ b/examples/langchain-langgraph/langchain/rag/quick_app.py
@@ -13,7 +13,7 @@ from langchain_openviking import InMemoryOpenVikingClient, OpenVikingRetriever
def build_app(client: InMemoryOpenVikingClient | None = None):
client = client or InMemoryOpenVikingClient(
{
- "viking://user/memories/preferences/deploy_color.md": (
+ "viking://~/memories/preferences/deploy_color.md": (
"The user prefers azure as the deployment color for LangChain examples."
),
"viking://resources/runbooks/langchain.md": (
@@ -23,7 +23,7 @@ def build_app(client: InMemoryOpenVikingClient | None = None):
)
retriever = OpenVikingRetriever(
client=client,
- target_uri=["viking://user/memories", "viking://resources"],
+ target_uri=["viking://~/memories", "viking://resources"],
limit=4,
content_mode="auto",
)
diff --git a/examples/langchain-langgraph/langgraph/agent/quick_app.py b/examples/langchain-langgraph/langgraph/agent/quick_app.py
index 7a5fcebd0..ba8a0e7f8 100644
--- a/examples/langchain-langgraph/langgraph/agent/quick_app.py
+++ b/examples/langchain-langgraph/langgraph/agent/quick_app.py
@@ -21,7 +21,7 @@ class AgentState(TypedDict, total=False):
def build_app(client: InMemoryOpenVikingClient | None = None):
client = client or InMemoryOpenVikingClient(
{
- "viking://user/memories/profile.md": (
+ "viking://~/memories/profile.md": (
"The user wants LangGraph agents to use OpenViking for durable context."
),
"viking://resources/runbooks/langgraph.md": (
diff --git a/examples/langchain-langgraph/langgraph/middleware/quick_app.py b/examples/langchain-langgraph/langgraph/middleware/quick_app.py
index 37c5d8777..b78d6e57b 100644
--- a/examples/langchain-langgraph/langgraph/middleware/quick_app.py
+++ b/examples/langchain-langgraph/langgraph/middleware/quick_app.py
@@ -21,7 +21,7 @@ class AgentState(TypedDict, total=False):
def build_app(client: InMemoryOpenVikingClient | None = None):
client = client or InMemoryOpenVikingClient(
{
- "viking://user/memories/profile.md": (
+ "viking://~/memories/profile.md": (
"OpenViking middleware examples should answer with azure."
)
}
@@ -29,7 +29,7 @@ def build_app(client: InMemoryOpenVikingClient | None = None):
session_id = "langgraph-middleware-demo"
middleware = OpenVikingContextMiddleware(
client=client,
- target_uri="viking://user/memories",
+ target_uri="viking://~/memories",
session_id_resolver=lambda _state, _runtime: session_id,
include_active_messages=True,
)
diff --git a/examples/memory-plugin-shared/README.md b/examples/memory-plugin-shared/README.md
index 0706d7be3..924d46053 100644
--- a/examples/memory-plugin-shared/README.md
+++ b/examples/memory-plugin-shared/README.md
@@ -3,6 +3,10 @@
This directory contains shared JavaScript modules that are vendored into the
Claude Code, Codex, OpenCode, and pi memory plugins by `sync.mjs`.
+> **Requires an OpenViking server with `viking://~` home-alias support.** Recall targets the
+> caller's own context space through `viking://~/memories` and `viking://~/skills`; the uid-less
+> `viking://user/memories` shorthand is rejected by newer servers.
+
## Workspace Peers
`lib/workspace-peer.mjs` derives the default actor peer from the current
diff --git a/examples/memory-plugin-shared/lib/recall-core.mjs b/examples/memory-plugin-shared/lib/recall-core.mjs
index 6b8011f90..11ac785d6 100644
--- a/examples/memory-plugin-shared/lib/recall-core.mjs
+++ b/examples/memory-plugin-shared/lib/recall-core.mjs
@@ -13,8 +13,8 @@ const STOPWORDS = new Set([
]);
const USER_RESERVED_DIRS = new Set(["memories", "skills"]);
const SOURCES = [
- { type: "memory", uri: "viking://user/memories", bucket: "memories" },
- { type: "skill", uri: "viking://user/skills", bucket: "skills" },
+ { type: "memory", uri: "viking://~/memories", bucket: "memories" },
+ { type: "skill", uri: "viking://~/skills", bucket: "skills" },
];
const DEFAULT_CONTEXT_LIMIT = 10;
const DEFAULT_CONTEXT_MAX_TOKENS = 1600;
@@ -271,6 +271,11 @@ async function resolveUserSpace(fetchJSON, actorPeerId = "") {
async function resolveTargetUri(fetchJSON, targetUri, actorPeerId = "") {
const trimmed = targetUri.trim().replace(/\/+$/, "");
+ // viking://~ is the home alias: the server expands it to the caller's own user
+ // space, so it needs no client-side rewrite.
+ if (trimmed === "viking://~" || trimmed.startsWith("viking://~/")) return trimmed;
+ // Legacy compat: uid-less viking://user/<reserved> URIs may still sit in plugin
+ // configs. Newer servers reject them, so rewrite to an explicit-uid URI here.
const m = trimmed.match(/^viking:\/\/user(?:\/(.*))?$/);
if (!m) return trimmed;
const rawRest = (m[1] ?? "").trim();
diff --git a/examples/openclaw-plugin/README.md b/examples/openclaw-plugin/README.md
index 634005472..3d1e3352b 100644
--- a/examples/openclaw-plugin/README.md
+++ b/examples/openclaw-plugin/README.md
@@ -269,7 +269,7 @@ They serve different roles:
Resource and skill imports are intentionally separate because they land in different OpenViking namespaces and use different server APIs:
- resources go through `/api/v1/resources` and land under `viking://resources/...`
-- skills go through `/api/v1/skills` and land under `viking://user/skills/...`
+- skills go through `/api/v1/skills` and land under `viking://user/<uid>/skills/...`
The plugin also registers explicit slash commands for manual imports:
@@ -277,7 +277,7 @@ The plugin also registers explicit slash commands for manual imports:
/add-resource ./README.md --to viking://resources/openviking-readme --wait
/add-skill ./skills/install-openviking-memory --wait
/ov-search "OpenViking install" --uri viking://resources/openviking-readme
-/ov-search "memory install skill" --uri viking://user/skills
+/ov-search "memory install skill" --uri viking://~/skills
```
Resource import supports remote URLs, Git URLs, local files, local directories, and uploaded zip files. OpenViking's built-in parsers cover common documents and media such as Markdown, text, PDF, HTML, Word, PowerPoint, Excel, EPUB, images, audio, and video. Directory imports also accept common code, documentation, and config file extensions such as `.py`, `.js`, `.ts`, `.go`, `.rs`, `.java`, `.cpp`, `.json`, `.yaml`, `.toml`, `.csv`, `.rst`, `.proto`, `.tf`, and `.vue`.
diff --git a/examples/openclaw-plugin/README_CN.md b/examples/openclaw-plugin/README_CN.md
index 5e855c981..3ad96c963 100644
--- a/examples/openclaw-plugin/README_CN.md
+++ b/examples/openclaw-plugin/README_CN.md
@@ -73,7 +73,7 @@ Agent 会自动完成安装 → 配置 → 重启 → 验证。详见 [INSTALL-A
| `ov_archive_search` | 对当前 session 已归档的原始对话消息做关键词 grep |
| `ov_archive_expand` | 按 archive ID 展开原始消息 |
| `ov_recall_trace` | 查看 auto-recall 和显式 recall/search 记录的召回链路 |
-| `add_skill` | 将 `SKILL.md`、skill 目录、原始 skill 内容或 MCP tool dict 导入 `viking://user/skills/...` |
+| `add_skill` | 将 `SKILL.md`、skill 目录、原始 skill 内容或 MCP tool dict 导入 `viking://user/<uid>/skills/...` |
| `ov_search` | 检索已导入的 resources 和 skills |
| `ov_read` | 读取 `ov_search` / trace 返回的 `viking://...` OpenViking 虚拟 URI 完整内容 |
| `ov_multi_read` | 一次读取多个精确 `viking://...` URI,适合同时读取 overview 和同级切片 |
@@ -314,7 +314,7 @@ preflight 阶段的 `assemble()` 并不是简单地把旧聊天记录塞回来
Resource 和 skill 保持两个入口,因为它们落在不同 OpenViking 命名空间,并使用不同服务端 API:
- resource 走 `/api/v1/resources`,落到 `viking://resources/...`
-- skill 走 `/api/v1/skills`,落到 `viking://user/skills/...`
+- skill 走 `/api/v1/skills`,落到 `viking://user/<uid>/skills/...`
插件也提供显式 slash command,方便手动导入:
@@ -322,7 +322,7 @@ Resource 和 skill 保持两个入口,因为它们落在不同 OpenViking 命
/add-resource ./README.md --to viking://resources/openviking-readme --wait
/add-skill ./skills/install-openviking-memory --wait
/ov-search "OpenViking install" --uri viking://resources/openviking-readme
-/ov-search "memory install skill" --uri viking://user/skills
+/ov-search "memory install skill" --uri viking://~/skills
/ov-recall-trace --turn latest --include-content
```
diff --git a/examples/openclaw-plugin/client.ts b/examples/openclaw-plugin/client.ts
index a24010d13..84e354e81 100644
--- a/examples/openclaw-plugin/client.ts
+++ b/examples/openclaw-plugin/client.ts
@@ -36,7 +36,7 @@ export type FsListResult = FsListEntry[];
export type CaptureMode = "semantic" | "keyword";
function userSessionUri(sessionId: string): string {
- return `viking://user/sessions/${encodeURIComponent(sessionId)}`;
+ return `viking://~/sessions/${encodeURIComponent(sessionId)}`;
}
export type OpenVikingClientOptions = {
diff --git a/examples/openclaw-plugin/config.ts b/examples/openclaw-plugin/config.ts
index 8f0ee8143..fe0cc01e9 100644
--- a/examples/openclaw-plugin/config.ts
+++ b/examples/openclaw-plugin/config.ts
@@ -136,7 +136,7 @@ export type ParsedMemoryOpenVikingConfig = Required<
};
const DEFAULT_BASE_URL = "http://127.0.0.1:1933";
-const DEFAULT_TARGET_URI = "viking://user/memories";
+const DEFAULT_TARGET_URI = "viking://~/memories";
const DEFAULT_TIMEOUT_MS = 15000;
const DEFAULT_CAPTURE_MODE = "semantic";
const DEFAULT_CAPTURE_MAX_LENGTH = 24000;
diff --git a/examples/openclaw-plugin/health_check_tools/ov-healthcheck.py b/examples/openclaw-plugin/health_check_tools/ov-healthcheck.py
index b59171ed7..622f0db53 100644
--- a/examples/openclaw-plugin/health_check_tools/ov-healthcheck.py
+++ b/examples/openclaw-plugin/health_check_tools/ov-healthcheck.py
@@ -852,7 +852,7 @@ class OpenVikingInspector:
self.base_url,
"/api/v1/search/find",
method="POST",
- body={"query": query, "target_uri": "viking://user/memories", "limit": limit},
+ body={"query": query, "target_uri": "viking://~/memories", "limit": limit},
headers=self.headers(),
timeout=20.0,
insecure=self.insecure,
diff --git a/examples/openclaw-plugin/memory-ranking.ts b/examples/openclaw-plugin/memory-ranking.ts
index 62ea28f62..38cbad323 100644
--- a/examples/openclaw-plugin/memory-ranking.ts
+++ b/examples/openclaw-plugin/memory-ranking.ts
@@ -232,8 +232,8 @@ function lexicalOverlapBoost(tokens: string[], text: string, maxBoost = DEFAULT_
function inferResourceType(item: FindResultItem): string | undefined {
if (item.uri.startsWith("viking://resources")) return "resource";
if (item.uri.startsWith("viking://session/")) return "session";
- if (item.uri.startsWith("viking://user/skills") || item.uri.startsWith("viking://skills")) return "agent";
- if (item.uri.startsWith("viking://user/")) return "user";
+ if (item.uri.startsWith("viking://user/skills") || item.uri.startsWith("viking://~/skills") || item.uri.startsWith("viking://skills")) return "agent";
+ if (item.uri.startsWith("viking://user/") || item.uri.startsWith("viking://~/")) return "user";
return undefined;
}
diff --git a/examples/openclaw-plugin/openclaw.plugin.json b/examples/openclaw-plugin/openclaw.plugin.json
index e54c954ad..6643a336e 100644
--- a/examples/openclaw-plugin/openclaw.plugin.json
+++ b/examples/openclaw-plugin/openclaw.plugin.json
@@ -120,7 +120,7 @@
},
"targetUri": {
"label": "Search Target URI",
- "placeholder": "viking://user/memories",
+ "placeholder": "viking://~/memories",
"help": "Default OpenViking target URI for memory search"
},
"timeoutMs": {
diff --git a/examples/openclaw-plugin/plugin/openviking-query-runtime.ts b/examples/openclaw-plugin/plugin/openviking-query-runtime.ts
index c0f6aed68..24d736116 100644
--- a/examples/openclaw-plugin/plugin/openviking-query-runtime.ts
+++ b/examples/openclaw-plugin/plugin/openviking-query-runtime.ts
@@ -386,7 +386,7 @@ export function createOpenVikingQueryRuntime<TQueryConfigContext>(deps: OpenViki
};
const [resourcesSettled, skillsSettled] = await Promise.allSettled([
runSearch("viking://resources"),
- runSearch("viking://user/skills"),
+ runSearch("viking://~/skills"),
]);
const successful: FindResult[] = [];
if (resourcesSettled.status === "fulfilled") {
diff --git a/examples/openclaw-plugin/plugin/openviking-recall-trace-runtime.ts b/examples/openclaw-plugin/plugin/openviking-recall-trace-runtime.ts
index 82921b099..e24468ce0 100644
--- a/examples/openclaw-plugin/plugin/openviking-recall-trace-runtime.ts
+++ b/examples/openclaw-plugin/plugin/openviking-recall-trace-runtime.ts
@@ -120,8 +120,8 @@ function toLimitedInteger(value: unknown, fallback: number, min: number, max: nu
function inferUriType(uri: string): string {
if (uri.startsWith("viking://resources") || uri.startsWith("viking://resource")) return "resource";
if (uri.startsWith("viking://session/")) return "session";
- if (uri.startsWith("viking://user/skills") || uri.startsWith("viking://skills")) return "skill";
- if (uri.startsWith("viking://user/")) return "user_memory";
+ if (uri.startsWith("viking://user/skills") || uri.startsWith("viking://~/skills") || uri.startsWith("viking://skills")) return "skill";
+ if (uri.startsWith("viking://user/") || uri.startsWith("viking://~/")) return "user_memory";
if (uri.includes("/archive") || uri.includes("/history/")) return "archive";
return "unknown";
}
diff --git a/examples/openclaw-plugin/plugin/openviking-runtime-utils.ts b/examples/openclaw-plugin/plugin/openviking-runtime-utils.ts
index 8e07ee3ba..4bdc0c5ec 100644
--- a/examples/openclaw-plugin/plugin/openviking-runtime-utils.ts
+++ b/examples/openclaw-plugin/plugin/openviking-runtime-utils.ts
@@ -10,8 +10,10 @@ export function previewText(value: unknown, maxChars: number): string | undefine
export function inferRecallResourceType(uri: string): RecallResourceType | undefined {
if (uri.startsWith("viking://resources")) return "resource";
- if (uri.startsWith("viking://user/skills") || uri.startsWith("viking://skills")) return "agent";
- if (uri.startsWith("viking://user/")) return "user";
+ // viking://~ is the home alias for the caller's own user space; configured target
+ // URIs use it, while server responses come back canonical as viking://user/<uid>/...
+ if (uri.startsWith("viking://user/skills") || uri.startsWith("viking://~/skills") || uri.startsWith("viking://skills")) return "agent";
+ if (uri.startsWith("viking://user/") || uri === "viking://~" || uri.startsWith("viking://~/")) return "user";
return undefined;
}
diff --git a/examples/openclaw-plugin/routing/memory-uri.ts b/examples/openclaw-plugin/routing/memory-uri.ts
index cc79441b3..da9e1523a 100644
--- a/examples/openclaw-plugin/routing/memory-uri.ts
+++ b/examples/openclaw-plugin/routing/memory-uri.ts
@@ -1,6 +1,10 @@
const MEMORY_URI_PATTERNS = [
/^viking:\/\/user\/(?:[^/]+(?:\/agent\/[^/]+)?\/)?memories(?:\/|$)/,
/^viking:\/\/user\/[^/]+\/peers\/[^/]+\/memories(?:\/|$)/,
+ // viking://~ is the home alias for the caller's own user space. Configured targets and
+ // model-supplied URIs may use it; server responses stay canonical viking://user/<uid>/...
+ /^viking:\/\/~\/memories(?:\/|$)/,
+ /^viking:\/\/~\/peers\/[^/]+\/memories(?:\/|$)/,
/^viking:\/\/agent\/(?:[^/]+(?:\/user\/[^/]+)?\/)?memories(?:\/|$)/,
];
diff --git a/examples/openclaw-plugin/setup-helper/install.js b/examples/openclaw-plugin/setup-helper/install.js
index 652e7aca1..6df189020 100755
--- a/examples/openclaw-plugin/setup-helper/install.js
+++ b/examples/openclaw-plugin/setup-helper/install.js
@@ -2446,7 +2446,7 @@ async function configureOpenClawPlugin({
const candidates = {
mode: "remote",
baseUrl: effectiveRuntimeConfig.baseUrl || remoteBaseUrl,
- targetUri: "viking://user/memories",
+ targetUri: "viking://~/memories",
autoRecall: true,
autoCapture: true,
apiKey: effectiveRuntimeConfig.apiKey || undefined,
diff --git a/examples/openclaw-plugin/skills/install-openviking-memory/SKILL.md b/examples/openclaw-plugin/skills/install-openviking-memory/SKILL.md
index a6b6f797f..97fdc3531 100644
--- a/examples/openclaw-plugin/skills/install-openviking-memory/SKILL.md
+++ b/examples/openclaw-plugin/skills/install-openviking-memory/SKILL.md
@@ -590,7 +590,7 @@ These are the keys under `plugins.entries.openviking.config` in `openclaw.json`.
| `peer_prefix` | `""` | Optional prefix for assistant `peer_id` / actor peer values when `peer_role=assistant`. Letters / digits / `_` / `-`. |
| `accountId` | — | Required when `apiKey` is a root key. |
| `userId` | — | Required when `apiKey` is a root key. |
-| `targetUri` | `viking://user/memories` | Default search scope URI. |
+| `targetUri` | `viking://~/memories` | Default search scope URI. |
| `timeoutMs` | (plugin default) | HTTP timeout for OpenViking calls. |
| `autoCapture` | `true` | Auto-append turn messages to the OpenViking session at `afterTurn`; extraction runs only after a threshold commit, `/compact`, or explicit `memory_store`. |
| `captureMode` | `"semantic"` | Filter mode used by the server-side extraction pipeline: `semantic` or `keyword`. |
diff --git a/examples/openclaw-plugin/skills/openviking-context-database/SKILL.md b/examples/openclaw-plugin/skills/openviking-context-database/SKILL.md
index c1ac41de9..4a557291e 100644
--- a/examples/openclaw-plugin/skills/openviking-context-database/SKILL.md
+++ b/examples/openclaw-plugin/skills/openviking-context-database/SKILL.md
@@ -67,7 +67,7 @@ Core config lives under `plugins.entries.openviking.config`:
| `peer_role` | `assistant` | Peer identity mode: `none`, `assistant`, or `person`. Session messages use body `peer_id`; data-plane recall/search uses `X-OpenViking-Actor-Peer`. |
| `peer_prefix` | empty | Optional prefix for assistant `peer_id` / actor peer values when `peer_role=assistant`. |
| `accountId` / `userId` | empty | Advanced tenant identity headers for root-key or trusted deployments. |
-| `targetUri` | `viking://user/memories` | Default search scope for legacy targeted memory search. |
+| `targetUri` | `viking://~/memories` | Default search scope for legacy targeted memory search. |
| `autoCapture` | `true` | Append sanitized turn text to OpenViking sessions. |
| `captureMode` | `semantic` | `semantic` or `keyword`; affects server-side extraction filtering. |
| `captureMaxLength` | `24000` | Max sanitized text length per captured turn. |
@@ -196,7 +196,7 @@ The current OpenClaw tool exposes the parameters above. The underlying client al
### `add_skill`
-Import Agent Skills into `viking://user/skills/...`.
+Import Agent Skills into `viking://~/skills/...`.
| Parameter | Required | Description |
|---|---|---|
diff --git a/examples/openclaw-plugin/skills/ov-experience-memory/SKILL.md b/examples/openclaw-plugin/skills/ov-experience-memory/SKILL.md
index 9472bff01..c70110027 100644
--- a/examples/openclaw-plugin/skills/ov-experience-memory/SKILL.md
+++ b/examples/openclaw-plugin/skills/ov-experience-memory/SKILL.md
@@ -50,7 +50,7 @@ context or deeper intent analysis is useful.
3. Search only the current user's Experience root:
```text
- viking://user/memories/experiences
+ viking://~/memories/experiences
```
For tools using MCP-style parameters, set `target_uri` to this root. For
diff --git a/examples/openclaw-plugin/tests/e2e/test-memory-chain.py b/examples/openclaw-plugin/tests/e2e/test-memory-chain.py
index a0036ada8..180f3d3cb 100644
--- a/examples/openclaw-plugin/tests/e2e/test-memory-chain.py
+++ b/examples/openclaw-plugin/tests/e2e/test-memory-chain.py
@@ -409,7 +409,7 @@ class OpenVikingInspector:
return result
def search_memories(
- self, query: str, target_uri: str = "viking://user/memories", limit: int = 10
+ self, query: str, target_uri: str = "viking://~/memories", limit: int = 10
) -> list:
result = self._post(
"/api/v1/search/find",
diff --git a/examples/openclaw-plugin/tests/test-memory-chain.py b/examples/openclaw-plugin/tests/test-memory-chain.py
index 01b04728c..0b114525d 100644
--- a/examples/openclaw-plugin/tests/test-memory-chain.py
+++ b/examples/openclaw-plugin/tests/test-memory-chain.py
@@ -239,7 +239,7 @@ class OpenVikingInspector:
return result
def search_memories(
- self, query: str, target_uri: str = "viking://user/memories", limit: int = 10
+ self, query: str, target_uri: str = "viking://~/memories", limit: int = 10
) -> list:
result = self._post(
"/api/v1/search/find",
diff --git a/examples/openclaw-plugin/tests/ut/client.test.ts b/examples/openclaw-plugin/tests/ut/client.test.ts
index 730abc4d6..530636326 100644
--- a/examples/openclaw-plugin/tests/ut/client.test.ts
+++ b/examples/openclaw-plugin/tests/ut/client.test.ts
@@ -60,6 +60,13 @@ describe("isMemoryUri", () => {
expect(isMemoryUri("viking://user/memories/")).toBe(true);
});
+ it("accepts the ~ home alias", () => {
+ expect(isMemoryUri("viking://~/memories")).toBe(true);
+ expect(isMemoryUri("viking://~/memories/abc-123")).toBe(true);
+ expect(isMemoryUri("viking://~/peers/assistant/memories/item-1")).toBe(true);
+ expect(isMemoryUri("viking://~/skills/abc")).toBe(false);
+ });
+
it("returns false for user skills URI", () => {
expect(isMemoryUri("viking://user/skills/abc")).toBe(false);
});
@@ -564,14 +571,14 @@ describe("OpenVikingClient canonical namespace policy", () => {
true,
{ transport },
);
- await client.find("test query", { targetUri: "viking://user/memories" }, "my-agent");
+ await client.find("test query", { targetUri: "viking://~/memories" }, "my-agent");
const findCall = transport.mock.calls.find((c) =>
String(c[0]).endsWith("/api/v1/search/find"),
)!;
const body = JSON.parse(String((findCall[1] as RequestInit).body));
const headers = new Headers((findCall[1] as RequestInit).headers);
- expect(body.target_uri).toBe("viking://user/memories");
+ expect(body.target_uri).toBe("viking://~/memories");
expect(headers.get("X-OpenViking-Actor-Peer")).toBe("my-agent");
});
@@ -593,14 +600,14 @@ describe("OpenVikingClient canonical namespace policy", () => {
true,
{ transport },
);
- await client.find("test query", { targetUri: "viking://user/memories" }, "my-agent");
+ await client.find("test query", { targetUri: "viking://~/memories" }, "my-agent");
const findCall = transport.mock.calls.find((c) =>
String(c[0]).endsWith("/api/v1/search/find"),
)!;
const body = JSON.parse(String((findCall[1] as RequestInit).body));
const headers = new Headers((findCall[1] as RequestInit).headers);
- expect(body.target_uri).toBe("viking://user/memories");
+ expect(body.target_uri).toBe("viking://~/memories");
expect(headers.get("X-OpenViking-Actor-Peer")).toBe("my-agent");
});
@@ -622,13 +629,13 @@ describe("OpenVikingClient canonical namespace policy", () => {
true,
{ transport },
);
- await client.find("test", { targetUri: "viking://user/memories" }, "shared-agent");
+ await client.find("test", { targetUri: "viking://~/memories" }, "shared-agent");
const findCall = transport.mock.calls.find((c) =>
String(c[0]).endsWith("/api/v1/search/find"),
)!;
const body = JSON.parse(String((findCall[1] as RequestInit).body));
- expect(body.target_uri).toBe("viking://user/memories");
+ expect(body.target_uri).toBe("viking://~/memories");
});
it("keeps user skill target URI unchanged while using actor peer routing", async () => {
@@ -649,13 +656,13 @@ describe("OpenVikingClient canonical namespace policy", () => {
false,
{ transport },
);
- await client.find("test", { targetUri: "viking://user/skills" }, "shared-agent");
+ await client.find("test", { targetUri: "viking://~/skills" }, "shared-agent");
const findCall = transport.mock.calls.find((c) =>
String(c[0]).endsWith("/api/v1/search/find"),
)!;
const body = JSON.parse(String((findCall[1] as RequestInit).body));
- expect(body.target_uri).toBe("viking://user/skills");
+ expect(body.target_uri).toBe("viking://~/skills");
});
it("includes peer_id when addSessionMessage receives one", async () => {
diff --git a/examples/openclaw-plugin/tests/ut/plugin-modules.test.ts b/examples/openclaw-plugin/tests/ut/plugin-modules.test.ts
index f4891fd8a..dbb776752 100644
--- a/examples/openclaw-plugin/tests/ut/plugin-modules.test.ts
+++ b/examples/openclaw-plugin/tests/ut/plugin-modules.test.ts
@@ -279,7 +279,7 @@ describe("plugin module seams", () => {
});
const search = await runtime.searchOpenViking({ query: "spec" }, "agent-main", { agentId: "agent-main", sessionId: "session-1" }) as any;
- expect(find.mock.calls.map(([, options]) => options.targetUri)).toEqual(["viking://resources", "viking://user/skills"]);
+ expect(find.mock.calls.map(([, options]) => options.targetUri)).toEqual(["viking://resources", "viking://~/skills"]);
expect(search.content[0].text).toContain("Found 2 OpenViking results for \"spec\"");
expect(search.details).toMatchObject({ action: "searched", total: 2 });
expect(recordAndFlush).toHaveBeenCalledWith(expect.objectContaining({
diff --git a/examples/openclaw-plugin/tests/ut/tools.test.ts b/examples/openclaw-plugin/tests/ut/tools.test.ts
index 31d4f99b5..0cbf774d8 100644
--- a/examples/openclaw-plugin/tests/ut/tools.test.ts
+++ b/examples/openclaw-plugin/tests/ut/tools.test.ts
@@ -958,7 +958,7 @@ describe("Tool: ov_search (behavioral)", () => {
.filter((call) => String(call[0]).endsWith("/api/v1/search/find"))
.map((call) => JSON.parse(String((call[1] as RequestInit).body)));
expect(findBodies.some((body) => body.target_uri === "viking://resources")).toBe(true);
- expect(findBodies.some((body) => String(body.target_uri).startsWith("viking://user/") && String(body.target_uri).endsWith("/skills"))).toBe(true);
+ expect(findBodies.some((body) => String(body.target_uri) === "viking://~/skills")).toBe(true);
});
it("returns partial results when one default scope search fails", async () => {
diff --git a/examples/opencode-plugin/README.md b/examples/opencode-plugin/README.md
index 2f40d2d47..d7a2624d0 100644
--- a/examples/opencode-plugin/README.md
+++ b/examples/opencode-plugin/README.md
@@ -2,6 +2,10 @@
A unified OpenCode plugin for OpenViking repository retrieval and long-term memory.
+> **Requires an OpenViking server with `viking://~` home-alias support.** Recall targets the
+> caller's own context space through `viking://~/memories` and `viking://~/skills`; the uid-less
+> `viking://user/memories` shorthand is rejected by newer servers.
+
This is the only OpenCode plugin example maintained in this repository. It supersedes the former split examples for indexed repository prompt injection and long-term memory.
The plugin uses OpenCode hooks for lifecycle behavior and registers OpenViking's standard stdio MCP proxy for model tools. It does not install or require an OpenCode skill, and agents do not need to run `ov` shell commands.
diff --git a/examples/opencode-plugin/lib/shared/recall-core.mjs b/examples/opencode-plugin/lib/shared/recall-core.mjs
index 83d444f26..bff58bc83 100644
--- a/examples/opencode-plugin/lib/shared/recall-core.mjs
+++ b/examples/opencode-plugin/lib/shared/recall-core.mjs
@@ -14,8 +14,8 @@ const STOPWORDS = new Set([
]);
const USER_RESERVED_DIRS = new Set(["memories", "skills"]);
const SOURCES = [
- { type: "memory", uri: "viking://user/memories", bucket: "memories" },
- { type: "skill", uri: "viking://user/skills", bucket: "skills" },
+ { type: "memory", uri: "viking://~/memories", bucket: "memories" },
+ { type: "skill", uri: "viking://~/skills", bucket: "skills" },
];
const DEFAULT_CONTEXT_LIMIT = 10;
const DEFAULT_CONTEXT_MAX_TOKENS = 1600;
@@ -272,6 +272,11 @@ async function resolveUserSpace(fetchJSON, actorPeerId = "") {
async function resolveTargetUri(fetchJSON, targetUri, actorPeerId = "") {
const trimmed = targetUri.trim().replace(/\/+$/, "");
+ // viking://~ is the home alias: the server expands it to the caller's own user
+ // space, so it needs no client-side rewrite.
+ if (trimmed === "viking://~" || trimmed.startsWith("viking://~/")) return trimmed;
+ // Legacy compat: uid-less viking://user/<reserved> URIs may still sit in plugin
+ // configs. Newer servers reject them, so rewrite to an explicit-uid URI here.
const m = trimmed.match(/^viking:\/\/user(?:\/(.*))?$/);
if (!m) return trimmed;
const rawRest = (m[1] ?? "").trim();
diff --git a/examples/openwebui-plugin/README.md b/examples/openwebui-plugin/README.md
index f143f76de..9f9803824 100644
--- a/examples/openwebui-plugin/README.md
+++ b/examples/openwebui-plugin/README.md
@@ -23,9 +23,9 @@ Seven curated tools, all auto-discovered by Open WebUI:
| Tool | OpenViking endpoint | Purpose |
| --- | --- | --- |
| `ov_search` | `POST /api/v1/search/find` | Semantic search across memories, resources, skills |
-| `ov_recall_memories` | `POST /api/v1/search/find` (scoped to `viking://user/memories/`) | Recall personal memories for the current query |
-| `ov_add_memory` | `POST /api/v1/content/write` to `viking://user/memories/<name>` | Persist a new memory |
-| `ov_list_memories` | `GET /api/v1/fs/ls?uri=viking://user/memories/` | Browse the memories directory |
+| `ov_recall_memories` | `POST /api/v1/search/find` (scoped to `viking://~/memories/`) | Recall personal memories for the current query |
+| `ov_add_memory` | `POST /api/v1/content/write` to `viking://~/memories/<name>` | Persist a new memory |
+| `ov_list_memories` | `GET /api/v1/fs/ls?uri=viking://~/memories/` | Browse the memories directory |
| `ov_read_resource` | `GET /api/v1/content/read` | Read full text content of any `viking://` URI |
| `ov_add_resource` | `POST /api/v1/resources` | Ingest a remote URL or path-reachable file |
| `ov_session_status` | `GET /api/v1/sessions/{id}` | Inspect counts and archive state of a session |
@@ -88,17 +88,17 @@ and returns `{hits: [{uri, score, snippet?}], raw}`. Use this when you want to
search across memories, resources, and skills together.
### `ov_recall_memories`
-Same as `ov_search` but `target_uri` is forced to `viking://user/memories/`,
+Same as `ov_search` but `target_uri` is forced to `viking://~/memories/`,
so only personal memories are searched. Use this in chat to ask "what do you
remember about me re: X?".
### `ov_add_memory`
Persists a memory. Takes `{name, content, mode?, wait?}` and writes
-`viking://user/memories/<name>` via OpenViking's content write API. `mode` is
+`viking://~/memories/<name>` via OpenViking's content write API. `mode` is
one of `replace | append | create`.
### `ov_list_memories`
-Lists entries directly under `viking://user/memories/`. Takes
+Lists entries directly under `viking://~/memories/`. Takes
`{recursive?, limit?}`.
### `ov_read_resource`
diff --git a/examples/openwebui-plugin/openviking_openwebui/config.py b/examples/openwebui-plugin/openviking_openwebui/config.py
index 1caf22439..8940214ae 100644
--- a/examples/openwebui-plugin/openviking_openwebui/config.py
+++ b/examples/openwebui-plugin/openviking_openwebui/config.py
@@ -47,7 +47,7 @@ class Settings:
@property
def memories_uri(self) -> str:
"""Conventional URI prefix where personal memories live."""
- return "viking://user/memories/"
+ return "viking://~/memories/"
def load_settings() -> Settings:
diff --git a/examples/openwebui-plugin/openviking_openwebui/tools.py b/examples/openwebui-plugin/openviking_openwebui/tools.py
index 4d4d8117d..f465fa492 100644
--- a/examples/openwebui-plugin/openviking_openwebui/tools.py
+++ b/examples/openwebui-plugin/openviking_openwebui/tools.py
@@ -60,7 +60,7 @@ class RecallRequest(BaseModel):
class AddMemoryRequest(BaseModel):
- name: str = Field(..., description="Filename under viking://user/memories/, e.g. 'profile.md'")
+ name: str = Field(..., description="Filename under viking://~/memories/, e.g. 'profile.md'")
content: str = Field(..., description="Memory body, plain text or Markdown")
mode: Literal["replace", "append", "create"] = "replace"
wait: bool = Field(False, description="Block until semantic indexing completes")
@@ -171,7 +171,7 @@ async def ov_recall_memories(
client: OVClient = Depends(get_client),
settings: Settings = Depends(get_settings),
) -> SearchResponse:
- """Search scoped to viking://user/memories/ for personal memory recall."""
+ """Search scoped to viking://~/memories/ for personal memory recall."""
payload = {
"query": body.query,
"limit": body.limit,
@@ -188,7 +188,7 @@ async def ov_recall_memories(
"/tools/ov_add_memory",
response_model=AddMemoryResponse,
operation_id="ov_add_memory",
- summary="Persist a new memory under viking://user/memories/.",
+ summary="Persist a new memory under viking://~/memories/.",
)
async def ov_add_memory(
body: AddMemoryRequest,
@@ -213,7 +213,7 @@ async def ov_add_memory(
@router.post(
"/tools/ov_list_memories",
operation_id="ov_list_memories",
- summary="List entries under viking://user/memories/.",
+ summary="List entries under viking://~/memories/.",
)
async def ov_list_memories(
body: ListMemoriesRequest,
diff --git a/examples/openwebui-plugin/tests/test_tools.py b/examples/openwebui-plugin/tests/test_tools.py
index 9af72660a..c25bfdf9d 100644
--- a/examples/openwebui-plugin/tests/test_tools.py
+++ b/examples/openwebui-plugin/tests/test_tools.py
@@ -51,7 +51,7 @@ async def test_ov_search_calls_find(client: httpx.AsyncClient) -> None:
"status": "ok",
"result": {
"memories": [
- {"uri": "viking://user/memories/a.md", "score": 0.9, "snippet": "hi"}
+ {"uri": "viking://~/memories/a.md", "score": 0.9, "snippet": "hi"}
],
"resources": [],
},
@@ -61,7 +61,7 @@ async def test_ov_search_calls_find(client: httpx.AsyncClient) -> None:
resp = await client.post("/tools/ov_search", json={"query": "hello", "limit": 5})
assert resp.status_code == 200, resp.text
data = resp.json()
- assert data["hits"][0]["uri"] == "viking://user/memories/a.md"
+ assert data["hits"][0]["uri"] == "viking://~/memories/a.md"
assert data["hits"][0]["score"] == pytest.approx(0.9)
assert route.called
sent = route.calls.last.request
@@ -79,7 +79,7 @@ async def test_ov_recall_scopes_to_memories(client: httpx.AsyncClient) -> None:
sent = route.calls.last.request
_assert_headers(sent)
raw = sent.content.decode()
- assert "viking://user/memories/" in raw
+ assert "viking://~/memories/" in raw
assert '"limit":3' in raw.replace(" ", "")
@@ -94,11 +94,11 @@ async def test_ov_add_memory_writes_under_memories(client: httpx.AsyncClient) ->
)
assert resp.status_code == 200, resp.text
data = resp.json()
- assert data["uri"] == "viking://user/memories/profile.md"
+ assert data["uri"] == "viking://~/memories/profile.md"
sent = route.calls.last.request
_assert_headers(sent)
raw = sent.content.decode()
- assert "viking://user/memories/profile.md" in raw
+ assert "viking://~/memories/profile.md" in raw
assert "I like Rust" in raw
@@ -111,7 +111,7 @@ async def test_ov_list_memories_calls_fs_ls(client: httpx.AsyncClient) -> None:
assert resp.status_code == 200
sent = route.calls.last.request
_assert_headers(sent)
- assert "uri=viking%3A%2F%2Fuser%2Fmemories%2F" in str(sent.url)
+ assert "uri=viking%3A%2F%2F~%2Fmemories%2F" in str(sent.url)
assert "recursive=true" in str(sent.url)
assert "node_limit=50" in str(sent.url)
diff --git a/examples/pi-coding-agent-extension/README.md b/examples/pi-coding-agent-extension/README.md
index 67bf54c6a..4397668ce 100644
--- a/examples/pi-coding-agent-extension/README.md
+++ b/examples/pi-coding-agent-extension/README.md
@@ -2,6 +2,10 @@
Long-term semantic memory and context takeover for [pi](https://github.com/earendil-works/pi) sessions, powered by [OpenViking](https://github.com/volcengine/OpenViking). Recall happens automatically before every prompt, capture happens after every turn, and OpenViking can own long-term context by replacing committed history with an archive overview in pi's `context` hook.
+> **Requires an OpenViking server with `viking://~` home-alias support.** Recall targets the
+> caller's own context space through `viking://~/memories` and `viking://~/skills`; the uid-less
+> `viking://user/memories` shorthand is rejected by newer servers.
+
> Design informed by lessons from all three OpenViking agent plugins: synchronous recall from OpenClaw, production-hardened capture/ranking from Claude Code, and anti-patterns dodged from Hermes's stale prefetch approach. See [DESIGN.md](./DESIGN.md) for the base design and [TAKEOVER.md](./TAKEOVER.md) for the context-takeover layer.
## Quick Start
diff --git a/examples/pi-coding-agent-extension/shared/recall-core.mjs b/examples/pi-coding-agent-extension/shared/recall-core.mjs
index 83d444f26..bff58bc83 100644
--- a/examples/pi-coding-agent-extension/shared/recall-core.mjs
+++ b/examples/pi-coding-agent-extension/shared/recall-core.mjs
@@ -14,8 +14,8 @@ const STOPWORDS = new Set([
]);
const USER_RESERVED_DIRS = new Set(["memories", "skills"]);
const SOURCES = [
- { type: "memory", uri: "viking://user/memories", bucket: "memories" },
- { type: "skill", uri: "viking://user/skills", bucket: "skills" },
+ { type: "memory", uri: "viking://~/memories", bucket: "memories" },
+ { type: "skill", uri: "viking://~/skills", bucket: "skills" },
];
const DEFAULT_CONTEXT_LIMIT = 10;
const DEFAULT_CONTEXT_MAX_TOKENS = 1600;
@@ -272,6 +272,11 @@ async function resolveUserSpace(fetchJSON, actorPeerId = "") {
async function resolveTargetUri(fetchJSON, targetUri, actorPeerId = "") {
const trimmed = targetUri.trim().replace(/\/+$/, "");
+ // viking://~ is the home alias: the server expands it to the caller's own user
+ // space, so it needs no client-side rewrite.
+ if (trimmed === "viking://~" || trimmed.startsWith("viking://~/")) return trimmed;
+ // Legacy compat: uid-less viking://user/<reserved> URIs may still sit in plugin
+ // configs. Newer servers reject them, so rewrite to an explicit-uid URI here.
const m = trimmed.match(/^viking:\/\/user(?:\/(.*))?$/);
if (!m) return trimmed;
const rawRest = (m[1] ?? "").trim();
diff --git a/examples/pi-coding-agent-extension/tools.ts b/examples/pi-coding-agent-extension/tools.ts
index 6228174f1..b806269ac 100644
--- a/examples/pi-coding-agent-extension/tools.ts
+++ b/examples/pi-coding-agent-extension/tools.ts
@@ -17,7 +17,7 @@ export function registerTools(pi: any, client: OVClient, sync?: SyncManager): vo
],
parameters: Type.Object({
query: Type.String({ description: "Search query" }),
- scope: Type.Optional(Type.String({ description: "Viking URI prefix to scope search (e.g., 'viking://user/memories/')" })),
+ scope: Type.Optional(Type.String({ description: "Viking URI prefix to scope search (e.g., 'viking://~/memories/')" })),
limit: Type.Optional(Type.Number({ description: "Max results (default: 10)" })),
}),
async execute(
diff --git a/examples/skills/ov-experience-memory/SKILL.md b/examples/skills/ov-experience-memory/SKILL.md
index 9472bff01..c70110027 100644
--- a/examples/skills/ov-experience-memory/SKILL.md
+++ b/examples/skills/ov-experience-memory/SKILL.md
@@ -50,7 +50,7 @@ context or deeper intent analysis is useful.
3. Search only the current user's Experience root:
```text
- viking://user/memories/experiences
+ viking://~/memories/experiences
```
For tools using MCP-style parameters, set `target_uri` to this root. For
diff --git a/examples/skills/ov-resources/docs/add-resource.md b/examples/skills/ov-resources/docs/add-resource.md
index d58e3d049..7287dd01d 100644
--- a/examples/skills/ov-resources/docs/add-resource.md
+++ b/examples/skills/ov-resources/docs/add-resource.md
@@ -43,7 +43,7 @@ ov add-resource ./docs --to "viking://resources/2026/2026-01-01/"
ov add-resource ./docs --parent "viking://resources/docs/"
# Place under the current user's private resource root
-ov add-resource ./docs --parent "viking://user/resources/docs/"
+ov add-resource ./docs --parent "viking://~/resources/docs/"
# Place under a specific peer's private resource root
ov add-resource ./docs --parent "viking://user/alice/peers/web-visitor-alice/resources/docs/"
@@ -53,7 +53,7 @@ ov add-resource ./docs --parent-auto-create "viking://resources/docs/2026/05/07"
ov add-resource ./docs -p "viking://resources/docs/{calendar:today}"
```
-`viking://user/resources/...` is current-user shorthand and resolves to `viking://user/{user_id}/resources/...`. `peer_id` path segments must be safe single-segment identifiers such as `web-visitor-alice`; values with `:`, `+`, `.`, `..`, or path separators are rejected.
+`viking://~/resources/...` is the home alias and expands to `viking://user/{user_id}/resources/...` for the authenticated caller. The uid-less spelling `viking://user/resources/...` is no longer accepted and returns an error pointing at the `viking://~/...` form. `peer_id` path segments must be safe single-segment identifiers such as `web-visitor-alice`; values with `:`, `+`, `.`, `..`, or path separators are rejected.
## Async Processing Control
diff --git a/examples/skills/ov-resources/docs/search.md b/examples/skills/ov-resources/docs/search.md
index f8ab44737..e2798aae3 100644
--- a/examples/skills/ov-resources/docs/search.md
+++ b/examples/skills/ov-resources/docs/search.md
@@ -105,10 +105,10 @@ Results are grouped by `context_type`:
ov find "authentication" --uri "viking://resources"
# Search only memories
-ov find "preferences" --uri "viking://user/memories"
+ov find "preferences" --uri "viking://~/memories"
# Search only skills
-ov find "web search" --uri "viking://user/skills"
+ov find "web search" --uri "viking://~/skills"
# Search specific project
ov find "API endpoints" --uri "viking://resources/my-project"
diff --git a/examples/skills/ov_dream/scripts/dream.py b/examples/skills/ov_dream/scripts/dream.py
index ceab51719..6f0f92e69 100644
--- a/examples/skills/ov_dream/scripts/dream.py
+++ b/examples/skills/ov_dream/scripts/dream.py
@@ -13,7 +13,10 @@ from urllib.request import Request, urlopen
DEFAULT_BASE_URL = "http://127.0.0.1:1933"
DEFAULT_TARGET_URI = "viking://user/default"
+# Legacy uid-less spelling, still accepted from existing configs.
LEGACY_TARGET_URI = "viking://user/memories"
+# Home alias for the caller's own user space; emitted URIs stay explicit-uid.
+HOME_MEMORIES_TARGET_URI = "viking://~/memories"
SERVERLESS_BASE_URL = "https://api.vikingdb.cn-beijing.volces.com/openviking"
@@ -78,7 +81,7 @@ class OpenVikingClient:
if normalized == DEFAULT_TARGET_URI:
user_space = self._headers().get("X-OpenViking-User", "default") or "default"
return f"viking://user/{user_space}"
- if normalized == LEGACY_TARGET_URI:
+ if normalized in {LEGACY_TARGET_URI, HOME_MEMORIES_TARGET_URI}:
user_space = self._headers().get("X-OpenViking-User", "default") or "default"
return f"viking://user/{user_space}/memories/"
return target_uri
diff --git a/examples/skills/ov_dream/tests/test_dream_cli.py b/examples/skills/ov_dream/tests/test_dream_cli.py
index 97b8c5c33..5b8e47ca4 100644
--- a/examples/skills/ov_dream/tests/test_dream_cli.py
+++ b/examples/skills/ov_dream/tests/test_dream_cli.py
@@ -59,6 +59,9 @@ def test_recall_expands_default_user_root_to_explicit_user_space(monkeypatch) ->
client._resolve_target_uri("viking://user/default/memories/")
== "viking://user/default/memories/"
)
+ # Home alias resolves to the same explicit-uid target as the legacy spelling.
+ assert client._resolve_target_uri("viking://~/memories") == "viking://user/default/memories/"
+ assert client._resolve_target_uri("viking://~/memories/") == "viking://user/default/memories/"
def test_recall_default_target_uri_is_user_root() -> None:
diff --git a/examples/zcode-memory-plugin/README.md b/examples/zcode-memory-plugin/README.md
index 766c7fb0f..a6db48bec 100644
--- a/examples/zcode-memory-plugin/README.md
+++ b/examples/zcode-memory-plugin/README.md
@@ -2,6 +2,10 @@
This package provides a ZCode lifecycle adapter for OpenViking long-term memory. It reuses the shared `memory-plugin-shared` runtime — no memory logic is duplicated. Only a thin ZCode adapter is new.
+> **Requires an OpenViking server with `viking://~` home-alias support.** Recall targets the
+> caller's own context space through `viking://~/memories` and `viking://~/skills`; the uid-less
+> `viking://user/memories` shorthand is rejected by newer servers.
+
## What it does
- **SessionStart** — injects user profile and preferences/entities into context.
diff --git a/examples/zcode-memory-plugin/scripts/shared/recall-core.mjs b/examples/zcode-memory-plugin/scripts/shared/recall-core.mjs
index 83d444f26..bff58bc83 100644
--- a/examples/zcode-memory-plugin/scripts/shared/recall-core.mjs
+++ b/examples/zcode-memory-plugin/scripts/shared/recall-core.mjs
@@ -14,8 +14,8 @@ const STOPWORDS = new Set([
]);
const USER_RESERVED_DIRS = new Set(["memories", "skills"]);
const SOURCES = [
- { type: "memory", uri: "viking://user/memories", bucket: "memories" },
- { type: "skill", uri: "viking://user/skills", bucket: "skills" },
+ { type: "memory", uri: "viking://~/memories", bucket: "memories" },
+ { type: "skill", uri: "viking://~/skills", bucket: "skills" },
];
const DEFAULT_CONTEXT_LIMIT = 10;
const DEFAULT_CONTEXT_MAX_TOKENS = 1600;
@@ -272,6 +272,11 @@ async function resolveUserSpace(fetchJSON, actorPeerId = "") {
async function resolveTargetUri(fetchJSON, targetUri, actorPeerId = "") {
const trimmed = targetUri.trim().replace(/\/+$/, "");
+ // viking://~ is the home alias: the server expands it to the caller's own user
+ // space, so it needs no client-side rewrite.
+ if (trimmed === "viking://~" || trimmed.startsWith("viking://~/")) return trimmed;
+ // Legacy compat: uid-less viking://user/<reserved> URIs may still sit in plugin
+ // configs. Newer servers reject them, so rewrite to an explicit-uid URI here.
const m = trimmed.match(/^viking:\/\/user(?:\/(.*))?$/);
if (!m) return trimmed;
const rawRest = (m[1] ?? "").trim();
diff --git a/examples/zcode-memory-plugin/scripts/zcode-hooks.test.mjs b/examples/zcode-memory-plugin/scripts/zcode-hooks.test.mjs
index 6e79c022a..3efe14d4e 100644
--- a/examples/zcode-memory-plugin/scripts/zcode-hooks.test.mjs
+++ b/examples/zcode-memory-plugin/scripts/zcode-hooks.test.mjs
@@ -16,7 +16,7 @@ const PLUGIN_ROOT = join(dirname(fileURLToPath(import.meta.url)), "..");
test("uri guard deny output contains only recognized keys", () => {
const output = evaluateZcodeUriGuard({
tool_name: "Read",
- tool_input: { file_path: "viking://user/memories/profile.md" },
+ tool_input: { file_path: "viking://~/memories/profile.md" },
});
assert.ok(output.hookSpecificOutput);
assert.equal(output.hookSpecificOutput.hookEventName, "PreToolUse");
diff --git a/integrations/langchain/README.md b/integrations/langchain/README.md
index 854204957..44c2794d2 100644
--- a/integrations/langchain/README.md
+++ b/integrations/langchain/README.md
@@ -5,6 +5,12 @@ LangChain and LangGraph applications. It keeps framework-specific adapters
separate from the OpenViking server and communicates with remote OpenViking
instances through the lightweight `openviking-sdk` package.
+> **OpenViking Server requirement**: examples here use the `viking://~` home alias
+> (for example `viking://~/memories`), which the server expands to the authenticated
+> caller's own user space, so they require a server with `viking://~` support. The
+> uid-less `viking://user/memories` shorthand is rejected by newer servers; pass an
+> explicit `viking://user/<uid>/...` URI when targeting another user.
+
## Installation
For LangChain retrievers, tools, message history, and context wrappers:
@@ -32,7 +38,7 @@ client = SyncHTTPClient(
client.initialize()
retriever = OpenVikingRetriever(
client=client,
- target_uri="viking://user/memories",
+ target_uri="viking://~/memories",
)
try:
diff --git a/integrations/langchain/README_CN.md b/integrations/langchain/README_CN.md
index da04dffe2..58f12bf09 100644
--- a/integrations/langchain/README_CN.md
+++ b/integrations/langchain/README_CN.md
@@ -4,6 +4,8 @@
集成包。框架适配逻辑不再依赖 OpenViking 服务端实现,远程访问统一通过轻量的
`openviking-sdk` 完成。
+> **OpenViking Server 要求**:文档中的示例使用 `viking://~` Home 别名(例如 `viking://~/memories`),Server 会将其展开为当前调用方自己的用户空间,因此需要一个支持 `viking://~` 的 Server。不带 uid 的 `viking://user/memories` 旧写法会被新版 Server 拒绝;要访问其他用户请显式传入 `viking://user/<uid>/...`。
+
## 安装
LangChain Retriever、Tools、Message History 和 Context Wrapper:
@@ -31,7 +33,7 @@ client = SyncHTTPClient(
client.initialize()
retriever = OpenVikingRetriever(
client=client,
- target_uri="viking://user/memories",
+ target_uri="viking://~/memories",
)
try:
diff --git a/integrations/langchain/src/langchain_openviking/_uri.py b/integrations/langchain/src/langchain_openviking/_uri.py
index 01f2822ce..e6ab79828 100644
--- a/integrations/langchain/src/langchain_openviking/_uri.py
+++ b/integrations/langchain/src/langchain_openviking/_uri.py
@@ -8,6 +8,10 @@ from dataclasses import dataclass
_CONTENT_SEGMENTS = frozenset({"memories", "resources", "skills"})
_PEER_CONTENT_SEGMENTS = frozenset({"memories", "resources"})
+# ``viking://~`` is the home alias for the caller's own user space. The server expands it
+# at the request boundary, so responses always come back as ``viking://user/<uid>/...``;
+# here we only need it to classify with the same shape as an explicit user URI.
+_HOME_ALIAS = "~"
@dataclass(frozen=True)
@@ -33,6 +37,12 @@ def _uri_parts(uri: str) -> tuple[str, ...]:
def _content_segment_index(parts: tuple[str, ...]) -> int | None:
+ if parts and parts[0] == _HOME_ALIAS:
+ if len(parts) >= 2 and parts[1] in _CONTENT_SEGMENTS:
+ return 1
+ if len(parts) >= 4 and parts[1] == "peers" and parts[3] in _PEER_CONTENT_SEGMENTS:
+ return 3
+ return None
if len(parts) >= 2 and parts[:2] == ("agent", "skills"):
return 1
if len(parts) >= 3 and parts[0] == "agent" and parts[2] in _CONTENT_SEGMENTS:
@@ -54,8 +64,11 @@ def classify_uri(uri: str) -> UriClassification:
"""Classify the user/agent namespace shape of a Viking URI."""
parts = _uri_parts(uri)
+ scope = parts[0] if parts else ""
+ if scope == _HOME_ALIAS:
+ scope = "user"
return UriClassification(
parts=parts,
- scope=parts[0] if parts else "",
+ scope=scope,
content_index=_content_segment_index(parts),
)
diff --git a/integrations/langchain/src/langchain_openviking/store.py b/integrations/langchain/src/langchain_openviking/store.py
index bc02f4915..1c546faa9 100644
--- a/integrations/langchain/src/langchain_openviking/store.py
+++ b/integrations/langchain/src/langchain_openviking/store.py
@@ -59,6 +59,12 @@ class OpenVikingStore(BaseStore):
Values are stored as JSON records under ``<root_uri>/data``. A separate
markdown projection under ``<root_uri>/index`` gives OpenViking semantic
retrieval a compact document to index for query-based ``search`` calls.
+
+ Args:
+ root_uri: Base URI for the store. Defaults to the ``viking://~`` home alias,
+ which the server expands to the authenticated caller's own user space, so
+ this requires an OpenViking server with ``viking://~`` support. Pass an
+ explicit ``viking://user/<uid>/...`` URI to target a specific user.
"""
def __init__(
@@ -71,7 +77,7 @@ class OpenVikingStore(BaseStore):
user: str | None = None,
user_id: str | None = None,
actor_peer_id: str | None = None,
- root_uri: str = "viking://user/memories/langgraph_store",
+ root_uri: str = "viking://~/memories/langgraph_store",
index: bool | list[str] | None = None,
wait: bool = True,
timeout: float | None = None,
diff --git a/integrations/langchain/src/langchain_openviking/testing.py b/integrations/langchain/src/langchain_openviking/testing.py
index b802c4287..a98d9a153 100644
--- a/integrations/langchain/src/langchain_openviking/testing.py
+++ b/integrations/langchain/src/langchain_openviking/testing.py
@@ -386,7 +386,7 @@ class InMemoryOpenVikingClient:
def add_skill(self, data: Any, **_: Any) -> dict[str, Any]:
name = data.get("name", "skill") if isinstance(data, dict) else "skill"
- uri = f"viking://user/skills/{name}.md"
+ uri = f"viking://~/skills/{name}.md"
self.records[uri] = str(data)
return {"status": "completed", "uri": uri, "name": name}
diff --git a/integrations/langchain/src/langchain_openviking/tools.py b/integrations/langchain/src/langchain_openviking/tools.py
index 6fad3f54a..591380abd 100644
--- a/integrations/langchain/src/langchain_openviking/tools.py
+++ b/integrations/langchain/src/langchain_openviking/tools.py
@@ -754,7 +754,7 @@ def _grep_session_history(
max_matches: int,
) -> dict[str, Any]:
session = call_openviking(client, "get_session", session_id=session_id, auto_create=False)
- session_uri = item_value(session, "uri", f"viking://user/sessions/{session_id}")
+ session_uri = item_value(session, "uri", f"viking://~/sessions/{session_id}")
history_uri = f"{str(session_uri).rstrip('/')}/history"
tokens = _archive_query_tokens(query)
try:
diff --git a/openviking/core/directories.py b/openviking/core/directories.py
index e21099f0c..409864fcd 100644
--- a/openviking/core/directories.py
+++ b/openviking/core/directories.py
@@ -164,9 +164,9 @@ class DirectoryInitializer:
async def initialize_account_directories(self, ctx: RequestContext) -> int:
"""Initialize account-shared scope roots.
- ``viking://user`` is a current-user shorthand at API boundaries. Its
- concrete metadata belongs to ``viking://user/{user_id}`` and is created
- by ``initialize_user_directories``.
+ ``viking://user`` is the container of user spaces, not a space itself.
+ Its concrete metadata belongs to ``viking://user/{user_id}`` and is
+ created by ``initialize_user_directories``.
"""
count = 0
scope_roots = {
diff --git a/openviking/core/namespace.py b/openviking/core/namespace.py
index 7858d2e47..d005d3104 100644
--- a/openviking/core/namespace.py
+++ b/openviking/core/namespace.py
@@ -255,14 +255,26 @@ def resolve_uri(
def resolve_request_uri(uri: str, ctx: RequestContext) -> str:
- """Resolve supported current-user shorthands at an authenticated request boundary."""
+ """Resolve supported URI aliases at an authenticated request boundary.
+
+ Supported aliases are the ``~`` home alias and the legacy ``session`` scope.
+ The uid-less ``viking://user/<reserved>`` shorthand is no longer expanded:
+ it fails closed with a hint pointing at ``viking://~/...``.
+ """
if ctx.role in {Role.USER, Role.ADMIN}:
return resolve_current_user_uri(uri, ctx)
return resolve_uri(uri).uri
def resolve_current_user_uri(uri: str, ctx: RequestContext) -> str:
- """Resolve a URI field whose contract explicitly denotes the current user."""
+ """Resolve a URI field whose contract explicitly denotes the current user.
+
+ Supported aliases are ``viking://~`` (the home alias) and the legacy
+ ``viking://session/...`` scope. ``viking://user/<reserved-segment>`` used to
+ expand to the caller's space; it now fails closed with a corrective hint,
+ because the same spelling is a valid explicit-uid URI for a user literally
+ named after the reserved segment.
+ """
parts = uri_parts(uri)
if not parts:
return "viking://"
@@ -280,12 +292,24 @@ def resolve_current_user_uri(uri: str, ctx: RequestContext) -> str:
canonical = f"{canonical}/{'/'.join(parts[2:])}"
return canonical
- if parts[0] == "user":
- if len(parts) == 1:
- return canonical_user_root(ctx)
- if parts[1] != ctx.user.user_id and _is_user_relative_root_segment(parts[1]):
- return f"{canonical_user_root(ctx)}/{'/'.join(parts[1:])}"
+ if (
+ parts[0] == "user"
+ and len(parts) >= 2
+ # Self-id escape: a caller literally named e.g. "resources" keeps
+ # viking://user/resources as their canonical root.
+ and parts[1] != ctx.user.user_id
+ and _is_reserved_user_root_segment(parts[1])
+ ):
+ rest = "/".join(parts[1:])
+ raise NamespaceShapeError(
+ f"'viking://user/{rest}' no longer expands to the current user's space: "
+ f"'{parts[1]}' is a reserved name, not a user id. Use 'viking://~/{rest}' "
+ f"for the current user, or 'viking://user/{{user_id}}/{rest}' for an "
+ f"explicit user."
+ )
+ # Bare 'viking://user' and explicit-uid forms fall through to the canonical
+ # parser; the bare form keeps container semantics (is_container=True).
return resolve_uri(uri).uri
@@ -414,5 +438,12 @@ def _resolve_user_uri(
)
-def _is_user_relative_root_segment(segment: str) -> bool:
+def _is_reserved_user_root_segment(segment: str) -> bool:
+ """Return whether a first-level user segment is a reserved space name.
+
+ Reserved names (``memories``, ``resources``, ``skills``, ``peers``,
+ ``privacy``, ``sessions``) are rejected at request boundaries when they
+ appear without an explicit user id, because they are ambiguous with a user
+ literally named after them.
+ """
return segment in _CONTENT_TYPES_BY_SCOPE["user"] or segment in _USER_RELATIVE_ROOT_SEGMENTS
diff --git a/openviking/eval/datasets/local_doc_example_glm5.jsonl b/openviking/eval/datasets/local_doc_example_glm5.jsonl
index e0dfb3185..a4a79f2e4 100644
--- a/openviking/eval/datasets/local_doc_example_glm5.jsonl
+++ b/openviking/eval/datasets/local_doc_example_glm5.jsonl
@@ -1,19 +1,19 @@
{"question": "OpenViking 的核心定位是什么?与传统向量数据库(如 Milvus、Pinecone)有何本质区别?", "files": ["OpenViking/README.md", "OpenViking/docs/en/concepts/01-architecture.md"], "answer": "OpenViking 是一个专门为 AI Agent 设计的开源上下文数据库(Context Database)。与传统向量数据库的本质区别在于:\n\n1. **设计范式不同**:OpenViking 采用\"文件系统范式\"统一管理记忆、资源和技能,而传统向量数据库仅提供扁平的向量存储。\n\n2. **解决的问题不同**:OpenViking 解决 Agent 开发中的五大挑战:上下文碎片化、上下文需求激增、检索效果差、上下文不可观察、记忆迭代受限。传统向量数据库主要解决向量检索问题。\n\n3. **功能特性不同**:\n - 分层上下文加载(L0/L1/L2三层结构)显著降低 Token 消耗\n - 目录递归检索结合目录定位与语义搜索\n - 可视化检索轨迹,支持调试\n - 自动会话管理,实现上下文自我迭代\n\n4. **架构层次**:OpenViking 包含 Client、Service、Retrieve、Session、Parse、Compressor、Storage 等多层架构,而传统向量数据库主要是存储和检索层。"}
{"question": "分层记忆设计(L0 抽象层、L1 概述层、L2 内容层)的设计初衷是什么?三层之间如何保持语义一致性?", "files": ["OpenViking/docs/en/concepts/03-context-layers.md"], "answer": "分层记忆设计的初衷是平衡检索效率与内容完整性。\n\n**三层结构说明**:\n- **L0(Abstract)**:最简洁的内容表示,约100 tokens,用于向量检索和快速过滤,存储在 `.abstract.md` 文件中。\n- **L1(Overview)**:约2k tokens的综合摘要,包含导航指引,用于重排序和理解访问方式,存储在 `.overview.md` 文件中。\n- **L2(Detail)**:完整原始内容,无 token 限制,仅在确认需要时加载。\n\n**语义一致性保证**:\n1. **生成机制**:SemanticProcessor 采用自底向上的方式遍历目录,为每个节点生成 L0/L1,确保层级间的语义关联。\n2. **统一来源**:所有层级都源自同一份原始内容,L0 是 L1 的精炼,L1 是 L2 的结构化摘要。\n3. **渐进式加载**:检索时先通过 L0 定位,再通过 L1 确认相关性,最后按需加载 L2,保证语义传递。\n\n**API 支持**:\n```python\nabstract = client.abstract(\"viking://resources/docs/auth\") # L0\noverview = client.overview(\"viking://resources/docs/auth\") # L1\ncontent = client.read(\"viking://resources/docs/auth/oauth.md\") # L2\n```"}
{"question": "OpenViking 的内置记忆类型如何划分?在实际应用中如何自动提取?", "files": ["OpenViking/docs/en/concepts/02-context-types.md", "OpenViking/openviking/session/compressor_v2.py"], "answer": "OpenViking 的记忆类型由 MemoryType Schema 定义,并可通过自定义模板扩展或覆盖。当前内置类型按用途可理解为三组:\n\n**用户与环境理解**:\n- **profile**:用户基本信息,存储在 `user/memories/profile.md`\n- **preferences**:用户偏好,存储在 `user/memories/preferences/`\n- **entities**:人物、项目、组织等实体知识,存储在 `user/memories/entities/`\n- **events**:决策、里程碑等事件记录,存储在 `user/memories/events/`\n\n**助手身份与连续性**:\n- **identity**:助手身份与自我介绍,存储在 `user/memories/identity.md`\n- **soul**:助手原则、边界、风格和连续性,存储在 `user/memories/soul.md`\n\n**任务执行与学习**:\n- **cases**:可训练、可评估的任务案例\n- **trajectories**:可复用的任务执行轨迹\n- **experiences**:从执行结果提炼的可复用经验\n- **tools**:工具使用经验与最佳实践\n- **skills**:技能执行经验与工作流策略\n\n这些类型默认存储在 `user/memories/` 的对应文件或子目录中;短路径会按当前身份解析到 `viking://user/{user_id}/...`,支持的类型也可按记忆策略写入相关 Peer 空间。\n\n**自动提取机制**:\n1. 提交 Session 后格式化会话消息\n2. 根据当前记忆策略选择已启用的 MemoryType Schema\n3. 调用 LLM 生成结构化 memory operations\n4. 按各 Schema 的目录、文件名和合并规则写入并建立索引"}
-{"question": "OpenViking 如何支持多 Agent 协作场景?不同 Agent 之间的记忆如何隔离与共享?", "files": ["OpenViking/docs/en/concepts/02-context-types.md", "OpenViking/docs/en/concepts/01-architecture.md"], "answer": "OpenViking 通过 URI 命名空间和作用域设计支持多 Agent 协作。\n\n**记忆隔离机制**:\n1. **URI 命名空间**:\n - `viking://user/memories/` - 用户级记忆\n - `viking://user/{user_id}/peers/{peer_id}/memories/` - Peer 级记忆\n - `viking://resources/` - 共享资源\n - `viking://user/skills/` - User 技能\n\n2. **作用域划分**:\n - **User Scope**:用户相关的 profile、preferences、entities、events\n - **Peer/Execution Scope**:Agent 学习到的 trajectories、experiences\n - **Resources Scope**:共享的知识库\n\n**记忆共享机制**:\n1. **资源层共享**:所有 Agent 可以访问 `viking://resources/` 下的共享知识库。\n2. **用户记忆共享**:同一用户的不同 Agent 可以共享 `viking://user/memories/` 下的用户偏好和实体记忆。\n3. **关系管理**:\n\n**实际应用**:\n```python\n# Agent A 添加资源\nclient.add_resource(\"./docs/api.pdf\", to=\"viking://resources/api\")\n\n# Agent B 可以检索到\nresults = client.find(\"API usage\", target_uri=\"viking://resources/\")\n```"}
+{"question": "OpenViking 如何支持多 Agent 协作场景?不同 Agent 之间的记忆如何隔离与共享?", "files": ["OpenViking/docs/en/concepts/02-context-types.md", "OpenViking/docs/en/concepts/01-architecture.md"], "answer": "OpenViking 通过 URI 命名空间和作用域设计支持多 Agent 协作。\n\n**记忆隔离机制**:\n1. **URI 命名空间**:\n - `viking://~/memories/` - 用户级记忆\n - `viking://user/{user_id}/peers/{peer_id}/memories/` - Peer 级记忆\n - `viking://resources/` - 共享资源\n - `viking://~/skills/` - User 技能\n\n2. **作用域划分**:\n - **User Scope**:用户相关的 profile、preferences、entities、events\n - **Peer/Execution Scope**:Agent 学习到的 trajectories、experiences\n - **Resources Scope**:共享的知识库\n\n**记忆共享机制**:\n1. **资源层共享**:所有 Agent 可以访问 `viking://resources/` 下的共享知识库。\n2. **用户记忆共享**:同一用户的不同 Agent 可以共享 `viking://~/memories/` 下的用户偏好和实体记忆。\n3. **关系管理**:\n\n**实际应用**:\n```python\n# Agent A 添加资源\nclient.add_resource(\"./docs/api.pdf\", to=\"viking://resources/api\")\n\n# Agent B 可以检索到\nresults = client.find(\"API usage\", target_uri=\"viking://resources/\")\n```"}
{"question": "会话的生命周期是如何管理的?commit_session 后记忆如何被持久化和索引?", "files": ["OpenViking/docs/en/concepts/08-session.md"], "answer": "会话生命周期遵循:创建 → 交互 → 提交 的模式。\n\n**生命周期管理**:\n1. **创建**:`session = client.session(session_id=\"chat_001\")`\n2. **交互**:\n - `session.add_message(role, parts)` - 添加消息\n - `session.used(contexts, skill)` - 记录使用的上下文/技能\n3. **提交**:`session.commit()` - 归档并提取记忆\n\n**commit 后的持久化流程**:\n1. **归档流程**:\n - 增加 compression_index\n - 复制当前消息到归档目录\n - 生成结构化摘要(LLM)\n - 清空当前消息列表\n\n2. **记忆提取**:\n - SessionCompressorV2 从消息中提取和更新记忆\n - 生成 L0(abstract)和 L1(overview)\n - 写入对应的 VikingFS 目录\n\n3. **索引构建**:\n - 对新生成的记忆内容进行向量化\n - 写入 Vector Index 支持语义检索\n\n**消息结构**:\n- Message:id、role、parts、created_at\n- Part 类型:TextPart、ContextPart、ToolPart\n\n**返回结果**:\n```python\n{\n \"status\": \"committed\",\n \"memories_extracted\": 5,\n \"active_count_updated\": 2,\n \"archived\": True\n}\n```"}
-{"question": "技能系统的设计理念是什么?与传统的 Function Calling 或 Tool Use 有何不同?", "files": ["OpenViking/docs/en/api/04-skills.md", "OpenViking/docs/en/concepts/02-context-types.md"], "answer": "技能系统的设计理念是将 Agent 可调用的能力统一管理,与 Function Calling 的区别在于存储和检索方式。\n\n**设计理念**:\n1. **统一存储**:技能作为上下文的一种类型,与记忆、资源采用相同的存储范式。\n2. **分层描述**:技能同样有 L0(简短描述)、L1(详细概述)、L2(完整定义)三层结构。\n3. **语义检索**:支持通过自然语言描述检索相关技能。\n\n**与传统 Function Calling 的区别**:\n| 维度 | OpenViking Skills | Function Calling |\n|------|-------------------|-----------------|\n| 存储方式 | 文件系统 + 向量索引 | 代码定义 |\n| 检索方式 | 语义检索 + 目录定位 | 精确匹配 |\n| 描述层次 | L0/L1/L2 三层 | 单层描述 |\n| 上下文关联 | 支持统一的上下文管理 | 无 |\n\n**存储位置**:\n```\nviking://user/skills/{skill-name}/\n├── .abstract.md # L0: 简短描述\n├── SKILL.md # L1: 详细概述\n└── scripts # L2: 完整定义\n```\n\n**支持的数据格式**:\n1. Dict(Skill 格式)\n2. Dict(MCP Tool 格式)- 自动检测并转换\n3. String(SKILL.md 内容)\n4. Path(文件或目录)"}
+{"question": "技能系统的设计理念是什么?与传统的 Function Calling 或 Tool Use 有何不同?", "files": ["OpenViking/docs/en/api/04-skills.md", "OpenViking/docs/en/concepts/02-context-types.md"], "answer": "技能系统的设计理念是将 Agent 可调用的能力统一管理,与 Function Calling 的区别在于存储和检索方式。\n\n**设计理念**:\n1. **统一存储**:技能作为上下文的一种类型,与记忆、资源采用相同的存储范式。\n2. **分层描述**:技能同样有 L0(简短描述)、L1(详细概述)、L2(完整定义)三层结构。\n3. **语义检索**:支持通过自然语言描述检索相关技能。\n\n**与传统 Function Calling 的区别**:\n| 维度 | OpenViking Skills | Function Calling |\n|------|-------------------|-----------------|\n| 存储方式 | 文件系统 + 向量索引 | 代码定义 |\n| 检索方式 | 语义检索 + 目录定位 | 精确匹配 |\n| 描述层次 | L0/L1/L2 三层 | 单层描述 |\n| 上下文关联 | 支持统一的上下文管理 | 无 |\n\n**存储位置**:\n```\nviking://~/skills/{skill-name}/\n├── .abstract.md # L0: 简短描述\n├── SKILL.md # L1: 详细概述\n└── scripts # L2: 完整定义\n```\n\n**支持的数据格式**:\n1. Dict(Skill 格式)\n2. Dict(MCP Tool 格式)- 自动检测并转换\n3. String(SKILL.md 内容)\n4. Path(文件或目录)"}
{"question": "OpenViking 适合哪些具体的应用场景?例如:长期记忆助手、知识库问答、代码助手等场景的适配性如何?", "files": ["OpenViking/README.md", "OpenViking/docs/en/concepts/01-architecture.md"], "answer": "OpenViking 专为 AI Agent 设计,适合需要长期上下文管理的场景。\n\n**核心应用场景**:\n\n1. **长期记忆助手**:\n - 自动从会话中提取用户偏好、实体记忆\n - 支持跨会话的记忆累积和检索\n - 适配性:★★★★★(核心场景)\n\n2. **知识库问答**:\n - 支持 PDF、Markdown、HTML 等多种文档格式\n - 分层检索提高效率和准确性\n - 适配性:★★★★★(核心场景)\n\n3. **代码助手**:\n - 支持代码仓库解析(Git/Zip)\n - 自动过滤非代码目录(.git、node_modules)\n - 语义检索代码片段\n - 适配性:★★★★☆(支持代码解析)\n\n4. **多模态助手**:\n - 支持图片、视频、音频处理\n - VLM 描述和向量化\n - 适配性:★★★★☆(需要 VLM 支持)\n\n5. **企业知识管理**:\n - 统一管理文档、代码、技能\n - 支持分层检索和上下文组织\n - 适配性:★★★★★(核心场景)\n\n**场景适配关键能力**:\n- 分层上下文加载:降低 Token 成本\n- 目录递归检索:提高检索精度\n- 可视化检索轨迹:便于调试优化\n- 自动会话管理:实现记忆迭代"}
{"question": "如何评估 OpenViking 的检索质量?是否有内置的评测机制或指标?", "files": ["OpenViking/openviking/eval/__init__.py:1-25", "OpenViking/examples/eval/rag_eval.py"], "answer": "OpenViking 提供了 eval 评估模块,支持 RAGAS 等主流评测工具集成。\n\n**内置评测机制**:\n\n1. **eval 模块组成**:\n - `EvalSample`:评估样本数据结构\n - `EvalDataset`:评估数据集\n - `RagasEvaluator`:RAGAS 评测适配器\n - `RAGQueryPipeline`:RAG 查询流水线\n\n2. **支持的评测指标**(通过 RAGAS):\n - **faithfulness**:答案忠实度\n - **answer_relevance**:答案相关性\n - **context_precision**:上下文精确度\n - **context_recall**:上下文召回率\n\n3. **评测流程**:\n```python\n# 准备评估样本\nsamples = [EvalSample(\n query=\"问题\",\n context=[\"检索到的上下文\"],\n response=\"生成的答案\",\n ground_truth=\"标准答案\"\n)]\n\n# 运行评测\nevaluator = RagasEvaluator()\nsummary = await evaluator.evaluate_dataset(dataset)\n```\n\n4. **CLI 评测工具**:\n```bash\nuv run rag_eval.py \\\n --docs_dir ./docs \\\n --question_file ./questions.json \\\n --output ./results.json\n```\n\n**评测报告输出**:\n- 平均分数(mean_scores)\n- 每个样本的详细分数\n- JSON 格式结果保存"}
{"question": "OpenViking 与主流 RAG 框架(LlamaIndex、LangChain)的集成方式是什么?是否可以无缝替换其向量存储组件?", "files": ["OpenViking/docs/en/concepts/05-storage.md", "OpenViking/docs/en/api/06-retrieval.md"], "answer": "OpenViking 采用独立的存储架构,通过 API 接口与 RAG 框架集成。\n\n**存储架构**:\nOpenViking 使用双层存储架构,分离内容存储与索引存储:\n- **AGFS**:内容存储层,存储 L0/L1/L2 全部内容、多媒体文件\n- **Vector Index**:索引存储层,存储 URI、向量、元数据(不含文件内容)\n\n**与 RAG 框架的集成方式**:\n\n1. **API 层集成**:\n - 提供 `find()` 和 `search()` API\n - `find()`:基础向量相似度搜索\n - `search()`:复杂检索(意图分析、会话上下文、查询扩展)\n\n2. **检索结果结构**:\n```python\nclass FindResult:\n memories: List[MatchedContext] # 记忆上下文\n resources: List[MatchedContext] # 资源上下文\n skills: List[MatchedContext] # 技能上下文\n```\n\n3. **替换向量存储的可行性**:\n - 可以通过 HTTP API 与 LlamaIndex/LangChain 集成\n - 但 OpenViking 提供的是完整的上下文管理方案,不仅仅是向量存储\n - 建议作为独立的上下文管理层使用\n\n**HTTP API 支持**:\n```bash\nPOST /api/v1/search/find\n{\n \"query\": \"how to authenticate users\",\n \"limit\": 10\n}\n```"}
{"question": "在生产环境中,OpenViking 的性能瓶颈可能出现在哪些环节?如何进行容量规划和性能调优?", "files": ["OpenViking/docs/en/concepts/05-storage.md", "OpenViking/openviking/storage/viking_vector_index_backend.py"], "answer": "OpenViking 的性能瓶颈主要出现在语义处理、向量检索和存储层。\n\n**潜在性能瓶颈**:\n\n1. **语义处理队列**:\n - L0/L1 生成依赖 LLM 调用\n - 大量资源添加时队列积压\n - 调优:增加并发处理数、使用更快的 VLM\n\n2. **向量检索**:\n - 大规模数据集的相似度计算\n - 调优:使用 VikingDB 后端、调整索引参数\n\n3. **存储层**:\n - AGFS 后端选择(local/s3/memory)\n - 向量索引存储(本地持久化/HTTP 服务/Volcengine VikingDB)\n\n**容量规划建议**:\n\n1. **存储后端选择**:\n - 本地开发:`backend: \"local\"`\n - 生产环境:`backend: \"s3\"` 或 `backend: \"volcengine\"`\n\n2. **向量索引配置**:\n```json\n{\n \"storage\": {\n \"vectordb\": {\n \"backend\": \"volcengine\",\n \"dimension\": 1024\n }\n }\n}\n```\n\n3. **性能调优参数**:\n - `batch_size`:嵌入请求批量大小\n - `limit`:检索结果数量限制\n - `score_threshold`:相关性分数阈值\n\n4. **监控指标**:\n - 语义处理队列长度\n - 向量检索延迟\n - 存储层 I/O 性能"}
-{"question": "VikingFS 与 AGFS 的关系是什么?为什么需要两层文件系统抽象?", "files": ["OpenViking/docs/en/concepts/05-storage.md"], "answer": "VikingFS 是 AGFS 之上的 URI 抽象层,两者构成双层存储架构。\n\n**关系说明**:\n\n```\n┌─────────────────────────────────────────┐\n│ VikingFS (URI Abstraction) │\n│ URI Mapping · Hierarchical Access │\n│ URI Mapping · Hierarchical Access │\n└────────────────┬────────────────────────┘\n ┌────────┴────────┐\n │ │\n┌───────▼────────┐ ┌─────▼───────────┐\n│ Vector Index │ │ AGFS │\n│ (Semantic │ │ (Content │\n│ Search) │ │ Storage) │\n└────────────────┘ └─────────────────┘\n```\n\n**职责划分**:\n\n| 层级 | 职责 | 内容 |\n|------|------|------|\n| **VikingFS** | URI 抽象层 | URI 映射、层级访问 |\n| **AGFS** | 内容存储层 | L0/L1/L2 全部内容、多媒体文件 |\n| **Vector Index** | 索引存储层 | URI、向量、元数据 |\n\n**为什么需要两层抽象**:\n\n1. **职责分离**:\n - VikingFS 处理 URI 到物理路径的映射\n - AGFS 处理实际的文件读写操作\n\n2. **后端灵活性**:\n - AGFS 支持多种后端:localfs、s3fs、memory\n - VikingFS 屏蔽底层存储差异\n\n3. **URI 映射示例**:\n```\nviking://resources/docs/auth → /local/resources/docs/auth\nviking://user/memories → /local/user/memories\n```\n\n4. **设计优势**:\n - 清晰职责:向量索引负责检索,AGFS 负责存储\n - 内存优化:向量索引不存储文件内容\n - 独立扩展:向量索引和 AGFS 可独立扩展"}
+{"question": "VikingFS 与 AGFS 的关系是什么?为什么需要两层文件系统抽象?", "files": ["OpenViking/docs/en/concepts/05-storage.md"], "answer": "VikingFS 是 AGFS 之上的 URI 抽象层,两者构成双层存储架构。\n\n**关系说明**:\n\n```\n┌─────────────────────────────────────────┐\n│ VikingFS (URI Abstraction) │\n│ URI Mapping · Hierarchical Access │\n│ URI Mapping · Hierarchical Access │\n└────────────────┬────────────────────────┘\n ┌────────┴────────┐\n │ │\n┌───────▼────────┐ ┌─────▼───────────┐\n│ Vector Index │ │ AGFS │\n│ (Semantic │ │ (Content │\n│ Search) │ │ Storage) │\n└────────────────┘ └─────────────────┘\n```\n\n**职责划分**:\n\n| 层级 | 职责 | 内容 |\n|------|------|------|\n| **VikingFS** | URI 抽象层 | URI 映射、层级访问 |\n| **AGFS** | 内容存储层 | L0/L1/L2 全部内容、多媒体文件 |\n| **Vector Index** | 索引存储层 | URI、向量、元数据 |\n\n**为什么需要两层抽象**:\n\n1. **职责分离**:\n - VikingFS 处理 URI 到物理路径的映射\n - AGFS 处理实际的文件读写操作\n\n2. **后端灵活性**:\n - AGFS 支持多种后端:localfs、s3fs、memory\n - VikingFS 屏蔽底层存储差异\n\n3. **URI 映射示例**:\n```\nviking://resources/docs/auth → /local/resources/docs/auth\nviking://~/memories → /local/user/memories\n```\n\n4. **设计优势**:\n - 清晰职责:向量索引负责检索,AGFS 负责存储\n - 内存优化:向量索引不存储文件内容\n - 独立扩展:向量索引和 AGFS 可独立扩展"}
{"question": "`client.add_resource` 支持哪些输入格式?如何处理本地目录的递归添加和子目录过滤?", "files": ["OpenViking/docs/en/api/02-resources.md", "OpenViking/openviking/parse/directory_scan.py:1-80"], "answer": "`add_resource` 支持多种输入格式,目录处理通过 directory_scan 模块实现。\n\n**支持的输入格式**:\n\n| 格式 | 扩展名 | 处理方式 |\n|------|--------|----------|\n| PDF | `.pdf` | 文本和图片提取 |\n| Markdown | `.md` | 原生支持 |\n| HTML | `.html`, `.htm` | 清理文本提取 |\n| 纯文本 | `.txt` | 直接导入 |\n| JSON/YAML | `.json`, `.yaml` | 结构化解析 |\n| 代码 | `.py`, `.js`, `.go` 等 | 语法感知解析 |\n| 图片 | `.png`, `.jpg` 等 | VLM 描述 |\n| 视频/音频 | `.mp4`, `.mp3` 等 | 转录 |\n\n**目录递归添加流程**:\n\n1. **DirectoryScan 预扫描**:\n - 遍历目录树\n - 分类文件为 processable / unsupported\n - 跳过:点文件、符号链接、空文件\n\n2. **目录过滤机制**:\n```python\ndef _should_skip_directory(dir_path, root, ignore_dirs):\n # 跳过:点目录、符号链接、IGNORE_DIRS\n```\n\n3. **内置忽略目录**:\n - `.git`、`node_modules`、`__pycache__` 等\n - 通过 `IGNORE_DIRS` 常量定义\n\n4. **API 参数**:\n```python\nclient.add_resource(\n \"./documents\", # 本地目录路径\n to=\"viking://resources/docs\", # 目标 URI\n reason=\"文档说明\", # 添加原因\n wait=True, # 等待处理完成\n timeout=300 # 超时时间\n)\n```\n\n**处理流水线**:\nInput → Parser → TreeBuilder → AGFS → SemanticQueue → Vector Index"}
{"question": "向量索引是如何构建和维护的?增量更新时如何避免全量重建?", "files": ["OpenViking/openviking/storage/viking_vector_index_backend.py", "OpenViking/docs/en/concepts/05-storage.md"], "answer": "向量索引通过 VikingVectorIndexBackend 实现,支持增量更新。\n\n**索引构建流程**:\n\n1. **初始化配置**:\n```python\nconfig = VectorDBBackendConfig(\n backend=\"local\", # local/http/volcengine\n path=\"./data/vectordb\",\n dimension=1024,\n distance_metric=\"cosine\"\n)\nbackend = VikingVectorIndexBackend(config=config)\n```\n\n2. **支持的后端模式**:\n - **local**:本地持久化存储\n - **http**:远程 HTTP 服务\n - **volcengine**:火山引擎 VikingDB\n\n3. **索引特性**:\n - 使用 BruteForce 索引进行向量相似度搜索\n - 支持标量过滤和多操作符\n - 每个集合自动管理索引\n\n**增量更新机制**:\n\n1. **URI 级别操作**:\n - VikingFS 的 `rm()`、`mv()` 操作同步更新向量索引\n - 新增内容自动触发向量化并写入索引\n\n2. **避免全量重建**:\n - 通过 URI 唯一标识每个向量条目\n - 更新时只删除旧向量、插入新向量\n - 不影响其他条目的索引\n\n3. **双层存储优势**:\n - 向量索引只存储 URI 引用和元数据\n - 内容变更不影响索引结构\n - 独立扩展存储和索引层\n\n**核心 API**:\n- `upsert()`:插入或更新向量\n- `delete()`:删除向量\n- `search()`:向量相似度搜索"}
{"question": "配置文件 `ov.conf` 的必填项有哪些?如何配置不同的 VLM 后端(OpenAI、Volcengine 等)?", "files": ["OpenViking/docs/en/guides/01-configuration.md:1-150"], "answer": "配置文件 `ov.conf` 包含 embedding、vlm、rerank、storage 等配置项。\n\n**必填配置项**:\n\n```json\n{\n \"embedding\": {\n \"dense\": {\n \"provider\": \"volcengine\", // 必填:volcengine/openai/vikingdb\n \"api_key\": \"your-api-key\", // 必填\n \"model\": \"doubao-embedding-vision-251215\",\n \"dimension\": 1024\n }\n },\n \"vlm\": {\n \"provider\": \"volcengine\", // 必填\n \"api_key\": \"your-api-key\", // 必填\n \"model\": \"doubao-seed-2-0-pro-260215\"\n }\n}\n```\n\n**VLM 后端配置**:\n\n1. **Volcengine(豆包模型)**:\n```json\n{\n \"vlm\": {\n \"api_base\": \"https://ark.cn-beijing.volces.com/api/v3\",\n \"api_key\": \"your-volcengine-api-key\",\n \"provider\": \"volcengine\",\n \"model\": \"doubao-seed-2-0-pro-260215\"\n }\n}\n```\n\n2. **OpenAI**:\n```json\n{\n \"vlm\": {\n \"api_base\": \"https://api.openai.com/v1\",\n \"api_key\": \"your-openai-api-key\",\n \"provider\": \"openai\",\n \"model\": \"gpt-4-vision-preview\"\n }\n}\n```\n\n**Embedding 配置**:\n\n| 参数 | 说明 |\n|------|------|\n| `provider` | volcengine/openai/vikingdb |\n| `api_key` | API 密钥 |\n| `model` | 模型名称 |\n| `dimension` | 向量维度 |\n| `input` | 输入类型:text/multimodal |\n\n**可选配置**:\n- `rerank`:重排序模型配置\n- `storage`:存储后端配置"}
{"question": "`HierarchicalRetriever` 的检索流程是怎样的?如何实现从 L0 到 L2 的层级穿透检索?", "files": ["OpenViking/openviking/retrieve/hierarchical_retriever.py"], "answer": "HierarchicalRetriever 实现目录递归检索和层级穿透。\n\n**检索流程**:\n\n1. **初始化**:\n```python\nclass HierarchicalRetriever:\n MAX_CONVERGENCE_ROUNDS = 3 # 收敛轮次\n SCORE_PROPAGATION_ALPHA = 0.5 # 分数传播系数\n DIRECTORY_DOMINANCE_RATIO = 1.2 # 目录分数阈值\n GLOBAL_SEARCH_TOPK = 3 # 全局检索数量\n```\n\n2. **检索模式**:\n - **THINKING**:深度思考模式\n - **QUICK**:快速检索模式\n\n3. **核心方法**:\n```python\nasync def retrieve(\n self,\n query: TypedQuery,\n limit: int = 5,\n mode: RetrieverMode = RetrieverMode.THINKING,\n score_threshold: Optional[float] = None,\n metadata_filter: Optional[Dict[str, Any]] = None,\n) -> QueryResult:\n```\n\n**层级穿透机制**:\n\n1. **L0 检索**:\n - 向量相似度搜索 `.abstract.md` 内容\n - 快速过滤不相关内容\n\n2. **L1 确认**:\n - 读取 `.overview.md` 进行重排序\n - 确认内容相关性\n\n3. **L2 加载**:\n - 按需读取完整内容\n - 仅在确认需要时加载\n\n**关键特性**:\n- 分数传播:目录分数向子节点传播\n- 目录优势:目录分数需超过最大子节点分数"}
{"question": "语义处理队列的工作机制是什么?如何监控和调试异步处理状态?", "files": ["OpenViking/docs/en/concepts/01-architecture.md", "OpenViking/openviking/service/resource_service.py:1-80"], "answer": "语义处理队列通过 SemanticQueue 异步生成 L0/L1 内容。\n\n**工作机制**:\n\n1. **处理流水线**:\n```\nInput → Parser → TreeBuilder → AGFS → SemanticQueue → Vector Index\n```\n\n2. **队列处理**:\n - TreeBuilder 将文件移动到 AGFS 后入队\n - SemanticQueue 异步处理队列项\n - 自底向上生成 L0/L1\n\n3. **异步处理优势**:\n - 不阻塞资源添加操作\n - 支持大规模文档处理\n - LLM 调用并行化\n\n**监控和调试**:\n\n1. **等待处理完成**:\n```python\nresult = client.add_resource(\"./docs\", wait=False)\nclient.wait_processed() # 等待队列处理完成\n```\n\n2. **超时控制**:\n```python\nresult = client.add_resource(\n \"./docs\",\n wait=True,\n timeout=300 # 超时时间(秒)\n)\n```\n\n3. **DebugService**:\n - 提供 ObserverService 用于调试\n - 可视化检索轨迹\n\n4. **日志监控**:\n - 通过 logger 获取处理状态\n - 监控队列长度和处理延迟\n\n**Service 层支持**:\n- ResourceService 管理 add_resource 操作\n- wait_processed() 方法等待语义处理完成"}
-{"question": "如何通过代码动态创建和管理 Session?Session 与 Memory 的关系是什么?", "files": ["OpenViking/docs/en/concepts/08-session.md", "OpenViking/openviking/session/compressor_v2.py"], "answer": "Session 通过 client API 动态创建,commit 后自动提取 Memory。\n\n**Session 创建和管理**:\n\n1. **创建 Session**:\n```python\n# 创建新会话\nsession = client.session(session_id=\"chat_001\")\n\n# 或使用 create_session\nresult = client.create_session()\n```\n\n2. **添加消息**:\n```python\nsession.add_message(\n \"user\",\n [TextPart(\"How to configure embedding?\")]\n)\n\nsession.add_message(\n \"assistant\",\n [\n TextPart(\"Here's how...\"),\n ContextPart(uri=\"viking://user/memories/profile.md\"),\n ]\n)\n```\n\n3. **记录使用**:\n```python\nsession.used(contexts=[\"viking://user/memories/profile.md\"])\nsession.used(skill={\n \"uri\": \"viking://user/skills/code-search\",\n \"input\": \"search config\",\n \"output\": \"found 3 files\",\n \"success\": True\n})\n```\n\n4. **提交会话**:\n```python\nresult = session.commit()\n# {\"status\": \"committed\", \"memories_extracted\": 5}\n```\n\n**Session 与 Memory 的关系**:\n\n1. **Memory 来源**:\n - Memory 从 Session 消息中提取\n - SessionCompressorV2 在 commit 时触发\n\n2. **提取流程**:\n - 格式化会话消息\n - 根据当前记忆策略调用 LLM 提取已启用的记忆类型\n - 写入当前用户或相关 Peer 的记忆目录并索引\n\n3. **内置记忆类型与默认位置**:\n - profile → `user/memories/profile.md`\n - preferences → `user/memories/preferences/`\n - entities → `user/memories/entities/`\n - events → `user/memories/events/`\n - identity → `user/memories/identity.md`\n - soul → `user/memories/soul.md`\n - cases → `user/memories/cases/`\n - trajectories → `user/memories/trajectories/`\n - experiences → `user/memories/experiences/`\n - tools → `user/memories/tools/`\n - skills → `user/memories/skills/`\n\n这些 `user/...` 短路径会按当前身份解析为 `viking://user/{user_id}/...`,应用也可以通过自定义模板扩展或调整记忆类型。"}
+{"question": "如何通过代码动态创建和管理 Session?Session 与 Memory 的关系是什么?", "files": ["OpenViking/docs/en/concepts/08-session.md", "OpenViking/openviking/session/compressor_v2.py"], "answer": "Session 通过 client API 动态创建,commit 后自动提取 Memory。\n\n**Session 创建和管理**:\n\n1. **创建 Session**:\n```python\n# 创建新会话\nsession = client.session(session_id=\"chat_001\")\n\n# 或使用 create_session\nresult = client.create_session()\n```\n\n2. **添加消息**:\n```python\nsession.add_message(\n \"user\",\n [TextPart(\"How to configure embedding?\")]\n)\n\nsession.add_message(\n \"assistant\",\n [\n TextPart(\"Here's how...\"),\n ContextPart(uri=\"viking://~/memories/profile.md\"),\n ]\n)\n```\n\n3. **记录使用**:\n```python\nsession.used(contexts=[\"viking://~/memories/profile.md\"])\nsession.used(skill={\n \"uri\": \"viking://~/skills/code-search\",\n \"input\": \"search config\",\n \"output\": \"found 3 files\",\n \"success\": True\n})\n```\n\n4. **提交会话**:\n```python\nresult = session.commit()\n# {\"status\": \"committed\", \"memories_extracted\": 5}\n```\n\n**Session 与 Memory 的关系**:\n\n1. **Memory 来源**:\n - Memory 从 Session 消息中提取\n - SessionCompressorV2 在 commit 时触发\n\n2. **提取流程**:\n - 格式化会话消息\n - 根据当前记忆策略调用 LLM 提取已启用的记忆类型\n - 写入当前用户或相关 Peer 的记忆目录并索引\n\n3. **内置记忆类型与默认位置**:\n - profile → `user/memories/profile.md`\n - preferences → `user/memories/preferences/`\n - entities → `user/memories/entities/`\n - events → `user/memories/events/`\n - identity → `user/memories/identity.md`\n - soul → `user/memories/soul.md`\n - cases → `user/memories/cases/`\n - trajectories → `user/memories/trajectories/`\n - experiences → `user/memories/experiences/`\n - tools → `user/memories/tools/`\n - skills → `user/memories/skills/`\n\n这些 `user/...` 短路径会按当前身份解析为 `viking://user/{user_id}/...`,应用也可以通过自定义模板扩展或调整记忆类型。"}
{"question": "OpenViking Server 模式与本地模式的区别是什么?如何选择部署方式?", "files": ["OpenViking/openviking/server/bootstrap.py:1-61", "OpenViking/docs/en/concepts/01-architecture.md"], "answer": "Server 模式提供 HTTP API,本地模式直接嵌入应用。\n\n**模式对比**:\n\n| 维度 | 本地模式 | Server 模式 |\n|------|----------|-------------|\n| 访问方式 | Python SDK | HTTP API |\n| 部署复杂度 | 简单 | 需启动服务 |\n| 多客户端 | 不支持 | 支持 |\n| 资源共享 | 单进程 | 多进程共享 |\n| 适用场景 | 单机应用 | 生产环境 |\n\n**Server 模式启动**:\n\n1. **命令行启动**:\n```bash\nopenviking-server --host 0.0.0.0 --port 1933 --config ./ov.conf\n```\n\n2. **参数说明**:\n- `--host`:绑定地址\n- `--port`:端口号\n- `--config`:配置文件路径\n\n3. **HTTP API 示例**:\n```bash\ncurl -X POST http://localhost:1933/api/v1/resources \\\n -H \"Content-Type: application/json\" \\\n -H \"X-API-Key: your-key\" \\\n -d '{\"path\": \"./documents/guide.md\"}'\n```\n\n**部署方式选择**:\n\n1. **选择本地模式**:\n - 单机应用开发\n - 快速原型验证\n - 无需多客户端访问\n\n2. **选择 Server 模式**:\n - 生产环境部署\n - 多客户端/多服务访问\n - 需要集中式上下文管理\n - 微服务架构集成\n\n**Service 层复用**:\n两种模式共享 Service 层逻辑,支持 HTTP Server 和 CLI 复用。"}
{"question": "eval 模块的 RAGAS 集成是如何实现的?如何自定义评测指标?", "files": ["OpenViking/openviking/eval/ragas.py", "OpenViking/openviking/eval/base.py:1-60"], "answer": "eval 模块通过 RagasEvaluator 适配器集成 RAGAS,支持自定义评测指标。\n\n**RAGAS 集成实现**:\n\n1. **RagasEvaluator 类**:\n```python\nclass RagasEvaluator(BaseEvaluator):\n def __init__(self, metrics=None, llm=None, embeddings=None):\n from ragas.metrics import (\n answer_relevance,\n context_precision,\n context_recall,\n faithfulness,\n )\n self.metrics = metrics or [\n faithfulness,\n answer_relevance,\n context_precision,\n context_recall,\n ]\n```\n\n2. **评测流程**:\n```python\nasync def evaluate_dataset(self, dataset: EvalDataset) -> SummaryResult:\n # 转换为 RAGAS 数据集格式\n data = {\n \"question\": [s.query for s in dataset.samples],\n \"contexts\": [s.context for s in dataset.samples],\n \"answer\": [s.response for s in dataset.samples],\n \"ground_truth\": [s.ground_truth for s in dataset.samples],\n }\n \n # 调用 RAGAS evaluate\n result = evaluate(data, metrics=self.metrics)\n```\n\n**自定义评测指标**:\n\n1. **继承 BaseEvaluator**:\n```python\nclass MyEvaluator(BaseEvaluator):\n async def evaluate_sample(self, sample: EvalSample) -> EvalResult:\n # 实现自定义评测逻辑\n scores = {\"my_metric\": 0.85}\n return EvalResult(sample=sample, scores=scores)\n```\n\n2. **自定义 RAGAS 指标**:\n```python\nfrom ragas import evaluate\nfrom ragas.metrics import Metric\n\nclass MyMetric(Metric):\n name = \"my_metric\"\n # 实现指标计算\n\nevaluator = RagasEvaluator(metrics=[MyMetric()])\n```\n\n3. **评测结果结构**:\n```python\nclass SummaryResult(BaseModel):\n dataset_name: str\n sample_count: int\n mean_scores: Dict[str, float] # 平均分数\n results: List[EvalResult] # 每个样本结果\n```"}
diff --git a/openviking/server/config.py b/openviking/server/config.py
index 2328ebc94..6b46ca94b 100644
--- a/openviking/server/config.py
+++ b/openviking/server/config.py
@@ -39,6 +39,33 @@ def _normalize_config_uri(value: Optional[str], field_name: str) -> Optional[str
return uri
+def _rewrite_legacy_current_user_uri(uri: str, field_name: str) -> str:
+ """Rewrite legacy uid-less current-user spellings to the ``~`` home alias.
+
+ ``viking://user/resources[/...]`` and ``viking://user/skills`` are no longer
+ expanded at request boundaries, but stored configurations (ov.conf
+ ``user_config_defaults.add_targets``, persisted ``user_config.json``, old
+ PATCH bodies) may still carry them. Their intent was unambiguous, so
+ normalize them here instead of breaking existing deployments.
+ """
+ from openviking.core.namespace import uri_parts
+
+ try:
+ parts = uri_parts(uri.rstrip("/"))
+ except ValueError:
+ return uri
+ if parts[:2] not in (["user", "resources"], ["user", "skills"]):
+ return uri
+ rewritten = f"viking://~/{'/'.join(parts[1:])}"
+ logger.info(
+ "Rewrote legacy current-user %s %r to %r; use the viking://~ home alias instead.",
+ field_name,
+ uri,
+ rewritten,
+ )
+ return rewritten
+
+
class AddTargetsConfig(BaseModel):
"""Add targets for resource and skill writes."""
@@ -55,17 +82,26 @@ class AddTargetsConfig(BaseModel):
return None
from openviking.core.namespace import classify_uri, uri_parts
from openviking.core.uri_validation import validate_viking_uri
+
+ uri = _rewrite_legacy_current_user_uri(uri, "resource_uri")
validate_viking_uri(uri, field_name="resource_uri")
normalized = uri.rstrip("/")
parts = uri_parts(normalized)
classification = classify_uri(normalized)
- if parts[:1] == ["resources"] or parts[:2] == ["user", "resources"] or (
- parts[:1] == ["user"]
- and classification.context_type == "resource"
- and classification.content_index is not None
+ if (
+ parts[:1] == ["resources"]
+ or parts[:2] == ["~", "resources"]
+ or (
+ parts[:1] == ["user"]
+ and classification.context_type == "resource"
+ and classification.content_index is not None
+ )
):
return normalized
- raise ValueError("resource_uri must be a resource directory URI")
+ raise ValueError(
+ "resource_uri must be a resource directory URI: viking://resources/..., "
+ "viking://~/resources[/...], or viking://user/{user_id}/resources[/...]"
+ )
@field_validator("skill_uri")
@classmethod
@@ -76,15 +112,16 @@ class AddTargetsConfig(BaseModel):
from openviking.core.namespace import uri_parts
from openviking.core.uri_validation import validate_viking_uri
+ uri = _rewrite_legacy_current_user_uri(uri, "skill_uri")
validate_viking_uri(uri, field_name="skill_uri")
normalized = uri.rstrip("/")
parts = uri_parts(normalized)
- if normalized in {"viking://user/skills", "viking://agent/skills"} or (
+ if parts in (["~", "skills"], ["agent", "skills"]) or (
len(parts) == 3 and parts[0] == "user" and parts[2] == "skills"
):
return normalized
raise ValueError(
- "skill_uri must be viking://user/skills, viking://user/{user_id}/skills, "
+ "skill_uri must be viking://~/skills, viking://user/{user_id}/skills, "
"or viking://agent/skills"
)
diff --git a/openviking/server/mcp_endpoint.py b/openviking/server/mcp_endpoint.py
index ed120ddfb..f9415d0cf 100644
--- a/openviking/server/mcp_endpoint.py
+++ b/openviking/server/mcp_endpoint.py
@@ -91,7 +91,7 @@ def _get_ctx() -> RequestContext:
def _resolve_mcp_workspace_uri(uri: str, ctx: RequestContext) -> str:
- """Resolve MCP's current-user workspace dialect at its request boundary."""
+ """Resolve MCP workspace URIs, expanding the viking://~ home alias, at its boundary."""
return validate_request_viking_uri(resolve_path_variables(uri), ctx)
@@ -325,7 +325,7 @@ async def search(
"in mode='context'"
)
# Resolve exclusions with the same strictness as the REST search router,
- # so alias/shorthand URIs match the canonical URIs they are compared against.
+ # so alias URIs match the canonical URIs they are compared against.
resolved_exclude_uris = [
_resolve_mcp_workspace_uri(exclude_uri, ctx) for exclude_uri in (exclude_uris or ())
]
@@ -561,7 +561,7 @@ async def write(
- Any new file (whether created by "replace" or "create") must end in one of: .md .txt .json .yaml .yml .toml .py .js .ts
- mode="append": append to the end of an existing file; fails if the file does not exist.
- Writable scopes: viking://resources/, viking://user/{user_id}/, viking://agent/. Documented current-user roots such as viking://user/resources are expanded at this MCP boundary. The managed user subtrees skills/, peers/, privacy/ and sessions/ are read-only. After a write, semantic search indexes refresh in the background; pass wait=true to block until search reflects the change."""
+ Writable scopes: viking://resources/, viking://user/{user_id}/, viking://agent/. The viking://~ home alias expands to the caller's user root. The managed user subtrees skills/, peers/, privacy/ and sessions/ are read-only. After a write, semantic search indexes refresh in the background; pass wait=true to block until search reflects the change."""
service = get_service()
ctx = _get_ctx()
uri = _resolve_mcp_workspace_uri(uri, ctx)
diff --git a/openviking/server/openviking_assets.py b/openviking/server/openviking_assets.py
index 0fdba11be..43c959708 100644
--- a/openviking/server/openviking_assets.py
+++ b/openviking/server/openviking_assets.py
@@ -162,8 +162,8 @@ def _normalize_asset_target_uri(
if ctx is not None:
# Use the same request-boundary URI, namespace-shape and access checks as
- # add_resource itself. In particular, this expands current-user
- # shorthand before the plan reaches the CLI and its local State file.
+ # add_resource itself. In particular, this expands the viking://~ home
+ # alias before the plan reaches the CLI and its local State file.
return validate_content_target_uri(target, ctx, kind="resource", field_name="to")
# Direct resolver callers do not always have a request identity. Preserve
diff --git a/openviking/storage/viking_fs/_access.py b/openviking/storage/viking_fs/_access.py
index 15d50d6e2..05b0f130e 100644
--- a/openviking/storage/viking_fs/_access.py
+++ b/openviking/storage/viking_fs/_access.py
@@ -204,8 +204,8 @@ class _AccessMixin:
)
if parts == ["user"]:
raise PermissionDeniedError(
- "Deleting viking://user is not supported; use an explicit user namespace "
- "or current-user content path instead.",
+ "Deleting viking://user is not supported; use viking://~/... or an "
+ "explicit viking://user/{user_id}/... path instead.",
resource=normalized_uri,
)
if parts == ["agent"]:
@@ -223,8 +223,8 @@ class _AccessMixin:
parts = [p for p in normalized_uri[len("viking://") :].strip("/").split("/") if p]
if parts == ["user"]:
raise PermissionDeniedError(
- "Writing viking://user is not supported; use an explicit user namespace "
- "or current-user content path instead.",
+ "Writing viking://user is not supported; use viking://~/... or an "
+ "explicit viking://user/{user_id}/... path instead.",
resource=normalized_uri,
)
if parts and parts[0] == "session":
diff --git a/openviking/usage_reporter/extractors.py b/openviking/usage_reporter/extractors.py
index 75b842b30..085b454f4 100644
--- a/openviking/usage_reporter/extractors.py
+++ b/openviking/usage_reporter/extractors.py
@@ -46,7 +46,14 @@ _OPENVIKING_SEARCH_SIMPLE_ROW_RE = re.compile(
r"^\s*\d+\s+(?:memory|resource|skill)\s+(viking://\S+)\s*$"
)
_LIST_FILE_RE = re.compile(r"^\s*\[file\]\s+(.+?)\s*$")
+# Historical transcripts recorded the removed uid-less shorthand; newer ones use
+# the viking://~ home alias. Both are canonicalized to the caller's user root.
_USER_MEMORY_SHORTHAND_PREFIX = "viking://user/memories/"
+_USER_MEMORY_HOME_ALIAS_PREFIX = "viking://~/memories/"
+_USER_MEMORY_RELATIVE_PREFIXES = (
+ _USER_MEMORY_SHORTHAND_PREFIX,
+ _USER_MEMORY_HOME_ALIAS_PREFIX,
+)
class UsageExtractor(Protocol):
@@ -148,9 +155,10 @@ def _unique_uris(uris: Iterable[str], context: UsageContext) -> list[str]:
def _canonicalize_usage_uri(uri: str, context: UsageContext) -> str:
normalized = uri.strip()
- if normalized.startswith(_USER_MEMORY_SHORTHAND_PREFIX):
- relative = normalized.removeprefix(_USER_MEMORY_SHORTHAND_PREFIX)
- return f"viking://user/{context.user_id}/memories/{relative}"
+ for prefix in _USER_MEMORY_RELATIVE_PREFIXES:
+ if normalized.startswith(prefix):
+ relative = normalized.removeprefix(prefix)
+ return f"viking://user/{context.user_id}/memories/{relative}"
return normalized
@@ -209,7 +217,8 @@ def _read_failed_in_text(uri: str, texts: Iterable[str], context: UsageContext)
aliases = [uri]
canonical_prefix = f"viking://user/{context.user_id}/memories/"
if uri.startswith(canonical_prefix):
- aliases.append(f"{_USER_MEMORY_SHORTHAND_PREFIX}{uri.removeprefix(canonical_prefix)}")
+ relative = uri.removeprefix(canonical_prefix)
+ aliases.extend(f"{prefix}{relative}" for prefix in _USER_MEMORY_RELATIVE_PREFIXES)
for text in texts:
for alias in aliases:
if f"(nothing found at {alias})" in text:
diff --git a/openviking_cli/utils/uri.py b/openviking_cli/utils/uri.py
index f7d43bb5c..3421e958d 100644
--- a/openviking_cli/utils/uri.py
+++ b/openviking_cli/utils/uri.py
@@ -20,8 +20,7 @@ class VikingURI:
Scopes:
- resources: Independent resource scope (viking://resources/{project}/...)
- user: Explicit user scope (viking://user/{user_id}/...), including sessions under
- viking://user/{user_id}/sessions/{session_id}. Authenticated API boundaries may
- accept documented current-user shorthands and expand them before internal use.
+ viking://user/{user_id}/sessions/{session_id}.
- session: Legacy alias for user sessions (viking://session/{session_id}/...)
- agent: Agent capabilities scope (viking://agent/skills/..., viking://agent/endpoints/...)
- queue: Queue scope (viking://queue/...)
diff --git a/sdk/go/README.md b/sdk/go/README.md
index c8fa8b5df..4eacf3e73 100644
--- a/sdk/go/README.md
+++ b/sdk/go/README.md
@@ -170,8 +170,8 @@ _, err := client.AdminRegisterUserWithOptions(ctx, "acme", "alice", "user", &ope
Seed: &seed,
UserConfig: map[string]any{
"add_targets": map[string]any{
- "resource_uri": "viking://user/resources/project-a",
- "skill_uri": "viking://user/skills",
+ "resource_uri": "viking://~/resources/project-a",
+ "skill_uri": "viking://~/skills",
},
},
})
diff --git a/sdk/go/README_CN.md b/sdk/go/README_CN.md
index 7b6a4b228..04bc19f2a 100644
--- a/sdk/go/README_CN.md
+++ b/sdk/go/README_CN.md
@@ -96,8 +96,8 @@ _, err := client.AdminRegisterUserWithOptions(ctx, "acme", "alice", "user", &ope
Seed: &seed,
UserConfig: map[string]any{
"add_targets": map[string]any{
- "resource_uri": "viking://user/resources/project-a",
- "skill_uri": "viking://user/skills",
+ "resource_uri": "viking://~/resources/project-a",
+ "skill_uri": "viking://~/skills",
},
},
})
diff --git a/sdk/go/examples/basic_usage/main.go b/sdk/go/examples/basic_usage/main.go
index aa4e1db7a..116d1b431 100644
--- a/sdk/go/examples/basic_usage/main.go
+++ b/sdk/go/examples/basic_usage/main.go
@@ -319,7 +319,7 @@ func main() {
fmt.Printf(" recent session commit tasks=%d\n", len(tasks))
memoryResults, err := client.Find(ctx, memoryMarker, &openviking.FindOptions{
- TargetURI: "viking://user/memories",
+ TargetURI: "viking://~/memories",
Limit: 5,
ContextType: []string{"memory"},
})
@@ -346,7 +346,7 @@ func main() {
defer peerClient.CloseIdleConnections()
peerMemoryResults, err := peerClient.Find(ctx, peerMarker, &openviking.FindOptions{
- TargetURI: "viking://user/memories",
+ TargetURI: "viking://~/memories",
Limit: 5,
ContextType: []string{"memory"},
})
diff --git a/sdk/python/README.md b/sdk/python/README.md
index d7eda9b34..7609046aa 100644
--- a/sdk/python/README.md
+++ b/sdk/python/README.md
@@ -300,8 +300,8 @@ root_client.admin_register_user(
seed="alice-seed",
user_config={
"add_targets": {
- "resource_uri": "viking://user/resources/project-a",
- "skill_uri": "viking://user/skills",
+ "resource_uri": "viking://~/resources/project-a",
+ "skill_uri": "viking://~/skills",
}
},
)
diff --git a/sdk/python/README_CN.md b/sdk/python/README_CN.md
index 28d856f8c..59beb4cdf 100644
--- a/sdk/python/README_CN.md
+++ b/sdk/python/README_CN.md
@@ -296,8 +296,8 @@ root_client.admin_register_user(
seed="alice-seed",
user_config={
"add_targets": {
- "resource_uri": "viking://user/resources/project-a",
- "skill_uri": "viking://user/skills",
+ "resource_uri": "viking://~/resources/project-a",
+ "skill_uri": "viking://~/skills",
}
},
)
diff --git a/tests/api_test/sessions/slow/test_session_message_format.py b/tests/api_test/sessions/slow/test_session_message_format.py
index cc4a60ebf..9d05c42e0 100644
--- a/tests/api_test/sessions/slow/test_session_message_format.py
+++ b/tests/api_test/sessions/slow/test_session_message_format.py
@@ -257,7 +257,7 @@ class TestSessionMessageFormat:
used_resp = api_client.session_used(
session_id,
- skill={"name": "test-skill", "uri": "viking://user/skills/test"},
+ skill={"name": "test-skill", "uri": "viking://~/skills/test"},
)
assert used_resp.status_code == 200
result = used_resp.json().get("result", {})
diff --git a/tests/api_test/sessions/test_session_commit_used_context.py b/tests/api_test/sessions/test_session_commit_used_context.py
index c4ebc6d83..4e3da1c6c 100644
--- a/tests/api_test/sessions/test_session_commit_used_context.py
+++ b/tests/api_test/sessions/test_session_commit_used_context.py
@@ -110,9 +110,9 @@ class TestSessionCommitUsedContext:
contexts=[
"viking://resources/context1",
"viking://resources/context2",
- "viking://user/skills/skill1",
+ "viking://~/skills/skill1",
],
- skill={"name": "multi-context-skill", "uri": "viking://user/skills/multi"},
+ skill={"name": "multi-context-skill", "uri": "viking://~/skills/multi"},
)
assert used_resp.status_code == 200
data = used_resp.json()
diff --git a/tests/integration/langchain_langgraph/live_e2e.py b/tests/integration/langchain_langgraph/live_e2e.py
index e1772209f..c5bc2366a 100644
--- a/tests/integration/langchain_langgraph/live_e2e.py
+++ b/tests/integration/langchain_langgraph/live_e2e.py
@@ -309,7 +309,7 @@ def test_true_live_langgraph_create_agent_middleware_e2e():
def test_true_live_retriever_and_langgraph_store_e2e():
_require_openviking_live_env()
client = _build_real_client()
- root_uri = f"viking://user/memories/langgraph_store_live_{uuid.uuid4().hex}"
+ root_uri = f"viking://~/memories/langgraph_store_live_{uuid.uuid4().hex}"
code = f"store_live_{uuid.uuid4().hex[:10]}"
try:
diff --git a/tests/integration/langchain_langgraph/test_runtime_actor_peer.py b/tests/integration/langchain_langgraph/test_runtime_actor_peer.py
index cb56d9186..3f209ba1b 100644
--- a/tests/integration/langchain_langgraph/test_runtime_actor_peer.py
+++ b/tests/integration/langchain_langgraph/test_runtime_actor_peer.py
@@ -44,7 +44,7 @@ class RuntimeActorPeerTrackingClient:
@pytest.mark.asyncio
async def test_real_create_agent_resolves_actor_peer_from_runtime_context():
client = RuntimeActorPeerTrackingClient(
- {"viking://user/memories/profile.md": "Runtime-scoped memory."}
+ {"viking://~/memories/profile.md": "Runtime-scoped memory."}
)
def resolve_actor_peer(_state: dict[str, Any], runtime: Any) -> str:
diff --git a/tests/server/test_add_locations.py b/tests/server/test_add_locations.py
index abd7190d2..168c73d97 100644
--- a/tests/server/test_add_locations.py
+++ b/tests/server/test_add_locations.py
@@ -41,6 +41,26 @@ def _configure_test_env(monkeypatch, tmp_path):
OpenVikingConfigSingleton.reset_instance()
+def user_role_client(app, client: httpx.AsyncClient):
+ """Client whose requests carry a USER-role identity.
+
+ The dev auth plugin resolves every request to ROOT, which deliberately skips
+ current-user alias resolution; add-location targets are a user-facing feature,
+ so these tests exercise them as a real user.
+ """
+ from openviking.server.auth import get_request_context
+ from openviking.server.identity import RequestContext, Role
+ from openviking_cli.session.user_id import UserIdentifier
+
+ app.dependency_overrides[get_request_context] = lambda: RequestContext(
+ user=UserIdentifier("default", "default"),
+ role=Role.USER,
+ )
+ yield client
+ app.dependency_overrides.pop(get_request_context, None)
+
+
async def _add_resource(client: httpx.AsyncClient, filename: str, **extra):
payload = {"temp_file_id": filename, "wait": True, **extra}
response = await client.post("/api/v1/resources", json=payload)
@@ -50,17 +70,25 @@ async def _add_resource(client: httpx.AsyncClient, filename: str, **extra):
async def test_add_locations_resource_server_default_and_precedence(
app,
- client: httpx.AsyncClient,
+ user_role_client: httpx.AsyncClient,
sample_markdown_file,
upload_temp_dir,
):
+ client = user_role_client
+ # Legacy uid-less spelling: still accepted in stored configs, normalized to
+ # the viking://~ home alias at validation time.
app.state.config.user_config_defaults = UserConfig(
add_targets=AddTargetsConfig(resource_uri="viking://user/resources")
)
+ assert (
+ app.state.config.user_config_defaults.add_targets.resource_uri == "viking://~/resources"
+ )
root_uri = await _add_resource(client, sample_markdown_file.name)
assert root_uri.startswith("viking://user/default/resources/")
+ # The one retained legacy PATCH spelling, proving the same normalization
+ # applies to old request bodies.
response = await client.patch(
"/api/v1/user-settings/add-locations",
json={"resource_uri": "viking://user/resources/project-a"},
@@ -109,7 +137,28 @@ async def test_add_locations_skill_server_default(
assert response.json()["result"]["root_uri"] == "viking://agent/skills/default-agent-skill"
+async def test_add_locations_patch_accepts_home_alias_uris(
+ app,
+ user_role_client: httpx.AsyncClient,
+ sample_markdown_file,
+ upload_temp_dir,
+):
+ client = user_role_client
+ response = await client.patch(
+ "/api/v1/user-settings/add-locations",
+ json={"resource_uri": "viking://~/resources/project-a", "skill_uri": "viking://~/skills"},
+ )
+ assert response.status_code == 200, response.text
+ effective = response.json()["result"]["effective"]
+ assert effective["resource_uri"] == "viking://user/default/resources/project-a"
+ assert effective["skill_uri"] == "viking://user/default/skills"
+
+ root_uri = await _add_resource(client, sample_markdown_file.name)
+ assert root_uri.startswith("viking://user/default/resources/project-a/")
+
+
async def test_add_locations_patch_rejects_bad_uris(client: httpx.AsyncClient):
+ # Rewritten to viking://~/skills/nested, which is still an invalid skill shape.
response = await client.patch(
"/api/v1/user-settings/add-locations",
json={"skill_uri": "viking://user/skills/nested"},
@@ -118,13 +167,84 @@ async def test_add_locations_patch_rejects_bad_uris(client: httpx.AsyncClient):
body = response.json()
assert body["status"] == "error"
assert body["error"]["code"] == "INVALID_ARGUMENT"
+ assert "skill_uri must be viking://~/skills" in body["error"]["message"]
+ # Rewritten to viking://~/skills, which is still not a resource directory.
response = await client.patch(
"/api/v1/user-settings/add-locations",
json={"resource_uri": "viking://user/skills"},
)
assert response.status_code == 400
- assert response.json()["error"]["code"] == "INVALID_ARGUMENT"
+ body = response.json()
+ assert body["error"]["code"] == "INVALID_ARGUMENT"
+ assert "resource_uri must be a resource directory URI" in body["error"]["message"]
+
+
+ ("stored", "expected"),
+ [
+ ("viking://user/resources", "viking://~/resources"),
+ ("viking://user/resources/", "viking://~/resources"),
+ ("viking://user/resources/project-a/docs", "viking://~/resources/project-a/docs"),
+ ],
+)
+def test_add_targets_normalizes_legacy_resource_uri(stored, expected):
+ assert AddTargetsConfig(resource_uri=stored).resource_uri == expected
+
+
+def test_add_targets_normalizes_legacy_skill_uri():
+ assert AddTargetsConfig(skill_uri="viking://user/skills").skill_uri == "viking://~/skills"
+
+
+ "uri",
+ [
+ "viking://~/resources",
+ "viking://~/resources/project-a",
+ "viking://resources/shared",
+ "viking://user/alice/resources/project-a",
+ ],
+)
+def test_add_targets_accepts_supported_resource_uris(uri):
+ assert AddTargetsConfig(resource_uri=uri).resource_uri == uri
+
+
+ "uri",
+ ["viking://~/skills", "viking://agent/skills", "viking://user/alice/skills"],
+)
+def test_add_targets_accepts_supported_skill_uris(uri):
+ assert AddTargetsConfig(skill_uri=uri).skill_uri == uri
+
+
+ "uri",
+ [
+ # Rewritten to viking://~/skills, which is not a resource directory.
+ "viking://user/skills",
+ "viking://user/memories",
+ "viking://~/memories",
+ "viking://agent/skills",
+ ],
+)
+def test_add_targets_rejects_invalid_resource_uris(uri):
+ with pytest.raises(ValueError, match="resource_uri must be a resource directory URI"):
+ AddTargetsConfig(resource_uri=uri)
+
+
+ "uri",
+ [
+ # Rewritten to viking://~/skills/nested, which is still an invalid shape.
+ "viking://user/skills/nested",
+ "viking://user/resources",
+ "viking://~/skills/nested",
+ "viking://resources/skills",
+ ],
+)
+def test_add_targets_rejects_invalid_skill_uris(uri):
+ with pytest.raises(ValueError, match="skill_uri must be viking://~/skills"):
+ AddTargetsConfig(skill_uri=uri)
def test_load_server_config_rejects_bad_add_locations(tmp_path):
diff --git a/tests/server/test_admin_api.py b/tests/server/test_admin_api.py
index 218eb5d63..cd8f9b064 100644
--- a/tests/server/test_admin_api.py
+++ b/tests/server/test_admin_api.py
@@ -305,6 +305,7 @@ async def test_create_user_paths_accept_initial_user_config(
json={
"account_id": acct,
"admin_user_id": "alice",
+ # Legacy uid-less spelling, normalized to the viking://~ home alias.
"user_config": {"add_targets": {"resource_uri": "viking://user/resources/admin"}},
},
headers=root_headers(),
@@ -322,7 +323,7 @@ async def test_create_user_paths_accept_initial_user_config(
json={
"user_id": "bob",
"role": "user",
- "user_config": {"add_targets": {"resource_uri": "viking://user/resources/bob"}},
+ "user_config": {"add_targets": {"resource_uri": "viking://~/resources/bob"}},
},
headers=root_headers(),
)
diff --git a/tests/server/test_admin_rebuild_api.py b/tests/server/test_admin_rebuild_api.py
index ca7557bfa..829e3da77 100644
--- a/tests/server/test_admin_rebuild_api.py
+++ b/tests/server/test_admin_rebuild_api.py
@@ -60,7 +60,7 @@ async def test_reindex_user_can_only_target_own_user_scope(monkeypatch):
monkeypatch.setattr("openviking.server.routers.content.get_service", lambda: FakeService())
own_scope = await reindex(
- body=ReindexRequest(uri="viking://user/resources", mode="vectors_only"),
+ body=ReindexRequest(uri="viking://~/resources", mode="vectors_only"),
ctx=ctx,
)
assert own_scope.status == "ok"
diff --git a/tests/server/test_api_resources.py b/tests/server/test_api_resources.py
index 346b11d6b..3a7d0278b 100644
--- a/tests/server/test_api_resources.py
+++ b/tests/server/test_api_resources.py
@@ -527,7 +527,7 @@ async def test_add_resource_with_resources_root_to_uses_child_uri(
assert body["result"]["root_uri"] == "viking://resources/tt_b"
-async def test_add_resource_with_user_resources_short_parent_initializes_root(
+async def test_add_resource_with_home_alias_resources_parent_initializes_root(
app,
client: httpx.AsyncClient,
upload_temp_dir,
@@ -546,8 +546,8 @@ async def test_add_resource_with_user_resources_short_parent_initializes_root(
"/api/v1/resources",
json={
"temp_file_id": archive_path.name,
- "parent": "viking://user/resources",
- "reason": "test user resource short parent import",
+ "parent": "viking://~/resources",
+ "reason": "test home alias resource parent import",
"wait": True,
},
)
diff --git a/tests/server/test_api_sessions.py b/tests/server/test_api_sessions.py
index f1dd8a246..b70bb5c1f 100644
--- a/tests/server/test_api_sessions.py
+++ b/tests/server/test_api_sessions.py
@@ -1259,7 +1259,7 @@ async def test_extract_session_jsonable_regression(client: httpx.AsyncClient, se
return {"uri": self.uri}
async def fake_extract(_session_id: str, _ctx):
- return [FakeMemory("viking://user/memories/mock.md")]
+ return [FakeMemory("viking://user/default/memories/mock.md")]
monkeypatch.setattr(service.sessions, "extract", fake_extract)
@@ -1270,7 +1270,7 @@ async def test_extract_session_jsonable_regression(client: httpx.AsyncClient, se
assert resp.status_code == 200
body = resp.json()
assert body["status"] == "ok"
- assert body["result"] == [{"uri": "viking://user/memories/mock.md"}]
+ assert body["result"] == [{"uri": "viking://user/default/memories/mock.md"}]
async def test_get_session_context_endpoint_returns_trimmed_latest_archive_and_messages(
diff --git a/tests/server/test_filesystem_router.py b/tests/server/test_filesystem_router.py
index 4422b5dc5..bb9c63c56 100644
--- a/tests/server/test_filesystem_router.py
+++ b/tests/server/test_filesystem_router.py
@@ -105,3 +105,28 @@ async def test_mkdir_echoes_canonical_home_alias(monkeypatch):
assert seen["uri"] == "viking://user/alice/resources/notes"
assert response.result["uri"] == "viking://user/alice/resources/notes"
+
+
+async def test_ls_user_container_lists_only_caller_space(app, client, service):
+ """`viking://user` is the container of user spaces, not a current-user shorthand."""
+ from openviking.server.auth import get_request_context
+
+ root_ctx = RequestContext(user=UserIdentifier("default", "default"), role=Role.ROOT)
+ await service.viking_fs.mkdir("viking://user/alice", exist_ok=True, ctx=root_ctx)
+ await service.viking_fs.mkdir("viking://user/bob", exist_ok=True, ctx=root_ctx)
+
+ app.dependency_overrides[get_request_context] = lambda: RequestContext(
+ user=UserIdentifier("default", "alice"), role=Role.USER
+ )
+ try:
+ response = await client.get(
+ "/api/v1/fs/ls",
+ params={"uri": "viking://user", "output": "original"},
+ )
+ finally:
+ app.dependency_overrides.pop(get_request_context, None)
+
+ assert response.status_code == 200, response.text
+ names = {entry["name"] for entry in response.json()["result"]}
+ assert names == {"alice"}
diff --git a/tests/server/test_mcp_endpoint.py b/tests/server/test_mcp_endpoint.py
index 463d4148f..22eda273e 100644
--- a/tests/server/test_mcp_endpoint.py
+++ b/tests/server/test_mcp_endpoint.py
@@ -7,6 +7,7 @@ Tests the tool functions directly by setting up the identity contextvar
and service dependency, avoiding MCP protocol complexity.
"""
+import re
from types import SimpleNamespace
from unittest.mock import AsyncMock
@@ -88,25 +89,34 @@ def test_get_ctx_raises_when_unset():
@pytest.mark.parametrize(
("uri", "expected"),
[
- ("viking://user", "viking://user/test_user"),
+ ("viking://user", "viking://user"),
("viking://user/notes.md", "viking://user/notes.md"),
(
"viking://user/project/notes.md",
"viking://user/project/notes.md",
),
- ("viking://user/resources", "viking://user/test_user/resources"),
(
"viking://user/test_user/project/notes.md",
"viking://user/test_user/project/notes.md",
),
("viking://resources/project/notes.md", "viking://resources/project/notes.md"),
+ ("viking://~/resources", "viking://user/test_user/resources"),
],
)
-def test_resolve_mcp_workspace_uri_only_expands_documented_shorthands(uri, expected):
+def test_resolve_mcp_workspace_uri_only_expands_documented_aliases(uri, expected):
user_ctx = RequestContext(DEFAULT_CTX.user, Role.USER)
assert _resolve_mcp_workspace_uri(uri, user_ctx) == expected
+ "segment", ["memories", "resources", "skills", "peers", "privacy", "sessions"]
+)
+def test_resolve_mcp_workspace_uri_rejects_reserved_user_root_shorthand(segment):
+ user_ctx = RequestContext(DEFAULT_CTX.user, Role.USER)
+ with pytest.raises(InvalidURIError, match=re.escape(f"viking://~/{segment}")):
+ _resolve_mcp_workspace_uri(f"viking://user/{segment}", user_ctx)
+
+
def test_resolve_mcp_workspace_uri_supports_dotted_current_user_id():
ctx = RequestContext(
user=UserIdentifier.the_default_user("[email protected]"),
@@ -120,6 +130,8 @@ def test_resolve_mcp_workspace_uri_supports_dotted_current_user_id():
assert _resolve_mcp_workspace_uri("viking://user/notes/todo.md", ctx) == (
"viking://user/notes/todo.md"
)
+ # DEFAULT_CTX is ROOT: root-role requests skip current-user resolution
+ # entirely, so a reserved first segment stays a literal user id.
assert _resolve_mcp_workspace_uri("viking://user/resources", DEFAULT_CTX) == (
"viking://user/resources"
)
@@ -1012,7 +1024,7 @@ async def test_cancel_watch_not_found(service):
async def test_forget_by_uri_deletes_memory(service):
ctx = DEFAULT_CTX
- uri = "viking://user/memories/test_forget.md"
+ uri = "viking://~/memories/test_forget.md"
canonical_uri = "viking://user/test_user/memories/test_forget.md"
await service.viking_fs.mkdir("viking://user/test_user/memories", ctx=ctx, exist_ok=True)
await service.viking_fs.write(canonical_uri, "test data", ctx=ctx)
@@ -1060,19 +1072,29 @@ async def test_forget_directory_with_recursive_succeeds(service):
@pytest.mark.parametrize(
- ("uri", "sentinel_uri"),
+ ("uri", "sentinel_uri", "expected_message"),
[
+ # 'viking://user' is the container of user spaces, never a deletable path.
(
"viking://user",
"viking://user/test_user/memories/forget_root_guard.md",
+ "Deleting viking://user is not supported",
+ ),
+ (
+ "viking://~",
+ "viking://user/test_user/memories/forget_home_guard.md",
+ "namespace root",
),
(
"viking://resources",
"viking://resources/forget_root_guard/sentinel.md",
+ "namespace root",
),
],
)
-async def test_forget_rejects_namespace_roots_for_non_root(service, uri, sentinel_uri):
+async def test_forget_rejects_namespace_roots_for_non_root(
+ service, uri, sentinel_uri, expected_message
+):
ctx = RequestContext(
user=UserIdentifier.the_default_user("test_user"),
role=Role.USER,
@@ -1083,7 +1105,7 @@ async def test_forget_rejects_namespace_roots_for_non_root(service, uri, sentine
token = _mcp_ctx.set(ctx)
try:
- with pytest.raises(PermissionDeniedError, match="namespace root"):
+ with pytest.raises(PermissionDeniedError, match=re.escape(expected_message)):
await forget(uri=uri, recursive=True)
finally:
_mcp_ctx.reset(token)
@@ -1236,12 +1258,15 @@ async def test_write_home_alias_uri(service):
try:
result = await write(uri="viking://~/memories/preferences/home_alias.md", content="x")
listing = await list_tool(uri="viking://~/memories/preferences")
+ read_back = await read(uris="viking://~/memories/preferences/home_alias.md")
finally:
_mcp_ctx.reset(token)
# Responses echo the expanded canonical URI, never the alias.
assert canonical in result
assert "viking://~" not in result
assert "home_alias.md" in listing
+ assert "x" in read_back
+ assert "viking://~" not in read_back
visible = await service.fs.read_visible(canonical, ctx=DEFAULT_CTX)
assert visible.strip() == "x"
@@ -1252,17 +1277,17 @@ async def test_home_alias_rejected_for_root_role(service):
await list_tool(uri="viking://~/memories")
-async def test_write_user_shorthand_uri(service):
- uri = "viking://user/memories/preferences/shorthand_write.md"
+async def test_write_home_alias_memory_uri(service):
+ uri = "viking://~/memories/preferences/home_alias_write.md"
user_ctx = RequestContext(DEFAULT_CTX.user, Role.USER)
token = _mcp_ctx.set(user_ctx)
try:
result = await write(uri=uri, content="x")
finally:
_mcp_ctx.reset(token)
- assert "shorthand_write.md" in result
+ assert "home_alias_write.md" in result
visible = await service.fs.read_visible(
- "viking://user/test_user/memories/preferences/shorthand_write.md",
+ "viking://user/test_user/memories/preferences/home_alias_write.md",
ctx=DEFAULT_CTX,
)
assert visible.strip() == "x"
diff --git a/tests/server/test_openviking_assets.py b/tests/server/test_openviking_assets.py
index f62ae17d8..fe85c8d60 100644
--- a/tests/server/test_openviking_assets.py
+++ b/tests/server/test_openviking_assets.py
@@ -480,7 +480,7 @@ async def test_resolve_endpoint_accepts_single_file_manifest(assets_client: http
assert body["result"]["catalog"] == "single-file.yaml"
-async def test_resolve_endpoint_canonicalizes_current_user_target(
+async def test_resolve_endpoint_canonicalizes_home_alias_target(
assets_client: httpx.AsyncClient,
):
manifest = """\
@@ -488,7 +488,7 @@ protocol: openviking-assets/1
catalog:
- name: private
connector: git
- to: viking://user/resources/repos/private
+ to: viking://~/resources/repos/private
params:
repo_url: https://github.com/org/private
"""
diff --git a/tests/server/test_privacy_config_service.py b/tests/server/test_privacy_config_service.py
index e4b801262..c90456c90 100644
--- a/tests/server/test_privacy_config_service.py
+++ b/tests/server/test_privacy_config_service.py
@@ -78,9 +78,9 @@ async def test_skill_read_restores_placeholder(service):
@pytest.mark.asyncio
-async def test_skill_read_restores_placeholder_with_user_shorthand(service):
+async def test_skill_read_restores_placeholder_for_agent_segment_name(service):
ctx = RequestContext(
- user=UserIdentifier.the_default_user("privacy_restore_user_shorthand"), role=Role.ROOT
+ user=UserIdentifier.the_default_user("privacy_restore_agent_segment"), role=Role.ROOT
)
await service.initialize_user_directories(ctx)
@@ -95,7 +95,7 @@ async def test_skill_read_restores_placeholder_with_user_shorthand(service):
)
restored = await service.fs.read(
- "viking://user/skills/restore-skill-agent-segment/SKILL.md",
+ f"{canonical_user_root(ctx)}/skills/restore-skill-agent-segment/SKILL.md",
ctx=ctx,
)
diff --git a/tests/unit/session/test_session_commit_resume.py b/tests/unit/session/test_session_commit_resume.py
index cdebae0f7..a58a99c65 100644
--- a/tests/unit/session/test_session_commit_resume.py
+++ b/tests/unit/session/test_session_commit_resume.py
@@ -51,7 +51,7 @@ class _MemoryVikingFS:
@pytest.mark.asyncio
async def test_resume_queued_commit_continues_phase2(monkeypatch):
- session_uri = "viking://user/sessions/session-1"
+ session_uri = "viking://user/default/sessions/session-1"
archive_uri = f"{session_uri}/history/archive_001"
archived = Message(id="archived", role="user", parts=[TextPart("old")])
retained = Message(id="retained", role="assistant", parts=[TextPart("new")])
@@ -94,7 +94,7 @@ async def test_resume_queued_commit_continues_phase2(monkeypatch):
async def test_resume_queued_commit_fails_terminally_for_unreadable_archive(
monkeypatch, archive_content
):
- session_uri = "viking://user/sessions/session-1"
+ session_uri = "viking://user/default/sessions/session-1"
archive_uri = f"{session_uri}/history/archive_001"
files = {}
if archive_content is not None:
@@ -126,7 +126,7 @@ async def test_resume_queued_commit_fails_terminally_for_unreadable_archive(
@pytest.mark.asyncio
async def test_session_context_skips_pending_archive_with_missing_messages(monkeypatch):
- session_uri = "viking://user/sessions/session-1"
+ session_uri = "viking://user/default/sessions/session-1"
archive_uri = f"{session_uri}/history/archive_001"
session = Session(
viking_fs=_MemoryVikingFS({}),
@@ -150,7 +150,7 @@ async def test_session_context_skips_pending_archive_with_missing_messages(monke
@pytest.mark.asyncio
async def test_resume_queued_commit_uses_agent_evolution_archive_snapshot(monkeypatch):
- session_uri = "viking://user/sessions/session-1"
+ session_uri = "viking://user/default/sessions/session-1"
archive_uri = f"{session_uri}/history/archive_001"
archived = Message(id="archived", role="user", parts=[TextPart("old")])
files = {
@@ -202,8 +202,8 @@ def test_session_commit_message_ignores_unknown_fields():
{
"task_id": "task-1",
"session_id": "session-1",
- "session_uri": "viking://user/sessions/session-1",
- "archive_uri": "viking://user/sessions/session-1/history/archive_001",
+ "session_uri": "viking://user/default/sessions/session-1",
+ "archive_uri": "viking://user/default/sessions/session-1/history/archive_001",
"user": {"account_id": "default", "user_id": "default"},
"actor_peer_id": "visitor-a",
}
diff --git a/tests/unit/test_langchain_async_integration.py b/tests/unit/test_langchain_async_integration.py
index f71988962..c444b935b 100644
--- a/tests/unit/test_langchain_async_integration.py
+++ b/tests/unit/test_langchain_async_integration.py
@@ -1290,12 +1290,12 @@ async def test_async_history_does_not_create_session_on_non_not_found_error():
@pytest.mark.asyncio
async def test_async_middleware_injects_and_captures_context():
backing = InMemoryOpenVikingClient(
- {"viking://user/memories/profile.md": "Async middleware prefers teal."}
+ {"viking://~/memories/profile.md": "Async middleware prefers teal."}
)
client = AsyncInMemoryOpenVikingClient(backing)
middleware = OpenVikingContextMiddleware(
async_client=client,
- target_uri="viking://user/memories",
+ target_uri="viking://~/memories",
session_id_resolver=lambda _state, _runtime: "async-middleware",
)
captured_request: dict[str, Any] = {}
@@ -1334,12 +1334,12 @@ async def test_async_middleware_injects_and_captures_context():
@pytest.mark.asyncio
async def test_async_middleware_clears_pending_context_when_model_call_is_cancelled():
backing = InMemoryOpenVikingClient(
- {"viking://user/memories/profile.md": "Cancelled context must not be reused."}
+ {"viking://~/memories/profile.md": "Cancelled context must not be reused."}
)
client = AsyncInMemoryOpenVikingClient(backing)
middleware = OpenVikingContextMiddleware(
async_client=client,
- target_uri="viking://user/memories",
+ target_uri="viking://~/memories",
session_id_resolver=lambda _state, _runtime: "async-cancelled-middleware",
)
handler_started = asyncio.Event()
diff --git a/tests/unit/test_langchain_integration.py b/tests/unit/test_langchain_integration.py
index 0e20fdcb4..424b70bb1 100644
--- a/tests/unit/test_langchain_integration.py
+++ b/tests/unit/test_langchain_integration.py
@@ -74,13 +74,13 @@ def _schema_has_description(schema: dict[str, Any]) -> bool:
def test_retriever_returns_langchain_documents():
client = InMemoryOpenVikingClient(
{
- "viking://user/memories/preferences.md": "The user prefers azure deploys.",
+ "viking://~/memories/preferences.md": "The user prefers azure deploys.",
"viking://resources/runbooks/release.md": "Release notes mention LangChain.",
}
)
retriever = OpenVikingRetriever(
client=client,
- target_uri=["viking://user/memories", "viking://resources"],
+ target_uri=["viking://~/memories", "viking://resources"],
limit=3,
)
@@ -88,18 +88,18 @@ def test_retriever_returns_langchain_documents():
assert {doc.metadata["openviking_uri"] for doc in docs} == {
"viking://resources/runbooks/release.md",
- "viking://user/memories/preferences.md",
+ "viking://~/memories/preferences.md",
}
assert all(doc.page_content for doc in docs)
def test_retriever_keeps_peer_id_out_of_retrieval():
client = InMemoryOpenVikingClient(
- {"viking://user/memories/preferences.md": "The peer prefers azure deploys."}
+ {"viking://~/memories/preferences.md": "The peer prefers azure deploys."}
)
retriever = OpenVikingRetriever(
client=client,
- target_uri="viking://user/memories",
+ target_uri="viking://~/memories",
actor_peer_id="peer-1",
)
@@ -125,7 +125,7 @@ def test_retriever_passes_tags_to_retrieval():
def test_create_openviking_tools_exposes_common_viking_primitives():
client = InMemoryOpenVikingClient(
- {"viking://user/memories/profile.md": "The user likes LangGraph agents."}
+ {"viking://~/memories/profile.md": "The user likes LangGraph agents."}
)
tools = create_openviking_tools(client=client, profile="agent")
names = {tool.name for tool in tools}
@@ -146,9 +146,7 @@ def test_create_openviking_tools_exposes_common_viking_primitives():
assert "viking_forget" not in names
find_tool = next(tool for tool in tools if tool.name == "viking_find")
- assert "viking://user/memories/profile.md" in find_tool.invoke(
- {"query": "LangGraph", "limit": 2}
- )
+ assert "viking://~/memories/profile.md" in find_tool.invoke({"query": "LangGraph", "limit": 2})
store_tool = next(tool for tool in tools if tool.name == "viking_store")
assert "explicit durable memories" in store_tool.description
@@ -179,7 +177,7 @@ def test_create_openviking_tools_exposes_common_viking_primitives():
def test_create_openviking_tools_uses_peer_id_only_for_message_attribution():
client = InMemoryOpenVikingClient(
- {"viking://user/memories/profile.md": "The peer likes LangGraph agents."}
+ {"viking://~/memories/profile.md": "The peer likes LangGraph agents."}
)
tools = {
tool.name: tool for tool in create_openviking_tools(client=client, peer_id="peer-tools")
@@ -751,11 +749,11 @@ def test_session_context_assembler_uses_archive_active_messages_and_recall():
def test_session_context_assembler_keeps_peer_id_out_of_recall():
client = InMemoryOpenVikingClient(
- {"viking://user/memories/peer.md": "Peer memory mentions azure."}
+ {"viking://~/memories/peer.md": "Peer memory mentions azure."}
)
assembler = OpenVikingSessionContextAssembler(
client=client,
- target_uri="viking://user/memories",
+ target_uri="viking://~/memories",
actor_peer_id="peer-assembler",
)
@@ -1193,11 +1191,11 @@ def test_langgraph_store_batch_rejects_ttl_writes():
@pytest.mark.parametrize(
- ("root_uri", "shorthand_prefix", "canonical_prefix"),
+ ("root_uri", "alias_prefix", "canonical_prefix"),
[
(
- "viking://user/memories/langgraph_store",
- "viking://user/memories",
+ "viking://~/memories/langgraph_store",
+ "viking://~/memories",
"viking://user/default/memories",
),
],
@@ -1205,15 +1203,15 @@ def test_langgraph_store_batch_rejects_ttl_writes():
"user-memory",
],
)
-def test_langgraph_store_accepts_canonical_result_uris_for_shorthand_root(
+def test_langgraph_store_accepts_canonical_result_uris_for_home_alias_root(
root_uri,
- shorthand_prefix,
+ alias_prefix,
canonical_prefix,
):
class CanonicalizingClient(InMemoryOpenVikingClient):
def _canonicalize(self, value):
if isinstance(value, str):
- return value.replace(f"{shorthand_prefix}/", f"{canonical_prefix}/", 1)
+ return value.replace(f"{alias_prefix}/", f"{canonical_prefix}/", 1)
if isinstance(value, list):
return [self._canonicalize(item) for item in value]
return value
@@ -1248,7 +1246,7 @@ def test_langgraph_store_accepts_canonical_result_uris_for_shorthand_root(
def test_langgraph_store_ignores_unrelated_canonical_result_uris():
store = OpenVikingStore(
client=InMemoryOpenVikingClient(),
- root_uri="viking://user/memories/langgraph_store",
+ root_uri="viking://~/memories/langgraph_store",
)
assert (
@@ -1307,7 +1305,7 @@ def test_langgraph_store_uses_create_first_and_preserves_created_at_on_replace()
store.put(("users",), "ada", {"color": "teal"})
second = store.get(("users",), "ada")
- data_uri = "viking://user/memories/langgraph_store/data/users/ada.json"
+ data_uri = "viking://~/memories/langgraph_store/data/users/ada.json"
assert client.write_modes[0] == (data_uri, "create")
assert (data_uri, "replace") in client.write_modes
assert second.created_at == first.created_at
@@ -1353,11 +1351,11 @@ def test_pending_token_commit_uses_persisted_value_without_session_lookup():
def test_langgraph_middleware_injects_recall_and_captures_messages():
client = InMemoryOpenVikingClient(
- {"viking://user/memories/profile.md": "The user prefers azure deployments."}
+ {"viking://~/memories/profile.md": "The user prefers azure deployments."}
)
middleware = OpenVikingContextMiddleware(
client=client,
- target_uri="viking://user/memories",
+ target_uri="viking://~/memories",
session_id_resolver=lambda state, runtime: "middleware-session",
commit_on_after_agent=True,
)
@@ -1453,11 +1451,11 @@ def test_langgraph_middleware_batches_persistence_before_separate_commit():
def test_langgraph_middleware_uses_peer_id_only_for_message_capture():
client = InMemoryOpenVikingClient(
- {"viking://user/memories/profile.md": "The middleware peer prefers azure."}
+ {"viking://~/memories/profile.md": "The middleware peer prefers azure."}
)
middleware = OpenVikingContextMiddleware(
client=client,
- target_uri="viking://user/memories",
+ target_uri="viking://~/memories",
session_id_resolver=lambda state, runtime: "middleware-peer-session",
)
@@ -1494,7 +1492,7 @@ def test_langgraph_middleware_uses_peer_id_only_for_message_capture():
def test_langgraph_middleware_does_not_duplicate_active_messages_in_context():
client = InMemoryOpenVikingClient(
- {"viking://user/memories/profile.md": "Middleware recall uses green context."}
+ {"viking://~/memories/profile.md": "Middleware recall uses green context."}
)
client.add_message(
"middleware-active-session",
@@ -1508,7 +1506,7 @@ def test_langgraph_middleware_does_not_duplicate_active_messages_in_context():
)
middleware = OpenVikingContextMiddleware(
client=client,
- target_uri="viking://user/memories",
+ target_uri="viking://~/memories",
session_id_resolver=lambda state, runtime: "middleware-active-session",
)
captured_request = {}
@@ -1536,11 +1534,11 @@ def test_langgraph_middleware_does_not_duplicate_active_messages_in_context():
def test_langgraph_middleware_uses_runtime_thread_id():
client = InMemoryOpenVikingClient(
- {"viking://user/memories/profile.md": "Runtime thread users prefer teal."}
+ {"viking://~/memories/profile.md": "Runtime thread users prefer teal."}
)
middleware = OpenVikingContextMiddleware(
client=client,
- target_uri="viking://user/memories",
+ target_uri="viking://~/memories",
)
captured_request = {}
@@ -1581,11 +1579,11 @@ def test_langgraph_middleware_uses_runtime_thread_id():
def test_langgraph_middleware_requires_explicit_session_id():
client = InMemoryOpenVikingClient(
- {"viking://user/memories/profile.md": "Shared fallback should never be used."}
+ {"viking://~/memories/profile.md": "Shared fallback should never be used."}
)
middleware = OpenVikingContextMiddleware(
client=client,
- target_uri="viking://user/memories",
+ target_uri="viking://~/memories",
)
class Request:
@@ -1759,12 +1757,10 @@ def test_langgraph_middleware_signature_includes_dict_tool_output():
def test_langgraph_middleware_clears_pending_context_on_duplicate_retry():
- client = InMemoryOpenVikingClient(
- {"viking://user/memories/profile.md": "Retry cleanup context."}
- )
+ client = InMemoryOpenVikingClient({"viking://~/memories/profile.md": "Retry cleanup context."})
middleware = OpenVikingContextMiddleware(
client=client,
- target_uri="viking://user/memories",
+ target_uri="viking://~/memories",
session_id_resolver=lambda state, runtime: "middleware-pending-cleanup",
)
@@ -1818,7 +1814,7 @@ def test_langgraph_middleware_clears_pending_context_on_duplicate_retry():
def test_langgraph_middleware_retries_failed_batch_with_pending_context():
class FailFirstBatchClient(InMemoryOpenVikingClient):
def __init__(self):
- super().__init__({"viking://user/memories/profile.md": "Retained retry context."})
+ super().__init__({"viking://~/memories/profile.md": "Retained retry context."})
self.batch_attempts = 0
def batch_add_messages(self, session_id, messages, **kwargs):
@@ -1830,7 +1826,7 @@ def test_langgraph_middleware_retries_failed_batch_with_pending_context():
client = FailFirstBatchClient()
middleware = OpenVikingContextMiddleware(
client=client,
- target_uri="viking://user/memories",
+ target_uri="viking://~/memories",
session_id_resolver=lambda state, runtime: "middleware-batch-retry",
)
diff --git a/tests/unit/test_langchain_package_boundary.py b/tests/unit/test_langchain_package_boundary.py
index c13faadfa..80b127f38 100644
--- a/tests/unit/test_langchain_package_boundary.py
+++ b/tests/unit/test_langchain_package_boundary.py
@@ -217,6 +217,13 @@ def test_legacy_imports_resolve_to_canonical_objects():
@pytest.mark.parametrize(
("uri", "expected_parts", "expected_scope", "expected_content_index"),
[
+ (
+ "viking://~/memories/store/data/users/ada.json",
+ ("~", "memories", "store", "data", "users", "ada.json"),
+ "user",
+ 1,
+ ),
+ # Legacy uid-less roots may still sit in older store configs; keep classifying them.
(
"viking://user/memories/store/data/users/ada.json",
("user", "memories", "store", "data", "users", "ada.json"),
@@ -235,6 +242,12 @@ def test_legacy_imports_resolve_to_canonical_objects():
"user",
4,
),
+ (
+ "viking://~/peers/assistant/memories/store/index.md",
+ ("~", "peers", "assistant", "memories", "store", "index.md"),
+ "user",
+ 3,
+ ),
(
"viking://user/peers/assistant/memories/store/index.md",
("user", "peers", "assistant", "memories", "store", "index.md"),
diff --git a/tests/unit/test_langchain_recording.py b/tests/unit/test_langchain_recording.py
index fdac314df..cc44df862 100644
--- a/tests/unit/test_langchain_recording.py
+++ b/tests/unit/test_langchain_recording.py
@@ -58,7 +58,7 @@ def test_recorder_filters_framework_control_messages_and_preserves_tool_parts():
context_parts = [
{
"type": "context",
- "uri": "viking://user/memories/preference.md",
+ "uri": "viking://~/memories/preference.md",
"context_type": "memory",
"abstract": "The user prefers azure.",
}
@@ -105,7 +105,7 @@ def test_recorder_filters_framework_control_messages_and_preserves_tool_parts():
assert context_parts == [
{
"type": "context",
- "uri": "viking://user/memories/preference.md",
+ "uri": "viking://~/memories/preference.md",
"context_type": "memory",
"abstract": "The user prefers azure.",
}
@@ -137,7 +137,7 @@ def test_recorder_uses_empty_assistant_as_context_carrier():
context_parts = [
{
"type": "context",
- "uri": "viking://user/memories/context-carrier.md",
+ "uri": "viking://~/memories/context-carrier.md",
"context_type": "memory",
}
]
@@ -170,7 +170,7 @@ def test_recorder_leaves_context_unattached_without_assistant_payload():
context_parts=[
{
"type": "context",
- "uri": "viking://user/memories/pending.md",
+ "uri": "viking://~/memories/pending.md",
"context_type": "memory",
}
],
@@ -191,7 +191,7 @@ def test_recorder_does_not_attribute_context_to_tool_result_payload():
context_parts = [
{
"type": "context",
- "uri": "viking://user/memories/assistant-only.md",
+ "uri": "viking://~/memories/assistant-only.md",
"context_type": "memory",
}
]
@@ -563,7 +563,7 @@ def test_chat_message_history_keeps_context_pending_until_assistant_message():
context_parts_provider=lambda _session_id: [
{
"type": "context",
- "uri": "viking://user/memories/history-pending.md",
+ "uri": "viking://~/memories/history-pending.md",
"context_type": "memory",
}
],
@@ -613,7 +613,7 @@ def test_chat_message_history_lifecycle_discards_pending_context(
context_parts_provider=lambda _session_id: [
{
"type": "context",
- "uri": "viking://user/memories/discarded.md",
+ "uri": "viking://~/memories/discarded.md",
"context_type": "memory",
}
],
@@ -664,7 +664,7 @@ def test_middleware_resumes_after_last_successful_recorder_batch():
middleware._pending_context_parts[capture_key] = [
{
"type": "context",
- "uri": "viking://user/memories/retry.md",
+ "uri": "viking://~/memories/retry.md",
"context_type": "memory",
"abstract": "Retry context.",
}
@@ -714,7 +714,7 @@ def test_middleware_retains_pending_context_when_first_recorder_batch_fails():
middleware._pending_context_parts[capture_key] = [
{
"type": "context",
- "uri": "viking://user/memories/retry.md",
+ "uri": "viking://~/memories/retry.md",
"context_type": "memory",
"abstract": "Retained retry context.",
}
@@ -746,7 +746,7 @@ def test_middleware_keeps_context_pending_until_empty_assistant_arrives():
middleware._pending_context_parts[capture_key] = [
{
"type": "context",
- "uri": "viking://user/memories/pending-assistant.md",
+ "uri": "viking://~/memories/pending-assistant.md",
"context_type": "memory",
}
]
diff --git a/tests/unit/test_namespace_uri_classification.py b/tests/unit/test_namespace_uri_classification.py
index 741845ca0..63c6a8efc 100644
--- a/tests/unit/test_namespace_uri_classification.py
+++ b/tests/unit/test_namespace_uri_classification.py
@@ -2,6 +2,8 @@
# SPDX-License-Identifier: Apache-2.0
"""Tests for shared Viking URI namespace/content classification."""
+import re
+
import pytest
from openviking.core.namespace import (
@@ -107,10 +109,10 @@ def test_session_uri_helpers_use_user_namespace():
assert canonical_session_uri(ctx) == "viking://user/alice/sessions"
assert canonical_session_uri(ctx, "s1") == "viking://user/alice/sessions/s1"
assert resolve_uri("viking://user/sessions/s1").uri == "viking://user/sessions/s1"
- assert (
+ # The uid-less 'sessions' shorthand no longer expands; it fails closed with a
+ # hint pointing at the '~' home alias.
+ with pytest.raises(NamespaceShapeError, match=re.escape("viking://~/sessions/s1")):
resolve_request_uri("viking://user/sessions/s1", ctx)
- == "viking://user/alice/sessions/s1"
- )
assert (
resolve_request_uri("viking://session/s1", ctx)
== "viking://user/alice/sessions/s1"
@@ -130,29 +132,24 @@ def test_session_uri_helpers_use_user_namespace():
assert "viking://agent/skills" in roots
-def test_request_boundary_expands_current_user_content_roots():
+def test_request_boundary_rejects_reserved_user_root_shorthand():
ctx = RequestContext(
user=UserIdentifier(account_id="acct", user_id="alice"),
role=Role.USER,
)
- assert (
+ with pytest.raises(NamespaceShapeError, match=re.escape("viking://~/resources")):
resolve_request_uri("viking://user/resources", ctx)
- == "viking://user/alice/resources"
- )
- assert (
+ with pytest.raises(NamespaceShapeError, match=re.escape("viking://~/resources/docs")):
resolve_request_uri("viking://user/resources/docs", ctx)
- == "viking://user/alice/resources/docs"
- )
- assert (
+ with pytest.raises(InvalidURIError, match=re.escape("viking://~/resources")):
validate_content_target_uri(
"viking://user/resources",
ctx,
kind="resource",
field_name="parent",
)
- == "viking://user/alice/resources"
- )
+ # Account-shared resources are untouched by the removal.
assert (
validate_content_target_uri(
"viking://resources/docs/",
@@ -163,6 +160,8 @@ def test_request_boundary_expands_current_user_content_roots():
== "viking://resources/docs"
)
assert resolve_uri("viking://user/alice/resources").uri == "viking://user/alice/resources"
+ # Self-id escape: a caller literally named 'resources' keeps the literal URI
+ # as their own canonical root.
collision_ctx = RequestContext(
user=UserIdentifier(account_id="acct", user_id="resources"),
role=Role.USER,
@@ -175,14 +174,11 @@ def test_request_boundary_expands_current_user_content_roots():
user=UserIdentifier(account_id="acct", user_id="admin"),
role=Role.ADMIN,
)
- assert (
+ with pytest.raises(NamespaceShapeError, match=re.escape("viking://~/resources")):
resolve_request_uri("viking://user/resources", admin_ctx)
- == "viking://user/admin/resources"
- )
- assert (
+ with pytest.raises(NamespaceShapeError, match=re.escape("viking://~/skills")):
resolve_request_uri("viking://user/skills", admin_ctx)
- == "viking://user/admin/skills"
- )
+ # ROOT requests never enter current-user resolution, so the literal parse stands.
root_ctx = RequestContext(
user=UserIdentifier(account_id="acct", user_id="root-actor"),
role=Role.ROOT,
@@ -194,6 +190,41 @@ def test_request_boundary_expands_current_user_content_roots():
assert is_content_root_uri("viking://resources", kind="resource")
+ "segment", ["memories", "resources", "skills", "peers", "privacy", "sessions"]
+)
[email protected]("role", [Role.USER, Role.ADMIN])
+def test_reserved_user_root_shorthand_rejection_message(segment, role):
+ ctx = RequestContext(
+ user=UserIdentifier(account_id="acct", user_id="alice"),
+ role=role,
+ )
+
+ with pytest.raises(NamespaceShapeError) as excinfo:
+ resolve_request_uri(f"viking://user/{segment}", ctx)
+ message = str(excinfo.value)
+ assert f"viking://~/{segment}" in message
+ assert f"viking://user/{{user_id}}/{segment}" in message
+
+ with pytest.raises(NamespaceShapeError) as nested:
+ resolve_request_uri(f"viking://user/{segment}/nested/leaf.md", ctx)
+ nested_message = str(nested.value)
+ assert f"viking://~/{segment}/nested/leaf.md" in nested_message
+ assert f"viking://user/{{user_id}}/{segment}/nested/leaf.md" in nested_message
+
+
+def test_bare_user_uri_stays_the_user_space_container():
+ ctx = RequestContext(
+ user=UserIdentifier(account_id="acct", user_id="alice"),
+ role=Role.USER,
+ )
+
+ assert resolve_request_uri("viking://user", ctx) == "viking://user"
+ assert resolve_request_uri("viking://user/", ctx) == "viking://user"
+ assert resolve_uri("viking://user").is_container is True
+ assert resolve_uri("viking://user").owner_user_id is None
+
+
def test_unreserved_user_root_segment_keeps_canonical_meaning():
# The generic namespace parser stays canonical-first for user id segments: an
# unreserved segment under viking://user/ is a peer user id, never a shorthand.
diff --git a/tests/unit/usage_reporter/test_memory_usage_extractor.py b/tests/unit/usage_reporter/test_memory_usage_extractor.py
index f54559b18..62c35ec9c 100644
--- a/tests/unit/usage_reporter/test_memory_usage_extractor.py
+++ b/tests/unit/usage_reporter/test_memory_usage_extractor.py
@@ -316,6 +316,31 @@ async def test_memory_usage_extractor_canonicalizes_short_user_list_uri():
]
+async def test_memory_usage_extractor_canonicalizes_home_alias_list_uri():
+ messages = [
+ Message(
+ id="msg-home-alias-list",
+ role="user",
+ parts=[
+ ToolPart(
+ tool_id="call-list",
+ tool_name="mcp__openviking__list",
+ tool_status="completed",
+ tool_input={"uri": "viking://~/memories/experiences"},
+ tool_output="[file] listed experience.md",
+ )
+ ],
+ )
+ ]
+
+ events = await MemoryUsageExtractor().extract(messages=messages, context=_context())
+
+ assert [event.resource_uri for event in events] == [
+ "viking://user/test/memories/experiences/listed experience.md"
+ ]
+
+
@pytest.mark.asyncio
@pytest.mark.parametrize(
("tool_name", "tool_input"),
@@ -475,6 +500,30 @@ async def test_memory_usage_extractor_ignores_short_user_read_not_found_result()
assert events == []
+async def test_memory_usage_extractor_ignores_home_alias_read_not_found_result():
+ alias_uri = "viking://~/memories/experiences/missing.md"
+ messages = [
+ Message(
+ id="msg-missing-home-alias-read",
+ role="user",
+ parts=[
+ ToolPart(
+ tool_id="call-read",
+ tool_name="mcp__openviking__read",
+ tool_status="completed",
+ tool_input={"uris": alias_uri},
+ tool_output=f"(nothing found at {alias_uri})",
+ )
+ ],
+ )
+ ]
+
+ events = await MemoryUsageExtractor().extract(messages=messages, context=_context())
+
+ assert events == []
+
+
@pytest.mark.asyncio
async def test_memory_usage_extractor_uses_message_time_for_event_time():
experience_uri = "viking://user/test/memories/experiences/no-order-exchange.md"