From 5536898634d3bc40103c304e7a566d15382a4c01 Mon Sep 17 00:00:00 2001 From: qin-ctx Date: Wed, 21 Oct 2026 11:21:46 +0800 Subject: [PATCH 1/6] =?UTF-8?q?fix(storage):=20=E5=8D=87=E7=BA=A7=E5=90=8E?= =?UTF-8?q?=E7=BB=A7=E7=BB=AD=E9=9A=90=E8=97=8F=E6=97=A7=E7=89=88=E5=A4=9A?= =?UTF-8?q?=E5=86=99=E5=85=83=E6=95=B0=E6=8D=AE?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit (cherry picked from commit 2bef4c2c31f04b191b7f3d01d0ed5a37b4fb8d9e) (cherry picked from commit 236e3c46d5f43f1e3bdcc7019ad3374fdca56158) Co-authored-by: TRAE CLI --- crates/ragfs/src/core/internal_names.rs | 5 +++-- crates/ragfs/src/core/mountable.rs | 13 +++++++++++++ 2 files changed, 16 insertions(+), 2 deletions(-) diff --git a/crates/ragfs/src/core/internal_names.rs b/crates/ragfs/src/core/internal_names.rs index f73ddd27d79..557bef882ee 100644 --- a/crates/ragfs/src/core/internal_names.rs +++ b/crates/ragfs/src/core/internal_names.rs @@ -15,9 +15,10 @@ pub fn is_hidden_runtime_lock_name(name: &str) -> bool { name == PATH_LOCK_FILE || name.starts_with(EXACT_LOCK_FILE_PREFIX) } -/// Returns `true` when `name` is a hidden runtime lock name. +/// Returns `true` for runtime locks and metadata left by V1 multi-write storage. pub fn is_hidden_internal_name(name: &str) -> bool { - is_hidden_runtime_lock_name(name) + // V1 metadata can remain during and after migration; never expose it as user data. + is_hidden_runtime_lock_name(name) || matches!(name, ".redirect.json" | ".sync_log.json") } /// Returns `true` when a logical path belongs to V2 multi-write internals. diff --git a/crates/ragfs/src/core/mountable.rs b/crates/ragfs/src/core/mountable.rs index e1fb696e14c..a452e4e10c8 100644 --- a/crates/ragfs/src/core/mountable.rs +++ b/crates/ragfs/src/core/mountable.rs @@ -2155,6 +2155,8 @@ mod tests { make_tree_entry("/c", "c", "c", true), make_tree_entry("/B", "B", "B", true), make_tree_entry("/.path.ovlock", ".path.ovlock", ".path.ovlock", false), + make_tree_entry("/.sync_log.json", ".sync_log.json", ".sync_log.json", false), + make_tree_entry("/.redirect.json", ".redirect.json", ".redirect.json", false), ], ); mfs.register_plugin(plugin).await; @@ -2170,6 +2172,17 @@ mod tests { assert_eq!(names, vec!["B", "c", "A.txt", "b.txt"]); + // Upgrade leftovers remain available for migration, but not to business callers. + let internal_names: Vec = mfs + .read_internal_dir("/sorted") + .await + .unwrap() + .into_iter() + .map(|entry| entry.name) + .collect(); + assert!(internal_names.iter().any(|name| name == ".sync_log.json")); + assert!(internal_names.iter().any(|name| name == ".redirect.json")); + let page: Vec = mfs .read_dir( "/sorted", From d58617016bdd91041eba174a399c015548ba597d Mon Sep 17 00:00:00 2001 From: baojun-zhang Date: Mon, 26 Oct 2026 14:59:08 +0800 Subject: [PATCH 2/6] fix(ragfs): backport multiwrite hotfixes to v0.5.0 (#6607) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * fix(ragfs): 在外部租约下跳过冗余加密锁 (cherry picked from commit 002b27fac4ce3e70fecd392ea0ace7217f48915d) * fix(multiwrite): 取消删除 v1 元数据时 glob 操作,在 import account 阶段进行删除 && 增加迁移阶段执行进度日志 (cherry picked from commit 42d99d8e7ffcce2d1fbadb60bcf34f414676c26f) (cherry picked from commit d8dd90d90d9fcca6df36ef8ba46a91b3ff2b72bd) Co-authored-by: TRAE CLI From b79897947bd66e071c90bc27092c9340913e8664 Mon Sep 17 00:00:00 2001 From: baojun-zhang Date: Mon, 26 Oct 2026 18:19:38 +0800 Subject: [PATCH 3/6] feat(ragfs): gate existing data reconciliation (#6618) Add a multi-write backup option to control whether startup scans pre-existing primary files into V2 metadata. Document the default disabled behavior and the conditions where historical backfill can be skipped. (cherry picked from commit 56e8bea092579c36ab3ad5c87f31a9d0f00b8f58) (cherry picked from commit ae29842fe80db93c2bec956f05647a54b46c604c) Co-authored-by: TRAE CLI --- crates/ragfs/src/core/mountable.rs | 1 + crates/ragfs/src/core/multibackend_wrapper.rs | 9 +++++++++ crates/ragfs/src/core/types.rs | 3 +++ crates/ragfs/src/git/service.rs | 1 + crates/ragfs/src/multibackend/factory.rs | 1 + crates/ragfs/src/multibackend/migration/mod.rs | 18 +++++++++++++++--- docs/en/concepts/14-multi-write-storage.md | 15 ++++++++++----- docs/en/guides/01-configuration.md | 2 ++ docs/en/guides/13-multi-write-storage.md | 13 ++++++++++--- docs/zh/concepts/14-multi-write-storage.md | 13 +++++++++---- docs/zh/guides/01-configuration.md | 2 ++ docs/zh/guides/13-multi-write-storage.md | 13 ++++++++++--- examples/ov.conf.example | 1 + 13 files changed, 74 insertions(+), 18 deletions(-) diff --git a/crates/ragfs/src/core/mountable.rs b/crates/ragfs/src/core/mountable.rs index a452e4e10c8..c39c75cc667 100644 --- a/crates/ragfs/src/core/mountable.rs +++ b/crates/ragfs/src/core/mountable.rs @@ -1254,6 +1254,7 @@ mod tests { service_name: "mw-test".to_string(), initial_partitions: 16, checkpoint_interval_secs: 86_400, + reconcile_existing_data: false, provider: "filesystem".to_string(), items: vec![BackendItemConfig { name: "backup1".to_string(), diff --git a/crates/ragfs/src/core/multibackend_wrapper.rs b/crates/ragfs/src/core/multibackend_wrapper.rs index 8d5553a378b..6e0addebffe 100644 --- a/crates/ragfs/src/core/multibackend_wrapper.rs +++ b/crates/ragfs/src/core/multibackend_wrapper.rs @@ -67,6 +67,7 @@ pub struct MultiWriteWrappedFSBuilder { metadata_provider: Option>, initial_partitions: u32, checkpoint_interval: Duration, + reconcile_existing_data: bool, ctx_resolver: Arc, } @@ -110,6 +111,12 @@ impl MultiWriteWrappedFSBuilder { self } + /// Set whether startup should reconcile existing primary data into V2 metadata. + pub fn reconcile_existing_data(mut self, reconcile_existing_data: bool) -> Self { + self.reconcile_existing_data = reconcile_existing_data; + self + } + /// Configure the resolver for mount-relative foreground paths. pub fn ctx_resolver(mut self, ctx_resolver: Arc) -> Self { self.ctx_resolver = ctx_resolver; @@ -210,6 +217,7 @@ impl MultiWriteWrappedFSBuilder { metadata_provider, self.initial_partitions, backup_names, + self.reconcile_existing_data, ); fs.inner.runtime.set_import_worker(async move { let result = importer.run().await; @@ -234,6 +242,7 @@ impl MultiWriteWrappedFS { metadata_provider: None, initial_partitions: 16, checkpoint_interval: Duration::from_secs(86_400), + reconcile_existing_data: false, ctx_resolver: Arc::new(DefaultFsContextResolver), } } diff --git a/crates/ragfs/src/core/types.rs b/crates/ragfs/src/core/types.rs index 9056b334c67..819189d6987 100644 --- a/crates/ragfs/src/core/types.rs +++ b/crates/ragfs/src/core/types.rs @@ -568,6 +568,9 @@ pub struct BackendsConfig { /// Checkpoint interval in seconds. #[serde(default = "default_checkpoint_interval_secs")] pub checkpoint_interval_secs: u64, + /// Whether to scan existing primary data and reconcile it into V2 metadata. + #[serde(default)] + pub reconcile_existing_data: bool, /// Metadata storage provider. #[serde(default = "default_backups_provider")] pub provider: String, diff --git a/crates/ragfs/src/git/service.rs b/crates/ragfs/src/git/service.rs index 92db4ecd01e..e34b97483b8 100644 --- a/crates/ragfs/src/git/service.rs +++ b/crates/ragfs/src/git/service.rs @@ -6663,6 +6663,7 @@ mod fast_path1_tests { service_name: "mw-test".to_string(), initial_partitions: 16, checkpoint_interval_secs: 86_400, + reconcile_existing_data: false, provider: "filesystem".to_string(), items: vec![BackendItemConfig { name: "backup1".to_string(), diff --git a/crates/ragfs/src/multibackend/factory.rs b/crates/ragfs/src/multibackend/factory.rs index 5bf37e7f106..1588642d6b3 100644 --- a/crates/ragfs/src/multibackend/factory.rs +++ b/crates/ragfs/src/multibackend/factory.rs @@ -188,6 +188,7 @@ pub(crate) async fn build_inactive_multi_write_fs( .with_backups(backup_entries) .initial_partitions(bc.initial_partitions) .checkpoint_interval(Duration::from_secs(bc.checkpoint_interval_secs)) + .reconcile_existing_data(bc.reconcile_existing_data) .ctx_resolver(Arc::new(RelativePathFsContextResolver)) .build_inactive() .await diff --git a/crates/ragfs/src/multibackend/migration/mod.rs b/crates/ragfs/src/multibackend/migration/mod.rs index 1789f4600e6..9aff6ee8d7a 100644 --- a/crates/ragfs/src/multibackend/migration/mod.rs +++ b/crates/ragfs/src/multibackend/migration/mod.rs @@ -59,6 +59,7 @@ pub struct FullDataImporter { provider: Arc, initial_partitions: u32, backup_names: Vec, + reconcile_existing_data: bool, } impl FullDataImporter { @@ -69,6 +70,7 @@ impl FullDataImporter { provider: Arc, initial_partitions: u32, backup_names: Vec, + reconcile_existing_data: bool, ) -> Self { Self { primary, @@ -76,6 +78,7 @@ impl FullDataImporter { provider, initial_partitions, backup_names, + reconcile_existing_data, } } @@ -94,7 +97,8 @@ impl FullDataImporter { .into_iter() .collect::>(); accounts.sort(); - self.import_scope(SYSTEM_DIR).await?; + self.import_scope(SYSTEM_DIR, self.reconcile_existing_data) + .await?; for account in &accounts { if !read_active_accounts(self.primary.as_ref()) .await? @@ -102,7 +106,8 @@ impl FullDataImporter { { continue; } - self.import_scope(account).await?; + self.import_scope(account, self.reconcile_existing_data) + .await?; } self.cleanup_v1_global_metadata().await?; @@ -129,7 +134,7 @@ impl FullDataImporter { } /// Initialize one V2 scope and import its current file states. - async fn import_scope(&self, account: &str) -> Result<()> { + async fn import_scope(&self, account: &str, reconcile_existing_data: bool) -> Result<()> { let partitions = self .store .initialize_account(account, self.initial_partitions, &self.backup_names) @@ -141,6 +146,13 @@ impl FullDataImporter { &partitions, ) .await?; + if !reconcile_existing_data { + tracing::info!( + account = %account, + "multi-write existing data reconciliation skipped" + ); + return Ok(()); + } let context = Arc::new(FsContextInner::new(account).with_auto_pathlock_disabled()); FS_CTX.scope(context, self.import_account(account)).await } diff --git a/docs/en/concepts/14-multi-write-storage.md b/docs/en/concepts/14-multi-write-storage.md index 356cab111c5..1bd5ef13e0f 100644 --- a/docs/en/concepts/14-multi-write-storage.md +++ b/docs/en/concepts/14-multi-write-storage.md @@ -27,12 +27,17 @@ created. Existing accounts keep their persisted partition count and routes when the configuration changes. Partition expansion and shrinking are not supported in this release. -## First Enable Import +## First Enable -When `.multiwrite.json` is absent, startup creates it as `V2/migrating`, -starts foreground V2 event submission, and imports the current primary files -in the background. Successful import changes the status to `stable`. Extra -old files on backups are not removed. +When `.multiwrite.json` is absent, startup creates it as `V2/migrating` and +starts foreground V2 event submission. If `reconcile_existing_data=true`, +startup scans current primary files and records them in V2 metadata. After +initialization and optional reconciliation succeed, the status changes to +`stable`. Extra old files on backups are not removed. + +With the default `reconcile_existing_data=false`, pre-existing primary files are +not recorded as V2 write events. Use it only when backups are already aligned or +historical backfill is intentionally skipped. Old multi-write protocols and old migration fields are rejected. They are not converted or interpreted. diff --git a/docs/en/guides/01-configuration.md b/docs/en/guides/01-configuration.md index e23bd6ee46d..9dc9e3616b8 100644 --- a/docs/en/guides/01-configuration.md +++ b/docs/en/guides/01-configuration.md @@ -1378,6 +1378,7 @@ top-level backend remains the only direct read source. "backups": { "initial_partitions": 16, "checkpoint_interval_secs": 86400, + "reconcile_existing_data": false, "provider": "filesystem", "items": [ { @@ -1400,6 +1401,7 @@ Common `backups` fields: |-----------|------|-------------|---------| | `initial_partitions` | int | Initial metadata partitions; changes do not affect existing accounts | `16` | | `checkpoint_interval_secs` | int | Checkpoint discovery interval; minimum `60` | `86400` | +| `reconcile_existing_data` | bool | Scan primary files that already exist when multi-write is first enabled and record them in V2 metadata. Keep `false` only when backups are already aligned or historical backfill is intentionally skipped. | `false` | | `provider` | str | Metadata provider: `filesystem` or top-level CacheRuntime-backed `cache` | `"filesystem"` | | `items` | array | Backups with `name`, `backend`, `params`, and optional `encryption` | `[]` | diff --git a/docs/en/guides/13-multi-write-storage.md b/docs/en/guides/13-multi-write-storage.md index 4a30c18abfa..24e159478a8 100644 --- a/docs/en/guides/13-multi-write-storage.md +++ b/docs/en/guides/13-multi-write-storage.md @@ -14,6 +14,7 @@ backups asynchronously. The primary is the only direct read source. "backups": { "initial_partitions": 16, "checkpoint_interval_secs": 86400, + "reconcile_existing_data": false, "provider": "filesystem", "items": [ { @@ -30,12 +31,13 @@ backups asynchronously. The primary is the only direct read source. } ``` -The three top-level V2 settings are: +The top-level V2 settings are: | Field | Default | Meaning | | --- | --- | --- | | `initial_partitions` | `16` | Metadata partitions created for an account | | `checkpoint_interval_secs` | `86400` | Checkpoint discovery interval; minimum `60` | +| `reconcile_existing_data` | `false` | Scan existing primary files and record them in V2 metadata | | `provider` | `"filesystem"` | Metadata segment provider: `filesystem` or `cache` | Each `items[]` entry needs `name`, `backend`, and backend-specific `params`. @@ -71,8 +73,13 @@ supported in this release. ## First Enable And Rollback When `.multiwrite.json` is absent, the mount starts foreground V2 event -submission and imports current primary files in the background. Extra old -files on backups are not removed. +submission and initializes V2 metadata. If `reconcile_existing_data=true`, +startup also scans current primary files and records them in V2 metadata. Extra +old files on backups are not removed. + +With the default `reconcile_existing_data=false`, files that already existed on +the primary are not recorded as V2 write events. Use this only when backups are +already aligned with the primary or historical backfill is intentionally skipped. Old multi-write protocols and old migration fields are rejected. Take a complete backup before enabling multi-write. Restore that backup before diff --git a/docs/zh/concepts/14-multi-write-storage.md b/docs/zh/concepts/14-multi-write-storage.md index d7d0dbdc3a1..a72525a886c 100644 --- a/docs/zh/concepts/14-multi-write-storage.md +++ b/docs/zh/concepts/14-multi-write-storage.md @@ -23,11 +23,16 @@ V2 多写以一个 primary backend 作为业务真相,并把文件复制到配 已有 account 始终使用持久化的 partition 数量和 routes,修改配置不会改变 现有布局。本期不支持扩容或缩容。 -## 首次启用导入 +## 首次启用 -`.multiwrite.json` 不存在时,启动流程创建 `V2/migrating` 状态,先启用前台 -V2 事件提交,再在后台导入 primary 当前文件。导入成功后切换为 `stable`。 -导入不会删除 backup 中多余的旧文件。 +`.multiwrite.json` 不存在时,启动流程创建 `V2/migrating` 状态,并启用前台 +V2 事件提交。若 `reconcile_existing_data=true`,启动流程会扫描 primary 当前文件 +并写入 V2 metadata。初始化和可选对账成功后,状态切换为 `stable`。该流程 +不会删除 backup 中多余的旧文件。 + +默认 `reconcile_existing_data=false` 时,primary 上启用前已存在的文件不会作为 +V2 write event 记录。只有在 backup 已与 primary 对齐,或明确跳过历史回填时 +才保持默认值。 旧多写协议和旧迁移字段直接拒绝,不执行转换或解释。 diff --git a/docs/zh/guides/01-configuration.md b/docs/zh/guides/01-configuration.md index 9223b45e705..6774346d2c5 100644 --- a/docs/zh/guides/01-configuration.md +++ b/docs/zh/guides/01-configuration.md @@ -1365,6 +1365,7 @@ RAGFS 默认使用 Rust binding 模式,通过 Rust 实现直接访问文件系 "backups": { "initial_partitions": 16, "checkpoint_interval_secs": 86400, + "reconcile_existing_data": false, "provider": "filesystem", "items": [ { @@ -1387,6 +1388,7 @@ RAGFS 默认使用 Rust binding 模式,通过 Rust 实现直接访问文件系 |------|------|------|--------| | `initial_partitions` | int | account 首次初始化的 metadata partition 数;修改不影响已有 account | `16` | | `checkpoint_interval_secs` | int | Checkpoint 扫描间隔,最小值为 `60` | `86400` | +| `reconcile_existing_data` | bool | 首次启用多写时,扫描 primary 已存在文件并写入 V2 metadata。仅在 backup 已对齐或明确跳过历史回填时保持 `false`。 | `false` | | `provider` | str | Metadata provider:`filesystem` 或复用顶层 CacheRuntime 的 `cache` | `"filesystem"` | | `items` | array | backup 列表,包含 `name`、`backend`、`params` 和可选 `encryption` | `[]` | diff --git a/docs/zh/guides/13-multi-write-storage.md b/docs/zh/guides/13-multi-write-storage.md index 3211082dbc8..82d1abc4d60 100644 --- a/docs/zh/guides/13-multi-write-storage.md +++ b/docs/zh/guides/13-multi-write-storage.md @@ -14,6 +14,7 @@ V2 多写在 primary 成功后返回,metadata 和 backup 在后台异步更新 "backups": { "initial_partitions": 16, "checkpoint_interval_secs": 86400, + "reconcile_existing_data": false, "provider": "filesystem", "items": [ { @@ -30,12 +31,13 @@ V2 多写在 primary 成功后返回,metadata 和 backup 在后台异步更新 } ``` -V2 的三个顶层配置是: +V2 的顶层配置是: | 字段 | 默认值 | 含义 | | --- | --- | --- | | `initial_partitions` | `16` | 为 account 创建的 metadata partition 数量 | | `checkpoint_interval_secs` | `86400` | Checkpoint 扫描间隔,最小值为 `60` | +| `reconcile_existing_data` | `false` | 扫描 primary 已存在文件并写入 V2 metadata | | `provider` | `"filesystem"` | Metadata segment provider:`filesystem` 或 `cache` | 每个 `items[]` 需要 `name`、`backend` 和 backend 专用 `params`。 @@ -66,8 +68,13 @@ redirects 字段,输出 warning 后会在调用 Rust 前删除,字段不生 ## 首次启用与回滚 -`.multiwrite.json` 不存在时,mount 先启用前台 V2 事件提交,再在后台导入 -primary 当前文件。导入不会删除 backup 中多余的旧文件。 +`.multiwrite.json` 不存在时,mount 先启用前台 V2 事件提交,并初始化 V2 +metadata。若 `reconcile_existing_data=true`,启动流程还会扫描 primary 当前文件 +并写入 V2 metadata。该流程不会删除 backup 中多余的旧文件。 + +默认 `reconcile_existing_data=false` 时,primary 上启用前已存在的文件不会作为 +V2 write event 记录。只有在 backup 已与 primary 对齐,或明确跳过历史回填时 +才保持默认值。 旧多写协议和旧迁移字段直接拒绝。启用多写前必须创建完整备份;回滚二进制 前必须先恢复该备份。 diff --git a/examples/ov.conf.example b/examples/ov.conf.example index 594b69ee6e2..4a2759e4d27 100644 --- a/examples/ov.conf.example +++ b/examples/ov.conf.example @@ -82,6 +82,7 @@ "_comment": "Rename this key to backups to enable V2 multi-write.", "initial_partitions": 16, "checkpoint_interval_secs": 86400, + "reconcile_existing_data": false, "provider": "cache", "items": [{ "name": "local-backup", From aebeb95d8d22b20a484fae0bc50a368c4eaeaf15 Mon Sep 17 00:00:00 2001 From: Qin Haojie Date: Mon, 26 Oct 2026 22:21:38 +0800 Subject: [PATCH 4/6] =?UTF-8?q?perf(admin):=20=E7=94=A8=E6=88=B7=E5=88=97?= =?UTF-8?q?=E8=A1=A8=E7=9B=B4=E6=8E=A5=E8=AF=BB=E5=8F=96=E5=86=85=E5=AD=98?= =?UTF-8?q?=20(#6629)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit (cherry picked from commit 5e45a875d613e796fbf9e487aec40fcc53f49469) Co-authored-by: TRAE CLI --- docs/en/api/08-admin.md | 2 + docs/zh/api/08-admin.md | 2 + openviking/server/api_keys/legacy.py | 2 - tests/server/test_admin_api.py | 71 ++++++++++++++++++++++++++++ 4 files changed, 75 insertions(+), 2 deletions(-) diff --git a/docs/en/api/08-admin.md b/docs/en/api/08-admin.md index df6bb6503af..2d11260ebfb 100644 --- a/docs/en/api/08-admin.md +++ b/docs/en/api/08-admin.md @@ -1528,6 +1528,8 @@ ov admin register-user acme bob-private --role user \ List active users in a workspace. Users with deletion in progress are omitted. +With the file account store, both HTTP and MCP `list_users` read the current process's in-memory user registry without refreshing files during the query. User changes completed in this process are immediately visible; changes from other processes become visible after the background watcher synchronizes them or the registry is reloaded. The `redis_mysql` account store continues to list users from MySQL. + **Processing Flow:** 1. Verify requester has ROOT privileges or is an ADMIN of the account 2. Call API Key Manager to get active users list (in creation order) diff --git a/docs/zh/api/08-admin.md b/docs/zh/api/08-admin.md index 9ccea777f7e..1ae511a6ef5 100644 --- a/docs/zh/api/08-admin.md +++ b/docs/zh/api/08-admin.md @@ -1394,6 +1394,8 @@ ov admin register-user acme bob-private --role user \ 列出工作区中的活跃用户。正在删除中的用户不会返回。 +使用 file 账户存储时,HTTP 和 MCP 的 `list_users` 都直接读取当前进程的内存用户登记信息,查询时不刷新文件。本进程完成的用户修改立即可见;其他进程的修改在后台 watcher 同步或登记信息重新加载后可见。`redis_mysql` 账户存储继续从 MySQL 查询用户列表。 + **处理流程:** 1. 验证请求者具有 ROOT 权限,或为本账户的 ADMIN 2. 调用 API Key Manager 获取活跃用户列表(按创建顺序排列) diff --git a/openviking/server/api_keys/legacy.py b/openviking/server/api_keys/legacy.py index 112b844fc09..3e93261d54d 100644 --- a/openviking/server/api_keys/legacy.py +++ b/openviking/server/api_keys/legacy.py @@ -1559,8 +1559,6 @@ async def list_users_page( async with self._mutation_lock: async with self._reload_lock: await self._refresh_account_users_from_store_unlocked(account_id) - else: - await self._refresh_users_for_management_read(account_id) return self._get_users_page( account_id, limit=limit, diff --git a/tests/server/test_admin_api.py b/tests/server/test_admin_api.py index c1e9be463b3..61f54213bda 100644 --- a/tests/server/test_admin_api.py +++ b/tests/server/test_admin_api.py @@ -2350,6 +2350,77 @@ async def test_list_accounts(admin_client: httpx.AsyncClient): assert "default" not in queried_ids +async def test_list_accounts_without_watcher_reads_only_accounts_registry( + lightweight_admin_client: httpx.AsyncClient, + lightweight_admin_app: FastAPI, + monkeypatch: pytest.MonkeyPatch, +): + """Without a watcher, account listing must not load user registries.""" + manager = lightweight_admin_app.state.api_key_manager + original_read_json = manager._store._read_json + read_paths: list[str] = [] + + async def _record_read(path: str): + read_paths.append(path) + return await original_read_json(path) + + monkeypatch.setattr(manager._store, "_read_json", _record_read) + + resp = await lightweight_admin_client.get( + "/api/v1/admin/accounts?limit=5&page=1", headers=root_headers() + ) + + assert resp.status_code == 200, resp.text + assert read_paths == ["/local/_system/accounts.json"] + + +async def test_list_users_reads_memory_without_storage( + lightweight_admin_client: httpx.AsyncClient, + lightweight_admin_app: FastAPI, + monkeypatch: pytest.MonkeyPatch, +): + """HTTP and MCP list locally registered users even when storage is unavailable.""" + from types import SimpleNamespace + + from openviking.server import mcp_endpoint + + acct = _uid() + await lightweight_admin_client.post( + "/api/v1/admin/accounts", + json={"account_id": acct, "admin_user_id": "alice"}, + headers=root_headers(), + ) + created = await lightweight_admin_client.post( + f"/api/v1/admin/accounts/{acct}/users", + json={"user_id": "bob", "role": "user"}, + headers=root_headers(), + ) + assert created.status_code == 200, created.text + monkeypatch.setattr( + lightweight_admin_app.state.fake_service.viking_fs.agfs, + "read", + Mock(side_effect=OSError("registry storage unavailable")), + ) + + resp = await lightweight_admin_client.get( + f"/api/v1/admin/accounts/{acct}/users", headers=root_headers() + ) + + assert resp.status_code == 200, resp.text + assert [user["user_id"] for user in resp.json()["result"]] == ["alice", "bob"] + + request = FastAPIRequest({"type": "http", "app": lightweight_admin_app}) + context = SimpleNamespace(request_context=SimpleNamespace(request=request)) + token = mcp_endpoint._mcp_ctx.set(RequestContext(UserIdentifier(acct, "alice"), Role.ADMIN)) + try: + assert await mcp_endpoint.list_users(context) == { + "users": [{"user_id": "alice"}, {"user_id": "bob"}], + "total": 2, + } + finally: + mcp_endpoint._mcp_ctx.reset(token) + + async def test_list_users_for_default_account_without_users_file_returns_empty_list( lightweight_admin_client: httpx.AsyncClient, ): From 45ddd62f28cc35fd035f5420eea18fc8b44d74c3 Mon Sep 17 00:00:00 2001 From: baojun-zhang Date: Mon, 26 Oct 2026 23:39:53 +0800 Subject: [PATCH 5/6] fix(storage): backport PathLock sidecar protocol to v0.5.0 (#6632) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * fix(storage): 修复递归删除导致 PathLock 提前失效 将目录锁迁移到父目录 sidecar,并兼容旧锁与 handoff;删除获锁后重新确认目标状态,避免并发请求沿用过期判断。 (cherry picked from commit 014bd7c8396d15906d5e4dcc28a8575090d45b42) * test(storage): 补充 PathLock 路径关系矩阵 使用共享文件系统上的独立 Manager 验证祖先、后代与兄弟路径的冲突和非冲突语义,防止 sidecar 迁移引入锁范围回归。 (cherry picked from commit c60e67a2b341d948aeb53987172a4cf8e5e96f02) * fix(storage): 收敛 PathLock sidecar 迁移协议 拆分 Tree 路径解析并修正根路径寻址,撤回无关的 Snapshot 行为变化,同时明确新旧锁协议的切换约束,降低迁移影响范围。 (cherry picked from commit 10ec440873a00650008015ba99a75b1b6c80187b) --------- Co-authored-by: zhanghe.1216 <@bytedance.com> (cherry picked from commit 36258b3d57e6c065009dafb2bddced72d9d1c35c) Co-authored-by: TRAE CLI --- crates/ragfs/src/lock/manager.rs | 356 ++++++++++++++----- crates/ragfs/src/lock/resolver.rs | 149 +++++--- docs/en/concepts/09-transaction.md | 35 +- docs/zh/concepts/09-transaction.md | 34 +- openviking/storage/viking_fs/_ops.py | 34 +- tests/storage/test_session_delete_storage.py | 14 + 6 files changed, 464 insertions(+), 158 deletions(-) diff --git a/crates/ragfs/src/lock/manager.rs b/crates/ragfs/src/lock/manager.rs index e9fe10b965a..63e773ec6f1 100644 --- a/crates/ragfs/src/lock/manager.rs +++ b/crates/ragfs/src/lock/manager.rs @@ -1049,15 +1049,13 @@ impl PathLockManager { }); } PathLockKind::Tree => { - let lock_path = self.resolver.resolve_tree_lock_path(&request.path).await?; + let resolved = self.resolver.resolve_tree_paths(&request.path).await?; self.check_ancestor_tree_locks(&request.path, owner_id) .await?; - let exact_candidates = self - .resolver - .resolve_exact_conflict_paths(&request.path) + self.check_lock_paths(&resolved.conflict_paths, owner_id) .await?; - self.check_lock_paths(&exact_candidates, owner_id).await?; self.check_descendant_locks(&request.path, owner_id).await?; + let lock_path = resolved.acquire_lock_path; self.ensure_lock_dir(&lock_path).await.map_err(|error| { PathLockError::Io(format!("failed to create lock dir: {error}")) })?; @@ -1099,11 +1097,11 @@ impl PathLockManager { PathLockKind::Tree => { self.check_ancestor_tree_locks(&request.path, owner_id) .await?; - let exact_candidates = self + let tree_candidates = self .resolver - .resolve_exact_conflict_paths(&request.path) + .resolve_tree_conflict_paths(&request.path) .await?; - self.check_lock_paths(&exact_candidates, owner_id).await?; + self.check_lock_paths(&tree_candidates, owner_id).await?; self.check_descendant_locks(&request.path, owner_id).await?; } } @@ -1252,37 +1250,25 @@ impl PathLockManager { /// Check ancestor directories for tree locks that would conflict. async fn check_ancestor_tree_locks(&self, path: &str, owner_id: &str) -> PathLockResult<()> { - let mut current = path.to_string(); let now_ns = Self::now_ns(); - loop { - let parent = match current.rsplit_once('/') { - Some((p, _)) if !p.is_empty() => p.to_string(), - Some(_) if current != "/" => "/".to_string(), - _ => break, - }; - - let ancestor_lock = if parent == "/" { - format!("/{}", PATH_LOCK_FILE) - } else { - format!("{}/{}", parent, PATH_LOCK_FILE) - }; - if let Some(token) = self.provider.read_token(&ancestor_lock).await? { - // Only Tree locks propagate to descendants; an Exact lock on - // /a must not block /a/b. - if token.lock_type == PathLockKind::Tree - && token.owner_id != owner_id - && !self.is_stale(&token, now_ns) - { - return Err(PathLockError::Conflict { - lock_path: ancestor_lock, - owner: token.owner_id, - kind: token.lock_type, - }); + for parent in LockPathResolver::ancestor_paths(path) { + for ancestor_lock in self.resolver.resolve_tree_conflict_paths(&parent).await? { + if let Some(token) = self.provider.read_token(&ancestor_lock).await? { + // Only Tree locks propagate to descendants; an Exact lock on + // /a must not block /a/b. + if token.lock_type == PathLockKind::Tree + && token.owner_id != owner_id + && !self.is_stale(&token, now_ns) + { + return Err(PathLockError::Conflict { + lock_path: ancestor_lock, + owner: token.owner_id, + kind: token.lock_type, + }); + } } } - - current = parent; } Ok(()) } @@ -1831,17 +1817,23 @@ impl PathLockManager { } PathLockHandleMode::LockPath if legacy_handoff => { let file_name = lp.rsplit('/').next().unwrap_or(""); - if lp == &format!("/{}", PATH_LOCK_FILE) + if !(lp == &format!("/{}", PATH_LOCK_FILE) || lp.ends_with(&format!("/{}", PATH_LOCK_FILE)) + || file_name.starts_with(EXACT_LOCK_FILE_PREFIX)) { - PathLockKind::Tree - } else if file_name.starts_with(EXACT_LOCK_FILE_PREFIX) { - PathLockKind::Exact - } else { return Err(PathLockError::InvalidRequest(format!( "legacy handoff lock path '{lp}' is not a supported lock file" ))); } + self.provider + .read_token(lp) + .await? + .ok_or_else(|| { + PathLockError::HandoffFailed(format!( + "lock path '{lp}' no longer exists" + )) + })? + .lock_type } PathLockHandleMode::LockPath => { let request = &handoff.covered_paths[index]; @@ -1852,7 +1844,9 @@ impl PathLockManager { .await? } PathLockKind::Tree => { - vec![self.resolver.resolve_tree_lock_path(&request.path).await?] + self.resolver + .resolve_tree_conflict_paths(&request.path) + .await? } }; if !expected_paths.contains(lp) { @@ -1968,16 +1962,11 @@ impl PathLockManager { return Ok(locked); } - // Check own .path.ovlock. - let dir_lock = format!("{}/{}", path.trim_end_matches('/'), PATH_LOCK_FILE); - if let Ok(Some(token)) = self.provider.read_token(&dir_lock).await { - if !ignore_stale || !self.is_stale(&token, now_ns) { - return Ok(true); - } - } - - // Check exact sidecar. - let exact_paths = self.resolver.resolve_exact_conflict_paths(path).await?; + // Check the current sidecar and the legacy in-directory token. + let exact_paths = self + .resolver + .resolve_exact_conflict_paths(&normalized_path) + .await?; for lp in &exact_paths { if let Ok(Some(token)) = self.provider.read_token(lp).await { if !ignore_stale || !self.is_stale(&token, now_ns) { @@ -1987,27 +1976,17 @@ impl PathLockManager { } // Check ancestor tree locks. - let mut current = path.to_string(); - loop { - let parent = match current.rsplit_once('/') { - Some((p, _)) if !p.is_empty() => p.to_string(), - Some(_) if current != "/" => "/".to_string(), - _ => break, - }; - let ancestor_lock = if parent == "/" { - format!("/{}", PATH_LOCK_FILE) - } else { - format!("{}/{}", parent, PATH_LOCK_FILE) - }; - if let Ok(Some(token)) = self.provider.read_token(&ancestor_lock).await { - // Only Tree locks propagate to descendants. - if token.lock_type == PathLockKind::Tree - && (!ignore_stale || !self.is_stale(&token, now_ns)) - { - return Ok(true); + for parent in LockPathResolver::ancestor_paths(&normalized_path) { + for ancestor_lock in self.resolver.resolve_tree_conflict_paths(&parent).await? { + if let Ok(Some(token)) = self.provider.read_token(&ancestor_lock).await { + // Only Tree locks propagate to descendants. + if token.lock_type == PathLockKind::Tree + && (!ignore_stale || !self.is_stale(&token, now_ns)) + { + return Ok(true); + } } } - current = parent; } Ok(false) @@ -2483,6 +2462,38 @@ mod tests { ) } + async fn make_filesystem_managers() -> (PathLockManager, PathLockManager) { + let fs = Arc::new(MemFileSystem::new()); + fs.mkdir("/data", 0o755).await.unwrap(); + fs.mkdir("/data/a", 0o755).await.unwrap(); + fs.mkdir("/data/a/b", 0o755).await.unwrap(); + fs.mkdir("/data/a/c", 0o755).await.unwrap(); + let config = PathLockConfig::default(); + let first_provider = Arc::new(crate::lock::provider::FilesystemPathLockProvider::new( + fs.clone(), + config.lock_expire_secs, + )); + let second_provider = Arc::new(crate::lock::provider::FilesystemPathLockProvider::new( + fs.clone(), + config.lock_expire_secs, + )); + ( + PathLockManager::new(fs.clone(), first_provider, config.clone()), + PathLockManager::new(fs, second_provider, config), + ) + } + + async fn acquire_kind( + manager: &PathLockManager, + path: &str, + kind: PathLockKind, + ) -> PathLockResult { + match kind { + PathLockKind::Exact => manager.acquire_exact(path, Duration::ZERO, None).await, + PathLockKind::Tree => manager.acquire_tree(path, Duration::ZERO, None).await, + } + } + #[tokio::test] async fn exact_locks_tolerate_concurrent_parent_directory_creation() { let inner = Arc::new(MemFileSystem::new()); @@ -2529,10 +2540,22 @@ mod tests { .acquire_tree("/data/delete-me", Duration::ZERO, None) .await .unwrap(); + assert!(lease.lease.lock_paths[0].starts_with("/data/.exact.ovlock.delete-me.")); fs.remove_all("/data/delete-me").await.unwrap(); + assert!( + mgr.acquire_tree("/data/delete-me", Duration::ZERO, None) + .await + .is_err(), + "the sidecar must keep the deleted path locked until release" + ); mgr.release(&lease).await.unwrap(); + let next = mgr + .acquire_tree("/data/delete-me", Duration::ZERO, None) + .await + .unwrap(); + mgr.release(&next).await.unwrap(); assert!(mgr .get_owned_lease_by_ref(&lease.lease.lease_ref) .await @@ -2635,7 +2658,7 @@ mod tests { assert!(matches!(result, Err(PathLockError::Timeout { .. }))); let token = mgr .provider - .read_token("/data/sub/.path.ovlock") + .read_token(&exact.lease.lock_paths[0]) .await .unwrap() .unwrap(); @@ -2669,6 +2692,131 @@ mod tests { mgr.release(&tree).await.unwrap(); } + #[tokio::test] + async fn filesystem_lock_relationship_matrix() { + struct Case { + name: &'static str, + held_path: &'static str, + held_kind: PathLockKind, + requested_path: &'static str, + requested_kind: PathLockKind, + conflicts: bool, + } + + let cases = [ + Case { + name: "ancestor tree blocks descendant exact", + held_path: "/data/a", + held_kind: PathLockKind::Tree, + requested_path: "/data/a/b", + requested_kind: PathLockKind::Exact, + conflicts: true, + }, + Case { + name: "descendant exact blocks ancestor tree", + held_path: "/data/a/b", + held_kind: PathLockKind::Exact, + requested_path: "/data/a", + requested_kind: PathLockKind::Tree, + conflicts: true, + }, + Case { + name: "ancestor tree blocks descendant tree", + held_path: "/data/a", + held_kind: PathLockKind::Tree, + requested_path: "/data/a/b", + requested_kind: PathLockKind::Tree, + conflicts: true, + }, + Case { + name: "descendant tree blocks ancestor tree", + held_path: "/data/a/b", + held_kind: PathLockKind::Tree, + requested_path: "/data/a", + requested_kind: PathLockKind::Tree, + conflicts: true, + }, + Case { + name: "ancestor exact allows descendant exact", + held_path: "/data/a", + held_kind: PathLockKind::Exact, + requested_path: "/data/a/b", + requested_kind: PathLockKind::Exact, + conflicts: false, + }, + Case { + name: "descendant exact allows ancestor exact", + held_path: "/data/a/b", + held_kind: PathLockKind::Exact, + requested_path: "/data/a", + requested_kind: PathLockKind::Exact, + conflicts: false, + }, + Case { + name: "sibling tree allows sibling exact", + held_path: "/data/a/b", + held_kind: PathLockKind::Tree, + requested_path: "/data/a/c", + requested_kind: PathLockKind::Exact, + conflicts: false, + }, + Case { + name: "sibling tree allows sibling tree", + held_path: "/data/a/b", + held_kind: PathLockKind::Tree, + requested_path: "/data/a/c", + requested_kind: PathLockKind::Tree, + conflicts: false, + }, + ]; + + for case in cases { + let (holder, contender) = make_filesystem_managers().await; + let held = acquire_kind(&holder, case.held_path, case.held_kind) + .await + .unwrap_or_else(|error| { + panic!("{}: failed to acquire held lock: {error}", case.name) + }); + let requested = + acquire_kind(&contender, case.requested_path, case.requested_kind).await; + + if case.conflicts { + assert!( + matches!(requested, Err(PathLockError::Timeout { .. })), + "{}: expected conflict, got {requested:?}", + case.name + ); + } else { + let requested = requested + .unwrap_or_else(|error| panic!("{}: unexpected conflict: {error}", case.name)); + contender.release(&requested).await.unwrap(); + } + holder.release(&held).await.unwrap(); + } + } + + #[tokio::test] + async fn legacy_tree_token_still_blocks_descendant_acquisition() { + let mgr = make_manager().await; + mgr.provider + .try_create_token( + "/data/sub/.path.ovlock", + &LockToken { + owner_id: "legacy-owner".to_string(), + time_ns: PathLockManager::now_ns(), + lock_type: PathLockKind::Tree, + }, + ) + .await + .unwrap(); + + assert!(matches!( + mgr.acquire_exact("/data/sub/file.txt", Duration::ZERO, None) + .await, + Err(PathLockError::Timeout { .. }) + )); + } + #[tokio::test] async fn handoff_and_adopt() { let mgr = make_manager().await; @@ -2931,6 +3079,36 @@ mod tests { consumer.release(&exact).await.unwrap(); } + #[tokio::test] + async fn adopt_accepts_legacy_tree_path_with_covered_paths() { + let mgr = make_manager().await; + let owner_id = "legacy-covered-owner".to_string(); + let lock_path = "/data/sub/.path.ovlock".to_string(); + mgr.provider + .try_create_token( + &lock_path, + &LockToken { + owner_id: owner_id.clone(), + time_ns: PathLockManager::now_ns(), + lock_type: PathLockKind::Tree, + }, + ) + .await + .unwrap(); + let handoff = PathLockHandoffRef { + lease_ref: Some("legacy-covered-lease".to_string()), + owner_id, + lock_paths: vec![lock_path], + covered_paths: vec![PathLockRequest { + path: "/data/sub".to_string(), + kind: PathLockKind::Tree, + }], + }; + + let adopted = mgr.adopt(&handoff).await.unwrap(); + mgr.release(&adopted).await.unwrap(); + } + #[tokio::test] async fn adopt_distinguishes_reentrant_leases_from_replay() { let (producer, fs) = make_manager_with_fs().await; @@ -3029,10 +3207,23 @@ mod tests { let fs = Arc::new(MemFileSystem::new()); fs.mkdir("/data", 0o755).await.unwrap(); let provider = Arc::new(FailNextRemoveProvider::with_busy_takeover()); + let mgr = PathLockManager::new( + fs, + provider.clone(), + PathLockConfig { + lock_expire_secs: 1.0, + ..PathLockConfig::default() + }, + ); + let lock_path = mgr + .resolver + .resolve_tree_lock_path("/data/file.txt") + .await + .unwrap(); provider .inner .try_create_token( - "/data/file.txt/.path.ovlock", + &lock_path, &LockToken { owner_id: "stale-owner".to_string(), time_ns: 1, @@ -3041,14 +3232,6 @@ mod tests { ) .await .unwrap(); - let mgr = PathLockManager::new( - fs, - provider.clone(), - PathLockConfig { - lock_expire_secs: 1.0, - ..PathLockConfig::default() - }, - ); let lease = mgr .acquire_tree("/data/file.txt", Duration::from_millis(200), None) @@ -3078,11 +3261,12 @@ mod tests { refresh_on_takeover: refresh, ..FailNextRemoveProvider::with_compare_miss() }); - let lock_path = "/data/.path.ovlock"; + let mgr = PathLockManager::new(fs, provider.clone(), PathLockConfig::default()); + let lock_path = mgr.resolver.resolve_tree_lock_path("/data").await.unwrap(); provider .inner .try_create_token( - lock_path, + &lock_path, &LockToken { owner_id: "original-owner".to_string(), time_ns: 1, @@ -3091,10 +3275,14 @@ mod tests { ) .await .unwrap(); - let mgr = PathLockManager::new(fs, provider.clone(), PathLockConfig::default()); let result = mgr.acquire_tree("/data", timeout, None).await; - let token = provider.inner.read_token(lock_path).await.unwrap().unwrap(); + let token = provider + .inner + .read_token(&lock_path) + .await + .unwrap() + .unwrap(); assert!(token.time_ns > 1); if refresh { // The heartbeat wins after the stale read but before takeover. diff --git a/crates/ragfs/src/lock/resolver.rs b/crates/ragfs/src/lock/resolver.rs index 2f32da81eaa..7a8dcbadf94 100644 --- a/crates/ragfs/src/lock/resolver.rs +++ b/crates/ragfs/src/lock/resolver.rs @@ -18,9 +18,18 @@ pub(crate) struct ResolvedExactPaths { pub conflict_paths: Vec, } +/// Tree-lock paths resolved for new writes plus legacy reads. +#[derive(Debug, Clone, PartialEq, Eq)] +pub(crate) struct ResolvedTreePaths { + /// Lock path used for the actual tree token creation. + pub acquire_lock_path: String, + /// Paths that may contain a tree token for the same logical path. + pub conflict_paths: Vec, +} + /// Computes lock-file paths for exact and tree locks. pub struct LockPathResolver { - /// Filesystem used for `stat` calls to determine is_dir. + /// Filesystem retained for lock-directory creation and compatibility checks. pub(crate) fs: Arc, } @@ -32,17 +41,13 @@ impl LockPathResolver { /// Compute exact lock paths for `path`. /// - /// - Existing directory → `{path}/.path.ovlock` - /// - File or non-existent path → `{parent}/.exact.ovlock..` + /// All paths use a parent sidecar so deleting a directory cannot delete its own token. pub async fn resolve_exact_lock_paths(&self, path: &str) -> PathLockResult> { Ok(vec![self.resolve_exact_lock_path(path).await?]) } /// Compute every lock-file path that can represent an exact lock for conflict checks. - pub async fn resolve_exact_conflict_paths( - &self, - path: &str, - ) -> PathLockResult> { + pub async fn resolve_exact_conflict_paths(&self, path: &str) -> PathLockResult> { Ok(self.resolve_exact_paths(path).await?.conflict_paths) } @@ -51,37 +56,54 @@ impl LockPathResolver { Ok(self.resolve_exact_paths(path).await?.acquire_lock_path) } - /// Resolve the exact acquire path and its conservative conflict set using one `stat`. - pub(crate) async fn resolve_exact_paths(&self, path: &str) -> PathLockResult { - let stat_result = self.fs.stat(path).await; - let acquire_lock_path = match stat_result { - Ok(info) if info.is_dir => path_lock_path(path), - _ => prefixed_exact_lock_path(path), - }; - let conflict_paths = if acquire_lock_path == path_lock_path(path) { - vec![acquire_lock_path.clone(), prefixed_exact_lock_path(path)] - } else { - vec![acquire_lock_path.clone(), path_lock_path(path)] - }; + /// Resolve the sidecar acquire path and include the legacy in-directory token for conflicts. + pub(crate) async fn resolve_exact_paths( + &self, + path: &str, + ) -> PathLockResult { + let acquire_lock_path = prefixed_exact_lock_path(path); + let conflict_paths = vec![acquire_lock_path.clone(), path_lock_path(path)]; Ok(ResolvedExactPaths { acquire_lock_path, conflict_paths, }) } - /// Compute the tree lock path for `path`. - /// - /// - Regular directory or missing path → `{path}/.path.ovlock` - /// - Existing file path → parent directory sidecar + /// Compute every lock-file path that can represent a tree lock. + pub async fn resolve_tree_conflict_paths(&self, path: &str) -> PathLockResult> { + Ok(self.resolve_tree_paths(path).await?.conflict_paths) + } + + /// Compute the primary lock-file path used when acquiring one tree lock. pub async fn resolve_tree_lock_path(&self, path: &str) -> PathLockResult { - let stat_result = self.fs.stat(path).await; - match stat_result { - Ok(info) if !info.is_dir => { - // Existing file: use parent sidecar to avoid `{file}/.path.ovlock`. - Ok(prefixed_exact_lock_path(path)) - } - _ => Ok(path_lock_path(path)), + Ok(self.resolve_tree_paths(path).await?.acquire_lock_path) + } + + /// Resolve the shared sidecar acquire path and include the legacy tree token for reads. + pub(crate) async fn resolve_tree_paths(&self, path: &str) -> PathLockResult { + let acquire_lock_path = prefixed_exact_lock_path(path); + let conflict_paths = vec![acquire_lock_path.clone(), path_lock_path(path)]; + Ok(ResolvedTreePaths { + acquire_lock_path, + conflict_paths, + }) + } + + /// Return every ancestor path from nearest parent to root. + pub(crate) fn ancestor_paths(path: &str) -> Vec { + let mut current = path.to_string(); + let mut ancestors = Vec::new(); + + loop { + let parent = match current.rsplit_once('/') { + Some((p, _)) if !p.is_empty() => p.to_string(), + Some(_) if current != "/" => "/".to_string(), + _ => break, + }; + ancestors.push(parent.clone()); + current = parent; } + ancestors } } @@ -93,13 +115,17 @@ fn path_lock_path(path: &str) -> String { /// Return the legacy-compatible prefixed exact sidecar path. fn prefixed_exact_lock_path(path: &str) -> String { let (parent, name) = split_parent_name(path); - format!( - "{}/{}{}.{}", - parent, + let file_name = format!( + "{}{}.{}", EXACT_LOCK_FILE_PREFIX, safe_name(name), hash_prefix(path) - ) + ); + if parent == "/" { + format!("/{file_name}") + } else { + format!("{parent}/{file_name}") + } } /// Split a path into (parent_dir, basename). @@ -137,7 +163,10 @@ fn safe_name(name: &str) -> String { /// First 16 hex chars of SHA-1 of the full backend path. fn hash_prefix(path: &str) -> String { let digest = Sha1::digest(path.as_bytes()); - digest[..8].iter().map(|b| format!("{:02x}", b)).collect::() + digest[..8] + .iter() + .map(|b| format!("{:02x}", b)) + .collect::() } #[cfg(test)] @@ -154,7 +183,7 @@ mod tests { } #[tokio::test] - async fn resolver_uses_path_lock_for_directories_and_sidecars_for_files() { + async fn resolver_uses_parent_sidecars_for_all_paths() { let fs = memfs().await; fs.mkdir("/data/dir", 0o755).await.unwrap(); fs.write("/data/file.txt", b"", 0, WriteFlag::Create) @@ -162,13 +191,28 @@ mod tests { .unwrap(); let resolver = LockPathResolver::new(fs); + let exact_dir = resolver + .resolve_exact_lock_paths("/data/dir") + .await + .unwrap(); + assert!(exact_dir[0].starts_with("/data/.exact.ovlock.dir.")); assert_eq!( - resolver.resolve_exact_lock_paths("/data/dir").await.unwrap(), - vec!["/data/dir/.path.ovlock".to_string()] + resolver.resolve_tree_lock_path("/data/dir").await.unwrap(), + exact_dir[0] ); assert_eq!( - resolver.resolve_tree_lock_path("/data/dir").await.unwrap(), - "/data/dir/.path.ovlock" + resolver + .resolve_tree_conflict_paths("/data/dir") + .await + .unwrap(), + vec![exact_dir[0].clone(), "/data/dir/.path.ovlock".to_string()] + ); + assert_eq!( + resolver + .resolve_exact_conflict_paths("/data/dir") + .await + .unwrap(), + vec![exact_dir[0].clone(), "/data/dir/.path.ovlock".to_string()] ); let exact_file = resolver @@ -186,6 +230,31 @@ mod tests { .await .unwrap()[0] .starts_with("/data/.exact.ovlock.new.txt.")); + assert!(resolver + .resolve_tree_lock_path("/top-level") + .await + .unwrap() + .starts_with("/.exact.ovlock.top-level.")); + assert!(!resolver + .resolve_tree_lock_path("/top-level") + .await + .unwrap() + .starts_with("//")); + assert!(resolver + .resolve_tree_lock_path("/") + .await + .unwrap() + .starts_with("/.exact.ovlock.path.")); + } + + #[test] + fn ancestor_paths_run_from_nearest_parent_to_root() { + assert_eq!( + LockPathResolver::ancestor_paths("/data/a/b"), + vec!["/data/a", "/data", "/"] + ); + assert_eq!(LockPathResolver::ancestor_paths("/data"), vec!["/"]); + assert!(LockPathResolver::ancestor_paths("/").is_empty()); } #[test] diff --git a/docs/en/concepts/09-transaction.md b/docs/en/concepts/09-transaction.md index f0470a5ca14..b6dd0b83bd1 100644 --- a/docs/en/concepts/09-transaction.md +++ b/docs/en/concepts/09-transaction.md @@ -242,17 +242,17 @@ Locks coordinate participating operations. The low-level `PathLockWrappedFS` use ### Filesystem Provider Lock Protocol -The caller chooses the lock type; the resolver chooses the token location from the target's state: +The caller chooses the lock type. The filesystem provider uses a parent sidecar for every target: | Target state | Exact token | Tree token | | --- | --- | --- | | Existing file `/docs/a` | `/docs/.exact.ovlock.a.`, containing E | Same sidecar, containing T | -| Existing directory `/docs/a` | `/docs/a/.path.ovlock`, containing E | Same file inside the directory, containing T | -| Missing `/docs/a` | Parent sidecar, containing E | Create the target directory, then write `.path.ovlock` inside it, containing T | +| Existing directory `/docs/a` | `/docs/.exact.ovlock.a.`, containing E | Same sidecar, containing T | +| Missing `/docs/a` | `/docs/.exact.ovlock.a.`, containing E | Same sidecar, containing T | -A sidecar sits beside its target but represents only that target, not its parent directory. `` is a SHA-1 prefix of the full backend path, not the business file's contents. +A sidecar sits beside its target but represents only that target, not its parent directory. Recursively deleting the target does not delete the token in its parent, so mutual exclusion remains active until the lease is formally released. `` is a SHA-1 prefix of the full backend path, not the business file's contents. -`.exact.ovlock.*` can contain a Tree token, and `.path.ovlock` can contain an Exact token. Filenames are part of the storage protocol, but do not alone identify the logical lock type. Token contents are: +`.exact.ovlock.*` stores E or T according to the logical lock type. For compatibility with tokens left by older versions, conflict checks still read `.path.ovlock` inside the target, but new locks are no longer written there. Filenames are part of the storage protocol, but do not alone identify the logical lock type. Token contents are: ```text {owner_id}:{time_ns}:{lock_type} @@ -262,6 +262,17 @@ A sidecar sits beside its target but represents only that target, not its parent A lease records logical scope in `covered_paths` separately from token locations in `lock_paths`. An owned lease controls refresh, release, and handoff. A borrowed lease proves coverage by an existing lock without permission to release the outer lock. +#### Protocol Migration and Deployment + +The new version reads both the new sidecar and the legacy `.path.ovlock`, but writes new tokens only to the sidecar. Existing leases are not migrated in place: refresh, release, and handoff continue to use the legacy `lock_paths` recorded by the lease until those tokens are released or expire. + +Old versions do not inspect new ancestor sidecars, so filesystem-provider instances of different protocol versions must not process writes against the same backend concurrently. The current version requires a coordinated cutover: + +1. Stop new writes, wait for active leases and pending handoffs to drain, then stop every old instance. +2. Start all new instances, confirm legacy tokens were released or can be reclaimed by expiry, then resume writes. + +A zero-downtime rolling deployment requires two independently deployable protocol stages: first deploy a compatibility version that reads both formats but still writes legacy tokens; after every instance is upgraded, switch all instances to reading both formats and writing only new sidecars. There must be no interval where an old instance can encounter a new sidecar. + ### Cache Provider Lock Protocol The cache provider stores the same token format in Redis HASH fields. It uses @@ -321,8 +332,8 @@ loop until timeout (poll interval: 200ms): - Missing target directory? -> treat as no descendant locks - Stale lock? -> remove and retry - Active lock? -> wait - 4. Ensure the resolved token parent exists; this creates a missing target as a directory - 5. Write the TREE (T) token (sidecar for an existing file, internal .path.ovlock otherwise) + 4. Ensure the resolved sidecar parent exists; do not create the missing target itself + 5. Write the TREE (T) token to the parent sidecar 6. TOCTOU double-check: re-scan descendants and ancestors - Conflict found: compare (timestamp, handle_id) - Later one (larger timestamp/handle_id) backs off (removes own lock) to prevent livelock @@ -335,17 +346,17 @@ Timeout (default 0 = no-wait) raises LockAcquisitionError ### Missing Directory Creation -The lock system may create directories so it can place lock files, but it checks -for conflicts first: +The lock system may create a missing parent chain so it can place a sidecar, +but it does not create the locked target itself. It checks for conflicts first: ``` -1. Ancestor TreeLock / same-path lock / descendant lock conflict -> do not create the directory -2. No current conflict -> create the directory and write the lock +1. Ancestor TreeLock / same-path lock / descendant lock conflict -> do not create directories +2. No current conflict -> create the sidecar parent and write the lock 3. A post-write double-check finds a new conflict -> remove our own lock and fail or retry 4. Step 3 does not roll back the empty directory ``` -Acquisition rollback and normal release clean up tokens without guaranteeing removal of directories created to store them. An Exact sidecar can also create a missing parent chain. Snapshots use a separate policy for missing targets; see [snapshot scope and concurrency](../guides/15-snapshot.md#commit-scope-and-concurrency). +Acquisition rollback and normal release clean up tokens without guaranteeing removal of a parent chain created to store the sidecar. Snapshots use a separate policy for missing targets; see [snapshot scope and concurrency](../guides/15-snapshot.md#commit-scope-and-concurrency). ### Lock Expiry Cleanup diff --git a/docs/zh/concepts/09-transaction.md b/docs/zh/concepts/09-transaction.md index 560df5d5d02..5d51ac49a12 100644 --- a/docs/zh/concepts/09-transaction.md +++ b/docs/zh/concepts/09-transaction.md @@ -239,17 +239,17 @@ Exact 和 Tree 表达操作范围,文件、目录或缺失路径表达目标 ### Filesystem Provider 锁协议 -锁类型由调用者选择,Resolver 根据目标状态决定 token 位置: +锁类型由调用者选择。Filesystem Provider 对所有目标统一使用父目录 sidecar: | 目标状态 | Exact token | Tree token | | --- | --- | --- | | 现存文件 `/docs/a` | `/docs/.exact.ovlock.a.`,内容为 E | 同一 sidecar,内容为 T | -| 现存目录 `/docs/a` | `/docs/a/.path.ovlock`,内容为 E | 同一目录内文件,内容为 T | -| 缺失路径 `/docs/a` | 父目录 sidecar,内容为 E | 创建目标目录后写内部 `.path.ovlock`,内容为 T | +| 现存目录 `/docs/a` | `/docs/.exact.ovlock.a.`,内容为 E | 同一 sidecar,内容为 T | +| 缺失路径 `/docs/a` | `/docs/.exact.ovlock.a.`,内容为 E | 同一 sidecar,内容为 T | -sidecar 位于目标旁边,但只代表该目标,不会锁住整个父目录。`` 来自完整后端路径的 SHA-1 前缀,与业务文件内容无关。 +sidecar 位于目标旁边,但只代表该目标,不会锁住整个父目录。递归删除目标时不会删除位于父目录中的 token,因此锁的互斥保护会持续到 lease 正式释放。`` 来自完整后端路径的 SHA-1 前缀,与业务文件内容无关。 -`.exact.ovlock.*` 可以存 Tree token,`.path.ovlock` 也可以存 Exact token。文件名是存储协议的一部分,不能单凭名字判断逻辑锁类型。token 内容为: +`.exact.ovlock.*` 根据实际锁类型存储 E 或 T。为兼容升级前遗留 token,冲突检测仍读取目标内部的 `.path.ovlock`,但新锁不再写入该位置。文件名是存储协议的一部分,不能单凭名字判断逻辑锁类型。token 内容为: ```text {owner_id}:{time_ns}:{lock_type} @@ -259,6 +259,17 @@ sidecar 位于目标旁边,但只代表该目标,不会锁住整个父目录 lease 将逻辑范围 `covered_paths` 与 token 位置 `lock_paths` 分开记录。Owned lease 控制续期、释放和交接;Borrowed lease 仅提供已有锁的覆盖证明,不能释放外层锁。 +#### 协议迁移与发布 + +新版本对新 sidecar 和旧 `.path.ovlock` 执行双读,但只向新 sidecar 写入 token。升级前已存在的 lease 不做原地迁移:续期、释放和交接继续使用 lease 中记录的旧 `lock_paths`,直到旧 token 正常释放或过期。 + +旧版本不会检查祖先路径的新 sidecar,因此 Filesystem Provider 不能让新旧版本在同一后端上同时处理写请求。当前版本采用协调切换: + +1. 停止新的写请求,等待活跃 lease 和待交接任务排空,然后停止所有旧实例。 +2. 全量启动新版本实例,确认旧 token 已释放或可按过期规则回收,再恢复写流量。 + +如果部署必须保持零停机滚动升级,需要拆成两个可独立发布的协议阶段:先发布“新旧双读、仍写旧 token”的兼容版本;全部实例升级后,再统一切换为“新旧双读、只写新 sidecar”。两个阶段之间不得存在旧实例读取新 sidecar 的窗口。 + ### Cache Provider 锁协议 Cache Provider 将相同 token 格式存入 Redis HASH field,并通过 Lua @@ -318,8 +329,8 @@ HASH。跨 scope batch 会被拒绝。 - 目标目录不存在? -> 视为无后代锁 - 陈旧锁? -> 移除后重试 - 活跃锁? -> 等待 - 4. 确保 Resolver 选定的 token 父目录存在;缺失目标会因此被创建成目录 - 5. 写入 TREE (T) token(现存文件用 sidecar,其余用内部 .path.ovlock) + 4. 确保 Resolver 选定的 sidecar 父目录存在;不会创建缺失目标本身 + 5. 在父目录 sidecar 写入 TREE (T) token 6. TOCTOU 双重检查:重新扫描后代目录和祖先目录 - 发现冲突:比较 (timestamp, handle_id) - 后到者(更大的 timestamp/handle_id)主动让步(删除自己的锁),防止活锁 @@ -332,11 +343,11 @@ HASH。跨 scope batch 会被拒绝。 ### 缺失目录创建规则 -锁系统允许为了放置锁文件而创建目录,但创建前必须先检查冲突: +锁系统允许为了放置 sidecar 而创建缺失的父目录链,但不会创建被锁目标本身。创建前必须先检查冲突: ``` 1. 发现祖先 TreeLock / 同路径锁 / 后代锁冲突 -> 不创建目录,直接失败或等待 -2. 当前无冲突 -> 可以创建目录并写锁 +2. 当前无冲突 -> 可以创建 sidecar 的父目录并写锁 3. 写锁后再次检查时发现新冲突 -> 删除自己的锁并失败或重试 4. 第 3 步不会回滚刚创建的空目录 ``` @@ -353,10 +364,9 @@ HASH。跨 scope batch 会被拒绝。 ``` 如果两个请求同时创建 `java-guide`,两边都可能先看到“当前无冲突”,但最终只有 -fencing token 校验通过的一方成功持有 `TreeLock(java-guide)`;失败方会删除自己的锁, -已创建出来的空目录可以保留。 +fencing token 校验通过的一方成功持有 `TreeLock(java-guide)`;失败方会删除自己的锁。 -获取失败的回滚和正常释放只清理 token,不保证删除为存放 token 创建的目录。Exact sidecar 也可能创建缺失的父目录链。Snapshot 对缺失目标采用单独的策略,见 [快照的范围与并发](../guides/15-snapshot.md#提交范围与并发)。 +获取失败的回滚和正常释放只清理 token,不保证删除为存放 sidecar 创建的父目录链。Snapshot 对缺失目标采用单独的策略,见 [快照的范围与并发](../guides/15-snapshot.md#提交范围与并发)。 ### 锁过期清理 diff --git a/openviking/storage/viking_fs/_ops.py b/openviking/storage/viking_fs/_ops.py index a055c09f596..2e0e9f8c36f 100644 --- a/openviking/storage/viking_fs/_ops.py +++ b/openviking/storage/viking_fs/_ops.py @@ -268,6 +268,18 @@ async def _estimate_deleted_count(target_path: str, real_ctx: RequestContext) -> logger.warning(f"[VikingFS] Failed to count nodes before delete: {e}") return 0 + async def _finish_missing_delete() -> Dict[str, Any]: + """Clean orphan index records for an idempotent delete.""" + if no_vector: + return {"estimated_deleted_count": 0} + uris_to_delete = await self._collect_uris(path, recursive, ctx=ctx) + uris_to_delete.append(target_uri) + real_ctx = self._ctx_or_default(ctx) + estimated_count = await _estimate_deleted_count(path, real_ctx) + await self._delete_from_vector_store(uris_to_delete, ctx=ctx) + logger.info(f"[VikingFS] rm target not found, cleaned orphan index: {uri}") + return {"estimated_deleted_count": estimated_count} + # Check existence and determine lock strategy try: stat = await self._async_agfs.stat(path) @@ -280,16 +292,7 @@ async def _estimate_deleted_count(target_path: str, real_ctx: RequestContext) -> raise if recursive: await self._ensure_access(target_uri, ctx, action=AclAction.MANAGE) - if no_vector: - return {"estimated_deleted_count": 0} - # Path does not exist: clean up any orphan index records and return - uris_to_delete = await self._collect_uris(path, recursive, ctx=ctx) - uris_to_delete.append(target_uri) - real_ctx = self._ctx_or_default(ctx) - estimated_count = await _estimate_deleted_count(path, real_ctx) - await self._delete_from_vector_store(uris_to_delete, ctx=ctx) - logger.info(f"[VikingFS] rm target not found, cleaned orphan index: {uri}") - return {"estimated_deleted_count": estimated_count} + return await _finish_missing_delete() if is_dir: await self._ensure_access(target_uri, ctx, action=AclAction.MANAGE) @@ -315,6 +318,17 @@ async def _estimate_deleted_count(target_path: str, real_ctx: RequestContext) -> raise ResourceBusyError(f"Resource is being processed: {uri}", uri=uri) try: + if lease_ref is None and lease is not None: + try: + await self._async_agfs.stat(path) + except Exception as exc: + if is_not_found_error(exc): + return await _finish_missing_delete() + mapped = map_exception(exc, resource=uri) + if mapped is not None: + raise mapped from exc + raise + check_descendant_acl = ( is_dir and (not no_vector or is_acl_uri(target_uri)) diff --git a/tests/storage/test_session_delete_storage.py b/tests/storage/test_session_delete_storage.py index f5e98983a69..ce4e5b79e8c 100644 --- a/tests/storage/test_session_delete_storage.py +++ b/tests/storage/test_session_delete_storage.py @@ -139,6 +139,20 @@ async def test_session_rm_releases_its_tree_lease_when_backend_delete_fails(stor assert storage.agfs.rm.await_args.kwargs["fs_ctx"]["lease_ref"] == "delete-lease" +async def test_session_rm_rechecks_existence_after_waiting_for_tree_lock(storage): + storage.agfs.stat.side_effect = [ + {"isDir": True}, + FileNotFoundError(SESSION_PATH), + ] + + result = await storage.fs.rm(SESSION_URI, recursive=True, ctx=storage.ctx, no_vector=True) + + assert result == {"estimated_deleted_count": 0} + storage.agfs.pathlock_acquire_tree.assert_awaited_once_with(SESSION_PATH) + storage.agfs.rm.assert_not_awaited() + storage.agfs.pathlock_release.assert_awaited_once_with(storage.lease) + + async def test_session_rm_reuses_outer_lease_without_releasing_it(storage): outer_lease = {"lease_ref": "outer-lease"} From a609d3f5a62d7cb5a4e3d0592cac504572f2847f Mon Sep 17 00:00:00 2001 From: qin-ctx Date: Tue, 27 Oct 2026 11:23:12 +0800 Subject: [PATCH 6/6] refactor(session): remove legacy path compatibility Stop probing obsolete session storage paths during normal operations and reject the legacy session URI alias. Update bundled callers to use current session URIs. (cherry picked from commit 68b1ea6f1531b7260620dff9030bd1de988588c2) (cherry picked from commit 14d622daec5e0afd6b268d97160aebcb5ab4c37c) Co-authored-by: TRAE CLI --- bot/vikingbot/openviking_mount/README.md | 2 +- docs/en/api/05-sessions.md | 4 +- docs/en/api/12-content.md | 2 +- docs/en/concepts/04-viking-uri.md | 7 +- docs/en/concepts/08-session.md | 3 +- docs/zh/api/05-sessions.md | 3 +- docs/zh/api/12-content.md | 2 +- docs/zh/concepts/04-viking-uri.md | 6 +- docs/zh/concepts/08-session.md | 3 +- examples/dsh-memory-plugin/client.test.mjs | 2 +- examples/openclaw-plugin/README_CN.md | 8 +- .../docs/openviking-openclaw-plugin-guide.md | 10 +- .../docs/openviking-websocket-rpc-api.md | 8 +- examples/openclaw-plugin/memory-ranking.ts | 2 +- .../plugin/openviking-archive-tools.ts | 2 +- .../plugin/openviking-recall-trace-runtime.ts | 2 +- .../plugin/openviking-tool-result-tools.ts | 14 +- .../skills/install-openviking-memory/SKILL.md | 2 +- .../openviking-context-database/SKILL.md | 2 +- .../tests/ut/plugin-modules.test.ts | 4 +- .../tests/ut/tool-round-trip.test.ts | 4 +- .../openclaw-plugin/tests/ut/tools.test.ts | 20 +- .../CONTEXT-WINDOW.md | 6 +- .../client.ts | 11 +- .../scripts/e2e-window.mjs | 2 +- .../tools.ts | 2 +- openviking/core/namespace.py | 19 +- openviking/core/uri_validation.py | 6 +- openviking/storage/viking_fs/_access.py | 295 ++---------------- openviking/storage/viking_fs/_grep.py | 37 +-- openviking/storage/viking_fs/_ops.py | 190 ++--------- openviking/storage/viking_fs/_semantic.py | 83 ++--- openviking_cli/utils/uri.py | 2 +- sdk/go/client_test.go | 8 +- sdk/typescript/tests/client.test.ts | 4 +- tests/server/test_admin_api.py | 20 +- tests/server/test_api_sessions.py | 17 - tests/service/test_session_service_metrics.py | 13 +- .../memory/test_memory_react_system_prompt.py | 6 +- tests/session/test_tool_result_synopsis.py | 4 +- tests/storage/test_session_delete_storage.py | 1 - .../storage/test_viking_fs_actor_peer_view.py | 116 ------- tests/storage/test_viking_fs_glob.py | 20 +- tests/storage/test_viking_fs_grep.py | 100 +----- tests/storage/test_viking_fs_tree.py | 15 - tests/test_token_estimation.py | 8 +- tests/unit/test_message.py | 22 +- .../unit/test_namespace_uri_classification.py | 13 +- tests/unit/test_summarizer_context_type.py | 2 +- tests/unit/test_uri_short_format.py | 1 - tests/unit/test_uri_validation.py | 1 - tests/unit/test_vectorize_file_strategy.py | 2 +- .../filesystem/-components/terminal-panel.tsx | 10 +- .../src/routes/resources/-lib/api.test.ts | 2 +- .../-components/memory-impact.test.tsx | 4 +- 55 files changed, 205 insertions(+), 949 deletions(-) diff --git a/bot/vikingbot/openviking_mount/README.md b/bot/vikingbot/openviking_mount/README.md index 4bc4feb0ec4..a81eb71f7ca 100644 --- a/bot/vikingbot/openviking_mount/README.md +++ b/bot/vikingbot/openviking_mount/README.md @@ -174,7 +174,7 @@ OpenViking URI 到本地文件路径的映射规则: OpenViking URI 本地路径 ------------------- ------------------ viking://resources/foo -> {mount_point}/resources/foo -viking://session/bar -> {mount_point}/session/bar +viking://user//sessions/bar -> {mount_point}/user//sessions/bar viking://user//baz -> {mount_point}/user//baz ``` diff --git a/docs/en/api/05-sessions.md b/docs/en/api/05-sessions.md index 1fe91fd97a9..a1210c8fedb 100644 --- a/docs/en/api/05-sessions.md +++ b/docs/en/api/05-sessions.md @@ -12,8 +12,8 @@ viking://user/{user_id}/sessions/{session_id} ``` Session APIs are scoped to the authenticated user and return canonical user -session URIs. URI-based APIs may also accept the backward-compatible -`viking://session/{session_id}` alias, resolved in the same user context. +session URIs. URI-based APIs also accept the `viking://~/sessions/{session_id}` +home alias for the authenticated user. ## API Reference diff --git a/docs/en/api/12-content.md b/docs/en/api/12-content.md index e179c771143..4d1b06f0b60 100644 --- a/docs/en/api/12-content.md +++ b/docs/en/api/12-content.md @@ -150,7 +150,7 @@ Read the complete text of an L0, L1, or L2 file. - `read()` accepts file URIs only. Passing an existing directory URI returns `INVALID_ARGUMENT` (`400`), not `NOT_FOUND`. This error carries a structured `details` payload — `details.expected` is `"file"`, `details.actual` is `"directory"`, and `details.resource` is the offending URI (present on the HTTP path) — so clients can detect a file-vs-directory mismatch programmatically (for example, fall back to `list`) instead of string-matching the message. - Instead of a Viking URI, you may pass the 32-character hex `id` returned by `stat()` for a file. The server looks up the URI via the vector index and applies the same permission checks. Because indexing is asynchronous, a newly returned ID might not be resolvable immediately; lookup also fails if the corresponding vector record has been deleted. In both cases, the server returns `NOT_FOUND` and indicates that the data may not have been indexed yet or may have been deleted. -- Public URI parameters accept `resources`, `user`, and `agent` scopes. For session files, use `viking://user/{user_id}/sessions/{session_id}/messages.jsonl` or the backward-compatible `viking://session/{session_id}/messages.jsonl` alias. Internal scopes such as `temp` and `queue` return `INVALID_URI`. +- Public URI parameters accept `resources`, `user`, and `agent` scopes. For session files, use `viking://user/{user_id}/sessions/{session_id}/messages.jsonl` or the current user's `viking://~/sessions/{session_id}/messages.jsonl` home alias. The old `viking://session/...` scope and internal scopes such as `temp` and `queue` return `INVALID_URI`. **Python SDK** diff --git a/docs/en/concepts/04-viking-uri.md b/docs/en/concepts/04-viking-uri.md index eae0fa9c767..6cb67ea8c68 100644 --- a/docs/en/concepts/04-viking-uri.md +++ b/docs/en/concepts/04-viking-uri.md @@ -24,8 +24,7 @@ viking://{scope}/{path} | **upload** | Temporary upload files | Temporary | Internal | Public API and CLI filesystem/content operations accept the public scopes -`resources`, `user`, and `agent`, plus the root URI `viking://`. `session` is retained -as a backward-compatible alias for user session paths; new session data lives +`resources`, `user`, and `agent`, plus the root URI `viking://`. Session data lives under `viking://user/{user_id}/sessions`. `temp`, `queue`, and `upload` are internal implementation scopes and cannot be addressed directly through public API URI parameters. @@ -170,9 +169,7 @@ viking://user/{user_id}/sessions/{session_id}/history # Archived history viking://~/sessions/{session_id}/ # Your own session, via the home alias ``` -`viking://session/{session_id}` is accepted as a backward-compatible alias for -the current user's session path. It is not a separate storage root for new -session data. +The old `viking://session/{session_id}` URI is no longer accepted. ## Path Variables diff --git a/docs/en/concepts/08-session.md b/docs/en/concepts/08-session.md index 84b3f78a2dd..163dc95bc88 100644 --- a/docs/en/concepts/08-session.md +++ b/docs/en/concepts/08-session.md @@ -253,8 +253,7 @@ viking://~/memories/ `viking://user/{user_id}/sessions/{session_id}` for the authenticated caller. The uid-less spelling `viking://user/sessions/{session_id}` is no longer accepted and returns an error pointing at the `viking://~/...` form. The old -`viking://session/{session_id}` form is still accepted as a backward-compatible -alias for the same session path and is not a separate storage root. +`viking://session/{session_id}` form is also rejected. ## Related Documents diff --git a/docs/zh/api/05-sessions.md b/docs/zh/api/05-sessions.md index 74a1cef2af0..5ce6c62dedb 100644 --- a/docs/zh/api/05-sessions.md +++ b/docs/zh/api/05-sessions.md @@ -12,8 +12,7 @@ viking://user/{user_id}/sessions/{session_id} ``` Session API 按认证用户作用域访问会话,并返回 canonical user session URI。 -基于 URI 的 API 也可以接受向后兼容的 `viking://session/{session_id}` 别名, -该别名会在同一个用户上下文中解析。 +基于 URI 的 API 可以使用 `viking://~/sessions/{session_id}` 表示当前用户的会话。 ## API 参考 diff --git a/docs/zh/api/12-content.md b/docs/zh/api/12-content.md index 4d34a508c3f..099d5fa6b24 100644 --- a/docs/zh/api/12-content.md +++ b/docs/zh/api/12-content.md @@ -150,7 +150,7 @@ ov overview viking://resources/docs/ - `read()` 只接受文件 URI。传入已存在的目录时返回 `INVALID_ARGUMENT`(HTTP `400`)。HTTP 响应的 `details` 包含 `expected: "file"`、`actual: "directory"` 和目标 `resource` URI,客户端可据此改用目录列表接口,无需解析错误消息。 - 除 Viking URI 外,还可以传入 `stat()` 返回的 32 字符十六进制文件 `id`。服务端通过向量索引查找对应 URI 并执行相同的权限校验。由于索引是异步生成的,新返回的 ID 可能暂时无法解析;对应向量记录被删除后,按 ID 查询也会失败。这两种情况下,服务端都会返回 `NOT_FOUND`,并提示数据可能尚未索引或已经删除。 -- 公开 URI 参数接受 `resources`、`user` 和 `agent` 作用域。访问 session 文件时,使用 `viking://user/{user_id}/sessions/{session_id}/messages.jsonl`,也可以使用向后兼容的 `viking://session/{session_id}/messages.jsonl` 别名。`temp`、`queue` 等内部作用域会返回 `INVALID_URI`。 +- 公开 URI 参数接受 `resources`、`user` 和 `agent` 作用域。访问 session 文件时,使用 `viking://user/{user_id}/sessions/{session_id}/messages.jsonl`,或表示当前用户的 `viking://~/sessions/{session_id}/messages.jsonl`。旧的 `viking://session/...` 以及 `temp`、`queue` 等内部作用域会返回 `INVALID_URI`。 **Python SDK** diff --git a/docs/zh/concepts/04-viking-uri.md b/docs/zh/concepts/04-viking-uri.md index 2c8cc63031e..6495f60f45b 100644 --- a/docs/zh/concepts/04-viking-uri.md +++ b/docs/zh/concepts/04-viking-uri.md @@ -24,8 +24,7 @@ viking://{scope}/{path} | **upload** | 临时上传文件 | 临时 | 内部 | 公开 API 和 CLI 的文件系统/内容操作接受公开作用域 `resources`、`user` 和 `agent`, -以及根 URI `viking://`。`session` 保留为 user session 路径的向后兼容别名; -新 session 数据位于 `viking://user/{user_id}/sessions`。 +以及根 URI `viking://`。Session 数据位于 `viking://user/{user_id}/sessions`。 `temp`、`queue` 和 `upload` 是内部实现作用域,不能通过公开 API 的 URI 参数直接访问。 ### Home 别名 `~` @@ -160,8 +159,7 @@ viking://user/{user_id}/sessions/{session_id}/history # 归档历史 viking://~/sessions/{session_id}/ # 自己的会话(家目录别名写法) ``` -`viking://session/{session_id}` 会作为当前用户 session 路径的向后兼容别名被接受。 -它不是新会话数据的独立存储根。 +旧 URI `viking://session/{session_id}` 不再接受。 ## 路径变量 diff --git a/docs/zh/concepts/08-session.md b/docs/zh/concepts/08-session.md index 5949e9674b6..58e65cbadc5 100644 --- a/docs/zh/concepts/08-session.md +++ b/docs/zh/concepts/08-session.md @@ -252,8 +252,7 @@ viking://~/memories/ `viking://~/sessions/{session_id}` 使用家目录别名,服务端会按认证身份将其展开为 `viking://user/{user_id}/sessions/{session_id}`。无 uid 的写法 `viking://user/sessions/{session_id}` 不再被接受,请求会报错并提示改用 `viking://~/...`。 -`viking://session/{session_id}` 仍会作为同一个 session 路径的向后兼容别名被接受, -不是独立的存储根。 +旧 URI `viking://session/{session_id}` 也不再接受。 ## 相关文档 diff --git a/examples/dsh-memory-plugin/client.test.mjs b/examples/dsh-memory-plugin/client.test.mjs index ee4a7ef8046..27ec3ca3e14 100644 --- a/examples/dsh-memory-plugin/client.test.mjs +++ b/examples/dsh-memory-plugin/client.test.mjs @@ -14,7 +14,7 @@ test("client sends OpenViking identity headers and preserves response trace ids" seen = { url, init }; return new Response(JSON.stringify({ status: "ok", - result: { trace_id: "trace-123", archive_uri: "viking://session/x" }, + result: { trace_id: "trace-123", archive_uri: "viking://user/default/sessions/x" }, }), { status: 200, headers: { "Content-Type": "application/json" }, diff --git a/examples/openclaw-plugin/README_CN.md b/examples/openclaw-plugin/README_CN.md index 84ed287b33e..26414127d73 100644 --- a/examples/openclaw-plugin/README_CN.md +++ b/examples/openclaw-plugin/README_CN.md @@ -80,7 +80,7 @@ Agent 会自动完成安装 → 配置 → 重启 → 验证。详见 [INSTALL-A | `ov_list` | 在检索后列出 OpenViking 目录,补查同级切片和 `.overview.md` 文件 | | `openviking_tool_result_list` | 列出当前 session 中被外置的大工具输出 | | `openviking_tool_result_search` | 在外置工具输出中按关键词搜索 | -| `openviking_tool_result_read` | 通过 `viking://session/.../tool-results/...` ref 分页读取外置工具输出 | +| `openviking_tool_result_read` | 通过 `viking://user/{user_id}/sessions/.../tool-results/...` ref 分页读取外置工具输出 | 插件还提供手动 slash command:`/add-resource`、`/add-skill`、`/ov-search`、`/ov-recall-trace`。Agent 可见的 `add_resource` 工具默认禁用(`enableAddResourceTool=false`),避免搜索/检索阶段误触发资源导入;如确实要允许 Agent 导入资源,可显式设置 `enableAddResourceTool=true`,否则使用手动 `/add-resource`。 @@ -88,7 +88,7 @@ Agent 会自动完成安装 → 配置 → 重启 → 验证。详见 [INSTALL-A - **发送内容**:每轮 user/assistant 消息文本(已剥离注入的记忆块和元数据噪音)。 - **发送去向**:仅发往你配置的 OpenViking 服务(`baseUrl`)。插件本身只与该服务通信;服务端对 embedding、VLM 等模型的调用取决于服务端配置。 -- **存储位置**:所有数据存储在你的 OpenViking 服务上,命名空间包括 `viking://user/*`、`viking://session/*`、`viking://resources/*` 等。 +- **存储位置**:所有数据存储在你的 OpenViking 服务上,命名空间包括 `viking://user/{user_id}/*`(其中包含 sessions)和 `viking://resources/*` 等。 - **API Key**:通过 `X-API-Key` header 发送,不会被日志记录或转发。 - **多租户隔离**:支持 `accountId`、`userId`。可选的 `peer_role` / `peer_prefix` 控制是否把 OpenClaw 说话人写入 OpenViking `peer_id`,并在数据面使用 `X-OpenViking-Actor-Peer`。 @@ -139,7 +139,7 @@ openclaw config get plugins.slots.contextEngine # 应输出:openviking - OpenClaw 在左侧,仍然是主运行时;插件并不接管 agent 执行本身。 - 插件中间层把 Hook、Context Engine、Tools、Runtime Manager 四部分合并在一个注册单元里。 - 所有 HTTP 调用最终都走 `OpenVikingClient`,由 client 层统一补 `X-OpenViking-*` 头和路由日志。 -- OpenViking 服务端承接 session、memory、archive 和 Phase 2 抽取,底层存储落在 `viking://user/*`(包含 `viking://user/sessions/*`)、`viking://session/*` 和 `viking://resources/*`。 +- OpenViking 服务端承接 session、memory、archive 和 Phase 2 抽取;session 存储在 `viking://user/{user_id}/sessions/*`。 这套拆分的意义,是让 OpenClaw 继续专注推理与编排,让 OpenViking 成为长期上下文的事实源。 @@ -346,7 +346,7 @@ Resource 导入支持远程 URL、Git URL、本地文件、本地目录和 zip Recall trace 默认关闭。可通过插件配置 `traceRecall`、`traceRecallPersist`、`traceRecallDir` 等开启,然后使用 `ov_recall_trace` 或 `/ov-recall-trace` 查询。持久化 trace 默认写入 `~/.openclaw/openviking/recall-traces`,并可通过保留天数和查询上限控制扫描范围。 -当 OpenViking 将超大工具输出外置时,可见 preview 会包含 `viking://session//tool-results/` 引用。使用 `openviking_tool_result_list` 发现 ref,使用 `openviking_tool_result_search` 定位片段,再使用 `openviking_tool_result_read` 结合 `offset`/`limit` 读取原始内容。 +当 OpenViking 将超大工具输出外置时,可见 preview 会包含 `viking://user/{user_id}/sessions//tool-results/` 引用。使用 `openviking_tool_result_list` 发现 ref,使用 `openviking_tool_result_search` 定位片段,再使用 `openviking_tool_result_read` 结合 `offset`/`limit` 读取原始内容。 ## 运行模式 diff --git a/examples/openclaw-plugin/docs/openviking-openclaw-plugin-guide.md b/examples/openclaw-plugin/docs/openviking-openclaw-plugin-guide.md index 7c7e2ab1aba..1cbfe0f8dd1 100644 --- a/examples/openclaw-plugin/docs/openviking-openclaw-plugin-guide.md +++ b/examples/openclaw-plugin/docs/openviking-openclaw-plugin-guide.md @@ -209,7 +209,7 @@ transformContext auto recall 流程: ### 5.6 外置 Tool Result 回读 -当 OpenViking 服务端将大工具结果外置为 `viking://session/.../tool-results/...` 时,插件提供: +当 OpenViking 服务端将大工具结果外置为 `viking://user/{user_id}/sessions/.../tool-results/...` 时,插件提供: | 工具 | 用途 | | --- | --- | @@ -262,7 +262,7 @@ transformContext auto recall 流程: | --- | --- | --- | --- | | `POST /api/v1/search/find` | 快速语义检索,不依赖 session context | 自动召回、`memory_recall`、`ov_search`、`memory_forget` | body: `query`、`target_uri`、`limit`、`score_threshold`;返回 `memories[]`、`resources[]`、`skills[]`,每项含 `uri`、`level`、`abstract`、`score`、`category`:`client.ts:428` | | `POST /api/v1/search/search` | 带 session context 和 intent analysis 的检索 | 暂未使用 | body 可带 `session_id`;返回 `query_plan` / `query_results`。当前插件为了稳定和低延迟统一用 `find()`,session context 由插件自己组装 | -| `POST /api/v1/search/grep` | 正则/关键词内容搜索 | `ov_archive_search` | body: `uri`、`pattern`、`case_insensitive`、`node_limit`;插件限定在 `viking://session/{id}/history` 内搜 archive:`client.ts:897` | +| `POST /api/v1/search/grep` | 正则/关键词内容搜索 | `ov_archive_search` | body: `uri`、`pattern`、`case_insensitive`、`node_limit`;插件限定在 `viking://user/{user_id}/sessions/{id}/history` 内搜 archive:`client.ts:897` | | `POST /api/v1/search/glob` | glob 文件匹配 | 暂未封装 | body: `pattern`、`uri`、`node_limit`;适合按 `**/*.md`、`src/**/*.ts` 找资源路径 | #### 6.2.3 Filesystem / Content @@ -339,8 +339,8 @@ transformContext auto recall 流程: | `viking://user/memories` | 当前用户长期记忆别名 | | `viking://resources` | account/resource 知识库 | | `viking://user/skills` | 当前 agent skill 空间 | -| `viking://session/{sessionId}/history` | session archive 历史 | -| `viking://session/{sessionId}/tool-results/{id}` | 外置工具结果 | +| `viking://user/{user_id}/sessions/{sessionId}/history` | session archive 历史 | +| `viking://user/{user_id}/sessions/{sessionId}/tool-results/{id}` | 外置工具结果 | 插件通过 `viking://user/...` 写入和检索 user-scoped memory;OpenViking 会根据请求里的租户身份和 actor peer context 解析这个别名。agent 维度通过 `peer_id` / `X-OpenViking-Actor-Peer` 表达,不再使用旧 agent URI namespace。 @@ -1322,7 +1322,7 @@ python health_check_tools/ov-healthcheck.py 5. 新开一轮问“我之前偏好什么语言回复技术文档?”。 6. 观察最新 user message 是否注入 ``,或用 `memory_recall` 显式查。 7. 用 OpenViking Console/TUI 检查 `viking://user/.../memories` 是否产生 leaf memory。 -8. 对长工具输出场景,确认 preview 中有 `viking://session/.../tool-results/...`,再用 tool-result 工具读取完整内容。 +8. 对长工具输出场景,确认 preview 中有 `viking://user/{user_id}/sessions/.../tool-results/...`,再用 tool-result 工具读取完整内容。 --- diff --git a/examples/openclaw-plugin/docs/openviking-websocket-rpc-api.md b/examples/openclaw-plugin/docs/openviking-websocket-rpc-api.md index ce10d7896db..ebf3510f0cf 100644 --- a/examples/openclaw-plugin/docs/openviking-websocket-rpc-api.md +++ b/examples/openclaw-plugin/docs/openviking-websocket-rpc-api.md @@ -450,7 +450,7 @@ Inspect recall traces when `traceRecall` is enabled. "name": "openviking_tool_result_search", "sessionKey": "main", "args": { - "tool_output_ref": "viking://session//tool-results/", + "tool_output_ref": "viking://user/{user_id}/sessions//tool-results/", "query": "error", "limit": 10, "context_chars": 300 @@ -463,7 +463,7 @@ Inspect recall traces when `traceRecall` is enabled. | 字段 | 类型 | 必填 | 说明 | |------|------|------|------| -| `tool_output_ref` | string | 是 | `viking://session/.../tool-results/...` URI,也兼容 `ref` 或 `uri` | +| `tool_output_ref` | string | 是 | `viking://user/{user_id}/sessions/.../tool-results/...` URI,也兼容 `ref` 或 `uri` | | `query` | string | 是 | 搜索关键词或精确文本 | | `limit` | number | 否 | 最多匹配数,默认 20 | | `context_chars` | number | 否 | 每个命中周围保留字符数,默认 300,也兼容 `contextChars` | @@ -481,7 +481,7 @@ Inspect recall traces when `traceRecall` is enabled. "name": "openviking_tool_result_read", "sessionKey": "main", "args": { - "tool_output_ref": "viking://session//tool-results/", + "tool_output_ref": "viking://user/{user_id}/sessions//tool-results/", "offset": 0, "limit": 4000 } @@ -493,7 +493,7 @@ Inspect recall traces when `traceRecall` is enabled. | 字段 | 类型 | 必填 | 说明 | |------|------|------|------| -| `tool_output_ref` | string | 是 | `viking://session/.../tool-results/...` URI,也兼容 `ref` 或 `uri` | +| `tool_output_ref` | string | 是 | `viking://user/{user_id}/sessions/.../tool-results/...` URI,也兼容 `ref` 或 `uri` | | `offset` | number | 否 | 起始字符偏移,默认 0 | | `limit` | number | 否 | 最多返回字符数 | diff --git a/examples/openclaw-plugin/memory-ranking.ts b/examples/openclaw-plugin/memory-ranking.ts index 38cbad323db..be7aaa06666 100644 --- a/examples/openclaw-plugin/memory-ranking.ts +++ b/examples/openclaw-plugin/memory-ranking.ts @@ -231,7 +231,7 @@ function lexicalOverlapBoost(tokens: string[], text: string, maxBoost = DEFAULT_ function inferResourceType(item: FindResultItem): string | undefined { if (item.uri.startsWith("viking://resources")) return "resource"; - if (item.uri.startsWith("viking://session/")) return "session"; + if (/^viking:\/\/(?:user\/[^/]+|~)\/sessions(?:\/|$)/.test(item.uri)) return "session"; if (item.uri.startsWith("viking://user/skills") || item.uri.startsWith("viking://~/skills") || item.uri.startsWith("viking://skills")) return "agent"; if (item.uri.startsWith("viking://user/") || item.uri.startsWith("viking://~/")) return "user"; return undefined; diff --git a/examples/openclaw-plugin/plugin/openviking-archive-tools.ts b/examples/openclaw-plugin/plugin/openviking-archive-tools.ts index 6bb11a21a8c..6b336bf2c84 100644 --- a/examples/openclaw-plugin/plugin/openviking-archive-tools.ts +++ b/examples/openclaw-plugin/plugin/openviking-archive-tools.ts @@ -150,7 +150,7 @@ export function registerOpenVikingArchiveTools(deps: OpenVikingArchiveToolsDeps) trigger: { query, derivedKeywords: [query] }, searches: [{ resourceType: "archive", - targetUriResolved: archiveId ? `viking://session/${ovSessionId}/history/${archiveId}` : `viking://session/${ovSessionId}/history`, + targetUriResolved: archiveId ? `viking://~/sessions/${ovSessionId}/history/${archiveId}` : `viking://~/sessions/${ovSessionId}/history`, limit: deps.traceRecallMaxResultsPerSearch, durationMs: Date.now() - started, total: result.matches?.length ?? result.count ?? 0, diff --git a/examples/openclaw-plugin/plugin/openviking-recall-trace-runtime.ts b/examples/openclaw-plugin/plugin/openviking-recall-trace-runtime.ts index e24468ce05d..8fe3090e791 100644 --- a/examples/openclaw-plugin/plugin/openviking-recall-trace-runtime.ts +++ b/examples/openclaw-plugin/plugin/openviking-recall-trace-runtime.ts @@ -119,7 +119,7 @@ function toLimitedInteger(value: unknown, fallback: number, min: number, max: nu function inferUriType(uri: string): string { if (uri.startsWith("viking://resources") || uri.startsWith("viking://resource")) return "resource"; - if (uri.startsWith("viking://session/")) return "session"; + if (/^viking:\/\/(?:user\/[^/]+|~)\/sessions(?:\/|$)/.test(uri)) return "session"; if (uri.startsWith("viking://user/skills") || uri.startsWith("viking://~/skills") || uri.startsWith("viking://skills")) return "skill"; if (uri.startsWith("viking://user/") || uri.startsWith("viking://~/")) return "user_memory"; if (uri.includes("/archive") || uri.includes("/history/")) return "archive"; diff --git a/examples/openclaw-plugin/plugin/openviking-tool-result-tools.ts b/examples/openclaw-plugin/plugin/openviking-tool-result-tools.ts index d1896d29943..2227ec7a0c0 100644 --- a/examples/openclaw-plugin/plugin/openviking-tool-result-tools.ts +++ b/examples/openclaw-plugin/plugin/openviking-tool-result-tools.ts @@ -78,7 +78,7 @@ export function parseToolResultRef(value: unknown): ToolResultRef | null { if (!raw) { return null; } - const match = raw.match(/^viking:\/\/session\/([^/]+)\/tool-results\/([^/?#]+)(?:[?#].*)?$/); + const match = raw.match(/^viking:\/\/(?:user\/[^/]+|~)\/sessions\/([^/]+)\/tool-results\/([^/?#]+)(?:[?#].*)?$/); if (!match) { return null; } @@ -90,7 +90,7 @@ export function parseToolResultRef(value: unknown): ToolResultRef | null { return { sessionId, toolResultId, - ref: `viking://session/${encodeURIComponent(sessionId)}/tool-results/${encodeURIComponent(toolResultId)}`, + ref: raw.split(/[?#]/, 1)[0]!, }; } @@ -120,14 +120,14 @@ export function registerOpenVikingToolResultTools({ description: "Restore the full original content of a tool result that was externalized by OpenViking. " + "Use when a previous tool result was externalized and only a preview is visible — " + - "the preview contains a [tool-result-ref] or viking://session/.../tool-results/... URI. " + + "the preview contains a [tool-result-ref] or viking://user/.../sessions/.../tool-results/... URI. " + "\"Read\" tool returns the same truncated preview; this tool returns the complete content. " + "To read all content: pass offset=0 and a limit large enough to cover the whole result " + "(e.g. limit=100000). Use offset/limit for paging only when you need a specific section.", parameters: Type.Object({ tool_output_ref: Type.String({ description: - "Exact OV URI from the preview, e.g. viking://session//tool-results/", + "Exact OV URI from the preview, e.g. viking://user//sessions//tool-results/", }), offset: Type.Optional(Type.Number({ description: "Unicode character offset. Default: 0" })), limit: Type.Optional(Type.Number({ description: "Maximum Unicode characters to read. Default: 20000" })), @@ -147,7 +147,7 @@ export function registerOpenVikingToolResultTools({ const parsed = parseToolResultRef(params.tool_output_ref ?? params.ref ?? params.uri); if (!parsed) { return { - content: [{ type: "text", text: "Error: tool_output_ref must be a viking://session/.../tool-results/... URI." }], + content: [{ type: "text", text: "Error: tool_output_ref must be a viking://user/.../sessions/.../tool-results/... URI." }], details: { error: "invalid_tool_output_ref" }, }; } @@ -221,7 +221,7 @@ export function registerOpenVikingToolResultTools({ parameters: Type.Object({ tool_output_ref: Type.String({ description: - "Exact OV URI from the preview, e.g. viking://session//tool-results/", + "Exact OV URI from the preview, e.g. viking://user//sessions//tool-results/", }), query: Type.String({ description: "Keyword or exact text to search for" }), limit: Type.Optional(Type.Number({ description: "Maximum matches. Default: 20" })), @@ -242,7 +242,7 @@ export function registerOpenVikingToolResultTools({ const parsed = parseToolResultRef(params.tool_output_ref ?? params.ref ?? params.uri); if (!parsed) { return { - content: [{ type: "text", text: "Error: tool_output_ref must be a viking://session/.../tool-results/... URI." }], + content: [{ type: "text", text: "Error: tool_output_ref must be a viking://user/.../sessions/.../tool-results/... URI." }], details: { error: "invalid_tool_output_ref" }, }; } diff --git a/examples/openclaw-plugin/skills/install-openviking-memory/SKILL.md b/examples/openclaw-plugin/skills/install-openviking-memory/SKILL.md index 162f99dce11..21ab175eed9 100644 --- a/examples/openclaw-plugin/skills/install-openviking-memory/SKILL.md +++ b/examples/openclaw-plugin/skills/install-openviking-memory/SKILL.md @@ -587,7 +587,7 @@ Requires `traceRecall=true`; persisted lookup also requires `traceRecallPersist= ### Externalized Tool Result Tools -Use these when a preview contains a `viking://session//tool-results/` ref. +Use these when a preview contains a `viking://user/{user_id}/sessions//tool-results/` ref. | Tool | Parameters | |---|---| diff --git a/examples/openclaw-plugin/skills/openviking-context-database/SKILL.md b/examples/openclaw-plugin/skills/openviking-context-database/SKILL.md index 18b9e12657c..61ed7f498c7 100644 --- a/examples/openclaw-plugin/skills/openviking-context-database/SKILL.md +++ b/examples/openclaw-plugin/skills/openviking-context-database/SKILL.md @@ -242,7 +242,7 @@ Trace records exist only when `traceRecall=true`; persisted lookup requires `tra ### Externalized tool-result tools -Use when a preview contains `viking://session//tool-results/`. +Use when a preview contains `viking://user/{user_id}/sessions//tool-results/`. | Tool | Parameters | |---|---| diff --git a/examples/openclaw-plugin/tests/ut/plugin-modules.test.ts b/examples/openclaw-plugin/tests/ut/plugin-modules.test.ts index 0ee2bc58d05..1fc4ed52e19 100644 --- a/examples/openclaw-plugin/tests/ut/plugin-modules.test.ts +++ b/examples/openclaw-plugin/tests/ut/plugin-modules.test.ts @@ -585,7 +585,7 @@ describe("plugin module seams", () => { const readFactory = registerTool.mock.calls[0]?.[0]; const readTool = readFactory({ sessionId: "session-1" }); const result = await readTool.execute("call-1", { - tool_output_ref: "viking://session/ov-session-1/tool-results/tr_1", + tool_output_ref: "viking://user/default/sessions/ov-session-1/tool-results/tr_1", }); expect(readToolResult).toHaveBeenCalledWith( @@ -603,7 +603,7 @@ describe("plugin module seams", () => { const grepSessionArchives = vi.fn().mockResolvedValue({ count: 1, matches: [{ - uri: "viking://session/ov-session-1/history/archive_001#L12", + uri: "viking://user/default/sessions/ov-session-1/history/archive_001#L12", line: 12, content: "important command output", }], diff --git a/examples/openclaw-plugin/tests/ut/tool-round-trip.test.ts b/examples/openclaw-plugin/tests/ut/tool-round-trip.test.ts index f9dc9170e5d..8cf6b48d349 100644 --- a/examples/openclaw-plugin/tests/ut/tool-round-trip.test.ts +++ b/examples/openclaw-plugin/tests/ut/tool-round-trip.test.ts @@ -145,7 +145,7 @@ describe("convertToAgentMessages: structured tool round-trip", () => { tool_status: "completed", tool_input: { path: "/tmp/big.txt" }, tool_output: "preview only", - tool_output_ref: "viking://session/s1/tool-results/tr_call_big_abc", + tool_output_ref: "viking://user/default/sessions/s1/tool-results/tr_call_big_abc", tool_output_original_chars: 120000, }, ], @@ -155,7 +155,7 @@ describe("convertToAgentMessages: structured tool round-trip", () => { const toolResult = result[1] as Record; const content = toolResult.content as Array>; expect(content[0]!.text).toContain("preview only"); - expect(content[0]!.text).toContain("viking://session/s1/tool-results/tr_call_big_abc"); + expect(content[0]!.text).toContain("viking://user/default/sessions/s1/tool-results/tr_call_big_abc"); expect(content[0]!.text).toContain("original_chars=120000"); }); diff --git a/examples/openclaw-plugin/tests/ut/tools.test.ts b/examples/openclaw-plugin/tests/ut/tools.test.ts index 6d0fdfbdab5..a04026e2673 100644 --- a/examples/openclaw-plugin/tests/ut/tools.test.ts +++ b/examples/openclaw-plugin/tests/ut/tools.test.ts @@ -711,7 +711,7 @@ describe("Tool: OpenViking tool result access", () => { total_chars: 42, has_more: true, metadata: { - storage_uri: "viking://session/test-session/tool-results/tr_call_abc", + storage_uri: "viking://user/default/sessions/test-session/tool-results/tr_call_abc", tool_name: "read_file", }, }); @@ -723,7 +723,7 @@ describe("Tool: OpenViking tool result access", () => { const tool = tools.get("openviking_tool_result_read")!; const result = await tool.execute("tc-read", { - tool_output_ref: "viking://session/test-session/tool-results/tr_call_abc", + tool_output_ref: "viking://user/default/sessions/test-session/tool-results/tr_call_abc", offset: 5, limit: 10, }) as ToolResult; @@ -731,7 +731,7 @@ describe("Tool: OpenViking tool result access", () => { expect(result.content[0]!.text).toBe("raw"); expect(result.details).toMatchObject({ action: "read", - tool_output_ref: "viking://session/test-session/tool-results/tr_call_abc", + tool_output_ref: "viking://user/default/sessions/test-session/tool-results/tr_call_abc", tool_result_id: "tr_call_abc", offset: 5, limit: 10, @@ -766,7 +766,7 @@ describe("Tool: OpenViking tool result access", () => { const tool = tools.get("openviking_tool_result_search")!; const result = await tool.execute("tc-search", { - tool_output_ref: "viking://session/test-session/tool-results/tr_call_abc", + tool_output_ref: "viking://user/default/sessions/test-session/tool-results/tr_call_abc", query: "needle", limit: 2, context_chars: 15, @@ -777,7 +777,7 @@ describe("Tool: OpenViking tool result access", () => { expect(result.content[0]!.text).toContain("hay needle stack"); expect(result.details).toMatchObject({ action: "searched", - tool_output_ref: "viking://session/test-session/tool-results/tr_call_abc", + tool_output_ref: "viking://user/default/sessions/test-session/tool-results/tr_call_abc", tool_result_id: "tr_call_abc", query: "needle", match_count: 1, @@ -793,7 +793,7 @@ describe("Tool: OpenViking tool result access", () => { tool_results: [ { tool_result_id: "tr_call_abc", - storage_uri: "viking://session/test-session/tool-results/tr_call_abc", + storage_uri: "viking://user/default/sessions/test-session/tool-results/tr_call_abc", tool_name: "read_file", original_chars: 42000, created_at: "2026-05-15T00:00:00Z", @@ -814,7 +814,7 @@ describe("Tool: OpenViking tool result access", () => { expect(result.content[0]!.text).toContain("read_file"); expect(result.content[0]!.text).toContain("original_chars=42000"); - expect(result.content[0]!.text).toContain("viking://session/test-session/tool-results/tr_call_abc"); + expect(result.content[0]!.text).toContain("viking://user/default/sessions/test-session/tool-results/tr_call_abc"); expect(result.details).toMatchObject({ action: "listed", session_id: "test-session", @@ -829,7 +829,7 @@ describe("Tool: OpenViking tool result access", () => { const tool = tools.get("openviking_tool_result_read")!; const result = await tool.execute("tc-read", { - tool_output_ref: "viking://session/other-session/tool-results/tr_call_abc", + tool_output_ref: "viking://user/default/sessions/other-session/tool-results/tr_call_abc", }) as ToolResult; expect(result.content[0]!.text).toContain("another session"); @@ -2021,7 +2021,7 @@ describe("Tool: ov_recall_trace", () => { return okResponse({ matches: [{ line: 12, - uri: "viking://session/test-session/history/archive_001#L12", + uri: "viking://user/default/sessions/test-session/history/archive_001#L12", content: "discussion about recall traces", }], count: 1, @@ -2045,7 +2045,7 @@ describe("Tool: ov_recall_trace", () => { const entry = (result.details.entries as any[])[0]; expect(entry.operationType).toBe("archive_grep"); expect(entry.selected).toEqual(expect.arrayContaining([ - expect.objectContaining({ uri: "viking://session/test-session/history/archive_001#L12", displayed: true }), + expect.objectContaining({ uri: "viking://user/default/sessions/test-session/history/archive_001#L12", displayed: true }), ])); }); }); diff --git a/examples/pi-experimental-context-management/CONTEXT-WINDOW.md b/examples/pi-experimental-context-management/CONTEXT-WINDOW.md index da91a555e95..c5b0c513764 100644 --- a/examples/pi-experimental-context-management/CONTEXT-WINDOW.md +++ b/examples/pi-experimental-context-management/CONTEXT-WINDOW.md @@ -626,9 +626,9 @@ summarizer. `/.overview.md` and, as a secondary signal, `GET /tasks/{id}`. `GET /sessions/{id}/context` is not used for waiting — right after a commit it still returns the previous overview. -- **No `viking://~` alias.** The server rejects it with `Invalid scope '~'`. - URIs come from `GET /sessions/{id}`'s `uri` field (cached) or from the - commit's `archive_uri`; the fallback is the legacy `viking://session/{id}`. +- Session URIs come from `GET /sessions/{id}`'s `uri` field (cached) or from the + commit's `archive_uri`; the fallback is the current user's + `viking://~/sessions/{id}` home alias. - **`ctx.getContextUsage()` is stale for one turn after a reset.** It counts the untransformed session, so the core ignores it while `awaitingFirstObservation` is set and reports its own estimate as diff --git a/examples/pi-experimental-context-management/client.ts b/examples/pi-experimental-context-management/client.ts index 764d8621c33..f3dbb4eaec0 100644 --- a/examples/pi-experimental-context-management/client.ts +++ b/examples/pi-experimental-context-management/client.ts @@ -323,11 +323,8 @@ export class OVClient { * Session root URI, e.g. `viking://user/default/sessions/pi-abc`. * * Reads the canonical `uri` from `GET /api/v1/sessions/{id}` and caches it. - * When the server does not answer (or answers without a `viking://` uri) this - * falls back to the legacy alias `viking://session/{id}`, which the target - * server still accepts. The fallback is deliberately NOT cached so a later - * call can still pick up the canonical URI. Note the `viking://~` alias is - * rejected by the server ("Invalid scope '~'") and is never produced here. + * If the metadata request fails, use the current user's home alias. The + * fallback is not cached so a later call can still pick up the canonical URI. */ async sessionRootUri(sessionId: string): Promise { const id = String(sessionId ?? ""); @@ -341,9 +338,9 @@ export class OVClient { return uri; } } catch { - // fall through to the legacy alias + // fall through to the home alias } - return `viking://session/${id}`; + return `viking://~/sessions/${id}`; } /** Strip `/history/archive_NNN` off a commit's `archive_uri` to get the session root. */ diff --git a/examples/pi-experimental-context-management/scripts/e2e-window.mjs b/examples/pi-experimental-context-management/scripts/e2e-window.mjs index 3507370472b..9898666332f 100755 --- a/examples/pi-experimental-context-management/scripts/e2e-window.mjs +++ b/examples/pi-experimental-context-management/scripts/e2e-window.mjs @@ -420,7 +420,7 @@ async function sessionRootUri(ovSessionId) { const res = await ovFetch(`/api/v1/sessions/${encodeURIComponent(ovSessionId)}`); const uri = typeof res.body?.result?.uri === "string" ? res.body.result.uri.trim() : ""; if (uri.startsWith("viking://")) return uri.replace(/\/+$/, ""); - return `viking://session/${ovSessionId}`; + return `viking://~/sessions/${ovSessionId}`; } /** Archive directories under `/history`, newest first. */ diff --git a/examples/pi-experimental-context-management/tools.ts b/examples/pi-experimental-context-management/tools.ts index c0a17e0142a..a2ef7987cd6 100644 --- a/examples/pi-experimental-context-management/tools.ts +++ b/examples/pi-experimental-context-management/tools.ts @@ -26,7 +26,7 @@ export function registerTools(pi: any, client: OVClient, sync?: SyncManager): vo // so the examples name the two forms it does accept. description: "Viking URI prefix to scope search, e.g. 'viking://user//memories/' " + - "or 'viking://session//'", + "or 'viking://~/sessions//'", })), limit: Type.Optional(Type.Number({ description: "Max results (default: 10)" })), }), diff --git a/openviking/core/namespace.py b/openviking/core/namespace.py index 7cdef532933..e469f0a133d 100644 --- a/openviking/core/namespace.py +++ b/openviking/core/namespace.py @@ -176,8 +176,6 @@ def canonical_session_uri(ctx: RequestContext, session_id: Optional[str] = None) def is_session_uri(uri: str) -> bool: parts = uri_parts(uri) - if parts[:1] == ["session"]: - return True return len(parts) >= 3 and parts[0] == "user" and parts[2] == "sessions" @@ -258,14 +256,14 @@ def resolve_uri( def resolve_request_uri(uri: str, ctx: RequestContext) -> str: """Resolve supported URI aliases at an authenticated request boundary. - Supported aliases are the ``~`` home alias and the legacy ``session`` scope. + The ``~`` home alias resolves to the authenticated user's namespace. The uid-less ``viking://user/`` shorthand is no longer expanded: it fails closed with a hint pointing at ``viking://~/...``. """ # Every authenticated request context carries an effective user identity, # including ROOT contexts produced by dev, API-key, and trusted auth modes. - # Resolve only the unambiguous home alias for every role; preserve the - # existing role-dependent handling of legacy/ambiguous spellings below. + # Resolve the home alias for every role; keep the role-dependent handling + # of ambiguous uid-less user paths below. parts = uri_parts(uri) if parts and parts[0] == "~": return resolve_current_user_uri(uri, ctx) @@ -277,8 +275,7 @@ def resolve_request_uri(uri: str, ctx: RequestContext) -> str: def resolve_current_user_uri(uri: str, ctx: RequestContext) -> str: """Resolve a URI field whose contract explicitly denotes the current user. - Supported aliases are ``viking://~`` (the home alias) and the legacy - ``viking://session/...`` scope. ``viking://user/`` used to + The supported alias is ``viking://~``. ``viking://user/`` used to expand to the caller's space; it now fails closed with a corrective hint, because the same spelling is a valid explicit-uid URI for a user literally named after the reserved segment. @@ -292,14 +289,6 @@ def resolve_current_user_uri(uri: str, ctx: RequestContext) -> str: return canonical_user_root(ctx) return f"{canonical_user_root(ctx)}/{'/'.join(parts[1:])}" - if parts[0] == "session": - if len(parts) == 1: - return canonical_session_root(ctx) - canonical = canonical_session_uri(ctx, parts[1]) - if len(parts) > 2: - canonical = f"{canonical}/{'/'.join(parts[2:])}" - return canonical - if ( parts[0] == "user" and len(parts) >= 2 diff --git a/openviking/core/uri_validation.py b/openviking/core/uri_validation.py index 5267fa2593b..3cb01f90989 100644 --- a/openviking/core/uri_validation.py +++ b/openviking/core/uri_validation.py @@ -14,10 +14,10 @@ from openviking_cli.exceptions import InvalidURIError, PermissionDeniedError from openviking_cli.utils.uri import VikingURI -_PUBLIC_API_SCOPES = frozenset( - {"", *VikingURI.PUBLIC_SCOPES, *VikingURI.LEGACY_SCOPES, *VikingURI.ALIAS_SCOPES} +_PUBLIC_API_SCOPES = frozenset({"", *VikingURI.PUBLIC_SCOPES, *VikingURI.ALIAS_SCOPES}) +_ALL_API_SCOPES = frozenset( + {"", *VikingURI.PUBLIC_SCOPES, *VikingURI.INTERNAL_SCOPES, *VikingURI.ALIAS_SCOPES} ) -_ALL_API_SCOPES = frozenset({"", *VikingURI.VISITABLE_SCOPES}) def _allowed_api_scopes( diff --git a/openviking/storage/viking_fs/_access.py b/openviking/storage/viking_fs/_access.py index 41163a0e3d5..d0a4f5a788b 100644 --- a/openviking/storage/viking_fs/_access.py +++ b/openviking/storage/viking_fs/_access.py @@ -4,7 +4,6 @@ import hashlib import inspect -import json import re from contextlib import contextmanager from typing import Any, Callable, Dict, List, Mapping, Optional, Sequence, Union @@ -587,17 +586,8 @@ async def _iter_visible_tree_entries( ): """Yield one visible tree page after namespace and ACL filtering.""" real_ctx = self._ctx_or_default(ctx) - primary_path = self._uri_to_path(uri, ctx=ctx) - path: Optional[str] = None - for candidate_path in self._read_paths(uri, ctx=ctx): - if not await self._read_path_visible(uri, candidate_path, primary_path, real_ctx): - continue - if await self._agfs_path_exists(candidate_path): - path = candidate_path - break - if path is None: - if self._is_session_root_uri(uri): - return + path = self._uri_to_path(uri, ctx=ctx) + if not await self._agfs_path_exists(path): raise NotFoundError(uri, "directory") if node_limit == 0: @@ -633,8 +623,6 @@ async def _iter_visible_tree_entries( acl_enabled=acl_enabled, ): continue - if not await self._read_path_visible(uri, entry["path"], primary_path, real_ctx): - continue entry_uri = self._alias_uri_for_path( request_uri=uri, base_path=path, @@ -731,64 +719,6 @@ def _uri_to_path(self, uri: str, ctx: Optional[RequestContext] = None) -> str: safe_parts = [self._shorten_component(p, self._MAX_FILENAME_BYTES) for p in parts] return f"/local/{account_id}/{'/'.join(safe_parts)}" - def _legacy_session_path(self, uri: str, ctx: Optional[RequestContext] = None) -> str: - """Map a legacy viking://session URI to its pre-user-namespace path.""" - real_ctx = self._ctx_or_default(ctx) - parts = self._safe_uri_parts(uri) - safe_parts = [self._shorten_component(p, self._MAX_FILENAME_BYTES) for p in parts] - return f"/local/{real_ctx.account_id}/{'/'.join(safe_parts)}" - - def _legacy_user_session_path( - self, uri: str, ctx: Optional[RequestContext] = None - ) -> Optional[str]: - """Return the legacy nested /session/{user_id}/{session_id} candidate.""" - real_ctx = self._ctx_or_default(ctx) - parts = self._safe_uri_parts(uri) - if len(parts) <= 3 or parts[0] != "user" or parts[2] != "sessions": - return None - nested_parts = ["session", parts[1], *parts[3:]] - safe_parts = [self._shorten_component(p, self._MAX_FILENAME_BYTES) for p in nested_parts] - return f"/local/{real_ctx.account_id}/{'/'.join(safe_parts)}" - - def _legacy_session_alias(self, uri: str) -> Optional[str]: - """Return the old storage alias for a canonical user session URI.""" - parts = self._safe_uri_parts(uri) - if len(parts) < 3 or parts[0] != "user" or parts[2] != "sessions": - return None - suffix = parts[3:] - return "viking://session" + (f"/{'/'.join(suffix)}" if suffix else "") - - def _is_session_root_uri(self, uri: str) -> bool: - return self._legacy_session_alias(uri) == "viking://session" - - 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)] - - legacy_uri = self._legacy_session_alias(uri) - if legacy_uri: - for candidate in ( - self._legacy_session_path(legacy_uri, ctx=ctx), - self._legacy_user_session_path(uri, ctx=ctx), - ): - if candidate and candidate not in paths: - paths.append(candidate) - return paths - - async def _read_path_visible( - self, - request_uri: str, - path: str, - primary_path: str, - ctx: RequestContext, - ) -> bool: - if path == primary_path: - return True - if self._legacy_session_alias(request_uri): - owner_user_id = self._safe_uri_parts(request_uri)[1] - return await self._legacy_session_path_visible(path, owner_user_id=owner_user_id) - return True - def _alias_uri_for_path( self, *, @@ -804,8 +734,6 @@ def _alias_uri_for_path( if entry_path.startswith(base): separator = "" if request_root.endswith("://") else "/" candidate_uri = request_root if not rel_path else f"{request_root}{separator}{rel_path}" - if self._legacy_session_alias(request_uri): - return candidate_uri if preserve_request_alias: return candidate_uri try: @@ -824,152 +752,6 @@ async def _agfs_path_exists(self, path: str) -> bool: return False raise - async def _looks_like_legacy_session_dir(self, path: str) -> bool: - for leaf in (".meta.json", "messages.jsonl", "history", "tool-results", "tools"): - if await self._agfs_path_exists(f"{path}/{leaf}"): - return True - return False - - async def _legacy_session_owner(self, session_root_path: str) -> str: - try: - raw = self._handle_agfs_read( - await self._async_agfs.read(f"{session_root_path}/.meta.json") - ) - except Exception as exc: - if is_not_found_error(exc): - return "" - raise - try: - data = json.loads(self._decode_bytes(raw)) - except json.JSONDecodeError: - return "" - 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 _legacy_session_visible( - self, - session_root_path: str, - ctx: RequestContext, - *, - owner_hint: Optional[str] = None, - ) -> bool: - if ctx.role == Role.ROOT: - return True - owner = await self._legacy_session_owner(session_root_path) - if owner: - return owner == ctx.user.user_id - if owner_hint: - return owner_hint == ctx.user.user_id - return True - - async def _legacy_session_path_visible( - self, - path: str, - *, - owner_user_id: str, - ) -> bool: - parts = [p for p in path.strip("/").split("/") if p] - try: - session_index = parts.index("session") - except ValueError: - return True - suffix = parts[session_index + 1 :] - if not suffix: - return True - - root_prefix = "/" + "/".join(parts[: session_index + 1]) - direct_root = f"{root_prefix}/{suffix[0]}" - if await self._looks_like_legacy_session_dir(direct_root): - owner = await self._legacy_session_owner(direct_root) - return bool(owner) and owner == owner_user_id - - if len(suffix) >= 2: - if suffix[0] != owner_user_id: - return False - nested_root = f"{root_prefix}/{suffix[0]}/{suffix[1]}" - if await self._looks_like_legacy_session_dir(nested_root): - owner = await self._legacy_session_owner(nested_root) - return not owner or owner == owner_user_id - return True - - async def _legacy_session_root_items( - self, - path: str, - ctx: RequestContext, - output_root_uri: str, - owner_user_id: str, - ) -> List[tuple[Dict[str, Any], str]]: - try: - entries = await self._ls_entries(path) - except Exception as exc: - if is_not_found_error(exc): - return [] - raise - - items: List[tuple[Dict[str, Any], str]] = [] - for entry in entries: - name = entry.get("name", "") - if not name or name in {".", ".."} or not entry.get("isDir"): - continue - child_path = f"{path.rstrip('/')}/{name}" - if await self._looks_like_legacy_session_dir(child_path): - legacy_owner = await self._legacy_session_owner(child_path) - if legacy_owner == owner_user_id: - items.append((entry, f"{output_root_uri}/{name}")) - continue - - if name != owner_user_id: - continue - try: - nested_entries = await self._ls_entries(child_path) - except Exception as exc: - if is_not_found_error(exc): - continue - raise - for nested in nested_entries: - nested_name = nested.get("name", "") - if not nested_name or nested_name in {".", ".."} or not nested.get("isDir"): - continue - nested_path = f"{child_path.rstrip('/')}/{nested_name}" - if not await self._looks_like_legacy_session_dir(nested_path): - continue - if await self._legacy_session_visible(nested_path, ctx, owner_hint=name): - items.append((nested, f"{output_root_uri}/{nested_name}")) - return items - - async def _session_root_items( - self, - uri: str, - ctx: RequestContext, - ) -> List[tuple[Dict[str, Any], str]]: - primary_path = self._uri_to_path(uri, ctx=ctx) - output_root_uri = uri.rstrip("/") - owner_user_id = self._safe_uri_parts(uri)[1] - by_name: Dict[str, tuple[Dict[str, Any], str]] = {} - try: - for entry in await self._ls_entries(primary_path, ctx=ctx): - name = entry.get("name", "") - if not name or name in {".", ".."}: - continue - by_name[name] = (entry, f"{output_root_uri}/{name}") - except Exception as exc: - if not is_not_found_error(exc): - raise - - legacy_path = self._legacy_session_path("viking://session", ctx=ctx) - for entry, entry_uri in await self._legacy_session_root_items( - legacy_path, ctx, output_root_uri, owner_user_id - ): - name = entry.get("name", "") - if name and name not in by_name: - by_name[name] = (entry, entry_uri) - return list(by_name.values()) - async def _list_read_path_items( self, uri: str, @@ -980,58 +762,37 @@ async def _list_read_path_items( ctx: Optional[RequestContext] = None, ) -> tuple[List[tuple[Dict[str, Any], str]], int, bool]: """Return one mapped RagFS page, consumed count, and exhaustion state.""" - real_ctx = self._ctx_or_default(ctx) - if self._is_session_root_uri(uri): - items = await self._session_root_items(uri, real_ctx) - return items, len(items), True - - primary_path = self._uri_to_path(uri, ctx=ctx) - merge_paths = self._legacy_session_alias(uri) is not None - found_path = False - last_not_found: Optional[Exception] = None - by_uri: Dict[str, tuple[Dict[str, Any], str]] = {} - raw_count = 0 - - for path in self._read_paths(uri, ctx=ctx): - try: - entries = await self._ls_entries( - path, - offset=0 if merge_paths else raw_offset, - limit=None if merge_paths else raw_limit, - sort_by=sort_by, - sort_order=sort_order, - filter_internal=False, - ctx=ctx, - ) - except Exception as exc: - if is_not_found_error(exc): - last_not_found = exc - continue - raise - - # Missing legacy directories need no owner probes. Check visibility - # before merging entries from a directory that actually exists. - if not await self._read_path_visible(uri, path, primary_path, real_ctx): - continue + path = self._uri_to_path(uri, ctx=ctx) + try: + raw_entries = await self._ls_entries( + path, + offset=raw_offset, + limit=raw_limit, + sort_by=sort_by, + sort_order=sort_order, + filter_internal=False, + ctx=ctx, + ) + except Exception as exc: + if is_not_found_error(exc): + raise NotFoundError(uri, "directory") from exc + raise - found_path = True - raw_count += len(entries) - entries = self._filter_ls_entries(path, entries) - for entry in entries: - entry_uri = self._alias_uri_for_path( + entries = self._filter_ls_entries(path, raw_entries) + items = [ + ( + entry, + self._alias_uri_for_path( request_uri=uri, base_path=path, entry_path=f"{path.rstrip('/')}/{entry.get('name', '')}", ctx=ctx, - ) - by_uri.setdefault(entry_uri, (entry, entry_uri)) - if not merge_paths: - break - - if found_path: - exhausted = raw_limit is None or merge_paths or raw_count < raw_limit - return list(by_uri.values()), raw_count, exhausted - raise NotFoundError(uri, "directory") from last_not_found + ), + ) + for entry in entries + ] + exhausted = raw_limit is None or len(raw_entries) < raw_limit + return items, len(raw_entries), exhausted def _path_to_uri(self, path: str, ctx: Optional[RequestContext] = None) -> str: """/local/{account}/... -> viking://... diff --git a/openviking/storage/viking_fs/_grep.py b/openviking/storage/viking_fs/_grep.py index b9c88fc21f0..8b60b646e5b 100644 --- a/openviking/storage/viking_fs/_grep.py +++ b/openviking/storage/viking_fs/_grep.py @@ -292,11 +292,7 @@ async def _grep_fs( after_context=0, ): """Filesystem grep path: prefer native agfs grep and fall back if unavailable.""" - native_safe = ( - content_transform is None - and allowed_uris is None - and await self._session_native_grep_safe(uri, ctx) - ) + native_safe = content_transform is None and allowed_uris is None if native_safe: try: # Session grep historically used the Python fallback, where @@ -336,37 +332,6 @@ async def _grep_fs( after_context=after_context, ) - async def _session_native_grep_safe(self, uri: str, ctx: Optional[RequestContext]) -> bool: - """Return whether native grep sees every visible path for ``uri``. - - Canonical session reads merge the current user namespace with two - historical storage layouts. Native AGFS grep accepts one physical - root, so it is complete only when no visible legacy candidate exists. - """ - legacy_uri = self._legacy_session_alias(uri) - if legacy_uri is None: - return True - - real_ctx = self._ctx_or_default(ctx) - if self._is_session_root_uri(uri): - primary_path = self._uri_to_path(uri, ctx=ctx) - if not await self._agfs_path_exists(primary_path): - return False - legacy_path = self._legacy_session_path(legacy_uri, ctx=ctx) - owner_user_id = self._safe_uri_parts(uri)[1] - legacy_items = await self._legacy_session_root_items( - legacy_path, real_ctx, uri.rstrip("/"), owner_user_id - ) - return not legacy_items - - primary_path = self._uri_to_path(uri, ctx=ctx) - for path in self._read_paths(uri, ctx=ctx)[1:]: - if not await self._agfs_path_exists(path): - continue - if await self._read_path_visible(uri, path, primary_path, real_ctx): - return False - return True - async def _grep_vikingdb_then_fs( self, uri, diff --git a/openviking/storage/viking_fs/_ops.py b/openviking/storage/viking_fs/_ops.py index 2e0e9f8c36f..8ddd1fd7ba7 100644 --- a/openviking/storage/viking_fs/_ops.py +++ b/openviking/storage/viking_fs/_ops.py @@ -148,25 +148,17 @@ async def read( real_ctx = self._ctx_or_default(ctx) uri = await self.resolve_uri(uri, real_ctx) await self._ensure_access(uri, ctx) - primary_path = self._uri_to_path(uri, ctx=ctx) + path = self._uri_to_path(uri, ctx=ctx) # Decryption + offset/size slicing now happen inside the ragfs encryption layer # (when configured); the plaintext stack reads bytes directly. Either way, pass the # offset/size through and let the Rust layer return the requested slice. - last_not_found: Optional[Exception] = None - for path in self._read_paths(uri, ctx=ctx): - if not await self._read_path_visible(uri, path, primary_path, real_ctx): - continue - try: - result = await self._async_agfs.read(path, offset, size) - break - except Exception as exc: - if is_not_found_error(exc): - last_not_found = exc - continue - raise - else: - raise NotFoundError(uri, "file") from last_not_found + try: + result = await self._async_agfs.read(path, offset, size) + except Exception as exc: + if is_not_found_error(exc): + raise NotFoundError(uri, "file") from exc + raise if isinstance(result, bytes): raw = result elif result is not None and hasattr(result, "content"): @@ -1163,35 +1155,13 @@ async def stat( real_ctx = self._ctx_or_default(ctx) uri = await self.resolve_uri(uri, real_ctx) await self._ensure_access(uri, ctx) - primary_path = self._uri_to_path(uri, ctx=ctx) - path = primary_path - last_not_found: Optional[Exception] = None - for candidate_path in self._read_paths(uri, ctx=ctx): - if not await self._read_path_visible(uri, candidate_path, primary_path, real_ctx): - continue - try: - result = await self._async_agfs.stat(candidate_path) - path = candidate_path - break - except Exception as exc: - if is_not_found_error(exc): - last_not_found = exc - continue - raise - else: - if self._is_session_root_uri(uri): - now = datetime.now(timezone.utc).isoformat() - result = { - "name": "session", - "size": 0, - "mode": 0o755, - "modTime": now, - "isDir": True, - } - if include_lock_status: - result["isLocked"] = False - return result - raise NotFoundError(uri, "file") from last_not_found + path = self._uri_to_path(uri, ctx=ctx) + try: + result = await self._async_agfs.stat(path) + except Exception as exc: + if is_not_found_error(exc): + raise NotFoundError(uri, "file") from exc + raise if isinstance(result, dict): result["uri"] = uri if include_lock_status: @@ -1228,14 +1198,7 @@ async def exists(self, uri: str, ctx: Optional[RequestContext] = None) -> bool: self._safe_uri_parts(uri) if not self._is_accessible(uri, real_ctx): return False - - primary_path = self._uri_to_path(uri, ctx=ctx) - for candidate_path in self._read_paths(uri, ctx=ctx): - if not await self._read_path_visible(uri, candidate_path, primary_path, real_ctx): - continue - if await self._agfs_path_exists(candidate_path): - return True - return self._is_session_root_uri(uri) + return await self._agfs_path_exists(self._uri_to_path(uri, ctx=ctx)) async def glob( self, @@ -1259,17 +1222,8 @@ async def glob( real_ctx = self._ctx_or_default(ctx) return_entries = extra_fields is not None aug_fields = list(extra_fields) if extra_fields else [] - primary_path = self._uri_to_path(uri, ctx=ctx) - path: Optional[str] = None - for candidate_path in self._read_paths(uri, ctx=ctx): - if not await self._read_path_visible(uri, candidate_path, primary_path, real_ctx): - continue - if await self._agfs_path_exists(candidate_path): - path = candidate_path - break - if path is None: - if self._is_session_root_uri(uri): - return {"matches": [], "count": 0} + path = self._uri_to_path(uri, ctx=ctx) + if not await self._agfs_path_exists(path): raise NotFoundError(uri, "directory") if not force_fs: @@ -1315,8 +1269,6 @@ async def glob( acl_enabled=acl_enabled, ): continue - if not await self._read_path_visible(uri, entry["path"], primary_path, real_ctx): - continue entry_uri = self._alias_uri_for_path( request_uri=uri, base_path=path, @@ -2080,23 +2032,15 @@ async def read_file( real_ctx = self._ctx_or_default(ctx) uri = await self.resolve_uri(uri, real_ctx) await self._ensure_access(uri, ctx) - primary_path = self._uri_to_path(uri, ctx=ctx) + path = self._uri_to_path(uri, ctx=ctx) # Verify the file exists before reading, because AGFS read returns # empty bytes for non-existent files instead of raising an error. - last_not_found: Optional[Exception] = None - for path in self._read_paths(uri, ctx=ctx): - if not await self._read_path_visible(uri, path, primary_path, real_ctx): - continue - try: - stat = await self._async_agfs.stat(path) - break - except Exception as exc: - if is_not_found_error(exc): - last_not_found = exc - continue - raise - else: - raise NotFoundError(uri, "file") from last_not_found + try: + stat = await self._async_agfs.stat(path) + except Exception as exc: + if is_not_found_error(exc): + raise NotFoundError(uri, "file") from exc + raise if isinstance(stat, dict) and stat.get("isDir", False): raise InvalidArgumentError( f"Directory URI is not readable as a file: {uri}. " @@ -2136,21 +2080,13 @@ async def read_file_bytes( real_ctx = self._ctx_or_default(ctx) uri = await self.resolve_uri(uri, real_ctx) await self._ensure_access(uri, ctx) - primary_path = self._uri_to_path(uri, ctx=ctx) - last_not_found: Optional[Exception] = None - for path in self._read_paths(uri, ctx=ctx): - if not await self._read_path_visible(uri, path, primary_path, real_ctx): - continue - try: - stat = await self._async_agfs.stat(path) - break - except Exception as exc: - if is_not_found_error(exc): - last_not_found = exc - continue - raise - else: - raise NotFoundError(uri, "file") from last_not_found + path = self._uri_to_path(uri, ctx=ctx) + try: + stat = await self._async_agfs.stat(path) + except Exception as exc: + if is_not_found_error(exc): + raise NotFoundError(uri, "file") from exc + raise if isinstance(stat, dict) and stat.get("isDir", False): raise InvalidArgumentError( f"Cannot read directory as file: {uri}", @@ -2331,67 +2267,6 @@ async def ls( overview_limit=overview_limit, ) - @staticmethod - def _ls_entry_mtime(entry: Dict[str, Any]) -> Optional[float]: - raw_time = entry.get("modTime") - if isinstance(raw_time, (int, float)): - return float(raw_time) - if isinstance(raw_time, str) and raw_time: - try: - return parse_iso_datetime(raw_time).timestamp() - except (TypeError, ValueError, OverflowError): - return None - - legacy_time = entry.get("mtime") - if isinstance(legacy_time, (int, float)): - return float(legacy_time) - return None - - @classmethod - def _sort_ls_entry_items( - cls, - entry_items: List[tuple[Dict[str, Any], str]], - sort_by: Optional[str], - sort_order: str, - ) -> List[tuple[Dict[str, Any], str]]: - if sort_by is None: - return entry_items - - descending = sort_order == "desc" - directories = [item for item in entry_items if item[0].get("isDir", False)] - files = [item for item in entry_items if not item[0].get("isDir", False)] - - def name_key(item: tuple[Dict[str, Any], str]) -> tuple[str, str]: - """Return the case-insensitive and original entry name.""" - name = str(item[0].get("name", "")) - return name.lower(), name - - if sort_by == "name": - directories.sort(key=name_key, reverse=descending) - files.sort(key=name_key, reverse=descending) - return directories + files - - def sort_by_mtime( - items: List[tuple[Dict[str, Any], str]], - ) -> List[tuple[Dict[str, Any], str]]: - timestamped = [] - missing = [] - for item in items: - timestamp = cls._ls_entry_mtime(item[0]) - if timestamp is None: - missing.append(item) - else: - timestamped.append((timestamp, item)) - timestamped.sort(key=lambda pair: name_key(pair[1])) - timestamped.sort( - key=lambda pair: pair[0], - reverse=descending, - ) - missing.sort(key=name_key) - return [item for _, item in timestamped] + missing - - return sort_by_mtime(directories) + sort_by_mtime(files) - async def _ls_original( self, uri: str, @@ -2473,7 +2348,6 @@ async def _ls_browsable_items( raw_offset = 0 raw_limit = None if node_limit is None else max(node_limit, 256) remaining_offset = offset - merge_paths = self._legacy_session_alias(uri) is not None browsable: List[tuple[Dict[str, Any], str]] = [] acl_enabled = await self._acl_enabled(ctx) expose_resource_names = acl_enabled and is_acl_uri(uri) @@ -2487,8 +2361,6 @@ async def _ls_browsable_items( sort_order=sort_order, ctx=ctx, ) - if merge_paths: - entry_items = self._sort_ls_entry_items(entry_items, sort_by, sort_order) entry_items = [ item for item in entry_items diff --git a/openviking/storage/viking_fs/_semantic.py b/openviking/storage/viking_fs/_semantic.py index 2c45873f580..2f31b19055e 100644 --- a/openviking/storage/viking_fs/_semantic.py +++ b/openviking/storage/viking_fs/_semantic.py @@ -27,7 +27,7 @@ from openviking.telemetry import get_current_telemetry from openviking.utils.image_search import build_multimodal_embedding_input from openviking.utils.time_decay import parse_duration_ms -from openviking_cli.exceptions import InvalidArgumentError, NotFoundError +from openviking_cli.exceptions import InvalidArgumentError from openviking_cli.retrieve import ContextType from openviking_cli.utils.config.retrieval_config import RetrievalConfig @@ -73,20 +73,7 @@ async def _read_abstract_for_known_dir( must guarantee that the URI points to a directory. """ await self._ensure_access(uri, ctx) - real_ctx = self._ctx_or_default(ctx) - primary_path = self._uri_to_path(uri, ctx=ctx) - for path in self._read_paths(uri, ctx=ctx): - if not await self._read_path_visible(uri, path, primary_path, real_ctx): - continue - try: - if not await self._agfs_path_exists(path): - continue - return await self._read_abstract_file(path, uri, ctx=ctx) - except Exception as exc: - if is_not_found_error(exc): - continue - raise - return f"# {uri} [Directory abstract is not ready]" + return await self._read_abstract_file(self._uri_to_path(uri, ctx=ctx), uri, ctx=ctx) async def abstract( self, @@ -99,31 +86,14 @@ async def abstract( the endpoint remains usable for both file and directory URIs. """ await self._ensure_access(uri, ctx) - real_ctx = self._ctx_or_default(ctx) - primary_path = self._uri_to_path(uri, ctx=ctx) - path = primary_path - last_exc: Optional[Exception] = None - for candidate_path in self._read_paths(uri, ctx=ctx): - if not await self._read_path_visible(uri, candidate_path, primary_path, real_ctx): - continue - try: - info = await self._async_agfs.stat(candidate_path) - path = candidate_path - break - except Exception as exc: - if is_not_found_error(exc): - last_exc = exc - continue - mapped = map_exception(exc, resource=uri) - if mapped is not None: - raise mapped from exc - raise - else: - if last_exc is not None: - mapped = map_exception(last_exc, resource=uri) - if mapped is not None: - raise mapped from last_exc - raise NotFoundError(uri, "directory") from last_exc + path = self._uri_to_path(uri, ctx=ctx) + try: + info = await self._async_agfs.stat(path) + except Exception as exc: + mapped = map_exception(exc, resource=uri) + if mapped is not None: + raise mapped from exc + raise if not info.get("isDir", info.get("is_dir")): parent_path = path.rsplit("/", 1)[0] or "/" parent_uri = self._path_to_uri(parent_path, ctx=ctx) @@ -146,31 +116,14 @@ async def overview( the endpoint remains usable for both file and directory URIs. """ await self._ensure_access(uri, ctx) - real_ctx = self._ctx_or_default(ctx) - primary_path = self._uri_to_path(uri, ctx=ctx) - path = primary_path - last_exc: Optional[Exception] = None - for candidate_path in self._read_paths(uri, ctx=ctx): - if not await self._read_path_visible(uri, candidate_path, primary_path, real_ctx): - continue - try: - info = await self._async_agfs.stat(candidate_path) - path = candidate_path - break - except Exception as exc: - if is_not_found_error(exc): - last_exc = exc - continue - mapped = map_exception(exc, resource=uri) - if mapped is not None: - raise mapped from exc - raise - else: - if last_exc is not None: - mapped = map_exception(last_exc, resource=uri) - if mapped is not None: - raise mapped from last_exc - raise NotFoundError(uri, "directory") from last_exc + path = self._uri_to_path(uri, ctx=ctx) + try: + info = await self._async_agfs.stat(path) + except Exception as exc: + mapped = map_exception(exc, resource=uri) + if mapped is not None: + raise mapped from exc + raise if not info.get("isDir", info.get("is_dir")): parent_path = path.rsplit("/", 1)[0] or "/" parent_uri = self._path_to_uri(parent_path, ctx=ctx) diff --git a/openviking_cli/utils/uri.py b/openviking_cli/utils/uri.py index 6a7123b52a1..853ef75a7c3 100644 --- a/openviking_cli/utils/uri.py +++ b/openviking_cli/utils/uri.py @@ -41,7 +41,7 @@ class VikingURI: - resources: Independent resource scope (viking://resources/{project}/...) - user: Explicit user scope (viking://user/{user_id}/...), including sessions under viking://user/{user_id}/sessions/{session_id}. - - session: Legacy alias for user sessions (viking://session/{session_id}/...) + - session: Historical scope parsed only for explicit data migration - agent: Agent capabilities scope (viking://agent/skills/..., viking://agent/endpoints/...) - system: Account-level system assets (viking://system/...) - queue: Queue scope (viking://queue/...) diff --git a/sdk/go/client_test.go b/sdk/go/client_test.go index b22f3429d80..b892a1c86a8 100644 --- a/sdk/go/client_test.go +++ b/sdk/go/client_test.go @@ -351,7 +351,7 @@ func TestListAndTreePreserveOptionsAndPagination(t *testing.T) { })) defer closeServer() - listPage, err := client.ListPage(context.Background(), "viking://session", &ListOptions{ + listPage, err := client.ListPage(context.Background(), "viking://~/sessions", &ListOptions{ NodeLimit: 200, Offset: 4, Limit: 5, @@ -370,9 +370,9 @@ func TestListAndTreePreserveOptionsAndPagination(t *testing.T) { if !listPage.HasMore || !reflect.DeepEqual(listPage.Result, entries) { t.Fatalf("list page = %#v", listPage) } - legacyList, err := client.List(context.Background(), "viking://session", nil) - if err != nil || !reflect.DeepEqual(legacyList, entries) { - t.Fatalf("list = %#v, err = %v", legacyList, err) + sessionList, err := client.List(context.Background(), "viking://~/sessions", nil) + if err != nil || !reflect.DeepEqual(sessionList, entries) { + t.Fatalf("list = %#v, err = %v", sessionList, err) } treePage, err := client.TreePage(context.Background(), "viking://resources/docs", &TreeOptions{ NodeLimit: 200, diff --git a/sdk/typescript/tests/client.test.ts b/sdk/typescript/tests/client.test.ts index 6e57cab77b2..2c57980735f 100644 --- a/sdk/typescript/tests/client.test.ts +++ b/sdk/typescript/tests/client.test.ts @@ -654,7 +654,7 @@ describe("OpenVikingClient", () => { fetch: fetcher, }); - const listPage = await client.listPage("viking://session", { + const listPage = await client.listPage("viking://~/sessions", { nodeLimit: 200, offset: 4, limit: 5, @@ -666,7 +666,7 @@ describe("OpenVikingClient", () => { extraFields: ["locked", "id"], }); expect(listPage).toEqual({ result: entries, hasMore: true }); - await expect(client.list("viking://session")).resolves.toEqual(entries); + await expect(client.list("viking://~/sessions")).resolves.toEqual(entries); const treePage = await client.treePage("viking://resources/docs", { levelLimit: 2, offset: 6, diff --git a/tests/server/test_admin_api.py b/tests/server/test_admin_api.py index 61f54213bda..a47e6ec012c 100644 --- a/tests/server/test_admin_api.py +++ b/tests/server/test_admin_api.py @@ -55,7 +55,7 @@ from openviking.session.memory.memory_type_registry import MemoryTypeRegistry, get_default_registry from openviking.session.memory.patch_merge_context_provider import PatchMergeContextProvider from openviking.session.memory.session_extract_context_provider import SessionExtractContextProvider -from openviking_cli.exceptions import OpenVikingError +from openviking_cli.exceptions import NotFoundError, OpenVikingError from openviking_cli.session.user_id import UserIdentifier from openviking_cli.utils.config import get_openviking_config @@ -3347,8 +3347,20 @@ async def test_legacy_cleanup_preserves_public_agent_directories( async def test_session_storage_uses_canonical_uri( admin_service: OpenVikingService, ): - """Canonical session URIs can read existing session storage.""" + """Canonical session reads do not fall back to obsolete storage paths.""" ctx = RequestContext(user=UserIdentifier("default", "admin_user"), role=Role.USER) + await _agfs_write( + admin_service, + "/local/default/user/admin_user/sessions/current-session/messages.jsonl", + '{"role":"user"}\n', + ) + assert ( + await admin_service.viking_fs.read_file( + "viking://user/admin_user/sessions/current-session/messages.jsonl", + ctx=ctx, + ) + == '{"role":"user"}\n' + ) await _agfs_write( admin_service, "/local/default/session/old-session/messages.jsonl", @@ -3360,13 +3372,11 @@ async def test_session_storage_uses_canonical_uri( '{"created_by_user_id":"admin_user"}', ) - assert ( + with pytest.raises(NotFoundError): await admin_service.viking_fs.read_file( "viking://user/admin_user/sessions/old-session/messages.jsonl", ctx=ctx, ) - == '{"role":"user"}\n' - ) @pytest_asyncio.fixture(scope="function") diff --git a/tests/server/test_api_sessions.py b/tests/server/test_api_sessions.py index 769e9347f50..f2db21aa9eb 100644 --- a/tests/server/test_api_sessions.py +++ b/tests/server/test_api_sessions.py @@ -170,23 +170,6 @@ async def test_get_session(client: httpx.AsyncClient): assert body["result"]["uri"] == session_uri -async def test_legacy_session_uri_alias_reads_current_user_session(client: httpx.AsyncClient): - session_id = "legacy-alias-read" - await client.post("/api/v1/sessions", json={"session_id": session_id}) - await client.post( - f"/api/v1/sessions/{session_id}/messages", - json=_message_request("user", content="legacy alias message"), - ) - - resp = await client.get( - "/api/v1/content/read", - params={"uri": f"viking://session/{session_id}/messages.jsonl"}, - ) - - assert resp.status_code == 200 - assert "legacy alias message" in resp.json()["result"] - - @pytest.mark.parametrize("artifact", ["empty", "recall_ledger", "meta"]) async def test_add_message_repairs_session_directory_without_live_messages( client: httpx.AsyncClient, diff --git a/tests/service/test_session_service_metrics.py b/tests/service/test_session_service_metrics.py index 6b63df44b14..0f14e892965 100644 --- a/tests/service/test_session_service_metrics.py +++ b/tests/service/test_session_service_metrics.py @@ -87,7 +87,7 @@ async def test_sessions_returns_empty_and_logs_when_storage_listing_fails( @pytest.mark.asyncio -async def test_sessions_uses_canonical_scope_and_relies_on_storage_compatibility(): +async def test_sessions_uses_canonical_scope(): service = SessionService(viking_fs=Mock()) ctx = _make_ctx() @@ -97,11 +97,6 @@ async def _ls(uri, ctx, **kwargs): return [ {"name": "duplicate", "isDir": True, "modTime": "2026-07-13T01:00:00Z"}, {"name": "new-session", "isDir": True, "modTime": "2026-07-13T02:00:00Z"}, - { - "name": "legacy-session", - "isDir": True, - "modTime": "2026-07-12T01:00:00Z", - }, ] service._viking_fs.ls = AsyncMock(side_effect=_ls) @@ -121,12 +116,6 @@ async def _ls(uri, ctx, **kwargs): "is_dir": True, "mod_time": "2026-07-13T02:00:00Z", }, - { - "session_id": "legacy-session", - "uri": "viking://user/alice/sessions/legacy-session", - "is_dir": True, - "mod_time": "2026-07-12T01:00:00Z", - }, ] service._viking_fs.ls.assert_awaited_once() diff --git a/tests/session/memory/test_memory_react_system_prompt.py b/tests/session/memory/test_memory_react_system_prompt.py index 0bbeee9a7b4..42635eef23f 100644 --- a/tests/session/memory/test_memory_react_system_prompt.py +++ b/tests/session/memory/test_memory_react_system_prompt.py @@ -146,7 +146,7 @@ def test_session_conversation_omits_skill_tool_call(self): ToolPart( tool_id="tool_1", tool_name="read", - tool_uri="viking://session/test/tools/tool_1", + tool_uri="viking://user/default/sessions/test/tools/tool_1", skill_uri="viking://user/skills/create_presentation", tool_input={"file_path": "/skills/ppt/SKILL.md"}, tool_output="ok", @@ -174,7 +174,7 @@ def test_session_conversation_omits_regular_tool_call(self): ToolPart( tool_id="tool_1", tool_name="read", - tool_uri="viking://session/test/tools/tool_1", + tool_uri="viking://user/default/sessions/test/tools/tool_1", tool_input={"file_path": "README.md"}, tool_output="ok", tool_status="completed", @@ -250,7 +250,7 @@ def test_detect_language_only_uses_text_parts(self): ToolPart( tool_id="tool_1", tool_name="read", - tool_uri="viking://session/test/tools/tool_1", + tool_uri="viking://user/default/sessions/test/tools/tool_1", tool_input={"file_path": "README.md"}, tool_output="这是中文工具输出", tool_status="completed", diff --git a/tests/session/test_tool_result_synopsis.py b/tests/session/test_tool_result_synopsis.py index 3dcf24f4c38..9de2fe64df3 100644 --- a/tests/session/test_tool_result_synopsis.py +++ b/tests/session/test_tool_result_synopsis.py @@ -27,7 +27,7 @@ def test_render_stub_preserves_navigation_contract(): rendered = render_tool_result_stub( synopsis, - ref="viking://session/s1/tool-results/tr_123", + ref="viking://user/default/sessions/s1/tool-results/tr_123", tool_name="read_file", sha256="0123456789abcdef0123", reason="single_threshold", @@ -40,7 +40,7 @@ def test_render_stub_preserves_navigation_contract(): assert "tool_name: read_file" in rendered assert "original_chars: 120" in rendered assert "preview_chars: 80" in rendered - assert "ref: viking://session/s1/tool-results/tr_123" in rendered + assert "ref: viking://user/default/sessions/s1/tool-results/tr_123" in rendered assert "openviking_tool_result_search" in rendered assert "openviking_tool_result_read" in rendered diff --git a/tests/storage/test_session_delete_storage.py b/tests/storage/test_session_delete_storage.py index ce4e5b79e8c..77cdcb1203c 100644 --- a/tests/storage/test_session_delete_storage.py +++ b/tests/storage/test_session_delete_storage.py @@ -48,7 +48,6 @@ def storage(): "request_uri", [ SESSION_URI, - "viking://session/session-1", "viking://~/sessions/session-1", "viking://temp/alice/raw-upload-1", ], diff --git a/tests/storage/test_viking_fs_actor_peer_view.py b/tests/storage/test_viking_fs_actor_peer_view.py index 9513fa90037..5d22e1b9d2c 100644 --- a/tests/storage/test_viking_fs_actor_peer_view.py +++ b/tests/storage/test_viking_fs_actor_peer_view.py @@ -24,28 +24,6 @@ def __init__(self): b"zhang" ), "/local/acct/user/support_bot/resources/guide.md": b"guide", - "/local/acct/user/support_bot/sessions/duplicate/messages.jsonl": ( - b'{"role":"user","content":"new"}\n' - ), - "/local/acct/user/support_bot/sessions/new-session/messages.jsonl": ( - b'{"role":"user","content":"new only"}\n' - ), - "/local/acct/session/duplicate/messages.jsonl": ( - b'{"role":"user","content":"legacy duplicate"}\n' - ), - "/local/acct/session/legacy-session/messages.jsonl": ( - b'{"role":"user","content":"legacy"}\n' - ), - "/local/acct/session/legacy-session/.meta.json": ( - b'{"created_by_user_id":"support_bot"}' - ), - "/local/acct/session/other-owned/.meta.json": b'{"created_by_user_id":"other"}', - "/local/acct/session/other-owned/messages.jsonl": ( - b'{"role":"user","content":"other"}\n' - ), - "/local/acct/session/support_bot/nested-session/messages.jsonl": ( - b'{"role":"user","content":"nested"}\n' - ), } self.dirs = set() for path in self.files: @@ -211,100 +189,6 @@ async def test_agent_directories_are_shared_within_account(fs, actor_ctx): 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): - session_root = "viking://user/support_bot/sessions" - entries = await fs.ls(session_root, ctx=actor_ctx) - - assert [entry["uri"] for entry in entries] == [ - f"{session_root}/duplicate", - f"{session_root}/new-session", - f"{session_root}/legacy-session", - f"{session_root}/nested-session", - ] - - assert ( - await fs.read_file(f"{session_root}/duplicate/messages.jsonl", ctx=actor_ctx) - == '{"role":"user","content":"new"}\n' - ) - assert ( - await fs.read_file(f"{session_root}/legacy-session/messages.jsonl", ctx=actor_ctx) - == '{"role":"user","content":"legacy"}\n' - ) - assert ( - await fs.read_file(f"{session_root}/nested-session/messages.jsonl", ctx=actor_ctx) - == '{"role":"user","content":"nested"}\n' - ) - with pytest.raises(NotFoundError): - await fs.read_file(f"{session_root}/other-owned/messages.jsonl", ctx=actor_ctx) - - for session_id in ("new-session", "legacy-session", "nested-session"): - children = await fs.ls(f"{session_root}/{session_id}", ctx=actor_ctx) - assert [entry["uri"] for entry in children] == [ - f"{session_root}/{session_id}/messages.jsonl" - ] - with pytest.raises(NotFoundError): - await fs.ls(f"{session_root}/other-owned", ctx=actor_ctx) - - -@pytest.mark.asyncio -async def test_session_grep_preserves_legacy_merge_and_primary_shadow(fs, actor_ctx): - session_root = "viking://user/support_bot/sessions" - - result = await fs.grep( - session_root, - pattern="new|legacy|nested|other", - ctx=actor_ctx, - ) - - assert result["matches"] == [ - { - "uri": f"{session_root}/duplicate/messages.jsonl", - "line": 1, - "content": '{"role":"user","content":"new"}', - }, - { - "uri": f"{session_root}/new-session/messages.jsonl", - "line": 1, - "content": '{"role":"user","content":"new only"}', - }, - { - "uri": f"{session_root}/legacy-session/messages.jsonl", - "line": 1, - "content": '{"role":"user","content":"legacy"}', - }, - { - "uri": f"{session_root}/nested-session/messages.jsonl", - "line": 1, - "content": '{"role":"user","content":"nested"}', - }, - ] - - -@pytest.mark.asyncio -async def test_session_native_grep_gate_allows_primary_only_session(fs, actor_ctx): - assert await fs._session_native_grep_safe( - "viking://user/support_bot/sessions/new-session", actor_ctx - ) - - -@pytest.mark.asyncio -async def test_session_native_grep_gate_rejects_visible_legacy_layouts(fs, actor_ctx): - assert not await fs._session_native_grep_safe( - "viking://user/support_bot/sessions/legacy-session", actor_ctx - ) - assert not await fs._session_native_grep_safe( - "viking://user/support_bot/sessions/nested-session", actor_ctx - ) - - -@pytest.mark.asyncio -async def test_session_native_grep_gate_ignores_other_owner_legacy_data(fs, actor_ctx): - assert await fs._session_native_grep_safe( - "viking://user/support_bot/sessions/other-owned", actor_ctx - ) - - @pytest.mark.asyncio async def test_actor_peer_view_filters_tree_from_user_root(fs, actor_ctx): entries = await fs.tree( diff --git a/tests/storage/test_viking_fs_glob.py b/tests/storage/test_viking_fs_glob.py index c651a5739f6..fba88298199 100644 --- a/tests/storage/test_viking_fs_glob.py +++ b/tests/storage/test_viking_fs_glob.py @@ -88,11 +88,7 @@ def fs(monkeypatch): monkeypatch.setattr( viking_fs, "_uri_to_path", lambda _uri, **_kwargs: "/local/test_account/resources" ) - monkeypatch.setattr( - viking_fs, "_read_paths", lambda _uri, **_kwargs: ["/local/test_account/resources"] - ) monkeypatch.setattr(viking_fs, "_agfs_path_exists", lambda _path: _async_true()) - monkeypatch.setattr(viking_fs, "_read_path_visible", lambda *_args, **_kwargs: _async_true()) monkeypatch.setattr( viking_fs, "_path_to_uri", @@ -816,7 +812,6 @@ async def fake_ensure_access(uri, ctx): @pytest.mark.asyncio async def test_glob_preserves_request_uri_alias(monkeypatch, fs): monkeypatch.setattr(fs, "_uri_to_path", lambda _uri, **_kwargs: "/local/test_account/user") - monkeypatch.setattr(fs, "_read_paths", lambda _uri, **_kwargs: ["/local/test_account/user"]) monkeypatch.setattr( fs, "_path_to_uri", lambda _path, **_kwargs: "viking://user/test_account/demo.md" ) @@ -844,7 +839,6 @@ async def fake_glob_directory(path, pattern, **kwargs): @pytest.mark.asyncio async def test_glob_preserves_root_uri(monkeypatch, fs): monkeypatch.setattr(fs, "_uri_to_path", lambda _uri, **_kwargs: "/local/test_account") - monkeypatch.setattr(fs, "_read_paths", lambda _uri, **_kwargs: ["/local/test_account"]) monkeypatch.setattr( fs, "_path_to_uri", lambda _path, **_kwargs: "viking://resources/should-not-leak.md" ) @@ -975,11 +969,6 @@ async def test_glob_preserves_canonical_session_uri(monkeypatch, fs): monkeypatch.setattr( fs, "_uri_to_path", lambda _uri, **_kwargs: "/local/test_account/user/alice/sessions/sess_1" ) - monkeypatch.setattr( - fs, - "_read_paths", - lambda _uri, **_kwargs: ["/local/test_account/user/alice/sessions/sess_1"], - ) async def fake_glob_directory(path, pattern, **kwargs): return { @@ -1009,18 +998,13 @@ async def fake_glob_directory(path, pattern, **kwargs): @pytest.mark.asyncio -async def test_glob_uses_path_to_uri_for_non_legacy_namespace(monkeypatch, fs): - """中文注释:非 legacy 命名空间必须回落到 _path_to_uri,避免错误沿用请求别名。""" +async def test_glob_uses_path_to_uri_when_request_mapping_differs(monkeypatch, fs): + """Return the physical path's URI when the requested mapping differs.""" monkeypatch.setattr( fs, "_uri_to_path", lambda _uri, **_kwargs: "/local/test_account/resources/actual-root", ) - monkeypatch.setattr( - fs, - "_read_paths", - lambda _uri, **_kwargs: ["/local/test_account/resources/actual-root"], - ) monkeypatch.setattr( fs, "_path_to_uri", diff --git a/tests/storage/test_viking_fs_grep.py b/tests/storage/test_viking_fs_grep.py index 06be08078e5..5769f462510 100644 --- a/tests/storage/test_viking_fs_grep.py +++ b/tests/storage/test_viking_fs_grep.py @@ -424,14 +424,7 @@ async def fake_count(uri, ctx): @pytest.mark.asyncio -@pytest.mark.parametrize( - "uri", - [ - "viking://user/alice/sessions/session-1", - "viking://session/session-1", - ], -) -async def test_session_grep_forces_fs_engine_in_auto_mode(monkeypatch, uri): +async def test_session_grep_forces_fs_engine_in_auto_mode(monkeypatch): viking_fs = VikingFS(agfs=_DummyAgfs()) monkeypatch.setattr(viking_fs, "stat", AsyncMock(return_value={"isDir": True})) resolve_engine = AsyncMock(return_value="vikingdb_then_fs") @@ -444,7 +437,7 @@ async def test_session_grep_forces_fs_engine_in_auto_mode(monkeypatch, uri): monkeypatch.setattr(viking_fs, "_grep_vikingdb_then_fs", grep_vikingdb) await viking_fs.grep( - uri, + "viking://user/alice/sessions/session-1", pattern="needle", ) @@ -454,12 +447,11 @@ async def test_session_grep_forces_fs_engine_in_auto_mode(monkeypatch, uri): @pytest.mark.asyncio -async def test_primary_only_session_grep_uses_native_agfs(monkeypatch): +async def test_session_grep_uses_native_agfs(monkeypatch): viking_fs = VikingFS(agfs=_DummyAgfs()) native_result = {"matches": [], "count": 0, "match_count": 0, "files_scanned": 4} native_grep = AsyncMock(return_value=native_result) fallback_grep = AsyncMock() - monkeypatch.setattr(viking_fs, "_session_native_grep_safe", AsyncMock(return_value=True)) monkeypatch.setattr(viking_fs, "_grep_with_agfs", native_grep) monkeypatch.setattr(viking_fs, "_grep_encrypted", fallback_grep) @@ -488,92 +480,6 @@ async def test_primary_only_session_grep_uses_native_agfs(monkeypatch): fallback_grep.assert_not_awaited() -@pytest.mark.asyncio -async def test_session_grep_with_visible_legacy_data_uses_merge_fallback(monkeypatch): - viking_fs = VikingFS(agfs=_DummyAgfs()) - fallback_result = {"matches": [], "count": 0, "match_count": 0, "files_scanned": 2} - native_grep = AsyncMock() - fallback_grep = AsyncMock(return_value=fallback_result) - monkeypatch.setattr(viking_fs, "_session_native_grep_safe", AsyncMock(return_value=False)) - monkeypatch.setattr(viking_fs, "_grep_with_agfs", native_grep) - monkeypatch.setattr(viking_fs, "_grep_encrypted", fallback_grep) - - result = await viking_fs._grep_fs( - uri="viking://user/alice/sessions/session-1", - pattern="needle", - exclude_uri=None, - case_insensitive=False, - node_limit=None, - level_limit=10, - ctx=None, - ) - - assert result == fallback_result - native_grep.assert_not_awaited() - fallback_grep.assert_awaited_once() - assert fallback_grep.await_args.kwargs["level_limit"] == 10 - - -@pytest.mark.asyncio -async def test_session_native_and_legacy_fallback_keep_level_limit_results_equal(monkeypatch): - viking_fs = VikingFS(agfs=_DummyAgfs()) - match = { - "uri": "viking://user/alice/sessions/s1/messages.jsonl", - "line": 1, - "content": "payment failed", - } - - async def fake_native_grep(**kwargs): - matches = [match] if kwargs["level_limit"] >= 2 else [] - return { - "matches": matches, - "count": len(matches), - "match_count": len(matches), - "files_scanned": len(matches), - } - - async def fake_fallback_grep(**kwargs): - matches = [match] if kwargs["level_limit"] >= 1 else [] - return { - "matches": matches, - "count": len(matches), - "match_count": len(matches), - "files_scanned": len(matches), - } - - monkeypatch.setattr(viking_fs, "_grep_with_agfs", fake_native_grep) - monkeypatch.setattr(viking_fs, "_grep_encrypted", fake_fallback_grep) - native_safe = AsyncMock(side_effect=[True, False]) - monkeypatch.setattr(viking_fs, "_session_native_grep_safe", native_safe) - kwargs = { - "uri": "viking://user/alice/sessions", - "pattern": "payment failed", - "exclude_uri": None, - "case_insensitive": False, - "node_limit": None, - "level_limit": 1, - "ctx": None, - } - - assert await viking_fs._grep_fs(**kwargs) == await viking_fs._grep_fs(**kwargs) - - -@pytest.mark.asyncio -async def test_virtual_empty_session_root_uses_merge_fallback(monkeypatch): - viking_fs = VikingFS(agfs=_DummyAgfs()) - primary_path = "/local/default/user/alice/sessions" - path_exists = AsyncMock(return_value=False) - legacy_items = AsyncMock(return_value=[]) - monkeypatch.setattr(viking_fs, "_agfs_path_exists", path_exists) - monkeypatch.setattr(viking_fs, "_legacy_session_root_items", legacy_items) - - assert not await viking_fs._session_native_grep_safe( - "viking://user/alice/sessions", None - ) - path_exists.assert_awaited_once_with(primary_path) - legacy_items.assert_not_awaited() - - @pytest.mark.asyncio @pytest.mark.parametrize( ("node_limit", "expected_remote_limit"), diff --git a/tests/storage/test_viking_fs_tree.py b/tests/storage/test_viking_fs_tree.py index 8130cb862fe..c2d89f83b58 100644 --- a/tests/storage/test_viking_fs_tree.py +++ b/tests/storage/test_viking_fs_tree.py @@ -40,9 +40,6 @@ async def resolve_uri(uri, _ctx): async def ensure_access(_uri, _ctx): return None - async def read_path_visible(_uri, _path, _primary_path, _ctx): - return True - async def stat_path(_path): return {"name": "example.md", "isDir": False} @@ -53,8 +50,6 @@ async def is_path_locked(queried_path): monkeypatch.setattr(fs, "resolve_uri", resolve_uri) monkeypatch.setattr(fs, "_ensure_access", ensure_access) monkeypatch.setattr(fs, "_uri_to_path", lambda _uri, **_kwargs: path) - monkeypatch.setattr(fs, "_read_paths", lambda _uri, **_kwargs: [path]) - monkeypatch.setattr(fs, "_read_path_visible", read_path_visible) monkeypatch.setattr(fs._async_agfs, "stat", stat_path) monkeypatch.setattr(fs, "_is_path_locked_async", is_path_locked) @@ -809,16 +804,6 @@ async def fake_can_access_many(uris, _ctx, **_kwargs): abstract.assert_not_awaited() overview.assert_awaited_once_with("viking://resources/docs", ctx=_default_ctx()) - tied = [ - ({"name": name, "isDir": False, "modTime": "2026-01-01T00:00:00Z"}, name) - for name in ["b.md", "a.md"] - ] - assert [entry["name"] for entry, _ in fs._sort_ls_entry_items(tied, "mtime", "desc")] == [ - "a.md", - "b.md", - ] - - @pytest.mark.asyncio async def test_tree_filters_and_paginates_before_summary_reads(monkeypatch, fs): """Only selected directories consume node slots and summary reads.""" diff --git a/tests/test_token_estimation.py b/tests/test_token_estimation.py index f9749fac781..0333eefaa0f 100644 --- a/tests/test_token_estimation.py +++ b/tests/test_token_estimation.py @@ -36,10 +36,10 @@ async def read_file(self, uri, ctx=None): del uri, ctx return '{"overview_tokens": 1}' - store = ArchiveStore(FakeFS(), None, "viking://session/test") + store = ArchiveStore(FakeFS(), None, "viking://user/default/sessions/test") tokens = await store.read_overview_tokens( - "viking://session/test/history/archive_001", + "viking://user/default/sessions/test/history/archive_001", "\u4f60\u597d\u4e16\u754c", ) @@ -52,10 +52,10 @@ async def read_file(self, uri, ctx=None): del uri, ctx return '{"overview_tokens": 5}' - store = ArchiveStore(FakeFS(), None, "viking://session/test") + store = ArchiveStore(FakeFS(), None, "viking://user/default/sessions/test") tokens = await store.read_overview_tokens( - "viking://session/test/history/archive_001", + "viking://user/default/sessions/test/history/archive_001", "abcd", ) diff --git a/tests/unit/test_message.py b/tests/unit/test_message.py index 77352d8b37e..1954718624b 100644 --- a/tests/unit/test_message.py +++ b/tests/unit/test_message.py @@ -160,7 +160,7 @@ def test_custom_values(self): part = ToolPart( tool_id="call-123", tool_name="search", - tool_uri="viking://session/test/tools/call-123", + tool_uri="viking://user/default/sessions/test/tools/call-123", skill_uri="viking://user/test/skills/search", tool_input={"query": "test"}, tool_output="Result", @@ -168,7 +168,7 @@ def test_custom_values(self): duration_ms=150.5, prompt_tokens=100, completion_tokens=50, - tool_output_ref="viking://session/s1/tool-results/tr_call", + tool_output_ref="viking://user/default/sessions/s1/tool-results/tr_call", tool_output_truncated=True, tool_output_original_chars=1000, tool_output_preview_chars=100, @@ -179,7 +179,7 @@ def test_custom_values(self): assert part.tool_id == "call-123" assert part.tool_name == "search" - assert part.tool_uri == "viking://session/test/tools/call-123" + assert part.tool_uri == "viking://user/default/sessions/test/tools/call-123" assert part.skill_uri == "viking://user/test/skills/search" assert part.tool_input == {"query": "test"} assert part.tool_output == "Result" @@ -187,7 +187,7 @@ def test_custom_values(self): assert part.duration_ms == 150.5 assert part.prompt_tokens == 100 assert part.completion_tokens == 50 - assert part.tool_output_ref == "viking://session/s1/tool-results/tr_call" + assert part.tool_output_ref == "viking://user/default/sessions/s1/tool-results/tr_call" assert part.tool_output_truncated is True assert part.tool_output_original_chars == 1000 assert part.tool_output_preview_chars == 100 @@ -256,7 +256,7 @@ def test_tool_part_from_dict(self): "type": "tool", "tool_id": "call-123", "tool_name": "search", - "tool_uri": "viking://session/test/tools/call-123", + "tool_uri": "viking://user/default/sessions/test/tools/call-123", "skill_uri": "viking://user/test/skills/search", "tool_input": {"query": "test"}, "tool_output": "Result", @@ -264,7 +264,7 @@ def test_tool_part_from_dict(self): "duration_ms": 150.0, "prompt_tokens": 100, "completion_tokens": 50, - "tool_output_ref": "viking://session/s1/tool-results/tr_call", + "tool_output_ref": "viking://user/default/sessions/s1/tool-results/tr_call", "tool_output_truncated": True, "tool_output_original_chars": 1000, "tool_output_preview_chars": 100, @@ -277,7 +277,7 @@ def test_tool_part_from_dict(self): assert part.tool_id == "call-123" assert part.tool_name == "search" assert part.tool_status == "completed" - assert part.tool_output_ref == "viking://session/s1/tool-results/tr_call" + assert part.tool_output_ref == "viking://user/default/sessions/s1/tool-results/tr_call" assert part.tool_output_truncated is True assert part.tool_output_original_chars == 1000 assert part.tool_output_preview_chars == 100 @@ -525,7 +525,7 @@ def test_to_dict_with_tool_part(self, tool_input): duration_ms=100, prompt_tokens=50, completion_tokens=25, - tool_output_ref="viking://session/s1/tool-results/tr_call", + tool_output_ref="viking://user/default/sessions/s1/tool-results/tr_call", tool_output_truncated=True, tool_output_original_chars=1000, tool_output_preview_chars=100, @@ -539,7 +539,7 @@ def test_to_dict_with_tool_part(self, tool_input): assert d["parts"][0]["type"] == "tool" assert d["parts"][0]["tool_id"] == "call-1" assert d["parts"][0]["duration_ms"] == 100 - assert d["parts"][0]["tool_output_ref"] == "viking://session/s1/tool-results/tr_call" + assert d["parts"][0]["tool_output_ref"] == "viking://user/default/sessions/s1/tool-results/tr_call" assert d["parts"][0]["tool_output_truncated"] is True assert d["parts"][0]["tool_output_original_chars"] == 1000 assert d["parts"][0]["tool_output_preview_chars"] == 100 @@ -677,7 +677,7 @@ def test_from_dict_with_tool_part(self): "tool_name": "search", "tool_uri": "viking://tools/1", "tool_status": "completed", - "tool_output_ref": "viking://session/s1/tool-results/tr_call", + "tool_output_ref": "viking://user/default/sessions/s1/tool-results/tr_call", "tool_output_truncated": True, "tool_output_original_chars": 1000, "tool_output_preview_chars": 100, @@ -691,7 +691,7 @@ def test_from_dict_with_tool_part(self): assert isinstance(msg.parts[0], ToolPart) assert msg.parts[0].tool_id == "call-1" - assert msg.parts[0].tool_output_ref == "viking://session/s1/tool-results/tr_call" + assert msg.parts[0].tool_output_ref == "viking://user/default/sessions/s1/tool-results/tr_call" assert msg.parts[0].tool_output_truncated is True assert msg.parts[0].tool_output_original_chars == 1000 assert msg.parts[0].tool_output_preview_chars == 100 diff --git a/tests/unit/test_namespace_uri_classification.py b/tests/unit/test_namespace_uri_classification.py index 5a9fbe83120..6ddbca07947 100644 --- a/tests/unit/test_namespace_uri_classification.py +++ b/tests/unit/test_namespace_uri_classification.py @@ -143,21 +143,10 @@ def test_session_uri_helpers_use_user_namespace(): # hint pointing at the '~' home alias. with pytest.raises(NamespaceShapeError, match=re.escape("viking://~/sessions/s1")): resolve_request_uri("viking://user/sessions/s1", ctx) - assert ( - resolve_request_uri("viking://session/s1", ctx) - == "viking://user/alice/sessions/s1" - ) - assert ( - resolve_request_uri( - "viking://session/s1/history/archive_001/messages.jsonl", ctx - ) - == "viking://user/alice/sessions/s1/history/archive_001/messages.jsonl" - ) assert is_session_uri("viking://user/alice/sessions/s1") assert not is_session_uri("viking://user/sessions/s1") - assert is_session_uri("viking://session/s1") roots = visible_roots(ctx) - assert "viking://session" not in roots + assert "viking://user/alice" in roots assert "viking://agent" in roots diff --git a/tests/unit/test_summarizer_context_type.py b/tests/unit/test_summarizer_context_type.py index 1b5d6a378e8..3493cefbc67 100644 --- a/tests/unit/test_summarizer_context_type.py +++ b/tests/unit/test_summarizer_context_type.py @@ -44,7 +44,7 @@ def test_resource_uri(self): def test_session_uri_defaults_to_resource(self): """Session URIs should not be treated as memory-specific content.""" - uri = "viking://session/default/sess_001/history/archive_001" + uri = "viking://user/default/sessions/sess_001/history/archive_001" assert context_type_for_uri(uri) == "resource" def test_resource_named_memories_does_not_classify_as_memory(self): diff --git a/tests/unit/test_uri_short_format.py b/tests/unit/test_uri_short_format.py index 6e85e4f97be..72c35dcbc1d 100644 --- a/tests/unit/test_uri_short_format.py +++ b/tests/unit/test_uri_short_format.py @@ -90,7 +90,6 @@ def test_build_rejects_home_alias_scope(self): [ ("viking://resources", "resources"), ("viking://user", "user"), - ("viking://session/abc123", "session"), ("viking://queue", "queue"), ("viking://temp", "temp"), ], diff --git a/tests/unit/test_uri_validation.py b/tests/unit/test_uri_validation.py index cabd1b94e10..15d8fa773b2 100644 --- a/tests/unit/test_uri_validation.py +++ b/tests/unit/test_uri_validation.py @@ -13,7 +13,6 @@ "uri", [ "viking://resources/docs", - "viking://session/s1", "viking://agent/skills/demo/SKILL.md", "viking://system/memory", "viking://", diff --git a/tests/unit/test_vectorize_file_strategy.py b/tests/unit/test_vectorize_file_strategy.py index 036e3a98cb4..76187c887a5 100644 --- a/tests/unit/test_vectorize_file_strategy.py +++ b/tests/unit/test_vectorize_file_strategy.py @@ -1041,7 +1041,7 @@ async def test_index_resource_skips_session_namespace(monkeypatch): ), ) await embedding_utils.index_resource( - uri="viking://session/default/sess_001/history/archive_001", + uri="viking://user/default/sessions/sess_001/history/archive_001", ctx=DummyReq(), ) diff --git a/web-studio/src/routes/filesystem/-components/terminal-panel.tsx b/web-studio/src/routes/filesystem/-components/terminal-panel.tsx index 291a9049f48..24f38c8c9a8 100644 --- a/web-studio/src/routes/filesystem/-components/terminal-panel.tsx +++ b/web-studio/src/routes/filesystem/-components/terminal-panel.tsx @@ -440,7 +440,7 @@ function sessionToRef(session: Pick) { return { label: session.session_id, meta: 'session', - uri: session.uri || `viking://session/${session.session_id}`, + uri: session.uri || `viking://~/sessions/${session.session_id}`, } } @@ -1091,7 +1091,7 @@ export function TerminalPanel({ const sessionRef = (id: string): ResourceRef => ({ label: id, meta: 'session', - uri: `viking://session/${id}`, + uri: `viking://~/sessions/${id}`, }) switch (subcommand) { @@ -1202,7 +1202,7 @@ export function TerminalPanel({ { label: archiveId, meta: 'archive', - uri: `viking://session/${id}/history/${archiveId}`, + uri: `viking://~/sessions/${id}/history/${archiveId}`, }, ], title: `/session archive ${id} ${archiveId}`, @@ -1283,7 +1283,7 @@ export function TerminalPanel({ { label: toolResultId, meta: 'tool result', - uri: `viking://session/${id}/tool-results/${toolResultId}`, + uri: `viking://~/sessions/${id}/tool-results/${toolResultId}`, }, ], title: `/session tool-result ${id} ${toolResultId}`, @@ -1316,7 +1316,7 @@ export function TerminalPanel({ { label: toolResultId, meta: 'tool search', - uri: `viking://session/${id}/tool-results/${toolResultId}`, + uri: `viking://~/sessions/${id}/tool-results/${toolResultId}`, }, ], title: `/session tool-search ${id} ${toolResultId}`, diff --git a/web-studio/src/routes/resources/-lib/api.test.ts b/web-studio/src/routes/resources/-lib/api.test.ts index fff8379cba1..d1756e7faab 100644 --- a/web-studio/src/routes/resources/-lib/api.test.ts +++ b/web-studio/src/routes/resources/-lib/api.test.ts @@ -63,7 +63,7 @@ describe('fetchDirectorySidecarContent', () => { describe('fetchFsList', () => { it('requests newest entries before the server applies node_limit', async () => { - await fetchFsList('viking://session', { nodeLimit: 200 }) + await fetchFsList('viking://~/sessions', { nodeLimit: 200 }) expect(getFsLsMock).toHaveBeenCalledWith({ query: expect.objectContaining({ diff --git a/web-studio/src/routes/sessions/-components/memory-impact.test.tsx b/web-studio/src/routes/sessions/-components/memory-impact.test.tsx index 5be22d4646d..98f1447234a 100644 --- a/web-studio/src/routes/sessions/-components/memory-impact.test.tsx +++ b/web-studio/src/routes/sessions/-components/memory-impact.test.tsx @@ -27,7 +27,7 @@ afterEach(cleanup) const diffs: SessionMemoryDiff[] = [ { archiveId: 'archive-1', - archiveUri: 'viking://session/archive-1', + archiveUri: 'viking://user/default/sessions/archive-1', extractedAt: '2026-07-26T00:00:00Z', operations: [ { @@ -47,7 +47,7 @@ const diffs: SessionMemoryDiff[] = [ }, { archiveId: 'archive-2', - archiveUri: 'viking://session/archive-2', + archiveUri: 'viking://user/default/sessions/archive-2', extractedAt: '2026-07-26T01:00:00Z', operations: [ {