From 68b1ea6f1531b7260620dff9030bd1de988588c2 Mon Sep 17 00:00:00 2001 From: qin-ctx Date: Tue, 27 Oct 2026 11:23:12 +0800 Subject: [PATCH] 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. --- 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_api_sessions.py | 17 - tests/service/test_session_service_metrics.py | 13 +- .../test_agent_experience_context_provider.py | 2 +- .../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 | 12 +- .../src/routes/resources/-lib/api.test.ts | 2 +- .../-components/memory-impact.test.tsx | 4 +- 55 files changed, 193 insertions(+), 945 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 3fcd6c8f92e..b7bee72a6c5 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 790558f908b..48b668996a3 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`. - Sensitive information handling: default reads (`raw=false`) preserve existing placeholders and sanitize remaining registered plaintext values; `raw=true` skips default sanitization and returns the restored content. Restoration affects only the response, not stored files; see [Privacy Configs](../concepts/13-privacy.md). **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 1f1cc4a6aae..80ff0149c33 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 2bc14bdd608..8949e62d1fc 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`。 - 敏感信息的处理:默认读取(`raw=false`)保留已有占位符,并对残留的已登记明文脱敏;`raw=true` 跳过默认脱敏,返回加载还原后的内容,该还原只影响返回内容,不修改存储文件,详见[隐私配置](../concepts/13-privacy.md)。 **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 64ad4927b46..f5e9709442d 100644 --- a/examples/openclaw-plugin/tests/ut/plugin-modules.test.ts +++ b/examples/openclaw-plugin/tests/ut/plugin-modules.test.ts @@ -581,7 +581,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( @@ -599,7 +599,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..c86fb2b17ec 100644 --- a/openviking/core/uri_validation.py +++ b/openviking/core/uri_validation.py @@ -15,9 +15,11 @@ from openviking_cli.utils.uri import VikingURI _PUBLIC_API_SCOPES = frozenset( - {"", *VikingURI.PUBLIC_SCOPES, *VikingURI.LEGACY_SCOPES, *VikingURI.ALIAS_SCOPES} + {"", *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 cf710ff2872..d9124442a0d 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 47d6da87456..c5d1453d4be 100644 --- a/sdk/typescript/tests/client.test.ts +++ b/sdk/typescript/tests/client.test.ts @@ -659,7 +659,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, @@ -671,7 +671,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_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_agent_experience_context_provider.py b/tests/session/memory/test_agent_experience_context_provider.py index 1a0660c66fd..c1a94491906 100644 --- a/tests/session/memory/test_agent_experience_context_provider.py +++ b/tests/session/memory/test_agent_experience_context_provider.py @@ -140,7 +140,7 @@ async def test_agent_experience_prefetch_includes_structured_read_results(): "task_query": "Discuss the album release party.", "retrieval_anchor": "Stage: final_response; Boundary: completed discussion.", "case_name": "discussion_case", - "source_archive_uri": "viking://session/previous/archive/001", + "source_archive_uri": "viking://user/default/sessions/previous/archive/001", "last_update_trace_id": "source-trace-id", "version": 3, }, 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 dc03dede342..5bafb870a22 100644 --- a/web-studio/src/routes/filesystem/-components/terminal-panel.tsx +++ b/web-studio/src/routes/filesystem/-components/terminal-panel.tsx @@ -468,7 +468,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}`, } } @@ -1173,7 +1173,7 @@ export function TerminalPanel({ id, formatJson(result), ]), - refs: [{ uri: `viking://session/${id}` }], + refs: [{ uri: `viking://~/sessions/${id}` }], }) } return @@ -1531,7 +1531,7 @@ export function TerminalPanel({ const sessionRef = (id: string): ResourceRef => ({ label: id, meta: 'session', - uri: `viking://session/${id}`, + uri: `viking://~/sessions/${id}`, }) switch (subcommand) { @@ -1642,7 +1642,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}`, @@ -1732,7 +1732,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}`, @@ -1765,7 +1765,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: [ {