Skip to content

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

feat(rebuild): add rebuild api scaffold (#1592)

Jiahui Zhouac3346422aef
diff --git a/Cargo.lock b/Cargo.lock
index f272aad47..521a0cfe5 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -2887,7 +2887,7 @@ checksum = "1a80800c0488c3a21695ea981a54918fbb37abf04f4d0720c453632255e2ff0e"
[[package]]
name = "ov_cli"
-version = "0.2.6"
+version = "0.3.14"
dependencies = [
"anyhow",
"bytes",
diff --git a/crates/ov_cli/src/client.rs b/crates/ov_cli/src/client.rs
index bfc917777..02adfc78e 100644
--- a/crates/ov_cli/src/client.rs
+++ b/crates/ov_cli/src/client.rs
@@ -168,12 +168,12 @@ impl HttpClient {
pub async fn reindex(
&self,
uri: &str,
- regenerate: bool,
+ mode: &str,
wait: bool,
) -> Result<serde_json::Value> {
let body = serde_json::json!({
"uri": uri,
- "regenerate": regenerate,
+ "mode": mode,
"wait": wait,
});
self.post("/api/v1/content/reindex", &body).await
diff --git a/crates/ov_cli/src/commands/content.rs b/crates/ov_cli/src/commands/content.rs
index 6938d073c..3e062a3dc 100644
--- a/crates/ov_cli/src/commands/content.rs
+++ b/crates/ov_cli/src/commands/content.rs
@@ -64,12 +64,12 @@ pub async fn write(
pub async fn reindex(
client: &HttpClient,
uri: &str,
- regenerate: bool,
+ mode: &str,
wait: bool,
output_format: OutputFormat,
compact: bool,
) -> Result<()> {
- let result = client.reindex(uri, regenerate, wait).await?;
+ let result = client.reindex(uri, mode, wait).await?;
crate::output::output_success(result, output_format, compact);
Ok(())
}
diff --git a/crates/ov_cli/src/handlers.rs b/crates/ov_cli/src/handlers.rs
index 7c595a74b..a4864ccb9 100644
--- a/crates/ov_cli/src/handlers.rs
+++ b/crates/ov_cli/src/handlers.rs
@@ -549,17 +549,14 @@ pub async fn handle_write(
.await
}
-pub async fn handle_reindex(uri: String, regenerate: bool, wait: bool, ctx: CliContext) -> Result<()> {
+pub async fn handle_reindex(
+ uri: String,
+ mode: String,
+ wait: bool,
+ ctx: CliContext,
+) -> Result<()> {
let client = ctx.get_client();
- commands::content::reindex(
- &client,
- &uri,
- regenerate,
- wait,
- ctx.output_format,
- ctx.compact,
- )
- .await
+ commands::content::reindex(&client, &uri, &mode, wait, ctx.output_format, ctx.compact).await
}
pub async fn handle_get(uri: String, local_path: String, ctx: CliContext) -> Result<()> {
diff --git a/crates/ov_cli/src/main.rs b/crates/ov_cli/src/main.rs
index 47426800b..ec3465478 100644
--- a/crates/ov_cli/src/main.rs
+++ b/crates/ov_cli/src/main.rs
@@ -576,15 +576,15 @@ enum Commands {
#[command(subcommand)]
action: SystemCommands,
},
- /// [Admin] Reindex content at URI (regenerates .abstract.md and .overview.md)
+ /// [Admin] Reindex semantic/vector artifacts for a URI
Reindex {
/// Viking URI
uri: String,
- /// Force regenerate summaries even if they exist
- #[arg(short, long)]
- regenerate: bool,
+ /// Reindex mode
+ #[arg(long, default_value = "vectors_only")]
+ mode: String,
/// Wait for reindex to complete
- #[arg(long, default_value = "true")]
+ #[arg(long, default_value_t = true, action = ArgAction::Set)]
wait: bool,
},
}
@@ -1186,9 +1186,9 @@ async fn main() {
}
Commands::Reindex {
uri,
- regenerate,
+ mode,
wait,
- } => handlers::handle_reindex(uri, regenerate, wait, ctx).await,
+ } => handlers::handle_reindex(uri, mode, wait, ctx).await,
Commands::Get { uri, local_path } => handlers::handle_get(uri, local_path, ctx).await,
Commands::Find {
query,
@@ -1372,6 +1372,20 @@ mod tests {
assert!(result.is_err(), "removed write flags should not parse");
}
+ #[test]
+ fn cli_parses_reindex_command() {
+ let result = Cli::try_parse_from([
+ "ov",
+ "reindex",
+ "viking://resources/demo",
+ "--mode",
+ "semantic_and_vectors",
+ "--wait=false",
+ ]);
+
+ assert!(result.is_ok(), "reindex command should parse");
+ }
+
#[test]
fn append_time_filter_params_only_emits_after_and_before() {
let mut params = Vec::new();
diff --git a/docs/en/api/01-overview.md b/docs/en/api/01-overview.md
index bb5e05a8d..cf46151d5 100644
--- a/docs/en/api/01-overview.md
+++ b/docs/en/api/01-overview.md
@@ -384,7 +384,7 @@ Below are all HTTP API endpoints provided by OpenViking, grouped by functional m
| GET | `/api/v1/content/overview` | Read overview (L1) |
| GET | `/api/v1/content/download` | Download raw file bytes |
| POST | `/api/v1/content/write` | Update an existing file and refresh semantics/vectors |
-| POST | `/api/v1/content/reindex` | Rebuild semantic/vector index for existing content (deprecated, use maintenance) |
+| POST | `/api/v1/content/reindex` | Rebuild semantic/vector index for existing content |
### Search
@@ -456,12 +456,6 @@ Below are all HTTP API endpoints provided by OpenViking, grouped by functional m
| GET | `/api/v1/debug/vector/scroll` | Paginated vector record inspection |
| GET | `/api/v1/debug/vector/count` | Count vector records |
-### Maintenance
-
-| Method | Path | Description | Permission |
-|--------|------|-------------|------------|
-| POST | `/api/v1/maintenance/reindex` | Reindex content (optional abstract regeneration) | ROOT/ADMIN |
-
### Statistics
| Method | Path | Description |
diff --git a/docs/en/api/07-system.md b/docs/en/api/07-system.md
index 657437d7f..1dca700ff 100644
--- a/docs/en/api/07-system.md
+++ b/docs/en/api/07-system.md
@@ -243,6 +243,189 @@ ov system wait --timeout 60
---
+### reindex()
+
+Reindex semantic and/or vector artifacts for existing content already stored in OpenViking. This is an operational maintenance API intended for scenarios such as embedding model changes, VLM changes, vector store rebuild, or post-upgrade repair of existing indexes.
+
+This API operates on existing `viking://...` content. It does not import new files. For normal ingestion, use [Resources](02-resources.md).
+
+**Authentication**
+
+- HTTP endpoint: requires root/admin access when authentication is enabled; root-key requests must include `X-OpenViking-Account`
+- Python embedded mode: uses the current service context
+- Python HTTP client / CLI: sends the current authenticated identity
+
+**Parameters**
+
+| Parameter | Type | Required | Default | Description |
+|-----------|------|----------|---------|-------------|
+| uri | str | Yes | - | Viking URI to reindex |
+| mode | str | No | `vectors_only` | Reindex mode: `vectors_only` or `semantic_and_vectors` |
+| wait | bool | No | `true` | Whether to wait for completion |
+
+The HTTP request body rejects unknown fields. `uri` may use OpenViking path variables accepted by other content APIs; it is resolved before validation.
+
+**Supported URI scopes**
+
+- `viking://`
+- `viking://user`
+- `viking://user/<user_id>`
+- `viking://agent`
+- `viking://agent/<agent_id>`
+- `viking://resources`
+- `viking://resources/...`
+- `viking://user/<user_id>/memories/...`
+- `viking://agent/<agent_id>/memories/...`
+- `viking://agent/<agent_id>/skills`
+- `viking://agent/<agent_id>/skills/<skill_name>`
+
+`viking://session/...` is not supported by `reindex()`.
+
+**Modes**
+
+- `vectors_only`: rebuilds vector-store records from currently recoverable source data without rewriting `.abstract.md` or `.overview.md`
+- `semantic_and_vectors`: regenerates semantic artifacts first, then rebuilds vectors from the refreshed semantic outputs
+
+For `resource` and `skill`, `semantic_and_vectors` refreshes directory/file semantic artifacts, including `.abstract.md` and `.overview.md`. For `memory`, it rebuilds the current persisted memory subtree semantics and vectors, but it does not replay historical extraction order.
+
+For `semantic_and_vectors`, semantic generation and vector rebuilding are sequenced by the reindex executor. The semantic refresh step does not enqueue its own background vectorization work; vectors are rebuilt by the reindex step so `wait=true` reflects the reindex operation itself.
+
+**Python SDK (Embedded / HTTP)**
+
+```python
+result = client.reindex(
+ uri="viking://resources",
+ mode="vectors_only",
+ wait=True,
+)
+print(result)
+```
+
+```python
+result = client.reindex(
+ uri="viking://agent/default/skills",
+ mode="semantic_and_vectors",
+ wait=False,
+)
+print(result["status"])
+```
+
+**HTTP API**
+
+```
+POST /api/v1/content/reindex
+```
+
+There is no `/api/v1/maintenance/reindex` endpoint. Use `/api/v1/content/reindex`.
+
+```bash
+curl -X POST http://localhost:1933/api/v1/content/reindex \
+ -H "Content-Type: application/json" \
+ -H "X-API-Key: your-key" \
+ -H "X-OpenViking-Account: default" \
+ -d '{
+ "uri": "viking://resources",
+ "mode": "vectors_only",
+ "wait": true
+ }'
+```
+
+**CLI**
+
+```bash
+openviking reindex viking://resources --mode vectors_only
+```
+
+```bash
+openviking reindex viking://agent/default/skills --mode semantic_and_vectors --wait false
+```
+
+**Synchronous response (`wait=true`)**
+
+```json
+{
+ "status": "ok",
+ "result": {
+ "uri": "viking://resources",
+ "mode": "vectors_only",
+ "status": "completed",
+ "object_type": "resource",
+ "scanned_records": 120,
+ "rebuilt_records": 118,
+ "unsupported_records": 2,
+ "failed_records": 0,
+ "duration_ms": 1284,
+ "warnings": []
+ },
+ "time": 0.1
+}
+```
+
+**Asynchronous response (`wait=false`)**
+
+```json
+{
+ "status": "ok",
+ "result": {
+ "uri": "viking://resources",
+ "mode": "vectors_only",
+ "object_type": "resource",
+ "status": "accepted",
+ "task_id": "task_xxx"
+ },
+ "time": 0.1
+}
+```
+
+Poll the returned task through the task API:
+
+```bash
+curl -X GET http://localhost:1933/api/v1/tasks/task_xxx \
+ -H "X-API-Key: your-key" \
+ -H "X-OpenViking-Account: default"
+```
+
+Reindex background tasks use `task_type="admin_reindex"` and `resource_id` equal to the requested `uri`, so they can also be listed with:
+
+```text
+GET /api/v1/tasks?task_type=admin_reindex&resource_id=viking://resources
+```
+
+Task records are kept in memory and can expire or be lost on server restart.
+
+**Result fields**
+
+| Field | Description |
+|-------|-------------|
+| status | `completed` for synchronous completion, `accepted` for background execution |
+| uri | Requested URI after path-variable resolution |
+| object_type | Inferred target type, such as `resource`, `skill`, `memory`, `user_namespace`, `agent_namespace`, `skill_namespace`, or `global_namespace` |
+| mode | Effective reindex mode |
+| scanned_records | Number of records or semantic sources considered |
+| rebuilt_records | Number of vector records successfully rebuilt |
+| unsupported_records | Number of records skipped because no usable vector source was available |
+| failed_records | Number of records that failed while rebuilding |
+| duration_ms | Synchronous run duration in milliseconds |
+| warnings | Recoverable per-record warnings |
+| task_id | Background task ID, present only when `wait=false` |
+
+**Behavior notes**
+
+- Reindex is non-destructive. It uses rebuild/upsert behavior and does not require dropping the vector collection first.
+- `viking://` reindex fans out to supported top-level namespaces and excludes `session`.
+- Namespace reindex operations such as `viking://user` or `viking://agent/default` propagate to their supported child content types.
+- `vectors_only` is the right mode when only the embedding model or vector index needs to be refreshed.
+- `semantic_and_vectors` is the right mode when semantic artifacts themselves must be regenerated before re-vectorization.
+- Only one reindex task can run for the same URI and owner at a time. A concurrent request for the same target returns a conflict.
+- For resource files, text files can use file content when no summary is available. Non-text files require a generated summary or existing vector record fallback; otherwise they are counted as unsupported.
+
+**Current limitations**
+
+- Reindex uses the best currently recoverable source inputs. It is not guaranteed to replay the exact historical embedding input byte-for-byte in every case.
+- Memory semantic reindex is based on the currently persisted memory tree. It does not reconstruct the original chronological memory-extraction pipeline.
+
+---
+
## Observer API
The observer API provides detailed component-level monitoring.
diff --git a/docs/zh/api/01-overview.md b/docs/zh/api/01-overview.md
index 68e3b6725..554244cb9 100644
--- a/docs/zh/api/01-overview.md
+++ b/docs/zh/api/01-overview.md
@@ -384,7 +384,7 @@ JSON 输出 - 错误:
| GET | `/api/v1/content/overview` | 读取概览(L1) |
| GET | `/api/v1/content/download` | 下载原始文件字节流 |
| POST | `/api/v1/content/write` | 修改已有文件并自动刷新语义与向量 |
-| POST | `/api/v1/content/reindex` | 重新构建语义/向量索引(已废弃,请使用 maintenance) |
+| POST | `/api/v1/content/reindex` | 重新构建已有内容的语义/向量索引 |
### 搜索端点
@@ -456,12 +456,6 @@ JSON 输出 - 错误:
| GET | `/api/v1/debug/vector/scroll` | 分页查看向量记录 |
| GET | `/api/v1/debug/vector/count` | 统计向量记录数量 |
-### 维护端点
-
-| 方法 | 路径 | 说明 | 权限 |
-|------|------|------|------|
-| POST | `/api/v1/maintenance/reindex` | 重新索引内容(可选择重新生成摘要) | ROOT/ADMIN |
-
### 统计端点
| 方法 | 路径 | 说明 |
diff --git a/docs/zh/api/07-system.md b/docs/zh/api/07-system.md
index 909d324fd..0c5de4c10 100644
--- a/docs/zh/api/07-system.md
+++ b/docs/zh/api/07-system.md
@@ -243,6 +243,189 @@ ov system wait --timeout 60
---
+### reindex()
+
+对已经存储在 OpenViking 中的现有内容,重新构建语义产物和/或向量索引。这是一个运维维护接口,适用于 embedding 模型更换、VLM 更换、向量库重刷、版本升级后修复历史索引等场景。
+
+这个接口面向已有的 `viking://...` 内容,不负责导入新文件。常规导入请使用 [Resources](02-resources.md)。
+
+**认证**
+
+- HTTP 端点:在开启认证时要求 root/admin 权限;root key 请求必须带 `X-OpenViking-Account`
+- Python embedded 模式:使用当前 service context
+- Python HTTP client / CLI:使用当前认证身份发起请求
+
+**参数**
+
+| 参数 | 类型 | 必填 | 默认值 | 说明 |
+|------|------|------|--------|------|
+| uri | str | 是 | - | 要重新索引的 Viking URI |
+| mode | str | 否 | `vectors_only` | 重建模式:`vectors_only` 或 `semantic_and_vectors` |
+| wait | bool | 否 | `true` | 是否等待任务完成 |
+
+HTTP 请求体不接受未知字段。`uri` 可以使用其他 content API 支持的 OpenViking 路径变量,服务端会先解析再校验。
+
+**支持的 URI 范围**
+
+- `viking://`
+- `viking://user`
+- `viking://user/<user_id>`
+- `viking://agent`
+- `viking://agent/<agent_id>`
+- `viking://resources`
+- `viking://resources/...`
+- `viking://user/<user_id>/memories/...`
+- `viking://agent/<agent_id>/memories/...`
+- `viking://agent/<agent_id>/skills`
+- `viking://agent/<agent_id>/skills/<skill_name>`
+
+`reindex()` 不支持 `viking://session/...`。
+
+**模式说明**
+
+- `vectors_only`:基于当前仍可恢复的源数据重建向量库记录,不会重写 `.abstract.md` 和 `.overview.md`
+- `semantic_and_vectors`:先重新生成语义产物,再基于新的语义结果重建向量
+
+对于 `resource` 和 `skill`,`semantic_and_vectors` 会刷新目录/文件语义产物,包括 `.abstract.md` 和 `.overview.md`。对于 `memory`,它会重建当前已持久化 memory 子树的语义和向量,但不会回放历史记忆抽取顺序。
+
+对于 `semantic_and_vectors`,语义刷新和向量重建由 reindex executor 串行编排。语义刷新阶段不会再额外向后台 embedding queue 投递自己的向量化任务;向量由 reindex 阶段统一重建,因此 `wait=true` 表示等待 reindex 操作本身完成。
+
+**Python SDK (Embedded / HTTP)**
+
+```python
+result = client.reindex(
+ uri="viking://resources",
+ mode="vectors_only",
+ wait=True,
+)
+print(result)
+```
+
+```python
+result = client.reindex(
+ uri="viking://agent/default/skills",
+ mode="semantic_and_vectors",
+ wait=False,
+)
+print(result["status"])
+```
+
+**HTTP API**
+
+```
+POST /api/v1/content/reindex
+```
+
+不存在 `/api/v1/maintenance/reindex` 端点。请使用 `/api/v1/content/reindex`。
+
+```bash
+curl -X POST http://localhost:1933/api/v1/content/reindex \
+ -H "Content-Type: application/json" \
+ -H "X-API-Key: your-key" \
+ -H "X-OpenViking-Account: default" \
+ -d '{
+ "uri": "viking://resources",
+ "mode": "vectors_only",
+ "wait": true
+ }'
+```
+
+**CLI**
+
+```bash
+openviking reindex viking://resources --mode vectors_only
+```
+
+```bash
+openviking reindex viking://agent/default/skills --mode semantic_and_vectors --wait false
+```
+
+**同步响应(`wait=true`)**
+
+```json
+{
+ "status": "ok",
+ "result": {
+ "uri": "viking://resources",
+ "mode": "vectors_only",
+ "status": "completed",
+ "object_type": "resource",
+ "scanned_records": 120,
+ "rebuilt_records": 118,
+ "unsupported_records": 2,
+ "failed_records": 0,
+ "duration_ms": 1284,
+ "warnings": []
+ },
+ "time": 0.1
+}
+```
+
+**异步响应(`wait=false`)**
+
+```json
+{
+ "status": "ok",
+ "result": {
+ "uri": "viking://resources",
+ "mode": "vectors_only",
+ "object_type": "resource",
+ "status": "accepted",
+ "task_id": "task_xxx"
+ },
+ "time": 0.1
+}
+```
+
+使用返回的 task 查询后台任务:
+
+```bash
+curl -X GET http://localhost:1933/api/v1/tasks/task_xxx \
+ -H "X-API-Key: your-key" \
+ -H "X-OpenViking-Account: default"
+```
+
+Reindex 后台任务的 `task_type` 为 `admin_reindex`,`resource_id` 等于请求中的 `uri`,也可以这样列出:
+
+```text
+GET /api/v1/tasks?task_type=admin_reindex&resource_id=viking://resources
+```
+
+任务记录保存在内存中,可能过期,也会在服务重启后丢失。
+
+**结果字段**
+
+| 字段 | 说明 |
+|------|------|
+| status | 同步完成时为 `completed`,后台执行时为 `accepted` |
+| uri | 解析路径变量后的请求 URI |
+| object_type | 推断出的目标类型,例如 `resource`、`skill`、`memory`、`user_namespace`、`agent_namespace`、`skill_namespace` 或 `global_namespace` |
+| mode | 实际执行的 reindex 模式 |
+| scanned_records | 被检查的记录或语义源数量 |
+| rebuilt_records | 成功重建的向量记录数量 |
+| unsupported_records | 因没有可用向量来源而跳过的记录数量 |
+| failed_records | 重建失败的记录数量 |
+| duration_ms | 同步执行耗时,单位毫秒 |
+| warnings | 可恢复的单条记录级 warning |
+| task_id | 后台任务 ID,仅 `wait=false` 时返回 |
+
+**行为说明**
+
+- Reindex 是非破坏式的,采用重建/覆盖写入,不需要先 drop 向量集合。
+- 对 `viking://` 发起 reindex 时,会向下分发到支持的顶层命名空间,并显式排除 `session`。
+- 命名空间级 reindex,例如 `viking://user` 或 `viking://agent/default`,会继续传播到其支持的子内容类型。
+- 如果只是 embedding 模型或向量索引需要刷新,应使用 `vectors_only`。
+- 如果语义产物本身也需要重建,再做重向量化,应使用 `semantic_and_vectors`。
+- 同一个 URI 和 owner 同时只能运行一个 reindex 任务。对同一目标的并发请求会返回 conflict。
+- 对 resource 文件,文本文件在没有 summary 时可以使用文件正文;非文本文件需要已生成的 summary 或已有向量记录 fallback,否则会计为 unsupported。
+
+**当前限制**
+
+- Reindex 会使用当前系统中“尽可能可恢复”的输入进行重建,不保证所有场景都能逐字节回放历史当时的 embedding 输入。
+- Memory 的 semantic reindex 基于当前已持久化的 memory 树,不会重建最初按时间顺序执行的记忆抽取流水线。
+
+---
+
## Observer API
Observer API 提供详细的组件级监控。
diff --git a/openviking/async_client.py b/openviking/async_client.py
index d7c6ad7e8..c3f79802f 100644
--- a/openviking/async_client.py
+++ b/openviking/async_client.py
@@ -208,6 +208,20 @@ class AsyncOpenViking:
await self._ensure_initialized()
return await self._client.get_task(task_id)
+ async def reindex(
+ self,
+ uri: str,
+ mode: str = "vectors_only",
+ wait: bool = True,
+ ) -> Dict[str, Any]:
+ """Reindex semantic/vector artifacts for a URI."""
+ await self._ensure_initialized()
+ return await self._client.reindex(
+ uri=uri,
+ mode=mode,
+ wait=wait,
+ )
+
# ============= Resource methods =============
async def add_resource(
diff --git a/openviking/client/local.py b/openviking/client/local.py
index f6d9db8c2..e8f800990 100644
--- a/openviking/client/local.py
+++ b/openviking/client/local.py
@@ -157,6 +157,19 @@ class LocalClient(BaseClient):
"""Wait for all processing to complete."""
return await self._service.resources.wait_processed(timeout=timeout)
+ async def reindex(
+ self,
+ uri: str,
+ mode: str = "vectors_only",
+ wait: bool = True,
+ ) -> Dict[str, Any]:
+ """Reindex semantic/vector artifacts for a URI."""
+ return await self._service.reindex(
+ uri=uri,
+ mode=mode,
+ wait=wait,
+ )
+
async def build_index(self, resource_uris: Union[str, List[str]], **kwargs) -> Dict[str, Any]:
"""Manually trigger index building."""
if isinstance(resource_uris, str):
diff --git a/openviking/core/context.py b/openviking/core/context.py
index 612437bde..e43d3c3fa 100644
--- a/openviking/core/context.py
+++ b/openviking/core/context.py
@@ -7,7 +7,7 @@ from enum import Enum
from typing import Any, Dict, List, Optional
from uuid import uuid4
-from openviking.core.namespace import owner_fields_for_uri
+from openviking.core.namespace import context_type_for_uri, owner_fields_for_uri
from openviking.utils.time_utils import format_iso8601, parse_iso_datetime
from openviking_cli.session.user_id import UserIdentifier
from openviking_cli.utils.uri import VikingURI
@@ -86,7 +86,7 @@ class Context:
self.temp_uri = temp_uri
self.is_leaf = is_leaf
self.abstract = abstract
- self.context_type = context_type or self._derive_context_type()
+ self.context_type = context_type or context_type_for_uri(uri)
self.category = category or self._derive_category()
self.created_at = created_at or datetime.now(timezone.utc)
self.updated_at = updated_at or self.created_at
@@ -125,15 +125,6 @@ class Context:
return user.user_id
return ""
- def _derive_context_type(self) -> str:
- """Derive context type from URI using substring matching."""
- if "/skills" in self.uri:
- return "skill"
- elif "/memories" in self.uri:
- return "memory"
- else:
- return "resource"
-
def _derive_category(self) -> str:
"""Derive category from URI using substring matching."""
if "/patterns" in self.uri:
diff --git a/openviking/core/directories.py b/openviking/core/directories.py
index ae97d7de5..4c0ad70ef 100644
--- a/openviking/core/directories.py
+++ b/openviking/core/directories.py
@@ -10,11 +10,12 @@ This module defines the preset directory structure that is created on initializa
from dataclasses import dataclass, field
from typing import TYPE_CHECKING, Dict, List, Optional
-from openviking.core.context import Context, ContextType, Vectorize
+from openviking.core.context import Context, Vectorize
from openviking.core.namespace import (
agent_space_fragment,
canonical_agent_root,
canonical_user_root,
+ context_type_for_uri,
user_space_fragment,
)
from openviking.server.identity import RequestContext
@@ -135,19 +136,6 @@ PRESET_DIRECTORIES: Dict[str, DirectoryDefinition] = {
}
-def get_context_type_for_uri(uri: str) -> str:
- """Determine context_type based on URI."""
- if "/memories" in uri:
- return ContextType.MEMORY.value
- elif "/resources" in uri:
- return ContextType.RESOURCE.value
- elif "/skills" in uri:
- return ContextType.SKILL.value
- elif uri.startswith("viking://session"):
- return ContextType.MEMORY.value
- return ContextType.RESOURCE.value
-
-
class DirectoryInitializer:
"""Initialize preset directory structure."""
@@ -309,7 +297,7 @@ class DirectoryInitializer:
uri=uri,
parent_uri=parent_uri,
is_leaf=False,
- context_type=get_context_type_for_uri(uri),
+ context_type=context_type_for_uri(uri),
abstract=defn.abstract,
level=level,
user=ctx.user,
diff --git a/openviking/core/namespace.py b/openviking/core/namespace.py
index ea714332e..e3e832814 100644
--- a/openviking/core/namespace.py
+++ b/openviking/core/namespace.py
@@ -17,6 +17,11 @@ _AGENT_SHORTHAND_SEGMENTS = {
".abstract.md",
".overview.md",
}
+_CROSS_SCOPE_OWNER_SEGMENT = {"user": "agent", "agent": "user"}
+_CONTENT_TYPES_BY_SCOPE = {
+ "user": {"memories": "memory"},
+ "agent": {"memories": "memory", "skills": "skill"},
+}
class NamespaceShapeError(ValueError):
@@ -34,8 +39,59 @@ class ResolvedNamespace:
is_container: bool = False
-def _uri_parts(uri: str) -> list[str]:
- normalized = VikingURI.normalize(uri).rstrip("/")
+@dataclass(frozen=True)
+class UriClassification:
+ """Viking URI classification derived from path structure."""
+
+ parts: tuple[str, ...]
+ scope: str
+ content_index: Optional[int]
+ context_type: str
+
+ @property
+ def is_memory(self) -> bool:
+ return self.context_type == "memory"
+
+ @property
+ def is_skill(self) -> bool:
+ return self.context_type == "skill"
+
+ @property
+ def is_user_namespace_root(self) -> bool:
+ return _is_namespace_root_parts(self.parts, "user")
+
+ @property
+ def is_agent_namespace_root(self) -> bool:
+ return _is_namespace_root_parts(self.parts, "agent")
+
+ @property
+ def is_memory_root(self) -> bool:
+ return (
+ self.is_memory
+ and self.content_index is not None
+ and len(self.parts) == self.content_index + 1
+ )
+
+ @property
+ def is_skill_namespace(self) -> bool:
+ return (
+ self.is_skill
+ and self.content_index is not None
+ and len(self.parts) == self.content_index + 1
+ )
+
+ @property
+ def is_skill_root(self) -> bool:
+ return (
+ self.is_skill
+ and self.content_index is not None
+ and len(self.parts) == self.content_index + 2
+ )
+
+
+def uri_parts(uri: str) -> list[str]:
+ """Return normalized Viking URI path segments without query parameters."""
+ normalized = VikingURI.normalize(uri.split("?", 1)[0]).rstrip("/")
if normalized == "viking:":
normalized = "viking://"
if normalized == "viking://":
@@ -43,6 +99,42 @@ def _uri_parts(uri: str) -> list[str]:
return [part for part in normalized[len("viking://") :].split("/") if part]
+def _content_segment_index(parts: tuple[str, ...]) -> Optional[int]:
+ """Return the first content segment after a user/agent namespace root."""
+ if len(parts) < 3 or parts[0] not in _CONTENT_TYPES_BY_SCOPE:
+ return None
+ cross_scope_segment = _CROSS_SCOPE_OWNER_SEGMENT[parts[0]]
+ if len(parts) >= 5 and parts[2] == cross_scope_segment:
+ return 4
+ return 2
+
+
+def _is_namespace_root_parts(parts: tuple[str, ...], scope: str) -> bool:
+ return parts[:1] == (scope,) and (
+ len(parts) == 2 or (len(parts) == 4 and parts[2] == _CROSS_SCOPE_OWNER_SEGMENT[scope])
+ )
+
+
+def classify_uri(uri: str) -> UriClassification:
+ parts = tuple(uri_parts(uri))
+ content_index = _content_segment_index(parts)
+ context_type = "resource"
+ if content_index is not None:
+ context_type = _CONTENT_TYPES_BY_SCOPE.get(parts[0], {}).get(
+ parts[content_index], "resource"
+ )
+ return UriClassification(
+ parts=parts,
+ scope=parts[0] if parts else "",
+ content_index=content_index,
+ context_type=context_type,
+ )
+
+
+def context_type_for_uri(uri: str) -> str:
+ return classify_uri(uri).context_type
+
+
def canonical_user_root(ctx: RequestContext) -> str:
return f"viking://user/{user_space_fragment(ctx)}"
@@ -94,7 +186,7 @@ def resolve_uri(
) -> ResolvedNamespace:
"""Resolve a URI into a canonical URI and owner tuple."""
- parts = _uri_parts(uri)
+ parts = uri_parts(uri)
if not parts:
return ResolvedNamespace(uri="viking://", scope="", is_container=True)
@@ -192,6 +284,16 @@ def owner_fields_for_uri(
}
+def owner_space_for_uri(uri: str, ctx: RequestContext) -> str:
+ """Derive the legacy owner_space bucket for vector records from URI scope and context."""
+ parts = uri_parts(uri)
+ if parts[:1] == ["agent"]:
+ return agent_space_fragment(ctx)
+ if parts[:1] in (["user"], ["session"]):
+ return user_space_fragment(ctx)
+ return ""
+
+
def _resolve_user_uri(
parts: list[str],
ctx: Optional[RequestContext],
diff --git a/openviking/server/app.py b/openviking/server/app.py
index 22ff282b0..0ff18f192 100644
--- a/openviking/server/app.py
+++ b/openviking/server/app.py
@@ -33,7 +33,6 @@ from openviking.server.routers import (
content_router,
debug_router,
filesystem_router,
- maintenance_router,
metrics_router,
observer_router,
pack_router,
@@ -448,7 +447,6 @@ def create_app(
app.include_router(metrics_router)
app.include_router(tasks_router)
app.include_router(webdav_router)
- app.include_router(maintenance_router)
app.include_router(bot_router, prefix="/bot/v1")
# Favicon: shared with the console static assets so 1933/console use the same logo.
diff --git a/openviking/server/auth.py b/openviking/server/auth.py
index e6517de82..32c525fbd 100644
--- a/openviking/server/auth.py
+++ b/openviking/server/auth.py
@@ -25,6 +25,9 @@ _ROOT_IMPLICIT_TENANT_ALLOWED_PREFIXES = (
"/api/v1/admin",
"/api/v1/observer",
)
+_ROOT_EXPLICIT_ACCOUNT_ONLY_PATHS = {
+ "/api/v1/content/reindex",
+}
_TRUSTED_RELAXED_IDENTITY_PREFIXES = ("/api/v1/admin",)
@@ -39,16 +42,21 @@ def _root_request_requires_explicit_tenant(path: str) -> bool:
"""Return True when a ROOT request targets tenant-scoped data APIs.
Root still needs access to admin and monitoring endpoints without a tenant
- context. For data APIs, implicit fallback to default/default is misleading,
- so callers must provide explicit account and user headers.
+ context. For data APIs, implicit fallback to default/default is misleading.
"""
if path in _ROOT_IMPLICIT_TENANT_ALLOWED_PATHS:
return False
+ if path in _ROOT_EXPLICIT_ACCOUNT_ONLY_PATHS:
+ return False
if path.startswith(_ROOT_IMPLICIT_TENANT_ALLOWED_PREFIXES):
return False
return True
+def _root_request_requires_explicit_account_only(path: str) -> bool:
+ return path in _ROOT_EXPLICIT_ACCOUNT_ONLY_PATHS
+
+
def _trusted_request_requires_explicit_identity(path: str) -> bool:
if path.startswith(_TRUSTED_RELAXED_IDENTITY_PREFIXES):
return False
@@ -237,19 +245,20 @@ async def get_request_context(
path = request.url.path
auth_mode = _auth_mode(request)
api_key_manager = getattr(request.app.state, "api_key_manager", None)
- if (
- auth_mode == AuthMode.API_KEY
- and api_key_manager is not None
- and identity.role == Role.ROOT
- and _root_request_requires_explicit_tenant(path)
- ):
+ if auth_mode == AuthMode.API_KEY and api_key_manager is not None and identity.role == Role.ROOT:
account_header = request.headers.get("X-OpenViking-Account")
- user_header = request.headers.get("X-OpenViking-User")
- if not account_header or not user_header:
- raise InvalidArgumentError(
- "ROOT requests to tenant-scoped APIs must include X-OpenViking-Account "
- "and X-OpenViking-User headers. Use a user key for regular data access."
- )
+ if _root_request_requires_explicit_account_only(path):
+ if not account_header:
+ raise InvalidArgumentError(
+ "ROOT requests to reindex must include X-OpenViking-Account header."
+ )
+ elif _root_request_requires_explicit_tenant(path):
+ user_header = request.headers.get("X-OpenViking-User")
+ if not account_header or not user_header:
+ raise InvalidArgumentError(
+ "ROOT requests to tenant-scoped APIs must include X-OpenViking-Account "
+ "and X-OpenViking-User headers. Use a user key for regular data access."
+ )
if auth_mode == AuthMode.TRUSTED:
is_admin_path = path.startswith(_TRUSTED_RELAXED_IDENTITY_PREFIXES)
diff --git a/openviking/server/models.py b/openviking/server/models.py
index ce6f3a9b3..afe315fcb 100644
--- a/openviking/server/models.py
+++ b/openviking/server/models.py
@@ -46,5 +46,7 @@ ERROR_CODE_TO_HTTP_STATUS = {
"EMBEDDING_FAILED": 500,
"VLM_FAILED": 500,
"SESSION_EXPIRED": 410,
+ "UNSUPPORTED_URI": 400,
+ "UNSUPPORTED_MODE": 400,
"UNKNOWN": 500,
}
diff --git a/openviking/server/routers/__init__.py b/openviking/server/routers/__init__.py
index 54b2d22b0..ec966483d 100644
--- a/openviking/server/routers/__init__.py
+++ b/openviking/server/routers/__init__.py
@@ -7,7 +7,6 @@ from openviking.server.routers.bot import router as bot_router
from openviking.server.routers.content import router as content_router
from openviking.server.routers.debug import router as debug_router
from openviking.server.routers.filesystem import router as filesystem_router
-from openviking.server.routers.maintenance import router as maintenance_router
from openviking.server.routers.metrics import router as metrics_router
from openviking.server.routers.observer import router as observer_router
from openviking.server.routers.pack import router as pack_router
@@ -39,5 +38,4 @@ __all__ = [
"observer_router",
"tasks_router",
"webdav_router",
- "maintenance_router",
]
diff --git a/openviking/server/routers/content.py b/openviking/server/routers/content.py
index b3ac2f9f9..544c43e23 100644
--- a/openviking/server/routers/content.py
+++ b/openviking/server/routers/content.py
@@ -2,7 +2,6 @@
# SPDX-License-Identifier: AGPL-3.0
"""Content endpoints for OpenViking HTTP Server."""
-import asyncio
from urllib.parse import quote
from fastapi import APIRouter, Body, Depends, Query
@@ -12,17 +11,13 @@ from pydantic import BaseModel, ConfigDict
from openviking.core.path_variables import resolve_path_variables
from openviking.core.uri_validation import validate_viking_uri
from openviking.pyagfs.exceptions import AGFSClientError, AGFSNotFoundError
-from openviking.server.auth import get_request_context, require_role
+from openviking.server.auth import (
+ get_request_context,
+ require_role,
+)
from openviking.server.dependencies import get_service
from openviking.server.identity import RequestContext, Role
from openviking.server.models import Response
-from openviking.server.responses import error_response, response_from_result
-from openviking.server.routers.maintenance import (
- REINDEX_TASK_TYPE,
- ReindexRequest,
- _background_reindex_tracked,
- _do_reindex,
-)
from openviking.server.telemetry import run_operation
from openviking.telemetry import TelemetryRequest
from openviking_cli.exceptions import NotFoundError
@@ -44,9 +39,24 @@ class WriteContentRequest(BaseModel):
telemetry: TelemetryRequest = False
+class ReindexRequest(BaseModel):
+ model_config = ConfigDict(extra="forbid")
+
+ uri: str
+ mode: str = "vectors_only"
+ wait: bool = True
+
+
router = APIRouter(prefix="/api/v1/content", tags=["content"])
+def _validate_reindex_uri(uri: str) -> str:
+ raw_uri = uri.strip() if isinstance(uri, str) else ""
+ if raw_uri.startswith("viking://"):
+ return raw_uri
+ return validate_viking_uri(raw_uri)
+
+
@router.get("/read")
async def read(
uri: str = Query(..., description="Viking URI"),
@@ -188,53 +198,19 @@ async def write(
).model_dump(exclude_none=True)
[email protected]("/reindex", deprecated=True)
[email protected]("/reindex")
async def reindex(
body: ReindexRequest = Body(...),
ctx: RequestContext = require_role(Role.ROOT, Role.ADMIN),
):
- """Compatibility alias for older clients that still call /api/v1/content/reindex."""
- from openviking.service.task_tracker import get_task_tracker
- from openviking.storage.viking_fs import get_viking_fs
-
+ """Reindex semantic/vector artifacts for a URI-scoped maintenance target."""
uri = resolve_path_variables(body.uri)
- uri = validate_viking_uri(uri)
- viking_fs = get_viking_fs()
-
- if not await viking_fs.exists(uri, ctx=ctx):
- return error_response("NOT_FOUND", f"URI not found: {uri}")
-
+ uri = _validate_reindex_uri(uri)
service = get_service()
- tracker = get_task_tracker()
-
- if body.wait:
- if tracker.has_running(
- REINDEX_TASK_TYPE,
- uri,
- owner_account_id=ctx.account_id,
- owner_user_id=ctx.user.user_id,
- ):
- return error_response("CONFLICT", f"URI {uri} already has a reindex in progress")
- result = await _do_reindex(service, uri, body.regenerate, ctx)
- return response_from_result(result)
-
- task = tracker.create_if_no_running(
- REINDEX_TASK_TYPE,
- uri,
- owner_account_id=ctx.account_id,
- owner_user_id=ctx.user.user_id,
- )
- if task is None:
- return error_response("CONFLICT", f"URI {uri} already has a reindex in progress")
- asyncio.create_task(
- _background_reindex_tracked(service, uri, body.regenerate, ctx, task.task_id)
- )
- return Response(
- status="ok",
- result={
- "uri": uri,
- "status": "accepted",
- "task_id": task.task_id,
- "message": "Reindex is processing in the background",
- },
+ result = await service.reindex(
+ uri=uri,
+ mode=body.mode,
+ wait=body.wait,
+ ctx=ctx,
)
+ return Response(status="ok", result=result)
diff --git a/openviking/server/routers/maintenance.py b/openviking/server/routers/maintenance.py
deleted file mode 100644
index 17592ca59..000000000
--- a/openviking/server/routers/maintenance.py
+++ /dev/null
@@ -1,135 +0,0 @@
-# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
-# SPDX-License-Identifier: AGPL-3.0
-"""Maintenance endpoints for OpenViking HTTP Server."""
-
-import asyncio
-
-from fastapi import APIRouter, Body
-from pydantic import BaseModel
-
-from openviking.core.path_variables import resolve_path_variables
-from openviking.core.uri_validation import validate_viking_uri
-from openviking.server.auth import require_role
-from openviking.server.dependencies import get_service
-from openviking.server.identity import RequestContext, Role
-from openviking.server.models import Response
-from openviking.server.responses import error_response, response_from_result
-from openviking_cli.utils import get_logger
-
-logger = get_logger(__name__)
-
-REINDEX_TASK_TYPE = "resource_reindex"
-
-
-class ReindexRequest(BaseModel):
- """Request to reindex content at a URI."""
-
- uri: str
- regenerate: bool = False
- wait: bool = True
-
-
-router = APIRouter(prefix="/api/v1/maintenance", tags=["maintenance"])
-
-
[email protected]("/reindex")
-async def reindex(
- body: ReindexRequest = Body(...),
- ctx: RequestContext = require_role(Role.ROOT, Role.ADMIN),
-):
- """Reindex content at a URI.
-
- Re-embeds existing .abstract.md/.overview.md content into the vector
- database. If regenerate=True, also regenerates L0/L1 summaries via LLM
- before re-embedding.
-
- Uses path locking to prevent concurrent reindexes on the same URI.
- Set wait=False to run in the background and track progress via task API.
- """
- from openviking.service.task_tracker import get_task_tracker
- from openviking.storage.viking_fs import get_viking_fs
-
- uri = resolve_path_variables(body.uri)
- uri = validate_viking_uri(uri)
- viking_fs = get_viking_fs()
-
- # Validate URI exists
- if not await viking_fs.exists(uri, ctx=ctx):
- return error_response("NOT_FOUND", f"URI not found: {uri}")
-
- service = get_service()
- tracker = get_task_tracker()
-
- if body.wait:
- # Synchronous path: block until reindex completes
- if tracker.has_running(
- REINDEX_TASK_TYPE,
- uri,
- owner_account_id=ctx.account_id,
- owner_user_id=ctx.user.user_id,
- ):
- return error_response("CONFLICT", f"URI {uri} already has a reindex in progress")
- result = await _do_reindex(service, uri, body.regenerate, ctx)
- return response_from_result(result)
- else:
- # Async path: run in background, return task_id for polling
- task = tracker.create_if_no_running(
- REINDEX_TASK_TYPE,
- uri,
- owner_account_id=ctx.account_id,
- owner_user_id=ctx.user.user_id,
- )
- if task is None:
- return error_response("CONFLICT", f"URI {uri} already has a reindex in progress")
- asyncio.create_task(
- _background_reindex_tracked(service, uri, body.regenerate, ctx, task.task_id)
- )
- return Response(
- status="ok",
- result={
- "uri": uri,
- "status": "accepted",
- "task_id": task.task_id,
- "message": "Reindex is processing in the background",
- },
- )
-
-
-async def _do_reindex(
- service,
- uri: str,
- regenerate: bool,
- ctx: RequestContext,
-) -> dict:
- """Execute reindex within a lock scope."""
- from openviking.storage.transaction import LockContext, get_lock_manager
-
- viking_fs = service.viking_fs
- path = viking_fs._uri_to_path(uri, ctx=ctx)
-
- async with LockContext(get_lock_manager(), [path], lock_mode="point"):
- if regenerate:
- return await service.resources.summarize([uri], ctx=ctx)
- else:
- return await service.resources.build_index([uri], ctx=ctx)
-
-
-async def _background_reindex_tracked(
- service,
- uri: str,
- regenerate: bool,
- ctx: RequestContext,
- task_id: str,
-) -> None:
- """Run reindex in background with task tracking."""
- from openviking.service.task_tracker import get_task_tracker
-
- tracker = get_task_tracker()
- tracker.start(task_id)
- try:
- result = await _do_reindex(service, uri, regenerate, ctx)
- tracker.complete(task_id, {"uri": uri, **result})
- logger.info("Background reindex completed: uri=%s task=%s", uri, task_id)
- except Exception as exc:
- tracker.fail(task_id, str(exc))
- logger.exception("Background reindex failed: uri=%s task=%s", uri, task_id)
diff --git a/openviking/service/core.py b/openviking/service/core.py
index 11fbeb71c..23996dbcb 100644
--- a/openviking/service/core.py
+++ b/openviking/service/core.py
@@ -389,6 +389,28 @@ class OpenVikingService:
logger.info("OpenVikingService closed")
+ async def reindex(
+ self,
+ *,
+ uri: str,
+ mode: str = "vectors_only",
+ wait: bool = True,
+ ctx: RequestContext | None = None,
+ ) -> dict[str, Any]:
+ """Reindex semantic/vector artifacts for a URI."""
+ if not self._initialized:
+ await self.initialize()
+
+ effective_ctx = ctx or RequestContext(user=self.user, role=Role.ROOT)
+ from openviking.service.reindex_executor import get_reindex_executor
+
+ return await get_reindex_executor().execute(
+ uri=uri,
+ mode=mode,
+ wait=wait,
+ ctx=effective_ctx,
+ )
+
def _ensure_initialized(self) -> None:
"""Ensure service is initialized."""
if not self._initialized:
diff --git a/openviking/service/fs_service.py b/openviking/service/fs_service.py
index eb01841c9..5cc8fe6de 100644
--- a/openviking/service/fs_service.py
+++ b/openviking/service/fs_service.py
@@ -8,9 +8,13 @@ Provides file system operations: ls, mkdir, rm, mv, tree, stat, read, abstract,
from typing import Any, Dict, List, Optional
-from openviking.core.directories import get_context_type_for_uri
-from openviking.privacy import UserPrivacyConfigService, get_skill_name_from_uri, restore_skill_content
+from openviking.core.namespace import context_type_for_uri
from openviking.core.uri_validation import validate_optional_viking_uri, validate_viking_uri
+from openviking.privacy import (
+ UserPrivacyConfigService,
+ get_skill_name_from_uri,
+ restore_skill_content,
+)
from openviking.server.identity import RequestContext
from openviking.storage.content_write import ContentWriteCoordinator
from openviking.storage.viking_fs import VikingFS
@@ -135,7 +139,7 @@ class FSService:
uri=directory_uri,
abstract=abstract,
overview="",
- context_type=get_context_type_for_uri(directory_uri),
+ context_type=context_type_for_uri(directory_uri),
ctx=ctx,
include_overview=False,
)
diff --git a/openviking/service/reindex_executor.py b/openviking/service/reindex_executor.py
new file mode 100644
index 000000000..c4b84dad7
--- /dev/null
+++ b/openviking/service/reindex_executor.py
@@ -0,0 +1,1349 @@
+# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
+# SPDX-License-Identifier: AGPL-3.0
+"""Admin reindex executor."""
+
+from __future__ import annotations
+
+import asyncio
+import time
+from dataclasses import dataclass, field
+from typing import Any, Iterable, Optional
+
+from openviking.core.context import (
+ Context,
+ ContextLevel,
+ ContextType,
+ ResourceContentType,
+ Vectorize,
+)
+from openviking.core.namespace import (
+ classify_uri,
+ context_type_for_uri,
+ owner_space_for_uri,
+)
+from openviking.server.dependencies import get_service
+from openviking.server.identity import RequestContext
+from openviking.service.task_tracker import get_task_tracker
+from openviking.session.memory.utils.messages import parse_memory_file_with_fields
+from openviking.storage.collection_schemas import TextEmbeddingHandler
+from openviking.storage.queuefs.embedding_msg_converter import EmbeddingMsgConverter
+from openviking.storage.queuefs.semantic_msg import SemanticMsg
+from openviking.storage.queuefs.semantic_processor import SemanticProcessor
+from openviking.storage.transaction import LockContext, get_lock_manager
+from openviking.storage.viking_fs import get_viking_fs
+from openviking.utils.embedding_utils import get_resource_content_type
+from openviking.utils.skill_processor import SkillProcessor
+from openviking_cli.exceptions import NotFoundError, OpenVikingError
+from openviking_cli.utils import VikingURI, get_logger
+from openviking_cli.utils.config import get_openviking_config
+
+logger = get_logger(__name__)
+
+REINDEX_TASK_TYPE = "admin_reindex"
+
+_reindex_executor: "ReindexExecutor | None" = None
+
+
+def get_reindex_executor() -> "ReindexExecutor":
+ global _reindex_executor
+ if _reindex_executor is None:
+ _reindex_executor = ReindexExecutor()
+ return _reindex_executor
+
+
+@dataclass
+class _ReindexCounters:
+ scanned_records: int = 0
+ rebuilt_records: int = 0
+ unsupported_records: int = 0
+ failed_records: int = 0
+ warnings: list[str] = field(default_factory=list)
+
+
+class ReindexExecutor:
+ """Non-destructive reindex orchestration for admin maintenance flows."""
+
+ SUPPORTED_MODES_BY_TYPE = {
+ "global_namespace": {"vectors_only", "semantic_and_vectors"},
+ "agent_namespace": {"vectors_only", "semantic_and_vectors"},
+ "user_namespace": {"vectors_only", "semantic_and_vectors"},
+ "skill_namespace": {"vectors_only", "semantic_and_vectors"},
+ "resource": {"vectors_only", "semantic_and_vectors"},
+ "skill": {"vectors_only", "semantic_and_vectors"},
+ "memory": {"vectors_only", "semantic_and_vectors"},
+ }
+
+ async def execute(
+ self,
+ *,
+ uri: str,
+ mode: str,
+ wait: bool,
+ ctx: RequestContext,
+ ) -> dict[str, Any]:
+ object_type = self._infer_target_type(uri)
+ self._validate_mode(object_type, mode)
+
+ tracker = get_task_tracker()
+ if wait:
+ if tracker.has_running(
+ REINDEX_TASK_TYPE,
+ uri,
+ owner_account_id=ctx.account_id,
+ owner_user_id=ctx.user.user_id,
+ ):
+ raise OpenVikingError(
+ f"URI {uri} already has a reindex in progress",
+ code="CONFLICT",
+ details={"uri": uri},
+ )
+ return await self._run(
+ uri=uri,
+ object_type=object_type,
+ mode=mode,
+ ctx=ctx,
+ )
+
+ task = tracker.create_if_no_running(
+ REINDEX_TASK_TYPE,
+ uri,
+ owner_account_id=ctx.account_id,
+ owner_user_id=ctx.user.user_id,
+ )
+ if task is None:
+ raise OpenVikingError(
+ f"URI {uri} already has a reindex in progress",
+ code="CONFLICT",
+ details={"uri": uri},
+ )
+
+ asyncio.create_task(
+ self._run_tracked(
+ task.task_id,
+ uri=uri,
+ object_type=object_type,
+ mode=mode,
+ ctx=ctx,
+ )
+ )
+ return {
+ "task_id": task.task_id,
+ "status": "accepted",
+ "uri": uri,
+ "object_type": object_type,
+ "mode": mode,
+ }
+
+ def _infer_target_type(self, uri: str) -> str:
+ if not uri.startswith("viking://"):
+ raise OpenVikingError(
+ f"Unsupported reindex URI: {uri}",
+ code="UNSUPPORTED_URI",
+ details={"uri": uri},
+ )
+ classification = classify_uri(uri)
+ parts = classification.parts
+ if not parts:
+ return "global_namespace"
+ if parts == ("user",):
+ return "user_namespace"
+ if parts == ("agent",):
+ return "agent_namespace"
+ if classification.is_user_namespace_root:
+ return "user_namespace"
+ if classification.is_agent_namespace_root:
+ return "agent_namespace"
+ if classification.is_memory:
+ return "memory"
+ if classification.is_skill_namespace:
+ return "skill_namespace"
+ if classification.is_skill_root:
+ return "skill"
+ if classification.is_skill:
+ raise OpenVikingError(
+ f"Unsupported reindex URI: {uri}",
+ code="UNSUPPORTED_URI",
+ details={"uri": uri},
+ )
+ if parts[0] in {"resources", "user", "agent"}:
+ return "resource"
+ raise OpenVikingError(
+ f"Unsupported reindex URI: {uri}",
+ code="UNSUPPORTED_URI",
+ details={"uri": uri},
+ )
+
+ async def _tree_all(
+ self,
+ viking_fs: Any,
+ uri: str,
+ *,
+ show_all_hidden: bool,
+ ctx: RequestContext,
+ ) -> list[dict[str, Any]]:
+ return await viking_fs.tree(
+ uri,
+ output="original",
+ show_all_hidden=show_all_hidden,
+ node_limit=None,
+ level_limit=None,
+ ctx=ctx,
+ )
+
+ async def _refresh_namespace_resource_semantics(
+ self,
+ *,
+ target_root: str,
+ directories: list[str],
+ files: list[str],
+ counters: _ReindexCounters,
+ ctx: RequestContext,
+ ) -> tuple[list[str], list[str]]:
+ prefix = self._child_prefix(target_root)
+ semantic_roots = sorted(
+ {
+ directory_uri
+ for directory_uri in directories
+ if directory_uri.startswith(prefix)
+ and "/" not in directory_uri[len(prefix) :]
+ and directory_uri[len(prefix) :]
+ }
+ )
+ filtered_directories = [
+ directory_uri
+ for directory_uri in directories
+ if any(
+ directory_uri == root or directory_uri.startswith(root + "/")
+ for root in semantic_roots
+ )
+ ]
+ filtered_files = [
+ file_uri
+ for file_uri in files
+ if any(file_uri.startswith(root + "/") for root in semantic_roots)
+ ]
+ filtered_file_set = set(filtered_files)
+ for file_uri in files:
+ if file_uri in filtered_file_set:
+ continue
+ counters.unsupported_records += 1
+ counters.warnings.append(
+ f"Skipped {file_uri}: namespace semantic_and_vectors only refreshes resource directories"
+ )
+ for semantic_root in semantic_roots:
+ await self._run_semantic_processor(
+ uri=semantic_root,
+ context_type="resource",
+ ctx=ctx,
+ )
+ return filtered_directories, filtered_files
+
+ @staticmethod
+ def _child_prefix(root: str) -> str:
+ if root.rstrip("/") == "viking:":
+ return "viking://"
+ return root.rstrip("/") + "/"
+
+ def _is_resource_entry_for_namespace(self, uri: str, target_root: str) -> bool:
+ if not uri.startswith(self._child_prefix(target_root)):
+ return False
+ classification = classify_uri(uri)
+ if classification.is_memory or classification.is_skill:
+ return False
+ return True
+
+ def _is_global_resource_entry(self, uri: str) -> bool:
+ return uri == "viking://resources" or uri.startswith("viking://resources/")
+
+ async def _reindex_skill_namespace(
+ self,
+ *,
+ uri: str,
+ mode: str,
+ counters: _ReindexCounters,
+ ctx: RequestContext,
+ ) -> None:
+ viking_fs = get_viking_fs()
+ try:
+ entries = await self._tree_all(viking_fs, uri, show_all_hidden=True, ctx=ctx)
+ except Exception as exc:
+ raise NotFoundError(uri, "resource") from exc
+
+ skill_roots = []
+ for entry in entries:
+ entry_uri = entry.get("uri")
+ if entry_uri and entry.get("isDir") and classify_uri(entry_uri).is_skill_root:
+ skill_roots.append(entry_uri)
+
+ for skill_root in sorted(set(skill_roots)):
+ await self._reindex_skill(uri=skill_root, mode=mode, counters=counters, ctx=ctx)
+
+ if not skill_roots:
+ counters.unsupported_records += 1
+ counters.warnings.append(f"No skill roots found under {uri}")
+
+ def _validate_mode(self, object_type: str, mode: str) -> None:
+ supported_modes = self.SUPPORTED_MODES_BY_TYPE[object_type]
+ if mode not in supported_modes:
+ raise OpenVikingError(
+ f"Mode {mode} is not supported for {object_type}",
+ code="UNSUPPORTED_MODE",
+ details={
+ "mode": mode,
+ "object_type": object_type,
+ "supported_modes": sorted(supported_modes),
+ },
+ )
+
+ async def _run(
+ self,
+ *,
+ uri: str,
+ object_type: str,
+ mode: str,
+ ctx: RequestContext,
+ ) -> dict[str, Any]:
+ service = get_service()
+ if service.viking_fs is None or service.vikingdb_manager is None:
+ raise RuntimeError("OpenVikingService not initialized")
+
+ path = service.viking_fs._uri_to_path(uri, ctx=ctx)
+ started_at = time.perf_counter()
+ counters = _ReindexCounters()
+
+ async with LockContext(get_lock_manager(), [path], lock_mode="subtree"):
+ if object_type == "global_namespace":
+ await self._reindex_global_namespace(
+ uri=uri,
+ mode=mode,
+ counters=counters,
+ ctx=ctx,
+ )
+ elif object_type == "agent_namespace":
+ await self._reindex_agent_namespace(
+ uri=uri,
+ mode=mode,
+ counters=counters,
+ ctx=ctx,
+ )
+ elif object_type == "user_namespace":
+ await self._reindex_user_namespace(
+ uri=uri,
+ mode=mode,
+ counters=counters,
+ ctx=ctx,
+ )
+ elif object_type == "skill_namespace":
+ await self._reindex_skill_namespace(
+ uri=uri,
+ mode=mode,
+ counters=counters,
+ ctx=ctx,
+ )
+ elif object_type == "resource":
+ await self._reindex_resource(uri=uri, mode=mode, counters=counters, ctx=ctx)
+ elif object_type == "skill":
+ await self._reindex_skill(uri=uri, mode=mode, counters=counters, ctx=ctx)
+ elif object_type == "memory":
+ await self._reindex_memory(uri=uri, mode=mode, counters=counters, ctx=ctx)
+ else:
+ raise OpenVikingError(
+ f"Unsupported reindex type: {object_type}",
+ code="UNSUPPORTED_URI",
+ details={"uri": uri},
+ )
+
+ return {
+ "status": "completed",
+ "uri": uri,
+ "object_type": object_type,
+ "mode": mode,
+ "scanned_records": counters.scanned_records,
+ "rebuilt_records": counters.rebuilt_records,
+ "unsupported_records": counters.unsupported_records,
+ "failed_records": counters.failed_records,
+ "duration_ms": int((time.perf_counter() - started_at) * 1000),
+ "warnings": counters.warnings,
+ }
+
+ async def _run_tracked(
+ self,
+ task_id: str,
+ *,
+ uri: str,
+ object_type: str,
+ mode: str,
+ ctx: RequestContext,
+ ) -> None:
+ tracker = get_task_tracker()
+ tracker.start(task_id)
+ try:
+ result = await self._run(
+ uri=uri,
+ object_type=object_type,
+ mode=mode,
+ ctx=ctx,
+ )
+ tracker.complete(task_id, result)
+ except Exception as exc:
+ tracker.fail(task_id, str(exc))
+
+ async def _reindex_resource(
+ self,
+ *,
+ uri: str,
+ mode: str,
+ counters: _ReindexCounters,
+ ctx: RequestContext,
+ ) -> None:
+ if mode == "semantic_and_vectors":
+ await self._run_semantic_processor(uri=uri, context_type="resource", ctx=ctx)
+ await self._reindex_resource_vectors(uri=uri, counters=counters, ctx=ctx)
+ return
+ await self._reindex_resource_vectors(uri=uri, counters=counters, ctx=ctx)
+
+ async def _reindex_skill(
+ self,
+ *,
+ uri: str,
+ mode: str,
+ counters: _ReindexCounters,
+ ctx: RequestContext,
+ ) -> None:
+ if mode == "semantic_and_vectors":
+ await self._regenerate_skill_semantics(uri=uri, ctx=ctx)
+ await self._reindex_skill_vectors(uri=uri, counters=counters, ctx=ctx)
+
+ async def _reindex_memory(
+ self,
+ *,
+ uri: str,
+ mode: str,
+ counters: _ReindexCounters,
+ ctx: RequestContext,
+ ) -> None:
+ if mode == "semantic_and_vectors":
+ await self._run_semantic_processor(uri=uri, context_type="memory", ctx=ctx)
+ await self._reindex_memory_vectors(uri=uri, counters=counters, ctx=ctx)
+ return
+ await self._reindex_memory_vectors(uri=uri, counters=counters, ctx=ctx)
+
+ async def _run_semantic_processor(
+ self, *, uri: str, context_type: str, ctx: RequestContext
+ ) -> None:
+ processor = SemanticProcessor()
+ msg = SemanticMsg(
+ uri=uri,
+ context_type=context_type,
+ recursive=True,
+ account_id=ctx.account_id,
+ user_id=ctx.user.user_id,
+ agent_id=ctx.user.agent_id,
+ role=ctx.role.value,
+ skip_vectorization=True,
+ )
+ await processor.on_dequeue({"data": msg.to_json()})
+
+ async def _reindex_resource_vectors(
+ self,
+ *,
+ uri: str,
+ counters: _ReindexCounters,
+ ctx: RequestContext,
+ ) -> None:
+ viking_fs = get_viking_fs()
+ try:
+ if not await viking_fs.exists(uri, ctx=ctx):
+ raise NotFoundError(uri, "resource")
+ stat = await viking_fs.stat(uri, ctx=ctx)
+ is_dir = stat.get("isDir", stat.get("is_dir")) if isinstance(stat, dict) else False
+ if is_dir:
+ entries = await self._tree_all(viking_fs, uri, show_all_hidden=True, ctx=ctx)
+ else:
+ entries = []
+ except Exception as exc:
+ raise NotFoundError(uri, "resource") from exc
+
+ if is_dir:
+ directories = [uri]
+ files: list[str] = []
+ for entry in entries:
+ entry_uri = entry.get("uri")
+ if not entry_uri:
+ continue
+ if entry.get("isDir"):
+ directories.append(entry_uri)
+ elif not self._is_hidden_meta_file(entry_uri):
+ files.append(entry_uri)
+ else:
+ directories = []
+ files = [uri]
+
+ await self._reindex_resource_vectors_from_entries(
+ root_uri=uri,
+ directories=directories,
+ files=files,
+ counters=counters,
+ ctx=ctx,
+ )
+
+ async def _reindex_resource_vectors_from_entries(
+ self,
+ *,
+ root_uri: str,
+ directories: Iterable[str],
+ files: Iterable[str],
+ counters: _ReindexCounters,
+ ctx: RequestContext,
+ ) -> None:
+ deduped_directories = []
+ seen_directories = set()
+ for directory_uri in directories:
+ if directory_uri and directory_uri not in seen_directories:
+ deduped_directories.append(directory_uri)
+ seen_directories.add(directory_uri)
+
+ deduped_files = []
+ seen_files = set()
+ for file_uri in files:
+ if file_uri and file_uri not in seen_files:
+ deduped_files.append(file_uri)
+ seen_files.add(file_uri)
+
+ for directory_uri in deduped_directories:
+ if directory_uri == "viking://":
+ continue
+ counters.scanned_records += 1
+ abstract = await self._read_directory_abstract(directory_uri, ctx=ctx)
+ overview = await self._read_directory_overview(directory_uri, ctx=ctx)
+ if not overview:
+ overview = abstract
+ if not abstract and not overview:
+ counters.unsupported_records += 1
+ counters.warnings.append(f"No semantic source found for {directory_uri}")
+ continue
+ if abstract:
+ try:
+ await self._upsert_context(
+ uri=directory_uri,
+ parent_uri=VikingURI(directory_uri).parent.uri,
+ abstract=abstract,
+ vector_text=abstract,
+ is_leaf=False,
+ context_type=context_type_for_uri(directory_uri),
+ level=ContextLevel.ABSTRACT,
+ ctx=ctx,
+ )
+ counters.rebuilt_records += 1
+ except Exception as exc:
+ counters.failed_records += 1
+ counters.warnings.append(f"Failed to reindex {directory_uri} L0 vector: {exc}")
+ if overview:
+ try:
+ await self._upsert_context(
+ uri=directory_uri,
+ parent_uri=VikingURI(directory_uri).parent.uri,
+ abstract=abstract,
+ vector_text=overview,
+ is_leaf=False,
+ context_type=context_type_for_uri(directory_uri),
+ level=ContextLevel.OVERVIEW,
+ ctx=ctx,
+ )
+ counters.rebuilt_records += 1
+ except Exception as exc:
+ counters.failed_records += 1
+ counters.warnings.append(f"Failed to reindex {directory_uri} L1 vector: {exc}")
+
+ for file_uri in deduped_files:
+ counters.scanned_records += 1
+ parent_uri = VikingURI(file_uri).parent.uri
+ summary = await self._best_file_summary(file_uri, ctx=ctx)
+ vector_text = await self._best_resource_file_vector_text(file_uri, summary, ctx=ctx)
+ if not vector_text:
+ counters.unsupported_records += 1
+ counters.warnings.append(f"No vector source found for {file_uri}")
+ continue
+ abstract = self._prefer_non_empty(summary, vector_text)
+ try:
+ await self._upsert_context(
+ uri=file_uri,
+ parent_uri=parent_uri,
+ abstract=abstract,
+ vector_text=vector_text,
+ is_leaf=True,
+ context_type=context_type_for_uri(file_uri),
+ level=ContextLevel.DETAIL,
+ ctx=ctx,
+ )
+ counters.rebuilt_records += 1
+ except Exception as exc:
+ counters.failed_records += 1
+ counters.warnings.append(f"Failed to reindex {file_uri} vector: {exc}")
+
+ async def _reindex_user_namespace(
+ self,
+ *,
+ uri: str,
+ mode: str,
+ counters: _ReindexCounters,
+ ctx: RequestContext,
+ ) -> None:
+ normalized_uri = uri.rstrip("/")
+ target_root = normalized_uri if normalized_uri else uri
+ viking_fs = get_viking_fs()
+ try:
+ entries = await self._tree_all(viking_fs, target_root, show_all_hidden=True, ctx=ctx)
+ except Exception as exc:
+ raise NotFoundError(uri, "resource") from exc
+
+ if target_root == "viking://user":
+ user_roots = [
+ entry.get("uri")
+ for entry in entries
+ if entry.get("isDir") and classify_uri(entry.get("uri", "")).is_user_namespace_root
+ ]
+ if user_roots:
+ for user_root in sorted(set(user_roots)):
+ await self._reindex_user_namespace(
+ uri=user_root,
+ mode=mode,
+ counters=counters,
+ ctx=ctx,
+ )
+ return
+
+ memory_roots: list[str] = []
+ resource_directories: list[str] = []
+ resource_files: list[str] = []
+
+ for entry in entries:
+ entry_uri = entry.get("uri")
+ if not entry_uri:
+ continue
+ classification = classify_uri(entry_uri)
+ if classification.is_memory:
+ if entry.get("isDir") and classification.is_memory_root:
+ memory_roots.append(entry_uri)
+ continue
+ if not self._is_resource_entry_for_namespace(entry_uri, target_root):
+ continue
+ if entry.get("isDir"):
+ resource_directories.append(entry_uri)
+ elif not self._is_hidden_meta_file(entry_uri):
+ resource_files.append(entry_uri)
+
+ for memory_root in sorted(set(memory_roots)):
+ memory_mode = (
+ "semantic_and_vectors" if mode == "semantic_and_vectors" else "vectors_only"
+ )
+ await self._reindex_memory(
+ uri=memory_root, mode=memory_mode, counters=counters, ctx=ctx
+ )
+
+ if mode == "semantic_and_vectors":
+ (
+ resource_directories,
+ resource_files,
+ ) = await self._refresh_namespace_resource_semantics(
+ target_root=target_root,
+ directories=resource_directories,
+ files=resource_files,
+ counters=counters,
+ ctx=ctx,
+ )
+
+ await self._reindex_resource_vectors_from_entries(
+ root_uri=target_root,
+ directories=resource_directories,
+ files=resource_files,
+ counters=counters,
+ ctx=ctx,
+ )
+
+ async def _reindex_agent_namespace(
+ self,
+ *,
+ uri: str,
+ mode: str,
+ counters: _ReindexCounters,
+ ctx: RequestContext,
+ ) -> None:
+ normalized_uri = uri.rstrip("/")
+ target_root = normalized_uri if normalized_uri else uri
+ viking_fs = get_viking_fs()
+ try:
+ entries = await self._tree_all(viking_fs, target_root, show_all_hidden=True, ctx=ctx)
+ except Exception as exc:
+ raise NotFoundError(uri, "resource") from exc
+
+ if target_root == "viking://agent":
+ agent_roots = [
+ entry.get("uri")
+ for entry in entries
+ if entry.get("isDir") and classify_uri(entry.get("uri", "")).is_agent_namespace_root
+ ]
+ if agent_roots:
+ for agent_root in sorted(set(agent_roots)):
+ await self._reindex_agent_namespace(
+ uri=agent_root,
+ mode=mode,
+ counters=counters,
+ ctx=ctx,
+ )
+ return
+
+ memory_roots: list[str] = []
+ skill_roots: list[str] = []
+ resource_directories: list[str] = []
+ resource_files: list[str] = []
+
+ for entry in entries:
+ entry_uri = entry.get("uri")
+ if not entry_uri:
+ continue
+ classification = classify_uri(entry_uri)
+ if classification.is_memory:
+ if entry.get("isDir") and classification.is_memory_root:
+ memory_roots.append(entry_uri)
+ continue
+ if classification.is_skill:
+ if entry.get("isDir") and classification.is_skill_root:
+ skill_roots.append(entry_uri)
+ continue
+ if not self._is_resource_entry_for_namespace(entry_uri, target_root):
+ continue
+ if entry.get("isDir"):
+ resource_directories.append(entry_uri)
+ elif not self._is_hidden_meta_file(entry_uri):
+ resource_files.append(entry_uri)
+
+ for memory_root in sorted(set(memory_roots)):
+ memory_mode = (
+ "semantic_and_vectors" if mode == "semantic_and_vectors" else "vectors_only"
+ )
+ await self._reindex_memory(
+ uri=memory_root, mode=memory_mode, counters=counters, ctx=ctx
+ )
+
+ for skill_root in sorted(set(skill_roots)):
+ skill_mode = (
+ "semantic_and_vectors" if mode == "semantic_and_vectors" else "vectors_only"
+ )
+ await self._reindex_skill(uri=skill_root, mode=skill_mode, counters=counters, ctx=ctx)
+
+ if mode == "semantic_and_vectors":
+ (
+ resource_directories,
+ resource_files,
+ ) = await self._refresh_namespace_resource_semantics(
+ target_root=target_root,
+ directories=resource_directories,
+ files=resource_files,
+ counters=counters,
+ ctx=ctx,
+ )
+
+ await self._reindex_resource_vectors_from_entries(
+ root_uri=target_root,
+ directories=resource_directories,
+ files=resource_files,
+ counters=counters,
+ ctx=ctx,
+ )
+
+ async def _reindex_global_namespace(
+ self,
+ *,
+ uri: str,
+ mode: str,
+ counters: _ReindexCounters,
+ ctx: RequestContext,
+ ) -> None:
+ target_root = "viking://"
+ viking_fs = get_viking_fs()
+ try:
+ entries = await self._tree_all(viking_fs, target_root, show_all_hidden=True, ctx=ctx)
+ except Exception as exc:
+ raise NotFoundError(uri, "resource") from exc
+
+ user_roots: list[str] = []
+ agent_roots: list[str] = []
+ resource_directories: list[str] = []
+ resource_files: list[str] = []
+
+ for entry in entries:
+ entry_uri = entry.get("uri")
+ if not entry_uri:
+ continue
+ if entry_uri in {"viking://user", "viking://agent"}:
+ continue
+ if entry_uri.startswith("viking://user/"):
+ remainder = entry_uri[len("viking://user/") :]
+ if entry.get("isDir") and remainder and "/" not in remainder:
+ user_roots.append(entry_uri)
+ continue
+ if entry_uri.startswith("viking://agent/"):
+ remainder = entry_uri[len("viking://agent/") :]
+ if entry.get("isDir") and remainder and "/" not in remainder:
+ agent_roots.append(entry_uri)
+ continue
+ if entry_uri == "viking://session" or entry_uri.startswith("viking://session/"):
+ continue
+ if not self._is_global_resource_entry(entry_uri):
+ continue
+ if entry.get("isDir"):
+ resource_directories.append(entry_uri)
+ elif not self._is_hidden_meta_file(entry_uri):
+ resource_files.append(entry_uri)
+
+ for user_root in sorted(set(user_roots)):
+ await self._reindex_user_namespace(
+ uri=user_root,
+ mode=mode,
+ counters=counters,
+ ctx=ctx,
+ )
+
+ for agent_root in sorted(set(agent_roots)):
+ await self._reindex_agent_namespace(
+ uri=agent_root,
+ mode=mode,
+ counters=counters,
+ ctx=ctx,
+ )
+
+ if mode == "semantic_and_vectors":
+ (
+ resource_directories,
+ resource_files,
+ ) = await self._refresh_namespace_resource_semantics(
+ target_root=target_root,
+ directories=resource_directories,
+ files=resource_files,
+ counters=counters,
+ ctx=ctx,
+ )
+
+ await self._reindex_resource_vectors_from_entries(
+ root_uri=target_root,
+ directories=resource_directories,
+ files=resource_files,
+ counters=counters,
+ ctx=ctx,
+ )
+
+ async def _reindex_skill_vectors(
+ self,
+ *,
+ uri: str,
+ counters: _ReindexCounters,
+ ctx: RequestContext,
+ ) -> None:
+ viking_fs = get_viking_fs()
+ counters.scanned_records += 1
+
+ abstract = await self._read_directory_abstract(uri, ctx=ctx)
+ overview = await self._read_directory_overview(uri, ctx=ctx)
+ if not abstract:
+ record = await self._fetch_existing_record(uri=uri, level=0, ctx=ctx)
+ abstract = self._record_abstract(record)
+ if not overview:
+ record = await self._fetch_existing_record(uri=uri, level=1, ctx=ctx)
+ overview = self._record_abstract(record) or abstract
+
+ if not abstract and not overview:
+ counters.unsupported_records += 1
+ counters.warnings.append(f"No semantic source found for {uri}")
+ return
+
+ parent_uri = VikingURI(uri).parent.uri
+ if abstract:
+ try:
+ await self._upsert_context(
+ uri=uri,
+ parent_uri=parent_uri,
+ abstract=abstract,
+ vector_text=abstract,
+ is_leaf=False,
+ context_type=ContextType.SKILL.value,
+ level=ContextLevel.ABSTRACT,
+ meta=await self._skill_meta(uri=uri, abstract=abstract, ctx=ctx),
+ ctx=ctx,
+ )
+ counters.rebuilt_records += 1
+ except Exception as exc:
+ counters.failed_records += 1
+ counters.warnings.append(f"Failed to reindex {uri} L0 vector: {exc}")
+ if overview:
+ try:
+ await self._upsert_context(
+ uri=uri,
+ parent_uri=parent_uri,
+ abstract=abstract,
+ vector_text=overview,
+ is_leaf=False,
+ context_type=ContextType.SKILL.value,
+ level=ContextLevel.OVERVIEW,
+ meta=await self._skill_meta(uri=uri, abstract=abstract, ctx=ctx),
+ ctx=ctx,
+ )
+ counters.rebuilt_records += 1
+ except Exception as exc:
+ counters.failed_records += 1
+ counters.warnings.append(f"Failed to reindex {uri} L1 vector: {exc}")
+
+ skill_file_uri = f"{uri}/SKILL.md"
+ if await viking_fs.exists(skill_file_uri, ctx=ctx):
+ counters.scanned_records += 1
+ skill_content = await self._safe_read_text(skill_file_uri, ctx=ctx)
+ if skill_content:
+ detail_abstract = self._prefer_non_empty(abstract, skill_content)
+ try:
+ await self._upsert_context(
+ uri=skill_file_uri,
+ parent_uri=uri,
+ abstract=detail_abstract,
+ vector_text=skill_content,
+ is_leaf=True,
+ context_type=ContextType.SKILL.value,
+ level=ContextLevel.DETAIL,
+ ctx=ctx,
+ )
+ counters.rebuilt_records += 1
+ except Exception as exc:
+ counters.failed_records += 1
+ counters.warnings.append(f"Failed to reindex {skill_file_uri} vector: {exc}")
+
+ async def _reindex_memory_directory_vectors(
+ self,
+ *,
+ uri: str,
+ counters: _ReindexCounters,
+ ctx: RequestContext,
+ ) -> None:
+ counters.scanned_records += 1
+ abstract = await self._read_directory_abstract(uri, ctx=ctx)
+ overview = await self._read_directory_overview(uri, ctx=ctx)
+ if not abstract and not overview:
+ counters.unsupported_records += 1
+ counters.warnings.append(f"No semantic source found for {uri}")
+ return
+
+ parent_uri = VikingURI(uri).parent.uri
+ if abstract:
+ try:
+ await self._upsert_context(
+ uri=uri,
+ parent_uri=parent_uri,
+ abstract=abstract,
+ vector_text=abstract,
+ is_leaf=False,
+ context_type=ContextType.MEMORY.value,
+ level=ContextLevel.ABSTRACT,
+ ctx=ctx,
+ )
+ counters.rebuilt_records += 1
+ except Exception as exc:
+ counters.failed_records += 1
+ counters.warnings.append(f"Failed to reindex {uri} L0 vector: {exc}")
+ if overview:
+ try:
+ await self._upsert_context(
+ uri=uri,
+ parent_uri=parent_uri,
+ abstract=abstract,
+ vector_text=overview,
+ is_leaf=False,
+ context_type=ContextType.MEMORY.value,
+ level=ContextLevel.OVERVIEW,
+ ctx=ctx,
+ )
+ counters.rebuilt_records += 1
+ except Exception as exc:
+ counters.failed_records += 1
+ counters.warnings.append(f"Failed to reindex {uri} L1 vector: {exc}")
+
+ async def _reindex_memory_vectors(
+ self,
+ *,
+ uri: str,
+ counters: _ReindexCounters,
+ ctx: RequestContext,
+ ) -> None:
+ viking_fs = get_viking_fs()
+ if await viking_fs.exists(uri, ctx=ctx):
+ stat = await viking_fs.stat(uri, ctx=ctx)
+ if stat.get("isDir", stat.get("is_dir")):
+ entries = await self._tree_all(viking_fs, uri, show_all_hidden=False, ctx=ctx)
+ directory_uris = {uri}
+ for entry in entries:
+ entry_uri = entry.get("uri")
+ if entry_uri and entry.get("isDir"):
+ directory_uris.add(entry_uri)
+ await self._reindex_memory_directory_chain(
+ directory_uris=sorted(directory_uris),
+ counters=counters,
+ ctx=ctx,
+ )
+ file_uris = [entry["uri"] for entry in entries if not entry.get("isDir")]
+ else:
+ file_uris = [uri]
+ else:
+ raise NotFoundError(uri, "memory")
+
+ for file_uri in file_uris:
+ counters.scanned_records += 1
+ body = await self._safe_read_text(file_uri, ctx=ctx)
+ parsed_body = parse_memory_file_with_fields(body) if body else {"content": ""}
+ memory_content = parsed_body.get("content", "")
+ existing = await self._fetch_existing_record(uri=file_uri, level=2, ctx=ctx)
+ abstract = self._best_non_empty(
+ self._record_abstract(existing),
+ await self._best_file_summary(file_uri, ctx=ctx),
+ )
+ if not body and existing is None:
+ counters.unsupported_records += 1
+ counters.warnings.append(f"No memory source found for {file_uri}")
+ continue
+
+ parent_uri = VikingURI(file_uri.split("#", 1)[0]).parent.uri
+ if body:
+ detail_abstract = self._prefer_non_empty(abstract, memory_content, body)
+ try:
+ await self._upsert_context(
+ uri=file_uri,
+ parent_uri=parent_uri,
+ abstract=detail_abstract,
+ vector_text=body,
+ is_leaf=True,
+ context_type=ContextType.MEMORY.value,
+ level=ContextLevel.DETAIL,
+ ctx=ctx,
+ )
+ counters.rebuilt_records += 1
+ except Exception as exc:
+ counters.failed_records += 1
+ counters.warnings.append(f"Failed to reindex {file_uri} vector: {exc}")
+ continue
+ for chunk_uri, chunk_text in self._chunk_memory_body(file_uri, body):
+ counters.scanned_records += 1
+ try:
+ await self._upsert_context(
+ uri=chunk_uri,
+ parent_uri=file_uri,
+ abstract=detail_abstract,
+ vector_text=chunk_text,
+ is_leaf=True,
+ context_type=ContextType.MEMORY.value,
+ level=ContextLevel.DETAIL,
+ ctx=ctx,
+ )
+ counters.rebuilt_records += 1
+ except Exception as exc:
+ counters.failed_records += 1
+ counters.warnings.append(f"Failed to reindex {chunk_uri} vector: {exc}")
+ continue
+
+ try:
+ await self._upsert_context(
+ uri=file_uri,
+ parent_uri=parent_uri,
+ abstract=abstract,
+ vector_text=abstract,
+ is_leaf=True,
+ context_type=ContextType.MEMORY.value,
+ level=ContextLevel.DETAIL,
+ ctx=ctx,
+ )
+ counters.rebuilt_records += 1
+ counters.warnings.append(
+ f"Reindexed {file_uri} from abstract fallback because original memory body is unavailable"
+ )
+ except Exception as exc:
+ counters.failed_records += 1
+ counters.warnings.append(f"Failed to reindex {file_uri} vector: {exc}")
+
+ async def _reindex_memory_directory_chain(
+ self,
+ *,
+ directory_uris: Iterable[str],
+ counters: _ReindexCounters,
+ ctx: RequestContext,
+ ) -> None:
+ for directory_uri in directory_uris:
+ counters.scanned_records += 1
+ abstract = await self._read_directory_abstract(directory_uri, ctx=ctx)
+ overview = await self._read_directory_overview(directory_uri, ctx=ctx)
+ if not abstract and not overview:
+ continue
+
+ parent_uri = VikingURI(directory_uri).parent.uri
+ if abstract:
+ try:
+ await self._upsert_context(
+ uri=directory_uri,
+ parent_uri=parent_uri,
+ abstract=abstract,
+ vector_text=abstract,
+ is_leaf=False,
+ context_type=ContextType.MEMORY.value,
+ level=ContextLevel.ABSTRACT,
+ ctx=ctx,
+ )
+ counters.rebuilt_records += 1
+ except Exception as exc:
+ counters.failed_records += 1
+ counters.warnings.append(f"Failed to reindex {directory_uri} L0 vector: {exc}")
+ if overview:
+ try:
+ await self._upsert_context(
+ uri=directory_uri,
+ parent_uri=parent_uri,
+ abstract=abstract,
+ vector_text=overview,
+ is_leaf=False,
+ context_type=ContextType.MEMORY.value,
+ level=ContextLevel.OVERVIEW,
+ ctx=ctx,
+ )
+ counters.rebuilt_records += 1
+ except Exception as exc:
+ counters.failed_records += 1
+ counters.warnings.append(f"Failed to reindex {directory_uri} L1 vector: {exc}")
+
+ async def _regenerate_skill_semantics(self, *, uri: str, ctx: RequestContext) -> None:
+ service = get_service()
+ if service.viking_fs is None or service.vikingdb_manager is None:
+ raise RuntimeError("OpenVikingService not initialized")
+
+ viking_fs = service.viking_fs
+ skill_file_uri = f"{uri}/SKILL.md"
+ skill_content = await self._safe_read_text(skill_file_uri, ctx=ctx)
+ if not skill_content:
+ raise OpenVikingError(
+ f"SKILL.md not found for {uri}",
+ code="NOT_FOUND",
+ details={"uri": uri},
+ )
+
+ skill_dict, _, _ = SkillProcessor(service.vikingdb_manager)._parse_skill(
+ skill_content,
+ allow_local_path_resolution=False,
+ )
+ overview = await SkillProcessor(service.vikingdb_manager)._generate_overview(
+ skill_dict,
+ get_openviking_config(),
+ )
+ await viking_fs.write_context(
+ uri=uri,
+ content=skill_content,
+ abstract=skill_dict.get("description", ""),
+ overview=overview,
+ content_filename="SKILL.md",
+ is_leaf=False,
+ ctx=ctx,
+ )
+
+ async def _read_directory_abstract(self, uri: str, *, ctx: RequestContext) -> str:
+ try:
+ return await get_viking_fs().abstract(uri, ctx=ctx)
+ except Exception:
+ return ""
+
+ async def _read_directory_overview(self, uri: str, *, ctx: RequestContext) -> str:
+ try:
+ return await get_viking_fs().overview(uri, ctx=ctx)
+ except Exception:
+ return ""
+
+ async def _best_file_summary(self, uri: str, *, ctx: RequestContext) -> str:
+ parent_uri = VikingURI(uri).parent.uri
+ file_name = uri.rsplit("/", 1)[-1]
+ overviews = await self._safe_read_text(f"{parent_uri}/.overview.md", ctx=ctx)
+ if overviews:
+ parsed = self._parse_overview_md(overviews)
+ if file_name in parsed:
+ return parsed[file_name]
+ existing = await self._fetch_existing_record(uri=uri, level=2, ctx=ctx)
+ return self._record_abstract(existing)
+
+ async def _best_resource_file_vector_text(
+ self,
+ uri: str,
+ summary: str,
+ ctx: RequestContext,
+ ) -> str:
+ text_source = getattr(get_openviking_config().embedding, "text_source", "summary_first")
+ existing = await self._fetch_existing_record(uri=uri, level=2, ctx=ctx)
+ fallback = self._record_abstract(existing)
+ content_type = get_resource_content_type(uri.rsplit("/", 1)[-1])
+
+ if content_type == ResourceContentType.TEXT:
+ content = await self._safe_read_text(uri, ctx=ctx)
+ if text_source in {"summary_first", "summary_only"} and summary:
+ return summary
+ if content:
+ return self._truncate_embedding_text(content)
+ if summary:
+ return summary
+ return fallback
+
+ if summary:
+ return summary
+ return fallback
+
+ async def _upsert_context(
+ self,
+ *,
+ uri: str,
+ parent_uri: str,
+ abstract: str,
+ vector_text: str,
+ is_leaf: bool,
+ context_type: str,
+ level: ContextLevel,
+ ctx: RequestContext,
+ meta: Optional[dict[str, Any]] = None,
+ ) -> None:
+ service = get_service()
+ assert service.vikingdb_manager is not None
+
+ context = Context(
+ uri=uri,
+ parent_uri=parent_uri,
+ is_leaf=is_leaf,
+ abstract=abstract or "",
+ context_type=context_type,
+ level=level,
+ user=ctx.user,
+ account_id=ctx.account_id,
+ owner_space=owner_space_for_uri(uri, ctx),
+ meta=meta or {},
+ )
+ context.set_vectorize(Vectorize(text=vector_text))
+ msg = EmbeddingMsgConverter.from_context(context)
+ if msg is None:
+ raise OpenVikingError(
+ f"No vector text generated for {uri}",
+ code="FAILED_PRECONDITION",
+ details={"uri": uri},
+ )
+
+ result = await TextEmbeddingHandler(service.vikingdb_manager).on_dequeue(
+ {"data": msg.to_json()}
+ )
+ if result is None:
+ raise OpenVikingError(
+ f"Failed to reindex vector for {uri}",
+ code="PROCESSING_ERROR",
+ details={"uri": uri, "level": int(level)},
+ )
+ logger.debug("Reindexed vector for %s level=%s", uri, int(level))
+
+ async def _fetch_existing_record(
+ self,
+ *,
+ uri: str,
+ level: int,
+ ctx: RequestContext,
+ ) -> Optional[dict[str, Any]]:
+ service = get_service()
+ assert service.vikingdb_manager is not None
+ records = await service.vikingdb_manager.get_context_by_uri(
+ uri=uri,
+ level=level,
+ limit=1,
+ ctx=ctx,
+ )
+ return records[0] if records else None
+
+ async def _skill_meta(
+ self,
+ *,
+ uri: str,
+ abstract: str,
+ ctx: RequestContext,
+ ) -> dict[str, Any]:
+ name = uri.rstrip("/").split("/")[-1]
+ return {"name": name, "description": abstract}
+
+ def _record_abstract(self, record: Optional[dict[str, Any]]) -> str:
+ if not record:
+ return ""
+ return str(record.get("abstract") or "")
+
+ def _is_hidden_meta_file(self, uri: str) -> bool:
+ return uri.endswith("/.abstract.md") or uri.endswith("/.overview.md")
+
+ def _truncate_embedding_text(self, value: str) -> str:
+ max_input_chars = int(
+ getattr(get_openviking_config().embedding, "max_input_chars", 1000) or 1000
+ )
+ if len(value) <= max_input_chars:
+ return value
+ return value[:max_input_chars] + "\n...(truncated for embedding)"
+
+ async def _safe_read_text(self, uri: str, *, ctx: RequestContext) -> str:
+ viking_fs = get_viking_fs()
+ try:
+ if not await viking_fs.exists(uri, ctx=ctx):
+ return ""
+ content = await viking_fs.read_file(uri, ctx=ctx)
+ if isinstance(content, bytes):
+ return content.decode("utf-8", errors="replace")
+ return str(content or "")
+ except Exception:
+ return ""
+
+ def _chunk_memory_body(self, uri: str, body: str) -> Iterable[tuple[str, str]]:
+ semantic = get_openviking_config().semantic
+ chunk_chars = semantic.memory_chunk_chars
+ overlap = semantic.memory_chunk_overlap
+ if len(body) <= chunk_chars:
+ return []
+
+ chunks: list[str] = []
+ start = 0
+ while start < len(body):
+ end = start + chunk_chars
+ if end < len(body):
+ boundary = body.rfind("\n\n", start, end)
+ if boundary > start + chunk_chars // 2:
+ end = boundary + 2
+ chunks.append(body[start:end].strip())
+ start = end - overlap
+ if start >= len(body):
+ break
+
+ return [(f"{uri}#chunk_{idx:04d}", chunk) for idx, chunk in enumerate(chunks) if chunk]
+
+ def _best_non_empty(self, *values: str) -> str:
+ for value in values:
+ if value:
+ return value
+ return ""
+
+ def _prefer_non_empty(self, *values: str) -> str:
+ for value in values:
+ if value:
+ return value
+ return ""
+
+ @staticmethod
+ def _parse_overview_md(content: str) -> dict[str, str]:
+ parsed: dict[str, str] = {}
+ current_name: Optional[str] = None
+ current_lines: list[str] = []
+ for line in (content or "").splitlines():
+ if line.startswith("## "):
+ if current_name is not None:
+ parsed[current_name] = "\n".join(current_lines).strip()
+ current_name = line[3:].strip()
+ current_lines = []
+ continue
+ if current_name is not None:
+ current_lines.append(line)
+ if current_name is not None:
+ parsed[current_name] = "\n".join(current_lines).strip()
+ return parsed
diff --git a/openviking/storage/content_write.py b/openviking/storage/content_write.py
index 3f819c4e4..411faf1bd 100644
--- a/openviking/storage/content_write.py
+++ b/openviking/storage/content_write.py
@@ -7,6 +7,7 @@ from __future__ import annotations
import os
from typing import Any, Dict, Optional
+from openviking.core.namespace import context_type_for_uri
from openviking.resource.watch_storage import is_watch_task_control_uri
from openviking.server.identity import RequestContext
from openviking.session.memory.utils.content import deserialize_full, serialize_with_metadata
@@ -68,7 +69,7 @@ class ContentWriteCoordinator:
if stat.get("isDir"):
raise InvalidArgumentError(f"write only supports existing files, got directory: {uri}")
- context_type = self._context_type_for_uri(normalized_uri)
+ context_type = context_type_for_uri(normalized_uri)
root_uri = await self._resolve_root_uri(normalized_uri, ctx=ctx)
written_bytes = len(content.encode("utf-8"))
telemetry_id = get_current_telemetry().telemetry_id
@@ -300,7 +301,7 @@ class ContentWriteCoordinator:
if not stat.get("not_found"):
raise AlreadyExistsError(uri, "file")
- context_type = self._context_type_for_uri(uri)
+ context_type = context_type_for_uri(uri)
root_uri = await self._resolve_root_uri(uri, ctx=ctx, _allow_not_found=True)
written_bytes = len(content.encode("utf-8"))
telemetry_id = get_current_telemetry().telemetry_id
@@ -339,7 +340,7 @@ class ContentWriteCoordinator:
mode: str,
ctx: RequestContext,
) -> None:
- if mode == "replace" and self._context_type_for_uri(uri) == "memory":
+ if mode == "replace" and context_type_for_uri(uri) == "memory":
existing_raw = await self._viking_fs.read_file(uri, ctx=ctx)
existing = deserialize_full(existing_raw)
if existing.memory_fields:
@@ -601,10 +602,3 @@ class ContentWriteCoordinator:
raise InvalidArgumentError(f"could not resolve write root for {uri}")
root_uri = parent.uri
return root_uri
-
- def _context_type_for_uri(self, uri: str) -> str:
- if "/memories/" in uri:
- return "memory"
- if "/skills/" in uri or uri.startswith("viking://agent/skills/"):
- return "skill"
- return "resource"
diff --git a/openviking/storage/local_fs.py b/openviking/storage/local_fs.py
index 9ecfd26d2..03457b5cf 100644
--- a/openviking/storage/local_fs.py
+++ b/openviking/storage/local_fs.py
@@ -6,7 +6,7 @@ import os
import re
import zipfile
-from openviking.core.directories import get_context_type_for_uri
+from openviking.core.namespace import context_type_for_uri
from openviking.resource.watch_storage import is_watch_task_control_uri
from openviking.server.identity import RequestContext
from openviking.utils.embedding_utils import vectorize_directory_meta, vectorize_file
@@ -134,7 +134,7 @@ async def _enqueue_direct_vectorization(viking_fs, uri: str, ctx: RequestContext
except Exception:
return
await vectorize_directory_meta(
- dir_uri, abstract, overview, context_type=get_context_type_for_uri(dir_uri), ctx=ctx
+ dir_uri, abstract, overview, context_type=context_type_for_uri(dir_uri), ctx=ctx
)
async def index_file(file_uri: str, parent_uri: str, name: str) -> None:
@@ -142,7 +142,7 @@ async def _enqueue_direct_vectorization(viking_fs, uri: str, ctx: RequestContext
file_path=file_uri,
summary_dict={"name": name},
parent_uri=parent_uri,
- context_type=get_context_type_for_uri(file_uri),
+ context_type=context_type_for_uri(file_uri),
ctx=ctx,
)
diff --git a/openviking/storage/queuefs/semantic_dag.py b/openviking/storage/queuefs/semantic_dag.py
index cbf4efff6..ffba43850 100644
--- a/openviking/storage/queuefs/semantic_dag.py
+++ b/openviking/storage/queuefs/semantic_dag.py
@@ -81,6 +81,7 @@ class SemanticDagExecutor:
lifecycle_lock_handle_id: str = "",
is_code_repo: bool = False,
changes: Optional[Dict[str, List[str]]] = None,
+ skip_vectorization: bool = False,
):
self._processor = processor
self._context_type = context_type
@@ -94,6 +95,7 @@ class SemanticDagExecutor:
self._lifecycle_lock_handle_id = lifecycle_lock_handle_id
self._is_code_repo = is_code_repo
self._changes = changes or {}
+ self._skip_vectorization = skip_vectorization
self._changed_paths = {
path for key in ("added", "modified", "deleted") for path in self._changes.get(key, [])
}
@@ -646,6 +648,12 @@ class SemanticDagExecutor:
async def _add_vectorize_task(self, task: VectorizeTask) -> None:
"""Add a vectorize task to the pending list."""
+ if self._skip_vectorization:
+ logger.info(
+ "Skipping vectorization task for %s (requested via SemanticMsg)",
+ task.uri,
+ )
+ return
async with self._vectorize_lock:
self._pending_vectorize_tasks.append(task)
if task.task_type == "file":
diff --git a/openviking/storage/queuefs/semantic_processor.py b/openviking/storage/queuefs/semantic_processor.py
index f12d00ed6..c50afe6f5 100644
--- a/openviking/storage/queuefs/semantic_processor.py
+++ b/openviking/storage/queuefs/semantic_processor.py
@@ -8,7 +8,6 @@ from contextlib import nullcontext
from dataclasses import dataclass, field
from typing import Any, Dict, List, Optional, Set, Tuple
-from openviking.core.namespace import agent_space_fragment, user_space_fragment
from openviking.observability.context import (
bind_root_observability_context,
reset_root_observability_context,
@@ -154,21 +153,6 @@ class SemanticProcessor(DequeueHandlerBase):
with cls._stats_lock:
return cls._request_stats_by_telemetry_id.pop(telemetry_id, None)
- @staticmethod
- def _owner_space_for_uri(uri: str, ctx: RequestContext) -> str:
- """Derive owner_space from a URI.
-
- Resources (viking://resources/...) always get owner_space="" so they
- are globally visible. User / agent / session URIs inherit the
- caller's space name.
- """
- if uri.startswith("viking://agent/"):
- return agent_space_fragment(ctx)
- if uri.startswith("viking://user/") or uri.startswith("viking://session/"):
- return user_space_fragment(ctx)
- # resources and anything else → shared (empty owner_space)
- return ""
-
@staticmethod
def _ctx_from_semantic_msg(msg: SemanticMsg) -> RequestContext:
role = Role(msg.role) if msg.role in {r.value for r in Role} else Role.ROOT
@@ -341,6 +325,7 @@ class SemanticProcessor(DequeueHandlerBase):
lifecycle_lock_handle_id=msg.lifecycle_lock_handle_id,
is_code_repo=msg.is_code_repo,
changes=msg.changes,
+ skip_vectorization=msg.skip_vectorization,
)
self._dag_executor = executor
if msg.lifecycle_lock_handle_id:
@@ -588,6 +573,10 @@ class SemanticProcessor(DequeueHandlerBase):
raise RuntimeError(f"Failed to write abstract/overview for {dir_uri}: {e}") from e
try:
+ if msg.skip_vectorization:
+ logger.info(f"Skipping vectorization for {dir_uri} (requested via SemanticMsg)")
+ _mark_done()
+ return
if msg.telemetry_id and msg.id:
from openviking.storage.queuefs.embedding_tracker import EmbeddingTaskTracker
diff --git a/openviking/storage/viking_fs.py b/openviking/storage/viking_fs.py
index 6195f5668..01373954a 100644
--- a/openviking/storage/viking_fs.py
+++ b/openviking/storage/viking_fs.py
@@ -26,6 +26,7 @@ from typing import TYPE_CHECKING, Any, Dict, List, Optional, Union
from openviking.core.namespace import (
NamespaceShapeError,
canonicalize_uri,
+ classify_uri,
)
from openviking.core.namespace import (
is_accessible as namespace_is_accessible,
@@ -1023,8 +1024,8 @@ class VikingFS:
output: str = "original",
abs_limit: int = 256,
show_all_hidden: bool = False,
- node_limit: int = 1000,
- level_limit: int = 3,
+ node_limit: Optional[int] = 1000,
+ level_limit: Optional[int] = 3,
ctx: Optional[RequestContext] = None,
) -> List[Dict[str, Any]]:
"""
@@ -1035,8 +1036,8 @@ class VikingFS:
output: str = "original" or "agent"
abs_limit: int = 256 (for agent output abstract truncation)
show_all_hidden: bool = False (list all hidden files, like -a)
- node_limit: int = 1000 (maximum number of nodes to list)
- level_limit: int = 3 (maximum depth level to traverse)
+ node_limit: int | None = 1000 (maximum number of nodes to list, None means unlimited)
+ level_limit: int | None = 3 (maximum depth level to traverse, None means unlimited)
output="original"
[{'name': '.abstract.md', 'size': 100, 'mode': 420, 'modTime': '2026-02-11T16:52:16.256334192+08:00', 'isDir': False, 'meta': {...}, 'rel_path': '.abstract.md', 'uri': 'viking://resources...'}]
@@ -1058,8 +1059,8 @@ class VikingFS:
self,
uri: str,
show_all_hidden: bool = False,
- node_limit: int = 1000,
- level_limit: int = 3,
+ node_limit: Optional[int] = 1000,
+ level_limit: Optional[int] = 3,
ctx: Optional[RequestContext] = None,
) -> List[Dict[str, Any]]:
"""Recursively list all contents (original format)."""
@@ -1068,10 +1069,12 @@ class VikingFS:
real_ctx = self._ctx_or_default(ctx)
async def _walk(current_path: str, current_rel: str, current_depth: int):
- if len(all_entries) >= node_limit or current_depth >= level_limit:
+ if node_limit is not None and len(all_entries) >= node_limit:
+ return
+ if level_limit is not None and current_depth >= level_limit:
return
for entry in self._ls_entries(current_path):
- if len(all_entries) >= node_limit:
+ if node_limit is not None and len(all_entries) >= node_limit:
break
name = entry.get("name", "")
if name in [".", ".."]:
@@ -1098,8 +1101,8 @@ class VikingFS:
uri: str,
abs_limit: int,
show_all_hidden: bool = False,
- node_limit: int = 1000,
- level_limit: int = 3,
+ node_limit: Optional[int] = 1000,
+ level_limit: Optional[int] = 3,
ctx: Optional[RequestContext] = None,
) -> List[Dict[str, Any]]:
"""Recursively list all contents (agent format with abstracts)."""
@@ -1109,10 +1112,12 @@ class VikingFS:
real_ctx = self._ctx_or_default(ctx)
async def _walk(current_path: str, current_rel: str, current_depth: int):
- if len(all_entries) >= node_limit or current_depth >= level_limit:
+ if node_limit is not None and len(all_entries) >= node_limit:
+ return
+ if level_limit is not None and current_depth >= level_limit:
return
for entry in self._ls_entries(current_path):
- if len(all_entries) >= node_limit:
+ if node_limit is not None and len(all_entries) >= node_limit:
break
name = entry.get("name", "")
if name in [".", ".."]:
@@ -1758,11 +1763,12 @@ class VikingFS:
"""Infer context_type from URI. Returns None when ambiguous."""
from openviking_cli.retrieve import ContextType
- if "/memories" in uri:
+ classification = classify_uri(uri)
+ if classification.is_memory:
return ContextType.MEMORY
- elif "/skills" in uri:
+ elif classification.is_skill:
return ContextType.SKILL
- elif "/resources" in uri:
+ elif classification.parts[:1] == ("resources",) or "resources" in classification.parts:
return ContextType.RESOURCE
return None
diff --git a/openviking/storage/vikingdb_manager.py b/openviking/storage/vikingdb_manager.py
index 800002cad..5b03b13d1 100644
--- a/openviking/storage/vikingdb_manager.py
+++ b/openviking/storage/vikingdb_manager.py
@@ -487,13 +487,15 @@ class VikingDBManagerProxy:
owner_space: Optional[str] = None,
level: Optional[int] = None,
limit: int = 1,
+ *,
+ ctx: Optional[RequestContext] = None,
) -> List[Dict[str, Any]]:
return await self._manager.get_context_by_uri(
uri=uri,
owner_space=owner_space,
level=level,
limit=limit,
- ctx=self._ctx,
+ ctx=ctx if ctx is not None else self._ctx,
)
async def delete_account_data(self, account_id: str) -> int:
diff --git a/openviking/sync_client.py b/openviking/sync_client.py
index 7f5deaec1..9cd9db772 100644
--- a/openviking/sync_client.py
+++ b/openviking/sync_client.py
@@ -105,6 +105,21 @@ class SyncOpenViking:
"""Query background task status."""
return run_async(self._async_client.get_task(task_id))
+ def reindex(
+ self,
+ uri: str,
+ mode: str = "vectors_only",
+ wait: bool = True,
+ ) -> Dict[str, Any]:
+ """Reindex semantic/vector artifacts for a URI."""
+ return run_async(
+ self._async_client.reindex(
+ uri=uri,
+ mode=mode,
+ wait=wait,
+ )
+ )
+
def add_resource(
self,
path: str,
diff --git a/openviking/utils/embedding_utils.py b/openviking/utils/embedding_utils.py
index 451163c5c..28b3d8959 100644
--- a/openviking/utils/embedding_utils.py
+++ b/openviking/utils/embedding_utils.py
@@ -12,8 +12,7 @@ from datetime import datetime, timezone
from typing import Dict, Optional
from openviking.core.context import Context, ContextLevel, ResourceContentType, Vectorize
-from openviking.core.directories import get_context_type_for_uri
-from openviking.core.namespace import agent_space_fragment, user_space_fragment
+from openviking.core.namespace import context_type_for_uri, owner_space_for_uri
from openviking.server.identity import RequestContext
from openviking.storage.queuefs import get_queue_manager
from openviking.storage.queuefs.embedding_msg_converter import EmbeddingMsgConverter
@@ -81,15 +80,6 @@ async def _decrement_embedding_tracker(semantic_msg_id: Optional[str], count: in
)
-def _owner_space_for_uri(uri: str, ctx: RequestContext) -> str:
- """Derive owner_space from a URI."""
- if uri.startswith("viking://agent/"):
- return agent_space_fragment(ctx)
- if uri.startswith("viking://user/") or uri.startswith("viking://session/"):
- return user_space_fragment(ctx)
- return ""
-
-
def _coerce_datetime(value: object) -> Optional[datetime]:
if isinstance(value, datetime):
return value
@@ -251,7 +241,7 @@ async def vectorize_directory_meta(
embedding_queue = queue_manager.get_queue(queue_manager.EMBEDDING)
parent_uri = VikingURI(uri).parent.uri
- owner_space = _owner_space_for_uri(uri, ctx)
+ owner_space = owner_space_for_uri(uri, ctx)
created_at, updated_at = await _resolve_context_timestamps(uri, ctx)
@@ -362,7 +352,7 @@ async def vectorize_file(
updated_at=updated_at,
user=ctx.user,
account_id=ctx.account_id,
- owner_space=_owner_space_for_uri(file_path, ctx),
+ owner_space=owner_space_for_uri(file_path, ctx),
)
content_type = get_resource_content_type(file_name)
@@ -442,8 +432,12 @@ async def index_resource(
(``/memories/``) are indexed as ``"memory"`` rather than the default
``"resource"``.
"""
+ if uri.startswith("viking://session/") or uri == "viking://session":
+ logger.info("Skipping indexing for session namespace: %s", uri)
+ return
+
viking_fs = get_viking_fs()
- context_type = get_context_type_for_uri(uri)
+ context_type = context_type_for_uri(uri)
# 1. Index Directory Metadata
abstract_uri = f"{uri}/.abstract.md"
diff --git a/openviking/utils/summarizer.py b/openviking/utils/summarizer.py
index beb5543b4..4be0acb71 100644
--- a/openviking/utils/summarizer.py
+++ b/openviking/utils/summarizer.py
@@ -7,7 +7,7 @@ Handles summarization and key information extraction.
from typing import TYPE_CHECKING, Any, Dict, List, Tuple
-from openviking.core.directories import get_context_type_for_uri
+from openviking.core.namespace import context_type_for_uri
from openviking.storage.queuefs import SemanticMsg, get_queue_manager
from openviking.storage.viking_fs import get_viking_fs
from openviking.telemetry import get_current_telemetry
@@ -77,7 +77,7 @@ class Summarizer:
for uri, temp_uri in zip(resource_uris, temp_uris, strict=True):
# Determine context_type based on URI
- context_type = get_context_type_for_uri(uri)
+ context_type = context_type_for_uri(uri)
enqueue_units: List[Tuple[str, str]] = []
if is_resources_root(uri) and uri != temp_uri:
diff --git a/openviking_cli/client/base.py b/openviking_cli/client/base.py
index 3acb8c9f7..fa2d89288 100644
--- a/openviking_cli/client/base.py
+++ b/openviking_cli/client/base.py
@@ -63,6 +63,16 @@ class BaseClient(ABC):
"""Wait for all processing to complete."""
...
+ @abstractmethod
+ async def reindex(
+ self,
+ uri: str,
+ mode: str = "vectors_only",
+ wait: bool = True,
+ ) -> Dict[str, Any]:
+ """Reindex semantic/vector artifacts for a URI."""
+ ...
+
# ============= File System =============
@abstractmethod
diff --git a/openviking_cli/client/http.py b/openviking_cli/client/http.py
index 937696706..7ae0e8d5f 100644
--- a/openviking_cli/client/http.py
+++ b/openviking_cli/client/http.py
@@ -964,6 +964,23 @@ class AsyncHTTPClient(BaseClient):
except Exception:
return False
+ async def reindex(
+ self,
+ uri: str,
+ mode: str = "vectors_only",
+ wait: bool = True,
+ ) -> Dict[str, Any]:
+ """Trigger reindex for a URI."""
+ response = await self._http.post(
+ "/api/v1/content/reindex",
+ json={
+ "uri": uri,
+ "mode": mode,
+ "wait": wait,
+ },
+ )
+ return self._handle_response(response)
+
# ============= Observer (Internal) =============
async def _get_queue_status(self) -> Dict[str, Any]:
diff --git a/openviking_cli/client/sync_http.py b/openviking_cli/client/sync_http.py
index d384c6c75..4e850cb03 100644
--- a/openviking_cli/client/sync_http.py
+++ b/openviking_cli/client/sync_http.py
@@ -140,6 +140,21 @@ class SyncHTTPClient:
"""Query background task status."""
return run_async(self._async_client.get_task(task_id))
+ def reindex(
+ self,
+ uri: str,
+ mode: str = "vectors_only",
+ wait: bool = True,
+ ) -> Dict[str, Any]:
+ """Trigger reindex for a URI."""
+ return run_async(
+ self._async_client.reindex(
+ uri=uri,
+ mode=mode,
+ wait=wait,
+ )
+ )
+
def commit_session(
self, session_id: str, telemetry: TelemetryRequest = False
) -> Dict[str, Any]:
diff --git a/tests/client/test_rebuild_clients.py b/tests/client/test_rebuild_clients.py
new file mode 100644
index 000000000..73ec6a0c3
--- /dev/null
+++ b/tests/client/test_rebuild_clients.py
@@ -0,0 +1,121 @@
+from types import SimpleNamespace
+from unittest.mock import AsyncMock, patch
+
+import pytest
+
+import openviking_cli.client.http as http_module
+from openviking import AsyncOpenViking, SyncOpenViking
+from openviking.client.local import LocalClient
+from openviking_cli.client.http import AsyncHTTPClient
+from openviking_cli.client.sync_http import SyncHTTPClient
+from openviking_cli.utils.config import OPENVIKING_CLI_CONFIG_ENV
+
+
[email protected](autouse=True)
+def clear_ovcli_config(monkeypatch):
+ monkeypatch.delenv(OPENVIKING_CLI_CONFIG_ENV, raising=False)
+ monkeypatch.setattr(http_module, "load_ovcli_config", lambda: None)
+
+
+async def test_async_openviking_reindex_forwards_to_local_client(tmp_path):
+ client = AsyncOpenViking(path=str(tmp_path))
+ with patch.object(client, "_ensure_initialized", new_callable=AsyncMock) as mock_init:
+ with patch.object(client._client, "reindex", new_callable=AsyncMock) as mock_reindex:
+ mock_reindex.return_value = {"status": "completed"}
+
+ result = await client.reindex(
+ "viking://resources/demo",
+ mode="vectors_only",
+ wait=False,
+ )
+
+ assert result == {"status": "completed"}
+ mock_init.assert_awaited_once()
+ mock_reindex.assert_awaited_once_with(
+ uri="viking://resources/demo",
+ mode="vectors_only",
+ wait=False,
+ )
+
+
+def test_sync_openviking_reindex_forwards_to_async_client():
+ client = SyncOpenViking()
+ with patch.object(
+ client._async_client,
+ "reindex",
+ return_value={"status": "completed"},
+ ) as mock_reindex:
+ with patch(
+ "openviking.sync_client.run_async", return_value={"status": "completed"}
+ ) as mock_run:
+ result = client.reindex(
+ "viking://resources/demo",
+ mode="semantic_and_vectors",
+ wait=True,
+ )
+
+ assert result == {"status": "completed"}
+ assert mock_run.called
+ assert mock_reindex.called
+
+
+async def test_local_client_reindex_forwards_to_service():
+ client = LocalClient.__new__(LocalClient)
+ client._service = SimpleNamespace(reindex=AsyncMock(return_value={"status": "completed"}))
+
+ result = await LocalClient.reindex(
+ client,
+ uri="viking://resources/demo",
+ mode="vectors_only",
+ wait=False,
+ )
+
+ assert result == {"status": "completed"}
+ client._service.reindex.assert_awaited_once()
+
+
+async def test_async_http_client_reindex_posts_content_reindex():
+ client = AsyncHTTPClient(url="http://localhost:1933")
+ fake_http = SimpleNamespace(post=AsyncMock(return_value=object()))
+ client._http = fake_http
+ with patch.object(
+ client, "_handle_response", return_value={"status": "completed"}
+ ) as mock_handle:
+ result = await client.reindex(
+ "viking://resources/demo",
+ mode="vectors_only",
+ wait=False,
+ )
+
+ assert result == {"status": "completed"}
+ fake_http.post.assert_awaited_once_with(
+ "/api/v1/content/reindex",
+ json={
+ "uri": "viking://resources/demo",
+ "mode": "vectors_only",
+ "wait": False,
+ },
+ )
+ assert mock_handle.called
+
+
+def test_sync_http_client_reindex_forwards_to_async_client():
+ client = SyncHTTPClient(url="http://localhost:1933")
+ with patch.object(
+ client._async_client,
+ "reindex",
+ return_value={"status": "accepted"},
+ ) as mock_reindex:
+ with patch(
+ "openviking_cli.client.sync_http.run_async",
+ return_value={"status": "accepted"},
+ ) as mock_run:
+ result = client.reindex(
+ "viking://resources/demo",
+ mode="vectors_only",
+ wait=False,
+ )
+
+ assert result == {"status": "accepted"}
+ assert mock_run.called
+ assert mock_reindex.called
diff --git a/tests/server/test_admin_rebuild_api.py b/tests/server/test_admin_rebuild_api.py
new file mode 100644
index 000000000..313830eb5
--- /dev/null
+++ b/tests/server/test_admin_rebuild_api.py
@@ -0,0 +1,1626 @@
+"""Tests for reindex admin endpoint and executor behavior."""
+
+import httpx
+import pytest
+
+from openviking.server.identity import RequestContext, Role
+from openviking_cli.exceptions import OpenVikingError
+from openviking_cli.session.user_id import UserIdentifier
+from tests.server.test_admin_api import ROOT_KEY
+from tests.server.test_admin_api import admin_app as _admin_app_fixture
+from tests.server.test_admin_api import admin_client as _admin_client_fixture
+from tests.server.test_admin_api import admin_service as _admin_service_fixture
+
+admin_service = _admin_service_fixture
+admin_app = _admin_app_fixture
+admin_client = _admin_client_fixture
+
+ROOT_ACCOUNT_HEADERS = {
+ "X-API-Key": ROOT_KEY,
+ "X-OpenViking-Account": "default",
+}
+
+
+async def test_reindex_requires_admin_role(admin_client: httpx.AsyncClient):
+ resp = await admin_client.post(
+ "/api/v1/content/reindex",
+ json={"uri": "viking://resources/demo", "mode": "vectors_only"},
+ )
+ assert resp.status_code == 401
+
+
+async def test_reindex_rejects_unsupported_uri(admin_client: httpx.AsyncClient):
+ resp = await admin_client.post(
+ "/api/v1/content/reindex",
+ json={"uri": "viking://unknown/demo", "mode": "vectors_only"},
+ headers=ROOT_ACCOUNT_HEADERS,
+ )
+ assert resp.status_code == 400
+ body = resp.json()
+ assert body["status"] == "error"
+ assert body["error"]["code"] == "UNSUPPORTED_URI"
+
+
+async def test_reindex_rejects_session_uri(admin_client: httpx.AsyncClient):
+ resp = await admin_client.post(
+ "/api/v1/content/reindex",
+ json={"uri": "viking://session/test/demo", "mode": "vectors_only"},
+ headers=ROOT_ACCOUNT_HEADERS,
+ )
+ assert resp.status_code == 400
+ body = resp.json()
+ assert body["status"] == "error"
+ assert body["error"]["code"] == "UNSUPPORTED_URI"
+
+
+async def test_reindex_rejects_reason_field(admin_client: httpx.AsyncClient):
+ resp = await admin_client.post(
+ "/api/v1/content/reindex",
+ json={
+ "uri": "viking://resources/demo",
+ "mode": "vectors_only",
+ "reason": "unused",
+ },
+ headers=ROOT_ACCOUNT_HEADERS,
+ )
+ assert resp.status_code == 400
+
+
+async def test_reindex_root_requires_explicit_account(admin_client: httpx.AsyncClient):
+ resp = await admin_client.post(
+ "/api/v1/content/reindex",
+ json={"uri": "viking://resources/demo", "mode": "vectors_only"},
+ headers={"X-API-Key": ROOT_KEY},
+ )
+ assert resp.status_code == 400
+ body = resp.json()
+ assert body["status"] == "error"
+ assert body["error"]["code"] == "INVALID_ARGUMENT"
+
+
+async def test_reindex_resource_vectors_only_wait_true(monkeypatch):
+ from openviking.server.routers.content import ReindexRequest, reindex
+
+ seen = {}
+
+ class FakeService:
+ async def reindex(self, *, uri, mode, wait, ctx):
+ seen["uri"] = uri
+ seen["mode"] = mode
+ seen["wait"] = wait
+ seen["ctx"] = ctx
+ return {
+ "status": "completed",
+ "uri": uri,
+ "object_type": "resource",
+ "mode": mode,
+ "rebuilt_records": 1,
+ "scanned_records": 1,
+ "unsupported_records": 0,
+ "failed_records": 0,
+ "duration_ms": 12,
+ "warnings": [],
+ }
+
+ ctx = RequestContext(
+ user=UserIdentifier(account_id="test", user_id="alice", agent_id="default"),
+ role=Role.ROOT,
+ )
+ request = ReindexRequest(uri="viking://resources/demo", mode="vectors_only", wait=True)
+
+ monkeypatch.setattr("openviking.server.routers.content.get_service", lambda: FakeService())
+ response = await reindex(body=request, ctx=ctx)
+
+ assert response.status == "ok"
+ assert response.result["status"] == "completed"
+ assert response.result["object_type"] == "resource"
+ assert response.result["rebuilt_records"] == 1
+ assert seen["uri"] == "viking://resources/demo"
+ assert seen["mode"] == "vectors_only"
+ assert seen["wait"] is True
+ assert seen["ctx"] == ctx
+ assert "reason" not in response.result
+
+
+async def test_reindex_resource_vectors_only_wait_false(monkeypatch):
+ from openviking.server.routers.content import ReindexRequest, reindex
+
+ class FakeService:
+ async def reindex(self, *, uri, mode, wait, ctx):
+ return {
+ "task_id": "rbld_123",
+ "status": "accepted",
+ "uri": uri,
+ "object_type": "resource",
+ "mode": mode,
+ }
+
+ ctx = RequestContext(
+ user=UserIdentifier(account_id="test", user_id="alice", agent_id="default"),
+ role=Role.ROOT,
+ )
+ request = ReindexRequest(uri="viking://resources/demo", mode="vectors_only", wait=False)
+
+ monkeypatch.setattr("openviking.server.routers.content.get_service", lambda: FakeService())
+ response = await reindex(body=request, ctx=ctx)
+
+ assert response.status == "ok"
+ assert response.result["status"] == "accepted"
+ assert response.result["task_id"] == "rbld_123"
+ assert response.result["object_type"] == "resource"
+ assert "reason" not in response.result
+
+
+async def test_reindex_memory_supports_semantic_and_vectors(monkeypatch):
+ from openviking.service.reindex_executor import ReindexExecutor
+
+ service = ReindexExecutor()
+ service._validate_mode("memory", "semantic_and_vectors")
+
+
+async def test_reindex_memory_semantic_and_vectors_rebuilds_full_subtree(monkeypatch):
+ from openviking.service.reindex_executor import ReindexExecutor, _ReindexCounters
+
+ seen = {"semantic": [], "vectors": []}
+
+ async def fake_run_semantic_processor(self, *, uri, context_type, ctx):
+ seen["semantic"].append((uri, context_type))
+
+ async def fake_reindex_memory_vectors(self, *, uri, counters, ctx):
+ seen["vectors"].append(uri)
+
+ monkeypatch.setattr(ReindexExecutor, "_run_semantic_processor", fake_run_semantic_processor)
+ monkeypatch.setattr(ReindexExecutor, "_reindex_memory_vectors", fake_reindex_memory_vectors)
+
+ service = ReindexExecutor()
+ counters = _ReindexCounters()
+ ctx = RequestContext(
+ user=UserIdentifier(account_id="test", user_id="alice", agent_id="default"),
+ role=Role.ROOT,
+ )
+
+ await service._reindex_memory(
+ uri="viking://user/default/memories",
+ mode="semantic_and_vectors",
+ counters=counters,
+ ctx=ctx,
+ )
+
+ assert seen["semantic"] == [("viking://user/default/memories", "memory")]
+ assert seen["vectors"] == ["viking://user/default/memories"]
+
+
+async def test_reindex_executor_infers_skill_supports_semantic_and_vectors():
+ from openviking.service.reindex_executor import ReindexExecutor
+
+ service = ReindexExecutor()
+ service._validate_mode("skill", "semantic_and_vectors")
+ service._validate_mode("skill_namespace", "semantic_and_vectors")
+
+
+async def test_reindex_executor_infers_resource_and_skill_container_scopes():
+ from openviking.service.reindex_executor import ReindexExecutor
+
+ service = ReindexExecutor()
+
+ assert service._infer_target_type("viking://resources") == "resource"
+ assert service._infer_target_type("viking://resources/demo.md") == "resource"
+ assert service._infer_target_type("viking://agent/default/skills") == "skill_namespace"
+ assert service._infer_target_type("viking://agent/default/skills/demo") == "skill"
+ with pytest.raises(OpenVikingError, match="Unsupported reindex URI"):
+ service._infer_target_type("viking://agent/default/skills/demo/SKILL.md")
+
+
+async def test_reindex_executor_infers_user_namespace_root():
+ from openviking.service.reindex_executor import ReindexExecutor
+
+ service = ReindexExecutor()
+
+ assert service._infer_target_type("viking://user/") == "user_namespace"
+ assert service._infer_target_type("viking://user/default") == "user_namespace"
+
+
+async def test_reindex_executor_infers_agent_namespace_root():
+ from openviking.service.reindex_executor import ReindexExecutor
+
+ service = ReindexExecutor()
+
+ assert service._infer_target_type("viking://agent/") == "agent_namespace"
+ assert service._infer_target_type("viking://agent/default") == "agent_namespace"
+
+
+async def test_reindex_executor_infers_global_namespace_root():
+ from openviking.service.reindex_executor import ReindexExecutor
+
+ service = ReindexExecutor()
+
+ assert service._infer_target_type("viking://") == "global_namespace"
+
+
+async def test_reindex_executor_does_not_treat_resource_named_memories_as_memory():
+ from openviking.core.namespace import classify_uri
+ from openviking.service.reindex_executor import ReindexExecutor
+
+ service = ReindexExecutor()
+
+ assert (
+ service._infer_target_type("viking://user/default/resources/memories/report.md")
+ == "resource"
+ )
+ assert not classify_uri("viking://user/default/resources/memories-report.md").is_memory
+ assert not classify_uri("viking://agent/default/resources/memories-report.md").is_memory
+
+
+async def test_reindex_executor_does_not_treat_skill_subdirectories_as_skill_roots():
+ from openviking.core.namespace import classify_uri
+
+ assert classify_uri("viking://agent/default/skills/my_skill").is_skill_root
+ assert not classify_uri("viking://agent/default/skills/my_skill/assets").is_skill_root
+ assert not classify_uri("viking://agent/default/resources/skills-report.md").is_skill
+
+
+async def test_reindex_user_namespace_semantic_and_vectors_promotes_memory_mode(monkeypatch):
+ from openviking.service.reindex_executor import ReindexExecutor, _ReindexCounters
+
+ class FakeVikingFS:
+ async def tree(
+ self,
+ uri,
+ output="original",
+ show_all_hidden=True,
+ node_limit=1000,
+ level_limit=None,
+ ctx=None,
+ ):
+ return [
+ {"uri": "viking://user/default/memories", "isDir": True},
+ {"uri": "viking://user/default/resources", "isDir": True},
+ ]
+
+ seen = {"memory_modes": [], "semantic_calls": [], "resource_calls": []}
+
+ async def fake_reindex_memory(self, *, uri, mode, counters, ctx):
+ seen["memory_modes"].append((uri, mode))
+
+ async def fake_run_semantic_processor(self, *, uri, context_type, ctx):
+ seen["semantic_calls"].append((uri, context_type))
+
+ async def fake_reindex_resource_vectors_from_entries(
+ self, *, root_uri, directories, files, counters, ctx
+ ):
+ seen["resource_calls"].append((root_uri, list(directories), list(files)))
+
+ monkeypatch.setattr("openviking.service.reindex_executor.get_viking_fs", lambda: FakeVikingFS())
+ monkeypatch.setattr(ReindexExecutor, "_reindex_memory", fake_reindex_memory)
+ monkeypatch.setattr(ReindexExecutor, "_run_semantic_processor", fake_run_semantic_processor)
+ monkeypatch.setattr(
+ ReindexExecutor,
+ "_reindex_resource_vectors_from_entries",
+ fake_reindex_resource_vectors_from_entries,
+ )
+
+ service = ReindexExecutor()
+ counters = _ReindexCounters()
+ ctx = RequestContext(
+ user=UserIdentifier(account_id="test", user_id="alice", agent_id="default"),
+ role=Role.ROOT,
+ )
+
+ await service._reindex_user_namespace(
+ uri="viking://user/default",
+ mode="semantic_and_vectors",
+ counters=counters,
+ ctx=ctx,
+ )
+
+ assert seen["memory_modes"] == [("viking://user/default/memories", "semantic_and_vectors")]
+ assert seen["semantic_calls"] == [("viking://user/default/resources", "resource")]
+ assert seen["resource_calls"]
+
+
+async def test_reindex_user_namespace_semantic_and_vectors_does_not_reprocess_memory_as_resource(
+ monkeypatch,
+):
+ from openviking.service.reindex_executor import ReindexExecutor, _ReindexCounters
+
+ class FakeVikingFS:
+ async def tree(
+ self,
+ uri,
+ output="original",
+ show_all_hidden=True,
+ node_limit=1000,
+ level_limit=None,
+ ctx=None,
+ ):
+ return [
+ {"uri": "viking://user/default/memories", "isDir": True},
+ {"uri": "viking://user/default/memories/preferences", "isDir": True},
+ {"uri": "viking://user/default/resources", "isDir": True},
+ ]
+
+ seen = {"memory_modes": [], "semantic_calls": []}
+
+ async def fake_reindex_memory(self, *, uri, mode, counters, ctx):
+ seen["memory_modes"].append((uri, mode))
+
+ async def fake_run_semantic_processor(self, *, uri, context_type, ctx):
+ seen["semantic_calls"].append((uri, context_type))
+
+ async def fake_reindex_resource_vectors_from_entries(
+ self, *, root_uri, directories, files, counters, ctx
+ ):
+ return None
+
+ monkeypatch.setattr("openviking.service.reindex_executor.get_viking_fs", lambda: FakeVikingFS())
+ monkeypatch.setattr(ReindexExecutor, "_reindex_memory", fake_reindex_memory)
+ monkeypatch.setattr(ReindexExecutor, "_run_semantic_processor", fake_run_semantic_processor)
+ monkeypatch.setattr(
+ ReindexExecutor,
+ "_reindex_resource_vectors_from_entries",
+ fake_reindex_resource_vectors_from_entries,
+ )
+
+ service = ReindexExecutor()
+ counters = _ReindexCounters()
+ ctx = RequestContext(
+ user=UserIdentifier(account_id="test", user_id="alice", agent_id="default"),
+ role=Role.ROOT,
+ )
+
+ await service._reindex_user_namespace(
+ uri="viking://user/default",
+ mode="semantic_and_vectors",
+ counters=counters,
+ ctx=ctx,
+ )
+
+ assert seen["memory_modes"] == [("viking://user/default/memories", "semantic_and_vectors")]
+ assert seen["semantic_calls"] == [("viking://user/default/resources", "resource")]
+
+
+async def test_reindex_user_namespace_semantic_and_vectors_skips_uncovered_root_files(
+ monkeypatch,
+):
+ from openviking.service.reindex_executor import ReindexExecutor, _ReindexCounters
+
+ class FakeVikingFS:
+ async def tree(
+ self,
+ uri,
+ output="original",
+ show_all_hidden=True,
+ node_limit=1000,
+ level_limit=None,
+ ctx=None,
+ ):
+ return [
+ {"uri": "viking://user/default/resources", "isDir": True},
+ {"uri": "viking://user/default/resources/doc.md", "isDir": False},
+ {"uri": "viking://user/default/profile.md", "isDir": False},
+ ]
+
+ seen = {"semantic_calls": [], "resource_files": []}
+
+ async def fake_run_semantic_processor(self, *, uri, context_type, ctx):
+ seen["semantic_calls"].append((uri, context_type))
+
+ async def fake_reindex_resource_vectors_from_entries(
+ self, *, root_uri, directories, files, counters, ctx
+ ):
+ seen["resource_files"] = list(files)
+
+ monkeypatch.setattr("openviking.service.reindex_executor.get_viking_fs", lambda: FakeVikingFS())
+ monkeypatch.setattr(ReindexExecutor, "_run_semantic_processor", fake_run_semantic_processor)
+ monkeypatch.setattr(
+ ReindexExecutor,
+ "_reindex_resource_vectors_from_entries",
+ fake_reindex_resource_vectors_from_entries,
+ )
+
+ service = ReindexExecutor()
+ counters = _ReindexCounters()
+ ctx = RequestContext(
+ user=UserIdentifier(account_id="test", user_id="alice", agent_id="default"),
+ role=Role.ROOT,
+ )
+
+ await service._reindex_user_namespace(
+ uri="viking://user/default",
+ mode="semantic_and_vectors",
+ counters=counters,
+ ctx=ctx,
+ )
+
+ assert seen["semantic_calls"] == [("viking://user/default/resources", "resource")]
+ assert seen["resource_files"] == ["viking://user/default/resources/doc.md"]
+ assert counters.unsupported_records == 1
+ assert "viking://user/default/profile.md" in counters.warnings[0]
+
+
+async def test_reindex_agent_namespace_semantic_and_vectors_promotes_memory_and_skill_modes(
+ monkeypatch,
+):
+ from openviking.service.reindex_executor import ReindexExecutor, _ReindexCounters
+
+ class FakeVikingFS:
+ async def tree(
+ self,
+ uri,
+ output="original",
+ show_all_hidden=True,
+ node_limit=1000,
+ level_limit=None,
+ ctx=None,
+ ):
+ return [
+ {"uri": "viking://agent/default/memories", "isDir": True},
+ {"uri": "viking://agent/default/skills/demo", "isDir": True},
+ {"uri": "viking://agent/default/resources", "isDir": True},
+ ]
+
+ seen = {"memory_modes": [], "skill_modes": [], "semantic_calls": [], "resource_calls": []}
+
+ async def fake_reindex_memory(self, *, uri, mode, counters, ctx):
+ seen["memory_modes"].append((uri, mode))
+
+ async def fake_reindex_skill(self, *, uri, mode, counters, ctx):
+ seen["skill_modes"].append((uri, mode))
+
+ async def fake_run_semantic_processor(self, *, uri, context_type, ctx):
+ seen["semantic_calls"].append((uri, context_type))
+
+ async def fake_reindex_resource_vectors_from_entries(
+ self, *, root_uri, directories, files, counters, ctx
+ ):
+ seen["resource_calls"].append((root_uri, list(directories), list(files)))
+
+ monkeypatch.setattr("openviking.service.reindex_executor.get_viking_fs", lambda: FakeVikingFS())
+ monkeypatch.setattr(ReindexExecutor, "_reindex_memory", fake_reindex_memory)
+ monkeypatch.setattr(ReindexExecutor, "_reindex_skill", fake_reindex_skill)
+ monkeypatch.setattr(ReindexExecutor, "_run_semantic_processor", fake_run_semantic_processor)
+ monkeypatch.setattr(
+ ReindexExecutor,
+ "_reindex_resource_vectors_from_entries",
+ fake_reindex_resource_vectors_from_entries,
+ )
+
+ service = ReindexExecutor()
+ counters = _ReindexCounters()
+ ctx = RequestContext(
+ user=UserIdentifier(account_id="test", user_id="alice", agent_id="default"),
+ role=Role.ROOT,
+ )
+
+ await service._reindex_agent_namespace(
+ uri="viking://agent/default",
+ mode="semantic_and_vectors",
+ counters=counters,
+ ctx=ctx,
+ )
+
+ assert seen["memory_modes"] == [("viking://agent/default/memories", "semantic_and_vectors")]
+ assert seen["skill_modes"] == [("viking://agent/default/skills/demo", "semantic_and_vectors")]
+ assert seen["semantic_calls"] == [("viking://agent/default/resources", "resource")]
+ assert seen["resource_calls"]
+
+
+async def test_reindex_agent_namespace_semantic_and_vectors_does_not_reprocess_memory_as_resource(
+ monkeypatch,
+):
+ from openviking.service.reindex_executor import ReindexExecutor, _ReindexCounters
+
+ class FakeVikingFS:
+ async def tree(
+ self,
+ uri,
+ output="original",
+ show_all_hidden=True,
+ node_limit=1000,
+ level_limit=None,
+ ctx=None,
+ ):
+ return [
+ {"uri": "viking://agent/default/memories", "isDir": True},
+ {"uri": "viking://agent/default/memories/cases", "isDir": True},
+ {"uri": "viking://agent/default/skills/demo", "isDir": True},
+ {"uri": "viking://agent/default/resources", "isDir": True},
+ ]
+
+ seen = {"memory_modes": [], "skill_modes": [], "semantic_calls": []}
+
+ async def fake_reindex_memory(self, *, uri, mode, counters, ctx):
+ seen["memory_modes"].append((uri, mode))
+
+ async def fake_reindex_skill(self, *, uri, mode, counters, ctx):
+ seen["skill_modes"].append((uri, mode))
+
+ async def fake_run_semantic_processor(self, *, uri, context_type, ctx):
+ seen["semantic_calls"].append((uri, context_type))
+
+ async def fake_reindex_resource_vectors_from_entries(
+ self, *, root_uri, directories, files, counters, ctx
+ ):
+ return None
+
+ monkeypatch.setattr("openviking.service.reindex_executor.get_viking_fs", lambda: FakeVikingFS())
+ monkeypatch.setattr(ReindexExecutor, "_reindex_memory", fake_reindex_memory)
+ monkeypatch.setattr(ReindexExecutor, "_reindex_skill", fake_reindex_skill)
+ monkeypatch.setattr(ReindexExecutor, "_run_semantic_processor", fake_run_semantic_processor)
+ monkeypatch.setattr(
+ ReindexExecutor,
+ "_reindex_resource_vectors_from_entries",
+ fake_reindex_resource_vectors_from_entries,
+ )
+
+ service = ReindexExecutor()
+ counters = _ReindexCounters()
+ ctx = RequestContext(
+ user=UserIdentifier(account_id="test", user_id="alice", agent_id="default"),
+ role=Role.ROOT,
+ )
+
+ await service._reindex_agent_namespace(
+ uri="viking://agent/default",
+ mode="semantic_and_vectors",
+ counters=counters,
+ ctx=ctx,
+ )
+
+ assert seen["memory_modes"] == [("viking://agent/default/memories", "semantic_and_vectors")]
+ assert seen["skill_modes"] == [("viking://agent/default/skills/demo", "semantic_and_vectors")]
+ assert seen["semantic_calls"] == [("viking://agent/default/resources", "resource")]
+
+
+async def test_reindex_skill_namespace_reindexes_only_skill_roots(monkeypatch):
+ from openviking.service.reindex_executor import ReindexExecutor, _ReindexCounters
+
+ class FakeVikingFS:
+ async def tree(
+ self,
+ uri,
+ output="original",
+ show_all_hidden=True,
+ node_limit=1000,
+ level_limit=3,
+ ctx=None,
+ ):
+ assert node_limit is None
+ assert level_limit is None
+ return [
+ {"uri": "viking://agent/default/skills/my_skill", "isDir": True},
+ {"uri": "viking://agent/default/skills/my_skill/assets", "isDir": True},
+ {"uri": "viking://agent/default/skills/my_skill/SKILL.md", "isDir": False},
+ ]
+
+ seen = []
+
+ async def fake_reindex_skill(self, *, uri, mode, counters, ctx):
+ seen.append((uri, mode))
+
+ monkeypatch.setattr("openviking.service.reindex_executor.get_viking_fs", lambda: FakeVikingFS())
+ monkeypatch.setattr(ReindexExecutor, "_reindex_skill", fake_reindex_skill)
+
+ service = ReindexExecutor()
+ counters = _ReindexCounters()
+ ctx = RequestContext(
+ user=UserIdentifier(account_id="test", user_id="alice", agent_id="default"),
+ role=Role.ROOT,
+ )
+
+ await service._reindex_skill_namespace(
+ uri="viking://agent/default/skills",
+ mode="semantic_and_vectors",
+ counters=counters,
+ ctx=ctx,
+ )
+
+ assert seen == [("viking://agent/default/skills/my_skill", "semantic_and_vectors")]
+
+
+async def test_reindex_global_namespace_semantic_and_vectors_propagates_to_child_namespaces(
+ monkeypatch,
+):
+ from openviking.service.reindex_executor import ReindexExecutor, _ReindexCounters
+
+ class FakeVikingFS:
+ async def tree(
+ self,
+ uri,
+ output="original",
+ show_all_hidden=True,
+ node_limit=1000,
+ level_limit=None,
+ ctx=None,
+ ):
+ return [
+ {"uri": "viking://user/default", "isDir": True},
+ {"uri": "viking://agent/default", "isDir": True},
+ {"uri": "viking://resources", "isDir": True},
+ ]
+
+ seen = {"user_modes": [], "agent_modes": [], "semantic_calls": [], "resource_calls": []}
+
+ async def fake_reindex_user_namespace(self, *, uri, mode, counters, ctx):
+ seen["user_modes"].append((uri, mode))
+
+ async def fake_reindex_agent_namespace(self, *, uri, mode, counters, ctx):
+ seen["agent_modes"].append((uri, mode))
+
+ async def fake_run_semantic_processor(self, *, uri, context_type, ctx):
+ seen["semantic_calls"].append((uri, context_type))
+
+ async def fake_reindex_resource_vectors_from_entries(
+ self, *, root_uri, directories, files, counters, ctx
+ ):
+ seen["resource_calls"].append((root_uri, list(directories), list(files)))
+
+ monkeypatch.setattr("openviking.service.reindex_executor.get_viking_fs", lambda: FakeVikingFS())
+ monkeypatch.setattr(ReindexExecutor, "_reindex_user_namespace", fake_reindex_user_namespace)
+ monkeypatch.setattr(ReindexExecutor, "_reindex_agent_namespace", fake_reindex_agent_namespace)
+ monkeypatch.setattr(ReindexExecutor, "_run_semantic_processor", fake_run_semantic_processor)
+ monkeypatch.setattr(
+ ReindexExecutor,
+ "_reindex_resource_vectors_from_entries",
+ fake_reindex_resource_vectors_from_entries,
+ )
+
+ service = ReindexExecutor()
+ counters = _ReindexCounters()
+ ctx = RequestContext(
+ user=UserIdentifier(account_id="test", user_id="alice", agent_id="default"),
+ role=Role.ROOT,
+ )
+
+ await service._reindex_global_namespace(
+ uri="viking://",
+ mode="semantic_and_vectors",
+ counters=counters,
+ ctx=ctx,
+ )
+
+ assert seen["user_modes"] == [("viking://user/default", "semantic_and_vectors")]
+ assert seen["agent_modes"] == [("viking://agent/default", "semantic_and_vectors")]
+ assert seen["semantic_calls"] == [("viking://resources", "resource")]
+ assert seen["resource_calls"]
+
+
+async def test_reindex_fetch_existing_record_uses_get_context_by_uri(monkeypatch):
+ from openviking.service.reindex_executor import ReindexExecutor
+
+ class FakeVikingDB:
+ def __init__(self):
+ self.fetch_calls = []
+ self.lookup_calls = []
+
+ async def fetch_by_uri(self, uri, *, ctx):
+ self.fetch_calls.append((uri, ctx))
+ return {"uri": uri, "level": 2, "abstract": "from-fetch"}
+
+ async def get_context_by_uri(self, uri, owner_space=None, level=None, limit=1, *, ctx=None):
+ self.lookup_calls.append((uri, owner_space, level, limit, ctx))
+ return [{"uri": uri, "level": level, "abstract": "from-lookup"}]
+
+ fake_service = type("Svc", (), {"vikingdb_manager": FakeVikingDB()})()
+ monkeypatch.setattr("openviking.service.reindex_executor.get_service", lambda: fake_service)
+
+ service = ReindexExecutor()
+ ctx = RequestContext(
+ user=UserIdentifier(account_id="test", user_id="alice", agent_id="default"),
+ role=Role.ROOT,
+ )
+
+ record = await service._fetch_existing_record(
+ uri="viking://resources/demo.txt",
+ level=2,
+ ctx=ctx,
+ )
+
+ assert record["abstract"] == "from-lookup"
+ assert not fake_service.vikingdb_manager.fetch_calls
+ assert fake_service.vikingdb_manager.lookup_calls
+
+
+async def test_reindex_resource_vectors_only_continues_after_single_record_failure(monkeypatch):
+ from openviking.service.reindex_executor import ReindexExecutor, _ReindexCounters
+ from openviking_cli.exceptions import OpenVikingError
+
+ class FakeVikingFS:
+ async def exists(self, uri, ctx=None):
+ return True
+
+ async def stat(self, uri, ctx=None):
+ return {"isDir": True}
+
+ async def tree(
+ self,
+ uri,
+ output="original",
+ show_all_hidden=True,
+ node_limit=1000,
+ level_limit=3,
+ ctx=None,
+ ):
+ assert node_limit is None
+ assert level_limit is None
+ return [
+ {"uri": "viking://resources/demo/bad.txt", "isDir": False},
+ {"uri": "viking://resources/demo/good.txt", "isDir": False},
+ ]
+
+ async def fake_read_directory_abstract(self, uri, *, ctx):
+ return ""
+
+ async def fake_read_directory_overview(self, uri, *, ctx):
+ return ""
+
+ async def fake_best_file_summary(self, uri, *, ctx):
+ return f"summary:{uri.rsplit('/', 1)[-1]}"
+
+ async def fake_best_resource_file_vector_text(self, uri, summary, ctx):
+ return summary
+
+ seen = []
+
+ async def fake_upsert_context(self, **kwargs):
+ seen.append(kwargs["uri"])
+ if kwargs["uri"].endswith("bad.txt"):
+ raise OpenVikingError("boom", code="PROCESSING_ERROR")
+
+ monkeypatch.setattr("openviking.service.reindex_executor.get_viking_fs", lambda: FakeVikingFS())
+ monkeypatch.setattr(ReindexExecutor, "_read_directory_abstract", fake_read_directory_abstract)
+ monkeypatch.setattr(ReindexExecutor, "_read_directory_overview", fake_read_directory_overview)
+ monkeypatch.setattr(ReindexExecutor, "_best_file_summary", fake_best_file_summary)
+ monkeypatch.setattr(
+ ReindexExecutor,
+ "_best_resource_file_vector_text",
+ fake_best_resource_file_vector_text,
+ )
+ monkeypatch.setattr(ReindexExecutor, "_upsert_context", fake_upsert_context)
+
+ service = ReindexExecutor()
+ counters = _ReindexCounters()
+ ctx = RequestContext(
+ user=UserIdentifier(account_id="test", user_id="alice", agent_id="default"),
+ role=Role.ROOT,
+ )
+
+ await service._reindex_resource_vectors(
+ uri="viking://resources/demo",
+ counters=counters,
+ ctx=ctx,
+ )
+
+ assert seen == [
+ "viking://resources/demo/bad.txt",
+ "viking://resources/demo/good.txt",
+ ]
+ assert counters.failed_records == 1
+ assert counters.rebuilt_records == 1
+
+
+async def test_reindex_semantic_processor_runs_with_skip_vectorization(monkeypatch):
+ from openviking.service.reindex_executor import ReindexExecutor
+
+ seen = {}
+
+ class FakeSemanticProcessor:
+ async def on_dequeue(self, payload):
+ seen["payload"] = payload
+
+ monkeypatch.setattr(
+ "openviking.service.reindex_executor.SemanticProcessor",
+ FakeSemanticProcessor,
+ )
+
+ service = ReindexExecutor()
+ ctx = RequestContext(
+ user=UserIdentifier(account_id="test", user_id="alice", agent_id="default"),
+ role=Role.ROOT,
+ )
+
+ await service._run_semantic_processor(
+ uri="viking://resources/demo",
+ context_type="resource",
+ ctx=ctx,
+ )
+
+ import json
+
+ msg = json.loads(seen["payload"]["data"])
+ assert msg["skip_vectorization"] is True
+
+
+async def test_reindex_resource_l2_falls_back_to_vector_text_when_summary_missing(monkeypatch):
+ from openviking.service.reindex_executor import ReindexExecutor, _ReindexCounters
+
+ class FakeVikingFS:
+ async def exists(self, uri, ctx=None):
+ return True
+
+ async def stat(self, uri, ctx=None):
+ return {"isDir": True}
+
+ async def tree(
+ self,
+ uri,
+ output="original",
+ show_all_hidden=True,
+ node_limit=1000,
+ level_limit=3,
+ ctx=None,
+ ):
+ assert node_limit is None
+ assert level_limit is None
+ return [{"uri": "viking://resources/demo/file.txt", "isDir": False}]
+
+ seen = {}
+
+ async def fake_read_directory_abstract(self, uri, *, ctx):
+ return "skill abstract"
+
+ async def fake_read_directory_overview(self, uri, *, ctx):
+ return ""
+
+ async def fake_best_file_summary(self, uri, *, ctx):
+ return ""
+
+ async def fake_best_resource_file_vector_text(self, uri, summary, ctx):
+ return "raw file body"
+
+ async def fake_upsert_context(self, **kwargs):
+ seen[kwargs["uri"]] = kwargs
+
+ monkeypatch.setattr("openviking.service.reindex_executor.get_viking_fs", lambda: FakeVikingFS())
+ monkeypatch.setattr(ReindexExecutor, "_read_directory_abstract", fake_read_directory_abstract)
+ monkeypatch.setattr(ReindexExecutor, "_read_directory_overview", fake_read_directory_overview)
+ monkeypatch.setattr(ReindexExecutor, "_best_file_summary", fake_best_file_summary)
+ monkeypatch.setattr(
+ ReindexExecutor,
+ "_best_resource_file_vector_text",
+ fake_best_resource_file_vector_text,
+ )
+ monkeypatch.setattr(ReindexExecutor, "_upsert_context", fake_upsert_context)
+
+ service = ReindexExecutor()
+ counters = _ReindexCounters()
+ ctx = RequestContext(
+ user=UserIdentifier(account_id="test", user_id="alice", agent_id="default"),
+ role=Role.ROOT,
+ )
+
+ await service._reindex_resource_vectors(
+ uri="viking://resources/demo",
+ counters=counters,
+ ctx=ctx,
+ )
+
+ assert seen["viking://resources/demo/file.txt"]["abstract"] == "raw file body"
+
+
+async def test_reindex_resource_vector_text_uses_existing_record_for_non_text(monkeypatch):
+ from openviking.service.reindex_executor import ReindexExecutor
+
+ async def fake_safe_read_text(self, uri, *, ctx):
+ return "decoded binary payload"
+
+ async def fake_fetch_existing_record(self, *, uri, level, ctx):
+ return {"abstract": "existing image summary"}
+
+ monkeypatch.setattr(ReindexExecutor, "_safe_read_text", fake_safe_read_text)
+ monkeypatch.setattr(ReindexExecutor, "_fetch_existing_record", fake_fetch_existing_record)
+
+ service = ReindexExecutor()
+ ctx = RequestContext(
+ user=UserIdentifier(account_id="test", user_id="alice", agent_id="default"),
+ role=Role.ROOT,
+ )
+
+ vector_text = await service._best_resource_file_vector_text(
+ "viking://resources/demo/image.png",
+ "",
+ ctx=ctx,
+ )
+
+ assert vector_text == "existing image summary"
+
+
+async def test_reindex_resource_vector_text_skips_non_text_body_without_summary(monkeypatch):
+ from openviking.service.reindex_executor import ReindexExecutor
+
+ async def fail_if_content_read(self, uri, *, ctx):
+ raise AssertionError("non-text resource content should not be read for vector text")
+
+ async def fake_fetch_existing_record(self, *, uri, level, ctx):
+ return None
+
+ monkeypatch.setattr(ReindexExecutor, "_safe_read_text", fail_if_content_read)
+ monkeypatch.setattr(ReindexExecutor, "_fetch_existing_record", fake_fetch_existing_record)
+
+ service = ReindexExecutor()
+ ctx = RequestContext(
+ user=UserIdentifier(account_id="test", user_id="alice", agent_id="default"),
+ role=Role.ROOT,
+ )
+
+ vector_text = await service._best_resource_file_vector_text(
+ "viking://resources/demo/image.png",
+ "",
+ ctx=ctx,
+ )
+
+ assert vector_text == ""
+
+
+async def test_reindex_resource_vectors_accepts_single_file_uri(monkeypatch):
+ from openviking.service.reindex_executor import ReindexExecutor, _ReindexCounters
+
+ class FakeVikingFS:
+ async def exists(self, uri, ctx=None):
+ return True
+
+ async def stat(self, uri, ctx=None):
+ return {"isDir": False}
+
+ async def tree(self, *args, **kwargs):
+ raise AssertionError("single-file reindex should not call tree")
+
+ seen = {}
+
+ async def fake_best_file_summary(self, uri, *, ctx):
+ return "file summary"
+
+ async def fake_best_resource_file_vector_text(self, uri, summary, ctx):
+ return summary
+
+ async def fake_upsert_context(self, **kwargs):
+ seen[kwargs["uri"]] = kwargs
+
+ monkeypatch.setattr("openviking.service.reindex_executor.get_viking_fs", lambda: FakeVikingFS())
+ monkeypatch.setattr(ReindexExecutor, "_best_file_summary", fake_best_file_summary)
+ monkeypatch.setattr(
+ ReindexExecutor,
+ "_best_resource_file_vector_text",
+ fake_best_resource_file_vector_text,
+ )
+ monkeypatch.setattr(ReindexExecutor, "_upsert_context", fake_upsert_context)
+
+ service = ReindexExecutor()
+ counters = _ReindexCounters()
+ ctx = RequestContext(
+ user=UserIdentifier(account_id="test", user_id="alice", agent_id="default"),
+ role=Role.ROOT,
+ )
+
+ await service._reindex_resource_vectors(
+ uri="viking://resources/demo/file.txt",
+ counters=counters,
+ ctx=ctx,
+ )
+
+ assert list(seen) == ["viking://resources/demo/file.txt"]
+ assert counters.scanned_records == 1
+ assert counters.rebuilt_records == 1
+
+
+async def test_reindex_memory_l2_falls_back_to_body_when_abstract_missing(monkeypatch):
+ from openviking.service.reindex_executor import ReindexExecutor, _ReindexCounters
+
+ class FakeVikingFS:
+ async def exists(self, uri, ctx=None):
+ return True
+
+ async def stat(self, uri, ctx=None):
+ return {"isDir": False}
+
+ seen = {}
+
+ async def fake_safe_read_text(self, uri, *, ctx):
+ return "memory body text"
+
+ async def fake_fetch_existing_record(self, *, uri, level, ctx):
+ return None
+
+ async def fake_best_file_summary(self, uri, *, ctx):
+ return ""
+
+ async def fake_upsert_context(self, **kwargs):
+ seen[kwargs["uri"]] = kwargs
+
+ monkeypatch.setattr("openviking.service.reindex_executor.get_viking_fs", lambda: FakeVikingFS())
+ monkeypatch.setattr(ReindexExecutor, "_safe_read_text", fake_safe_read_text)
+ monkeypatch.setattr(ReindexExecutor, "_fetch_existing_record", fake_fetch_existing_record)
+ monkeypatch.setattr(ReindexExecutor, "_best_file_summary", fake_best_file_summary)
+ monkeypatch.setattr(ReindexExecutor, "_chunk_memory_body", lambda self, uri, body: [])
+ monkeypatch.setattr(ReindexExecutor, "_upsert_context", fake_upsert_context)
+
+ service = ReindexExecutor()
+ counters = _ReindexCounters()
+ ctx = RequestContext(
+ user=UserIdentifier(account_id="test", user_id="alice", agent_id="default"),
+ role=Role.ROOT,
+ )
+
+ await service._reindex_memory_vectors(
+ uri="viking://user/default/memories/events/item.md",
+ counters=counters,
+ ctx=ctx,
+ )
+
+ assert seen["viking://user/default/memories/events/item.md"]["abstract"] == "memory body text"
+
+
+async def test_reindex_memory_l2_strips_memory_fields_from_abstract(monkeypatch):
+ from openviking.service.reindex_executor import ReindexExecutor, _ReindexCounters
+
+ class FakeVikingFS:
+ async def exists(self, uri, ctx=None):
+ return True
+
+ async def stat(self, uri, ctx=None):
+ return {"isDir": False}
+
+ seen = {}
+ raw_body = (
+ "User has a preference for watermelon, as mentioned in the conversation: "
+ '\'我爱吃西瓜\'. <!-- MEMORY_FIELDS { "user": "user", "topic": "food_preference" } -->'
+ )
+
+ async def fake_safe_read_text(self, uri, *, ctx):
+ return raw_body
+
+ async def fake_fetch_existing_record(self, *, uri, level, ctx):
+ return None
+
+ async def fake_best_file_summary(self, uri, *, ctx):
+ return ""
+
+ async def fake_upsert_context(self, **kwargs):
+ seen[kwargs["uri"]] = kwargs
+
+ monkeypatch.setattr("openviking.service.reindex_executor.get_viking_fs", lambda: FakeVikingFS())
+ monkeypatch.setattr(ReindexExecutor, "_safe_read_text", fake_safe_read_text)
+ monkeypatch.setattr(ReindexExecutor, "_fetch_existing_record", fake_fetch_existing_record)
+ monkeypatch.setattr(ReindexExecutor, "_best_file_summary", fake_best_file_summary)
+ monkeypatch.setattr(ReindexExecutor, "_chunk_memory_body", lambda self, uri, body: [])
+ monkeypatch.setattr(ReindexExecutor, "_upsert_context", fake_upsert_context)
+
+ service = ReindexExecutor()
+ counters = _ReindexCounters()
+ ctx = RequestContext(
+ user=UserIdentifier(account_id="test", user_id="alice", agent_id="default"),
+ role=Role.ROOT,
+ )
+
+ await service._reindex_memory_vectors(
+ uri="viking://user/default/memories/preferences/food_preference.md",
+ counters=counters,
+ ctx=ctx,
+ )
+
+ assert (
+ seen["viking://user/default/memories/preferences/food_preference.md"]["abstract"]
+ == "User has a preference for watermelon, as mentioned in the conversation: '我爱吃西瓜'."
+ )
+ assert (
+ seen["viking://user/default/memories/preferences/food_preference.md"]["vector_text"]
+ == raw_body
+ )
+
+
+async def test_reindex_memory_vectors_walks_deep_subtree(monkeypatch):
+ from openviking.service.reindex_executor import ReindexExecutor, _ReindexCounters
+
+ class FakeVikingFS:
+ async def exists(self, uri, ctx=None):
+ return True
+
+ async def stat(self, uri, ctx=None):
+ return {"isDir": True}
+
+ async def tree(
+ self,
+ uri,
+ output="original",
+ show_all_hidden=False,
+ node_limit=1000,
+ level_limit=3,
+ ctx=None,
+ ):
+ if level_limit is not None:
+ return [
+ {"uri": "viking://user/default/memories/preferences/user", "isDir": True},
+ ]
+ return [
+ {"uri": "viking://user/default/memories/preferences/user", "isDir": True},
+ {
+ "uri": "viking://user/default/memories/preferences/user/food_preference.md",
+ "isDir": False,
+ },
+ ]
+
+ seen = {}
+
+ async def fake_safe_read_text(self, uri, *, ctx):
+ return "likes spicy food"
+
+ async def fake_fetch_existing_record(self, *, uri, level, ctx):
+ return None
+
+ async def fake_best_file_summary(self, uri, *, ctx):
+ return ""
+
+ async def fake_upsert_context(self, **kwargs):
+ seen[kwargs["uri"]] = kwargs
+
+ monkeypatch.setattr("openviking.service.reindex_executor.get_viking_fs", lambda: FakeVikingFS())
+ monkeypatch.setattr(ReindexExecutor, "_safe_read_text", fake_safe_read_text)
+ monkeypatch.setattr(ReindexExecutor, "_fetch_existing_record", fake_fetch_existing_record)
+ monkeypatch.setattr(ReindexExecutor, "_best_file_summary", fake_best_file_summary)
+ monkeypatch.setattr(ReindexExecutor, "_chunk_memory_body", lambda self, uri, body: [])
+ monkeypatch.setattr(ReindexExecutor, "_upsert_context", fake_upsert_context)
+
+ service = ReindexExecutor()
+ counters = _ReindexCounters()
+ ctx = RequestContext(
+ user=UserIdentifier(account_id="test", user_id="alice", agent_id="default"),
+ role=Role.ROOT,
+ )
+
+ await service._reindex_memory_vectors(
+ uri="viking://user/default/memories/preferences",
+ counters=counters,
+ ctx=ctx,
+ )
+
+ assert "viking://user/default/memories/preferences/user/food_preference.md" in seen
+
+
+async def test_reindex_memory_vectors_rebuilds_directory_levels_without_regenerating_semantics(
+ monkeypatch,
+):
+ from openviking.core.context import ContextLevel
+ from openviking.service.reindex_executor import ReindexExecutor, _ReindexCounters
+
+ class FakeVikingFS:
+ async def exists(self, uri, ctx=None):
+ return True
+
+ async def stat(self, uri, ctx=None):
+ return {"isDir": True}
+
+ async def tree(
+ self,
+ uri,
+ output="original",
+ show_all_hidden=False,
+ node_limit=1000,
+ level_limit=3,
+ ctx=None,
+ ):
+ return [
+ {"uri": "viking://user/default/memories/preferences/user", "isDir": True},
+ {
+ "uri": "viking://user/default/memories/preferences/user/food_preference.md",
+ "isDir": False,
+ },
+ ]
+
+ seen = []
+
+ async def fake_read_directory_abstract(self, uri, *, ctx):
+ if uri == "viking://user/default/memories/preferences/user":
+ return "user preferences abstract"
+ return ""
+
+ async def fake_read_directory_overview(self, uri, *, ctx):
+ if uri == "viking://user/default/memories/preferences":
+ return "preferences overview"
+ if uri == "viking://user/default/memories/preferences/user":
+ return "user preferences overview"
+ return ""
+
+ async def fake_safe_read_text(self, uri, *, ctx):
+ return "likes spicy food"
+
+ async def fake_fetch_existing_record(self, *, uri, level, ctx):
+ return None
+
+ async def fake_best_file_summary(self, uri, *, ctx):
+ return ""
+
+ async def fake_upsert_context(self, **kwargs):
+ seen.append(
+ {
+ "uri": kwargs["uri"],
+ "level": int(kwargs["level"]),
+ "vector_text": kwargs["vector_text"],
+ }
+ )
+
+ monkeypatch.setattr("openviking.service.reindex_executor.get_viking_fs", lambda: FakeVikingFS())
+ monkeypatch.setattr(ReindexExecutor, "_read_directory_abstract", fake_read_directory_abstract)
+ monkeypatch.setattr(ReindexExecutor, "_read_directory_overview", fake_read_directory_overview)
+ monkeypatch.setattr(ReindexExecutor, "_safe_read_text", fake_safe_read_text)
+ monkeypatch.setattr(ReindexExecutor, "_fetch_existing_record", fake_fetch_existing_record)
+ monkeypatch.setattr(ReindexExecutor, "_best_file_summary", fake_best_file_summary)
+ monkeypatch.setattr(ReindexExecutor, "_chunk_memory_body", lambda self, uri, body: [])
+ monkeypatch.setattr(ReindexExecutor, "_upsert_context", fake_upsert_context)
+
+ service = ReindexExecutor()
+ counters = _ReindexCounters()
+ ctx = RequestContext(
+ user=UserIdentifier(account_id="test", user_id="alice", agent_id="default"),
+ role=Role.ROOT,
+ )
+
+ await service._reindex_memory_vectors(
+ uri="viking://user/default/memories/preferences",
+ counters=counters,
+ ctx=ctx,
+ )
+
+ assert {
+ ("viking://user/default/memories/preferences", int(ContextLevel.OVERVIEW)),
+ ("viking://user/default/memories/preferences/user", int(ContextLevel.ABSTRACT)),
+ ("viking://user/default/memories/preferences/user", int(ContextLevel.OVERVIEW)),
+ (
+ "viking://user/default/memories/preferences/user/food_preference.md",
+ int(ContextLevel.DETAIL),
+ ),
+ } <= {(item["uri"], item["level"]) for item in seen}
+
+
+async def test_reindex_user_namespace_partitions_memory_and_resource(monkeypatch):
+ from openviking.service.reindex_executor import ReindexExecutor, _ReindexCounters
+
+ class FakeVikingFS:
+ async def tree(
+ self,
+ uri,
+ output="original",
+ show_all_hidden=True,
+ node_limit=1000,
+ level_limit=None,
+ ctx=None,
+ ):
+ return [
+ {"uri": "viking://user/default/memories", "isDir": True},
+ {"uri": "viking://user/default/memories/preferences", "isDir": True},
+ {"uri": "viking://user/default/resources", "isDir": True},
+ {"uri": "viking://user/default/resources/doc.md", "isDir": False},
+ {"uri": "viking://user/default/profile.md", "isDir": False},
+ {"uri": "viking://user/default/memories/preferences/theme.md", "isDir": False},
+ ]
+
+ seen = {"memory": [], "resource_dirs": [], "resource_files": []}
+
+ async def fake_reindex_memory(self, *, uri, mode, counters, ctx):
+ seen["memory"].append((uri, mode))
+
+ async def fake_reindex_resource_vectors_from_entries(
+ self,
+ *,
+ root_uri,
+ directories,
+ files,
+ counters,
+ ctx,
+ ):
+ seen["resource_dirs"] = list(directories)
+ seen["resource_files"] = list(files)
+
+ monkeypatch.setattr("openviking.service.reindex_executor.get_viking_fs", lambda: FakeVikingFS())
+ monkeypatch.setattr(ReindexExecutor, "_reindex_memory", fake_reindex_memory)
+ monkeypatch.setattr(
+ ReindexExecutor,
+ "_reindex_resource_vectors_from_entries",
+ fake_reindex_resource_vectors_from_entries,
+ )
+
+ service = ReindexExecutor()
+ counters = _ReindexCounters()
+ ctx = RequestContext(
+ user=UserIdentifier(account_id="test", user_id="alice", agent_id="default"),
+ role=Role.ROOT,
+ )
+
+ await service._reindex_user_namespace(
+ uri="viking://user/",
+ mode="vectors_only",
+ counters=counters,
+ ctx=ctx,
+ )
+
+ assert seen["memory"] == [("viking://user/default/memories", "vectors_only")]
+ assert "viking://user/default/resources" in seen["resource_dirs"]
+ assert "viking://user/default/memories" not in seen["resource_dirs"]
+ assert seen["resource_files"] == [
+ "viking://user/default/resources/doc.md",
+ "viking://user/default/profile.md",
+ ]
+
+
+async def test_reindex_agent_namespace_partitions_memory_skill_and_resource(monkeypatch):
+ from openviking.service.reindex_executor import ReindexExecutor, _ReindexCounters
+
+ class FakeVikingFS:
+ async def tree(
+ self,
+ uri,
+ output="original",
+ show_all_hidden=True,
+ node_limit=1000,
+ level_limit=None,
+ ctx=None,
+ ):
+ return [
+ {"uri": "viking://agent/default/memories", "isDir": True},
+ {"uri": "viking://agent/default/memories/cases", "isDir": True},
+ {"uri": "viking://agent/default/skills", "isDir": True},
+ {"uri": "viking://agent/default/skills/my_skill", "isDir": True},
+ {"uri": "viking://agent/default/resources", "isDir": True},
+ {"uri": "viking://agent/default/resources/doc.md", "isDir": False},
+ {"uri": "viking://agent/default/notes.md", "isDir": False},
+ {"uri": "viking://agent/default/memories/cases/a.md", "isDir": False},
+ {"uri": "viking://agent/default/skills/my_skill/SKILL.md", "isDir": False},
+ ]
+
+ seen = {"memory": [], "skill": [], "resource_dirs": [], "resource_files": []}
+
+ async def fake_reindex_memory(self, *, uri, mode, counters, ctx):
+ seen["memory"].append((uri, mode))
+
+ async def fake_reindex_skill(self, *, uri, mode, counters, ctx):
+ seen["skill"].append((uri, mode))
+
+ async def fake_reindex_resource_vectors_from_entries(
+ self,
+ *,
+ root_uri,
+ directories,
+ files,
+ counters,
+ ctx,
+ ):
+ seen["resource_dirs"] = list(directories)
+ seen["resource_files"] = list(files)
+
+ monkeypatch.setattr("openviking.service.reindex_executor.get_viking_fs", lambda: FakeVikingFS())
+ monkeypatch.setattr(ReindexExecutor, "_reindex_memory", fake_reindex_memory)
+ monkeypatch.setattr(ReindexExecutor, "_reindex_skill", fake_reindex_skill)
+ monkeypatch.setattr(
+ ReindexExecutor,
+ "_reindex_resource_vectors_from_entries",
+ fake_reindex_resource_vectors_from_entries,
+ )
+
+ service = ReindexExecutor()
+ counters = _ReindexCounters()
+ ctx = RequestContext(
+ user=UserIdentifier(account_id="test", user_id="alice", agent_id="default"),
+ role=Role.ROOT,
+ )
+
+ await service._reindex_agent_namespace(
+ uri="viking://agent/",
+ mode="vectors_only",
+ counters=counters,
+ ctx=ctx,
+ )
+
+ assert seen["memory"] == [("viking://agent/default/memories", "vectors_only")]
+ assert seen["skill"] == [("viking://agent/default/skills/my_skill", "vectors_only")]
+ assert "viking://agent/default/resources" in seen["resource_dirs"]
+ assert "viking://agent/default/memories" not in seen["resource_dirs"]
+ assert "viking://agent/default/skills" not in seen["resource_dirs"]
+ assert seen["resource_files"] == [
+ "viking://agent/default/resources/doc.md",
+ "viking://agent/default/notes.md",
+ ]
+
+
+async def test_reindex_global_namespace_partitions_user_agent_and_resources(monkeypatch):
+ from openviking.service.reindex_executor import ReindexExecutor, _ReindexCounters
+
+ class FakeVikingFS:
+ async def tree(
+ self,
+ uri,
+ output="original",
+ show_all_hidden=True,
+ node_limit=1000,
+ level_limit=None,
+ ctx=None,
+ ):
+ return [
+ {"uri": "viking://user", "isDir": True},
+ {"uri": "viking://user/default", "isDir": True},
+ {"uri": "viking://user/default/memories", "isDir": True},
+ {"uri": "viking://agent", "isDir": True},
+ {"uri": "viking://agent/default", "isDir": True},
+ {"uri": "viking://agent/default/skills", "isDir": True},
+ {"uri": "viking://session", "isDir": True},
+ {"uri": "viking://session/default", "isDir": True},
+ {"uri": "viking://resources", "isDir": True},
+ {"uri": "viking://session/default/archive.txt", "isDir": False},
+ {"uri": "viking://resources/demo.txt", "isDir": False},
+ {"uri": "viking://README.md", "isDir": False},
+ ]
+
+ seen = {"user": [], "agent": [], "resource_dirs": [], "resource_files": []}
+
+ async def fake_reindex_user_namespace(self, *, uri, mode, counters, ctx):
+ seen["user"].append((uri, mode))
+
+ async def fake_reindex_agent_namespace(self, *, uri, mode, counters, ctx):
+ seen["agent"].append((uri, mode))
+
+ async def fake_reindex_resource_vectors_from_entries(
+ self,
+ *,
+ root_uri,
+ directories,
+ files,
+ counters,
+ ctx,
+ ):
+ seen["resource_dirs"] = list(directories)
+ seen["resource_files"] = list(files)
+
+ monkeypatch.setattr("openviking.service.reindex_executor.get_viking_fs", lambda: FakeVikingFS())
+ monkeypatch.setattr(ReindexExecutor, "_reindex_user_namespace", fake_reindex_user_namespace)
+ monkeypatch.setattr(ReindexExecutor, "_reindex_agent_namespace", fake_reindex_agent_namespace)
+ monkeypatch.setattr(
+ ReindexExecutor,
+ "_reindex_resource_vectors_from_entries",
+ fake_reindex_resource_vectors_from_entries,
+ )
+
+ service = ReindexExecutor()
+ counters = _ReindexCounters()
+ ctx = RequestContext(
+ user=UserIdentifier(account_id="test", user_id="alice", agent_id="default"),
+ role=Role.ROOT,
+ )
+
+ await service._reindex_global_namespace(
+ uri="viking://",
+ mode="vectors_only",
+ counters=counters,
+ ctx=ctx,
+ )
+
+ assert seen["user"] == [("viking://user/default", "vectors_only")]
+ assert seen["agent"] == [("viking://agent/default", "vectors_only")]
+ assert "viking://resources" in seen["resource_dirs"]
+ assert "viking://" not in seen["resource_dirs"]
+ assert "viking://user" not in seen["resource_dirs"]
+ assert "viking://agent" not in seen["resource_dirs"]
+ assert "viking://session" not in seen["resource_dirs"]
+ assert "viking://session/default" not in seen["resource_dirs"]
+ assert seen["resource_files"] == ["viking://resources/demo.txt"]
+
+
+async def test_reindex_skill_l2_falls_back_to_skill_content_when_abstract_missing(monkeypatch):
+ from openviking.service.reindex_executor import ReindexExecutor, _ReindexCounters
+
+ class FakeVikingFS:
+ async def exists(self, uri, ctx=None):
+ return True
+
+ seen = {}
+
+ async def fake_read_directory_abstract(self, uri, *, ctx):
+ return "skill abstract"
+
+ async def fake_read_directory_overview(self, uri, *, ctx):
+ return ""
+
+ async def fake_fetch_existing_record(self, *, uri, level, ctx):
+ return None
+
+ async def fake_safe_read_text(self, uri, *, ctx):
+ return "# Skill Title\n\nDo things well."
+
+ async def fake_upsert_context(self, **kwargs):
+ seen[kwargs["uri"]] = kwargs
+
+ async def fake_skill_meta(self, *, uri, abstract, ctx):
+ return {"name": "my_skill", "description": abstract}
+
+ monkeypatch.setattr("openviking.service.reindex_executor.get_viking_fs", lambda: FakeVikingFS())
+ monkeypatch.setattr(ReindexExecutor, "_read_directory_abstract", fake_read_directory_abstract)
+ monkeypatch.setattr(ReindexExecutor, "_read_directory_overview", fake_read_directory_overview)
+ monkeypatch.setattr(ReindexExecutor, "_fetch_existing_record", fake_fetch_existing_record)
+ monkeypatch.setattr(ReindexExecutor, "_safe_read_text", fake_safe_read_text)
+ monkeypatch.setattr(ReindexExecutor, "_skill_meta", fake_skill_meta)
+ monkeypatch.setattr(ReindexExecutor, "_upsert_context", fake_upsert_context)
+
+ service = ReindexExecutor()
+ counters = _ReindexCounters()
+ ctx = RequestContext(
+ user=UserIdentifier(account_id="test", user_id="alice", agent_id="default"),
+ role=Role.ROOT,
+ )
+
+ await service._reindex_skill_vectors(
+ uri="viking://agent/skills/my_skill",
+ counters=counters,
+ ctx=ctx,
+ )
+
+ assert seen["viking://agent/skills/my_skill/SKILL.md"]["abstract"] == "skill abstract"
+
+
+async def test_openviking_service_reindex_uses_default_root_context(monkeypatch):
+ from openviking.service.core import OpenVikingService
+
+ seen = {}
+
+ class FakeExecutor:
+ async def execute(self, *, uri, mode, wait, ctx):
+ seen["uri"] = uri
+ seen["mode"] = mode
+ seen["wait"] = wait
+ seen["ctx"] = ctx
+ return {"status": "completed", "uri": uri}
+
+ import sys
+
+ monkeypatch.setattr(
+ sys.modules["openviking.service.reindex_executor"],
+ "get_reindex_executor",
+ lambda: FakeExecutor(),
+ )
+
+ service = OpenVikingService.__new__(OpenVikingService)
+ service._initialized = True
+ service._user = UserIdentifier(account_id="acct", user_id="alice", agent_id="assistant")
+
+ result = await OpenVikingService.reindex(
+ service,
+ uri="viking://resources/demo",
+ mode="vectors_only",
+ wait=True,
+ )
+
+ assert result == {"status": "completed", "uri": "viking://resources/demo"}
+ assert seen["ctx"].role == Role.ROOT
+ assert seen["ctx"].user.account_id == "acct"
+ assert seen["ctx"].user.user_id == "alice"
+ assert seen["ctx"].user.agent_id == "assistant"
diff --git a/tests/server/test_api_content.py b/tests/server/test_api_content.py
index b2d97de4e..5ee9eaba8 100644
--- a/tests/server/test_api_content.py
+++ b/tests/server/test_api_content.py
@@ -1,9 +1,7 @@
# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
# SPDX-License-Identifier: AGPL-3.0
-"""Tests for content endpoints: read, abstract, overview."""
-
-from types import SimpleNamespace
+"""Tests for content endpoints: read, abstract, overview, reindex."""
import pytest
@@ -97,12 +95,12 @@ async def test_overview_missing_uri_returns_not_found(client):
async def test_reindex_missing_uri(client):
- """Test reindex without uri field returns 422."""
+ """Test reindex without uri field returns structured INVALID_ARGUMENT."""
resp = await client.post(
"/api/v1/content/reindex",
- json={"regenerate": False},
+ json={"mode": "vectors_only"},
)
- assert resp.status_code == 422
+ assert resp.status_code == 400
async def test_reindex_endpoint_registered(client):
@@ -115,15 +113,14 @@ async def test_reindex_request_validation(client):
"""Test reindex validates the request body schema."""
# Empty body — uri is required
resp = await client.post("/api/v1/content/reindex", json={})
- assert resp.status_code == 422
+ assert resp.status_code == 400
- # Invalid type for regenerate
+ # Invalid mode should not be accepted by the endpoint
resp = await client.post(
"/api/v1/content/reindex",
- json={"uri": "viking://resources/test", "regenerate": "not_a_bool"},
+ json={"uri": "viking://resources/test", "mode": "not_a_mode"},
)
- # Pydantic coerces strings to bool, so this may or may not fail
- assert resp.status_code in (200, 422, 500)
+ assert resp.status_code in (200, 400)
async def test_reindex_wait_parameter_schema(client):
@@ -143,75 +140,46 @@ async def test_reindex_uses_request_tenant_for_exists(monkeypatch):
"""Reindex must validate URI existence inside the caller's tenant."""
seen = {}
- class FakeVikingFS:
- async def exists(self, uri, ctx=None):
+ class FakeService:
+ async def reindex(self, *, uri, mode, wait, ctx):
seen["uri"] = uri
+ seen["mode"] = mode
+ seen["wait"] = wait
seen["ctx"] = ctx
- return True
-
- class FakeTracker:
- def has_running(self, task_type, uri, owner_account_id=None, owner_user_id=None):
- return False
-
- async def fake_do_reindex(service, uri, regenerate, ctx):
- return {"status": "success", "message": "Indexed 1 resources"}
+ return {"status": "completed", "uri": uri, "mode": mode}
ctx = RequestContext(
user=UserIdentifier(account_id="test", user_id="alice", agent_id="default"),
role=Role.ADMIN,
)
- request = ReindexRequest(uri="viking://resources/demo/demo-note.md", wait=True)
-
- monkeypatch.setattr("openviking.storage.viking_fs.get_viking_fs", lambda: FakeVikingFS())
- monkeypatch.setattr(
- "openviking.service.task_tracker.get_task_tracker",
- lambda: FakeTracker(),
- )
- monkeypatch.setattr(
- "openviking.server.routers.content.get_service",
- lambda: SimpleNamespace(),
+ request = ReindexRequest(
+ uri="viking://resources/demo/demo-note.md",
+ mode="semantic_and_vectors",
+ wait=True,
)
- monkeypatch.setattr("openviking.server.routers.content._do_reindex", fake_do_reindex)
+
+ monkeypatch.setattr("openviking.server.routers.content.get_service", lambda: FakeService())
response = await reindex(body=request, ctx=ctx)
assert response.status == "ok"
assert seen["uri"] == "viking://resources/demo/demo-note.md"
+ assert seen["mode"] == "semantic_and_vectors"
+ assert seen["wait"] is True
assert seen["ctx"] == ctx
-async def test_maintenance_reindex_sync_success_returns_ok_payload(client, monkeypatch):
- async def fake_do_reindex(service, uri, regenerate, ctx):
- return {"status": "success", "message": "Indexed 1 resources"}
-
- class FakeVikingFS:
- async def exists(self, uri, ctx=None):
- return True
-
- class FakeTracker:
- def has_running(self, task_type, uri, owner_account_id=None, owner_user_id=None):
- return False
-
- monkeypatch.setattr(
- "openviking.storage.viking_fs.get_viking_fs",
- lambda: FakeVikingFS(),
- )
- monkeypatch.setattr(
- "openviking.service.task_tracker.get_task_tracker",
- lambda: FakeTracker(),
- )
- monkeypatch.setattr(
- "openviking.server.routers.maintenance.get_service",
- lambda: SimpleNamespace(),
+async def test_content_rebuild_endpoint_removed(client):
+ response = await client.post(
+ "/api/v1/content/rebuild",
+ json={"uri": "viking://resources/demo", "mode": "vectors_only"},
)
- monkeypatch.setattr("openviking.server.routers.maintenance._do_reindex", fake_do_reindex)
+ assert response.status_code == 404
+
+async def test_maintenance_reindex_endpoint_removed(client):
response = await client.post(
"/api/v1/maintenance/reindex",
json={"uri": "viking://resources/demo", "wait": True},
)
-
- assert response.status_code == 200
- body = response.json()
- assert body["status"] == "ok"
- assert body["result"]["status"] == "success"
+ assert response.status_code == 404
diff --git a/tests/server/test_api_fs_content_endpoint_suite.py b/tests/server/test_api_fs_content_endpoint_suite.py
index 0a2e84527..95c1bf2f4 100644
--- a/tests/server/test_api_fs_content_endpoint_suite.py
+++ b/tests/server/test_api_fs_content_endpoint_suite.py
@@ -197,150 +197,75 @@ async def test_write_permission_denied_returns_structured_error(app, service, mo
async def test_reindex_missing_uri_returns_not_found_error_payload(client, monkeypatch):
- monkeypatch.setattr(
- "openviking.storage.viking_fs.get_viking_fs",
- lambda: _FakeVikingFS(False),
- )
+ class FakeService:
+ async def reindex(self, *, uri, mode, wait, ctx):
+ from openviking_cli.exceptions import NotFoundError
+
+ raise NotFoundError(uri, "resource")
+
+ monkeypatch.setattr("openviking.server.routers.content.get_service", lambda: FakeService())
response = await client.post(
"/api/v1/content/reindex",
- json={"uri": "viking://resources/missing", "wait": True},
+ json={"uri": "viking://resources/missing", "mode": "vectors_only", "wait": True},
)
_assert_error(response, status_code=404, error_code="NOT_FOUND")
async def test_reindex_sync_conflict_returns_error_payload(client, monkeypatch):
- monkeypatch.setattr(
- "openviking.storage.viking_fs.get_viking_fs",
- lambda: _FakeVikingFS(True),
- )
- monkeypatch.setattr(
- "openviking.service.task_tracker.get_task_tracker",
- lambda: _FakeTracker(has_running=True),
- )
- monkeypatch.setattr(
- "openviking.server.routers.content.get_service",
- lambda: SimpleNamespace(),
- )
- response = await client.post(
- "/api/v1/content/reindex",
- json={"uri": "viking://resources/conflict", "wait": True},
- )
- _assert_error(response, status_code=409, error_code="CONFLICT")
+ class FakeService:
+ async def reindex(self, *, uri, mode, wait, ctx):
+ from openviking_cli.exceptions import OpenVikingError
+ raise OpenVikingError(
+ f"URI {uri} already has a reindex in progress",
+ code="CONFLICT",
+ details={"uri": uri},
+ )
-async def test_reindex_sync_business_error_returns_error_envelope(client, monkeypatch):
- async def fake_do_reindex(service, uri, regenerate, ctx):
- return {"status": "error", "message": "bad summarize"}
-
- monkeypatch.setattr(
- "openviking.storage.viking_fs.get_viking_fs",
- lambda: _FakeVikingFS(True),
- )
- monkeypatch.setattr(
- "openviking.service.task_tracker.get_task_tracker",
- lambda: _FakeTracker(has_running=False),
- )
- monkeypatch.setattr(
- "openviking.server.routers.content.get_service",
- lambda: SimpleNamespace(),
- )
- monkeypatch.setattr("openviking.server.routers.content._do_reindex", fake_do_reindex)
+ monkeypatch.setattr("openviking.server.routers.content.get_service", lambda: FakeService())
response = await client.post(
"/api/v1/content/reindex",
- json={"uri": "viking://resources/demo", "wait": True, "regenerate": True},
- )
- _assert_error(
- response,
- status_code=500,
- error_code="PROCESSING_ERROR",
- message_fragment="bad summarize",
- )
-
-
-async def test_maintenance_reindex_sync_business_error_returns_error_envelope(client, monkeypatch):
- async def fake_do_reindex(service, uri, regenerate, ctx):
- return {"status": "error", "message": "bad maintenance summarize"}
-
- monkeypatch.setattr(
- "openviking.storage.viking_fs.get_viking_fs",
- lambda: _FakeVikingFS(True),
- )
- monkeypatch.setattr(
- "openviking.service.task_tracker.get_task_tracker",
- lambda: _FakeTracker(has_running=False),
- )
- monkeypatch.setattr(
- "openviking.server.routers.maintenance.get_service",
- lambda: SimpleNamespace(),
- )
- monkeypatch.setattr("openviking.server.routers.maintenance._do_reindex", fake_do_reindex)
- response = await client.post(
- "/api/v1/maintenance/reindex",
- json={"uri": "viking://resources/demo", "wait": True, "regenerate": True},
- )
- _assert_error(
- response,
- status_code=500,
- error_code="PROCESSING_ERROR",
- message_fragment="bad maintenance summarize",
+ json={"uri": "viking://resources/conflict", "mode": "vectors_only", "wait": True},
)
+ _assert_error(response, status_code=409, error_code="CONFLICT")
async def test_reindex_sync_success_returns_ok_payload(client, monkeypatch):
- async def fake_do_reindex(service, uri, regenerate, ctx):
- return {"status": "success", "message": "Indexed 1 resources"}
+ class FakeService:
+ async def reindex(self, *, uri, mode, wait, ctx):
+ return {"status": "completed", "mode": mode, "uri": uri}
- monkeypatch.setattr(
- "openviking.storage.viking_fs.get_viking_fs",
- lambda: _FakeVikingFS(True),
- )
- monkeypatch.setattr(
- "openviking.service.task_tracker.get_task_tracker",
- lambda: _FakeTracker(has_running=False),
- )
- monkeypatch.setattr(
- "openviking.server.routers.content.get_service",
- lambda: SimpleNamespace(),
- )
- monkeypatch.setattr("openviking.server.routers.content._do_reindex", fake_do_reindex)
+ monkeypatch.setattr("openviking.server.routers.content.get_service", lambda: FakeService())
response = await client.post(
"/api/v1/content/reindex",
- json={"uri": "viking://resources/demo", "wait": True},
+ json={"uri": "viking://resources/demo", "mode": "semantic_and_vectors", "wait": True},
)
assert response.status_code == 200
body = response.json()
assert body["status"] == "ok"
- assert body["result"]["status"] == "success"
+ assert body["result"]["status"] == "completed"
+ assert body["result"]["mode"] == "semantic_and_vectors"
async def test_reindex_async_returns_task_id(client, monkeypatch):
- created = {"called": False}
-
- def fake_create_task(coro):
- created["called"] = True
- coro.close()
- return None
-
- monkeypatch.setattr(
- "openviking.storage.viking_fs.get_viking_fs",
- lambda: _FakeVikingFS(True),
- )
- monkeypatch.setattr(
- "openviking.service.task_tracker.get_task_tracker",
- lambda: _FakeTracker(task_id="task-123"),
- )
- monkeypatch.setattr(
- "openviking.server.routers.content.get_service",
- lambda: SimpleNamespace(),
- )
- monkeypatch.setattr("openviking.server.routers.content.asyncio.create_task", fake_create_task)
+ class FakeService:
+ async def reindex(self, *, uri, mode, wait, ctx):
+ return {
+ "task_id": "task-123",
+ "status": "accepted",
+ "uri": uri,
+ "object_type": "resource",
+ "mode": mode,
+ }
+
+ monkeypatch.setattr("openviking.server.routers.content.get_service", lambda: FakeService())
response = await client.post(
"/api/v1/content/reindex",
- json={"uri": "viking://resources/demo", "wait": False},
+ json={"uri": "viking://resources/demo", "mode": "vectors_only", "wait": False},
)
assert response.status_code == 200
body = response.json()
assert body["status"] == "ok"
assert body["result"]["status"] == "accepted"
assert body["result"]["task_id"] == "task-123"
- assert created["called"] is True
+ assert body["result"]["mode"] == "vectors_only"
diff --git a/tests/server/test_auth.py b/tests/server/test_auth.py
index cc8cb8096..c14337501 100644
--- a/tests/server/test_auth.py
+++ b/tests/server/test_auth.py
@@ -564,6 +564,31 @@ async def test_root_tenant_scoped_requests_allow_explicit_identity():
assert ctx.user.user_id == "alice"
+async def test_root_reindex_requests_require_explicit_account():
+ """ROOT reindex must select an account because indexes are account-scoped."""
+ request = _make_request("/api/v1/content/reindex", auth_enabled=True)
+ identity = ResolvedIdentity(role=Role.ROOT, account_id="default", user_id="default")
+
+ with pytest.raises(InvalidArgumentError, match="X-OpenViking-Account"):
+ await get_request_context(request, identity)
+
+
+async def test_root_reindex_requests_allow_account_without_user():
+ """ROOT reindex is account-scoped and does not require a user header."""
+ request = _make_request(
+ "/api/v1/content/reindex",
+ headers={"X-OpenViking-Account": "acme"},
+ auth_enabled=True,
+ )
+ identity = ResolvedIdentity(role=Role.ROOT, account_id="acme", user_id="default")
+
+ ctx = await get_request_context(request, identity)
+
+ assert ctx.role == Role.ROOT
+ assert ctx.user.account_id == "acme"
+ assert ctx.user.user_id == "default"
+
+
async def test_root_monitoring_requests_allow_implicit_default_identity():
"""Observer/debug endpoints keep the existing ROOT monitoring flow."""
observer_request = _make_request("/api/v1/observer/system", auth_enabled=True)
diff --git a/tests/storage/test_rebuild_schema.py b/tests/storage/test_rebuild_schema.py
new file mode 100644
index 000000000..df40ef57b
--- /dev/null
+++ b/tests/storage/test_rebuild_schema.py
@@ -0,0 +1,10 @@
+"""Schema coverage for rebuild support."""
+
+from openviking.storage.collection_schemas import CollectionSchemas
+
+
+def test_context_collection_does_not_contain_rebuild_content_snapshot_field():
+ schema = CollectionSchemas.context_collection("ctx", 8)
+ field_names = {field["FieldName"] for field in schema["Fields"]}
+ assert "content" not in field_names
+ assert "embedding_content" not in field_names
diff --git a/tests/storage/test_semantic_dag_stats.py b/tests/storage/test_semantic_dag_stats.py
index 42a2966fc..751fa3dfc 100644
--- a/tests/storage/test_semantic_dag_stats.py
+++ b/tests/storage/test_semantic_dag_stats.py
@@ -65,7 +65,11 @@ class _FakeProcessor:
class _DummyTracker:
+ def __init__(self):
+ self.register_calls = []
+
async def register(self, **_kwargs):
+ self.register_calls.append(_kwargs)
return None
@@ -127,5 +131,62 @@ async def test_semantic_dag_stats_collects_nodes(monkeypatch):
)
+async def test_semantic_dag_skip_vectorization_does_not_schedule_tasks(monkeypatch):
+ root_uri = "viking://resources/root"
+ tree = {
+ root_uri: [
+ {"name": "a.txt", "isDir": False},
+ {"name": "child", "isDir": True},
+ ],
+ f"{root_uri}/child": [
+ {"name": "b.txt", "isDir": False},
+ ],
+ }
+ fake_fs = _FakeVikingFS(tree)
+ tracker = _DummyTracker()
+ monkeypatch.setattr("openviking.storage.queuefs.semantic_dag.get_viking_fs", lambda: fake_fs)
+ monkeypatch.setattr(
+ "openviking.storage.queuefs.embedding_tracker.EmbeddingTaskTracker.get_instance",
+ lambda: tracker,
+ )
+
+ mock_handle = MagicMock()
+ monkeypatch.setattr(
+ "openviking.storage.transaction.lock_context.LockContext.__aenter__",
+ AsyncMock(return_value=mock_handle),
+ )
+ monkeypatch.setattr(
+ "openviking.storage.transaction.lock_context.LockContext.__aexit__",
+ AsyncMock(return_value=False),
+ )
+ monkeypatch.setattr(
+ "openviking.storage.transaction.get_lock_manager",
+ lambda: MagicMock(),
+ )
+
+ processor = _FakeProcessor()
+ ctx = RequestContext(user=UserIdentifier("acc1", "user1", "agent1"), role=Role.USER)
+ executor = SemanticDagExecutor(
+ processor=processor,
+ context_type="resource",
+ max_concurrent_llm=2,
+ ctx=ctx,
+ skip_vectorization=True,
+ )
+ await executor.run(root_uri)
+ await asyncio.sleep(0)
+
+ assert fake_fs.writes == [
+ (f"{root_uri}/child/.overview.md", "overview"),
+ (f"{root_uri}/child/.abstract.md", "abstract"),
+ (f"{root_uri}/.overview.md", "overview"),
+ (f"{root_uri}/.abstract.md", "abstract"),
+ ]
+ assert processor.vectorized_dirs == []
+ assert processor.vectorized_files == []
+ assert tracker.register_calls == []
+
+
if __name__ == "__main__":
pytest.main([__file__])
diff --git a/tests/unit/test_context.py b/tests/unit/test_context.py
index 039117351..f70e68350 100644
--- a/tests/unit/test_context.py
+++ b/tests/unit/test_context.py
@@ -170,8 +170,8 @@ class TestContextInit:
assert ctx.vectorize.text == "Test"
-class TestContextDeriveContextType:
- """Test Context._derive_context_type."""
+class TestContextContextType:
+ """Test Context context_type inference."""
def test_derive_skill(self):
"""Test deriving skill type from URI."""
diff --git a/tests/unit/test_namespace_uri_classification.py b/tests/unit/test_namespace_uri_classification.py
new file mode 100644
index 000000000..6d07c5f0b
--- /dev/null
+++ b/tests/unit/test_namespace_uri_classification.py
@@ -0,0 +1,54 @@
+# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
+# SPDX-License-Identifier: Apache-2.0
+"""Tests for shared Viking URI namespace/content classification."""
+
+from openviking.core.namespace import (
+ classify_uri,
+ context_type_for_uri,
+ owner_space_for_uri,
+)
+from openviking.server.identity import AccountNamespacePolicy, RequestContext, Role
+from openviking_cli.session.user_id import UserIdentifier
+
+
+def test_context_type_for_uri_uses_path_segments():
+ assert context_type_for_uri("viking://user/alice/memories/entities/m1.md") == "memory"
+ assert context_type_for_uri("viking://agent/default/memories/cases/m1.md") == "memory"
+ assert (
+ context_type_for_uri("viking://user/alice/agent/default/memories/entities/m1.md")
+ == "memory"
+ )
+ assert context_type_for_uri("viking://agent/default/skills/demo") == "skill"
+ assert context_type_for_uri("viking://agent/default/user/alice/skills/demo") == "skill"
+ assert context_type_for_uri("viking://resources/memories-report.md") == "resource"
+ assert context_type_for_uri("viking://agent/default/resources/skills-report.md") == "resource"
+
+
+def test_exact_memory_and_skill_root_detection():
+ assert classify_uri("viking://user/alice/memories/preferences/prefs.md").is_memory
+ assert classify_uri("viking://user/alice/memories").is_memory_root
+ assert not classify_uri("viking://user/alice/memories/preferences").is_memory_root
+
+ assert classify_uri("viking://agent/default/skills/demo/SKILL.md").is_skill
+ assert classify_uri("viking://agent/default/skills/demo").is_skill_root
+ assert not classify_uri("viking://agent/default/skills").is_skill_root
+ assert not classify_uri("viking://agent/default/skills/demo/assets").is_skill_root
+
+
+def test_owner_space_for_uri_respects_namespace_policy():
+ ctx = RequestContext(
+ user=UserIdentifier(account_id="acct", user_id="alice", agent_id="planner"),
+ role=Role.ROOT,
+ namespace_policy=AccountNamespacePolicy(
+ isolate_user_scope_by_agent=True,
+ isolate_agent_scope_by_user=True,
+ ),
+ )
+
+ assert owner_space_for_uri("viking://user/alice/agent/planner/memories", ctx) == (
+ "alice/agent/planner"
+ )
+ assert owner_space_for_uri("viking://agent/planner/user/alice/skills/demo", ctx) == (
+ "planner/user/alice"
+ )
+ assert owner_space_for_uri("viking://resources/readme.md", ctx) == ""
diff --git a/tests/unit/test_summarizer_context_type.py b/tests/unit/test_summarizer_context_type.py
index aff55fe6f..1b424909a 100644
--- a/tests/unit/test_summarizer_context_type.py
+++ b/tests/unit/test_summarizer_context_type.py
@@ -2,13 +2,11 @@
# SPDX-License-Identifier: Apache-2.0
"""Tests for context_type classification in Summarizer.
-Verifies that the summarizer uses get_context_type_for_uri() to correctly
+Verifies that the summarizer uses context_type_for_uri() to correctly
classify memory, skill, and resource URIs (fixes #1060).
"""
-import pytest
-
-from openviking.core.directories import get_context_type_for_uri
+from openviking.core.namespace import context_type_for_uri
class TestSummarizerContextType:
@@ -17,42 +15,47 @@ class TestSummarizerContextType:
def test_user_memory_uri(self):
"""User memory URIs should classify as 'memory'."""
uri = "viking://user/default/memories/entities/mem_abc123.md"
- assert get_context_type_for_uri(uri) == "memory"
+ assert context_type_for_uri(uri) == "memory"
def test_agent_memory_uri(self):
"""Agent memory URIs should classify as 'memory'."""
uri = "viking://agent/default/memories/cases/mem_xyz789.md"
- assert get_context_type_for_uri(uri) == "memory"
+ assert context_type_for_uri(uri) == "memory"
def test_memory_profile_uri(self):
"""Profile memory URI should classify as 'memory'."""
uri = "viking://user/default/memories/profile.md"
- assert get_context_type_for_uri(uri) == "memory"
+ assert context_type_for_uri(uri) == "memory"
def test_memory_preferences_uri(self):
"""Preferences memory URI should classify as 'memory'."""
uri = "viking://user/default/memories/preferences/coding-style.md"
- assert get_context_type_for_uri(uri) == "memory"
+ assert context_type_for_uri(uri) == "memory"
def test_skill_uri(self):
"""Skill URIs should classify as 'skill'."""
uri = "viking://agent/default/skills/search.md"
- assert get_context_type_for_uri(uri) == "skill"
+ assert context_type_for_uri(uri) == "skill"
def test_resource_uri(self):
"""Resource URIs should classify as 'resource'."""
uri = "viking://resources/docs/readme.md"
- assert get_context_type_for_uri(uri) == "resource"
+ assert context_type_for_uri(uri) == "resource"
- def test_session_uri(self):
- """Session URIs should classify as 'memory'."""
+ def test_session_uri_defaults_to_resource(self):
+ """Session URIs should not be treated as memory-specific content."""
uri = "viking://session/default/sess_001/history/archive_001"
- assert get_context_type_for_uri(uri) == "memory"
+ assert context_type_for_uri(uri) == "resource"
+
+ def test_resource_named_memories_does_not_classify_as_memory(self):
+ """String containment alone should not classify a resource as memory."""
+ uri = "viking://resources/memories-report.md"
+ assert context_type_for_uri(uri) == "resource"
def test_unknown_uri_defaults_to_resource(self):
"""Unknown URIs should default to 'resource'."""
uri = "viking://unknown/something"
- assert get_context_type_for_uri(uri) == "resource"
+ assert context_type_for_uri(uri) == "resource"
def test_old_broken_prefix_would_fail(self):
"""Regression: the old startswith('viking://memory/') check would miss real URIs."""
@@ -63,5 +66,7 @@ class TestSummarizerContextType:
"viking://user/john/memories/events/mem_003.md",
]
for uri in real_uris:
- assert not uri.startswith("viking://memory/"), f"URI unexpectedly matches old prefix: {uri}"
- assert get_context_type_for_uri(uri) == "memory", f"URI should classify as memory: {uri}"
+ assert not uri.startswith("viking://memory/"), (
+ f"URI unexpectedly matches old prefix: {uri}"
+ )
+ assert context_type_for_uri(uri) == "memory", f"URI should classify as memory: {uri}"
diff --git a/tests/unit/test_vectorize_file_strategy.py b/tests/unit/test_vectorize_file_strategy.py
index 0eded560d..1635e6164 100644
--- a/tests/unit/test_vectorize_file_strategy.py
+++ b/tests/unit/test_vectorize_file_strategy.py
@@ -31,6 +31,12 @@ class DummyFS:
async def read_file(self, _path, ctx=None):
return self.content
+ async def exists(self, _path, ctx=None):
+ return False
+
+ async def ls(self, _uri, ctx=None):
+ return []
+
class DummyUser:
account_id = "default"
@@ -114,3 +120,29 @@ async def test_vectorize_file_truncates_content_when_content_only(monkeypatch):
text = queue.items[0].get_vectorization_text()
assert text.endswith("...(truncated for embedding)")
assert "token-199" not in text
+
+
+async def test_index_resource_skips_session_namespace(monkeypatch):
+ queue = DummyQueue()
+ monkeypatch.setattr(embedding_utils, "get_queue_manager", lambda: DummyQueueManager(queue))
+ monkeypatch.setattr(embedding_utils, "get_viking_fs", lambda: DummyFS("ignored"))
+ monkeypatch.setattr(
+ embedding_utils,
+ "get_openviking_config",
+ lambda: types.SimpleNamespace(
+ embedding=types.SimpleNamespace(text_source="summary_first", max_input_tokens=1000)
+ ),
+ )
+ monkeypatch.setattr(
+ embedding_utils.EmbeddingMsgConverter,
+ "from_context",
+ lambda context: context,
+ )
+
+ await embedding_utils.index_resource(
+ uri="viking://session/default/sess_001/history/archive_001",
+ ctx=DummyReq(),
+ )
+
+ assert queue.items == []