Macro is a unified workspace for teams: email, chat, docs, tasks, agents, calls, and CRM — @-linked together with shared AI memory.
TypeScript agentaiai-agentsall-in-onecrmcrm-systememaillinearmcpmessagingnotesnotionofficerustslackslack-alternativestartupstartup-toolstypescriptworkspace
feat(tags): any/all tag matching in AI tools (#4688)
gbirmand9293419a13a
diff --git a/js/app/packages/service-clients/service-cognition/generated/tools/schemas.ts b/js/app/packages/service-clients/service-cognition/generated/tools/schemas.tsindex 5c2af71c02..986796cc8a 100644--- a/js/app/packages/service-clients/service-cognition/generated/tools/schemas.ts+++ b/js/app/packages/service-clients/service-cognition/generated/tools/schemas.ts@@ -141,6 +141,27 @@ export const ContentSearch = z.object({z.null(),]).optional(),+ tagsMatch: z+ .any()+ .superRefine((x, ctx) => {+ const schemas = [z.literal('any'), z.literal('all')];+ const errors = schemas.reduce<z.ZodError[]>(+ (errors, schema) =>+ ((result) => (result.error ? [...errors, result.error] : errors))(+ schema.safeParse(x)+ ),+ []+ );+ if (schemas.length - errors.length !== 1) {+ ctx.addIssue({+ path: ctx.path,+ code: 'invalid_union',+ unionErrors: errors,+ message: 'Invalid input: Should pass single schema',+ });+ }+ })+ .optional(),});export const SearchToolResponse = z.object({@@ -914,6 +935,27 @@ export const ListEntities = z.object({z.null(),]).optional(),+ tagsMatch: z+ .any()+ .superRefine((x, ctx) => {+ const schemas = [z.literal('any'), z.literal('all')];+ const errors = schemas.reduce<z.ZodError[]>(+ (errors, schema) =>+ ((result) => (result.error ? [...errors, result.error] : errors))(+ schema.safeParse(x)+ ),+ []+ );+ if (schemas.length - errors.length !== 1) {+ ctx.addIssue({+ path: ctx.path,+ code: 'invalid_union',+ unionErrors: errors,+ message: 'Invalid input: Should pass single schema',+ });+ }+ })+ .optional(),});export const ListEntitiesResponse = z.object({@@ -1316,6 +1358,27 @@ export const NameSearch = z.object({z.null(),]).optional(),+ tagsMatch: z+ .any()+ .superRefine((x, ctx) => {+ const schemas = [z.literal('any'), z.literal('all')];+ const errors = schemas.reduce<z.ZodError[]>(+ (errors, schema) =>+ ((result) => (result.error ? [...errors, result.error] : errors))(+ schema.safeParse(x)+ ),+ []+ );+ if (schemas.length - errors.length !== 1) {+ ctx.addIssue({+ path: ctx.path,+ code: 'invalid_union',+ unionErrors: errors,+ message: 'Invalid input: Should pass single schema',+ });+ }+ })+ .optional(),});export const ReadCallRecord = z.object({ callId: z.string().uuid() });diff --git a/js/app/packages/service-clients/service-cognition/generated/tools/types.ts b/js/app/packages/service-clients/service-cognition/generated/tools/types.tsindex 9f7fbc647e..97a9f4571b 100644--- a/js/app/packages/service-clients/service-cognition/generated/tools/types.ts+++ b/js/app/packages/service-clients/service-cognition/generated/tools/types.ts@@ -116,6 +116,10 @@ export type UnifiedSearchIndex =* offered to the model.*/export type SearchMatchType = 'partial' | 'exact';+/**+ * How multiple tag filters combine when filtering items.+ */+export type TagMatch = 'any' | 'all';export type ContentType =| 'channel'| 'channel-message'@@ -1063,9 +1067,10 @@ export interface ContentSearch {*/query: string;/**- * Restrict results to items carrying at least one of the given tags (OR semantics). Each entry names a tag by its label, matched case-insensitively against the user's own tags; only set scope ("personal" or "team") when the user distinguishes between their personal and team tags. An unknown label fails with the list of available tags — call ListTags first when unsure what tags exist. Only taggable items (documents, emails, AI chats, projects) can match, so channels and call records are dropped while a tag filter is active.+ * Restrict results to items carrying the given tags — any of them by default, every one of them with tagsMatch="all". Each entry names a tag by its label, matched case-insensitively against the user's own tags; only set scope ("personal" or "team") when the user distinguishes between their personal and team tags. An unknown label fails with the list of available tags — call ListTags first when unsure what tags exist. Only taggable items (documents, emails, AI chats, projects) can match, so channels and call records are dropped while a tag filter is active.*/tags?: TagFilter[] | null;+ tagsMatch?: TagMatch;}/*** A tag selector in a tool request, matched by label against the caller's tag sets.@@ -1812,9 +1817,10 @@ export interface ListEntities {};sortBy?: SortBy;/**- * Filter results to items carrying at least one of the given tags (OR semantics). Each entry names a tag by its label, matched case-insensitively against the user's own tags; only set scope ("personal" or "team") when the user distinguishes between their personal and team tags. An unknown label fails with the list of available tags — call ListTags first when unsure what tags exist. Only taggable items (documents, tasks, projects, emails, AI chats) can match a tag filter. Prefer this over hand-building a propf filter for tags.+ * Filter results to items carrying the given tags — any of them by default, every one of them with tagsMatch="all". Each entry names a tag by its label, matched case-insensitively against the user's own tags; only set scope ("personal" or "team") when the user distinguishes between their personal and team tags. An unknown label fails with the list of available tags — call ListTags first when unsure what tags exist. Only taggable items (documents, tasks, projects, emails, AI chats) can match a tag filter. Prefer this over hand-building a propf filter for tags.*/tags?: TagFilter[] | null;+ tagsMatch?: TagMatch;}/*** Response returned by the list entities AI tool.@@ -2204,9 +2210,10 @@ export interface NameSearch {*/name: string;/**- * Restrict results to items carrying at least one of the given tags (OR semantics). Each entry names a tag by its label, matched case-insensitively against the user's own tags; only set scope ("personal" or "team") when the user distinguishes between their personal and team tags. An unknown label fails with the list of available tags — call ListTags first when unsure what tags exist. Only taggable items (documents, emails, AI chats, projects) can match, so channels and call records are dropped while a tag filter is active.+ * Restrict results to items carrying the given tags — any of them by default, every one of them with tagsMatch="all". Each entry names a tag by its label, matched case-insensitively against the user's own tags; only set scope ("personal" or "team") when the user distinguishes between their personal and team tags. An unknown label fails with the list of available tags — call ListTags first when unsure what tags exist. Only taggable items (documents, emails, AI chats, projects) can match, so channels and call records are dropped while a tag filter is active.*/tags?: TagFilter[] | null;+ tagsMatch?: TagMatch;}/*** Metadata for a project fetched from the databasediff --git a/rust/cloud-storage/ai_tools/src/search/search_service/content.rs b/rust/cloud-storage/ai_tools/src/search/search_service/content.rsindex 1e93cce969..c1b3bd02f2 100644--- a/rust/cloud-storage/ai_tools/src/search/search_service/content.rs+++ b/rust/cloud-storage/ai_tools/src/search/search_service/content.rs@@ -1,13 +1,14 @@use super::context::SearchToolContext;use super::types::{PAGE_SIZE, SearchMatchType, SearchToolResponse, annotate_result_tags, resolve_tag_filters,+ tag_filter_mode,};use ai_toolset::{AsyncTool, RequestContext, ServiceContext, ToolCallError, ToolResult};use async_trait::async_trait;use email::domain::ports::EmailService;use item_filters::{EmailFilters, EntityFilters};use macro_user_id::user_id::MacroUserIdStr;-use models_properties::service::tag_sets::TagFilter;+use models_properties::service::tag_sets::{TagFilter, TagMatch};use models_search::unified::{UnifiedSearchIndex, UnifiedSearchRequest, entity_filters_from_include,};@@ -45,14 +46,23 @@ pub struct ContentSearch {pub inbox: Option<String>,#[schemars(description = "\-Restrict results to items carrying at least one of the given tags (OR semantics). Each entry \-names a tag by its label, matched case-insensitively against the user's own tags; only set \-scope (\"personal\" or \"team\") when the user distinguishes between their personal and team \-tags. An unknown label fails with the list of available tags — call ListTags first when \-unsure what tags exist. Only taggable items (documents, emails, AI chats, projects) can \-match, so channels and call records are dropped while a tag filter is active.")]+Restrict results to items carrying the given tags — any of them by default, every one of \+them with tagsMatch=\"all\". Each entry names a tag by its label, matched case-insensitively \+against the user's own tags; only set scope (\"personal\" or \"team\") when the user \+distinguishes between their personal and team tags. An unknown label fails with the list of \+available tags — call ListTags first when unsure what tags exist. Only taggable items \+(documents, emails, AI chats, projects) can match, so channels and call records are dropped \+while a tag filter is active.")]#[serde(default)]pub tags: Option<Vec<TagFilter>>,++ #[schemars(description = "\+How multiple entries in tags combine: \"any\" (the default) matches items carrying at least \+one of the tags, \"all\" only items carrying every one of them. With \"all\", a label that \+exists in both the personal and team sets is ambiguous — set scope on that entry to pick one. \+Ignored unless tags is set.")]+ #[serde(default)]+ pub tags_match: TagMatch,}#[async_trait]@@ -107,6 +117,7 @@ impl AsyncTool<SearchToolContext> for ContentSearch {&search_context,(*request_context.user_id).as_ref(),filters,+ self.tags_match,).await?;tag_sets = Some(sets);@@ -116,6 +127,7 @@ impl AsyncTool<SearchToolContext> for ContentSearch {let base_filters = EntityFilters {email_filters,tag_option_ids,+ tag_filter_mode: tag_filter_mode(self.tags_match),..Default::default()};let search_request = UnifiedSearchRequest {diff --git a/rust/cloud-storage/ai_tools/src/search/search_service/name.rs b/rust/cloud-storage/ai_tools/src/search/search_service/name.rsindex d7407c0f83..36422b4fc9 100644--- a/rust/cloud-storage/ai_tools/src/search/search_service/name.rs+++ b/rust/cloud-storage/ai_tools/src/search/search_service/name.rs@@ -1,13 +1,14 @@use super::context::SearchToolContext;use super::types::{PAGE_SIZE, SearchMatchType, SearchToolResponse, annotate_result_tags, resolve_tag_filters,+ tag_filter_mode,};use ai_toolset::{AsyncTool, RequestContext, ServiceContext, ToolCallError, ToolResult};use async_trait::async_trait;use email::domain::ports::EmailService;use item_filters::{EmailFilters, EntityFilters};use macro_user_id::user_id::MacroUserIdStr;-use models_properties::service::tag_sets::TagFilter;+use models_properties::service::tag_sets::{TagFilter, TagMatch};use models_search::unified::{UnifiedSearchIndex, UnifiedSearchRequest, entity_filters_from_include,};@@ -45,14 +46,23 @@ pub struct NameSearch {pub inbox: Option<String>,#[schemars(description = "\-Restrict results to items carrying at least one of the given tags (OR semantics). Each entry \-names a tag by its label, matched case-insensitively against the user's own tags; only set \-scope (\"personal\" or \"team\") when the user distinguishes between their personal and team \-tags. An unknown label fails with the list of available tags — call ListTags first when \-unsure what tags exist. Only taggable items (documents, emails, AI chats, projects) can \-match, so channels and call records are dropped while a tag filter is active.")]+Restrict results to items carrying the given tags — any of them by default, every one of \+them with tagsMatch=\"all\". Each entry names a tag by its label, matched case-insensitively \+against the user's own tags; only set scope (\"personal\" or \"team\") when the user \+distinguishes between their personal and team tags. An unknown label fails with the list of \+available tags — call ListTags first when unsure what tags exist. Only taggable items \+(documents, emails, AI chats, projects) can match, so channels and call records are dropped \+while a tag filter is active.")]#[serde(default)]pub tags: Option<Vec<TagFilter>>,++ #[schemars(description = "\+How multiple entries in tags combine: \"any\" (the default) matches items carrying at least \+one of the tags, \"all\" only items carrying every one of them. With \"all\", a label that \+exists in both the personal and team sets is ambiguous — set scope on that entry to pick one. \+Ignored unless tags is set.")]+ #[serde(default)]+ pub tags_match: TagMatch,}#[async_trait]@@ -107,6 +117,7 @@ impl AsyncTool<SearchToolContext> for NameSearch {&search_context,(*request_context.user_id).as_ref(),filters,+ self.tags_match,).await?;tag_sets = Some(sets);@@ -116,6 +127,7 @@ impl AsyncTool<SearchToolContext> for NameSearch {let base_filters = EntityFilters {email_filters,tag_option_ids,+ tag_filter_mode: tag_filter_mode(self.tags_match),..Default::default()};let search_request = UnifiedSearchRequest {diff --git a/rust/cloud-storage/ai_tools/src/search/search_service/types.rs b/rust/cloud-storage/ai_tools/src/search/search_service/types.rsindex 49be1aef1b..4a75a23f52 100644--- a/rust/cloud-storage/ai_tools/src/search/search_service/types.rs+++ b/rust/cloud-storage/ai_tools/src/search/search_service/types.rs@@ -1,7 +1,8 @@use ai_toolset::{ToolCallError, ToolResult};+use item_filters::TagFilterMode;use models_properties::DataType;use models_properties::service::property_value::PropertyValue;-use models_properties::service::tag_sets::{AppliedTag, CallerTagSets, TagFilter};+use models_properties::service::tag_sets::{AppliedTag, CallerTagSets, TagFilter, TagMatch};use models_search::MatchType;use models_search::unified::UnifiedSearchResponseItem;use models_soup::SoupProperty;@@ -51,19 +52,39 @@ pub struct SearchToolResponse {pub results: Vec<TaggedSearchResult>,}+/// Map the model-facing tag match mode onto the search request's filter mode.+pub(super) fn tag_filter_mode(mode: TagMatch) -> TagFilterMode {+ match mode {+ TagMatch::Any => TagFilterMode::Any,+ TagMatch::All => TagFilterMode::All,+ }+}+/// Resolve the model's tag filters against the caller's tag sets, returning/// the matched option ids for `EntityFilters::tag_option_ids` plus the sets-/// for later result annotation. An unknown label fails with the available tags.+/// for later result annotation. An unknown label fails with the available+/// tags. In all mode every filter must name exactly one tag — the option ids+/// AND together, so expanding an unscoped label across scopes would require+/// items to carry both variants; the ambiguity fails and asks for a scope.pub(super) async fn resolve_tag_filters(context: &SearchToolContext,user_id: &str,filters: &[TagFilter],+ mode: TagMatch,) -> ToolResult<(CallerTagSets, Vec<String>)> {let sets = fetch_caller_tag_sets(context, user_id).await?;- let resolved = sets.resolve_filters(filters).map_err(|e| ToolCallError {- description: e.to_string(),- internal_error: anyhow::anyhow!(e),- })?;+ let resolved = match mode {+ TagMatch::Any => sets.resolve_filters(filters).map_err(|e| ToolCallError {+ description: e.to_string(),+ internal_error: anyhow::anyhow!(e),+ })?,+ TagMatch::All => sets+ .resolve_filters_unique(filters)+ .map_err(|e| ToolCallError {+ description: e.to_string(),+ internal_error: anyhow::anyhow!(e),+ })?,+ };let option_ids = resolved.into_iter().map(|option| option.option_id.to_string())diff --git a/rust/cloud-storage/models_properties/src/service/tag_sets.rs b/rust/cloud-storage/models_properties/src/service/tag_sets.rsindex 57df6686c0..7ece787d62 100644--- a/rust/cloud-storage/models_properties/src/service/tag_sets.rs+++ b/rust/cloud-storage/models_properties/src/service/tag_sets.rs@@ -52,6 +52,17 @@ pub struct TagFilter {pub scope: Option<TagScope>,}+/// How multiple tag filters combine when filtering items.+#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Deserialize, JsonSchema)]+#[serde(rename_all = "snake_case")]+pub enum TagMatch {+ /// Items carrying at least one of the tags match.+ #[default]+ Any,+ /// Only items carrying every one of the tags match.+ All,+}+/// A tag filter label that matched nothing in the caller's tag sets.#[derive(Debug, Clone, thiserror::Error)]#[error("unknown tag \"{label}\"{}", format_available(available))]@@ -70,6 +81,45 @@ fn format_available(available: &[String]) -> String {}}+/// A tag filter label that matched more than one of the caller's tags, in a+/// context that needs each filter to name exactly one.+#[derive(Debug, Clone, thiserror::Error)]+#[error(+ "tag \"{label}\" is ambiguous: it matches {}. Set scope (\"personal\" or \"team\") on that entry to pick one",+ format_matches(matches)+)]+pub struct AmbiguousTagError {+ /// The label that resolved to more than one tag.+ pub label: String,+ /// Every tag the label matched.+ pub matches: Vec<AppliedTag>,+}++fn format_matches(matches: &[AppliedTag]) -> String {+ matches+ .iter()+ .map(|tag| {+ let scope = match tag.scope {+ TagScope::Personal => "a personal",+ TagScope::Team => "a team",+ };+ format!("{scope} tag \"{}\"", tag.label)+ })+ .collect::<Vec<_>>()+ .join(" and ")+}++/// Errors from resolving tag filters that must each name exactly one tag.+#[derive(Debug, Clone, thiserror::Error)]+pub enum TagFilterError {+ /// A label matched nothing in the caller's tag sets.+ #[error(transparent)]+ Unknown(#[from] UnknownTagError),+ /// A label matched more than one tag.+ #[error(transparent)]+ Ambiguous(#[from] AmbiguousTagError),+}+/// One resolved tag option from the caller's sets.#[derive(Debug, Clone)]pub struct CallerTagOption {@@ -165,21 +215,7 @@ impl CallerTagSets {) -> Result<Vec<CallerTagOption>, UnknownTagError> {let mut resolved: Vec<CallerTagOption> = Vec::new();for filter in filters {- let matches: Vec<&CallerTagOption> = self- .options- .iter()- .filter(|o| {- o.label.eq_ignore_ascii_case(filter.label.trim())- && filter.scope.is_none_or(|scope| o.scope == scope)- })- .collect();- if matches.is_empty() {- return Err(UnknownTagError {- label: filter.label.clone(),- available: self.available_labels(),- });- }- for option in matches {+ for option in self.filter_matches(filter)? {if !resolved.iter().any(|r| r.option_id == option.option_id) {resolved.push(option.clone());}@@ -187,4 +223,55 @@ impl CallerTagSets {}Ok(resolved)}++ /// Like [`Self::resolve_filters`], but every filter must match exactly one+ /// tag. Used when the resolved options combine with AND: silently+ /// expanding an unscoped label present in both the personal and team set+ /// would require items to carry both variants, so the ambiguity fails+ /// loudly and asks for a scope instead.+ pub fn resolve_filters_unique(+ &self,+ filters: &[TagFilter],+ ) -> Result<Vec<CallerTagOption>, TagFilterError> {+ let mut resolved: Vec<CallerTagOption> = Vec::new();+ for filter in filters {+ let matches = self.filter_matches(filter)?;+ if matches.len() > 1 {+ return Err(AmbiguousTagError {+ label: filter.label.clone(),+ matches: matches+ .into_iter()+ .map(|o| AppliedTag {+ label: o.label.clone(),+ scope: o.scope,+ })+ .collect(),+ }+ .into());+ }+ let option = matches[0];+ if !resolved.iter().any(|r| r.option_id == option.option_id) {+ resolved.push(option.clone());+ }+ }+ Ok(resolved)+ }++ fn filter_matches(&self, filter: &TagFilter) -> Result<Vec<&CallerTagOption>, UnknownTagError> {+ let matches: Vec<&CallerTagOption> = self+ .options+ .iter()+ .filter(|o| {+ o.label.eq_ignore_ascii_case(filter.label.trim())+ && filter.scope.is_none_or(|scope| o.scope == scope)+ })+ .collect();+ if matches.is_empty() {+ return Err(UnknownTagError {+ label: filter.label.clone(),+ available: self.available_labels(),+ });+ }+ Ok(matches)+ }}diff --git a/rust/cloud-storage/models_properties/src/service/tag_sets/test.rs b/rust/cloud-storage/models_properties/src/service/tag_sets/test.rsindex 385d8ae523..d3b9fbc9af 100644--- a/rust/cloud-storage/models_properties/src/service/tag_sets/test.rs+++ b/rust/cloud-storage/models_properties/src/service/tag_sets/test.rs@@ -119,6 +119,48 @@ fn unknown_label_errors_with_available_labels() {assert!(err.to_string().contains("backend, mobile"));}+#[test]+fn unique_resolve_rejects_a_label_present_in_both_sets() {+ let personal_option = Uuid::from_u128(1);+ let team_option = Uuid::from_u128(2);+ let sets = CallerTagSets::new(vec![+ tag_set(+ Uuid::from_u128(10),+ user_owner(),+ &[(personal_option, "urgent")],+ ),+ tag_set(+ Uuid::from_u128(11),+ team_owner(),+ &[(team_option, "urgent")],+ ),+ ]);++ let err = sets+ .resolve_filters_unique(&[filter("urgent", None)])+ .unwrap_err();+ let TagFilterError::Ambiguous(err) = err else {+ panic!("expected ambiguous error, got {err:?}");+ };+ assert_eq!(err.label, "urgent");+ assert_eq!(err.matches.len(), 2);+ let message = err.to_string();+ assert!(message.contains("ambiguous"), "{message}");+ assert!(message.contains("scope"), "{message}");++ // A scope disambiguates, and unknown labels still fail as unknown.+ let resolved = sets+ .resolve_filters_unique(&[filter("urgent", Some(TagScope::Team))])+ .unwrap();+ assert_eq!(resolved.len(), 1);+ assert_eq!(resolved[0].option_id, team_option);++ let err = sets+ .resolve_filters_unique(&[filter("nonexistent", None)])+ .unwrap_err();+ assert!(matches!(err, TagFilterError::Unknown(_)));+}+#[test]fn duplicate_filters_dedupe_options() {let option_id = Uuid::from_u128(1);diff --git a/rust/cloud-storage/soup/src/inbound/toolset/list_entities.rs b/rust/cloud-storage/soup/src/inbound/toolset/list_entities.rsindex 5ab7104e22..e6ace6a9ab 100644--- a/rust/cloud-storage/soup/src/inbound/toolset/list_entities.rs+++ b/rust/cloud-storage/soup/src/inbound/toolset/list_entities.rs@@ -26,7 +26,7 @@ use item_filters::{use models_pagination::{SimpleSortMethod, TypeEraseCursor};use models_properties::DataType;use models_properties::service::property_value::PropertyValue;-use models_properties::service::tag_sets::{AppliedTag, CallerTagSets, TagFilter};+use models_properties::service::tag_sets::{AppliedTag, CallerTagSets, TagFilter, TagMatch};use models_soup::{SoupProperty, document::SoupDocumentSubType, item::SoupItem};use schemars::JsonSchema;use serde::{Deserialize, Serialize};@@ -449,17 +449,27 @@ inbox\"); call ListInboxes first to get the exact address. Only affects email re#[serde(default)]pub inbox: Option<String>,- /// Filter results to items carrying at least one of these tags.+ /// Filter results to items carrying these tags.#[schemars(description = "\-Filter results to items carrying at least one of the given tags (OR semantics). Each entry \-names a tag by its label, matched case-insensitively against the user's own tags; only set \-scope (\"personal\" or \"team\") when the user distinguishes between their personal and team \-tags. An unknown label fails with the list of available tags — call ListTags first when \-unsure what tags exist. Only taggable items (documents, tasks, projects, emails, AI chats) \-can match a tag filter. Prefer this over hand-building a propf filter for tags.")]+Filter results to items carrying the given tags — any of them by default, every one of them \+with tagsMatch=\"all\". Each entry names a tag by its label, matched case-insensitively \+against the user's own tags; only set scope (\"personal\" or \"team\") when the user \+distinguishes between their personal and team tags. An unknown label fails with the list of \+available tags — call ListTags first when unsure what tags exist. Only taggable items \+(documents, tasks, projects, emails, AI chats) can match a tag filter. Prefer this over \+hand-building a propf filter for tags.")]#[serde(default)]pub tags: Option<Vec<TagFilter>>,+ /// How multiple entries in `tags` combine.+ #[schemars(description = "\+How multiple entries in tags combine: \"any\" (the default) returns items carrying at least \+one of the tags, \"all\" returns only items carrying every one of them. With \"all\", a label \+that exists in both the personal and team sets is ambiguous — set scope on that entry to pick \+one. Ignored unless tags is set.")]+ #[serde(default)]+ pub tags_match: TagMatch,+/// Maximum number of items to return.#[schemars(description = "Maximum number of items to return. Defaults to 50; max 500.")]#[serde(default)]@@ -613,12 +623,30 @@ whereNone} else {let sets = fetch_caller_tag_sets(&service_context, &request_context).await?;- let resolved = sets- .resolve_filters(self.tag_filters())- .map_err(|e| ToolCallError {- description: e.to_string(),- internal_error: anyhow::anyhow!(e),- })?;+ // In all mode every filter must name exactly one tag — expanding+ // an unscoped label across scopes would AND both variants in.+ let resolved = match self.tags_match {+ TagMatch::Any => {+ sets.resolve_filters(self.tag_filters())+ .map_err(|e| ToolCallError {+ description: e.to_string(),+ internal_error: anyhow::anyhow!(e),+ })?+ }+ TagMatch::All => sets+ .resolve_filters_unique(self.tag_filters())+ .map_err(|e| ToolCallError {+ description: e.to_string(),+ internal_error: anyhow::anyhow!(e),+ })?,+ };+ // Each resolved option becomes its own literal; the match mode+ // picks how they combine (any = OR, all = AND across the item's+ // tag properties, which may span definitions).+ let combine = match self.tags_match {+ TagMatch::Any => Expr::or,+ TagMatch::All => Expr::and,+ };let expr = resolved.into_iter().map(|option| {@@ -628,7 +656,7 @@ wherevalue: PropertyMatchValue::SelectOption(option.option_id),})})- .reduce(Expr::or);+ .reduce(combine);tag_sets = Some(sets);expr};diff --git a/rust/cloud-storage/soup/src/inbound/toolset/test.rs b/rust/cloud-storage/soup/src/inbound/toolset/test.rsindex 6a53a1f4ce..96f6c6521f 100644--- a/rust/cloud-storage/soup/src/inbound/toolset/test.rs+++ b/rust/cloud-storage/soup/src/inbound/toolset/test.rs@@ -273,12 +273,20 @@ fn test_converts_foreign_entity_soup_item() {}#[test]-fn test_tags_arg_deserializes_and_documents_or_semantics() {+fn test_tags_arg_deserializes_and_documents_match_modes() {let validated = generate_validated_input_schema::<ListEntities>().unwrap();let schema_json = serde_json::to_string(&validated.schema).unwrap();assert!(- schema_json.contains("OR semantics"),- "tags arg should document OR semantics"+ schema_json.contains("any of them by default"),+ "tags arg should document the default any-of combining"+ );+ assert!(+ schema_json.contains("tagsMatch"),+ "tags arg should point at tagsMatch for all-of combining"+ );+ assert!(+ schema_json.contains("is ambiguous"),+ "tagsMatch arg should document the all-mode scope requirement");assert!(schema_json.contains("ListTags"),@@ -300,6 +308,21 @@ fn test_tags_arg_deserializes_and_documents_or_semantics() {tags[1].scope,Some(models_properties::service::tag_sets::TagScope::Team));+ assert_eq!(+ list.tags_match,+ models_properties::service::tag_sets::TagMatch::Any,+ "tagsMatch defaults to any"+ );++ let list: ListEntities = serde_json::from_value(serde_json::json!({+ "tags": [{ "label": "bug-report" }],+ "tagsMatch": "all"+ }))+ .unwrap();+ assert_eq!(+ list.tags_match,+ models_properties::service::tag_sets::TagMatch::All+ );}#[test]