Self-evolving Context Database for AI Agents. Unify Agent Memory, Knowledge RAG and Skills.
Python agent-contextagent-memoryagent-pluginsagentic-ragcontext-databasedsh-pluginknowledge-basememorymemory-managementself-evolvingvector-database
refactor(admin)!: 退役旧会话迁移,保留迁移接口 (#6746)
bot-of-qin-ctxe6b1f8e3bd1f
diff --git a/crates/ov_cli/README.md b/crates/ov_cli/README.mdindex 217818224..bd8abb640 100644--- a/crates/ov_cli/README.md+++ b/crates/ov_cli/README.md@@ -249,7 +249,6 @@ Use `--sudo` for commands that require the configured `root_api_key`.- `admin set-role` - Change a user's role. ROOT only.- `admin regenerate-key` - Rotate a user's API key.- `admin set-account-settings` - Update allowlisted account settings.-- `admin migrate` - Migrate legacy agent/session data. ROOT only.- `system` - Administrative system utility commands.- `reindex` - Rebuild semantic and vector artifacts for a URI.diff --git a/crates/ov_cli/README_CN.md b/crates/ov_cli/README_CN.mdindex cd58a1195..b6b705fb6 100644--- a/crates/ov_cli/README_CN.md+++ b/crates/ov_cli/README_CN.md@@ -248,7 +248,6 @@ ov session commit s1 --no-event-tags- `admin remove-user` - 移除用户。- `admin set-role` - 修改用户角色,仅 ROOT。- `admin regenerate-key` - 轮转用户 API key。-- `admin migrate` - 迁移 legacy agent/session 数据,仅 ROOT。- `system` - 管理类系统工具命令。- `reindex` - 为 URI 重建语义和向量产物。diff --git a/crates/ov_cli/src/client.rs b/crates/ov_cli/src/client.rsindex de193a0c2..5863a56a4 100644--- a/crates/ov_cli/src/client.rs+++ b/crates/ov_cli/src/client.rs@@ -1889,15 +1889,6 @@ impl HttpClient {self.delete(&path, &[]).await}- pub async fn admin_migrate(&self, cleanup: bool) -> Result<Value> {- let action = if cleanup { "cleanup" } else { "migrate" };- self.post(- "/api/v1/admin/migrate",- &serde_json::json!({ "action": action }),- )- .await- }-// ============ Debug Vector Methods ============/// Get paginated vector recordsdiff --git a/crates/ov_cli/src/commands/admin.rs b/crates/ov_cli/src/commands/admin.rsindex 811dd0adf..201a1191f 100644--- a/crates/ov_cli/src/commands/admin.rs+++ b/crates/ov_cli/src/commands/admin.rs@@ -58,17 +58,6 @@ pub async fn delete_account(Ok(())}-pub async fn migrate(- client: &HttpClient,- cleanup: bool,- output_format: OutputFormat,- compact: bool,-) -> Result<()> {- let response = client.admin_migrate(cleanup).await?;- output_success(&response, output_format, compact);- Ok(())-}-pub async fn register_user(client: &HttpClient,account_id: &str,diff --git a/crates/ov_cli/src/error_ui.rs b/crates/ov_cli/src/error_ui.rsindex ab95f3d61..80c7d24d5 100644--- a/crates/ov_cli/src/error_ui.rs+++ b/crates/ov_cli/src/error_ui.rs@@ -432,7 +432,6 @@ fn contextual_help_command(command: &str) -> Option<String> {"create-account","list-accounts","delete-account",- "migrate","register-user","list-users","create-group",diff --git a/crates/ov_cli/src/handlers.rs b/crates/ov_cli/src/handlers.rsindex bc6d8a95f..b517d4554 100644--- a/crates/ov_cli/src/handlers.rs+++ b/crates/ov_cli/src/handlers.rs@@ -620,9 +620,6 @@ pub async fn handle_admin(cmd: AdminCommands, ctx: CliContext) -> Result<()> {commands::admin::delete_account(&client, &account_id, ctx.output_format, ctx.compact).await}- AdminCommands::Migrate { cleanup } => {- commands::admin::migrate(&client, cleanup, ctx.output_format, ctx.compact).await- }AdminCommands::RegisterUser {account_id,user_id,diff --git a/crates/ov_cli/src/help_ui.rs b/crates/ov_cli/src/help_ui.rsindex d1eaacb19..99e3f3c4d 100644--- a/crates/ov_cli/src/help_ui.rs+++ b/crates/ov_cli/src/help_ui.rs@@ -1362,14 +1362,6 @@ const COMMAND_HELP_SPECS: &[CommandHelpSpec] = &[label: "ov admin regenerate-key <account> <user> --seed <seed>",description: "Regenerate a predictable API key from a seed.",},- HelpItem {- label: "ov admin migrate --sudo",- description: "Start legacy agent/session migration.",- },- HelpItem {- label: "ov admin migrate --cleanup --sudo",- description: "Remove legacy agent/session directories after verifying migration.",- },],next_steps: &[HelpItem {diff --git a/crates/ov_cli/src/main.rs b/crates/ov_cli/src/main.rsindex fd6fb3922..3e20361f6 100644--- a/crates/ov_cli/src/main.rs+++ b/crates/ov_cli/src/main.rs@@ -2144,12 +2144,6 @@ enum AdminCommands {#[arg(value_name = "account-id")]account_id: String,},- /// Migrate legacy agent/session data to user-owned namespaces (ROOT only)- Migrate {- /// Remove legacy agent/session directories after migration is verified- #[arg(long)]- cleanup: bool,- },/// Register a new user in an accountRegisterUser {/// Account ID@@ -2854,7 +2848,6 @@ fn is_admin_subcommand(token: &str) -> bool {"create-account"| "list-accounts"| "delete-account"- | "migrate"| "register-user"| "list-users"| "create-group"@@ -4085,8 +4078,8 @@ mod tests {render_pre_language_help_request, resolve_output_format,};use crate::config::{Config, DEFAULT_CUSTOM_URL};+ use crate::handlers;use crate::output::OutputFormat;- use crate::{AdminCommands, handlers};use clap::{CommandFactory, Parser};use std::ffi::OsString;@@ -4222,31 +4215,6 @@ mod tests {}}- #[test]- fn cli_parses_admin_migrate_cleanup_flag() {- let migrate = Cli::try_parse_from(["ov", "--sudo", "admin", "migrate"])- .expect("admin migrate should parse");- match migrate.command {- Commands::Admin { action } => match action {- AdminCommands::Migrate { cleanup } => assert!(!cleanup),- _ => panic!("expected admin migrate command"),- },- _ => panic!("expected admin command"),- }-- let cleanup = Cli::try_parse_from(["ov", "--sudo", "admin", "migrate", "--cleanup"])- .expect("admin migrate cleanup should parse");-- assert!(cleanup.sudo);- match cleanup.command {- Commands::Admin { action } => match action {- AdminCommands::Migrate { cleanup } => assert!(cleanup),- _ => panic!("expected admin migrate command"),- },- _ => panic!("expected admin command"),- }- }-#[test]fn cli_parses_search_context_mode_and_type() {let cli = Cli::try_parse_from([@@ -4742,7 +4710,6 @@ mod tests {&["ov", "admin", "create-account"],&["ov", "admin", "list-accounts"],&["ov", "admin", "delete-account"],- &["ov", "admin", "migrate"],&["ov", "admin", "register-user"],&["ov", "admin", "list-users"],&["ov", "admin", "create-group"],@@ -5318,7 +5285,7 @@ mod tests {"task","list","--task-type",- "legacy_migration",+ "admin_reindex",]).expect("sudo task list should parse");assert!(list.sudo);diff --git a/docs/en/about/02-changelog.md b/docs/en/about/02-changelog.mdindex 9b666662f..70e462022 100644--- a/docs/en/about/02-changelog.md+++ b/docs/en/about/02-changelog.md@@ -7,6 +7,14 @@ This changelog is automatically generated from [GitHub Releases](https://github.## Unreleased+- **Legacy session migration removed (breaking change)**: Removed the legacy+ implementation, `ov admin migrate` (including `--cleanup`), and the corresponding+ Python, TypeScript, and Go SDK methods. The ROOT-only `POST /api/v1/admin/migrate`+ endpoint remains reserved and currently returns `400 / INVALID_ARGUMENT` without+ creating a task. New releases no longer+ provide migration or cleanup of legacy 0.3.x sessions; upgrading does not move or+ delete those old directories. Migrated sessions and normal session operations+ are unaffected.- **Gateway deployment and behavior**:- New standalone Helm chart, `deploy/helm/openviking-gateway`: one SQLite replica with aPVC, or several replicas sharing Redis. Until a release includes these features, setdiff --git a/docs/en/api/01-overview.md b/docs/en/api/01-overview.mdindex 33c58491b..51f22d56c 100644--- a/docs/en/api/01-overview.md+++ b/docs/en/api/01-overview.md@@ -514,7 +514,7 @@ This catalog follows the routes actually mounted by the server. Each group headi| DELETE | `/api/v1/admin/accounts/{account_id}/memory-templates/{memory_type}` | Remove a memory template override and restore deployment defaults || POST | `/api/v1/admin/accounts` | Create an account and its first administrator || GET | `/api/v1/admin/accounts` | List accounts |-| POST | `/api/v1/admin/migrate` | Migrate legacy identity data |+| POST | `/api/v1/admin/migrate` | Reserved migration endpoint; ROOT-only, currently returns 400 INVALID_ARGUMENT || GET | `/api/v1/admin/accounts/{account_id}` | Get credential-free metadata for one account || DELETE | `/api/v1/admin/accounts/{account_id}` | Delete an account || POST | `/api/v1/admin/accounts/{account_id}/users` | Register a user |diff --git a/docs/en/api/08-admin.md b/docs/en/api/08-admin.mdindex 19b1704cd..5687b2dd6 100644--- a/docs/en/api/08-admin.md+++ b/docs/en/api/08-admin.md@@ -48,8 +48,7 @@ Configure `root_api_key` in `~/.openviking/ovcli.conf`:- `ov --sudo admin` - Account and user management- `ov --sudo system` - System utility commands- `ov --sudo reindex` - Rebuild indexes-- `ov --sudo admin migrate` - Legacy session migration and cleanup-- `ov --sudo task status/list` - Query root/system background tasks, such as migration tasks+- `ov --sudo task status/list` - Query root/system background tasks, such as account deletion tasks### Usage Limitations@@ -2044,113 +2043,23 @@ the request is in progress, the command exits with an error and keeps the return----### migrate_legacy_data+### Reserved migration endpoint-#### 1. API Implementation Overview--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 session files; during cleanup, delete old session vector records before deleting old session AGFS directories--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-- `openviking/service/legacy_migration.py:LegacyDataMigration` - Migration implementation--#### 2. Interface and Parameters--**HTTP API**--```-POST /api/v1/admin/migrate-```--**Parameters**--| Parameter | Type | Required | Default | Description |-|-----------|------|----------|---------|-------------|-| action | str | No | migrate | `migrate` runs migration; `cleanup` removes old namespaces |--**Migration result fields**--| Field | Description |-|-------|-------------|-| migrated.files / migrated.directories | Number of files and directories copied |-| migrated.operations | Session migration operation count (`sessions`) |-| skipped / created_users | Skipped files and users created automatically |--**Cleanup result fields**--| Field | Description |-|-------|-------------|-| cleanup.directories | Number of legacy directories deleted |-| cleanup.vector_records | Number of old vector records deleted |-| cleanup.targets | Legacy scopes that were cleaned |-| skipped / warnings | Skipped items and warnings |+`POST /api/v1/admin/migrate` is reserved for future migration operations. It requires+ROOT authentication and currently returns `400 Bad Request` with error code+`INVALID_ARGUMENT` and message `Data migration is not currently supported.`-#### 3. Usage Examples--**HTTP API**+No migration parameters are currently supported. Sending the previous+`{"action":"migrate"}` or `{"action":"cleanup"}` body also returns this error.+The endpoint does not create a task or modify migration data. Unauthenticated+requests return `401`; authenticated ADMIN or USER requests return `403`.```bash-# Run migration-curl -X POST http://localhost:1933/api/v1/admin/migrate \- -H "Content-Type: application/json" \- -H "X-API-Key: <root-key>" \- -d '{"action": "migrate"}'--# Clean old namespaces after the migration task finishes and migrated data is verifiedcurl -X POST http://localhost:1933/api/v1/admin/migrate \- -H "Content-Type: application/json" \- -H "X-API-Key: <root-key>" \- -d '{"action": "cleanup"}'-```--**Python SDK**--```python-print(client.admin_migrate(cleanup=False))-```--**TypeScript SDK**--```typescript-console.log(await client.adminMigrate(false));-```--**Go SDK**--```go-result, err := client.AdminMigrate(ctx, &openviking.AdminMigrateOptions{- Cleanup: false,-})-if err != nil {- return err-}-fmt.Println(result["task_id"])-```--**CLI**--```bash-ov --sudo admin migrate --output json-# Check the returned task with ov --sudo task status <task_id>, then verify migrated data.-ov --sudo admin migrate --cleanup --output json+ -H "X-API-Key: <root-key>"```-**CLI Response Example (default compact output)**--```json-{- "ok": true,- "result": {"task_id": "6de05fc3-0334-40d6-ba9b-dd317eb4d351"}-}-```+The old `ov admin migrate` command and corresponding SDK methods have been removed.---diff --git a/docs/zh/about/02-changelog.md b/docs/zh/about/02-changelog.mdindex 5a1d8329a..1d2a1cf16 100644--- a/docs/zh/about/02-changelog.md+++ b/docs/zh/about/02-changelog.md@@ -7,6 +7,11 @@ OpenViking 的所有重要变更都将记录在此文件中。## 未发布+- **移除旧会话迁移(不兼容变更)**:删除旧迁移实现、`ov admin migrate`(含 `--cleanup`)+ 及 Python、TypeScript、Go SDK 的对应方法。保留仅 ROOT 可调用的+ `POST /api/v1/admin/migrate` 入口,当前返回 `400 / INVALID_ARGUMENT`,不创建任务。+ 新版本不再提供 0.3.x 遗留会话的迁移和清理工具;升级不会自动迁移或删除这些旧目录。+ 已迁移的会话和正常会话操作不受影响。- **网关部署与行为**:- 新增独立 Helm chart `deploy/helm/openviking-gateway`:带 PVC 的单副本 SQLite,或共享 Redis 的多副本部署。在包含这些功能的版本发布之前,需要显式设置 `image.tag`,diff --git a/docs/zh/api/01-overview.md b/docs/zh/api/01-overview.mdindex 1ad5011d3..503b31466 100644--- a/docs/zh/api/01-overview.md+++ b/docs/zh/api/01-overview.md@@ -509,7 +509,7 @@ JSON 输出 - 错误:| DELETE | `/api/v1/admin/accounts/{account_id}/memory-templates/{memory_type}` | 删除记忆模板覆盖,恢复部署默认值 || POST | `/api/v1/admin/accounts` | 创建账号及首个管理员 || GET | `/api/v1/admin/accounts` | 列出账号 |-| POST | `/api/v1/admin/migrate` | 迁移旧版身份数据 |+| POST | `/api/v1/admin/migrate` | 预留迁移入口;仅 ROOT 可调用,当前返回 400 INVALID_ARGUMENT || GET | `/api/v1/admin/accounts/{account_id}` | 获取单个账号的无凭据元数据 || DELETE | `/api/v1/admin/accounts/{account_id}` | 删除账号 || POST | `/api/v1/admin/accounts/{account_id}/users` | 注册用户 |diff --git a/docs/zh/api/08-admin.md b/docs/zh/api/08-admin.mdindex 019a5802b..20b2dd5ee 100644--- a/docs/zh/api/08-admin.md+++ b/docs/zh/api/08-admin.md@@ -48,8 +48,7 @@ Admin API 用于多租户环境下的账户、用户和用户组管理。包括- `ov --sudo admin` - 账户和用户管理- `ov --sudo system` - 系统工具命令- `ov --sudo reindex` - 重建索引-- `ov --sudo admin migrate` - 旧 Session 迁移和清理-- `ov --sudo task status/list` - 查询 root/system 后台任务,例如迁移任务+- `ov --sudo task status/list` - 查询 root/system 后台任务,例如账号删除任务### 使用限制@@ -1896,113 +1895,22 @@ CLI 在请求轮换前检查能否准备替换文件。如果服务端已换钥----### migrate_legacy_data+### 预留迁移入口-#### 1. API 实现介绍--将旧 `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. 迁移时复制 Session 文件;cleanup 时先删除旧 Session 向量记录,再删除旧 Session AGFS 目录+`POST /api/v1/admin/migrate` 为后续迁移需求保留,仅 ROOT 可调用。当前返回+`400 Bad Request`,错误码为 `INVALID_ARGUMENT`,错误消息为+`Data migration is not currently supported.`(当前不支持数据迁移)。-迁移保留目标路径中已有的文件。cleanup 不删除 `agent` 公共目录或已迁移的用户数据。--**代码入口:**-- `openviking/server/routers/admin.py:migrate_legacy_data` - HTTP 路由-- `openviking/service/legacy_migration.py:LegacyDataMigration` - 迁移实现--#### 2. 接口和参数说明--**HTTP API**--```-POST /api/v1/admin/migrate-```--**参数**--| 参数 | 类型 | 必填 | 默认值 | 说明 |-|------|------|------|--------|------|-| action | str | 否 | migrate | `migrate` 执行迁移;`cleanup` 清理旧 namespace |--**迁移结果字段**--| 字段 | 说明 |-|------|------|-| migrated.files / migrated.directories | 复制的文件和目录数量 |-| migrated.operations | Session 迁移操作数量(`sessions`) |-| skipped / created_users | 跳过的文件、自动创建的用户 |--**Cleanup 结果字段**--| 字段 | 说明 |-|------|------|-| cleanup.directories | 删除的 legacy 目录数量 |-| cleanup.vector_records | 删除的旧向量记录数量 |-| cleanup.targets | 已清理的 legacy scope |-| skipped / warnings | 跳过项和告警 |--#### 3. 使用示例--**HTTP API**+当前没有支持的迁移参数。传入原来的 `{"action":"migrate"}` 或+`{"action":"cleanup"}` 也返回上述错误,不创建任务,不读写迁移数据。+未认证请求返回 `401`;已认证的 ADMIN 或 USER 请求返回 `403`。```bash-# 执行迁移-curl -X POST http://localhost:1933/api/v1/admin/migrate \- -H "Content-Type: application/json" \- -H "X-API-Key: <root-key>" \- -d '{"action": "migrate"}'--# 迁移任务完成并核对目标数据后,再清理旧 namespacecurl -X POST http://localhost:1933/api/v1/admin/migrate \- -H "Content-Type: application/json" \- -H "X-API-Key: <root-key>" \- -d '{"action": "cleanup"}'-```--**Python SDK**--```python-print(client.admin_migrate(cleanup=False))-```--**TypeScript SDK**--```typescript-console.log(await client.adminMigrate(false));-```--**Go SDK**--```go-result, err := client.AdminMigrate(ctx, &openviking.AdminMigrateOptions{- Cleanup: false,-})-if err != nil {- return err-}-fmt.Println(result["task_id"])-```--**CLI**--```bash-ov --sudo admin migrate --output json-# 先用 ov --sudo task status <task_id> 查询返回的任务,再核对迁移结果。-ov --sudo admin migrate --cleanup --output json+ -H "X-API-Key: <root-key>"```-**CLI 响应示例(默认 compact 输出)**--```json-{- "ok": true,- "result": {"task_id": "6de05fc3-0334-40d6-ba9b-dd317eb4d351"}-}-```+旧 `ov admin migrate` 命令和对应 SDK 方法已移除。---diff --git a/openviking/server/routers/admin.py b/openviking/server/routers/admin.pyindex be44f44fd..9ed391617 100644--- a/openviking/server/routers/admin.py+++ b/openviking/server/routers/admin.py@@ -33,14 +33,6 @@ from openviking.server.user_config import (write_user_config,write_user_memory_policy,)-from openviking.service.legacy_migration import LegacyDataMigration-from openviking.service.task_store import (- SYSTEM_TASK_ACCOUNT_ID,- SYSTEM_TASK_USER_ID,-)-from openviking.service.task_tracker import (- get_task_tracker,-)from openviking.session.memory.account_templates import (EDITABLE_MEMORY_TEMPLATE_FIELDS,default_memory_template,@@ -96,10 +88,6 @@ class CreateGroupRequest(BaseModel):group_id: str-class MigrateLegacyDataRequest(BaseModel):- action: str = "migrate"--class SetAgentEvolutionRequest(BaseModel):enabled: bool@@ -424,28 +412,6 @@ def _user_settings_result(}-async def _run_legacy_migration_task(- task_id: str,- migration: LegacyDataMigration,- *,- action: str,- account_id: str,- user_id: str,-) -> None:- tracker = get_task_tracker()- await tracker.start(task_id, account_id=account_id, user_id=user_id, stage="running")- try:- if action == "cleanup":- result = await migration.cleanup()- else:- result = await migration.run()- except Exception as exc:- await tracker.fail(task_id, str(exc), account_id=account_id, user_id=user_id)- logger.exception("Legacy %s task %s failed", action, task_id)- return- await tracker.complete(task_id, result, account_id=account_id, user_id=user_id)--# ---- Account endpoints ----@@ -537,54 +503,14 @@ async def get_account(return Response(status="ok", result=account)[email protected]("/migrate")[email protected]("/migrate", status_code=400)@require_auth_root-async def migrate_legacy_data(+async def migrate_data(request: Request,- body: MigrateLegacyDataRequest | None = None,ctx: RequestContext = Depends(get_request_context),):- """Preflight and enqueue legacy session data migration or cleanup."""- manager = _get_api_key_manager(request)- service = get_service()- if service.viking_fs is None:- raise FailedPreconditionError("OpenViking service is not initialized.")- action = (body.action if body else "migrate").strip().lower()- if action not in {"migrate", "cleanup"}:- raise InvalidArgumentError("Migration action must be 'migrate' or 'cleanup'.")-- migration = LegacyDataMigration(- viking_fs=service.viking_fs,- api_key_manager=manager,- service=service,- )- if action == "migrate":- plan = await migration.preflight()- if plan.errors:- raise FailedPreconditionError(- "Legacy migration preflight failed.",- details=plan.to_preflight_result(),- )-- tracker = get_task_tracker()- task_type = "legacy_cleanup" if action == "cleanup" else "legacy_migration"- resource_id = "legacy-data-cleanup" if action == "cleanup" else "legacy-data"- task = await tracker.create(- task_type,- resource_id=resource_id,- account_id=SYSTEM_TASK_ACCOUNT_ID,- user_id=SYSTEM_TASK_USER_ID,- )- asyncio.create_task(- _run_legacy_migration_task(- task.task_id,- migration,- action=action,- account_id=SYSTEM_TASK_ACCOUNT_ID,- user_id=SYSTEM_TASK_USER_ID,- )- )- return Response(status="ok", result={"task_id": task.task_id})+ """Reserve the ROOT migration endpoint without running a migration."""+ raise InvalidArgumentError("Data migration is not currently supported.")@router.delete("/accounts/{account_id}", status_code=202)diff --git a/openviking/service/legacy_migration.py b/openviking/service/legacy_migration.pydeleted file mode 100644index 1146962ab..000000000--- a/openviking/service/legacy_migration.py+++ /dev/null@@ -1,473 +0,0 @@-# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.-# SPDX-License-Identifier: AGPL-3.0-"""Legacy session data migration to user-owned namespaces."""--from __future__ import annotations--import json-from dataclasses import dataclass, field-from typing import Any--from openviking.pyagfs import AsyncAGFSClient-from openviking.server.identity import RequestContext, Role-from openviking.storage.vector_migration import (- VectorMigrationResult,- delete_vector_records,-)-from openviking.storage.viking_fs import VikingFS-from openviking_cli.exceptions import FailedPreconditionError-from openviking_cli.session.user_id import UserIdentifier, validate_user_id---@dataclass(frozen=True)-class TreeCopy:- source_path: str- target_path: str- category: str---@dataclass(frozen=True)-class LegacyCleanupTarget:- account_id: str- source_path: str- source_uri: str- category: str---@dataclass-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)- errors: list[dict[str, Any]] = field(default_factory=list)-- def to_preflight_result(self) -> dict[str, Any]:- return {- "errors": list(self.errors),- "created_users": [- {"account_id": account_id, "user_id": user_id}- for account_id, user_id in sorted(self.created_users)- ],- "operation_count": len(self.operations),- }---@dataclass-class LegacyCleanupPlan:- targets: list[LegacyCleanupTarget] = field(default_factory=list)---@dataclass-class MigrationResult:- files: int = 0- directories: int = 0- operations: dict[str, int] = field(default_factory=dict)- skipped: list[dict[str, Any]] = field(default_factory=list)- created_users: list[dict[str, Any]] = field(default_factory=list)-- def mark_operation(self, category: str) -> None:- self.operations[category] = self.operations.get(category, 0) + 1-- def to_dict(self) -> dict[str, Any]:- return {- "migrated": {- "files": self.files,- "directories": self.directories,- "operations": dict(sorted(self.operations.items())),- },- "skipped": self.skipped,- "created_users": self.created_users,- }---@dataclass-class LegacyCleanupResult:- vector_records: int = 0- removed: list[dict[str, Any]] = field(default_factory=list)- skipped: list[dict[str, Any]] = field(default_factory=list)- warnings: list[str] = field(default_factory=list)-- def to_dict(self) -> dict[str, Any]:- return {- "cleanup": {- "directories": len(self.removed),- "vector_records": self.vector_records,- "targets": self.removed,- },- "skipped": self.skipped,- "warnings": self.warnings,- }---def target_to_dict(target: LegacyCleanupTarget) -> dict[str, str]:- return {- "account_id": target.account_id,- "type": target.category,- "source": target.source_uri,- }---class LegacyDataMigration:- """Plan and execute legacy session migration."""-- def __init__(self, *, viking_fs: VikingFS, api_key_manager: Any, service: Any):- if api_key_manager is None:- raise FailedPreconditionError("Admin migration requires an API key user registry.")- self._viking_fs = viking_fs- self._agfs = AsyncAGFSClient(viking_fs.agfs)- self._api_key_manager = api_key_manager- self._service = service-- async def preflight(self) -> MigrationPlan:- plan = MigrationPlan()- registry_accounts = await self._registry_account_ids()- physical_accounts = await self._physical_account_ids()- for account_id in sorted(physical_accounts - registry_accounts):- if await self._exists(f"/local/{account_id}/session"):- plan.errors.append(- {- "account_id": account_id,- "reason": (- "legacy data exists under an account missing from the user registry"- ),- }- )-- for account_id in sorted(registry_accounts):- plan.account_users[account_id] = set()- for user_id in sorted(await self._registry_user_ids(account_id)):- await self._ensure_plan_user(account_id, user_id, plan)- if await self._exists(f"/local/{account_id}/session"):- for user_id in sorted(await self._physical_user_ids(account_id)):- await self._ensure_plan_user(account_id, user_id, plan)- await self._plan_sessions(account_id, plan)- return plan-- async def run(self) -> dict[str, Any]:- plan = await self.preflight()- if plan.errors:- raise FailedPreconditionError(- "Legacy migration preflight failed.",- details=plan.to_preflight_result(),- )-- result = MigrationResult()- for account_id, user_id in sorted(plan.created_users):- if await self._has_user(account_id, user_id):- continue- user_ctx = RequestContext(user=UserIdentifier(account_id, user_id), role=Role.USER)- await self._api_key_manager.register_user(account_id, user_id, "user")- await self._service.initialize_user_directories(user_ctx)- result.created_users.append({"account_id": account_id, "user_id": user_id})-- for operation in plan.operations:- if await self._copy_path(operation.source_path, operation.target_path, result):- result.mark_operation(operation.category)- return result.to_dict()-- async def cleanup_preflight(self) -> LegacyCleanupPlan:- plan = LegacyCleanupPlan()- for account_id in sorted(await self._physical_account_ids()):- session_path = f"/local/{account_id}/session"- if await self._exists(session_path):- plan.targets.append(self._cleanup_target(account_id, session_path, "session"))-- return plan-- async def cleanup(self) -> dict[str, Any]:- plan = await self.cleanup_preflight()- result = LegacyCleanupResult()- for target in plan.targets:- if not await self._exists(target.source_path):- skipped = target_to_dict(target)- skipped["reason"] = "missing"- result.skipped.append(skipped)- continue- vector_result = await self._delete_vectors(target)- result.vector_records += vector_result.deleted- result.warnings.extend(vector_result.warnings)- if vector_result.failed:- skipped = target_to_dict(target)- skipped["reason"] = "vector cleanup failed"- result.skipped.append(skipped)- continue- await self._agfs.rm(target.source_path, recursive=True)- result.removed.append(target_to_dict(target))- return result.to_dict()-- async def _registry_account_ids(self) -> set[str]:- return {- str(item.get("account_id", ""))- for item in await self._api_key_manager.list_accounts()- if item.get("account_id")- }-- async def _registry_user_ids(self, account_id: str) -> set[str]:- page = await self._api_key_manager.list_users_page(- account_id,- limit=1_000_000,- expose_key=False,- )- return {- str(item.get("user_id", ""))- for item in page["users"]- if item.get("user_id")- }-- async def _has_user(self, account_id: str, user_id: str) -> bool:- return await self._api_key_manager.has_user(account_id, user_id)-- async def _physical_account_ids(self) -> set[str]:- entries = await self._ls("/local")- return {- entry["name"] for entry in entries if entry["is_dir"] and entry["name"] != "_system"- }-- async def _physical_user_ids(self, account_id: str) -> set[str]:- entries = await self._ls(f"/local/{account_id}/user")- return {entry["name"] for entry in entries if entry["is_dir"]}-- 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):- if not entry["is_dir"]:- continue- source_path = f"{session_root}/{entry['name']}"- if await self._looks_like_session_dir(source_path):- await self._plan_one_session(- account_id,- session_id=entry["name"],- source_path=source_path,- owner_hint=None,- plan=plan,- )- continue- for nested in await self._ls(source_path):- if not nested["is_dir"]:- continue- nested_path = f"{source_path}/{nested['name']}"- if await self._looks_like_session_dir(nested_path):- await self._plan_one_session(- account_id,- session_id=nested["name"],- source_path=nested_path,- owner_hint=entry["name"],- plan=plan,- )-- async def _plan_one_session(- self,- account_id: str,- *,- session_id: str,- source_path: str,- owner_hint: str | None,- plan: MigrationPlan,- ) -> None:- owner = await self._session_owner(source_path)- if not owner and owner_hint:- owner = owner_hint- users = plan.account_users.setdefault(account_id, set())- if not owner and len(users) == 1:- owner = next(iter(users))- if not owner:- plan.errors.append(- {- "account_id": account_id,- "session_id": session_id,- "source": self._path_to_uri(account_id, source_path),- "reason": "session owner cannot be inferred in a multi-user account",- }- )- return- if validate_user_id(owner):- plan.errors.append(- {- "account_id": account_id,- "session_id": session_id,- "user_id": owner,- "reason": "session owner user_id is invalid",- }- )- return- await self._ensure_plan_user(account_id, owner, plan)- target_path = f"/local/{account_id}/user/{owner}/sessions/{session_id}"- plan.operations.append(- TreeCopy(- source_path=source_path,- target_path=target_path,- category="sessions",- )- )-- async def _session_owner(self, source_path: str) -> str:- data = await self._read_json_file(f"{source_path}/.meta.json")- if not isinstance(data, dict):- return ""- for key in (- "created_by_user_id",- "user_id",- "owner_user_id",- "created_by",- ):- value = data.get(key)- if isinstance(value, str) and value.strip():- return value.strip()- return ""-- async def _looks_like_session_dir(self, path: str) -> bool:- for leaf in (".meta.json", "messages.jsonl", "history", "tool-results", "tools"):- if await self._exists(f"{path}/{leaf}"):- return True- return False-- async def _ensure_plan_user(self, account_id: str, user_id: str, plan: MigrationPlan) -> bool:- if error := validate_user_id(user_id):- detail = {- "account_id": account_id,- "user_id": user_id,- "reason": f"user_id is invalid: {error}",- }- if detail not in plan.errors:- plan.errors.append(detail)- return False- users = plan.account_users.setdefault(account_id, set())- if user_id in users:- return True- users.add(user_id)- if not await self._has_user(account_id, user_id):- plan.created_users.add((account_id, user_id))- return True-- def _cleanup_target(- self,- account_id: str,- source_path: str,- category: str,- ) -> LegacyCleanupTarget:- return LegacyCleanupTarget(- account_id=account_id,- source_path=source_path,- source_uri=self._path_to_uri(account_id, source_path),- category=category,- )-- async def _copy_path(- self,- source_path: str,- target_path: str,- result: MigrationResult,- ) -> bool:- stat = await self._stat(source_path)- if not stat:- result.skipped.append(- {"type": "path", "source": source_path, "target": target_path, "reason": "missing"}- )- return False- if stat["is_dir"]:- copied = await self._mkdir_if_missing(target_path)- if copied:- result.directories += 1- for entry in await self._ls(source_path):- child_copied = await self._copy_path(- f"{source_path}/{entry['name']}",- f"{target_path}/{entry['name']}",- result,- )- copied = copied or child_copied- return copied- if await self._exists(target_path):- result.skipped.append(- {- "type": "file",- "source": source_path,- "target": target_path,- "reason": "target already exists; kept existing target",- }- )- return False- await self._ensure_parent_dirs(target_path)- await self._agfs.write(target_path, await self._agfs.read(source_path))- result.files += 1- return True-- async def _read_json_file(self, path: str) -> Any:- try:- raw = await self._agfs.read(path)- except Exception:- return None- if isinstance(raw, bytes):- text = raw.decode("utf-8")- elif hasattr(raw, "content"):- text = raw.content.decode("utf-8")- else:- text = str(raw)- try:- return json.loads(text)- except json.JSONDecodeError:- return None-- async def _delete_vectors(self, target: LegacyCleanupTarget) -> VectorMigrationResult:- vector_store = getattr(self._service, "vikingdb_manager", None)- return await delete_vector_records(- vector_store,- account_id=target.account_id,- uri=target.source_uri,- recursive=True,- )-- async def _ls(self, path: str) -> list[dict[str, Any]]:- try:- entries = await self._agfs.ls(path)- except Exception:- return []- normalized = []- for entry in entries:- name = entry.get("name", "")- if not name or name in {".", ".."}:- continue- normalized.append(- {- "name": name,- "is_dir": bool(entry.get("isDir", entry.get("is_dir", False))),- }- )- return normalized-- async def _stat(self, path: str) -> dict[str, Any] | None:- try:- stat = await self._agfs.stat(path)- except Exception:- return None- return {"is_dir": bool(stat.get("isDir", stat.get("is_dir", False)))}-- async def _exists(self, path: str) -> bool:- return await self._stat(path) is not None-- async def _mkdir_if_missing(self, path: str) -> bool:- if await self._exists(path):- return False- await self._ensure_parent_dirs(path)- try:- await self._agfs.mkdir(path)- return True- except Exception as exc:- if "exist" in str(exc).lower() or "already" in str(exc).lower():- return False- raise-- async def _ensure_parent_dirs(self, path: str) -> None:- parent = path.rsplit("/", 1)[0]- if not parent or parent == path:- return- parts = [part for part in parent.strip("/").split("/") if part]- current = ""- for part in parts:- current = f"{current}/{part}" if current else f"/{part}"- await self._mkdir_if_missing(current)-- def _path_to_uri(self, account_id: str, path: str) -> str:- prefix = f"/local/{account_id}/"- if path.startswith(prefix):- return "viking://" + path[len(prefix) :].strip("/")- return pathdiff --git a/openviking/storage/vector_migration.py b/openviking/storage/vector_migration.pyindex bf1e45389..1ad4fdc25 100644--- a/openviking/storage/vector_migration.py+++ b/openviking/storage/vector_migration.py@@ -1,10 +1,9 @@# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.# SPDX-License-Identifier: AGPL-3.0-"""Helpers for copying and deleting vector records during namespace migration."""+"""Helpers for transferring vector records when content is copied or moved."""from __future__ import annotations-from dataclasses import dataclass, fieldfrom typing import Any, Literalfrom openviking.core.namespace import (@@ -12,7 +11,7 @@ from openviking.core.namespace import (owner_fields_for_uri,owner_space_for_uri,)-from openviking.server.identity import RequestContext, Role+from openviking.server.identity import RequestContextfrom openviking.storage.abstract_overview import (rewrite_abstract_overview_for_transfer,rewrite_viking_uri_references,@@ -20,22 +19,8 @@ from openviking.storage.abstract_overview import (from openviking.storage.acl import ACL_CONTEXT_FIELDSfrom openviking.storage.expr import And, Contains, Eq, Or, PathScopefrom openviking.storage.vector_ids import vector_record_id-from openviking_cli.session.user_id import UserIdentifierfrom openviking_cli.utils.uri import VikingURI-_MAX_VECTOR_RECORDS_PER_SCOPE = 100_000---@dataclass-class VectorMigrationResult:- deleted: int = 0- failed: int = 0- warnings: list[str] = field(default_factory=list)---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(uri).uri.rstrip("/")@@ -130,77 +115,3 @@ def rewrite_vector_record(target_scope_uri=target_uri,)return payload---async def _records_in_scope(- vector_store: Any,- *,- account_id: str,- uri: str,- recursive: bool,-) -> list[dict[str, Any]]:- filters = [Eq("uri", uri)]- if recursive:- filters.append(PathScope("uri", uri, depth=-1))- if getattr(vector_store, "mode", None) == "volcengine":- parent = VikingURI(uri).parent- if parent is not None and parent.uri != "viking://":- filters.append(PathScope("uri", parent.uri, depth=1))- else:- filters.append(Contains("uri", uri + "#"))-- ctx = _root_ctx(account_id)- records = await vector_store.filter(- filter=And([Eq("account_id", account_id), Or(filters)]),- limit=_MAX_VECTOR_RECORDS_PER_SCOPE,- output_fields=["id", "uri"],- ctx=ctx,- )- return [- record- for record in records- if isinstance(record.get("uri"), str)- and uri_in_transfer_scope(record["uri"], uri, recursive=recursive)- ]---async def delete_vector_records(- vector_store: Any,- *,- account_id: str,- uri: str,- recursive: bool = True,-) -> VectorMigrationResult:- """Delete vector records for a legacy URI scope."""- result = VectorMigrationResult()- if (- not vector_store- or not hasattr(vector_store, "filter")- or not hasattr(vector_store, "delete")- ):- result.warnings.append(f"Skipped vector cleanup for {uri}: vector store is unavailable")- return result-- uri = uri.rstrip("/")- ctx = _root_ctx(account_id)- try:- records = await _records_in_scope(- vector_store,- account_id=account_id,- uri=uri,- recursive=recursive,- )- except Exception as exc:- result.failed += 1- result.warnings.append(f"Failed to read vectors for cleanup {uri}: {exc}")- return result-- ids = sorted({str(record["id"]) for record in records if record.get("id")})- if not ids:- return result- try:- result.deleted = int(await vector_store.delete(ids, ctx=ctx) or 0)- except Exception as exc:- result.failed += len(ids)- result.warnings.append(f"Failed to delete vectors for {uri}: {exc}")- return resultdiff --git a/sdk/go/README.md b/sdk/go/README.mdindex 0ee4ed1ac..de709f6e7 100644--- a/sdk/go/README.md+++ b/sdk/go/README.md@@ -174,7 +174,7 @@ Implemented:| Sessions and tasks | `CreateSession`, `ListSessions`, `GetSession`, `UpdateSessionConfig`, `SessionExists`, `GetSessionContext`, `GetSessionArchive`, `DeleteSession`, `AddMessage`, `BatchAddMessages`, `CommitSession`, `GetTask`, `ListTasks` || Packs | `ExportOVPack`, `BackupOVPack`, `ImportOVPack`, `RestoreOVPack` || System and observer | `Health`, `CheckConsistency`, `GetStatus`, `IsHealthy`, `QueueStatus`, `VikingDBStatus`, `ModelsStatus` |-| Admin | `AdminCreateAccount`, `AdminCreateAccountWithOptions`, `AdminListAccounts`, `AdminGetAccount`, `AdminDeleteAccount`, `AdminRegisterUser`, `AdminRegisterUserWithOptions`, `AdminListUsers`, `AdminGetUser`, `AdminRemoveUser`, `AdminSetRole`, `AdminRegenerateKey`, `AdminRegenerateKeyWithOptions`, `AdminMigrate` |+| Admin | `AdminCreateAccount`, `AdminCreateAccountWithOptions`, `AdminListAccounts`, `AdminGetAccount`, `AdminDeleteAccount`, `AdminRegisterUser`, `AdminRegisterUserWithOptions`, `AdminListUsers`, `AdminGetUser`, `AdminRemoveUser`, `AdminSetRole`, `AdminRegenerateKey`, `AdminRegenerateKeyWithOptions` |Not implemented in Go SDK v1:diff --git a/sdk/go/README_CN.md b/sdk/go/README_CN.mdindex bba7a0d3e..c105b00c3 100644--- a/sdk/go/README_CN.md+++ b/sdk/go/README_CN.md@@ -73,7 +73,7 @@ _, _, _ = imageResults, storedImageResults, similarPosters| 会话和任务 | `CreateSession`, `ListSessions`, `GetSession`, `UpdateSessionConfig`, `SessionExists`, `GetSessionContext`, `GetSessionArchive`, `DeleteSession`, `AddMessage`, `BatchAddMessages`, `CommitSession`, `GetTask`, `ListTasks` || OVPack | `ExportOVPack`, `BackupOVPack`, `ImportOVPack`, `RestoreOVPack` || 系统和 observer | `Health`, `CheckConsistency`, `GetStatus`, `IsHealthy`, `QueueStatus`, `VikingDBStatus`, `ModelsStatus` |-| 管理接口 | `AdminCreateAccount`, `AdminCreateAccountWithOptions`, `AdminListAccounts`, `AdminGetAccount`, `AdminDeleteAccount`, `AdminRegisterUser`, `AdminRegisterUserWithOptions`, `AdminListUsers`, `AdminGetUser`, `AdminRemoveUser`, `AdminSetRole`, `AdminRegenerateKey`, `AdminRegenerateKeyWithOptions`, `AdminMigrate` |+| 管理接口 | `AdminCreateAccount`, `AdminCreateAccountWithOptions`, `AdminListAccounts`, `AdminGetAccount`, `AdminDeleteAccount`, `AdminRegisterUser`, `AdminRegisterUserWithOptions`, `AdminListUsers`, `AdminGetUser`, `AdminRemoveUser`, `AdminSetRole`, `AdminRegenerateKey`, `AdminRegenerateKeyWithOptions` |## 暂未实现接口diff --git a/sdk/go/admin.go b/sdk/go/admin.goindex 3c5c56a33..c5baae678 100644--- a/sdk/go/admin.go+++ b/sdk/go/admin.go@@ -208,17 +208,6 @@ func (c *Client) AdminRemoveGroupMember(ctx context.Context, accountID, groupID,return result, err}-// AdminMigrate starts legacy data migration or cleanup.-func (c *Client) AdminMigrate(ctx context.Context, opts *AdminMigrateOptions) (map[string]any, error) {- action := "migrate"- if opts != nil && opts.Cleanup {- action = "cleanup"- }- var result map[string]any- err := c.doJSON(ctx, http.MethodPost, "/api/v1/admin/migrate", nil, map[string]any{"action": action}, &result)- return result, err-}-// AdminGetAgentEvolution returns the effective Agent Evolution switch for the// caller's account.func (c *Client) AdminGetAgentEvolution(ctx context.Context) (map[string]any, error) {diff --git a/sdk/go/types.go b/sdk/go/types.goindex 33d8c11bf..77ff6b61a 100644--- a/sdk/go/types.go+++ b/sdk/go/types.go@@ -521,11 +521,6 @@ type ImportPackOptions struct {VectorMode string}-// AdminMigrateOptions controls AdminMigrate.-type AdminMigrateOptions struct {- Cleanup bool-}-// FindResult is the structured retrieval response returned by Find and Search.type FindResult struct {Memories []MatchedContext `json:"memories,omitempty"`diff --git a/sdk/python/openviking_sdk/client.py b/sdk/python/openviking_sdk/client.pyindex 7c5882d01..23f29c280 100644--- a/sdk/python/openviking_sdk/client.py+++ b/sdk/python/openviking_sdk/client.py@@ -2198,11 +2198,6 @@ class AsyncHTTPClient:)return self._handle_response(response)- async def admin_migrate(self, cleanup: bool = False) -> Dict[str, Any]:- action = "cleanup" if cleanup else "migrate"- response = await self._request("POST", "/api/v1/admin/migrate", json={"action": action})- return self._handle_response(response)-async def admin_get_agent_evolution(self) -> Dict[str, Any]:"""Return the effective Agent Evolution switch for the caller's account."""response = await self._request("GET", "/api/v1/admin/agent-evolution")@@ -3324,9 +3319,6 @@ class SyncHTTPClient:self._async_client.admin_remove_group_member(account_id, group_id, user_id))- def admin_migrate(self, cleanup: bool = False) -> Dict[str, Any]:- return run_async(self._async_client.admin_migrate(cleanup=cleanup))-def admin_get_agent_evolution(self) -> Dict[str, Any]:return run_async(self._async_client.admin_get_agent_evolution())diff --git a/sdk/python/tests/test_async_client_behaviors.py b/sdk/python/tests/test_async_client_behaviors.pyindex 60d267037..d720759eb 100644--- a/sdk/python/tests/test_async_client_behaviors.py+++ b/sdk/python/tests/test_async_client_behaviors.py@@ -505,19 +505,6 @@ async def test_async_http_client_write_omits_default_processing_mode_for_legacy_assert "processing_mode" not in payload[email protected](("cleanup", "action"), [(False, "migrate"), (True, "cleanup")])-async def test_async_http_client_admin_migrate_posts_action_payload(cleanup, action):- client = AsyncHTTPClient(url="http://localhost:1933")- client._request = AsyncMock(return_value=object())- client._handle_response = lambda _response: {"status": "accepted"}-- assert await client.admin_migrate(cleanup=cleanup) == {"status": "accepted"}- client._request.assert_awaited_once_with(- "POST", "/api/v1/admin/migrate", json={"action": action}- )--def test_sync_http_client_reindex_forwards_to_async_client():client = SyncHTTPClient(url="http://localhost:1933")with patch.object(diff --git a/sdk/typescript/src/client.ts b/sdk/typescript/src/client.tsindex 37edc0863..a5af61544 100644--- a/sdk/typescript/src/client.ts+++ b/sdk/typescript/src/client.ts@@ -1343,12 +1343,6 @@ export class OpenVikingClient {{ body: seed === undefined ? undefined : { seed } },);}- /** Start legacy-data migration or cleanup. */- adminMigrate(cleanup = false): Promise<JsonObject> {- return this.request("POST", "/api/v1/admin/migrate", {- body: { action: cleanup ? "cleanup" : "migrate" },- });- }/** Return the effective Agent Evolution switch for the caller's account. */adminGetAgentEvolution(): Promise<JsonObject> {return this.request("GET", "/api/v1/admin/agent-evolution");diff --git a/tests/server/test_admin_api.py b/tests/server/test_admin_api.pyindex e063585f3..9e53e33d9 100644--- a/tests/server/test_admin_api.py+++ b/tests/server/test_admin_api.py@@ -291,15 +291,6 @@ async def _agfs_write(service: OpenVikingService, path: str, content: str) -> Noawait service.viking_fs._async_agfs.write(path, content.encode("utf-8"))-async def _agfs_read_text(service: OpenVikingService, path: str) -> str:- raw = await service.viking_fs._async_agfs.read(path)- if isinstance(raw, bytes):- return raw.decode("utf-8")- if hasattr(raw, "content"):- return raw.content.decode("utf-8")- return str(raw)--async def _wait_for_task(client: httpx.AsyncClient, task_id: str) -> dict:# Budget ~30s: recursive AGFS cleanup can take a couple of seconds, and the# original 1s budget was too tight on slower backends/interpreters.@@ -3513,146 +3504,31 @@ async def test_no_auth_admin_api_returns_401(admin_client: httpx.AsyncClient):assert resp.status_code == 401-# ---- Legacy migration -------async def test_user_role_cannot_run_legacy_migration(admin_client: httpx.AsyncClient):- """Legacy migration is ROOT-only."""- acct = _uid()- await admin_client.post(- "/api/v1/admin/accounts",- json={"account_id": acct, "admin_user_id": "alice"},- headers=root_headers(),- )- resp = await admin_client.post(- f"/api/v1/admin/accounts/{acct}/users",- json={"user_id": "bob", "role": "user"},- headers=root_headers(),- )- bob_key = resp.json()["result"]["user_key"]-- resp = await admin_client.post(- "/api/v1/admin/migrate",- headers={"X-API-Key": bob_key},- )- assert resp.status_code == 403---async def test_legacy_migration_preflight_failure_does_not_create_task(- admin_client: httpx.AsyncClient,- admin_service: OpenVikingService,+async def test_migration_endpoint_is_root_only_and_unsupported(+ lightweight_admin_app, lightweight_admin_client):- """Ambiguous session ownership fails preflight before task creation."""- 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(- f"/api/v1/admin/accounts/{acct}/users",- json={"user_id": "bob", "role": "user"},- headers=root_headers(),- )- await _agfs_write(admin_service, f"/local/{acct}/session/orphan/messages.jsonl", "{}\n")-- resp = await admin_client.post("/api/v1/admin/migrate", headers=root_headers())- assert resp.status_code == 412- error = resp.json()["error"]- assert error["code"] == "FAILED_PRECONDITION"- assert error["details"]["operation_count"] == 0- assert error["details"]["errors"][0]["session_id"] == "orphan"-- tasks_resp = await admin_client.get(- "/api/v1/tasks?task_type=legacy_migration",- headers=root_headers(),- )- assert tasks_resp.status_code == 200- assert tasks_resp.json()["result"] == []+ """The reserved endpoint rejects migration without relaxing ROOT authentication."""+ from openviking.server.auth import get_request_context+ url = "/api/v1/admin/migrate"+ response = await lightweight_admin_client.post(url)+ assert response.status_code == 401-async def test_legacy_migration_only_moves_sessions(- admin_client: httpx.AsyncClient,- admin_app,- admin_service: OpenVikingService,-):- """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(),- )- 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}/session/{session_id}/.meta.json",- json.dumps({"created_by_user_id": owner}),- )- await _agfs_write(- admin_service,- f"/local/{acct}/session/{session_id}/messages.jsonl",- '{"role":"user"}\n',- )+ for payload in (None, {"action": "migrate"}, {"action": "cleanup"}):+ response = await lightweight_admin_client.post(url, headers=root_headers(), json=payload)+ assert response.status_code == 400+ body = response.json()+ assert body["status"] == "error"+ assert body["error"]["code"] == "INVALID_ARGUMENT"+ assert body["error"]["message"] == "Data migration is not currently supported."+ assert body.get("result") is None- 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 result["migrated"]["operations"] == {"sessions": 2}- assert result["created_users"] == [{"account_id": acct, "user_id": "charlie"}]- assert await 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'+ for role in (Role.ADMIN, Role.USER):+ lightweight_admin_app.dependency_overrides[get_request_context] = lambda role=role: (+ RequestContext(user=UserIdentifier("default", "default"), role=role))- assert not await _agfs_exists(admin_service, f"/local/{acct}/user/{owner}/peers/workflows")---async def test_legacy_cleanup_preserves_public_agent_directories(- admin_client: httpx.AsyncClient,- admin_service: OpenVikingService,-):- """Session cleanup leaves public agent directories and user-owned data intact."""- acct = _uid()- await admin_client.post(- "/api/v1/admin/accounts",- json={"account_id": acct, "admin_user_id": "alice"},- headers=root_headers(),- )- 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",- json={"action": "cleanup"},- headers=root_headers(),- )- assert resp.status_code == 200- 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"]["targets"] == [- {"account_id": acct, "type": "session", "source": "viking://session"}- ]- assert not await _agfs_exists(admin_service, f"/local/{acct}/session")- for path in preserved_paths:- assert await _agfs_read_text(admin_service, path) == "preserved"+ response = await lightweight_admin_client.post(url)+ assert response.status_code == 403async def test_session_storage_uses_canonical_uri(diff --git a/tests/storage/test_vector_migration.py b/tests/storage/test_vector_migration.pyindex 508bb0bfe..3943b6cb5 100644--- a/tests/storage/test_vector_migration.py+++ b/tests/storage/test_vector_migration.py@@ -6,7 +6,6 @@ import pytestfrom openviking.server.identity import RequestContext, Rolefrom openviking.storage import vector_migrationfrom openviking.storage.abstract_overview import parse_abstract_overview-from openviking.storage.vector_migration import delete_vector_recordsfrom openviking_cli.session.user_id import UserIdentifier@@ -127,51 +126,3 @@ directory: viking://resources/业务域/content_doc = parse_abstract_overview(result["content"])assert content_doc.metadata["directory"] == "viking://resources/归档域/"assert content_doc.body.strip() == "[chapter](viking://resources/归档域/章节.md)"---class FakeVectorStore:- def __init__(self, records):- self.records = [dict(record) for record in records]- self.deleted_ids = []-- async def filter(self, **_kwargs):- return [dict(record) for record in self.records]-- async def delete(self, ids, *, ctx):- self.deleted_ids.extend(ids)- return len(ids)---async def test_delete_vector_records_deletes_records_in_scope_only():- store = FakeVectorStore(- [- {- "id": "old-dir",- "uri": "viking://session",- "account_id": "acct",- "vector": [0.1, 0.2],- },- {- "id": "old-file",- "uri": "viking://session/s1/messages.jsonl",- "account_id": "acct",- "vector": [0.3, 0.4],- },- {- "id": "new-file",- "uri": "viking://user/alice/sessions/s1/messages.jsonl",- "account_id": "acct",- "vector": [0.5, 0.6],- },- ]- )-- result = await delete_vector_records(- store,- account_id="acct",- uri="viking://session",- )-- assert result.deleted == 2- assert store.deleted_ids == ["old-dir", "old-file"]diff --git a/tests/test_task_tracker.py b/tests/test_task_tracker.pyindex 1d724a4ce..5f267ddf5 100644--- a/tests/test_task_tracker.py+++ b/tests/test_task_tracker.py@@ -443,7 +443,7 @@ async def test_complete_task_updates_resource_id(tracker: TaskTracker):async def test_task_result_redacts_user_key(tracker: TaskTracker):- task = await tracker.create("legacy_migration", **_owner_kwargs())+ task = await tracker.create("admin_reindex", **_owner_kwargs())await tracker.complete(task.task_id,{diff --git a/web-studio/src/i18n/locales/en/workspace.ts b/web-studio/src/i18n/locales/en/workspace.tsindex 0c893d116..f73f1ec72 100644--- a/web-studio/src/i18n/locales/en/workspace.ts+++ b/web-studio/src/i18n/locales/en/workspace.ts@@ -588,8 +588,6 @@ const workspace = {connector_import: 'Connector import',admin_reindex: 'Reindex',snapshot_restore_reindex: 'Snapshot reindex',- legacy_migration: 'Legacy migration',- legacy_cleanup: 'Legacy cleanup',},},watchesPage: {diff --git a/web-studio/src/i18n/locales/zh-CN/workspace.ts b/web-studio/src/i18n/locales/zh-CN/workspace.tsindex df7672a74..f745bb953 100644--- a/web-studio/src/i18n/locales/zh-CN/workspace.ts+++ b/web-studio/src/i18n/locales/zh-CN/workspace.ts@@ -568,8 +568,6 @@ const workspace = {connector_import: '连接器导入',admin_reindex: '重建索引',snapshot_restore_reindex: '快照恢复索引',- legacy_migration: '旧数据迁移',- legacy_cleanup: '旧数据清理',},},watchesPage: {diff --git a/web-studio/src/routes/tasks/-lib/task-list.ts b/web-studio/src/routes/tasks/-lib/task-list.tsindex ab501627b..cedfeda4c 100644--- a/web-studio/src/routes/tasks/-lib/task-list.ts+++ b/web-studio/src/routes/tasks/-lib/task-list.ts@@ -10,8 +10,6 @@ export type TaskTypeFilter =| 'add_skill'| 'admin_reindex'| 'connector_import'- | 'legacy_cleanup'- | 'legacy_migration'| 'session_commit'| 'snapshot_restore_reindex'| 'all'diff --git a/web-studio/src/routes/tasks/route.tsx b/web-studio/src/routes/tasks/route.tsxindex 2aad6480e..805c49e63 100644--- a/web-studio/src/routes/tasks/route.tsx+++ b/web-studio/src/routes/tasks/route.tsx@@ -76,8 +76,6 @@ const TASK_TYPE_OPTIONS: Exclude<TaskTypeFilter, 'all'>[] = ['connector_import','admin_reindex','snapshot_restore_reindex',- 'legacy_migration',- 'legacy_cleanup',]const TASK_STATUS_OPTIONS: Exclude<TaskStatusFilter, 'all'>[] = ['pending',@@ -510,8 +508,6 @@ function TasksRoute() {'snapshot_restore_reindex','add_skill','connector_import',- 'legacy_migration',- 'legacy_cleanup',]const typeCounts: Record<string, number> = {}