From b0c8f03c4b9d50b9aaf7677490cccba3bde9fa22 Mon Sep 17 00:00:00 2001 From: "zhoujiahui.01" Date: Wed, 23 Sep 2026 14:29:42 +0800 Subject: [PATCH] feat(tags): support explicit clear mode Add clear semantics across resource ingestion, content writes, reindexing, RNFV scalar planning, SDKs, CLI, and Web Studio. Treat empty replace tags as a no-op while preserving clear through durable queues and only updating vector scalars when the normalized value changes. Co-authored-by: TRAE CLI Co-authored-by: TRAE CLI --- crates/ov_cli/src/client.rs | 25 +- crates/ov_cli/src/main.rs | 59 ++- docs/en/api/02-resources.md | 2 + docs/en/api/12-content.md | 16 +- docs/zh/api/02-resources.md | 2 +- docs/zh/api/12-content.md | 16 +- openviking/connector/delegate.py | 14 +- openviking/server/mcp_endpoint.py | 3 +- openviking/server/routers/content.py | 4 +- openviking/service/core.py | 2 +- openviking/service/reindex_executor.py | 4 +- openviking/service/resource_service.py | 11 +- openviking/session/memory/memory_updater.py | 6 +- openviking/storage/context_update_plan.py | 6 +- openviking/storage/resource_rnfv.py | 2 +- openviking/utils/embedding_utils.py | 5 +- openviking/utils/ingest_options.py | 27 +- sdk/go/client_test.go | 60 +++ sdk/go/filesystem.go | 12 +- sdk/go/resources.go | 6 +- sdk/python/openviking_sdk/options.py | 6 +- .../tests/test_async_client_behaviors.py | 54 +++ sdk/typescript/src/client.ts | 13 +- sdk/typescript/src/types.ts | 6 +- sdk/typescript/tests/client.test.ts | 22 + tests/server/test_admin_rebuild_api.py | 85 +++- tests/server/test_api_content.py | 35 ++ .../test_resource_service_connector.py | 74 ++++ tests/service/test_resource_service_watch.py | 34 ++ tests/storage/test_context_update_plan.py | 405 +++++++++++++++++- tests/storage/test_resource_diff_snapshot.py | 57 +++ .../test_semantic_msg_ingest_options.py | 15 + .../session/memory/test_embedding_template.py | 14 +- tests/utils/test_ingest_options.py | 31 ++ web-studio/src/i18n/locales/en/resources.ts | 1 + .../src/i18n/locales/zh-CN/resources.ts | 1 + .../additional-resource-options.tsx | 6 +- .../-lib/resource-import-request.test.ts | 14 + .../resources/-lib/resource-import-request.ts | 6 +- .../resources/-lib/resource-import-types.ts | 2 +- 40 files changed, 1075 insertions(+), 88 deletions(-) create mode 100644 tests/utils/test_ingest_options.py diff --git a/crates/ov_cli/src/client.rs b/crates/ov_cli/src/client.rs index 51b3833b023..d054bfedbb8 100644 --- a/crates/ov_cli/src/client.rs +++ b/crates/ov_cli/src/client.rs @@ -39,13 +39,15 @@ fn compact_request_body(body: &mut Value) { } fn add_resource_tag_fields(body: &mut Value, tags: &[String], tag_mode: &str) { - if tags.is_empty() { + if tags.is_empty() && tag_mode != "clear" { return; } let obj = body .as_object_mut() .expect("add_resource request body must be an object"); - obj.insert("tags".to_string(), serde_json::json!(tags)); + if !tags.is_empty() { + obj.insert("tags".to_string(), serde_json::json!(tags)); + } obj.insert("tag_mode".to_string(), serde_json::json!(tag_mode)); } @@ -482,13 +484,7 @@ impl HttpClient { if !recursive { body["recursive"] = serde_json::json!(false); } - if !tags.is_empty() { - let obj = body - .as_object_mut() - .expect("reindex request body must be an object"); - obj.insert("tags".to_string(), serde_json::json!(tags)); - obj.insert("tag_mode".to_string(), serde_json::json!(tag_mode)); - } + add_resource_tag_fields(&mut body, &tags, tag_mode); self.post("/api/v1/content/reindex", &body).await } @@ -2127,6 +2123,17 @@ mod tests { assert!(!obj.contains_key("tag_mode")); } + #[test] + fn add_resource_tag_fields_sends_clear_without_tags() { + let mut body = json!({"path": "https://example.com/demo.md"}); + + super::add_resource_tag_fields(&mut body, &[], "clear"); + + let obj = body.as_object().unwrap(); + assert!(!obj.contains_key("tags")); + assert_eq!(body["tag_mode"], json!("clear")); + } + #[test] fn timeout_config_calculation() { let config = TimeoutConfig::new(60, 2.0); diff --git a/crates/ov_cli/src/main.rs b/crates/ov_cli/src/main.rs index 932185be61b..351d5d6e05a 100644 --- a/crates/ov_cli/src/main.rs +++ b/crates/ov_cli/src/main.rs @@ -455,11 +455,11 @@ enum Commands { /// Comma-separated k=v retrieval tags to apply after import #[arg(long = "tags", value_delimiter = ',', value_name = "k=v", help_heading = "Common options")] tags: Vec, - /// Tag update mode when --tags is provided + /// Tag update mode; clear does not require --tags #[arg( long = "tag-mode", default_value = "replace", - value_parser = ["replace", "append"], + value_parser = ["replace", "append", "clear"], help_heading = "Common options" )] tag_mode: String, @@ -746,8 +746,8 @@ enum Commands { /// Comma-separated k=v retrieval tags to write with the content #[arg(long = "tags", value_delimiter = ',')] tags: Vec, - /// Tag update mode when --tags is provided - #[arg(long = "tag-mode", default_value = "replace", value_parser = ["replace", "append"])] + /// Tag update mode; clear does not require --tags + #[arg(long = "tag-mode", default_value = "replace", value_parser = ["replace", "append", "clear"])] tag_mode: String, }, /// [Data] Update explicit retrieval tags metadata for a file or directory @@ -1260,11 +1260,11 @@ enum Commands { /// Comma-separated k=v retrieval tags for rebuilt vector records #[arg(long = "tags", value_delimiter = ',', value_name = "k=v", help_heading = "Common options")] tags: Vec, - /// Tag update mode when --tags is provided + /// Tag update mode; clear does not require --tags #[arg( long = "tag-mode", default_value = "replace", - value_parser = ["replace", "append"], + value_parser = ["replace", "append", "clear"], help_heading = "Common options" )] tag_mode: String, @@ -4746,6 +4746,53 @@ mod tests { } } + #[test] + fn cli_parses_clear_tag_mode_without_tags() { + let add = Cli::try_parse_from([ + "ov", + "add-resource", + "./README.md", + "--tag-mode", + "clear", + ]) + .expect("add-resource clear mode should parse"); + match add.command { + Commands::AddResource { tags, tag_mode, .. } => { + assert!(tags.is_empty()); + assert_eq!(tag_mode, "clear"); + } + _ => panic!("expected add-resource command"), + } + + let write = Cli::try_parse_from([ + "ov", + "write", + "viking://resources/demo.md", + "--content", + "content", + "--tag-mode", + "clear", + ]) + .expect("write clear mode should parse"); + assert!(matches!( + write.command, + Commands::Write { tag_mode, tags, .. } if tag_mode == "clear" && tags.is_empty() + )); + + let reindex = Cli::try_parse_from([ + "ov", + "reindex", + "viking://resources/demo", + "--tag-mode", + "clear", + ]) + .expect("reindex clear mode should parse"); + assert!(matches!( + reindex.command, + Commands::Reindex { tag_mode, tags, .. } if tag_mode == "clear" && tags.is_empty() + )); + } + #[test] fn cli_parses_skills_command_group() { let list = Cli::try_parse_from(["ov", "skills", "list", "--limit", "25"]) diff --git a/docs/en/api/02-resources.md b/docs/en/api/02-resources.md index 406abaeffe3..881b693f60a 100644 --- a/docs/en/api/02-resources.md +++ b/docs/en/api/02-resources.md @@ -189,6 +189,8 @@ This endpoint is the core entry point for resource management. It supports vario | watch_interval | float | No | 0 | Scheduled update interval (minutes). >0 creates a new Watch for a re-readable source, subject to target ownership rules; uploaded `temp_file_id` snapshots cannot be watched. <=0 creates no Watch: native imports with explicit `to` pause a single accessible task (409 if ambiguous), while Connector imports leave Watches untouched. Explicit `to` wins, otherwise the Watch binds to the imported `root_uri`. | | is_active | bool | No | True | Initial Watch scheduling state. `false` requires `watch_interval > 0` and either `to` or `parent`. `parent` is supported for native Feishu URL and Git imports; Connector imports still require an exact `to`. The initial import still runs once and the Watch remains paused afterward | | processing_mode | string | No | `semantic_and_vectors` | Post-ingest processing mode. `semantic_and_vectors` is the normal flow: generate semantic artifacts (`.abstract.md`, `.overview.md`) and vectors. `vectors_only` skips semantic understanding/VLM summarization and only vectorizes current resource files | +| tags | string[] | No | None | Explicit `k=v` retrieval tags written with generated vector records. An empty list with `replace` does not change existing tags | +| tag_mode | string | No | `replace` | Tag write mode: `replace`, `append`, or `clear`; `clear` removes existing tags without requiring `tags` and ignores supplied tag values | | telemetry | TelemetryRequest | No | False | Whether to return telemetry data | **Additional Notes**: diff --git a/docs/en/api/12-content.md b/docs/en/api/12-content.md index f1bf45cccd7..eb726bffcae 100644 --- a/docs/en/api/12-content.md +++ b/docs/en/api/12-content.md @@ -223,7 +223,7 @@ Write a file and automatically refresh related semantics and vectors. | wait | bool | No | `false` | Wait for background semantic/vector refresh | | timeout | float | No | `null` | Timeout in seconds when `wait=true` | | tags | string[] | No | Unset | Explicit retrieval tags for the written file, for example `["team=search", "env=prod"]` | -| tag_mode | string | No | `replace` | Tag update mode when `tags` is supplied: `replace` overwrites tags; `append` merges tags by key | +| tag_mode | string | No | `replace` | Tag update mode: `replace` overwrites tags, `append` merges by key, and `clear` removes existing tags without requiring `tags` | **Notes** @@ -233,7 +233,7 @@ Write a file and automatically refresh related semantics and vectors. - 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 automatically schedules related semantic and vector processing. - Parent L0/L1 refreshes for resource writes are best-effort: a parent lock conflict skips that directory refresh while preserving the file write and its own summary/vector work. Skipping L0/L1 persistence also skips directory vector updates; a later refresh is not guaranteed. Locks on the written file itself still raise conflicts. Contention detected before enqueueing returns `semantic_status: "skipped"`; skips during background execution are logged, and `wait=true` does not guarantee updated parent summaries. -- When `tags` is supplied, tags are included in the file's first vector upsert rather than updated after processing. Omitting `tags` preserves existing tags; explicit `tags: []` with `tag_mode: "replace"` clears them. +- When non-empty `tags` are supplied, tags are included in the file's first vector upsert rather than updated after processing. Omitting `tags`, or using `tags: []` with `tag_mode: "replace"`, preserves existing tags. Use `tag_mode: "clear"` to remove all existing tags; `clear` ignores any supplied tag values. **Python SDK** @@ -601,8 +601,8 @@ This API operates on existing `viking://...` content. It does not import new fil | wait | bool | No | `true` | Whether to wait for completion | | dry_run | bool | No | `false` | Only valid with `mode="prune_orphans"`; report orphan vector records without deleting them | | recursive | bool | No | `true` | Whether to process descendants recursively; `false` applies only to `semantic_and_vectors` on a `resource`, `memory`, or `skill` directory | -| tags | list[str] | No | `null` | Write tags to every successfully rebuilt vector record. Omit to preserve existing tags; an empty list with `replace` clears them | -| tag_mode | str | No | `replace` | Tag write mode: `replace` or `append` | +| tags | list[str] | No | `null` | Write tags to every successfully rebuilt vector record. Omitting tags, or passing an empty list with `replace`, preserves existing tags | +| tag_mode | str | No | `replace` | Tag write mode: `replace`, `append`, or `clear`; `clear` removes existing tags without requiring `tags` | The HTTP request body rejects unknown fields. `uri` may use OpenViking path variables accepted by other content APIs; it is resolved before validation. @@ -635,7 +635,7 @@ For a `resource` or `memory` directory, `recursive=false` regenerates only the t For `prune_orphans`, source existence is checked against the filesystem. If an entire directory is missing, vector records for files and semantic sidecars below that directory, such as `.abstract.md` and `.overview.md`, are pruned together. `dry_run` is rejected for other modes. -When `tags` is provided, tags are included in the same upsert as each vector record produced by reindex; reindex does not call `set_tags` afterwards. Directory and namespace reindex operations apply tags to successfully rebuilt directory L0/L1 and leaf L2 records. `replace` overwrites existing tags, while `append` merges by key. When `tags` is omitted, `tag_mode` is ignored and existing tags remain unchanged. `prune_orphans` produces no vectors and ignores both fields. +When non-empty `tags` are provided, tags are included in the same upsert as each vector record produced by reindex; reindex does not call `set_tags` afterwards. Directory and namespace reindex operations apply tags to successfully rebuilt directory L0/L1 and leaf L2 records. `replace` overwrites existing tags, while `append` merges by key. `replace` with an empty tag list is a no-op. `clear` removes existing tags and does not require `tags`; if values are supplied with `clear`, they are ignored. `prune_orphans` produces no vectors and ignores both fields. Subtree reindex is not transactional. Records skipped because no semantic source is available, or records whose embedding fails, do not receive the new tags. @@ -738,7 +738,11 @@ openviking reindex viking://resources --mode vectors_only \ --tags team=search,env=prod --tag-mode replace ``` -The CLI sends tag fields only when non-empty `--tags` is provided. Use HTTP or an SDK to clear tags with `tags: []`. +Use `--tag-mode clear` without `--tags` to clear existing tags: + +```bash +openviking reindex viking://resources --mode vectors_only --tag-mode clear +``` ```bash openviking reindex viking://user/default/skills --mode semantic_and_vectors --wait false diff --git a/docs/zh/api/02-resources.md b/docs/zh/api/02-resources.md index 73c45f446d7..d7b46e6b320 100644 --- a/docs/zh/api/02-resources.md +++ b/docs/zh/api/02-resources.md @@ -183,7 +183,7 @@ URL/文件 Parser TreeBuilder AGFS Summarizer/Vector | is_active | bool | 否 | True | Watch 初始调度状态。设为 `false` 时要求 `watch_interval > 0`,并在 `to`、`parent` 中二选一。`parent` 支持原生飞书 URL 和 Git 导入;Connector 仍要求精确的 `to`。首次导入仍执行一次,随后保持暂停 | | processing_mode | string | 否 | `semantic_and_vectors` | 入库后的处理模式。`semantic_and_vectors` 是默认流程:生成语义产物(`.abstract.md`、`.overview.md`)并生成向量。`vectors_only` 跳过语义理解/VLM 总结,只对当前资源文件生成向量 | | tags | string[] | 否 | None | 导入时写入向量检索记录的显式检索标签,格式必须是 `k=v`,例如 `["team=search", "env=test"]`。搜索接口可用同名 `tags` 参数过滤召回 | -| tag_mode | string | 否 | `"replace"` | `tags` 的写入模式,可选 `replace` 或 `append`。导入新资源时会随本次生成的每条向量记录写入;不会在完成后额外调用 `set_tags`,响应也不返回 `tags_result` | +| tag_mode | string | 否 | `"replace"` | 标签写入模式:`replace` 覆盖、`append` 按 key 合并、`clear` 清空。`clear` 不要求传 `tags`;`replace` 配合空数组不会修改已有标签。导入时标签会随本次生成的每条向量记录写入;不会在完成后额外调用 `set_tags`,响应也不返回 `tags_result` | | telemetry | TelemetryRequest | 否 | False | 是否返回遥测数据 | **补充说明**: diff --git a/docs/zh/api/12-content.md b/docs/zh/api/12-content.md index 9d9556841e3..8060524ce1f 100644 --- a/docs/zh/api/12-content.md +++ b/docs/zh/api/12-content.md @@ -223,7 +223,7 @@ openviking read viking://resources/docs/api.md | wait | bool | 否 | `false` | 是否等待后台语义/向量刷新完成 | | timeout | float | 否 | `null` | 当 `wait=true` 时的超时时间(秒) | | tags | string[] | 否 | 未设置 | 写入文件的显式检索标签,例如 `["team=search", "env=prod"]` | -| tag_mode | string | 否 | `replace` | 提供 `tags` 时的更新方式:`replace` 覆盖标签,`append` 按 key 合并标签 | +| tag_mode | string | 否 | `replace` | 标签更新方式:`replace` 覆盖、`append` 按 key 合并、`clear` 清空已有标签且不要求传 `tags` | **说明** @@ -233,7 +233,7 @@ openviking read viking://resources/docs/api.md - 文件内容会在 API 返回前完成更新;`wait` 只控制是否等待语义/向量刷新完成。 - 公共 API 已不再接受 `regenerate_semantics` 或 `revectorize`;写入后会自动调度相关语义与向量处理。 - 资源写入附带的父目录 L0/L1 刷新采用尽力更新:父目录锁冲突时跳过本次目录刷新,保留原文写入及文件自身的摘要、向量处理。跳过 L0/L1 写回时也跳过目录向量更新,不保证自动补刷;原文文件本身的锁冲突仍报错。提交任务前发现冲突时返回 `semantic_status: "skipped"`;后台运行期间的跳过记录在日志中,`wait=true` 也不保证父目录摘要更新。 -- 提供 `tags` 时,标签会在该文件首次向量 upsert 时写入,而非在处理完成后再单独更新。省略 `tags` 不改变已有标签;显式 `tags: []` 配合 `tag_mode: "replace"` 可清空标签。 +- 提供非空 `tags` 时,标签会在该文件首次向量 upsert 时写入,而非在处理完成后再单独更新。省略 `tags`,或显式传 `tags: []` 配合 `tag_mode: "replace"`,都不会修改已有标签。使用 `tag_mode: "clear"` 可清空全部已有标签,且 `clear` 会忽略同时传入的标签值。 **Python SDK** @@ -601,8 +601,8 @@ ov set-tags viking://resources/project/ \ | wait | bool | 否 | `true` | 是否等待任务完成 | | dry_run | bool | 否 | `false` | 仅适用于 `mode="prune_orphans"`;只报告 orphan 向量记录,不实际删除 | | recursive | bool | 否 | `true` | 是否递归处理下级内容;`false` 仅对 `resource`、`memory` 或 `skill` 目录的 `semantic_and_vectors` 生效 | -| tags | list[str] | 否 | `null` | 写入本次成功重建的全部向量记录。省略时保留已有 tags;空数组配合 `replace` 可清空 | -| tag_mode | str | 否 | `replace` | `tags` 的写入模式:`replace` 或 `append` | +| tags | list[str] | 否 | `null` | 写入本次成功重建的全部向量记录。省略或空数组配合 `replace` 时保留已有 tags | +| tag_mode | str | 否 | `replace` | 标签写入模式:`replace`、`append` 或 `clear`;`clear` 不要求传 `tags` 并清空已有标签 | HTTP 请求体不接受未知字段。`uri` 可以使用其他 content API 支持的 OpenViking 路径变量,服务端会先解析再校验。 @@ -635,7 +635,7 @@ session 子树会被跳过。 对于 `prune_orphans`,源文件是否存在以当前文件系统为准。如果整个目录已经不存在,该目录下的正文文件向量和语义 sidecar 向量(例如 `.abstract.md`、`.overview.md`)会一起清理。`dry_run` 用在其他模式时会被拒绝。 -传入 `tags` 时,标签会随 reindex 生成的向量记录在同一次 upsert 中写入,不会在完成后额外调用 `set_tags`。目录或 namespace reindex 会把标签应用到本次成功重建的目录 L0/L1 和叶子 L2 记录。`replace` 覆盖已有标签,`append` 按 key 合并;省略 `tags` 时不校验 `tag_mode` 且不修改已有标签。`prune_orphans` 不生成向量,因此会忽略 `tags` 和 `tag_mode`。 +传入非空 `tags` 时,标签会随 reindex 生成的向量记录在同一次 upsert 中写入,不会在完成后额外调用 `set_tags`。目录或 namespace reindex 会把标签应用到本次成功重建的目录 L0/L1 和叶子 L2 记录。`replace` 覆盖已有标签,`append` 按 key 合并;`replace` 配合空数组时不修改已有标签。`clear` 不要求传 `tags`,会清空已有标签;即使同时传入标签值也会忽略。`prune_orphans` 不生成向量,因此会忽略 `tags` 和 `tag_mode`。 子树 reindex 不是事务性操作。如果部分记录因缺少语义来源或 embedding 失败而未重建,只有成功写入的记录会更新标签。 @@ -738,7 +738,11 @@ openviking reindex viking://resources --mode vectors_only \ --tags team=search,env=prod --tag-mode replace ``` -CLI 仅在 `--tags` 非空时发送标签字段;如需用 `tags: []` 清空标签,请使用 HTTP 或 SDK。 +使用 `--tag-mode clear` 且无需传 `--tags` 即可清空已有标签: + +```bash +openviking reindex viking://resources --mode vectors_only --tag-mode clear +``` ```bash openviking reindex viking://user/default/skills --mode semantic_and_vectors --wait false diff --git a/openviking/connector/delegate.py b/openviking/connector/delegate.py index 5fa40760e25..b60a8337aac 100644 --- a/openviking/connector/delegate.py +++ b/openviking/connector/delegate.py @@ -628,11 +628,15 @@ async def submit( account_id=ctx.account_id, ) extra_params = None - if tags is not None: - extra_params = { - "tags": normalize_search_tags(tags), - "tag_mode": tag_mode, - } + if tag_mode == "clear": + extra_params = {"tag_mode": tag_mode} + elif tags is not None: + normalized_tags = normalize_search_tags(tags) + if normalized_tags: + extra_params = { + "tags": normalized_tags, + "tag_mode": tag_mode, + } task_tracker = get_task_tracker() task = await task_tracker.create( diff --git a/openviking/server/mcp_endpoint.py b/openviking/server/mcp_endpoint.py index 601247ea4f7..6c6041ca2a4 100644 --- a/openviking/server/mcp_endpoint.py +++ b/openviking/server/mcp_endpoint.py @@ -1213,7 +1213,8 @@ async def add_resource( ``add_type`` is set. Leaving both empty derives the directory and the name from the source and handles collisions like ``parent``. tags: Optional explicit k=v retrieval tags to apply after ingestion. - tag_mode: Tag update mode, "replace" or "append". Defaults to "replace". + tag_mode: Tag update mode: "replace", "append", or "clear". Clear removes + existing tags without requiring ``tags``. Defaults to "replace". args: Parser-specific options, e.g. {"auth_config": {"token": "..."}} for native HTTPS Git imports and watches, {"feishu_access_token": "..."} for Feishu imports, {"site": true} for whole-site ingestion, or diff --git a/openviking/server/routers/content.py b/openviking/server/routers/content.py index ca123bfbbae..859af0e6950 100644 --- a/openviking/server/routers/content.py +++ b/openviking/server/routers/content.py @@ -48,7 +48,7 @@ class WriteContentRequest(BaseModel): telemetry: TelemetryRequest = False processing_mode: ProcessingMode = DEFAULT_PROCESSING_MODE tags: list[str] | None = None - tag_mode: Literal["replace", "append"] = "replace" + tag_mode: Literal["replace", "append", "clear"] = "replace" class BatchWriteOperation(BaseModel): @@ -335,7 +335,7 @@ async def reindex( } if not body.recursive: reindex_kwargs["recursive"] = False - if body.tags is not None: + if body.tags is not None or body.tag_mode == "clear": reindex_kwargs["tags"] = body.tags reindex_kwargs["tag_mode"] = body.tag_mode result = await service.reindex( diff --git a/openviking/service/core.py b/openviking/service/core.py index eba57f31f6e..2a62a80f978 100644 --- a/openviking/service/core.py +++ b/openviking/service/core.py @@ -703,7 +703,7 @@ async def reindex( } if not recursive: execute_kwargs["recursive"] = False - if tags is not None: + if tags is not None or tag_mode == "clear": execute_kwargs["tags"] = tags execute_kwargs["tag_mode"] = tag_mode return await get_reindex_executor().execute(**execute_kwargs) diff --git a/openviking/service/reindex_executor.py b/openviking/service/reindex_executor.py index 67087c41982..f487d879943 100644 --- a/openviking/service/reindex_executor.py +++ b/openviking/service/reindex_executor.py @@ -264,9 +264,9 @@ def _resolve_ingest_options( tags: list[str] | None, tag_mode: str, ) -> IngestOptions | None: - if mode == "prune_orphans" or tags is None: + if mode == "prune_orphans" or (tags is None and tag_mode != "clear"): return None - if tag_mode not in {"replace", "append"}: + if tag_mode not in {"replace", "append", "clear"}: raise InvalidArgumentError(f"unsupported tag mode: {tag_mode}") return IngestOptions.from_search_tags(tags, mode=tag_mode) diff --git a/openviking/service/resource_service.py b/openviking/service/resource_service.py index 205abf725fe..c9a1971afe6 100644 --- a/openviking/service/resource_service.py +++ b/openviking/service/resource_service.py @@ -152,7 +152,7 @@ } ) _ADD_RESOURCE_TRANSIENT_ARGS = frozenset({"tos_signature", "tos_access"}) -_ADD_RESOURCE_TAG_MODES = frozenset({"replace", "append"}) +_ADD_RESOURCE_TAG_MODES = frozenset({"replace", "append", "clear"}) _INTERNAL_INGESTION_FIELDS = frozenset( { @@ -323,8 +323,9 @@ def _watch_processor_kwargs( tag_mode: str, ) -> Dict[str, Any]: watch_kwargs = self._sanitize_watch_processor_kwargs(processor_kwargs) - if tags is not None: - watch_kwargs["tags"] = tags + if tags is not None or tag_mode == "clear": + if tags is not None: + watch_kwargs["tags"] = tags watch_kwargs["tag_mode"] = tag_mode return watch_kwargs @@ -348,7 +349,7 @@ def _validate_add_resource_tag_policy( tags: Optional[List[str]], tag_mode: str, ) -> None: - if tags is not None and tag_mode not in _ADD_RESOURCE_TAG_MODES: + if (tags is not None or tag_mode == "clear") and tag_mode not in _ADD_RESOURCE_TAG_MODES: raise InvalidArgumentError(f"unsupported tag mode: {tag_mode}") def _add_resource_ingest_tag_kwargs( @@ -357,7 +358,7 @@ def _add_resource_ingest_tag_kwargs( tags: Optional[List[str]], tag_mode: str, ) -> Dict[str, Any]: - if tags is None: + if tags is None and tag_mode != "clear": return {} return {"ingest_options": IngestOptions.from_search_tags(tags, mode=tag_mode)} diff --git a/openviking/session/memory/memory_updater.py b/openviking/session/memory/memory_updater.py index 066209ad3a7..93297c26bc1 100644 --- a/openviking/session/memory/memory_updater.py +++ b/openviking/session/memory/memory_updater.py @@ -47,6 +47,7 @@ from openviking.telemetry import tracer from openviking.telemetry.request_wait_tracker import get_request_wait_tracker from openviking.telemetry.tracer import get_trace_id +from openviking.utils.ingest_options import IngestOptions from openviking.utils.time_utils import parse_iso_datetime from openviking_cli.exceptions import NotFoundError from openviking_cli.utils import VikingURI, get_logger @@ -1413,6 +1414,7 @@ async def _vectorize_memories( search_tags_by_uri: Transient search tags to attach while indexing each URI ingest_options: Write options for a single-file content write. """ + ingest_options = IngestOptions.from_value(ingest_options) if not self._vikingdb: logger.debug("VikingDB not available, skipping vectorization") return 0 @@ -1502,7 +1504,9 @@ async def _vectorize_memories( if getattr(ingest_options, "search_tags", None) is not None: embedding_msg.context_data["search_tags"] = list(ingest_options.search_tags) embedding_msg.context_data["_upsert_options"] = { - "search_tag_mode": ingest_options.search_tag_mode + "search_tag_mode": IngestOptions.vector_search_tag_mode( + ingest_options.search_tag_mode + ) } else: transient_tags = search_tags_by_uri.get(uri) diff --git a/openviking/storage/context_update_plan.py b/openviking/storage/context_update_plan.py index 1c3de125353..755959ec499 100644 --- a/openviking/storage/context_update_plan.py +++ b/openviking/storage/context_update_plan.py @@ -578,7 +578,11 @@ def _field_patch(request: RequestIntent, record: VectorRecordSnapshot | None) -> continue candidate = FieldPatch({intent.field: intent.value}, {intent.field: intent.mode}) desired = candidate.resolve(existing).get(intent.field) - if record is None or existing.get(intent.field) != desired: + current = FieldPatch( + {intent.field: existing.get(intent.field)}, + {intent.field: "replace"}, + ).resolve({})[intent.field] + if record is None or current != desired: values[intent.field] = intent.value modes[intent.field] = intent.mode return FieldPatch(values, modes) if values else None diff --git a/openviking/storage/resource_rnfv.py b/openviking/storage/resource_rnfv.py index 9077eff66a9..f71e95c3359 100644 --- a/openviking/storage/resource_rnfv.py +++ b/openviking/storage/resource_rnfv.py @@ -113,7 +113,7 @@ def from_ingest_options( scalar_intents = ( ScalarIntent( field="search_tags", - mode=options.search_tag_mode, + mode=IngestOptions.vector_search_tag_mode(options.search_tag_mode), value=tuple(options.search_tags), target_levels=( frozenset({2}) if str(mode) == "vectors_only" else frozenset({0, 1, 2}) diff --git a/openviking/utils/embedding_utils.py b/openviking/utils/embedding_utils.py index 318704b4c59..fb336ae436c 100644 --- a/openviking/utils/embedding_utils.py +++ b/openviking/utils/embedding_utils.py @@ -111,8 +111,9 @@ def _apply_ingest_options( ingest_options = IngestOptions.from_value(ingest_options) if not embedding_msg or ingest_options.search_tags is None: return + tag_mode = IngestOptions.vector_search_tag_mode(ingest_options.search_tag_mode) incoming_tags = list(ingest_options.search_tags or []) - if ingest_options.search_tag_mode == "append" and ( + if tag_mode == "append" and ( embedding_msg.action is IndexAction.MERGE or embedding_msg.context_data.get("_upsert_options", {}).get("partial_update") is False ): @@ -123,7 +124,7 @@ def _apply_ingest_options( ) embedding_msg.context_data["search_tags"] = incoming_tags embedding_msg.context_data.setdefault("_upsert_options", {})["search_tag_mode"] = ( - ingest_options.search_tag_mode + tag_mode ) diff --git a/openviking/utils/ingest_options.py b/openviking/utils/ingest_options.py index cd7dc0e64da..a2c4f153795 100644 --- a/openviking/utils/ingest_options.py +++ b/openviking/utils/ingest_options.py @@ -23,6 +23,11 @@ class IngestOptions: search_tags: Optional[list[str]] = None search_tag_mode: str = "replace" + @staticmethod + def vector_search_tag_mode(mode: str) -> str: + """Map request intent to the modes understood by vector backends.""" + return "replace" if mode == "clear" else mode + @classmethod def from_search_tags( cls, @@ -30,10 +35,15 @@ def from_search_tags( *, mode: str = "replace", ) -> "IngestOptions": + if mode == "clear": + return cls(search_tags=[], search_tag_mode="clear") if tags is None: return cls() + normalized_tags = normalize_search_tags(tags, discard_invalid=True) + if mode == "replace" and not normalized_tags: + return cls() return cls( - search_tags=normalize_search_tags(tags, discard_invalid=True), + search_tags=normalized_tags, search_tag_mode=mode, ) @@ -42,14 +52,13 @@ def from_value(cls, value: "IngestOptions | Mapping[str, Any] | None") -> "Inges if value is None: return cls() if isinstance(value, IngestOptions): - return value - return cls( - search_tags=( - list(value.get("search_tags") or []) - if value.get("search_tags") is not None - else None - ), - search_tag_mode=str(value.get("search_tag_mode", "replace")), + return cls.from_search_tags( + value.search_tags, + mode=value.search_tag_mode, + ) + return cls.from_search_tags( + value.get("search_tags"), + mode=str(value.get("search_tag_mode", "replace")), ) def to_dict(self) -> dict[str, Any]: diff --git a/sdk/go/client_test.go b/sdk/go/client_test.go index 03afea16026..44f24f25b3f 100644 --- a/sdk/go/client_test.go +++ b/sdk/go/client_test.go @@ -398,6 +398,26 @@ func TestReindexSendsExplicitEmptyTags(t *testing.T) { } } +func TestReindexSendsClearWithoutTags(t *testing.T) { + client, closeServer := testClient(t, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + body := readJSONBody(t, r) + if _, ok := body["tags"]; ok { + t.Fatalf("tags = %#v", body["tags"]) + } + if body["tag_mode"] != "clear" { + t.Fatalf("tag_mode = %#v", body["tag_mode"]) + } + writeOK(t, w, map[string]any{"status": "completed"}) + })) + defer closeServer() + + if _, err := client.Reindex(context.Background(), "resources/demo", &ReindexOptions{ + TagMode: "clear", + }); err != nil { + t.Fatal(err) + } +} + func TestReindexSendsExtraAndRejectsOverrides(t *testing.T) { client, closeServer := testClient(t, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { body := readJSONBody(t, r) @@ -670,6 +690,26 @@ func TestWriteSendsProcessingModeAndExtra(t *testing.T) { } } +func TestWriteSendsClearWithoutTags(t *testing.T) { + client, closeServer := testClient(t, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + body := readJSONBody(t, r) + if _, ok := body["tags"]; ok { + t.Fatalf("tags = %#v", body["tags"]) + } + if body["tag_mode"] != "clear" { + t.Fatalf("tag_mode = %#v", body["tag_mode"]) + } + writeOK(t, w, map[string]any{"uri": "viking://resources/a.md"}) + })) + defer closeServer() + + if _, err := client.Write(context.Background(), "resources/a.md", "", &WriteOptions{ + TagMode: "clear", + }); err != nil { + t.Fatal(err) + } +} + func TestFilesystemTagProjectionOptionsAreSent(t *testing.T) { requests := 0 client, closeServer := testClient(t, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { @@ -1167,6 +1207,26 @@ func TestAddResourceSendsTagsAndTagMode(t *testing.T) { } } +func TestAddResourceSendsClearWithoutTags(t *testing.T) { + client, closeServer := testClient(t, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + body := readJSONBody(t, r) + if _, ok := body["tags"]; ok { + t.Fatalf("tags = %#v", body["tags"]) + } + if body["tag_mode"] != "clear" { + t.Fatalf("tag_mode = %#v", body["tag_mode"]) + } + writeOK(t, w, map[string]any{"uri": "viking://resources/demo.md"}) + })) + defer closeServer() + + if _, err := client.AddResource(context.Background(), "https://example.com/demo.md", &AddResourceOptions{ + TagMode: "clear", + }); err != nil { + t.Fatal(err) + } +} + // An explicitly-provided but empty Args map is treated the same as no args: the // key is omitted so the request stays compatible with pre-#2549 instances. The // resources create route defaults args to {} server-side, so "absent" and diff --git a/sdk/go/filesystem.go b/sdk/go/filesystem.go index 04529a6716b..e82732afc7c 100644 --- a/sdk/go/filesystem.go +++ b/sdk/go/filesystem.go @@ -224,8 +224,10 @@ func (c *Client) Write(ctx context.Context, uri string, content string, opts *Wr setFloatPtr(payload, "timeout", opts.Timeout) setAny(payload, "telemetry", opts.Telemetry) setString(payload, "processing_mode", opts.ProcessingMode) - if opts.Tags != nil { - payload["tags"] = opts.Tags + if opts.Tags != nil || opts.TagMode == "clear" { + if opts.Tags != nil { + payload["tags"] = opts.Tags + } tagMode := opts.TagMode if tagMode == "" { tagMode = "replace" @@ -317,8 +319,10 @@ func (c *Client) Reindex(ctx context.Context, uri string, opts *ReindexOptions) "dry_run": opts.DryRun, "recursive": boolValue(opts.Recursive, true), } - if opts.Tags != nil { - payload["tags"] = opts.Tags + if opts.Tags != nil || opts.TagMode == "clear" { + if opts.Tags != nil { + payload["tags"] = opts.Tags + } tagMode := opts.TagMode if tagMode == "" { tagMode = "replace" diff --git a/sdk/go/resources.go b/sdk/go/resources.go index 0a6d3d5231a..eff5a7540cc 100644 --- a/sdk/go/resources.go +++ b/sdk/go/resources.go @@ -43,8 +43,10 @@ func (c *Client) AddResource(ctx context.Context, path string, opts *AddResource if len(opts.Args) > 0 { payload["args"] = opts.Args } - if opts.Tags != nil { - payload["tags"] = opts.Tags + if opts.Tags != nil || opts.TagMode == "clear" { + if opts.Tags != nil { + payload["tags"] = opts.Tags + } if opts.TagMode != "" { payload["tag_mode"] = opts.TagMode } diff --git a/sdk/python/openviking_sdk/options.py b/sdk/python/openviking_sdk/options.py index cc3d8e49ce0..9fd028b4e69 100644 --- a/sdk/python/openviking_sdk/options.py +++ b/sdk/python/openviking_sdk/options.py @@ -74,7 +74,7 @@ class AddResourceOptions(_ExtraOptions, total=False): processing_mode: ProcessingMode add_type: str tags: List[str] - tag_mode: Literal["replace", "append"] + tag_mode: Literal["replace", "append", "clear"] class AddSkillOptions(_ExtraOptions, total=False): @@ -90,7 +90,7 @@ class WriteOptions(_ExtraOptions, total=False): telemetry: Any processing_mode: ProcessingMode tags: List[str] - tag_mode: Literal["replace", "append"] + tag_mode: Literal["replace", "append", "clear"] class BatchWriteOptions(_ExtraOptions, total=False): @@ -108,7 +108,7 @@ class SetTagsOptions(_ExtraOptions, total=False): class ReindexOptions(_ExtraOptions, total=False): tags: List[str] - tag_mode: Literal["replace", "append"] + tag_mode: Literal["replace", "append", "clear"] class CreateSessionOptions(_ExtraOptions, total=False): diff --git a/sdk/python/tests/test_async_client_behaviors.py b/sdk/python/tests/test_async_client_behaviors.py index 4935b6c2e27..9e2ce2b1329 100644 --- a/sdk/python/tests/test_async_client_behaviors.py +++ b/sdk/python/tests/test_async_client_behaviors.py @@ -342,6 +342,23 @@ async def test_async_http_client_reindex_sends_explicit_empty_tags(): assert fake_http.post.await_args.kwargs["json"]["tag_mode"] == "replace" +@pytest.mark.asyncio +async def test_async_http_client_reindex_sends_clear_without_tags(): + client = AsyncHTTPClient(url="http://localhost:1933") + fake_http = SimpleNamespace(post=AsyncMock(return_value=object())) + client._http = fake_http + client._handle_response = lambda _response: {"status": "completed"} + + await client.reindex( + "viking://resources/demo", + options={"tag_mode": "clear"}, + ) + + payload = fake_http.post.await_args.kwargs["json"] + assert "tags" not in payload + assert payload["tag_mode"] == "clear" + + @pytest.mark.asyncio async def test_async_http_client_write_forwards_processing_mode(): client = AsyncHTTPClient(url="http://localhost:1933") @@ -379,6 +396,24 @@ async def test_async_http_client_write_forwards_explicit_tags_and_mode(): assert payload["tag_mode"] == "replace" +@pytest.mark.asyncio +async def test_async_http_client_write_forwards_clear_without_tags(): + 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": {}} + + await client.write( + "viking://resources/demo.md", + "updated", + options={"tag_mode": "clear"}, + ) + + payload = fake_http.post.await_args.kwargs["json"] + assert "tags" not in payload + assert payload["tag_mode"] == "clear" + + @pytest.mark.asyncio async def test_async_http_client_filesystem_tags_are_omission_aware(): client = AsyncHTTPClient(url="http://localhost:1933") @@ -1179,6 +1214,25 @@ async def test_add_resource_sends_tags_and_tag_mode(): ) +@pytest.mark.asyncio +async def test_add_resource_sends_clear_without_tags(): + 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": {"root_uri": "viking://resources/demo"} + } + + await client.add_resource( + "https://example.com/demo.md", + options={"tag_mode": "clear"}, + ) + + payload = fake_http.post.await_args.kwargs["json"] + assert "tags" not in payload + assert payload["tag_mode"] == "clear" + + @pytest.mark.asyncio async def test_find_uses_node_limit_as_http_limit_and_normalizes_target_uri_list(): client = AsyncHTTPClient(url="http://localhost:1933") diff --git a/sdk/typescript/src/client.ts b/sdk/typescript/src/client.ts index fd536af1a47..874d4c21eff 100644 --- a/sdk/typescript/src/client.ts +++ b/sdk/typescript/src/client.ts @@ -157,7 +157,10 @@ export class OpenVikingClient { ? options.args : undefined, tags: options.tags, - tag_mode: options.tags ? options.tagMode : undefined, + tag_mode: + options.tags !== undefined || options.tagMode === "clear" + ? (options.tagMode ?? "replace") + : undefined, telemetry: options.telemetry, }); const local = await nodePathToBlob(source); @@ -602,7 +605,9 @@ export class OpenVikingClient { processing_mode: options.processingMode, tags: options.tags, tag_mode: - options.tags === undefined ? undefined : (options.tagMode ?? "replace"), + options.tags !== undefined || options.tagMode === "clear" + ? (options.tagMode ?? "replace") + : undefined, wait: options.wait, timeout: options.timeout, telemetry: options.telemetry, @@ -668,7 +673,9 @@ export class OpenVikingClient { recursive: options.recursive ?? true, tags: options.tags, tag_mode: - options.tags === undefined ? undefined : (options.tagMode ?? "replace"), + options.tags !== undefined || options.tagMode === "clear" + ? (options.tagMode ?? "replace") + : undefined, }); return this.request("POST", "/api/v1/content/reindex", { body: mergeExtra(body, options.extra, ["tags", "tag_mode"]), diff --git a/sdk/typescript/src/types.ts b/sdk/typescript/src/types.ts index 8715f7eca33..5d5a657e0c7 100644 --- a/sdk/typescript/src/types.ts +++ b/sdk/typescript/src/types.ts @@ -91,7 +91,7 @@ export interface AddResourceOptions extends WaitOptions { processingMode?: ProcessingMode; args?: JsonObject; tags?: string[]; - tagMode?: "replace" | "append"; + tagMode?: "replace" | "append" | "clear"; extra?: JsonObject; } /** Content write options. */ @@ -99,7 +99,7 @@ export interface WriteOptions extends WaitOptions { mode?: string; processingMode?: ProcessingMode; tags?: string[]; - tagMode?: "replace" | "append"; + tagMode?: "replace" | "append" | "clear"; extra?: JsonObject; } /** One file write in a batch. */ @@ -133,7 +133,7 @@ export interface ReindexOptions { dryRun?: boolean; recursive?: boolean; tags?: string[]; - tagMode?: "replace" | "append"; + tagMode?: "replace" | "append" | "clear"; extra?: JsonObject; } /** Semantic retrieval options shared by find and search. */ diff --git a/sdk/typescript/tests/client.test.ts b/sdk/typescript/tests/client.test.ts index 285c08d8d04..7181214a9ff 100644 --- a/sdk/typescript/tests/client.test.ts +++ b/sdk/typescript/tests/client.test.ts @@ -452,6 +452,28 @@ describe("OpenVikingClient", () => { expect(JSON.parse(String(fetcher.mock.calls[3]![1]?.body))).toMatchObject({ tags: ["env=prod"], include_tags: true }); }); + it("sends clear tag mode without tags", async () => { + const fetcher = vi + .fn() + .mockImplementation(async () => ok({})); + const client = new OpenVikingClient({ + baseUrl: "https://example.com", + fetch: fetcher, + }); + + await client.addResource("https://example.com/demo.md", { + tagMode: "clear", + }); + await client.write("resources/demo.md", "updated", { tagMode: "clear" }); + await client.reindex("resources/demo.md", { tagMode: "clear" }); + + for (const call of fetcher.mock.calls) { + const body = JSON.parse(String(call[1]?.body)); + expect(body).not.toHaveProperty("tags"); + expect(body.tag_mode).toBe("clear"); + } + }); + it("supports batch write, byte download, and resource extra", async () => { const fetcher = vi .fn() diff --git a/tests/server/test_admin_rebuild_api.py b/tests/server/test_admin_rebuild_api.py index 2468bce064c..4806c8d5e36 100644 --- a/tests/server/test_admin_rebuild_api.py +++ b/tests/server/test_admin_rebuild_api.py @@ -234,6 +234,46 @@ async def reindex( assert "reason" not in response.result +@pytest.mark.asyncio +async def test_reindex_clear_without_tags_is_forwarded(monkeypatch): + from openviking.server.routers.content import ReindexRequest, reindex + + seen = {} + + class FakeService: + async def reindex(self, **kwargs): + seen.update(kwargs) + return {"status": "completed"} + + ctx = RequestContext( + user=UserIdentifier(account_id="test", user_id="alice"), + role=Role.ROOT, + ) + monkeypatch.setattr("openviking.server.routers.content.get_service", lambda: FakeService()) + + await reindex( + body=ReindexRequest( + uri="viking://resources/demo", + tag_mode="clear", + ), + ctx=ctx, + ) + + assert seen["tags"] is None + assert seen["tag_mode"] == "clear" + + +def test_reindex_executor_resolves_clear_without_tags(): + from openviking.service.reindex_executor import ReindexExecutor + from openviking.utils.ingest_options import IngestOptions + + assert ReindexExecutor._resolve_ingest_options( + mode="vectors_only", + tags=None, + tag_mode="clear", + ) == IngestOptions(search_tags=[], search_tag_mode="clear") + + @pytest.mark.asyncio async def test_reindex_resource_vectors_only_wait_false(monkeypatch): from openviking.server.routers.content import ReindexRequest, reindex @@ -3209,7 +3249,7 @@ async def fake_vectorize_directory(uri, abstract, overview, **kwargs): @pytest.mark.asyncio -async def test_reindex_upsert_applies_empty_replace_tags_to_embedding_message(monkeypatch): +async def test_reindex_upsert_ignores_empty_replace_tags(monkeypatch): from types import SimpleNamespace from openviking.service.reindex_executor import ReindexExecutor @@ -3247,6 +3287,49 @@ async def enqueue_embedding_msg(self, msg): ingest_options=IngestOptions.from_search_tags([], mode="replace"), ) + assert "search_tags" not in queued[0].context_data + assert "_upsert_options" not in queued[0].context_data + + +@pytest.mark.asyncio +async def test_reindex_upsert_applies_clear_tags_to_embedding_message(monkeypatch): + from types import SimpleNamespace + + from openviking.service.reindex_executor import ReindexExecutor + from openviking.utils.ingest_options import IngestOptions + + queued = [] + + class FakeVikingDB: + async def enqueue_embedding_msg(self, msg): + queued.append(msg) + return True + + monkeypatch.setattr( + "openviking.service.reindex_executor.get_service", + lambda: SimpleNamespace(vikingdb_manager=FakeVikingDB()), + ) + monkeypatch.setattr( + "openviking.service.reindex_executor.get_request_wait_tracker", + lambda: SimpleNamespace(register_embedding_root=lambda *args: None), + ) + + ctx = RequestContext( + user=UserIdentifier(account_id="test", user_id="alice"), + role=Role.ROOT, + ) + await ReindexExecutor()._upsert_context( + uri="viking://resources/demo.md", + parent_uri="viking://resources", + abstract="demo", + vector_text="demo", + is_leaf=True, + context_type="resource", + level=ContextLevel.DETAIL, + ctx=ctx, + ingest_options=IngestOptions.from_search_tags(None, mode="clear"), + ) + assert queued[0].context_data["search_tags"] == [] assert queued[0].context_data["_upsert_options"] == {"search_tag_mode": "replace"} diff --git a/tests/server/test_api_content.py b/tests/server/test_api_content.py index 3e749b22d9e..80e6f5fc958 100644 --- a/tests/server/test_api_content.py +++ b/tests/server/test_api_content.py @@ -41,6 +41,17 @@ def test_write_content_request_accepts_tags_and_tag_mode(): assert request.tag_mode == "append" +def test_write_content_request_accepts_clear_without_tags(): + request = WriteContentRequest( + uri="viking://resources/demo.md", + content="updated", + tag_mode="clear", + ) + + assert request.tags is None + assert request.tag_mode == "clear" + + async def test_write_forwards_processing_mode_to_service(monkeypatch): seen = {} @@ -90,6 +101,30 @@ async def fake_write(**kwargs): assert seen["tag_mode"] == "append" +async def test_write_forwards_clear_without_tags_to_service(monkeypatch): + seen = {} + + async def fake_write(**kwargs): + seen.update(kwargs) + return {"uri": kwargs["uri"]} + + 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) + + await content_router.write( + WriteContentRequest( + uri="viking://resources/demo.md", + content="updated", + tag_mode="clear", + ), + ctx, + ) + + assert seen["tags"] is None + assert seen["tag_mode"] == "clear" + + async def _first_child_uri(client, uri: str) -> str: response = await client.get( "/api/v1/fs/ls", diff --git a/tests/service/test_resource_service_connector.py b/tests/service/test_resource_service_connector.py index 7c641254e2f..9e0812c75f2 100644 --- a/tests/service/test_resource_service_connector.py +++ b/tests/service/test_resource_service_connector.py @@ -2291,6 +2291,80 @@ async def test_tos_connector_forwards_tags_and_mode( } +@pytest.mark.asyncio +async def test_tos_connector_forwards_clear_without_tags( + monkeypatch, + connector_config, + ctx, + service, +): + tracker = _task_tracker() + connector_client = SimpleNamespace( + submit_doc_add=AsyncMock(return_value={"task_key": "connector-1"}) + ) + _install_connector_dependencies(monkeypatch, tracker, connector_client) + + await service.add_resource( + path="tos://bucket/prefix", + ctx=ctx, + to="viking://resources/imports", + tag_mode="clear", + ) + + submitted = connector_client.submit_doc_add.await_args.kwargs + assert submitted["extra_params"] == {"tag_mode": "clear"} + + +@pytest.mark.asyncio +async def test_tos_connector_clear_ignores_invalid_tags( + monkeypatch, + connector_config, + ctx, + service, +): + tracker = _task_tracker() + connector_client = SimpleNamespace( + submit_doc_add=AsyncMock(return_value={"task_key": "connector-1"}) + ) + _install_connector_dependencies(monkeypatch, tracker, connector_client) + + await service.add_resource( + path="tos://bucket/prefix", + ctx=ctx, + to="viking://resources/imports", + tags=["invalid"], + tag_mode="clear", + ) + + submitted = connector_client.submit_doc_add.await_args.kwargs + assert submitted["extra_params"] == {"tag_mode": "clear"} + + +@pytest.mark.asyncio +async def test_tos_connector_ignores_empty_replace_tags( + monkeypatch, + connector_config, + ctx, + service, +): + tracker = _task_tracker() + connector_client = SimpleNamespace( + submit_doc_add=AsyncMock(return_value={"task_key": "connector-1"}) + ) + _install_connector_dependencies(monkeypatch, tracker, connector_client) + + await service.add_resource( + path="tos://bucket/prefix", + ctx=ctx, + to="viking://resources/imports", + tags=[], + tag_mode="replace", + ) + + submitted = connector_client.submit_doc_add.await_args.kwargs + assert submitted["extra_params"] is None + + @pytest.mark.asyncio async def test_monitor_links_reason_memory_on_success( monkeypatch, diff --git a/tests/service/test_resource_service_watch.py b/tests/service/test_resource_service_watch.py index b9d213bf8bf..70471bbe4d3 100644 --- a/tests/service/test_resource_service_watch.py +++ b/tests/service/test_resource_service_watch.py @@ -405,6 +405,40 @@ async def fake_finish_prepared_resource(*args, **kwargs): search_tag_mode="append", ) + def test_clear_without_tags_builds_clear_ingest_options( + self, resource_service: ResourceService + ): + assert resource_service._add_resource_ingest_tag_kwargs( + tags=None, + tag_mode="clear", + ) == { + "ingest_options": IngestOptions( + search_tags=[], + search_tag_mode="clear", + ) + } + + def test_watch_persists_clear_without_tags(self, resource_service: ResourceService): + assert resource_service._watch_processor_kwargs({}, None, "clear") == { + "tag_mode": "clear" + } + + def test_add_resource_message_round_trip_preserves_clear_without_tags(self): + message = AddResourceMsg( + task_id="task-clear", + path="https://example.com/demo.md", + root_uri="viking://resources/demo", + account_id="acct", + user_id="user", + role="user", + tag_mode="clear", + ) + + restored = AddResourceMsg.from_dict(message.to_dict()) + + assert restored.tags is None + assert restored.tag_mode == "clear" + @pytest.mark.asyncio async def test_create_watch_task_with_default_interval( self, resource_service: ResourceService, request_context: RequestContext diff --git a/tests/storage/test_context_update_plan.py b/tests/storage/test_context_update_plan.py index e3538aed107..b8c30eeaf34 100644 --- a/tests/storage/test_context_update_plan.py +++ b/tests/storage/test_context_update_plan.py @@ -974,6 +974,341 @@ def test_healthy_noop_produces_no_actions_or_semantic_plan(): assert plan.direct_index_actions == () +@pytest.mark.asyncio +async def test_healthy_rnfv_clear_request_produces_scalar_only_update(): + from openviking.storage.context_update_plan import ( + FieldPatch, + build_context_update_plan_from_snapshot, + ) + from openviking.storage.resource_rnfv import ( + FormalEntry, + FormalTreeSnapshot, + NewArtifactSnapshot, + NewEntry, + RequestIntent, + RNFVSnapshot, + VectorIndexSnapshot, + VectorRecordSnapshot, + ) + from openviking.utils.ingest_options import IngestOptions + + uri = "viking://resources/repo/a.txt" + ingest_options = IngestOptions.from_search_tags(None, mode="clear") + request = RequestIntent.from_ingest_options( + target_uri=uri, + processing_mode="vectors_only", + ingest_options=ingest_options, + ) + snapshot = RNFVSnapshot( + request, + NewArtifactSnapshot({"": NewEntry(md5="same")}), + FormalTreeSnapshot({"": FormalEntry()}), + VectorIndexSnapshot( + { + "a-l2": VectorRecordSnapshot( + "a-l2", + uri, + "", + 2, + {"md5": "same", "search_tags": ["scope=old"]}, + ) + }, + request.required_vector_fields(), + ), + ) + + diff, plan = await build_context_update_plan_from_snapshot( + snapshot=snapshot, + store=AsyncMock(), + artifact_ref=object(), + target=AsyncMock(), + vikingdb=AsyncMock(), + context_type="resource", + is_code_repo=False, + account_id="acc", + ctx=object(), + root_preexisting=True, + artifact_paths={"": "repository/a.txt"}, + ingest_options=ingest_options, + root_is_file=True, + ) + + assert diff.entries[""].content_state.value == "unchanged" + assert request.scalar_intents[0].value == () + assert request.required_vector_fields() >= {"search_tags"} + assert plan.content_tree_actions == () + assert plan.semantic_plan is None + assert len(plan.direct_index_actions) == 1 + action = plan.direct_index_actions[0] + assert action.action.value == "update_fields" + assert action.record_id == "a-l2" + assert action.field_patch == FieldPatch( + {"search_tags": ()}, + {"search_tags": "replace"}, + { + "uri": uri, + "account_id": "acc", + "level": 2, + "md5": "same", + "search_tags": [], + }, + ) + + +@pytest.mark.asyncio +async def test_healthy_rnfv_empty_replace_request_is_noop(): + from openviking.storage.context_update_plan import build_context_update_plan_from_snapshot + from openviking.storage.resource_rnfv import ( + FormalEntry, + FormalTreeSnapshot, + NewArtifactSnapshot, + NewEntry, + RequestIntent, + RNFVSnapshot, + VectorIndexSnapshot, + VectorRecordSnapshot, + ) + from openviking.utils.ingest_options import IngestOptions + + uri = "viking://resources/repo/a.txt" + ingest_options = IngestOptions.from_search_tags([], mode="replace") + request = RequestIntent.from_ingest_options( + target_uri=uri, + processing_mode="vectors_only", + ingest_options=ingest_options, + ) + snapshot = RNFVSnapshot( + request, + NewArtifactSnapshot({"": NewEntry(md5="same")}), + FormalTreeSnapshot({"": FormalEntry()}), + VectorIndexSnapshot( + { + "a-l2": VectorRecordSnapshot( + "a-l2", + uri, + "", + 2, + {"md5": "same", "search_tags": ["scope=old"]}, + ) + }, + request.required_vector_fields(), + ), + ) + + diff, plan = await build_context_update_plan_from_snapshot( + snapshot=snapshot, + store=AsyncMock(), + artifact_ref=object(), + target=AsyncMock(), + vikingdb=AsyncMock(), + context_type="resource", + is_code_repo=False, + account_id="acc", + ctx=object(), + root_preexisting=True, + artifact_paths={"": "repository/a.txt"}, + ingest_options=ingest_options, + root_is_file=True, + ) + + assert diff.entries[""].content_state.value == "unchanged" + assert request.scalar_intents == () + assert "search_tags" not in request.required_vector_fields() + assert plan.is_noop() + + +def test_healthy_directory_rnfv_clear_updates_all_vector_levels(): + from openviking.storage.context_update_plan import ( + ContentState, + IndexState, + build_context_update_plan, + ) + from openviking.storage.resource_diff import ResourceDiffEntry, ResourceDiffResult + from openviking.storage.resource_rnfv import ( + RequestIntent, + VectorRecordSnapshot, + ) + from openviking.utils.ingest_options import IngestOptions + + root = "viking://resources/repo" + request = RequestIntent.from_ingest_options( + target_uri=root, + processing_mode="semantic_and_vectors", + ingest_options=IngestOptions.from_search_tags(None, mode="clear"), + ) + records = { + "root-l0": VectorRecordSnapshot( + "root-l0", root, "", 0, {"search_tags": ["scope=old"]} + ), + "root-l1": VectorRecordSnapshot( + "root-l1", root, "", 1, {"search_tags": ["scope=old"]} + ), + "a-l2": VectorRecordSnapshot( + "a-l2", + root + "/a.py", + "a.py", + 2, + {"md5": "same", "search_tags": ["scope=old"]}, + ), + } + + plan = build_context_update_plan( + root_uri=root, + context_type="resource", + request=request, + diff=ResourceDiffResult( + { + "": ResourceDiffEntry( + "", + ContentState.UNCHANGED, + IndexState.COMPLETE, + old_kind="directory", + new_kind="directory", + ), + "a.py": ResourceDiffEntry( + "a.py", + ContentState.UNCHANGED, + IndexState.COMPLETE, + old_kind="file", + new_kind="file", + md5="same", + ), + } + ), + new_kinds={"": "directory", "a.py": "file"}, + artifact_paths={"a.py": "repository/a.py"}, + records=records, + is_code_repo=False, + account_id="acc", + ) + + assert plan.content_tree_actions == () + assert plan.semantic_plan is None + assert { + (action.record_id, action.level, action.action.value) + for action in plan.direct_index_actions + } == { + ("root-l0", 0, "update_fields"), + ("root-l1", 1, "update_fields"), + ("a-l2", 2, "update_fields"), + } + assert all( + action.field_patch.values == {"search_tags": []} + and action.field_patch.modes == {"search_tags": "replace"} + for action in plan.direct_index_actions + ) + + +@pytest.mark.parametrize("existing_tags", [None, []]) +def test_healthy_rnfv_clear_is_noop_when_vector_has_no_tags(existing_tags): + from openviking.storage.context_update_plan import ( + ContentState, + IndexState, + build_context_update_plan, + ) + from openviking.storage.resource_diff import ResourceDiffEntry, ResourceDiffResult + from openviking.storage.resource_rnfv import RequestIntent, VectorRecordSnapshot + from openviking.utils.ingest_options import IngestOptions + + root = "viking://resources/repo" + fields = {"md5": "same"} + if existing_tags is not None: + fields["search_tags"] = existing_tags + request = RequestIntent.from_ingest_options( + target_uri=root, + processing_mode="vectors_only", + ingest_options=IngestOptions.from_search_tags(None, mode="clear"), + ) + plan = build_context_update_plan( + root_uri=root, + context_type="resource", + request=request, + diff=ResourceDiffResult( + { + "a.py": ResourceDiffEntry( + "a.py", + ContentState.UNCHANGED, + IndexState.COMPLETE, + old_kind="file", + new_kind="file", + md5="same", + ) + } + ), + new_kinds={"a.py": "file"}, + artifact_paths={"a.py": "repository/a.py"}, + records={ + "a-l2": VectorRecordSnapshot( + "a-l2", root + "/a.py", "a.py", 2, fields + ) + }, + is_code_repo=False, + account_id="acc", + ) + + assert plan.is_noop() + + +@pytest.mark.parametrize( + ("existing_tags", "expected_update"), + [ + (["scope=old"], True), + (["scope=new"], False), + (None, True), + ([], True), + ], +) +def test_healthy_rnfv_non_empty_replace_compares_against_vector_tags( + existing_tags, expected_update +): + from openviking.storage.context_update_plan import ( + ContentState, + IndexState, + build_context_update_plan, + ) + from openviking.storage.resource_diff import ResourceDiffEntry, ResourceDiffResult + from openviking.storage.resource_rnfv import RequestIntent, VectorRecordSnapshot + from openviking.utils.ingest_options import IngestOptions + + root = "viking://resources/repo" + fields = {"md5": "same"} + if existing_tags is not None: + fields["search_tags"] = existing_tags + request = RequestIntent.from_ingest_options( + target_uri=root, + processing_mode="vectors_only", + ingest_options=IngestOptions.from_search_tags(["scope=new"], mode="replace"), + ) + plan = build_context_update_plan( + root_uri=root, + context_type="resource", + request=request, + diff=ResourceDiffResult( + { + "a.py": ResourceDiffEntry( + "a.py", + ContentState.UNCHANGED, + IndexState.COMPLETE, + old_kind="file", + new_kind="file", + md5="same", + ) + } + ), + new_kinds={"a.py": "file"}, + artifact_paths={"a.py": "repository/a.py"}, + records={ + "a-l2": VectorRecordSnapshot( + "a-l2", root + "/a.py", "a.py", 2, fields + ) + }, + is_code_repo=False, + account_id="acc", + ) + + assert bool(plan.direct_index_actions) is expected_update + + @pytest.mark.asyncio async def test_vectorize_disabled_plan_ignores_stale_vectors_and_compares_formal_content(): from openviking.storage.context_update_plan import ( @@ -1601,19 +1936,58 @@ def test_vectors_only_missing_index_for_existing_content_uses_partial_update_rep assert plan.direct_index_actions[0].action.value == "merge" -def test_vectors_only_partial_repair_preserves_explicit_replace_empty_tags(): +def test_vectors_only_partial_repair_ignores_explicit_replace_empty_tags(): from openviking.storage.context_update_plan import build_context_update_plan from openviking.storage.resource_diff import ResourceDiffEntry, ResourceDiffResult - from openviking.storage.resource_rnfv import RequestIntent, ScalarIntent + from openviking.storage.resource_rnfv import RequestIntent + from openviking.utils.ingest_options import IngestOptions root = "viking://resources/repo" plan = build_context_update_plan( root_uri=root, context_type="resource", - request=RequestIntent( - root, - "vectors_only", - scalar_intents=(ScalarIntent("search_tags", "replace", ()),), + request=RequestIntent.from_ingest_options( + target_uri=root, + processing_mode="vectors_only", + ingest_options=IngestOptions.from_search_tags([], mode="replace"), + ), + diff=ResourceDiffResult( + { + "a.py": ResourceDiffEntry( + "a.py", + "unchanged", + "missing", + old_kind="file", + new_kind="file", + md5="same", + ) + } + ), + new_kinds={"a.py": "file"}, + artifact_paths={"a.py": "repository/a.py"}, + records={}, + is_code_repo=False, + account_id="acc", + ) + + assert len(plan.direct_index_actions) == 1 + assert plan.direct_index_actions[0].field_patch is None + + +def test_vectors_only_partial_repair_preserves_clear_tags_intent(): + from openviking.storage.context_update_plan import build_context_update_plan + from openviking.storage.resource_diff import ResourceDiffEntry, ResourceDiffResult + from openviking.storage.resource_rnfv import RequestIntent + from openviking.utils.ingest_options import IngestOptions + + root = "viking://resources/repo" + plan = build_context_update_plan( + root_uri=root, + context_type="resource", + request=RequestIntent.from_ingest_options( + target_uri=root, + processing_mode="vectors_only", + ingest_options=IngestOptions.from_search_tags(None, mode="clear"), ), diff=ResourceDiffResult( { @@ -2225,6 +2599,16 @@ async def enqueue(queue, message, **kwargs): {"search_tags": "replace"}, ), ), + DirectIndexAction( + "update_fields", + "viking://resources/repo/clear.py", + 2, + "id-clear", + field_patch=FieldPatch( + {"search_tags": []}, + {"search_tags": "replace"}, + ), + ), DirectIndexAction( "merge", "viking://resources/repo/c.py", @@ -2239,9 +2623,16 @@ async def enqueue(queue, message, **kwargs): ), ctx=ctx, ) - assert [msg.action.value for msg in enqueued] == ["delete", "update_fields"] + assert [msg.action.value for msg in enqueued] == [ + "delete", + "update_fields", + "update_fields", + ] assert enqueued[0].record_ids == ["id-a"] assert enqueued[1].update_fields["search_tags"] == ["scope=new"] + assert enqueued[2].record_ids == ["id-clear"] + assert enqueued[2].update_fields["search_tags"] == [] + assert enqueued[2].field_modes == {"search_tags": "replace"} processor._vectorize_resource_file.assert_awaited_once_with( "viking://resources/repo/c.py", ctx=ctx, diff --git a/tests/storage/test_resource_diff_snapshot.py b/tests/storage/test_resource_diff_snapshot.py index 00e516b82f5..1b8b2c46fb6 100644 --- a/tests/storage/test_resource_diff_snapshot.py +++ b/tests/storage/test_resource_diff_snapshot.py @@ -313,6 +313,63 @@ async def test_build_rnfv_snapshot_skips_vector_inventory_when_vectorize_disable vikingdb.get_incremental_inventory_under_uri.assert_not_awaited() +@pytest.mark.asyncio +@pytest.mark.parametrize( + ("tags", "tag_mode", "expects_search_tags"), + [ + (None, "clear", True), + ([], "replace", False), + ], +) +async def test_build_rnfv_snapshot_projects_tags_only_for_effective_request_intent( + tmp_path, tags, tag_mode, expects_search_tags +): + from openviking.parse.output import LocalParseOutputStore + from openviking.storage.resource_rnfv import RequestIntent + from openviking.utils.ingest_options import IngestOptions + + root = "viking://resources/x" + store = LocalParseOutputStore(local_root=str(tmp_path / "out")) + ref = await store.create_artifact(root_type="dir") + await store.write_bytes(ref, "repository/a.py", b"same") + inventory = await prepare_artifact_inventory(store, ref, doc_rel="repository") + vikingdb = _FakeVikingDB( + { + f"{root}/a.py": { + "id": "a-l2", + "level": 2, + "md5": inventory.entries["a.py"].md5, + "search_tags": ["scope=old"], + } + } + ) + request = RequestIntent.from_ingest_options( + target_uri=root, + processing_mode="vectors_only", + ingest_options=IngestOptions.from_search_tags(tags, mode=tag_mode), + ) + + snapshot = await build_rnfv_snapshot( + viking_fs=_FakeVikingFS( + [{"rel_path": "a.py", "isDir": False, "uri": f"{root}/a.py"}] + ), + vikingdb=vikingdb, + store=store, + artifact_ref=ref, + target_uri=root, + ctx=_Ctx(), + doc_rel="repository", + request_intent=request, + artifact_inventory=inventory, + target_preexisting=True, + ) + + assert ("search_tags" in vikingdb.inventory_output_fields) is expects_search_tags + assert ("search_tags" in snapshot.vectors.projected_fields) is expects_search_tags + record = snapshot.vectors.records_by_id["a-l2"] + assert ("search_tags" in record.fields) is expects_search_tags + + @pytest.mark.asyncio async def test_build_rnfv_snapshot_starts_new_formal_and_vector_reads_concurrently( tmp_path, monkeypatch diff --git a/tests/storage/test_semantic_msg_ingest_options.py b/tests/storage/test_semantic_msg_ingest_options.py index a9a31f89aa0..cb6572c9eb5 100644 --- a/tests/storage/test_semantic_msg_ingest_options.py +++ b/tests/storage/test_semantic_msg_ingest_options.py @@ -123,3 +123,18 @@ def test_semantic_msg_roundtrip_preserves_local_artifact_snapshot(): assert restored.artifact_ref["resource_rel"] == "repository" assert restored.artifact_files == ["a.py", "src/b.py"] assert restored.file_abstracts == {"viking://resources/x/a.py": "summary a"} + + +def test_clear_ingest_options_survive_semantic_message_round_trip(): + msg = SemanticMsg( + uri="viking://resources/demo", + context_type="resource", + ingest_options=IngestOptions.from_search_tags(None, mode="clear"), + ) + + restored = SemanticMsg.from_dict(msg.to_dict()) + + assert restored.ingest_options == IngestOptions( + search_tags=[], + search_tag_mode="clear", + ) diff --git a/tests/unit/session/memory/test_embedding_template.py b/tests/unit/session/memory/test_embedding_template.py index e88974a7c1d..881e5f9a67d 100644 --- a/tests/unit/session/memory/test_embedding_template.py +++ b/tests/unit/session/memory/test_embedding_template.py @@ -104,10 +104,14 @@ def test_content_template_render_failure_is_logged_before_plain_content_fallback class TestEmbeddingTextConstruction: @pytest.mark.asyncio @pytest.mark.parametrize( - ("tags", "mode"), - [(["team=search"], "replace"), (["env=prod"], "append"), ([], "replace")], + ("tags", "mode", "expected_mode"), + [ + (["team=search"], "replace", "replace"), + (["env=prod"], "append", "append"), + ([], "clear", "replace"), + ], ) - async def test_vectorization_preserves_write_tag_mode(self, tags, mode): + async def test_vectorization_preserves_write_tag_mode(self, tags, mode, expected_mode): registry = MemoryTypeRegistry(load_schemas=False) memory_dir = PromptManager._get_bundled_templates_dir() / "memory" registry.load_from_yaml(str(memory_dir / "trajectories.yaml")) @@ -147,7 +151,9 @@ async def test_vectorization_preserves_write_tag_mode(self, tags, mode): embedding_msg = updater._vikingdb.enqueue_embedding_msg.await_args.args[0] assert embedding_msg.context_data["search_tags"] == tags - assert embedding_msg.context_data["_upsert_options"] == {"search_tag_mode": mode} + assert embedding_msg.context_data["_upsert_options"] == { + "search_tag_mode": expected_mode + } @pytest.mark.asyncio async def test_trajectory_vectorization_adds_source_experience_search_tags(self): diff --git a/tests/utils/test_ingest_options.py b/tests/utils/test_ingest_options.py new file mode 100644 index 00000000000..46b8b00017c --- /dev/null +++ b/tests/utils/test_ingest_options.py @@ -0,0 +1,31 @@ +from openviking.utils.ingest_options import IngestOptions + + +def test_replace_with_empty_tags_has_no_tag_intent(): + assert IngestOptions.from_search_tags([], mode="replace") == IngestOptions() + + +def test_clear_without_tags_becomes_explicit_empty_replacement(): + assert IngestOptions.from_search_tags(None, mode="clear") == IngestOptions( + search_tags=[], + search_tag_mode="clear", + ) + + +def test_clear_ignores_supplied_tags(): + assert IngestOptions.from_search_tags(["team=search"], mode="clear") == IngestOptions( + search_tags=[], + search_tag_mode="clear", + ) + + +def test_deserialized_empty_replace_has_no_tag_intent(): + assert IngestOptions.from_value( + {"search_tags": [], "search_tag_mode": "replace"} + ) == IngestOptions() + + +def test_direct_empty_replace_is_normalized_when_consumed(): + assert IngestOptions.from_value( + IngestOptions(search_tags=[], search_tag_mode="replace") + ) == IngestOptions() diff --git a/web-studio/src/i18n/locales/en/resources.ts b/web-studio/src/i18n/locales/en/resources.ts index 69e5a4aee32..a4f97e97056 100644 --- a/web-studio/src/i18n/locales/en/resources.ts +++ b/web-studio/src/i18n/locales/en/resources.ts @@ -315,6 +315,7 @@ const resources = { tagMode: 'Tag Write Mode', 'tagMode.replace': 'Replace', 'tagMode.append': 'Append', + 'tagMode.clear': 'Clear', reason: 'Reason', 'reason.placeholder': 'Why are you adding this resource?', instruction: 'Instruction', diff --git a/web-studio/src/i18n/locales/zh-CN/resources.ts b/web-studio/src/i18n/locales/zh-CN/resources.ts index c026a4a3376..236f3a4c978 100644 --- a/web-studio/src/i18n/locales/zh-CN/resources.ts +++ b/web-studio/src/i18n/locales/zh-CN/resources.ts @@ -296,6 +296,7 @@ const resources = { tagMode: '标签写入方式', 'tagMode.replace': '替换', 'tagMode.append': '追加', + 'tagMode.clear': '清空', reason: '添加原因', 'reason.placeholder': '为什么要添加这个资源?', instruction: '处理指令', diff --git a/web-studio/src/routes/resources/-components/additional-resource-options.tsx b/web-studio/src/routes/resources/-components/additional-resource-options.tsx index 2d33680ae15..5375091b0d4 100644 --- a/web-studio/src/routes/resources/-components/additional-resource-options.tsx +++ b/web-studio/src/routes/resources/-components/additional-resource-options.tsx @@ -208,7 +208,10 @@ export function AdditionalResourceOptions({ onValueChange={(tagMode) => onChange({ ...value, - tagMode: tagMode === 'append' ? 'append' : 'replace', + tagMode: + tagMode === 'append' || tagMode === 'clear' + ? tagMode + : 'replace', }) } disabled={disabled} @@ -219,6 +222,7 @@ export function AdditionalResourceOptions({ {t('tagMode.replace')} {t('tagMode.append')} + {t('tagMode.clear')} diff --git a/web-studio/src/routes/resources/-lib/resource-import-request.test.ts b/web-studio/src/routes/resources/-lib/resource-import-request.test.ts index 55f5545871e..2ee4813e6ac 100644 --- a/web-studio/src/routes/resources/-lib/resource-import-request.test.ts +++ b/web-studio/src/routes/resources/-lib/resource-import-request.test.ts @@ -181,6 +181,20 @@ describe('resource import request builders', () => { }) }) + it('serializes clear mode without tags', () => { + const body = buildResourceImportCommonBody({ + ...BASE_FORM_STATE, + additionalOptions: { + ...BASE_FORM_STATE.additionalOptions, + tagMode: 'clear', + tags: '', + }, + }) + + expect(body).not.toHaveProperty('tags') + expect(body.tag_mode).toBe('clear') + }) + it('removes remote-only scheduling and routing fields from uploads', () => { expect( buildUploadedResourceRequest(' temp-id ', 'guide.pdf', { diff --git a/web-studio/src/routes/resources/-lib/resource-import-request.ts b/web-studio/src/routes/resources/-lib/resource-import-request.ts index 9c2c465d0df..c19a5d04144 100644 --- a/web-studio/src/routes/resources/-lib/resource-import-request.ts +++ b/web-studio/src/routes/resources/-lib/resource-import-request.ts @@ -76,7 +76,11 @@ export function buildResourceImportCommonBody({ processing_mode: sourceCapabilities.nativeOptions ? additionalOptions.processingMode : 'semantic_and_vectors', - ...(tags.length ? { tags, tag_mode: additionalOptions.tagMode } : {}), + ...(tags.length + ? { tags, tag_mode: additionalOptions.tagMode } + : additionalOptions.tagMode === 'clear' + ? { tag_mode: 'clear' as const } + : {}), ...(mode === 'remote' && sourceCapabilities.nativeOptions && additionalOptions.sourceName.trim() diff --git a/web-studio/src/routes/resources/-lib/resource-import-types.ts b/web-studio/src/routes/resources/-lib/resource-import-types.ts index 29f04be2e09..37fc03733d7 100644 --- a/web-studio/src/routes/resources/-lib/resource-import-types.ts +++ b/web-studio/src/routes/resources/-lib/resource-import-types.ts @@ -8,7 +8,7 @@ export type TempUploadResult = { export type ResourceProcessingMode = 'semantic_and_vectors' | 'vectors_only' -export type ResourceTagMode = 'replace' | 'append' +export type ResourceTagMode = 'replace' | 'append' | 'clear' export type ResourceImportArgs = Record & { allow_external_links?: boolean