Skip to content

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

fix(uri): server 入口校验并补全 URI,内部只用规范 URI (#4048)

Qin Haojie81eba498b4fd
diff --git a/docs/design/ov-compile-design.md b/docs/design/ov-compile-design.md
index e8813c5c3..5c2e9b920 100644
--- a/docs/design/ov-compile-design.md
+++ b/docs/design/ov-compile-design.md
@@ -141,7 +141,7 @@ Compile 只增加任务编排和领域规则,基础能力使用现有实现:
| CLI | `CliContext`、`HttpClient`、全局认证、`OutputFormat`、`output_success()` | compile request、状态轮询和 human formatter |
| Bot proxy | `get_bot_url()`、`_create_bot_proxy_client()`、`_attach_openviking_connection()` | create/status 路由 |
| Gateway 认证 | `OpenAPIChannel` 的 Gateway Token dependency、`OpenVikingConnection` 和 principal scope | compile request model 和 task owner 绑定 |
-| URI 与权限 | `fs/attrs` 返回的 canonical URI、`validate_viking_uri()`、`canonicalize_uri()`、`context_type_for_uri()`、VikingFS access check | 用户上下文中的目录约束和 target containment |
+| URI 与权限 | `fs/attrs` 返回的 canonical URI、请求边界 URI 校验与简写展开、`context_type_for_uri()`、VikingFS access check | 用户上下文中的目录约束和 target containment |
| Skill | OpenViking Skills API、`SkillLoader.parse()`、VikingBot `SkillsLoader`、`SandboxManager` | OV bundle 快照和 task-local materialization |
| Agent | `AgentLoop._run_agent_loop()`、`ToolRegistry`、`register_default_tools()` | structured wrapper、scope guard 和 `submit_wiki_bundle` |
| 内容读取 | `openviking_list/search/grep/glob/multi_read` | 限定允许的 URI roots;不增加同义读取工具 |
@@ -470,7 +470,7 @@ POST /api/v1/content/batch-write
Batch write 负责:
-- 要求 `root_uri` 是已存在的可写目录;canonicalize 所有 URI,拒绝空 operations、重复 URI、跨 context type 以及 root 之外的目标,并按 canonical URI 稳定排序;
+- 要求 `root_uri` 和 operation URI 都是规范 URI,且 `root_uri` 是已存在的可写目录;拒绝空 operations、重复 URI、跨 context type 以及 root 之外的目标,并按 URI 稳定排序;
- 校验用户对每个目标 URI 的写权限;
- 保证目标 URI 位于 `root_uri` 下;
- 在目标 tree lock 内读取当前 raw bytes 并检查所有 precondition;
@@ -486,7 +486,7 @@ hash 定义为最终 raw UTF-8 bytes 的小写 SHA-256,API 表示为 `sha256:<
```text
content.batch-write router
- -> validate_viking_uri / canonicalize_uri / existing target-shape check
+ -> validate_viking_uri / current-user shorthand expansion / existing target-shape check
-> LockManager target tree lease
-> read current raw bytes; classify unchanged; validate all remaining preconditions
-> for each changed operation: VikingFS.write_file(..., lock_handle=lease.handle)
diff --git a/openviking/connector/delegate.py b/openviking/connector/delegate.py
index 6ce988044..1622f98fb 100644
--- a/openviking/connector/delegate.py
+++ b/openviking/connector/delegate.py
@@ -31,7 +31,6 @@ from openviking.connector.routing import (
detect_connector_add_type,
is_full_commit_sha,
)
-from openviking.core.content_targets import ContentTargetSpec
from openviking.parse.mode import ParseMode
from openviking.resource.processing_mode import (
DEFAULT_PROCESSING_MODE,
@@ -187,17 +186,6 @@ class ConnectorDelegate:
)
return False
- if ctx is not None and (to or parent):
- target = ContentTargetSpec.from_fields(
- ctx=ctx,
- kind="resource",
- to=to,
- parent=parent,
- create_parent=bool((kwargs or {}).get("create_parent", False)),
- )
- to = target.to
- parent = target.parent
-
unsupported = self._unsupported_params(
add_type=add_type,
wait=wait,
@@ -328,15 +316,9 @@ class ConnectorDelegate:
raise InvalidArgumentError(f"'{path}' does not match any Connector source type.")
add_type, _ = resolved
- target = ContentTargetSpec.from_fields(
- ctx=ctx,
- kind="resource",
- to=to,
- create_parent=bool(kwargs.get("create_parent", False)),
- )
- if not target.to:
+ task_resource_id = to or ""
+ if not task_resource_id:
raise InvalidArgumentError("Connector import requires an exact 'to' target.")
- task_resource_id = target.to
if not kwargs.get("create_parent", False):
# Match the native pipeline default: unless create_parent=true is
diff --git a/openviking/core/content_targets.py b/openviking/core/content_targets.py
deleted file mode 100644
index 822fcfc43..000000000
--- a/openviking/core/content_targets.py
+++ /dev/null
@@ -1,52 +0,0 @@
-"""Shared target resolution for user-supplied content destinations."""
-
-from __future__ import annotations
-
-from dataclasses import dataclass
-from typing import TYPE_CHECKING, Optional
-
-from openviking.core.path_variables import resolve_path_variables
-from openviking.core.uri_validation import validate_optional_content_target_uri
-from openviking_cli.exceptions import InvalidArgumentError
-
-if TYPE_CHECKING:
- from openviking.server.identity import RequestContext
-
-
-@dataclass(frozen=True)
-class ContentTargetSpec:
- """Canonical content destination fields for resource and skill writes."""
-
- to: str = ""
- parent: str = ""
- create_parent: bool = False
-
- @classmethod
- def from_fields(
- cls,
- *,
- ctx: RequestContext,
- kind: str,
- to: Optional[str] = None,
- parent: Optional[str] = None,
- create_parent: bool = False,
- ) -> "ContentTargetSpec":
- resolved_to = resolve_path_variables(to) if to else None
- resolved_parent = resolve_path_variables(parent) if parent else None
- if (resolved_to or "").strip() and (resolved_parent or "").strip():
- raise InvalidArgumentError("Cannot specify both 'to' and 'parent' at the same time.")
- return cls(
- to=validate_optional_content_target_uri(
- resolved_to,
- ctx,
- kind=kind,
- field_name="to",
- ),
- parent=validate_optional_content_target_uri(
- resolved_parent,
- ctx,
- kind=kind,
- field_name="parent",
- ),
- create_parent=create_parent,
- )
diff --git a/openviking/core/context.py b/openviking/core/context.py
index 80176d763..845df6346 100644
--- a/openviking/core/context.py
+++ b/openviking/core/context.py
@@ -105,26 +105,14 @@ class Context:
self.session_id = session_id
self.user = user
self.account_id = account_id or (user.account_id if user else "default")
- owner_fields = owner_fields_for_uri(
- uri,
- user=user,
- account_id=self.account_id,
- )
+ owner_fields = owner_fields_for_uri(uri)
self.owner_user_id = (
owner_user_id if owner_user_id is not None else owner_fields["owner_user_id"]
)
- self.owner_space = owner_space or self._derive_owner_space(user)
+ self.owner_space = owner_space or owner_fields["owner_user_id"] or ""
self.vector: Optional[List[float]] = None
self.vectorize = Vectorize(abstract)
- def _derive_owner_space(self, user: Optional[UserIdentifier]) -> str:
- """Best-effort owner space derived from URI and user."""
- if not user:
- return ""
- if self.uri.startswith("viking://user/") or self.uri.startswith("viking://session/"):
- return user.user_id
- return ""
-
def _derive_category(self) -> str:
"""Derive category from URI using substring matching."""
if "/patterns" in self.uri:
diff --git a/openviking/core/namespace.py b/openviking/core/namespace.py
index 2cfdd626a..d3cc6d6a8 100644
--- a/openviking/core/namespace.py
+++ b/openviking/core/namespace.py
@@ -26,7 +26,7 @@ class NamespaceShapeError(ValueError):
@dataclass(frozen=True)
class ResolvedNamespace:
- """Canonicalized namespace information for a URI."""
+ """Namespace information parsed from a canonical URI."""
uri: str
scope: str
@@ -85,12 +85,13 @@ class UriClassification:
def uri_parts(uri: str) -> list[str]:
- """Return normalized Viking URI path segments without query parameters."""
- normalized = VikingURI.normalize(uri.split("?", 1)[0]).rstrip("/")
- if normalized == "viking:":
- normalized = "viking://"
+ """Return canonical Viking URI path segments without query parameters."""
+ normalized = uri.split("?", 1)[0]
+ if not normalized.startswith("viking://"):
+ raise ValueError("URI must start with 'viking://'")
if normalized == "viking://":
return []
+ normalized = normalized.rstrip("/")
return [part for part in normalized[len("viking://") :].split("/") if part]
@@ -122,10 +123,6 @@ def _content_segment_index(parts: tuple[str, ...]) -> Optional[int]:
return 2
if len(parts) < 2 or parts[0] != "user":
return None
- if parts[1] in _CONTENT_TYPES_BY_SCOPE["user"]:
- return 1
- if len(parts) >= 4 and parts[1] == "peers" and parts[3] in _PEER_CONTENT_SEGMENTS:
- return 3
if len(parts) >= 5 and parts[2] == "peers" and parts[4] in _PEER_CONTENT_SEGMENTS:
return 4
if len(parts) >= 3 and parts[2] in _CONTENT_TYPES_BY_SCOPE["user"]:
@@ -176,14 +173,10 @@ def canonical_session_uri(ctx: RequestContext, session_id: Optional[str] = None)
return f"{root}/{session_id}"
-
-
def is_session_uri(uri: str) -> bool:
parts = uri_parts(uri)
if parts[:1] == ["session"]:
return True
- if parts[:2] == ["user", "sessions"]:
- return True
return len(parts) >= 3 and parts[0] == "user" and parts[2] == "sessions"
@@ -222,10 +215,10 @@ def _actor_peer_view_user_suffix(uri: str, ctx: RequestContext) -> Optional[list
if not ctx.actor_peer_id:
return None
try:
- canonical_uri = canonicalize_uri(uri, ctx)
+ resolve_uri(uri)
except NamespaceShapeError:
return None
- parts = uri_parts(canonical_uri)
+ parts = uri_parts(uri)
user_root_parts = ["user", ctx.user.user_id]
if parts[: len(user_root_parts)] != user_root_parts:
return None
@@ -234,30 +227,55 @@ def _actor_peer_view_user_suffix(uri: str, ctx: RequestContext) -> Optional[list
def resolve_uri(
uri: str,
- ctx: Optional[RequestContext] = None,
- *,
- require_canonical: bool = False,
) -> ResolvedNamespace:
- """Resolve a URI into a canonical URI and owner tuple."""
+ """Parse a canonical URI into its namespace and owner tuple."""
+ parsed = VikingURI(uri)
+ canonical_uri = parsed.uri.rstrip("/") or "viking://"
parts = uri_parts(uri)
if not parts:
return ResolvedNamespace(uri="viking://", scope="", is_container=True)
scope = parts[0]
if scope == "user":
- return _resolve_user_uri(parts, ctx=ctx, require_canonical=require_canonical)
+ return _resolve_user_uri(parts)
if scope == "agent":
- return ResolvedNamespace(uri=VikingURI.normalize(uri).rstrip("/"), scope=scope)
+ return ResolvedNamespace(uri=canonical_uri, scope=scope)
if scope == "session":
- return _resolve_session_uri(parts, ctx=ctx, require_canonical=require_canonical)
+ raise NamespaceShapeError(f"Legacy session URI is not canonical: {'/'.join(parts)}")
if scope in {"resources", "temp", "queue", "upload"}:
- return ResolvedNamespace(uri=VikingURI.normalize(uri).rstrip("/"), scope=scope)
- return ResolvedNamespace(uri=VikingURI.normalize(uri).rstrip("/"), scope=scope)
+ return ResolvedNamespace(uri=canonical_uri, scope=scope)
+ return ResolvedNamespace(uri=canonical_uri, scope=scope)
-def canonicalize_uri(uri: str, ctx: Optional[RequestContext] = None) -> str:
- return resolve_uri(uri, ctx=ctx).uri
+def resolve_request_uri(uri: str, ctx: RequestContext) -> str:
+ """Resolve supported current-user shorthands at an authenticated request boundary."""
+ if getattr(ctx.role, "value", ctx.role) == "user":
+ 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."""
+ parts = uri_parts(uri)
+ if not parts:
+ return "viking://"
+
+ if parts[0] == "session":
+ if len(parts) == 1:
+ return canonical_session_root(ctx)
+ canonical = canonical_session_uri(ctx, parts[1])
+ if len(parts) > 2:
+ 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:])}"
+
+ return resolve_uri(uri).uri
def is_accessible(uri: str, ctx: RequestContext) -> bool:
@@ -265,7 +283,7 @@ def is_accessible(uri: str, ctx: RequestContext) -> bool:
return True
try:
- target = resolve_uri(uri, ctx=ctx)
+ target = resolve_uri(uri)
except NamespaceShapeError:
return False
@@ -287,30 +305,24 @@ def is_accessible(uri: str, ctx: RequestContext) -> bool:
def is_content_root_uri(
uri: str,
- ctx: RequestContext,
*,
kind: str,
) -> bool:
try:
- canonical_uri = canonicalize_uri(uri, ctx)
+ resolve_uri(uri)
except (ValueError, NamespaceShapeError):
return False
- parts = uri_parts(canonical_uri)
+ parts = uri_parts(uri)
if kind == "resource" and parts == ["resources"]:
return True
- classification = classify_uri(canonical_uri)
+ classification = classify_uri(uri)
return (
classification.context_type == kind
and classification.content_index is not None
and len(parts) == classification.content_index + 1
)
-
-
def _validate_peer_id_segments(parts: list[str]) -> None:
- if len(parts) >= 3 and parts[0] == "user" and parts[1] == "peers":
- _require_peer_id_segment(parts[2])
- return
if len(parts) >= 4 and parts[0] == "user" and parts[2] == "peers":
_require_peer_id_segment(parts[3])
@@ -325,33 +337,12 @@ def _require_peer_id_segment(peer_id: str) -> None:
def owner_fields_for_uri(
uri: str,
- ctx: Optional[RequestContext] = None,
- *,
- user=None,
- account_id: Optional[str] = None,
) -> dict:
- resolved_ctx = ctx
- if resolved_ctx is None and user is not None:
- from openviking.server.identity import Role
-
- resolved_ctx = RequestContext(
- user=user,
- role=Role.ROOT,
- )
- if resolved_ctx is None and account_id:
- from openviking.server.identity import Role
- from openviking_cli.session.user_id import UserIdentifier
-
- resolved_ctx = RequestContext(
- user=UserIdentifier(account_id, "default"),
- role=Role.ROOT,
- )
-
try:
- resolved = resolve_uri(uri, ctx=resolved_ctx)
- except NamespaceShapeError:
+ resolved = resolve_uri(uri)
+ except (ValueError, NamespaceShapeError):
return {
- "uri": VikingURI.normalize(uri).rstrip("/"),
+ "uri": uri.rstrip("/"),
"owner_user_id": None,
}
return {
@@ -361,46 +352,33 @@ def owner_fields_for_uri(
def content_owner_context_for_uri(uri: str, ctx: RequestContext) -> RequestContext:
- """Use the URI owner for user-scoped content writes while retaining caller authority."""
- owner = owner_fields_for_uri(uri, ctx=ctx).get("owner_user_id")
- if not owner or owner == ctx.user.user_id:
+ """Use the canonical URI owner for content writes performed with caller authority."""
+ owner_user_id = owner_fields_for_uri(uri).get("owner_user_id")
+ if not owner_user_id or owner_user_id == ctx.user.user_id:
return ctx
return RequestContext(
- user=UserIdentifier(ctx.account_id, owner),
+ user=UserIdentifier(ctx.account_id, owner_user_id),
role=ctx.role,
actor_peer_id=ctx.actor_peer_id,
from_oauth=ctx.from_oauth,
+ api_key=ctx.api_key,
)
-def owner_space_for_uri(uri: str, ctx: RequestContext) -> str:
- """Derive the legacy owner_space bucket for vector records from URI scope and context."""
- parts = uri_parts(uri)
- if parts[:1] in (["user"], ["session"]):
- return user_space_fragment(ctx)
+def owner_space_for_uri(uri: str) -> str:
+ """Derive the legacy owner_space bucket from the canonical URI owner."""
+ resolved = resolve_uri(uri)
+ if resolved.scope == "user" and resolved.owner_user_id:
+ return resolved.owner_user_id
return ""
def _resolve_user_uri(
parts: list[str],
- ctx: Optional[RequestContext],
- *,
- require_canonical: bool,
) -> ResolvedNamespace:
- normalized = "viking://" + "/".join(parts)
if len(parts) == 1:
return ResolvedNamespace(uri="viking://user", scope="user", is_container=True)
- if _is_current_user_relative_uri(parts, ctx):
- if require_canonical:
- raise NamespaceShapeError(f"Shorthand user URI is not allowed here: {normalized}")
- if ctx is None:
- raise NamespaceShapeError(f"User shorthand URI requires request context: {normalized}")
- suffix = parts[1:]
- return resolve_uri(
- "/".join([canonical_user_root(ctx)[len("viking://") :], *suffix]), ctx=ctx
- )
-
second = parts[1]
user_id = second
validation_error = validate_user_id(user_id)
@@ -425,50 +403,5 @@ def _resolve_user_uri(
)
-def _is_current_user_relative_uri(parts: list[str], ctx: Optional[RequestContext]) -> bool:
- if len(parts) < 2 or parts[0] != "user":
- return False
- if ctx is not None and parts[1] == ctx.user.user_id:
- return False
- return _is_user_relative_root_segment(parts[1])
-
-
def _is_user_relative_root_segment(segment: str) -> bool:
return segment in _CONTENT_TYPES_BY_SCOPE["user"] or segment in _USER_RELATIVE_ROOT_SEGMENTS
-
-
-def _resolve_session_uri(
- parts: list[str],
- ctx: Optional[RequestContext],
- *,
- require_canonical: bool,
-) -> ResolvedNamespace:
- normalized = "viking://" + "/".join(parts)
- if require_canonical:
- raise NamespaceShapeError(f"Legacy session URI is not allowed here: {normalized}")
- if ctx is not None:
- if len(parts) == 1:
- return ResolvedNamespace(
- uri=canonical_session_uri(ctx),
- scope="user",
- owner_user_id=ctx.user.user_id,
- is_container=True,
- )
- session_id = parts[1]
- suffix = parts[2:]
- canonical = canonical_session_uri(ctx, session_id)
- if suffix:
- canonical = f"{canonical}/{'/'.join(suffix)}"
- return ResolvedNamespace(
- uri=canonical,
- scope="user",
- owner_user_id=ctx.user.user_id,
- )
-
- if len(parts) == 1:
- return ResolvedNamespace(uri="viking://session", scope="session", is_container=True)
- session_id = parts[1]
- canonical = f"viking://session/{session_id}"
- if len(parts) > 2:
- canonical = f"{canonical}/{'/'.join(parts[2:])}"
- return ResolvedNamespace(uri=canonical, scope="session")
diff --git a/openviking/core/retrieval_targets.py b/openviking/core/retrieval_targets.py
index 410bc5a88..f22532d7c 100644
--- a/openviking/core/retrieval_targets.py
+++ b/openviking/core/retrieval_targets.py
@@ -6,9 +6,7 @@ from dataclasses import dataclass
from typing import List, Optional, Union
from openviking.core.namespace import (
- NamespaceShapeError,
canonical_user_root,
- canonicalize_uri,
is_hidden_by_actor_peer_view,
uri_parts,
)
@@ -16,7 +14,6 @@ from openviking.core.peer_id import normalize_peer_id
from openviking.server.identity import RequestContext, Role
from openviking_cli.exceptions import InvalidArgumentError, PermissionDeniedError
from openviking_cli.retrieve import ContextType
-from openviking_cli.utils.uri import VikingURI
@dataclass(frozen=True)
@@ -32,7 +29,7 @@ def resolve_retrieval_targets(
ctx: RequestContext,
) -> ResolvedRetrievalTargets:
"""Resolve search/find target directories."""
- target_uris = _canonicalize_target_uris(target_uri, ctx)
+ target_uris = _dedupe_target_uris(target_uri)
if not target_uris:
return ResolvedRetrievalTargets(
@@ -86,21 +83,14 @@ def default_target_directories(
return [user_root, "viking://resources"]
-def _canonicalize_target_uris(
- target_uri: Union[str, List[str]],
- ctx: RequestContext,
-) -> List[str]:
+def _dedupe_target_uris(target_uri: Union[str, List[str]]) -> List[str]:
target_uri_list = [target_uri] if isinstance(target_uri, str) else (target_uri or [])
target_uris: List[str] = []
for item in target_uri_list:
if not item or item in {"/", "viking://"}:
continue
- try:
- target_uri = canonicalize_uri(item, ctx)
- except NamespaceShapeError as exc:
- raise InvalidArgumentError(str(exc)) from exc
- if target_uri not in target_uris:
- target_uris.append(target_uri)
+ if item not in target_uris:
+ target_uris.append(item)
return target_uris
@@ -213,13 +203,8 @@ def _dedupe(items: List[str]) -> List[str]:
def _is_current_user_root(target_uri: str, ctx: RequestContext) -> bool:
- normalized = VikingURI.normalize(target_uri).rstrip("/")
- return normalized in {"viking://user", canonical_user_root(ctx).rstrip("/")}
+ return target_uri.rstrip("/") == canonical_user_root(ctx).rstrip("/")
def _is_default_user_content_root(target_uri: str, ctx: RequestContext, segment: str) -> bool:
- normalized = VikingURI.normalize(target_uri).rstrip("/")
- return normalized in {
- f"viking://user/{segment}",
- f"{canonical_user_root(ctx).rstrip('/')}/{segment}",
- }
+ return target_uri.rstrip("/") == f"{canonical_user_root(ctx).rstrip('/')}/{segment}"
diff --git a/openviking/core/uri_validation.py b/openviking/core/uri_validation.py
index 78b050065..e72e6a5d7 100644
--- a/openviking/core/uri_validation.py
+++ b/openviking/core/uri_validation.py
@@ -2,37 +2,23 @@
# SPDX-License-Identifier: AGPL-3.0
"""Validation helpers for externally supplied Viking URI fields."""
-import re
from collections.abc import Collection
from openviking.core.namespace import (
NamespaceShapeError,
- canonicalize_uri,
classify_uri,
is_accessible,
+ resolve_request_uri,
uri_parts,
)
from openviking_cli.exceptions import InvalidURIError, PermissionDeniedError
from openviking_cli.utils.uri import VikingURI
-_URI_SCHEME_RE = re.compile(r"^[A-Za-z][A-Za-z0-9+.-]*:")
_PUBLIC_API_SCOPES = frozenset({"", *VikingURI.PUBLIC_SCOPES, *VikingURI.LEGACY_SCOPES})
_ALL_API_SCOPES = frozenset({"", *VikingURI.VISITABLE_SCOPES})
-def _scope_from_uri(uri: str) -> str:
- normalized = uri if uri.startswith(f"{VikingURI.SCHEME}://") else VikingURI.normalize(uri)
- path = normalized[len(f"{VikingURI.SCHEME}://") :]
- if not path.strip("/"):
- return ""
- return path.split("/")[0]
-
-
-def _format_scope_names(scopes: Collection[str]) -> str:
- return ", ".join(sorted(scope for scope in scopes if scope))
-
-
-def _scope_set(
+def _allowed_api_scopes(
*,
allow_internal: bool,
allowed_scopes: Collection[str] | str | None,
@@ -44,13 +30,6 @@ def _scope_set(
return _ALL_API_SCOPES if allow_internal else _PUBLIC_API_SCOPES
-def _invalid_scope_reason(scope: str, allowed_scopes: Collection[str]) -> str:
- scope_names = _format_scope_names(allowed_scopes)
- if not scope:
- return f"URI must include one of: {scope_names}"
- return f"Invalid scope '{scope}'. Must be one of: {scope_names}"
-
-
def validate_viking_uri(
uri: str,
*,
@@ -58,62 +37,47 @@ def validate_viking_uri(
allow_internal: bool = False,
allowed_scopes: Collection[str] | str | None = None,
) -> str:
- """Validate a user-supplied Viking URI or supported short-format URI.
-
- Short formats such as ``resources/docs`` are allowed for existing CLI/API
- compatibility. Explicit non-viking schemes such as ``s3://`` or malformed
- viking schemes such as ``viking:/`` are rejected as INVALID_URI. Internal
- scopes such as ``temp`` and ``queue`` are rejected by default at the API
- boundary unless ``allow_internal`` or an explicit ``allowed_scopes`` is used.
- """
+ """Validate a user-supplied URI in explicit ``viking://`` form."""
raw_uri = uri.strip() if isinstance(uri, str) else ""
if not raw_uri:
raise InvalidURIError(str(uri), f"{field_name} must not be empty")
- scheme_match = _URI_SCHEME_RE.match(raw_uri)
- if scheme_match and not raw_uri.startswith(f"{VikingURI.SCHEME}://"):
- scheme = scheme_match.group(0)[:-1]
- if scheme == VikingURI.SCHEME:
- reason = f"URI must start with '{VikingURI.SCHEME}://'"
- else:
- reason = f"unsupported URI scheme '{scheme}'"
- raise InvalidURIError(raw_uri, reason)
-
- scopes = _scope_set(allow_internal=allow_internal, allowed_scopes=allowed_scopes)
-
try:
parsed = VikingURI(raw_uri)
except ValueError as exc:
- reason = str(exc)
- if reason.startswith("Invalid scope"):
- reason = _invalid_scope_reason(_scope_from_uri(raw_uri), scopes)
- raise InvalidURIError(raw_uri, reason) from exc
+ raise InvalidURIError(raw_uri, str(exc)) from exc
+ scopes = _allowed_api_scopes(allow_internal=allow_internal, allowed_scopes=allowed_scopes)
if parsed.scope not in scopes:
- raise InvalidURIError(raw_uri, _invalid_scope_reason(parsed.scope, scopes))
+ scope_names = ", ".join(sorted(scope for scope in scopes if scope))
+ if not parsed.scope:
+ reason = f"URI must include one of: {scope_names}"
+ else:
+ reason = f"Invalid scope '{parsed.scope}'. Must be one of: {scope_names}"
+ raise InvalidURIError(raw_uri, reason)
return raw_uri
-def validate_optional_viking_uri(
- uri: str | None,
+def validate_request_viking_uri(
+ uri: str,
+ ctx,
*,
field_name: str = "uri",
allow_internal: bool = False,
allowed_scopes: Collection[str] | str | None = None,
) -> str:
- """Validate an optional Viking URI field, preserving empty-as-unspecified."""
- if uri is None:
- return ""
- raw_uri = uri.strip() if isinstance(uri, str) else ""
- if not raw_uri:
- return ""
- return validate_viking_uri(
- raw_uri,
+ """Validate an external URI and resolve supported aliases using request identity."""
+ raw_uri = validate_viking_uri(
+ uri,
field_name=field_name,
allow_internal=allow_internal,
allowed_scopes=allowed_scopes,
)
+ try:
+ return resolve_request_uri(raw_uri, ctx)
+ except (ValueError, NamespaceShapeError) as exc:
+ raise InvalidURIError(raw_uri, str(exc)) from exc
def validate_content_target_uri(
@@ -128,10 +92,7 @@ def validate_content_target_uri(
if not raw_uri:
raise InvalidURIError(str(uri), f"{field_name} must not be empty")
- try:
- canonical_uri = canonicalize_uri(raw_uri, ctx)
- except (ValueError, NamespaceShapeError) as exc:
- raise InvalidURIError(raw_uri, str(exc)) from exc
+ canonical_uri = validate_request_viking_uri(raw_uri, ctx, field_name=field_name)
if _matches_content_kind(canonical_uri, kind):
if is_accessible(canonical_uri, ctx):
@@ -141,26 +102,6 @@ def validate_content_target_uri(
raise InvalidURIError(raw_uri, f"{field_name} must target {kind} content")
-def validate_optional_content_target_uri(
- uri: str | None,
- ctx,
- *,
- kind: str,
- field_name: str = "uri",
-) -> str:
- if uri is None:
- return ""
- raw_uri = uri.strip() if isinstance(uri, str) else ""
- if not raw_uri:
- return ""
- return validate_content_target_uri(
- raw_uri,
- ctx,
- kind=kind,
- field_name=field_name,
- )
-
-
def _matches_content_kind(uri: str, kind: str) -> bool:
if kind not in {"resource", "skill"}:
raise ValueError(f"Unsupported content target kind: {kind}")
@@ -169,39 +110,3 @@ def _matches_content_kind(uri: str, kind: str) -> bool:
return True
classification = classify_uri(uri)
return classification.context_type == kind and classification.content_index is not None
-
-
-def validate_optional_viking_uris(
- uri: str | list[str] | None,
- *,
- field_name: str = "uri",
- allow_internal: bool = False,
- allowed_scopes: Collection[str] | str | None = None,
-) -> str | list[str]:
- """Validate an optional Viking URI field that may be a single URI or a list.
-
- Like :func:`validate_optional_viking_uri` but also accepts ``list[str]``.
- Returns a validated ``str`` when the input is a single URI, or a
- ``list[str]`` with each element validated when the input is a list.
- Empty / ``None`` inputs produce ``""``; empty lists produce ``[]``.
- """
- if uri is None:
- return ""
- if isinstance(uri, list):
- validated: list[str] = []
- for item in uri:
- result = validate_optional_viking_uri(
- item,
- field_name=field_name,
- allow_internal=allow_internal,
- allowed_scopes=allowed_scopes,
- )
- if result:
- validated.append(result)
- return validated
- return validate_optional_viking_uri(
- uri,
- field_name=field_name,
- allow_internal=allow_internal,
- allowed_scopes=allowed_scopes,
- )
diff --git a/openviking/parse/tree_builder.py b/openviking/parse/tree_builder.py
index a44109813..7ada17124 100644
--- a/openviking/parse/tree_builder.py
+++ b/openviking/parse/tree_builder.py
@@ -73,9 +73,6 @@ class TreeBuilder:
if media_type:
return get_media_base_uri(media_type)
return "viking://resources"
- if scope == "user":
- # user resources go to memories (no separate resources dir)
- return "viking://user"
raise ValueError(f"unsupported tree scope: {scope}")
# ============================================================================
@@ -104,7 +101,7 @@ class TreeBuilder:
auto_base_uri = self._get_base_uri(scope, source_path, source_format)
base_uri = parent_uri or auto_base_uri
- use_to_as_parent = bool(to_uri and is_content_root_uri(to_uri, ctx, kind="resource"))
+ use_to_as_parent = bool(to_uri and is_content_root_uri(to_uri, kind="resource"))
if to_uri and not use_to_as_parent:
return to_uri, None
@@ -115,7 +112,6 @@ class TreeBuilder:
viking_fs = get_viking_fs()
parent_is_content_root = is_content_root_uri(
effective_parent_uri,
- ctx,
kind="resource",
)
try:
diff --git a/openviking/server/config.py b/openviking/server/config.py
index 0bdd74889..cd9ed4138 100644
--- a/openviking/server/config.py
+++ b/openviking/server/config.py
@@ -55,13 +55,11 @@ class AddTargetsConfig(BaseModel):
return None
from openviking.core.namespace import classify_uri, uri_parts
from openviking.core.uri_validation import validate_viking_uri
- from openviking_cli.utils.uri import VikingURI
-
validate_viking_uri(uri, field_name="resource_uri")
- normalized = VikingURI.normalize(uri).rstrip("/")
+ normalized = uri.rstrip("/")
parts = uri_parts(normalized)
classification = classify_uri(normalized)
- if parts[:1] == ["resources"] or (
+ 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
@@ -75,12 +73,20 @@ class AddTargetsConfig(BaseModel):
uri = _normalize_config_uri(value, "skill_uri")
if uri is None:
return None
- from openviking_cli.utils.uri import VikingURI
+ from openviking.core.namespace import uri_parts
+ from openviking.core.uri_validation import validate_viking_uri
- normalized = VikingURI.normalize(uri).rstrip("/")
- if normalized in {"viking://user/skills", "viking://agent/skills"}:
+ 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 (
+ len(parts) == 3 and parts[0] == "user" and parts[2] == "skills"
+ ):
return normalized
- raise ValueError("skill_uri must be viking://user/skills or viking://agent/skills")
+ raise ValueError(
+ "skill_uri must be viking://user/skills, viking://user/{user_id}/skills, "
+ "or viking://agent/skills"
+ )
class AgentEvolutionConfig(BaseModel):
diff --git a/openviking/server/mcp_endpoint.py b/openviking/server/mcp_endpoint.py
index c6553146c..a4e79aa29 100644
--- a/openviking/server/mcp_endpoint.py
+++ b/openviking/server/mcp_endpoint.py
@@ -30,7 +30,11 @@ from starlette.requests import Request
from starlette.responses import JSONResponse
from starlette.types import ASGIApp, Receive, Scope, Send
-from openviking.core.namespace import canonical_user_root, canonicalize_uri, uri_parts
+from openviking.core.path_variables import resolve_path_variables
+from openviking.core.uri_validation import (
+ validate_content_target_uri,
+ validate_request_viking_uri,
+)
from openviking.parse.mode import ParseMode, normalize_parse_mode
from openviking.resource.processing_mode import DEFAULT_PROCESSING_MODE, ProcessingMode
from openviking.retrieve.context_assembler import (
@@ -87,22 +91,8 @@ def _get_ctx() -> RequestContext:
def _resolve_mcp_workspace_uri(uri: str, ctx: RequestContext) -> str:
- """Resolve ``viking://user/...`` as the current user's MCP workspace.
-
- Generic namespace parsing must preserve canonical cross-user URIs, so it
- cannot infer whether the first segment after ``user`` is a user id or a
- file/directory name. MCP has a narrower contract: its filesystem tools act
- on the authenticated user's workspace. An exact current-user id is already
- canonical; every other suffix is relative to that user's root.
- """
- parts = uri_parts(uri)
- if parts[:1] != ["user"]:
- return uri
- suffix = parts[1:]
- if suffix[:1] == [ctx.user.user_id]:
- return canonicalize_uri(uri, ctx)
- root = canonical_user_root(ctx)
- return root if not suffix else f"{root}/{'/'.join(suffix)}"
+ """Resolve MCP's current-user workspace dialect at its request boundary."""
+ return validate_request_viking_uri(resolve_path_variables(uri), ctx)
def _scope_to_origin(scope: Scope) -> Optional[str]:
@@ -566,7 +556,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/ (all paths are relative to the authenticated user's root unless the URI already contains that exact user id), viking://agent/. 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/. 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."""
service = get_service()
ctx = _get_ctx()
uri = _resolve_mcp_workspace_uri(uri, ctx)
@@ -801,6 +791,21 @@ async def add_resource(
service = get_service()
ctx = _get_ctx()
+ try:
+ to = resolve_path_variables(to).strip() if to else ""
+ if to:
+ to = validate_content_target_uri(to, ctx, kind="resource", field_name="to")
+ parent = resolve_path_variables(parent).strip() if parent else ""
+ if parent:
+ parent = validate_content_target_uri(
+ parent,
+ ctx,
+ kind="resource",
+ field_name="parent",
+ )
+ except (InvalidArgumentError, PermissionDeniedError) as exc:
+ return f"Error: {exc}"
+
try:
mode = normalize_parse_mode((args or {}).get("parse_mode", ParseMode.DEFAULT))
except InvalidArgumentError as exc:
@@ -1019,6 +1024,7 @@ async def cancel_watch(to_uri: str) -> str:
service = get_service()
ctx = _get_ctx()
+ to_uri = _resolve_mcp_workspace_uri(to_uri, ctx)
scheduler = getattr(service, "watch_scheduler", None)
if scheduler is None or not scheduler.is_running:
return "Error: Watch scheduler not running"
diff --git a/openviking/server/openviking_assets.py b/openviking/server/openviking_assets.py
index 4f54b562e..0fdba11be 100644
--- a/openviking/server/openviking_assets.py
+++ b/openviking/server/openviking_assets.py
@@ -161,7 +161,7 @@ def _normalize_asset_target_uri(
raise InvalidArgumentError(f"{where}: 'to' must be a non-empty string when set")
if ctx is not None:
- # Use the same canonicalization, namespace-shape and access checks as
+ # 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.
return validate_content_target_uri(target, ctx, kind="resource", field_name="to")
diff --git a/openviking/server/routers/agent_evolution.py b/openviking/server/routers/agent_evolution.py
index ea1d8f83f..00ac6f5d4 100644
--- a/openviking/server/routers/agent_evolution.py
+++ b/openviking/server/routers/agent_evolution.py
@@ -4,6 +4,7 @@
from fastapi import APIRouter, Depends, Query
+from openviking.core.uri_validation import validate_request_viking_uri
from openviking.server.auth import get_request_context
from openviking.server.dependencies import get_service
from openviking.server.identity import RequestContext
@@ -31,6 +32,7 @@ async def list_experience_trajectories(
):
"""List trajectories produced by commits that read an Experience."""
service = get_service()
+ experience_uri = validate_request_viking_uri(experience_uri, _ctx)
result = await service.agent_evolution.list_trajectories_by_experience(
experience_uri=experience_uri,
ctx=_ctx,
@@ -51,6 +53,7 @@ async def get_experience_outcome_distribution(
):
"""Count application trajectories by outcome for an Experience."""
service = get_service()
+ experience_uri = validate_request_viking_uri(experience_uri, _ctx)
result = await service.agent_evolution.get_experience_outcome_distribution(
experience_uri=experience_uri,
ctx=_ctx,
diff --git a/openviking/server/routers/content.py b/openviking/server/routers/content.py
index 4bf4976f4..d3e9e5a6e 100644
--- a/openviking/server/routers/content.py
+++ b/openviking/server/routers/content.py
@@ -10,13 +10,12 @@ from fastapi.responses import Response as FastAPIResponse
from pydantic import BaseModel, ConfigDict, model_validator
from openviking.core.namespace import (
- canonicalize_uri,
is_hidden_by_actor_peer_view,
may_include_hidden_actor_peers,
resolve_uri,
)
from openviking.core.path_variables import resolve_path_variables
-from openviking.core.uri_validation import validate_viking_uri
+from openviking.core.uri_validation import validate_request_viking_uri
from openviking.pyagfs.exceptions import AGFSClientError, AGFSNotFoundError
from openviking.resource.processing_mode import DEFAULT_PROCESSING_MODE, ProcessingMode
from openviking.server.auth import (
@@ -115,31 +114,23 @@ class ReindexRequest(BaseModel):
router = APIRouter(prefix="/api/v1/content", tags=["content"])
-def _validate_reindex_uri(uri: str) -> str:
- raw_uri = uri.strip() if isinstance(uri, str) else ""
- if raw_uri.startswith("viking://"):
- return raw_uri
- return validate_viking_uri(raw_uri)
-
-
def _authorize_reindex_uri(uri: str, ctx: RequestContext) -> str:
"""Allow users to reindex only their own private namespace."""
if ctx.role != Role.USER:
return uri
- canonical_uri = canonicalize_uri(uri, ctx)
- target = resolve_uri(canonical_uri, ctx=ctx, require_canonical=True)
+ target = resolve_uri(uri)
if (
target.scope != "user"
or target.owner_user_id != ctx.user.user_id
- or is_hidden_by_actor_peer_view(canonical_uri, ctx)
- or may_include_hidden_actor_peers(canonical_uri, ctx)
+ or is_hidden_by_actor_peer_view(uri, ctx)
+ or may_include_hidden_actor_peers(uri, ctx)
):
raise PermissionDeniedError(
"USER can only reindex their own user namespace.",
- resource=canonical_uri,
+ resource=uri,
)
- return canonical_uri
+ return uri
@router.get("/read")
@@ -152,7 +143,7 @@ async def read(
):
"""Read file content (L2)."""
service = get_service()
- uri = resolve_path_variables(uri)
+ uri = validate_request_viking_uri(resolve_path_variables(uri), _ctx)
try:
if raw:
result = await service.fs.read(uri, ctx=_ctx, offset=offset, limit=limit)
@@ -176,7 +167,7 @@ async def abstract(
):
"""Read L0 abstract."""
service = get_service()
- uri = resolve_path_variables(uri)
+ uri = validate_request_viking_uri(resolve_path_variables(uri), _ctx)
try:
result = await service.fs.abstract(uri, ctx=_ctx)
except AGFSNotFoundError:
@@ -196,7 +187,7 @@ async def overview(
):
"""Read L1 overview."""
service = get_service()
- uri = resolve_path_variables(uri)
+ uri = validate_request_viking_uri(resolve_path_variables(uri), _ctx)
try:
result = await service.fs.overview(uri, ctx=_ctx)
except AGFSNotFoundError:
@@ -216,7 +207,7 @@ async def download(
):
"""Download file as raw bytes (for images, binaries, etc.)."""
service = get_service()
- uri = resolve_path_variables(uri)
+ uri = validate_request_viking_uri(resolve_path_variables(uri), _ctx)
try:
content = await service.fs.read_file_bytes(uri, ctx=_ctx)
except AGFSNotFoundError:
@@ -250,7 +241,7 @@ async def write(
):
"""Write text content to a file (replace, append, or create) and refresh semantics/vectors."""
service = get_service()
- uri = resolve_path_variables(request.uri)
+ uri = validate_request_viking_uri(resolve_path_variables(request.uri), _ctx)
execution = await run_operation(
operation="content.write",
telemetry=request.telemetry,
@@ -278,10 +269,12 @@ async def batch_write(
):
"""Apply preconditioned file writes and refresh their indexes as one request."""
service = get_service()
- root_uri = resolve_path_variables(request.root_uri)
+ root_uri = validate_request_viking_uri(resolve_path_variables(request.root_uri), _ctx)
operations = [operation.model_dump(exclude_none=True) for operation in request.operations]
for operation in operations:
- operation["uri"] = resolve_path_variables(operation["uri"])
+ operation["uri"] = validate_request_viking_uri(
+ resolve_path_variables(operation["uri"]), _ctx
+ )
execution = await run_operation(
operation="content.batch_write",
telemetry=request.telemetry,
@@ -307,7 +300,7 @@ async def set_tags(
):
"""Set explicit k=v retrieval tags metadata for a file or directory."""
service = get_service()
- uri = resolve_path_variables(request.uri)
+ uri = validate_request_viking_uri(resolve_path_variables(request.uri), _ctx)
execution = await run_operation(
operation="content.set_tags",
telemetry=request.telemetry,
@@ -334,8 +327,7 @@ async def reindex(
"""Reindex semantic/vector artifacts for a URI-scoped maintenance target."""
if body.dry_run and body.mode != "prune_orphans":
raise InvalidArgumentError("dry_run is only supported for prune_orphans reindex mode.")
- uri = resolve_path_variables(body.uri)
- uri = _validate_reindex_uri(uri)
+ uri = validate_request_viking_uri(resolve_path_variables(body.uri), ctx)
uri = _authorize_reindex_uri(uri, ctx)
service = get_service()
reindex_kwargs = {
diff --git a/openviking/server/routers/debug.py b/openviking/server/routers/debug.py
index dad71b7e5..6f8114359 100644
--- a/openviking/server/routers/debug.py
+++ b/openviking/server/routers/debug.py
@@ -13,10 +13,11 @@ from typing import Optional
from fastapi import APIRouter, Depends, Query
from openviking.core.path_variables import resolve_path_variables
+from openviking.core.uri_validation import validate_request_viking_uri
from openviking.server.auth import get_request_context
from openviking.server.dependencies import get_service
from openviking.server.identity import RequestContext
-from openviking.server.models import ErrorInfo, Response
+from openviking.server.models import Response
from openviking.server.responses import error_response
from openviking.storage.vikingdb_manager import VikingDBManagerProxy
@@ -52,7 +53,7 @@ async def debug_vector_scroll(
filter_expr = None
if uri:
# Resolve path variables before using URI
- uri = resolve_path_variables(uri)
+ uri = validate_request_viking_uri(resolve_path_variables(uri), _ctx)
filter_expr = {"op": "must", "field": "uri", "conds": [uri]}
records, next_cursor = await proxy.scroll(filter=filter_expr, limit=limit, cursor=cursor)
@@ -88,7 +89,7 @@ async def debug_vector_count(
if uri:
# Resolve path variables before using URI
- uri = resolve_path_variables(uri)
+ uri = validate_request_viking_uri(resolve_path_variables(uri), _ctx)
uri_filter = {"op": "must", "field": "uri", "conds": [uri]}
if filter_expr:
# For combining filters, we should use And from expr, but for simplicity, let's use RawDSL for now
diff --git a/openviking/server/routers/filesystem.py b/openviking/server/routers/filesystem.py
index 557f98b2b..17b674d1a 100644
--- a/openviking/server/routers/filesystem.py
+++ b/openviking/server/routers/filesystem.py
@@ -7,8 +7,9 @@ from typing import Any, Literal, Optional
from fastapi import APIRouter, Body, Depends, Query
from pydantic import BaseModel
-from openviking.core.namespace import NamespaceShapeError, canonicalize_uri, context_type_for_uri
+from openviking.core.namespace import context_type_for_uri
from openviking.core.path_variables import resolve_path_variables
+from openviking.core.uri_validation import validate_request_viking_uri
from openviking.pyagfs.exceptions import AGFSClientError, AGFSNotFoundError
from openviking.server.auth import get_request_context
from openviking.server.dependencies import get_service
@@ -19,7 +20,7 @@ from openviking.server.routers.content import SetTagsRequest
from openviking.server.routers.content import set_tags as content_set_tags
from openviking.storage.expr import And, Eq, In
from openviking.storage.vikingdb_manager import VikingDBManagerProxy
-from openviking_cli.exceptions import InvalidArgumentError, NotFoundError
+from openviking_cli.exceptions import NotFoundError
router = APIRouter(prefix="/api/v1/fs", tags=["filesystem"])
@@ -85,7 +86,7 @@ async def ls(
service = get_service()
actual_node_limit = limit if limit is not None else node_limit
# Resolve path variables
- uri = resolve_path_variables(uri)
+ uri = validate_request_viking_uri(resolve_path_variables(uri), _ctx)
try:
result = await service.fs.ls(
uri,
@@ -124,7 +125,7 @@ async def tree(
service = get_service()
actual_node_limit = limit if limit is not None else node_limit
# Resolve path variables
- uri = resolve_path_variables(uri)
+ uri = validate_request_viking_uri(resolve_path_variables(uri), _ctx)
try:
result = await service.fs.tree(
uri,
@@ -153,7 +154,7 @@ async def stat(
"""Get resource status."""
service = get_service()
# Resolve path variables
- uri = resolve_path_variables(uri)
+ uri = validate_request_viking_uri(resolve_path_variables(uri), _ctx)
try:
result = await service.fs.stat(uri, ctx=_ctx)
return Response(status="ok", result=result)
@@ -178,26 +179,21 @@ async def attrs(
):
"""Get logical extended attributes for a URI."""
service = get_service()
- uri = resolve_path_variables(uri)
+ uri = validate_request_viking_uri(resolve_path_variables(uri), _ctx)
try:
stat_result = await service.fs.stat(uri, ctx=_ctx)
- try:
- canonical_uri = canonicalize_uri(uri, _ctx)
- except NamespaceShapeError as exc:
- raise InvalidArgumentError(str(exc)) from exc
-
result = {
- "uri": canonical_uri,
- "context_type": context_type_for_uri(canonical_uri),
+ "uri": uri,
+ "context_type": context_type_for_uri(uri),
"attrs": {
"tags": await _tags_attr(
- service, canonical_uri, _ctx, is_dir=stat_result.get("isDir", False)
+ service, uri, _ctx, is_dir=stat_result.get("isDir", False)
),
},
}
if result["context_type"] == "memory" and not stat_result.get("isDir", False):
result["attrs"]["memory"] = _clean_memory_attrs(
- await service.fs.read(canonical_uri, ctx=_ctx)
+ await service.fs.read(uri, ctx=_ctx)
)
return Response(status="ok", result=result)
except AGFSNotFoundError:
@@ -238,7 +234,7 @@ async def mkdir(
"""Create directory."""
service = get_service()
# Resolve path variables
- uri = resolve_path_variables(request.uri)
+ uri = validate_request_viking_uri(resolve_path_variables(request.uri), _ctx)
try:
await service.fs.mkdir(uri, ctx=_ctx, description=request.description)
except AGFSClientError as e:
@@ -260,7 +256,7 @@ async def rm(
"""Remove resource."""
service = get_service()
# Resolve path variables
- uri = resolve_path_variables(uri)
+ uri = validate_request_viking_uri(resolve_path_variables(uri), _ctx)
try:
result = await service.fs.rm(uri, ctx=_ctx, recursive=recursive, wait=wait, timeout=timeout)
except AGFSNotFoundError:
@@ -305,8 +301,12 @@ async def mv(
"""Move resource."""
service = get_service()
# Resolve path variables
- from_uri = resolve_path_variables(request.from_uri)
- to_uri = resolve_path_variables(request.to_uri)
+ from_uri = validate_request_viking_uri(
+ resolve_path_variables(request.from_uri), _ctx, field_name="from_uri"
+ )
+ to_uri = validate_request_viking_uri(
+ resolve_path_variables(request.to_uri), _ctx, field_name="to_uri"
+ )
try:
await service.fs.mv(from_uri, to_uri, ctx=_ctx)
except AGFSNotFoundError:
diff --git a/openviking/server/routers/pack.py b/openviking/server/routers/pack.py
index 56b266c07..85d5ea3c5 100644
--- a/openviking/server/routers/pack.py
+++ b/openviking/server/routers/pack.py
@@ -12,6 +12,7 @@ from pydantic import BaseModel, ConfigDict
from starlette.background import BackgroundTask
from openviking.core.path_variables import resolve_path_variables
+from openviking.core.uri_validation import validate_request_viking_uri
from openviking.server.auth import (
get_request_context,
require_auth_role,
@@ -81,7 +82,7 @@ async def export_ovpack(
service = get_service()
# Resolve path variables
- uri = resolve_path_variables(body.uri)
+ uri = validate_request_viking_uri(resolve_path_variables(body.uri), ctx)
# Create temp file for export
temp_dir = tempfile.gettempdir()
@@ -175,7 +176,9 @@ async def import_ovpack(
resolved = await store.resolve_for_consume(body.temp_file_id, ctx)
# Resolve path variables
- parent = resolve_path_variables(body.parent)
+ parent = validate_request_viking_uri(
+ resolve_path_variables(body.parent), ctx, field_name="parent"
+ )
try:
result = await service.pack.import_ovpack(
diff --git a/openviking/server/routers/resources.py b/openviking/server/routers/resources.py
index a254cf6bb..be9bd3944 100644
--- a/openviking/server/routers/resources.py
+++ b/openviking/server/routers/resources.py
@@ -7,6 +7,8 @@ from typing import Any, Dict, Literal, Optional
from fastapi import APIRouter, Depends, File, Form, HTTPException, Request, UploadFile
from pydantic import BaseModel, ConfigDict, Field, model_validator
+from openviking.core.path_variables import resolve_path_variables
+from openviking.core.uri_validation import validate_content_target_uri
from openviking.resource.processing_mode import DEFAULT_PROCESSING_MODE, ProcessingMode
from openviking.server.auth import get_request_context, get_upload_request_context
from openviking.server.dependencies import get_service
@@ -214,6 +216,17 @@ async def add_resource(
):
"""Add resource to OpenViking."""
service = get_service()
+ to_uri = resolve_path_variables(request.to).strip() if request.to else ""
+ if to_uri:
+ to_uri = validate_content_target_uri(to_uri, _ctx, kind="resource", field_name="to")
+ parent_uri = resolve_path_variables(request.parent).strip() if request.parent else ""
+ if parent_uri:
+ parent_uri = validate_content_target_uri(
+ parent_uri,
+ _ctx,
+ kind="resource",
+ field_name="parent",
+ )
path = request.path
allow_local_path_resolution = False
@@ -270,8 +283,8 @@ async def add_resource(
path=path,
ctx=_ctx,
add_type=request.add_type,
- to=request.to,
- parent=request.parent,
+ to=to_uri,
+ parent=parent_uri,
reason=request.reason,
instruction=request.instruction,
wait=request.wait,
@@ -307,6 +320,14 @@ async def add_skill(
):
"""Add skill to OpenViking."""
service = get_service()
+ target_uri = resolve_path_variables(request.target_uri).strip() if request.target_uri else ""
+ if target_uri:
+ target_uri = validate_content_target_uri(
+ target_uri,
+ _ctx,
+ kind="skill",
+ field_name="target_uri",
+ )
data = request.data
allow_local_path_resolution = False
resolved = None
@@ -340,7 +361,7 @@ async def add_skill(
timeout=request.timeout,
allow_local_path_resolution=allow_local_path_resolution,
source_path_hint=source_path_hint,
- target_uri=request.target_uri,
+ target_uri=target_uri,
)
await persist_skill_source_metadata(service, _ctx, result, source_metadata)
except Exception:
diff --git a/openviking/server/routers/search.py b/openviking/server/routers/search.py
index c46a72cf4..acec157e8 100644
--- a/openviking/server/routers/search.py
+++ b/openviking/server/routers/search.py
@@ -10,6 +10,7 @@ from fastapi import Response as FastAPIResponse
from pydantic import BaseModel, ConfigDict, Field, model_validator
from openviking.core.path_variables import resolve_path_variables
+from openviking.core.uri_validation import validate_request_viking_uri
from openviking.pyagfs.exceptions import AGFSClientError, AGFSNotFoundError
from openviking.retrieve.context_assembler import (
CATEGORY_KEYS,
@@ -34,6 +35,7 @@ from openviking.server.identity import RequestContext
from openviking.server.models import Response
from openviking.server.telemetry import run_operation
from openviking.telemetry import TelemetryRequest
+from openviking.utils.image_search import is_viking_uri
from openviking.utils.search_filters import (
SearchContextTypeInput,
_resolve_levels,
@@ -92,11 +94,28 @@ def _resolve_search_filter(
raise InvalidArgumentError(str(exc)) from exc
-def _resolve_uri_or_uris(uri: Union[str, List[str]]) -> Union[str, List[str]]:
+def _resolve_uri_or_uris(
+ uri: Union[str, List[str]], ctx: RequestContext
+) -> Union[str, List[str]]:
"""Resolve path variables in a single URI or list of URIs."""
if isinstance(uri, list):
- return [resolve_path_variables(u) for u in uri]
- return resolve_path_variables(uri)
+ return [validate_request_viking_uri(resolve_path_variables(u), ctx) for u in uri]
+ if not uri:
+ return ""
+ return validate_request_viking_uri(resolve_path_variables(uri), ctx)
+
+
+def _resolve_uri_list(uris: Sequence[str], ctx: RequestContext) -> list[str]:
+ return [validate_request_viking_uri(resolve_path_variables(uri), ctx) for uri in uris]
+
+
+def _resolve_image_url(image_url: Optional[str], ctx: RequestContext) -> Optional[str]:
+ if not image_url:
+ return image_url
+ resolved = resolve_path_variables(image_url)
+ if is_viking_uri(resolved):
+ return validate_request_viking_uri(resolved, ctx, field_name="image_url")
+ return resolved
class FindRequest(BaseModel):
@@ -283,7 +302,8 @@ async def find(
request.time_field,
request.tags,
)
- resolved_target_uri = _resolve_uri_or_uris(request.target_uri)
+ resolved_target_uri = _resolve_uri_or_uris(request.target_uri, _ctx)
+ resolved_image_url = _resolve_image_url(request.image_url, _ctx)
execution = await run_operation(
operation="search.find",
telemetry=request.telemetry,
@@ -295,7 +315,7 @@ async def find(
score_threshold=request.score_threshold,
filter=effective_filter,
level=_resolve_levels(request.level) or None,
- image_url=request.image_url,
+ image_url=resolved_image_url,
),
)
result = execution.result
@@ -332,7 +352,7 @@ async def _search_context(
"""Assemble an injection-ready context block for one request."""
params = AssembleParams(
query=request.query,
- image_url=request.image_url,
+ image_url=_resolve_image_url(request.image_url, ctx),
limit=actual_limit,
score_threshold=request.score_threshold,
filter=effective_filter,
@@ -343,7 +363,7 @@ async def _search_context(
purpose=request.purpose,
detail=request.detail,
dedup_turns=request.dedup_turns,
- exclude_uris=request.exclude_uris,
+ exclude_uris=_resolve_uri_list(request.exclude_uris, ctx),
peer_scope=request.peer_scope,
other_peer_penalty=request.other_peer_penalty,
rewrite=request.rewrite,
@@ -389,7 +409,8 @@ async def search(
effective_filter=effective_filter,
actual_limit=actual_limit,
)
- resolved_target_uri = _resolve_uri_or_uris(request.target_uri)
+ resolved_target_uri = _resolve_uri_or_uris(request.target_uri, _ctx)
+ resolved_image_url = _resolve_image_url(request.image_url, _ctx)
async def _search():
session = None
@@ -406,7 +427,7 @@ async def search(
score_threshold=request.score_threshold,
filter=effective_filter,
level=_resolve_levels(request.level) or None,
- image_url=request.image_url,
+ image_url=resolved_image_url,
)
execution = await run_operation(
@@ -434,6 +455,8 @@ async def recall(
"""Deprecated preset over context assembly; use /search with mode="context"."""
service = get_service()
params, aliases = fold_recall_request(request.model_dump(), request.model_fields_set)
+ params.image_url = _resolve_image_url(params.image_url, _ctx)
+ params.exclude_uris = _resolve_uri_list(params.exclude_uris, _ctx)
execution = await run_operation(
operation="search.recall",
telemetry=request.telemetry,
@@ -457,10 +480,12 @@ async def grep(
):
"""Content search with pattern."""
service = get_service()
- resolved_uri = resolve_path_variables(request.uri)
+ resolved_uri = validate_request_viking_uri(resolve_path_variables(request.uri), _ctx)
resolved_exclude_uri = None
if request.exclude_uri:
- resolved_exclude_uri = resolve_path_variables(request.exclude_uri)
+ resolved_exclude_uri = validate_request_viking_uri(
+ resolve_path_variables(request.exclude_uri), _ctx, field_name="exclude_uri"
+ )
try:
result = await service.fs.grep(
resolved_uri,
@@ -493,7 +518,7 @@ async def glob(
):
"""File pattern matching."""
service = get_service()
- resolved_uri = resolve_path_variables(request.uri)
+ resolved_uri = validate_request_viking_uri(resolve_path_variables(request.uri), _ctx)
try:
result = await service.fs.glob(
request.pattern, ctx=_ctx, uri=resolved_uri, node_limit=request.node_limit
diff --git a/openviking/server/routers/sessions.py b/openviking/server/routers/sessions.py
index edc6390b9..ef6d5748c 100644
--- a/openviking/server/routers/sessions.py
+++ b/openviking/server/routers/sessions.py
@@ -9,14 +9,16 @@ from pydantic import BaseModel, Field, field_validator, model_validator
from openviking.core.path_variables import resolve_path_variables
from openviking.core.peer_id import normalize_peer_id
+from openviking.core.uri_validation import validate_request_viking_uri
from openviking.message.part import Part, TextPart, part_from_dict
from openviking.server.auth import get_session_request_context
from openviking.server.dependencies import get_service
from openviking.server.identity import RequestContext
-from openviking.server.models import ErrorInfo, Response
+from openviking.server.models import Response
from openviking.server.responses import error_response
from openviking.server.telemetry import run_operation
from openviking.telemetry import TelemetryRequest
+from openviking.utils.image_search import is_viking_uri
from openviking_cli.utils import get_logger
router = APIRouter(prefix="/api/v1/sessions", tags=["sessions"])
@@ -213,10 +215,10 @@ def _commit_event_tags(
return metadata.event.tags
-def _resolve_message_parts(msg_request: AddMessageRequest) -> List[Part]:
+def _resolve_message_parts(msg_request: AddMessageRequest, ctx: RequestContext) -> List[Part]:
"""Resolve parts from an AddMessageRequest, handling path variables."""
if msg_request.parts is not None:
- return [_part_request_to_part(p) for p in msg_request.parts]
+ return [_part_request_to_part(p, ctx) for p in msg_request.parts]
return [TextPart(text=msg_request.content or "")]
@@ -233,27 +235,49 @@ def _session_pending_tokens(session: Any) -> int:
return 0
-def _part_request_to_part(raw_part: Dict[str, Any]) -> Part:
+def _part_request_to_part(raw_part: Dict[str, Any], ctx: RequestContext) -> Part:
"""Convert request part payload into an internal Part."""
if not isinstance(raw_part, dict):
return TextPart(text=str(raw_part))
part_copy = dict(raw_part)
- if part_copy.get("type") == "context" and "uri" in part_copy:
- part_copy["uri"] = resolve_path_variables(part_copy["uri"])
+ if part_copy.get("type") == "context" and part_copy.get("uri"):
+ part_copy["uri"] = validate_request_viking_uri(
+ resolve_path_variables(part_copy["uri"]), ctx
+ )
if part_copy.get("type") == "tool":
- if "tool_uri" in part_copy:
- part_copy["tool_uri"] = resolve_path_variables(part_copy["tool_uri"])
- if "skill_uri" in part_copy:
- part_copy["skill_uri"] = resolve_path_variables(part_copy["skill_uri"])
+ if part_copy.get("tool_uri"):
+ part_copy["tool_uri"] = validate_request_viking_uri(
+ resolve_path_variables(part_copy["tool_uri"]), ctx, field_name="tool_uri"
+ )
+ if part_copy.get("skill_uri"):
+ part_copy["skill_uri"] = validate_request_viking_uri(
+ resolve_path_variables(part_copy["skill_uri"]), ctx, field_name="skill_uri"
+ )
+ if part_copy.get("tool_output_storage_uri"):
+ part_copy["tool_output_storage_uri"] = validate_request_viking_uri(
+ resolve_path_variables(part_copy["tool_output_storage_uri"]),
+ ctx,
+ field_name="tool_output_storage_uri",
+ )
if part_copy.get("type") == "image_url":
image_url = part_copy.get("image_url")
if isinstance(image_url, dict) and "url" in image_url:
image_url = dict(image_url)
- image_url["url"] = resolve_path_variables(image_url["url"])
+ resolved_url = resolve_path_variables(image_url["url"])
+ if is_viking_uri(resolved_url):
+ resolved_url = validate_request_viking_uri(
+ resolved_url, ctx, field_name="image_url"
+ )
+ image_url["url"] = resolved_url
part_copy["image_url"] = image_url
elif isinstance(image_url, str):
- part_copy["image_url"] = resolve_path_variables(image_url)
+ resolved_url = resolve_path_variables(image_url)
+ part_copy["image_url"] = (
+ validate_request_viking_uri(resolved_url, ctx, field_name="image_url")
+ if is_viking_uri(resolved_url)
+ else resolved_url
+ )
try:
return part_from_dict(part_copy)
except ValueError as exc:
@@ -711,7 +735,7 @@ async def add_message(
async def _add() -> dict[str, Any]:
session = await service.sessions.get(session_id, _ctx, auto_create=True)
- parts = _resolve_message_parts(request)
+ parts = _resolve_message_parts(request, _ctx)
specs = [
{
@@ -768,7 +792,7 @@ async def batch_add_messages(
session = await service.sessions.get(session_id, _ctx, auto_create=True)
specs = []
for msg_request in request.messages:
- parts = _resolve_message_parts(msg_request)
+ parts = _resolve_message_parts(msg_request, _ctx)
specs.append(
{
"role": msg_request.role,
@@ -821,13 +845,18 @@ async def record_used(
# Resolve path variables in contexts
resolved_contexts = None
if request.contexts is not None:
- resolved_contexts = [resolve_path_variables(uri) for uri in request.contexts]
+ resolved_contexts = [
+ validate_request_viking_uri(resolve_path_variables(uri), _ctx)
+ for uri in request.contexts
+ ]
# Resolve path variables in skill URI if present
resolved_skill = request.skill
if resolved_skill is not None and "uri" in resolved_skill:
resolved_skill = dict(resolved_skill)
- resolved_skill["uri"] = resolve_path_variables(resolved_skill["uri"])
+ resolved_skill["uri"] = validate_request_viking_uri(
+ resolve_path_variables(resolved_skill["uri"]), _ctx
+ )
session.used(contexts=resolved_contexts, skill=resolved_skill)
return Response(
diff --git a/openviking/server/routers/skills.py b/openviking/server/routers/skills.py
index 7a1f8196d..81fad7d26 100644
--- a/openviking/server/routers/skills.py
+++ b/openviking/server/routers/skills.py
@@ -19,6 +19,7 @@ from pydantic import BaseModel, ConfigDict, model_validator
from openviking.core.namespace import canonical_user_root
from openviking.core.path_variables import resolve_path_variables
from openviking.core.skill_loader import validate_skill_format
+from openviking.core.uri_validation import validate_request_viking_uri
from openviking.privacy.service import UserPrivacyConfigVersion
from openviking.server.auth import get_request_context
from openviking.server.dependencies import get_service
@@ -88,7 +89,9 @@ def _agent_skills_root(ctx: RequestContext, target_uri: Optional[str] = None) ->
user_root = f"{canonical_user_root(ctx)}/skills"
if not target_uri:
return user_root
- resolved_uri = resolve_path_variables(target_uri).rstrip("/")
+ resolved_uri = validate_request_viking_uri(
+ resolve_path_variables(target_uri), ctx, field_name="target_uri"
+ ).rstrip("/")
if resolved_uri == "viking://agent/skills" or resolved_uri.startswith("viking://agent/skills/"):
return "viking://agent/skills"
if resolved_uri == user_root or resolved_uri.startswith(f"{user_root}/"):
@@ -261,8 +264,7 @@ async def _require_skill(
service, ctx: RequestContext, skill_name: str, target_uri: Optional[str] = None
) -> str:
if target_uri:
- resolved_uri = resolve_path_variables(target_uri)
- root_uri = _skill_root_uri(ctx, skill_name, resolved_uri)
+ root_uri = _skill_root_uri(ctx, skill_name, target_uri)
try:
stat = await service.fs.stat(root_uri, ctx=ctx)
if stat and stat.get("isDir", False):
@@ -534,7 +536,9 @@ async def list_skills(
"""List installed agent skills."""
service = get_service()
if target_uri:
- resolved_uri = resolve_path_variables(target_uri)
+ resolved_uri = validate_request_viking_uri(
+ resolve_path_variables(target_uri), _ctx, field_name="target_uri"
+ )
skills = await _list_skills_from_root(service, _ctx, resolved_uri)
return Response(
status="ok", result={"root_uri": resolved_uri, "skills": skills, "total": len(skills)}
@@ -568,7 +572,9 @@ async def find_skills(
service = get_service()
target_uri = request.target_uri
if target_uri:
- resolved_uri = resolve_path_variables(target_uri)
+ resolved_uri = validate_request_viking_uri(
+ resolve_path_variables(target_uri), _ctx, field_name="target_uri"
+ )
execution = await run_operation(
operation="skills.find",
telemetry=request.telemetry,
diff --git a/openviking/server/routers/snapshot.py b/openviking/server/routers/snapshot.py
index 4e4e66ad1..069d9d4b9 100644
--- a/openviking/server/routers/snapshot.py
+++ b/openviking/server/routers/snapshot.py
@@ -12,6 +12,7 @@ from fastapi import APIRouter, Body, Depends, Query
from fastapi.responses import Response as FastAPIResponse
from pydantic import BaseModel, ConfigDict
+from openviking.core.uri_validation import validate_request_viking_uri
from openviking.pyagfs.exceptions import (
AGFSClientError,
AGFSNotFoundError,
@@ -53,10 +54,15 @@ async def commit(
):
"""Create a new snapshot of the current workspace state."""
service = get_service()
+ paths = (
+ [validate_request_viking_uri(path, _ctx, field_name="paths") for path in request.paths]
+ if request.paths is not None
+ else None
+ )
try:
result = await service.fs.commit(
message=request.message,
- paths=request.paths,
+ paths=paths,
branch=request.branch,
author_name=request.author_name,
author_email=request.author_email,
@@ -86,8 +92,15 @@ async def log(
):
"""Walk commit history newest-first along parents[0]."""
service = get_service()
+ canonical_paths = (
+ [validate_request_viking_uri(path, _ctx, field_name="paths") for path in paths]
+ if paths is not None
+ else None
+ )
try:
- result = await service.fs.log(branch=branch, limit=limit, paths=paths, ctx=_ctx)
+ result = await service.fs.log(
+ branch=branch, limit=limit, paths=canonical_paths, ctx=_ctx
+ )
except AGFSNotFoundError:
raise NotFoundError(branch, "git_ref")
except (AGFSClientError, ValueError) as e:
@@ -119,9 +132,14 @@ async def restore(
):
"""Forward-commit restore: rebuild project_dir from source_commit on top of HEAD."""
service = get_service()
+ project_dir = (
+ validate_request_viking_uri(request.project_dir, _ctx, field_name="project_dir")
+ if request.project_dir
+ else None
+ )
try:
result = await service.fs.restore(
- project_dir=request.project_dir,
+ project_dir=project_dir,
source_commit=request.source_commit,
branch=request.branch,
dry_run=request.dry_run,
@@ -168,15 +186,20 @@ async def show(
):
"""Without ``path``: commit metadata JSON. With ``path``: raw blob bytes + X-Snapshot-* headers."""
service = get_service()
+ canonical_path = (
+ validate_request_viking_uri(path, _ctx, field_name="path") if path is not None else None
+ )
try:
- if path is None:
+ if canonical_path is None:
result = await service.fs.show(target_ref, ctx=_ctx)
return Response(status="ok", result=result)
- blob = await service.fs.show_blob_raw(target_ref, path=path, ctx=_ctx)
+ blob = await service.fs.show_blob_raw(target_ref, path=canonical_path, ctx=_ctx)
except AGFSNotFoundError as e:
- resource = path if path is not None else target_ref
- raise NotFoundError(resource, "git_blob" if path is not None else "git_ref") from e
+ resource = canonical_path if canonical_path is not None else target_ref
+ raise NotFoundError(
+ resource, "git_blob" if canonical_path is not None else "git_ref"
+ ) from e
except (AGFSClientError, ValueError) as e:
mapped = map_exception(e)
if mapped is not None:
@@ -192,7 +215,7 @@ async def show(
from openviking.session.memory.utils.memory_file_utils import MemoryFileUtils
- content = MemoryFileUtils.read(text, uri=path).content.encode("utf-8")
+ content = MemoryFileUtils.read(text, uri=canonical_path).content.encode("utf-8")
return FastAPIResponse(
content=content,
@@ -218,6 +241,7 @@ async def diff(
):
"""Return a unified text diff for one path between two snapshots."""
service = get_service()
+ path = validate_request_viking_uri(path, _ctx, field_name="path")
try:
result = await service.fs.diff(
path=path,
diff --git a/openviking/server/routers/system.py b/openviking/server/routers/system.py
index f0b634ecc..3800ac764 100644
--- a/openviking/server/routers/system.py
+++ b/openviking/server/routers/system.py
@@ -10,7 +10,7 @@ from fastapi.responses import JSONResponse
from pydantic import BaseModel
from openviking.core.path_variables import resolve_path_variables
-from openviking.core.uri_validation import validate_viking_uri
+from openviking.core.uri_validation import validate_request_viking_uri
from openviking.pyagfs.exceptions import AGFSInvalidOperationError, AGFSNotSupportedError
from openviking.server.auth import get_request_context, require_role
from openviking.server.dependencies import get_service
@@ -256,7 +256,7 @@ async def check_consistency(
):
"""Check filesystem/vector-index consistency for a URI subtree."""
service = get_service()
- uri = validate_viking_uri(request.uri)
+ uri = validate_request_viking_uri(resolve_path_variables(request.uri), ctx)
result = await service.check_consistency(
uri=uri,
ctx=ctx,
@@ -271,7 +271,7 @@ async def backend_sync_status(
):
"""Return multi-write backend sync status for a Viking URI subtree."""
service = get_service()
- uri = validate_viking_uri(resolve_path_variables(request.uri))
+ uri = validate_request_viking_uri(resolve_path_variables(request.uri), ctx)
result = await service.fs.system_sync_status(uri, ctx=ctx)
return Response(status="ok", result=result)
@@ -283,7 +283,7 @@ async def backend_sync_retry(
):
"""Retry pending multi-write backend sync work for a Viking URI subtree."""
service = get_service()
- uri = validate_viking_uri(resolve_path_variables(request.uri))
+ uri = validate_request_viking_uri(resolve_path_variables(request.uri), ctx)
result = await service.fs.system_sync_retry(uri, ctx=ctx)
return Response(status="ok", result=result)
@@ -295,7 +295,7 @@ async def admin_sync_status(
):
"""Return multi-write backend sync status for one URI subtree through the admin API."""
service = get_service()
- uri = validate_viking_uri(resolve_path_variables(sync_path))
+ uri = validate_request_viking_uri(resolve_path_variables(sync_path), ctx)
result = await service.fs.system_sync_status(uri, ctx=ctx)
return Response(status="ok", result=result)
@@ -307,6 +307,6 @@ async def admin_sync_retry(
):
"""Retry pending multi-write backend sync work for one URI subtree through the admin API."""
service = get_service()
- uri = validate_viking_uri(resolve_path_variables(sync_path))
+ uri = validate_request_viking_uri(resolve_path_variables(sync_path), ctx)
result = await service.fs.system_sync_retry(uri, ctx=ctx)
return Response(status="ok", result=result)
diff --git a/openviking/server/routers/watches.py b/openviking/server/routers/watches.py
index eb08d1d7a..53cb02565 100644
--- a/openviking/server/routers/watches.py
+++ b/openviking/server/routers/watches.py
@@ -14,6 +14,7 @@ from typing import Optional
from fastapi import APIRouter, Body, Depends, Path, Query
from pydantic import BaseModel, ConfigDict, field_validator
+from openviking.core.uri_validation import validate_request_viking_uri
from openviking.resource import watch_manager as wm_mod
from openviking.resource.watch_manager import WatchManager, WatchTask
from openviking.server.auth import get_request_context
@@ -111,6 +112,8 @@ async def _resolve_task(
"""
if not task_id and not to_uri:
raise InvalidArgumentError("Either {task_id} or ?to_uri= is required")
+ if to_uri:
+ to_uri = validate_request_viking_uri(to_uri, ctx, field_name="to_uri")
wm = _wm()
account_id, user_id, role = _identity(ctx)
@@ -157,6 +160,7 @@ async def list_or_get_watch(
wm = _wm()
account_id, user_id, role = _identity(_ctx)
if to_uri:
+ to_uri = validate_request_viking_uri(to_uri, _ctx, field_name="to_uri")
task = await wm.get_task_by_uri(to_uri, account_id, user_id, role)
if task is None or (active_only and not task.is_active):
raise NotFoundError(to_uri, "watch_task")
diff --git a/openviking/server/user_config.py b/openviking/server/user_config.py
index 908d5a858..04edfe3cb 100644
--- a/openviking/server/user_config.py
+++ b/openviking/server/user_config.py
@@ -75,7 +75,12 @@ def validate_resource_add_target(
ctx: RequestContext,
viking_fs: VikingFS,
) -> str:
- resolved = validate_content_target_uri(uri, ctx, kind="resource", field_name="resource_uri")
+ resolved = validate_content_target_uri(
+ uri,
+ ctx,
+ kind="resource",
+ field_name="resource_uri",
+ )
_ensure_mutable(viking_fs, resolved, ctx)
return resolved
@@ -86,16 +91,12 @@ def validate_skill_add_target(
ctx: RequestContext,
viking_fs: VikingFS,
) -> str:
- normalized = uri.strip().rstrip("/")
- if normalized == "viking://user/skills":
- resolved = f"{canonical_user_root(ctx)}/skills"
- elif normalized == "viking://agent/skills":
- resolved = "viking://agent/skills"
- else:
- raise InvalidArgumentError(
- "skill_uri must be viking://user/skills or viking://agent/skills",
- details={"field": "skill_uri"},
- )
+ resolved = validate_content_target_uri(
+ uri,
+ ctx,
+ kind="skill",
+ field_name="skill_uri",
+ )
_ensure_mutable(viking_fs, resolved, ctx)
return resolved
@@ -150,7 +151,9 @@ async def update_user_config(
current = await read_user_config(viking_fs, ctx)
before = current.model_dump()
result = updater(current)
- validate_add_targets(current.add_targets, ctx=ctx, viking_fs=viking_fs)
+ runtime = validate_add_targets(current.add_targets, ctx=ctx, viking_fs=viking_fs)
+ current.add_targets.resource_uri = runtime.resource_uri
+ current.add_targets.skill_uri = runtime.skill_uri
if current.model_dump() != before:
await viking_fs.write_file(
uri,
@@ -171,6 +174,8 @@ async def write_user_config(
user_config: UserConfig,
) -> ResolvedAddTargets:
runtime = validate_add_targets(user_config.add_targets, ctx=ctx, viking_fs=viking_fs)
+ user_config.add_targets.resource_uri = runtime.resource_uri
+ user_config.add_targets.skill_uri = runtime.skill_uri
uri = user_config_uri(ctx)
async with _user_config_lock(viking_fs, uri, ctx) as handle:
await viking_fs.write_file(
diff --git a/openviking/service/agent_evolution_service.py b/openviking/service/agent_evolution_service.py
index 9cce530bb..9a95a3262 100644
--- a/openviking/service/agent_evolution_service.py
+++ b/openviking/service/agent_evolution_service.py
@@ -8,7 +8,6 @@ import asyncio
from datetime import date, datetime, time, timedelta, timezone
from typing import TYPE_CHECKING, Any, Optional
-from openviking.core.namespace import canonicalize_uri
from openviking.server.identity import RequestContext
from openviking.session.memory.experience_lineage import (
TRAJECTORY_OUTCOMES,
@@ -130,10 +129,7 @@ class AgentEvolutionService:
if self._vikingdb is None:
raise NotInitializedError("VikingDB")
- trajectory_root = canonicalize_uri(
- f"viking://user/{ctx.user.user_id}/memories/trajectories",
- ctx,
- )
+ trajectory_root = f"viking://user/{ctx.user.user_id}/memories/trajectories"
return canonical_uri, trajectory_root, self._vikingdb
async def list_trajectories_by_experience(
diff --git a/openviking/service/core.py b/openviking/service/core.py
index 0912a5ba9..119c878c5 100644
--- a/openviking/service/core.py
+++ b/openviking/service/core.py
@@ -11,7 +11,6 @@ import os
from typing import TYPE_CHECKING, Any, Optional
from openviking.core.directories import DirectoryInitializer
-from openviking.core.namespace import canonicalize_uri
from openviking.privacy import UserPrivacyConfigService
from openviking.resource.uri_mutation_coordinator import UriMutationCoordinator
from openviking.resource.watch_scheduler import WatchScheduler
@@ -576,11 +575,10 @@ class OpenVikingService:
await self.initialize()
effective_ctx = ctx or RequestContext(user=self.user, role=Role.ROOT)
- canonical_uri = canonicalize_uri(uri, effective_ctx)
from openviking.service.reindex_executor import get_reindex_executor
execute_kwargs = {
- "uri": canonical_uri,
+ "uri": uri,
"mode": mode,
"wait": wait,
"dry_run": dry_run,
diff --git a/openviking/service/fs_service.py b/openviking/service/fs_service.py
index 6c4feb336..1a1b93e9f 100644
--- a/openviking/service/fs_service.py
+++ b/openviking/service/fs_service.py
@@ -11,7 +11,6 @@ from typing import TYPE_CHECKING, Any, Dict, List, Optional
from openviking.core.context import ContextLevel
from openviking.core.namespace import classify_uri, context_type_for_uri
-from openviking.core.uri_validation import validate_optional_viking_uri, validate_viking_uri
from openviking.privacy import (
UserPrivacyConfigService,
get_skill_name_from_uri,
@@ -137,7 +136,6 @@ class FSService:
sort_order: Sort direction, "asc" or "desc"
"""
viking_fs = self._ensure_initialized()
- uri = validate_viking_uri(uri)
if simple:
# Only return URIs — skip expensive abstract fetching to save tokens
@@ -192,7 +190,6 @@ class FSService:
description: Optional[str] = None,
) -> None:
"""Create directory."""
- uri = validate_viking_uri(uri)
viking_fs = self._ensure_initialized()
await viking_fs.mkdir(uri, ctx=ctx)
abstract = self._normalize_directory_description(description)
@@ -252,7 +249,6 @@ class FSService:
timeout: Optional[float] = None,
) -> Optional[Dict[str, Any]]:
"""Remove resource."""
- uri = validate_viking_uri(uri)
viking_fs = self._ensure_initialized()
cleanup_result: Optional[Dict[str, Any]] = None
context_type = context_type_for_uri(uri)
@@ -446,8 +442,6 @@ class FSService:
async def mv(self, from_uri: str, to_uri: str, ctx: RequestContext) -> None:
"""Move resource."""
- from_uri = validate_viking_uri(from_uri, field_name="from_uri")
- to_uri = validate_viking_uri(to_uri, field_name="to_uri")
viking_fs = self._ensure_initialized()
watch_manager = self._get_watch_manager()
if not watch_manager or context_type_for_uri(from_uri) != "resource":
@@ -555,7 +549,6 @@ class FSService:
) -> List[Dict[str, Any]]:
"""Get directory tree."""
viking_fs = self._ensure_initialized()
- uri = validate_viking_uri(uri)
return await viking_fs.tree(
uri,
ctx=ctx,
@@ -569,25 +562,21 @@ class FSService:
async def stat(self, uri: str, ctx: RequestContext) -> Dict[str, Any]:
"""Get resource status."""
viking_fs = self._ensure_initialized()
- uri = validate_viking_uri(uri)
return await viking_fs.stat(uri, ctx=ctx)
async def system_sync_status(self, uri: str, ctx: RequestContext) -> Dict[str, Any]:
"""Return multi-write sync status for one Viking URI subtree."""
viking_fs = self._ensure_initialized()
- uri = validate_viking_uri(uri)
return await viking_fs.system_sync_status(uri, ctx=ctx)
async def system_sync_retry(self, uri: str, ctx: RequestContext) -> Dict[str, Any]:
"""Retry multi-write sync work for one Viking URI subtree."""
viking_fs = self._ensure_initialized()
- uri = validate_viking_uri(uri)
return await viking_fs.system_sync_retry(uri, ctx=ctx)
async def read(self, uri: str, ctx: RequestContext, offset: int = 0, limit: int = -1) -> str:
"""Read file content."""
viking_fs = self._ensure_initialized()
- uri = validate_viking_uri(uri)
content = await viking_fs.read_file(uri, ctx=ctx)
skill_name = get_skill_name_from_uri(uri)
if skill_name and self._privacy_config_service:
@@ -613,7 +602,6 @@ class FSService:
limit: int = -1,
) -> str:
"""Read public content, hiding reserved metadata from memory files."""
- uri = validate_viking_uri(uri)
if not classify_uri(uri).is_memory:
return await self.read(uri, ctx=ctx, offset=offset, limit=limit)
content = await self.read(uri, ctx=ctx)
@@ -622,13 +610,11 @@ class FSService:
async def abstract(self, uri: str, ctx: RequestContext) -> str:
"""Read L0 abstract (.abstract.md)."""
viking_fs = self._ensure_initialized()
- uri = validate_viking_uri(uri)
return await viking_fs.abstract(uri, ctx=ctx)
async def overview(self, uri: str, ctx: RequestContext) -> str:
"""Read L1 overview (.overview.md)."""
viking_fs = self._ensure_initialized()
- uri = validate_viking_uri(uri)
return await viking_fs.overview(uri, ctx=ctx)
async def grep(
@@ -643,8 +629,6 @@ class FSService:
) -> Dict:
"""Content search."""
viking_fs = self._ensure_initialized()
- uri = validate_viking_uri(uri)
- exclude_uri = validate_optional_viking_uri(exclude_uri, field_name="exclude_uri") or None
kwargs = {
"exclude_uri": exclude_uri,
"case_insensitive": case_insensitive,
@@ -665,13 +649,11 @@ class FSService:
) -> Dict:
"""File pattern matching."""
viking_fs = self._ensure_initialized()
- uri = validate_viking_uri(uri)
return await viking_fs.glob(pattern, uri=uri, node_limit=node_limit, ctx=ctx)
async def read_file_bytes(self, uri: str, ctx: RequestContext) -> bytes:
"""Read file as raw bytes."""
viking_fs = self._ensure_initialized()
- uri = validate_viking_uri(uri)
return await viking_fs.read_file_bytes(uri, ctx=ctx)
async def write(
@@ -685,7 +667,6 @@ class FSService:
processing_mode: str = "semantic_and_vectors",
) -> Dict[str, Any]:
"""Write to an existing file and refresh semantics/vectors."""
- uri = validate_viking_uri(uri)
viking_fs = self._ensure_initialized()
coordinator = ContentWriteCoordinator(viking_fs=viking_fs, vikingdb=self._vikingdb)
return await coordinator.write(
@@ -708,7 +689,6 @@ class FSService:
timeout: Optional[float] = None,
) -> Dict[str, Any]:
"""Apply a preconditioned multi-file write and aggregate downstream refresh."""
- root_uri = validate_viking_uri(root_uri, field_name="root_uri")
viking_fs = self._ensure_initialized()
coordinator = ContentWriteCoordinator(viking_fs=viking_fs, vikingdb=self._vikingdb)
return await coordinator.batch_write(
@@ -728,7 +708,6 @@ class FSService:
ctx: RequestContext,
) -> Dict[str, Any]:
"""Set explicit retrieval tags for a file or directory semantic nodes."""
- uri = validate_viking_uri(uri)
viking_fs = self._ensure_initialized()
coordinator = ContentWriteCoordinator(viking_fs=viking_fs)
return await coordinator.set_tags(
@@ -751,10 +730,9 @@ class FSService:
) -> Dict[str, Any]:
"""Forward to VikingFS.commit. See viking_fs.commit for semantics."""
viking_fs = self._ensure_initialized()
- validated = [validate_viking_uri(p) for p in paths] if paths is not None else None
return await viking_fs.commit(
message=message,
- paths=validated,
+ paths=paths,
branch=branch,
author_name=author_name,
author_email=author_email,
@@ -775,8 +753,6 @@ class FSService:
) -> Dict[str, Any]:
"""Forward to VikingFS.restore. See viking_fs.restore for semantics."""
viking_fs = self._ensure_initialized()
- if project_dir is not None:
- project_dir = validate_viking_uri(project_dir, field_name="project_dir")
return await viking_fs.restore(
project_dir=project_dir,
source_commit=source_commit,
@@ -797,8 +773,6 @@ class FSService:
) -> Any:
"""Forward to VikingFS.show. Returns dict (metadata) or bytes (blob)."""
viking_fs = self._ensure_initialized()
- # validate_optional_viking_uri returns "" for None input; VikingFS.show needs None.
- path = validate_optional_viking_uri(path, field_name="path") or None
return await viking_fs.show(target_ref, path=path, ctx=ctx)
async def show_blob_raw(
@@ -810,7 +784,6 @@ class FSService:
) -> Dict[str, Any]:
"""Forward to VikingFS.show_blob_raw. Returns ``{"oid", "size", "bytes"}``."""
viking_fs = self._ensure_initialized()
- path = validate_viking_uri(path, field_name="path")
return await viking_fs.show_blob_raw(target_ref, path=path, ctx=ctx)
async def diff(
@@ -824,7 +797,6 @@ class FSService:
) -> Dict[str, Any]:
"""Return a unified text diff for one path between two snapshots."""
viking_fs = self._ensure_initialized()
- path = validate_viking_uri(path, field_name="path")
return await viking_fs.diff(
path=path,
from_ref=from_ref,
@@ -843,10 +815,6 @@ class FSService:
) -> List[Dict[str, Any]]:
"""Forward to VikingFS.log. Walks parents[0] up to limit commits."""
viking_fs = self._ensure_initialized()
- if paths is not None:
- paths = [validate_viking_uri(path, field_name="paths") for path in paths]
- if not paths:
- paths = None
return await viking_fs.log(branch=branch, limit=limit, paths=paths, ctx=ctx)
async def get_gitignore(self, *, ctx: RequestContext) -> str:
diff --git a/openviking/service/pack_service.py b/openviking/service/pack_service.py
index f339ffb8c..e786048ac 100644
--- a/openviking/service/pack_service.py
+++ b/openviking/service/pack_service.py
@@ -8,8 +8,6 @@ Provides ovpack export/import and backup/restore operations.
from typing import Optional
-from openviking.core.namespace import canonicalize_uri
-from openviking.core.uri_validation import validate_viking_uri
from openviking.server.identity import RequestContext, Role
from openviking.storage.ovpack.operations import backup_ovpack as local_backup_ovpack
from openviking.storage.ovpack.operations import export_ovpack as local_export_ovpack
@@ -46,7 +44,7 @@ class PackService:
@staticmethod
def _account_maintenance_ctx(ctx: RequestContext) -> RequestContext:
- """Return an account-scoped context that can traverse every user namespace."""
+ """Use account-wide authority for backup/restore without changing URI ownership."""
if ctx.role not in {Role.ROOT, Role.ADMIN}:
raise PermissionDeniedError("OVPack backup and restore require ROOT or ADMIN role")
return RequestContext(
@@ -72,7 +70,6 @@ class PackService:
Exported file path
"""
viking_fs = self._ensure_initialized()
- uri = canonicalize_uri(validate_viking_uri(uri), ctx)
return await local_export_ovpack(
viking_fs,
uri,
@@ -118,7 +115,6 @@ class PackService:
Imported root resource URI
"""
viking_fs = self._ensure_initialized()
- parent = canonicalize_uri(validate_viking_uri(parent, field_name="parent"), ctx)
return await local_import_ovpack(
viking_fs,
file_path,
diff --git a/openviking/service/reindex_executor.py b/openviking/service/reindex_executor.py
index 566f43db5..9ffe35f6b 100644
--- a/openviking/service/reindex_executor.py
+++ b/openviking/service/reindex_executor.py
@@ -922,7 +922,7 @@ class ReindexExecutor:
uri = str(record.get("uri") or "")
owner = record.get("owner_user_id")
if not owner:
- owner = owner_fields_for_uri(uri, ctx=ctx).get("owner_user_id")
+ owner = owner_fields_for_uri(uri).get("owner_user_id")
if not owner or owner == ctx.user.user_id:
return ctx
return RequestContext(
@@ -1830,7 +1830,7 @@ class ReindexExecutor:
level=level,
user=owner_ctx.user,
account_id=owner_ctx.account_id,
- owner_space=owner_space_for_uri(uri, owner_ctx),
+ owner_space=owner_space_for_uri(uri),
meta=merged_meta,
)
context.set_vectorize(Vectorize(text=vector_text))
diff --git a/openviking/service/resource_memory_link_service.py b/openviking/service/resource_memory_link_service.py
index c7007ccf9..4e7711070 100644
--- a/openviking/service/resource_memory_link_service.py
+++ b/openviking/service/resource_memory_link_service.py
@@ -17,7 +17,6 @@ from typing import TYPE_CHECKING, Any, Dict, List, Optional, Sequence
from openviking.core.namespace import (
NamespaceShapeError,
canonical_user_root,
- canonicalize_uri,
context_type_for_uri,
uri_parts,
)
@@ -92,7 +91,7 @@ def _resource_reason_peer_id(ctx: RequestContext, resource_uri: str) -> Optional
def _peer_id_from_resource_uri(resource_uri: str, ctx: RequestContext) -> Optional[str]:
try:
- parts = uri_parts(canonicalize_uri(resource_uri, ctx))
+ parts = uri_parts(resource_uri)
except (NamespaceShapeError, ValueError):
return None
if len(parts) >= 5 and parts[0] == "user" and parts[2] == "peers":
diff --git a/openviking/service/resource_service.py b/openviking/service/resource_service.py
index d9e67e18f..1defa2379 100644
--- a/openviking/service/resource_service.py
+++ b/openviking/service/resource_service.py
@@ -18,9 +18,7 @@ from typing import TYPE_CHECKING, Any, Dict, List, Optional
from urllib.parse import urlparse
from uuid import uuid4
-from openviking.core.content_targets import ContentTargetSpec
from openviking.core.namespace import is_content_root_uri
-from openviking.core.uri_validation import validate_optional_content_target_uri
from openviking.parse.backend import ParserBackend, normalize_parser_backend
from openviking.parse.mode import ParseMode, normalize_parse_mode
from openviking.parse.parsers.constants import MPEG_TS_EXTENSION_ALIAS
@@ -271,13 +269,23 @@ class ResourceService:
return {}
return {"ingest_options": IngestOptions.from_search_tags(tags, mode=tag_mode)}
+ @staticmethod
+ def _ensure_single_resource_target(
+ *,
+ to: Optional[str],
+ parent: Optional[str],
+ ) -> None:
+ if (to or "").strip() and (parent or "").strip():
+ raise InvalidArgumentError("Cannot specify both 'to' and 'parent' at the same time.")
+
async def _manage_watch_if_needed(
self,
*,
watch_manager: Optional["WatchManager"],
manage_watch: bool,
watch_interval: float,
- target: ContentTargetSpec,
+ to: str,
+ parent: str,
to_is_directory: bool,
root_uri: str,
path: str,
@@ -295,15 +303,10 @@ class ResourceService:
telemetry = get_current_telemetry()
with telemetry.measure("resource.watch"):
if watch_interval > 0:
- watch_to = target.to
- parent_uri = target.parent
+ watch_to = to
+ parent_uri = parent
if not watch_to:
- watch_to = validate_optional_content_target_uri(
- root_uri,
- ctx,
- kind="resource",
- field_name="root_uri",
- )
+ watch_to = root_uri
parent_uri = None
if not watch_to:
raise InvalidArgumentError(
@@ -343,12 +346,12 @@ class ResourceService:
logger.warning(
f"[ResourceService] Failed to create watch task for {watch_to}: {e}"
)
- elif target.to:
+ elif to:
try:
- await self._handle_watch_task_cancellation(to_uri=target.to, ctx=ctx)
+ await self._handle_watch_task_cancellation(to_uri=to, ctx=ctx)
except Exception as e:
logger.warning(
- f"[ResourceService] Failed to cancel watch task for {target.to}: {e}"
+ f"[ResourceService] Failed to cancel watch task for {to}: {e}"
)
def _normalize_add_resource_args(
@@ -870,7 +873,9 @@ class ResourceService:
plan: _SourcePlan,
*,
ctx: RequestContext,
- target: ContentTargetSpec,
+ to: str,
+ parent: str,
+ create_parent: bool,
reason: str,
instruction: str,
timeout: Optional[float],
@@ -890,16 +895,14 @@ class ResourceService:
from openviking.storage.queuefs.add_resource_msg import AddResourceMsg
planned_to_is_directory = (
- to_is_directory if to_is_directory is not None else bool(target.to)
- )
- target_to_is_exact = bool(
- target.to and not is_content_root_uri(target.to, ctx, kind="resource")
+ to_is_directory if to_is_directory is not None else bool(to)
)
+ target_to_is_exact = bool(to and not is_content_root_uri(to, kind="resource"))
defer_candidate_resolution = bool(
(
plan.defer_unnamed_target
and plan.source_identity.source_name is None
- and not target.to
+ and not to
)
or (mode is ParseMode.NO_SPLIT and not target_to_is_exact)
)
@@ -911,7 +914,9 @@ class ResourceService:
root_uri, resource_lock, defer_target_resolution = await self._plan_source_job_target(
path=plan.path,
ctx=ctx,
- target=target,
+ to=to,
+ parent=parent,
+ create_parent=create_parent,
source_info=plan.source_identity,
defer_candidate_resolution=defer_candidate_resolution,
)
@@ -956,7 +961,7 @@ class ResourceService:
exclude=processor_kwargs.get("exclude"),
directly_upload_media=bool(processor_kwargs.get("directly_upload_media", True)),
preserve_structure=processor_kwargs.get("preserve_structure"),
- create_parent=bool(processor_kwargs.get("create_parent", False)),
+ create_parent=create_parent,
source_name=plan.source_identity.source_name,
to_is_directory=planned_to_is_directory,
args=plan.processor_args,
@@ -999,7 +1004,9 @@ class ResourceService:
*,
path: str,
ctx: RequestContext,
- target: ContentTargetSpec,
+ to: str,
+ parent: str,
+ create_parent: bool,
source_info: _ResourceSourceInfo,
defer_candidate_resolution: bool,
) -> tuple[str, Optional[Dict[str, Any]], bool]:
@@ -1012,11 +1019,11 @@ class ResourceService:
ctx=ctx,
doc_name=doc_name,
scope="resources",
- to_uri=target.to,
- parent_uri=target.parent,
+ to_uri=to,
+ parent_uri=parent,
source_path=source_path,
source_format=source_info.source_format,
- create_parent=target.create_parent,
+ create_parent=create_parent,
)
if candidate_uri and defer_candidate_resolution:
return root_uri, None, True
@@ -1283,6 +1290,11 @@ class ResourceService:
parent = default_parent
kwargs["create_parent"] = True
+ self._ensure_single_resource_target(to=to, parent=parent)
+ target_to = to or ""
+ target_parent = parent or ""
+ target_create_parent = bool(kwargs.get("create_parent", False))
+
if self._connector.should_delegate(
path,
ctx=ctx,
@@ -1315,13 +1327,6 @@ class ResourceService:
path = require_remote_resource_source(path)
kwargs.setdefault("request_validator", ensure_public_remote_target)
- target = ContentTargetSpec.from_fields(
- ctx=ctx,
- kind="resource",
- to=to,
- parent=parent,
- create_parent=bool(kwargs.get("create_parent", False)),
- )
source_plan = await self._prepare_standard_source_plan(
path=path,
ctx=ctx,
@@ -1334,7 +1339,9 @@ class ResourceService:
result = await self._enqueue_source_plan(
source_plan,
ctx=ctx,
- target=target,
+ to=target_to,
+ parent=target_parent,
+ create_parent=target_create_parent,
reason=reason,
instruction=instruction,
timeout=timeout,
@@ -1355,9 +1362,9 @@ class ResourceService:
result = await self._execute_resource_ingestion(
path=path,
ctx=ctx,
- to=to,
+ to=target_to,
to_is_directory=to_is_directory,
- parent=parent,
+ parent=target_parent,
reason=reason,
instruction=instruction,
defer_post_processing=True,
@@ -1454,15 +1461,11 @@ class ResourceService:
telemetry.set("resource.flags.watch_enabled", watch_enabled)
try:
- target = ContentTargetSpec.from_fields(
- ctx=ctx,
- kind="resource",
- to=to,
- parent=parent,
- create_parent=bool(kwargs.get("create_parent", False)),
- )
+ self._ensure_single_resource_target(to=to, parent=parent)
+ target_to = to or ""
+ target_parent = parent or ""
if to_is_directory is None:
- to_is_directory = bool(target.to)
+ to_is_directory = bool(target_to)
watch_to_is_directory = to_is_directory
if enforce_public_remote_targets and is_remote_resource_source(path):
path = require_remote_resource_source(path)
@@ -1476,8 +1479,8 @@ class ResourceService:
reason=reason,
instruction=instruction,
scope="resources",
- to=target.to,
- parent=target.parent,
+ to=target_to,
+ parent=target_parent,
to_is_directory=to_is_directory,
build_index=build_index,
summarize=summarize,
@@ -1507,7 +1510,8 @@ class ResourceService:
watch_manager=watch_manager,
manage_watch=manage_watch,
watch_interval=watch_interval,
- target=target,
+ to=target_to,
+ parent=target_parent,
to_is_directory=watch_to_is_directory,
root_uri=str(result.get("root_uri") or ""),
path=path,
diff --git a/openviking/service/search_service.py b/openviking/service/search_service.py
index 6a6259d09..9a3992284 100644
--- a/openviking/service/search_service.py
+++ b/openviking/service/search_service.py
@@ -8,8 +8,6 @@ Provides semantic search operations: search, find.
from typing import TYPE_CHECKING, Any, Dict, List, Optional, Union
-from openviking.core.path_variables import resolve_path_variables
-from openviking.core.uri_validation import validate_optional_viking_uris
from openviking.server.identity import RequestContext
from openviking.storage.viking_fs import VikingFS
from openviking.utils.image_search import (
@@ -66,7 +64,6 @@ class SearchService:
) -> Optional[str]:
if not image_url:
return None
- image_url = resolve_path_variables(image_url)
if is_viking_uri(image_url):
viking_fs = self._ensure_initialized()
content = await viking_fs.read_file_bytes(image_url, ctx=ctx)
@@ -105,7 +102,6 @@ class SearchService:
"""
resolved_image_url = await self._resolve_image_url(image_url, ctx)
_ensure_non_empty_query(query, resolved_image_url)
- target_uri = validate_optional_viking_uris(target_uri, field_name="target_uri")
viking_fs = self._ensure_initialized()
session_info = None
@@ -152,7 +148,6 @@ class SearchService:
"""
resolved_image_url = await self._resolve_image_url(image_url, ctx)
_ensure_non_empty_query(query, resolved_image_url)
- target_uri = validate_optional_viking_uris(target_uri, field_name="target_uri")
viking_fs = self._ensure_initialized()
result = await viking_fs.find(
query=query,
diff --git a/openviking/service/session_service.py b/openviking/service/session_service.py
index 0273a1ba8..e5ceb59f0 100644
--- a/openviking/service/session_service.py
+++ b/openviking/service/session_service.py
@@ -319,25 +319,6 @@ class SessionService:
except Exception:
logger.debug("Failed to list sessions", exc_info=True)
- try:
- entries = await self._viking_fs.ls(
- "viking://session",
- sort_by="mtime",
- sort_order="desc",
- ctx=ctx,
- )
- for entry in entries:
- name = entry.get("name", "")
- if name in [".", ".."] or name in sessions_by_id:
- continue
- sessions_by_id[name] = {
- "session_id": name,
- "uri": entry.get("uri", f"viking://session/{name}"),
- "is_dir": entry.get("isDir", False),
- "mod_time": entry.get("modTime", ""),
- }
- except Exception:
- logger.debug("Failed to list legacy sessions", exc_info=True)
return list(sessions_by_id.values())
async def delete(self, session_id: str, ctx: RequestContext) -> bool:
diff --git a/openviking/session/memory/experience_lineage.py b/openviking/session/memory/experience_lineage.py
index e7874cb65..b213f6640 100644
--- a/openviking/session/memory/experience_lineage.py
+++ b/openviking/session/memory/experience_lineage.py
@@ -8,7 +8,7 @@ import json
import re
from typing import Any, Iterable
-from openviking.core.namespace import canonicalize_uri, uri_parts
+from openviking.core.namespace import uri_parts
from openviking.message import Message, ToolPart
from openviking.server.identity import RequestContext
from openviking.utils.tags import normalize_search_tag
@@ -40,10 +40,9 @@ def is_experience_uri_for_user(uri: str, user_id: str) -> bool:
def canonical_experience_uri(uri: str, ctx: RequestContext) -> str | None:
- """Canonicalize an Experience URI and enforce current-user ownership."""
- try:
- canonical_uri = canonicalize_uri(str(uri or "").strip(), ctx)
- except (TypeError, ValueError):
+ """Enforce canonical Experience URI shape and current-user ownership."""
+ canonical_uri = str(uri or "").strip()
+ if not canonical_uri.startswith("viking://"):
return None
if not is_experience_uri_for_user(canonical_uri, ctx.user.user_id):
return None
diff --git a/openviking/session/train/batch_runner.py b/openviking/session/train/batch_runner.py
index f3c65b654..42a7b0cbd 100644
--- a/openviking/session/train/batch_runner.py
+++ b/openviking/session/train/batch_runner.py
@@ -256,7 +256,7 @@ async def run_batch_train_eval(config: BatchTrainEvalConfig) -> BatchTrainEvalRe
client = _build_http_client(config)
await client.initialize()
try:
- policy_root_uri = "viking://user/memories/experiences"
+ policy_root_uri = f"viking://user/{config.user_id}/memories/experiences"
policy_set = ExperienceSet(
root_uri=policy_root_uri,
policies=[],
diff --git a/openviking/storage/content_write.py b/openviking/storage/content_write.py
index aa3b9eb71..09e7494f5 100644
--- a/openviking/storage/content_write.py
+++ b/openviking/storage/content_write.py
@@ -12,8 +12,6 @@ from collections import defaultdict
from typing import Any, Dict, Optional
from openviking.core.namespace import (
- NamespaceShapeError,
- canonicalize_uri,
classify_uri,
context_type_for_uri,
relative_uri_path,
@@ -105,13 +103,10 @@ class ContentWriteCoordinator:
timeout: Optional[float] = None,
processing_mode: ProcessingMode = DEFAULT_PROCESSING_MODE,
) -> Dict[str, Any]:
- try:
- normalized_uri = canonicalize_uri(uri, ctx)
- except NamespaceShapeError as exc:
- raise InvalidArgumentError(str(exc)) from exc
self._validate_mode(mode)
processing_mode = normalize_processing_mode(processing_mode)
- self._validate_target_uri(normalized_uri)
+ normalized_uri = self._validate_uri_path(uri, field_name="uri")
+ self._ensure_content_write_policy(normalized_uri)
self._viking_fs._ensure_mutable_access(normalized_uri, ctx)
if mode == "create":
@@ -126,10 +121,14 @@ class ContentWriteCoordinator:
stat = await self._safe_stat(normalized_uri, ctx=ctx)
if stat.get("isDir"):
- raise InvalidArgumentError(f"write only supports existing files, got directory: {uri}")
+ raise InvalidArgumentError(
+ f"write only supports existing files, got directory: {normalized_uri}"
+ )
context_type = context_type_for_uri(normalized_uri)
- root_uri = await self._resolve_root_uri(normalized_uri, ctx=ctx, anchor_to_parent=True)
+ root_uri = await self._resolve_root_uri(
+ normalized_uri, ctx=ctx, anchor_to_parent=True
+ )
written_bytes = len(content.encode("utf-8"))
telemetry_id = get_current_telemetry().telemetry_id
@@ -176,7 +175,7 @@ class ContentWriteCoordinator:
tree lock is held and before the first new write. Refresh runs only after that
lock is released so semantic processing can safely acquire descendant locks.
"""
- normalized_root = self._canonicalize(root_uri, ctx=ctx, field_name="root_uri")
+ normalized_root = self._validate_uri_path(root_uri, field_name="root_uri")
await self._validate_batch_root(normalized_root, ctx=ctx)
normalized_operations = self._normalize_batch_operations(
normalized_root, operations, ctx=ctx
@@ -358,10 +357,10 @@ class ContentWriteCoordinator:
"queue_status": queue_status,
}
- def _canonicalize(self, uri: str, *, ctx: RequestContext, field_name: str) -> str:
+ def _validate_uri_path(self, uri: str, *, field_name: str) -> str:
try:
- return validate_safe_viking_uri_path(canonicalize_uri(uri, ctx))
- except (NamespaceShapeError, ValueError) as exc:
+ return validate_safe_viking_uri_path(uri)
+ except ValueError as exc:
raise InvalidArgumentError(f"invalid {field_name}: {exc}") from exc
async def _validate_batch_root(self, root_uri: str, *, ctx: RequestContext) -> None:
@@ -410,7 +409,7 @@ class ContentWriteCoordinator:
for raw in operations:
if not isinstance(raw, dict):
raise InvalidArgumentError("batch-write operation must be an object")
- uri = self._canonicalize(raw.get("uri", ""), ctx=ctx, field_name="operation uri")
+ uri = self._validate_uri_path(raw.get("uri", ""), field_name="operation uri")
if uri in seen:
raise InvalidArgumentError(f"duplicate batch-write target: {uri}")
seen.add(uri)
@@ -420,7 +419,7 @@ class ContentWriteCoordinator:
raise InvalidArgumentError(
f"batch-write target has a different context type: {uri}"
)
- self._validate_target_uri(uri)
+ self._ensure_content_write_policy(uri)
self._viking_fs._ensure_mutable_access(uri, ctx)
has_content = "content" in raw
@@ -636,24 +635,19 @@ class ContentWriteCoordinator:
recursive: bool = False,
ctx: RequestContext,
) -> Dict[str, Any]:
- try:
- normalized_uri = canonicalize_uri(uri, ctx)
- except NamespaceShapeError as exc:
- raise InvalidArgumentError(str(exc)) from exc
-
self._validate_tag_mode(mode)
normalized_tags = normalize_search_tags(tags, discard_invalid=True)
- stat = await self._safe_stat(normalized_uri, ctx=ctx)
+ stat = await self._safe_stat(uri, ctx=ctx)
if stat.get("isDir"):
return await self._set_directory_tags(
- uri=normalized_uri,
+ uri=uri,
tags=normalized_tags,
mode=mode,
recursive=recursive,
ctx=ctx,
)
return await self._set_single_uri_tags(
- uri=normalized_uri,
+ uri=uri,
tags=normalized_tags,
mode=mode,
recursive=recursive,
@@ -951,17 +945,13 @@ class ContentWriteCoordinator:
if mode not in {"replace", "append"}:
raise InvalidArgumentError(f"unsupported tag mode: {mode}")
- def _validate_target_uri(self, uri: str) -> None:
+ def _ensure_content_write_policy(self, uri: str) -> None:
name = uri.rstrip("/").split("/")[-1]
if name in _DERIVED_FILENAMES:
raise InvalidArgumentError(f"cannot write derived semantic file directly: {uri}")
if is_watch_task_control_uri(uri):
raise InvalidArgumentError(f"cannot write watch task control file directly: {uri}")
- parsed = VikingURI(uri)
- if parsed.scope not in {"resources", "user", "agent"}:
- raise InvalidArgumentError(f"write is not supported for scope: {parsed.scope}")
-
def _is_not_found(self, exc: Exception) -> bool:
"""Check if an exception indicates a not-found error (OpenViking or AGFS)."""
if isinstance(exc, NotFoundError):
diff --git a/openviking/storage/ovpack/index.py b/openviking/storage/ovpack/index.py
index df95627fe..b7ed2cf16 100644
--- a/openviking/storage/ovpack/index.py
+++ b/openviking/storage/ovpack/index.py
@@ -6,7 +6,7 @@ from __future__ import annotations
from typing import Any
-from openviking.core.namespace import context_type_for_uri, is_session_uri
+from openviking.core.namespace import context_type_for_uri, is_session_uri, owner_fields_for_uri
from openviking.server.identity import RequestContext
from openviking.storage.expr import Eq
from openviking.storage.ovpack.format import (
@@ -155,6 +155,7 @@ def append_index_records(
rel_path: str,
kind: str,
records: list[dict[str, Any]],
+ user_id: str | None = None,
) -> None:
for record in records:
item = {
@@ -163,6 +164,8 @@ def append_index_records(
"kind": kind,
"level": int(record.get("level", 2)),
}
+ if user_id:
+ item["user_id"] = user_id
text = record.get("text")
if isinstance(text, str) and text:
item["text"] = text
@@ -193,7 +196,11 @@ async def build_manifest(
scopes: list[str] | None = None,
include_vectors: bool = False,
) -> tuple[dict[str, Any], list[dict[str, Any]], list[float]]:
- manifest_entries = [{"path": "", "kind": "directory"}]
+ root_user_id = owner_fields_for_uri(root_uri).get("owner_user_id")
+ root_entry: dict[str, Any] = {"path": "", "kind": "directory"}
+ if root_user_id:
+ root_entry["user_id"] = root_user_id
+ manifest_entries = [root_entry]
index_records: list[dict[str, Any]] = []
dense_values: list[float] = []
@@ -206,19 +213,28 @@ async def build_manifest(
ctx=ctx,
include_vectors=include_vectors,
)
- append_index_records(index_records, dense_values, "", "directory", root_records)
+ append_index_records(
+ index_records,
+ dense_values,
+ "",
+ "directory",
+ root_records,
+ user_id=root_user_id,
+ )
for entry in entries:
rel_path = entry["rel_path"]
is_dir = bool(entry.get("isDir"))
entry_uri = join_uri(root_uri, rel_path)
- manifest_entries.append(
- {
- "path": rel_path,
- "kind": "directory" if is_dir else "file",
- "size": entry.get("size", 0) if not is_dir else 0,
- }
- )
+ entry_user_id = owner_fields_for_uri(entry_uri).get("owner_user_id")
+ manifest_entry = {
+ "path": rel_path,
+ "kind": "directory" if is_dir else "file",
+ "size": entry.get("size", 0) if not is_dir else 0,
+ }
+ if entry_user_id:
+ manifest_entry["user_id"] = entry_user_id
+ manifest_entries.append(manifest_entry)
if is_session_uri(entry_uri):
continue
records = await index_records_for_uri(
@@ -235,6 +251,7 @@ async def build_manifest(
rel_path,
"directory" if is_dir else "file",
records,
+ user_id=entry_user_id,
)
root = {
@@ -250,6 +267,8 @@ async def build_manifest(
}
if package_type:
root["package_type"] = package_type
+ if root_user_id:
+ root["user_id"] = root_user_id
if scopes is not None:
manifest["scopes"] = scopes
return manifest, index_records, dense_values
diff --git a/openviking/storage/ovpack/manifest.py b/openviking/storage/ovpack/manifest.py
index a009016fb..d2d246020 100644
--- a/openviking/storage/ovpack/manifest.py
+++ b/openviking/storage/ovpack/manifest.py
@@ -8,13 +8,15 @@ import json
import zipfile
from typing import Any
-from openviking.core.namespace import uri_leaf_name
+from openviking.core.identifiers import validate_user_id
+from openviking.core.namespace import owner_fields_for_uri, uri_leaf_name
from openviking.storage.ovpack.format import (
OVPACK_DENSE_PATH,
OVPACK_FORMAT_VERSION,
OVPACK_INDEX_RECORDS_PATH,
OVPACK_KIND,
OVPACK_MANIFEST_ZIP_LEAF,
+ join_uri,
normalize_sha256,
validate_ovpack_rel_path,
)
@@ -120,6 +122,47 @@ def validate_manifest_root_matches_zip(manifest: dict[str, Any], base_name: str)
details={"manifest_root_name": root_name, "root_uri": root_uri},
)
+ expected_user_id = owner_fields_for_uri(root_uri).get("owner_user_id")
+ declared_user_id = root.get("user_id")
+ if declared_user_id is not None and declared_user_id != expected_user_id:
+ raise InvalidArgumentError(
+ "ovpack manifest root user_id does not match root uri",
+ details={"user_id": declared_user_id, "root_uri": root_uri},
+ )
+ if expected_user_id:
+ root["user_id"] = expected_user_id
+
+
+def _entry_user_id(manifest: dict[str, Any], rel_path: str) -> str | None:
+ root_uri = manifest_root_uri(manifest)
+ if not root_uri:
+ return None
+ target_uri = join_uri(root_uri, rel_path) if rel_path else root_uri
+ return owner_fields_for_uri(target_uri).get("owner_user_id")
+
+
+def manifest_entry_target_uri(
+ root_uri: str,
+ rel_path: str,
+ entry: dict[str, Any],
+) -> str:
+ """Map one validated manifest entry to its canonical restore target URI."""
+ parts = rel_path.split("/") if rel_path else []
+ if root_uri != "viking://" or not parts or parts[0] != "user":
+ return join_uri(root_uri, rel_path)
+ if len(parts) == 1:
+ return "viking://user"
+
+ user_id = entry.get("user_id")
+ if not isinstance(user_id, str) or not user_id:
+ raise InvalidArgumentError(
+ "Missing ovpack manifest user_id for user data",
+ details={"path": rel_path},
+ )
+ suffix = "/".join(parts[2:])
+ user_root = f"viking://user/{user_id}"
+ return join_uri(user_root, suffix) if suffix else user_root
+
def manifest_entries_by_path(manifest: dict[str, Any]) -> dict[str, dict[str, Any]]:
if not isinstance(manifest, dict) or "entries" not in manifest:
@@ -155,6 +198,21 @@ def manifest_entries_by_path(manifest: dict[str, Any]) -> dict[str, dict[str, An
"Duplicate ovpack manifest entry",
details={"path": rel_path},
)
+ expected_user_id = _entry_user_id(manifest, rel_path)
+ declared_user_id = entry.get("user_id")
+ if declared_user_id is not None and declared_user_id != expected_user_id:
+ raise InvalidArgumentError(
+ "ovpack manifest entry user_id does not match path",
+ details={"path": rel_path, "user_id": declared_user_id},
+ )
+ if expected_user_id:
+ validation_error = validate_user_id(expected_user_id)
+ if validation_error:
+ raise InvalidArgumentError(
+ f"Invalid ovpack manifest user_id: {validation_error}",
+ details={"path": rel_path, "user_id": expected_user_id},
+ )
+ entry["user_id"] = expected_user_id
by_path[rel_path] = entry
return by_path
diff --git a/openviking/storage/ovpack/operations.py b/openviking/storage/ovpack/operations.py
index e25e6e3bf..ef9fabf53 100644
--- a/openviking/storage/ovpack/operations.py
+++ b/openviking/storage/ovpack/operations.py
@@ -39,6 +39,7 @@ from openviking.storage.ovpack.format import (
from openviking.storage.ovpack.index import build_manifest, read_text_if_exists
from openviking.storage.ovpack.manifest import (
manifest_entries_by_path,
+ manifest_entry_target_uri,
read_manifest,
validate_manifest_root_matches_zip,
)
@@ -133,17 +134,6 @@ async def _remove_existing_root(viking_fs, root_uri: str, ctx: RequestContext) -
return
-async def _existing_scope_roots(
- viking_fs, scopes: tuple[str, ...], ctx: RequestContext
-) -> list[str]:
- existing: list[str] = []
- for scope in scopes:
- scope_uri = f"viking://{scope}"
- if await _root_exists(viking_fs, scope_uri, ctx):
- existing.append(scope_uri)
- return existing
-
-
def _exportable_entries(entries: list[dict[str, Any]]) -> list[dict[str, Any]]:
exportable: list[dict[str, Any]] = []
for entry in entries:
@@ -362,7 +352,14 @@ async def import_ovpack(
if not is_session_uri(root_uri):
if vector_action == "restore":
- await restore_vector_snapshot(vector_store, root_uri, index_records, dense_vectors, ctx)
+ await restore_vector_snapshot(
+ vector_store,
+ root_uri,
+ index_records,
+ dense_vectors,
+ manifest_entries_by_path(manifest),
+ ctx,
+ )
logger.info(f"[ovpack] Restored vector snapshot for: {root_uri}")
else:
await _enqueue_direct_vectorization(
@@ -638,6 +635,7 @@ async def restore_ovpack(
index_records: list[dict[str, Any]] = []
dense_vectors: dict[str, list[float]] = {}
vector_action = "recompute"
+ manifest_entries: dict[str, dict[str, Any]] = {}
restored_entries: list[dict[str, Any]] = []
with zipfile.ZipFile(file_path, "r") as zf:
@@ -661,7 +659,11 @@ async def restore_ovpack(
index_records = validate_manifest_content(zf, manifest, infolist, base_name)
dense_vectors = read_dense_vectors(zf, manifest, base_name, index_records)
- existing_roots = await _existing_scope_roots(viking_fs, backup_scopes, ctx)
+ existing_roots = []
+ for scope in backup_scopes:
+ scope_uri = f"viking://{scope}"
+ if await _root_exists(viking_fs, scope_uri, ctx):
+ existing_roots.append(scope_uri)
if existing_roots:
if conflict_action == "skip":
logger.info("[ovpack] Skipped backup restore because target scopes exist")
@@ -688,7 +690,8 @@ async def restore_ovpack(
content_members.sort(key=lambda member: (member[2] != "directory", member[3].count("/")))
for _, safe_zip_path, kind, rel_path in content_members:
- target_uri = join_uri(root_uri, rel_path)
+ manifest_entry = manifest_entries[rel_path]
+ target_uri = manifest_entry_target_uri(root_uri, rel_path, manifest_entry)
if target_uri == "viking://user":
continue
@@ -718,13 +721,21 @@ async def restore_ovpack(
logger.info(f"[ovpack] Successfully restored backup {file_path}")
if vector_action == "restore":
- await restore_vector_snapshot(vector_store, root_uri, index_records, dense_vectors, ctx)
+ await restore_vector_snapshot(
+ vector_store,
+ root_uri,
+ index_records,
+ dense_vectors,
+ manifest_entries,
+ ctx,
+ )
logger.info("[ovpack] Restored vector snapshot for backup")
return root_uri
vectorization_groups: dict[str, list[dict[str, Any]]] = {}
for entry in restored_entries:
- parts = entry["rel_path"].split("/")
+ target_uri = entry["uri"]
+ parts = target_uri.removeprefix("viking://").split("/")
if parts[0] == "resources":
group_uri = "viking://resources"
elif parts[0] == "user" and len(parts) >= 2:
diff --git a/openviking/storage/ovpack/validation.py b/openviking/storage/ovpack/validation.py
index 53faecf4b..af9f3958d 100644
--- a/openviking/storage/ovpack/validation.py
+++ b/openviking/storage/ovpack/validation.py
@@ -195,6 +195,16 @@ def _validate_index_record(
details={"index": index, "path": rel_path},
)
+ expected_user_id = manifest_entries[rel_path].get("user_id")
+ declared_user_id = record.get("user_id")
+ if declared_user_id is not None and declared_user_id != expected_user_id:
+ raise InvalidArgumentError(
+ "ovpack index record user_id does not match manifest entry",
+ details={"index": index, "path": rel_path, "user_id": declared_user_id},
+ )
+ if expected_user_id:
+ record["user_id"] = expected_user_id
+
def _validate_dense_references(
dense_info: dict[str, Any] | None,
diff --git a/openviking/storage/ovpack/vectors.py b/openviking/storage/ovpack/vectors.py
index 9efc759cb..d7cb40233 100644
--- a/openviking/storage/ovpack/vectors.py
+++ b/openviking/storage/ovpack/vectors.py
@@ -20,10 +20,9 @@ from openviking.storage.ovpack.format import (
OVPACK_DENSE_PATH,
dense_values_bytes,
internal_zip_path,
- join_uri,
sha256_hex,
)
-from openviking.storage.ovpack.manifest import manifest_dense_info
+from openviking.storage.ovpack.manifest import manifest_dense_info, manifest_entry_target_uri
from openviking.storage.ovpack.validation import dense_record_count, record_dense_ref
from openviking.utils.time_utils import get_current_timestamp
from openviking_cli.exceptions import InvalidArgumentError
@@ -279,7 +278,7 @@ async def _upsert_vector_snapshot_record(
) -> None:
level = int(record.get("level", 2))
scalars = dict(record.get("scalars") or {})
- owner_fields = owner_fields_for_uri(target_uri, ctx=ctx)
+ owner_fields = owner_fields_for_uri(target_uri)
timestamp = get_current_timestamp()
payload = {
**scalars,
@@ -310,6 +309,7 @@ async def restore_vector_snapshot(
root_uri: str,
index_records: list[dict[str, Any]],
dense_vectors: dict[str, list[float]],
+ manifest_entries: dict[str, dict[str, Any]],
ctx: RequestContext,
) -> None:
for record in index_records:
@@ -319,7 +319,10 @@ async def restore_vector_snapshot(
rel_path = record.get("path")
if not isinstance(rel_path, str):
continue
- target_uri = join_uri(root_uri, rel_path)
+ manifest_entry = manifest_entries.get(rel_path)
+ if manifest_entry is None:
+ continue
+ target_uri = manifest_entry_target_uri(root_uri, rel_path, manifest_entry)
if target_uri == "viking://user" or is_session_uri(target_uri):
continue
owner_ctx = content_owner_context_for_uri(target_uri, ctx)
diff --git a/openviking/storage/queuefs/embedding_msg_converter.py b/openviking/storage/queuefs/embedding_msg_converter.py
index 0fccba418..43fa33e2c 100644
--- a/openviking/storage/queuefs/embedding_msg_converter.py
+++ b/openviking/storage/queuefs/embedding_msg_converter.py
@@ -38,11 +38,7 @@ class EmbeddingMsgConverter:
uri = context_data.get("uri", "")
owner_fields = None
if uri:
- owner_fields = owner_fields_for_uri(
- uri,
- user=context.user,
- account_id=context_data.get("account_id"),
- )
+ owner_fields = owner_fields_for_uri(uri)
context_data["uri"] = owner_fields["uri"]
if context_data.get("owner_user_id") is None:
if owner_fields is not None:
diff --git a/openviking/storage/vector_migration.py b/openviking/storage/vector_migration.py
index 635b53809..806233a3f 100644
--- a/openviking/storage/vector_migration.py
+++ b/openviking/storage/vector_migration.py
@@ -58,10 +58,6 @@ def _root_ctx(account_id: str) -> RequestContext:
return RequestContext(user=UserIdentifier(account_id, "default"), role=Role.ROOT)
-def _normalize_uri(uri: str) -> str:
- return VikingURI.normalize(uri).rstrip("/")
-
-
def _seed_uri_for_id(uri: str, level: Any) -> str:
try:
level_int = int(level)
@@ -154,8 +150,8 @@ async def copy_vector_records(
result.warnings.append(f"Skipped vector copy for {source_uri}: vector store is unavailable")
return result
- source_uri = _normalize_uri(source_uri)
- target_uri = _normalize_uri(target_uri)
+ source_uri = source_uri.rstrip("/")
+ target_uri = target_uri.rstrip("/")
ctx = _root_ctx(account_id)
try:
records = await _records_in_scope(
@@ -183,11 +179,7 @@ async def copy_vector_records(
continue
rewritten_uri = _rewrite_uri(source_record_uri, source_uri, target_uri)
- owner_fields = owner_fields_for_uri(
- rewritten_uri,
- user=ctx.user,
- account_id=account_id,
- )
+ owner_fields = owner_fields_for_uri(rewritten_uri)
level = record.get("level", 2)
payload = {
key: value
@@ -236,7 +228,7 @@ async def delete_vector_records(
result.warnings.append(f"Skipped vector cleanup for {uri}: vector store is unavailable")
return result
- uri = _normalize_uri(uri)
+ uri = uri.rstrip("/")
ctx = _root_ctx(account_id)
try:
records = await _records_in_scope(
diff --git a/openviking/storage/viking_fs/__init__.py b/openviking/storage/viking_fs/__init__.py
index 3062c56b3..dae95911c 100644
--- a/openviking/storage/viking_fs/__init__.py
+++ b/openviking/storage/viking_fs/__init__.py
@@ -21,6 +21,7 @@ import hashlib
import json
import os
import re
+import sys as _sys
import time
from contextlib import contextmanager
from dataclasses import dataclass, field
@@ -29,12 +30,11 @@ from typing import TYPE_CHECKING, Any, Callable, Dict, List, Optional, TypeVar,
from openviking.core.context import ContextLevel
from openviking.core.namespace import (
- canonicalize_uri,
- is_hidden_by_actor_peer_view,
- may_include_hidden_actor_peers,
+ is_accessible as namespace_is_accessible,
)
from openviking.core.namespace import (
- is_accessible as namespace_is_accessible,
+ is_hidden_by_actor_peer_view,
+ may_include_hidden_actor_peers,
)
from openviking.core.retrieval_targets import resolve_retrieval_targets
from openviking.pyagfs import AsyncAGFSClient
@@ -53,33 +53,19 @@ from openviking.server.error_mapping import is_not_found_error, map_exception
from openviking.server.identity import RequestContext, Role
from openviking.storage.expr import And, PathScope, RawDSL
from openviking.storage.internal_names import STORAGE_INTERNAL_ENTRY_NAMES
-from openviking.telemetry import get_current_telemetry
-from openviking.utils.image_search import build_multimodal_embedding_input
-from openviking.utils.time_utils import format_iso8601, get_current_timestamp, parse_iso_datetime
-from openviking_cli.exceptions import (
- FailedPreconditionError,
- InvalidArgumentError,
- NotFoundError,
- PermissionDeniedError,
- ResourceExhaustedError,
-)
-from openviking_cli.session.user_id import UserIdentifier
-from openviking_cli.utils.config.grep_config import GrepEngine
-from openviking_cli.utils.logger import get_logger
-from openviking_cli.utils.uri import VikingURI
# Import mixins
from openviking.storage.viking_fs import _base as _base_mod
from openviking.storage.viking_fs._access import _AccessMixin
from openviking.storage.viking_fs._base import (
+ _ABSTRACT_WORKER_COUNT,
+ _DEFAULT_GREP_FILE_CONCURRENCY,
+ _T,
LS_ALL_NODES,
SNAPSHOT_DIFF_MAX_FILE_BYTES,
SNAPSHOT_DIFF_MAX_LINES,
SNAPSHOT_DIFF_MAX_OUTPUT_BYTES,
SNAPSHOT_DIFF_TIMEOUT_MS,
- _ABSTRACT_WORKER_COUNT,
- _DEFAULT_GREP_FILE_CONCURRENCY,
- _T,
_ensure_non_empty_search_query,
_get_abstract_worker_count,
_get_cpu_count,
@@ -97,6 +83,20 @@ from openviking.storage.viking_fs._semantic import _SemanticMixin
from openviking.storage.viking_fs._snapshot import _SnapshotMixin
from openviking.storage.viking_fs._sync import SyncDiff, _SyncMixin
from openviking.storage.viking_fs._vector import _VectorMixin
+from openviking.telemetry import get_current_telemetry
+from openviking.utils.image_search import build_multimodal_embedding_input
+from openviking.utils.time_utils import format_iso8601, get_current_timestamp, parse_iso_datetime
+from openviking_cli.exceptions import (
+ FailedPreconditionError,
+ InvalidArgumentError,
+ NotFoundError,
+ PermissionDeniedError,
+ ResourceExhaustedError,
+)
+from openviking_cli.session.user_id import UserIdentifier
+from openviking_cli.utils.config.grep_config import GrepEngine
+from openviking_cli.utils.logger import get_logger
+from openviking_cli.utils.uri import VikingURI
if TYPE_CHECKING:
from openviking.storage.viking_vector_index_backend import VikingVectorIndexBackend
@@ -161,7 +161,6 @@ VikingFS.__module__ = __name__
# __getattr__; we also need to intercept writes so that assigning to
# ``openviking.storage.viking_fs._instance`` updates the real singleton in
# ``_base`` where ``get_viking_fs``/``init_viking_fs`` read/write it.
-import sys as _sys
class _ModuleProxy: # pragma: no cover - trivial proxy
diff --git a/openviking/storage/viking_fs/_access.py b/openviking/storage/viking_fs/_access.py
index 362ac3f85..15d50d6e2 100644
--- a/openviking/storage/viking_fs/_access.py
+++ b/openviking/storage/viking_fs/_access.py
@@ -1,26 +1,23 @@
# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
# SPDX-License-Identifier: AGPL-3.0
-"""Access control, URI normalization, path conversion, and visibility mixin for VikingFS."""
+"""Access control, URI/path conversion, and visibility mixin for VikingFS."""
-import contextvars
import hashlib
import json
import re
from contextlib import contextmanager
-from typing import TYPE_CHECKING, Any, Callable, Dict, List, Optional, Union
+from typing import Any, Callable, Dict, List, Optional, Union
from openviking.core.context import ContextLevel
from openviking.core.namespace import (
- canonicalize_uri,
- is_hidden_by_actor_peer_view,
- may_include_hidden_actor_peers,
- uri_parts,
+ is_accessible as namespace_is_accessible,
)
from openviking.core.namespace import (
- is_accessible as namespace_is_accessible,
+ is_hidden_by_actor_peer_view,
+ may_include_hidden_actor_peers,
)
from openviking.resource.watch_storage import is_watch_task_control_uri
-from openviking.server.error_mapping import is_not_found_error, map_exception
+from openviking.server.error_mapping import is_not_found_error
from openviking.server.identity import RequestContext, Role
from openviking.storage.internal_names import STORAGE_INTERNAL_ENTRY_NAMES
from openviking_cli.exceptions import (
@@ -31,10 +28,6 @@ from openviking_cli.exceptions import (
from openviking_cli.session.user_id import UserIdentifier
from openviking_cli.utils.uri import VikingURI
-if TYPE_CHECKING:
- from openviking.storage.viking_vector_index_backend import VikingVectorIndexBackend
- from openviking_cli.utils.config import GrepConfig, RerankConfig, RetrievalConfig
-
class _AccessMixin:
"""URI normalization, access control, path conversion, and visibility helpers."""
@@ -103,36 +96,30 @@ class _AccessMixin:
self._bound_ctx.reset(token)
@staticmethod
- def _normalize_uri(uri: str) -> str:
- """Normalize short-format URIs to the canonical viking:// form."""
- if uri.startswith("viking://"):
- return uri
- return VikingURI.normalize(uri)
-
- @classmethod
- def _normalized_uri_parts(cls, uri: str) -> tuple[str, List[str]]:
- """Normalize a URI and reject ambiguous or platform-specific path traversal forms."""
- normalized = cls._normalize_uri(uri)
- parts = [p for p in normalized[len("viking://") :].strip("/").split("/") if p]
+ def _safe_uri_parts(uri: str) -> List[str]:
+ """Split a canonical URI and reject unsafe path traversal forms."""
+ if not uri.startswith("viking://"):
+ raise ValueError("URI must start with 'viking://'")
+ parts = [p for p in uri[len("viking://") :].strip("/").split("/") if p]
for part in parts:
if part in {".", ".."}:
raise PermissionDeniedError(
- f"Unsafe URI traversal segment '{part}' in {normalized}",
- resource=normalized,
+ f"Unsafe URI traversal segment '{part}' in {uri}",
+ resource=uri,
)
if "\\" in part:
raise PermissionDeniedError(
- f"Unsafe URI path separator '\\\\' in component '{part}' of {normalized}",
- resource=normalized,
+ f"Unsafe URI path separator '\\\\' in component '{part}' of {uri}",
+ resource=uri,
)
if len(part) >= 2 and part[1] == ":" and part[0].isalpha():
raise PermissionDeniedError(
- f"Unsafe URI drive-prefixed component '{part}' in {normalized}",
- resource=normalized,
+ f"Unsafe URI drive-prefixed component '{part}' in {uri}",
+ resource=uri,
)
- return normalized, parts
+ return parts
# TODO: Once pathlock moves down into ragfs, stop reconstructing the
# encrypted mount-relative path in Python and derive the lock target from
@@ -160,38 +147,30 @@ class _AccessMixin:
def _ensure_access(self, uri: str, ctx: Optional[RequestContext]) -> None:
real_ctx = self._ctx_or_default(ctx)
- normalized_uri, _ = self._normalized_uri_parts(uri)
- if not self._is_accessible(normalized_uri, real_ctx):
- raise PermissionDeniedError(f"Access denied for {uri}", resource=normalized_uri)
+ if not self._is_accessible(uri, real_ctx):
+ raise PermissionDeniedError(f"Access denied for {uri}", resource=uri)
def _ensure_mutable_access(self, uri: str, ctx: Optional[RequestContext]) -> None:
self._ensure_access(uri, ctx)
real_ctx = self._ctx_or_default(ctx)
self._ensure_user_not_deleting(real_ctx)
- normalized_uri, _ = self._normalized_uri_parts(uri)
- if is_hidden_by_actor_peer_view(normalized_uri, real_ctx) or may_include_hidden_actor_peers(
- normalized_uri, real_ctx
- ):
- raise PermissionDeniedError(f"Access denied for {uri}", resource=normalized_uri)
- self._ensure_supported_write_namespace(normalized_uri)
- if real_ctx.role != Role.ROOT and normalized_uri.rstrip("/") == "viking://temp":
+ if is_hidden_by_actor_peer_view(uri, real_ctx) or may_include_hidden_actor_peers(uri, real_ctx):
+ raise PermissionDeniedError(f"Access denied for {uri}", resource=uri)
+ self._ensure_supported_write_namespace(uri)
+ if real_ctx.role != Role.ROOT and uri.rstrip("/") == "viking://temp":
raise PermissionDeniedError(
"Temp root is read-only for non-root users",
- resource=normalized_uri,
+ resource=uri,
)
def _ensure_delete_access(self, uri: str, ctx: Optional[RequestContext]) -> None:
self._ensure_access(uri, ctx)
real_ctx = self._ctx_or_default(ctx)
self._ensure_user_not_deleting(real_ctx)
- normalized_uri, _ = self._normalized_uri_parts(uri)
- if is_hidden_by_actor_peer_view(normalized_uri, real_ctx) or may_include_hidden_actor_peers(
- normalized_uri, real_ctx
- ):
- raise PermissionDeniedError(f"Access denied for {uri}", resource=normalized_uri)
- canonical_uri = canonicalize_uri(normalized_uri, real_ctx)
- self._ensure_supported_delete_namespace(canonical_uri)
- canonical_parts = uri_parts(canonical_uri)
+ if is_hidden_by_actor_peer_view(uri, real_ctx) or may_include_hidden_actor_peers(uri, real_ctx):
+ raise PermissionDeniedError(f"Access denied for {uri}", resource=uri)
+ self._ensure_supported_delete_namespace(uri)
+ canonical_parts = self._safe_uri_parts(uri)
if real_ctx.role != Role.ROOT and (
canonical_parts == ["resources"]
or (canonical_parts[:1] == ["user"] and len(canonical_parts) == 2)
@@ -199,12 +178,12 @@ class _AccessMixin:
raise PermissionDeniedError(
"Deleting a namespace root requires root access; use a concrete content "
"path instead.",
- resource=canonical_uri,
+ resource=uri,
)
- if real_ctx.role != Role.ROOT and normalized_uri.rstrip("/") == "viking://temp":
+ if real_ctx.role != Role.ROOT and uri.rstrip("/") == "viking://temp":
raise PermissionDeniedError(
"Temp root is read-only for non-root users",
- resource=normalized_uri,
+ resource=uri,
)
def _ensure_user_not_deleting(self, ctx: RequestContext) -> None:
@@ -383,7 +362,7 @@ class _AccessMixin:
path = candidate_path
break
if path is None:
- if self._is_legacy_session_root_uri(uri):
+ if self._is_session_root_uri(uri):
return
raise NotFoundError(uri, "directory")
@@ -456,15 +435,15 @@ class _AccessMixin:
"""
real_ctx = self._ctx_or_default(ctx)
account_id = real_ctx.account_id
- normalized_uri, legacy_parts = self._normalized_uri_parts(uri)
- if legacy_parts and legacy_parts[0] == "agent" and self._is_legacy_agent_id_uri(uri):
+ parts = self._safe_uri_parts(uri)
+ if parts[:1] == ["session"]:
+ raise ValueError(f"Legacy session URI is not accepted internally: {uri}")
+ if parts and parts[0] == "agent" and self._is_legacy_agent_id_uri(uri):
# Old format: viking://agent/{agent_id}/... — direct mapping for read-only compat
safe_parts = [
- self._shorten_component(p, self._MAX_FILENAME_BYTES) for p in legacy_parts
+ self._shorten_component(p, self._MAX_FILENAME_BYTES) for p in parts
]
return f"/local/{account_id}/{'/'.join(safe_parts)}"
- canonical_uri = canonicalize_uri(uri, real_ctx)
- _, parts = self._normalized_uri_parts(canonical_uri)
if not parts:
return f"/local/{account_id}"
@@ -474,32 +453,35 @@ class _AccessMixin:
def _legacy_session_path(self, uri: str, ctx: Optional[RequestContext] = None) -> str:
"""Map a legacy viking://session URI to its pre-user-namespace path."""
real_ctx = self._ctx_or_default(ctx)
- _, parts = self._normalized_uri_parts(uri)
+ parts = self._safe_uri_parts(uri)
safe_parts = [self._shorten_component(p, self._MAX_FILENAME_BYTES) for p in parts]
return f"/local/{real_ctx.account_id}/{'/'.join(safe_parts)}"
- def _legacy_current_user_session_path(
+ def _legacy_user_session_path(
self, uri: str, ctx: Optional[RequestContext] = None
) -> Optional[str]:
"""Return the legacy nested /session/{user_id}/{session_id} candidate."""
real_ctx = self._ctx_or_default(ctx)
- _, parts = self._normalized_uri_parts(uri)
- if len(parts) <= 1 or parts[0] != "session":
+ parts = self._safe_uri_parts(uri)
+ if len(parts) <= 3 or parts[0] != "user" or parts[2] != "sessions":
return None
- nested_parts = ["session", real_ctx.user.user_id, *parts[1:]]
+ nested_parts = ["session", parts[1], *parts[3:]]
safe_parts = [self._shorten_component(p, self._MAX_FILENAME_BYTES) for p in nested_parts]
return f"/local/{real_ctx.account_id}/{'/'.join(safe_parts)}"
- def _is_legacy_session_uri(self, uri: str) -> bool:
- _, parts = self._normalized_uri_parts(uri)
- return bool(parts and parts[0] == "session")
+ def _legacy_session_alias(self, uri: str) -> Optional[str]:
+ """Return the old storage alias for a canonical user session URI."""
+ parts = self._safe_uri_parts(uri)
+ if len(parts) < 3 or parts[0] != "user" or parts[2] != "sessions":
+ return None
+ suffix = parts[3:]
+ return "viking://session" + (f"/{'/'.join(suffix)}" if suffix else "")
- def _is_legacy_session_root_uri(self, uri: str) -> bool:
- _, parts = self._normalized_uri_parts(uri)
- return parts == ["session"]
+ def _is_session_root_uri(self, uri: str) -> bool:
+ return self._legacy_session_alias(uri) == "viking://session"
def _is_legacy_agent_id_uri(self, uri: str) -> bool:
- _, parts = self._normalized_uri_parts(uri)
+ parts = self._safe_uri_parts(uri)
return bool(
parts
and parts[0] == "agent"
@@ -511,10 +493,11 @@ class _AccessMixin:
"""Return read candidates for a URI, including legacy alias fallbacks."""
paths = [self._uri_to_path(uri, ctx=ctx)]
- if self._is_legacy_session_uri(uri):
+ legacy_uri = self._legacy_session_alias(uri)
+ if legacy_uri:
for candidate in (
- self._legacy_session_path(uri, ctx=ctx),
- self._legacy_current_user_session_path(uri, ctx=ctx),
+ self._legacy_session_path(legacy_uri, ctx=ctx),
+ self._legacy_user_session_path(uri, ctx=ctx),
):
if candidate and candidate not in paths:
paths.append(candidate)
@@ -529,8 +512,11 @@ class _AccessMixin:
) -> bool:
if path == primary_path:
return True
- if self._is_legacy_session_uri(request_uri):
- return await self._legacy_session_path_visible(path, ctx)
+ if self._legacy_session_alias(request_uri):
+ owner_user_id = self._safe_uri_parts(request_uri)[1]
+ return await self._legacy_session_path_visible(
+ path, owner_user_id=owner_user_id
+ )
return True
def _alias_uri_for_path(
@@ -542,23 +528,21 @@ class _AccessMixin:
ctx: Optional[RequestContext],
) -> str:
base = base_path.rstrip("/")
- normalized_request, request_parts = self._normalized_uri_parts(request_uri)
+ request_parts = self._safe_uri_parts(request_uri)
request_root = (
- normalized_request
- if normalized_request == "viking://"
- else normalized_request.rstrip("/")
+ request_uri if request_uri == "viking://" else request_uri.rstrip("/")
)
- preserve_request_alias = normalized_request in {"viking://", "viking://user"} or bool(
+ preserve_request_alias = request_uri in {"viking://", "viking://user"} or bool(
request_parts
- and (
- request_parts[0] == "session"
- or (request_parts[0] == "agent" and self._is_legacy_agent_id_uri(request_uri))
- )
+ and request_parts[0] == "agent"
+ and self._is_legacy_agent_id_uri(request_uri)
)
rel_path = entry_path[len(base) :].strip("/") if entry_path.startswith(base) else ""
if entry_path.startswith(base):
separator = "" if request_root.endswith("://") else "/"
candidate_uri = request_root if not rel_path else f"{request_root}{separator}{rel_path}"
+ if self._legacy_session_alias(request_uri):
+ return candidate_uri
if preserve_request_alias:
return candidate_uri
try:
@@ -620,7 +604,12 @@ class _AccessMixin:
return owner_hint == ctx.user.user_id
return True
- async def _legacy_session_path_visible(self, path: str, ctx: RequestContext) -> bool:
+ async def _legacy_session_path_visible(
+ self,
+ path: str,
+ *,
+ owner_user_id: str,
+ ) -> bool:
parts = [p for p in path.strip("/").split("/") if p]
try:
session_index = parts.index("session")
@@ -633,22 +622,24 @@ class _AccessMixin:
root_prefix = "/" + "/".join(parts[: session_index + 1])
direct_root = f"{root_prefix}/{suffix[0]}"
if await self._looks_like_legacy_session_dir(direct_root):
- return await self._legacy_session_visible(direct_root, ctx)
+ owner = await self._legacy_session_owner(direct_root)
+ return bool(owner) and owner == owner_user_id
if len(suffix) >= 2:
+ if suffix[0] != owner_user_id:
+ return False
nested_root = f"{root_prefix}/{suffix[0]}/{suffix[1]}"
if await self._looks_like_legacy_session_dir(nested_root):
- return await self._legacy_session_visible(
- nested_root,
- ctx,
- owner_hint=suffix[0],
- )
+ owner = await self._legacy_session_owner(nested_root)
+ return not owner or owner == owner_user_id
return True
async def _legacy_session_root_items(
self,
path: str,
ctx: RequestContext,
+ output_root_uri: str,
+ owner_user_id: str,
) -> List[tuple[Dict[str, Any], str]]:
try:
entries = await self._ls_entries(path)
@@ -664,11 +655,12 @@ class _AccessMixin:
continue
child_path = f"{path.rstrip('/')}/{name}"
if await self._looks_like_legacy_session_dir(child_path):
- if await self._legacy_session_visible(child_path, ctx):
- items.append((entry, f"viking://session/{name}"))
+ legacy_owner = await self._legacy_session_owner(child_path)
+ if legacy_owner == owner_user_id:
+ items.append((entry, f"{output_root_uri}/{name}"))
continue
- if ctx.role != Role.ROOT and name != ctx.user.user_id:
+ if name != owner_user_id:
continue
try:
nested_entries = await self._ls_entries(child_path)
@@ -684,7 +676,7 @@ class _AccessMixin:
if not await self._looks_like_legacy_session_dir(nested_path):
continue
if await self._legacy_session_visible(nested_path, ctx, owner_hint=name):
- items.append((nested, f"viking://session/{nested_name}"))
+ items.append((nested, f"{output_root_uri}/{nested_name}"))
return items
async def _session_root_items(
@@ -693,19 +685,23 @@ class _AccessMixin:
ctx: RequestContext,
) -> List[tuple[Dict[str, Any], str]]:
primary_path = self._uri_to_path(uri, ctx=ctx)
+ output_root_uri = uri.rstrip("/")
+ owner_user_id = self._safe_uri_parts(uri)[1]
by_name: Dict[str, tuple[Dict[str, Any], str]] = {}
try:
for entry in await self._ls_entries(primary_path, ctx=ctx):
name = entry.get("name", "")
if not name or name in {".", ".."}:
continue
- by_name[name] = (entry, f"viking://session/{name}")
+ by_name[name] = (entry, f"{output_root_uri}/{name}")
except Exception as exc:
if not is_not_found_error(exc):
raise
- legacy_path = self._legacy_session_path(uri, ctx=ctx)
- for entry, entry_uri in await self._legacy_session_root_items(legacy_path, ctx):
+ legacy_path = self._legacy_session_path("viking://session", ctx=ctx)
+ for entry, entry_uri in await self._legacy_session_root_items(
+ legacy_path, ctx, output_root_uri, owner_user_id
+ ):
name = entry.get("name", "")
if name and name not in by_name:
by_name[name] = (entry, entry_uri)
@@ -717,11 +713,11 @@ class _AccessMixin:
ctx: Optional[RequestContext] = None,
) -> List[tuple[Dict[str, Any], str]]:
real_ctx = self._ctx_or_default(ctx)
- if self._is_legacy_session_root_uri(uri):
+ if self._is_session_root_uri(uri):
return await self._session_root_items(uri, real_ctx)
primary_path = self._uri_to_path(uri, ctx=ctx)
- merge_paths = self._is_legacy_session_uri(uri)
+ merge_paths = self._legacy_session_alias(uri) is not None
found_path = False
last_not_found: Optional[Exception] = None
by_uri: Dict[str, tuple[Dict[str, Any], str]] = {}
@@ -759,9 +755,7 @@ class _AccessMixin:
Pure prefix replacement: strips /local/{account_id}/ and prepends viking://.
No implicit space stripping.
"""
- if path.startswith("viking://"):
- return path
- elif path.startswith("/local/"):
+ if path.startswith("/local/"):
inner = path[7:].strip("/")
if not inner:
return "viking://"
@@ -772,10 +766,7 @@ class _AccessMixin:
if not parts:
return "viking://"
return f"viking://{'/'.join(parts)}"
- elif path.startswith("/"):
- return f"viking:/{path}"
- else:
- return f"viking://{path}"
+ raise ValueError(f"AGFS path must start with '/local/': {path!r}")
def _looks_like_legacy_temp_leaf(self, value: str) -> bool:
return bool(re.match(r"^\d{8}_[0-9a-f]{6}$", value or ""))
@@ -789,14 +780,14 @@ class _AccessMixin:
def _is_accessible(self, uri: str, ctx: RequestContext) -> bool:
"""Check whether a URI is visible/accessible under current request context."""
- normalized_uri, parts = self._normalized_uri_parts(uri)
+ parts = self._safe_uri_parts(uri)
if ctx.role == Role.ROOT:
return True
- if is_hidden_by_actor_peer_view(normalized_uri, ctx):
+ if is_hidden_by_actor_peer_view(uri, ctx):
return False
if not parts:
return True
- if is_watch_task_control_uri(normalized_uri):
+ if is_watch_task_control_uri(uri):
return False
scope = parts[0]
@@ -820,7 +811,7 @@ class _AccessMixin:
if not ctx.actor_peer_id or len(parts) < 2:
return True
return parts[1] == ctx.actor_peer_id
- return namespace_is_accessible(normalized_uri, ctx)
+ return namespace_is_accessible(uri, ctx)
def _handle_agfs_read(self, result: Union[bytes, Any, None]) -> bytes:
"""Handle AGFSClient read return types consistently."""
@@ -876,12 +867,12 @@ class _AccessMixin:
— passing them through silently would result in a no-op commit and
confuse callers.
"""
- real_ctx = self._ctx_or_default(ctx)
- canonical = canonicalize_uri(uri, real_ctx)
- _, parts = self._normalized_uri_parts(canonical)
+ parts = self._safe_uri_parts(uri)
if not parts:
raise ValueError(f"git tree path cannot be the account root: {uri!r}")
first = parts[0]
+ if first == "session":
+ raise ValueError(f"Legacy session URI is not accepted internally: {uri}")
if first in self._GIT_INTERNAL_FIRST_SEGMENTS:
raise ValueError(f"git tree path rejects internal scope/segment {first!r}: {uri!r}")
return "/".join(parts)
@@ -889,7 +880,7 @@ class _AccessMixin:
def _tree_path_to_uri(self, tree_path: str) -> str:
"""Convert an account-relative git tree path to a viking:// URI.
- Inverse of :py:meth:`_uri_to_tree_path` (without context canonicalization).
+ Inverse of :py:meth:`_uri_to_tree_path`.
"""
cleaned = tree_path.strip("/")
if not cleaned:
diff --git a/openviking/storage/viking_fs/_grep.py b/openviking/storage/viking_fs/_grep.py
index aa9b8ca44..41212fc8b 100644
--- a/openviking/storage/viking_fs/_grep.py
+++ b/openviking/storage/viking_fs/_grep.py
@@ -6,9 +6,8 @@ import asyncio
import re
import sys
import time
-from typing import TYPE_CHECKING, Any, Callable, Dict, List, Optional
+from typing import Any, Callable, Dict, List, Optional
-from openviking.core.namespace import canonicalize_uri
from openviking.pyagfs.exceptions import AGFSNotSupportedError
from openviking.server.identity import RequestContext
from openviking.storage.expr import And, PathScope, RawDSL
@@ -20,11 +19,6 @@ def _pkg():
return sys.modules[__package__]
-if TYPE_CHECKING:
- from openviking.storage.viking_vector_index_backend import VikingVectorIndexBackend
- from openviking_cli.utils.config import GrepConfig, RerankConfig, RetrievalConfig
-
-
class _GrepMixin:
"""Grep and search-backend methods."""
@@ -63,10 +57,6 @@ class _GrepMixin:
Returns:
Dict with matches, count, match_count, files_scanned
"""
- real_ctx = self._ctx_or_default(ctx)
- uri = canonicalize_uri(uri, real_ctx)
- if exclude_uri:
- exclude_uri = canonicalize_uri(exclude_uri, real_ctx)
self._ensure_access(uri, ctx)
# Skip vector_store.count() — the count field is not needed for grep,
# and avoiding it saves one VikingDB API call.
diff --git a/openviking/storage/viking_fs/_ops.py b/openviking/storage/viking_fs/_ops.py
index ec9dcca01..beba09304 100644
--- a/openviking/storage/viking_fs/_ops.py
+++ b/openviking/storage/viking_fs/_ops.py
@@ -4,16 +4,15 @@
import asyncio
from datetime import datetime, timezone
-from typing import TYPE_CHECKING, Any, Callable, Dict, List, Optional, Union
+from typing import Any, Dict, List, Optional, Union
from openviking.core.namespace import (
- canonicalize_uri,
may_include_hidden_actor_peers,
)
from openviking.pyagfs.exceptions import (
+ AGFSClientError,
AGFSDirectoryNotEmptyError,
AGFSHTTPError,
- AGFSClientError,
)
from openviking.server.error_mapping import is_not_found_error, map_exception
from openviking.server.identity import RequestContext
@@ -21,22 +20,18 @@ from openviking.storage.expr import PathScope
from openviking.storage.internal_names import STORAGE_INTERNAL_ENTRY_NAMES
from openviking.storage.viking_fs._base import (
_ABSTRACT_WORKER_COUNT,
+ LS_ALL_NODES,
_ensure_non_empty_search_query,
_is_directory_not_empty_error,
logger,
- LS_ALL_NODES,
)
+from openviking.utils.time_utils import format_iso8601, parse_iso_datetime
from openviking_cli.exceptions import (
FailedPreconditionError,
InvalidArgumentError,
NotFoundError,
)
from openviking_cli.utils.uri import VikingURI
-from openviking.utils.time_utils import format_iso8601, parse_iso_datetime
-
-if TYPE_CHECKING:
- from openviking.storage.viking_vector_index_backend import VikingVectorIndexBackend
- from openviking_cli.utils.config import GrepConfig, RerankConfig, RetrievalConfig
class _OpsMixin:
@@ -151,9 +146,7 @@ class _OpsMixin:
if not vector_store:
return 0
try:
- target_canonical_uri = canonicalize_uri(
- self._path_to_uri(target_path, ctx=real_ctx), real_ctx
- )
+ target_canonical_uri = self._path_to_uri(target_path, ctx=real_ctx)
filter_expr = PathScope("uri", target_canonical_uri, depth=-1)
return await vector_store.count(filter=filter_expr, ctx=real_ctx)
except Exception as e:
@@ -287,10 +280,6 @@ class _OpsMixin:
details={"from_uri": old_uri, "to_uri": new_uri},
)
- real_ctx = self._ctx_or_default(ctx)
- old_uri = canonicalize_uri(old_uri, real_ctx)
- new_uri = canonicalize_uri(new_uri, real_ctx)
-
if is_dir:
lease = await self._async_agfs.pathlock_acquire_batch(
[
@@ -561,7 +550,7 @@ class _OpsMixin:
continue
raise
else:
- if self._is_legacy_session_root_uri(uri):
+ if self._is_session_root_uri(uri):
now = datetime.now(timezone.utc).isoformat()
return {
"name": "session",
@@ -579,11 +568,8 @@ class _OpsMixin:
try:
vector_store = self._get_vector_store()
if vector_store:
- target_canonical_uri = canonicalize_uri(
- self._path_to_uri(path, ctx=real_ctx), real_ctx
- )
- if not may_include_hidden_actor_peers(target_canonical_uri, real_ctx):
- filter_expr = PathScope("uri", target_canonical_uri, depth=-1)
+ if not may_include_hidden_actor_peers(uri, real_ctx):
+ filter_expr = PathScope("uri", uri, depth=-1)
result["count"] = await vector_store.count(
filter=filter_expr,
ctx=real_ctx,
@@ -628,7 +614,7 @@ class _OpsMixin:
path = candidate_path
break
if path is None:
- if self._is_legacy_session_root_uri(uri):
+ if self._is_session_root_uri(uri):
return {"matches": [], "count": 0}
raise NotFoundError(uri, "directory")
diff --git a/openviking/storage/viking_fs/_snapshot.py b/openviking/storage/viking_fs/_snapshot.py
index 938db3bad..0f1de09d7 100644
--- a/openviking/storage/viking_fs/_snapshot.py
+++ b/openviking/storage/viking_fs/_snapshot.py
@@ -4,10 +4,8 @@
import asyncio
import sys
-from typing import TYPE_CHECKING, Any, Dict, List, Optional, Union
+from typing import Any, Dict, List, Optional, Union
-from openviking.core.context import ContextLevel
-from openviking.core.namespace import canonicalize_uri
from openviking.pyagfs.exceptions import (
AGFSInvalidOperationError,
AGFSNotFoundError,
@@ -30,11 +28,6 @@ from openviking_cli.exceptions import (
def _pkg():
return sys.modules[__package__]
-if TYPE_CHECKING:
- from openviking.storage.viking_vector_index_backend import VikingVectorIndexBackend
- from openviking_cli.utils.config import GrepConfig, RerankConfig, RetrievalConfig
-
-
class _SnapshotMixin:
"""Snapshot/git-like version control (commit/restore/show/diff/log)."""
@@ -441,7 +434,6 @@ class _SnapshotMixin:
) -> Dict[str, Any]:
"""Return a unified text diff for one path between two snapshots."""
real_ctx = self._ctx_or_default(ctx)
- path = canonicalize_uri(path, ctx=real_ctx)
self._ensure_access(path, real_ctx)
from_meta: Optional[Dict[str, Any]] = None
diff --git a/openviking/storage/viking_vector_index_backend.py b/openviking/storage/viking_vector_index_backend.py
index 86ad2be10..b4cac16d6 100644
--- a/openviking/storage/viking_vector_index_backend.py
+++ b/openviking/storage/viking_vector_index_backend.py
@@ -10,7 +10,7 @@ from contextlib import asynccontextmanager
from dataclasses import dataclass
from typing import Any, AsyncIterator, Dict, List, Mapping, Optional
-from openviking.core.namespace import canonicalize_uri, uri_parts, visible_roots
+from openviking.core.namespace import uri_parts, visible_roots
from openviking.server.identity import RequestContext, Role
from openviking.storage.expr import And, Eq, FilterExpr, In, Or, PathScope, RawDSL
from openviking.storage.vectordb.collection.collection import Collection
@@ -1010,9 +1010,8 @@ class VikingVectorIndexBackend:
from openviking.utils.tags import merge_search_tags
- canonical_uri = canonicalize_uri(uri, ctx)
if levels is None:
- record = await self.fetch_by_uri(canonical_uri, ctx=ctx)
+ record = await self.fetch_by_uri(uri, ctx=ctx)
if not record or not record.get("id"):
return []
@@ -1020,7 +1019,7 @@ class VikingVectorIndexBackend:
if not full_records:
logger.warning(
"update_search_tags failed to fetch full exact record uri=%s account_id=%s id=%s",
- canonical_uri,
+ uri,
ctx.account_id,
record.get("id"),
)
@@ -1038,7 +1037,7 @@ class VikingVectorIndexBackend:
logger.warning(
"update_search_tags failed to merge exact record tags uri=%s "
"account_id=%s existing_tags=%s incoming_tags=%s error=%s",
- canonical_uri,
+ uri,
ctx.account_id,
updated_record.get("search_tags"),
tags,
@@ -1051,7 +1050,7 @@ class VikingVectorIndexBackend:
return []
records = await self.filter(
- filter=And([Eq("uri", canonical_uri), In("level", levels)]),
+ filter=And([Eq("uri", uri), In("level", levels)]),
limit=max(len(levels), 2),
output_fields=FETCH_BY_URI_OUTPUT_FIELDS,
ctx=ctx,
@@ -1075,7 +1074,7 @@ class VikingVectorIndexBackend:
if not full_record:
logger.warning(
"update_search_tags failed to fetch full leveled record uri=%s account_id=%s level=%s id=%s",
- canonical_uri,
+ uri,
ctx.account_id,
record.get("level"),
record.get("id"),
@@ -1093,7 +1092,7 @@ class VikingVectorIndexBackend:
logger.warning(
"update_search_tags failed to merge leveled record tags uri=%s "
"account_id=%s level=%s existing_tags=%s incoming_tags=%s error=%s",
- canonical_uri,
+ uri,
ctx.account_id,
updated_record.get("level"),
updated_record.get("search_tags"),
@@ -1356,7 +1355,7 @@ class VikingVectorIndexBackend:
ctx: RequestContext,
) -> List[Dict[str, Any]]:
conds: List[FilterExpr] = [
- PathScope("uri", canonicalize_uri(uri, ctx), depth=0),
+ PathScope("uri", uri, depth=0),
Eq("account_id", ctx.account_id),
]
if level is not None:
@@ -1391,10 +1390,9 @@ class VikingVectorIndexBackend:
async def delete_uris(self, ctx: RequestContext, uris: List[str]) -> None:
for uri in uris:
- canonical_uri = canonicalize_uri(uri, ctx)
conds: List[FilterExpr] = [
Eq("account_id", ctx.account_id),
- Or([Eq("uri", canonical_uri), In("uri", [f"{canonical_uri}/"])]),
+ Or([Eq("uri", uri), In("uri", [f"{uri}/"])]),
]
backend = self._get_backend_for_context(ctx)
@@ -1409,9 +1407,7 @@ class VikingVectorIndexBackend:
) -> bool:
import hashlib
- canonical_uri = canonicalize_uri(uri, ctx)
- canonical_new_uri = canonicalize_uri(new_uri, ctx)
- conds: List[FilterExpr] = [Eq("uri", canonical_uri), Eq("account_id", ctx.account_id)]
+ conds: List[FilterExpr] = [Eq("uri", uri), Eq("account_id", ctx.account_id)]
if levels:
conds.append(In("level", levels))
@@ -1427,8 +1423,8 @@ class VikingVectorIndexBackend:
if not record_ids:
logger.warning(
"update_uri_mapping found records without ids: uri=%s new_uri=%s account_id=%s",
- canonical_uri,
- canonical_new_uri,
+ uri,
+ new_uri,
ctx.account_id,
)
return False
@@ -1436,8 +1432,8 @@ class VikingVectorIndexBackend:
if not full_records:
logger.warning(
"update_uri_mapping failed to fetch full records: uri=%s new_uri=%s account_id=%s ids=%s",
- canonical_uri,
- canonical_new_uri,
+ uri,
+ new_uri,
ctx.account_id,
record_ids,
)
@@ -1461,21 +1457,21 @@ class VikingVectorIndexBackend:
except (TypeError, ValueError):
level = 2
- seed_uri = _seed_uri_for_id(canonical_new_uri, level)
+ seed_uri = _seed_uri_for_id(new_uri, level)
id_seed = f"{ctx.account_id}:{seed_uri}"
new_id = hashlib.md5(id_seed.encode("utf-8")).hexdigest()
updated = {
**record,
"id": new_id,
- "uri": canonical_new_uri,
+ "uri": new_uri,
}
vector = updated.get("vector")
if not vector:
logger.warning(
"update_uri_mapping skipped record without dense vector: old_uri=%s new_uri=%s level=%s account_id=%s id=%s",
- canonical_uri,
- canonical_new_uri,
+ uri,
+ new_uri,
level,
ctx.account_id,
record.get("id"),
@@ -1526,13 +1522,9 @@ class VikingVectorIndexBackend:
if context_type:
filters.append(Eq("context_type", context_type))
- canonical_targets = [
- canonicalize_uri(target_dir, ctx)
- for target_dir in target_directories or []
- if target_dir
- ]
+ targets = [target_dir for target_dir in target_directories or [] if target_dir]
tenant_filter = self._tenant_filter(ctx, context_type=context_type)
- if tenant_filter and self._targets_within_visible_roots(ctx, canonical_targets):
+ if tenant_filter and self._targets_within_visible_roots(ctx, targets):
# The target scopes are already narrower than the tenant-visible
# roots. Keep account isolation, but avoid recursively evaluating
# the broader path scopes as an additional filter.
@@ -1540,8 +1532,8 @@ class VikingVectorIndexBackend:
if tenant_filter:
filters.append(tenant_filter)
- if canonical_targets:
- uri_conds = [PathScope("uri", target_dir, depth=-1) for target_dir in canonical_targets]
+ if targets:
+ uri_conds = [PathScope("uri", target_dir, depth=-1) for target_dir in targets]
if uri_conds:
filters.append(Or(uri_conds))
@@ -1557,8 +1549,8 @@ class VikingVectorIndexBackend:
return self._merge_filters(*filters)
@staticmethod
- def _targets_within_visible_roots(ctx: RequestContext, canonical_targets: List[str]) -> bool:
- if not canonical_targets:
+ def _targets_within_visible_roots(ctx: RequestContext, targets: List[str]) -> bool:
+ if not targets:
return False
root_parts = [tuple(uri_parts(root)) for root in visible_roots(ctx)]
@@ -1567,7 +1559,7 @@ class VikingVectorIndexBackend:
len(target_parts) >= len(root) and target_parts[: len(root)] == root
for root in root_parts
)
- for target_parts in (tuple(uri_parts(target)) for target in canonical_targets)
+ for target_parts in (tuple(uri_parts(target)) for target in targets)
)
@staticmethod
diff --git a/openviking/utils/embedding_utils.py b/openviking/utils/embedding_utils.py
index e66b3eb0f..25e710396 100644
--- a/openviking/utils/embedding_utils.py
+++ b/openviking/utils/embedding_utils.py
@@ -384,7 +384,7 @@ async def vectorize_directory_meta(
embedding_queue = queue_manager.get_queue(queue_manager.EMBEDDING)
parent_uri = VikingURI(uri).parent.uri
- owner_space = owner_space_for_uri(uri, ctx)
+ owner_space = owner_space_for_uri(uri)
created_at, updated_at = await _resolve_context_timestamps(uri, ctx)
# Cap the abstract scalar below the bytes_row 65535-byte limit. #2774
@@ -539,7 +539,7 @@ async def vectorize_file(
updated_at=updated_at,
user=ctx.user,
account_id=ctx.account_id,
- owner_space=owner_space_for_uri(file_path, ctx),
+ owner_space=owner_space_for_uri(file_path),
)
content_type = await _resolve_resource_content_type(file_path, file_name, viking_fs, ctx)
diff --git a/openviking_cli/utils/uri.py b/openviking_cli/utils/uri.py
index 81fb24ae5..c88571fc9 100644
--- a/openviking_cli/utils/uri.py
+++ b/openviking_cli/utils/uri.py
@@ -19,16 +19,17 @@ class VikingURI:
Scopes:
- resources: Independent resource scope (viking://resources/{project}/...)
- - user: User scope (viking://user/...), including sessions under
- viking://user/{user_id}/sessions/{session_id}
+ - 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.
- 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/...)
Examples:
- viking://resources/my_project/docs/api
- - viking://user/memories/preferences/code_style
- - viking://user/skills/pdf
+ - viking://user/alice/memories/preferences/code_style
+ - viking://user/alice/skills/pdf
- viking://user/alice/sessions/session123/messages.jsonl
"""
@@ -50,13 +51,10 @@ class VikingURI:
"""
Initialize URI handler.
- Accepts both full-format (viking://...) and short-format (/resources, resources)
- URIs. Short-format URIs are automatically normalized to full format.
-
Args:
- uri: URI string (full or short format)
+ uri: URI string in full ``viking://`` format
"""
- self.uri = self.normalize(uri)
+ self.uri = uri
self._parsed = self._parse()
def _parse(self) -> Dict[str, str]:
@@ -83,7 +81,8 @@ class VikingURI:
# Parse scope
scope = path.split("/")[0]
if scope not in self.VISITABLE_SCOPES:
- raise ValueError(f"Invalid scope '{scope}'")
+ scope_names = ", ".join(sorted(self.VISITABLE_SCOPES))
+ raise ValueError(f"Invalid scope '{scope}'. Must be one of: {scope_names}")
return {
"scheme": self.SCHEME,
@@ -272,33 +271,6 @@ class VikingURI:
def __hash__(self) -> int:
return hash(self.uri)
- @staticmethod
- def normalize(uri: str) -> str:
- """
- Normalize URI by ensuring it has the viking:// scheme.
-
- If the input already starts with viking://, returns it as-is.
- If it starts with /, prepends viking:// (resulting in viking:///... which is invalid,
- so we strip leading / first).
- Otherwise, prepends viking://.
-
- Examples:
- "/resources/images" -> "viking://resources/images"
- "resources/images" -> "viking://resources/images"
- "viking://resources/images" -> "viking://resources/images"
-
- Args:
- uri: Input URI string
-
- Returns:
- Normalized URI with viking:// scheme
- """
- if uri.startswith(f"{VikingURI.SCHEME}://"):
- return uri
- # Strip leading slashes
- uri = uri.lstrip("/")
- return f"{VikingURI.SCHEME}://{uri}"
-
@classmethod
def create_temp_uri(cls, space: Optional[str] = None) -> str:
"""Create temp directory URI.
diff --git a/tests/agfs/test_viking_fs_git.py b/tests/agfs/test_viking_fs_git.py
index 5896be325..fd27face0 100644
--- a/tests/agfs/test_viking_fs_git.py
+++ b/tests/agfs/test_viking_fs_git.py
@@ -122,11 +122,11 @@ class TestUriToTreePath:
)
def test_session_uri(self, vfs):
- # ``session`` is a virtual scope: it canonicalizes into the owning
- # user's sessions subtree, and the git tree path mirrors that real
- # storage layout (so commit/restore target the actual stored bytes).
ctx = _make_ctx()
- assert vfs._uri_to_tree_path("viking://session", ctx=ctx) == "user/user1/sessions"
+ assert (
+ vfs._uri_to_tree_path("viking://user/user1/sessions", ctx=ctx)
+ == "user/user1/sessions"
+ )
def test_trailing_slash_kept_as_directory(self, vfs):
# Normalization may strip trailing slash; this is acceptable
diff --git a/tests/misc/test_ovpack_import_policy.py b/tests/misc/test_ovpack_import_policy.py
index b4b1db1a7..23d58071e 100644
--- a/tests/misc/test_ovpack_import_policy.py
+++ b/tests/misc/test_ovpack_import_policy.py
@@ -28,10 +28,13 @@ from openviking_cli.session.user_id import UserIdentifier
class FakeVikingFS:
- def __init__(self) -> None:
+ def __init__(self, existing_roots: set[str] | None = None) -> None:
self.written_files: list[str] = []
self.created_dirs: list[str] = []
self.tree_calls: list[str] = []
+ self.write_contexts: list[RequestContext] = []
+ self.existing_roots = existing_roots or set()
+ self.removed_roots: list[str] = []
async def stat(self, uri: str, ctx=None):
return {"uri": uri, "isDir": True}
@@ -40,10 +43,17 @@ class FakeVikingFS:
self.created_dirs.append(uri)
async def ls(self, uri: str, ctx=None):
+ if uri in self.existing_roots:
+ return []
raise NotFoundError(uri, "file")
+ async def rm(self, uri: str, recursive: bool = False, ctx=None):
+ assert recursive is True
+ self.removed_roots.append(uri)
+
async def write_file_bytes(self, uri: str, data: bytes, ctx=None):
self.written_files.append(uri)
+ self.write_contexts.append(ctx)
async def tree(self, uri: str, node_limit=None, level_limit=None, ctx=None):
self.tree_calls.append(uri)
@@ -171,7 +181,7 @@ class FakeBackupVikingFS:
def __init__(self) -> None:
self.binary_files = {
"viking://resources/README.md": b"hello",
- "viking://user/alice/sessions/sess_1/.meta.json": b'{"session_id":"sess_1"}',
+ "viking://user/resources/sessions/sess_1/.meta.json": b'{"session_id":"sess_1"}',
}
self.tree_contexts: list[tuple[str, RequestContext]] = []
@@ -199,26 +209,26 @@ class FakeBackupVikingFS:
if uri == "viking://user":
return [
{
- "rel_path": "alice",
- "uri": "viking://user/alice",
+ "rel_path": "resources",
+ "uri": "viking://user/resources",
"isDir": True,
"size": 0,
},
{
- "rel_path": "alice/sessions",
- "uri": "viking://user/alice/sessions",
+ "rel_path": "resources/sessions",
+ "uri": "viking://user/resources/sessions",
"isDir": True,
"size": 0,
},
{
- "rel_path": "alice/sessions/sess_1",
- "uri": "viking://user/alice/sessions/sess_1",
+ "rel_path": "resources/sessions/sess_1",
+ "uri": "viking://user/resources/sessions/sess_1",
"isDir": True,
"size": 0,
},
{
- "rel_path": "alice/sessions/sess_1/.meta.json",
- "uri": "viking://user/alice/sessions/sess_1/.meta.json",
+ "rel_path": "resources/sessions/sess_1/.meta.json",
+ "uri": "viking://user/resources/sessions/sess_1/.meta.json",
"isDir": False,
"size": 23,
},
@@ -605,7 +615,7 @@ async def test_backup_restore_contract(
manifest = json.loads(zf.read("openviking-backup/_ovpack/manifest.json").decode("utf-8"))
assert "openviking-backup/files/resources/README.md" in names
- assert "openviking-backup/files/user/alice/sessions/sess_1/.meta.json" in names
+ assert "openviking-backup/files/user/resources/sessions/sess_1/.meta.json" in names
assert all(ctx.role == Role.ROOT for _, ctx in backup_fs.tree_contexts)
assert manifest["root"] == {
"name": "openviking-backup",
@@ -614,34 +624,50 @@ async def test_backup_restore_contract(
"package_type": "backup",
}
assert manifest["scopes"] == ["resources", "user"]
+ user_entries = {
+ entry["path"]: entry
+ for entry in manifest["entries"]
+ if entry["path"].startswith("user/resources")
+ }
+ assert user_entries
+ assert {entry["user_id"] for entry in user_entries.values()} == {"resources"}
with pytest.raises(InvalidArgumentError, match=r"must be restored"):
await import_ovpack(FakeVikingFS(), str(temp_ovpack_path), "viking://", admin_ctx)
+ vectorization_calls: list[tuple[str, RequestContext]] = []
+
+ async def capture_vectorization(viking_fs, uri, ctx, **kwargs):
+ vectorization_calls.append((uri, ctx))
+
monkeypatch.setattr(
"openviking.storage.ovpack.operations._enqueue_direct_vectorization",
- AsyncMock(),
+ capture_vectorization,
)
fake_fs = FakeVikingFS()
fake_fs.ls = AsyncMock(return_value=[])
fake_fs.stat = AsyncMock(side_effect=FileNotFoundError())
fake_fs.rm = AsyncMock()
- restore_service = PackService(fake_fs)
-
assert (
- await restore_service.restore_ovpack(
- str(temp_ovpack_path),
- admin_ctx,
- on_conflict="overwrite",
+ await PackService(fake_fs).restore_ovpack(
+ str(temp_ovpack_path), ctx=admin_ctx, on_conflict="overwrite"
)
== "viking://"
)
assert fake_fs.written_files == [
"viking://resources/README.md",
- "viking://user/alice/sessions/sess_1/.meta.json",
+ "viking://user/resources/sessions/sess_1/.meta.json",
]
fake_fs.rm.assert_not_awaited()
+ assert all(ctx.role == Role.ROOT for ctx in fake_fs.write_contexts)
+ assert [uri for uri, _ in vectorization_calls] == [
+ "viking://resources",
+ "viking://user/resources",
+ ]
+ user_vector_ctx = vectorization_calls[1][1]
+ assert user_vector_ctx.user.user_id == "resources"
+ assert user_vector_ctx.role == Role.ROOT
assert "viking://user" not in fake_fs.created_dirs
diff --git a/tests/misc/test_vikingfs_uri_guard.py b/tests/misc/test_vikingfs_uri_guard.py
index 47ac343a6..e97d48f3f 100644
--- a/tests/misc/test_vikingfs_uri_guard.py
+++ b/tests/misc/test_vikingfs_uri_guard.py
@@ -65,7 +65,6 @@ class TestVikingFSURITraversalGuard:
[
"viking://resources/../_system/users.json",
"viking://resources/../../_system/accounts.json",
- "/resources/../_system/users.json",
"viking://resources/..\\..\\_system\\users.json",
"viking://resources/C:\\Windows\\System32",
],
@@ -74,7 +73,7 @@ class TestVikingFSURITraversalGuard:
fs = _make_viking_fs()
with pytest.raises(PermissionDeniedError, match="Unsafe URI"):
- fs._normalized_uri_parts(uri)
+ fs._uri_to_path(uri)
@pytest.mark.asyncio
async def test_read_file_rejects_traversal_before_agfs_read(self) -> None:
@@ -112,11 +111,8 @@ class TestVikingFSURITraversalGuard:
"uri",
[
"viking://",
- "/",
"viking://user",
"viking://user/",
- "/user",
- "user",
"viking://agent",
"viking://agent/",
],
@@ -163,7 +159,7 @@ class TestVikingFSURITraversalGuard:
fs.agfs.rm.assert_not_called()
@pytest.mark.parametrize(
- "uri", ["viking://user/alice", "viking://resources", "viking://session"]
+ "uri", ["viking://user/alice", "viking://resources"]
)
@pytest.mark.asyncio
async def test_rm_allows_maintenance_scope_roots_for_root(self, uri: str) -> None:
@@ -179,7 +175,6 @@ class TestVikingFSURITraversalGuard:
"uri",
[
"viking://user/alice/memories",
- "viking://user/memories",
"viking://resources/project",
],
)
@@ -199,7 +194,7 @@ class TestVikingFSURITraversalGuard:
fs.agfs.stat = AsyncMock(side_effect=RuntimeError("sentinel"))
with pytest.raises(RuntimeError, match="sentinel"):
- await fs.rm("viking://session", recursive=True, ctx=_user_ctx())
+ await fs.rm("viking://user/alice/sessions", recursive=True, ctx=_user_ctx())
fs.agfs.stat.assert_called_once_with("/local/acct1/user/alice/sessions")
@@ -245,16 +240,13 @@ class TestVikingFSURITraversalGuard:
@pytest.mark.parametrize(
("source_uri", "match"),
[
- # Bare account root: the net-new gap — rm() rejects it (#2873) but mv()'s
- # write guard alone used to let it through to the recursive source delete.
+ # Account root: rm() rejects it (#2873), and mv() must not let it
+ # through to the recursive source delete.
("viking://", "Deleting viking://"),
- ("/", "Deleting viking://"),
# viking://user is already blocked by the write guard; assert mv still
# refuses it (parity with rm) regardless of which guard fires first.
("viking://user", "viking://user is not supported"),
("viking://user/", "viking://user is not supported"),
- ("/user", "viking://user is not supported"),
- ("user", "viking://user is not supported"),
],
)
async def test_mv_rejects_protected_namespace_roots_in_source_before_side_effects(
diff --git a/tests/server/test_actor_peer_retrieval_targets.py b/tests/server/test_actor_peer_retrieval_targets.py
index 6f4d52368..dcbaac1dd 100644
--- a/tests/server/test_actor_peer_retrieval_targets.py
+++ b/tests/server/test_actor_peer_retrieval_targets.py
@@ -66,7 +66,7 @@ def test_actor_search_keeps_explicit_resource_target():
def test_actor_search_user_root_keeps_user_content_and_filters_peer_collection():
- targets = _target_dirs("viking://user", actor_peer_id="web-visitor-alice")
+ targets = _target_dirs("viking://user/support_bot", actor_peer_id="web-visitor-alice")
assert targets == [
"viking://user/support_bot/memories",
@@ -120,7 +120,7 @@ def test_actor_default_resource_targets_global_and_actor_peer_resources():
def test_explicit_user_memory_target_stays_self_memory_only():
- targets = _target_dirs("viking://user/memories")
+ targets = _target_dirs("viking://user/support_bot/memories")
assert targets == ["viking://user/support_bot/memories"]
diff --git a/tests/server/test_admin_api.py b/tests/server/test_admin_api.py
index 82b378ab5..6c559ee9c 100644
--- a/tests/server/test_admin_api.py
+++ b/tests/server/test_admin_api.py
@@ -304,7 +304,7 @@ async def test_create_user_paths_accept_initial_user_config(
viking_fs,
RequestContext(user=UserIdentifier(acct, "alice"), role=Role.ADMIN),
)
- assert alice_settings.resource_uri == "viking://user/resources/admin"
+ assert alice_settings.resource_uri == "viking://user/alice/resources/admin"
resp = await lightweight_admin_client.post(
f"/api/v1/admin/accounts/{acct}/users",
@@ -321,7 +321,7 @@ async def test_create_user_paths_accept_initial_user_config(
viking_fs,
RequestContext(user=UserIdentifier(acct, "bob"), role=Role.USER),
)
- assert bob_settings.resource_uri == "viking://user/resources/bob"
+ assert bob_settings.resource_uri == "viking://user/bob/resources/bob"
async def test_create_user_paths_ignore_deprecated_agent_evolution_config(
@@ -1241,7 +1241,7 @@ async def test_legacy_cleanup_removes_only_legacy_namespaces(
)
-async def test_legacy_agent_and_session_uri_reads_are_read_only(
+async def test_legacy_agent_uri_is_read_only_and_session_storage_uses_canonical_uri(
admin_service: OpenVikingService,
):
"""Old agent/session URIs remain readable but not mutable."""
@@ -1256,6 +1256,11 @@ async def test_legacy_agent_and_session_uri_reads_are_read_only(
"/local/default/session/old-session/messages.jsonl",
'{"role":"user"}\n',
)
+ await _agfs_write(
+ admin_service,
+ "/local/default/session/old-session/.meta.json",
+ '{"created_by_user_id":"admin_user"}',
+ )
assert (
await admin_service.viking_fs.read_file(
@@ -1266,7 +1271,7 @@ async def test_legacy_agent_and_session_uri_reads_are_read_only(
)
assert (
await admin_service.viking_fs.read_file(
- "viking://session/old-session/messages.jsonl",
+ "viking://user/admin_user/sessions/old-session/messages.jsonl",
ctx=ctx,
)
== '{"role":"user"}\n'
@@ -1277,8 +1282,6 @@ async def test_legacy_agent_and_session_uri_reads_are_read_only(
"blocked",
ctx=ctx,
)
- with pytest.raises(PermissionDeniedError):
- await admin_service.viking_fs.mkdir("viking://session/new-session", ctx=ctx)
@pytest_asyncio.fixture(scope="function")
diff --git a/tests/server/test_admin_rebuild_api.py b/tests/server/test_admin_rebuild_api.py
index 2ea3048cc..9a9b1cc4f 100644
--- a/tests/server/test_admin_rebuild_api.py
+++ b/tests/server/test_admin_rebuild_api.py
@@ -2922,7 +2922,7 @@ async def test_openviking_service_reindex_uses_default_root_context(monkeypatch)
@pytest.mark.asyncio
-async def test_openviking_service_reindex_canonicalizes_user_shorthand(monkeypatch):
+async def test_openviking_service_reindex_keeps_canonical_user_id(monkeypatch):
from openviking.service.core import OpenVikingService
seen = {}
@@ -2951,13 +2951,13 @@ async def test_openviking_service_reindex_canonicalizes_user_shorthand(monkeypat
result = await OpenVikingService.reindex(
service,
- uri="viking://user/memories",
+ uri="viking://user/resources/memories",
mode="prune_orphans",
wait=True,
dry_run=True,
ctx=ctx,
)
- assert result == {"status": "completed", "uri": "viking://user/alice/memories"}
- assert seen["uri"] == "viking://user/alice/memories"
+ assert result == {"status": "completed", "uri": "viking://user/resources/memories"}
+ assert seen["uri"] == "viking://user/resources/memories"
assert seen["ctx"] is ctx
diff --git a/tests/server/test_api_content_write.py b/tests/server/test_api_content_write.py
index 4e2bda395..ddfe4b10b 100644
--- a/tests/server/test_api_content_write.py
+++ b/tests/server/test_api_content_write.py
@@ -131,7 +131,7 @@ async def test_write_without_wait_is_immediately_readable(client_with_resource):
@pytest.mark.asyncio
async def test_write_missing_uri_validation(client):
resp = await client.post("/api/v1/content/write", json={"content": "missing uri"})
- assert resp.status_code == 422
+ assert resp.status_code == 400
@pytest.mark.asyncio
@@ -149,7 +149,7 @@ async def test_write_rejects_removed_semantic_flags(client_with_resource):
},
)
- assert resp.status_code == 422
+ assert resp.status_code == 400
async def test_api_create_mode_new_file_success(client):
diff --git a/tests/server/test_api_resources.py b/tests/server/test_api_resources.py
index 82cccc694..346b11d6b 100644
--- a/tests/server/test_api_resources.py
+++ b/tests/server/test_api_resources.py
@@ -528,9 +528,16 @@ async def test_add_resource_with_resources_root_to_uses_child_uri(
async def test_add_resource_with_user_resources_short_parent_initializes_root(
+ app,
client: httpx.AsyncClient,
upload_temp_dir,
):
+ from openviking.server.auth import get_request_context
+
+ app.dependency_overrides[get_request_context] = lambda: RequestContext(
+ user=UserIdentifier("default", "default"),
+ role=Role.USER,
+ )
archive_path = upload_temp_dir / "user_short_docs.zip"
with zipfile.ZipFile(archive_path, "w") as zf:
zf.writestr("user_short_docs/readme.md", "# hello\n")
diff --git a/tests/server/test_content_batch_write.py b/tests/server/test_content_batch_write.py
index 476628760..05ed34d4c 100644
--- a/tests/server/test_content_batch_write.py
+++ b/tests/server/test_content_batch_write.py
@@ -372,8 +372,8 @@ async def test_batch_refresh_groups_resource_and_memory_work(monkeypatch):
refresh_kinds={
"viking://resources/wiki/a.md": "added",
"viking://resources/wiki/b.md": "modified",
- "viking://user/memories/preferences/wiki/a.md": "added",
- "viking://user/memories/preferences/wiki/b.md": "modified",
+ "viking://user/default/memories/preferences/wiki/a.md": "added",
+ "viking://user/default/memories/preferences/wiki/b.md": "modified",
},
ctx=ctx,
wait=False,
diff --git a/tests/server/test_content_write_service.py b/tests/server/test_content_write_service.py
index 19f8c842f..c64f26787 100644
--- a/tests/server/test_content_write_service.py
+++ b/tests/server/test_content_write_service.py
@@ -813,8 +813,7 @@ async def test_create_mode_new_file_success(monkeypatch):
@pytest.mark.asyncio
-async def test_create_mode_canonicalizes_user_shorthand_memory_uri(monkeypatch):
- input_uri = "viking://user/memories/new_file.md"
+async def test_create_mode_refreshes_canonical_user_memory_uri(monkeypatch):
canonical_uri = "viking://user/default/memories/new_file.md"
root_uri = "viking://user/default/memories"
ctx = RequestContext(user=UserIdentifier.the_default_user(), role=Role.USER)
@@ -849,7 +848,7 @@ async def test_create_mode_canonicalizes_user_shorthand_memory_uri(monkeypatch):
)
result = await coordinator.write(
- uri=input_uri, content="new content", mode="create", ctx=ctx, wait=True
+ uri=canonical_uri, content="new content", mode="create", ctx=ctx, wait=True
)
assert result["uri"] == canonical_uri
diff --git a/tests/server/test_error_scenarios.py b/tests/server/test_error_scenarios.py
index c503e5f4d..1b9f0bc2f 100644
--- a/tests/server/test_error_scenarios.py
+++ b/tests/server/test_error_scenarios.py
@@ -98,17 +98,16 @@ async def test_wrong_content_type(client: httpx.AsyncClient):
async def test_invalid_uri_format(client: httpx.AsyncClient):
- """Invalid URI format triggers unhandled FileNotFoundError.
-
- BUG: The server should catch this and return a structured error response,
- but currently FileNotFoundError is not mapped to OpenVikingError.
- """
- resp = await client.get(
- "/api/v1/fs/ls",
- params={"uri": "viking://"},
- )
- # Valid URI should work
- assert resp.status_code == 200
+ """Public URI fields reject filesystem-like paths without a Viking scheme."""
+ for uri in ("resources", "/resources"):
+ resp = await client.get(
+ "/api/v1/fs/ls",
+ params={"uri": uri},
+ )
+ assert resp.status_code == 400
+ body = resp.json()
+ assert body["error"]["code"] == "INVALID_URI"
+ assert "viking://" in body["error"]["message"]
async def test_export_nonexistent_uri(client: httpx.AsyncClient):
diff --git a/tests/server/test_mcp_endpoint.py b/tests/server/test_mcp_endpoint.py
index e9282b775..889ec72e8 100644
--- a/tests/server/test_mcp_endpoint.py
+++ b/tests/server/test_mcp_endpoint.py
@@ -88,11 +88,12 @@ def test_get_ctx_raises_when_unset():
("uri", "expected"),
[
("viking://user", "viking://user/test_user"),
- ("viking://user/notes.md", "viking://user/test_user/notes.md"),
+ ("viking://user/notes.md", "viking://user/notes.md"),
(
"viking://user/project/notes.md",
- "viking://user/test_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",
@@ -100,8 +101,9 @@ def test_get_ctx_raises_when_unset():
("viking://resources/project/notes.md", "viking://resources/project/notes.md"),
],
)
-def test_resolve_mcp_workspace_uri_is_current_user_relative(uri, expected):
- assert _resolve_mcp_workspace_uri(uri, DEFAULT_CTX) == expected
+def test_resolve_mcp_workspace_uri_only_expands_documented_shorthands(uri, expected):
+ user_ctx = RequestContext(DEFAULT_CTX.user, Role.USER)
+ assert _resolve_mcp_workspace_uri(uri, user_ctx) == expected
def test_resolve_mcp_workspace_uri_supports_dotted_current_user_id():
@@ -114,9 +116,11 @@ def test_resolve_mcp_workspace_uri_supports_dotted_current_user_id():
_resolve_mcp_workspace_uri("viking://user/[email protected]/notes/todo.md", ctx)
== "viking://user/[email protected]/notes/todo.md"
)
- assert (
- _resolve_mcp_workspace_uri("viking://user/notes/todo.md", ctx)
- == "viking://user/[email protected]/notes/todo.md"
+ assert _resolve_mcp_workspace_uri("viking://user/notes/todo.md", ctx) == (
+ "viking://user/notes/todo.md"
+ )
+ assert _resolve_mcp_workspace_uri("viking://user/resources", DEFAULT_CTX) == (
+ "viking://user/resources"
)
@@ -268,7 +272,7 @@ async def test_find_tool_calls_lightweight_find(service, monkeypatch):
result = await mcp_endpoint.find(
query="fast lookup",
- target_uri="viking://user/project",
+ target_uri="viking://user/test_user/project",
limit=2,
min_score=0.2,
context_type=["memory", "resource"],
@@ -314,7 +318,7 @@ async def test_search_tool_calls_context_aware_search_with_session(service, monk
result = await search(
query="deep lookup",
- target_uri="viking://user/project",
+ target_uri="viking://user/test_user/project",
session_id="session-1",
limit=4,
min_score=0.1,
@@ -529,7 +533,7 @@ async def test_mcp_middleware_rejects_invalid_actor_peer_header():
async def test_read_nonexistent_uri(service):
- result = await read("viking://user/memories/does_not_exist.md")
+ result = await read("viking://user/test_user/memories/does_not_exist.md")
assert "not found" in result.lower()
@@ -548,8 +552,8 @@ async def test_read_directory_uri_returns_recoverable_hint(service):
async def test_read_batch(service):
result = await read(
[
- "viking://user/memories/does_not_exist_1.md",
- "viking://user/memories/does_not_exist_2.md",
+ "viking://user/test_user/memories/does_not_exist_1.md",
+ "viking://user/test_user/memories/does_not_exist_2.md",
]
)
assert "===" in result
@@ -563,7 +567,7 @@ async def test_read_delegates_to_visible_read(monkeypatch):
"get_service",
lambda: SimpleNamespace(fs=SimpleNamespace(read_visible=read_visible)),
)
- uri = "viking://user/project/private.md"
+ uri = "viking://user/test_user/project/private.md"
assert await read(uri) == "visible memory"
read_visible.assert_awaited_once_with(
@@ -587,7 +591,7 @@ async def test_list_empty_dir(service):
await service.viking_fs.mkdir(
"viking://user/test_user/memories/empty_test", ctx=ctx, exist_ok=True
)
- result = await list_tool("viking://user/memories/empty_test")
+ result = await list_tool("viking://user/test_user/memories/empty_test")
assert isinstance(result, str)
@@ -1012,7 +1016,11 @@ async def test_forget_by_uri_deletes_memory(service):
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)
- result = await forget(uri=uri)
+ token = _mcp_ctx.set(RequestContext(DEFAULT_CTX.user, Role.USER))
+ try:
+ result = await forget(uri=uri)
+ finally:
+ _mcp_ctx.reset(token)
assert "deleted" in result.lower()
assert "test_forget.md" in result
@@ -1205,7 +1213,7 @@ async def test_edit_noop_reports_no_changes(service):
async def test_edit_memory_file_preserves_metadata(service):
- uri = "viking://user/memories/preferences/test_edit_memory.md"
+ uri = "viking://user/test_user/memories/preferences/test_edit_memory.md"
await write(uri=uri, content="likes: tea\n")
raw_before = await service.fs.read(uri, ctx=DEFAULT_CTX)
assert "MEMORY_FIELDS" in raw_before
@@ -1221,27 +1229,35 @@ async def test_edit_memory_file_preserves_metadata(service):
async def test_write_user_shorthand_uri(service):
uri = "viking://user/memories/preferences/shorthand_write.md"
- result = await write(uri=uri, content="x")
+ 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
- visible = await service.fs.read_visible(uri, ctx=DEFAULT_CTX)
+ visible = await service.fs.read_visible(
+ "viking://user/test_user/memories/preferences/shorthand_write.md",
+ ctx=DEFAULT_CTX,
+ )
assert visible.strip() == "x"
-async def test_write_user_root_file_via_shorthand(service):
- # The first relative segment can be any file or directory name; MCP does
- # not guess from a file-extension allowlist.
- result = await write(uri="viking://user/project/zeus-persona.md", content="# Zeus persona\n")
+async def test_write_user_root_file_via_canonical_uri(service):
+ result = await write(
+ uri="viking://user/test_user/project/zeus-persona.md",
+ content="# Zeus persona\n",
+ )
assert "viking://user/test_user/project/zeus-persona.md" in result
body = await service.fs.read("viking://user/test_user/project/zeus-persona.md", ctx=DEFAULT_CTX)
assert body == "# Zeus persona\n"
async def test_write_plain_file_directly_at_user_root(service):
- # A file with no intermediate directory: the write coordinator anchors its
- # refresh at the user root itself, which is the shape the shorthand exists for.
- result = await write(uri="viking://user/persona.md", content="# Persona\n")
- assert "viking://user/test_user/persona.md" in result
- assert "# Persona" in await read(uris="viking://user/persona.md")
+ uri = "viking://user/test_user/persona.md"
+ result = await write(uri=uri, content="# Persona\n")
+ assert uri in result
+ assert "# Persona" in await read(uris=uri)
async def test_write_user_root_subdirectory_file(service):
@@ -1250,8 +1266,8 @@ async def test_write_user_root_subdirectory_file(service):
assert "- buy milk" in await read(uris=uri)
-async def test_edit_user_root_file_via_same_shorthand(service):
- uri = "viking://user/project/editable.md"
+async def test_edit_user_root_file_via_canonical_uri(service):
+ uri = "viking://user/test_user/project/editable.md"
await write(uri=uri, content="before\n")
result = await edit(uri=uri, old_string="before", new_string="after")
diff --git a/tests/server/test_watch_task_acl.py b/tests/server/test_watch_task_acl.py
index e42166190..67446f3c1 100644
--- a/tests/server/test_watch_task_acl.py
+++ b/tests/server/test_watch_task_acl.py
@@ -15,7 +15,7 @@ from openviking.resource.watch_storage import (
from openviking.server.identity import RequestContext, Role
from openviking.storage.content_write import ContentWriteCoordinator
from openviking.storage.viking_fs import VikingFS
-from openviking_cli.exceptions import InvalidArgumentError
+from openviking_cli.exceptions import InvalidArgumentError, PermissionDeniedError
from openviking_cli.session.user_id import UserIdentifier
@@ -36,6 +36,11 @@ def bare_viking_fs() -> VikingFS:
return fs
+class _NoWriteVikingFS:
+ def _ensure_mutable_access(self, uri, ctx):
+ raise AssertionError(f"mutable access should not be reached for {uri}")
+
+
@pytest.mark.parametrize(
"uri",
[
@@ -48,7 +53,7 @@ def test_watch_task_control_files_are_root_only(bare_viking_fs, root_ctx, user_c
assert bare_viking_fs._is_accessible(uri, root_ctx) is True
assert bare_viking_fs._is_accessible(uri, user_ctx) is False
- with pytest.raises(PermissionError):
+ with pytest.raises(PermissionDeniedError):
bare_viking_fs._ensure_access(uri, user_ctx)
@@ -56,29 +61,37 @@ def test_watch_task_control_files_are_root_only(bare_viking_fs, root_ctx, user_c
async def test_hidden_listing_filters_watch_task_control_files_for_non_root(
bare_viking_fs, root_ctx, user_ctx
):
+ async def ls_entries(path, ctx=None):
+ return [
+ {
+ "name": ".watch_tasks.json",
+ "isDir": False,
+ "size": 10,
+ "modTime": "2026-01-01T00:00:00+00:00",
+ },
+ {
+ "name": ".watch_tasks.json.bak",
+ "isDir": False,
+ "size": 10,
+ "modTime": "2026-01-01T00:00:00+00:00",
+ },
+ {
+ "name": ".watch_tasks.json.tmp",
+ "isDir": False,
+ "size": 10,
+ "modTime": "2026-01-01T00:00:00+00:00",
+ },
+ {
+ "name": "public.txt",
+ "isDir": False,
+ "size": 5,
+ "modTime": "2026-01-01T00:00:00+00:00",
+ },
+ ]
+
bare_viking_fs._uri_to_path = lambda uri, ctx=None: "/fake/resources"
bare_viking_fs._ctx_or_default = lambda ctx=None: ctx
- bare_viking_fs._ls_entries = lambda path: [
- {
- "name": ".watch_tasks.json",
- "isDir": False,
- "size": 10,
- "modTime": "2026-01-01T00:00:00+00:00",
- },
- {
- "name": ".watch_tasks.json.bak",
- "isDir": False,
- "size": 10,
- "modTime": "2026-01-01T00:00:00+00:00",
- },
- {
- "name": ".watch_tasks.json.tmp",
- "isDir": False,
- "size": 10,
- "modTime": "2026-01-01T00:00:00+00:00",
- },
- {"name": "public.txt", "isDir": False, "size": 5, "modTime": "2026-01-01T00:00:00+00:00"},
- ]
+ bare_viking_fs._ls_entries = ls_entries
bare_viking_fs._path_to_uri = lambda path, ctx=None: f"viking://resources/{path.split('/')[-1]}"
root_entries = await bare_viking_fs._ls_original(
@@ -114,24 +127,26 @@ async def test_hidden_listing_filters_watch_task_control_files_for_non_root(
WATCH_TASK_STORAGE_TMP_URI,
],
)
-def test_content_write_rejects_watch_task_control_files(uri):
- coordinator = object.__new__(ContentWriteCoordinator)
+async def test_content_write_rejects_watch_task_control_files(user_ctx, uri):
+ coordinator = ContentWriteCoordinator(_NoWriteVikingFS())
with pytest.raises(InvalidArgumentError, match="watch task control file"):
- coordinator._validate_target_uri(uri)
+ await coordinator.write(uri=uri, content="x", ctx=user_ctx)
@pytest.mark.parametrize(
"uri",
[
"viking://resources//.watch_tasks.json",
- "resources//.watch_tasks.json.bak",
- "/resources///.watch_tasks.json.tmp/",
+ "viking://resources//.watch_tasks.json.bak",
+ "viking://resources///.watch_tasks.json.tmp/",
],
)
-def test_redundant_separator_aliases_cannot_bypass_watch_task_acl(bare_viking_fs, user_ctx, uri):
+async def test_redundant_separator_aliases_cannot_bypass_watch_task_acl(
+ bare_viking_fs, user_ctx, uri
+):
assert bare_viking_fs._is_accessible(uri, user_ctx) is False
- coordinator = object.__new__(ContentWriteCoordinator)
+ coordinator = ContentWriteCoordinator(_NoWriteVikingFS())
with pytest.raises(InvalidArgumentError, match="watch task control file"):
- coordinator._validate_target_uri(uri)
+ await coordinator.write(uri=uri, content="x", ctx=user_ctx)
diff --git a/tests/service/test_resource_service_connector.py b/tests/service/test_resource_service_connector.py
index 0f1be63f0..b8a78a29f 100644
--- a/tests/service/test_resource_service_connector.py
+++ b/tests/service/test_resource_service_connector.py
@@ -996,15 +996,14 @@ async def test_postprocess_queue_message_drops_git_auth(ctx, service):
assert "secret-token" not in json.dumps(payload)
[email protected]("to", ["viking://resources/manuals", "resources/manuals"])
-def test_connector_route_accepts_public_exact_to(connector_config, ctx, service, to):
+def test_connector_route_accepts_public_exact_to(connector_config, ctx, service):
connector_config.allowed_add_types = ["tos", "git"]
assert (
service._connector.should_delegate(
"https://git.example/org/repo.git",
ctx=ctx,
- to=to,
+ to="viking://resources/manuals",
)
is True
)
diff --git a/tests/service/test_resource_service_parse_mode.py b/tests/service/test_resource_service_parse_mode.py
index fb045d9b2..f91ab68b6 100644
--- a/tests/service/test_resource_service_parse_mode.py
+++ b/tests/service/test_resource_service_parse_mode.py
@@ -279,22 +279,14 @@ async def test_no_split_allows_directory_flattening(
@pytest.mark.asyncio
- "to_uri",
- [
- "viking://resources/0803_shendiao_01",
- "viking://resources/0803_shendiao_01/",
- ],
-)
async def test_no_split_treats_explicit_to_as_directory_target(
service: ResourceService,
ctx: RequestContext,
- to_uri: str,
):
await service.add_resource(
path="/test/神雕.md",
ctx=ctx,
- to=to_uri,
+ to="viking://resources/0803_shendiao_01",
args={"parse_mode": "no_split"},
)
diff --git a/tests/service/test_session_service_metrics.py b/tests/service/test_session_service_metrics.py
index e9929b034..d8faff72e 100644
--- a/tests/service/test_session_service_metrics.py
+++ b/tests/service/test_session_service_metrics.py
@@ -82,37 +82,26 @@ async def test_sessions_returns_empty_and_logs_when_storage_listing_fails(
result = await service.sessions(ctx)
assert result == []
- assert debug.call_count == 2
+ assert debug.call_count == 1
@pytest.mark.asyncio
-async def test_sessions_merges_canonical_and_legacy_session_scope():
+async def test_sessions_uses_canonical_scope_and_relies_on_storage_compatibility():
service = SessionService(viking_fs=Mock())
ctx = _make_ctx()
async def _ls(uri, ctx, **kwargs):
+ assert uri == "viking://user/alice/sessions"
assert kwargs == {"sort_by": "mtime", "sort_order": "desc"}
- if uri == "viking://user/alice/sessions":
- return [
- {"name": "duplicate", "isDir": True, "modTime": "2026-07-13T01:00:00Z"},
- {"name": "new-session", "isDir": True, "modTime": "2026-07-13T02:00:00Z"},
- ]
- if uri == "viking://session":
- return [
- {
- "name": "duplicate",
- "uri": "viking://session/duplicate",
- "isDir": True,
- "modTime": "2026-07-13T01:00:00Z",
- },
- {
- "name": "legacy-session",
- "uri": "viking://session/legacy-session",
- "isDir": True,
- "modTime": "2026-07-12T01:00:00Z",
- },
- ]
- raise AssertionError(uri)
+ return [
+ {"name": "duplicate", "isDir": True, "modTime": "2026-07-13T01:00:00Z"},
+ {"name": "new-session", "isDir": True, "modTime": "2026-07-13T02:00:00Z"},
+ {
+ "name": "legacy-session",
+ "isDir": True,
+ "modTime": "2026-07-12T01:00:00Z",
+ },
+ ]
service._viking_fs.ls = AsyncMock(side_effect=_ls)
@@ -133,8 +122,9 @@ async def test_sessions_merges_canonical_and_legacy_session_scope():
},
{
"session_id": "legacy-session",
- "uri": "viking://session/legacy-session",
+ "uri": "viking://user/alice/sessions/legacy-session",
"is_dir": True,
"mod_time": "2026-07-12T01:00:00Z",
},
]
+ service._viking_fs.ls.assert_awaited_once()
diff --git a/tests/session/test_tool_result_externalization.py b/tests/session/test_tool_result_externalization.py
index 9639c86e8..c11bec603 100644
--- a/tests/session/test_tool_result_externalization.py
+++ b/tests/session/test_tool_result_externalization.py
@@ -136,7 +136,7 @@ async def test_list_tool_results_filters_tool_name_before_limit():
store = ToolResultStore(
FakeVikingFS(),
- "viking://session/filter-before-limit",
+ "viking://user/alice/sessions/filter-before-limit",
"filter-before-limit",
ctx=None,
)
diff --git a/tests/storage/test_content_write_processing_mode.py b/tests/storage/test_content_write_processing_mode.py
index 9b4ce79cb..3aa3a029c 100644
--- a/tests/storage/test_content_write_processing_mode.py
+++ b/tests/storage/test_content_write_processing_mode.py
@@ -218,8 +218,8 @@ async def test_memory_write_accepts_processing_mode_without_switching_refresh(mo
coordinator._write_in_place = AsyncMock()
result = await coordinator._write_memory_with_refresh(
- uri="viking://user/memories/demo.md",
- root_uri="viking://user/memories",
+ uri="viking://user/user-1/memories/demo.md",
+ root_uri="viking://user/user-1/memories",
content="updated",
mode="replace",
wait=True,
diff --git a/tests/storage/test_embedding_msg_converter_tenant.py b/tests/storage/test_embedding_msg_converter_tenant.py
index 9a841a1c4..a20595406 100644
--- a/tests/storage/test_embedding_msg_converter_tenant.py
+++ b/tests/storage/test_embedding_msg_converter_tenant.py
@@ -14,8 +14,8 @@ from openviking_cli.session.user_id import UserIdentifier
("uri", "expected_uri", "expected_owner_user_id"),
[
(
- "viking://user/memories/preferences/me.md",
- lambda user: f"viking://user/{user.user_id}/memories/preferences/me.md",
+ "viking://user/alice/memories/preferences/me.md",
+ "viking://user/alice/memories/preferences/me.md",
lambda user: user.user_id,
),
(
diff --git a/tests/storage/test_memory_semantic_stall.py b/tests/storage/test_memory_semantic_stall.py
index d58d9882a..3dbf9fb1e 100644
--- a/tests/storage/test_memory_semantic_stall.py
+++ b/tests/storage/test_memory_semantic_stall.py
@@ -16,7 +16,7 @@ from openviking.storage.queuefs.semantic_msg import SemanticMsg
from openviking.storage.queuefs.semantic_processor import SemanticProcessor
-def _make_msg(uri="viking://user/memories", context_type="memory", **kwargs):
+def _make_msg(uri="viking://user/usr1/memories", context_type="memory", **kwargs):
"""Build a minimal SemanticMsg for testing."""
defaults = {
"id": "test-msg-1",
diff --git a/tests/storage/test_semantic_dag_skip_files.py b/tests/storage/test_semantic_dag_skip_files.py
index 4a09b8041..10859e669 100644
--- a/tests/storage/test_semantic_dag_skip_files.py
+++ b/tests/storage/test_semantic_dag_skip_files.py
@@ -73,15 +73,9 @@ class _FakeProcessor:
@pytest.mark.asyncio
- "root_uri",
- [
- "viking://session/test-session",
- "viking://user/user1/sessions/test-session",
- ],
-)
-async def test_messages_jsonl_excluded_from_summary(monkeypatch, root_uri):
+async def test_messages_jsonl_excluded_from_summary(monkeypatch):
"""messages.jsonl should be skipped by _list_dir and never summarized."""
+ root_uri = "viking://user/user1/sessions/test-session"
tree = {
root_uri: [
{"name": "messages.jsonl", "isDir": False},
@@ -109,15 +103,9 @@ async def test_messages_jsonl_excluded_from_summary(monkeypatch, root_uri):
@pytest.mark.asyncio
- "root_uri",
- [
- "viking://session/test-session",
- "viking://user/user1/sessions/test-session",
- ],
-)
-async def test_messages_jsonl_excluded_in_subdirectory(monkeypatch, root_uri):
+async def test_messages_jsonl_excluded_in_subdirectory(monkeypatch):
"""messages.jsonl in a subdirectory should also be skipped."""
+ root_uri = "viking://user/user1/sessions/test-session"
tree = {
root_uri: [
{"name": "subdir", "isDir": True},
diff --git a/tests/storage/test_semantic_processor_mv_vector_store.py b/tests/storage/test_semantic_processor_mv_vector_store.py
index ea0011c87..389b66933 100644
--- a/tests/storage/test_semantic_processor_mv_vector_store.py
+++ b/tests/storage/test_semantic_processor_mv_vector_store.py
@@ -8,18 +8,19 @@ from openviking_cli.session.user_id import UserIdentifier
@pytest.mark.asyncio
-async def test_mv_canonicalizes_user_shorthand_before_vector_update(monkeypatch):
+async def test_mv_preserves_canonical_user_uris_for_vector_update(monkeypatch):
ctx = RequestContext(user=UserIdentifier("acc", "default"), role=Role.ROOT)
fs = VikingFS.__new__(VikingFS)
fs._async_agfs = AsyncMock()
fs._async_agfs.stat.return_value = {"isDir": False}
+ fs._async_agfs.pathlock_acquire_batch.return_value = {"lease_ref": "lease-1"}
fs._collect_uris = AsyncMock(return_value=[])
fs._copy_for_mv = AsyncMock()
fs._update_vector_store_uris = AsyncMock()
await fs.mv(
- "viking://user/peers/vaka/memories/profile.md",
- "viking://user/memories/profile.md",
+ "viking://user/default/peers/vaka/memories/profile.md",
+ "viking://user/default/memories/profile.md",
ctx=ctx,
)
diff --git a/tests/storage/test_session_commit_processor_identity.py b/tests/storage/test_session_commit_processor_identity.py
index 7b9bce2b7..f8a9e9df4 100644
--- a/tests/storage/test_session_commit_processor_identity.py
+++ b/tests/storage/test_session_commit_processor_identity.py
@@ -71,8 +71,8 @@ def _make_msg() -> SessionCommitMsg:
return SessionCommitMsg(
task_id="task-1",
session_id="sess-1",
- session_uri="viking://sessions/sess-1",
- archive_uri="viking://sessions/sess-1/history/archive_001",
+ session_uri="viking://user/alice/sessions/sess-1",
+ archive_uri="viking://user/alice/sessions/sess-1/history/archive_001",
user={"account_id": "acme", "user_id": "alice"},
)
diff --git a/tests/storage/test_viking_fs_actor_peer_view.py b/tests/storage/test_viking_fs_actor_peer_view.py
index c293afc72..d0d18d57f 100644
--- a/tests/storage/test_viking_fs_actor_peer_view.py
+++ b/tests/storage/test_viking_fs_actor_peer_view.py
@@ -33,6 +33,9 @@ class _MemoryAGFS:
"/local/acct/session/legacy-session/messages.jsonl": (
b'{"role":"user","content":"legacy"}\n'
),
+ "/local/acct/session/legacy-session/.meta.json": (
+ b'{"created_by_user_id":"support_bot"}'
+ ),
"/local/acct/session/other-owned/.meta.json": b'{"created_by_user_id":"other"}',
"/local/acct/session/other-owned/messages.jsonl": (
b'{"role":"user","content":"other"}\n'
@@ -205,29 +208,30 @@ async def test_actor_peer_view_filters_legacy_agent_collection(fs, actor_ctx):
@pytest.mark.asyncio
async def test_legacy_session_scope_merges_new_and_unmigrated_sessions(fs, actor_ctx):
- entries = await fs.ls("viking://session", ctx=actor_ctx)
+ session_root = "viking://user/support_bot/sessions"
+ entries = await fs.ls(session_root, ctx=actor_ctx)
assert [entry["uri"] for entry in entries] == [
- "viking://session/duplicate",
- "viking://session/new-session",
- "viking://session/legacy-session",
- "viking://session/nested-session",
+ f"{session_root}/duplicate",
+ f"{session_root}/new-session",
+ f"{session_root}/legacy-session",
+ f"{session_root}/nested-session",
]
assert (
- await fs.read_file("viking://session/duplicate/messages.jsonl", ctx=actor_ctx)
+ await fs.read_file(f"{session_root}/duplicate/messages.jsonl", ctx=actor_ctx)
== '{"role":"user","content":"new"}\n'
)
assert (
- await fs.read_file("viking://session/legacy-session/messages.jsonl", ctx=actor_ctx)
+ await fs.read_file(f"{session_root}/legacy-session/messages.jsonl", ctx=actor_ctx)
== '{"role":"user","content":"legacy"}\n'
)
assert (
- await fs.read_file("viking://session/nested-session/messages.jsonl", ctx=actor_ctx)
+ await fs.read_file(f"{session_root}/nested-session/messages.jsonl", ctx=actor_ctx)
== '{"role":"user","content":"nested"}\n'
)
with pytest.raises(NotFoundError):
- await fs.read_file("viking://session/other-owned/messages.jsonl", ctx=actor_ctx)
+ await fs.read_file(f"{session_root}/other-owned/messages.jsonl", ctx=actor_ctx)
@pytest.mark.asyncio
diff --git a/tests/storage/test_viking_fs_glob.py b/tests/storage/test_viking_fs_glob.py
index 754ff5a73..6ffe35d66 100644
--- a/tests/storage/test_viking_fs_glob.py
+++ b/tests/storage/test_viking_fs_glob.py
@@ -258,8 +258,7 @@ async def test_glob_keeps_directory_matches(monkeypatch, fs):
@pytest.mark.asyncio
-async def test_glob_preserves_legacy_session_alias(monkeypatch, fs):
- """中文注释:legacy session URI 仍应保持旧别名返回。"""
+async def test_glob_preserves_canonical_session_uri(monkeypatch, fs):
monkeypatch.setattr(
fs, "_uri_to_path", lambda _uri, **_kwargs: "/local/test_account/user/alice/sessions/sess_1"
)
@@ -284,9 +283,16 @@ async def test_glob_preserves_legacy_session_alias(monkeypatch, fs):
monkeypatch.setattr(fs._async_agfs, "glob_directory", fake_glob_directory)
- result = await fs.glob("**/*.jsonl", uri="viking://session/alice/sess_1", ctx=_default_ctx())
+ result = await fs.glob(
+ "**/*.jsonl",
+ uri="viking://user/alice/sessions/sess_1",
+ ctx=_default_ctx(),
+ )
- assert result == {"matches": ["viking://session/alice/sess_1/messages.jsonl"], "count": 1}
+ assert result == {
+ "matches": ["viking://user/alice/sessions/sess_1/messages.jsonl"],
+ "count": 1,
+ }
@pytest.mark.asyncio
diff --git a/tests/storage/test_viking_vector_scope_filter.py b/tests/storage/test_viking_vector_scope_filter.py
index a250068e5..d7acc5f5b 100644
--- a/tests/storage/test_viking_vector_scope_filter.py
+++ b/tests/storage/test_viking_vector_scope_filter.py
@@ -80,7 +80,7 @@ def test_all_targets_may_be_under_different_visible_roots():
ctx = _ctx()
targets = [
"viking://resources/wiki/physics",
- "viking://user/resources/private-notes",
+ "viking://user/alice/resources/private-notes",
"viking://agent/skills/research",
]
diff --git a/tests/unit/test_context.py b/tests/unit/test_context.py
index a3f2cb40a..732ad1a53 100644
--- a/tests/unit/test_context.py
+++ b/tests/unit/test_context.py
@@ -476,14 +476,14 @@ class TestContextWithUser:
ctx = Context(uri="viking://user/test/memories/test.md", user=user)
assert ctx.owner_user_id == "test"
- assert ctx.owner_space == user.user_id
+ assert ctx.owner_space == "test"
def test_owner_fields_session(self):
"""Test owner fields for session URI."""
user = UserIdentifier(account_id="account-123", user_id="user-123")
- ctx = Context(uri="viking://session/test/msg/1.md", user=user)
+ ctx = Context(uri="viking://user/user-123/sessions/test/msg/1.md", user=user)
- assert ctx.owner_user_id is None
+ assert ctx.owner_user_id == user.user_id
assert ctx.owner_space == user.user_id
def test_owner_fields_resource_default(self):
diff --git a/tests/unit/test_namespace_uri_classification.py b/tests/unit/test_namespace_uri_classification.py
index dbc3f4acc..3919cf449 100644
--- a/tests/unit/test_namespace_uri_classification.py
+++ b/tests/unit/test_namespace_uri_classification.py
@@ -6,12 +6,13 @@ import pytest
from openviking.core.namespace import (
canonical_session_uri,
- canonicalize_uri,
classify_uri,
context_type_for_uri,
is_content_root_uri,
is_session_uri,
owner_space_for_uri,
+ resolve_request_uri,
+ resolve_uri,
visible_roots,
)
from openviking.core.uri_validation import validate_content_target_uri
@@ -22,9 +23,9 @@ from openviking_cli.session.user_id import UserIdentifier
def test_context_type_for_uri_uses_path_segments():
assert context_type_for_uri("viking://user/alice/memories/entities/m1.md") == "memory"
- assert context_type_for_uri("viking://user/memories/entities/m1.md") == "memory"
+ assert context_type_for_uri("viking://user/memories/entities/m1.md") == "resource"
assert context_type_for_uri("viking://user/alice/skills/demo") == "skill"
- assert context_type_for_uri("viking://user/skills/demo") == "skill"
+ assert context_type_for_uri("viking://user/skills/demo") == "resource"
assert (
context_type_for_uri(
"viking://user/support_bot/peers/web-visitor-alice/memories/profile.md"
@@ -75,12 +76,12 @@ def test_user_content_target_uri_rejects_invalid_user_id():
def test_exact_memory_and_skill_root_detection():
assert classify_uri("viking://user/alice/memories/preferences/prefs.md").is_memory
assert classify_uri("viking://user/alice/memories").is_memory_root
- assert classify_uri("viking://user/memories").is_memory_root
+ assert not classify_uri("viking://user/memories").is_memory_root
assert not classify_uri("viking://user/alice/memories/preferences").is_memory_root
assert classify_uri("viking://user/alice/skills/demo/SKILL.md").is_skill
assert classify_uri("viking://user/alice/skills/demo").is_skill_root
- assert classify_uri("viking://user/skills/demo").is_skill_root
+ assert not classify_uri("viking://user/skills/demo").is_skill_root
assert classify_uri("viking://agent/skills").is_skill_namespace
assert classify_uri("viking://agent/skills/demo").is_skill_root
assert not classify_uri("viking://user/alice/skills").is_skill_root
@@ -88,14 +89,9 @@ def test_exact_memory_and_skill_root_detection():
def test_owner_space_for_uri_uses_user_only():
- ctx = RequestContext(
- user=UserIdentifier(account_id="acct", user_id="alice"),
- role=Role.ROOT,
- )
-
- assert owner_space_for_uri("viking://user/alice/memories", ctx) == "alice"
- assert owner_space_for_uri("viking://user/alice/skills/demo", ctx) == "alice"
- assert owner_space_for_uri("viking://resources/readme.md", ctx) == ""
+ assert owner_space_for_uri("viking://user/alice/memories") == "alice"
+ assert owner_space_for_uri("viking://user/alice/skills/demo") == "alice"
+ assert owner_space_for_uri("viking://resources/readme.md") == ""
def test_session_uri_helpers_use_user_namespace():
@@ -106,15 +102,23 @@ 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 canonicalize_uri("viking://user/sessions/s1", ctx) == ("viking://user/alice/sessions/s1")
- assert canonicalize_uri("user/sessions/s1", ctx) == "viking://user/alice/sessions/s1"
- assert canonicalize_uri("viking://session/s1", ctx) == "viking://user/alice/sessions/s1"
+ assert resolve_uri("viking://user/sessions/s1").uri == "viking://user/sessions/s1"
+ assert (
+ 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"
+ )
assert (
- canonicalize_uri("viking://session/s1/history/archive_001/messages.jsonl", ctx)
+ resolve_request_uri(
+ "viking://session/s1/history/archive_001/messages.jsonl", ctx
+ )
== "viking://user/alice/sessions/s1/history/archive_001/messages.jsonl"
)
assert is_session_uri("viking://user/alice/sessions/s1")
- assert is_session_uri("viking://user/sessions/s1")
+ assert not is_session_uri("viking://user/sessions/s1")
assert is_session_uri("viking://session/s1")
roots = visible_roots(ctx)
assert "viking://session" not in roots
@@ -122,15 +126,18 @@ def test_session_uri_helpers_use_user_namespace():
assert "viking://agent/skills" in roots
-def test_current_user_short_content_roots_are_canonicalized_from_content_segments():
+def test_request_boundary_expands_current_user_content_roots():
ctx = RequestContext(
user=UserIdentifier(account_id="acct", user_id="alice"),
role=Role.USER,
)
- assert canonicalize_uri("viking://user/resources", ctx) == "viking://user/alice/resources"
assert (
- canonicalize_uri("viking://user/resources/docs", ctx)
+ resolve_request_uri("viking://user/resources", ctx)
+ == "viking://user/alice/resources"
+ )
+ assert (
+ resolve_request_uri("viking://user/resources/docs", ctx)
== "viking://user/alice/resources/docs"
)
assert (
@@ -142,41 +149,59 @@ def test_current_user_short_content_roots_are_canonicalized_from_content_segment
)
== "viking://user/alice/resources"
)
- assert canonicalize_uri("viking://user/alice/resources", ctx) == (
- "viking://user/alice/resources"
+ assert (
+ validate_content_target_uri(
+ "viking://resources/docs/",
+ ctx,
+ kind="resource",
+ field_name="parent",
+ )
+ == "viking://resources/docs"
)
- assert is_content_root_uri("viking://resources", ctx, kind="resource")
-
-
-def test_unreserved_user_root_segment_keeps_canonical_meaning():
- ctx = RequestContext(
- user=UserIdentifier(account_id="acct", user_id="alice"),
+ assert resolve_uri("viking://user/alice/resources").uri == "viking://user/alice/resources"
+ collision_ctx = RequestContext(
+ user=UserIdentifier(account_id="acct", user_id="resources"),
role=Role.USER,
)
+ assert (
+ resolve_request_uri("viking://user/resources", collision_ctx)
+ == "viking://user/resources"
+ )
+ admin_ctx = RequestContext(
+ user=UserIdentifier(account_id="acct", user_id="admin"),
+ role=Role.ADMIN,
+ )
+ assert (
+ resolve_request_uri("viking://user/resources", admin_ctx)
+ == "viking://user/resources"
+ )
+ assert is_content_root_uri("viking://resources", kind="resource")
+
+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.
- assert canonicalize_uri("viking://user/notes/todo.md", ctx) == "viking://user/notes/todo.md"
+ assert resolve_uri("viking://user/notes/todo.md").uri == "viking://user/notes/todo.md"
assert (
- canonicalize_uri("viking://user/bob/zeus-persona.md", ctx)
+ resolve_uri("viking://user/bob/zeus-persona.md").uri
== "viking://user/bob/zeus-persona.md"
)
# A valid canonical user id may itself end in a common file extension.
assert (
- canonicalize_uri("viking://user/writer.md/memories/profile.md", ctx)
+ resolve_uri("viking://user/writer.md/memories/profile.md").uri
== "viking://user/writer.md/memories/profile.md"
)
assert (
- canonicalize_uri("viking://user/alice.smith/memories/preferences/p.md", ctx)
+ resolve_uri("viking://user/alice.smith/memories/preferences/p.md").uri
== "viking://user/alice.smith/memories/preferences/p.md"
)
assert (
- canonicalize_uri("viking://user/[email protected]/resources/r.md", ctx)
+ resolve_uri("viking://user/[email protected]/resources/r.md").uri
== "viking://user/[email protected]/resources/r.md"
)
# The current user's own canonical form remains unchanged.
assert (
- canonicalize_uri("viking://user/alice/notes/todo.md", ctx)
+ resolve_uri("viking://user/alice/notes/todo.md").uri
== "viking://user/alice/notes/todo.md"
)
diff --git a/tests/unit/test_uri_short_format.py b/tests/unit/test_uri_short_format.py
index 38bac8876..9b0c3129f 100644
--- a/tests/unit/test_uri_short_format.py
+++ b/tests/unit/test_uri_short_format.py
@@ -1,106 +1,63 @@
# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
# SPDX-License-Identifier: AGPL-3.0
-"""Tests for VikingURI short-format URI normalization.
-
-Verifies that VikingURI accepts short-format paths (e.g., '/resources',
-'user/memories') in addition to full-format URIs ('viking://resources').
-
-Ref: https://github.com/volcengine/OpenViking/issues/259
-"""
+"""Tests for the explicit Viking URI contract."""
import pytest
from openviking_cli.utils.uri import VikingURI
-class TestVikingURIShortFormat:
- """VikingURI should accept and auto-normalize short-format URIs."""
-
- def test_slash_prefix_path(self):
- """'/resources' should be normalized to 'viking://resources'."""
- uri = VikingURI("/resources")
- assert uri.uri == "viking://resources"
- assert uri.scope == "resources"
+class TestVikingURIExplicitFormat:
+ """VikingURI only accepts explicit ``viking://`` values."""
- def test_bare_path(self):
- """'resources' should be normalized to 'viking://resources'."""
- uri = VikingURI("resources")
- assert uri.uri == "viking://resources"
- assert uri.scope == "resources"
-
- def test_slash_prefix_nested(self):
- """'/user/memories/preferences' should normalize correctly."""
- uri = VikingURI("/user/memories/preferences")
- assert uri.uri == "viking://user/memories/preferences"
- assert uri.scope == "user"
-
- def test_bare_nested_path(self):
- """'user/skills/pdf' should normalize correctly."""
- uri = VikingURI("user/skills/pdf")
- assert uri.uri == "viking://user/skills/pdf"
- assert uri.scope == "user"
+ @pytest.mark.parametrize(
+ "value",
+ [
+ "/resources",
+ "resources",
+ "/user/memories/preferences",
+ "user/skills/pdf",
+ "/",
+ ],
+ )
+ def test_path_input_is_rejected(self, value: str):
+ with pytest.raises(ValueError, match="must start with 'viking://'"):
+ VikingURI(value)
def test_full_format_unchanged(self):
- """Full-format URIs should pass through unchanged."""
uri = VikingURI("viking://resources/my_project")
assert uri.uri == "viking://resources/my_project"
- def test_root_slash(self):
- """'/' should normalize to 'viking://'."""
- uri = VikingURI("/")
- assert uri.uri == "viking://"
- assert uri.scope == ""
-
def test_full_root(self):
- """'viking://' should work as before."""
uri = VikingURI("viking://")
- assert uri.uri == "viking://"
assert uri.scope == ""
- def test_join_after_short_format(self):
- """join() should work on auto-normalized URIs."""
- uri = VikingURI("/resources")
- joined = uri.join("my_project")
+ def test_join(self):
+ joined = VikingURI("viking://resources").join("my_project")
assert joined.uri == "viking://resources/my_project"
- def test_parent_after_short_format(self):
- """parent should work on auto-normalized URIs."""
- uri = VikingURI("/user/memories/preferences")
- parent = uri.parent
+ def test_parent(self):
+ parent = VikingURI("viking://user/alice/memories/preferences").parent
assert parent is not None
- assert parent.uri == "viking://user/memories"
+ assert parent.uri == "viking://user/alice/memories"
- def test_is_valid_short_format(self):
- """is_valid should accept short-format URIs after normalization."""
- assert VikingURI.is_valid("/resources")
- assert VikingURI.is_valid("user/memories")
+ def test_is_valid_rejects_path_input(self):
+ assert not VikingURI.is_valid("/resources")
+ assert not VikingURI.is_valid("user/memories")
def test_invalid_scope_still_rejected(self):
- """Invalid scopes should still raise ValueError."""
with pytest.raises(ValueError, match="Invalid scope"):
- VikingURI("/invalid_scope/foo")
-
- def test_normalize_idempotent(self):
- """Normalizing an already-normalized URI should be idempotent."""
- original = "viking://resources/docs"
- assert VikingURI.normalize(original) == original
- assert (
- VikingURI.normalize(VikingURI.normalize("/resources/docs")) == "viking://resources/docs"
- )
+ VikingURI("viking://invalid_scope/foo")
@pytest.mark.parametrize(
- "short,expected",
+ "value,scope",
[
- ("/resources", "viking://resources"),
- ("/user", "viking://user"),
- ("/user/skills", "viking://user/skills"),
- ("/session/abc123", "viking://session/abc123"),
- ("/queue", "viking://queue"),
- ("/temp", "viking://temp"),
- ("resources/images", "viking://resources/images"),
+ ("viking://resources", "resources"),
+ ("viking://user", "user"),
+ ("viking://session/abc123", "session"),
+ ("viking://queue", "queue"),
+ ("viking://temp", "temp"),
],
)
- def test_all_scopes(self, short, expected):
- """All valid scopes should work with short format."""
- uri = VikingURI(short)
- assert uri.uri == expected
+ def test_explicit_scopes(self, value: str, scope: str):
+ assert VikingURI(value).scope == scope
diff --git a/tests/unit/test_uri_validation.py b/tests/unit/test_uri_validation.py
index 6314cd5e9..d3f05960c 100644
--- a/tests/unit/test_uri_validation.py
+++ b/tests/unit/test_uri_validation.py
@@ -5,7 +5,7 @@
import pytest
-from openviking.core.uri_validation import validate_optional_viking_uri, validate_viking_uri
+from openviking.core.uri_validation import validate_viking_uri
from openviking_cli.exceptions import InvalidURIError
@@ -13,8 +13,6 @@ from openviking_cli.exceptions import InvalidURIError
"uri",
[
"viking://resources/docs",
- "resources/docs",
- "/resources/docs",
"viking://session/s1",
"viking://agent/code-agent/memories/facts/project.md",
"viking://",
@@ -30,6 +28,8 @@ def test_validate_viking_uri_accepts_supported_forms(uri: str):
"",
" ",
"viking:/resources/docs",
+ "resources/docs",
+ "/resources/docs",
"s3://bucket/key",
"https://example.com/doc.md",
"viking://unsupported/doc.md",
@@ -42,12 +42,12 @@ def test_validate_viking_uri_rejects_invalid_or_unsupported_forms(uri: str):
validate_viking_uri(uri)
-def test_validate_viking_uri_hides_internal_scopes_in_public_error():
+def test_validate_viking_uri_reports_explicit_scheme_requirement():
with pytest.raises(InvalidURIError) as exc_info:
validate_viking_uri("ssd")
message = str(exc_info.value)
- assert "resources" in message
+ assert "viking://" in message
assert "temp" not in message
assert "queue" not in message
assert "frozenset" not in message
@@ -65,7 +65,8 @@ def test_validate_viking_uri_supports_internal_and_operation_scopes():
assert "temp" not in message
assert "queue" not in message
-
-def test_validate_optional_viking_uri_preserves_unspecified():
- assert validate_optional_viking_uri(None) == ""
- assert validate_optional_viking_uri(" ") == ""
+ with pytest.raises(InvalidURIError, match="Invalid scope"):
+ validate_viking_uri(
+ "viking://invalid_scope/doc",
+ allowed_scopes={"invalid_scope"},
+ )