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: support processing mode for content write (#3615)
Jiahui Zhou6f43a4040cbe
diff --git a/crates/ov_cli/src/client.rs b/crates/ov_cli/src/client.rsindex 6a34df5f3..084518a9f 100644--- a/crates/ov_cli/src/client.rs+++ b/crates/ov_cli/src/client.rs@@ -387,8 +387,9 @@ impl HttpClient {mode: &str,wait: bool,timeout: Option<f64>,+ processing_mode: &str,) -> Result<serde_json::Value> {- let body = Self::build_write_body(uri, content, mode, wait, timeout);+ let body = Self::build_write_body(uri, content, mode, wait, timeout, processing_mode);self.post("/api/v1/content/write", &body).await}@@ -414,14 +415,18 @@ impl HttpClient {mode: &str,wait: bool,timeout: Option<f64>,+ processing_mode: &str,) -> Value {- serde_json::json!({+ let mut body = serde_json::json!({"uri": uri,"content": content,"mode": mode,"wait": wait,"timeout": timeout,- })+ "processing_mode": processing_mode,+ });+ compact_request_body(&mut body);+ body}pub async fn reindex(@@ -2046,6 +2051,7 @@ mod tests {"replace",true,Some(3.0),+ "semantic_and_vectors",);assert_eq!(@@ -2062,6 +2068,34 @@ mod tests {assert!(body.get("revectorize").is_none());}+ #[test]+ fn build_write_body_drops_default_processing_mode_for_legacy_servers() {+ let body = HttpClient::build_write_body(+ "viking://resources/demo.md",+ "updated",+ "replace",+ true,+ None,+ "semantic_and_vectors",+ );++ assert!(body.get("processing_mode").is_none());+ }++ #[test]+ fn build_write_body_keeps_vectors_only_processing_mode() {+ let body = HttpClient::build_write_body(+ "viking://resources/demo.md",+ "updated",+ "replace",+ true,+ None,+ "vectors_only",+ );++ assert_eq!(body["processing_mode"], "vectors_only");+ }+#[tokio::test]async fn ls_does_not_send_display_time_query() {let (base_url, request_rx) = spawn_request_capture_server().await;diff --git a/crates/ov_cli/src/commands/content.rs b/crates/ov_cli/src/commands/content.rsindex b9b43e2a4..446d4687d 100644--- a/crates/ov_cli/src/commands/content.rs+++ b/crates/ov_cli/src/commands/content.rs@@ -43,10 +43,13 @@ pub async fn write(mode: &str,wait: bool,timeout: Option<f64>,+ processing_mode: &str,output_format: OutputFormat,compact: bool,) -> Result<()> {- let result = client.write(uri, content, mode, wait, timeout).await?;+ let result = client+ .write(uri, content, mode, wait, timeout, processing_mode)+ .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.rsindex 93b2a6ca7..f06f096c0 100644--- a/crates/ov_cli/src/handlers.rs+++ b/crates/ov_cli/src/handlers.rs@@ -1285,6 +1285,7 @@ pub async fn handle_write(mode: String,wait: bool,timeout: Option<f64>,+ processing_mode: String,ctx: CliContext,) -> Result<()> {let client = ctx.get_client();@@ -1305,6 +1306,7 @@ pub async fn handle_write(&mode,wait,timeout,+ &processing_mode,ctx.output_format,ctx.compact,)diff --git a/crates/ov_cli/src/main.rs b/crates/ov_cli/src/main.rsindex 5f62aa244..126b5610d 100644--- a/crates/ov_cli/src/main.rs+++ b/crates/ov_cli/src/main.rs@@ -619,6 +619,14 @@ enum Commands {/// Wait for async processing to finish#[arg(long, default_value = "false", help_heading = "Common options")]wait: bool,+ /// Content post-write processing mode+ #[arg(+ long = "processing-mode",+ default_value = "semantic_and_vectors",+ value_parser = ["semantic_and_vectors", "vectors_only"],+ help_heading = "Advanced options"+ )]+ processing_mode: String,/// Optional wait timeout in seconds#[arg(long,@@ -3369,6 +3377,7 @@ async fn main() {append,mode,wait,+ processing_mode,timeout,} => {let effective_mode = if let Some(m) = mode {@@ -3378,8 +3387,17 @@ async fn main() {} else {"replace".to_string()};- handlers::handle_write(uri, content, from_file, effective_mode, wait, timeout, ctx)- .await+ handlers::handle_write(+ uri,+ content,+ from_file,+ effective_mode,+ wait,+ timeout,+ processing_mode,+ ctx,+ )+ .await}Commands::SetTags {uri,diff --git a/openviking/async_client.py b/openviking/async_client.pyindex ecd40d925..64adce871 100644--- a/openviking/async_client.py+++ b/openviking/async_client.py@@ -686,6 +686,7 @@ class AsyncOpenViking:wait: bool = False,timeout: Optional[float] = None,telemetry: TelemetryRequest = False,+ processing_mode: str = "semantic_and_vectors",) -> Dict[str, Any]:"""Write text content to an existing file and refresh semantics/vectors."""await self._ensure_initialized()@@ -696,6 +697,7 @@ class AsyncOpenViking:wait=wait,timeout=timeout,telemetry=telemetry,+ processing_mode=processing_mode,)async def set_tags(diff --git a/openviking/client/local.py b/openviking/client/local.pyindex 8729c96a1..8dca1c796 100644--- a/openviking/client/local.py+++ b/openviking/client/local.py@@ -660,6 +660,7 @@ class LocalClient(BaseClient):wait: bool = False,timeout: Optional[float] = None,telemetry: TelemetryRequest = False,+ processing_mode: str = "semantic_and_vectors",) -> Dict[str, Any]:"""Write text content to an existing file and refresh semantics/vectors."""execution = await run_with_telemetry(@@ -672,6 +673,7 @@ class LocalClient(BaseClient):mode=mode,wait=wait,timeout=timeout,+ processing_mode=processing_mode,),)return attach_telemetry_payload(diff --git a/openviking/server/routers/content.py b/openviking/server/routers/content.pyindex fc6a7f97e..8d48204fa 100644--- a/openviking/server/routers/content.py+++ b/openviking/server/routers/content.py@@ -18,6 +18,7 @@ from openviking.core.namespace import (from openviking.core.path_variables import resolve_path_variablesfrom openviking.core.uri_validation import validate_viking_urifrom openviking.pyagfs.exceptions import AGFSClientError, AGFSNotFoundError+from openviking.resource.processing_mode import DEFAULT_PROCESSING_MODE, ProcessingModefrom openviking.server.auth import (get_request_context,require_role,@@ -45,6 +46,7 @@ class WriteContentRequest(BaseModel):wait: bool = Falsetimeout: float | None = Nonetelemetry: TelemetryRequest = False+ processing_mode: ProcessingMode = DEFAULT_PROCESSING_MODEclass BatchWritePrecondition(BaseModel):@@ -257,6 +259,7 @@ async def write(mode=request.mode,wait=request.wait,timeout=request.timeout,+ processing_mode=request.processing_mode,),)return Response(diff --git a/openviking/service/fs_service.py b/openviking/service/fs_service.pyindex f5c6fa971..d73779640 100644--- a/openviking/service/fs_service.py+++ b/openviking/service/fs_service.py@@ -584,6 +584,7 @@ class FSService:mode: str = "replace",wait: bool = False,timeout: Optional[float] = None,+ processing_mode: str = "semantic_and_vectors",) -> Dict[str, Any]:"""Write to an existing file and refresh semantics/vectors."""uri = validate_viking_uri(uri)@@ -596,6 +597,7 @@ class FSService:mode=mode,wait=wait,timeout=timeout,+ processing_mode=processing_mode,)async def batch_write(diff --git a/openviking/storage/content_write.py b/openviking/storage/content_write.pyindex 6a4a776ce..c177d0ce2 100644--- a/openviking/storage/content_write.py+++ b/openviking/storage/content_write.py@@ -19,6 +19,12 @@ from openviking.core.namespace import (relative_uri_path,uri_parts,)+from openviking.resource.processing_mode import (+ DEFAULT_PROCESSING_MODE,+ VECTORS_ONLY,+ ProcessingMode,+ normalize_processing_mode,+)from openviking.resource.watch_storage import is_watch_task_control_urifrom openviking.server.identity import RequestContextfrom openviking.session.memory.memory_updater import MemoryUpdater@@ -35,6 +41,7 @@ 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.path_safety import validate_safe_viking_uri_path+from openviking.utils.embedding_utils import vectorize_filefrom openviking.utils.tags import normalize_search_tagsfrom openviking_cli.exceptions import (AlreadyExistsError,@@ -86,12 +93,14 @@ class ContentWriteCoordinator:mode: str = "replace",wait: bool = False,timeout: Optional[float] = None,+ processing_mode: ProcessingMode = DEFAULT_PROCESSING_MODE,) -> Dict[str, Any]:try:normalized_uri = canonicalize_uri(uri, ctx)except NamespaceShapeError as exc:raise InvalidArgumentError(str(exc)) from excself._validate_mode(mode)+ processing_mode = normalize_processing_mode(processing_mode)self._validate_target_uri(normalized_uri)self._viking_fs._ensure_mutable_access(normalized_uri, ctx)@@ -102,6 +111,7 @@ class ContentWriteCoordinator:ctx=ctx,wait=wait,timeout=timeout,+ processing_mode=processing_mode,)stat = await self._safe_stat(normalized_uri, ctx=ctx)@@ -124,6 +134,7 @@ class ContentWriteCoordinator:ctx=ctx,written_bytes=written_bytes,telemetry_id=telemetry_id,+ processing_mode=processing_mode,)return await self._write_direct_with_refresh(@@ -137,6 +148,7 @@ class ContentWriteCoordinator:ctx=ctx,written_bytes=written_bytes,telemetry_id=telemetry_id,+ processing_mode=processing_mode,)async def batch_write(@@ -692,6 +704,7 @@ class ContentWriteCoordinator:ctx: RequestContext,written_bytes: int,telemetry_id: str,+ processing_mode: ProcessingMode = DEFAULT_PROCESSING_MODE,) -> Dict[str, Any]:lock_path = self._viking_fs._uri_to_path(uri, ctx=ctx)try:@@ -704,8 +717,9 @@ class ContentWriteCoordinator:previous_content: Optional[str] = Nonecontent_written = False- semantic_enqueued = False+ post_process_started = Falselock_released = False+ vector_enqueued = Falsetry:if mode != "create":previous_content = await self._viking_fs.read_file(uri, ctx=ctx)@@ -713,14 +727,22 @@ class ContentWriteCoordinator:get_request_wait_tracker().register_request(telemetry_id)await self._write_in_place(uri, content, mode=mode, ctx=ctx, lease_ref=lease)content_written = True- await self._enqueue_semantic_refresh(- root_uri=root_uri,- changed_uri=uri,- context_type=context_type,- ctx=ctx,- change_type="added" if mode == "create" else "modified",- )- semantic_enqueued = True+ if processing_mode == VECTORS_ONLY:+ vector_enqueued = await self._vectorize_written_file(+ uri=uri,+ context_type=context_type,+ ctx=ctx,+ )+ post_process_started = True+ else:+ await self._enqueue_semantic_refresh(+ root_uri=root_uri,+ changed_uri=uri,+ context_type=context_type,+ ctx=ctx,+ change_type="added" if mode == "create" else "modified",+ )+ post_process_started = Trueawait self._viking_fs._async_agfs.pathlock_release(lease)lock_released = Truequeue_status = (@@ -728,6 +750,19 @@ class ContentWriteCoordinator:if waitelse None)+ result_kwargs = {}+ if processing_mode == VECTORS_ONLY:+ if vector_enqueued:+ _, vector_status = self._refresh_statuses(+ wait=wait,+ queue_status=queue_status,+ )+ else:+ vector_status = "skipped"+ result_kwargs = {+ "semantic_status": "skipped",+ "vector_status": vector_status,+ }return self._build_write_result(uri=uri,root_uri=root_uri,@@ -736,9 +771,10 @@ class ContentWriteCoordinator:written_bytes=written_bytes,wait=wait,queue_status=queue_status,+ **result_kwargs,)except Exception:- if not semantic_enqueued and content_written:+ if not post_process_started and content_written:await self._rollback_direct_write(uri=uri,previous_content=previous_content,@@ -776,6 +812,26 @@ class ContentWriteCoordinator:except Exception:logger.error("Failed to rollback direct content write for %s", uri, exc_info=True)+ async def _vectorize_written_file(+ self,+ *,+ uri: str,+ context_type: str,+ ctx: RequestContext,+ ) -> bool:+ parent = VikingURI(uri).parent+ if parent is None:+ return False+ name = uri.rstrip("/").rsplit("/", 1)[-1]+ return await vectorize_file(+ file_path=uri,+ summary_dict={"name": name, "summary": ""},+ parent_uri=parent.uri,+ context_type=context_type,+ ctx=ctx,+ register_request_wait=True,+ )+def _validate_mode(self, mode: str) -> None:if mode not in {"replace", "append", "create"}:raise InvalidArgumentError(f"unsupported write mode: {mode}")@@ -834,6 +890,7 @@ class ContentWriteCoordinator:ctx: RequestContext,wait: bool,timeout: Optional[float],+ processing_mode: ProcessingMode,) -> Dict[str, Any]:self._validate_create_extension(uri)@@ -859,6 +916,7 @@ class ContentWriteCoordinator:ctx=ctx,written_bytes=written_bytes,telemetry_id=telemetry_id,+ processing_mode=processing_mode,)return await self._write_direct_with_refresh(@@ -872,6 +930,7 @@ class ContentWriteCoordinator:ctx=ctx,written_bytes=written_bytes,telemetry_id=telemetry_id,+ processing_mode=processing_mode,)async def _write_in_place(@@ -967,7 +1026,10 @@ class ContentWriteCoordinator:ctx: RequestContext,written_bytes: int,telemetry_id: str,+ processing_mode: ProcessingMode = DEFAULT_PROCESSING_MODE,) -> Dict[str, Any]:+ del processing_mode+lock_path = self._viking_fs._uri_to_path(uri, ctx=ctx)try:lease = await self._viking_fs._async_agfs.pathlock_acquire_exact(lock_path)diff --git a/openviking/sync_client.py b/openviking/sync_client.pyindex 50b7dcd30..acdd0e3ae 100644--- a/openviking/sync_client.py+++ b/openviking/sync_client.py@@ -525,6 +525,7 @@ class SyncOpenViking:wait: bool = False,timeout: Optional[float] = None,telemetry: TelemetryRequest = False,+ processing_mode: str = "semantic_and_vectors",) -> Dict[str, Any]:"""Write text content to an existing file and refresh semantics/vectors."""return run_async(@@ -535,6 +536,7 @@ class SyncOpenViking:wait=wait,timeout=timeout,telemetry=telemetry,+ processing_mode=processing_mode,))diff --git a/openviking/utils/embedding_utils.py b/openviking/utils/embedding_utils.pyindex 923b79a26..5d457a36d 100644--- a/openviking/utils/embedding_utils.py+++ b/openviking/utils/embedding_utils.py@@ -23,6 +23,7 @@ from openviking.parse.parsers.media.utils import (MPEG_TS_PROBE_BYTES,is_mpeg_ts,)+from openviking.parse.parsers.upload_utils import is_text_filefrom openviking.server.identity import RequestContextfrom openviking.service.task_work_index import TaskWorkRejectedfrom openviking.storage.queuefs import get_queue_manager@@ -488,13 +489,14 @@ async def vectorize_file(scalar_override: Optional[Dict[str, Any]] = None,register_request_wait: bool = False,ingest_options: IngestOptions | None = None,-) -> None:+) -> bool:"""Vectorize a single file.Creates Context object for the file and enqueues it.The effective vectorization strategy is resolved once from either the explicit`use_summary` flag (code path override) or the embedding config.+ Returns whether an embedding message was enqueued."""enqueued = Falseregistered_wait_root: Optional[tuple[str, str]] = None@@ -502,7 +504,7 @@ async def vectorize_file(try:if not ctx:logger.warning("No context provided for vectorization")- return+ return Falsequeue_manager = get_queue_manager()embedding_queue = queue_manager.get_queue(queue_manager.EMBEDDING)@@ -535,9 +537,7 @@ async def vectorize_file(owner_space=owner_space_for_uri(file_path, ctx),)- content_type = await _resolve_resource_content_type(- file_path, file_name, viking_fs, ctx- )+ content_type = await _resolve_resource_content_type(file_path, file_name, viking_fs, ctx)embedding_cfg = get_openviking_config().embeddingconfigured_text_source = getattr(embedding_cfg, "text_source", "content_only")effective_text_source = "summary_only" if use_summary else configured_text_source@@ -547,22 +547,25 @@ async def vectorize_file(context.abstract = effective_textcontext.set_vectorize(Vectorize(text=effective_text, full_text=effective_text))elif content_type is None:- # Unsupported file type: fall back to summary if available- if summary:- logger.warning(- f"Unsupported file type for {file_path}, falling back to summary for vectorization"- )+ full_content = ""+ if summary or is_text_file(file_name):full_content = (reusable_contentif has_reusable_contentelse await _read_unknown_file_text_for_fulltext(file_path, viking_fs, ctx))+ if summary:+ logger.warning(+ f"Unsupported file type for {file_path}, falling back to summary for vectorization"+ )context.set_vectorize(Vectorize(text=summary, full_text=full_content or summary))+ elif full_content:+ context.set_vectorize(Vectorize(text=full_content, full_text=full_content))else:logger.warning(f"Unsupported file type for {file_path} and no summary available, skipping vectorization")- return+ return Falseelif content_type == ResourceContentType.TEXT:# Known text files use VikingFS' text read path once, then reuse that# content for BM25 regardless of whether embedding uses summary or raw text.@@ -580,7 +583,7 @@ async def vectorize_file(context.set_vectorize(Vectorize(text=summary, full_text=summary))else:logger.warning(f"No summary available for {file_path}, skipping vectorization")- return+ return Falseelse:if summary and effective_text_source in {"summary_first", "summary_only"}:# Use summary for vectorization, but reuse the single raw text read for BM25.@@ -599,17 +602,17 @@ async def vectorize_file(logger.debug(f"Skipping image {file_path} (image unreadable and no summary available)")- return+ return Falseelif summary:# For non-text files, use summarycontext.set_vectorize(Vectorize(text=summary, full_text=summary))else:logger.debug(f"Skipping file {file_path} (no text content or summary)")- return+ return Falseembedding_msg = EmbeddingMsgConverter.from_context(context)if not embedding_msg:- return+ return False_apply_scalar_overrides(embedding_msg, scalar_override)_apply_ingest_options(embedding_msg, ingest_options)@@ -627,7 +630,7 @@ async def vectorize_file(embedding_msg.id,f"Failed to enqueue file vector for {file_path}",)- return+ return Falseenqueued = Truelogger.debug(f"Enqueued file for vectorization: {file_path}")@@ -651,6 +654,7 @@ async def vectorize_file(finally:if not enqueued:await _decrement_embedding_tracker(semantic_msg_id, 1)+ return enqueuedasync def index_resource(diff --git a/sdk/python/openviking_sdk/client.py b/sdk/python/openviking_sdk/client.pyindex 6407be5ac..525fa50c8 100644--- a/sdk/python/openviking_sdk/client.py+++ b/sdk/python/openviking_sdk/client.py@@ -1123,18 +1123,22 @@ class AsyncHTTPClient:wait: bool = False,timeout: Optional[float] = None,telemetry: Any = False,+ processing_mode: Optional[str] = None,) -> Dict[str, Any]:+ payload = {+ "uri": VikingURI.normalize(uri),+ "content": content,+ "mode": mode,+ "wait": wait,+ "timeout": timeout,+ "telemetry": telemetry,+ }+ if processing_mode is not None:+ payload["processing_mode"] = processing_moderesponse = await self._request("POST","/api/v1/content/write",- json={- "uri": VikingURI.normalize(uri),- "content": content,- "mode": mode,- "wait": wait,- "timeout": timeout,- "telemetry": telemetry,- },+ json=payload,)return self._handle_response_data(response).get("result", {})@@ -2164,6 +2168,7 @@ class SyncHTTPClient:wait: bool = False,timeout: Optional[float] = None,telemetry: Any = False,+ processing_mode: Optional[str] = None,) -> Dict[str, Any]:return run_async(self._async_client.write(@@ -2173,6 +2178,7 @@ class SyncHTTPClient:wait=wait,timeout=timeout,telemetry=telemetry,+ processing_mode=processing_mode,))diff --git a/sdk/python/tests/test_async_client_behaviors.py b/sdk/python/tests/test_async_client_behaviors.pyindex bc374e48a..9bad6fed2 100644--- a/sdk/python/tests/test_async_client_behaviors.py+++ b/sdk/python/tests/test_async_client_behaviors.py@@ -163,6 +163,36 @@ async def test_async_http_client_reindex_posts_content_reindex():)+async def test_async_http_client_write_forwards_processing_mode():+ client = AsyncHTTPClient(url="http://localhost:1933")+ fake_http = SimpleNamespace(post=AsyncMock(return_value=object()))+ client._http = fake_http+ client._handle_response_data = lambda _response: {"result": {"uri": "viking://resources/demo.md"}}++ await client.write(+ "viking://resources/demo.md",+ "updated",+ processing_mode="vectors_only",+ )++ payload = fake_http.post.await_args.kwargs["json"]+ assert payload["processing_mode"] == "vectors_only"+++async def test_async_http_client_write_omits_default_processing_mode_for_legacy_servers():+ client = AsyncHTTPClient(url="http://localhost:1933")+ fake_http = SimpleNamespace(post=AsyncMock(return_value=object()))+ client._http = fake_http+ client._handle_response_data = lambda _response: {"result": {"uri": "viking://resources/demo.md"}}++ await client.write("viking://resources/demo.md", "updated")++ payload = fake_http.post.await_args.kwargs["json"]+ assert "processing_mode" not in payload++@pytest.mark.asyncio@pytest.mark.parametrize(("cleanup", "action"), [(False, "migrate"), (True, "cleanup")])async def test_async_http_client_admin_migrate_posts_action_payload(cleanup, action):diff --git a/sdk/typescript/src/client.ts b/sdk/typescript/src/client.tsindex f4de8976b..1af7e8c5c 100644--- a/sdk/typescript/src/client.ts+++ b/sdk/typescript/src/client.ts@@ -26,6 +26,7 @@ import type {TreeOptions,UpdateWatchOptions,WaitOptions,+ WriteOptions,} from "./types.js";const compact = (value: JsonObject): JsonObject =>@@ -502,13 +503,14 @@ export class OpenVikingClient {write(uri: string,content: string,- options: WaitOptions & { mode?: string } = {},+ options: WriteOptions = {},): Promise<JsonObject> {return this.request("POST", "/api/v1/content/write", {body: compact({uri: normalizeURI(uri),content,mode: options.mode ?? "replace",+ processing_mode: options.processingMode,wait: options.wait ?? false,timeout: options.timeout,telemetry: options.telemetry,diff --git a/sdk/typescript/src/types.ts b/sdk/typescript/src/types.tsindex 6305c5aad..2d27e29cd 100644--- a/sdk/typescript/src/types.ts+++ b/sdk/typescript/src/types.ts@@ -90,6 +90,11 @@ export interface AddResourceOptions extends WaitOptions {tags?: string[];tagMode?: "replace" | "append";}+/** Content write options. */+export interface WriteOptions extends WaitOptions {+ mode?: string;+ processingMode?: ProcessingMode;+}/** Semantic retrieval options. */export interface SearchOptions {targetUri?: TargetURI;diff --git a/sdk/typescript/tests/client.test.ts b/sdk/typescript/tests/client.test.tsindex 2acfc8873..6c5173203 100644--- a/sdk/typescript/tests/client.test.ts+++ b/sdk/typescript/tests/client.test.ts@@ -122,6 +122,29 @@ describe("OpenVikingClient", () => {});});+ it("sends processing_mode for write requests", async () => {+ const fetcher = vi.fn<typeof fetch>().mockResolvedValue(ok({}));+ const client = new OpenVikingClient({+ baseUrl: "https://example.com",+ fetch: fetcher,+ });++ await client.write("resources/demo.md", "updated", {+ processingMode: "vectors_only",+ wait: true,+ });++ const [url, init] = fetcher.mock.calls[0]!;+ expect(String(url)).toBe("https://example.com/api/v1/content/write");+ expect(JSON.parse(String(init?.body))).toMatchObject({+ uri: "viking://resources/demo.md",+ content: "updated",+ mode: "replace",+ processing_mode: "vectors_only",+ wait: true,+ });+ });+it("maps response envelopes to typed errors", async () => {const fetcher = vi.fn<typeof fetch>().mockResolvedValue(new Response(diff --git a/tests/client/test_filesystem.py b/tests/client/test_filesystem.pyindex 966d87b76..b9d18caaf 100644--- a/tests/client/test_filesystem.py+++ b/tests/client/test_filesystem.py@@ -108,6 +108,26 @@ class TestRead:assert str(seen["telemetry_id"]).startswith("tm_")assert seen["kwargs"]["wait"] is True+ async def test_local_client_write_forwards_processing_mode(self):+ seen: dict[str, object] = {}++ async def _fake_write(**kwargs):+ seen["kwargs"] = kwargs+ return {"uri": kwargs["uri"]}++ client = LocalClient.__new__(LocalClient)+ client._ctx = RequestContext(user=UserIdentifier.the_default_user(), role=Role.USER)+ client._service = SimpleNamespace(fs=SimpleNamespace(write=_fake_write))++ await LocalClient.write(+ client,+ uri="viking://resources/demo.md",+ content="Updated from client test",+ processing_mode="vectors_only",+ )++ assert seen["kwargs"]["processing_mode"] == "vectors_only"+class TestAbstract:"""Test abstract operation"""@@ -190,6 +210,7 @@ async def test_sync_openviking_write_updates_existing_file(test_data_dir, samplewait=True,timeout=3.0,telemetry=False,+ processing_mode="vectors_only",)assert write_result == {"uri": "viking://resources/demo.md"}@@ -200,6 +221,7 @@ async def test_sync_openviking_write_updates_existing_file(test_data_dir, samplewait=True,timeout=3.0,telemetry=False,+ processing_mode="vectors_only",)finally:client.close()diff --git a/tests/client/test_write_signature_compat.py b/tests/client/test_write_signature_compat.pynew file mode 100644index 000000000..f5ecf1c14--- /dev/null+++ b/tests/client/test_write_signature_compat.py@@ -0,0 +1,80 @@+import inspect++from openviking import AsyncOpenViking, SyncOpenViking+from openviking.client.local import LocalClient+from openviking_sdk.client import AsyncHTTPClient, SyncHTTPClient+++def test_async_openviking_write_preserves_positional_telemetry():+ bound = inspect.signature(AsyncOpenViking.write).bind_partial(+ object(),+ "viking://resources/demo.md",+ "updated",+ "append",+ True,+ 3.0,+ False,+ )++ assert bound.arguments["telemetry"] is False+ assert "processing_mode" not in bound.arguments+++def test_sync_openviking_write_preserves_positional_telemetry():+ bound = inspect.signature(SyncOpenViking.write).bind_partial(+ object(),+ "viking://resources/demo.md",+ "updated",+ "append",+ True,+ 3.0,+ False,+ )++ assert bound.arguments["telemetry"] is False+ assert "processing_mode" not in bound.arguments+++def test_local_client_write_preserves_positional_telemetry():+ bound = inspect.signature(LocalClient.write).bind_partial(+ object(),+ "viking://resources/demo.md",+ "updated",+ "append",+ True,+ 3.0,+ False,+ )++ assert bound.arguments["telemetry"] is False+ assert "processing_mode" not in bound.arguments+++def test_async_http_client_write_preserves_positional_telemetry():+ bound = inspect.signature(AsyncHTTPClient.write).bind_partial(+ object(),+ "viking://resources/demo.md",+ "updated",+ "append",+ True,+ 3.0,+ False,+ )++ assert bound.arguments["telemetry"] is False+ assert "processing_mode" not in bound.arguments+++def test_sync_http_client_write_preserves_positional_telemetry():+ bound = inspect.signature(SyncHTTPClient.write).bind_partial(+ object(),+ "viking://resources/demo.md",+ "updated",+ "append",+ True,+ 3.0,+ False,+ )++ assert bound.arguments["telemetry"] is False+ assert "processing_mode" not in bound.argumentsdiff --git a/tests/server/test_api_content.py b/tests/server/test_api_content.pyindex 87b69e0e5..c553e639e 100644--- a/tests/server/test_api_content.py+++ b/tests/server/test_api_content.py@@ -9,10 +9,50 @@ import pytestfrom openviking.server.identity import RequestContext, Rolefrom openviking.server.routers import content as content_router-from openviking.server.routers.content import ReindexRequest, reindex+from openviking.server.routers.content import ReindexRequest, WriteContentRequest, reindexfrom openviking_cli.session.user_id import UserIdentifier+def test_write_content_request_accepts_processing_mode():+ request = WriteContentRequest(+ uri="viking://resources/demo.md",+ content="updated",+ processing_mode="vectors_only",+ )++ assert request.processing_mode == "vectors_only"+++def test_write_content_request_defaults_processing_mode():+ request = WriteContentRequest(uri="viking://resources/demo.md", content="updated")++ assert request.processing_mode == "semantic_and_vectors"+++async def test_write_forwards_processing_mode_to_service(monkeypatch):+ seen = {}++ async def fake_write(**kwargs):+ seen.update(kwargs)+ return {"uri": kwargs["uri"], "semantic_status": "skipped"}++ service = SimpleNamespace(fs=SimpleNamespace(write=fake_write))+ monkeypatch.setattr(content_router, "get_service", lambda: service)+ ctx = RequestContext(user=UserIdentifier("account-1", "user-1"), role=Role.USER)++ response = await content_router.write(+ WriteContentRequest(+ uri="viking://resources/demo.md",+ content="updated",+ processing_mode="vectors_only",+ ),+ ctx,+ )++ assert response["status"] == "ok"+ assert seen["processing_mode"] == "vectors_only"++async def _first_child_uri(client, uri: str) -> str:response = await client.get("/api/v1/fs/ls",diff --git a/tests/storage/test_content_write_processing_mode.py b/tests/storage/test_content_write_processing_mode.pynew file mode 100644index 000000000..394d8db12--- /dev/null+++ b/tests/storage/test_content_write_processing_mode.py@@ -0,0 +1,178 @@+# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.+# SPDX-License-Identifier: AGPL-3.0++from types import SimpleNamespace+from unittest.mock import AsyncMock++import pytest++from openviking.server.identity import RequestContext, Role+from openviking.storage import content_write as content_write_module+from openviking.storage.content_write import ContentWriteCoordinator+from openviking_cli.session.user_id import UserIdentifier+++class _FakePathLock:+ """Mock for _async_agfs pathlock operations."""++ def __init__(self):+ self._lease = SimpleNamespace(id="lock-1")+ self.release_calls = []++ async def pathlock_acquire_exact(self, lock_path):+ del lock_path+ return self._lease++ async def pathlock_release(self, lease):+ self.release_calls.append(lease.id)+++class _FakeVikingFS:+ def __init__(self):+ self.write_file = AsyncMock()+ self.read_file = AsyncMock(return_value="previous")+ self._async_agfs = _FakePathLock()++ def _uri_to_path(self, uri, ctx=None):+ return f"/fake/{uri}"+++def ctx():+ return RequestContext(user=UserIdentifier("account-1", "user-1"), role=Role.USER)+++async def test_vectors_only_write_skips_semantic_refresh_and_vectorizes_file(monkeypatch, ctx):+ fake_fs = _FakeVikingFS()+ vectorize_file = AsyncMock(return_value=True)+ semantic_refresh = AsyncMock(side_effect=AssertionError("semantic refresh should not run"))+ monkeypatch.setattr(content_write_module, "vectorize_file", vectorize_file, raising=False)+ coordinator = ContentWriteCoordinator(viking_fs=fake_fs)+ coordinator._enqueue_semantic_refresh = semantic_refresh++ result = await coordinator._write_direct_with_refresh(+ uri="viking://resources/demo.md",+ root_uri="viking://resources",+ content="updated",+ mode="replace",+ context_type="resource",+ wait=False,+ timeout=None,+ ctx=ctx,+ written_bytes=7,+ telemetry_id="",+ processing_mode="vectors_only",+ )++ semantic_refresh.assert_not_awaited()+ vectorize_file.assert_awaited_once()+ assert vectorize_file.await_args.kwargs["file_path"] == "viking://resources/demo.md"+ assert vectorize_file.await_args.kwargs["parent_uri"] == "viking://resources"+ assert vectorize_file.await_args.kwargs["summary_dict"] == {+ "name": "demo.md",+ "summary": "",+ }+ assert vectorize_file.await_args.kwargs["register_request_wait"] is True+ assert result["semantic_status"] == "skipped"+ assert result["vector_status"] == "queued"+++async def test_vectors_only_write_wait_reports_embedding_status(monkeypatch, ctx):+ fake_fs = _FakeVikingFS()+ queue_status = {+ "Embedding": {"processed": 1, "error_count": 0, "errors": []},+ "Semantic": {"processed": 0, "error_count": 0, "errors": []},+ }+ monkeypatch.setattr(+ content_write_module, "vectorize_file", AsyncMock(return_value=True), raising=False+ )+ coordinator = ContentWriteCoordinator(viking_fs=fake_fs)+ coordinator._wait_for_request = AsyncMock(return_value=queue_status)++ result = await coordinator._write_direct_with_refresh(+ uri="viking://resources/demo.md",+ root_uri="viking://resources",+ content="updated",+ mode="replace",+ context_type="resource",+ wait=True,+ timeout=3.0,+ ctx=ctx,+ written_bytes=7,+ telemetry_id="tm-test",+ processing_mode="vectors_only",+ )++ assert result["queue_status"] == queue_status+ assert result["semantic_status"] == "skipped"+ assert result["vector_status"] == "complete"+++async def test_vectors_only_write_wait_reports_skipped_when_nothing_enqueued(monkeypatch, ctx):+ fake_fs = _FakeVikingFS()+ monkeypatch.setattr(+ content_write_module, "vectorize_file", AsyncMock(return_value=False), raising=False+ )+ coordinator = ContentWriteCoordinator(viking_fs=fake_fs)+ coordinator._wait_for_request = AsyncMock(return_value=None)++ result = await coordinator._write_direct_with_refresh(+ uri="viking://resources/obsolete.md",+ root_uri="viking://resources",+ content="",+ mode="replace",+ context_type="resource",+ wait=True,+ timeout=3.0,+ ctx=ctx,+ written_bytes=0,+ telemetry_id="tm-test",+ processing_mode="vectors_only",+ )++ assert result["semantic_status"] == "skipped"+ assert result["vector_status"] == "skipped"+++async def test_memory_write_accepts_processing_mode_without_switching_refresh(monkeypatch, ctx):+ fake_fs = _FakeVikingFS()+ monkeypatch.setattr(+ content_write_module.MemoryUpdater,+ "refresh_schema_overview",+ AsyncMock(),+ )+ monkeypatch.setattr(+ content_write_module.MemoryUpdater,+ "refresh_file_embedding",+ AsyncMock(return_value=False),+ )+ monkeypatch.setattr(+ content_write_module.MemoryUpdater,+ "memory_type_from_uri",+ lambda uri: "user",+ )+ coordinator = ContentWriteCoordinator(viking_fs=fake_fs)+ coordinator._write_in_place = AsyncMock()++ result = await coordinator._write_memory_with_refresh(+ uri="viking://user/memories/demo.md",+ root_uri="viking://user/memories",+ content="updated",+ mode="replace",+ wait=True,+ timeout=3.0,+ ctx=ctx,+ written_bytes=7,+ telemetry_id="tm-test",+ processing_mode="vectors_only",+ )++ content_write_module.MemoryUpdater.refresh_schema_overview.assert_awaited_once()+ content_write_module.MemoryUpdater.refresh_file_embedding.assert_awaited_once()+ assert result["context_type"] == "memory"+ assert result["semantic_status"] == "skipped"+ assert result["overview_status"] == "complete"diff --git a/tests/unit/test_vectorize_file_strategy.py b/tests/unit/test_vectorize_file_strategy.pyindex a60f94844..9521c78df 100644--- a/tests/unit/test_vectorize_file_strategy.py+++ b/tests/unit/test_vectorize_file_strategy.py@@ -326,6 +326,58 @@ async def test_vectorize_unknown_text_file_embeds_summary_but_indexes_raw_contenassert msg.context_data["content"] == raw_makefile+async def test_vectorize_unknown_text_file_without_summary_indexes_raw_content(monkeypatch):+ queue = DummyQueue()+ raw_makefile = "build:\n\tcargo build --release\n"+ monkeypatch.setattr(embedding_utils, "get_queue_manager", lambda: DummyQueueManager(queue))+ monkeypatch.setattr(embedding_utils, "get_viking_fs", lambda: DummyFS(raw_makefile))+ monkeypatch.setattr(+ embedding_utils,+ "get_openviking_config",+ lambda: types.SimpleNamespace(+ embedding=types.SimpleNamespace(text_source="content_only", max_input_tokens=1000)+ ),+ )++ enqueued = await embedding_utils.vectorize_file(+ file_path="viking://user/default/resources/Makefile",+ summary_dict={"name": "Makefile", "summary": ""},+ parent_uri="viking://user/default/resources",+ ctx=DummyReq(),+ )++ assert enqueued is True+ assert len(queue.items) == 1+ msg = queue.items[0]+ assert msg.context_data["content"] == raw_makefile+ assert msg.message == raw_makefile+++async def test_vectorize_empty_content_reports_not_enqueued(monkeypatch):+ queue = DummyQueue()+ monkeypatch.setattr(embedding_utils, "get_queue_manager", lambda: DummyQueueManager(queue))+ monkeypatch.setattr(embedding_utils, "get_viking_fs", lambda: DummyFS(""))+ monkeypatch.setattr(+ embedding_utils,+ "get_openviking_config",+ lambda: types.SimpleNamespace(+ embedding=types.SimpleNamespace(text_source="content_only", max_input_tokens=1000)+ ),+ )++ enqueued = await embedding_utils.vectorize_file(+ file_path="viking://user/default/resources/obsolete.md",+ summary_dict={"name": "obsolete.md", "summary": ""},+ parent_uri="viking://user/default/resources",+ ctx=DummyReq(),+ )++ assert enqueued is False+ assert queue.items == []++@pytest.mark.asyncioasync def test_vectorize_file_writes_search_tags_into_embedding_context(monkeypatch):queue = DummyQueue()