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
fix: create missing files on content write (#4360)
Jiahui Zhou9952ce1ec644
diff --git a/docs/en/api/12-content.md b/docs/en/api/12-content.mdindex 89f21e121..dd6d6305b 100644--- a/docs/en/api/12-content.md+++ b/docs/en/api/12-content.md@@ -210,22 +210,22 @@ openviking read viking://resources/docs/api.md### write()-Update an existing file, or create a new one when `mode="create"`, and automatically refresh related semantics and vectors.+Write a file and automatically refresh related semantics and vectors.**Parameters**| Parameter | Type | Required | Default | Description ||-----------|------|----------|---------|-------------|-| uri | str | Yes | - | File URI to write. For `mode="create"`, the file must not already exist |+| uri | str | Yes | - | File URI to write || content | str | Yes | - | New content to write |-| mode | str | No | `replace` | `replace`, `append`, or `create` |+| mode | str | No | `replace` | `replace` overwrites an existing file or creates a missing file; `append` appends to an existing file or creates a missing file; `create` creates only a missing file and returns `409 Conflict` if it already exists || wait | bool | No | `false` | Wait for background semantic/vector refresh || timeout | float | No | `null` | Timeout in seconds when `wait=true` |**Notes**-- `replace` and `append` require the file to exist; `create` targets a new file and returns `409 Conflict` when the path already exists. Directories are always rejected.-- `create` only accepts text-writable extensions: `.md`, `.txt`, `.json`, `.yaml`, `.yml`, `.toml`, `.py`, `.js`, `.ts`. Parent directories are created automatically.+- `replace` and `append` create a missing target file. `append` uses the supplied content as the initial file content in that case. `create` targets only a missing file and returns `409 Conflict` when the path already exists. Directories are always rejected.+- Explicit `create` only accepts text-writable extensions: `.md`, `.txt`, `.json`, `.yaml`, `.yml`, `.toml`, `.py`, `.js`, `.ts`. Parent directories are created automatically for every write mode.- Existing `.abstract.md` and `.overview.md` bodies may be updated, but public APIs cannot create them. A body-only request preserves stored OKF metadata; a full-OKF request must match the stored metadata. Unknown metadata fields are silently dropped. A sidecar body write rebuilds only the directory's existing L0/L1 vectors and does not regenerate semantics.- File content is updated before the API returns. `wait` only controls whether the call waits for semantic/vector refresh to finish.- The public API no longer accepts `regenerate_semantics` or `revectorize`; write always refreshes related semantics and vectors.diff --git a/docs/en/guides/06-mcp-integration.md b/docs/en/guides/06-mcp-integration.mdindex deba945f7..2bbc702b8 100644--- a/docs/en/guides/06-mcp-integration.md+++ b/docs/en/guides/06-mcp-integration.md@@ -139,7 +139,7 @@ Once connected, OpenViking exposes 15 tools:| `list` | List entries under a `viking://` directory | `uri`, `recursive` (optional) || `tree` | Show the recursive directory tree under a `viking://` URI, indented by depth — use when you need a full picture of the file tree (prefer `list` for a single level, `glob` for filename patterns) | `uri` (optional), `level_limit` (default 3), `node_limit` (default 1000), `include_abstract` (optional — also show each file's summary) || `remember` | Store messages into long-term memory (triggers extraction) | `messages` (list of `{role, content}`) |-| `write` | Write text to a `viking://` file (create/overwrite/append). Parent directories are created automatically; use `read` first to see current content before overwriting, and prefer `edit` for changing part of an existing file | `uri`, `content`, `mode` (optional: `replace` default — creates the file if missing, `append`, `create` — fail if it exists), `wait` (optional, block until re-indexed), `timeout` (optional) |+| `write` | Write text to a `viking://` file (create/overwrite/append). Parent directories are created automatically; use `read` first to see current content before overwriting, and prefer `edit` for changing part of an existing file | `uri`, `content`, `mode` (optional: `replace` default — overwrites or creates if missing; `append` — appends or creates if missing; `create` — fails if it exists), `wait` (optional, block until re-indexed), `timeout` (optional) || `edit` | Replace an exact string with new text in an existing `viking://` file — for targeted changes instead of a full rewrite. The file is left unchanged if `old_string` is not found, or matches multiple times while `replace_all` is false | `uri`, `old_string`, `new_string`, `replace_all` (optional), `wait` (optional, block until re-indexed), `timeout` (optional) || `add_resource` | Add a local file or URL as a resource (local files trigger a progressive upload flow) | `path`, `temp_file_id` (optional), `description` (optional), `watch_interval` (optional, minutes — auto-refresh cadence for remote URLs), `processing_mode` (optional: `semantic_and_vectors` default, or `vectors_only` to skip VLM semantic understanding and only vectorize current files), `to` (optional, target `viking://resources/...` URI; if omitted when `watch_interval > 0`, the watch auto-binds to the resource's created URI), `args` (optional parser-specific options, including `{"parse_mode":"no_split"}` to parse each source document into one Markdown body, `{"feishu_access_token":"u-..."}` for one-time Feishu user-token imports, or `{"feishu_access_token":"u-...","feishu_refresh_token":"r-..."}` for Feishu user-token watches) || `list_watches` | List watch tasks (auto-refresh subscriptions) visible to the current agent. Each entry shows target URI, refresh interval (minutes), active/paused status, and next scheduled execution time | none |diff --git a/docs/zh/agent-integrations/16-capability-reference.md b/docs/zh/agent-integrations/16-capability-reference.mdindex 1282cdc4d..b85f611b7 100644--- a/docs/zh/agent-integrations/16-capability-reference.md+++ b/docs/zh/agent-integrations/16-capability-reference.md@@ -94,7 +94,7 @@ per-harness 章节(档案卡)只写差异;所有共享事实均在本章| 4 | `list` | 列目录(函数名 `ls`,注册名显式改写为 `list`) | `recursive=False`(`:423`) || 5 | `tree` | 递归目录树 | `level_limit=3, node_limit=1000, include_abstract=False`(`:449`) || 6 | `remember` | 写长期记忆 | 内部建一次性会话 `mcp-store-<uuid12>` 并立即 `commit_async`(`:504-523`)——这是 MCP 面唯一的 commit 入口;MCP 没有显式 commit 工具 |-| 7 | `write` | 写 `viking://` 文件 | `mode=replace\|append\|create`,replace 遇 NotFound 自动降级 create;新建文件扩展名白名单 `.md .txt .json .yaml .yml .toml .py .js .ts`;可写域 `resources/user/agent`;用户根下 `skills/ peers/ privacy/ sessions/` 只读;已存在的 `.abstract.md/.overview.md` sidecar 可改正文,但公共 API 不能创建(`:529`;`content_write.py:60-81`) |+| 7 | `write` | 写 `viking://` 文件 | `mode=replace\|append\|create`:replace 覆盖或在缺失时创建,append 追加或在缺失时创建,create 仅创建缺失文件且已存在时返回冲突;显式 create 的文件扩展名白名单为 `.md .txt .json .yaml .yml .toml .py .js .ts`;可写域 `resources/user/agent`;用户根下 `skills/ peers/ privacy/ sessions/` 只读;已存在的 `.abstract.md/.overview.md` sidecar 可改正文,但公共 API 不能创建(`:529`;`content_write.py:60-81`) || 8 | `edit` | 精确字符串替换 | `old_string` 空/0 命中/多命中且非 replace_all 均报错,且文件内容不变(`:569`) || 9 | `add_resource` | 资源摄取(远程 URL / 本地文件签名上传 / Connector) | `watch_interval` 单位为分钟(0=不 watch);本地路径分支返回签名上传 URL(TTL 默认 600s),上传后自动入库,无需二次调用(`:723-947`) || 10 | `list_watches` | 列 watch 订阅,商业版尚未支持 | scheduler 未运行时返回错误串(`:958`) |diff --git a/docs/zh/api/12-content.md b/docs/zh/api/12-content.mdindex 21c052ff6..e00ba6211 100644--- a/docs/zh/api/12-content.md+++ b/docs/zh/api/12-content.md@@ -210,22 +210,22 @@ openviking read viking://resources/docs/api.md### write()-修改一个已存在的文件,或在 `mode="create"` 时创建新文件,并自动刷新相关语义与向量。+写入文件,并自动刷新相关语义与向量。**参数**| 参数 | 类型 | 必填 | 默认值 | 说明 ||------|------|------|--------|------|-| uri | str | 是 | - | 要写入的文件 URI。`mode="create"` 时目标文件必须不存在 |+| uri | str | 是 | - | 要写入的文件 URI || content | str | 是 | - | 要写入的新内容 |-| mode | str | 否 | `replace` | `replace`、`append` 或 `create` |+| mode | str | 否 | `replace` | `replace` 覆盖已有文件、缺失时创建;`append` 追加已有文件、缺失时创建;`create` 仅创建缺失文件,目标已存在时返回 `409 Conflict` || wait | bool | 否 | `false` | 是否等待后台语义/向量刷新完成 || timeout | float | 否 | `null` | 当 `wait=true` 时的超时时间(秒) |**说明**-- `replace` 和 `append` 要求文件已存在;`create` 仅用于创建新文件,目标路径已存在时返回 `409 Conflict`。目录始终会被拒绝。-- `create` 只允许以下文本类扩展名:`.md`、`.txt`、`.json`、`.yaml`、`.yml`、`.toml`、`.py`、`.js`、`.ts`。父目录会自动创建。+- `replace` 和 `append` 在目标文件缺失时都会创建文件;其中 `append` 会以传入内容作为新文件的初始内容。`create` 仅用于创建缺失文件,目标路径已存在时返回 `409 Conflict`。目录始终会被拒绝。+- 显式 `create` 只允许以下文本类扩展名:`.md`、`.txt`、`.json`、`.yaml`、`.yml`、`.toml`、`.py`、`.js`、`.ts`。所有写入模式都会自动创建父目录。- 已存在的 `.abstract.md` / `.overview.md` 可以修改正文,但不能通过公共 API 创建;只提交正文时会保留现有 OKF metadata,提交完整 OKF 时 metadata 必须与存量值一致。未知 metadata 字段会静默丢弃。sidecar 正文写入只重建该目录实际存在的 L0/L1 向量,不触发语义重新生成。- 文件内容会在 API 返回前完成更新;`wait` 只控制是否等待语义/向量刷新完成。- 公共 API 已不再接受 `regenerate_semantics` 或 `revectorize`;写入后一定会自动刷新相关语义与向量。diff --git a/docs/zh/guides/06-mcp-integration.md b/docs/zh/guides/06-mcp-integration.mdindex 5e8f4c9c2..1e4cba8ce 100644--- a/docs/zh/guides/06-mcp-integration.md+++ b/docs/zh/guides/06-mcp-integration.md@@ -131,7 +131,7 @@ claude mcp add --transport http openviking \| `list` | 列出 `viking://` 目录下的条目 | `uri`, `recursive`(可选) || `tree` | 以缩进形式展示 `viking://` URI 下的递归目录树——当需要全面了解文件树结构时使用(单层列表用 `list`,按文件名查找用 `glob`) | `uri`(可选), `level_limit`(默认 3), `node_limit`(默认 1000), `include_abstract`(可选——同时展示每个文件的摘要) || `remember` | 存储消息到长期记忆(触发记忆提取) | `messages`(`{role, content}` 列表) |-| `write` | 向 `viking://` 文件写入文本(创建/覆盖/追加)。自动创建缺失的父目录;覆盖前请先用 `read` 查看当前内容;只改文件局部时优先用 `edit` | `uri`, `content`, `mode`(可选:默认 `replace` — 文件不存在时自动创建,`append` 追加,`create` — 已存在则失败), `wait`(可选,阻塞直到重建索引完成), `timeout`(可选) |+| `write` | 向 `viking://` 文件写入文本(创建/覆盖/追加)。自动创建缺失的父目录;覆盖前请先用 `read` 查看当前内容;只改文件局部时优先用 `edit` | `uri`, `content`, `mode`(可选:默认 `replace` — 覆盖或在缺失时创建,`append` — 追加或在缺失时创建,`create` — 已存在则失败), `wait`(可选,阻塞直到重建索引完成), `timeout`(可选) || `edit` | 在已有 `viking://` 文件中把精确字符串替换为新文本——用于局部修改,避免整文件重写。若 `old_string` 找不到、或匹配多处且 `replace_all` 为 false,则编辑失败且文件保持不变 | `uri`, `old_string`, `new_string`, `replace_all`(可选), `wait`(可选,阻塞直到重建索引完成), `timeout`(可选) || `add_resource` | 添加本地文件或 URL 作为资源(本地文件触发渐进式上传流) | `path`, `temp_file_id`(可选), `description`(可选), `watch_interval`(可选,分钟数 — 远程 URL 的自动刷新周期), `processing_mode`(可选:默认 `semantic_and_vectors`;传 `vectors_only` 时跳过 VLM 语义理解,只向量化当前文件), `to`(可选,目标 `viking://resources/...` URI;`watch_interval > 0` 时若省略 `to`,watch 将自动绑定到本次 add 创建的资源 URI), `args`(可选,特定 parser 参数,包括 `{"parse_mode":"no_split"}` 用于正常解析但每个源文档只生成一个 Markdown 正文、飞书一次性用户 token 导入使用 `{"feishu_access_token":"u-..."}`,或飞书用户 token watch 使用 `{"feishu_access_token":"u-...","feishu_refresh_token":"r-..."}`) || `list_watches` | 列出当前 Agent 可见的 watch 任务(自动刷新订阅),每行显示目标 URI、刷新间隔(分钟)、active/paused 状态以及下一次调度时间 | 无 |diff --git a/openviking/storage/content_write.py b/openviking/storage/content_write.pyindex fb829bd2d..2c8838dbb 100644--- a/openviking/storage/content_write.py+++ b/openviking/storage/content_write.py@@ -141,7 +141,20 @@ class ContentWriteCoordinator:processing_mode=processing_mode,)- stat = await self._safe_stat(normalized_uri, ctx=ctx)+ stat = await self._safe_stat(normalized_uri, ctx=ctx, allow_not_found=True)+ if stat.get("not_found"):+ # replace and append are idempotent writes: a missing target starts+ # from an empty file while retaining the caller's requested mode.+ return await self._create_and_write(+ uri=normalized_uri,+ content=content,+ ctx=ctx,+ wait=wait,+ timeout=timeout,+ processing_mode=processing_mode,+ result_mode=mode,+ validate_extension=False,+ )if stat.get("isDir"):raise InvalidArgumentError(f"write only supports existing files, got directory: {normalized_uri}"@@ -750,6 +763,7 @@ class ContentWriteCoordinator:root_uri: str,content: str,mode: str,+ response_mode: Optional[str] = None,context_type: str,wait: bool,timeout: Optional[float],@@ -1014,10 +1028,13 @@ class ContentWriteCoordinator:wait: bool,timeout: Optional[float],processing_mode: ProcessingMode,+ result_mode: str = "create",+ validate_extension: bool = True,) -> Dict[str, Any]:if is_abstract_overview_uri(uri):raise InvalidArgumentError(f"cannot create generated abstract overview directly: {uri}")- self._validate_create_extension(uri)+ if validate_extension:+ self._validate_create_extension(uri)stat = await self._safe_stat(uri, ctx=ctx, allow_not_found=True)if not stat.get("not_found"):@@ -1036,6 +1053,7 @@ class ContentWriteCoordinator:root_uri=root_uri,content=content,mode="create",+ response_mode=result_mode,wait=wait,timeout=timeout,ctx=ctx,@@ -1049,6 +1067,7 @@ class ContentWriteCoordinator:root_uri=root_uri,content=content,mode="create",+ response_mode=result_mode,context_type=context_type,wait=wait,timeout=timeout,@@ -1176,6 +1195,7 @@ class ContentWriteCoordinator:root_uri: str,content: str,mode: str,+ response_mode: Optional[str] = None,wait: bool,timeout: Optional[float],ctx: RequestContext,@@ -1231,7 +1251,7 @@ class ContentWriteCoordinator:uri=uri,root_uri=root_uri,context_type="memory",- mode=mode,+ mode=response_mode or mode,written_bytes=written_bytes,wait=wait,queue_status=queue_status,diff --git a/tests/server/test_content_write_service.py b/tests/server/test_content_write_service.pyindex a5494d8d4..306791117 100644--- a/tests/server/test_content_write_service.py+++ b/tests/server/test_content_write_service.py@@ -821,6 +821,40 @@ class _FakeVikingFSForCreate:# Create-mode tests[email protected]("mode", ["replace", "append"])+async def test_replace_and_append_create_missing_file(monkeypatch, mode):+ file_uri = "viking://resources/demo/missing.csv"+ root_uri = "viking://resources/demo"+ ctx = RequestContext(user=UserIdentifier.the_default_user(), role=Role.USER)+ viking_fs = _FakeVikingFSForCreate(file_uri=file_uri, root_uri=root_uri, file_exists=False)+ coordinator = ContentWriteCoordinator(viking_fs=viking_fs)++ refresh_calls = []+ write_calls = []++ async def _fake_write_in_place(uri, content, *, mode, ctx, lease_ref=None, existing_raw=None):+ del ctx, lease_ref, existing_raw+ write_calls.append((uri, content, mode))+ viking_fs.content[uri] = content++ async def _fake_enqueue_semantic_refresh(**kwargs):+ refresh_calls.append(kwargs)+ return None++ monkeypatch.setattr(coordinator, "_write_in_place", _fake_write_in_place)+ monkeypatch.setattr(coordinator, "_enqueue_semantic_refresh", _fake_enqueue_semantic_refresh)++ result = await coordinator.write(+ uri=file_uri, content="new content", mode=mode, ctx=ctx, wait=False+ )++ assert result["mode"] == mode+ assert viking_fs.content[file_uri] == "new content"+ assert write_calls == [(file_uri, "new content", "create")]+ assert refresh_calls[0]["change_type"] == "added"++@pytest.mark.asyncioasync def test_create_mode_new_file_success(monkeypatch):file_uri = "viking://user/default/memories/new_file.md"