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(content-write): 支持 mode=create 创建新文件 (#1608)
A0nameless0man94699a8eb115
diff --git a/crates/ov_cli/src/commands/content.rs b/crates/ov_cli/src/commands/content.rsindex e032e9802..6938d073c 100644--- a/crates/ov_cli/src/commands/content.rs+++ b/crates/ov_cli/src/commands/content.rs@@ -42,7 +42,7 @@ pub async fn write(client: &HttpClient,uri: &str,content: &str,- append: bool,+ mode: &str,wait: bool,timeout: Option<f64>,output_format: OutputFormat,@@ -52,7 +52,7 @@ pub async fn write(.write(uri,content,- if append { "append" } else { "replace" },+ mode,wait,timeout,)diff --git a/crates/ov_cli/src/handlers.rs b/crates/ov_cli/src/handlers.rsindex 62c0c6ef1..5e7541a4e 100644--- a/crates/ov_cli/src/handlers.rs+++ b/crates/ov_cli/src/handlers.rs@@ -422,7 +422,7 @@ pub async fn handle_write(uri: String,content: Option<String>,from_file: Option<String>,- append: bool,+ mode: String,wait: bool,timeout: Option<f64>,ctx: CliContext,@@ -442,7 +442,7 @@ pub async fn handle_write(&client,&uri,&payload,- append,+ &mode,wait,timeout,ctx.output_format,diff --git a/crates/ov_cli/src/main.rs b/crates/ov_cli/src/main.rsindex 5913696da..676711a46 100644--- a/crates/ov_cli/src/main.rs+++ b/crates/ov_cli/src/main.rs@@ -297,6 +297,9 @@ enum Commands {/// Append instead of replacing the file#[arg(long)]append: bool,+ /// Write mode: replace, append, or create (default: replace)+ #[arg(long, value_name = "MODE", conflicts_with = "append")]+ mode: Option<String>,/// Wait for async processing to finish#[arg(long, default_value = "false")]wait: bool,@@ -877,9 +880,19 @@ async fn main() {content,from_file,append,+ mode,wait,timeout,- } => handlers::handle_write(uri, content, from_file, append, wait, timeout, ctx).await,+ } => {+ let effective_mode = if let Some(m) = mode {+ m+ } else if append {+ "append".to_string()+ } else {+ "replace".to_string()+ };+ handlers::handle_write(uri, content, from_file, effective_mode, wait, timeout, ctx).await+ }Commands::Reindex {uri,regenerate,diff --git a/openviking/server/routers/content.py b/openviking/server/routers/content.pyindex 09ba9046c..5326e42c9 100644--- a/openviking/server/routers/content.py+++ b/openviking/server/routers/content.py@@ -29,7 +29,7 @@ logger = get_logger(__name__)class WriteContentRequest(BaseModel):- """Request to write or append text content to an existing file."""+ """Request to write, append, or create text content to a file."""model_config = ConfigDict(extra="forbid")@@ -159,7 +159,7 @@ async def write(request: WriteContentRequest = Body(...),_ctx: RequestContext = Depends(get_request_context),):- """Write text content to an existing file and refresh semantics/vectors."""+ """Write text content to a file (replace, append, or create) and refresh semantics/vectors."""service = get_service()execution = await run_operation(operation="content.write",diff --git a/openviking/storage/content_write.py b/openviking/storage/content_write.pyindex 519dfc018..c88197227 100644--- a/openviking/storage/content_write.py+++ b/openviking/storage/content_write.py@@ -18,17 +18,25 @@ from openviking.telemetry import get_current_telemetryfrom openviking.telemetry.request_wait_tracker import get_request_wait_trackerfrom openviking.telemetry.resource_summary import build_queue_status_payloadfrom openviking.utils.embedding_utils import vectorize_file-from openviking_cli.exceptions import DeadlineExceededError, InvalidArgumentError, NotFoundError+from openviking_cli.exceptions import (+ AlreadyExistsError,+ DeadlineExceededError,+ InvalidArgumentError,+ NotFoundError,+)from openviking_cli.utils import VikingURIfrom openviking_cli.utils.logger import get_loggerlogger = get_logger(__name__)_DERIVED_FILENAMES = frozenset({".abstract.md", ".overview.md", ".relations.json"})+_CREATE_ALLOWED_EXTENSIONS = frozenset(+ {".md", ".txt", ".json", ".yaml", ".yml", ".toml", ".py", ".js", ".ts"}+)class ContentWriteCoordinator:- """Write an existing file and trigger downstream maintenance."""+ """Write a file (create or modify) and trigger downstream maintenance."""def __init__(self, viking_fs: VikingFS):self._viking_fs = viking_fs@@ -47,6 +55,15 @@ class ContentWriteCoordinator:self._validate_mode(mode)self._validate_target_uri(normalized_uri)+ if mode == "create":+ return await self._create_and_write(+ uri=normalized_uri,+ content=content,+ ctx=ctx,+ wait=wait,+ timeout=timeout,+ )+stat = await self._safe_stat(normalized_uri, ctx=ctx)if stat.get("isDir"):raise InvalidArgumentError(f"write only supports existing files, got directory: {uri}")@@ -129,7 +146,7 @@ class ContentWriteCoordinator:get_request_wait_tracker().cleanup(telemetry_id)def _validate_mode(self, mode: str) -> None:- if mode not in {"replace", "append"}:+ if mode not in {"replace", "append", "create"}:raise InvalidArgumentError(f"unsupported write mode: {mode}")def _validate_target_uri(self, uri: str) -> None:@@ -143,14 +160,130 @@ class ContentWriteCoordinator:if parsed.scope not in {"resources", "user", "agent"}:raise InvalidArgumentError(f"write is not supported for scope: {parsed.scope}")- async def _safe_stat(self, uri: str, *, ctx: RequestContext) -> Dict[str, Any]:+ def _is_not_found(self, exc: Exception) -> bool:+ """Check if an exception indicates a not-found error (OpenViking or AGFS)."""+ if isinstance(exc, NotFoundError):+ return True+ # AGFS raises its own AGFSNotFoundError which is unrelated to our NotFoundError+ try:+ from openviking.pyagfs import AGFSNotFoundError++ return isinstance(exc, AGFSNotFoundError)+ except ImportError:+ return False++ async def _safe_stat(+ self, uri: str, *, ctx: RequestContext, allow_not_found: bool = False+ ) -> Dict[str, Any]:try:return await self._viking_fs.stat(uri, ctx=ctx)except Exception as exc:- if isinstance(exc, NotFoundError):- raise+ if self._is_not_found(exc):+ if allow_not_found:+ return {"not_found": True}+ if isinstance(exc, NotFoundError):+ raise+ raise NotFoundError(uri, "file") from excraise NotFoundError(uri, "file") from exc+ def _validate_create_extension(self, uri: str) -> None:+ _, ext = os.path.splitext(uri)+ if ext.lower() not in _CREATE_ALLOWED_EXTENSIONS:+ raise InvalidArgumentError(f"create mode does not allow extension '{ext}': {uri}")++ async def _create_and_write(+ self,+ *,+ uri: str,+ content: str,+ ctx: RequestContext,+ wait: bool,+ timeout: Optional[float],+ ) -> Dict[str, Any]:+ self._validate_create_extension(uri)++ stat = await self._safe_stat(uri, ctx=ctx, allow_not_found=True)+ if not stat.get("not_found"):+ raise AlreadyExistsError(uri, "file")++ # VikingFS.write_file auto-creates parent directories+ await self._viking_fs.write_file(uri, content, ctx=ctx)++ context_type = self._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++ if context_type == "memory":+ return await self._write_memory_with_refresh(+ uri=uri,+ root_uri=root_uri,+ content=content,+ mode="create",+ wait=wait,+ timeout=timeout,+ ctx=ctx,+ written_bytes=written_bytes,+ telemetry_id=telemetry_id,+ )++ lock_manager = get_lock_manager()+ handle = lock_manager.create_handle()+ lock_path = self._viking_fs._uri_to_path(root_uri, ctx=ctx)+ acquired = await lock_manager.acquire_subtree(handle, lock_path)+ if not acquired:+ await lock_manager.release(handle)+ raise InvalidArgumentError(f"resource is busy and cannot be written now: {uri}")++ temp_root_uri = ""+ lock_transferred = False+ try:+ if wait and telemetry_id:+ get_request_wait_tracker().register_request(telemetry_id)+ temp_root_uri, temp_target_uri = await self._prepare_temp_write(+ uri=uri,+ root_uri=root_uri,+ content=content,+ mode="create",+ ctx=ctx,+ )+ await self._enqueue_semantic_refresh(+ temp_root_uri=temp_root_uri,+ target_root_uri=root_uri,+ temp_target_uri=temp_target_uri,+ context_type=context_type,+ ctx=ctx,+ lifecycle_lock_handle_id=handle.id,+ )+ lock_transferred = True+ queue_status = (+ await self._wait_for_request(telemetry_id=telemetry_id, timeout=timeout)+ if wait+ else None+ )+ return {+ "uri": uri,+ "root_uri": root_uri,+ "context_type": context_type,+ "mode": "create",+ "written_bytes": written_bytes,+ "semantic_updated": True,+ "vector_updated": True,+ "queue_status": queue_status,+ }+ except Exception:+ if not lock_transferred and temp_root_uri:+ try:+ await self._viking_fs.delete_temp(temp_root_uri, ctx=ctx)+ except Exception:+ logger.debug("Failed to clean temp tree after write failure", exc_info=True)+ if not lock_transferred:+ await lock_manager.release(handle)+ raise+ finally:+ if wait and telemetry_id:+ get_request_wait_tracker().cleanup(telemetry_id)+async def _write_in_place(self,uri: str,@@ -411,7 +544,13 @@ class ContentWriteCoordinator:if wait and telemetry_id:get_request_wait_tracker().cleanup(telemetry_id)- async def _resolve_root_uri(self, uri: str, *, ctx: RequestContext) -> str:+ async def _resolve_root_uri(+ self,+ uri: str,+ *,+ ctx: RequestContext,+ _allow_not_found: bool = False,+ ) -> str:parsed = VikingURI(uri)parts = [part for part in parsed.full_path.split("/") if part]if not parts:@@ -449,8 +588,8 @@ class ContentWriteCoordinator:)root_uri = VikingURI.build(*parts[: memories_idx + 2])- stat = await self._safe_stat(root_uri, ctx=ctx)- if not stat.get("isDir"):+ stat = await self._safe_stat(root_uri, ctx=ctx, allow_not_found=_allow_not_found)+ if stat.get("not_found") or not stat.get("isDir"):parent = VikingURI(uri).parentif parent is None:raise InvalidArgumentError(f"could not resolve write root for {uri}")diff --git a/tests/server/test_api_content_write.py b/tests/server/test_api_content_write.pyindex cea70741f..f70c001f6 100644--- a/tests/server/test_api_content_write.py+++ b/tests/server/test_api_content_write.py@@ -113,3 +113,117 @@ async def test_write_rejects_removed_semantic_flags(client_with_resource):)assert resp.status_code == 422+++async def test_api_create_mode_new_file_success(client):+ """Test create mode with a new file."""+ resp = await client.post(+ "/api/v1/content/write",+ json={+ "uri": "viking://user/default/memories/new_file.md",+ "content": "new content",+ "mode": "create",+ "wait": True,+ },+ )+ assert resp.status_code == 200+ body = resp.json()+ assert body["status"] == "ok"+ assert body["result"]["mode"] == "create"+++async def test_api_create_mode_write_then_read(client):+ """Create a new file then read it back — verify content roundtrips."""+ uri = "viking://user/default/memories/create_readback_test.md"++ write_resp = await client.post(+ "/api/v1/content/write",+ json={+ "uri": uri,+ "content": "# Hello\n\nWrite-then-read verification.",+ "mode": "create",+ "wait": True,+ },+ )+ assert write_resp.status_code == 200++ read_resp = await client.get("/api/v1/content/read", params={"uri": uri})+ assert read_resp.status_code == 200+ assert read_resp.json()["result"] == "# Hello\n\nWrite-then-read verification."+++async def test_api_create_mode_existing_file_409(client_with_resource):+ """Test create mode on an existing file should return 409."""+ client, uri = client_with_resource+ file_uri = await _first_file_uri(client, uri)++ resp = await client.post(+ "/api/v1/content/write",+ json={+ "uri": file_uri,+ "content": "new content",+ "mode": "create",+ "wait": True,+ },+ )+ assert resp.status_code == 409+ body = resp.json()+ assert body["status"] == "error"+ assert body["error"]["code"] == "ALREADY_EXISTS"+++async def test_api_create_mode_invalid_extension_400(client):+ """Test create mode with .exe extension should return 400."""+ resp = await client.post(+ "/api/v1/content/write",+ json={+ "uri": "viking://user/default/memories/test.exe",+ "content": "malicious content",+ "mode": "create",+ "wait": True,+ },+ )+ assert resp.status_code == 400+ body = resp.json()+ assert body["status"] == "error"+ assert "extension" in body["error"]["message"].lower()+++async def test_api_create_mode_empty_content_success(client):+ """Test create mode with empty content should succeed."""+ resp = await client.post(+ "/api/v1/content/write",+ json={+ "uri": "viking://user/default/memories/empty.md",+ "content": "",+ "mode": "create",+ "wait": True,+ },+ )+ assert resp.status_code == 200+ body = resp.json()+ assert body["status"] == "ok"+ assert body["result"]["mode"] == "create"+++async def test_api_create_mode_regression_replace_unchanged(client_with_resource):+ """Test replace mode still works (regression test)."""+ client, uri = client_with_resource+ file_uri = await _first_file_uri(client, uri)+ resp = await client.post(+ "/api/v1/content/write",+ json={+ "uri": file_uri,+ "content": "# Updated\n\nFresh content.",+ "mode": "replace",+ "wait": True,+ },+ )+ assert resp.status_code == 200+ body = resp.json()+ assert body["status"] == "ok"+ assert body["result"]["mode"] == "replace"++ read_resp = await client.get("/api/v1/content/read", params={"uri": file_uri})+ assert read_resp.status_code == 200+ assert read_resp.json()["result"] == "# Updated\n\nFresh content."diff --git a/tests/server/test_content_write_service.py b/tests/server/test_content_write_service.pyindex 6fb72c40a..0b42031f5 100644--- a/tests/server/test_content_write_service.py+++ b/tests/server/test_content_write_service.py@@ -8,7 +8,12 @@ import pytestfrom openviking.server.identity import RequestContext, Rolefrom openviking.session.memory.utils.content import deserialize_full, serialize_with_metadatafrom openviking.storage.content_write import ContentWriteCoordinator-from openviking_cli.exceptions import DeadlineExceededError, NotFoundError+from openviking_cli.exceptions import (+ AlreadyExistsError,+ DeadlineExceededError,+ InvalidArgumentError,+ NotFoundError,+)from openviking_cli.session.user_id import UserIdentifier@@ -262,3 +267,393 @@ async def test_memory_write_timeout_after_enqueue_does_not_release_lock(monkeypa)assert lock_manager.release_calls == []+++# Create-mode test helpers+++class _FakeVikingFSForCreate:+ """Variant of _FakeVikingFS that supports 'file doesn't exist' scenarios."""++ def __init__(self, file_uri: str, root_uri: str, file_exists: bool = True):+ self._file_uri = file_uri+ self._root_uri = root_uri+ self._file_exists = file_exists+ self.delete_temp_calls = []+ self.write_file_calls = []++ async def stat(self, uri: str, ctx=None):+ del ctx+ if uri == self._file_uri:+ if self._file_exists:+ return {"isDir": False}+ raise NotFoundError(uri, "file")+ if uri == self._root_uri:+ return {"isDir": True}+ # Parent directories should exist for creation+ if uri.startswith(self._root_uri) and uri != self._file_uri:+ return {"isDir": True}+ raise NotFoundError(uri, "path")++ def _uri_to_path(self, uri: str, ctx=None):+ del ctx+ return f"/fake/{uri.replace('://', '/').strip('/')}"++ async def delete_temp(self, temp_uri: str, ctx=None):+ del ctx+ self.delete_temp_calls.append(temp_uri)++ async def write_file(self, uri: str, content: str, *, ctx=None):+ del ctx+ self.write_file_calls.append((uri, content))+++# Create-mode tests+++async def test_create_mode_new_file_success(monkeypatch):+ file_uri = "viking://user/default/memories/new_file.md"+ root_uri = "viking://user/default/memories"+ 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)+ lock_manager = _FakeLockManager()++ monkeypatch.setattr("openviking.storage.content_write.get_lock_manager", lambda: lock_manager)++ async def _fake_write_in_place(uri, content, *, mode, ctx):+ del uri, mode, ctx+ return content++ async def _fake_vectorize_single_file(uri, *, context_type, ctx):+ del uri, context_type, ctx+ return None++ async def _fake_enqueue_memory_refresh(**kwargs):+ del kwargs+ return None++ async def _fake_wait_for_queues(*, timeout):+ del timeout+ return None++ monkeypatch.setattr(coordinator, "_write_in_place", _fake_write_in_place)+ monkeypatch.setattr(coordinator, "_vectorize_single_file", _fake_vectorize_single_file)+ monkeypatch.setattr(coordinator, "_enqueue_memory_refresh", _fake_enqueue_memory_refresh)+ monkeypatch.setattr(coordinator, "_wait_for_queues", _fake_wait_for_queues)++ result = await coordinator.write(+ uri=file_uri, content="new content", mode="create", ctx=ctx, wait=True+ )++ assert result["mode"] == "create"+++async def test_create_mode_existing_file_raises_409(monkeypatch):+ file_uri = "viking://user/default/memories/existing.md"+ root_uri = "viking://user/default/memories"+ ctx = RequestContext(user=UserIdentifier.the_default_user(), role=Role.USER)+ viking_fs = _FakeVikingFSForCreate(file_uri=file_uri, root_uri=root_uri, file_exists=True)+ coordinator = ContentWriteCoordinator(viking_fs=viking_fs)++ async def _fake_write_in_place(uri, content, *, mode, ctx):+ del uri, content, mode, ctx+ return None++ async def _fake_vectorize_single_file(uri, *, context_type, ctx):+ del uri, context_type, ctx+ return None++ async def _fake_enqueue_memory_refresh(**kwargs):+ del kwargs+ return None++ async def _fake_wait_for_queues(*, timeout):+ del timeout+ return None++ monkeypatch.setattr(coordinator, "_write_in_place", _fake_write_in_place)+ monkeypatch.setattr(coordinator, "_vectorize_single_file", _fake_vectorize_single_file)+ monkeypatch.setattr(coordinator, "_enqueue_memory_refresh", _fake_enqueue_memory_refresh)+ monkeypatch.setattr(coordinator, "_wait_for_queues", _fake_wait_for_queues)++ with pytest.raises(AlreadyExistsError):+ await coordinator.write(uri=file_uri, content="content", mode="create", ctx=ctx, wait=True)+++async def test_create_mode_invalid_extension_raises_400(monkeypatch):+ file_uri = "viking://user/default/memories/test.exe"+ root_uri = "viking://user/default/memories"+ 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)++ async def _fake_write_in_place(uri, content, *, mode, ctx):+ del uri, content, mode, ctx+ return None++ async def _fake_vectorize_single_file(uri, *, context_type, ctx):+ del uri, context_type, ctx+ return None++ async def _fake_enqueue_memory_refresh(**kwargs):+ del kwargs+ return None++ async def _fake_wait_for_queues(*, timeout):+ del timeout+ return None++ monkeypatch.setattr(coordinator, "_write_in_place", _fake_write_in_place)+ monkeypatch.setattr(coordinator, "_vectorize_single_file", _fake_vectorize_single_file)+ monkeypatch.setattr(coordinator, "_enqueue_memory_refresh", _fake_enqueue_memory_refresh)+ monkeypatch.setattr(coordinator, "_wait_for_queues", _fake_wait_for_queues)++ with pytest.raises(InvalidArgumentError):+ await coordinator.write(uri=file_uri, content="content", mode="create", ctx=ctx, wait=True)+++async def test_create_mode_parent_dirs_auto_created(monkeypatch):+ file_uri = "viking://user/default/memories/new_subdir/test.md"+ root_uri = "viking://user/default/memories"+ 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)+ lock_manager = _FakeLockManager()++ monkeypatch.setattr("openviking.storage.content_write.get_lock_manager", lambda: lock_manager)++ async def _fake_write_in_place(uri, content, *, mode, ctx):+ del uri, mode, ctx+ return content++ async def _fake_vectorize_single_file(uri, *, context_type, ctx):+ del uri, context_type, ctx+ return None++ async def _fake_enqueue_memory_refresh(**kwargs):+ del kwargs+ return None++ async def _fake_wait_for_queues(*, timeout):+ del timeout+ return None++ monkeypatch.setattr(coordinator, "_write_in_place", _fake_write_in_place)+ monkeypatch.setattr(coordinator, "_vectorize_single_file", _fake_vectorize_single_file)+ monkeypatch.setattr(coordinator, "_enqueue_memory_refresh", _fake_enqueue_memory_refresh)+ monkeypatch.setattr(coordinator, "_wait_for_queues", _fake_wait_for_queues)++ await coordinator.write(+ uri=file_uri, content="nested content", mode="create", ctx=ctx, wait=True+ )++ assert len(viking_fs.write_file_calls) > 0+++async def test_create_mode_valid_extensions_pass(monkeypatch):+ ctx = RequestContext(user=UserIdentifier.the_default_user(), role=Role.USER)++ # Test a representative set of valid extensions+ valid_extensions = [".md", ".txt", ".json", ".yaml", ".yml", ".py", ".js", ".ts"]++ for ext in valid_extensions:+ file_uri = f"viking://user/default/memories/test{ext}"+ root_uri = "viking://user/default/memories"+ viking_fs = _FakeVikingFSForCreate(file_uri=file_uri, root_uri=root_uri, file_exists=False)+ coordinator = ContentWriteCoordinator(viking_fs=viking_fs)+ lock_manager = _FakeLockManager()++ _captured_lock = lock_manager++ monkeypatch.setattr(+ "openviking.storage.content_write.get_lock_manager", lambda _l=_captured_lock: _l+ )++ async def _fake_write_in_place(uri, content, *, mode, ctx):+ del uri, mode, ctx+ return content++ async def _fake_vectorize_single_file(uri, *, context_type, ctx):+ del uri, context_type, ctx+ return None++ async def _fake_enqueue_memory_refresh(**kwargs):+ del kwargs+ return None++ async def _fake_wait_for_queues(*, timeout):+ del timeout+ return None++ monkeypatch.setattr(coordinator, "_write_in_place", _fake_write_in_place)+ monkeypatch.setattr(coordinator, "_vectorize_single_file", _fake_vectorize_single_file)+ monkeypatch.setattr(coordinator, "_enqueue_memory_refresh", _fake_enqueue_memory_refresh)+ monkeypatch.setattr(coordinator, "_wait_for_queues", _fake_wait_for_queues)++ result = await coordinator.write(+ uri=file_uri, content="content", mode="create", ctx=ctx, wait=True+ )+ assert result["mode"] == "create"+++async def test_create_mode_memory_scope(monkeypatch):+ file_uri = "viking://user/default/memories/test.md"+ root_uri = "viking://user/default/memories"+ 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)+ lock_manager = _FakeLockManager()++ monkeypatch.setattr("openviking.storage.content_write.get_lock_manager", lambda: lock_manager)++ async def _fake_write_in_place(uri, content, *, mode, ctx):+ del uri, mode, ctx+ return content++ async def _fake_vectorize_single_file(uri, *, context_type, ctx):+ # Verify memory-scope URIs take the memory write path+ assert context_type == "memory"+ del uri, ctx+ return None++ async def _fake_enqueue_memory_refresh(**kwargs):+ del kwargs+ return None++ async def _fake_wait_for_queues(*, timeout):+ del timeout+ return None++ monkeypatch.setattr(coordinator, "_write_in_place", _fake_write_in_place)+ monkeypatch.setattr(coordinator, "_vectorize_single_file", _fake_vectorize_single_file)+ monkeypatch.setattr(coordinator, "_enqueue_memory_refresh", _fake_enqueue_memory_refresh)+ monkeypatch.setattr(coordinator, "_wait_for_queues", _fake_wait_for_queues)++ result = await coordinator.write(+ uri=file_uri, content="content", mode="create", ctx=ctx, wait=True+ )+ assert result["context_type"] == "memory"+++async def test_create_mode_resource_scope(monkeypatch):+ file_uri = "viking://resources/demo/test.md"+ 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)+ lock_manager = _FakeLockManager()++ monkeypatch.setattr("openviking.storage.content_write.get_lock_manager", lambda: lock_manager)++ async def _fake_prepare_temp_write(**kwargs):+ del kwargs+ return "viking://temp/demo", "viking://temp/demo/test.md"++ async def _fake_enqueue_semantic_refresh(**kwargs):+ # Verify resource-scope URIs take the resource write path+ assert kwargs["context_type"] == "resource"+ del kwargs+ return None++ async def _fake_wait_for_queues(*, timeout):+ del timeout+ return None++ monkeypatch.setattr(coordinator, "_prepare_temp_write", _fake_prepare_temp_write)+ monkeypatch.setattr(coordinator, "_enqueue_semantic_refresh", _fake_enqueue_semantic_refresh)+ monkeypatch.setattr(coordinator, "_wait_for_queues", _fake_wait_for_queues)++ result = await coordinator.write(+ uri=file_uri, content="content", mode="create", ctx=ctx, wait=True+ )+ assert result["context_type"] == "resource"+++async def test_create_mode_regression_replace_unchanged(monkeypatch):+ file_uri = "viking://user/default/memories/theme.md"+ root_uri = "viking://user/default/memories"+ ctx = RequestContext(user=UserIdentifier.the_default_user(), role=Role.USER)+ viking_fs = _FakeVikingFSForCreate(file_uri=file_uri, root_uri=root_uri, file_exists=True)+ coordinator = ContentWriteCoordinator(viking_fs=viking_fs)+ lock_manager = _FakeLockManager()++ monkeypatch.setattr("openviking.storage.content_write.get_lock_manager", lambda: lock_manager)++ async def _fake_write_in_place(uri, content, *, mode, ctx):+ # Verify mode="replace" still works+ assert mode == "replace"+ del uri, content, ctx+ return None++ async def _fake_vectorize_single_file(uri, *, context_type, ctx):+ del uri, context_type, ctx+ return None++ async def _fake_enqueue_memory_refresh(**kwargs):+ del kwargs+ return None++ async def _fake_wait_for_queues(*, timeout):+ del timeout+ return None++ monkeypatch.setattr(coordinator, "_write_in_place", _fake_write_in_place)+ monkeypatch.setattr(coordinator, "_vectorize_single_file", _fake_vectorize_single_file)+ monkeypatch.setattr(coordinator, "_enqueue_memory_refresh", _fake_enqueue_memory_refresh)+ monkeypatch.setattr(coordinator, "_wait_for_queues", _fake_wait_for_queues)++ result = await coordinator.write(+ uri=file_uri, content="updated", ctx=ctx, mode="replace", wait=True+ )++ assert result["mode"] == "replace"+++async def test_create_mode_regression_append_unchanged(monkeypatch):+ file_uri = "viking://user/default/memories/theme.md"+ root_uri = "viking://user/default/memories"+ ctx = RequestContext(user=UserIdentifier.the_default_user(), role=Role.USER)+ viking_fs = _FakeVikingFSForCreate(file_uri=file_uri, root_uri=root_uri, file_exists=True)+ coordinator = ContentWriteCoordinator(viking_fs=viking_fs)+ lock_manager = _FakeLockManager()++ monkeypatch.setattr("openviking.storage.content_write.get_lock_manager", lambda: lock_manager)++ async def _fake_write_in_place(uri, content, *, mode, ctx):+ # Verify mode="append" still works+ assert mode == "append"+ del uri, content, ctx+ return None++ async def _fake_vectorize_single_file(uri, *, context_type, ctx):+ del uri, context_type, ctx+ return None++ async def _fake_enqueue_memory_refresh(**kwargs):+ del kwargs+ return None++ async def _fake_wait_for_queues(*, timeout):+ del timeout+ return None++ monkeypatch.setattr(coordinator, "_write_in_place", _fake_write_in_place)+ monkeypatch.setattr(coordinator, "_vectorize_single_file", _fake_vectorize_single_file)+ monkeypatch.setattr(coordinator, "_enqueue_memory_refresh", _fake_enqueue_memory_refresh)+ monkeypatch.setattr(coordinator, "_wait_for_queues", _fake_wait_for_queues)++ result = await coordinator.write(+ uri=file_uri, content="appended", ctx=ctx, mode="append", wait=True+ )++ assert result["mode"] == "append"