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
fix(search): force exact matching for quoted search terms (#4355)
gbirmanc948d339d007
diff --git a/js/app/packages/app/component/next-soup/soup-view/create-search-state.ts b/js/app/packages/app/component/next-soup/soup-view/create-search-state.tsindex cf77c28e26..5580b866a1 100644--- a/js/app/packages/app/component/next-soup/soup-view/create-search-state.ts+++ b/js/app/packages/app/component/next-soup/soup-view/create-search-state.ts@@ -26,6 +26,18 @@ import type {} from '@service-search/generated/models';import { type Accessor, createMemo, on, type Setter } from 'solid-js';+// A fully-quoted term searches exactly, not as a prefix. Quotes stay in the+// query so the backend tokenizer still groups a quoted phrase.+function isSingleQuotedTerm(query: string): boolean {+ const trimmed = query.trim();+ return (+ trimmed.length >= 2 &&+ trimmed.startsWith('"') &&+ trimmed.endsWith('"') &&+ trimmed.indexOf('"', 1) === trimmed.length - 1+ );+}+// Map the tasks-view property filters (status/priority/assignee/custom) into the// search request shape, mirroring the soup path so search and soup agree. Values// are grouped by property id: multiple values on one property are OR'd (a task@@ -235,6 +247,7 @@ export const createSearchState = ({const state = filters();const query = debouncedSearchForService();const baseFilters = filterDataToQueryFilters(state);+ const matchType = isSingleQuotedTerm(query) ? 'exact' : 'partial';// CRM is opt-in on the backend. A view includes CRM in search unless it// NIL-excludes the CRM target (the same sentinel pattern other entity@@ -245,7 +258,7 @@ export const createSearchState = ({if (!includeCrm) {return {search_on: 'name_content',- match_type: 'partial',+ match_type: matchType,query,filters: baseFilters,};@@ -259,7 +272,7 @@ export const createSearchState = ({// Companies preset.return {search_on: 'name_content',- match_type: 'partial',+ match_type: matchType,query,include_crm: true,filters: {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 78c28b5f85..adda1e7ee5 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@@ -85,6 +85,29 @@ export const ContentSearch = z.object({).default([]),inbox: z.union([z.string(), z.null()]).default(null),+ matchType: z+ .intersection(+ z.any().superRefine((x, ctx) => {+ const schemas = [z.literal('partial'), z.literal('exact')];+ 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',+ });+ }+ }),+ z.any().default('partial')+ )+ .optional(),query: z.string(),});@@ -850,6 +873,29 @@ export const NameSearch = z.object({).default([]),inbox: z.union([z.string(), z.null()]).default(null),+ matchType: z+ .intersection(+ z.any().superRefine((x, ctx) => {+ const schemas = [z.literal('partial'), z.literal('exact')];+ 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',+ });+ }+ }),+ z.any().default('partial')+ )+ .optional(),name: z.string(),});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 42b9c31d85..83b75581b2 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@@ -106,6 +106,12 @@ export type UnifiedSearchIndex =| 'channels'| 'projects'| 'call_records';+/**+ * How search tools match query terms. Restricted to partial/exact — the+ * backend also supports regexp and an internal query mode, but those are not+ * offered to the model.+ */+export type SearchMatchType = 'partial' | 'exact';export type ContentType =| 'channel'| 'channel-message'@@ -847,7 +853,7 @@ export interface Thread {updatedAt?: string | null;}/**- * Search items by their content: document body text; email subject/body/sender/recipient/cc/bcc and the display names on those addresses; chat messages; call transcripts. This is keyword search, not semantic search: queries only match literal words/tokens, prefixes, or exact quoted terms that appear in the indexed content. Use this for targeted keyword/content lookup, not for activity-summary questions like "what happened today", "what's going on", "catch me up", or "what happened in standup today"; those should start with ListEntities using time/type/channel filters. Whitespace-separated terms are ANDed. For documents and emails, every term must match somewhere in the document — different terms can appear in different chunks/pages or different fields. For documents and emails specifically, each single-word term is matched as a prefix (so `scri` matches `script`); for emails the prefix expansion also runs against the local-part of address fields. For chats, channels, and call transcripts the whole query is matched as a single adjacent phrase prefix — so pass 1-3 targeted keywords drawn from words that would literally appear in the content, not the user's natural-language description; long phrases will not match. Wrap a term in double quotes (e.g. `"deal review"` or `"[email protected]"`) to force exact-token / exact-phrase matching instead of prefix. If the user's request combines a person with a topic, run separate searches rather than one combined query. Leave entityTypes empty by default; only filter when the user explicitly scopes to a type.+ * Search items by their content: document body text; email subject/body/sender/recipient/cc/bcc and the display names on those addresses; chat messages; call transcripts. This is keyword search, not semantic search: queries only match literal words/tokens, prefixes, or exact quoted terms that appear in the indexed content. Use this for targeted keyword/content lookup, not for activity-summary questions like "what happened today", "what's going on", "catch me up", or "what happened in standup today"; those should start with ListEntities using time/type/channel filters. Whitespace-separated terms are ANDed. For documents and emails, every term must match somewhere in the document — different terms can appear in different chunks/pages or different fields. For documents and emails specifically, each single-word term is matched as a prefix (so `scri` matches `script`); for emails the prefix expansion also runs against the local-part of address fields. For chats, channels, and call transcripts the whole query is matched as a single adjacent phrase prefix — so pass 1-3 targeted keywords drawn from words that would literally appear in the content, not the user's natural-language description; long phrases will not match. Matching defaults to prefix; set matchType to 'exact' to match whole tokens/phrases with no prefix expansion (e.g. an exact word, identifier, or full email address). Wrap a multi-word phrase in double quotes to keep it together as one adjacent phrase. If the user's request combines a person with a topic, run separate searches rather than one combined query. Leave entityTypes empty by default; only filter when the user explicitly scopes to a type.*/export interface ContentSearch {/**@@ -858,8 +864,9 @@ export interface ContentSearch {* Restrict email results to a single connected inbox, given as that inbox's email address (from ListInboxes). Omit to search every inbox the user can access. Only set this when the user scopes the request to a specific mailbox. Only affects email results.*/inbox?: string | null;+ matchType?: SearchMatchType & string;/**- * The text to search. Pass 1-3 keywords drawn from words that would literally appear in the content, not the user's natural-language description. Whitespace-separated terms are ANDed. For documents, every term must appear somewhere in the document (different chunks/pages are fine). For emails each term is matched across subject/body/sender/recipient. For chats/channels/calls the whole query is matched as a single adjacent phrase prefix, so long phrases will not match. Wrap a term in double quotes to force exact-token (or full-email-address) matching.+ * The text to search. Pass 1-3 keywords drawn from words that would literally appear in the content, not the user's natural-language description. Whitespace-separated terms are ANDed. For documents, every term must appear somewhere in the document (different chunks/pages are fine). For emails each term is matched across subject/body/sender/recipient. For chats/channels/calls the whole query is matched as a single adjacent phrase prefix, so long phrases will not match. Wrap a multi-word phrase in double quotes to match it as one phrase. Use matchType 'exact' for whole-token (or full email address) matching instead of prefix.*/query: string;}@@ -1775,7 +1782,7 @@ export interface MarkNotificationsSeen {notificationIds: string[];}/**- * Search items by their name or title: document name, email subject, chat title, project name, the channel name a call belongs to. This is keyword search, not semantic search: queries only match literal words/tokens, prefixes, or exact quoted terms that appear in the indexed title/name. Use this for targeted name/title lookup, not for activity-summary questions like "what happened today", "what's going on", "catch me up", or "what happened in standup today"; those should start with ListEntities using time/type/channel filters. For emails, whitespace-separated terms are ANDed and each is a prefix match against the subject. For all other types the whole query is matched as a single adjacent phrase prefix — so pass 1-3 targeted keywords drawn from words that would literally appear in the title, not the user's natural-language description; long phrases will not match. Wrap a term in double quotes (e.g. `"deal review"`) to force exact-token matching instead of prefix. If the user's request combines a person with a topic, run separate searches (NameSearch for the person, ContentSearch for the topic) rather than one combined query. Leave entityTypes empty by default; only filter when the user explicitly scopes to a type.+ * Search items by their name or title: document name, email subject, chat title, project name, the channel name a call belongs to. This is keyword search, not semantic search: queries only match literal words/tokens, prefixes, or exact quoted terms that appear in the indexed title/name. Use this for targeted name/title lookup, not for activity-summary questions like "what happened today", "what's going on", "catch me up", or "what happened in standup today"; those should start with ListEntities using time/type/channel filters. For emails, whitespace-separated terms are ANDed and each is a prefix match against the subject. For all other types the whole query is matched as a single adjacent phrase prefix — so pass 1-3 targeted keywords drawn from words that would literally appear in the title, not the user's natural-language description; long phrases will not match. Matching defaults to prefix; set matchType to 'exact' to match whole tokens/phrases with no prefix expansion. Wrap a multi-word phrase in double quotes to keep it together as one adjacent phrase. If the user's request combines a person with a topic, run separate searches (NameSearch for the person, ContentSearch for the topic) rather than one combined query. Leave entityTypes empty by default; only filter when the user explicitly scopes to a type.*/export interface NameSearch {/**@@ -1786,8 +1793,9 @@ export interface NameSearch {* Restrict email results to a single connected inbox, given as that inbox's email address (from ListInboxes). Omit to search every inbox the user can access. Only set this when the user scopes the request to a specific mailbox. Only affects email results.*/inbox?: string | null;+ matchType?: SearchMatchType & string;/**- * The name or title to search. Pass 1-3 keywords drawn from words that would literally appear in the title, not the user's natural-language description. Whitespace-separated terms are ANDed. For non-email types the whole query is matched as a single adjacent phrase prefix, so long phrases will not match. For emails each term is matched against the subject. Wrap a term in double quotes to force exact-token matching.+ * The name or title to search. Pass 1-3 keywords drawn from words that would literally appear in the title, not the user's natural-language description. Whitespace-separated terms are ANDed. For non-email types the whole query is matched as a single adjacent phrase prefix, so long phrases will not match. For emails each term is matched against the subject. Wrap a multi-word phrase in double quotes to match it as one phrase. Use matchType 'exact' for whole-token matching instead of prefix.*/name: string;}diff --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 622cfdd681..9de16b33c2 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,12 @@use super::context::SearchToolContext;-use super::types::{PAGE_SIZE, SearchToolResponse};+use super::types::{PAGE_SIZE, SearchMatchType, SearchToolResponse};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_search::{- MatchType,- unified::{UnifiedSearchIndex, UnifiedSearchRequest, entity_filters_from_include},+use models_search::unified::{+ UnifiedSearchIndex, UnifiedSearchRequest, entity_filters_from_include,};use schemars::JsonSchema;use serde::Deserialize;@@ -15,15 +14,21 @@ use serde::Deserialize;#[derive(Debug, JsonSchema, Deserialize, Clone)]#[serde(rename_all = "camelCase")]#[schemars(- description = "Search items by their content: document body text; email subject/body/sender/recipient/cc/bcc and the display names on those addresses; chat messages; call transcripts. This is keyword search, not semantic search: queries only match literal words/tokens, prefixes, or exact quoted terms that appear in the indexed content. Use this for targeted keyword/content lookup, not for activity-summary questions like \"what happened today\", \"what's going on\", \"catch me up\", or \"what happened in standup today\"; those should start with ListEntities using time/type/channel filters. Whitespace-separated terms are ANDed. For documents and emails, every term must match somewhere in the document — different terms can appear in different chunks/pages or different fields. For documents and emails specifically, each single-word term is matched as a prefix (so `scri` matches `script`); for emails the prefix expansion also runs against the local-part of address fields. For chats, channels, and call transcripts the whole query is matched as a single adjacent phrase prefix — so pass 1-3 targeted keywords drawn from words that would literally appear in the content, not the user's natural-language description; long phrases will not match. Wrap a term in double quotes (e.g. `\"deal review\"` or `\"[email protected]\"`) to force exact-token / exact-phrase matching instead of prefix. If the user's request combines a person with a topic, run separate searches rather than one combined query. Leave entityTypes empty by default; only filter when the user explicitly scopes to a type.",+ description = "Search items by their content: document body text; email subject/body/sender/recipient/cc/bcc and the display names on those addresses; chat messages; call transcripts. This is keyword search, not semantic search: queries only match literal words/tokens, prefixes, or exact quoted terms that appear in the indexed content. Use this for targeted keyword/content lookup, not for activity-summary questions like \"what happened today\", \"what's going on\", \"catch me up\", or \"what happened in standup today\"; those should start with ListEntities using time/type/channel filters. Whitespace-separated terms are ANDed. For documents and emails, every term must match somewhere in the document — different terms can appear in different chunks/pages or different fields. For documents and emails specifically, each single-word term is matched as a prefix (so `scri` matches `script`); for emails the prefix expansion also runs against the local-part of address fields. For chats, channels, and call transcripts the whole query is matched as a single adjacent phrase prefix — so pass 1-3 targeted keywords drawn from words that would literally appear in the content, not the user's natural-language description; long phrases will not match. Matching defaults to prefix; set matchType to 'exact' to match whole tokens/phrases with no prefix expansion (e.g. an exact word, identifier, or full email address). Wrap a multi-word phrase in double quotes to keep it together as one adjacent phrase. If the user's request combines a person with a topic, run separate searches rather than one combined query. Leave entityTypes empty by default; only filter when the user explicitly scopes to a type.",title = "ContentSearch")]pub struct ContentSearch {#[schemars(- description = "The text to search. Pass 1-3 keywords drawn from words that would literally appear in the content, not the user's natural-language description. Whitespace-separated terms are ANDed. For documents, every term must appear somewhere in the document (different chunks/pages are fine). For emails each term is matched across subject/body/sender/recipient. For chats/channels/calls the whole query is matched as a single adjacent phrase prefix, so long phrases will not match. Wrap a term in double quotes to force exact-token (or full-email-address) matching."+ description = "The text to search. Pass 1-3 keywords drawn from words that would literally appear in the content, not the user's natural-language description. Whitespace-separated terms are ANDed. For documents, every term must appear somewhere in the document (different chunks/pages are fine). For emails each term is matched across subject/body/sender/recipient. For chats/channels/calls the whole query is matched as a single adjacent phrase prefix, so long phrases will not match. Wrap a multi-word phrase in double quotes to match it as one phrase. Use matchType 'exact' for whole-token (or full email address) matching instead of prefix.")]pub query: String,+ #[schemars(+ description = "Matching mode. 'partial' (the default) matches each single word as a prefix, so `scri` matches `script`. 'exact' matches each term as a complete token or phrase with no prefix expansion — use it when the user wants an exact word, identifier, code, email address, or quoted phrase rather than a prefix."+ )]+ #[serde(default)]+ pub match_type: SearchMatchType,+#[schemars(description = "Which types of items to search. Leave empty (the default) to search all types — this is almost always what you want. Only set this when the user's request clearly targets one or more specific types. Examples: ['documents'], ['emails', 'documents'], ['channels'], ['call_records'].")]@@ -88,7 +93,7 @@ impl AsyncTool<SearchToolContext> for ContentSearch {};let search_request = UnifiedSearchRequest {query: self.query.to_owned(),- match_type: MatchType::Partial,+ match_type: self.match_type.into(),filters: entity_filters_from_include(self.entity_types.clone(), base_filters),search_on: models_search::SearchOn::Content,include_crm: false,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 657a7a7ba9..cfc1ba66dd 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,12 @@use super::context::SearchToolContext;-use super::types::{PAGE_SIZE, SearchToolResponse};+use super::types::{PAGE_SIZE, SearchMatchType, SearchToolResponse};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_search::{- MatchType,- unified::{UnifiedSearchIndex, UnifiedSearchRequest, entity_filters_from_include},+use models_search::unified::{+ UnifiedSearchIndex, UnifiedSearchRequest, entity_filters_from_include,};use schemars::JsonSchema;use serde::Deserialize;@@ -15,15 +14,21 @@ use serde::Deserialize;#[derive(Debug, JsonSchema, Deserialize, Clone)]#[serde(rename_all = "camelCase")]#[schemars(- description = "Search items by their name or title: document name, email subject, chat title, project name, the channel name a call belongs to. This is keyword search, not semantic search: queries only match literal words/tokens, prefixes, or exact quoted terms that appear in the indexed title/name. Use this for targeted name/title lookup, not for activity-summary questions like \"what happened today\", \"what's going on\", \"catch me up\", or \"what happened in standup today\"; those should start with ListEntities using time/type/channel filters. For emails, whitespace-separated terms are ANDed and each is a prefix match against the subject. For all other types the whole query is matched as a single adjacent phrase prefix — so pass 1-3 targeted keywords drawn from words that would literally appear in the title, not the user's natural-language description; long phrases will not match. Wrap a term in double quotes (e.g. `\"deal review\"`) to force exact-token matching instead of prefix. If the user's request combines a person with a topic, run separate searches (NameSearch for the person, ContentSearch for the topic) rather than one combined query. Leave entityTypes empty by default; only filter when the user explicitly scopes to a type.",+ description = "Search items by their name or title: document name, email subject, chat title, project name, the channel name a call belongs to. This is keyword search, not semantic search: queries only match literal words/tokens, prefixes, or exact quoted terms that appear in the indexed title/name. Use this for targeted name/title lookup, not for activity-summary questions like \"what happened today\", \"what's going on\", \"catch me up\", or \"what happened in standup today\"; those should start with ListEntities using time/type/channel filters. For emails, whitespace-separated terms are ANDed and each is a prefix match against the subject. For all other types the whole query is matched as a single adjacent phrase prefix — so pass 1-3 targeted keywords drawn from words that would literally appear in the title, not the user's natural-language description; long phrases will not match. Matching defaults to prefix; set matchType to 'exact' to match whole tokens/phrases with no prefix expansion. Wrap a multi-word phrase in double quotes to keep it together as one adjacent phrase. If the user's request combines a person with a topic, run separate searches (NameSearch for the person, ContentSearch for the topic) rather than one combined query. Leave entityTypes empty by default; only filter when the user explicitly scopes to a type.",title = "NameSearch")]pub struct NameSearch {#[schemars(- description = "The name or title to search. Pass 1-3 keywords drawn from words that would literally appear in the title, not the user's natural-language description. Whitespace-separated terms are ANDed. For non-email types the whole query is matched as a single adjacent phrase prefix, so long phrases will not match. For emails each term is matched against the subject. Wrap a term in double quotes to force exact-token matching."+ description = "The name or title to search. Pass 1-3 keywords drawn from words that would literally appear in the title, not the user's natural-language description. Whitespace-separated terms are ANDed. For non-email types the whole query is matched as a single adjacent phrase prefix, so long phrases will not match. For emails each term is matched against the subject. Wrap a multi-word phrase in double quotes to match it as one phrase. Use matchType 'exact' for whole-token matching instead of prefix.")]pub name: String,+ #[schemars(+ description = "Matching mode. 'partial' (the default) matches each single word as a prefix, so `scri` matches `script`. 'exact' matches each term as a complete token or phrase with no prefix expansion — use it when the user wants an exact word, identifier, code, email address, or quoted phrase rather than a prefix."+ )]+ #[serde(default)]+ pub match_type: SearchMatchType,+#[schemars(description = "Which types of items to search. Leave empty (the default) to search all types — this is almost always what you want. Only set this when the user's request clearly targets one or more specific types. Examples: ['documents'], ['emails', 'documents'], ['channels'], ['call_records'].")]@@ -88,7 +93,7 @@ impl AsyncTool<SearchToolContext> for NameSearch {};let search_request = UnifiedSearchRequest {query: self.name.to_owned(),- match_type: MatchType::Partial,+ match_type: self.match_type.into(),filters: entity_filters_from_include(self.entity_types.clone(), base_filters),search_on: models_search::SearchOn::Name,include_crm: false,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 828b1699f6..dc89fce7f0 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,9 +1,32 @@+use models_search::MatchType;use models_search::unified::UnifiedSearchResponseItem;use schemars::JsonSchema;use serde::{Deserialize, Serialize};pub const PAGE_SIZE: i64 = 50;+/// How search tools match query terms. Restricted to partial/exact — the+/// backend also supports regexp and an internal query mode, but those are not+/// offered to the model.+#[derive(Serialize, Deserialize, Debug, Clone, Copy, Default, JsonSchema)]+#[serde(rename_all = "snake_case")]+pub enum SearchMatchType {+ /// Prefix matching: a single-word term matches tokens that start with it.+ #[default]+ Partial,+ /// Whole-token / exact-phrase matching, no prefix expansion.+ Exact,+}++impl From<SearchMatchType> for MatchType {+ fn from(value: SearchMatchType) -> Self {+ match value {+ SearchMatchType::Partial => MatchType::Partial,+ SearchMatchType::Exact => MatchType::Exact,+ }+ }+}+#[derive(Serialize, Deserialize, Debug, JsonSchema)]pub struct SearchToolResponse {pub results: Vec<UnifiedSearchResponseItem>,diff --git a/rust/cloud-storage/opensearch_client/src/search/emails.rs b/rust/cloud-storage/opensearch_client/src/search/emails.rsindex 8c4a2d159a..31f2d65bb3 100644--- a/rust/cloud-storage/opensearch_client/src/search/emails.rs+++ b/rust/cloud-storage/opensearch_client/src/search/emails.rs@@ -69,18 +69,21 @@ const MIN_PREFIX_LEN: usize = 3;/// Single-word terms become `term*` so a prefix like `scri` matches the/// token `script` in subject/content/display-name fields. Terms shorter than/// `MIN_PREFIX_LEN` fall back to a grouped exact-token match to keep term-/// expansion bounded. Multi-word terms (quoted phrases from-/// `split_search_terms`) and `@`-containing terms are wrapped in quotes to+/// expansion bounded. In `exact` match mode the prefix wildcard is dropped so+/// every single-word term is an exact-token match. Multi-word terms (quoted+/// phrases from `split_search_terms`) and `@`-containing terms are wrapped in+/// quotes to/// force phrase matching — otherwise `default_operator: "AND"` would turn/// `(reply test)` into `reply AND test` and match each token independently/// anywhere in the field instead of as an adjacent phrase.-fn build_text_query_string(terms: &[String]) -> String {+fn build_text_query_string(terms: &[String], match_type: &str) -> String {+ let exact = match_type == "exact";terms.iter().map(|term| {if term.contains('@') || term.contains(' ') {format!("\"{}\"", term)- } else if term.chars().count() < MIN_PREFIX_LEN {+ } else if exact || term.chars().count() < MIN_PREFIX_LEN {format!("({})", term)} else {format!("{}*", term)@@ -206,7 +209,7 @@ impl EmailQueryBuilder {.default_operator("AND");let text_sqs = SimpleQueryStringQuery::new(- build_text_query_string(&self.inner.terms),+ build_text_query_string(&self.inner.terms, &self.inner.match_type),EMAIL_TEXT_FIELDS.iter().copied(),).default_operator("AND");diff --git a/rust/cloud-storage/opensearch_client/src/search/emails/test.rs b/rust/cloud-storage/opensearch_client/src/search/emails/test.rsindex 078f25a420..0f91d86eaf 100644--- a/rust/cloud-storage/opensearch_client/src/search/emails/test.rs+++ b/rust/cloud-storage/opensearch_client/src/search/emails/test.rs@@ -49,40 +49,46 @@ fn test_build_keyword_query_string_email_term_mixed_with_word() {#[test]fn test_build_text_query_string_single_term_is_prefix() {- let result = build_text_query_string(&["scri".to_string()]);+ let result = build_text_query_string(&["scri".to_string()], "partial");assert_eq!(result, "scri*");}#[test]fn test_build_text_query_string_multiple_terms_are_prefixed_and_anded() {- let result = build_text_query_string(&["scri".to_string(), "test".to_string()]);+ let result = build_text_query_string(&["scri".to_string(), "test".to_string()], "partial");assert_eq!(result, "scri* + test*");}+#[test]+fn test_build_text_query_string_exact_drops_prefix_wildcard() {+ let result = build_text_query_string(&["scri".to_string(), "test".to_string()], "exact");+ assert_eq!(result, "(scri) + (test)");+}+#[test]fn test_build_text_query_string_multi_word_term_uses_phrase() {// Multi-word terms come from quoted phrases via `split_search_terms`// and must render as a phrase so simple_query_string's AND default// operator doesn't decompose them into independent tokens.- let result = build_text_query_string(&["hi there".to_string()]);+ let result = build_text_query_string(&["hi there".to_string()], "partial");assert_eq!(result, "\"hi there\"");}#[test]fn test_build_text_query_string_email_term_uses_phrase() {- let result = build_text_query_string(&["[email protected]".to_string()]);+ let result = build_text_query_string(&["[email protected]".to_string()], "partial");assert_eq!(result, "\"[email protected]\"");}#[test]fn test_build_text_query_string_short_term_skips_prefix() {- let result = build_text_query_string(&["ab".to_string()]);+ let result = build_text_query_string(&["ab".to_string()], "partial");assert_eq!(result, "(ab)");}#[test]fn test_build_text_query_string_three_char_term_gets_prefix() {- let result = build_text_query_string(&["abc".to_string()]);+ let result = build_text_query_string(&["abc".to_string()], "partial");assert_eq!(result, "abc*");}@@ -280,7 +286,7 @@ fn test_build_bool_query() -> anyhow::Result<()> {"simple_query_string": {"default_operator": "AND","fields": ["subject", "content", "sender_name", "recipient_names", "cc_names", "bcc_names"],- "query": "test*"+ "query": "(test)"}}]diff --git a/rust/cloud-storage/opensearch_client/src/search/unified/test.rs b/rust/cloud-storage/opensearch_client/src/search/unified/test.rsindex 97e196e373..7af9e20860 100644--- a/rust/cloud-storage/opensearch_client/src/search/unified/test.rs+++ b/rust/cloud-storage/opensearch_client/src/search/unified/test.rs@@ -678,7 +678,7 @@ fn test_build_unified_search_request_content() -> anyhow::Result<()> {"simple_query_string": {"default_operator": "AND","fields": ["subject", "content", "sender_name", "recipient_names", "cc_names", "bcc_names"],- "query": "test*"+ "query": "(test)"}}]