Self-evolving Context Database for AI Agents. Unify Agent Memory, Knowledge RAG and Skills.
Python agent-contextagent-memoryagent-pluginsagentic-ragcontext-databasedsh-pluginknowledge-basememorymemory-managementself-evolvingvector-database
feat(session): 将 session 存储到 user 命名空间 (#2556)
Qin Haojiee06671b351b8
diff --git a/crates/ov_cli/src/commands/session.rs b/crates/ov_cli/src/commands/session.rsindex 93b5bd560..90e27d6f4 100644--- a/crates/ov_cli/src/commands/session.rs+++ b/crates/ov_cli/src/commands/session.rs@@ -63,9 +63,6 @@ fn render_session_get_for_table(value: &Value) -> Option<String> {lines.push(String::new());lines.push(theme::heading("Identity").bold().to_string());push_optional_row(&mut lines, "created by", object.get("created_by_user_id"));- if let Some(users) = object.get("participant_user_ids") {- push_row(&mut lines, "participants", &format_list(users));- }if let Some(user) = object.get("user").and_then(Value::as_object) {push_row(&mut lines, "active user", &format_identity(user));}@@ -159,18 +156,6 @@ fn pad_label(label: &str, width: usize) -> String {}}-fn format_list(value: &Value) -> String {- if let Some(items) = value.as_array() {- return items- .iter()- .map(format_json_value)- .filter(|value| !value.is_empty() && value != "null")- .collect::<Vec<_>>()- .join(", ");- }- format_json_value(value)-}-fn format_identity(object: &serde_json::Map<String, Value>) -> String {["account_id", "user_id"].into_iter()@@ -477,7 +462,6 @@ mod tests {"created_at": "2026-05-26T09:53:03.661Z","updated_at": "2026-05-26T10:00:07.603Z","created_by_user_id": "haozhe",- "participant_user_ids": ["haozhe"],"message_count": 0,"commit_count": 1,"memories_extracted": {diff --git a/docs/en/api/03-filesystem.md b/docs/en/api/03-filesystem.mdindex e7b46fbce..ec9a2724e 100644--- a/docs/en/api/03-filesystem.md+++ b/docs/en/api/03-filesystem.md@@ -136,7 +136,7 @@ Read L2 full content.**Notes**- `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.-- Public URI parameters accept `resources`, `user`, `agent`, and `session` scopes. Internal scopes such as `temp` and `queue` return `INVALID_URI`.+- Public URI parameters accept `resources` and `user` scopes. For session files, use `viking://user/{user_id}/sessions/{session_id}` or the backward-compatible `viking://session/{session_id}` alias. Internal scopes such as `temp` and `queue` return `INVALID_URI`.**Python SDK (Embedded / HTTP)**@@ -1148,12 +1148,12 @@ Imports a `.ovpack` file to a specified location for restoring or migrating data- The API no longer accepts `vectorize` or `force`.- `vector_mode=auto` restores a compatible dense snapshot when present, otherwise recomputes vectors. `recompute` always ignores package vectors. `require` fails unless a compatible dense snapshot is present.- Dense snapshot compatibility checks compare embedding provider, model, input mode, query/document parameters, and dimensions.-- Session imports restore session files and do not trigger vectorization.+- Session files are part of the user namespace (`viking://user/{user_id}/sessions/...`) and do not trigger vectorization.- `on_conflict=fail` returns a structured `409 CONFLICT` when the target root already exists.- `on_conflict=overwrite` replaces the existing target root. `on_conflict=skip` keeps the existing target root and returns it without writing package contents. `skip` is root-level, not file-level.- Packages without a manifest are rejected by default because they cannot provide content integrity guarantees.- Packages with manifest entries are rejected if content files or directories are missing, extra files or directories are present, file sizes differ, per-file `sha256` differs, or `content_sha256` is missing or differs.-- Packages whose manifest `format_version` is not the current supported version are rejected.+- Packages whose manifest `format_version` is not the current supported version (`3`) are rejected.- `.abstract.md` and `.overview.md` are restored as semantic sidecars. `.relations.json` and OVPack internals are excluded.- Manifest `context_type`, when present in index scalar metadata, must match the final import path semantics.- Top-level scope packages such as `viking://resources/` must be imported to `viking://`.@@ -1248,8 +1248,9 @@ ov import ./exports/my-project.ovpack viking://resources/imported/ --vector-mode### backup_ovpackBack up public scope roots as a restore-only `.ovpack` file. The backup includes-`resources`, `user`, `agent`, and `session`; it excludes internal runtime data-such as `temp` and `queue`. Set `include_vectors=true` to include compatible+`resources` and `user`; sessions are included through the user namespace under+`user/{user_id}/sessions`. It excludes internal runtime data such as `temp` and+`queue`. Set `include_vectors=true` to include compatiblepure-dense vector snapshots; hybrid index types reject vector snapshot export.```@@ -1277,7 +1278,8 @@ ov backup ./backups/openviking.ovpack --include-vectorsRestore a backup package created by `backup_ovpack` to the original public scoperoots. Regular import rejects backup packages. Vector handling follows-`vector_mode`; session files are restored without vectorization.+`vector_mode`; session files under the user namespace are restored without+vectorization.| Parameter | Type | Required | Default | Description ||-----------|------|----------|---------|-------------|diff --git a/docs/en/api/05-sessions.md b/docs/en/api/05-sessions.mdindex 72bc15add..0a61588ac 100644--- a/docs/en/api/05-sessions.md+++ b/docs/en/api/05-sessions.md@@ -5,6 +5,16 @@ Sessions manage conversation state, track context usage, and extract long-term m- L1 (overview): Key decisions- L2 (messages): Complete messages+Sessions are stored under the current user's namespace:++```text+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.+## API Reference### create_session()@@ -85,6 +95,7 @@ ov session new"status": "ok","result": {"session_id": "a1b2c3d4",+ "uri": "viking://user/alice/sessions/a1b2c3d4","user": {"account_id": "default","user_id": "alice"@@ -152,12 +163,12 @@ ov session list"result": [{"session_id": "a1b2c3d4",- "uri": "viking://session/alice/a1b2c3d4",+ "uri": "viking://user/alice/sessions/a1b2c3d4","is_dir": true},{"session_id": "e5f6g7h8",- "uri": "viking://session/alice/e5f6g7h8",+ "uri": "viking://user/alice/sessions/e5f6g7h8","is_dir": true}],@@ -965,7 +976,7 @@ ov session commit a1b2c3d4"session_id": "a1b2c3d4","status": "accepted","task_id": "uuid-xxx",- "archive_uri": "viking://session/alice/a1b2c3d4/history/archive_001",+ "archive_uri": "viking://user/alice/sessions/a1b2c3d4/history/archive_001","archived": true}}@@ -1087,7 +1098,7 @@ print(f"Status: {task['status']}")"status": "completed","result": {"session_id": "a1b2c3d4",- "archive_uri": "viking://session/alice/a1b2c3d4/history/archive_001",+ "archive_uri": "viking://user/alice/sessions/a1b2c3d4/history/archive_001","memories_extracted": {"profile": 1,"preferences": 2,@@ -1177,7 +1188,7 @@ curl -X GET "http://localhost:1933/api/v1/tasks?task_type=session_commit&status=| Property | Type | Description ||----------|------|-------------|-| uri | str | Session Viking URI (`viking://session/{session_id}/`) |+| uri | str | Session Viking URI (`viking://user/{user_id}/sessions/{session_id}/`) || messages | List[Message] | Current messages in the session || stats | SessionStats | Session statistics || summary | str | Compression summary |@@ -1188,7 +1199,7 @@ curl -X GET "http://localhost:1933/api/v1/tasks?task_type=session_commit&status=## Session Storage Structure```-viking://session/{user_id}/{session_id}/+viking://user/{user_id}/sessions/{session_id}/+-- .abstract.md # L0: Session overview+-- .overview.md # L1: Key decisions+-- messages.jsonl # Current messages@@ -1215,7 +1226,7 @@ Each commit writes a `memory_diff.json` to the archive directory, recording all```json{- "archive_uri": "viking://session/{session_id}/history/archive_001",+ "archive_uri": "viking://user/{user_id}/sessions/{session_id}/history/archive_001","extracted_at": "2026-04-21T10:00:00Z","operations": {"adds": [diff --git a/docs/en/api/07-system.md b/docs/en/api/07-system.mdindex da1cd70a1..87f6ada38 100644--- a/docs/en/api/07-system.md+++ b/docs/en/api/07-system.md@@ -403,7 +403,9 @@ The HTTP request body rejects unknown fields. `uri` may use OpenViking path vari- `viking://user/<user_id>/skills`- `viking://user/<user_id>/skills/<skill_name>`-`viking://session/...` is not supported by `reindex()`.+Session namespaces are not supported by `reindex()`. Requests for+`viking://session/...` or `viking://user/<user_id>/sessions/...` are rejected;+when reindexing a broader user namespace, session subtrees are skipped.**Modes**diff --git a/docs/en/api/08-admin.md b/docs/en/api/08-admin.mdindex ab4f24337..6d8de19c3 100644--- a/docs/en/api/08-admin.md+++ b/docs/en/api/08-admin.md@@ -262,7 +262,7 @@ Delete a workspace and all associated users and data (ROOT only).**Processing Flow:**1. Verify requester has ROOT privileges-2. Cascade delete all AGFS data for the account (user/, agent/, session/, resources/)+2. Cascade delete all AGFS data for the account (`user/` and `resources/`; sessions live under `user/`)3. Cascade delete all vector DB records for the account4. Finally delete account metadata and all user keysdiff --git a/docs/en/concepts/04-viking-uri.md b/docs/en/concepts/04-viking-uri.mdindex e2ce9dcfe..a588e646c 100644--- a/docs/en/concepts/04-viking-uri.md+++ b/docs/en/concepts/04-viking-uri.md@@ -9,7 +9,7 @@ viking://{scope}/{path}```- **scheme**: Always `viking`-- **scope**: Top-level namespace (`resources`, `user`, `agent`, `session`; `temp` and `queue` are internal)+- **scope**: Top-level namespace (`resources`, `user`; `temp`, `queue`, and `upload` are internal)- **path**: Resource path within the scope## Scopes@@ -17,16 +17,17 @@ viking://{scope}/{path}| Scope | Description | Lifecycle | Visibility ||-------|-------------|-----------|------------|| **resources** | Independent resources | Long-term | Global |-| **user** | User-level data | Long-term | Global |-| **agent** | Agent-level data | Long-term | Global |-| **session** | Session-level data | Session lifetime | Current session |+| **user** | User-level data, including sessions | Long-term / session lifetime | Current user || **queue** | Processing queue | Temporary | Internal || **temp** | Temporary files | During parsing | Internal |+| **upload** | Temporary upload files | Temporary | Internal |-Public API and CLI filesystem/content operations accept only the public scopes:-`resources`, `user`, `agent`, and `session` (plus the root URI `viking://`).-`temp` and `queue` are internal implementation scopes and cannot be addressed-directly through public API URI parameters.+Public API and CLI filesystem/content operations accept the public scopes+`resources` and `user` (plus the root URI `viking://`). `session` is retained+as a backward-compatible alias for user session paths; new session data lives+under `viking://user/{user_id}/sessions`.+`agent` is deprecated. `temp`, `queue`, and `upload` are internal implementation+scopes and cannot be addressed directly through public API URI parameters.## Initial Directory Structure@@ -34,33 +35,19 @@ Moving away from traditional flat database thinking, all context is organized as```viking://-├── session/{session_id}/-│ ├── .abstract.md # L0: One-line session summary-│ ├── .overview.md # L1: Session overview-│ ├── .meta.json # Session metadata-│ ├── messages.json # Structured message storage-│ ├── checkpoints/ # Version snapshots-│ ├── summaries/ # Compression summary history-│ └── .relations.json # Relations table-│├── user/-│ ├── .abstract.md # L0: Content summary-│ ├── .overview.md # User profile-│ └── memories/ # User memory storage-│ ├── .overview.md # Memory overview-│ ├── preferences/ # User preferences-│ ├── entities/ # Entity memories-│ └── events/ # Event records-│-├── agent/-│ ├── .abstract.md # L0: Content summary-│ ├── .overview.md # Agent overview-│ ├── memories/ # Agent learning memories-│ │ ├── .overview.md-│ │ ├── cases/ # Cases-│ │ └── patterns/ # Patterns-│ ├── instructions/ # Agent instructions-│ └── skills/ # Skills directory+│ └── {user_id}/+│ ├── profile.md # User profile+│ ├── memories/ # User memory storage+│ ├── skills/ # User skills+│ └── sessions/ # User session storage+│ └── {session_id}/+│ ├── .abstract.md+│ ├── .overview.md+│ ├── .meta.json+│ ├── messages.jsonl+│ ├── tools/+│ └── history/│└── resources/{project}/ # Resource workspace```@@ -104,12 +91,17 @@ OpenViking expands it internally to explicit namespace paths such as### Session Data```-viking://session/{session_id}/ # Session root-viking://session/{session_id}/messages/ # Session messages-viking://session/{session_id}/tools/ # Tool executions-viking://session/{session_id}/history/ # Archived history+viking://user/{user_id}/sessions/{session_id}/ # Session root+viking://user/{user_id}/sessions/{session_id}/messages # Session messages+viking://user/{user_id}/sessions/{session_id}/tools # Tool executions+viking://user/{user_id}/sessions/{session_id}/history # Archived history+viking://user/sessions/{session_id}/ # Current-user short form```+`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.+## Path VariablesViking URI supports path variables for dynamic path generation. This is especially useful for organizing time-series data like emails, logs, daily reports, etc.@@ -202,8 +194,8 @@ viking://│ ├── entities/ # Each independent│ └── events/ # Each independent│-└── session/{user_space}/{session_id}/- ├── messages/+└── user/{user_id}/sessions/{session_id}/+ ├── messages.jsonl├── tools/└── history/```diff --git a/docs/en/concepts/08-session.md b/docs/en/concepts/08-session.mdindex 9da0c445b..d547af250 100644--- a/docs/en/concepts/08-session.md+++ b/docs/en/concepts/08-session.md@@ -62,7 +62,7 @@ result = session.commit()# {# "status": "accepted",# "task_id": "uuid-xxx",-# "archive_uri": "viking://session/.../history/archive_001",+# "archive_uri": "viking://user/{user_id}/sessions/.../history/archive_001",# "archived": True# }@@ -175,7 +175,7 @@ Each `session.commit()` writes a `memory_diff.json` to the archive directory, re```json{- "archive_uri": "viking://session/{session_id}/history/archive_001",+ "archive_uri": "viking://user/{user_id}/sessions/{session_id}/history/archive_001","extracted_at": "2026-04-21T10:00:00Z","operations": {"adds": [@@ -223,7 +223,7 @@ An empty `memory_diff.json` (all counts zero) is written even when no memory ope## Storage Structure```-viking://session/{session_id}/+viking://user/{user_id}/sessions/{session_id}/├── messages.jsonl # Current messages├── .abstract.md # Current abstract├── .overview.md # Current overview@@ -251,6 +251,12 @@ viking://user/memories/└── skills/```+`viking://user/sessions/{session_id}` is accepted as a short form relative to+the current request user and is canonicalized to+`viking://user/{user_id}/sessions/{session_id}`. The old+`viking://session/{session_id}` form is accepted as a backward-compatible alias+for the same current-user session path and is not a separate storage root.+## Related Documents- [Architecture Overview](./01-architecture.md) - System architecturediff --git a/docs/en/guides/05-observability.md b/docs/en/guides/05-observability.mdindex d30b77eaf..9b3e5e70c 100644--- a/docs/en/guides/05-observability.md+++ b/docs/en/guides/05-observability.md@@ -135,7 +135,8 @@ Prerequisites:This TUI is useful for two kinds of inspection:-- checking what actually exists under `viking://resources`, `viking://user`, and `viking://session`+- checking what actually exists under `viking://resources` and `viking://user`+ (sessions live under `viking://user/{user_id}/sessions`)- checking whether vector records for a URI were actually written, and how many there areCommon keys:diff --git a/docs/en/guides/09-ovpack.md b/docs/en/guides/09-ovpack.mdindex 70796f954..7dc45c85b 100644--- a/docs/en/guides/09-ovpack.md+++ b/docs/en/guides/09-ovpack.md@@ -16,14 +16,16 @@ Regular `export/import` handles one package root:- `viking://resources/...`- `viking://user/...`-- `viking://session/...`Full migration uses the separate `backup/restore` flow. It packages publicscope roots together:- `viking://resources`- `viking://user`-- `viking://session`++Sessions are included through the user namespace at+`viking://user/{user_id}/sessions/{session_id}`. The+`viking://session/...` alias is not an OVPack v3 import/export scope.Internal or runtime data such as `temp`, `queue`, `upload`, lock files, watchcontrol files, and `.relations.json` are outside the OVPack migration scope.@@ -244,7 +246,7 @@ curl -X POST http://localhost:1933/api/v1/pack/backup \## Package Layout-OVPack v2 is a standard ZIP archive with one package root directory:+OVPack v3 is a standard ZIP archive with one package root directory:```textmy-project/@@ -268,7 +270,7 @@ internal index files. It does not inline per-file index records:```json{"kind": "openviking.ovpack",- "format_version": 2,+ "format_version": 3,"root": {"name": "my-project","uri": "viking://resources/my-project",@@ -365,7 +367,7 @@ Import validates the entire package before writing package content. Core checks:6. Each file `size` and `sha256` must match actual content.7. `content_sha256` must match the sorted file inventory.8. `_ovpack/index_records.jsonl` and optional `_ovpack/dense.f32` must match manifest hashes, counts, and dimensions.-9. Source scope and target scope must match; structured scopes such as `user`, `agent`, and `session` also keep root depth stable.+9. Source scope and target scope must match; structured scopes such as `user` also keep root depth stable.10. No package content is written before validation passes; conflict handling also runs before writes.Typical rejection examples:@@ -404,14 +406,15 @@ ov import ./exports/resources.ovpack viking:// --on-conflict overwriteThese imports are rejected:```bash-# A resources package cannot be imported into session.-ov import ./exports/a.ovpack viking://session/+# A resources package cannot be imported into user.+ov import ./exports/a.ovpack viking://user/alice/-# A session subtree cannot be imported into resources.+# A user session subtree cannot be imported into resources.ov import ./exports/sess_123.ovpack viking://resources/-# A session subtree cannot use itself as parent, which would create session/sess_123/sess_123.-ov import ./exports/sess_123.ovpack viking://session/sess_123/+# A session subtree cannot use itself as parent, which would create+# sessions/sess_123/sess_123.+ov import ./exports/sess_123.ovpack viking://user/alice/sessions/sess_123/```## Memories and Sessions@@ -426,33 +429,31 @@ ov export viking://user/default/memories ./exports/user-memories.ovpackov import ./exports/user-memories.ovpack viking://user/default/ --on-conflict overwrite```-User memories:+Session data:```bash-ov export viking://user/default/memories ./exports/agent-memories.ovpack-ov import ./exports/agent-memories.ovpack viking://user/default/ --on-conflict overwrite+ov export viking://user/alice/sessions/sess_123 ./exports/sess_123.ovpack+ov import ./exports/sess_123.ovpack viking://user/alice/sessions/ --on-conflict overwrite```-Sessions restore file state only and do not trigger vectorization:--```bash-ov export viking://session/sess_123 ./exports/sess_123.ovpack-ov import ./exports/sess_123.ovpack viking://session/ --on-conflict overwrite-```+Sessions restore file state only and do not trigger vectorization.Result:```text-viking://session/sess_123+viking://user/alice/sessions/sess_123```## Old Packages and Future Versions-The current implementation only accepts OVPack v2. Legacy packages without a+The current implementation only accepts OVPack v3. Legacy packages without amanifest do not provide a file set, directory set, or checksums, so OpenVikingcannot tell whether content was removed, modified, or mixed in. They arerejected by default. To migrate a legacy package, import it in a trusted old-environment first, then re-export it with the current version.+environment first, then re-export it with OVPack v3.++OVPack v2 packages are also rejected by current OpenViking. Re-export old+packages with a current server before importing them here.Future package versions are not silently accepted either. Upgrade OpenViking orre-export from an environment that can read that version.@@ -461,11 +462,11 @@ re-export from an environment that can read that version.| Error | Common cause | Fix || --- | --- | --- |-| `Missing ovpack manifest` | Legacy package without a manifest | Re-export as v2 in a trusted environment. |+| `Missing ovpack manifest` | Legacy package without a manifest | Re-export as v3 in a trusted environment. || `Unsupported ovpack format_version` | Package format version is not currently supported | Upgrade OpenViking or re-export. || `sha256 does not match manifest` | File or internal index content was changed | Discard the package or re-export from a trusted source. || `ovpack entries do not match manifest` | ZIP content is missing files/directories or includes extra files/directories | Discard the package or re-export. |-| `source scope does not match target scope` | Cross-scope import, such as session into resources | Import into a parent directory in the same scope. |+| `source scope does not match target scope` | Cross-scope import, such as user into resources | Import into a parent directory in the same scope. || `source path is incompatible with target path` | Structured scope root depth would change | Import into the correct system parent directory. || `Top-level scope ovpack packages must be imported to viking://` | A top-level scope package was imported to a non-root parent | Import to `viking://`. || `Backup ovpack packages must be restored` | A backup package was imported with regular import | Use `ov restore`. |diff --git a/docs/zh/api/03-filesystem.md b/docs/zh/api/03-filesystem.mdindex 39b9e5304..fd7485f4d 100644--- a/docs/zh/api/03-filesystem.md+++ b/docs/zh/api/03-filesystem.md@@ -136,7 +136,7 @@ openviking overview viking://resources/docs/**说明**- `read()` 只接受文件 URI。传入已存在的目录 URI 时返回 `INVALID_ARGUMENT`(`400`),而不是 `NOT_FOUND`。该错误会携带结构化的 `details` 字段——`details.expected` 为 `"file"`,`details.actual` 为 `"directory"`,`details.resource` 为出错的 URI(HTTP 路径上会带上)——客户端据此即可以编程方式判断"文件 vs 目录"不匹配(例如回退到 `list`),而无需对错误消息做字符串匹配。-- 公开 URI 参数只接受 `resources`、`user`、`agent`、`session` 作用域。`temp`、`queue` 等内部作用域会返回 `INVALID_URI`。+- 公开 URI 参数接受 `resources` 和 `user` 作用域。访问 session 文件时,使用 `viking://user/{user_id}/sessions/{session_id}`,也可以使用向后兼容的 `viking://session/{session_id}` 别名。`temp`、`queue` 等内部作用域会返回 `INVALID_URI`。**Python SDK (Embedded / HTTP)**@@ -1149,12 +1149,12 @@ ov export viking://resources/my-project/ ./exports/my-project.ovpack --include-v- API 已不再接受 `vectorize` 或 `force`。- `vector_mode=auto` 会在存在兼容 dense 快照时直接恢复,否则重新向量化;`recompute` 总是忽略包内向量;`require` 要求必须存在兼容 dense 快照,否则导入失败。- dense 快照兼容性会比较 embedding provider、model、input、query/document 参数和维度。-- Session 导入只恢复 session 文件状态,不触发向量化。+- Session 文件属于 user 命名空间(`viking://user/{user_id}/sessions/...`),恢复后不触发向量化。- `on_conflict=fail` 且目标 root 已存在时,会返回结构化的 `409 CONFLICT`。- `on_conflict=overwrite` 会替换已有目标 root。`on_conflict=skip` 会保留已有目标 root,并直接返回该路径,不写入包内容。`skip` 是 root 级跳过,不是文件级补齐。- 默认拒绝没有 manifest 的包,因为这类包无法提供内容完整性校验。- 带 manifest entries 的包如果缺少内容文件或目录、混入额外文件或目录、文件大小不同、单文件 `sha256` 不同,或整体 `content_sha256` 缺失/不匹配,都会被拒绝导入。-- manifest `format_version` 不是当前支持版本的包会被拒绝。+- manifest `format_version` 不是当前支持版本(`3`)的包会被拒绝。- `.abstract.md` 和 `.overview.md` 会作为语义侧边文件恢复;`.relations.json` 和 OVPack 内部文件会被排除。- manifest index 标量中的 `context_type` 如果存在,必须和最终导入路径语义一致。- `viking://resources/` 这类顶级 scope 包必须导入到 `viking://`。@@ -1249,7 +1249,8 @@ ov import ./exports/my-project.ovpack viking://resources/imported/ --vector-mode### backup_ovpack将公开 scope root 备份为只能通过 restore 恢复的 `.ovpack` 文件。备份包含-`resources`、`user`、`agent`、`session`,不包含 `temp`、`queue` 等内部运行态数据。+`resources` 和 `user`;session 会通过 user 命名空间下的 `user/{user_id}/sessions`+一起包含,不包含 `temp`、`queue` 等内部运行态数据。设置 `include_vectors=true` 时,会额外导出兼容的纯 dense 向量快照;底层 index type 为 hybrid 时会拒绝导出向量快照。```@@ -1276,7 +1277,7 @@ ov backup ./backups/openviking.ovpack --include-vectors### restore_ovpack恢复 `backup_ovpack` 生成的备份包到原始公开 scope root。普通 import 不接受备份包。-向量处理遵循 `vector_mode`;session 只恢复文件状态。+向量处理遵循 `vector_mode`;user 命名空间下的 session 文件只恢复文件状态,不触发向量化。| 参数 | 类型 | 必填 | 默认值 | 说明 ||------|------|------|--------|------|diff --git a/docs/zh/api/05-sessions.md b/docs/zh/api/05-sessions.mdindex f70593026..5e531b745 100644--- a/docs/zh/api/05-sessions.md+++ b/docs/zh/api/05-sessions.md@@ -5,6 +5,16 @@- L1(overview): 关键决策和总结- L2(messages): 完整消息+会话存储在当前用户命名空间下:++```text+viking://user/{user_id}/sessions/{session_id}+```++Session API 按认证用户作用域访问会话,并返回 canonical user session URI。+基于 URI 的 API 也可以接受向后兼容的 `viking://session/{session_id}` 别名,+该别名会在同一个用户上下文中解析。+## API 参考### create_session()@@ -85,6 +95,7 @@ ov session new"status": "ok","result": {"session_id": "a1b2c3d4",+ "uri": "viking://user/alice/sessions/a1b2c3d4","user": {"account_id": "default","user_id": "alice"@@ -152,12 +163,12 @@ ov session list"result": [{"session_id": "a1b2c3d4",- "uri": "viking://session/alice/a1b2c3d4",+ "uri": "viking://user/alice/sessions/a1b2c3d4","is_dir": true},{"session_id": "e5f6g7h8",- "uri": "viking://session/alice/e5f6g7h8",+ "uri": "viking://user/alice/sessions/e5f6g7h8","is_dir": true}],@@ -965,7 +976,7 @@ ov session commit a1b2c3d4"session_id": "a1b2c3d4","status": "accepted","task_id": "uuid-xxx",- "archive_uri": "viking://session/alice/a1b2c3d4/history/archive_001",+ "archive_uri": "viking://user/alice/sessions/a1b2c3d4/history/archive_001","archived": true}}@@ -1087,7 +1098,7 @@ print(f"Status: {task['status']}")"status": "completed","result": {"session_id": "a1b2c3d4",- "archive_uri": "viking://session/alice/a1b2c3d4/history/archive_001",+ "archive_uri": "viking://user/alice/sessions/a1b2c3d4/history/archive_001","memories_extracted": {"profile": 1,"preferences": 2,@@ -1175,7 +1186,7 @@ curl -X GET "http://localhost:1933/api/v1/tasks?task_type=session_commit&status=| 属性 | 类型 | 说明 ||------|------|------|-| uri | str | 会话 Viking URI(`viking://session/{session_id}/`) |+| uri | str | 会话 Viking URI(`viking://user/{user_id}/sessions/{session_id}/`) || messages | List[Message] | 会话中的当前消息 || stats | SessionStats | 会话统计信息 || summary | str | 压缩摘要 |@@ -1186,7 +1197,7 @@ curl -X GET "http://localhost:1933/api/v1/tasks?task_type=session_commit&status=## 会话存储结构```-viking://session/{user_id}/{session_id}/+viking://user/{user_id}/sessions/{session_id}/├── .abstract.md # L0:会话概览├── .overview.md # L1:关键决策├── .meta.json # 元数据@@ -1213,7 +1224,7 @@ viking://session/{user_id}/{session_id}/```json{- "archive_uri": "viking://session/{session_id}/history/archive_001",+ "archive_uri": "viking://user/{user_id}/sessions/{session_id}/history/archive_001","extracted_at": "2026-04-21T10:00:00Z","operations": {"adds": [diff --git a/docs/zh/api/07-system.md b/docs/zh/api/07-system.mdindex 42876b99e..0e986d0ad 100644--- a/docs/zh/api/07-system.md+++ b/docs/zh/api/07-system.md@@ -397,7 +397,9 @@ HTTP 请求体不接受未知字段。`uri` 可以使用其他 content API 支- `viking://user/<user_id>/skills`- `viking://user/<user_id>/skills/<skill_name>`-`reindex()` 不支持 `viking://session/...`。+`reindex()` 不支持会话命名空间。请求 `viking://session/...` 或+`viking://user/<user_id>/sessions/...` 会被拒绝;重建更大的 user 命名空间时,+session 子树会被跳过。**模式说明**diff --git a/docs/zh/api/08-admin.md b/docs/zh/api/08-admin.mdindex 5ee1517e8..3df10861e 100644--- a/docs/zh/api/08-admin.md+++ b/docs/zh/api/08-admin.md@@ -260,7 +260,7 @@ ov --sudo admin list-accounts**处理流程:**1. 验证请求者具有 ROOT 权限-2. 级联删除账户下的所有 AGFS 数据(user/、agent/、session/、resources/)+2. 级联删除账户下的所有 AGFS 数据(`user/` 和 `resources/`;sessions 位于 `user/` 下)3. 级联删除向量数据库中该账户的所有记录4. 最后删除账户元数据和所有用户密钥diff --git a/docs/zh/concepts/04-viking-uri.md b/docs/zh/concepts/04-viking-uri.mdindex 1bf29e47b..bbfcada4b 100644--- a/docs/zh/concepts/04-viking-uri.md+++ b/docs/zh/concepts/04-viking-uri.md@@ -9,7 +9,7 @@ viking://{scope}/{path}```- **scheme**: 始终为 `viking`-- **scope**: 顶级命名空间(`resources`、`user`、`agent`、`session`;`temp` 和 `queue` 为内部作用域)+- **scope**: 顶级命名空间(`resources`、`user`;`temp`、`queue` 和 `upload` 为内部作用域)- **path**: 作用域内的资源路径## 作用域@@ -17,15 +17,15 @@ viking://{scope}/{path}| 作用域 | 说明 | 生命周期 | 可见性 ||--------|------|----------|--------|| **resources** | 独立资源 | 长期 | 全局 |-| **user** | 用户级数据 | 长期 | 全局 |-| **agent** | Agent 级数据 | 长期 | 全局 |-| **session** | 会话级数据 | 会话生命周期 | 当前会话 |+| **user** | 用户级数据,包括 session | 长期 / 会话生命周期 | 当前用户 || **queue** | 处理队列 | 临时 | 内部 || **temp** | 临时文件 | 解析期间 | 内部 |+| **upload** | 临时上传文件 | 临时 | 内部 |-公开 API 和 CLI 的文件系统/内容操作只接受公开作用域:-`resources`、`user`、`agent`、`session`,以及根 URI `viking://`。-`temp` 和 `queue` 是内部实现作用域,不能通过公开 API 的 URI 参数直接访问。+公开 API 和 CLI 的文件系统/内容操作接受公开作用域 `resources` 和 `user`,+以及根 URI `viking://`。`session` 保留为 user session 路径的向后兼容别名;+新 session 数据位于 `viking://user/{user_id}/sessions`。`agent` 已废弃。+`temp`、`queue` 和 `upload` 是内部实现作用域,不能通过公开 API 的 URI 参数直接访问。## 初始目录@@ -33,33 +33,19 @@ viking://{scope}/{path}```viking://-├── session/{session_id}/-│ ├── .abstract.md # L0: 会话一句话摘要-│ ├── .overview.md # L1: 会话概览-│ ├── .meta.json # 会话元数据-│ ├── messages.json # 结构化消息存储-│ ├── checkpoints/ # 版本快照-│ ├── summaries/ # 压缩摘要历史-│ └── .relations.json # 关联表-│├── user/-│ ├── .abstract.md # L0: 内容摘要-│ ├── .overview.md # 用户画像-│ └── memories/ # 用户记忆存储-│ ├── .overview.md # 记忆概览-│ ├── preferences/ # 用户偏好-│ ├── entities/ # 实体记忆-│ └── events/ # 事件记录-│-├── agent/-│ ├── .abstract.md # L0: 内容摘要-│ ├── .overview.md # Agent概览-│ ├── memories/ # Agent学习记忆-│ │ ├── .overview.md-│ │ ├── cases/ # 案例-│ │ └── patterns/ # 模式-│ ├── instructions/ # Agent指令-│ └── skills/ # 技能目录+│ └── {user_id}/+│ ├── profile.md # 用户画像+│ ├── memories/ # 用户记忆+│ ├── skills/ # 用户技能+│ └── sessions/ # 用户会话+│ └── {session_id}/+│ ├── .abstract.md+│ ├── .overview.md+│ ├── .meta.json+│ ├── messages.jsonl+│ ├── tools/+│ └── history/│└── resources/{project}/ # 资源工作区```@@ -103,12 +89,16 @@ OpenViking 会在存储和检索前将它展开为显式命名空间路径,例### 会话数据```-viking://session/{session_id}/ # 会话根目录-viking://session/{session_id}/messages/ # 会话消息-viking://session/{session_id}/tools/ # 工具执行-viking://session/{session_id}/history/ # 归档历史+viking://user/{user_id}/sessions/{session_id}/ # 会话根目录+viking://user/{user_id}/sessions/{session_id}/messages # 会话消息+viking://user/{user_id}/sessions/{session_id}/tools # 工具执行+viking://user/{user_id}/sessions/{session_id}/history # 归档历史+viking://user/sessions/{session_id}/ # 当前用户短路径```+`viking://session/{session_id}` 会作为当前用户 session 路径的向后兼容别名被接受。+它不是新会话数据的独立存储根。+## 路径变量Viking URI 支持路径变量用于动态路径生成。这对于按时间序列组织数据(如邮件、日志、日报等)特别有用。@@ -201,8 +191,8 @@ viking://│ ├── entities/ # 每条独立│ └── events/ # 每条独立│-└── session/{session_id}/- ├── messages/+└── user/{user_id}/sessions/{session_id}/+ ├── messages.jsonl├── tools/└── history/```diff --git a/docs/zh/concepts/08-session.md b/docs/zh/concepts/08-session.mdindex d93c0b2e3..982b07bb0 100644--- a/docs/zh/concepts/08-session.md+++ b/docs/zh/concepts/08-session.md@@ -62,7 +62,7 @@ result = session.commit()# {# "status": "accepted",# "task_id": "uuid-xxx",-# "archive_uri": "viking://session/.../history/archive_001",+# "archive_uri": "viking://user/{user_id}/sessions/.../history/archive_001",# "archived": True# }@@ -175,7 +175,7 @@ LLM 去重决策 → candidate(skip/create/none) + item(merge/delete)```json{- "archive_uri": "viking://session/{session_id}/history/archive_001",+ "archive_uri": "viking://user/{user_id}/sessions/{session_id}/history/archive_001","extracted_at": "2026-04-21T10:00:00Z","operations": {"adds": [@@ -223,7 +223,7 @@ LLM 去重决策 → candidate(skip/create/none) + item(merge/delete)## 存储结构```-viking://session/{session_id}/+viking://user/{user_id}/sessions/{session_id}/├── messages.jsonl # 当前消息├── .abstract.md # 当前摘要├── .overview.md # 当前概览@@ -251,6 +251,11 @@ viking://user/memories/└── skills/```+`viking://user/sessions/{session_id}` 是相对当前请求用户的短路径,服务端会将其+规范化为 `viking://user/{user_id}/sessions/{session_id}`。+`viking://session/{session_id}` 会作为同一个当前用户 session 路径的向后兼容别名+被接受,不是独立的存储根。+## 相关文档- [架构概述](./01-architecture.md) - 系统整体架构diff --git a/docs/zh/guides/05-observability.md b/docs/zh/guides/05-observability.mdindex 8bba6ab30..63541c3f6 100644--- a/docs/zh/guides/05-observability.md+++ b/docs/zh/guides/05-observability.md@@ -135,7 +135,8 @@ ov tui viking://resources这个 TUI 适合做两类观测:-- 看 `viking://resources`、`viking://user`、`viking://session` 下实际落了哪些数据+- 看 `viking://resources` 和 `viking://user` 下实际落了哪些数据+ (session 位于 `viking://user/{user_id}/sessions`)- 看某个 URI 对应的向量记录是否已经写入,以及数量是否符合预期常用按键:diff --git a/docs/zh/guides/09-ovpack.md b/docs/zh/guides/09-ovpack.mdindex e97eee9b4..d1a7d9f45 100644--- a/docs/zh/guides/09-ovpack.md+++ b/docs/zh/guides/09-ovpack.md@@ -13,13 +13,15 @@ checksum,保证包内容没有偏离 manifest;如果攻击者能同时篡改- `viking://resources/...`- `viking://user/...`-- `viking://session/...`全量迁移使用单独的 `backup/restore`,它会把公开 scope root 一起打进备份包:- `viking://resources`- `viking://user`-- `viking://session`++Session 通过 user 命名空间一起迁移,路径为+`viking://user/{user_id}/sessions/{session_id}`。`viking://session/...`+别名不属于 OVPack v3 的导入/导出 scope。`temp`、`queue`、`upload`、锁文件、watch control 文件、`.relations.json` 等内部或运行态数据不属于 OVPack 迁移范围。@@ -225,7 +227,7 @@ curl -X POST http://localhost:1933/api/v1/pack/backup \## 包结构-OVPack v2 是标准 ZIP。ZIP 内部有一个包根目录:+OVPack v3 是标准 ZIP。ZIP 内部有一个包根目录:```textmy-project/@@ -247,7 +249,7 @@ manifest 只保存包结构、文件 checksum 和内部索引文件的 checksum```json{"kind": "openviking.ovpack",- "format_version": 2,+ "format_version": 3,"root": {"name": "my-project","uri": "viking://resources/my-project",@@ -339,7 +341,7 @@ dense 快照,也会按目标 URI、目标账号和当前时间重建运行态6. 每个文件的 `size` 和 `sha256` 必须匹配实际内容。7. `content_sha256` 必须匹配按路径排序后的文件清单。8. `_ovpack/index_records.jsonl` 和可选 `_ovpack/dense.f32` 必须匹配 manifest 中的 hash、数量和维度。-9. source scope 和 target scope 必须一致;`user`、`agent`、`session` 这类结构化 scope 还要求 root 层级一致。+9. source scope 和 target scope 必须一致;`user` 这类结构化 scope 还要求 root 层级一致。10. 校验通过前不会写入包内容;冲突策略也在写入前处理。典型拒绝示例:@@ -377,14 +379,14 @@ ov import ./exports/resources.ovpack viking:// --on-conflict overwrite以下导入会被拒绝:```bash-# resources 包不能导入 session-ov import ./exports/a.ovpack viking://session/+# resources 包不能导入 user+ov import ./exports/a.ovpack viking://user/alice/-# session 子树不能导入 resources+# user session 子树不能导入 resourcesov import ./exports/sess_123.ovpack viking://resources/-# session 子树不能把自身路径当父目录,否则会变成 session/sess_123/sess_123-ov import ./exports/sess_123.ovpack viking://session/sess_123/+# session 子树不能把自身路径当父目录,否则会变成 sessions/sess_123/sess_123+ov import ./exports/sess_123.ovpack viking://user/alice/sessions/sess_123/```## 记忆和 Session@@ -398,31 +400,28 @@ ov export viking://user/default/memories ./exports/user-memories.ovpackov import ./exports/user-memories.ovpack viking://user/default/ --on-conflict overwrite```-用户记忆:+Session 数据:```bash-ov export viking://user/default/memories ./exports/agent-memories.ovpack-ov import ./exports/agent-memories.ovpack viking://user/default/ --on-conflict overwrite+ov export viking://user/alice/sessions/sess_123 ./exports/sess_123.ovpack+ov import ./exports/sess_123.ovpack viking://user/alice/sessions/ --on-conflict overwrite```-Session 只恢复文件状态,不触发向量化:--```bash-ov export viking://session/sess_123 ./exports/sess_123.ovpack-ov import ./exports/sess_123.ovpack viking://session/ --on-conflict overwrite-```+Session 只恢复文件状态,不触发向量化。结果:```text-viking://session/sess_123+viking://user/alice/sessions/sess_123```## 旧包和未来版本-当前实现只接受 OVPack v2。旧版无 manifest 包没有文件集合、目录集合和 checksum 信息,无法判断+当前实现只接受 OVPack v3。旧版无 manifest 包没有文件集合、目录集合和 checksum 信息,无法判断是否被删改或混入内容,因此默认拒绝。需要迁移旧包时,应先在可信旧环境中导入,再用当前版本-重新导出。+重新导出为 OVPack v3。++OVPack v2 包也会被当前 OpenViking 拒绝。导入旧包前,需要先用当前版本服务重新导出。未来版本包也不会静默兼容。处理方式是升级 OpenViking,或在支持该版本的环境中重新导出为当前支持格式。@@ -431,11 +430,11 @@ viking://session/sess_123| 错误 | 常见原因 | 处理方式 || --- | --- | --- |-| `Missing ovpack manifest` | 旧版无 manifest 包 | 在可信环境重新导出为 v2。 |+| `Missing ovpack manifest` | 旧版无 manifest 包 | 在可信环境重新导出为 v3。 || `Unsupported ovpack format_version` | 包格式版本不是当前支持版本 | 升级 OpenViking 或重新导出。 || `sha256 does not match manifest` | 文件或内部索引内容被改动 | 丢弃该包,或从可信源重新导出。 || `ovpack entries do not match manifest` | ZIP 中缺文件/目录,或混入额外文件/目录 | 丢弃该包,或重新导出。 |-| `source scope does not match target scope` | 跨 scope 导入,例如 session 导入 resources | 导入到同 scope 的父目录。 |+| `source scope does not match target scope` | 跨 scope 导入,例如 user 导入 resources | 导入到同 scope 的父目录。 || `source path is incompatible with target path` | 结构化 scope 的 root 层级会改变 | 导入到正确系统父目录。 || `Top-level scope ovpack packages must be imported to viking://` | 将顶级 scope 包导入了非根父目录 | 改为导入 `viking://`。 || `Backup ovpack packages must be restored` | 用普通 import 导入 backup 包 | 使用 `ov restore`。 |diff --git a/examples/codex-memory-plugin/DESIGN.md b/examples/codex-memory-plugin/DESIGN.mdindex a1fa36c74..1244ddf7c 100644--- a/examples/codex-memory-plugin/DESIGN.md+++ b/examples/codex-memory-plugin/DESIGN.md@@ -11,7 +11,7 @@ events imply "context for a particular codex `session_id` is gone".- **codex `session_id`** — the codex thread/session id. Stable acrossprocess restarts when zouk-daemon resumes the same thread; replaced when`/clear`, `/new`, fresh codex startup, or zouk reset occurs.-- **OV session** — `viking://session/cx-<codex-session-id>`. New captures+- **OV session** — `viking://user/sessions/cx-<codex-session-id>`. New capturesderive the OV session id from the codex `session_id` with a `cx-` prefix,append messages on every `Stop`, and commit it (which triggers OV'smemory extractor) at session-end-equivalent moments. `/messages`@@ -203,7 +203,7 @@ continuity unless the most recent committed memories are surfaced.Proposed flow:1. Load state for the resumed `session_id`. If `ovSessionId` is non-null,no action — the session is still appendable.-2. Otherwise list `viking://session/cx-<codex-session-id>/history/archive_*/`+2. Otherwise list `viking://user/sessions/cx-<codex-session-id>/history/archive_*/`on the OV server, take the most recent.3. Read its abstract (L0) / overview (L1).4. Emit via `hookSpecificOutput.additionalContext` so codex injects thediff --git a/examples/codex-memory-plugin/VERIFICATION.md b/examples/codex-memory-plugin/VERIFICATION.mdindex da73dd912..65ed593ad 100644--- a/examples/codex-memory-plugin/VERIFICATION.md+++ b/examples/codex-memory-plugin/VERIFICATION.md@@ -44,7 +44,7 @@ cat $STATE_DIR/state/verify-sess.jsonOV side:```bash-OPENVIKING_CONFIG_FILE=$OV_CONF ov read viking://session/cx-verify-sess/messages.jsonl+OPENVIKING_CONFIG_FILE=$OV_CONF ov read viking://user/sessions/cx-verify-sess/messages.jsonl# 2 JSONL records: user "fuchsia", assistant "noted"```@@ -78,7 +78,7 @@ echo '{"session_id":"verify-sess","transcript_path":"'"$STATE_DIR"'/transcript.j```Expect: `appended 2 turn(s)` (only the new ones). Re-read-`viking://session/cx-verify-sess/messages.jsonl` — 4 records now.+`viking://user/sessions/cx-verify-sess/messages.jsonl` — 4 records now.## 4. PreCompact — commit + reset@@ -96,10 +96,10 @@ State file: `ovSessionId` is now `null`, `capturedTurnCount` stays at 4.OV side:```bash-OPENVIKING_CONFIG_FILE=$OV_CONF ov ls viking://session/cx-verify-sess+OPENVIKING_CONFIG_FILE=$OV_CONF ov ls viking://user/sessions/cx-verify-sess# messages.jsonl is now size 0 (archived)# history/archive_001/ exists with the committed messages-OPENVIKING_CONFIG_FILE=$OV_CONF ov read viking://session/cx-verify-sess/history/archive_001/messages.jsonl+OPENVIKING_CONFIG_FILE=$OV_CONF ov read viking://user/sessions/cx-verify-sess/history/archive_001/messages.jsonl```## 5. Post-compact Stop — same deterministic OV session iddiff --git a/examples/openclaw-plugin/README.md b/examples/openclaw-plugin/README.mdindex c737884ef..b20fb10dd 100644--- a/examples/openclaw-plugin/README.md+++ b/examples/openclaw-plugin/README.md@@ -50,7 +50,7 @@ Once installed, the plugin provides these agent tools:- **What is sent**: User/assistant message text from each turn (after stripping injected memory blocks and metadata noise).- **Where it goes**: Your configured OpenViking server (`baseUrl`). The plugin only sends data to that server; downstream model/provider data handling (embedding, VLM) depends on the server's configuration.-- **Storage**: All data lives on your OpenViking server under `viking://user/*`, `viking://resources/*`, and `viking://session/*`.+- **Storage**: All data lives on your OpenViking server under `viking://user/*` (including `viking://user/sessions/*`) and `viking://resources/*`.- **API Key**: Sent as `X-OpenViking-Key` header over your configured connection. Never logged or forwarded.- **Multi-tenant isolation**: Supports `accountId` and `userId`. Optional `peer_role` / `peer_prefix` controls whether OpenClaw speakers are written as OpenViking `peer_id`.@@ -100,7 +100,7 @@ The diagram above reflects the current implementation boundary:- OpenClaw remains the primary runtime on the left. The plugin does not take over agent execution.- The middle layer combines hooks, the context engine, tools, and runtime management in one plugin registration.- All HTTP traffic goes through `OpenVikingClient`, which centralizes tenant headers and routing logs.-- The OpenViking service owns sessions, memories, archives, and Phase 2 extraction, with storage under `viking://user/*`, `viking://resources/*`, and `viking://session/*`.+- The OpenViking service owns sessions, memories, archives, and Phase 2 extraction, with storage under `viking://user/*` (including `viking://user/sessions/*`) and `viking://resources/*`.That split lets OpenClaw stay focused on reasoning and orchestration while OpenViking becomes the source of truth for long-lived context.diff --git a/examples/openclaw-plugin/README_CN.md b/examples/openclaw-plugin/README_CN.mdindex 6db7c7165..c51f091a2 100644--- a/examples/openclaw-plugin/README_CN.md+++ b/examples/openclaw-plugin/README_CN.md@@ -50,7 +50,7 @@ Agent 会自动完成安装 → 配置 → 重启 → 验证。详见 [INSTALL-A- **发送内容**:每轮 user/assistant 消息文本(已剥离注入的记忆块和元数据噪音)。- **发送去向**:仅发往你配置的 OpenViking 服务(`baseUrl`)。插件本身只与该服务通信;服务端对 embedding、VLM 等模型的调用取决于服务端配置。-- **存储位置**:所有数据存储在你的 OpenViking 服务上,路径为 `viking://user/*`、`viking://resources/*`、`viking://session/*`。+- **存储位置**:所有数据存储在你的 OpenViking 服务上,路径为 `viking://user/*`(包含 `viking://user/sessions/*`)和 `viking://resources/*`。- **API Key**:通过 `X-OpenViking-Key` header 发送,不会被日志记录或转发。- **多租户隔离**:支持 `accountId`、`userId`。可选的 `peer_role` / `peer_prefix` 控制是否把 OpenClaw 说话人写入 OpenViking `peer_id`。@@ -100,7 +100,7 @@ openclaw config get plugins.slots.contextEngine # 应输出:openviking- OpenClaw 在左侧,仍然是主运行时;插件并不接管 agent 执行本身。- 插件中间层把 Hook、Context Engine、Tools、Runtime Manager 四部分合并在一个注册单元里。- 所有 HTTP 调用最终都走 `OpenVikingClient`,由 client 层统一补租户 header 和路由日志。-- OpenViking 服务端承接 session、memory、archive 和 Phase 2 抽取,底层存储落在 `viking://user/*`、`viking://resources/*`、`viking://session/*`。+- OpenViking 服务端承接 session、memory、archive 和 Phase 2 抽取,底层存储落在 `viking://user/*`(包含 `viking://user/sessions/*`)和 `viking://resources/*`。这套拆分的意义,是让 OpenClaw 继续专注推理与编排,让 OpenViking 成为长期上下文的事实源。diff --git a/examples/openclaw-plugin/client.ts b/examples/openclaw-plugin/client.tsindex af5364c7b..cc7c7237e 100644--- a/examples/openclaw-plugin/client.ts+++ b/examples/openclaw-plugin/client.ts@@ -29,6 +29,11 @@ export type RuntimeIdentity = {userId: string;agentId: string;};++function userSessionUri(sessionId: string): string {+ return `viking://user/sessions/${encodeURIComponent(sessionId)}`;+}+export type CommitSessionResult = {session_id: string;/** "accepted" (async), "completed", "failed", or "timeout" (wait mode). */@@ -301,7 +306,7 @@ export class OpenVikingClient {X_OpenViking_User: tenantHeaders.userId ?? null,resolved_user_id: identity.userId,session_vfs_hint: detail.sessionId- ? `viking://session/${String(detail.sessionId)}`+ ? userSessionUri(String(detail.sessionId)): undefined,}),);@@ -938,7 +943,7 @@ export class OpenVikingClient {match_count?: number;files_scanned?: number;}> {- const baseUri = `viking://session/${sessionId}/history`;+ const baseUri = `${userSessionUri(sessionId)}/history`;const uri = options.archiveId ? `${baseUri}/${options.archiveId}` : baseUri;return this.request("/api/v1/search/grep",diff --git a/examples/openclaw-plugin/docs/workmemory-v2-design.md b/examples/openclaw-plugin/docs/workmemory-v2-design.mdindex bb3d80a71..e6746b020 100644--- a/examples/openclaw-plugin/docs/workmemory-v2-design.md+++ b/examples/openclaw-plugin/docs/workmemory-v2-design.md@@ -307,7 +307,7 @@ OpenViking 在插件侧暴露两个独立的 archive 回查工具。- **插件工具**:`ov_archive_search`,参数 `query: string` + 可选 `archiveId: string`- **客户端封装**:`client.grepSessionArchives(sessionId, pattern, options)`-- **服务端 API**:`POST /api/v1/search/grep`,body `{uri, pattern, case_insensitive}`。`uri` 默认 `viking://session/{sessionId}/history`(覆盖所有 archive);指定 `archiveId` 时收窄为 `viking://session/{sessionId}/history/{archiveId}`+- **服务端 API**:`POST /api/v1/search/grep`,body `{uri, pattern, case_insensitive}`。`uri` 默认 `viking://user/sessions/{sessionId}/history`(覆盖所有 archive);指定 `archiveId` 时收窄为 `viking://user/sessions/{sessionId}/history/{archiveId}`- **工具输出给 LLM**:最多 12 条命中消息,每条最多 1500 字符,附 archive 标签(如 `archive_005`)和行号- **行为约束**:- 默认遍历所有 archive(新到旧)diff --git a/examples/openclaw-plugin/index.ts b/examples/openclaw-plugin/index.tsindex 5ef1c723e..c65799eeb 100644--- a/examples/openclaw-plugin/index.ts+++ b/examples/openclaw-plugin/index.ts@@ -168,12 +168,22 @@ type ToolResultRef = {ref: string;};+function userSessionUri(sessionId: string): string {+ return `viking://user/sessions/${encodeURIComponent(sessionId)}`;+}++function toolResultRef(sessionId: string, toolResultId: string): string {+ return `${userSessionUri(sessionId)}/tool-results/${encodeURIComponent(toolResultId)}`;+}+function parseToolResultRef(value: unknown): ToolResultRef | null {const raw = typeof value === "string" ? value.trim() : "";if (!raw) {return null;}- const match = raw.match(/^viking:\/\/session\/([^/]+)\/tool-results\/([^/?#]+)(?:[?#].*)?$/);+ const match =+ raw.match(/^viking:\/\/user\/(?:(?:[^/]+)\/)?sessions\/([^/]+)\/tool-results\/([^/?#]+)(?:[?#].*)?$/) ??+ raw.match(/^viking:\/\/session\/([^/]+)\/tool-results\/([^/?#]+)(?:[?#].*)?$/);if (!match) {return null;}@@ -185,7 +195,7 @@ function parseToolResultRef(value: unknown): ToolResultRef | null {return {sessionId,toolResultId,- ref: `viking://session/${encodeURIComponent(sessionId)}/tool-results/${encodeURIComponent(toolResultId)}`,+ ref: toolResultRef(sessionId, toolResultId),};}@@ -1663,14 +1673,14 @@ const contextEnginePlugin = {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/<session_id>/tool-results/<tool_result_id>",+ "Exact OV URI from the preview, e.g. viking://user/sessions/<session_id>/tool-results/<tool_result_id>",}),offset: Type.Optional(Type.Number({ description: "Unicode character offset. Default: 0" })),limit: Type.Optional(Type.Number({ description: "Maximum Unicode characters to read. Default: 20000" })),@@ -1690,7 +1700,7 @@ const contextEnginePlugin = {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" },};}@@ -1765,7 +1775,7 @@ const contextEnginePlugin = {parameters: Type.Object({tool_output_ref: Type.String({description:- "Exact OV URI from the preview, e.g. viking://session/<session_id>/tool-results/<tool_result_id>",+ "Exact OV URI from the preview, e.g. viking://user/sessions/<session_id>/tool-results/<tool_result_id>",}),query: Type.String({ description: "Keyword or exact text to search for" }),limit: Type.Optional(Type.Number({ description: "Maximum matches. Default: 20" })),@@ -1786,7 +1796,7 @@ const contextEnginePlugin = {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/tests/ut/client.test.ts b/examples/openclaw-plugin/tests/ut/client.test.tsindex 43f54e68f..5445a114e 100644--- a/examples/openclaw-plugin/tests/ut/client.test.ts+++ b/examples/openclaw-plugin/tests/ut/client.test.ts@@ -603,4 +603,22 @@ describe("OpenVikingClient canonical user namespace", () => {const body = JSON.parse(String(init.body));expect(body.peer_id).toBe("telegram_12345");});++ it("greps session archives through the user session alias", async () => {+ const fetchMock = vi.fn().mockResolvedValue(okResponse({ matches: [], count: 0 }));+ vi.stubGlobal("fetch", fetchMock);++ const client = new OpenVikingClient("http://127.0.0.1:1933", "", "agent", 5000);+ await client.grepSessionArchives("s1", "needle", {+ archiveId: "archive_001",+ caseInsensitive: true,+ agentId: "agent",+ });++ const [, init] = fetchMock.mock.calls[0] as [string, RequestInit];+ const body = JSON.parse(String(init.body));+ expect(body.uri).toBe("viking://user/sessions/s1/history/archive_001");+ expect(body.pattern).toBe("needle");+ expect(body.case_insensitive).toBe(true);+ });});diff --git a/examples/openclaw-plugin/tests/ut/tool-round-trip.test.ts b/examples/openclaw-plugin/tests/ut/tool-round-trip.test.tsindex e65b61fd9..918aacdbc 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/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<string, unknown>;const content = toolResult.content as Array<Record<string, string>>;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/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.tsindex 49517b197..e1d9702e5 100644--- a/examples/openclaw-plugin/tests/ut/tools.test.ts+++ b/examples/openclaw-plugin/tests/ut/tools.test.ts@@ -732,7 +732,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/sessions/test-session/tool-results/tr_call_abc",tool_name: "read_file",},});@@ -744,7 +744,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/sessions/test-session/tool-results/tr_call_abc",offset: 5,limit: 10,}) as ToolResult;@@ -752,7 +752,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/sessions/test-session/tool-results/tr_call_abc",tool_result_id: "tr_call_abc",offset: 5,limit: 10,@@ -787,7 +787,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,@@ -798,7 +798,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/sessions/test-session/tool-results/tr_call_abc",tool_result_id: "tr_call_abc",query: "needle",match_count: 1,@@ -814,7 +814,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/sessions/test-session/tool-results/tr_call_abc",tool_name: "read_file",original_chars: 42000,created_at: "2026-05-15T00:00:00Z",@@ -835,7 +835,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/sessions/test-session/tool-results/tr_call_abc");expect(result.details).toMatchObject({action: "listed",session_id: "test-session",@@ -856,6 +856,34 @@ describe("Tool: OpenViking tool result access", () => {expect(result.content[0]!.text).toContain("another session");expect(result.details.error).toBe("session_mismatch");});++ it("accepts legacy tool result refs as input", async () => {+ const fetchMock = vi.fn(async () =>+ okResponse({+ tool_result_id: "tr_call_abc",+ content: "raw",+ offset: 0,+ limit: 20000,+ offset_unit: "unicode_code_point",+ total_chars: 3,+ has_more: false,+ }),+ );+ vi.stubGlobal("fetch", fetchMock);++ const { tools, api } = setupPlugin();+ contextEnginePlugin.register(api as any);+ 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",+ }) as ToolResult;++ expect(result.content[0]!.text).toBe("raw");+ expect(result.details.tool_output_ref).toBe(+ "viking://user/sessions/test-session/tool-results/tr_call_abc",+ );+ });});describe("Tool: add_resource, add_skill, and ov_search (registration)", () => {diff --git a/openviking/client/local.py b/openviking/client/local.pyindex ca56a7516..87c09901e 100644--- a/openviking/client/local.py+++ b/openviking/client/local.py@@ -17,6 +17,7 @@ from openviking.telemetry.execution import ()from openviking.utils.search_filters import merge_time_filterfrom openviking_cli.client.base import BaseClient+from openviking_cli.exceptions import NotFoundErrorfrom openviking_cli.session.user_id import UserIdentifierfrom openviking_cli.utils import run_async@@ -443,6 +444,7 @@ class LocalClient(BaseClient):)return {"session_id": session.session_id,+ "uri": session.uri,"user": session.user.to_dict(),}@@ -454,6 +456,7 @@ class LocalClient(BaseClient):"""Get session details."""session = await self._service.sessions.get(session_id, self._ctx, auto_create=auto_create)result = session.meta.to_dict()+ result["uri"] = session.uriresult["user"] = session.user.to_dict()return result@@ -461,15 +464,13 @@ class LocalClient(BaseClient):self, session_id: str, token_budget: int = 128_000) -> Dict[str, Any]:"""Get assembled session context."""- session = self._service.sessions.session(self._ctx, session_id)- await session.load()+ session = await self._service.sessions.get(session_id, self._ctx, auto_create=False)result = await session.get_session_context(token_budget=token_budget)return _to_jsonable(result)async def get_session_archive(self, session_id: str, archive_id: str) -> Dict[str, Any]:"""Get one completed archive for a session."""- session = self._service.sessions.session(self._ctx, session_id)- await session.load()+ session = await self._service.sessions.get(session_id, self._ctx, auto_create=False)result = await session.get_session_archive(archive_id)return _to_jsonable(result)@@ -709,14 +710,17 @@ class LocalClient(BaseClient):Session object if exists, None otherwise."""- session = self._service.sessions.session(self._ctx, session_id)- if not run_async(session.exists()):- if must_exist and session_id:- from openviking_cli.exceptions import NotFoundError+ if session_id:+ try:+ return run_async(+ self._service.sessions.get(session_id, self._ctx, auto_create=False)+ )+ except NotFoundError:+ if must_exist:+ raise NotFoundError(session_id, "session")- raise NotFoundError(session_id, "session")- else:- run_async(session.ensure_exists())+ session = self._service.sessions.session(self._ctx, session_id)+ run_async(session.ensure_exists())return sessionasync def session_exists(self, session_id: str) -> bool:@@ -728,8 +732,11 @@ class LocalClient(BaseClient):Returns:True if the session exists, False otherwise"""- session = self._service.sessions.session(self._ctx, session_id)- return await session.exists()+ try:+ await self._service.sessions.get(session_id, self._ctx, auto_create=False)+ return True+ except NotFoundError:+ return Falsedef get_status(self) -> Any:"""Get system status.diff --git a/openviking/core/directories.py b/openviking/core/directories.pyindex 9a95ee075..54d38a259 100644--- a/openviking/core/directories.py+++ b/openviking/core/directories.py@@ -36,11 +36,6 @@ class DirectoryDefinition:# Preset directory tree - each scope has a root DirectoryDefinitionPRESET_DIRECTORIES: Dict[str, DirectoryDefinition] = {- "session": DirectoryDefinition(- path="",- abstract="Session scope. Stores complete context for a single conversation, including original messages and compressed summaries.",- overview="Session-level temporary data storage, can be archived or cleaned after session ends.",- ),"user": DirectoryDefinition(path="",abstract="User scope. Stores user's long-term memory, persisted across sessions.",@@ -159,7 +154,6 @@ class DirectoryInitializer:scope_roots = {"user": PRESET_DIRECTORIES["user"],"resources": PRESET_DIRECTORIES["resources"],- "session": PRESET_DIRECTORIES["session"],}for scope, defn in scope_roots.items():root_uri = f"viking://{scope}"diff --git a/openviking/core/namespace.py b/openviking/core/namespace.pyindex ac651a6ba..d70e22ccd 100644--- a/openviking/core/namespace.py+++ b/openviking/core/namespace.py@@ -12,6 +12,7 @@ _USER_SHORTHAND_SEGMENTS = {"memories","peers","privacy",+ "sessions",".abstract.md",".overview.md","profile.md",@@ -164,16 +165,35 @@ def user_space_fragment(ctx: RequestContext) -> str:return ctx.user.user_id-def canonical_session_uri(session_id: Optional[str] = None) -> str:+def canonical_session_root(ctx: RequestContext) -> str:+ return f"{canonical_user_root(ctx)}/sessions"+++def canonical_session_uri(ctx: RequestContext, session_id: Optional[str] = None) -> str:+ root = canonical_session_root(ctx)+ if not session_id:+ return root+ return f"{root}/{session_id}"+++def legacy_session_uri(session_id: Optional[str] = None) -> str:if not session_id:return "viking://session"return f"viking://session/{session_id}"+def is_session_uri(uri: str) -> bool:+ parts = uri_parts(uri)+ if parts[:1] == ["session"]:+ return True+ if parts[:2] == ["user", "sessions"]:+ return True+ return len(parts) >= 3 and parts[0] == "user" and parts[2] == "sessions"++def visible_roots(ctx: RequestContext) -> list[str]:return ["viking://resources",- "viking://session",canonical_user_root(ctx),]@@ -196,7 +216,7 @@ def resolve_uri(if scope == "agent":raise NamespaceShapeError("viking://agent is deprecated; use viking://user instead")if scope == "session":- return _resolve_session_uri(parts)+ return _resolve_session_uri(parts, ctx=ctx, require_canonical=require_canonical)if scope in {"resources", "temp", "queue", "upload"}:return ResolvedNamespace(uri=VikingURI.normalize(uri).rstrip("/"), scope=scope)return ResolvedNamespace(uri=VikingURI.normalize(uri).rstrip("/"), scope=scope)@@ -215,7 +235,7 @@ def is_accessible(uri: str, ctx: RequestContext) -> bool:except NamespaceShapeError:return False- if target.scope in {"", "resources", "temp", "queue", "session"}:+ if target.scope in {"", "resources", "temp", "queue"}:return Trueif target.scope == "upload":return False@@ -317,7 +337,34 @@ def _resolve_user_uri()-def _resolve_session_uri(parts: list[str]) -> ResolvedNamespace:+def _resolve_session_uri(+ parts: list[str],+ ctx: Optional[RequestContext],+ *,+ require_canonical: bool,+) -> ResolvedNamespace:+ normalized = "viking://" + "/".join(parts)+ if require_canonical:+ raise NamespaceShapeError(f"Legacy session URI is not allowed here: {normalized}")+ if ctx is not None:+ if len(parts) == 1:+ return ResolvedNamespace(+ uri=canonical_session_uri(ctx),+ scope="user",+ owner_user_id=ctx.user.user_id,+ is_container=True,+ )+ session_id = parts[1]+ suffix = parts[2:]+ canonical = canonical_session_uri(ctx, session_id)+ if suffix:+ canonical = f"{canonical}/{'/'.join(suffix)}"+ return ResolvedNamespace(+ uri=canonical,+ scope="user",+ owner_user_id=ctx.user.user_id,+ )+if len(parts) == 1:return ResolvedNamespace(uri="viking://session", scope="session", is_container=True)session_id = parts[1]diff --git a/openviking/core/uri_validation.py b/openviking/core/uri_validation.pyindex 24cf6655a..07497daa3 100644--- a/openviking/core/uri_validation.py+++ b/openviking/core/uri_validation.py@@ -9,7 +9,7 @@ from openviking_cli.exceptions import InvalidURIErrorfrom openviking_cli.utils.uri import VikingURI_URI_SCHEME_RE = re.compile(r"^[A-Za-z][A-Za-z0-9+.-]*:")-_PUBLIC_API_SCOPES = frozenset({"", *VikingURI.PUBLIC_SCOPES})+_PUBLIC_API_SCOPES = frozenset({"", *VikingURI.PUBLIC_SCOPES, *VikingURI.LEGACY_SCOPES})_ALL_API_SCOPES = frozenset({"", *VikingURI.VISITABLE_SCOPES})diff --git a/openviking/integrations/langchain/testing.py b/openviking/integrations/langchain/testing.pyindex 6448b287b..10ef9a4e2 100644--- a/openviking/integrations/langchain/testing.py+++ b/openviking/integrations/langchain/testing.py@@ -229,7 +229,11 @@ class InMemoryOpenVikingClient:def create_session(self, session_id: str | None = None) -> dict[str, Any]:session_id = session_id or f"session-{uuid.uuid4().hex[:12]}"self.sessions.setdefault(session_id, [])- return {"session_id": session_id}+ return {"session_id": session_id, "uri": self._session_uri(session_id)}++ @staticmethod+ def _session_uri(session_id: str) -> str:+ return f"viking://user/default/sessions/{session_id}"def add_message(self,@@ -287,6 +291,7 @@ class InMemoryOpenVikingClient:self.create_session(session_id=session_id)return {"session_id": session_id,+ "uri": self._session_uri(session_id),"message_count": len(self.sessions.get(session_id, [])),"pending_tokens": self.pending_tokens.get(session_id, 0),}@@ -338,7 +343,7 @@ class InMemoryOpenVikingClient:archive_id = f"archive_{len(self.archives[session_id]) + 1:03d}"overview = "\n".join(_message_text(message) for message in messages)if messages:- archive_uri = f"viking://session/{session_id}/history/{archive_id}"+ archive_uri = f"{self._session_uri(session_id)}/history/{archive_id}"self.archives[session_id].append({"archive_id": archive_id,@@ -366,7 +371,7 @@ class InMemoryOpenVikingClient:self.sessions.pop(session_id, None)self.archives.pop(session_id, None)self.pending_tokens.pop(session_id, None)- session_uri = f"viking://session/{session_id}"+ session_uri = self._session_uri(session_id)for uri in list(self.records):if uri == session_uri or uri.startswith(f"{session_uri}/"):del self.records[uri]diff --git a/openviking/integrations/langchain/tools.py b/openviking/integrations/langchain/tools.pyindex 9e858f0fc..97af2b40e 100644--- a/openviking/integrations/langchain/tools.py+++ b/openviking/integrations/langchain/tools.py@@ -755,7 +755,9 @@ def _grep_session_history(query: str,max_matches: int,) -> dict[str, Any]:- history_uri = f"viking://session/{session_id}/history"+ session = call_openviking(client, "get_session", session_id=session_id, auto_create=False)+ session_uri = item_value(session, "uri", f"viking://user/sessions/{session_id}")+ history_uri = f"{str(session_uri).rstrip('/')}/history"tokens = _archive_query_tokens(query)try:result = call_openviking(diff --git a/openviking/message/part.py b/openviking/message/part.pyindex 603171587..36d849368 100644--- a/openviking/message/part.py+++ b/openviking/message/part.py@@ -40,7 +40,7 @@ class ToolPart:type: Literal["tool"] = "tool"tool_id: str = ""tool_name: str = ""- tool_uri: str = "" # viking://session/{user_space_name}/{session_id}/tools/{tool_id}+ tool_uri: str = "" # viking://user/{user_id}/sessions/{session_id}/tools/{tool_id}skill_uri: str = "" # viking://user/{user_id}/skills/{skill_name}tool_input: Optional[dict] = Nonetool_output: str = ""diff --git a/openviking/server/routers/admin.py b/openviking/server/routers/admin.pyindex 1d97d521c..a703a9d7a 100644--- a/openviking/server/routers/admin.py+++ b/openviking/server/routers/admin.py@@ -141,7 +141,6 @@ async def delete_account(viking_fs = get_viking_fs()account_prefixes = ["viking://user/",- "viking://session/","viking://resources/",]for prefix in account_prefixes:diff --git a/openviking/server/routers/sessions.py b/openviking/server/routers/sessions.pyindex 461663b0a..1a06c563e 100644--- a/openviking/server/routers/sessions.py+++ b/openviking/server/routers/sessions.py@@ -5,7 +5,7 @@from typing import Any, Dict, List, Literal, Optionalfrom fastapi import APIRouter, Body, Depends, Path, Query, Request-from pydantic import BaseModel, ConfigDict, Field, model_validator+from pydantic import BaseModel, Field, model_validatorfrom openviking.core.path_variables import resolve_path_variablesfrom openviking.core.peer_id import normalize_peer_id@@ -178,6 +178,7 @@ async def create_session()return {"session_id": session.session_id,+ "uri": session.uri,"user": session.user.to_dict(),}@@ -214,6 +215,7 @@ async def get_session(except NotFoundError:return error_response("NOT_FOUND", f"Session {session_id} not found")result = session.meta.to_dict()+ result["uri"] = session.uriresult["user"] = session.user.to_dict()result["pending_tokens"] = int(session.meta.pending_tokens or 0)return Response(status="ok", result=result)@@ -342,8 +344,6 @@ class CommitRequest(BaseModel):behavior."""- model_config = ConfigDict(extra="forbid")-keep_recent_count: int = Field(default=0,ge=0,diff --git a/openviking/service/reindex_executor.py b/openviking/service/reindex_executor.pyindex 43e8ee231..611ca699a 100644--- a/openviking/service/reindex_executor.py+++ b/openviking/service/reindex_executor.py@@ -19,6 +19,7 @@ from openviking.core.context import (from openviking.core.namespace import (classify_uri,context_type_for_uri,+ is_session_uri,owner_space_for_uri,)from openviking.server.dependencies import get_service@@ -72,6 +73,7 @@ def _is_not_ready_sentinel(text: str, suffix: str) -> bool:head = head[: -len(suffix)].strip()return head.startswith("#") and "\n" not in head+_reindex_executor: "ReindexExecutor | None" = None@@ -182,6 +184,12 @@ class ReindexExecutor:parts = classification.partsif not parts:return "global_namespace"+ if is_session_uri(uri):+ raise OpenVikingError(+ f"Unsupported reindex URI: {uri}",+ code="UNSUPPORTED_URI",+ details={"uri": uri},+ )if parts == ("user",):return "user_namespace"if classification.is_user_namespace_root:@@ -740,6 +748,8 @@ class ReindexExecutor:entry_uri = entry.get("uri")if not entry_uri:continue+ if is_session_uri(entry_uri):+ continueclassification = classify_uri(entry_uri)if classification.is_memory:if entry.get("isDir") and classification.is_memory_root:@@ -826,7 +836,7 @@ class ReindexExecutor:if entry.get("isDir") and remainder and "/" not in remainder:user_roots.append(entry_uri)continue- if entry_uri == "viking://session" or entry_uri.startswith("viking://session/"):+ if is_session_uri(entry_uri):continueif not self._is_global_resource_entry(entry_uri):continuediff --git a/openviking/service/session_service.py b/openviking/service/session_service.pyindex d822dd01c..07a663263 100644--- a/openviking/service/session_service.py+++ b/openviking/service/session_service.py@@ -6,14 +6,13 @@ Session Service for OpenViking.Provides session management operations: session, sessions, add_message, commit, delete."""-import jsonfrom typing import TYPE_CHECKING, Any, Dict, List, Optionalfrom openviking.core.namespace import canonical_session_urifrom openviking.server.config import ToolOutputExternalizationConfig-from openviking.server.identity import RequestContext, Role+from openviking.server.identity import RequestContextfrom openviking.service.task_tracker import get_task_tracker-from openviking.session import Session, SessionMeta+from openviking.session import Sessionfrom openviking.session.memory.memory_type_registry import MemoryTypeRegistryfrom openviking.session.memory_policy import MemoryPolicyfrom openviking.storage import VikingDBManager@@ -92,7 +91,13 @@ class SessionService:exc_info=True,)- def session(self, ctx: RequestContext, session_id: Optional[str] = None) -> Session:+ def session(+ self,+ ctx: RequestContext,+ session_id: Optional[str] = None,+ *,+ session_uri: Optional[str] = None,+ ) -> Session:"""Create a new session or load an existing one.Args:@@ -109,61 +114,10 @@ class SessionService:user=ctx.user,ctx=ctx,session_id=session_id,+ session_uri=session_uri,tool_output_externalization_config=self._tool_output_externalization_config,)- @staticmethod- def _session_account_id(meta: SessionMeta) -> str:- return getattr(meta, "created_by_account_id", "") or getattr(meta, "account_id", "")-- def _session_is_visible_in_account(self, ctx: RequestContext, meta: SessionMeta) -> bool:- if ctx.role == Role.ROOT:- return True-- account_id = self._session_account_id(meta)- return bool(account_id and account_id == ctx.account_id)-- async def _read_session_meta(self, session_id: str, ctx: RequestContext) -> SessionMeta:- self._ensure_initialized()- raw = await self._viking_fs.read_file(- f"{canonical_session_uri(session_id)}/.meta.json",- ctx=ctx,- )- data = json.loads(raw)- if not data.get("created_by_account_id") and data.get("account_id"):- data["created_by_account_id"] = data["account_id"]- return SessionMeta.from_dict(data)-- async def _load_session_meta_for_visibility(- self, session_id: str, ctx: RequestContext- ) -> SessionMeta:- """Read persisted metadata, deriving legacy fields without writing side effects."""- try:- meta = await self._read_session_meta(session_id, ctx)- except Exception:- session = self.session(ctx, session_id)- await session.load()- meta = session.meta- if not meta.session_id:- meta.session_id = session_id- if not meta.created_by_account_id:- session = self.session(ctx, session_id)- await session.load()- meta = session.meta- if not meta.session_id:- meta.session_id = session_id- return meta-- async def _assert_session_visible(self, session_id: str, ctx: RequestContext) -> None:- if ctx.role == Role.ROOT:- return- try:- meta = await self._load_session_meta_for_visibility(session_id, ctx)- except Exception as exc:- raise NotFoundError(session_id, "session") from exc- if not self._session_is_visible_in_account(ctx, meta):- raise NotFoundError(session_id, "session")-async def create(self,ctx: RequestContext,@@ -218,8 +172,6 @@ class SessionService:if not auto_create:raise NotFoundError(session_id, "session")await session.ensure_exists()- else:- await self._assert_session_visible(session_id, ctx)await session.load()self._record_lifecycle_metric("get", "ok")return session@@ -234,22 +186,15 @@ class SessionService:List of session info dicts"""self._ensure_initialized()- session_base_uri = canonical_session_uri()+ session_base_uri = canonical_session_uri(ctx)+ sessions = []try:entries = await self._viking_fs.ls(session_base_uri, ctx=ctx)- sessions = []for entry in entries:name = entry.get("name", "")if name in [".", ".."]:continue- if ctx.role != Role.ROOT:- try:- meta = await self._load_session_meta_for_visibility(name, ctx)- except Exception:- continue- if not self._session_is_visible_in_account(ctx, meta):- continuesessions.append({"session_id": name,@@ -257,10 +202,9 @@ class SessionService:"is_dir": entry.get("isDir", False),})- return sessionsexcept Exception:logger.debug("Failed to list sessions", exc_info=True)- return []+ return sessionsasync def delete(self, session_id: str, ctx: RequestContext) -> bool:"""Delete a session.@@ -272,23 +216,19 @@ class SessionService:True if deleted successfully"""self._ensure_initialized()- if ctx.role not in {Role.ADMIN, Role.ROOT}:- from openviking_cli.exceptions import PermissionDeniedError-- raise PermissionDeniedError("Deleting shared sessions requires ADMIN or ROOT role")- session_uri = canonical_session_uri(session_id)-- try:- await self._viking_fs.rm(session_uri, recursive=True, ctx=ctx)- logger.info(f"Deleted session: {session_id}")- self._record_lifecycle_metric("delete", "ok")- return True- except Exception as e:- logger.error(f"Failed to delete session {session_id}: {e}")+ session_uri = canonical_session_uri(ctx, session_id)+ if await self.session(ctx, session_id).exists():+ storage_ctx = ctx+ else:self._record_lifecycle_metric("delete", "error")raise NotFoundError(session_id, "session")+ await self._viking_fs.rm(session_uri, recursive=True, ctx=storage_ctx)+ logger.info(f"Deleted session: {session_id}")+ self._record_lifecycle_metric("delete", "ok")+ return True+async def commit(self,session_id: str,@@ -362,8 +302,7 @@ class SessionService:raise NotInitializedError("SessionCompressorV2")session = await self.get(session_id, ctx)- session_uri = canonical_session_uri(session_id)- archive_uri = f"{session_uri}/manual_extract"+ archive_uri = f"{session.uri}/manual_extract"memories = await self._session_compressor.extract_long_term_memories(messages=session.messages,diff --git a/openviking/session/session.py b/openviking/session/session.pyindex 765bc82d9..4b08dc675 100644--- a/openviking/session/session.py+++ b/openviking/session/session.py@@ -211,7 +211,6 @@ class SessionMeta:updated_at: str = ""created_by_account_id: str = ""created_by_user_id: str = ""- participant_user_ids: List[str] = field(default_factory=list)message_count: int = 0total_message_count: Optional[int] = 0commit_count: int = 0@@ -250,7 +249,6 @@ class SessionMeta:"updated_at": self.updated_at,"created_by_account_id": self.created_by_account_id,"created_by_user_id": self.created_by_user_id,- "participant_user_ids": list(self.participant_user_ids),"message_count": self.message_count,"commit_count": self.commit_count,"memories_extracted": dict(self.memories_extracted),@@ -285,7 +283,6 @@ class SessionMeta:created_by_account_id=data.get("created_by_account_id", "")or data.get("account_id", ""),created_by_user_id=data.get("created_by_user_id", ""),- participant_user_ids=list(data.get("participant_user_ids", [])),message_count=data.get("message_count", 0),total_message_count=data.get("total_message_count"),commit_count=data.get("commit_count", 0),@@ -331,6 +328,7 @@ class Session:user: Optional["UserIdentifier"] = None,ctx: Optional[RequestContext] = None,session_id: Optional[str] = None,+ session_uri: Optional[str] = None,auto_commit_threshold: int = 8000,tool_output_externalization_config: Optional[ToolOutputExternalizationConfig] = None,):@@ -342,7 +340,7 @@ class Session:self.session_id = session_id or str(uuid4())self.created_at = int(datetime.now(timezone.utc).timestamp() * 1000)self._auto_commit_threshold = auto_commit_threshold- self._session_uri = canonical_session_uri(self.session_id)+ self._session_uri = session_uri or canonical_session_uri(self.ctx, self.session_id)self._messages: List[Message] = []self._usage_records: List[Usage] = []@@ -353,7 +351,6 @@ class Session:created_at=get_current_timestamp(),created_by_account_id=self.ctx.account_id,created_by_user_id=self.ctx.user.user_id,- participant_user_ids=[self.ctx.user.user_id],)self._loaded = Falseself._tool_output_externalization_config = (@@ -412,8 +409,6 @@ class Session:self._meta.created_by_account_id = self.ctx.account_idif not self._meta.created_by_user_id:self._meta.created_by_user_id = self.ctx.user.user_id- if not self._meta.participant_user_ids:- self._meta.participant_user_ids = [self._meta.created_by_user_id]# WM v2: always rebuild pending_tokens from current messages so the# counter stays consistent across restarts and is also backfilled for# legacy sessions whose .meta.json predates these fields. O(n) once,diff --git a/openviking/storage/index_consistency.py b/openviking/storage/index_consistency.pyindex 67faadbb0..f056e585a 100644--- a/openviking/storage/index_consistency.py+++ b/openviking/storage/index_consistency.py@@ -8,6 +8,7 @@ from dataclasses import dataclassfrom typing import Anyfrom openviking.core.context import ResourceContentType+from openviking.core.namespace import is_session_urifrom openviking.server.identity import RequestContextfrom openviking.storage.expr import Eqfrom openviking.utils.embedding_utils import get_resource_content_type@@ -88,7 +89,7 @@ def _entry_uri(root_uri: str, entry: dict[str, Any]) -> str:def _is_index_scope(uri: str) -> bool:try:- return VikingURI(uri).scope not in NON_INDEX_SCOPES+ return VikingURI(uri).scope not in NON_INDEX_SCOPES and not is_session_uri(uri)except Exception:return Falsediff --git a/openviking/storage/ovpack/format.py b/openviking/storage/ovpack/format.pyindex b0666cb1c..3ef3ddafc 100644--- a/openviking/storage/ovpack/format.py+++ b/openviking/storage/ovpack/format.py@@ -19,7 +19,7 @@ from typing import Any, Optionalfrom openviking_cli.exceptions import InvalidArgumentErrorfrom openviking_cli.utils.uri import VikingURI-OVPACK_FORMAT_VERSION = 2+OVPACK_FORMAT_VERSION = 3OVPACK_KIND = "openviking.ovpack"OVPACK_INTERNAL_DIR = "_ovpack"OVPACK_FILES_DIR = "files"diff --git a/openviking/storage/ovpack/index.py b/openviking/storage/ovpack/index.pyindex 40c213f4c..df95627fe 100644--- a/openviking/storage/ovpack/index.py+++ b/openviking/storage/ovpack/index.py@@ -6,7 +6,7 @@ from __future__ import annotationsfrom typing import Any-from openviking.core.namespace import context_type_for_uri+from openviking.core.namespace import context_type_for_uri, is_session_urifrom openviking.server.identity import RequestContextfrom openviking.storage.expr import Eqfrom openviking.storage.ovpack.format import (@@ -197,7 +197,7 @@ async def build_manifest(index_records: list[dict[str, Any]] = []dense_values: list[float] = []- if root_uri != "viking://":+ if root_uri != "viking://" and not is_session_uri(root_uri):root_records = await index_records_for_uri(viking_fs,vector_store,@@ -211,6 +211,7 @@ async def build_manifest(for entry in entries:rel_path = entry["rel_path"]is_dir = bool(entry.get("isDir"))+ entry_uri = join_uri(root_uri, rel_path)manifest_entries.append({"path": rel_path,@@ -218,10 +219,12 @@ async def build_manifest("size": entry.get("size", 0) if not is_dir else 0,})+ if is_session_uri(entry_uri):+ continuerecords = await index_records_for_uri(viking_fs,vector_store,- join_uri(root_uri, rel_path),+ entry_uri,is_dir=is_dir,ctx=ctx,include_vectors=include_vectors,diff --git a/openviking/storage/ovpack/manifest.py b/openviking/storage/ovpack/manifest.pyindex 7c70b34c3..a009016fb 100644--- a/openviking/storage/ovpack/manifest.py+++ b/openviking/storage/ovpack/manifest.py@@ -37,7 +37,7 @@ def read_manifest(zf: zipfile.ZipFile, base_name: str) -> dict[str, Any]:raise invalid_manifest("Missing ovpack manifest",manifest_path,- hint="Re-export this package with OVPack v2 checksum support before importing.",+ hint="Re-export this package with the current OVPack format before importing.",)try:diff --git a/openviking/storage/ovpack/operations.py b/openviking/storage/ovpack/operations.pyindex 5e37c6037..5edd2eaa3 100644--- a/openviking/storage/ovpack/operations.py+++ b/openviking/storage/ovpack/operations.py@@ -8,7 +8,7 @@ import osimport zipfilefrom typing import Any, Optional-from openviking.core.namespace import context_type_for_uri, relative_uri_path+from openviking.core.namespace import context_type_for_uri, is_session_uri, relative_uri_pathfrom openviking.server.identity import RequestContextfrom openviking.storage.index_consistency import check_index_consistencyfrom openviking.storage.ovpack.format import (@@ -38,7 +38,6 @@ from openviking.storage.ovpack.manifest import (validate_manifest_root_matches_zip,)from openviking.storage.ovpack.policy import (- NON_VECTOR_SCOPES,PUBLIC_SCOPES,backup_scopes_from_manifest,is_backup_package,@@ -189,6 +188,10 @@ async def _enqueue_direct_vectorization(index_records: Optional[list[dict[str, Any]]] = None,manifest_path_root_uri: Optional[str] = None,) -> None:+ if is_session_uri(uri):+ logger.info(f"[ovpack] Skipped vectorization for session namespace: {uri}")+ return+index_records = index_records or []manifest_path_root_uri = manifest_path_root_uri or urientries = await viking_fs.tree(uri, node_limit=None, level_limit=None, ctx=ctx)@@ -198,6 +201,8 @@ async def _enqueue_direct_vectorization(entry_uri = entry.get("uri")if not entry_uri:continue+ if is_session_uri(entry_uri):+ continuerel_path = entry.get("rel_path") or relative_uri_path(uri, entry_uri)manifest_rel_path = relative_uri_path(manifest_path_root_uri, entry_uri)if entry.get("isDir"):@@ -318,7 +323,7 @@ async def import_ovpack(index_records = validate_manifest_content(zf, manifest, infolist, base_name)dense_vectors = read_dense_vectors(zf, manifest, base_name, index_records)- if VikingURI(root_uri).scope not in NON_VECTOR_SCOPES:+ if not is_session_uri(root_uri):vector_action = choose_vector_restore_action(manifest,index_records,@@ -346,7 +351,7 @@ async def import_ovpack(logger.info(f"[ovpack] Successfully imported {file_path} to {root_uri}")- if VikingURI(root_uri).scope not in NON_VECTOR_SCOPES:+ if not is_session_uri(root_uri):if vector_action == "restore":await restore_vector_snapshot(vector_store, root_uri, index_records, dense_vectors, ctx)logger.info(f"[ovpack] Restored vector snapshot for: {root_uri}")@@ -359,7 +364,7 @@ async def import_ovpack()logger.info(f"[ovpack] Enqueued direct vectorization for: {root_uri}")else:- logger.info(f"[ovpack] Skipped vectorization for non-vector scope: {root_uri}")+ logger.info(f"[ovpack] Skipped vectorization for session namespace: {root_uri}")return root_uri@@ -688,9 +693,6 @@ async def restore_ovpack(return root_urifor scope in backup_scopes:- if scope in NON_VECTOR_SCOPES:- logger.info(f"[ovpack] Skipped vectorization for non-vector scope: {scope}")- continuescope_uri = f"viking://{scope}"await _enqueue_direct_vectorization(viking_fs,diff --git a/openviking/storage/ovpack/policy.py b/openviking/storage/ovpack/policy.pyindex e21a44eaa..20401db53 100644--- a/openviking/storage/ovpack/policy.py+++ b/openviking/storage/ovpack/policy.py@@ -18,11 +18,10 @@ from openviking.storage.ovpack.format import (from openviking_cli.exceptions import InvalidArgumentErrorfrom openviking_cli.utils.uri import VikingURI-PUBLIC_SCOPES = ("resources", "user", "session")+PUBLIC_SCOPES = ("resources", "user")IMPORTABLE_SCOPES = frozenset(PUBLIC_SCOPES)-STRUCTURED_IMPORT_SCOPES = frozenset({"user", "session"})+STRUCTURED_IMPORT_SCOPES = frozenset({"user"})EXCLUDED_FILENAMES = frozenset({".relations.json"})-NON_VECTOR_SCOPES = frozenset({"session"})def is_excluded_rel_path(rel_path: str) -> bool:diff --git a/openviking/storage/ovpack/vectors.py b/openviking/storage/ovpack/vectors.pyindex 220f27b82..5fc6c546d 100644--- a/openviking/storage/ovpack/vectors.py+++ b/openviking/storage/ovpack/vectors.py@@ -9,7 +9,7 @@ import structimport zipfilefrom typing import Any-from openviking.core.namespace import context_type_for_uri, owner_fields_for_uri+from openviking.core.namespace import context_type_for_uri, is_session_uri, owner_fields_for_urifrom openviking.server.identity import RequestContextfrom openviking.storage.ovpack.format import (OVPACK_DENSE_PATH,@@ -19,12 +19,10 @@ from openviking.storage.ovpack.format import (sha256_hex,)from openviking.storage.ovpack.manifest import manifest_dense_info-from openviking.storage.ovpack.policy import NON_VECTOR_SCOPESfrom openviking.storage.ovpack.validation import dense_record_count, record_dense_reffrom openviking.utils.time_utils import get_current_timestampfrom openviking_cli.exceptions import InvalidArgumentErrorfrom openviking_cli.utils.logger import get_logger-from openviking_cli.utils.uri import VikingURIlogger = get_logger(__name__)@@ -315,7 +313,7 @@ async def restore_vector_snapshot(if not isinstance(rel_path, str):continuetarget_uri = join_uri(root_uri, rel_path)- if VikingURI(target_uri).scope in NON_VECTOR_SCOPES:+ if is_session_uri(target_uri):continueawait _upsert_vector_snapshot_record(vector_store,diff --git a/openviking/storage/stats_aggregator.py b/openviking/storage/stats_aggregator.pyindex b4b1469fa..b85eb35f3 100644--- a/openviking/storage/stats_aggregator.py+++ b/openviking/storage/stats_aggregator.py@@ -140,8 +140,7 @@ class StatsAggregator:Returns:Dictionary with session extraction statistics."""- session = service.sessions.session(ctx, session_id)- await session.load()+ session = await service.sessions.get(session_id, ctx, auto_create=False)stats = session.statsreturn {diff --git a/openviking/utils/embedding_utils.py b/openviking/utils/embedding_utils.pyindex e29a42137..681139cfd 100644--- a/openviking/utils/embedding_utils.py+++ b/openviking/utils/embedding_utils.py@@ -12,7 +12,7 @@ from datetime import datetime, timezonefrom typing import Any, Dict, Optionalfrom openviking.core.context import Context, ContextLevel, ResourceContentType, Vectorize-from openviking.core.namespace import context_type_for_uri, owner_space_for_uri+from openviking.core.namespace import context_type_for_uri, is_session_uri, owner_space_for_urifrom openviking.server.identity import RequestContextfrom openviking.storage.queuefs import get_queue_managerfrom openviking.storage.queuefs.embedding_msg_converter import EmbeddingMsgConverter@@ -480,7 +480,7 @@ async def index_resource((``/memories/``) are indexed as ``"memory"`` rather than the default``"resource"``."""- if uri.startswith("viking://session/") or uri == "viking://session":+ if is_session_uri(uri):logger.info("Skipping indexing for session namespace: %s", uri)returndiff --git a/openviking_cli/utils/uri.py b/openviking_cli/utils/uri.pyindex da216e46e..eefdeb6cd 100644--- a/openviking_cli/utils/uri.py+++ b/openviking_cli/utils/uri.py@@ -19,15 +19,16 @@ class VikingURI:Scopes:- resources: Independent resource scope (viking://resources/{project}/...)- - user: User scope (viking://user/...)- - session: Session scope (viking://session/{session_id}/...)+ - user: User scope (viking://user/...), including sessions under+ viking://user/{user_id}/sessions/{session_id}+ - session: Legacy alias for user sessions (viking://session/{session_id}/...)- queue: Queue scope (viking://queue/...)Examples:- viking://resources/my_project/docs/api- viking://user/memories/preferences/code_style- viking://user/skills/pdf- - viking://session/session123/messages+ - viking://user/alice/sessions/session123/messages.jsonl"""SCHEME = "viking"@@ -35,13 +36,13 @@ class VikingURI:LISTABLE_SCOPES = {"resources","user",- "session",}PUBLIC_SCOPES = frozenset(LISTABLE_SCOPES)+ LEGACY_SCOPES = frozenset({"session"})INTERNAL_SCOPES = frozenset({"temp", "queue", "upload"})# All valid scopes that can be addressed by the URI parser/storage internals.# Public API handlers must not use this as their external whitelist.- VISITABLE_SCOPES = PUBLIC_SCOPES | INTERNAL_SCOPES+ VISITABLE_SCOPES = PUBLIC_SCOPES | LEGACY_SCOPES | INTERNAL_SCOPESdef __init__(self, uri: str):"""diff --git a/tests/api_test/sessions/slow/test_multi_session_isolation.py b/tests/api_test/sessions/slow/test_multi_session_isolation.pyindex ede2563a8..01578a339 100644--- a/tests/api_test/sessions/slow/test_multi_session_isolation.py+++ b/tests/api_test/sessions/slow/test_multi_session_isolation.py@@ -193,14 +193,13 @@ class TestMultiSessionIsolation:finally:api_client.delete_session(sid)- def test_participant_ids_is_list(self, api_client):+ def test_participant_ids_are_not_returned(self, api_client):r = api_client.create_session()sid = r.json()["result"]["session_id"]try:get_resp = api_client.get_session(sid)result = get_resp.json().get("result", {})- pids = result.get("participant_ids", None)- if pids is not None:- assert isinstance(pids, list), f"participant_ids should be list, got {type(pids)}"+ assert "participant_ids" not in result+ assert "participant_user_ids" not in resultfinally:api_client.delete_session(sid)diff --git a/tests/api_test/sessions/slow/test_session_detail_fields.py b/tests/api_test/sessions/slow/test_session_detail_fields.pyindex ba894dfd2..e34429746 100644--- a/tests/api_test/sessions/slow/test_session_detail_fields.py+++ b/tests/api_test/sessions/slow/test_session_detail_fields.py@@ -209,7 +209,7 @@ class TestSessionDetailFields:if session_id:api_client.delete_session(session_id)- def test_session_participant_ids_are_lists(self, api_client):+ def test_session_participant_ids_are_not_returned(self, api_client):session_id = Nonetry:create_resp = api_client.create_session()@@ -220,9 +220,7 @@ class TestSessionDetailFields:assert get_resp.status_code == 200result = get_resp.json().get("result", {})- assert isinstance(result.get("participant_user_ids"), (list, type(None))), (- "participant_user_ids should be a list or None"- )+ assert "participant_user_ids" not in resultfinally:if session_id:api_client.delete_session(session_id)@@ -248,9 +246,10 @@ class TestSessionDetailFields:assert target is not None, f"newly created session {session_id} should appear in list"assert "session_id" in target, "session list item should have session_id"assert "uri" in target, "session list item should have uri"- assert target["uri"].startswith("viking://session/"), (- f"session uri should start with viking://session/, got {target['uri']}"+ assert target["uri"].startswith("viking://user/"), (+ f"session uri should start with viking://user/, got {target['uri']}")+ assert f"/sessions/{session_id}" in target["uri"]finally:if session_id:api_client.delete_session(session_id)diff --git a/tests/misc/test_ovpack_import_policy.py b/tests/misc/test_ovpack_import_policy.pyindex affcd4d38..005b245f5 100644--- a/tests/misc/test_ovpack_import_policy.py+++ b/tests/misc/test_ovpack_import_policy.py@@ -169,7 +169,7 @@ class FakeBackupVikingFS:def __init__(self) -> None:self.binary_files = {"viking://resources/README.md": b"hello",- "viking://session/sess_1/.meta.json": b'{"session_id":"sess_1"}',+ "viking://user/alice/sessions/sess_1/.meta.json": b'{"session_id":"sess_1"}',}async def tree(@@ -192,17 +192,29 @@ class FakeBackupVikingFS:"size": 5,}]- if uri == "viking://session":+ if uri == "viking://user":return [{- "rel_path": "sess_1",- "uri": "viking://session/sess_1",+ "rel_path": "alice",+ "uri": "viking://user/alice",+ "isDir": True,+ "size": 0,+ },+ {+ "rel_path": "alice/sessions",+ "uri": "viking://user/alice/sessions","isDir": True,"size": 0,},{- "rel_path": "sess_1/.meta.json",- "uri": "viking://session/sess_1/.meta.json",+ "rel_path": "alice/sessions/sess_1",+ "uri": "viking://user/alice/sessions/sess_1",+ "isDir": True,+ "size": 0,+ },+ {+ "rel_path": "alice/sessions/sess_1/.meta.json",+ "uri": "viking://user/alice/sessions/sess_1/.meta.json","isDir": False,"size": 23,},@@ -418,7 +430,7 @@ def _manifest_for_files(root_name: str, files: dict[str, str]) -> dict[str, objemanifest: dict[str, object] = {"kind": "openviking.ovpack",- "format_version": 2,+ "format_version": 3,"root": {"name": root_name,"uri": f"viking://resources/{root_name}",@@ -513,7 +525,7 @@ def test_index_consistency_report_limits_public_and_error_records():@pytest.mark.asyncio-async def test_export_ovpack_writes_v2_manifest_with_semantic_sidecars(+async def test_export_ovpack_writes_v3_manifest_with_semantic_sidecars(temp_ovpack_path: Path, request_ctx: RequestContext):await export_ovpack(@@ -533,7 +545,7 @@ async def test_export_ovpack_writes_v2_manifest_with_semantic_sidecars(assert "demo/files/notes.txt" in namesassert "demo/files/.overview.md" in names- assert manifest["format_version"] == 2+ assert manifest["format_version"] == 3assert manifest["kind"] == "openviking.ovpack"note_entry = next(entry for entry in manifest["entries"] if entry["path"] == "notes.txt")note_sha256 = hashlib.sha256(b"hello").hexdigest()@@ -588,14 +600,14 @@ async def test_backup_restore_contract(temp_ovpack_path: Path, request_ctx: Requmanifest = json.loads(zf.read("openviking-backup/_ovpack/manifest.json").decode("utf-8"))assert "openviking-backup/files/resources/README.md" in names- assert "openviking-backup/files/session/sess_1/.meta.json" in names+ assert "openviking-backup/files/user/alice/sessions/sess_1/.meta.json" in namesassert manifest["root"] == {"name": "openviking-backup","uri": "viking://","scope": "root","package_type": "backup",}- assert manifest["scopes"] == ["resources", "user", "session"]+ assert manifest["scopes"] == ["resources", "user"]with pytest.raises(InvalidArgumentError, match=r"must be restored"):await import_ovpack(FakeVikingFS(), str(temp_ovpack_path), "viking://", request_ctx)@@ -604,7 +616,7 @@ async def test_backup_restore_contract(temp_ovpack_path: Path, request_ctx: Requassert await restore_ovpack(fake_fs, str(temp_ovpack_path), request_ctx) == "viking://"assert fake_fs.written_files == ["viking://resources/README.md",- "viking://session/sess_1/.meta.json",+ "viking://user/alice/sessions/sess_1/.meta.json",]assert fake_fs.tree_calls == ["viking://resources", "viking://user"]@@ -883,15 +895,15 @@ async def test_import_ovpack_rejects_manifest_file_hash_mismatch(@pytest.mark.asyncio-async def test_import_ovpack_rejects_legacy_manifest_version(+async def test_import_ovpack_rejects_previous_manifest_version(temp_ovpack_path: Path, request_ctx: RequestContext):manifest = _manifest_for_files("demo", {"notes.txt": "hello"})- manifest["format_version"] = 1+ manifest["format_version"] = 2_write_ovpack_with_manifest(temp_ovpack_path, "demo", {"notes.txt": "hello"}, manifest=manifest)fake_fs = FakeVikingFS()- with pytest.raises(InvalidArgumentError, match=r"Unsupported ovpack format_version 1"):+ with pytest.raises(InvalidArgumentError, match=r"Unsupported ovpack format_version 2"):await import_ovpack(fake_fs, str(temp_ovpack_path), "viking://resources", request_ctx)assert fake_fs.written_files == []@@ -924,7 +936,7 @@ async def test_import_ovpack_rejects_manifest_unexpected_directory(@pytest.mark.asyncio-async def test_import_ovpack_restores_session_without_vectorization(+async def test_import_ovpack_restores_user_session_without_vectorization(temp_ovpack_path: Path, request_ctx: RequestContext):files = {@@ -934,8 +946,8 @@ async def test_import_ovpack_restores_session_without_vectorization(manifest = _manifest_for_files("victim", files)manifest["root"] = {"name": "victim",- "uri": "viking://session/victim",- "scope": "session",+ "uri": "viking://user/alice/sessions/victim",+ "scope": "user",}_write_ovpack_with_manifest(temp_ovpack_path,@@ -945,12 +957,17 @@ async def test_import_ovpack_restores_session_without_vectorization()fake_fs = FakeVikingFS()- result = await import_ovpack(fake_fs, str(temp_ovpack_path), "viking://session", request_ctx)+ result = await import_ovpack(+ fake_fs,+ str(temp_ovpack_path),+ "viking://user/alice/sessions",+ request_ctx,+ )- assert result == "viking://session/victim"+ assert result == "viking://user/alice/sessions/victim"assert fake_fs.written_files == [- "viking://session/victim/.meta.json",- "viking://session/victim/messages.jsonl",+ "viking://user/alice/sessions/victim/.meta.json",+ "viking://user/alice/sessions/victim/messages.jsonl",]assert fake_fs.tree_calls == []@@ -961,21 +978,21 @@ async def test_import_ovpack_restores_session_without_vectorization(await import_ovpack(invalid_fs,str(temp_ovpack_path),- "viking://session/victim",+ "viking://user/alice/sessions/victim",request_ctx,)assert invalid_fs.written_files == []@pytest.mark.asyncio-async def test_import_ovpack_rejects_scope_mismatch(+async def test_import_ovpack_rejects_legacy_session_scope(temp_ovpack_path: Path, request_ctx: RequestContext):manifest = _manifest_for_files("demo", {"notes.txt": "hello"})_write_ovpack_with_manifest(temp_ovpack_path, "demo", {"notes.txt": "hello"}, manifest=manifest)fake_fs = FakeVikingFS()- with pytest.raises(InvalidArgumentError, match=r"source scope does not match target scope"):+ with pytest.raises(InvalidArgumentError, match=r"scope: session"):await import_ovpack(fake_fs, str(temp_ovpack_path), "viking://session", request_ctx)assert fake_fs.written_files == []diff --git a/tests/server/test_admin_rebuild_api.py b/tests/server/test_admin_rebuild_api.pyindex 387668261..8745da0de 100644--- a/tests/server/test_admin_rebuild_api.py+++ b/tests/server/test_admin_rebuild_api.py@@ -47,16 +47,22 @@ async def test_reindex_rejects_unsupported_uri(admin_client: httpx.AsyncClient):assert body["error"]["code"] == "UNSUPPORTED_URI"-async def test_reindex_rejects_session_uri(admin_client: httpx.AsyncClient):+ "uri",+ [+ "viking://session/test/demo",+ "viking://user/default/sessions/test/demo",+ ],+)+async def test_reindex_rejects_session_uri(admin_client: httpx.AsyncClient, uri: str):resp = await admin_client.post("/api/v1/content/reindex",- json={"uri": "viking://session/test/demo", "mode": "vectors_only"},+ json={"uri": uri, "mode": "vectors_only"},headers=ROOT_ACCOUNT_HEADERS,)- assert resp.status_code == 400+ assert resp.status_code == 403body = resp.json()assert body["status"] == "error"- assert body["error"]["code"] == "UNSUPPORTED_URI"async def test_reindex_rejects_reason_field(admin_client: httpx.AsyncClient):@@ -1178,8 +1184,11 @@ async def test_reindex_user_namespace_partitions_memory_skill_and_resource(monke{"uri": "viking://user/default/memories/preferences", "isDir": True},{"uri": "viking://user/default/skills", "isDir": True},{"uri": "viking://user/default/skills/my_skill", "isDir": True},+ {"uri": "viking://user/default/sessions", "isDir": True},+ {"uri": "viking://user/default/sessions/s1", "isDir": True},{"uri": "viking://user/default/resources", "isDir": True},{"uri": "viking://user/default/resources/doc.md", "isDir": False},+ {"uri": "viking://user/default/sessions/s1/messages.jsonl", "isDir": False},{"uri": "viking://user/default/profile.md", "isDir": False},{"uri": "viking://user/default/memories/preferences/theme.md", "isDir": False},{"uri": "viking://user/default/skills/my_skill/SKILL.md", "isDir": False},@@ -1232,6 +1241,7 @@ async def test_reindex_user_namespace_partitions_memory_skill_and_resource(monkeassert "viking://user/default/resources" in seen["resource_dirs"]assert "viking://user/default/memories" not in seen["resource_dirs"]assert "viking://user/default/skills" not in seen["resource_dirs"]+ assert "viking://user/default/sessions" not in seen["resource_dirs"]assert seen["resource_files"] == ["viking://user/default/resources/doc.md","viking://user/default/profile.md",diff --git a/tests/server/test_api_sessions.py b/tests/server/test_api_sessions.pyindex 43e445e25..da9291491 100644--- a/tests/server/test_api_sessions.py+++ b/tests/server/test_api_sessions.py@@ -18,7 +18,6 @@ from openviking.server.config import ServerConfig, ToolOutputExternalizationConffrom openviking.server.dependencies import set_servicefrom openviking.server.identity import RequestContext, Rolefrom openviking.server.routers import sessions as sessions_router-from openviking.session import SessionMetafrom openviking_cli.session.user_id import UserIdentifierfrom openviking_cli.utils.config import OPENVIKING_CONFIG_ENVfrom openviking_cli.utils.config.open_viking_config import OpenVikingConfigSingleton@@ -147,48 +146,31 @@ async def test_list_sessions(client: httpx.AsyncClient):async def test_get_session(client: httpx.AsyncClient):create_resp = await client.post("/api/v1/sessions", json={})session_id = create_resp.json()["result"]["session_id"]+ session_uri = create_resp.json()["result"]["uri"]resp = await client.get(f"/api/v1/sessions/{session_id}")assert resp.status_code == 200body = resp.json()assert body["status"] == "ok"assert body["result"]["session_id"] == session_id+ assert body["result"]["uri"] == session_uri-async def test_legacy_session_without_meta_remains_visible_to_owner(service):- session_id = "legacy-no-meta"- owner_ctx = RequestContext(- user=UserIdentifier("acct-legacy", "owner"),- role=Role.USER,+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"),)- session = service.sessions.session(owner_ctx, session_id)- await session.ensure_exists()- session.add_message("user", [TextPart("legacy message")], peer_id="owner")- await service.viking_fs.rm(f"viking://session/{session_id}/.meta.json", ctx=owner_ctx)-- loaded = await service.sessions.get(session_id, owner_ctx, auto_create=False)- listed = await service.sessions.sessions(owner_ctx)-- assert [part.text for part in loaded.messages[0].parts] == ["legacy message"]- assert loaded.meta.created_by_account_id == "acct-legacy"- assert loaded.meta.created_by_user_id == "owner"- assert any(item["session_id"] == session_id for item in listed)--def test_session_visibility_is_account_scoped_for_non_root(service):- ctx = RequestContext(- user=UserIdentifier("acct-current", "owner"),- role=Role.USER,+ resp = await client.get(+ "/api/v1/content/read",+ params={"uri": f"viking://session/{session_id}/messages.jsonl"},)- meta = SessionMeta(created_by_user_id="owner", participant_user_ids=["owner"])- assert service.sessions._session_is_visible_in_account(ctx, meta) is False-- meta.created_by_account_id = "acct-current"- meta.created_by_user_id = "someone-else"- meta.participant_user_ids = ["someone-else"]- assert service.sessions._session_is_visible_in_account(ctx, meta) is True+ assert resp.status_code == 200+ assert "legacy alias message" in resp.json()["result"]async def test_get_session_context(client: httpx.AsyncClient):@@ -242,9 +224,11 @@ async def test_tool_result_externalization_read_and_search(client: httpx.AsyncClcontext_resp = await client.get(f"/api/v1/sessions/{session_id}/context")assert context_resp.status_code == 200+ session_resp = await client.get(f"/api/v1/sessions/{session_id}")+ session_uri = session_resp.json()["result"]["uri"]part = context_resp.json()["result"]["messages"][0]["parts"][0]assert part["tool_output_truncated"] is True- assert part["tool_output_ref"].startswith(f"viking://session/{session_id}/tool-results/")+ assert part["tool_output_ref"].startswith(f"{session_uri}/tool-results/")assert raw not in part["tool_output"]assert "kind: text" in part["tool_output"]assert "openviking_tool_result_search" in part["tool_output"]@@ -651,6 +635,7 @@ async def test_get_session_context_endpoint_returns_trimmed_latest_archive_and_m):create_resp = await client.post("/api/v1/sessions", json={})session_id = create_resp.json()["result"]["session_id"]+ session_uri = create_resp.json()["result"]["uri"]await client.post(f"/api/v1/sessions/{session_id}/messages",@@ -670,7 +655,7 @@ async def test_get_session_context_endpoint_returns_trimmed_latest_archive_and_m"type": "tool","tool_id": "tool_123","tool_name": "demo_tool",- "tool_uri": f"viking://session/{session_id}/tools/tool_123",+ "tool_uri": f"{session_uri}/tools/tool_123","tool_input": {"x": 1},"tool_status": "running",},diff --git a/tests/server/test_auth.py b/tests/server/test_auth.pyindex b5c2a866e..1776e3c5d 100644--- a/tests/server/test_auth.py+++ b/tests/server/test_auth.py@@ -586,10 +586,10 @@ async def test_cross_tenant_session_get_returns_not_found(auth_client: httpx.Asyassert cross_get.json()["error"]["code"] == "NOT_FOUND"-async def test_sessions_are_visible_to_users_within_account(+async def test_sessions_are_isolated_between_users_within_account(auth_client: httpx.AsyncClient, auth_app):- """Session access is account-scoped, not user-isolated within an account."""+ """Session access is user-scoped even within the same account."""manager = auth_app.state.api_key_manageraccount_id = _uid()admin_key = await manager.create_account(account_id, "admin_user")@@ -619,7 +619,7 @@ async def test_sessions_are_visible_to_users_within_account(assert alice_list.status_code == 200alice_ids = {item["session_id"] for item in alice_list.json()["result"]}assert alice_session in alice_ids- assert bob_session in alice_ids+ assert bob_session not in alice_idsbob_list = await auth_client.get("/api/v1/sessions",@@ -628,7 +628,7 @@ async def test_sessions_are_visible_to_users_within_account(assert bob_list.status_code == 200bob_ids = {item["session_id"] for item in bob_list.json()["result"]}assert bob_session in bob_ids- assert alice_session in bob_ids+ assert alice_session not in bob_idsadmin_list = await auth_client.get("/api/v1/sessions",@@ -636,21 +636,36 @@ async def test_sessions_are_visible_to_users_within_account()assert admin_list.status_code == 200admin_ids = {item["session_id"] for item in admin_list.json()["result"]}- assert {alice_session, bob_session}.issubset(admin_ids)+ assert alice_session not in admin_ids+ assert bob_session not in admin_idsbob_get_alice = await auth_client.get(f"/api/v1/sessions/{alice_session}",headers={"X-API-Key": bob_key},)- assert bob_get_alice.status_code == 200+ assert bob_get_alice.status_code == 404bob_write_alice = await auth_client.post(f"/api/v1/sessions/{alice_session}/messages",- json={"role": "user", "content": "bob writes in same account session"},+ json={"role": "user", "content": "bob writes same id in his own namespace"},headers={"X-API-Key": bob_key},)assert bob_write_alice.status_code == 200+ alice_get_after_bob_write = await auth_client.get(+ f"/api/v1/sessions/{alice_session}",+ headers={"X-API-Key": alice_key},+ )+ assert alice_get_after_bob_write.status_code == 200+ assert alice_get_after_bob_write.json()["result"]["message_count"] == 0++ bob_get_same_id = await auth_client.get(+ f"/api/v1/sessions/{alice_session}",+ headers={"X-API-Key": bob_key},+ )+ assert bob_get_same_id.status_code == 200+ assert bob_get_same_id.json()["result"]["message_count"] == 1+async def test_root_tenant_scoped_requests_rejected_in_api_key_mode():"""ROOT API keys cannot access tenant-scoped data APIs in api_key mode."""diff --git a/tests/session/conftest.py b/tests/session/conftest.pyindex 432f0a089..85cd77e43 100644--- a/tests/session/conftest.py+++ b/tests/session/conftest.py@@ -71,7 +71,7 @@ async def session_with_tool_call(tool_part = ToolPart(tool_id=tool_id,tool_name="test_tool",- tool_uri=f"viking://session/{session.session_id}/tools/{tool_id}",+ tool_uri=f"{session.uri}/tools/{tool_id}",skill_uri="viking://user/skills/test_skill",tool_input={"param": "value"},tool_status="running",diff --git a/tests/session/test_session_messages.py b/tests/session/test_session_messages.pyindex 5ab4880f9..e06552fc5 100644--- a/tests/session/test_session_messages.py+++ b/tests/session/test_session_messages.py@@ -57,7 +57,7 @@ class TestAddMessage:tool_part = ToolPart(tool_id="tool_123",tool_name="search_tool",- tool_uri="viking://session/test/tools/tool_123",+ tool_uri=f"{session.uri}/tools/tool_123",skill_uri="viking://user/skills/search",tool_input={"query": "test"},tool_status="running",@@ -99,7 +99,8 @@ class TestAddMessage:self, client: AsyncOpenViking):session_id = "batch_message_preservation_test"- await client.create_session(session_id=session_id)+ created = await client.create_session(session_id=session_id)+ session_uri = created["uri"]result = await client.batch_add_messages(session_id,@@ -128,7 +129,7 @@ class TestAddMessage:"type": "tool","tool_id": "tool_123","tool_name": "search_tool",- "tool_uri": f"viking://session/test/{session_id}/tools/tool_123",+ "tool_uri": f"{session_uri}/tools/tool_123","skill_uri": "viking://user/skills/search","tool_status": "completed","tool_output": "Found a result",diff --git a/tests/session/test_tool_result_externalization.py b/tests/session/test_tool_result_externalization.pyindex e58b6bee1..c7f3a0408 100644--- a/tests/session/test_tool_result_externalization.py+++ b/tests/session/test_tool_result_externalization.py@@ -102,7 +102,7 @@ async def test_add_message_externalizes_large_tool_output(session: Session):part = msg.get_tool_parts()[0]assert part.tool_output_truncated is True- assert part.tool_output_ref.startswith(f"viking://session/{session.session_id}/tool-results/")+ assert part.tool_output_ref.startswith(f"{session.uri}/tool-results/")assert part.tool_output_original_chars == len(raw)assert part.tool_output_externalized_reason == "single_threshold"assert raw not in part.tool_output@@ -460,7 +460,7 @@ async def test_assistant_turn_budget_uses_rendered_stub_length(session: Session)raw_b = _json_items_payload(40)raw_c = _json_items_payload(1)ref_a = (- f"viking://session/{session.session_id}/tool-results/"+ f"{session.uri}/tool-results/"f"{tool_result_store.build_tool_result_id('call_a', tool_result_store.sha256_text(raw_a))}")stub_a = tool_result_store.make_preview(diff --git a/tests/storage/test_semantic_dag_skip_files.py b/tests/storage/test_semantic_dag_skip_files.pyindex 70bae748d..95e0568fa 100644--- a/tests/storage/test_semantic_dag_skip_files.py+++ b/tests/storage/test_semantic_dag_skip_files.py@@ -87,10 +87,16 @@ class _DummyTracker:@pytest.mark.asyncio-async def test_messages_jsonl_excluded_from_summary(monkeypatch):+ "root_uri",+ [+ "viking://session/test-session",+ "viking://user/user1/sessions/test-session",+ ],+)+async def test_messages_jsonl_excluded_from_summary(monkeypatch, root_uri):"""messages.jsonl should be skipped by _list_dir and never summarized."""_mock_transaction_layer(monkeypatch)- root_uri = "viking://session/test-session"tree = {root_uri: [{"name": "messages.jsonl", "isDir": False},@@ -122,10 +128,16 @@ async def test_messages_jsonl_excluded_from_summary(monkeypatch):@pytest.mark.asyncio-async def test_messages_jsonl_excluded_in_subdirectory(monkeypatch):+ "root_uri",+ [+ "viking://session/test-session",+ "viking://user/user1/sessions/test-session",+ ],+)+async def test_messages_jsonl_excluded_in_subdirectory(monkeypatch, root_uri):"""messages.jsonl in a subdirectory should also be skipped."""_mock_transaction_layer(monkeypatch)- root_uri = "viking://session/test-session"tree = {root_uri: [{"name": "subdir", "isDir": True},diff --git a/tests/storage/test_viking_fs_tree.py b/tests/storage/test_viking_fs_tree.pyindex ce8b86051..6a024ab93 100644--- a/tests/storage/test_viking_fs_tree.py+++ b/tests/storage/test_viking_fs_tree.py@@ -127,8 +127,8 @@ async def default_batch_fetch(entries, abs_limit, **_kwargs):[("resources", "/local/test_account", True),("user", "/local/test_account", True),- ("agent", "/local/test_account", True),- ("session", "/local/test_account", True),+ ("agent", "/local/test_account", False),+ ("session", "/local/test_account", False),("tasks", "/local/test_account", False),("_system", "/local/test_account", False),("temp", "/local/test_account", False),diff --git a/tests/test_session_task_tracking.py b/tests/test_session_task_tracking.pyindex 839524a9d..f7af78254 100644--- a/tests/test_session_task_tracking.py+++ b/tests/test_session_task_tracking.py@@ -10,6 +10,7 @@ import httpximport pytest_asynciofrom openviking import AsyncOpenViking+from openviking.core.namespace import canonical_session_urifrom openviking.server.app import create_appfrom openviking.server.config import ServerConfigfrom openviking.server.dependencies import set_service@@ -72,7 +73,7 @@ def _make_tracked_commit(behavior="instant", result_overrides=None, gate=None, saccount_id=_ctx.account_id,user_id=_ctx.user.user_id,)- archive_uri = f"viking://session/test/{_sid}/history/archive_001"+ archive_uri = f"{canonical_session_uri(_ctx, _sid)}/history/archive_001"async def _background():await tracker.start(task.task_id, account_id=_ctx.account_id, user_id=_ctx.user.user_id)diff --git a/tests/unit/test_langchain_integration.py b/tests/unit/test_langchain_integration.pyindex 337a17cba..f161695b1 100644--- a/tests/unit/test_langchain_integration.py+++ b/tests/unit/test_langchain_integration.py@@ -969,7 +969,7 @@ def test_archive_search_without_archive_id_searches_raw_history():)assert "Hidden cobalt archive detail" in searched- assert "viking://session/archive-search-session/history" in searched+ assert "viking://user/default/sessions/archive-search-session/history" in searcheddef test_archive_grep_pattern_uses_backend_safe_token_regex():diff --git a/tests/unit/test_namespace_uri_classification.py b/tests/unit/test_namespace_uri_classification.pyindex 55a2dc02b..079ae9626 100644--- a/tests/unit/test_namespace_uri_classification.py+++ b/tests/unit/test_namespace_uri_classification.py@@ -3,9 +3,14 @@"""Tests for shared Viking URI namespace/content classification."""from openviking.core.namespace import (+ canonical_session_uri,+ canonicalize_uri,classify_uri,context_type_for_uri,+ is_session_uri,+ legacy_session_uri,owner_space_for_uri,+ visible_roots,)from openviking.server.identity import RequestContext, Rolefrom openviking_cli.session.user_id import UserIdentifier@@ -48,3 +53,25 @@ def test_owner_space_for_uri_uses_user_only():assert owner_space_for_uri("viking://user/alice/memories", ctx) == "alice"assert owner_space_for_uri("viking://user/alice/skills/demo", ctx) == "alice"assert owner_space_for_uri("viking://resources/readme.md", ctx) == ""+++def test_session_uri_helpers_use_user_namespace():+ ctx = RequestContext(+ user=UserIdentifier(account_id="acct", user_id="alice"),+ role=Role.USER,+ )++ assert canonical_session_uri(ctx) == "viking://user/alice/sessions"+ assert canonical_session_uri(ctx, "s1") == "viking://user/alice/sessions/s1"+ assert canonicalize_uri("viking://user/sessions/s1", ctx) == ("viking://user/alice/sessions/s1")+ assert canonicalize_uri("user/sessions/s1", ctx) == "viking://user/alice/sessions/s1"+ assert canonicalize_uri("viking://session/s1", ctx) == "viking://user/alice/sessions/s1"+ assert (+ canonicalize_uri("viking://session/s1/history/archive_001/messages.jsonl", ctx)+ == "viking://user/alice/sessions/s1/history/archive_001/messages.jsonl"+ )+ assert legacy_session_uri("s1") == "viking://session/s1"+ assert is_session_uri("viking://user/alice/sessions/s1")+ assert is_session_uri("viking://user/sessions/s1")+ assert is_session_uri("viking://session/s1")+ assert "viking://session" not in visible_roots(ctx)diff --git a/tests/unit/test_uri_validation.py b/tests/unit/test_uri_validation.pyindex 227673f11..fe63758fe 100644--- a/tests/unit/test_uri_validation.py+++ b/tests/unit/test_uri_validation.py@@ -15,6 +15,7 @@ from openviking_cli.exceptions import InvalidURIError"viking://resources/docs","resources/docs","/resources/docs",+ "viking://session/s1","viking://",],)