Self-evolving Context Database for AI Agents. Unify Agent Memory, Knowledge RAG and Skills.
Python agent-contextagent-memoryagent-pluginsagentic-ragcontext-databasedsh-pluginknowledge-basememorymemory-managementself-evolvingvector-database
feat(uri): add viking://~ home alias for the caller's user root (#4167)
t0sakiff38bb5dd1da
diff --git a/docs/en/concepts/04-viking-uri.md b/docs/en/concepts/04-viking-uri.mdindex c1e05b610..c42698d27 100644--- a/docs/en/concepts/04-viking-uri.md+++ b/docs/en/concepts/04-viking-uri.md@@ -30,6 +30,27 @@ under `viking://user/{user_id}/sessions`.`temp`, `queue`, and `upload` are internal implementationscopes and cannot be addressed directly through public API URI parameters.+### Home Alias `~`++`~` is a server-side alias for the caller's own user root. `viking://~` expands to+`viking://user/{user_id}`, and `viking://~/memories/note.md` to+`viking://user/{user_id}/memories/note.md`, where `{user_id}` comes from the request's+authenticated identity — the same string therefore points at a different directory for+each caller.++- Universal: accepted by every control plane (REST API, `ov` CLI, SDKs, MCP), anywhere a+ public-scope URI is accepted.+- First segment only: `viking://resources/~/x` and `viking://user/alice/~/x` keep `~` as+ a literal path segment.+- Accepted, not advertised: `~` is not part of the public scope list, so the+ `Invalid scope ... Must be one of:` error message never mentions it.+- Responses always echo the expanded canonical URI, never `viking://~`, and persisted+ data (vector records, watch keys) stays canonical as well.+- Requires an authenticated user identity. Expansion happens at the request boundary for+ 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.+## Initial Directory StructureMoving away from traditional flat database thinking, all context is organized as a filesystem. Agents no longer just find data through vector search, but can locate and browse data through deterministic paths and standard filesystem commands. Each context or directory is assigned a unique URI identifier string in the format viking://{scope}/{path}, allowing the system to precisely locate and access resources stored in different locations.diff --git a/docs/en/guides/06-mcp-integration.md b/docs/en/guides/06-mcp-integration.mdindex 0ca1520f4..d9b716521 100644--- a/docs/en/guides/06-mcp-integration.md+++ b/docs/en/guides/06-mcp-integration.md@@ -155,6 +155,12 @@ For MCP tools, `viking://user` is the authenticated user's workspace. For examplextension. 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+[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.> Feishu/Lark imports without `args.feishu_access_token` keep the existing app/tenant-token behavior and can be watched. Feishu/Lark one-time user-token imports pass only `args.feishu_access_token`; Feishu/Lark user-token watches must also pass `args.feishu_refresh_token` and require the same Feishu app credentials configured on the OpenViking server.diff --git a/docs/zh/concepts/04-viking-uri.md b/docs/zh/concepts/04-viking-uri.mdindex 704bd99ac..e11eeefae 100644--- a/docs/zh/concepts/04-viking-uri.md+++ b/docs/zh/concepts/04-viking-uri.md@@ -28,6 +28,21 @@ viking://{scope}/{path}新 session 数据位于 `viking://user/{user_id}/sessions`。`temp`、`queue` 和 `upload` 是内部实现作用域,不能通过公开 API 的 URI 参数直接访问。+### Home 别名 `~`++`~` 是当前调用方用户根目录的服务端别名。`viking://~` 展开为 `viking://user/{user_id}`,+`viking://~/memories/note.md` 展开为 `viking://user/{user_id}/memories/note.md`,+其中 `{user_id}` 取自请求的认证身份——同一个字符串对不同调用方指向不同目录。++- 通用:所有控制面(REST API、`ov` CLI、SDK、MCP)都接受,可用于任何接受公开作用域 URI 的位置。+- 仅识别第 0 段:`viking://resources/~/x` 和 `viking://user/alice/~/x` 中的 `~` 仍是字面路径段。+- 接受但不宣传:`~` 不属于公开作用域列表,`Invalid scope ... Must be one of:` 错误信息中不会出现它。+- 响应始终回显展开后的 canonical URI,不会返回 `viking://~`;持久化数据(向量记录、watch key)+ 同样保持 canonical 形式。+- 需要认证用户身份。展开发生在 user / admin 调用方的请求入口;root 角色与未认证上下文,+ 以及要求 URI 已是 canonical 形式的场景(内部存储路径、后台任务),会直接拒绝该别名,+ 而不会猜测用户。+## 初始目录摒弃传统的扁平化数据库思维,将所有上下文组织为一套文件系统。Agent 不再仅是通过向量搜索来找数据,而是可以通过确定性的路径和标准文件系统指令来定位和浏览数据。每个上下文或目录分配唯一的 URI 标识字符串,格式为 viking://{scope}/{path},让系统能精准定位并访问存储在不同位置的资源。diff --git a/docs/zh/guides/06-mcp-integration.md b/docs/zh/guides/06-mcp-integration.mdindex 23953c043..bd3e24037 100644--- a/docs/zh/guides/06-mcp-integration.md+++ b/docs/zh/guides/06-mcp-integration.md@@ -146,6 +146,11 @@ claude mcp add --transport http openviking \`viking://user/<当前用户>/notes/todo.md`,不依赖文件名或扩展名判断。工具返回的、包含当前用户 ID 的 canonical URI 也可以直接使用;这套简写不用于跨用户访问。+`viking://~` 是另一个通用别名,表示调用方的用户根目录:它在所有控制面(REST API、`ov` CLI、+SDK 和 MCP)上都会展开为 `viking://user/<当前用户>`,且响应始终回显展开后的 canonical URI。+上面的 `viking://user/<path>` 简写则仍是 MCP 专属。详见+[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 使用上述操作。> 未传 `args.feishu_access_token` 的飞书/Lark 导入保持现有应用/tenant token 行为,也支持 watch。飞书/Lark 一次性用户 token 导入只传 `args.feishu_access_token`;飞书/Lark 用户 token watch 还必须传 `args.feishu_refresh_token`,并要求 OpenViking 服务端配置同一个飞书应用凭证。diff --git a/openviking/core/namespace.py b/openviking/core/namespace.pyindex 707f017c8..7858d2e47 100644--- a/openviking/core/namespace.py+++ b/openviking/core/namespace.py@@ -241,6 +241,12 @@ def resolve_uri(return _resolve_user_uri(parts)if scope == "agent":return ResolvedNamespace(uri=canonical_uri, scope=scope)+ if scope == "~":+ # The home alias is expanded at the request boundary only. Reaching the+ # canonical parser with it (root-role requests, internal callers, storage+ # paths) means no identity is available, so fail closed instead of+ # creating a literal '~' namespace.+ raise NamespaceShapeError(f"Home alias URI is not canonical: {'/'.join(parts)}")if scope == "session":raise NamespaceShapeError(f"Legacy session URI is not canonical: {'/'.join(parts)}")if scope in {"resources", "temp", "queue", "upload"}:@@ -261,6 +267,11 @@ def resolve_current_user_uri(uri: str, ctx: RequestContext) -> str:if not parts:return "viking://"+ if parts[0] == "~":+ if len(parts) == 1:+ return canonical_user_root(ctx)+ return f"{canonical_user_root(ctx)}/{'/'.join(parts[1:])}"+if parts[0] == "session":if len(parts) == 1:return canonical_session_root(ctx)diff --git a/openviking/core/uri_validation.py b/openviking/core/uri_validation.pyindex e72e6a5d7..5d977e51d 100644--- a/openviking/core/uri_validation.py+++ b/openviking/core/uri_validation.py@@ -14,7 +14,9 @@ from openviking.core.namespace import (from openviking_cli.exceptions import InvalidURIError, PermissionDeniedErrorfrom openviking_cli.utils.uri import VikingURI-_PUBLIC_API_SCOPES = frozenset({"", *VikingURI.PUBLIC_SCOPES, *VikingURI.LEGACY_SCOPES})+_PUBLIC_API_SCOPES = frozenset(+ {"", *VikingURI.PUBLIC_SCOPES, *VikingURI.LEGACY_SCOPES, *VikingURI.ALIAS_SCOPES}+)_ALL_API_SCOPES = frozenset({"", *VikingURI.VISITABLE_SCOPES})@@ -49,7 +51,10 @@ def validate_viking_uri(scopes = _allowed_api_scopes(allow_internal=allow_internal, allowed_scopes=allowed_scopes)if parsed.scope not in scopes:- scope_names = ", ".join(sorted(scope for scope in scopes if scope))+ # Alias scopes are accepted but never advertised in scope error messages.+ scope_names = ", ".join(+ sorted(scope for scope in scopes if scope and scope not in VikingURI.ALIAS_SCOPES)+ )if not parsed.scope:reason = f"URI must include one of: {scope_names}"else:diff --git a/openviking/server/mcp_endpoint.py b/openviking/server/mcp_endpoint.pyindex a4e79aa29..ed120ddfb 100644--- a/openviking/server/mcp_endpoint.py+++ b/openviking/server/mcp_endpoint.py@@ -324,6 +324,11 @@ async def search("other_peer_penalty cannot be combined with other_peer_penalties ""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.+ resolved_exclude_uris = [+ _resolve_mcp_workspace_uri(exclude_uri, ctx) for exclude_uri in (exclude_uris or ())+ ]result = await assemble_context(service=service,ctx=ctx,@@ -339,7 +344,7 @@ async def search(purpose=purpose,detail=detail_by_category or (None if detail == "auto" else detail),dedup_turns=dedup_turns,- exclude_uris=exclude_uris or (),+ exclude_uris=resolved_exclude_uris,peer_scope=peer_scope,other_peer_penalty=other_peer_penalties or other_peer_penalty,rewrite=rewrite == "auto",diff --git a/openviking_cli/utils/uri.py b/openviking_cli/utils/uri.pyindex c88571fc9..f7d43bb5c 100644--- a/openviking_cli/utils/uri.py+++ b/openviking_cli/utils/uri.py@@ -25,6 +25,7 @@ class VikingURI:- 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/...)+ - ~: Server-side alias for the caller's user root, expanded to viking://user/{user_id}Examples:- viking://resources/my_project/docs/api@@ -43,9 +44,12 @@ class VikingURI:PUBLIC_SCOPES = frozenset(LISTABLE_SCOPES)LEGACY_SCOPES = frozenset({"session"})INTERNAL_SCOPES = frozenset({"temp", "queue", "upload"})+ # Server-side alias for the caller's user namespace root. Only valid as segment 0,+ # and never persisted or echoed back: the server always expands it to viking://user/{user_id}.+ ALIAS_SCOPES = frozenset({"~"})# All valid scopes that can be addressed by the URI parser/storage internals.# Public API handlers must not use this as their external whitelist.- VISITABLE_SCOPES = PUBLIC_SCOPES | LEGACY_SCOPES | INTERNAL_SCOPES+ VISITABLE_SCOPES = PUBLIC_SCOPES | LEGACY_SCOPES | INTERNAL_SCOPES | ALIAS_SCOPESdef __init__(self, uri: str):"""@@ -81,7 +85,8 @@ class VikingURI:# Parse scopescope = path.split("/")[0]if scope not in self.VISITABLE_SCOPES:- scope_names = ", ".join(sorted(self.VISITABLE_SCOPES))+ # Alias scopes are accepted but never advertised in scope error messages.+ scope_names = ", ".join(sorted(self.VISITABLE_SCOPES - self.ALIAS_SCOPES))raise ValueError(f"Invalid scope '{scope}'. Must be one of: {scope_names}")return {@@ -195,7 +200,8 @@ class VikingURI:Returns:Viking URI string"""- if scope not in VikingURI.VISITABLE_SCOPES:+ # Alias scopes are inputs only: the server never mints a '~' URI.+ if scope not in VikingURI.VISITABLE_SCOPES or scope in VikingURI.ALIAS_SCOPES:raise ValueError(f"Invalid scope '{scope}'")parts = [scope] + list(path_parts)diff --git a/tests/server/test_api_watches.py b/tests/server/test_api_watches.pyindex 59d468d7f..3e732b991 100644--- a/tests/server/test_api_watches.py+++ b/tests/server/test_api_watches.py@@ -244,3 +244,42 @@ async def test_patch_partial_preserves_unset_fields(client: httpx.AsyncClient, wbody = resp.json()assert body["result"]["watch_interval"] == original_intervalassert body["result"]["is_active"] is False+++async def test_home_alias_to_uri_resolves_to_canonically_keyed_task(+ app, client: httpx.AsyncClient, watch_manager+):+ """`?to_uri=viking://~/...` addresses the task stored under the canonical key.++ Watch tasks are keyed on the canonical URI, and the router canonicalizes+ ``to_uri`` at the request boundary, so the alias resolves to the same task+ and the response keeps echoing the stored canonical key. The dev auth plugin+ resolves test requests to root, which never expands the alias, so this test+ overrides the request context with a user-role identity.+ """+ from openviking.server.auth import get_request_context+ from openviking.server.identity import RequestContext, Role+ from openviking_cli.session.user_id import UserIdentifier++ canonical = "viking://user/default/resources/home-alias"+ task = await _seed(watch_manager, to_uri=canonical)+ app.dependency_overrides[get_request_context] = lambda: RequestContext(+ user=UserIdentifier(account_id="default", user_id="default"),+ role=Role.USER,+ )+ try:+ resp = await client.get(+ "/api/v1/watches", params={"to_uri": "viking://~/resources/home-alias"}+ )+ assert resp.status_code == 200+ assert resp.json()["result"]["task_id"] == task.task_id+ assert resp.json()["result"]["to_uri"] == canonical++ resp = await client.delete(+ "/api/v1/watches", params={"to_uri": "viking://~/resources/home-alias"}+ )+ assert resp.status_code == 200+ assert resp.json()["result"]["deleted"] is True+ assert resp.json()["result"]["to_uri"] == canonical+ finally:+ app.dependency_overrides.pop(get_request_context, None)diff --git a/tests/server/test_filesystem_router.py b/tests/server/test_filesystem_router.pyindex b0331f98e..4422b5dc5 100644--- a/tests/server/test_filesystem_router.py+++ b/tests/server/test_filesystem_router.py@@ -83,3 +83,25 @@ async def test_attrs_returns_memory_fields_and_tags(monkeypatch):"memory_type": "preferences",}assert attrs["tags"] == ["team=search"]+++async def test_mkdir_echoes_canonical_home_alias(monkeypatch):+ seen = {}++ async def fake_mkdir(uri, ctx=None, description=None):+ seen["uri"] = uri++ monkeypatch.setattr(+ filesystem,+ "get_service",+ lambda: SimpleNamespace(fs=SimpleNamespace(mkdir=fake_mkdir)),+ )++ response = await filesystem.mkdir(+ filesystem.MkdirRequest(uri="viking://~/resources/notes"),+ _ctx=RequestContext(user=UserIdentifier("acct", "alice"), role=Role.USER),+ )++ assert seen["uri"] == "viking://user/alice/resources/notes"+ assert response.result["uri"] == "viking://user/alice/resources/notes"diff --git a/tests/server/test_mcp_endpoint.py b/tests/server/test_mcp_endpoint.pyindex 889ec72e8..463d4148f 100644--- a/tests/server/test_mcp_endpoint.py+++ b/tests/server/test_mcp_endpoint.py@@ -44,6 +44,7 @@ from openviking_cli.exceptions import (AlreadyExistsError,FailedPreconditionError,InvalidArgumentError,+ InvalidURIError,NotFoundError,PermissionDeniedError,UnauthenticatedError,@@ -1227,6 +1228,30 @@ async def test_edit_memory_file_preserves_metadata(service):assert visible.strip() == "likes: coffee"+async def test_write_home_alias_uri(service):+ """`viking://~/...` writes into the caller's canonical user root."""+ user_ctx = RequestContext(DEFAULT_CTX.user, Role.USER)+ canonical = f"viking://user/{DEFAULT_CTX.user.user_id}/memories/preferences/home_alias.md"+ token = _mcp_ctx.set(user_ctx)+ try:+ result = await write(uri="viking://~/memories/preferences/home_alias.md", content="x")+ listing = await list_tool(uri="viking://~/memories/preferences")+ 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+ visible = await service.fs.read_visible(canonical, ctx=DEFAULT_CTX)+ assert visible.strip() == "x"+++async def test_home_alias_rejected_for_root_role(service):+ """Root-role MCP calls skip current-user resolution, so the alias fails closed."""+ with pytest.raises(InvalidURIError, match="Home alias URI is not canonical"):+ await list_tool(uri="viking://~/memories")++async def test_write_user_shorthand_uri(service):uri = "viking://user/memories/preferences/shorthand_write.md"user_ctx = RequestContext(DEFAULT_CTX.user, Role.USER)diff --git a/tests/unit/test_namespace_uri_classification.py b/tests/unit/test_namespace_uri_classification.pyindex 0040c8b22..741845ca0 100644--- a/tests/unit/test_namespace_uri_classification.py+++ b/tests/unit/test_namespace_uri_classification.py@@ -5,6 +5,7 @@import pytestfrom openviking.core.namespace import (+ NamespaceShapeError,canonical_session_uri,classify_uri,context_type_for_uri,@@ -15,7 +16,10 @@ from openviking.core.namespace import (resolve_uri,visible_roots,)-from openviking.core.uri_validation import validate_content_target_uri+from openviking.core.uri_validation import (+ validate_content_target_uri,+ validate_request_viking_uri,+)from openviking.server.identity import RequestContext, Rolefrom openviking_cli.exceptions import InvalidURIErrorfrom openviking_cli.session.user_id import UserIdentifier@@ -191,9 +195,14 @@ def test_request_boundary_expands_current_user_content_roots():def test_unreserved_user_root_segment_keeps_canonical_meaning():- # The generic namespace parser stays canonical-first. Callers that expose- # a current-user workspace dialect (such as MCP) must opt into that policy- # at their boundary instead of guessing from file extensions or server state.+ # 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.+ # The '~' home alias does not weaken that rule -- it is a reserved token that+ # cannot be a valid user id (see identifiers.validate_user_id), and it is only+ # recognized as segment 0, so it never competes with a canonical user segment.+ # Callers that expose a current-user workspace dialect (such as MCP) must still+ # opt into that policy at their boundary instead of guessing from file+ # extensions or server state.assert resolve_uri("viking://user/notes/todo.md").uri == "viking://user/notes/todo.md"assert (resolve_uri("viking://user/bob/zeus-persona.md").uri@@ -217,3 +226,76 @@ def test_unreserved_user_root_segment_keeps_canonical_meaning():resolve_uri("viking://user/alice/notes/todo.md").uri== "viking://user/alice/notes/todo.md")+++def test_home_alias_expands_to_current_user_root_at_request_boundary():+ for role in (Role.USER, Role.ADMIN):+ ctx = RequestContext(+ user=UserIdentifier(account_id="acct", user_id="alice"),+ role=role,+ )++ assert resolve_request_uri("viking://~", ctx) == "viking://user/alice"+ assert resolve_request_uri("viking://~/", ctx) == "viking://user/alice"+ assert (+ resolve_request_uri("viking://~/memories/preferences/p.md", ctx)+ == "viking://user/alice/memories/preferences/p.md"+ )+ assert (+ resolve_request_uri("viking://~/resources/docs/", ctx)+ == "viking://user/alice/resources/docs"+ )+ assert (+ validate_request_viking_uri("viking://~/resources/docs", ctx)+ == "viking://user/alice/resources/docs"+ )++ ctx = RequestContext(+ user=UserIdentifier(account_id="acct", user_id="alice"),+ role=Role.USER,+ )+ expanded = resolve_request_uri("viking://~/memories", ctx)+ # The expanded alias is field-for-field identical to the explicit form.+ assert resolve_uri(expanded) == resolve_uri("viking://user/alice/memories")+ assert context_type_for_uri(resolve_request_uri("viking://~/memories/m.md", ctx)) == "memory"+ assert is_content_root_uri(resolve_request_uri("viking://~/resources", ctx), kind="resource")+ assert (+ validate_content_target_uri("viking://~/resources", ctx, kind="resource")+ == "viking://user/alice/resources"+ )+++def test_home_alias_fails_closed_without_current_user_resolution():+ root_ctx = RequestContext(+ user=UserIdentifier(account_id="acct", user_id="root-actor"),+ role=Role.ROOT,+ )++ # Root-role requests skip current-user resolution, so the alias never becomes+ # a literal '~' namespace -- it is rejected instead of guessing a user.+ with pytest.raises(NamespaceShapeError, match="Home alias URI is not canonical"):+ resolve_request_uri("viking://~/resources/docs", root_ctx)+ with pytest.raises(InvalidURIError, match="Home alias URI is not canonical"):+ validate_request_viking_uri("viking://~/resources/docs", root_ctx)++ # Every internal consumer of the canonical parser is protected the same way.+ with pytest.raises(NamespaceShapeError, match="Home alias URI is not canonical"):+ resolve_uri("viking://~")+ with pytest.raises(NamespaceShapeError, match="Home alias URI is not canonical"):+ resolve_uri("viking://~/x")+ assert not is_content_root_uri("viking://~/resources", kind="resource")+++def test_home_alias_is_only_recognized_as_first_segment():+ ctx = RequestContext(+ user=UserIdentifier(account_id="acct", user_id="alice"),+ role=Role.USER,+ )++ # '~' is not a valid user id, so it can never shadow a real user namespace.+ with pytest.raises(NamespaceShapeError, match="Invalid user_id"):+ resolve_request_uri("viking://user/~/x", ctx)++ # Anywhere else it stays a literal path segment.+ assert resolve_request_uri("viking://resources/~/x", ctx) == "viking://resources/~/x"+ assert resolve_request_uri("viking://user/alice/~/x", ctx) == "viking://user/alice/~/x"diff --git a/tests/unit/test_uri_short_format.py b/tests/unit/test_uri_short_format.pyindex 9b0c3129f..3318cdd85 100644--- a/tests/unit/test_uri_short_format.py+++ b/tests/unit/test_uri_short_format.py@@ -49,6 +49,35 @@ class TestVikingURIExplicitFormat:with pytest.raises(ValueError, match="Invalid scope"):VikingURI("viking://invalid_scope/foo")+ def test_home_alias_is_parsable(self):+ """'viking://~' should parse with the home alias scope."""+ uri = VikingURI("viking://~")+ assert uri.uri == "viking://~"+ assert uri.scope == "~"++ def test_home_alias_with_suffix_is_parsable(self):+ """'viking://~/notes' keeps the alias scope and its suffix."""+ uri = VikingURI("viking://~/notes")+ assert uri.uri == "viking://~/notes"+ assert uri.scope == "~"+ assert uri.full_path == "~/notes"++ def test_invalid_scope_error_copy_hides_home_alias(self):+ """The parser's own scope enumeration never advertises the alias."""+ with pytest.raises(ValueError, match="Invalid scope") as exc_info:+ VikingURI("viking://invalid_scope/foo")+ message = str(exc_info.value)+ assert "Must be one of:" in message+ assert "~" not in message.split("Must be one of:", 1)[1]++ def test_build_rejects_home_alias_scope(self):+ """build() must never mint an alias URI: responses stay canonical."""+ with pytest.raises(ValueError, match="Invalid scope"):+ VikingURI.build("~")+ with pytest.raises(ValueError, match="Invalid scope"):+ VikingURI.build("~", "notes")+ assert VikingURI.build("user", "alice") == "viking://user/alice"+@pytest.mark.parametrize("value,scope",[diff --git a/tests/unit/test_uri_validation.py b/tests/unit/test_uri_validation.pyindex d3f05960c..0bc054668 100644--- a/tests/unit/test_uri_validation.py+++ b/tests/unit/test_uri_validation.py@@ -16,6 +16,8 @@ from openviking_cli.exceptions import InvalidURIError"viking://session/s1","viking://agent/code-agent/memories/facts/project.md","viking://",+ "viking://~",+ "viking://~/memories/x",],)def test_validate_viking_uri_accepts_supported_forms(uri: str):@@ -53,6 +55,24 @@ def test_validate_viking_uri_reports_explicit_scheme_requirement():assert "frozenset" not in message+def test_validate_viking_uri_hides_home_alias_in_public_scope_list():+ with pytest.raises(InvalidURIError) as exc_info:+ validate_viking_uri("viking://temp/generated")++ reason = exc_info.value.details["reason"]+ scope_list = reason.split("Must be one of:", 1)[1]+ assert "resources" in scope_list+ # The home alias is accepted but never advertised in the public scope list.+ assert "~" not in scope_list++ with pytest.raises(InvalidURIError) as exc_info:+ validate_viking_uri("viking://", allowed_scopes={"resources"})++ reason = exc_info.value.details["reason"]+ assert reason.startswith("URI must include one of:")+ assert "~" not in reason++def test_validate_viking_uri_supports_internal_and_operation_scopes():assert validate_viking_uri("viking://temp/generated", allow_internal=True)@@ -70,3 +90,24 @@ def test_validate_viking_uri_supports_internal_and_operation_scopes():"viking://invalid_scope/doc",allowed_scopes={"invalid_scope"},)+++def test_validate_viking_uri_hides_home_alias_for_unknown_scopes():+ # Unknown scopes fail at the parser, whose message also enumerates scopes.+ with pytest.raises(InvalidURIError) as exc_info:+ validate_viking_uri("viking://bogus/x")++ reason = exc_info.value.details["reason"]+ assert "~" not in reason.split("Must be one of:", 1)[1]+++def test_validate_viking_uri_rejects_home_alias_for_restricted_scopes():+ with pytest.raises(InvalidURIError) as exc_info:+ validate_viking_uri("viking://~", allowed_scopes={"resources"})++ reason = exc_info.value.details["reason"]+ assert reason.startswith("Invalid scope '~'")+ # Only the echoed offending scope may mention '~'; the advertised list must not.+ scope_list = reason.split("Must be one of:", 1)[1]+ assert "resources" in scope_list+ assert "~" not in scope_list