Skip to content

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

feat(fs): 新增 attrs 元信息接口 (#2906)

Qin Haojie6223537a00aa
diff --git a/crates/ov_cli/src/client.rs b/crates/ov_cli/src/client.rs
index 8d4000325..f558de69f 100644
--- a/crates/ov_cli/src/client.rs
+++ b/crates/ov_cli/src/client.rs
@@ -279,7 +279,7 @@ impl HttpClient {
"mode": mode,
"recursive": recursive,
});
- self.post("/api/v1/content/set_tags", &body).await
+ self.post("/api/v1/fs/attrs/set_tags", &body).await
}
fn build_write_body(
@@ -464,6 +464,11 @@ impl HttpClient {
self.get("/api/v1/fs/stat", &params).await
}
+ pub async fn attrs(&self, uri: &str) -> Result<serde_json::Value> {
+ let params = vec![("uri".to_string(), uri.to_string())];
+ self.get("/api/v1/fs/attrs", &params).await
+ }
+
// ============ Search Methods ============
pub async fn find(
diff --git a/crates/ov_cli/src/commands/filesystem.rs b/crates/ov_cli/src/commands/filesystem.rs
index e75de3cfc..80ad88cfc 100644
--- a/crates/ov_cli/src/commands/filesystem.rs
+++ b/crates/ov_cli/src/commands/filesystem.rs
@@ -1,6 +1,6 @@
use super::render_utils::{append_profile_lines, with_ascii_ellipsis, wrap_display_text};
use crate::client::HttpClient;
-use crate::error::Result;
+use crate::error::{Error, Result};
use crate::output::{OutputFormat, output_success};
use crate::theme;
use chrono::{DateTime, Local};
@@ -434,6 +434,31 @@ pub async fn stat(
Ok(())
}
+pub async fn attrs(
+ client: &HttpClient,
+ uri: &str,
+ key: Option<&str>,
+ output_format: OutputFormat,
+ compact: bool,
+) -> Result<()> {
+ let mut result = client.attrs(uri).await?;
+ if let Some(key) = key {
+ result = select_attr_key(&result, key)
+ .cloned()
+ .ok_or_else(|| Error::Client(format!("Attribute not found: {key}")))?;
+ }
+ output_success(&result, output_format, compact);
+ Ok(())
+}
+
+fn select_attr_key<'a>(result: &'a Value, key: &str) -> Option<&'a Value> {
+ let mut current = result.get("attrs")?;
+ for part in key.strip_prefix("attrs.").unwrap_or(key).split('.') {
+ current = current.get(part)?;
+ }
+ Some(current)
+}
+
fn output_message_result(
result: serde_json::Value,
message: String,
diff --git a/crates/ov_cli/src/handlers.rs b/crates/ov_cli/src/handlers.rs
index fb2fed9ac..84fb38a4b 100644
--- a/crates/ov_cli/src/handlers.rs
+++ b/crates/ov_cli/src/handlers.rs
@@ -1499,6 +1499,18 @@ pub async fn handle_stat(uri: String, ctx: CliContext) -> Result<()> {
commands::filesystem::stat(&client, &uri, ctx.output_format, ctx.compact).await
}
+pub async fn handle_attrs(uri: String, key: Option<String>, ctx: CliContext) -> Result<()> {
+ let client = ctx.get_client();
+ commands::filesystem::attrs(
+ &client,
+ &uri,
+ key.as_deref(),
+ ctx.output_format,
+ ctx.compact,
+ )
+ .await
+}
+
pub async fn handle_grep(
uri: String,
exclude_uri: Option<String>,
diff --git a/crates/ov_cli/src/main.rs b/crates/ov_cli/src/main.rs
index 109bd5ae2..db9f6835b 100644
--- a/crates/ov_cli/src/main.rs
+++ b/crates/ov_cli/src/main.rs
@@ -235,6 +235,33 @@ impl CliContext {
}
}
+#[derive(Subcommand)]
+enum AttrsCommands {
+ /// Get logical extended attributes
+ Get {
+ /// Viking URI to get attributes for
+ #[arg(value_name = "uri")]
+ uri: String,
+ /// Optional attrs key, for example tags, memory, or memory.tags
+ #[arg(value_name = "key")]
+ key: Option<String>,
+ },
+ /// Update explicit retrieval tags metadata for a file or directory
+ SetTags {
+ /// Viking URI
+ uri: String,
+ /// Comma-separated k=v tags, e.g. env=prod,team=search
+ #[arg(long = "tags", value_delimiter = ',')]
+ tags: Vec<String>,
+ /// Tag update mode: replace or append (append replaces existing values by key)
+ #[arg(long, default_value = "replace")]
+ mode: String,
+ /// Recursively update descendant files and semantic nodes when target is a directory
+ #[arg(long, default_value = "false")]
+ recursive: bool,
+ },
+}
+
// Commands are organized with category tags in their doc comments.
//
// # Command Tagging System
@@ -463,6 +490,11 @@ enum Commands {
#[arg(value_name = "uri")]
uri: String,
},
+ /// [Data] Get logical extended attributes
+ Attrs {
+ #[command(subcommand)]
+ action: AttrsCommands,
+ },
/// [Data] Read file content (Level 2)
Read {
/// Viking URI
@@ -521,6 +553,7 @@ enum Commands {
timeout: Option<f64>,
},
/// [Data] Update explicit retrieval tags metadata for a file or directory
+ #[command(hide = true)]
SetTags {
/// Viking URI
uri: String,
@@ -2938,6 +2971,15 @@ async fn main() {
} => handlers::handle_rm(uri, recursive, wait, timeout, ctx).await,
Commands::Mv { from_uri, to_uri } => handlers::handle_mv(from_uri, to_uri, ctx).await,
Commands::Stat { uri } => handlers::handle_stat(uri, ctx).await,
+ Commands::Attrs { action } => match action {
+ AttrsCommands::Get { uri, key } => handlers::handle_attrs(uri, key, ctx).await,
+ AttrsCommands::SetTags {
+ uri,
+ tags,
+ mode,
+ recursive,
+ } => handlers::handle_set_tags(uri, tags, mode, recursive, ctx).await,
+ },
Commands::AddMemory { content } => handlers::handle_add_memory(content, ctx).await,
Commands::Tui { uri } => handlers::handle_tui(uri, ctx).await,
Commands::Chat {
diff --git a/docs/en/api/01-overview.md b/docs/en/api/01-overview.md
index 977d72a4c..fd02d6ee8 100644
--- a/docs/en/api/01-overview.md
+++ b/docs/en/api/01-overview.md
@@ -431,6 +431,8 @@ Below are all HTTP API endpoints provided by OpenViking, grouped by functional m
| GET | `/api/v1/fs/ls` | List directory |
| GET | `/api/v1/fs/tree` | Directory tree |
| GET | `/api/v1/fs/stat` | Resource status |
+| GET | `/api/v1/fs/attrs` | Logical extended attributes |
+| POST | `/api/v1/fs/attrs/set_tags` | Set retrieval tags |
| POST | `/api/v1/fs/mkdir` | Create directory |
| DELETE | `/api/v1/fs` | Delete resource |
| POST | `/api/v1/fs/mv` | Move/rename resource |
diff --git a/docs/en/api/03-filesystem.md b/docs/en/api/03-filesystem.md
index 2778ab2c5..01a1cbb1f 100644
--- a/docs/en/api/03-filesystem.md
+++ b/docs/en/api/03-filesystem.md
@@ -586,6 +586,103 @@ The `count` field (directories only) contains the estimated number of items (fil
---
+### attrs()
+
+Get logical extended attributes for a file or directory.
+
+**Parameters**
+
+| Parameter | Type | Required | Default | Description |
+|-----------|------|----------|---------|-------------|
+| uri | str | Yes | - | Viking URI |
+
+**Python SDK (HTTP)**
+
+```python
+attrs = client.attrs("viking://resources/docs/api.md")
+print(attrs["attrs"]["tags"])
+```
+
+**Go SDK**
+
+```go
+attrs, err := client.Attrs(ctx, "viking://resources/docs/api.md")
+if err != nil {
+ return err
+}
+metadata := attrs["attrs"].(map[string]any)
+fmt.Println(metadata["tags"])
+```
+
+**HTTP API**
+
+```
+GET /api/v1/fs/attrs?uri={uri}
+POST /api/v1/fs/attrs/set_tags
+```
+
+```bash
+curl -X GET "http://localhost:1933/api/v1/fs/attrs?uri=viking://resources/docs/api.md" \
+ -H "X-API-Key: your-key"
+
+curl -X POST "http://localhost:1933/api/v1/fs/attrs/set_tags" \
+ -H "X-API-Key: your-key" \
+ -H "Content-Type: application/json" \
+ -d '{"uri":"viking://resources/docs","tags":["team=search"],"mode":"append","recursive":true}'
+```
+
+**CLI**
+
+```bash
+openviking attrs get viking://resources/docs/api.md
+openviking attrs get viking://resources/docs/api.md tags
+openviking attrs get viking://user/alice/memories/experiences/foo.md memory.resource_refs
+openviking attrs set-tags viking://resources/docs/api.md --tags team=search,env=prod
+openviking attrs set-tags viking://resources/docs --tags team=search --mode append --recursive
+```
+
+Directory targets update the directory semantic records; `recursive=true` also updates existing descendant files and directory semantic records.
+
+**Response (Resource)**
+
+```json
+{
+ "status": "ok",
+ "result": {
+ "uri": "viking://resources/docs/api.md",
+ "context_type": "resource",
+ "attrs": {
+ "tags": ["team=search", "env=prod"]
+ }
+ }
+}
+```
+
+**Response (Memory)**
+
+```json
+{
+ "status": "ok",
+ "result": {
+ "uri": "viking://user/alice/memories/experiences/foo.md",
+ "context_type": "memory",
+ "attrs": {
+ "memory": {
+ "memory_type": "experiences",
+ "name": "foo",
+ "tags": ["ui"],
+ "resource_refs": ["viking://resources/docs/api.md"]
+ },
+ "tags": ["team=search"]
+ }
+ }
+}
+```
+
+`attrs.memory` is parsed from `MEMORY_FIELDS` metadata with content removed. `attrs.tags` is the explicit retrieval tag list used by `attrs set-tags` and search filters.
+
+---
+
### mkdir()
Create a directory.
diff --git a/docs/zh/api/01-overview.md b/docs/zh/api/01-overview.md
index d57ad5f89..02c9a57e4 100644
--- a/docs/zh/api/01-overview.md
+++ b/docs/zh/api/01-overview.md
@@ -427,6 +427,8 @@ JSON 输出 - 错误:
| GET | `/api/v1/fs/ls` | 列出目录内容 |
| GET | `/api/v1/fs/tree` | 获取目录树结构 |
| GET | `/api/v1/fs/stat` | 获取资源状态 |
+| GET | `/api/v1/fs/attrs` | 获取逻辑扩展属性 |
+| POST | `/api/v1/fs/attrs/set_tags` | 设置检索标签 |
| POST | `/api/v1/fs/mkdir` | 创建目录 |
| DELETE | `/api/v1/fs` | 删除资源 |
| POST | `/api/v1/fs/mv` | 移动/重命名资源 |
diff --git a/docs/zh/api/03-filesystem.md b/docs/zh/api/03-filesystem.md
index 45288e663..8504d77f7 100644
--- a/docs/zh/api/03-filesystem.md
+++ b/docs/zh/api/03-filesystem.md
@@ -587,6 +587,103 @@ openviking stat viking://resources/my-project/docs
---
+### attrs()
+
+获取文件或目录的逻辑扩展属性。
+
+**参数**
+
+| 参数 | 类型 | 必填 | 默认值 | 说明 |
+|------|------|------|--------|------|
+| uri | str | 是 | - | Viking URI |
+
+**Python SDK (HTTP)**
+
+```python
+attrs = client.attrs("viking://resources/docs/api.md")
+print(attrs["attrs"]["tags"])
+```
+
+**Go SDK**
+
+```go
+attrs, err := client.Attrs(ctx, "viking://resources/docs/api.md")
+if err != nil {
+ return err
+}
+metadata := attrs["attrs"].(map[string]any)
+fmt.Println(metadata["tags"])
+```
+
+**HTTP API**
+
+```
+GET /api/v1/fs/attrs?uri={uri}
+POST /api/v1/fs/attrs/set_tags
+```
+
+```bash
+curl -X GET "http://localhost:1933/api/v1/fs/attrs?uri=viking://resources/docs/api.md" \
+ -H "X-API-Key: your-key"
+
+curl -X POST "http://localhost:1933/api/v1/fs/attrs/set_tags" \
+ -H "X-API-Key: your-key" \
+ -H "Content-Type: application/json" \
+ -d '{"uri":"viking://resources/docs","tags":["team=search"],"mode":"append","recursive":true}'
+```
+
+**CLI**
+
+```bash
+openviking attrs get viking://resources/docs/api.md
+openviking attrs get viking://resources/docs/api.md tags
+openviking attrs get viking://user/alice/memories/experiences/foo.md memory.resource_refs
+openviking attrs set-tags viking://resources/docs/api.md --tags team=search,env=prod
+openviking attrs set-tags viking://resources/docs --tags team=search --mode append --recursive
+```
+
+目录目标会更新目录语义记录;`recursive=true` 还会更新已有子文件和子目录语义记录。
+
+**响应(Resource)**
+
+```json
+{
+ "status": "ok",
+ "result": {
+ "uri": "viking://resources/docs/api.md",
+ "context_type": "resource",
+ "attrs": {
+ "tags": ["team=search", "env=prod"]
+ }
+ }
+}
+```
+
+**响应(Memory)**
+
+```json
+{
+ "status": "ok",
+ "result": {
+ "uri": "viking://user/alice/memories/experiences/foo.md",
+ "context_type": "memory",
+ "attrs": {
+ "memory": {
+ "memory_type": "experiences",
+ "name": "foo",
+ "tags": ["ui"],
+ "resource_refs": ["viking://resources/docs/api.md"]
+ },
+ "tags": ["team=search"]
+ }
+ }
+}
+```
+
+`attrs.memory` 来自 `MEMORY_FIELDS` 元信息,已去掉正文内容。`attrs.tags` 是 `attrs set-tags` 和搜索过滤使用的显式检索标签。
+
+---
+
### mkdir()
创建目录。
diff --git a/openviking/server/routers/filesystem.py b/openviking/server/routers/filesystem.py
index 210d56013..849d590c8 100644
--- a/openviking/server/routers/filesystem.py
+++ b/openviking/server/routers/filesystem.py
@@ -2,11 +2,12 @@
# SPDX-License-Identifier: AGPL-3.0
"""Filesystem endpoints for OpenViking HTTP Server."""
-from typing import Optional
+from typing import Any, Optional
-from fastapi import APIRouter, Depends, Query
+from fastapi import APIRouter, Body, Depends, Query
from pydantic import BaseModel
+from openviking.core.namespace import NamespaceShapeError, canonicalize_uri, context_type_for_uri
from openviking.core.path_variables import resolve_path_variables
from openviking.pyagfs.exceptions import AGFSClientError, AGFSNotFoundError
from openviking.server.auth import get_request_context
@@ -14,11 +15,45 @@ from openviking.server.dependencies import get_service
from openviking.server.error_mapping import map_exception
from openviking.server.identity import RequestContext
from openviking.server.models import Response
-from openviking_cli.exceptions import NotFoundError
+from openviking.server.routers.content import SetTagsRequest, set_tags as content_set_tags
+from openviking.storage import VikingDBManagerProxy
+from openviking_cli.exceptions import InvalidArgumentError, NotFoundError
router = APIRouter(prefix="/api/v1/fs", tags=["filesystem"])
+_ATTR_INDEX_FIELDS = ["level", "search_tags"]
+
+
+def _clean_memory_attrs(raw: str) -> dict[str, Any]:
+ from openviking.session.memory.utils.memory_file_utils import MemoryFileUtils
+
+ mf = MemoryFileUtils.read(raw)
+ attrs: dict[str, Any] = mf.to_metadata()
+ attrs.pop("content", None)
+ return attrs
+
+
+async def _tags_attr(service: Any, uri: str, ctx: RequestContext) -> list[str]:
+ vikingdb_manager = getattr(service, "vikingdb_manager", None)
+ if not vikingdb_manager:
+ return []
+
+ proxy = VikingDBManagerProxy(vikingdb_manager, ctx)
+ records = await proxy.filter(
+ filter={"op": "must", "field": "uri", "conds": [uri]},
+ limit=10,
+ output_fields=_ATTR_INDEX_FIELDS,
+ )
+ records = sorted(records, key=lambda item: item.get("level", 99))
+ tags: list[str] = []
+ for record in records:
+ for tag in record.get("search_tags") or []:
+ if tag not in tags:
+ tags.append(tag)
+ return tags
+
+
@router.get("/ls")
async def ls(
uri: str = Query(..., description="Viking URI"),
@@ -119,6 +154,56 @@ async def stat(
raise
+async def attrs(
+ uri: str = Query(..., description="Viking URI"),
+ _ctx: RequestContext = Depends(get_request_context),
+):
+ """Get logical extended attributes for a URI."""
+ service = get_service()
+ uri = resolve_path_variables(uri)
+ try:
+ stat_result = await service.fs.stat(uri, ctx=_ctx)
+ try:
+ canonical_uri = canonicalize_uri(uri, _ctx)
+ except NamespaceShapeError as exc:
+ raise InvalidArgumentError(str(exc)) from exc
+
+ result = {
+ "uri": canonical_uri,
+ "context_type": context_type_for_uri(canonical_uri),
+ "attrs": {
+ "tags": await _tags_attr(service, canonical_uri, _ctx),
+ },
+ }
+ if result["context_type"] == "memory" and not stat_result.get("isDir", False):
+ result["attrs"]["memory"] = _clean_memory_attrs(
+ await service.fs.read(canonical_uri, ctx=_ctx)
+ )
+ return Response(status="ok", result=result)
+ except AGFSNotFoundError:
+ raise NotFoundError(uri, "file")
+ except AGFSClientError as e:
+ mapped = map_exception(e, resource=uri, resource_type="file")
+ if mapped is not None:
+ raise mapped from e
+ raise
+ except Exception as exc:
+ mapped = map_exception(exc, resource=uri)
+ if mapped is not None:
+ raise mapped from exc
+ raise
+
+
[email protected]("/attrs/set_tags")
+async def attrs_set_tags(
+ request: SetTagsRequest = Body(...),
+ _ctx: RequestContext = Depends(get_request_context),
+):
+ """Set explicit k=v retrieval tags metadata for a file or directory."""
+ return await content_set_tags(request, _ctx)
+
+
class MkdirRequest(BaseModel):
"""Request model for mkdir."""
diff --git a/sdk/go/README.md b/sdk/go/README.md
index 2284c7eb8..f916b511c 100644
--- a/sdk/go/README.md
+++ b/sdk/go/README.md
@@ -111,7 +111,7 @@ Implemented:
| Resource and skill import | `AddResource`, `AddSkill`, `WaitProcessed` |
| Skill management | `ListSkills`, `FindSkills`, `ValidateSkill`, `GetSkill`, `UpdateSkill`, `DeleteSkill` |
| Watch management | `ListWatches`, `GetWatch`, `UpdateWatch`, `DeleteWatch`, `TriggerWatch` |
-| Filesystem and content | `List`, `Tree`, `Stat`, `Mkdir`, `Remove`, `Move`, `Read`, `Abstract`, `Overview`, `Write`, `SetTags`, `Reindex` |
+| Filesystem and content | `List`, `Tree`, `Stat`, `Attrs`, `Mkdir`, `Remove`, `Move`, `Read`, `Abstract`, `Overview`, `Write`, `SetTags`, `Reindex` |
| Retrieval | `Find`, `Search`, `Grep`, `Glob` |
| Sessions and tasks | `CreateSession`, `ListSessions`, `GetSession`, `SessionExists`, `GetSessionContext`, `GetSessionArchive`, `DeleteSession`, `AddMessage`, `BatchAddMessages`, `CommitSession`, `GetTask`, `ListTasks` |
| Packs | `ExportOVPack`, `BackupOVPack`, `ImportOVPack`, `RestoreOVPack` |
diff --git a/sdk/go/README_CN.md b/sdk/go/README_CN.md
index 4bbb17c90..bb74b1e8d 100644
--- a/sdk/go/README_CN.md
+++ b/sdk/go/README_CN.md
@@ -40,7 +40,7 @@ Go SDK 仅支持 HTTP 模式,不支持 Python embedded 模式,也不保留
| 资源和技能导入 | `AddResource`, `AddSkill`, `WaitProcessed` |
| 技能管理 | `ListSkills`, `FindSkills`, `ValidateSkill`, `GetSkill`, `UpdateSkill`, `DeleteSkill` |
| Watch 管理 | `ListWatches`, `GetWatch`, `UpdateWatch`, `DeleteWatch`, `TriggerWatch` |
-| 文件系统和内容 | `List`, `Tree`, `Stat`, `Mkdir`, `Remove`, `Move`, `Read`, `Abstract`, `Overview`, `Write`, `SetTags`, `Reindex` |
+| 文件系统和内容 | `List`, `Tree`, `Stat`, `Attrs`, `Mkdir`, `Remove`, `Move`, `Read`, `Abstract`, `Overview`, `Write`, `SetTags`, `Reindex` |
| 检索 | `Find`, `Search`, `Grep`, `Glob` |
| 会话和任务 | `CreateSession`, `ListSessions`, `GetSession`, `SessionExists`, `GetSessionContext`, `GetSessionArchive`, `DeleteSession`, `AddMessage`, `BatchAddMessages`, `CommitSession`, `GetTask`, `ListTasks` |
| OVPack | `ExportOVPack`, `BackupOVPack`, `ImportOVPack`, `RestoreOVPack` |
diff --git a/sdk/go/client_test.go b/sdk/go/client_test.go
index ebf23b0c1..1c8a7d623 100644
--- a/sdk/go/client_test.go
+++ b/sdk/go/client_test.go
@@ -820,7 +820,7 @@ func TestHealth(t *testing.T) {
func TestSetTagsSendsBody(t *testing.T) {
client, closeServer := testClient(t, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
- if r.URL.Path != "/api/v1/content/set_tags" {
+ if r.URL.Path != "/api/v1/fs/attrs/set_tags" {
t.Fatalf("path = %s", r.URL.Path)
}
if r.Method != http.MethodPost {
@@ -862,7 +862,7 @@ func TestSetTagsSendsBody(t *testing.T) {
func TestSetTagsDefaultsModeAndOmitsTelemetry(t *testing.T) {
client, closeServer := testClient(t, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
- if r.URL.Path != "/api/v1/content/set_tags" {
+ if r.URL.Path != "/api/v1/fs/attrs/set_tags" {
t.Fatalf("path = %s", r.URL.Path)
}
body := readJSONBody(t, r)
diff --git a/sdk/go/filesystem.go b/sdk/go/filesystem.go
index 246890a29..bb499e2be 100644
--- a/sdk/go/filesystem.go
+++ b/sdk/go/filesystem.go
@@ -72,6 +72,14 @@ func (c *Client) Stat(ctx context.Context, uri string) (map[string]any, error) {
return result, err
}
+// Attrs returns logical extended attributes for a URI.
+func (c *Client) Attrs(ctx context.Context, uri string) (map[string]any, error) {
+ query := url.Values{"uri": []string{NormalizeURI(uri)}}
+ var result map[string]any
+ err := c.doJSON(ctx, http.MethodGet, "/api/v1/fs/attrs", query, nil, &result)
+ return result, err
+}
+
// Mkdir creates a directory.
func (c *Client) Mkdir(ctx context.Context, uri string, description string) error {
payload := map[string]any{"uri": NormalizeURI(uri)}
@@ -176,7 +184,7 @@ func (c *Client) SetTags(ctx context.Context, uri string, tags []string, opts *S
}
setAny(payload, "telemetry", opts.Telemetry)
var result map[string]any
- err := c.doJSON(ctx, http.MethodPost, "/api/v1/content/set_tags", nil, payload, &result)
+ err := c.doJSON(ctx, http.MethodPost, "/api/v1/fs/attrs/set_tags", nil, payload, &result)
return result, err
}
diff --git a/sdk/python/openviking_sdk/client.py b/sdk/python/openviking_sdk/client.py
index f50cfd041..83644504c 100644
--- a/sdk/python/openviking_sdk/client.py
+++ b/sdk/python/openviking_sdk/client.py
@@ -781,6 +781,12 @@ class AsyncHTTPClient:
response = await self._http.get("/api/v1/fs/stat", params={"uri": VikingURI.normalize(uri)})
return self._handle_response(response)
+ async def attrs(self, uri: str) -> Dict[str, Any]:
+ response = await self._http.get(
+ "/api/v1/fs/attrs", params={"uri": VikingURI.normalize(uri)}
+ )
+ return self._handle_response(response)
+
async def mkdir(self, uri: str, description: Optional[str] = None) -> None:
payload = {"uri": VikingURI.normalize(uri)}
if description is not None:
@@ -858,7 +864,7 @@ class AsyncHTTPClient:
telemetry: Any = False,
) -> Dict[str, Any]:
response = await self._http.post(
- "/api/v1/content/set_tags",
+ "/api/v1/fs/attrs/set_tags",
json={
"uri": VikingURI.normalize(uri),
"tags": tags,
@@ -1679,6 +1685,9 @@ class SyncHTTPClient:
def stat(self, uri: str) -> Dict[str, Any]:
return run_async(self._async_client.stat(uri))
+ def attrs(self, uri: str) -> Dict[str, Any]:
+ return run_async(self._async_client.attrs(uri))
+
def mkdir(self, uri: str, description: Optional[str] = None) -> None:
run_async(self._async_client.mkdir(uri, description=description))
diff --git a/tests/server/test_api_content_write.py b/tests/server/test_api_content_write.py
index 134201591..29bda4063 100644
--- a/tests/server/test_api_content_write.py
+++ b/tests/server/test_api_content_write.py
@@ -23,7 +23,7 @@ async def test_write_endpoint_registered(client):
async def test_set_tags_endpoint_registered(client):
- resp = await client.get("/api/v1/content/set_tags")
+ resp = await client.get("/api/v1/fs/attrs/set_tags")
assert resp.status_code == 405
@@ -262,7 +262,7 @@ async def test_api_create_mode_regression_replace_unchanged(client_with_resource
async def test_set_tags_requires_tags_field(client_with_resource):
client, uri = client_with_resource
file_uri = await _first_file_uri(client, uri)
- resp = await client.post("/api/v1/content/set_tags", json={"uri": file_uri})
+ resp = await client.post("/api/v1/fs/attrs/set_tags", json={"uri": file_uri})
assert resp.status_code == 400
@@ -287,7 +287,7 @@ async def test_set_tags_passes_tags_to_service(client, service, monkeypatch):
monkeypatch.setattr(service.fs, "set_tags", fake_set_tags)
resp = await client.post(
- "/api/v1/content/set_tags",
+ "/api/v1/fs/attrs/set_tags",
json={
"uri": "viking://resources/demo/file.md",
"tags": ["a", "b"],
@@ -310,7 +310,7 @@ async def test_set_tags_rejects_wait_and_timeout_fields(client_with_resource):
client, uri = client_with_resource
file_uri = await _first_file_uri(client, uri)
resp = await client.post(
- "/api/v1/content/set_tags",
+ "/api/v1/fs/attrs/set_tags",
json={
"uri": file_uri,
"tags": ["team=search"],
@@ -327,7 +327,7 @@ async def test_set_tags_rejects_invalid_kv_tag(client_with_resource):
client, uri = client_with_resource
file_uri = await _first_file_uri(client, uri)
resp = await client.post(
- "/api/v1/content/set_tags",
+ "/api/v1/fs/attrs/set_tags",
json={"uri": file_uri, "tags": ["project-a"]},
)
assert resp.status_code == 400
diff --git a/tests/server/test_api_search.py b/tests/server/test_api_search.py
index 5a2ea8735..87ef3dee0 100644
--- a/tests/server/test_api_search.py
+++ b/tests/server/test_api_search.py
@@ -82,7 +82,7 @@ async def test_find_with_target_uri_and_tags_after_set_tags(client_with_resource
client, uri = client_with_resource
set_tags_resp = await client.post(
- "/api/v1/content/set_tags",
+ "/api/v1/fs/attrs/set_tags",
json={"uri": uri, "tags": ["team=search"]},
)
assert set_tags_resp.status_code == 200
diff --git a/tests/server/test_filesystem_router.py b/tests/server/test_filesystem_router.py
index 5d6c5a1dd..b0331f98e 100644
--- a/tests/server/test_filesystem_router.py
+++ b/tests/server/test_filesystem_router.py
@@ -33,3 +33,53 @@ async def test_rm_preserves_memory_cleanup(monkeypatch):
assert response.result["uri"] == "viking://resources/id_card.pdf"
assert response.result["estimated_deleted_count"] == 1
assert response.result["memory_cleanup"] == cleanup
+
+
+async def test_attrs_returns_memory_fields_and_tags(monkeypatch):
+ raw_memory = (
+ "Original preference\n\n"
+ "<!-- MEMORY_FIELDS\n"
+ '{"memory_type": "preferences", "tags": ["ui"], "fields": {"topic": "theme"}, '
+ '"resource_refs": ["viking://resources/docs/api.md"]}\n'
+ "-->"
+ )
+
+ async def fake_stat(uri, ctx=None):
+ return {"isDir": False}
+
+ async def fake_read(uri, ctx=None):
+ return raw_memory
+
+ class FakeVectorManager:
+ async def filter(self, **kwargs):
+ return [
+ {
+ "uri": kwargs["filter"]["conds"][0],
+ "level": 2,
+ "search_tags": ["team=search"],
+ }
+ ]
+
+ monkeypatch.setattr(
+ filesystem,
+ "get_service",
+ lambda: SimpleNamespace(
+ fs=SimpleNamespace(stat=fake_stat, read=fake_read),
+ vikingdb_manager=FakeVectorManager(),
+ ),
+ )
+
+ response = await filesystem.attrs(
+ uri="viking://user/alice/memories/preferences/theme.md",
+ _ctx=RequestContext(user=UserIdentifier("acct", "alice"), role=Role.USER),
+ )
+
+ attrs = response.result["attrs"]
+ assert attrs["memory"] == {
+ "tags": ["ui"],
+ "fields": {"topic": "theme"},
+ "resource_refs": ["viking://resources/docs/api.md"],
+ "memory_type": "preferences",
+ }
+ assert attrs["tags"] == ["team=search"]