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(search): add CRM company search to unified search (#3840)
Evan Hutnik34444f8c80f4
diff --git a/js/app/packages/queries/soup/normalized-cache/operations.ts b/js/app/packages/queries/soup/normalized-cache/operations.tsindex 2350380adf..ba7dc5c83d 100644--- a/js/app/packages/queries/soup/normalized-cache/operations.ts+++ b/js/app/packages/queries/soup/normalized-cache/operations.ts@@ -399,6 +399,7 @@ function getSearchResultId(result: UnifiedSearchResponseItem): string {.with({ type: 'email' }, (r) => r.thread_id).with({ type: 'project' }, (r) => r.id).with({ type: 'call' }, (r) => r.call_id)+ .with({ type: 'company' }, (r) => r.id).exhaustive();}diff --git a/js/app/packages/queries/soup/transform-utils.ts b/js/app/packages/queries/soup/transform-utils.tsindex a7f6dacf65..9c72672b4d 100644--- a/js/app/packages/queries/soup/transform-utils.ts+++ b/js/app/packages/queries/soup/transform-utils.ts@@ -273,6 +273,11 @@ export const useSearchResponseItemMapper = () => {searchQuery: string): (WithSearch<EntityData> | undefined)[] => {switch (result.type) {+ // CRM companies are opt-in via `include_crm`, which soup search does+ // not set, so this is never hit at runtime. Handle it as a no-op to+ // keep the union exhaustive; soup doesn't render CRM companies yet.+ case 'company':+ return [];case 'document': {if (!result.metadata || result.metadata.deleted_at) return [];const searchFileType =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 c90a5aeea9..408c8e349f 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@@ -370,6 +370,27 @@ export const SearchToolResponse = z.object({}),z.object({ type: z.literal('call') })),+ z.intersection(+ z.object({+ createdAt: z.string().datetime({ offset: true }),+ description: z.union([z.string(), z.null()]).optional(),+ domains: z.array(+ z.object({+ companyId: z.string().uuid(),+ createdAt: z.string().datetime({ offset: true }),+ domain: z.string(),+ id: z.string().uuid(),+ })+ ),+ hidden: z.boolean(),+ id: z.string().uuid(),+ name: z.union([z.string(), z.null()]).optional(),+ nameHighlighted: z.union([z.string(), z.null()]).optional(),+ teamId: z.string().uuid(),+ updatedAt: z.string().datetime({ offset: true }),+ }),+ z.object({ type: z.literal('company') })+ ),];const errors = schemas.reduce<z.ZodError[]>((errors, schema) =>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 5d711568cd..2b215f2b66 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@@ -218,6 +218,9 @@ export type UnifiedSearchResponseItem =})| (CallRecordSearchResponseItemWithMetadata & {type: 'call';+ })+ | (CrmCompanySearchResponseItem & {+ type: 'company';});/*** Response from the SendEmail tool.@@ -798,6 +801,69 @@ export interface CreateDocumentResponse {*/documentId: string;}+/**+ * A CRM domain attached to a company in search results.+ */+export interface CrmCompanySearchDomain {+ /**+ * The id of the company the domain belongs to.+ */+ companyId: string;+ /**+ * When the domain record was created.+ */+ createdAt: string;+ /**+ * The domain (lowercased, e.g. "acme.com").+ */+ domain: string;+ /**+ * The id of the domain record.+ */+ id: string;+}+/**+ * A CRM company match in unified search results. Carries the display+ * metadata resolved from the primary domain plus the highlighted name.+ */+export interface CrmCompanySearchResponseItem {+ /**+ * When the company was created.+ */+ createdAt: string;+ /**+ * Display description from the primary domain's directory entry.+ */+ description?: string | null;+ /**+ * Domains associated with this company, primary first.+ */+ domains: CrmCompanySearchDomain[];+ /**+ * Whether the company is hidden from CRM listings.+ */+ hidden: boolean;+ /**+ * The id of the company.+ */+ id: string;+ /**+ * Display name from the primary domain's directory entry.+ */+ name?: string | null;+ /**+ * `name` with matched spans wrapped in `<macro_em>…</macro_em>`.+ */+ nameHighlighted?: string | null;+ /**+ * The id of the team that owns this company record.+ */+ teamId: string;+ /**+ * When the company was last updated (the sort key).+ */+ updatedAt: string;+}/*** API-visible content lifecycle and location metadata.*/diff --git a/js/app/packages/service-clients/service-search/generated/models/crmCompanySearchDomain.ts b/js/app/packages/service-clients/service-search/generated/models/crmCompanySearchDomain.tsnew file mode 100644index 0000000000..399a1a92de--- /dev/null+++ b/js/app/packages/service-clients/service-search/generated/models/crmCompanySearchDomain.ts@@ -0,0 +1,20 @@+/**+ * Generated by orval v7.21.0 🍺+ * Do not edit manually.+ * search_service+ * OpenAPI spec version: 0.1.0+ */++/**+ * A CRM domain attached to a company in search results.+ */+export interface CrmCompanySearchDomain {+ /** The id of the company the domain belongs to. */+ companyId: string;+ /** When the domain record was created. */+ createdAt: string;+ /** The domain (lowercased, e.g. "acme.com"). */+ domain: string;+ /** The id of the domain record. */+ id: string;+}diff --git a/js/app/packages/service-clients/service-search/generated/models/crmCompanySearchResponseItem.ts b/js/app/packages/service-clients/service-search/generated/models/crmCompanySearchResponseItem.tsnew file mode 100644index 0000000000..ac080e6358--- /dev/null+++ b/js/app/packages/service-clients/service-search/generated/models/crmCompanySearchResponseItem.ts@@ -0,0 +1,36 @@+/**+ * Generated by orval v7.21.0 🍺+ * Do not edit manually.+ * search_service+ * OpenAPI spec version: 0.1.0+ */++import type { CrmCompanySearchDomain } from './crmCompanySearchDomain';+import type { CrmCompanySearchResponseItemDescription } from './crmCompanySearchResponseItemDescription';+import type { CrmCompanySearchResponseItemName } from './crmCompanySearchResponseItemName';+import type { CrmCompanySearchResponseItemNameHighlighted } from './crmCompanySearchResponseItemNameHighlighted';++/**+ * A CRM company match in unified search results. Carries the display+metadata resolved from the primary domain plus the highlighted name.+ */+export interface CrmCompanySearchResponseItem {+ /** When the company was created. */+ createdAt: string;+ /** Display description from the primary domain's directory entry. */+ description?: CrmCompanySearchResponseItemDescription;+ /** Domains associated with this company, primary first. */+ domains: CrmCompanySearchDomain[];+ /** Whether the company is hidden from CRM listings. */+ hidden: boolean;+ /** The id of the company. */+ id: string;+ /** Display name from the primary domain's directory entry. */+ name?: CrmCompanySearchResponseItemName;+ /** `name` with matched spans wrapped in `<macro_em>…</macro_em>`. */+ nameHighlighted?: CrmCompanySearchResponseItemNameHighlighted;+ /** The id of the team that owns this company record. */+ teamId: string;+ /** When the company was last updated (the sort key). */+ updatedAt: string;+}diff --git a/js/app/packages/service-clients/service-search/generated/models/crmCompanySearchResponseItemDescription.ts b/js/app/packages/service-clients/service-search/generated/models/crmCompanySearchResponseItemDescription.tsnew file mode 100644index 0000000000..1dcd91d16f--- /dev/null+++ b/js/app/packages/service-clients/service-search/generated/models/crmCompanySearchResponseItemDescription.ts@@ -0,0 +1,11 @@+/**+ * Generated by orval v7.21.0 🍺+ * Do not edit manually.+ * search_service+ * OpenAPI spec version: 0.1.0+ */++/**+ * Display description from the primary domain's directory entry.+ */+export type CrmCompanySearchResponseItemDescription = string | null;diff --git a/js/app/packages/service-clients/service-search/generated/models/crmCompanySearchResponseItemName.ts b/js/app/packages/service-clients/service-search/generated/models/crmCompanySearchResponseItemName.tsnew file mode 100644index 0000000000..fc7a783a3d--- /dev/null+++ b/js/app/packages/service-clients/service-search/generated/models/crmCompanySearchResponseItemName.ts@@ -0,0 +1,11 @@+/**+ * Generated by orval v7.21.0 🍺+ * Do not edit manually.+ * search_service+ * OpenAPI spec version: 0.1.0+ */++/**+ * Display name from the primary domain's directory entry.+ */+export type CrmCompanySearchResponseItemName = string | null;diff --git a/js/app/packages/service-clients/service-search/generated/models/crmCompanySearchResponseItemNameHighlighted.ts b/js/app/packages/service-clients/service-search/generated/models/crmCompanySearchResponseItemNameHighlighted.tsnew file mode 100644index 0000000000..08b5b0d950--- /dev/null+++ b/js/app/packages/service-clients/service-search/generated/models/crmCompanySearchResponseItemNameHighlighted.ts@@ -0,0 +1,11 @@+/**+ * Generated by orval v7.21.0 🍺+ * Do not edit manually.+ * search_service+ * OpenAPI spec version: 0.1.0+ */++/**+ * `name` with matched spans wrapped in `<macro_em>…</macro_em>`.+ */+export type CrmCompanySearchResponseItemNameHighlighted = string | null;diff --git a/js/app/packages/service-clients/service-search/generated/models/index.ts b/js/app/packages/service-clients/service-search/generated/models/index.tsindex 4fdaeb2539..81c1f11720 100644--- a/js/app/packages/service-clients/service-search/generated/models/index.ts+++ b/js/app/packages/service-clients/service-search/generated/models/index.ts@@ -73,6 +73,11 @@ export * from './chatSearchResponseItemWithMetadataAllOf';export * from './chatSearchResponseItemWithMetadataAllOfMetadata';export * from './crmCompanyFilters';export * from './crmCompanyFiltersHidden';+export * from './crmCompanySearchDomain';+export * from './crmCompanySearchResponseItem';+export * from './crmCompanySearchResponseItemDescription';+export * from './crmCompanySearchResponseItemName';+export * from './crmCompanySearchResponseItemNameHighlighted';export * from './dataType';export * from './documentFilters';export * from './documentFiltersImportance';@@ -271,6 +276,9 @@ export * from './unifiedSearchResponseItemOneOfAllOfType';export * from './unifiedSearchResponseItemOneOfFour';export * from './unifiedSearchResponseItemOneOfFourAllOf';export * from './unifiedSearchResponseItemOneOfFourAllOfType';+export * from './unifiedSearchResponseItemOneOfOnenine';+export * from './unifiedSearchResponseItemOneOfOnenineAllOf';+export * from './unifiedSearchResponseItemOneOfOnenineAllOfType';export * from './unifiedSearchResponseItemOneOfOnesix';export * from './unifiedSearchResponseItemOneOfOnesixAllOf';export * from './unifiedSearchResponseItemOneOfOnesixAllOfType';diff --git a/js/app/packages/service-clients/service-search/generated/models/unifiedSearchRequest.ts b/js/app/packages/service-clients/service-search/generated/models/unifiedSearchRequest.tsindex 9899a55bc1..599582546f 100644--- a/js/app/packages/service-clients/service-search/generated/models/unifiedSearchRequest.ts+++ b/js/app/packages/service-clients/service-search/generated/models/unifiedSearchRequest.ts@@ -14,6 +14,11 @@ export interface UnifiedSearchRequest {collapse?: UnifiedSearchRequestCollapse;/** Entity filters in the same shape as soup. Entity types with a NIL UUID in their primary ID field are excluded from search. */filters?: EntityFilters;+ /** Opt in to searching the caller's team CRM companies (name/domain).+Off by default: CRM results are only included when this is true and+the caller has a qualifying team membership. CRM has no content+index, so it is searched only under Name / NameContent. */+ include_crm?: boolean;/** How to match the search terms. 'exact' for precise case-sensitive phrase matches, 'partial' for prefix/partial matches. REQUIRED field. */match_type: MatchType;/** The search query string. Must be at least 3 characters. */diff --git a/js/app/packages/service-clients/service-search/generated/models/unifiedSearchResponseItem.ts b/js/app/packages/service-clients/service-search/generated/models/unifiedSearchResponseItem.tsindex 9c7c1c9695..d17f9d3a85 100644--- a/js/app/packages/service-clients/service-search/generated/models/unifiedSearchResponseItem.ts+++ b/js/app/packages/service-clients/service-search/generated/models/unifiedSearchResponseItem.ts@@ -6,6 +6,7 @@*/import type { UnifiedSearchResponseItemOneOf } from './unifiedSearchResponseItemOneOf';import type { UnifiedSearchResponseItemOneOfFour } from './unifiedSearchResponseItemOneOfFour';+import type { UnifiedSearchResponseItemOneOfOnenine } from './unifiedSearchResponseItemOneOfOnenine';import type { UnifiedSearchResponseItemOneOfOnesix } from './unifiedSearchResponseItemOneOfOnesix';import type { UnifiedSearchResponseItemOneOfOnethree } from './unifiedSearchResponseItemOneOfOnethree';import type { UnifiedSearchResponseItemOneOfOnezero } from './unifiedSearchResponseItemOneOfOnezero';@@ -17,4 +18,5 @@ export type UnifiedSearchResponseItem =| UnifiedSearchResponseItemOneOfSeven| UnifiedSearchResponseItemOneOfOnezero| UnifiedSearchResponseItemOneOfOnethree- | UnifiedSearchResponseItemOneOfOnesix;+ | UnifiedSearchResponseItemOneOfOnesix+ | UnifiedSearchResponseItemOneOfOnenine;diff --git a/js/app/packages/service-clients/service-search/generated/models/unifiedSearchResponseItemOneOfOnenine.ts b/js/app/packages/service-clients/service-search/generated/models/unifiedSearchResponseItemOneOfOnenine.tsnew file mode 100644index 0000000000..ba38e65c1b--- /dev/null+++ b/js/app/packages/service-clients/service-search/generated/models/unifiedSearchResponseItemOneOfOnenine.ts@@ -0,0 +1,11 @@+/**+ * Generated by orval v7.21.0 🍺+ * Do not edit manually.+ * search_service+ * OpenAPI spec version: 0.1.0+ */+import type { CrmCompanySearchResponseItem } from './crmCompanySearchResponseItem';+import type { UnifiedSearchResponseItemOneOfOnenineAllOf } from './unifiedSearchResponseItemOneOfOnenineAllOf';++export type UnifiedSearchResponseItemOneOfOnenine =+ CrmCompanySearchResponseItem & UnifiedSearchResponseItemOneOfOnenineAllOf;diff --git a/js/app/packages/service-clients/service-search/generated/models/unifiedSearchResponseItemOneOfOnenineAllOf.ts b/js/app/packages/service-clients/service-search/generated/models/unifiedSearchResponseItemOneOfOnenineAllOf.tsnew file mode 100644index 0000000000..d75f2fa6db--- /dev/null+++ b/js/app/packages/service-clients/service-search/generated/models/unifiedSearchResponseItemOneOfOnenineAllOf.ts@@ -0,0 +1,11 @@+/**+ * Generated by orval v7.21.0 🍺+ * Do not edit manually.+ * search_service+ * OpenAPI spec version: 0.1.0+ */+import type { UnifiedSearchResponseItemOneOfOnenineAllOfType } from './unifiedSearchResponseItemOneOfOnenineAllOfType';++export type UnifiedSearchResponseItemOneOfOnenineAllOf = {+ type: UnifiedSearchResponseItemOneOfOnenineAllOfType;+};diff --git a/js/app/packages/service-clients/service-search/generated/models/unifiedSearchResponseItemOneOfOnenineAllOfType.ts b/js/app/packages/service-clients/service-search/generated/models/unifiedSearchResponseItemOneOfOnenineAllOfType.tsnew file mode 100644index 0000000000..338d2ce383--- /dev/null+++ b/js/app/packages/service-clients/service-search/generated/models/unifiedSearchResponseItemOneOfOnenineAllOfType.ts@@ -0,0 +1,14 @@+/**+ * Generated by orval v7.21.0 🍺+ * Do not edit manually.+ * search_service+ * OpenAPI spec version: 0.1.0+ */++export type UnifiedSearchResponseItemOneOfOnenineAllOfType =+ (typeof UnifiedSearchResponseItemOneOfOnenineAllOfType)[keyof typeof UnifiedSearchResponseItemOneOfOnenineAllOfType];++// eslint-disable-next-line @typescript-eslint/no-redeclare+export const UnifiedSearchResponseItemOneOfOnenineAllOfType = {+ company: 'company',+} as const;diff --git a/js/app/packages/service-clients/service-search/openapi.json b/js/app/packages/service-clients/service-search/openapi.jsonindex 6e10a3a0f4..b5a47f945d 100644--- a/js/app/packages/service-clients/service-search/openapi.json+++ b/js/app/packages/service-clients/service-search/openapi.json@@ -836,6 +836,89 @@}}},+ "CrmCompanySearchDomain": {+ "type": "object",+ "description": "A CRM domain attached to a company in search results.",+ "required": ["id", "companyId", "domain", "createdAt"],+ "properties": {+ "companyId": {+ "type": "string",+ "format": "uuid",+ "description": "The id of the company the domain belongs to."+ },+ "createdAt": {+ "type": "string",+ "format": "date-time",+ "description": "When the domain record was created."+ },+ "domain": {+ "type": "string",+ "description": "The domain (lowercased, e.g. \"acme.com\")."+ },+ "id": {+ "type": "string",+ "format": "uuid",+ "description": "The id of the domain record."+ }+ }+ },+ "CrmCompanySearchResponseItem": {+ "type": "object",+ "description": "A CRM company match in unified search results. Carries the display\nmetadata resolved from the primary domain plus the highlighted name.",+ "required": [+ "id",+ "teamId",+ "hidden",+ "createdAt",+ "updatedAt",+ "domains"+ ],+ "properties": {+ "createdAt": {+ "type": "string",+ "format": "date-time",+ "description": "When the company was created."+ },+ "description": {+ "type": ["string", "null"],+ "description": "Display description from the primary domain's directory entry."+ },+ "domains": {+ "type": "array",+ "items": {+ "$ref": "#/components/schemas/CrmCompanySearchDomain"+ },+ "description": "Domains associated with this company, primary first."+ },+ "hidden": {+ "type": "boolean",+ "description": "Whether the company is hidden from CRM listings."+ },+ "id": {+ "type": "string",+ "format": "uuid",+ "description": "The id of the company."+ },+ "name": {+ "type": ["string", "null"],+ "description": "Display name from the primary domain's directory entry."+ },+ "nameHighlighted": {+ "type": ["string", "null"],+ "description": "`name` with matched spans wrapped in `<macro_em>…</macro_em>`."+ },+ "teamId": {+ "type": "string",+ "format": "uuid",+ "description": "The id of the team that owns this company record."+ },+ "updatedAt": {+ "type": "string",+ "format": "date-time",+ "description": "When the company was last updated (the sort key)."+ }+ }+ },"DataType": {"type": "string","description": "Data type for property values, determining storage and validation.",@@ -3579,6 +3662,10 @@"$ref": "#/components/schemas/EntityFilters","description": "Entity filters in the same shape as soup. Entity types with a NIL UUID in their primary ID field are excluded from search."},+ "include_crm": {+ "type": "boolean",+ "description": "Opt in to searching the caller's team CRM companies (name/domain).\nOff by default: CRM results are only included when this is true and\nthe caller has a qualifying team membership. CRM has no content\nindex, so it is searched only under Name / NameContent."+ },"match_type": {"$ref": "#/components/schemas/MatchType","description": "How to match the search terms. 'exact' for precise case-sensitive phrase matches, 'partial' for prefix/partial matches. REQUIRED field."@@ -3713,6 +3800,23 @@}}]+ },+ {+ "allOf": [+ {+ "$ref": "#/components/schemas/CrmCompanySearchResponseItem"+ },+ {+ "type": "object",+ "required": ["type"],+ "properties": {+ "type": {+ "type": "string",+ "enum": ["company"]+ }+ }+ }+ ]}]}diff --git a/js/app/packages/service-clients/service-storage/generated/schemas/index.ts b/js/app/packages/service-clients/service-storage/generated/schemas/index.tsindex 5dd2585c0b..a304057a04 100644--- a/js/app/packages/service-clients/service-storage/generated/schemas/index.ts+++ b/js/app/packages/service-clients/service-storage/generated/schemas/index.ts@@ -770,6 +770,7 @@ export * from './soupContactSfsPhotoUrl';export * from './soupCrmCompany';export * from './soupCrmCompanyDescription';export * from './soupCrmCompanyName';+export * from './soupCrmCompanyViewedAt';export * from './soupCrmDomain';export * from './soupDocument';export * from './soupDocumentBranchedFromId';diff --git a/js/app/packages/service-clients/service-storage/generated/schemas/soupCrmCompany.ts b/js/app/packages/service-clients/service-storage/generated/schemas/soupCrmCompany.tsindex 3c0821650a..efc1324ff5 100644--- a/js/app/packages/service-clients/service-storage/generated/schemas/soupCrmCompany.ts+++ b/js/app/packages/service-clients/service-storage/generated/schemas/soupCrmCompany.ts@@ -6,6 +6,7 @@*/import type { SoupCrmCompanyDescription } from './soupCrmCompanyDescription';import type { SoupCrmCompanyName } from './soupCrmCompanyName';+import type { SoupCrmCompanyViewedAt } from './soupCrmCompanyViewedAt';import type { SoupCrmDomain } from './soupCrmDomain';/**@@ -35,4 +36,7 @@ these out by default. */teamId: string;/** When the company was last updated. */updatedAt: string;+ /** When the requesting user last viewed this company, or `None` if+never viewed. Mirrors the `viewed_at` other soup entities carry. */+ viewedAt?: SoupCrmCompanyViewedAt;}diff --git a/js/app/packages/service-clients/service-storage/generated/schemas/soupCrmCompanyViewedAt.ts b/js/app/packages/service-clients/service-storage/generated/schemas/soupCrmCompanyViewedAt.tsnew file mode 100644index 0000000000..d41026c190--- /dev/null+++ b/js/app/packages/service-clients/service-storage/generated/schemas/soupCrmCompanyViewedAt.ts@@ -0,0 +1,12 @@+/**+ * Generated by orval v7.21.0 🍺+ * Do not edit manually.+ * document_storage_service+ * OpenAPI spec version: 0.1.0+ */++/**+ * When the requesting user last viewed this company, or `None` if+never viewed. Mirrors the `viewed_at` other soup entities carry.+ */+export type SoupCrmCompanyViewedAt = string | null;diff --git a/js/app/packages/service-clients/service-storage/generated/zod.ts b/js/app/packages/service-clients/service-storage/generated/zod.tsindex d4fbc650c8..da256d765a 100644--- a/js/app/packages/service-clients/service-storage/generated/zod.ts+++ b/js/app/packages/service-clients/service-storage/generated/zod.ts@@ -7250,6 +7250,12 @@ export const getItemsSoupResponse = zod.object({updatedAt: zod.iso.datetime({}).describe('When the company was last updated.'),+ viewedAt: zod.iso+ .datetime({})+ .nullish()+ .describe(+ 'When the requesting user last viewed this company, or `None` if\nnever viewed. Mirrors the `viewed_at` other soup entities carry.'+ ),}).describe('A CRM company as displayed in Soup. Carries the core company\nfields plus display metadata resolved from `crm_domain_directory`\nagainst the primary (earliest-created) domain.'@@ -9097,6 +9103,12 @@ export const postItemsSoupResponse = zod.object({updatedAt: zod.iso.datetime({}).describe('When the company was last updated.'),+ viewedAt: zod.iso+ .datetime({})+ .nullish()+ .describe(+ 'When the requesting user last viewed this company, or `None` if\nnever viewed. Mirrors the `viewed_at` other soup entities carry.'+ ),}).describe('A CRM company as displayed in Soup. Carries the core company\nfields plus display metadata resolved from `crm_domain_directory`\nagainst the primary (earliest-created) domain.'@@ -10537,6 +10549,12 @@ export const postItemsSoupAstResponse = zod.object({updatedAt: zod.iso.datetime({}).describe('When the company was last updated.'),+ viewedAt: zod.iso+ .datetime({})+ .nullish()+ .describe(+ 'When the requesting user last viewed this company, or `None` if\nnever viewed. Mirrors the `viewed_at` other soup entities carry.'+ ),}).describe('A CRM company as displayed in Soup. Carries the core company\nfields plus display metadata resolved from `crm_domain_directory`\nagainst the primary (earliest-created) domain.'diff --git a/js/app/packages/service-clients/service-storage/openapi.json b/js/app/packages/service-clients/service-storage/openapi.jsonindex 4b999f6082..2ae3caf7b6 100644--- a/js/app/packages/service-clients/service-storage/openapi.json+++ b/js/app/packages/service-clients/service-storage/openapi.json@@ -16110,6 +16110,11 @@"type": "string","format": "date-time","description": "When the company was last updated."+ },+ "viewedAt": {+ "type": ["string", "null"],+ "format": "date-time",+ "description": "When the requesting user last viewed this company, or `None` if\nnever viewed. Mirrors the `viewed_at` other soup entities carry."}}},diff --git a/rust/cloud-storage/.sqlx/query-ac1221f53b3482f947f70affe1fa95f778b5cc841f3a08c8d406752da8d25be3.json b/rust/cloud-storage/.sqlx/query-ac1221f53b3482f947f70affe1fa95f778b5cc841f3a08c8d406752da8d25be3.jsonnew file mode 100644index 0000000000..418264801b--- /dev/null+++ b/rust/cloud-storage/.sqlx/query-ac1221f53b3482f947f70affe1fa95f778b5cc841f3a08c8d406752da8d25be3.json@@ -0,0 +1,84 @@+{+ "db_name": "PostgreSQL",+ "query": "\n SELECT\n c.id AS \"company_id!\",\n c.team_id AS \"company_team_id!\",\n c.email_sync AS \"company_email_sync!\",\n c.hidden AS \"company_hidden!\",\n c.first_interaction AS \"company_created_at!\",\n c.last_interaction AS \"company_updated_at!\",\n d.id AS \"domain_id?\",\n d.domain AS \"domain?\",\n d.created_at AS \"domain_created_at?\",\n dd.name AS \"dir_name?\",\n dd.description AS \"dir_description?\"\n FROM crm_companies c\n LEFT JOIN crm_domains d ON d.company_id = c.id\n LEFT JOIN crm_domain_directory dd\n ON LOWER(dd.domain) = LOWER(d.domain)\n WHERE c.team_id = $1\n AND c.id = ANY($2)\n AND ($3 OR c.hidden = FALSE)\n ORDER BY c.last_interaction DESC, c.id DESC, d.created_at ASC NULLS LAST\n ",+ "describe": {+ "columns": [+ {+ "ordinal": 0,+ "name": "company_id!",+ "type_info": "Uuid"+ },+ {+ "ordinal": 1,+ "name": "company_team_id!",+ "type_info": "Uuid"+ },+ {+ "ordinal": 2,+ "name": "company_email_sync!",+ "type_info": "Bool"+ },+ {+ "ordinal": 3,+ "name": "company_hidden!",+ "type_info": "Bool"+ },+ {+ "ordinal": 4,+ "name": "company_created_at!",+ "type_info": "Timestamptz"+ },+ {+ "ordinal": 5,+ "name": "company_updated_at!",+ "type_info": "Timestamptz"+ },+ {+ "ordinal": 6,+ "name": "domain_id?",+ "type_info": "Uuid"+ },+ {+ "ordinal": 7,+ "name": "domain?",+ "type_info": "Text"+ },+ {+ "ordinal": 8,+ "name": "domain_created_at?",+ "type_info": "Timestamptz"+ },+ {+ "ordinal": 9,+ "name": "dir_name?",+ "type_info": "Text"+ },+ {+ "ordinal": 10,+ "name": "dir_description?",+ "type_info": "Text"+ }+ ],+ "parameters": {+ "Left": [+ "Uuid",+ "UuidArray",+ "Bool"+ ]+ },+ "nullable": [+ false,+ false,+ false,+ false,+ false,+ false,+ false,+ false,+ false,+ true,+ true+ ]+ },+ "hash": "ac1221f53b3482f947f70affe1fa95f778b5cc841f3a08c8d406752da8d25be3"+}diff --git a/rust/cloud-storage/.sqlx/query-42a235c2075b26c57bb8da489f7bb3e128b612caacf68635ea29ec275cd14aae.json b/rust/cloud-storage/.sqlx/query-e3cbccf7e62eaa5d655b12fbf32d181f2bb79b25ac3c2300e2eab17c912697af.jsonsimilarity index 79%rename from rust/cloud-storage/.sqlx/query-42a235c2075b26c57bb8da489f7bb3e128b612caacf68635ea29ec275cd14aae.jsonrename to rust/cloud-storage/.sqlx/query-e3cbccf7e62eaa5d655b12fbf32d181f2bb79b25ac3c2300e2eab17c912697af.jsonindex 10fa4557ee..be2165bfbe 100644--- a/rust/cloud-storage/.sqlx/query-42a235c2075b26c57bb8da489f7bb3e128b612caacf68635ea29ec275cd14aae.json+++ b/rust/cloud-storage/.sqlx/query-e3cbccf7e62eaa5d655b12fbf32d181f2bb79b25ac3c2300e2eab17c912697af.json@@ -1,6 +1,6 @@{"db_name": "PostgreSQL",- "query": "\n WITH limited_companies AS (\n SELECT\n c.id,\n c.team_id,\n c.email_sync,\n c.hidden,\n c.first_interaction,\n c.last_interaction\n FROM crm_companies c\n LEFT JOIN \"UserHistory\" uh\n ON uh.\"itemId\" = c.id::text\n AND uh.\"itemType\" = 'crm_company'\n AND uh.\"userId\" = $8\n WHERE c.team_id = $1\n AND c.hidden = COALESCE($5::bool, FALSE)\n AND EXISTS (\n SELECT 1 FROM team_crm_settings tcs\n WHERE tcs.team_id = $1 AND tcs.crm_enabled\n )\n AND (cardinality($2::uuid[]) = 0 OR c.id = ANY($2::uuid[]))\n -- Keyset seek (NULL = first page): keep only rows that\n -- sort strictly after the cursor.\n AND (\n $6::timestamptz IS NULL\n OR (\n CASE $4\n WHEN 'created_at' THEN c.first_interaction\n WHEN 'viewed_at' THEN uh.\"updatedAt\"\n WHEN 'viewed_updated'\n THEN COALESCE(uh.\"updatedAt\", c.last_interaction)\n ELSE c.last_interaction\n END,\n c.id::text\n ) < ($6, $7)\n )\n ORDER BY\n CASE $4\n WHEN 'created_at' THEN c.first_interaction\n WHEN 'viewed_at' THEN uh.\"updatedAt\"\n WHEN 'viewed_updated'\n THEN COALESCE(uh.\"updatedAt\", c.last_interaction)\n ELSE c.last_interaction\n END DESC NULLS LAST,\n c.id DESC\n LIMIT $3\n )\n SELECT\n lc.id AS \"company_id!\",\n lc.team_id AS \"company_team_id!\",\n lc.email_sync AS \"company_email_sync!\",\n lc.hidden AS \"company_hidden!\",\n lc.first_interaction AS \"company_created_at!\",\n lc.last_interaction AS \"company_updated_at!\",\n d.id AS \"domain_id?\",\n d.domain AS \"domain?\",\n d.created_at AS \"domain_created_at?\",\n dd.name AS \"dir_name?\",\n dd.description AS \"dir_description?\"\n FROM limited_companies lc\n LEFT JOIN \"UserHistory\" uh\n ON uh.\"itemId\" = lc.id::text\n AND uh.\"itemType\" = 'crm_company'\n AND uh.\"userId\" = $8\n LEFT JOIN crm_domains d ON d.company_id = lc.id\n LEFT JOIN crm_domain_directory dd\n ON LOWER(dd.domain) = LOWER(d.domain)\n ORDER BY\n CASE $4\n WHEN 'created_at' THEN lc.first_interaction\n WHEN 'viewed_at' THEN uh.\"updatedAt\"\n WHEN 'viewed_updated'\n THEN COALESCE(uh.\"updatedAt\", lc.last_interaction)\n ELSE lc.last_interaction\n END DESC NULLS LAST,\n lc.id DESC,\n d.created_at ASC NULLS LAST\n ",+ "query": "\n WITH limited_companies AS (\n SELECT\n c.id,\n c.team_id,\n c.email_sync,\n c.hidden,\n c.first_interaction,\n c.last_interaction\n FROM crm_companies c\n LEFT JOIN \"UserHistory\" uh\n ON uh.\"itemId\" = c.id::text\n AND uh.\"itemType\" = 'crm_company'\n AND uh.\"userId\" = $8\n WHERE c.team_id = $1\n AND c.hidden = COALESCE($5::bool, FALSE)\n AND EXISTS (\n SELECT 1 FROM team_crm_settings tcs\n WHERE tcs.team_id = $1 AND tcs.crm_enabled\n )\n AND (cardinality($2::uuid[]) = 0 OR c.id = ANY($2::uuid[]))\n -- Keyset seek (NULL = first page): keep only rows that\n -- sort strictly after the cursor.\n AND (\n $6::timestamptz IS NULL\n OR (\n CASE $4\n WHEN 'created_at' THEN c.first_interaction\n WHEN 'viewed_at' THEN uh.\"updatedAt\"\n WHEN 'viewed_updated'\n THEN COALESCE(uh.\"updatedAt\", c.last_interaction)\n ELSE c.last_interaction\n END,\n c.id::text\n ) < ($6, $7)\n )\n ORDER BY\n CASE $4\n WHEN 'created_at' THEN c.first_interaction\n WHEN 'viewed_at' THEN uh.\"updatedAt\"\n WHEN 'viewed_updated'\n THEN COALESCE(uh.\"updatedAt\", c.last_interaction)\n ELSE c.last_interaction\n END DESC NULLS LAST,\n c.id DESC\n LIMIT $3\n )\n SELECT\n lc.id AS \"company_id!\",\n lc.team_id AS \"company_team_id!\",\n lc.email_sync AS \"company_email_sync!\",\n lc.hidden AS \"company_hidden!\",\n lc.first_interaction AS \"company_created_at!\",\n lc.last_interaction AS \"company_updated_at!\",\n d.id AS \"domain_id?\",\n d.domain AS \"domain?\",\n d.created_at AS \"domain_created_at?\",\n dd.name AS \"dir_name?\",\n dd.description AS \"dir_description?\",\n uh.\"updatedAt\"::timestamptz AS \"viewed_at?\"\n FROM limited_companies lc\n LEFT JOIN \"UserHistory\" uh\n ON uh.\"itemId\" = lc.id::text\n AND uh.\"itemType\" = 'crm_company'\n AND uh.\"userId\" = $8\n LEFT JOIN crm_domains d ON d.company_id = lc.id\n LEFT JOIN crm_domain_directory dd\n ON LOWER(dd.domain) = LOWER(d.domain)\n ORDER BY\n CASE $4\n WHEN 'created_at' THEN lc.first_interaction\n WHEN 'viewed_at' THEN uh.\"updatedAt\"\n WHEN 'viewed_updated'\n THEN COALESCE(uh.\"updatedAt\", lc.last_interaction)\n ELSE lc.last_interaction\n END DESC NULLS LAST,\n lc.id DESC,\n d.created_at ASC NULLS LAST\n ","describe": {"columns": [{@@ -57,6 +57,11 @@"ordinal": 10,"name": "dir_description?","type_info": "Text"+ },+ {+ "ordinal": 11,+ "name": "viewed_at?",+ "type_info": "Timestamptz"}],"parameters": {@@ -82,8 +87,9 @@false,false,true,- true+ true,+ null]},- "hash": "42a235c2075b26c57bb8da489f7bb3e128b612caacf68635ea29ec275cd14aae"+ "hash": "e3cbccf7e62eaa5d655b12fbf32d181f2bb79b25ac3c2300e2eab17c912697af"}diff --git a/rust/cloud-storage/.sqlx/query-e63fd5c15b6e5327aecb2524ee304fcd25df705766b08c6fd8d39d10cacfb33e.json b/rust/cloud-storage/.sqlx/query-e63fd5c15b6e5327aecb2524ee304fcd25df705766b08c6fd8d39d10cacfb33e.jsonnew file mode 100644index 0000000000..982ccd411b--- /dev/null+++ b/rust/cloud-storage/.sqlx/query-e63fd5c15b6e5327aecb2524ee304fcd25df705766b08c6fd8d39d10cacfb33e.json@@ -0,0 +1,48 @@+{+ "db_name": "PostgreSQL",+ "query": "\n WITH matched AS (\n SELECT c.id, c.last_interaction AS updated_at\n FROM crm_companies c\n WHERE c.team_id = $1\n AND (\n (c.hidden = FALSE AND ($2::bool IS NULL OR $2 = FALSE))\n OR (c.hidden = TRUE AND $2 = TRUE AND $9)\n )\n AND (cardinality($3::uuid[]) = 0 OR c.id = ANY($3))\n AND EXISTS (\n SELECT 1\n FROM crm_domains d\n LEFT JOIN crm_domain_directory dd\n ON LOWER(dd.domain) = LOWER(d.domain)\n WHERE d.company_id = c.id\n AND (d.domain ILIKE $4 OR dd.name ILIKE $4)\n )\n AND ($7::timestamptz IS NULL OR (c.last_interaction, c.id) < ($7, $8))\n ORDER BY c.last_interaction DESC, c.id DESC\n LIMIT $5\n ),\n primary_domain AS (\n SELECT DISTINCT ON (d.company_id)\n d.company_id,\n COALESCE(dd.name, d.domain) AS display_name\n FROM crm_domains d\n LEFT JOIN crm_domain_directory dd\n ON LOWER(dd.domain) = LOWER(d.domain)\n WHERE d.company_id IN (SELECT id FROM matched)\n ORDER BY d.company_id, d.created_at ASC NULLS LAST\n )\n SELECT\n m.id AS \"id!\",\n COALESCE(pd.display_name, '') AS \"name!\",\n regexp_replace(\n COALESCE(pd.display_name, ''),\n $6, '<macro_em>\\1</macro_em>', 'gi'\n ) AS \"name_highlighted!\",\n m.updated_at AS \"updated_at!\"\n FROM matched m\n LEFT JOIN primary_domain pd ON pd.company_id = m.id\n ORDER BY m.updated_at DESC, m.id DESC\n ",+ "describe": {+ "columns": [+ {+ "ordinal": 0,+ "name": "id!",+ "type_info": "Uuid"+ },+ {+ "ordinal": 1,+ "name": "name!",+ "type_info": "Text"+ },+ {+ "ordinal": 2,+ "name": "name_highlighted!",+ "type_info": "Text"+ },+ {+ "ordinal": 3,+ "name": "updated_at!",+ "type_info": "Timestamptz"+ }+ ],+ "parameters": {+ "Left": [+ "Uuid",+ "Bool",+ "UuidArray",+ "Text",+ "Int8",+ "Text",+ "Timestamptz",+ "Uuid",+ "Bool"+ ]+ },+ "nullable": [+ false,+ null,+ null,+ false+ ]+ },+ "hash": "e63fd5c15b6e5327aecb2524ee304fcd25df705766b08c6fd8d39d10cacfb33e"+}diff --git a/rust/cloud-storage/Cargo.lock b/rust/cloud-storage/Cargo.lockindex 2c3e298a45..8620e18dd0 100644--- a/rust/cloud-storage/Cargo.lock+++ b/rust/cloud-storage/Cargo.lock@@ -10260,8 +10260,10 @@ dependencies = ["chrono","comms","comms_db_client",+ "crm","document_sub_type","email_db_client",+ "entity_access","futures","http-body-util","indexmap 2.14.0",@@ -10294,6 +10296,7 @@ dependencies = ["tower-http","tracing","utoipa",+ "uuid",][[package]]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 4aba5e119d..33364f06ef 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@@ -61,6 +61,7 @@ impl AsyncTool<Arc<SearchServiceClient>> for ContentSearch {match_type: MatchType::Partial,filters: entity_filters_from_include(self.entity_types.clone(), base_filters),search_on: models_search::SearchOn::Content,+ include_crm: false,collapse: Some(true),};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 a5c12d4956..7f9ec1c902 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@@ -61,6 +61,7 @@ impl AsyncTool<Arc<SearchServiceClient>> for NameSearch {match_type: MatchType::Partial,filters: entity_filters_from_include(self.entity_types.clone(), base_filters),search_on: models_search::SearchOn::Name,+ include_crm: false,collapse: Some(true),};diff --git a/rust/cloud-storage/crm/Cargo.toml b/rust/cloud-storage/crm/Cargo.tomlindex a07921c03f..8b0c150b75 100644--- a/rust/cloud-storage/crm/Cargo.toml+++ b/rust/cloud-storage/crm/Cargo.toml@@ -19,6 +19,9 @@ default = ["inbound", "outbound", "ports"]inbound = ["axum", "ports"]outbound = ["dep:reqwest", "dep:sqlx", "dep:unfurl", "ports"]ports = []+# Read-only CRM search (name/domain). Pulls only sqlx + ports — no+# reqwest/unfurl/axum — so search consumers stay lightweight.+search = ["dep:sqlx", "ports"][dependencies]anyhow = { workspace = true }diff --git a/rust/cloud-storage/crm/src/domain.rs b/rust/cloud-storage/crm/src/domain.rsindex aec1f2a614..c6958a93ff 100644--- a/rust/cloud-storage/crm/src/domain.rs+++ b/rust/cloud-storage/crm/src/domain.rs@@ -22,3 +22,10 @@ pub mod service;/// Capability-token receipt wrappers gating per-entity CRM service calls#[cfg(feature = "ports")]pub mod auth;++/// Port + domain types for CRM company search (name/domain)+#[cfg(feature = "search")]+pub mod search_repo;+/// The CRM search service trait and implementation+#[cfg(feature = "search")]+pub mod search_service;diff --git a/rust/cloud-storage/crm/src/domain/model.rs b/rust/cloud-storage/crm/src/domain/model.rsindex 482580fd5d..b669683417 100644--- a/rust/cloud-storage/crm/src/domain/model.rs+++ b/rust/cloud-storage/crm/src/domain/model.rs@@ -15,6 +15,11 @@ pub struct CrmCompanyForSoup {pub name: Option<String>,/// Display description from the primary domain's directory entry.pub description: Option<String>,+ /// When the requesting user last viewed this company+ /// (`UserHistory.updatedAt`), or `None` if never viewed. Drives the+ /// soup `viewed_at` / `viewed_updated` sorts and the recently-viewed+ /// feed. `None` for sources that don't resolve view history (search).+ pub viewed_at: Option<DateTime<Utc>>,}/// A [`CrmCompany`] bundled with its directory display metadatadiff --git a/rust/cloud-storage/crm/src/domain/search_repo.rs b/rust/cloud-storage/crm/src/domain/search_repo.rsnew file mode 100644index 0000000000..9f8ed33c5e--- /dev/null+++ b/rust/cloud-storage/crm/src/domain/search_repo.rs@@ -0,0 +1,71 @@+//! Port + domain types for CRM company search (name / domain).++use chrono::{DateTime, Utc};+use uuid::Uuid;++use crate::domain::model::{CrmCompanyForSoup, CrmError};++/// A single CRM company name/domain match.+#[derive(Debug, Clone)]+pub struct CrmCompanyNameMatch {+ /// The company id.+ pub id: Uuid,+ /// The company's display name.+ pub name: String,+ /// `name` with matched spans wrapped in `<macro_em>…</macro_em>`.+ pub name_highlighted: String,+ /// The company's last-interaction time (its "updated_at"), used as the+ /// sort + keyset-pagination key.+ pub updated_at: DateTime<Utc>,+}++/// Keyset cursor for company-name search. Seeks strictly past the last+/// row of the previous page under the `(updated_at DESC, id DESC)` sort.+/// `None` = first page.+#[derive(Debug, Clone, Copy)]+pub struct CrmCompanySearchCursor {+ /// `updated_at` of the previous page's last row.+ pub last_updated_at: DateTime<Utc>,+ /// Id of the previous page's last row; tiebreaks equal timestamps.+ pub last_id: Uuid,+}++/// Persistence port for CRM company search.+pub trait CrmSearchRepository: Clone + Send + Sync + 'static {+ /// Searches a team's CRM companies by `term` over the company name and+ /// its domains (`crm_domains.domain`), case-insensitive substring+ /// match. `company_ids` restricts to those ids when non-empty;+ /// `hidden` selects the visible (`None`/`Some(false)`) or hidden+ /// (`Some(true)`) set. Hidden rows are returned only when+ /// `include_hidden` is true (admin/owner); a non-admin requesting+ /// `Some(true)` gets no rows. Results are ordered `(updated_at DESC,+ /// id DESC)` and capped at `limit`; pass `cursor` to seek past a+ /// previous page.+ #[allow(clippy::too_many_arguments)]+ fn search_company_names(+ &self,+ team_id: &Uuid,+ term: &str,+ company_ids: &[Uuid],+ hidden: Option<bool>,+ include_hidden: bool,+ limit: i64,+ cursor: Option<CrmCompanySearchCursor>,+ ) -> impl Future<Output = Result<Vec<CrmCompanyNameMatch>, CrmError>> + Send;++ /// Hydrate a set of matched company ids (scoped to `team_id`) into the+ /// full listing shape — directory display name/description from the+ /// primary (earliest-created) domain plus the company's domains. This+ /// is the batch enrich step: same join shape as the single-company+ /// `get_company_for_team`, minus contacts. Companies not owned by the+ /// team are silently dropped, as are hidden companies unless+ /// `include_hidden` is true (admin/owner) — matching+ /// `get_company_for_team`'s gate, so a member can't enrich a hidden id.+ /// Result order is unspecified — callers re-order by the match results.+ fn enrich_companies(+ &self,+ team_id: &Uuid,+ company_ids: &[Uuid],+ include_hidden: bool,+ ) -> impl Future<Output = Result<Vec<CrmCompanyForSoup>, CrmError>> + Send;+}diff --git a/rust/cloud-storage/crm/src/domain/search_service.rs b/rust/cloud-storage/crm/src/domain/search_service.rsnew file mode 100644index 0000000000..c8e02ea108--- /dev/null+++ b/rust/cloud-storage/crm/src/domain/search_service.rs@@ -0,0 +1,121 @@+//! The CrmSearchService trait and its default implementation.++use entity_access::domain::models::{MemberTeamRole, TeamRole};+use uuid::Uuid;++use crate::domain::{+ auth::CrmTeamReceipt,+ model::{CrmCompanyForSoup, CrmError},+ search_repo::{CrmCompanyNameMatch, CrmCompanySearchCursor, CrmSearchRepository},+};++/// Read-only search over CRM records, backed by a [`CrmSearchRepository`].+pub trait CrmSearchService: Clone + Send + Sync + 'static {+ /// Name/domain search over the CRM companies owned by the team in+ /// `access`. The team is derived from the capability-token receipt+ /// (minted from a verified team membership), so authorization is a+ /// compile-time precondition rather than a default-team lookup. See+ /// [`CrmSearchRepository::search_company_names`].+ fn search_company_names(+ &self,+ access: &CrmTeamReceipt<MemberTeamRole>,+ term: &str,+ company_ids: &[Uuid],+ hidden: Option<bool>,+ limit: i64,+ cursor: Option<CrmCompanySearchCursor>,+ ) -> impl Future<Output = Result<Vec<CrmCompanyNameMatch>, CrmError>> + Send;++ /// Hydrate matched company ids into the full listing shape (name ++ /// description + domains), scoped to the team in `access`. The batch+ /// enrich step that follows a name match — see+ /// [`CrmSearchRepository::enrich_companies`].+ fn enrich_companies(+ &self,+ access: &CrmTeamReceipt<MemberTeamRole>,+ company_ids: &[Uuid],+ ) -> impl Future<Output = Result<Vec<CrmCompanyForSoup>, CrmError>> + Send;+}++/// [`CrmSearchService`] backed by a [`CrmSearchRepository`].+#[derive(Debug)]+pub struct CrmSearchServiceImpl<SR>+where+ SR: CrmSearchRepository,+{+ /// The underlying search repository.+ search_repository: SR,+}++impl<SR> Clone for CrmSearchServiceImpl<SR>+where+ SR: CrmSearchRepository,+{+ fn clone(&self) -> Self {+ Self {+ search_repository: self.search_repository.clone(),+ }+ }+}++impl<SR> CrmSearchServiceImpl<SR>+where+ SR: CrmSearchRepository,+{+ /// Creates a new CrmSearchServiceImpl.+ pub fn new(search_repository: SR) -> Self {+ Self { search_repository }+ }+}++impl<SR> CrmSearchService for CrmSearchServiceImpl<SR>+where+ SR: CrmSearchRepository,+{+ #[tracing::instrument(skip(self, access), err)]+ async fn search_company_names(+ &self,+ access: &CrmTeamReceipt<MemberTeamRole>,+ term: &str,+ company_ids: &[Uuid],+ hidden: Option<bool>,+ limit: i64,+ cursor: Option<CrmCompanySearchCursor>,+ ) -> Result<Vec<CrmCompanyNameMatch>, CrmError> {+ let team_id = access.team_id();+ // Members see only visible companies; admins/owners may also reach+ // hidden ones. Derived from the receipt's actual team role, so the+ // service — not the caller — enforces the hidden gate.+ let include_hidden = access+ .receipt()+ .entity_permission()+ .allows_team_role(TeamRole::Admin);+ self.search_repository+ .search_company_names(+ &team_id,+ term,+ company_ids,+ hidden,+ include_hidden,+ limit,+ cursor,+ )+ .await+ }++ #[tracing::instrument(skip(self, access), err)]+ async fn enrich_companies(+ &self,+ access: &CrmTeamReceipt<MemberTeamRole>,+ company_ids: &[Uuid],+ ) -> Result<Vec<CrmCompanyForSoup>, CrmError> {+ let team_id = access.team_id();+ let include_hidden = access+ .receipt()+ .entity_permission()+ .allows_team_role(TeamRole::Admin);+ self.search_repository+ .enrich_companies(&team_id, company_ids, include_hidden)+ .await+ }+}diff --git a/rust/cloud-storage/crm/src/lib.rs b/rust/cloud-storage/crm/src/lib.rsindex 15211fb183..ee7d79f321 100644--- a/rust/cloud-storage/crm/src/lib.rs+++ b/rust/cloud-storage/crm/src/lib.rs@@ -18,5 +18,5 @@ pub mod domain;pub mod inbound;/// The outbound module contains the outbound adapters for CRM-#[cfg(feature = "outbound")]+#[cfg(any(feature = "outbound", feature = "search"))]pub mod outbound;diff --git a/rust/cloud-storage/crm/src/outbound.rs b/rust/cloud-storage/crm/src/outbound.rsindex e327feed04..83bef2a03a 100644--- a/rust/cloud-storage/crm/src/outbound.rs+++ b/rust/cloud-storage/crm/src/outbound.rs@@ -1,8 +1,15 @@/// Apollo.io-backed implementation of the company metadata resolver+#[cfg(feature = "outbound")]pub mod apollo_resolver;/// Postgres implementation of the companies repository+#[cfg(feature = "outbound")]pub mod companies_repo;/// Resolver stub for binaries that don't populate the CRM+#[cfg(feature = "outbound")]pub mod no_op_resolver;+/// Postgres implementation of the CRM search repository+#[cfg(feature = "search")]+pub mod search_repo;/// Unfurl-backed implementation of the company metadata resolver+#[cfg(feature = "outbound")]pub mod unfurl_resolver;diff --git a/rust/cloud-storage/crm/src/outbound/companies_repo.rs b/rust/cloud-storage/crm/src/outbound/companies_repo.rsindex 166fbb7b6f..c05d8a9df4 100644--- a/rust/cloud-storage/crm/src/outbound/companies_repo.rs+++ b/rust/cloud-storage/crm/src/outbound/companies_repo.rs@@ -1145,7 +1145,8 @@ impl CompaniesRepository for CompaniesRepositoryImpl {d.domain AS "domain?",d.created_at AS "domain_created_at?",dd.name AS "dir_name?",- dd.description AS "dir_description?"+ dd.description AS "dir_description?",+ uh."updatedAt"::timestamptz AS "viewed_at?"FROM limited_companies lcLEFT JOIN "UserHistory" uhON uh."itemId" = lc.id::text@@ -1196,6 +1197,7 @@ impl CompaniesRepository for CompaniesRepositoryImpl {},name: row.dir_name,description: row.dir_description,+ viewed_at: row.viewed_at,});}// LEFT JOIN gives an all-NULL domain row for companies withdiff --git a/rust/cloud-storage/crm/src/outbound/search_repo.rs b/rust/cloud-storage/crm/src/outbound/search_repo.rsnew file mode 100644index 0000000000..a03be76268--- /dev/null+++ b/rust/cloud-storage/crm/src/outbound/search_repo.rs@@ -0,0 +1,236 @@+//! Postgres implementation of [`CrmSearchRepository`].++use sqlx::PgPool;+use uuid::Uuid;++use crate::domain::{+ model::{CrmCompany, CrmCompanyForSoup, CrmDomain, CrmError},+ search_repo::{CrmCompanyNameMatch, CrmCompanySearchCursor, CrmSearchRepository},+};++#[cfg(test)]+mod test;++/// PostgreSQL-backed [`CrmSearchRepository`].+#[derive(Clone)]+pub struct CrmSearchRepositoryImpl {+ /// Pool connected to macrodb.+ pool: PgPool,+}++impl CrmSearchRepositoryImpl {+ /// Creates a new CrmSearchRepositoryImpl.+ pub fn new(pool: PgPool) -> Self {+ Self { pool }+ }+}++/// Escapes regex metacharacters so `term` is treated literally inside the+/// highlight `regexp_replace`.+fn escape_regex(term: &str) -> String {+ const SPECIAL: &[char] = &[+ '\\', '.', '+', '*', '?', '(', ')', '[', ']', '{', '}', '^', '$', '|',+ ];+ let mut out = String::with_capacity(term.len() * 2);+ for c in term.chars() {+ if SPECIAL.contains(&c) {+ out.push('\\');+ }+ out.push(c);+ }+ out+}++/// Escapes LIKE wildcards so `term` matches literally. Relies on Postgres's+/// default `\` escape character for ILIKE, so no `ESCAPE` clause is needed.+fn escape_like(term: &str) -> String {+ let mut out = String::with_capacity(term.len() * 2);+ for c in term.chars() {+ if matches!(c, '%' | '_' | '\\') {+ out.push('\\');+ }+ out.push(c);+ }+ out+}++impl CrmSearchRepository for CrmSearchRepositoryImpl {+ #[tracing::instrument(skip(self), err)]+ async fn search_company_names(+ &self,+ team_id: &Uuid,+ term: &str,+ company_ids: &[Uuid],+ hidden: Option<bool>,+ include_hidden: bool,+ limit: i64,+ cursor: Option<CrmCompanySearchCursor>,+ ) -> Result<Vec<CrmCompanyNameMatch>, CrmError> {+ let pattern = format!("%{}%", escape_like(term));+ let highlight = format!("({})", escape_regex(term));+ let cursor_ts = cursor.map(|c| c.last_updated_at);+ let cursor_id = cursor.map(|c| c.last_id);++ // Company names live in `crm_domain_directory` (keyed by domain),+ // not on `crm_companies` — so we match over both the domain string+ // and the directory name, and resolve the display name from the+ // company's primary (earliest-created) domain, mirroring+ // `list_companies_for_soup`. `$2` (hidden) defaults to visible-only+ // when NULL. The keyset guard ($7/$8) seeks past the previous page+ // under the `(updated_at DESC, id DESC)` sort; NULL = first page.+ let rows = sqlx::query!(+ r#"+ WITH matched AS (+ SELECT c.id, c.last_interaction AS updated_at+ FROM crm_companies c+ WHERE c.team_id = $1+ AND (+ (c.hidden = FALSE AND ($2::bool IS NULL OR $2 = FALSE))+ OR (c.hidden = TRUE AND $2 = TRUE AND $9)+ )+ AND (cardinality($3::uuid[]) = 0 OR c.id = ANY($3))+ AND EXISTS (+ SELECT 1+ FROM crm_domains d+ LEFT JOIN crm_domain_directory dd+ ON LOWER(dd.domain) = LOWER(d.domain)+ WHERE d.company_id = c.id+ AND (d.domain ILIKE $4 OR dd.name ILIKE $4)+ )+ AND ($7::timestamptz IS NULL OR (c.last_interaction, c.id) < ($7, $8))+ ORDER BY c.last_interaction DESC, c.id DESC+ LIMIT $5+ ),+ primary_domain AS (+ SELECT DISTINCT ON (d.company_id)+ d.company_id,+ COALESCE(dd.name, d.domain) AS display_name+ FROM crm_domains d+ LEFT JOIN crm_domain_directory dd+ ON LOWER(dd.domain) = LOWER(d.domain)+ WHERE d.company_id IN (SELECT id FROM matched)+ ORDER BY d.company_id, d.created_at ASC NULLS LAST+ )+ SELECT+ m.id AS "id!",+ COALESCE(pd.display_name, '') AS "name!",+ regexp_replace(+ COALESCE(pd.display_name, ''),+ $6, '<macro_em>\1</macro_em>', 'gi'+ ) AS "name_highlighted!",+ m.updated_at AS "updated_at!"+ FROM matched m+ LEFT JOIN primary_domain pd ON pd.company_id = m.id+ ORDER BY m.updated_at DESC, m.id DESC+ "#,+ team_id,+ hidden,+ company_ids,+ pattern,+ limit,+ highlight,+ cursor_ts,+ cursor_id,+ include_hidden,+ )+ .fetch_all(&self.pool)+ .await+ .map_err(|e| CrmError::StorageLayerError(e.into()))?;++ Ok(rows+ .into_iter()+ .map(|r| CrmCompanyNameMatch {+ id: r.id,+ name: r.name,+ name_highlighted: r.name_highlighted,+ updated_at: r.updated_at,+ })+ .collect())+ }++ #[tracing::instrument(skip(self), err)]+ async fn enrich_companies(+ &self,+ team_id: &Uuid,+ company_ids: &[Uuid],+ include_hidden: bool,+ ) -> Result<Vec<CrmCompanyForSoup>, CrmError> {+ // Batch form of `get_company_for_team`'s hydration (minus+ // contacts): one row per (company, domain), domains ordered+ // `created_at ASC` so the first row per company carries the+ // primary domain's directory name/description. `first_interaction`+ // / `last_interaction` fill the CrmCompany created_at / updated_at+ // slots — same convention as the soup listing. The outer+ // `(last_interaction DESC, id DESC)` keeps each company's rows+ // contiguous and gives a deterministic order.+ let rows = sqlx::query!(+ r#"+ SELECT+ c.id AS "company_id!",+ c.team_id AS "company_team_id!",+ c.email_sync AS "company_email_sync!",+ c.hidden AS "company_hidden!",+ c.first_interaction AS "company_created_at!",+ c.last_interaction AS "company_updated_at!",+ d.id AS "domain_id?",+ d.domain AS "domain?",+ d.created_at AS "domain_created_at?",+ dd.name AS "dir_name?",+ dd.description AS "dir_description?"+ FROM crm_companies c+ LEFT JOIN crm_domains d ON d.company_id = c.id+ LEFT JOIN crm_domain_directory dd+ ON LOWER(dd.domain) = LOWER(d.domain)+ WHERE c.team_id = $1+ AND c.id = ANY($2)+ AND ($3 OR c.hidden = FALSE)+ ORDER BY c.last_interaction DESC, c.id DESC, d.created_at ASC NULLS LAST+ "#,+ team_id,+ company_ids,+ include_hidden,+ )+ .fetch_all(&self.pool)+ .await+ .map_err(|e| CrmError::StorageLayerError(e.into()))?;++ // First row per company carries the primary domain's directory+ // metadata; remaining rows only contribute to `domains`.+ let mut result: Vec<CrmCompanyForSoup> = Vec::new();+ for row in rows {+ let cid = row.company_id;+ if result.last().is_none_or(|c| c.company.id != cid) {+ result.push(CrmCompanyForSoup {+ company: CrmCompany {+ id: cid,+ team_id: row.company_team_id,+ email_sync: row.company_email_sync,+ hidden: row.company_hidden,+ created_at: row.company_created_at,+ updated_at: row.company_updated_at,+ domains: Vec::new(),+ },+ name: row.dir_name,+ description: row.dir_description,+ // Search results aren't resolved against per-user view+ // history; the soup listing path supplies viewed_at.+ viewed_at: None,+ });+ }+ // LEFT JOIN yields an all-NULL domain row for companies with+ // zero domains — skip the push then.+ if let (Some(did), Some(domain), Some(created_at)) =+ (row.domain_id, row.domain, row.domain_created_at)+ {+ result.last_mut().unwrap().company.domains.push(CrmDomain {+ id: did,+ company_id: cid,+ domain,+ created_at,+ });+ }+ }++ Ok(result)+ }+}diff --git a/rust/cloud-storage/crm/src/outbound/search_repo/test.rs b/rust/cloud-storage/crm/src/outbound/search_repo/test.rsnew file mode 100644index 0000000000..2d1dcac1ad--- /dev/null+++ b/rust/cloud-storage/crm/src/outbound/search_repo/test.rs@@ -0,0 +1,789 @@+//! Tests for [`super::CrmSearchRepositoryImpl`] — CRM company name/domain+//! search and the batch enrich step, with their team-scoping and+//! hidden-visibility gates.+//!+//! Self-contained seed helpers: the `companies_repo` test helpers are+//! `pub(super)` to that module tree and not reachable here.++use super::{CrmSearchRepositoryImpl, escape_regex};+use crate::domain::search_repo::{CrmCompanySearchCursor, CrmSearchRepository};+use macro_db_migrator::MACRO_DB_MIGRATIONS;+use sqlx::PgPool;+use uuid::Uuid;++// --------------------------------------------------------------------------+// Seed helpers+// --------------------------------------------------------------------------++async fn seed_team(pool: &PgPool, team_id: Uuid, owner_id: &str) -> sqlx::Result<()> {+ let macro_user_id = Uuid::now_v7();+ sqlx::query(+ r#"INSERT INTO macro_user (id, username, email, stripe_customer_id) VALUES ($1, $2, $3, $4)"#,+ )+ .bind(macro_user_id)+ .bind(owner_id)+ .bind(owner_id)+ .bind(format!("stripe_{macro_user_id}"))+ .execute(pool)+ .await?;++ sqlx::query(r#"INSERT INTO "User" (id, email, macro_user_id) VALUES ($1, $2, $3)"#)+ .bind(owner_id)+ .bind(owner_id)+ .bind(macro_user_id)+ .execute(pool)+ .await?;++ sqlx::query(r#"INSERT INTO team (id, name, owner_id) VALUES ($1, $2, $3)"#)+ .bind(team_id)+ .bind("test team")+ .bind(owner_id)+ .execute(pool)+ .await?;++ Ok(())+}++/// Inserts a company with its domains. Each domain is a separate statement+/// (separate transaction) so `created_at` strictly increases in array order+/// — the first domain is the "primary" the directory join resolves against.+async fn insert_company(pool: &PgPool, team_id: Uuid, domains: &[&str]) -> sqlx::Result<Uuid> {+ let company_id = Uuid::now_v7();+ sqlx::query(+ r#"INSERT INTO crm_companies (id, team_id, email_sync, first_interaction, last_interaction)+ VALUES ($1, $2, TRUE, now(), now())"#,+ )+ .bind(company_id)+ .bind(team_id)+ .execute(pool)+ .await?;++ for domain in domains {+ sqlx::query(r#"INSERT INTO crm_domains (company_id, team_id, domain) VALUES ($1, $2, $3)"#)+ .bind(company_id)+ .bind(team_id)+ .bind(*domain)+ .execute(pool)+ .await?;+ }+ Ok(company_id)+}++async fn set_hidden(pool: &PgPool, company_id: Uuid) -> sqlx::Result<()> {+ sqlx::query(r#"UPDATE crm_companies SET hidden = TRUE WHERE id = $1"#)+ .bind(company_id)+ .execute(pool)+ .await?;+ Ok(())+}++async fn set_interaction(+ pool: &PgPool,+ company_id: Uuid,+ ts: chrono::DateTime<chrono::Utc>,+) -> sqlx::Result<()> {+ sqlx::query(+ r#"UPDATE crm_companies SET first_interaction = $2, last_interaction = $2 WHERE id = $1"#,+ )+ .bind(company_id)+ .bind(ts)+ .execute(pool)+ .await?;+ Ok(())+}++async fn insert_directory(+ pool: &PgPool,+ domain: &str,+ name: Option<&str>,+ description: Option<&str>,+) -> sqlx::Result<()> {+ sqlx::query(+ r#"INSERT INTO crm_domain_directory (domain, name, description) VALUES ($1, $2, $3)"#,+ )+ .bind(domain)+ .bind(name)+ .bind(description)+ .execute(pool)+ .await?;+ Ok(())+}++fn ts(s: &str) -> chrono::DateTime<chrono::Utc> {+ s.parse().expect("valid timestamp")+}++// --------------------------------------------------------------------------+// escape_regex (pure, no DB)+// --------------------------------------------------------------------------++#[test]+fn escape_regex_escapes_metacharacters() {+ assert_eq!(escape_regex("c++"), r"c\+\+");+ assert_eq!(escape_regex("a.b*c"), r"a\.b\*c");+ assert_eq!(escape_regex("(x)[y]{z}"), r"\(x\)\[y\]\{z\}");+ assert_eq!(escape_regex(r"back\slash"), r"back\\slash");+ // Ordinary text is untouched.+ assert_eq!(escape_regex("acme"), "acme");+}++// --------------------------------------------------------------------------+// search_company_names — matching+// --------------------------------------------------------------------------++#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]+async fn search_matches_by_directory_name(pool: PgPool) -> anyhow::Result<()> {+ let team = Uuid::now_v7();+ seed_team(&pool, team, "macro|[email protected]").await?;+ let acme = insert_company(&pool, team, &["acme.com"]).await?;+ insert_directory(&pool, "acme.com", Some("Acme Inc."), None).await?;++ let repo = CrmSearchRepositoryImpl::new(pool);+ let results = repo+ .search_company_names(&team, "acme", &[], None, false, 100, None)+ .await?;++ assert_eq!(results.len(), 1);+ assert_eq!(results[0].id, acme);+ assert_eq!(results[0].name, "Acme Inc.");+ Ok(())+}++#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]+async fn search_matches_by_domain_when_no_directory(pool: PgPool) -> anyhow::Result<()> {+ let team = Uuid::now_v7();+ seed_team(&pool, team, "macro|[email protected]").await?;+ let acme = insert_company(&pool, team, &["acme.com"]).await?;++ let repo = CrmSearchRepositoryImpl::new(pool);+ let results = repo+ .search_company_names(&team, "acme", &[], None, false, 100, None)+ .await?;++ assert_eq!(results.len(), 1);+ assert_eq!(results[0].id, acme);+ // No directory row — display name falls back to the domain.+ assert_eq!(results[0].name, "acme.com");+ Ok(())+}++#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]+async fn search_is_case_insensitive(pool: PgPool) -> anyhow::Result<()> {+ let team = Uuid::now_v7();+ seed_team(&pool, team, "macro|[email protected]").await?;+ insert_company(&pool, team, &["acme.com"]).await?;++ let repo = CrmSearchRepositoryImpl::new(pool);+ let results = repo+ .search_company_names(&team, "ACME", &[], None, false, 100, None)+ .await?;+ assert_eq!(results.len(), 1);+ Ok(())+}++#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]+async fn search_matches_substring(pool: PgPool) -> anyhow::Result<()> {+ let team = Uuid::now_v7();+ seed_team(&pool, team, "macro|[email protected]").await?;+ insert_company(&pool, team, &["acme.com"]).await?;++ let repo = CrmSearchRepositoryImpl::new(pool);+ let results = repo+ .search_company_names(&team, "cme", &[], None, false, 100, None)+ .await?;+ assert_eq!(results.len(), 1);+ Ok(())+}++#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]+async fn search_no_match_returns_empty(pool: PgPool) -> anyhow::Result<()> {+ let team = Uuid::now_v7();+ seed_team(&pool, team, "macro|[email protected]").await?;+ insert_company(&pool, team, &["acme.com"]).await?;++ let repo = CrmSearchRepositoryImpl::new(pool);+ let results = repo+ .search_company_names(&team, "zzz", &[], None, false, 100, None)+ .await?;+ assert!(results.is_empty());+ Ok(())+}++#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]+async fn search_matches_secondary_domain_but_names_from_primary(+ pool: PgPool,+) -> anyhow::Result<()> {+ let team = Uuid::now_v7();+ seed_team(&pool, team, "macro|[email protected]").await?;+ // Primary acme.com (with directory), secondary globex.net (the match).+ let id = insert_company(&pool, team, &["acme.com", "globex.net"]).await?;+ insert_directory(&pool, "acme.com", Some("Acme Inc."), None).await?;++ let repo = CrmSearchRepositoryImpl::new(pool);+ let results = repo+ .search_company_names(&team, "globex", &[], None, false, 100, None)+ .await?;++ assert_eq!(results.len(), 1);+ assert_eq!(results[0].id, id);+ // Matched via the secondary domain, but the display name resolves from+ // the primary (earliest-created) domain's directory entry.+ assert_eq!(results[0].name, "Acme Inc.");+ Ok(())+}++#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]+async fn search_company_with_no_domains_never_matches(pool: PgPool) -> anyhow::Result<()> {+ let team = Uuid::now_v7();+ seed_team(&pool, team, "macro|[email protected]").await?;+ // Company with zero domains — the EXISTS(domains) guard excludes it.+ insert_company(&pool, team, &[]).await?;++ let repo = CrmSearchRepositoryImpl::new(pool);+ let results = repo+ .search_company_names(&team, "anything", &[], None, false, 100, None)+ .await?;+ assert!(results.is_empty());+ Ok(())+}++// --------------------------------------------------------------------------+// search_company_names — highlighting+// --------------------------------------------------------------------------++#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]+async fn search_highlights_matched_span(pool: PgPool) -> anyhow::Result<()> {+ let team = Uuid::now_v7();+ seed_team(&pool, team, "macro|[email protected]").await?;+ insert_company(&pool, team, &["acme.com"]).await?;+ insert_directory(&pool, "acme.com", Some("Acme Inc."), None).await?;++ let repo = CrmSearchRepositoryImpl::new(pool);+ let results = repo+ .search_company_names(&team, "acme", &[], None, false, 100, None)+ .await?;++ assert_eq!(results.len(), 1);+ // Case-insensitive match, original case preserved in the wrapped span.+ assert_eq!(+ results[0].name_highlighted,+ "<macro_em>Acme</macro_em> Inc."+ );+ Ok(())+}++#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]+async fn search_escapes_regex_metacharacters_in_highlight(pool: PgPool) -> anyhow::Result<()> {+ let team = Uuid::now_v7();+ seed_team(&pool, team, "macro|[email protected]").await?;+ insert_company(&pool, team, &["cpp.com"]).await?;+ insert_directory(&pool, "cpp.com", Some("C++ Corp"), None).await?;++ let repo = CrmSearchRepositoryImpl::new(pool);+ let results = repo+ .search_company_names(&team, "c++", &[], None, false, 100, None)+ .await?;++ assert_eq!(+ results.len(),+ 1,+ "literal '++' must match, not blow up the regex"+ );+ assert_eq!(results[0].name_highlighted, "<macro_em>C++</macro_em> Corp");+ Ok(())+}++// --------------------------------------------------------------------------+// search_company_names — hidden visibility gate+// --------------------------------------------------------------------------++/// Seeds one visible + one hidden company, both matching the term "corp".+async fn seed_visible_and_hidden(pool: &PgPool, team: Uuid) -> sqlx::Result<(Uuid, Uuid)> {+ let visible = insert_company(pool, team, &["acme.com"]).await?;+ insert_directory(pool, "acme.com", Some("Acme Corp"), None).await?;+ let hidden = insert_company(pool, team, &["globex.com"]).await?;+ insert_directory(pool, "globex.com", Some("Globex Corp"), None).await?;+ set_hidden(pool, hidden).await?;+ Ok((visible, hidden))+}++#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]+async fn search_excludes_hidden_with_hidden_none(pool: PgPool) -> anyhow::Result<()> {+ let team = Uuid::now_v7();+ seed_team(&pool, team, "macro|[email protected]").await?;+ let (visible, _hidden) = seed_visible_and_hidden(&pool, team).await?;++ let repo = CrmSearchRepositoryImpl::new(pool);+ let results = repo+ .search_company_names(&team, "corp", &[], None, false, 100, None)+ .await?;+ let ids: Vec<Uuid> = results.iter().map(|m| m.id).collect();+ assert_eq!(ids, vec![visible]);+ Ok(())+}++#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]+async fn search_visible_explicit_false_same_as_none(pool: PgPool) -> anyhow::Result<()> {+ let team = Uuid::now_v7();+ seed_team(&pool, team, "macro|[email protected]").await?;+ let (visible, _hidden) = seed_visible_and_hidden(&pool, team).await?;++ let repo = CrmSearchRepositoryImpl::new(pool);+ let results = repo+ .search_company_names(&team, "corp", &[], Some(false), false, 100, None)+ .await?;+ let ids: Vec<Uuid> = results.iter().map(|m| m.id).collect();+ assert_eq!(ids, vec![visible]);+ Ok(())+}++#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]+async fn search_hidden_only_for_admin(pool: PgPool) -> anyhow::Result<()> {+ let team = Uuid::now_v7();+ seed_team(&pool, team, "macro|[email protected]").await?;+ let (_visible, hidden) = seed_visible_and_hidden(&pool, team).await?;++ let repo = CrmSearchRepositoryImpl::new(pool);+ // hidden=Some(true) + include_hidden (admin) → hidden rows only.+ let results = repo+ .search_company_names(&team, "corp", &[], Some(true), true, 100, None)+ .await?;+ let ids: Vec<Uuid> = results.iter().map(|m| m.id).collect();+ assert_eq!(ids, vec![hidden]);+ Ok(())+}++#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]+async fn search_hidden_requested_by_member_returns_empty(pool: PgPool) -> anyhow::Result<()> {+ let team = Uuid::now_v7();+ seed_team(&pool, team, "macro|[email protected]").await?;+ let (_visible, _hidden) = seed_visible_and_hidden(&pool, team).await?;++ let repo = CrmSearchRepositoryImpl::new(pool);+ // hidden=Some(true) but NOT include_hidden (member) → no hidden rows leak.+ let results = repo+ .search_company_names(&team, "corp", &[], Some(true), false, 100, None)+ .await?;+ assert!(+ results.is_empty(),+ "a member must not be able to search the hidden set"+ );+ Ok(())+}++#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]+async fn search_active_tab_ignores_capability(pool: PgPool) -> anyhow::Result<()> {+ let team = Uuid::now_v7();+ seed_team(&pool, team, "macro|[email protected]").await?;+ let (visible, _hidden) = seed_visible_and_hidden(&pool, team).await?;++ let repo = CrmSearchRepositoryImpl::new(pool);+ // hidden=None even with the capability → still visible only.+ let results = repo+ .search_company_names(&team, "corp", &[], None, true, 100, None)+ .await?;+ let ids: Vec<Uuid> = results.iter().map(|m| m.id).collect();+ assert_eq!(ids, vec![visible]);+ Ok(())+}++// --------------------------------------------------------------------------+// search_company_names — scoping+// --------------------------------------------------------------------------++#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]+async fn search_scopes_to_team(pool: PgPool) -> anyhow::Result<()> {+ let team_a = Uuid::now_v7();+ let team_b = Uuid::now_v7();+ seed_team(&pool, team_a, "macro|[email protected]").await?;+ seed_team(&pool, team_b, "macro|[email protected]").await?;+ let a = insert_company(&pool, team_a, &["acme.com"]).await?;+ let _b = insert_company(&pool, team_b, &["acme.com"]).await?;++ let repo = CrmSearchRepositoryImpl::new(pool);+ let results = repo+ .search_company_names(&team_a, "acme", &[], None, false, 100, None)+ .await?;+ let ids: Vec<Uuid> = results.iter().map(|m| m.id).collect();+ assert_eq!(+ ids,+ vec![a],+ "must not leak the other team's identically-named company"+ );+ Ok(())+}++#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]+async fn search_filters_by_company_ids_when_non_empty(pool: PgPool) -> anyhow::Result<()> {+ let team = Uuid::now_v7();+ seed_team(&pool, team, "macro|[email protected]").await?;+ let wanted = insert_company(&pool, team, &["acme-one.com"]).await?;+ let _other = insert_company(&pool, team, &["acme-two.com"]).await?;++ let repo = CrmSearchRepositoryImpl::new(pool);+ let results = repo+ .search_company_names(&team, "acme", &[wanted], None, false, 100, None)+ .await?;+ let ids: Vec<Uuid> = results.iter().map(|m| m.id).collect();+ assert_eq!(ids, vec![wanted]);+ Ok(())+}++// --------------------------------------------------------------------------+// search_company_names — ordering, limit, pagination+// --------------------------------------------------------------------------++#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]+async fn search_orders_by_interaction_desc(pool: PgPool) -> anyhow::Result<()> {+ let team = Uuid::now_v7();+ seed_team(&pool, team, "macro|[email protected]").await?;+ let older = insert_company(&pool, team, &["acme1.com"]).await?;+ let newer = insert_company(&pool, team, &["acme2.com"]).await?;+ let newest = insert_company(&pool, team, &["acme3.com"]).await?;+ set_interaction(&pool, older, ts("2024-01-01T00:00:00Z")).await?;+ set_interaction(&pool, newer, ts("2024-01-02T00:00:00Z")).await?;+ set_interaction(&pool, newest, ts("2024-01-03T00:00:00Z")).await?;++ let repo = CrmSearchRepositoryImpl::new(pool);+ let results = repo+ .search_company_names(&team, "acme", &[], None, false, 100, None)+ .await?;+ let ids: Vec<Uuid> = results.iter().map(|m| m.id).collect();+ assert_eq!(ids, vec![newest, newer, older]);+ Ok(())+}++#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]+async fn search_respects_limit(pool: PgPool) -> anyhow::Result<()> {+ let team = Uuid::now_v7();+ seed_team(&pool, team, "macro|[email protected]").await?;+ let a = insert_company(&pool, team, &["acme1.com"]).await?;+ let b = insert_company(&pool, team, &["acme2.com"]).await?;+ let c = insert_company(&pool, team, &["acme3.com"]).await?;+ set_interaction(&pool, a, ts("2024-01-01T00:00:00Z")).await?;+ set_interaction(&pool, b, ts("2024-01-02T00:00:00Z")).await?;+ set_interaction(&pool, c, ts("2024-01-03T00:00:00Z")).await?;++ let repo = CrmSearchRepositoryImpl::new(pool);+ let results = repo+ .search_company_names(&team, "acme", &[], None, false, 2, None)+ .await?;+ let ids: Vec<Uuid> = results.iter().map(|m| m.id).collect();+ assert_eq!(ids, vec![c, b], "limit caps to the two newest");+ Ok(())+}++#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]+async fn search_paginates_past_cursor(pool: PgPool) -> anyhow::Result<()> {+ let team = Uuid::now_v7();+ seed_team(&pool, team, "macro|[email protected]").await?;++ let mut companies = Vec::new();+ for day in 1..=5 {+ let domain = format!("acme{day}.com");+ let id = insert_company(&pool, team, &[domain.as_str()]).await?;+ set_interaction(&pool, id, ts(&format!("2024-01-0{day}T00:00:00Z"))).await?;+ companies.push(id);+ }+ let expected: Vec<Uuid> = companies.iter().rev().copied().collect();++ let repo = CrmSearchRepositoryImpl::new(pool);+ let mut seen: Vec<Uuid> = Vec::new();+ let mut cursor: Option<CrmCompanySearchCursor> = None;+ let mut first_page: Vec<Uuid> = Vec::new();+ for page_idx in 0..10 {+ let page = repo+ .search_company_names(&team, "acme", &[], None, false, 2, cursor)+ .await?;+ if page.is_empty() {+ break;+ }+ let page_ids: Vec<Uuid> = page.iter().map(|m| m.id).collect();+ if page_idx == 0 {+ first_page = page_ids.clone();+ } else {+ assert_ne!(+ page_ids, first_page,+ "cursor did not advance — page {page_idx} repeated the first page"+ );+ }+ let last = page.last().unwrap();+ cursor = Some(CrmCompanySearchCursor {+ last_updated_at: last.updated_at,+ last_id: last.id,+ });+ let exhausted = page.len() < 2;+ seen.extend(page_ids);+ if exhausted {+ break;+ }+ }++ assert_eq!(+ seen, expected,+ "pagination must yield every match exactly once in descending interaction order"+ );+ Ok(())+}++#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]+async fn search_pagination_breaks_ties_on_id(pool: PgPool) -> anyhow::Result<()> {+ let team = Uuid::now_v7();+ seed_team(&pool, team, "macro|[email protected]").await?;++ let newest = ts("2024-01-05T00:00:00Z");+ let tie = ts("2024-01-04T00:00:00Z");+ let mid = ts("2024-01-03T00:00:00Z");+ let oldest = ts("2024-01-02T00:00:00Z");++ let mut want: Vec<(chrono::DateTime<chrono::Utc>, Uuid)> = Vec::new();+ for (idx, t) in [newest, tie, tie, mid, oldest].into_iter().enumerate() {+ let domain = format!("acme{idx}.com");+ let id = insert_company(&pool, team, &[domain.as_str()]).await?;+ set_interaction(&pool, id, t).await?;+ want.push((t, id));+ }+ want.sort_by(|a, b| b.0.cmp(&a.0).then(b.1.cmp(&a.1)));+ let expected: Vec<Uuid> = want.iter().map(|(_, id)| *id).collect();++ let repo = CrmSearchRepositoryImpl::new(pool);+ let mut seen: Vec<Uuid> = Vec::new();+ let mut cursor: Option<CrmCompanySearchCursor> = None;+ for _ in 0..10 {+ let page = repo+ .search_company_names(&team, "acme", &[], None, false, 2, cursor)+ .await?;+ if page.is_empty() {+ break;+ }+ let last = page.last().unwrap();+ cursor = Some(CrmCompanySearchCursor {+ last_updated_at: last.updated_at,+ last_id: last.id,+ });+ let exhausted = page.len() < 2;+ seen.extend(page.iter().map(|m| m.id));+ if exhausted {+ break;+ }+ }++ assert_eq!(+ seen, expected,+ "tied timestamps must paginate by id without skipping or repeating"+ );+ Ok(())+}++// --------------------------------------------------------------------------+// enrich_companies — hydration+// --------------------------------------------------------------------------++#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]+async fn enrich_hydrates_name_description_and_domains(pool: PgPool) -> anyhow::Result<()> {+ let team = Uuid::now_v7();+ seed_team(&pool, team, "macro|[email protected]").await?;+ let id = insert_company(&pool, team, &["acme.com", "acmecorp.com"]).await?;+ insert_directory(&pool, "acme.com", Some("Acme Inc."), Some("Rocket skates.")).await?;++ let repo = CrmSearchRepositoryImpl::new(pool);+ let results = repo.enrich_companies(&team, &[id], false).await?;++ assert_eq!(results.len(), 1);+ assert_eq!(results[0].company.id, id);+ assert_eq!(results[0].name.as_deref(), Some("Acme Inc."));+ assert_eq!(results[0].description.as_deref(), Some("Rocket skates."));+ assert_eq!(results[0].company.domains.len(), 2);+ assert_eq!(results[0].company.domains[0].domain, "acme.com");+ Ok(())+}++#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]+async fn enrich_uses_primary_domain_for_directory(pool: PgPool) -> anyhow::Result<()> {+ let team = Uuid::now_v7();+ seed_team(&pool, team, "macro|[email protected]").await?;+ // Directory only on the SECONDARY domain — must not be picked.+ let id = insert_company(&pool, team, &["acme.com", "globex.net"]).await?;+ insert_directory(&pool, "globex.net", Some("Globex"), Some("nope")).await?;++ let repo = CrmSearchRepositoryImpl::new(pool);+ let results = repo.enrich_companies(&team, &[id], false).await?;++ assert_eq!(results.len(), 1);+ assert_eq!(+ results[0].name, None,+ "name must come from the primary domain only"+ );+ assert_eq!(results[0].description, None);+ assert_eq!(results[0].company.domains.len(), 2);+ Ok(())+}++#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]+async fn enrich_negative_cache_directory_yields_none(pool: PgPool) -> anyhow::Result<()> {+ let team = Uuid::now_v7();+ seed_team(&pool, team, "macro|[email protected]").await?;+ let id = insert_company(&pool, team, &["acme.com"]).await?;+ insert_directory(&pool, "acme.com", None, None).await?;++ let repo = CrmSearchRepositoryImpl::new(pool);+ let results = repo.enrich_companies(&team, &[id], false).await?;++ assert_eq!(results.len(), 1);+ assert_eq!(results[0].name, None);+ assert_eq!(results[0].description, None);+ Ok(())+}++#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]+async fn enrich_no_directory_yields_none_but_hydrates_domains(pool: PgPool) -> anyhow::Result<()> {+ let team = Uuid::now_v7();+ seed_team(&pool, team, "macro|[email protected]").await?;+ let id = insert_company(&pool, team, &["acme.com"]).await?;++ let repo = CrmSearchRepositoryImpl::new(pool);+ let results = repo.enrich_companies(&team, &[id], false).await?;++ assert_eq!(results.len(), 1);+ assert_eq!(results[0].name, None);+ assert_eq!(results[0].company.domains.len(), 1);+ assert_eq!(results[0].company.domains[0].domain, "acme.com");+ Ok(())+}++#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]+async fn enrich_company_with_no_domains(pool: PgPool) -> anyhow::Result<()> {+ let team = Uuid::now_v7();+ seed_team(&pool, team, "macro|[email protected]").await?;+ let id = insert_company(&pool, team, &[]).await?;++ let repo = CrmSearchRepositoryImpl::new(pool);+ let results = repo.enrich_companies(&team, &[id], false).await?;++ assert_eq!(results.len(), 1, "a domainless company is still returned");+ assert!(results[0].company.domains.is_empty());+ assert_eq!(results[0].name, None);+ Ok(())+}++#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]+async fn enrich_domains_ordered_by_created_at(pool: PgPool) -> anyhow::Result<()> {+ let team = Uuid::now_v7();+ seed_team(&pool, team, "macro|[email protected]").await?;+ let id = insert_company(&pool, team, &["a.com", "b.com", "c.com"]).await?;++ let repo = CrmSearchRepositoryImpl::new(pool);+ let results = repo.enrich_companies(&team, &[id], false).await?;++ let domains: Vec<String> = results[0]+ .company+ .domains+ .iter()+ .map(|d| d.domain.clone())+ .collect();+ assert_eq!(domains, vec!["a.com", "b.com", "c.com"]);+ Ok(())+}++// --------------------------------------------------------------------------+// enrich_companies — filtering, scoping, hidden gate+// --------------------------------------------------------------------------++#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]+async fn enrich_filters_by_company_ids(pool: PgPool) -> anyhow::Result<()> {+ let team = Uuid::now_v7();+ seed_team(&pool, team, "macro|[email protected]").await?;+ let wanted = insert_company(&pool, team, &["acme.com"]).await?;+ let _other = insert_company(&pool, team, &["globex.com"]).await?;++ let repo = CrmSearchRepositoryImpl::new(pool);+ let results = repo.enrich_companies(&team, &[wanted], false).await?;+ let ids: Vec<Uuid> = results.iter().map(|c| c.company.id).collect();+ assert_eq!(ids, vec![wanted]);+ Ok(())+}++#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]+async fn enrich_scopes_to_team(pool: PgPool) -> anyhow::Result<()> {+ let team_a = Uuid::now_v7();+ let team_b = Uuid::now_v7();+ seed_team(&pool, team_a, "macro|[email protected]").await?;+ seed_team(&pool, team_b, "macro|[email protected]").await?;+ let b_company = insert_company(&pool, team_b, &["acme.com"]).await?;++ let repo = CrmSearchRepositoryImpl::new(pool);+ // Ask team_a to enrich team_b's id → silently dropped.+ let results = repo.enrich_companies(&team_a, &[b_company], false).await?;+ assert!(results.is_empty());+ Ok(())+}++#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]+async fn enrich_member_cannot_enrich_hidden(pool: PgPool) -> anyhow::Result<()> {+ let team = Uuid::now_v7();+ seed_team(&pool, team, "macro|[email protected]").await?;+ let hidden = insert_company(&pool, team, &["acme.com"]).await?;+ set_hidden(&pool, hidden).await?;++ let repo = CrmSearchRepositoryImpl::new(pool);+ // Member passes the hidden id directly — must still get nothing.+ let results = repo.enrich_companies(&team, &[hidden], false).await?;+ assert!(+ results.is_empty(),+ "a member must not be able to enrich a hidden company even with its id"+ );+ Ok(())+}++#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]+async fn enrich_admin_can_enrich_hidden(pool: PgPool) -> anyhow::Result<()> {+ let team = Uuid::now_v7();+ seed_team(&pool, team, "macro|[email protected]").await?;+ let hidden = insert_company(&pool, team, &["acme.com"]).await?;+ set_hidden(&pool, hidden).await?;++ let repo = CrmSearchRepositoryImpl::new(pool);+ let results = repo.enrich_companies(&team, &[hidden], true).await?;+ let ids: Vec<Uuid> = results.iter().map(|c| c.company.id).collect();+ assert_eq!(ids, vec![hidden]);+ assert!(results[0].company.hidden);+ Ok(())+}++#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]+async fn enrich_member_gets_only_visible_from_mixed_ids(pool: PgPool) -> anyhow::Result<()> {+ let team = Uuid::now_v7();+ seed_team(&pool, team, "macro|[email protected]").await?;+ let visible = insert_company(&pool, team, &["acme.com"]).await?;+ let hidden = insert_company(&pool, team, &["globex.com"]).await?;+ set_hidden(&pool, hidden).await?;++ let repo = CrmSearchRepositoryImpl::new(pool);+ let results = repo+ .enrich_companies(&team, &[visible, hidden], false)+ .await?;+ let ids: Vec<Uuid> = results.iter().map(|c| c.company.id).collect();+ assert_eq!(ids, vec![visible], "hidden id is dropped, visible kept");+ Ok(())+}++#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]+async fn enrich_returns_all_requested_visible_companies(pool: PgPool) -> anyhow::Result<()> {+ let team = Uuid::now_v7();+ seed_team(&pool, team, "macro|[email protected]").await?;+ let a = insert_company(&pool, team, &["a.com"]).await?;+ let b = insert_company(&pool, team, &["b.com"]).await?;+ let c = insert_company(&pool, team, &["c.com"]).await?;++ let repo = CrmSearchRepositoryImpl::new(pool);+ let results = repo.enrich_companies(&team, &[a, b, c], false).await?;+ let mut ids: Vec<Uuid> = results.iter().map(|r| r.company.id).collect();+ ids.sort();+ let mut want = vec![a, b, c];+ want.sort();+ assert_eq!(+ ids, want,+ "every requested visible company is hydrated once"+ );+ Ok(())+}diff --git a/rust/cloud-storage/document_storage_service/src/api/context.rs b/rust/cloud-storage/document_storage_service/src/api/context.rsindex 99b36d7840..05d184cf27 100644--- a/rust/cloud-storage/document_storage_service/src/api/context.rs+++ b/rust/cloud-storage/document_storage_service/src/api/context.rs@@ -358,6 +358,7 @@ impl From<&ApiContext> for SearchHandlerState {SearchHandlerState {db: ctx.readonly_db.clone(),opensearch_client: ctx.opensearch_client.clone(),+ entity_access_service: ctx.entity_access_service.clone(),}}}diff --git a/rust/cloud-storage/macro_db_client/src/entity_name.rs b/rust/cloud-storage/macro_db_client/src/entity_name.rsindex 1b6f86ecf8..8595966c42 100644--- a/rust/cloud-storage/macro_db_client/src/entity_name.rs+++ b/rust/cloud-storage/macro_db_client/src/entity_name.rs@@ -85,6 +85,9 @@ pub async fn get_entity_name_and_owner(SearchEntityType::CallRecords => {anyhow::bail!("entity type not supported");}+ SearchEntityType::CrmCompanies => {+ anyhow::bail!("entity type not supported");+ }};Ok(result)diff --git a/rust/cloud-storage/models_opensearch/src/lib.rs b/rust/cloud-storage/models_opensearch/src/lib.rsindex 70569505e2..b9f64cb2b5 100644--- a/rust/cloud-storage/models_opensearch/src/lib.rs+++ b/rust/cloud-storage/models_opensearch/src/lib.rs@@ -23,7 +23,11 @@ pub enum SearchIndex {CallRecords,}-/// All searchable entity types. Projects are Postgres-only.+/// All searchable entity types — the tag on a unified `SearchHit`,+/// independent of where the hit came from. Most are backed by an+/// OpenSearch index, but some (Projects, CrmCompanies) are Postgres-only+/// and synthesized by name searches; those never appear in OpenSearch+/// responses. The OpenSearch-backed subset is [`OpenSearchEntityType`].#[derive(Debug,Clone,@@ -51,6 +55,8 @@ pub enum SearchEntityType {Projects,/// The call records entity type (has OpenSearch index)CallRecords,+ /// The CRM company entity type (Postgres-only)+ CrmCompanies,}/// `SearchEntityType` variants that have an OpenSearch index.diff --git a/rust/cloud-storage/models_search/src/crm_company.rs b/rust/cloud-storage/models_search/src/crm_company.rsnew file mode 100644index 0000000000..c44e7a38df--- /dev/null+++ b/rust/cloud-storage/models_search/src/crm_company.rs@@ -0,0 +1,48 @@+//! CRM company items in unified search results. Postgres-only, hydrated+//! from the `crm` crate's search service; the `crm` types are mapped into+//! these wire shapes in `search_service` so this crate stays dep-light.++use chrono::{DateTime, Utc};+use schemars::JsonSchema;+use serde::{Deserialize, Serialize};+use utoipa::ToSchema;+use uuid::Uuid;++/// A CRM domain attached to a company in search results.+#[derive(Debug, Serialize, Deserialize, ToSchema, JsonSchema)]+#[serde(rename_all = "camelCase")]+pub struct CrmCompanySearchDomain {+ /// The id of the domain record.+ pub id: Uuid,+ /// The id of the company the domain belongs to.+ pub company_id: Uuid,+ /// The domain (lowercased, e.g. "acme.com").+ pub domain: String,+ /// When the domain record was created.+ pub created_at: DateTime<Utc>,+}++/// A CRM company match in unified search results. Carries the display+/// metadata resolved from the primary domain plus the highlighted name.+#[derive(Debug, Serialize, Deserialize, ToSchema, JsonSchema)]+#[serde(rename_all = "camelCase")]+pub struct CrmCompanySearchResponseItem {+ /// The id of the company.+ pub id: Uuid,+ /// The id of the team that owns this company record.+ pub team_id: Uuid,+ /// Display name from the primary domain's directory entry.+ pub name: Option<String>,+ /// `name` with matched spans wrapped in `<macro_em>…</macro_em>`.+ pub name_highlighted: Option<String>,+ /// Display description from the primary domain's directory entry.+ pub description: Option<String>,+ /// Whether the company is hidden from CRM listings.+ pub hidden: bool,+ /// When the company was created.+ pub created_at: DateTime<Utc>,+ /// When the company was last updated (the sort key).+ pub updated_at: DateTime<Utc>,+ /// Domains associated with this company, primary first.+ pub domains: Vec<CrmCompanySearchDomain>,+}diff --git a/rust/cloud-storage/models_search/src/lib.rs b/rust/cloud-storage/models_search/src/lib.rsindex bbd9538bb1..94bb1ca831 100644--- a/rust/cloud-storage/models_search/src/lib.rs+++ b/rust/cloud-storage/models_search/src/lib.rs@@ -6,6 +6,7 @@ use utoipa::ToSchema;pub mod call_record;pub mod channel;pub mod chat;+pub mod crm_company;pub mod document;pub mod email;pub mod project;diff --git a/rust/cloud-storage/models_search/src/unified.rs b/rust/cloud-storage/models_search/src/unified.rsindex 874acba6e2..4896535d0a 100644--- a/rust/cloud-storage/models_search/src/unified.rs+++ b/rust/cloud-storage/models_search/src/unified.rs@@ -86,6 +86,13 @@ pub struct UnifiedSearchRequest {#[serde(default)]pub search_on: SearchOn,+ /// Opt in to searching the caller's team CRM companies (name/domain).+ /// Off by default: CRM results are only included when this is true and+ /// the caller has a qualifying team membership. CRM has no content+ /// index, so it is searched only under Name / NameContent.+ #[serde(default)]+ pub include_crm: bool,+#[schemars(skip)]pub collapse: Option<bool>,}@@ -205,6 +212,7 @@ pub enum UnifiedSearchResponseItem {Channel(ChannelSearchResponseItemWithMetadata),Project(ProjectSearchResponseItemWithMetadata),Call(CallRecordSearchResponseItemWithMetadata),+ Company(crate::crm_company::CrmCompanySearchResponseItem),}impl UnifiedSearchResponseItem {@@ -216,6 +224,7 @@ impl UnifiedSearchResponseItem {Self::Channel(item) => item.extra.id,Self::Project(item) => item.extra.id,Self::Call(item) => item.extra.id,+ Self::Company(item) => item.id,}}/// Get the updated_at timestamp for each item@@ -238,6 +247,7 @@ impl UnifiedSearchResponseItem {}Self::Project(item) => item.metadata.as_ref().map(|m| m.updated_at),Self::Call(item) => item.metadata.as_ref().map(|m| m.updated_at),+ Self::Company(item) => Some(item.updated_at),}}}diff --git a/rust/cloud-storage/models_search_cursor/src/lib.rs b/rust/cloud-storage/models_search_cursor/src/lib.rsindex bc2f6565c2..b4226d1c01 100644--- a/rust/cloud-storage/models_search_cursor/src/lib.rs+++ b/rust/cloud-storage/models_search_cursor/src/lib.rs@@ -160,6 +160,10 @@ pub struct SearchCursor {pub content_cursor: SearchCursorOption,/// The project cursorpub project_name_cursor: SearchCursorOption,+ /// The CRM company name cursor. `#[serde(default)]` so cursors minted+ /// before CRM search existed still decode (defaults to a fresh cursor).+ #[serde(default)]+ pub crm_company_cursor: SearchCursorOption,}impl SearchCursor {@@ -184,5 +188,58 @@ impl SearchCursor {&& self.chat_name_cursor.is_done()&& self.content_cursor.is_done()&& self.project_name_cursor.is_done()+ && self.crm_company_cursor.is_done()+ }+}++#[cfg(test)]+mod test {+ use super::*;++ /// A cursor minted before CRM search existed (no `crm_company_cursor`+ /// field) must still decode, with the new field defaulting to a fresh+ /// `NotDone(None)` rather than failing.+ #[test]+ fn decodes_legacy_cursor_without_crm_field() {+ let legacy = r#"{"document_name_cursor":"Done","chat_name_cursor":"Done","content_cursor":"Done","project_name_cursor":"Done"}"#;+ let encoded = BASE64.encode(legacy);++ let cursor = SearchCursor::decode(&encoded).expect("legacy cursor should decode");++ assert!(+ cursor.crm_company_cursor.has_more(),+ "missing crm cursor should default to NotDone(None)"+ );+ // The four legacy sources are Done, but the defaulted CRM cursor is+ // NotDone, so the whole cursor is not yet exhausted.+ assert!(!cursor.is_exhausted());+ }++ #[test]+ fn crm_cursor_round_trips() {+ let cursor = SearchCursor {+ crm_company_cursor: SearchCursorOption::Done,+ ..Default::default()+ };+ let decoded = SearchCursor::decode(&cursor.encode().expect("encode")).expect("decode");+ assert!(decoded.crm_company_cursor.is_done());+ }++ #[test]+ fn is_exhausted_requires_crm_done() {+ let mut cursor = SearchCursor {+ document_name_cursor: SearchCursorOption::Done,+ chat_name_cursor: SearchCursorOption::Done,+ content_cursor: SearchCursorOption::Done,+ project_name_cursor: SearchCursorOption::Done,+ crm_company_cursor: SearchCursorOption::Done,+ };+ assert!(cursor.is_exhausted());++ cursor.crm_company_cursor = SearchCursorOption::NotDone(None);+ assert!(+ !cursor.is_exhausted(),+ "a not-done CRM cursor must keep the aggregate cursor alive"+ );}}diff --git a/rust/cloud-storage/models_soup/src/crm_company.rs b/rust/cloud-storage/models_soup/src/crm_company.rsindex b46daba53f..2078dcef5f 100644--- a/rust/cloud-storage/models_soup/src/crm_company.rs+++ b/rust/cloud-storage/models_soup/src/crm_company.rs@@ -55,6 +55,9 @@ pub struct SoupCrmCompany {pub created_at: DateTime<Utc>,/// When the company was last updated.pub updated_at: DateTime<Utc>,+ /// When the requesting user last viewed this company, or `None` if+ /// never viewed. Mirrors the `viewed_at` other soup entities carry.+ pub viewed_at: Option<DateTime<Utc>>,/// Domains associated with this company, ordered by creation time/// ascending (primary first).pub domains: Vec<SoupCrmDomain>,@@ -66,6 +69,7 @@ impl From<CrmCompanyForSoup> for SoupCrmCompany {company,name,description,+ viewed_at,} = c;SoupCrmCompany {id: company.id,@@ -76,6 +80,7 @@ impl From<CrmCompanyForSoup> for SoupCrmCompany {hidden: company.hidden,created_at: company.created_at,updated_at: company.updated_at,+ viewed_at,domains: company.domains.into_iter()diff --git a/rust/cloud-storage/models_soup/src/item.rs b/rust/cloud-storage/models_soup/src/item.rsindex 1ac21e990b..bb63cdabec 100644--- a/rust/cloud-storage/models_soup/src/item.rs+++ b/rust/cloud-storage/models_soup/src/item.rs@@ -126,8 +126,13 @@ impl SoupItem {.unwrap_or(soup_channel.channel.channel.updated_at),(SoupItem::Call(record), SimpleSortMethod::CreatedAt) => record.started_at,(SoupItem::Call(record), _) => record.ended_at.unwrap_or(record.started_at),- // No viewed_at signal for CrmCompany yet — fall back to updated_at.(SoupItem::CrmCompany(company), SimpleSortMethod::CreatedAt) => company.created_at,+ (SoupItem::CrmCompany(company), SimpleSortMethod::ViewedAt) => {+ company.viewed_at.unwrap_or_default()+ }+ (SoupItem::CrmCompany(company), SimpleSortMethod::ViewedUpdated) => {+ company.viewed_at.unwrap_or(company.updated_at)+ }(SoupItem::CrmCompany(company), _) => company.updated_at,(SoupItem::ForeignEntity(foreign_entity), SimpleSortMethod::CreatedAt) => {foreign_entity.created_atdiff --git a/rust/cloud-storage/opensearch_client/src/search/unified.rs b/rust/cloud-storage/opensearch_client/src/search/unified.rsindex 4d35224369..22242bfcd7 100644--- a/rust/cloud-storage/opensearch_client/src/search/unified.rs+++ b/rust/cloud-storage/opensearch_client/src/search/unified.rs@@ -223,6 +223,7 @@ pub struct SplitUnifiedSearchResponseValues {pub email: Vec<SearchHit>,pub project: Vec<SearchHit>,pub call_record: Vec<SearchHit>,+ pub crm_company: Vec<SearchHit>,}pub trait SplitUnifiedSearchResponse: Iterator<Item = SearchHit> {@@ -234,40 +235,53 @@ whereT: Iterator<Item = SearchHit>,{fn split_search_response(self) -> SplitUnifiedSearchResponseValues {- let (channel_message, chat, document, email, project, call_record) = self.into_iter().fold(- (vec![], vec![], vec![], vec![], vec![], vec![]),- |(- mut channel_message,- mut chat,- mut document,- mut email,- mut project,- mut call_record,- ),- item| {- match item.entity_type {- SearchEntityType::Channels => {- channel_message.push(item);+ let (channel_message, chat, document, email, project, call_record, crm_company) =+ self.into_iter().fold(+ (vec![], vec![], vec![], vec![], vec![], vec![], vec![]),+ |(+ mut channel_message,+ mut chat,+ mut document,+ mut email,+ mut project,+ mut call_record,+ mut crm_company,+ ),+ item| {+ match item.entity_type {+ SearchEntityType::Channels => {+ channel_message.push(item);+ }+ SearchEntityType::Chats => {+ chat.push(item);+ }+ SearchEntityType::Documents => {+ document.push(item);+ }+ SearchEntityType::Emails => {+ email.push(item);+ }+ SearchEntityType::Projects => {+ project.push(item);+ }+ SearchEntityType::CallRecords => {+ call_record.push(item);+ }+ SearchEntityType::CrmCompanies => {+ crm_company.push(item);+ }}- SearchEntityType::Chats => {- chat.push(item);- }- SearchEntityType::Documents => {- document.push(item);- }- SearchEntityType::Emails => {- email.push(item);- }- SearchEntityType::Projects => {- project.push(item);- }- SearchEntityType::CallRecords => {- call_record.push(item);- }- }- (channel_message, chat, document, email, project, call_record)- },- );+ (+ channel_message,+ chat,+ document,+ email,+ project,+ call_record,+ crm_company,+ )+ },+ );SplitUnifiedSearchResponseValues {channel_message,@@ -276,6 +290,7 @@ whereemail,project,call_record,+ crm_company,}}}diff --git a/rust/cloud-storage/search_service/Cargo.toml b/rust/cloud-storage/search_service/Cargo.tomlindex 384b122799..9265954167 100644--- a/rust/cloud-storage/search_service/Cargo.toml+++ b/rust/cloud-storage/search_service/Cargo.toml@@ -20,8 +20,12 @@ axum = { workspace = true }chrono = { workspace = true }comms = { path = "../comms", default-features = false, features = ["outbound"] }comms_db_client = { path = "../comms_db_client" }+crm = { path = "../crm", default-features = false, features = ["search"] }document_sub_type = { path = "../document_sub_type" }email_db_client = { path = "../email_db_client" }+entity_access = { path = "../entity_access", default-features = false, features = [+ "outbound",+] }futures = { workspace = true }http-body-util = { workspace = true }indexmap = "2"@@ -55,6 +59,7 @@ tower = { workspace = true }tower-http = { workspace = true }tracing = { workspace = true }utoipa = { workspace = true }+uuid = { workspace = true }[dev-dependencies]macro_auth = { path = "../macro_auth", features = ["testing"] }diff --git a/rust/cloud-storage/search_service/src/api/context.rs b/rust/cloud-storage/search_service/src/api/context.rsindex 096bc9e08c..f8b1b83508 100644--- a/rust/cloud-storage/search_service/src/api/context.rs+++ b/rust/cloud-storage/search_service/src/api/context.rs@@ -1,8 +1,14 @@use axum::extract::FromRef;+use entity_access::domain::service::EntityAccessServiceImpl;+use entity_access::outbound::PgAccessRepository;use opensearch_client::OpensearchClient;use readonly_pool::ReadOnlyPool;use std::sync::Arc;+/// Concrete entity-access service backing the team receipt extractor. Same+/// type the parent app constructs, so its `Arc` can be passed in directly.+pub type SearchEntityAccessService = EntityAccessServiceImpl<PgAccessRepository>;+/// Minimal state required by search handlers./// This can be extracted from any state that implements `FromRef<SearchHandlerState>`.#[derive(Clone, FromRef)]@@ -11,4 +17,6 @@ pub struct SearchHandlerState {pub db: ReadOnlyPool,/// OpenSearch client for full-text searchpub opensearch_client: Arc<OpensearchClient>,+ /// Resolves the caller's team membership to mint CRM capability receipts.+ pub entity_access_service: Arc<SearchEntityAccessService>,}diff --git a/rust/cloud-storage/search_service/src/api/search/crm_company.rs b/rust/cloud-storage/search_service/src/api/search/crm_company.rsnew file mode 100644index 0000000000..6613d141e5--- /dev/null+++ b/rust/cloud-storage/search_service/src/api/search/crm_company.rs@@ -0,0 +1,254 @@+//! CRM company search source + enrichment for unified search.+//!+//! CRM companies are Postgres-only (like projects) and gated by a+//! capability-token receipt, so they don't flow through the OpenSearch+//! split/enrich path: [`search_company_names`] synthesizes `SearchHit`s+//! the same way the other name searches do, and [`enrich_crm_companies`]+//! hydrates them into [`UnifiedSearchResponseItem::Company`].++use std::collections::HashMap;++use crm::domain::auth::CrmTeamReceipt;+use crm::domain::model::CrmCompanyForSoup;+use crm::domain::search_repo::CrmCompanySearchCursor;+use crm::domain::search_service::{CrmSearchService, CrmSearchServiceImpl};+use crm::outbound::search_repo::CrmSearchRepositoryImpl;+use entity_access::domain::models::{+ Entity, EntityAccessReceipt, EntityPermission, EntityType, MemberTeamRole,+};+use entity_access::domain::ports::EntityAccessService;+use item_filters::CrmCompanyFilters;+use macro_user_id::user_id::MacroUserIdStr;+use model::user::UserContext;+use models_opensearch::SearchEntityType;+use models_search::crm_company::{CrmCompanySearchDomain, CrmCompanySearchResponseItem};+use models_search::unified::UnifiedSearchResponseItem;+use models_search_cursor::{SearchCursorOption, SearchMethodCursor};+use opensearch_client::search::model::{Highlight, SearchHit};+use uuid::Uuid;++use crate::api::context::SearchHandlerState;+use crate::api::search::simple::SearchError;++/// Resolve the caller's CRM team capability when `include_crm` is set.+///+/// Returns `None` (the CRM slice stays empty) — without erroring — when CRM+/// isn't requested or the user has no qualifying team membership; a missing+/// team must not fail the aggregate search. The role rides along inside the+/// receipt so the CRM service derives the hidden-company gate from it.+///+/// Assumes a single effective team per user (`get_user_team`). If multi-team+/// membership is introduced, this should take an explicit team id rather+/// than picking the highest-role team.+pub(in crate::api::search) async fn resolve_crm_team_receipt(+ ctx: &SearchHandlerState,+ user_context: &UserContext,+ include_crm: bool,+) -> Result<Option<CrmTeamReceipt<MemberTeamRole>>, SearchError> {+ if !include_crm {+ return Ok(None);+ }+ let user_id = MacroUserIdStr::try_from(user_context.user_id.clone())+ .map_err(|_| SearchError::InvalidUserId(user_context.user_id.clone()))?;+ let Some(team) = ctx+ .entity_access_service+ .get_user_team(&user_id)+ .await+ .map_err(|e| SearchError::InternalError(e.into()))?+ else {+ return Ok(None);+ };+ // Member is the floor for MemberTeamRole, so this never rejects; the+ // role still rides along for the hidden-company gate.+ let receipt = EntityAccessReceipt::<MemberTeamRole>::try_new_authenticated_user(+ user_id,+ Entity {+ entity_id: team.team_id.to_string(),+ entity_type: EntityType::Team,+ },+ EntityPermission::TeamRole { role: team.role },+ )+ .map_err(|e| SearchError::InternalError(e.into()))?;+ CrmTeamReceipt::from_team_receipt(receipt)+ .map(Some)+ .map_err(|e| SearchError::InternalError(e.into()))+}++/// Builds the CRM search service over the read-only pool. Search and+/// enrich are both read-only, so the read replica is fine.+fn search_service(ctx: &SearchHandlerState) -> CrmSearchServiceImpl<CrmSearchRepositoryImpl> {+ CrmSearchServiceImpl::new(CrmSearchRepositoryImpl::new(ctx.db.0.clone()))+}++/// Name/domain search over the caller's team CRM companies, returning+/// `SearchHit`s tagged [`SearchEntityType::CrmCompanies`] plus the next+/// CRM cursor. The hidden gate is enforced inside the CRM service from+/// the receipt's role — the caller can't widen it.+#[tracing::instrument(skip(ctx, access, filters), err)]+pub(in crate::api::search) async fn search_company_names(+ ctx: &SearchHandlerState,+ access: &CrmTeamReceipt<MemberTeamRole>,+ filters: &CrmCompanyFilters,+ term: String,+ limit: u32,+ cursor: SearchCursorOption,+) -> Result<(Vec<SearchHit>, SearchCursorOption), SearchError> {+ // A Done cursor means this source is exhausted for the page set.+ let inner_cursor = match cursor {+ SearchCursorOption::Done => return Ok((vec![], SearchCursorOption::Done)),+ SearchCursorOption::NotDone(c) => c,+ };++ // Defensive: an empty term would match every company via `ILIKE '%%'`.+ // Callers already enforce a 3-char minimum upstream, but CRM is DB-backed+ // and opt-in, so guard against accidentally listing the whole team.+ let term = term.trim();+ if term.is_empty() {+ return Ok((vec![], SearchCursorOption::Done));+ }++ let crm_cursor =+ inner_cursor+ .and_then(|c| c.as_updated_at())+ .map(|(last_id, last_updated_at)| CrmCompanySearchCursor {+ last_updated_at,+ last_id,+ });++ // Parse strictly: an invalid id is a malformed request, not "no filter".+ // Silently dropping it would let a fully-invalid id list collapse to the+ // empty set, which the repo reads as "all the team's companies".+ let mut company_ids: Vec<Uuid> = Vec::with_capacity(filters.company_ids.len());+ for id in &filters.company_ids {+ company_ids+ .push(Uuid::parse_str(id).map_err(|_| SearchError::InvalidCrmCompanyId(id.clone()))?);+ }++ // Fetch one extra row to detect whether a next page exists.+ let fetch_limit = limit as i64 + 1;+ let mut matches = search_service(ctx)+ .search_company_names(+ access,+ term,+ &company_ids,+ filters.hidden,+ fetch_limit,+ crm_cursor,+ )+ .await+ .map_err(|e| SearchError::InternalError(e.into()))?;++ let has_more = matches.len() > limit as usize;+ if has_more {+ matches.pop();+ }+ let next_cursor = if has_more {+ match matches.last() {+ Some(last) => SearchCursorOption::NotDone(Some(SearchMethodCursor::UpdatedAt {+ entity_id: last.id,+ updated_at: last.updated_at,+ })),+ None => SearchCursorOption::Done,+ }+ } else {+ SearchCursorOption::Done+ };++ let hits = matches+ .into_iter()+ .map(|m| SearchHit {+ entity_id: m.id,+ entity_type: SearchEntityType::CrmCompanies,+ score: None,+ highlight: Highlight {+ name: Some(m.name_highlighted),+ ..Default::default()+ },+ goto: None,+ updated_at: Some(m.updated_at),+ })+ .collect();++ Ok((hits, next_cursor))+}++/// Hydrate CRM company hits into [`UnifiedSearchResponseItem::Company`],+/// preserving the hits' sort order and attaching each hit's highlighted+/// name. Non-CRM hits are ignored.+#[tracing::instrument(skip(ctx, access, results), err)]+pub(in crate::api::search) async fn enrich_crm_companies(+ ctx: &SearchHandlerState,+ access: Option<&CrmTeamReceipt<MemberTeamRole>>,+ results: Vec<SearchHit>,+) -> Result<Vec<UnifiedSearchResponseItem>, SearchError> {+ let results: Vec<SearchHit> = results+ .into_iter()+ .filter(|r| r.entity_type == SearchEntityType::CrmCompanies)+ .collect();++ if results.is_empty() {+ return Ok(vec![]);+ }+ // There are no CRM hits without a receipt; stay defensive regardless.+ let Some(access) = access else {+ return Ok(vec![]);+ };++ let ids: Vec<Uuid> = results.iter().map(|r| r.entity_id).collect();++ let companies = search_service(ctx)+ .enrich_companies(access, &ids)+ .await+ .map_err(|e| SearchError::InternalError(e.into()))?;++ let mut by_id: HashMap<Uuid, CrmCompanyForSoup> =+ companies.into_iter().map(|c| (c.company.id, c)).collect();++ // Rebuild in match order, attaching the highlighted name from the hit.+ let items = results+ .into_iter()+ .filter_map(|hit| {+ let company = by_id.remove(&hit.entity_id)?;+ Some(UnifiedSearchResponseItem::Company(to_response_item(+ company,+ hit.highlight.name,+ )))+ })+ .collect();++ Ok(items)+}++/// Map an enriched company plus its highlighted name into the wire item.+fn to_response_item(+ c: CrmCompanyForSoup,+ name_highlighted: Option<String>,+) -> CrmCompanySearchResponseItem {+ let CrmCompanyForSoup {+ company,+ name,+ description,+ // Search results aren't view-tracked; no viewed_at in the response.+ viewed_at: _,+ } = c;+ CrmCompanySearchResponseItem {+ id: company.id,+ team_id: company.team_id,+ name,+ name_highlighted,+ description,+ hidden: company.hidden,+ created_at: company.created_at,+ updated_at: company.updated_at,+ domains: company+ .domains+ .into_iter()+ .map(|d| CrmCompanySearchDomain {+ id: d.id,+ company_id: d.company_id,+ domain: d.domain,+ created_at: d.created_at,+ })+ .collect(),+ }+}diff --git a/rust/cloud-storage/search_service/src/api/search/enrich.rs b/rust/cloud-storage/search_service/src/api/search/enrich.rsindex eadb308739..2ec60bb16e 100644--- a/rust/cloud-storage/search_service/src/api/search/enrich.rs+++ b/rust/cloud-storage/search_service/src/api/search/enrich.rs@@ -69,5 +69,8 @@ pub async fn enrich_search_response(.map(UnifiedSearchResponseItem::Call).collect())}+ // CRM companies are enriched separately (they need the team+ // receipt) via `crm_company::enrich_crm_companies`.+ SearchEntityType::CrmCompanies => Ok(vec![]),}}diff --git a/rust/cloud-storage/search_service/src/api/search/mod.rs b/rust/cloud-storage/search_service/src/api/search/mod.rsindex bdeba1eb5a..6d4434eb5d 100644--- a/rust/cloud-storage/search_service/src/api/search/mod.rs+++ b/rust/cloud-storage/search_service/src/api/search/mod.rs@@ -5,6 +5,7 @@ use crate::api::context::SearchHandlerState;pub(in crate::api) mod call_record;pub(in crate::api) mod channel;pub(in crate::api) mod chat;+pub(in crate::api) mod crm_company;pub(in crate::api) mod document;pub(in crate::api) mod email;pub(in crate::api::search) mod enrich;diff --git a/rust/cloud-storage/search_service/src/api/search/simple/mod.rs b/rust/cloud-storage/search_service/src/api/search/simple/mod.rsindex 9adde747d9..db55bac728 100644--- a/rust/cloud-storage/search_service/src/api/search/simple/mod.rs+++ b/rust/cloud-storage/search_service/src/api/search/simple/mod.rs@@ -44,6 +44,9 @@ pub enum SearchError {#[error("searching with an invalid cursor")]/// Searching with an invalid cursorInvalidCursor,+ /// A CRM company filter id was not a valid UUID+ #[error("invalid crm company id: {0}")]+ InvalidCrmCompanyId(String),/// Opensearch error occurred#[error("unable to search")]Search(#[from] OpensearchClientError),@@ -62,6 +65,7 @@ impl IntoResponse for SearchError {SearchError::InvalidPageSize| SearchError::InvalidQuerySize| SearchError::InvalidCursor+ | SearchError::InvalidCrmCompanyId(_)| SearchError::NoQueryOrTermsProvided| SearchError::NoChannelIds => StatusCode::BAD_REQUEST,SearchError::NameSearch(NameSearchError::IncompatibleCursor) => StatusCode::BAD_REQUEST,diff --git a/rust/cloud-storage/search_service/src/api/search/simple/simple_unified.rs b/rust/cloud-storage/search_service/src/api/search/simple/simple_unified.rsindex 89b75fcefe..a52ca3be42 100644--- a/rust/cloud-storage/search_service/src/api/search/simple/simple_unified.rs+++ b/rust/cloud-storage/search_service/src/api/search/simple/simple_unified.rs@@ -1,5 +1,6 @@use crate::api::search::simple::filter::FilterVariantToSearchArgs;+use crate::api::search::crm_company;use crate::api::search::simple::{simple_chat, simple_document, simple_project};use crate::api::{context::SearchHandlerState,@@ -10,6 +11,8 @@ use axum::{extract::{self, State},response::Json,};+use crm::domain::auth::CrmTeamReceipt;+use entity_access::domain::models::MemberTeamRole;use macro_user_id::user_id::MacroUserId;use model::{response::ErrorResponse, user::UserContext};use models_search::unified::SearchEntityFilters;@@ -28,6 +31,7 @@ enum SearchSource {ChatName,ProjectName,Content,+ CrmCompany,}/// Wrapper for SearchHit that tracks its source for cursor regeneration@@ -84,6 +88,7 @@ use crate::api::search::terms::split_search_terms;pub(in crate::api::search) async fn perform_unified_search(ctx: &SearchHandlerState,user_context: &UserContext,+ crm_access: Option<&CrmTeamReceipt<MemberTeamRole>>,query_params: SearchPaginationParams,req: UnifiedSearchRequest,) -> Result<@@ -131,6 +136,12 @@ pub(in crate::api::search) async fn perform_unified_search(let match_type = req.match_type;+ // CRM is opt-in: it only runs when the caller resolved a team receipt+ // (set only when `include_crm` is true and the user has a qualifying+ // membership). `crm_company_filters` scopes/selects within the team.+ let crm_company_filters = req.filters.crm_company_filters.clone();+ let should_include_crm = crm_access.is_some();+let search_filters = SearchEntityFilters::from(req.filters);let channel_filters = search_filters.channel_filters;let email_filters = search_filters.email_filters;@@ -232,11 +243,17 @@ pub(in crate::api::search) async fn perform_unified_search(.map(|c| c.content_cursor.clone()).unwrap_or_default();+ let crm_cursor = cursor+ .as_ref()+ .map(|c| c.crm_company_cursor.clone())+ .unwrap_or_default();+// Clone cursors for passing to search functions (originals needed for cursor regeneration)let document_cursor_for_search = document_cursor.clone();let chat_cursor_for_search = chat_cursor.clone();let project_cursor_for_search = project_cursor.clone();let content_cursor_for_search = content_cursor.clone();+ let crm_cursor_for_search = crm_cursor.clone();let unified_search_args = UnifiedSearchArgs {user_id: user_id.as_ref().to_string(),@@ -278,7 +295,7 @@ pub(in crate::api::search) async fn perform_unified_search(// Call search functions in parallel for included entity types// search_names handles Done cursors internally by returning early- let (doc_name_results, chat_results, project_results, content_results) = tokio::join!(+ let (doc_name_results, chat_results, project_results, content_results, crm_results) = tokio::join!(async {if should_include_documents {match search_on {@@ -365,6 +382,24 @@ pub(in crate::api::search) async fn perform_unified_search(ctx.opensearch_client.search_unified(args).await}},+ async {+ // CRM companies are name/domain only — no content index — so+ // they only participate under Name / NameContent.+ match (should_include_crm, crm_access, search_on) {+ (true, Some(access), SearchOn::Name | SearchOn::NameContent) => {+ crm_company::search_company_names(+ ctx,+ access,+ &crm_company_filters,+ name_search_term.clone(),+ page_size,+ crm_cursor_for_search,+ )+ .await+ }+ _ => Ok((vec![], SearchCursorOption::Done)),+ }+ },);// Extract results and next cursors@@ -372,12 +407,14 @@ pub(in crate::api::search) async fn perform_unified_search(let (chat_hits, chat_next_cursor) = chat_results?;let (project_hits, project_next_cursor) = project_results?;let (content_hits, content_next_cursor) = content_results?;+ let (crm_hits, crm_next_cursor) = crm_results?;// Track original counts before combininglet doc_name_count = doc_hits.len();let chat_name_count = chat_hits.len();let project_name_count = project_hits.len();let content_count = content_hits.len();+ let crm_count = crm_hits.len();let final_tagged = {let _span = tracing::info_span!(@@ -407,6 +444,10 @@ pub(in crate::api::search) async fn perform_unified_search(hit,source: SearchSource::Content,}));+ combined.extend(crm_hits.into_iter().map(|hit| TaggedSearchHit {+ hit,+ source: SearchSource::CrmCompany,+ }));tracing::debug!(total_combined = combined.len(), "combined all results");@@ -453,6 +494,10 @@ pub(in crate::api::search) async fn perform_unified_search(.iter().filter(|h| h.source == SearchSource::Content).count();+ let included_crm = final_tagged+ .iter()+ .filter(|h| h.source == SearchSource::CrmCompany)+ .count();// Generate new cursors using helper functionlet new_doc_cursor = compute_next_cursor(@@ -487,11 +532,20 @@ pub(in crate::api::search) async fn perform_unified_search(&content_cursor,);+ let new_crm_cursor = compute_next_cursor(+ &crm_next_cursor,+ included_crm,+ crm_count,+ find_last_of_source(&final_tagged, SearchSource::CrmCompany),+ &crm_cursor,+ );+// Build next cursor if any source has more resultslet has_more = new_doc_cursor.has_more()|| new_chat_cursor.has_more()|| new_project_cursor.has_more()- || new_content_cursor.has_more();+ || new_content_cursor.has_more()+ || new_crm_cursor.has_more();if has_more {let cursor = SearchCursor {@@ -499,6 +553,7 @@ pub(in crate::api::search) async fn perform_unified_search(chat_name_cursor: new_chat_cursor,content_cursor: new_content_cursor,project_name_cursor: new_project_cursor,+ crm_company_cursor: new_crm_cursor,};cursor.encode()} else {@@ -542,8 +597,9 @@ pub async fn handler("simple_unified_search");+ // CRM opt-in is wired through the unified `/search` endpoint only.let (results, _next_cursor) =- perform_unified_search(&ctx, &user_context, query_params, req).await?;+ perform_unified_search(&ctx, &user_context, None, query_params, req).await?;let results = results.into_iter().map(|a| a.into()).collect();diff --git a/rust/cloud-storage/search_service/src/api/search/simple/simple_unified/test.rs b/rust/cloud-storage/search_service/src/api/search/simple/simple_unified/test.rsindex a8c02f5d83..8e6787d1a2 100644--- a/rust/cloud-storage/search_service/src/api/search/simple/simple_unified/test.rs+++ b/rust/cloud-storage/search_service/src/api/search/simple/simple_unified/test.rs@@ -345,3 +345,99 @@ fn test_cursor_logic_source_exhausted_scenario() {assert!(new_doc_cursor.is_done());}++// ==================== CRM source cursor scenarios ====================++#[test]+fn test_cursor_logic_crm_starved_preserves_cursor() {+ // The regression-prone case for the newly-added CRM source: CRM returned+ // a page of hits and reported more available, but the global merge/sort+ // put only newer non-CRM hits on this page. The CRM cursor must be carried+ // forward unchanged — advancing it (or marking it Done) would skip the CRM+ // hits that never made it onto a page. This mirrors the exact arguments+ // `perform_unified_search` passes for the CRM source.+ let incoming_crm_id = Uuid::new_v4();+ let incoming_crm_ts = ts(500);+ let incoming_crm_cursor = SearchCursorOption::NotDone(Some(SearchMethodCursor::UpdatedAt {+ entity_id: incoming_crm_id,+ updated_at: incoming_crm_ts,+ }));++ // Final page: all non-CRM (CRM starved out by newer doc/chat hits).+ let final_tagged: Vec<TaggedSearchHit> = vec![+ make_tagged_hit(Uuid::new_v4(), Some(ts(9000)), SearchSource::DocumentName),+ make_tagged_hit(Uuid::new_v4(), Some(ts(8000)), SearchSource::ChatName),+ ];++ // CRM returned hits this round and reported more available.+ let crm_next_cursor = SearchCursorOption::NotDone(Some(SearchMethodCursor::UpdatedAt {+ entity_id: Uuid::new_v4(),+ updated_at: ts(100),+ }));+ let included_crm = final_tagged+ .iter()+ .filter(|h| h.source == SearchSource::CrmCompany)+ .count();+ assert_eq!(included_crm, 0, "precondition: no CRM hit made the page");++ let new_crm_cursor = compute_next_cursor(+ &crm_next_cursor,+ included_crm,+ 5, // CRM originally returned a full page of hits+ find_last_of_source(&final_tagged, SearchSource::CrmCompany),+ &incoming_crm_cursor,+ );++ match new_crm_cursor {+ SearchCursorOption::NotDone(Some(cursor)) => {+ let (id, t) = cursor.as_updated_at().expect("expected UpdatedAt cursor");+ assert_eq!(id, incoming_crm_id, "CRM cursor must not advance");+ assert_eq!(t, incoming_crm_ts, "CRM cursor must not advance");+ }+ other => panic!(+ "expected the incoming CRM cursor preserved, got {:?}",+ other+ ),+ }+}++#[test]+fn test_cursor_logic_crm_included_advances_cursor() {+ // The companion case: when a CRM hit does make the page, the CRM cursor+ // advances to the last included CRM hit (keyset position for the next page).+ let crm_id = Uuid::new_v4();+ let crm_ts = ts(7000);+ let final_tagged: Vec<TaggedSearchHit> = vec![+ make_tagged_hit(Uuid::new_v4(), Some(ts(9000)), SearchSource::DocumentName),+ make_tagged_hit(crm_id, Some(crm_ts), SearchSource::CrmCompany),+ ];++ let crm_next_cursor = SearchCursorOption::NotDone(Some(SearchMethodCursor::UpdatedAt {+ entity_id: Uuid::new_v4(),+ updated_at: ts(100),+ }));+ let included_crm = final_tagged+ .iter()+ .filter(|h| h.source == SearchSource::CrmCompany)+ .count();++ let new_crm_cursor = compute_next_cursor(+ &crm_next_cursor,+ included_crm,+ 5,+ find_last_of_source(&final_tagged, SearchSource::CrmCompany),+ &SearchCursorOption::NotDone(None),+ );++ match new_crm_cursor {+ SearchCursorOption::NotDone(Some(cursor)) => {+ let (id, t) = cursor.as_updated_at().expect("expected UpdatedAt cursor");+ assert_eq!(id, crm_id);+ assert_eq!(t, crm_ts);+ }+ other => panic!(+ "expected cursor at the last included CRM hit, got {:?}",+ other+ ),+ }+}diff --git a/rust/cloud-storage/search_service/src/api/search/unified.rs b/rust/cloud-storage/search_service/src/api/search/unified.rsindex e6b76fa265..d08644474d 100644--- a/rust/cloud-storage/search_service/src/api/search/unified.rs+++ b/rust/cloud-storage/search_service/src/api/search/unified.rs@@ -2,6 +2,7 @@ use super::SearchPaginationParams;use crate::api::{context::SearchHandlerState,search::{+ crm_company::{enrich_crm_companies, resolve_crm_team_receipt},enrich::enrich_search_response,simple::{SearchError, simple_unified::perform_unified_search},},@@ -46,9 +47,15 @@ pub async fn handler(user_id = user_context.user_id,query = ?req.query,search_on = ?req.search_on,+ include_crm = req.include_crm,"unified_search");+ // CRM is opt-in: only when the caller asks for it does this resolve a+ // team membership and mint a capability receipt. No membership → empty+ // CRM slice, not a failed search. See `resolve_crm_team_receipt`.+ let crm_access = resolve_crm_team_receipt(&ctx, &user_context, req.include_crm).await?;+let document_name_term = match req.search_on {models_search::SearchOn::Name | models_search::SearchOn::NameContent => {let trimmed = req.query.trim();@@ -58,7 +65,7 @@ pub async fn handler(};let (results, next_cursor) =- perform_unified_search(&ctx, &user_context, query_params, req).await?;+ perform_unified_search(&ctx, &user_context, crm_access.as_ref(), query_params, req).await?;// Split the results by entity typelet SplitUnifiedSearchResponseValues {@@ -68,6 +75,7 @@ pub async fn handler(email,project,call_record,+ crm_company,} = {let _span = tracing::info_span!("split_search_response_by_type").entered();results.into_iter().split_search_response()@@ -80,6 +88,7 @@ pub async fn handler(enriched_project_results,enriched_email_results,enriched_call_record_results,+ enriched_crm_results,) = tokio::try_join!(enrich_search_response(&ctx,@@ -123,6 +132,7 @@ pub async fn handler(models_opensearch::SearchEntityType::CallRecords,None,),+ enrich_crm_companies(&ctx, crm_access.as_ref(), crm_company),).map_err(|e| SearchError::InternalError(anyhow::anyhow!("tokio error: {:?}", e)))?;@@ -137,6 +147,7 @@ pub async fn handler(results.extend(enriched_project_results);results.extend(enriched_email_results);results.extend(enriched_call_record_results);+ results.extend(enriched_crm_results);sort_unified_search_results(results)};