Skip to content

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

fix(namespace): 统一 agent 公共目录并删除旧身份逻辑 (#5069)

bot-of-qin-ctxa126eaff21cb
diff --git a/docs/en/api/08-admin.md b/docs/en/api/08-admin.md
index a05e2e484..bbd930f14 100644
--- a/docs/en/api/08-admin.md
+++ b/docs/en/api/08-admin.md
@@ -1375,15 +1375,15 @@ ov --sudo admin regenerate-key acme bob
#### 1. API Implementation Overview
-Migrate 0.3.x legacy `viking://agent/...` / `viking://session/...` data into the 0.4.0 user / peer namespace, or clean up old namespaces after migration has been verified. This endpoint is ROOT-only and runs as a background task.
+Migrate legacy `viking://session/...` data into `viking://user/<user_id>/sessions/...`, or clean up old session directories after verifying migration. This endpoint is ROOT-only and runs as a background task. The account-shared `agent` directory is excluded from migration and cleanup.
**Processing Flow:**
1. Verify requester has ROOT privileges
2. For `action=migrate`, run preflight checks for account registry, session owner metadata, and other prerequisites
3. Create a root-level background task
-4. During migration, copy files and existing vector records; during cleanup, delete old vector records before deleting old AGFS directories
+4. During migration, copy session files; during cleanup, delete old session vector records before deleting old session AGFS directories
-Migration does not automatically call `reindex`. If retrieval after migration is not as expected, users should manually reindex the new paths.
+Migration preserves files that already exist at the destination. Cleanup leaves shared `agent` directories and migrated user data intact.
**Code Entry Points:**
- `openviking/server/routers/admin.py:migrate_legacy_data` - HTTP route
@@ -1408,10 +1408,8 @@ POST /api/v1/admin/migrate
| Field | Description |
|-------|-------------|
| migrated.files / migrated.directories | Number of files and directories copied |
-| migrated.vector_records | Number of existing vector records copied |
-| migrated.skipped_vector_records | Number of old records skipped because they had no vector payload |
-| migrated.operations | Operation counts grouped by migration category |
-| skipped / warnings / created_users | Skipped items, warnings, and users created automatically |
+| migrated.operations | Session migration operation count (`sessions`) |
+| skipped / created_users | Skipped files and users created automatically |
**Cleanup result fields**
diff --git a/docs/en/concepts/04-viking-uri.md b/docs/en/concepts/04-viking-uri.md
index 07d3edb28..fc0f8a77f 100644
--- a/docs/en/concepts/04-viking-uri.md
+++ b/docs/en/concepts/04-viking-uri.md
@@ -143,9 +143,10 @@ viking://agent/tools/mcp/ # MCP tool configuration (pl
viking://agent/payments/ap2/ # Payment configuration (planned)
```
-`viking://agent/...` is a global shared scope, accessible to all users under the account,
-without agent_id isolation. Legacy (0.3.x) data under `viking://agent/...` remains accessible
-via a read-only compatibility entry, but new data should be written according to the new directory semantics.
+`viking://agent/...` is an account-shared directory for capabilities and configuration,
+including skills, endpoints, tools, payments, and other subdirectories. Directory names
+do not identify agents, and `actor_peer_id` does not filter this scope. Sharing is limited
+to the current account. Peer data belongs under `viking://user/<user_id>/peers/<peer_id>/...`.
The home alias `viking://~/...` is relative to the current request identity. OpenViking
expands it internally to the explicit namespace path `viking://user/{user_id}/...` before
@@ -284,9 +285,9 @@ viking://
└── history/
```
-`viking://agent/...` is a global shared scope for agent capabilities, accessible to all users under the account,
-without agent_id isolation. Legacy (0.3.x) data under `viking://agent/...` remains accessible
-via a read-only compatibility entry, but new data should be written according to the new directory semantics.
+`viking://agent/...` is an account-shared directory without an Agent ID identity layer.
+`actor_peer_id` filters only the current user's `peers` collection. Shared directories
+remain isolated by account.
## URI Operations
diff --git a/docs/en/migration/01-user-peer-model.md b/docs/en/migration/01-user-peer-model.md
index 5299060f6..2480622cd 100644
--- a/docs/en/migration/01-user-peer-model.md
+++ b/docs/en/migration/01-user-peer-model.md
@@ -1,5 +1,7 @@
# OpenViking 0.3.x to 0.4.0 Upgrade Guide
+> **Version scope:** This page documents the historical 0.3.x-to-0.4.0 migration. Its Agent directory compatibility and migration instructions do not apply to current versions. `viking://agent/...` now denotes account-shared directories; Agent ID path compatibility, migration, and cleanup have been removed. The current `admin migrate` command handles legacy sessions only.
+
This guide is for users already running OpenViking 0.3.x. It explains what to do before and after upgrading to 0.4.0, which legacy usage remains compatible, how to migrate data, and how to move application code to the new model.
## Upgrade Decision
diff --git a/docs/zh/api/08-admin.md b/docs/zh/api/08-admin.md
index 07a09d669..d65f4fdd9 100644
--- a/docs/zh/api/08-admin.md
+++ b/docs/zh/api/08-admin.md
@@ -1318,15 +1318,15 @@ ov --sudo admin regenerate-key acme bob
#### 1. API 实现介绍
-将 0.3.x legacy `viking://agent/...` / `viking://session/...` 数据迁移到 0.4.0 的 user / peer namespace,或在确认迁移结果后清理旧 namespace。该接口仅 ROOT 可调用,并以后台 task 执行。
+将旧 `viking://session/...` 数据迁移到 `viking://user/<user_id>/sessions/...`,或在确认迁移结果后清理旧 Session 目录。该接口仅 ROOT 可调用,并以后台 task 执行。`agent` 是账号内公共目录,不参与迁移或 cleanup。
**处理流程:**
1. 验证请求者具有 ROOT 权限
2. `action=migrate` 时执行 preflight,检查 account registry、session owner 等前置条件
3. 创建 root 级后台 task
-4. 迁移时复制文件和已有向量记录;cleanup 时先删除旧向量记录,再删除旧 AGFS 目录
+4. 迁移时复制 Session 文件;cleanup 时先删除旧 Session 向量记录,再删除旧 Session AGFS 目录
-迁移不会自动调用 `reindex`。如果迁移后的检索结果不符合预期,需要用户对新路径手动执行 reindex。
+迁移保留目标路径中已有的文件。cleanup 不删除 `agent` 公共目录或已迁移的用户数据。
**代码入口:**
- `openviking/server/routers/admin.py:migrate_legacy_data` - HTTP 路由
@@ -1351,10 +1351,8 @@ POST /api/v1/admin/migrate
| 字段 | 说明 |
|------|------|
| migrated.files / migrated.directories | 复制的文件和目录数量 |
-| migrated.vector_records | 复制的已有向量记录数量 |
-| migrated.skipped_vector_records | 因没有向量 payload 而跳过的旧记录数量 |
-| migrated.operations | 按迁移类别统计的操作数量 |
-| skipped / warnings / created_users | 跳过项、告警、自动创建的用户 |
+| migrated.operations | Session 迁移操作数量(`sessions`) |
+| skipped / created_users | 跳过的文件、自动创建的用户 |
**Cleanup 结果字段**
diff --git a/docs/zh/concepts/04-viking-uri.md b/docs/zh/concepts/04-viking-uri.md
index 9f0fd58e6..e93d51cec 100644
--- a/docs/zh/concepts/04-viking-uri.md
+++ b/docs/zh/concepts/04-viking-uri.md
@@ -146,9 +146,9 @@ viking://agent/tools/mcp/ # MCP 工具配置(规划
viking://agent/payments/ap2/ # 支付配置(规划中)
```
-`viking://agent/...` 为全局共享作用域,account 下所有用户均可访问,
-不通过 agent_id 隔离。旧版(0.3.x)遗留的 `viking://agent/...` 数据仍可通过
-只读兼容入口访问,但新数据应按照新的目录语义写入。
+`viking://agent/...` 是 account 内公共能力与配置目录,可包含 skills、endpoints、tools、payments 等子目录。
+目录名不表示 Agent 身份,`actor_peer_id` 不过滤该目录;共享范围限于当前账号。
+Peer 数据使用 `viking://user/<user_id>/peers/<peer_id>/...`。
### 会话数据
@@ -273,8 +273,8 @@ viking://
└── history/
```
-`viking://agent/...` 作用域为全局共享的 agent 能力根,account 下所有用户均可访问,
-不通过 agent_id 隔离。旧版(0.3.x)遗留的 `viking://agent/...` 数据仍可通过只读兼容入口访问。
+`viking://agent/...` 是 account 内公共目录,不包含 Agent ID 身份层。
+`actor_peer_id` 只过滤当前用户的 `peers` 集合,公共目录仍按账号隔离。
## URI 操作
diff --git a/docs/zh/migration/01-user-peer-model.md b/docs/zh/migration/01-user-peer-model.md
index 4b8890ba6..c27c8d7e0 100644
--- a/docs/zh/migration/01-user-peer-model.md
+++ b/docs/zh/migration/01-user-peer-model.md
@@ -1,5 +1,7 @@
# OpenViking 0.3.x 到 0.4.0 升级指南
+> **版本范围:** 本页记录 0.3.x 到 0.4.0 的历史迁移流程,不适用于当前版本的 Agent 目录。当前 `viking://agent/...` 统一表示账号内公共目录,已移除 Agent ID 路径兼容及其迁移、cleanup。当前 `admin migrate` 只处理旧 Session 数据。
+
本文面向已经运行 OpenViking 0.3.x 的用户,说明升级到 0.4.0 前后需要做什么、哪些旧用法仍然兼容、数据迁移如何执行,以及业务代码如何逐步迁移到新模型。
## 是否需要升级
diff --git a/openviking/core/namespace.py b/openviking/core/namespace.py
index 65fed4b18..e8694e7dd 100644
--- a/openviking/core/namespace.py
+++ b/openviking/core/namespace.py
@@ -13,7 +13,7 @@ from openviking_cli.utils.uri import VikingURI
_CONTENT_TYPES_BY_SCOPE = {
"user": {"memories": "memory", "resources": "resource", "skills": "skill"},
- "agent": {"memories": "memory", "resources": "resource", "skills": "skill"},
+ "agent": {"skills": "skill"},
}
_PEER_CONTENT_SEGMENTS = frozenset({"memories", "resources"})
_USER_RELATIVE_ROOT_SEGMENTS = frozenset({"peers", "privacy", "sessions"})
@@ -55,10 +55,6 @@ class UriClassification:
def is_user_namespace_root(self) -> bool:
return _is_namespace_root_parts(self.parts, "user")
- @property
- def is_agent_namespace_root(self) -> bool:
- return self.scope == "agent" and len(self.parts) == 2
-
@property
def is_memory_root(self) -> bool:
return (
@@ -119,8 +115,6 @@ def _content_segment_index(parts: tuple[str, ...]) -> Optional[int]:
"""Return the content segment for a supported namespace shape."""
if len(parts) >= 2 and parts[:2] == ("agent", "skills"):
return 1
- if len(parts) >= 3 and parts[0] == "agent" and parts[2] in _CONTENT_TYPES_BY_SCOPE["agent"]:
- return 2
if len(parts) < 2 or parts[0] != "user":
return None
if len(parts) >= 5 and parts[2] == "peers" and parts[4] in _PEER_CONTENT_SEGMENTS:
@@ -180,13 +174,13 @@ def is_session_uri(uri: str) -> bool:
return len(parts) >= 3 and parts[0] == "user" and parts[2] == "sessions"
-AGENT_SHARED_ROOTS: tuple[str, ...] = ("viking://agent/skills",)
+AGENT_SKILLS_ROOT = "viking://agent/skills"
def visible_roots(ctx: RequestContext) -> list[str]:
return [
"viking://resources",
- *AGENT_SHARED_ROOTS,
+ "viking://agent",
canonical_user_root(ctx),
]
@@ -329,7 +323,7 @@ def is_accessible(uri: str, ctx: RequestContext) -> bool:
except NamespaceShapeError:
return False
- if target.scope in {"", "resources", "temp", "queue"}:
+ if target.scope in {"", "resources", "agent", "temp", "queue"}:
return True
if target.scope == "upload":
return False
@@ -337,11 +331,6 @@ def is_accessible(uri: str, ctx: RequestContext) -> bool:
if target.owner_user_id and target.owner_user_id != ctx.user.user_id:
return False
return True
- if target.scope == "agent":
- parts = uri_parts(target.uri)
- if ctx.actor_peer_id and len(parts) >= 2 and parts[1] != ctx.actor_peer_id:
- return False
- return True
return True
diff --git a/openviking/core/retrieval_targets.py b/openviking/core/retrieval_targets.py
index f22532d7c..039c45609 100644
--- a/openviking/core/retrieval_targets.py
+++ b/openviking/core/retrieval_targets.py
@@ -6,6 +6,7 @@ from dataclasses import dataclass
from typing import List, Optional, Union
from openviking.core.namespace import (
+ AGENT_SKILLS_ROOT,
canonical_user_root,
is_hidden_by_actor_peer_view,
uri_parts,
@@ -77,7 +78,7 @@ def default_target_directories(
)
return ["viking://resources", user_root]
if context_type == ContextType.SKILL:
- return _dedupe([*_default_skill_targets(ctx), *_default_agent_skill_targets()])
+ return _dedupe([*_default_skill_targets(ctx), AGENT_SKILLS_ROOT])
if ctx.actor_peer_id:
return _dedupe(["viking://resources", *_default_user_root_targets(ctx)])
return [user_root, "viking://resources"]
@@ -102,10 +103,6 @@ def _target_directories_for_uri(
if _is_current_user_root(target_uri, ctx):
return _default_user_root_targets(ctx)
- # New agent scope: direct access for agent/skills/, agent/endpoints/, etc.
- if _is_agent_scope_uri(target_uri):
- return [target_uri]
-
peer_target = _resolve_peer_target(target_uri, ctx=ctx)
if peer_target is not None:
return peer_target
@@ -117,10 +114,6 @@ def _target_directories_for_uri(
return [target_uri]
-def _default_agent_skill_targets() -> List[str]:
- return ["viking://agent/skills"]
-
-
def _default_user_root_targets(ctx: RequestContext) -> List[str]:
user_root = canonical_user_root(ctx)
if not ctx.actor_peer_id:
@@ -147,10 +140,6 @@ def _actor_peer_targets(ctx: RequestContext) -> List[str]:
f"{peer_root}/memories",
f"{peer_root}/resources",
]
-def _is_agent_scope_uri(target_uri: str) -> bool:
- parts = target_uri[len("viking://"):].strip("/").split("/")
- return parts and parts[0] == "agent" and len(parts) >= 2 and parts[1] in {"skills", "endpoints", "tools", "payments"}
-
def _resolve_peer_target(
diff --git a/openviking/retrieve/context_assembler/gather.py b/openviking/retrieve/context_assembler/gather.py
index 1330b0ff9..5d293e33e 100644
--- a/openviking/retrieve/context_assembler/gather.py
+++ b/openviking/retrieve/context_assembler/gather.py
@@ -12,7 +12,7 @@ import asyncio
from dataclasses import dataclass, replace
from typing import Any, Dict, List, Mapping, Optional, Sequence, Set, Tuple
-from openviking.core.namespace import AGENT_SHARED_ROOTS, canonical_user_root
+from openviking.core.namespace import AGENT_SKILLS_ROOT, canonical_user_root
from openviking.core.retrieval_targets import default_target_directories
from openviking.retrieve.context_assembler.params import (
MEMORY_CATEGORIES,
@@ -105,7 +105,7 @@ def category_targets(category: str, ctx: RequestContext) -> List[str]:
if category == "skills":
return default_target_directories(ctx, context_type=ContextType.SKILL) or [
f"{user_root}/skills",
- *AGENT_SHARED_ROOTS,
+ AGENT_SKILLS_ROOT,
]
return [f"{root.rstrip('/')}/{category}" for root in memory_target_roots(ctx)]
diff --git a/openviking/server/routers/admin.py b/openviking/server/routers/admin.py
index 57baeeefc..7d6d231f9 100644
--- a/openviking/server/routers/admin.py
+++ b/openviking/server/routers/admin.py
@@ -367,7 +367,7 @@ async def migrate_legacy_data(
body: MigrateLegacyDataRequest | None = None,
ctx: RequestContext = Depends(get_request_context),
):
- """Preflight and enqueue legacy agent/session data migration or cleanup."""
+ """Preflight and enqueue legacy session data migration or cleanup."""
manager = _get_api_key_manager(request)
service = get_service()
if service.viking_fs is None:
diff --git a/openviking/service/legacy_migration.py b/openviking/service/legacy_migration.py
index aa267257a..6286f14c7 100644
--- a/openviking/service/legacy_migration.py
+++ b/openviking/service/legacy_migration.py
@@ -1,6 +1,6 @@
# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
# SPDX-License-Identifier: AGPL-3.0
-"""Legacy agent/session data migration to user-owned namespaces."""
+"""Legacy session data migration to user-owned namespaces."""
from __future__ import annotations
@@ -12,7 +12,6 @@ from openviking.pyagfs import AsyncAGFSClient
from openviking.server.identity import RequestContext, Role
from openviking.storage.vector_migration import (
VectorMigrationResult,
- copy_vector_records,
delete_vector_records,
)
from openviking.storage.viking_fs import VikingFS
@@ -20,22 +19,11 @@ from openviking_cli.exceptions import FailedPreconditionError
from openviking_cli.session.user_id import UserIdentifier, validate_user_id
-# Reserved sub-directories of viking://agent/ that belong to the new public
-# scope layout (skills, endpoints, tools, payments). They must not be treated
-# as legacy ``agent_id`` directories by either the migration planner or the
-# cleanup planner.
-_AGENT_RESERVED_SUBDIRS = frozenset({"skills", "endpoints", "tools", "payments"})
-
-
@dataclass(frozen=True)
class TreeCopy:
source_path: str
target_path: str
category: str
- source_uri: str
- target_uri: str
- skip_tree_if_target_exists: bool = False
- copy_contents: bool = False
@dataclass(frozen=True)
@@ -51,15 +39,11 @@ class MigrationPlan:
account_users: dict[str, set[str]] = field(default_factory=dict)
created_users: set[tuple[str, str]] = field(default_factory=set)
operations: list[TreeCopy] = field(default_factory=list)
- warnings: list[str] = field(default_factory=list)
- skipped: list[dict[str, Any]] = field(default_factory=list)
errors: list[dict[str, Any]] = field(default_factory=list)
def to_preflight_result(self) -> dict[str, Any]:
return {
"errors": list(self.errors),
- "warnings": list(self.warnings),
- "skipped": list(self.skipped),
"created_users": [
{"account_id": account_id, "user_id": user_id}
for account_id, user_id in sorted(self.created_users)
@@ -73,32 +57,12 @@ class LegacyCleanupPlan:
targets: list[LegacyCleanupTarget] = field(default_factory=list)
-@dataclass(frozen=True)
-class VectorCopyScope:
- source_uri: str
- target_uri: str
- recursive: bool
-
-
-@dataclass
-class CopyResult:
- copied: bool = False
- vector_scopes: list[VectorCopyScope] = field(default_factory=list)
-
- def extend(self, other: "CopyResult") -> None:
- self.copied = self.copied or other.copied
- self.vector_scopes.extend(other.vector_scopes)
-
-
@dataclass
class MigrationResult:
files: int = 0
directories: int = 0
- vector_records: int = 0
- skipped_vector_records: int = 0
operations: dict[str, int] = field(default_factory=dict)
skipped: list[dict[str, Any]] = field(default_factory=list)
- warnings: list[str] = field(default_factory=list)
created_users: list[dict[str, Any]] = field(default_factory=list)
def mark_operation(self, category: str) -> None:
@@ -109,12 +73,9 @@ class MigrationResult:
"migrated": {
"files": self.files,
"directories": self.directories,
- "vector_records": self.vector_records,
- "skipped_vector_records": self.skipped_vector_records,
"operations": dict(sorted(self.operations.items())),
},
"skipped": self.skipped,
- "warnings": self.warnings,
"created_users": self.created_users,
}
@@ -147,7 +108,7 @@ def target_to_dict(target: LegacyCleanupTarget) -> dict[str, str]:
class LegacyDataMigration:
- """Plan and execute legacy agent/session migration."""
+ """Plan and execute legacy session migration."""
def __init__(self, *, viking_fs: VikingFS, api_key_manager: Any, service: Any):
if api_key_manager is None:
@@ -162,7 +123,7 @@ class LegacyDataMigration:
registry_accounts = self._registry_account_ids()
physical_accounts = await self._physical_account_ids()
for account_id in sorted(physical_accounts - registry_accounts):
- if await self._account_has_legacy_data(account_id):
+ if await self._exists(f"/local/{account_id}/session"):
plan.errors.append(
{
"account_id": account_id,
@@ -176,13 +137,10 @@ class LegacyDataMigration:
plan.account_users[account_id] = set()
for user_id in sorted(self._registry_user_ids(account_id)):
self._ensure_plan_user(account_id, user_id, plan)
- if await self._account_has_legacy_data(account_id):
+ if await self._exists(f"/local/{account_id}/session"):
for user_id in sorted(await self._physical_user_ids(account_id)):
self._ensure_plan_user(account_id, user_id, plan)
- await self._plan_user_agent_data(account_id, plan)
- await self._plan_agent_user_data(account_id, plan)
await self._plan_sessions(account_id, plan)
- await self._plan_shared_agent_data(account_id, plan)
return plan
async def run(self) -> dict[str, Any]:
@@ -193,10 +151,7 @@ class LegacyDataMigration:
details=plan.to_preflight_result(),
)
- result = MigrationResult(
- skipped=list(plan.skipped),
- warnings=list(plan.warnings),
- )
+ result = MigrationResult()
for account_id, user_id in sorted(plan.created_users):
if self._has_user(account_id, user_id):
continue
@@ -206,40 +161,17 @@ class LegacyDataMigration:
result.created_users.append({"account_id": account_id, "user_id": user_id})
for operation in plan.operations:
- copied = await self._copy_tree(operation, result)
- if copied.copied:
+ if await self._copy_path(operation.source_path, operation.target_path, result):
result.mark_operation(operation.category)
- await self._copy_vectors(operation, copied, result)
return result.to_dict()
async def cleanup_preflight(self) -> LegacyCleanupPlan:
plan = LegacyCleanupPlan()
for account_id in sorted(await self._physical_account_ids()):
- agent_path = f"/local/{account_id}/agent"
- if await self._exists(agent_path):
- for entry in await self._ls(agent_path):
- if not entry["is_dir"]:
- continue
- if entry["name"] in _AGENT_RESERVED_SUBDIRS:
- continue
- legacy_path = f"{agent_path}/{entry['name']}"
- plan.targets.append(
- self._cleanup_target(account_id, legacy_path, "agent")
- )
-
session_path = f"/local/{account_id}/session"
if await self._exists(session_path):
plan.targets.append(self._cleanup_target(account_id, session_path, "session"))
- user_root = f"/local/{account_id}/user"
- for user_entry in await self._ls(user_root):
- if not user_entry["is_dir"]:
- continue
- user_agent_path = f"{user_root}/{user_entry['name']}/agent"
- if await self._exists(user_agent_path):
- plan.targets.append(
- self._cleanup_target(account_id, user_agent_path, "user_agent")
- )
return plan
async def cleanup(self) -> dict[str, Any]:
@@ -294,17 +226,6 @@ class LegacyDataMigration:
entries = await self._ls(f"/local/{account_id}/user")
return {entry["name"] for entry in entries if entry["is_dir"]}
- async def _account_has_legacy_data(self, account_id: str) -> bool:
- for leaf in ("agent", "session"):
- if await self._exists(f"/local/{account_id}/{leaf}"):
- return True
- user_root = f"/local/{account_id}/user"
- for user_entry in await self._ls(user_root):
- agent_root = f"{user_root}/{user_entry['name']}/agent"
- if user_entry["is_dir"] and await self._exists(agent_root):
- return True
- return False
-
async def _plan_sessions(self, account_id: str, plan: MigrationPlan) -> None:
session_root = f"/local/{account_id}/session"
for entry in await self._ls(session_root):
@@ -375,9 +296,6 @@ class LegacyDataMigration:
source_path=source_path,
target_path=target_path,
category="sessions",
- source_uri=self._path_to_uri(account_id, source_path),
- target_uri=f"viking://user/{owner}/sessions/{session_id}",
- skip_tree_if_target_exists=False,
)
)
@@ -402,148 +320,6 @@ class LegacyDataMigration:
return True
return False
- async def _plan_user_agent_data(self, account_id: str, plan: MigrationPlan) -> None:
- user_root = f"/local/{account_id}/user"
- for user_entry in await self._ls(user_root):
- if not user_entry["is_dir"]:
- continue
- user_id = user_entry["name"]
- agent_root = f"{user_root}/{user_id}/agent"
- if not await self._exists(agent_root):
- continue
- if not self._ensure_plan_user(account_id, user_id, plan):
- continue
- for agent_entry in await self._ls(agent_root):
- if agent_entry["is_dir"]:
- await self._plan_agent_tree(
- account_id,
- agent_id=agent_entry["name"],
- source_agent_path=f"{agent_root}/{agent_entry['name']}",
- user_ids=[user_id],
- plan=plan,
- )
-
- async def _plan_agent_user_data(self, account_id: str, plan: MigrationPlan) -> None:
- agent_root = f"/local/{account_id}/agent"
- for agent_entry in await self._ls(agent_root):
- if not agent_entry["is_dir"]:
- continue
- agent_id = agent_entry["name"]
- if agent_id in _AGENT_RESERVED_SUBDIRS:
- continue
- user_root = f"{agent_root}/{agent_id}/user"
- for user_entry in await self._ls(user_root):
- if not user_entry["is_dir"]:
- continue
- user_id = user_entry["name"]
- if not self._ensure_plan_user(account_id, user_id, plan):
- continue
- await self._plan_agent_tree(
- account_id,
- agent_id=agent_id,
- source_agent_path=f"{user_root}/{user_id}",
- user_ids=[user_id],
- plan=plan,
- )
-
- async def _plan_shared_agent_data(self, account_id: str, plan: MigrationPlan) -> None:
- agent_root = f"/local/{account_id}/agent"
- user_ids = sorted(plan.account_users.setdefault(account_id, set()))
- for agent_entry in await self._ls(agent_root):
- if not agent_entry["is_dir"]:
- continue
- agent_id = agent_entry["name"]
- if agent_id in _AGENT_RESERVED_SUBDIRS:
- continue
- source_agent_path = f"{agent_root}/{agent_id}"
- if not user_ids:
- plan.warnings.append(
- f"Skipped shared legacy agent {agent_id!r} "
- f"in account {account_id!r}: no users exist."
- )
- continue
- await self._plan_agent_tree(
- account_id,
- agent_id=agent_id,
- source_agent_path=source_agent_path,
- user_ids=user_ids,
- plan=plan,
- )
-
- async def _plan_agent_tree(
- self,
- account_id: str,
- *,
- agent_id: str,
- source_agent_path: str,
- user_ids: list[str],
- plan: MigrationPlan,
- ) -> None:
- memories_path = f"{source_agent_path}/memories"
- if await self._exists(memories_path):
- for user_id in user_ids:
- plan.operations.append(
- TreeCopy(
- source_path=memories_path,
- target_path=f"/local/{account_id}/user/{user_id}/peers/{agent_id}/memories",
- category="agent_memories",
- source_uri=self._path_to_uri(account_id, memories_path),
- target_uri=f"viking://user/{user_id}/peers/{agent_id}/memories",
- copy_contents=True,
- )
- )
-
- skills_path = f"{source_agent_path}/skills"
- if await self._exists(skills_path):
- await self._plan_agent_skills(account_id, agent_id, skills_path, user_ids, plan)
-
- instructions_path = f"{source_agent_path}/instructions"
- if await self._exists(instructions_path):
- plan.warnings.append(
- f"Skipped legacy instructions for agent {agent_id!r} in account {account_id!r}."
- )
-
- async def _plan_agent_skills(
- self,
- account_id: str,
- agent_id: str,
- skills_path: str,
- user_ids: list[str],
- plan: MigrationPlan,
- ) -> None:
- for skill_entry in await self._ls(skills_path):
- if not skill_entry["is_dir"]:
- continue
- skill_name = skill_entry["name"]
- source_skill_path = f"{skills_path}/{skill_name}"
- for user_id in user_ids:
- target_skill_path = f"/local/{account_id}/user/{user_id}/skills/{skill_name}"
- if await self._exists(target_skill_path):
- plan.skipped.append(
- {
- "type": "skill",
- "source": self._path_to_uri(account_id, source_skill_path),
- "target": f"viking://user/{user_id}/skills/{skill_name}",
- "reason": "target skill already exists",
- }
- )
- continue
- plan.operations.append(
- TreeCopy(
- source_path=source_skill_path,
- target_path=target_skill_path,
- category="agent_skills",
- source_uri=self._path_to_uri(account_id, source_skill_path),
- target_uri=f"viking://user/{user_id}/skills/{skill_name}",
- skip_tree_if_target_exists=True,
- )
- )
- if not await self._ls(skills_path):
- plan.warnings.append(
- f"Legacy skills directory for agent {agent_id!r} "
- f"in account {account_id!r} is empty."
- )
-
def _ensure_plan_user(self, account_id: str, user_id: str, plan: MigrationPlan) -> bool:
if error := validate_user_id(user_id):
detail = {
@@ -575,88 +351,29 @@ class LegacyDataMigration:
category=category,
)
- async def _copy_tree(self, operation: TreeCopy, result: MigrationResult) -> CopyResult:
- if operation.skip_tree_if_target_exists and await self._exists(operation.target_path):
- result.skipped.append(
- {
- "type": operation.category,
- "source": operation.source_uri,
- "target": operation.target_uri,
- "reason": "target already exists; kept existing target",
- }
- )
- return CopyResult()
- account_id = self._account_id_from_path(operation.source_path)
- if operation.copy_contents:
- copied = CopyResult()
- created_root = await self._mkdir_if_missing(operation.target_path)
- for entry in await self._ls(operation.source_path):
- source = f"{operation.source_path}/{entry['name']}"
- target = f"{operation.target_path}/{entry['name']}"
- child_result = await self._copy_path(
- source,
- target,
- result,
- account_id=account_id,
- collect_vectors=not created_root,
- )
- copied.extend(child_result)
- if created_root and copied.copied:
- copied.vector_scopes.append(
- VectorCopyScope(
- source_uri=operation.source_uri,
- target_uri=operation.target_uri,
- recursive=True,
- )
- )
- return copied
- return await self._copy_path(
- operation.source_path,
- operation.target_path,
- result,
- account_id=account_id,
- collect_vectors=True,
- )
-
async def _copy_path(
self,
source_path: str,
target_path: str,
result: MigrationResult,
- *,
- account_id: str,
- collect_vectors: bool,
- ) -> CopyResult:
+ ) -> bool:
stat = await self._stat(source_path)
if not stat:
result.skipped.append(
{"type": "path", "source": source_path, "target": target_path, "reason": "missing"}
)
- return CopyResult()
+ return False
if stat["is_dir"]:
- created = await self._mkdir_if_missing(target_path)
- copied = CopyResult(copied=created)
- if created:
+ copied = await self._mkdir_if_missing(target_path)
+ if copied:
result.directories += 1
for entry in await self._ls(source_path):
- source = f"{source_path}/{entry['name']}"
- target = f"{target_path}/{entry['name']}"
- child_result = await self._copy_path(
- source,
- target,
+ child_copied = await self._copy_path(
+ f"{source_path}/{entry['name']}",
+ f"{target_path}/{entry['name']}",
result,
- account_id=account_id,
- collect_vectors=collect_vectors and not created,
- )
- copied.extend(child_result)
- if collect_vectors and created and copied.copied:
- copied.vector_scopes.append(
- VectorCopyScope(
- source_uri=self._path_to_uri(account_id, source_path),
- target_uri=self._path_to_uri(account_id, target_path),
- recursive=True,
- )
)
+ copied = copied or child_copied
return copied
if await self._exists(target_path):
result.skipped.append(
@@ -667,20 +384,11 @@ class LegacyDataMigration:
"reason": "target already exists; kept existing target",
}
)
- return CopyResult()
+ return False
await self._ensure_parent_dirs(target_path)
await self._agfs.write(target_path, await self._agfs.read(source_path))
result.files += 1
- copied = CopyResult(copied=True)
- if collect_vectors:
- copied.vector_scopes.append(
- VectorCopyScope(
- source_uri=self._path_to_uri(account_id, source_path),
- target_uri=self._path_to_uri(account_id, target_path),
- recursive=False,
- )
- )
- return copied
+ return True
async def _read_json_file(self, path: str) -> Any:
try:
@@ -698,36 +406,6 @@ class LegacyDataMigration:
except json.JSONDecodeError:
return None
- async def _copy_vectors(
- self,
- operation: TreeCopy,
- copied: CopyResult,
- result: MigrationResult,
- ) -> None:
- if operation.category == "sessions" or not copied.vector_scopes:
- return
- vector_store = getattr(self._service, "vikingdb_manager", None)
- account_id = self._account_id_from_path(operation.source_path)
- vector_result = VectorMigrationResult()
- seen: set[tuple[str, str, bool]] = set()
- for scope in copied.vector_scopes:
- key = (scope.source_uri, scope.target_uri, scope.recursive)
- if key in seen:
- continue
- seen.add(key)
- vector_result.extend(
- await copy_vector_records(
- vector_store,
- account_id=account_id,
- source_uri=scope.source_uri,
- target_uri=scope.target_uri,
- recursive=scope.recursive,
- )
- )
- result.vector_records += vector_result.copied
- result.skipped_vector_records += vector_result.skipped
- result.warnings.extend(vector_result.warnings)
-
async def _delete_vectors(self, target: LegacyCleanupTarget) -> VectorMigrationResult:
vector_store = getattr(self._service, "vikingdb_manager", None)
return await delete_vector_records(
@@ -792,9 +470,3 @@ class LegacyDataMigration:
if path.startswith(prefix):
return "viking://" + path[len(prefix) :].strip("/")
return path
-
- def _account_id_from_path(self, path: str) -> str:
- parts = [part for part in path.strip("/").split("/") if part]
- if len(parts) >= 2 and parts[0] == "local":
- return parts[1]
- return ""
diff --git a/openviking/service/reindex_executor.py b/openviking/service/reindex_executor.py
index ef7a2b6fa..9bbebf993 100644
--- a/openviking/service/reindex_executor.py
+++ b/openviking/service/reindex_executor.py
@@ -296,25 +296,6 @@ class ReindexExecutor:
return "user_namespace"
if classification.is_user_namespace_root:
return "user_namespace"
- if parts[0] == "agent":
- if len(parts) >= 2 and parts[1] in {"skills", "endpoints", "tools", "payments"}:
- if classification.is_skill_namespace:
- return "skill_namespace"
- if classification.is_skill_root:
- return "skill"
- if classification.is_skill:
- raise OpenVikingError(
- f"Unsupported reindex URI: {uri}",
- code="UNSUPPORTED_URI",
- details={"uri": uri},
- )
- return "resource"
- raise OpenVikingError(
- "viking://agent/{agent_id}/... is no longer supported; "
- "use viking://agent/skills/... or viking://user/... instead.",
- code="UNSUPPORTED_URI",
- details={"uri": uri},
- )
if classification.is_memory:
return "memory"
if classification.is_skill_namespace:
@@ -327,7 +308,7 @@ class ReindexExecutor:
code="UNSUPPORTED_URI",
details={"uri": uri},
)
- if parts[0] in {"resources", "user"}:
+ if parts[0] in {"resources", "user"} or (parts[0] == "agent" and len(parts) >= 2):
return "resource"
raise OpenVikingError(
f"Unsupported reindex URI: {uri}",
diff --git a/openviking/storage/vector_migration.py b/openviking/storage/vector_migration.py
index 297940503..1bd328dbc 100644
--- a/openviking/storage/vector_migration.py
+++ b/openviking/storage/vector_migration.py
@@ -19,48 +19,18 @@ from openviking.storage.abstract_overview import (
)
from openviking.storage.expr import And, Contains, Eq, Or, PathScope
from openviking.storage.vector_ids import vector_record_id
-from openviking.utils.time_utils import get_current_timestamp
from openviking_cli.session.user_id import UserIdentifier
from openviking_cli.utils.uri import VikingURI
-VECTOR_MIGRATION_OUTPUT_FIELDS = [
- "id",
- "uri",
- "type",
- "context_type",
- "vector",
- "sparse_vector",
- "created_at",
- "updated_at",
- "active_count",
- "level",
- "name",
- "description",
- "tags",
- "abstract",
- "account_id",
- "owner_user_id",
-]
-
-_VECTOR_PAYLOAD_FIELDS = ("vector", "sparse_vector")
_MAX_VECTOR_RECORDS_PER_SCOPE = 100_000
@dataclass
class VectorMigrationResult:
- copied: int = 0
deleted: int = 0
- skipped: int = 0
failed: int = 0
warnings: list[str] = field(default_factory=list)
- def extend(self, other: "VectorMigrationResult") -> None:
- self.copied += other.copied
- self.deleted += other.deleted
- self.skipped += other.skipped
- self.failed += other.failed
- self.warnings.extend(other.warnings)
-
def _root_ctx(account_id: str) -> RequestContext:
return RequestContext(user=UserIdentifier(account_id, "default"), role=Role.ROOT)
@@ -74,14 +44,6 @@ def _vector_record_id(account_id: str, uri: str, level: Any) -> str:
return vector_record_id(account_id, uri, level)
-def _has_vector_payload(record: dict[str, Any]) -> bool:
- for field_name in _VECTOR_PAYLOAD_FIELDS:
- value = record.get(field_name)
- if isinstance(value, (list, dict)) and value:
- return True
- return False
-
-
def uri_in_transfer_scope(uri: str, scope_uri: str, *, recursive: bool) -> bool:
"""Return whether *uri* belongs to a file or recursive directory transfer."""
scope_uri = _normalize_uri(scope_uri)
@@ -186,7 +148,7 @@ async def _records_in_scope(
records = await vector_store.filter(
filter=And([Eq("account_id", account_id), Or(filters)]),
limit=_MAX_VECTOR_RECORDS_PER_SCOPE,
- output_fields=VECTOR_MIGRATION_OUTPUT_FIELDS,
+ output_fields=["id", "uri"],
ctx=ctx,
)
return [
@@ -197,71 +159,6 @@ async def _records_in_scope(
]
-async def copy_vector_records(
- vector_store: Any,
- *,
- account_id: str,
- source_uri: str,
- target_uri: str,
- recursive: bool,
-) -> VectorMigrationResult:
- """Copy vector records from one URI scope to another without re-embedding."""
- result = VectorMigrationResult()
- if (
- not vector_store
- or not hasattr(vector_store, "filter")
- or not hasattr(vector_store, "upsert")
- ):
- result.warnings.append(f"Skipped vector copy for {source_uri}: vector store is unavailable")
- return result
-
- source_uri = source_uri.rstrip("/")
- target_uri = target_uri.rstrip("/")
- ctx = _root_ctx(account_id)
- try:
- records = await _records_in_scope(
- vector_store,
- account_id=account_id,
- uri=source_uri,
- recursive=recursive,
- )
- except Exception as exc:
- result.failed += 1
- result.warnings.append(f"Failed to read vectors for {source_uri}: {exc}")
- return result
-
- if len(records) >= _MAX_VECTOR_RECORDS_PER_SCOPE:
- result.warnings.append(
- f"Vector copy for {source_uri} reached the per-scope record limit "
- f"({_MAX_VECTOR_RECORDS_PER_SCOPE}); run reindex if records are missing"
- )
-
- timestamp = get_current_timestamp()
- for record in records:
- source_record_uri = record["uri"]
- if not _has_vector_payload(record):
- result.skipped += 1
- continue
-
- payload = rewrite_vector_record(
- record,
- source_uri=source_uri,
- target_uri=target_uri,
- ctx=ctx,
- mode="copy",
- timestamp=timestamp,
- )
- try:
- await vector_store.upsert(payload, ctx=ctx)
- result.copied += 1
- except Exception as exc:
- result.failed += 1
- result.warnings.append(
- f"Failed to copy vector {source_record_uri} to {payload['uri']}: {exc}"
- )
- return result
-
-
async def delete_vector_records(
vector_store: Any,
*,
diff --git a/openviking/storage/viking_fs/_access.py b/openviking/storage/viking_fs/_access.py
index dda787a8b..4d7f46e74 100644
--- a/openviking/storage/viking_fs/_access.py
+++ b/openviking/storage/viking_fs/_access.py
@@ -413,11 +413,6 @@ class _AccessMixin:
f"Writing {normalized_uri} is not supported; use user-owned namespaces instead.",
resource=normalized_uri,
)
- if self._is_legacy_agent_id_uri(normalized_uri):
- raise PermissionDeniedError(
- "viking://agent/{agent_id} is deprecated. Use viking://user/.../peers/{agent_id} instead.",
- resource=normalized_uri,
- )
def _pathlock_fs_ctx(
self,
@@ -648,10 +643,6 @@ class _AccessMixin:
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 parts]
- return f"/local/{account_id}/{'/'.join(safe_parts)}"
if not parts:
return f"/local/{account_id}"
@@ -688,16 +679,6 @@ class _AccessMixin:
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._safe_uri_parts(uri)
- return bool(
- parts
- and parts[0] == "agent"
- and len(parts) >= 2
- and parts[1] not in {"skills", "endpoints", "tools", "payments"}
- and not (len(parts) == 2 and parts[1] in self._DIR_MARKER_LEVELS)
- )
-
def _read_paths(self, uri: str, ctx: Optional[RequestContext] = None) -> List[str]:
"""Return read candidates for a URI, including legacy alias fallbacks."""
paths = [self._uri_to_path(uri, ctx=ctx)]
@@ -735,13 +716,8 @@ class _AccessMixin:
ctx: Optional[RequestContext],
) -> str:
base = base_path.rstrip("/")
- request_parts = self._safe_uri_parts(request_uri)
request_root = request_uri if request_uri == "viking://" else request_uri.rstrip("/")
- preserve_request_alias = request_uri in {"viking://", "viking://user"} or bool(
- request_parts
- and request_parts[0] == "agent"
- and self._is_legacy_agent_id_uri(request_uri)
- )
+ preserve_request_alias = request_uri in {"viking://", "viking://user"}
rel_path = entry_path[len(base) :].strip("/") if entry_path.startswith(base) else ""
if entry_path.startswith(base):
separator = "" if request_root.endswith("://") else "/"
@@ -1029,14 +1005,6 @@ class _AccessMixin:
return ctx.role == Role.ROOT
if scope == "_system":
return False
- if scope == "agent":
- # New format: agent/skills/..., agent/endpoints/... — globally readable (account scope)
- if len(parts) >= 2 and parts[1] in {"skills", "endpoints", "tools", "payments"}:
- return True
- # Old format: agent/{agent_id}/... — actor_peer_id match for read-only access
- if not ctx.actor_peer_id or len(parts) < 2:
- return True
- return parts[1] == ctx.actor_peer_id
return namespace_is_accessible(uri, ctx)
def _handle_agfs_read(self, result: Union[bytes, Any, None]) -> bytes:
diff --git a/tests/server/test_admin_api.py b/tests/server/test_admin_api.py
index d4feeeec9..51aaf5c3d 100644
--- a/tests/server/test_admin_api.py
+++ b/tests/server/test_admin_api.py
@@ -37,7 +37,8 @@ from openviking.service.task_store import (
SYSTEM_TASK_USER_ID,
)
from openviking.service.task_tracker import get_task_tracker
-from openviking_cli.exceptions import OpenVikingError, PermissionDeniedError
+from openviking.session.memory.account_templates import EDITABLE_MEMORY_TEMPLATE_FIELDS
+from openviking_cli.exceptions import OpenVikingError
from openviking_cli.session.user_id import UserIdentifier
from openviking_cli.utils.config import get_openviking_config
@@ -2401,276 +2402,72 @@ async def test_legacy_migration_preflight_failure_does_not_create_task(
assert tasks_resp.json()["result"] == []
-async def test_legacy_migration_task_migrates_legacy_data(
+async def test_legacy_migration_only_moves_sessions(
admin_client: httpx.AsyncClient,
admin_app,
admin_service: OpenVikingService,
):
- """ROOT migrate fans out shared agent data and moves sessions under users."""
+ """Migration preserves public agent content and moves sessions under their owners."""
acct = _uid()
await admin_client.post(
"/api/v1/admin/accounts",
json={"account_id": acct, "admin_user_id": "alice"},
headers=root_headers(),
)
- register_bob = await admin_client.post(
- f"/api/v1/admin/accounts/{acct}/users",
- json={"user_id": "bob", "role": "user"},
- headers=root_headers(),
- )
- bob_key = register_bob.json()["result"]["user_key"]
-
- await _agfs_write(
- admin_service,
- f"/local/{acct}/agent/code-agent/memories/facts/project.md",
- "shared fact",
- )
- await _agfs_write(
- admin_service,
- f"/local/{acct}/agent/code-agent/skills/code-review/SKILL.md",
- "legacy skill",
- )
- await _agfs_write(
- admin_service,
- f"/local/{acct}/agent/code-agent/instructions/system.md",
- "do not migrate",
- )
- await _agfs_write(
- admin_service,
- f"/local/{acct}/user/bob/skills/code-review/SKILL.md",
- "existing skill",
- )
- await _agfs_write(
- admin_service,
- f"/local/{acct}/session/sess-001/.meta.json",
- json.dumps({"created_by_user_id": "alice"}),
- )
- await _agfs_write(
- admin_service,
- f"/local/{acct}/session/sess-001/messages.jsonl",
- '{"role":"user"}\n',
- )
- await _agfs_write(
- admin_service,
- f"/local/{acct}/session/sess-002/.meta.json",
- json.dumps({"user_id": "charlie"}),
- )
- await _agfs_write(
- admin_service,
- f"/local/{acct}/session/sess-002/messages.jsonl",
- '{"role":"assistant"}\n',
- )
-
- resp = await admin_client.post("/api/v1/admin/migrate", headers=root_headers())
- assert resp.status_code == 200
- task_id = resp.json()["result"]["task_id"]
- assert await _agfs_exists(
- admin_service,
- f"/local/{SYSTEM_TASK_ACCOUNT_ID}/tasks/{SYSTEM_TASK_USER_ID}/{task_id}.json",
- )
- hidden_resp = await admin_client.get(f"/api/v1/tasks/{task_id}", headers={"X-API-Key": bob_key})
- assert hidden_resp.status_code == 404
-
- task = await _wait_for_task(admin_client, task_id)
- assert task["status"] == "completed"
- result = task["result"]
- created_user = next(item for item in result["created_users"] if item["user_id"] == "charlie")
- assert created_user["account_id"] == acct
- assert "user_key" not in created_user
- assert result["migrated"]["operations"]["agent_memories"] == 3
- assert result["migrated"]["operations"]["agent_skills"] == 2
- assert result["migrated"]["operations"]["sessions"] == 2
- assert any(item["reason"] == "target skill already exists" for item in result["skipped"])
- assert any("Skipped legacy instructions" in item for item in result["warnings"])
-
- manager = admin_app.state.api_key_manager
- assert manager.has_user(acct, "charlie")
- for user_id in ("alice", "bob", "charlie"):
- assert (
- await _agfs_read_text(
- admin_service,
- f"/local/{acct}/user/{user_id}/peers/code-agent/memories/facts/project.md",
- )
- == "shared fact"
- )
- assert (
- await _agfs_read_text(
- admin_service,
- f"/local/{acct}/user/alice/skills/code-review/SKILL.md",
- )
- == "legacy skill"
- )
- assert (
- await _agfs_read_text(
- admin_service,
- f"/local/{acct}/user/bob/skills/code-review/SKILL.md",
- )
- == "existing skill"
- )
- assert (
- await _agfs_read_text(
+ shared_path = f"/local/{acct}/agent/workflows/memories/guide.md"
+ await _agfs_write(admin_service, shared_path, "shared workflow")
+ for session_id, owner in (("s1", "alice"), ("s2", "charlie")):
+ await _agfs_write(
admin_service,
- f"/local/{acct}/user/alice/sessions/sess-001/messages.jsonl",
+ f"/local/{acct}/session/{session_id}/.meta.json",
+ json.dumps({"created_by_user_id": owner}),
)
- == '{"role":"user"}\n'
- )
- assert (
- await _agfs_read_text(
+ await _agfs_write(
admin_service,
- f"/local/{acct}/user/charlie/sessions/sess-002/messages.jsonl",
+ f"/local/{acct}/session/{session_id}/messages.jsonl",
+ '{"role":"user"}\n',
)
- == '{"role":"assistant"}\n'
- )
- assert not await _agfs_exists(
- admin_service,
- f"/local/{acct}/user/alice/peers/code-agent/instructions/system.md",
- )
-
-
-async def test_legacy_migration_covers_all_accounts_and_agent_user_layout(
- admin_client: httpx.AsyncClient,
- admin_app,
- admin_service: OpenVikingService,
-):
- """One ROOT migration scans all accounts and handles agent/user scoped legacy data."""
- acct = _uid()
- other_acct = _uid()
- await admin_client.post(
- "/api/v1/admin/accounts",
- json={"account_id": acct, "admin_user_id": "admin"},
- headers=root_headers(),
- )
- await admin_client.post(
- "/api/v1/admin/accounts",
- json={"account_id": other_acct, "admin_user_id": "dana"},
- headers=root_headers(),
- )
- await _agfs_write(
- admin_service,
- f"/local/{acct}/user/charlie/memories/.overview.md",
- "legacy physical user",
- )
- await _agfs_write(
- admin_service,
- f"/local/{acct}/agent/code-agent/memories/facts/shared.md",
- "shared fact",
- )
- await _agfs_write(
- admin_service,
- f"/local/{acct}/agent/review-agent/user/charlie/memories/facts/private.md",
- "private fact",
- )
- await _agfs_write(
- admin_service,
- f"/local/{acct}/agent/review-agent/user/charlie/skills/review/SKILL.md",
- "review skill",
- )
- await _agfs_write(
- admin_service,
- f"/local/{other_acct}/agent/code-agent/memories/facts/other.md",
- "other account fact",
- )
resp = await admin_client.post("/api/v1/admin/migrate", headers=root_headers())
assert resp.status_code == 200
task = await _wait_for_task(admin_client, resp.json()["result"]["task_id"])
assert task["status"] == "completed"
-
result = task["result"]
- assert any(
- item["account_id"] == acct and item["user_id"] == "charlie"
- for item in result["created_users"]
- )
- manager = admin_app.state.api_key_manager
- assert manager.has_user(acct, "charlie")
- assert (
- await _agfs_read_text(
- admin_service,
- f"/local/{acct}/user/admin/peers/code-agent/memories/facts/shared.md",
- )
- == "shared fact"
- )
- assert (
- await _agfs_read_text(
- admin_service,
- f"/local/{acct}/user/charlie/peers/code-agent/memories/facts/shared.md",
- )
- == "shared fact"
- )
- assert (
- await _agfs_read_text(
- admin_service,
- f"/local/{acct}/user/charlie/peers/review-agent/memories/facts/private.md",
- )
- == "private fact"
- )
- assert (
- await _agfs_read_text(
- admin_service,
- f"/local/{acct}/user/charlie/skills/review/SKILL.md",
- )
- == "review skill"
- )
- assert not await _agfs_exists(
- admin_service,
- f"/local/{acct}/user/admin/peers/review-agent/memories/facts/private.md",
- )
- assert (
- await _agfs_read_text(
- admin_service,
- f"/local/{other_acct}/user/dana/peers/code-agent/memories/facts/other.md",
+ assert result["migrated"]["operations"] == {"sessions": 2}
+ assert result["created_users"] == [{"account_id": acct, "user_id": "charlie"}]
+ assert admin_app.state.api_key_manager.has_user(acct, "charlie")
+ assert await _agfs_read_text(admin_service, shared_path) == "shared workflow"
+ for session_id, owner in (("s1", "alice"), ("s2", "charlie")):
+ assert (
+ await _agfs_read_text(
+ admin_service, f"/local/{acct}/user/{owner}/sessions/{session_id}/messages.jsonl"
+ )
+ == '{"role":"user"}\n'
)
- == "other account fact"
- )
+ assert not await _agfs_exists(admin_service, f"/local/{acct}/user/{owner}/peers/workflows")
-async def test_legacy_cleanup_removes_only_legacy_namespaces(
+async def test_legacy_cleanup_preserves_public_agent_directories(
admin_client: httpx.AsyncClient,
admin_service: OpenVikingService,
):
- """Cleanup removes legacy agent/session roots without deleting migrated user data."""
+ """Session cleanup leaves public agent directories and user-owned data intact."""
acct = _uid()
- other_acct = _uid()
await admin_client.post(
"/api/v1/admin/accounts",
json={"account_id": acct, "admin_user_id": "alice"},
headers=root_headers(),
)
- await admin_client.post(
- "/api/v1/admin/accounts",
- json={"account_id": other_acct, "admin_user_id": "dana"},
- headers=root_headers(),
- )
- await _agfs_write(
- admin_service,
- f"/local/{acct}/agent/code-agent/memories/facts/old.md",
- "legacy agent",
- )
- await _agfs_write(
- admin_service,
- f"/local/{acct}/session/sess-001/messages.jsonl",
- '{"role":"user"}\n',
- )
- await _agfs_write(
- admin_service,
- f"/local/{acct}/user/alice/agent/review-agent/memories/facts/old.md",
- "legacy user agent",
- )
- await _agfs_write(
- admin_service,
- f"/local/{acct}/user/alice/peers/code-agent/memories/facts/new.md",
- "new peer data",
- )
- await _agfs_write(
- admin_service,
- f"/local/{acct}/user/alice/sessions/sess-001/messages.jsonl",
- '{"role":"assistant"}\n',
- )
- await _agfs_write(
- admin_service,
- f"/local/{other_acct}/agent/code-agent/memories/facts/old.md",
- "other legacy agent",
- )
+ await _agfs_write(admin_service, f"/local/{acct}/session/s1/messages.jsonl", "old session")
+ preserved_paths = [
+ f"/local/{acct}/agent/skills/demo/SKILL.md",
+ f"/local/{acct}/agent/workflows/daily.md",
+ f"/local/{acct}/user/alice/agent/notes.md",
+ f"/local/{acct}/user/alice/peers/customer/memories/profile.md",
+ f"/local/{acct}/user/alice/sessions/s1/messages.jsonl",
+ ]
+ for path in preserved_paths:
+ await _agfs_write(admin_service, path, "preserved")
resp = await admin_client.post(
"/api/v1/admin/migrate",
@@ -2681,47 +2478,19 @@ async def test_legacy_cleanup_removes_only_legacy_namespaces(
task = await _wait_for_task(admin_client, resp.json()["result"]["task_id"])
assert task["status"] == "completed"
assert task["task_type"] == "legacy_cleanup"
- assert task["result"]["cleanup"]["directories"] == 4
- removed = {
- (item["account_id"], item["source"]) for item in task["result"]["cleanup"]["targets"]
- }
- # Cleanup targets each legacy agent_id individually (reserved subdirs such as
- # viking://agent/skills are preserved), so the agent roots appear per agent.
- assert (acct, "viking://agent/code-agent") in removed
- assert (acct, "viking://session") in removed
- assert (acct, "viking://user/alice/agent") in removed
- assert (other_acct, "viking://agent/code-agent") in removed
-
- assert not await _agfs_exists(admin_service, f"/local/{acct}/agent/code-agent")
+ assert task["result"]["cleanup"]["targets"] == [
+ {"account_id": acct, "type": "session", "source": "viking://session"}
+ ]
assert not await _agfs_exists(admin_service, f"/local/{acct}/session")
- assert not await _agfs_exists(admin_service, f"/local/{acct}/user/alice/agent")
- assert not await _agfs_exists(admin_service, f"/local/{other_acct}/agent/code-agent")
- assert (
- await _agfs_read_text(
- admin_service,
- f"/local/{acct}/user/alice/peers/code-agent/memories/facts/new.md",
- )
- == "new peer data"
- )
- assert (
- await _agfs_read_text(
- admin_service,
- f"/local/{acct}/user/alice/sessions/sess-001/messages.jsonl",
- )
- == '{"role":"assistant"}\n'
- )
+ for path in preserved_paths:
+ assert await _agfs_read_text(admin_service, path) == "preserved"
-async def test_legacy_agent_uri_is_read_only_and_session_storage_uses_canonical_uri(
+async def test_session_storage_uses_canonical_uri(
admin_service: OpenVikingService,
):
- """Old agent/session URIs remain readable but not mutable."""
+ """Canonical session URIs can read existing session storage."""
ctx = RequestContext(user=UserIdentifier("default", "admin_user"), role=Role.USER)
- await _agfs_write(
- admin_service,
- "/local/default/agent/code-agent/memories/facts/project.md",
- "legacy agent fact",
- )
await _agfs_write(
admin_service,
"/local/default/session/old-session/messages.jsonl",
@@ -2733,13 +2502,6 @@ async def test_legacy_agent_uri_is_read_only_and_session_storage_uses_canonical_
'{"created_by_user_id":"admin_user"}',
)
- assert (
- await admin_service.viking_fs.read_file(
- "viking://agent/code-agent/memories/facts/project.md",
- ctx=ctx,
- )
- == "legacy agent fact"
- )
assert (
await admin_service.viking_fs.read_file(
"viking://user/admin_user/sessions/old-session/messages.jsonl",
@@ -2747,12 +2509,6 @@ async def test_legacy_agent_uri_is_read_only_and_session_storage_uses_canonical_
)
== '{"role":"user"}\n'
)
- with pytest.raises(PermissionDeniedError):
- await admin_service.viking_fs.write_file(
- "viking://agent/code-agent/memories/facts/new.md",
- "blocked",
- 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 1f7f083fe..037d50d15 100644
--- a/tests/server/test_admin_rebuild_api.py
+++ b/tests/server/test_admin_rebuild_api.py
@@ -1638,12 +1638,15 @@ async def test_reindex_executor_infers_user_namespace_root():
@pytest.mark.asyncio
-async def test_reindex_executor_rejects_deprecated_agent_namespace_root():
+async def test_reindex_executor_infers_shared_agent_content():
from openviking.service.reindex_executor import ReindexExecutor
service = ReindexExecutor()
- with pytest.raises(OpenVikingError, match="no longer supported"):
+ assert service._infer_target_type("viking://agent/skills") == "skill_namespace"
+ assert service._infer_target_type("viking://agent/skills/demo") == "skill"
+ assert service._infer_target_type("viking://agent/workflows/daily.md") == "resource"
+ with pytest.raises(OpenVikingError, match="Unsupported reindex URI"):
service._infer_target_type("viking://agent/")
diff --git a/tests/storage/test_vector_migration.py b/tests/storage/test_vector_migration.py
index a234e6239..a9b256551 100644
--- a/tests/storage/test_vector_migration.py
+++ b/tests/storage/test_vector_migration.py
@@ -6,7 +6,7 @@ import pytest
from openviking.server.identity import RequestContext, Role
from openviking.storage import vector_migration
from openviking.storage.abstract_overview import parse_abstract_overview
-from openviking.storage.vector_migration import copy_vector_records, delete_vector_records
+from openviking.storage.vector_migration import delete_vector_records
from openviking_cli.session.user_id import UserIdentifier
@@ -132,145 +132,35 @@ directory: viking://resources/source/
class FakeVectorStore:
def __init__(self, records):
self.records = [dict(record) for record in records]
- self.upserts = []
self.deleted_ids = []
async def filter(self, **_kwargs):
return [dict(record) for record in self.records]
- async def upsert(self, data, *, ctx):
- self.upserts.append(dict(data))
- return data["id"]
-
async def delete(self, ids, *, ctx):
self.deleted_ids.extend(ids)
return len(ids)
-async def test_copy_vector_records_rewrites_file_and_chunk_uris():
- store = FakeVectorStore(
- [
- {
- "id": "old-file",
- "uri": "viking://agent/code-agent/memories/facts/project.md",
- "account_id": "acct",
- "owner_user_id": None,
- "context_type": "memory",
- "level": 2,
- "abstract": "project",
- "vector": [0.1, 0.2],
- },
- {
- "id": "old-chunk",
- "uri": "viking://agent/code-agent/memories/facts/project.md#chunk_0000",
- "account_id": "acct",
- "context_type": "memory",
- "level": 2,
- "abstract": "chunk",
- "vector": [0.3, 0.4],
- },
- {
- "id": "outside",
- "uri": "viking://agent/code-agent/memories/facts/other.md",
- "account_id": "acct",
- "context_type": "memory",
- "level": 2,
- "abstract": "other",
- "vector": [0.5, 0.6],
- },
- ]
- )
-
- result = await copy_vector_records(
- store,
- account_id="acct",
- source_uri="viking://agent/code-agent/memories/facts/project.md",
- target_uri="viking://user/alice/peers/code-agent/memories/facts/project.md",
- recursive=False,
- )
-
- assert result.copied == 2
- assert result.skipped == 0
- assert {record["uri"] for record in store.upserts} == {
- "viking://user/alice/peers/code-agent/memories/facts/project.md",
- "viking://user/alice/peers/code-agent/memories/facts/project.md#chunk_0000",
- }
- assert {record["owner_user_id"] for record in store.upserts} == {"alice"}
- assert {record["context_type"] for record in store.upserts} == {"memory"}
- assert all(record["active_count"] == 0 for record in store.upserts)
- assert all(record["id"] not in {"old-file", "old-chunk"} for record in store.upserts)
-
-
-async def test_copy_vector_records_rewrites_directory_subtree_and_skips_scalar_only_records():
- store = FakeVectorStore(
- [
- {
- "id": "old-dir",
- "uri": "viking://agent/code-agent/skills/review",
- "account_id": "acct",
- "context_type": "skill",
- "level": 0,
- "abstract": "review skill",
- "vector": [0.1, 0.2],
- },
- {
- "id": "old-file",
- "uri": "viking://agent/code-agent/skills/review/SKILL.md",
- "account_id": "acct",
- "context_type": "skill",
- "level": 2,
- "abstract": "skill body",
- "vector": [0.3, 0.4],
- },
- {
- "id": "no-vector",
- "uri": "viking://agent/code-agent/skills/review/README.md",
- "account_id": "acct",
- "context_type": "skill",
- "level": 2,
- "abstract": "no vector",
- },
- ]
- )
-
- result = await copy_vector_records(
- store,
- account_id="acct",
- source_uri="viking://agent/code-agent/skills/review",
- target_uri="viking://user/alice/skills/review",
- recursive=True,
- )
-
- assert result.copied == 2
- assert result.skipped == 1
- assert {record["uri"] for record in store.upserts} == {
- "viking://user/alice/skills/review",
- "viking://user/alice/skills/review/SKILL.md",
- }
- assert {record["context_type"] for record in store.upserts} == {"skill"}
-
-
@pytest.mark.asyncio
async def test_delete_vector_records_deletes_records_in_scope_only():
store = FakeVectorStore(
[
{
"id": "old-dir",
- "uri": "viking://agent/code-agent/memories",
+ "uri": "viking://session",
"account_id": "acct",
"vector": [0.1, 0.2],
},
{
"id": "old-file",
- "uri": "viking://agent/code-agent/memories/facts/project.md",
+ "uri": "viking://session/s1/messages.jsonl",
"account_id": "acct",
"vector": [0.3, 0.4],
},
{
"id": "new-file",
- "uri": "viking://user/alice/peers/code-agent/memories/facts/project.md",
+ "uri": "viking://user/alice/sessions/s1/messages.jsonl",
"account_id": "acct",
"vector": [0.5, 0.6],
},
@@ -280,7 +170,7 @@ async def test_delete_vector_records_deletes_records_in_scope_only():
result = await delete_vector_records(
store,
account_id="acct",
- uri="viking://agent/code-agent/memories",
+ uri="viking://session",
)
assert result.deleted == 2
diff --git a/tests/storage/test_viking_fs_actor_peer_view.py b/tests/storage/test_viking_fs_actor_peer_view.py
index 86c75a25b..dfd167331 100644
--- a/tests/storage/test_viking_fs_actor_peer_view.py
+++ b/tests/storage/test_viking_fs_actor_peer_view.py
@@ -1,6 +1,8 @@
# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
# SPDX-License-Identifier: AGPL-3.0
+from dataclasses import replace
+
import pytest
from openviking.server.identity import RequestContext, Role
@@ -14,8 +16,9 @@ _MOD_TIME = "2026-01-01T00:00:00Z"
class _MemoryAGFS:
def __init__(self):
self.files = {
- "/local/acct/agent/customer-wang-yue/memories/profile.md": b"legacy-wang",
- "/local/acct/agent/customer-zhang-xiaoxiao/memories/profile.md": b"legacy-zhang",
+ "/local/acct/agent/skills/demo/SKILL.md": b"shared skill",
+ "/local/acct/agent/tools/search/config.json": b"{}",
+ "/local/acct/agent/workflows/daily.md": b"shared workflow",
"/local/acct/user/support_bot/peers/customer-wang-yue/memories/profile.md": b"wang",
"/local/acct/user/support_bot/peers/customer-zhang-xiaoxiao/memories/profile.md": (
b"zhang"
@@ -54,7 +57,7 @@ class _MemoryAGFS:
self.writes = []
self.removed = []
- def ls(self, path, ctx=None):
+ def ls(self, path, ctx=None, *, offset=0, limit=None):
if path not in self.dirs:
raise FileNotFoundError(path)
prefix = path.rstrip("/") + "/"
@@ -65,7 +68,8 @@ class _MemoryAGFS:
rest = candidate[len(prefix) :]
if rest and "/" not in rest:
names.add(rest)
- return [self._entry(f"{prefix}{name}") for name in sorted(names)]
+ entries = [self._entry(f"{prefix}{name}") for name in sorted(names)]
+ return entries[offset : offset + limit if limit is not None else None]
def tree_directory(
self,
@@ -188,23 +192,24 @@ async def test_actor_peer_view_filters_ls_peer_collection(fs, actor_ctx):
@pytest.mark.asyncio
-async def test_actor_peer_view_filters_legacy_agent_collection(fs, actor_ctx):
- entries = await fs.ls("viking://agent", ctx=actor_ctx)
-
- assert [entry["uri"] for entry in entries] == ["viking://agent/customer-wang-yue"]
- assert (
- await fs.read_file(
- "viking://agent/customer-wang-yue/memories/profile.md",
- ctx=actor_ctx,
- )
- == "legacy-wang"
- )
- with pytest.raises(PermissionDeniedError):
- await fs.read_file(
- "viking://agent/customer-zhang-xiaoxiao/memories/profile.md",
- ctx=actor_ctx,
+async def test_agent_directories_are_shared_within_account(fs, actor_ctx):
+ for ctx in (actor_ctx, replace(actor_ctx, actor_peer_id="another-peer")):
+ entries = await fs.ls("viking://agent", ctx=ctx)
+ assert [entry["uri"] for entry in entries] == [
+ "viking://agent/skills",
+ "viking://agent/tools",
+ "viking://agent/workflows",
+ ]
+ assert await fs.read_file("viking://agent/skills/demo/SKILL.md", ctx=ctx) == "shared skill"
+ await fs.write_file("viking://agent/workflows/daily.md", "updated workflow", ctx=ctx)
+ assert (
+ await fs.read_file("viking://agent/workflows/daily.md", ctx=ctx) == "updated workflow"
)
+ other_account = replace(actor_ctx, user=UserIdentifier("other-acct", "support_bot"))
+ with pytest.raises(NotFoundError):
+ await fs.read_file("viking://agent/skills/demo/SKILL.md", ctx=other_account)
+
@pytest.mark.asyncio
async def test_legacy_session_scope_merges_new_and_unmigrated_sessions(fs, actor_ctx):
diff --git a/tests/storage/test_viking_vector_scope_filter.py b/tests/storage/test_viking_vector_scope_filter.py
index bed68f88f..666790d01 100644
--- a/tests/storage/test_viking_vector_scope_filter.py
+++ b/tests/storage/test_viking_vector_scope_filter.py
@@ -103,7 +103,7 @@ def test_all_targets_may_be_under_different_visible_roots():
targets = [
"viking://resources/wiki/physics",
"viking://user/alice/resources/private-notes",
- "viking://agent/skills/research",
+ "viking://agent/tools/search",
]
result = _build(ctx, targets)
@@ -116,7 +116,7 @@ def test_all_targets_may_be_under_different_visible_roots():
[
PathScope("uri", "viking://resources/wiki/physics", depth=-1),
PathScope("uri", "viking://user/alice/resources/private-notes", depth=-1),
- PathScope("uri", "viking://agent/skills/research", depth=-1),
+ PathScope("uri", "viking://agent/tools/search", depth=-1),
]
),
]
@@ -160,7 +160,7 @@ async def test_tenant_search_enforces_visible_roots_and_shared_acl(tmp_path, leg
{
**legacy_mode,
"id": "legacy-shared",
- "uri": "viking://resources/legacy.md",
+ "uri": "viking://agent/workflows/daily.md",
"account_id": "acct",
"context_type": "resource",
},
@@ -305,7 +305,7 @@ def test_segment_prefix_and_visible_root_ancestor_do_not_elide_tenant_filter():
ctx = _ctx()
segment_prefix = _build(ctx, ["viking://resources-other/wiki"])
- ancestor = _build(ctx, ["viking://agent"])
+ ancestor = _build(ctx, ["viking://user"])
assert segment_prefix == And(
[
@@ -318,7 +318,7 @@ def test_segment_prefix_and_visible_root_ancestor_do_not_elide_tenant_filter():
[
Eq("context_type", "resource"),
_tenant_filter(ctx),
- Or([PathScope("uri", "viking://agent", depth=-1)]),
+ Or([PathScope("uri", "viking://user", depth=-1)]),
]
)
diff --git a/tests/unit/test_namespace_uri_classification.py b/tests/unit/test_namespace_uri_classification.py
index 6026c3fe5..765a420aa 100644
--- a/tests/unit/test_namespace_uri_classification.py
+++ b/tests/unit/test_namespace_uri_classification.py
@@ -42,9 +42,8 @@ def test_context_type_for_uri_uses_path_segments():
context_type_for_uri("viking://user/support_bot/peers/web-visitor-alice/resources/faq.md")
== "resource"
)
- assert context_type_for_uri("viking://agent/code-agent/memories/profile.md") == "memory"
- assert context_type_for_uri("viking://agent/code-agent/resources/faq.md") == "resource"
- assert context_type_for_uri("viking://agent/code-agent/skills/demo") == "skill"
+ assert context_type_for_uri("viking://agent/tools/memories/guide.md") == "resource"
+ assert context_type_for_uri("viking://agent/workflows/skills/demo.md") == "resource"
assert context_type_for_uri("viking://agent/skills") == "skill"
assert context_type_for_uri("viking://agent/skills/demo") == "skill"
assert context_type_for_uri("viking://resources/memories-report.md") == "resource"
@@ -94,11 +93,20 @@ def test_exact_memory_and_skill_root_detection():
assert not classify_uri("viking://user/alice/skills/demo/assets").is_skill_root
-def test_owner_space_for_uri_uses_user_only():
+def test_shared_agent_skill_target_has_no_user_owner_or_peer_filter():
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") == ""
+ ctx = RequestContext(
+ user=UserIdentifier(account_id="acct", user_id="support_bot"),
+ role=Role.ADMIN,
+ actor_peer_id="workspace-test-peer",
+ )
+ for uri in ("viking://agent/skills", "viking://agent/skills/demo"):
+ assert validate_content_target_uri(uri, ctx, kind="skill") == uri
+ assert owner_space_for_uri(uri) == ""
+
def test_session_uri_helpers_use_user_namespace():
ctx = RequestContext(
@@ -128,8 +136,7 @@ def test_session_uri_helpers_use_user_namespace():
assert is_session_uri("viking://session/s1")
roots = visible_roots(ctx)
assert "viking://session" not in roots
- assert "viking://agent" not in roots
- assert "viking://agent/skills" in roots
+ assert "viking://agent" in roots
def test_request_boundary_rejects_reserved_user_root_shorthand():
diff --git a/tests/unit/test_uri_validation.py b/tests/unit/test_uri_validation.py
index 0bc054668..ca529b812 100644
--- a/tests/unit/test_uri_validation.py
+++ b/tests/unit/test_uri_validation.py
@@ -14,7 +14,7 @@ from openviking_cli.exceptions import InvalidURIError
[
"viking://resources/docs",
"viking://session/s1",
- "viking://agent/code-agent/memories/facts/project.md",
+ "viking://agent/skills/demo/SKILL.md",
"viking://",
"viking://~",
"viking://~/memories/x",