Self-evolving Context Database for AI Agents. Unify Agent Memory, Knowledge RAG and Skills.
Python agent-contextagent-memoryagent-pluginsagentic-ragcontext-databasedsh-pluginknowledge-basememorymemory-managementself-evolvingvector-database
feat(filesystem): support directory descriptions on mkdir (#1443)
Qin Haojieb7d50d8dbf0e
diff --git a/crates/ov_cli/src/client.rs b/crates/ov_cli/src/client.rsindex 77afe352e..c908c0359 100644--- a/crates/ov_cli/src/client.rs+++ b/crates/ov_cli/src/client.rs@@ -449,8 +449,11 @@ impl HttpClient {self.get("/api/v1/fs/tree", ¶ms).await}- pub async fn mkdir(&self, uri: &str) -> Result<()> {- let body = serde_json::json!({ "uri": uri });+ pub async fn mkdir(&self, uri: &str, description: Option<&str>) -> Result<()> {+ let body = match description {+ Some(description) => serde_json::json!({ "uri": uri, "description": description }),+ None => serde_json::json!({ "uri": uri }),+ };let _: serde_json::Value = self.post("/api/v1/fs/mkdir", &body).await?;Ok(())}diff --git a/crates/ov_cli/src/commands/filesystem.rs b/crates/ov_cli/src/commands/filesystem.rsindex 934faa180..956b3bce0 100644--- a/crates/ov_cli/src/commands/filesystem.rs+++ b/crates/ov_cli/src/commands/filesystem.rs@@ -57,10 +57,11 @@ pub async fn tree(pub async fn mkdir(client: &HttpClient,uri: &str,+ description: Option<&str>,_output_format: OutputFormat,_compact: bool,) -> Result<()> {- client.mkdir(uri).await?;+ client.mkdir(uri, description).await?;println!("Directory created: {}", uri);Ok(())}diff --git a/crates/ov_cli/src/main.rs b/crates/ov_cli/src/main.rsindex 571720c11..c3bd50165 100644--- a/crates/ov_cli/src/main.rs+++ b/crates/ov_cli/src/main.rs@@ -283,6 +283,9 @@ enum Commands {Mkdir {/// Directory URI to createuri: String,+ /// Initial directory description+ #[arg(long)]+ description: Option<String>,},/// Remove resource#[command(alias = "del", alias = "delete")]@@ -735,7 +738,7 @@ async fn main() {node_limit,level_limit,} => handle_tree(uri, abs_limit, all, node_limit, level_limit, ctx).await,- Commands::Mkdir { uri } => handle_mkdir(uri, ctx).await,+ Commands::Mkdir { uri, description } => handle_mkdir(uri, description, ctx).await,Commands::Rm { uri, recursive } => handle_rm(uri, recursive, ctx).await,Commands::Mv { from_uri, to_uri } => handle_mv(from_uri, to_uri, ctx).await,Commands::Stat { uri } => handle_stat(uri, ctx).await,@@ -1430,9 +1433,16 @@ async fn handle_tree(.await}-async fn handle_mkdir(uri: String, ctx: CliContext) -> Result<()> {+async fn handle_mkdir(uri: String, description: Option<String>, ctx: CliContext) -> Result<()> {let client = ctx.get_client();- commands::filesystem::mkdir(&client, &uri, ctx.output_format, ctx.compact).await+ commands::filesystem::mkdir(+ &client,+ &uri,+ description.as_deref(),+ ctx.output_format,+ ctx.compact,+ )+ .await}async fn handle_rm(uri: String, recursive: bool, ctx: CliContext) -> Result<()> {diff --git a/docs/en/api/03-filesystem.md b/docs/en/api/03-filesystem.mdindex 75f28ba5b..ba18fe5ba 100644--- a/docs/en/api/03-filesystem.md+++ b/docs/en/api/03-filesystem.md@@ -440,11 +440,13 @@ Create a directory.| Parameter | Type | Required | Default | Description ||-----------|------|----------|---------|-------------|| uri | str | Yes | - | Viking URI for the new directory |+| description | str | No | `null` | Initial directory description. When provided, it is written to `.abstract.md` and queued for L0 vectorization. |**Python SDK (Embedded / HTTP)**```pythonclient.mkdir("viking://resources/new-project/")+client.mkdir("viking://resources/new-project/", description="API docs directory")```**HTTP API**@@ -458,7 +460,8 @@ curl -X POST http://localhost:1933/api/v1/fs/mkdir \-H "Content-Type: application/json" \-H "X-API-Key: your-key" \-d '{- "uri": "viking://resources/new-project/"+ "uri": "viking://resources/new-project/",+ "description": "API docs directory"}'```@@ -466,6 +469,7 @@ curl -X POST http://localhost:1933/api/v1/fs/mkdir \```bashopenviking mkdir viking://resources/new-project/+openviking mkdir viking://resources/new-project/ --description "API docs directory"```**Response**diff --git a/docs/zh/api/03-filesystem.md b/docs/zh/api/03-filesystem.mdindex f16af6cd1..a21a615e2 100644--- a/docs/zh/api/03-filesystem.md+++ b/docs/zh/api/03-filesystem.md@@ -440,11 +440,13 @@ openviking stat viking://resources/my-project/docs/api.md| 参数 | 类型 | 必填 | 默认值 | 说明 ||------|------|------|--------|------|| uri | str | 是 | - | 新目录的 Viking URI |+| description | str | 否 | `null` | 目录初始说明。传入后会写入 `.abstract.md`,并进入目录 L0 向量化队列。 |**Python SDK (Embedded / HTTP)**```pythonclient.mkdir("viking://resources/new-project/")+client.mkdir("viking://resources/new-project/", description="接口文档目录")```**HTTP API**@@ -458,7 +460,8 @@ curl -X POST http://localhost:1933/api/v1/fs/mkdir \-H "Content-Type: application/json" \-H "X-API-Key: your-key" \-d '{- "uri": "viking://resources/new-project/"+ "uri": "viking://resources/new-project/",+ "description": "接口文档目录"}'```@@ -466,6 +469,7 @@ curl -X POST http://localhost:1933/api/v1/fs/mkdir \```bashopenviking mkdir viking://resources/new-project/+openviking mkdir viking://resources/new-project/ --description "接口文档目录"```**响应**diff --git a/openviking/async_client.py b/openviking/async_client.pyindex 2042bbfa0..7c564cb93 100644--- a/openviking/async_client.py+++ b/openviking/async_client.py@@ -470,10 +470,10 @@ class AsyncOpenViking:node_limit=node_limit,)- async def mkdir(self, uri: str) -> None:+ async def mkdir(self, uri: str, description: Optional[str] = None) -> None:"""Create directory"""await self._ensure_initialized()- await self._client.mkdir(uri)+ await self._client.mkdir(uri, description=description)async def stat(self, uri: str) -> Dict:"""Get resource status"""diff --git a/openviking/client/local.py b/openviking/client/local.pyindex 874e78054..ab7ab6f51 100644--- a/openviking/client/local.py+++ b/openviking/client/local.py@@ -195,9 +195,9 @@ class LocalClient(BaseClient):"""Get resource status."""return await self._service.fs.stat(uri, ctx=self._ctx)- async def mkdir(self, uri: str) -> None:+ async def mkdir(self, uri: str, description: Optional[str] = None) -> None:"""Create directory."""- await self._service.fs.mkdir(uri, ctx=self._ctx)+ await self._service.fs.mkdir(uri, ctx=self._ctx, description=description)async def rm(self, uri: str, recursive: bool = False) -> None:"""Remove resource."""@@ -443,7 +443,6 @@ class LocalClient(BaseClient):If both content and parts are provided, parts takes precedence."""- from datetime import datetime, timezonefrom openviking.message.part import Part, TextPart, part_from_dictdiff --git a/openviking/server/routers/filesystem.py b/openviking/server/routers/filesystem.pyindex b5dcdb379..3bb9e88aa 100644--- a/openviking/server/routers/filesystem.py+++ b/openviking/server/routers/filesystem.py@@ -92,6 +92,7 @@ class MkdirRequest(BaseModel):"""Request model for mkdir."""uri: str+ description: Optional[str] = None@router.post("/mkdir")@@ -101,7 +102,7 @@ async def mkdir():"""Create directory."""service = get_service()- await service.fs.mkdir(request.uri, ctx=_ctx)+ await service.fs.mkdir(request.uri, ctx=_ctx, description=request.description)return Response(status="ok", result={"uri": request.uri})diff --git a/openviking/service/fs_service.py b/openviking/service/fs_service.pyindex 02a909ca7..026176c14 100644--- a/openviking/service/fs_service.py+++ b/openviking/service/fs_service.py@@ -8,11 +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_urifrom openviking.server.identity import RequestContextfrom openviking.storage.content_write import ContentWriteCoordinatorfrom openviking.storage.viking_fs import VikingFS+from openviking.utils.embedding_utils import vectorize_directory_metafrom openviking_cli.exceptions import NotInitializedError-from openviking_cli.utils import get_logger+from openviking_cli.utils import VikingURI, get_loggerlogger = get_logger(__name__)@@ -100,10 +102,42 @@ class FSService:)return entries- async def mkdir(self, uri: str, ctx: RequestContext) -> None:+ async def mkdir(+ self,+ uri: str,+ ctx: RequestContext,+ description: Optional[str] = None,+ ) -> None:"""Create directory."""viking_fs = self._ensure_initialized()await viking_fs.mkdir(uri, ctx=ctx)+ abstract = self._normalize_directory_description(description)+ if not abstract:+ return++ directory_uri, abstract_uri = self._resolve_directory_uris(uri)+ await viking_fs.write_file(abstract_uri, abstract, ctx=ctx)+ await vectorize_directory_meta(+ uri=directory_uri,+ abstract=abstract,+ overview="",+ context_type=get_context_type_for_uri(directory_uri),+ ctx=ctx,+ include_overview=False,+ )++ @staticmethod+ def _normalize_directory_description(description: Optional[str]) -> Optional[str]:+ if description is None:+ return None+ abstract = description.strip()+ return abstract or None++ @staticmethod+ def _resolve_directory_uris(uri: str) -> tuple[str, str]:+ abstract_uri = VikingURI(uri).join(".abstract.md").uri+ directory_uri = VikingURI(abstract_uri).parent.uri+ return directory_uri, abstract_uriasync def rm(self, uri: str, ctx: RequestContext, recursive: bool = False) -> None:"""Remove resource."""diff --git a/openviking/sync_client.py b/openviking/sync_client.pyindex 1f1067505..5d65d628c 100644--- a/openviking/sync_client.py+++ b/openviking/sync_client.py@@ -282,9 +282,7 @@ class SyncOpenViking:) -> Dict:"""Content search"""return run_async(- self._async_client.grep(- uri, pattern, case_insensitive, node_limit, exclude_uri- )+ self._async_client.grep(uri, pattern, case_insensitive, node_limit, exclude_uri))def glob(self, pattern: str, uri: str = "viking://") -> Dict:@@ -303,9 +301,9 @@ class SyncOpenViking:"""Get resource status"""return run_async(self._async_client.stat(uri))- def mkdir(self, uri: str) -> None:+ def mkdir(self, uri: str, description: Optional[str] = None) -> None:"""Create directory"""- return run_async(self._async_client.mkdir(uri))+ return run_async(self._async_client.mkdir(uri, description=description))def get_status(self):"""Get system status.diff --git a/openviking/utils/embedding_utils.py b/openviking/utils/embedding_utils.pyindex bb0e7dcf1..4d3b25b39 100644--- a/openviking/utils/embedding_utils.py+++ b/openviking/utils/embedding_utils.py@@ -135,6 +135,7 @@ async def vectorize_directory_meta(context_type: str = "resource",ctx: Optional[RequestContext] = None,semantic_msg_id: Optional[str] = None,+ include_overview: bool = True,) -> None:"""Vectorize directory metadata (.abstract.md and .overview.md).@@ -142,6 +143,7 @@ async def vectorize_directory_meta(Creates Context objects for abstract and overview and enqueues them."""enqueued = 0+ expected = 2 if include_overview else 1try:if not ctx:logger.warning("No context provided for vectorization")@@ -179,33 +181,34 @@ async def vectorize_directory_meta(exc_info=True,)- # Vectorize L1: .overview.md (overview)- context_overview = Context(- uri=uri,- parent_uri=parent_uri,- is_leaf=False,- abstract=abstract,- context_type=context_type,- level=ContextLevel.OVERVIEW,- user=ctx.user,- account_id=ctx.account_id,- owner_space=owner_space,- )- context_overview.set_vectorize(Vectorize(text=overview))- msg_overview = EmbeddingMsgConverter.from_context(context_overview)- if msg_overview:- msg_overview.semantic_msg_id = semantic_msg_id- try:- await embedding_queue.enqueue(msg_overview)- enqueued += 1- logger.debug(f"Enqueued directory L1 (overview) for vectorization: {uri}")- except Exception as e:- logger.error(- f"Failed to enqueue directory L1 (overview) for vectorization: {uri}: {e}",- exc_info=True,- )+ if include_overview:+ # Vectorize L1: .overview.md (overview)+ context_overview = Context(+ uri=uri,+ parent_uri=parent_uri,+ is_leaf=False,+ abstract=abstract,+ context_type=context_type,+ level=ContextLevel.OVERVIEW,+ user=ctx.user,+ account_id=ctx.account_id,+ owner_space=owner_space,+ )+ context_overview.set_vectorize(Vectorize(text=overview))+ msg_overview = EmbeddingMsgConverter.from_context(context_overview)+ if msg_overview:+ msg_overview.semantic_msg_id = semantic_msg_id+ try:+ await embedding_queue.enqueue(msg_overview)+ enqueued += 1+ logger.debug(f"Enqueued directory L1 (overview) for vectorization: {uri}")+ except Exception as e:+ logger.error(+ f"Failed to enqueue directory L1 (overview) for vectorization: {uri}: {e}",+ exc_info=True,+ )finally:- await _decrement_embedding_tracker(semantic_msg_id, 2 - enqueued)+ await _decrement_embedding_tracker(semantic_msg_id, expected - enqueued)async def vectorize_file(@@ -353,9 +356,7 @@ async def index_resource(overview = content.decode("utf-8")if abstract or overview:- await vectorize_directory_meta(- uri, abstract, overview, context_type=context_type, ctx=ctx- )+ await vectorize_directory_meta(uri, abstract, overview, context_type=context_type, ctx=ctx)# 2. Index Filestry:diff --git a/openviking_cli/client/base.py b/openviking_cli/client/base.pyindex 55c21b833..51abb0c8e 100644--- a/openviking_cli/client/base.py+++ b/openviking_cli/client/base.py@@ -96,7 +96,7 @@ class BaseClient(ABC):...@abstractmethod- async def mkdir(self, uri: str) -> None:+ async def mkdir(self, uri: str, description: Optional[str] = None) -> None:"""Create directory."""...@@ -182,7 +182,7 @@ class BaseClient(ABC):pattern: str,case_insensitive: bool = False,exclude_uri: Optional[str] = None,- node_limit: Optional[int] = None+ node_limit: Optional[int] = None,) -> Dict[str, Any]:"""Content search with pattern."""...diff --git a/openviking_cli/client/http.py b/openviking_cli/client/http.pyindex 470ce9e3d..198b50f2b 100644--- a/openviking_cli/client/http.py+++ b/openviking_cli/client/http.py@@ -491,12 +491,15 @@ class AsyncHTTPClient(BaseClient):)return self._handle_response(response)- async def mkdir(self, uri: str) -> None:+ async def mkdir(self, uri: str, description: Optional[str] = None) -> None:"""Create directory."""uri = VikingURI.normalize(uri)+ payload = {"uri": uri}+ if description is not None:+ payload["description"] = descriptionresponse = await self._http.post("/api/v1/fs/mkdir",- json={"uri": uri},+ json=payload,)self._handle_response(response)diff --git a/openviking_cli/client/sync_http.py b/openviking_cli/client/sync_http.pyindex d5cf7a301..2da8c2d8b 100644--- a/openviking_cli/client/sync_http.py+++ b/openviking_cli/client/sync_http.py@@ -312,9 +312,9 @@ class SyncHTTPClient:"""Get resource status."""return run_async(self._async_client.stat(uri))- def mkdir(self, uri: str) -> None:+ def mkdir(self, uri: str, description: Optional[str] = None) -> None:"""Create directory."""- run_async(self._async_client.mkdir(uri))+ run_async(self._async_client.mkdir(uri, description=description))def rm(self, uri: str, recursive: bool = False) -> None:"""Remove resource."""diff --git a/tests/api_test/api/client.py b/tests/api_test/api/client.pyindex b722321c5..4fbfd12cf 100644--- a/tests/api_test/api/client.py+++ b/tests/api_test/api/client.py@@ -335,10 +335,13 @@ class OpenVikingAPIClient:url = self._build_url(self.server_url, endpoint, params)return self._request_with_retry("GET", url)- def fs_mkdir(self, uri: str) -> requests.Response:+ def fs_mkdir(self, uri: str, description: Optional[str] = None) -> requests.Response:endpoint = "/api/v1/fs/mkdir"url = self._build_url(self.server_url, endpoint)- return self._request_with_retry("POST", url, json={"uri": uri})+ payload = {"uri": uri}+ if description is not None:+ payload["description"] = description+ return self._request_with_retry("POST", url, json=payload)def fs_read(self, uri: str) -> requests.Response:endpoint = "/api/v1/content/read"diff --git a/tests/client/test_filesystem.py b/tests/client/test_filesystem.pyindex 3b4bcb3d4..966d87b76 100644--- a/tests/client/test_filesystem.py+++ b/tests/client/test_filesystem.py@@ -157,6 +157,24 @@ class TestTree:assert isinstance(tree, (list, dict))+async def test_local_client_mkdir_forwards_description():+ client = LocalClient.__new__(LocalClient)+ client._ctx = RequestContext(user=UserIdentifier.the_default_user(), role=Role.USER)+ client._service = SimpleNamespace(fs=SimpleNamespace(mkdir=AsyncMock()))++ await LocalClient.mkdir(+ client,+ "viking://resources/demo-dir/",+ description="Demo directory",+ )++ client._service.fs.mkdir.assert_awaited_once_with(+ "viking://resources/demo-dir/",+ ctx=client._ctx,+ description="Demo directory",+ )++async def test_sync_openviking_write_updates_existing_file(test_data_dir, sample_markdown_file):"""Sync OpenViking exposes write() and delegates to the async client."""await AsyncOpenViking.reset()diff --git a/tests/server/test_api_filesystem.py b/tests/server/test_api_filesystem.pyindex 0c57b6ddb..f034056f5 100644--- a/tests/server/test_api_filesystem.py+++ b/tests/server/test_api_filesystem.py@@ -59,6 +59,43 @@ async def test_mkdir_and_ls(client: httpx.AsyncClient):assert resp.status_code == 200+async def test_mkdir_with_description_initializes_abstract_and_enqueues_l0(+ client: httpx.AsyncClient,+ monkeypatch,+):+ seen = {}++ async def _fake_vectorize_directory_meta(**kwargs):+ seen.update(kwargs)++ monkeypatch.setattr(+ "openviking.service.fs_service.vectorize_directory_meta",+ _fake_vectorize_directory_meta,+ )++ uri = "viking://resources/described_dir/"+ description = "Directory for API docs"+ resp = await client.post(+ "/api/v1/fs/mkdir",+ json={"uri": uri, "description": description},+ )+ assert resp.status_code == 200+ assert resp.json()["status"] == "ok"++ abstract_resp = await client.get(+ "/api/v1/content/abstract",+ params={"uri": uri},+ )+ assert abstract_resp.status_code == 200+ assert abstract_resp.json()["result"] == description+ assert seen["uri"] == "viking://resources/described_dir"+ assert seen["abstract"] == description+ assert seen["overview"] == ""+ assert seen["context_type"] == "resource"+ assert seen["include_overview"] is False+ assert seen["ctx"] is not None++async def test_tree(client: httpx.AsyncClient):resp = await client.get("/api/v1/fs/tree", params={"uri": "viking://"})assert resp.status_code == 200diff --git a/tests/server/test_http_client_sdk.py b/tests/server/test_http_client_sdk.pyindex 530694f9f..b7d92289f 100644--- a/tests/server/test_http_client_sdk.py+++ b/tests/server/test_http_client_sdk.py@@ -121,6 +121,17 @@ async def test_sdk_mkdir_and_ls(http_client):assert isinstance(result, list)+async def test_sdk_mkdir_with_description_sets_abstract(http_client):+ client, _ = http_client+ uri = "viking://resources/sdk_dir_desc/"+ description = "SDK directory description"++ await client.mkdir(uri, description=description)++ abstract = await client.abstract(uri)+ assert abstract == description++async def test_sdk_tree(http_client):client, _ = http_clientresult = await client.tree("viking://")