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(foreign_entity): add foreign entity to soup (#3626)
Will Hutchinsonf6ffbc1e16ba
diff --git a/js/app/packages/app/component/next-soup/filters/filter-store/compile.ts b/js/app/packages/app/component/next-soup/filters/filter-store/compile.tsindex 1bcee5f8c8..27874153cc 100644--- a/js/app/packages/app/component/next-soup/filters/filter-store/compile.ts+++ b/js/app/packages/app/component/next-soup/filters/filter-store/compile.ts@@ -16,7 +16,15 @@ type BackendAst =| { '!': BackendAst }| { l: unknown };-type QueryTarget = 'df' | 'ef' | 'chanf' | 'cf' | 'pf' | 'callf' | 'propf';+type QueryTarget =+ | 'df'+ | 'ef'+ | 'chanf'+ | 'cf'+ | 'pf'+ | 'callf'+ | 'fef'+ | 'propf';export type TargetAstMap = {[K in QueryTarget]?: BackendAst;@@ -102,6 +110,7 @@ const FIELD_CONFIG: Record<callChannelId: { target: 'callf', field: 'ChannelId' },callSpeakerId: { target: 'callf', field: 'Speaker' },callAttended: { target: 'callf', field: 'Attended' },+ foreignEntityRecordId: { target: 'fef', field: 'id' },};const DATE_RANGE_FIELDS: Record<@@ -151,6 +160,7 @@ export function compileToAst(state: QueryState): TargetAstMap {cf: [],pf: [],callf: [],+ fef: [],propf: [],};@@ -284,6 +294,7 @@ const ID_FIELD_NAMES: Partial<Record<QueryTarget, FieldName>> = {cf: 'chatId',pf: 'folderId',callf: 'callId',+ fef: 'foreignEntityRecordId',};type DefineQueryFiltersOptions = {diff --git a/js/app/packages/app/component/next-soup/filters/filter-store/types.ts b/js/app/packages/app/component/next-soup/filters/filter-store/types.tsindex 1161ebcffa..280552469c 100644--- a/js/app/packages/app/component/next-soup/filters/filter-store/types.ts+++ b/js/app/packages/app/component/next-soup/filters/filter-store/types.ts@@ -34,6 +34,7 @@ export type ArrayFieldFilters = {callId?: string[];callChannelId?: string[];callSpeakerId?: string[];+ foreignEntityRecordId?: string[];properties?: PropertyFilter[];};diff --git a/js/app/packages/app/component/next-soup/filters/query-filters.ts b/js/app/packages/app/component/next-soup/filters/query-filters.tsindex 93107fb311..4c935135cb 100644--- a/js/app/packages/app/component/next-soup/filters/query-filters.ts+++ b/js/app/packages/app/component/next-soup/filters/query-filters.ts@@ -13,6 +13,7 @@ export const QUERY_FILTERS_BASE: SoupItemsQueryFilters = {chat_filters: { chat_ids: EXCLUDE },document_filters: { document_ids: EXCLUDE },email_filters: { email_thread_ids: EXCLUDE },+ foreign_entity_filters: { ids: EXCLUDE },project_filters: { project_ids: EXCLUDE },};@@ -78,5 +79,18 @@ export function filterSoupItemByRequestBody(!isIdFilteredOut(body.call_filters?.call_ids, data.callId) &&!isAttendedFilteredOut(body.call_filters?.attended, data.attended))+ .with(+ { tag: 'foreignEntity' },+ ({ data }) =>+ !isIdFilteredOut(body.foreign_entity_filters?.ids, data.id) &&+ !isIdFilteredOut(+ body.foreign_entity_filters?.foreign_entity_ids,+ data.foreignEntityId+ ) &&+ !isValueFilteredOut(+ body.foreign_entity_filters?.foreign_entity_sources,+ data.foreignEntitySource+ )+ ).exhaustive();}diff --git a/js/app/packages/app/component/next-soup/soup-view/create-search-state.ts b/js/app/packages/app/component/next-soup/soup-view/create-search-state.tsindex bd20f6339e..e4ae8a5083 100644--- a/js/app/packages/app/component/next-soup/soup-view/create-search-state.ts+++ b/js/app/packages/app/component/next-soup/soup-view/create-search-state.ts@@ -107,6 +107,13 @@ function filterDataToQueryFilters(data: QueryState): EntityFilters {};}+ // Foreign entity filters+ if (include.foreignEntityRecordId?.length) {+ filters.foreign_entity_filters = {+ ids: include.foreignEntityRecordId,+ };+ }+return filters;}diff --git a/js/app/packages/queries/notification/user-notifications.ts b/js/app/packages/queries/notification/user-notifications.tsindex bfb06be322..4badbe3e39 100644--- a/js/app/packages/queries/notification/user-notifications.ts+++ b/js/app/packages/queries/notification/user-notifications.ts@@ -538,6 +538,7 @@ function notificationEntityTypeToSoupTag(.with('channel', () => 'channel' as const).with('project', () => 'project' as const).with('email_thread', () => 'emailThread' as const)+ .with('foreign_entity', () => 'foreignEntity' as const).with(P.union('user', 'team', 'call', 'static_file'), () => null).exhaustive();}diff --git a/js/app/packages/queries/properties/entity.ts b/js/app/packages/queries/properties/entity.tsindex e2e418bdcb..51bbb023d0 100644--- a/js/app/packages/queries/properties/entity.ts+++ b/js/app/packages/queries/properties/entity.ts@@ -86,6 +86,7 @@ function optimisticUpdateSoupEntityProperty(!current ||current.tag === 'channel' ||current.tag === 'call' ||+ current.tag === 'foreignEntity' ||!current.data.properties) {return undefined;diff --git a/js/app/packages/queries/soup/normalized-cache/operations.ts b/js/app/packages/queries/soup/normalized-cache/operations.tsindex ccd89fd72d..6fcf3f2306 100644--- a/js/app/packages/queries/soup/normalized-cache/operations.ts+++ b/js/app/packages/queries/soup/normalized-cache/operations.ts@@ -295,6 +295,10 @@ export function buildSingleEntityFilter(...base,call_filters: { call_ids: [entityId] },}))+ .with('foreignEntity', () => ({+ ...base,+ foreign_entity_filters: { ids: [entityId] },+ })).exhaustive();}@@ -319,8 +323,8 @@ export function optimisticUpdateSoupItemViewedAt(itemId: string) {data: { channel: { id: itemId }, viewed_at: now },frecency_score: current.frecency_score,});- } else if (current.tag === 'call') {- // Call records don't have viewedAt — skip.+ } else if (current.tag === 'call' || current.tag === 'foreignEntity') {+ // Call records and foreign entities don't have viewedAt — skip.return;} else {optimisticUpdateSoupEntity({diff --git a/js/app/packages/queries/soup/recently-viewed.ts b/js/app/packages/queries/soup/recently-viewed.tsindex c58b16e7d7..4e4d699b2f 100644--- a/js/app/packages/queries/soup/recently-viewed.ts+++ b/js/app/packages/queries/soup/recently-viewed.ts@@ -41,15 +41,19 @@ export function useRecentlyViewedSoupQuery() {},}));- return page.items- .filter((item) => item.tag !== 'call')- .map((item) => ({- id: item.tag === 'channel' ? item.data.channel.id : item.data.id,- viewedAt:- (item.tag === 'channel'- ? item.data.viewed_at- : item.data.viewedAt) ?? undefined,- }));+ return page.items.flatMap((item): RecentlyViewedItem[] => {+ if (item.tag === 'call' || item.tag === 'foreignEntity') return [];++ return [+ {+ id: item.tag === 'channel' ? item.data.channel.id : item.data.id,+ viewedAt:+ (item.tag === 'channel'+ ? item.data.viewed_at+ : item.data.viewedAt) ?? undefined,+ },+ ];+ });},staleTime: RECENTLY_VIEWED_STALE_TIME,gcTime: RECENTLY_VIEWED_GC_TIME,diff --git a/js/app/packages/queries/soup/transform-utils.ts b/js/app/packages/queries/soup/transform-utils.tsindex f1a1427753..3c882d4190 100644--- a/js/app/packages/queries/soup/transform-utils.ts+++ b/js/app/packages/queries/soup/transform-utils.ts@@ -47,6 +47,11 @@ type InnerSearchResult =| ProjectSearchResult| CallRecordSearchResult;+type DisplayableSoupItem = Exclude<+ SoupPage['items'][number],+ { tag: 'foreignEntity' }+>;+type TypedInnerSearchResult =| { results: InnerSearchResult[]; type?: undefined }| { results: DocumentSearchResult[]; type: 'pdf'; searchQuery: string }@@ -458,10 +463,11 @@ export const mapSoupPageToEntityList: ()[] = (data, options) => {return data.items.filter(- (item) =>- item.tag !== 'document' ||- !options.instructionsIdQuery.isSuccess ||- item.data.id !== options.instructionsIdQuery.data+ (item): item is DisplayableSoupItem =>+ item.tag !== 'foreignEntity' &&+ (item.tag !== 'document' ||+ !options.instructionsIdQuery.isSuccess ||+ item.data.id !== options.instructionsIdQuery.data)).map((diff --git a/js/app/packages/service-clients/service-cognition/generated/schemas/entityType.ts b/js/app/packages/service-clients/service-cognition/generated/schemas/entityType.tsindex d867033750..25e7f80a20 100644--- a/js/app/packages/service-clients/service-cognition/generated/schemas/entityType.ts+++ b/js/app/packages/service-clients/service-cognition/generated/schemas/entityType.ts@@ -20,5 +20,6 @@ export const EntityType = {email_thread: 'email_thread',team: 'team',call: 'call',+ foreign_entity: 'foreign_entity',static_file: 'static_file',} as const;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 3b843ad242..fc3bca55fb 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@@ -506,10 +506,19 @@ export const ListEntities = z.object({ef: z.any().default(null),emailPreset: z.union([z.literal('signal'), z.null()]).optional(),emailView: z.union([z.string(), z.null()]).default(null),+ fef: z.any().default(null),includeTypes: z.union([z.array(- z.enum(['document', 'ai_chat', 'project', 'email', 'channel', 'call'])+ z.enum([+ 'document',+ 'ai_chat',+ 'project',+ 'email',+ 'channel',+ 'call',+ 'foreign_entity',+ ])),z.null(),])@@ -556,6 +565,13 @@ export const ListEntitiesResponse = z.object({id: z.string().uuid(),type: z.literal('call'),}),+ z.object({+ foreignEntityId: z.string(),+ foreignEntitySource: z.string(),+ id: z.string().uuid(),+ metadata: z.any(),+ type: z.literal('foreignEntity'),+ }),];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 0aa9ab4350..8350ad8bcb 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@@ -118,6 +118,13 @@ export type EntityItem =createdBy: string;id: string;type: 'call';+ }+ | {+ foreignEntityId: string;+ foreignEntitySource: string;+ id: string;+ metadata: unknown;+ type: 'foreignEntity';};export type ToolEntityType =| 'document'@@ -133,7 +140,8 @@ export type ItemType =| 'project'| 'email'| 'channel'- | 'call';+ | 'call'+ | 'foreign_entity';export type SortBy =| 'recently_viewed'| 'recently_updated'@@ -1163,7 +1171,7 @@ export interface ListCallRecordsResponse {records: CallRecordSummary[];}/**- * Browse the user's workspace to see recent items they have access to. Returns documents, AI conversations, projects, emails, and chat channels. Use this to get an overview of what the user has been working on or to find items by type. For finding specific items by name or content, use the search tool instead.+ * Browse the user's workspace to see recent items they have access to. Returns documents, AI conversations, projects, emails, chat channels, call records, and foreign entities. Use this to get an overview of what the user has been working on or to find items by type. For finding specific items by name or content, use the search tool instead.*/export interface ListEntities {/**@@ -1206,6 +1214,12 @@ export interface ListEntities {* When the user asks about signal or important emails, use emailView="inbox" together with emailPreset="signal" — do not set emailView="important" in that case. Only override the default when the user explicitly asks for a specific mailbox or label view (e.g. "sent", "drafts", "my Foo label").*/emailView?: string | null;+ /**+ * Full soup AST foreign entity filter (fef).+ */+ fef?: {+ [k: string]: unknown;+ };/*** Filter returned items to specific item types. If not provided, returns all types. Example: ["document", "email"] returns only documents and emails. This is folded into the AST and applied as part of cursor-level filtering.*/diff --git a/js/app/packages/service-clients/service-cognition/openapi.json b/js/app/packages/service-clients/service-cognition/openapi.jsonindex 428ce85ad2..b70784cada 100644--- a/js/app/packages/service-clients/service-cognition/openapi.json+++ b/js/app/packages/service-clients/service-cognition/openapi.json@@ -2395,6 +2395,7 @@"email_thread","team","call",+ "foreign_entity","static_file"]},diff --git a/js/app/packages/service-clients/service-connection/generated/schemas/entityType.ts b/js/app/packages/service-clients/service-connection/generated/schemas/entityType.tsindex 9fd4930034..d853b81635 100644--- a/js/app/packages/service-clients/service-connection/generated/schemas/entityType.ts+++ b/js/app/packages/service-clients/service-connection/generated/schemas/entityType.ts@@ -20,5 +20,6 @@ export const EntityType = {email_thread: 'email_thread',team: 'team',call: 'call',+ foreign_entity: 'foreign_entity',static_file: 'static_file',} as const;diff --git a/js/app/packages/service-clients/service-connection/openapi.json b/js/app/packages/service-clients/service-connection/openapi.jsonindex d4adf5ef31..e25a098ee0 100644--- a/js/app/packages/service-clients/service-connection/openapi.json+++ b/js/app/packages/service-clients/service-connection/openapi.json@@ -238,6 +238,7 @@"email_thread","team","call",+ "foreign_entity","static_file"]},diff --git a/js/app/packages/service-clients/service-notification/generated/schemas/entityType.ts b/js/app/packages/service-clients/service-notification/generated/schemas/entityType.tsindex c9aa0310c0..6f8fd0bf4b 100644--- a/js/app/packages/service-clients/service-notification/generated/schemas/entityType.ts+++ b/js/app/packages/service-clients/service-notification/generated/schemas/entityType.ts@@ -20,5 +20,6 @@ export const EntityType = {email_thread: 'email_thread',team: 'team',call: 'call',+ foreign_entity: 'foreign_entity',static_file: 'static_file',} as const;diff --git a/js/app/packages/service-clients/service-notification/generated/zod.ts b/js/app/packages/service-clients/service-notification/generated/zod.tsindex a90a0e6ec3..24bc910286 100644--- a/js/app/packages/service-clients/service-notification/generated/zod.ts+++ b/js/app/packages/service-clients/service-notification/generated/zod.ts@@ -116,6 +116,7 @@ export const listTypedNotificationsResponse = zod'email_thread','team','call',+ 'foreign_entity','static_file',]).describe('The type of an entity in Macro'),@@ -632,6 +633,7 @@ export const bulkGetTypedNotificationsByEventItemIdsResponse = zod'email_thread','team','call',+ 'foreign_entity','static_file',]).describe('The type of an entity in Macro'),@@ -1142,6 +1144,7 @@ export const getTypedNotificationsByEventItemIdResponse = zod'email_thread','team','call',+ 'foreign_entity','static_file',]).describe('The type of an entity in Macro'),@@ -1663,6 +1666,7 @@ export const getTypedNotificationByIdResponse = zod'email_thread','team','call',+ 'foreign_entity','static_file',]).describe('The type of an entity in Macro'),diff --git a/js/app/packages/service-clients/service-notification/openapi.json b/js/app/packages/service-clients/service-notification/openapi.jsonindex 3e206dac16..df2c78a270 100644--- a/js/app/packages/service-clients/service-notification/openapi.json+++ b/js/app/packages/service-clients/service-notification/openapi.json@@ -1473,6 +1473,7 @@"email_thread","team","call",+ "foreign_entity","static_file"]},diff --git a/js/app/packages/service-clients/service-search/generated/models/entityFilters.ts b/js/app/packages/service-clients/service-search/generated/models/entityFilters.tsindex bc0477fc1c..febec78bd6 100644--- a/js/app/packages/service-clients/service-search/generated/models/entityFilters.ts+++ b/js/app/packages/service-clients/service-search/generated/models/entityFilters.ts@@ -9,6 +9,7 @@ import type { ChannelFilters } from './channelFilters';import type { ChatFilters } from './chatFilters';import type { DocumentFilters } from './documentFilters';import type { EmailFilters } from './emailFilters';+import type { ForeignEntityFilters } from './foreignEntityFilters';import type { ProjectFilters } from './projectFilters';import type { PropertyFilter } from './propertyFilter';@@ -26,6 +27,8 @@ export interface EntityFilters {document_filters?: DocumentFilters;/** the bundled [EmailFilters] */email_filters?: EmailFilters;+ /** the bundled [ForeignEntityFilters] */+ foreign_entity_filters?: ForeignEntityFilters;/** the bundled [ProjectFilters] */project_filters?: ProjectFilters;/** property-based filters applied across entity types */diff --git a/js/app/packages/service-clients/service-search/generated/models/foreignEntityFilters.ts b/js/app/packages/service-clients/service-search/generated/models/foreignEntityFilters.tsnew file mode 100644index 0000000000..6d1bca274e--- /dev/null+++ b/js/app/packages/service-clients/service-search/generated/models/foreignEntityFilters.ts@@ -0,0 +1,18 @@+/**+ * Generated by orval v7.21.0 🍺+ * Do not edit manually.+ * search_service+ * OpenAPI spec version: 0.1.0+ */++/**+ * Filters for foreign entity records.+ */+export interface ForeignEntityFilters {+ /** External entity identifiers to filter by. Empty to include all external IDs. */+ foreign_entity_ids?: string[];+ /** External source names to filter by. Empty to include all sources. */+ foreign_entity_sources?: string[];+ /** Internal foreign entity record IDs to filter by. Empty to include all records. */+ ids?: string[];+}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 2cb13f4274..a689f918f8 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@@ -128,6 +128,7 @@ export * from './entityReferenceSpecificMessageId';export * from './entityType';export * from './errorResponse';export * from './fileType';+export * from './foreignEntityFilters';export * from './matchType';export * from './notificationFilters';export * from './notificationFiltersDone';diff --git a/js/app/packages/service-clients/service-search/openapi.json b/js/app/packages/service-clients/service-search/openapi.jsonindex a69779b6a2..075b9a40d0 100644--- a/js/app/packages/service-clients/service-search/openapi.json+++ b/js/app/packages/service-clients/service-search/openapi.json@@ -1452,6 +1452,10 @@"$ref": "#/components/schemas/EmailFilters","description": "the bundled [EmailFilters]"},+ "foreign_entity_filters": {+ "$ref": "#/components/schemas/ForeignEntityFilters",+ "description": "the bundled [ForeignEntityFilters]"+ },"project_filters": {"$ref": "#/components/schemas/ProjectFilters","description": "the bundled [ProjectFilters]"@@ -1936,6 +1940,33 @@"swf"]},+ "ForeignEntityFilters": {+ "type": "object",+ "description": "Filters for foreign entity records.",+ "properties": {+ "foreign_entity_ids": {+ "type": "array",+ "items": {+ "type": "string"+ },+ "description": "External entity identifiers to filter by. Empty to include all external IDs."+ },+ "foreign_entity_sources": {+ "type": "array",+ "items": {+ "type": "string"+ },+ "description": "External source names to filter by. Empty to include all sources."+ },+ "ids": {+ "type": "array",+ "items": {+ "type": "string"+ },+ "description": "Internal foreign entity record IDs to filter by. Empty to include all records."+ }+ }+ },"MatchType": {"type": "string","enum": ["exact", "partial", "regexp", "query"]diff --git a/js/app/packages/service-clients/service-storage/generated/schemas/apiEntityFilterAst.ts b/js/app/packages/service-clients/service-storage/generated/schemas/apiEntityFilterAst.tsindex 9064b5ed23..eeed1530cf 100644--- a/js/app/packages/service-clients/service-storage/generated/schemas/apiEntityFilterAst.ts+++ b/js/app/packages/service-clients/service-storage/generated/schemas/apiEntityFilterAst.ts@@ -29,6 +29,8 @@ tree only; CRM scope is carried by the `ecd` / `eca` siblingfields). On this endpoint the email filter stays a bare tree,unlike the materialized [`EntityFilterAst`] used for cursors. */ef?: unknown;+ /** the filters that should be applied to foreign entity records */+ fef?: unknown;/** the filters that should be applied to the project entity */pf?: unknown;/** the filters that should be applied based on entity properties */diff --git a/js/app/packages/service-clients/service-storage/generated/schemas/entityFilters.ts b/js/app/packages/service-clients/service-storage/generated/schemas/entityFilters.tsindex 7a6750b159..a9ef5fd6ed 100644--- a/js/app/packages/service-clients/service-storage/generated/schemas/entityFilters.ts+++ b/js/app/packages/service-clients/service-storage/generated/schemas/entityFilters.ts@@ -9,6 +9,7 @@ import type { ChannelFilters } from './channelFilters';import type { ChatFilters } from './chatFilters';import type { DocumentFilters } from './documentFilters';import type { EmailFilters } from './emailFilters';+import type { ForeignEntityFilters } from './foreignEntityFilters';import type { ProjectFilters } from './projectFilters';import type { PropertyFilter } from './propertyFilter';@@ -26,6 +27,8 @@ export interface EntityFilters {document_filters?: DocumentFilters;/** the bundled [EmailFilters] */email_filters?: EmailFilters;+ /** the bundled [ForeignEntityFilters] */+ foreign_entity_filters?: ForeignEntityFilters;/** the bundled [ProjectFilters] */project_filters?: ProjectFilters;/** property-based filters applied across entity types */diff --git a/js/app/packages/service-clients/service-storage/generated/schemas/foreignEntityFilters.ts b/js/app/packages/service-clients/service-storage/generated/schemas/foreignEntityFilters.tsnew file mode 100644index 0000000000..4af467c417--- /dev/null+++ b/js/app/packages/service-clients/service-storage/generated/schemas/foreignEntityFilters.ts@@ -0,0 +1,18 @@+/**+ * Generated by orval v7.21.0 🍺+ * Do not edit manually.+ * document_storage_service+ * OpenAPI spec version: 0.1.0+ */++/**+ * Filters for foreign entity records.+ */+export interface ForeignEntityFilters {+ /** External entity identifiers to filter by. Empty to include all external IDs. */+ foreign_entity_ids?: string[];+ /** External source names to filter by. Empty to include all sources. */+ foreign_entity_sources?: string[];+ /** Internal foreign entity record IDs to filter by. Empty to include all records. */+ ids?: string[];+}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 b7beeae6d1..8ede092e09 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@@ -428,6 +428,7 @@ export * from './fileTypeUpdate';export * from './fileTypeUpdateOneOf';export * from './folderItem';export * from './folderItemFileType';+export * from './foreignEntityFilters';export * from './genericErrorResponse';export * from './genericResponse';export * from './genericResponseMessage';@@ -750,6 +751,8 @@ export * from './soupEmailThreadPreviewSnippet';export * from './soupEmailThreadPreviewViewedAt';export * from './soupEnrichedEmailThreadPreview';export * from './soupEnrichedEmailThreadPreviewAllOf';+export * from './soupForeignEntity';+export * from './soupForeignEntityMetadata';export * from './soupItem';export * from './soupItemOneOf';export * from './soupItemOneOfFive';@@ -758,6 +761,8 @@ export * from './soupItemOneOfNine';export * from './soupItemOneOfNineTag';export * from './soupItemOneOfOneone';export * from './soupItemOneOfOneoneTag';+export * from './soupItemOneOfOnethree';+export * from './soupItemOneOfOnethreeTag';export * from './soupItemOneOfSeven';export * from './soupItemOneOfSevenTag';export * from './soupItemOneOfTag';diff --git a/js/app/packages/service-clients/service-storage/generated/schemas/soupForeignEntity.ts b/js/app/packages/service-clients/service-storage/generated/schemas/soupForeignEntity.tsnew file mode 100644index 0000000000..0968d42edb--- /dev/null+++ b/js/app/packages/service-clients/service-storage/generated/schemas/soupForeignEntity.ts@@ -0,0 +1,29 @@+/**+ * Generated by orval v7.21.0 🍺+ * Do not edit manually.+ * document_storage_service+ * OpenAPI spec version: 0.1.0+ */+import type { SoupForeignEntityMetadata } from './soupForeignEntityMetadata';++/**+ * A foreign entity record as displayed in Soup.+ */+export interface SoupForeignEntity {+ /** Timestamp when the record was created. */+ createdAt: string;+ /** Identifier assigned by the external system. */+ foreignEntityId: string;+ /** Source system that owns the external identifier. */+ foreignEntitySource: string;+ /** Internal primary key for this foreign entity record. */+ id: string;+ /** Arbitrary metadata stored with the mapping. */+ metadata: SoupForeignEntityMetadata;+ /** Internal auth entity namespace this foreign entity is stored for. */+ storedForAuthEntity: string;+ /** Internal entity identifier this foreign entity is stored for. */+ storedForId: string;+ /** Timestamp when the record was last updated. */+ updatedAt: string;+}diff --git a/js/app/packages/service-clients/service-storage/generated/schemas/soupForeignEntityMetadata.ts b/js/app/packages/service-clients/service-storage/generated/schemas/soupForeignEntityMetadata.tsnew file mode 100644index 0000000000..67880a1c76--- /dev/null+++ b/js/app/packages/service-clients/service-storage/generated/schemas/soupForeignEntityMetadata.ts@@ -0,0 +1,11 @@+/**+ * Generated by orval v7.21.0 🍺+ * Do not edit manually.+ * document_storage_service+ * OpenAPI spec version: 0.1.0+ */++/**+ * Arbitrary metadata stored with the mapping.+ */+export type SoupForeignEntityMetadata = { [key: string]: unknown };diff --git a/js/app/packages/service-clients/service-storage/generated/schemas/soupItem.ts b/js/app/packages/service-clients/service-storage/generated/schemas/soupItem.tsindex 7b325dd5dd..eb64aced21 100644--- a/js/app/packages/service-clients/service-storage/generated/schemas/soupItem.ts+++ b/js/app/packages/service-clients/service-storage/generated/schemas/soupItem.ts@@ -8,6 +8,7 @@ import type { SoupItemOneOf } from './soupItemOneOf';import type { SoupItemOneOfFive } from './soupItemOneOfFive';import type { SoupItemOneOfNine } from './soupItemOneOfNine';import type { SoupItemOneOfOneone } from './soupItemOneOfOneone';+import type { SoupItemOneOfOnethree } from './soupItemOneOfOnethree';import type { SoupItemOneOfSeven } from './soupItemOneOfSeven';import type { SoupItemOneOfThree } from './soupItemOneOfThree';@@ -17,4 +18,5 @@ export type SoupItem =| SoupItemOneOfFive| SoupItemOneOfSeven| SoupItemOneOfNine- | SoupItemOneOfOneone;+ | SoupItemOneOfOneone+ | SoupItemOneOfOnethree;diff --git a/js/app/packages/service-clients/service-storage/generated/schemas/soupItemOneOfOnethree.ts b/js/app/packages/service-clients/service-storage/generated/schemas/soupItemOneOfOnethree.tsnew file mode 100644index 0000000000..21ae77a21d--- /dev/null+++ b/js/app/packages/service-clients/service-storage/generated/schemas/soupItemOneOfOnethree.ts@@ -0,0 +1,13 @@+/**+ * Generated by orval v7.21.0 🍺+ * Do not edit manually.+ * document_storage_service+ * OpenAPI spec version: 0.1.0+ */+import type { SoupForeignEntity } from './soupForeignEntity';+import type { SoupItemOneOfOnethreeTag } from './soupItemOneOfOnethreeTag';++export type SoupItemOneOfOnethree = {+ data: SoupForeignEntity;+ tag: SoupItemOneOfOnethreeTag;+};diff --git a/js/app/packages/service-clients/service-storage/generated/schemas/soupItemOneOfOnethreeTag.ts b/js/app/packages/service-clients/service-storage/generated/schemas/soupItemOneOfOnethreeTag.tsnew file mode 100644index 0000000000..4380bddfd2--- /dev/null+++ b/js/app/packages/service-clients/service-storage/generated/schemas/soupItemOneOfOnethreeTag.ts@@ -0,0 +1,14 @@+/**+ * Generated by orval v7.21.0 🍺+ * Do not edit manually.+ * document_storage_service+ * OpenAPI spec version: 0.1.0+ */++export type SoupItemOneOfOnethreeTag =+ (typeof SoupItemOneOfOnethreeTag)[keyof typeof SoupItemOneOfOnethreeTag];++// eslint-disable-next-line @typescript-eslint/no-redeclare+export const SoupItemOneOfOnethreeTag = {+ foreignEntity: 'foreignEntity',+} as const;diff --git a/js/app/packages/service-clients/service-storage/generated/zod.ts b/js/app/packages/service-clients/service-storage/generated/zod.tsindex d9896dee5a..1c9eb17df5 100644--- a/js/app/packages/service-clients/service-storage/generated/zod.ts+++ b/js/app/packages/service-clients/service-storage/generated/zod.ts@@ -6303,6 +6303,43 @@ export const getItemsSoupResponse = zod.object({),tag: zod.enum(['call']),}),+ zod.object({+ data: zod+ .object({+ createdAt: zod.iso+ .datetime({})+ .describe('Timestamp when the record was created.'),+ foreignEntityId: zod+ .string()+ .describe('Identifier assigned by the external system.'),+ foreignEntitySource: zod+ .string()+ .describe('Source system that owns the external identifier.'),+ id: zod+ .uuid()+ .describe(+ 'Internal primary key for this foreign entity record.'+ ),+ metadata: zod+ .object({})+ .describe('Arbitrary metadata stored with the mapping.'),+ storedForAuthEntity: zod+ .string()+ .describe(+ 'Internal auth entity namespace this foreign entity is stored for.'+ ),+ storedForId: zod+ .string()+ .describe(+ 'Internal entity identifier this foreign entity is stored for.'+ ),+ updatedAt: zod.iso+ .datetime({})+ .describe('Timestamp when the record was last updated.'),+ })+ .describe('A foreign entity record as displayed in Soup.'),+ tag: zod.enum(['foreignEntity']),+ }),]).and(zod.object({@@ -6656,6 +6693,29 @@ export const postItemsSoupBody = zod.describe('The email filters used to filter down what emails you search over.'),+ foreign_entity_filters: zod+ .object({+ foreign_entity_ids: zod+ .array(zod.string())+ .optional()+ .describe(+ 'External entity identifiers to filter by. Empty to include all external IDs.'+ ),+ foreign_entity_sources: zod+ .array(zod.string())+ .optional()+ .describe(+ 'External source names to filter by. Empty to include all sources.'+ ),+ ids: zod+ .array(zod.string())+ .optional()+ .describe(+ 'Internal foreign entity record IDs to filter by. Empty to include all records.'+ ),+ })+ .optional()+ .describe('Filters for foreign entity records.'),project_filters: zod.object({importance: zod@@ -8006,6 +8066,43 @@ export const postItemsSoupResponse = zod.object({),tag: zod.enum(['call']),}),+ zod.object({+ data: zod+ .object({+ createdAt: zod.iso+ .datetime({})+ .describe('Timestamp when the record was created.'),+ foreignEntityId: zod+ .string()+ .describe('Identifier assigned by the external system.'),+ foreignEntitySource: zod+ .string()+ .describe('Source system that owns the external identifier.'),+ id: zod+ .uuid()+ .describe(+ 'Internal primary key for this foreign entity record.'+ ),+ metadata: zod+ .object({})+ .describe('Arbitrary metadata stored with the mapping.'),+ storedForAuthEntity: zod+ .string()+ .describe(+ 'Internal auth entity namespace this foreign entity is stored for.'+ ),+ storedForId: zod+ .string()+ .describe(+ 'Internal entity identifier this foreign entity is stored for.'+ ),+ updatedAt: zod.iso+ .datetime({})+ .describe('Timestamp when the record was last updated.'),+ })+ .describe('A foreign entity record as displayed in Soup.'),+ tag: zod.enum(['foreignEntity']),+ }),]).and(zod.object({@@ -8061,6 +8158,10 @@ export const postItemsSoupAstBody = zod.describe('the filters that should be applied to the email entity (raw AST\ntree only; CRM scope is carried by the `ecd` \/ `eca` sibling\nfields). On this endpoint the email filter stays a bare tree,\nunlike the materialized [`EntityFilterAst`] used for cursors.'),+ fef: zod+ .unknown()+ .optional()+ .describe('the filters that should be applied to foreign entity records'),pf: zod.unknown().optional()@@ -9340,6 +9441,43 @@ export const postItemsSoupAstResponse = zod.object({),tag: zod.enum(['call']),}),+ zod.object({+ data: zod+ .object({+ createdAt: zod.iso+ .datetime({})+ .describe('Timestamp when the record was created.'),+ foreignEntityId: zod+ .string()+ .describe('Identifier assigned by the external system.'),+ foreignEntitySource: zod+ .string()+ .describe('Source system that owns the external identifier.'),+ id: zod+ .uuid()+ .describe(+ 'Internal primary key for this foreign entity record.'+ ),+ metadata: zod+ .object({})+ .describe('Arbitrary metadata stored with the mapping.'),+ storedForAuthEntity: zod+ .string()+ .describe(+ 'Internal auth entity namespace this foreign entity is stored for.'+ ),+ storedForId: zod+ .string()+ .describe(+ 'Internal entity identifier this foreign entity is stored for.'+ ),+ updatedAt: zod.iso+ .datetime({})+ .describe('Timestamp when the record was last updated.'),+ })+ .describe('A foreign entity record as displayed in Soup.'),+ tag: zod.enum(['foreignEntity']),+ }),]).and(zod.object({diff --git a/js/app/packages/service-clients/service-storage/openapi.json b/js/app/packages/service-clients/service-storage/openapi.jsonindex 96975b42d3..8392478f1f 100644--- a/js/app/packages/service-clients/service-storage/openapi.json+++ b/js/app/packages/service-clients/service-storage/openapi.json@@ -8474,6 +8474,9 @@"ef": {"description": "the filters that should be applied to the email entity (raw AST\ntree only; CRM scope is carried by the `ecd` / `eca` sibling\nfields). On this endpoint the email filter stays a bare tree,\nunlike the materialized [`EntityFilterAst`] used for cursors."},+ "fef": {+ "description": "the filters that should be applied to foreign entity records"+ },"pf": {"description": "the filters that should be applied to the project entity"},@@ -11263,6 +11266,10 @@"$ref": "#/components/schemas/EmailFilters","description": "the bundled [EmailFilters]"},+ "foreign_entity_filters": {+ "$ref": "#/components/schemas/ForeignEntityFilters",+ "description": "the bundled [ForeignEntityFilters]"+ },"project_filters": {"$ref": "#/components/schemas/ProjectFilters","description": "the bundled [ProjectFilters]"@@ -11957,6 +11964,33 @@}}},+ "ForeignEntityFilters": {+ "type": "object",+ "description": "Filters for foreign entity records.",+ "properties": {+ "foreign_entity_ids": {+ "type": "array",+ "items": {+ "type": "string"+ },+ "description": "External entity identifiers to filter by. Empty to include all external IDs."+ },+ "foreign_entity_sources": {+ "type": "array",+ "items": {+ "type": "string"+ },+ "description": "External source names to filter by. Empty to include all sources."+ },+ "ids": {+ "type": "array",+ "items": {+ "type": "string"+ },+ "description": "Internal foreign entity record IDs to filter by. Empty to include all records."+ }+ }+ },"GenericErrorResponse": {"type": "object","required": ["error", "message"],@@ -15008,6 +15042,57 @@}]},+ "SoupForeignEntity": {+ "type": "object",+ "description": "A foreign entity record as displayed in Soup.",+ "required": [+ "id",+ "foreignEntityId",+ "foreignEntitySource",+ "metadata",+ "storedForId",+ "storedForAuthEntity",+ "createdAt",+ "updatedAt"+ ],+ "properties": {+ "createdAt": {+ "type": "string",+ "format": "date-time",+ "description": "Timestamp when the record was created."+ },+ "foreignEntityId": {+ "type": "string",+ "description": "Identifier assigned by the external system."+ },+ "foreignEntitySource": {+ "type": "string",+ "description": "Source system that owns the external identifier."+ },+ "id": {+ "type": "string",+ "format": "uuid",+ "description": "Internal primary key for this foreign entity record."+ },+ "metadata": {+ "type": "object",+ "description": "Arbitrary metadata stored with the mapping."+ },+ "storedForAuthEntity": {+ "type": "string",+ "description": "Internal auth entity namespace this foreign entity is stored for."+ },+ "storedForId": {+ "type": "string",+ "description": "Internal entity identifier this foreign entity is stored for."+ },+ "updatedAt": {+ "type": "string",+ "format": "date-time",+ "description": "Timestamp when the record was last updated."+ }+ }+ },"SoupItem": {"oneOf": [{@@ -15087,6 +15172,19 @@"enum": ["call"]}}+ },+ {+ "type": "object",+ "required": ["data", "tag"],+ "properties": {+ "data": {+ "$ref": "#/components/schemas/SoupForeignEntity"+ },+ "tag": {+ "type": "string",+ "enum": ["foreignEntity"]+ }+ }}]},diff --git a/rust/cloud-storage/.sqlx/query-1174bf6390d826cba31f55507174a5685ec293663d6c1418b3fad3a07d26c08a.json b/rust/cloud-storage/.sqlx/query-1174bf6390d826cba31f55507174a5685ec293663d6c1418b3fad3a07d26c08a.jsonnew file mode 100644index 0000000000..e34e1c8fed--- /dev/null+++ b/rust/cloud-storage/.sqlx/query-1174bf6390d826cba31f55507174a5685ec293663d6c1418b3fad3a07d26c08a.json@@ -0,0 +1,70 @@+{+ "db_name": "PostgreSQL",+ "query": "\n WITH source_ids AS (\n SELECT DISTINCT stored_for_id, stored_for_auth_entity\n FROM UNNEST($1::text[], $2::text[])\n AS source_rows(stored_for_id, stored_for_auth_entity)\n ),\n deduped AS (\n SELECT DISTINCT ON (fe.foreign_entity_source, fe.foreign_entity_id)\n fe.id,\n fe.foreign_entity_id,\n fe.foreign_entity_source,\n fe.metadata,\n fe.stored_for_id,\n fe.stored_for_auth_entity,\n fe.created_at,\n fe.updated_at,\n CASE $3::text\n WHEN 'created_at' THEN fe.created_at\n ELSE fe.updated_at\n END AS sort_at\n FROM foreign_entity fe\n WHERE EXISTS (\n SELECT 1\n FROM source_ids s\n WHERE s.stored_for_id = fe.stored_for_id\n AND s.stored_for_auth_entity = fe.stored_for_auth_entity\n )\n AND (\n $4::text IS NULL\n OR jsonb_path_match(\n jsonb_build_object(\n 'id', fe.id::text,\n 'foreignEntityId', fe.foreign_entity_id,\n 'foreignEntitySource', fe.foreign_entity_source\n ),\n ($4::text)::jsonpath\n )\n )\n ORDER BY fe.foreign_entity_source, fe.foreign_entity_id, sort_at DESC, fe.id DESC\n )\n SELECT\n id as \"id!: Uuid\",\n foreign_entity_id as \"foreign_entity_id!: String\",\n foreign_entity_source as \"foreign_entity_source!: String\",\n metadata as \"metadata!: serde_json::Value\",\n stored_for_id as \"stored_for_id!: String\",\n stored_for_auth_entity as \"stored_for_auth_entity!: String\",\n created_at as \"created_at!: DateTime<Utc>\",\n updated_at as \"updated_at!: DateTime<Utc>\"\n FROM deduped\n WHERE $5::timestamptz IS NULL\n OR (sort_at, id) < ($5::timestamptz, $6::uuid)\n ORDER BY sort_at DESC, id DESC\n LIMIT $7\n ",+ "describe": {+ "columns": [+ {+ "ordinal": 0,+ "name": "id!: Uuid",+ "type_info": "Uuid"+ },+ {+ "ordinal": 1,+ "name": "foreign_entity_id!: String",+ "type_info": "Text"+ },+ {+ "ordinal": 2,+ "name": "foreign_entity_source!: String",+ "type_info": "Text"+ },+ {+ "ordinal": 3,+ "name": "metadata!: serde_json::Value",+ "type_info": "Jsonb"+ },+ {+ "ordinal": 4,+ "name": "stored_for_id!: String",+ "type_info": "Text"+ },+ {+ "ordinal": 5,+ "name": "stored_for_auth_entity!: String",+ "type_info": "Text"+ },+ {+ "ordinal": 6,+ "name": "created_at!: DateTime<Utc>",+ "type_info": "Timestamptz"+ },+ {+ "ordinal": 7,+ "name": "updated_at!: DateTime<Utc>",+ "type_info": "Timestamptz"+ }+ ],+ "parameters": {+ "Left": [+ "TextArray",+ "TextArray",+ "Text",+ "Text",+ "Timestamptz",+ "Uuid",+ "Int8"+ ]+ },+ "nullable": [+ false,+ false,+ false,+ false,+ false,+ false,+ false,+ false+ ]+ },+ "hash": "1174bf6390d826cba31f55507174a5685ec293663d6c1418b3fad3a07d26c08a"+}diff --git a/rust/cloud-storage/.sqlx/query-1daa88e349f8067e35be783a31260caad8711fe6793f600a90599f9f84a783b1.json b/rust/cloud-storage/.sqlx/query-1daa88e349f8067e35be783a31260caad8711fe6793f600a90599f9f84a783b1.jsonnew file mode 100644index 0000000000..ee321949b6--- /dev/null+++ b/rust/cloud-storage/.sqlx/query-1daa88e349f8067e35be783a31260caad8711fe6793f600a90599f9f84a783b1.json@@ -0,0 +1,22 @@+{+ "db_name": "PostgreSQL",+ "query": "\n SELECT COUNT(*) as \"persisted_count!\"\n FROM foreign_entity\n WHERE id = $1\n ",+ "describe": {+ "columns": [+ {+ "ordinal": 0,+ "name": "persisted_count!",+ "type_info": "Int8"+ }+ ],+ "parameters": {+ "Left": [+ "Uuid"+ ]+ },+ "nullable": [+ null+ ]+ },+ "hash": "1daa88e349f8067e35be783a31260caad8711fe6793f600a90599f9f84a783b1"+}diff --git a/rust/cloud-storage/.sqlx/query-280b524fe0ce00b66ee0adb59a63d54749a76b03fc7006ea64270c34763f605f.json b/rust/cloud-storage/.sqlx/query-280b524fe0ce00b66ee0adb59a63d54749a76b03fc7006ea64270c34763f605f.jsonnew file mode 100644index 0000000000..ba7824ec45--- /dev/null+++ b/rust/cloud-storage/.sqlx/query-280b524fe0ce00b66ee0adb59a63d54749a76b03fc7006ea64270c34763f605f.json@@ -0,0 +1,16 @@+{+ "db_name": "PostgreSQL",+ "query": "\n UPDATE foreign_entity\n SET created_at = $2, updated_at = $3\n WHERE id = $1\n ",+ "describe": {+ "columns": [],+ "parameters": {+ "Left": [+ "Uuid",+ "Timestamptz",+ "Timestamptz"+ ]+ },+ "nullable": []+ },+ "hash": "280b524fe0ce00b66ee0adb59a63d54749a76b03fc7006ea64270c34763f605f"+}diff --git a/rust/cloud-storage/.sqlx/query-308c21dbdc26bcddf5343fb06b4903989ff52fa3ac924017c0bd5a50e0640134.json b/rust/cloud-storage/.sqlx/query-308c21dbdc26bcddf5343fb06b4903989ff52fa3ac924017c0bd5a50e0640134.jsonnew file mode 100644index 0000000000..d110de19dc--- /dev/null+++ b/rust/cloud-storage/.sqlx/query-308c21dbdc26bcddf5343fb06b4903989ff52fa3ac924017c0bd5a50e0640134.json@@ -0,0 +1,22 @@+{+ "db_name": "PostgreSQL",+ "query": "SELECT id FROM in_progress_user_link WHERE id = $1",+ "describe": {+ "columns": [+ {+ "ordinal": 0,+ "name": "id",+ "type_info": "Uuid"+ }+ ],+ "parameters": {+ "Left": [+ "Uuid"+ ]+ },+ "nullable": [+ false+ ]+ },+ "hash": "308c21dbdc26bcddf5343fb06b4903989ff52fa3ac924017c0bd5a50e0640134"+}diff --git a/rust/cloud-storage/.sqlx/query-68ba7cb71623522b89eee53109b6c6030fa4b339e95d3965b2ea4e447054673e.json b/rust/cloud-storage/.sqlx/query-68ba7cb71623522b89eee53109b6c6030fa4b339e95d3965b2ea4e447054673e.jsonnew file mode 100644index 0000000000..ecd353f8c0--- /dev/null+++ b/rust/cloud-storage/.sqlx/query-68ba7cb71623522b89eee53109b6c6030fa4b339e95d3965b2ea4e447054673e.json@@ -0,0 +1,14 @@+{+ "db_name": "PostgreSQL",+ "query": "\n UPDATE foreign_entity\n SET updated_at = NOW() - INTERVAL '1 hour'\n WHERE id = $1\n ",+ "describe": {+ "columns": [],+ "parameters": {+ "Left": [+ "Uuid"+ ]+ },+ "nullable": []+ },+ "hash": "68ba7cb71623522b89eee53109b6c6030fa4b339e95d3965b2ea4e447054673e"+}diff --git a/rust/cloud-storage/.sqlx/query-a070af6b64aa1575ea0583b7c47d0a31db822d1ae1b471387b335f416f8ee095.json b/rust/cloud-storage/.sqlx/query-a070af6b64aa1575ea0583b7c47d0a31db822d1ae1b471387b335f416f8ee095.jsonnew file mode 100644index 0000000000..9ee6143607--- /dev/null+++ b/rust/cloud-storage/.sqlx/query-a070af6b64aa1575ea0583b7c47d0a31db822d1ae1b471387b335f416f8ee095.json@@ -0,0 +1,22 @@+{+ "db_name": "PostgreSQL",+ "query": "SELECT id FROM github_links WHERE id = $1",+ "describe": {+ "columns": [+ {+ "ordinal": 0,+ "name": "id",+ "type_info": "Uuid"+ }+ ],+ "parameters": {+ "Left": [+ "Uuid"+ ]+ },+ "nullable": [+ false+ ]+ },+ "hash": "a070af6b64aa1575ea0583b7c47d0a31db822d1ae1b471387b335f416f8ee095"+}diff --git a/rust/cloud-storage/Cargo.lock b/rust/cloud-storage/Cargo.lockindex ef267c6289..20e5aa0434 100644--- a/rust/cloud-storage/Cargo.lock+++ b/rust/cloud-storage/Cargo.lock@@ -115,6 +115,7 @@ dependencies = ["email_service_client","entity_access","entity_access_management",+ "foreign_entity","frecency","futures","item_filters",@@ -3335,6 +3336,7 @@ dependencies = ["email_service_client","entity_access","entity_access_management",+ "foreign_entity","frecency","futures","http 1.4.0",@@ -4459,8 +4461,11 @@ version = "0.1.0"dependencies = ["anyhow","chrono",+ "filter_ast",+ "item_filters","macro_db_migrator","macro_uuid",+ "models_pagination","serde","serde_json","sqlx",@@ -6781,6 +6786,7 @@ dependencies = ["email_service_client","entity_access","entity_access_management",+ "foreign_entity","frecency","fusionauth","http 1.4.0",@@ -6855,6 +6861,7 @@ dependencies = ["email_service_client","entity_access","entity_access_management",+ "foreign_entity","frecency","futures","lexical_client",@@ -7285,6 +7292,7 @@ dependencies = ["models_pagination","models_properties","serde",+ "serde_json","strum","utoipa","uuid",@@ -10842,6 +10850,7 @@ dependencies = ["email","entity_access","filter_ast",+ "foreign_entity","frecency","futures","http-body-util",diff --git a/rust/cloud-storage/ai_tools/Cargo.toml b/rust/cloud-storage/ai_tools/Cargo.tomlindex 297eaa612d..95e8811ed4 100644--- a/rust/cloud-storage/ai_tools/Cargo.toml+++ b/rust/cloud-storage/ai_tools/Cargo.toml@@ -32,6 +32,7 @@ email = { path = "../email", features = ["ai_schema", "ai_tools", "axum", "outboemail_service_client = { path = "../email_service_client" }entity_access = { path = "../entity_access" }entity_access_management = { path = "../entity_access_management" }+foreign_entity = { path = "../foreign_entity" }frecency = { path = "../frecency", features = ["outbound", "postgres"] }futures.workspace = trueitem_filters = { path = "../item_filters" }diff --git a/rust/cloud-storage/ai_tools/src/build_context.rs b/rust/cloud-storage/ai_tools/src/build_context.rsindex 1f96b5b966..41d091ba17 100644--- a/rust/cloud-storage/ai_tools/src/build_context.rs+++ b/rust/cloud-storage/ai_tools/src/build_context.rs@@ -23,6 +23,10 @@ use email::outbound::EmailPgRepo;use email_service_client::EmailServiceClientExternal;use entity_access::domain::service::EntityAccessServiceImpl;use entity_access::outbound::PgAccessRepository;+use foreign_entity::{+ domain::service::ForeignEntityServiceImpl,+ outbound::pg_foreign_entity_repo::PgForeignEntityRepo,+};use frecency::domain::services::FrecencyQueryServiceImpl;use frecency::outbound::postgres::FrecencyPgStorage;use lexical_client::LexicalClient;@@ -168,12 +172,15 @@ pub async fn build_tool_service_context_from_env(let channel_tool_context = crate::tool_context::build_channel_tool_context(pool.clone());let email_service_for_tools: Arc<crate::tool_context::ToolEmailService> =Arc::new(email_service.clone());+ let foreign_entity_service =+ ForeignEntityServiceImpl::new(PgForeignEntityRepo::new(pool.clone()));let soup_service = Arc::new(SoupImpl::new(PgSoupRepo::new(ReadOnlyPool(pool.clone())),frecency_service,ReadonlyEmailPreviewAdapter(email_service),channels_service,call::domain::ports::NoOpCallRecordQueryService,+ foreign_entity_service,));let s3_client = macro_aws_config::s3_client().await;diff --git a/rust/cloud-storage/ai_tools/src/lib.rs b/rust/cloud-storage/ai_tools/src/lib.rsindex 438c960272..50e9a188bf 100644--- a/rust/cloud-storage/ai_tools/src/lib.rs+++ b/rust/cloud-storage/ai_tools/src/lib.rs@@ -38,7 +38,7 @@ pub use tool_context::{ToolChannelMessagesService, ToolChannelToolContext, ToolChatService, ToolChatToolContext,ToolCommsService, ToolDocumentService, ToolDocumentToolContext, ToolEmailService,ToolEmailToolContext, ToolEntityAccessManagementService, ToolEntityAccessService,- ToolFrecencyService, ToolNotificationQueue, ToolNotificationService,+ ToolForeignEntityService, ToolFrecencyService, ToolNotificationQueue, ToolNotificationService,ToolNotificationToolContext, ToolPropertiesService, ToolPropertiesToolContext,ToolServiceContext, ToolSoupService, ToolSystemPropertiesService, ToolTeamService,ToolTeamToolContext, ToolUserEmailService, build_channel_tool_context,diff --git a/rust/cloud-storage/ai_tools/src/tool_context.rs b/rust/cloud-storage/ai_tools/src/tool_context.rsindex a545406128..8d325b86ed 100644--- a/rust/cloud-storage/ai_tools/src/tool_context.rs+++ b/rust/cloud-storage/ai_tools/src/tool_context.rs@@ -17,6 +17,10 @@ use documents::{domain::ports::TaskPropertiesPort, inbound::toolset::DocumentToouse email::{domain::service::EmailServiceImpl, inbound::toolset::EmailToolContext, outbound::EmailPgRepo,};+use foreign_entity::{+ domain::service::ForeignEntityServiceImpl,+ outbound::pg_foreign_entity_repo::PgForeignEntityRepo,+};use macro_user_id::user_id::MacroUserIdStr;use notification::inbound::ai_tool::NotificationToolContext;use properties::inbound::toolset::PropertiesToolContext;@@ -428,6 +432,9 @@ pub type ToolEntityAccessService = entity_access::domain::service::EntityAccessSpub type ToolDocumentToolContext =DocumentToolContext<ToolDocumentService, ToolEntityAccessService>;+/// Type alias for the foreign entity service implementation used by AI tools.+pub type ToolForeignEntityService = ForeignEntityServiceImpl<PgForeignEntityRepo>;+/// Type alias for the soup service implementationpub type ToolSoupService = SoupImpl<soup::outbound::pg_soup_repo::PgSoupRepo,@@ -435,6 +442,7 @@ pub type ToolSoupService = SoupImpl<email::domain::ports::ReadonlyEmailPreviewAdapter<ToolEmailService>,ToolCommsService,call::domain::ports::NoOpCallRecordQueryService,+ ToolForeignEntityService,>;/// No-op notification service for properties (tools don't send assignment notifications)diff --git a/rust/cloud-storage/document_cognition_service/Cargo.toml b/rust/cloud-storage/document_cognition_service/Cargo.tomlindex 67f316c6ad..40a9a54231 100644--- a/rust/cloud-storage/document_cognition_service/Cargo.toml+++ b/rust/cloud-storage/document_cognition_service/Cargo.toml@@ -54,6 +54,7 @@ email = { path = "../email", features = ["outbound", "attachment"] }email_service_client = { path = "../email_service_client" }entity_access = { path = "../entity_access" }entity_access_management = { path = "../entity_access_management" }+foreign_entity = { path = "../foreign_entity" }frecency = { path = "../frecency", features = ["outbound", "postgres"] }futures = { workspace = true }http = { workspace = true }diff --git a/rust/cloud-storage/document_cognition_service/src/api/context/test.rs b/rust/cloud-storage/document_cognition_service/src/api/context/test.rsindex d40cbcdef6..6cd5ae4c24 100644--- a/rust/cloud-storage/document_cognition_service/src/api/context/test.rs+++ b/rust/cloud-storage/document_cognition_service/src/api/context/test.rs@@ -117,6 +117,10 @@ pub async fn test_api_context(pool: sqlx::Pool<sqlx::Postgres>) -> std::sync::Aruse email::domain::service::EmailServiceImpl;use email::outbound::EmailPgRepo;use email_service_client::{EmailServiceClient, EmailServiceClientExternal};+ use foreign_entity::{+ domain::service::ForeignEntityServiceImpl,+ outbound::pg_foreign_entity_repo::PgForeignEntityRepo,+ };use frecency::domain::services::FrecencyQueryServiceImpl;use frecency::outbound::postgres::FrecencyPgStorage;use lexical_client::LexicalClient;@@ -177,12 +181,15 @@ pub async fn test_api_context(pool: sqlx::Pool<sqlx::Postgres>) -> std::sync::Arfrecency_storage,);let email_service_for_tools: Arc<ai_tools::ToolEmailService> = Arc::new(email_service.clone());+ let foreign_entity_service =+ ForeignEntityServiceImpl::new(PgForeignEntityRepo::new(pool.clone()));let soup_service = Arc::new(SoupImpl::new(PgSoupRepo::new(readonly_pool::ReadOnlyPool(pool.clone())),frecency_service,ReadonlyEmailPreviewAdapter(email_service),channels_service,call::domain::ports::NoOpCallRecordQueryService,+ foreign_entity_service,));let ingress_queue = SqsQueue::new(diff --git a/rust/cloud-storage/document_cognition_service/src/main.rs b/rust/cloud-storage/document_cognition_service/src/main.rsindex e585485f2a..be2d82624d 100644--- a/rust/cloud-storage/document_cognition_service/src/main.rs+++ b/rust/cloud-storage/document_cognition_service/src/main.rs@@ -22,6 +22,10 @@ use email::domain::service::EmailServiceImpl;use email::outbound::EmailPgRepo;use email_service_client::{EmailServiceClient, EmailServiceClientExternal};use entity_access::{domain::service::EntityAccessServiceImpl, outbound::PgAccessRepository};+use foreign_entity::{+ domain::service::ForeignEntityServiceImpl,+ outbound::pg_foreign_entity_repo::PgForeignEntityRepo,+};use frecency::domain::services::FrecencyQueryServiceImpl;use frecency::outbound::postgres::FrecencyPgStorage;use macro_auth::middleware::decode_jwt::JwtValidationArgs;@@ -217,12 +221,15 @@ async fn main() -> anyhow::Result<()> {frecency_storage,);let email_service_for_tools: Arc<ai_tools::ToolEmailService> = Arc::new(email_service.clone());+ let foreign_entity_service =+ ForeignEntityServiceImpl::new(PgForeignEntityRepo::new(db.clone()));let soup_service = Arc::new(soup::domain::service::SoupImpl::new(soup::outbound::pg_soup_repo::PgSoupRepo::new(ReadOnlyPool(db.clone())),frecency_service,ReadonlyEmailPreviewAdapter(email_service),channels_service,call::domain::ports::NoOpCallRecordQueryService,+ foreign_entity_service,));tracing::info!("initialized soup service");diff --git a/rust/cloud-storage/document_storage_service/src/api/context.rs b/rust/cloud-storage/document_storage_service/src/api/context.rsindex 171c260a54..3f39fb1e66 100644--- a/rust/cloud-storage/document_storage_service/src/api/context.rs+++ b/rust/cloud-storage/document_storage_service/src/api/context.rs@@ -111,6 +111,7 @@ type DssSoupState = SoupRouterState<ReadonlyEmailPreviewAdapter<DssEmailService>,CommsChannelServiceImpl<PgCommsRepo, PgUserRepo, FrecencyPgStorage>,call::domain::service::CallRecordQueryServiceImpl<call::outbound::pg_call_repo::PgCallRepo>,+ ForeignEntityServiceType,>,DssEmailService,EntityAccessService,diff --git a/rust/cloud-storage/document_storage_service/src/api/swagger.rs b/rust/cloud-storage/document_storage_service/src/api/swagger.rsindex 5e0f34323c..28cb209be5 100644--- a/rust/cloud-storage/document_storage_service/src/api/swagger.rs+++ b/rust/cloud-storage/document_storage_service/src/api/swagger.rs@@ -117,6 +117,7 @@ use models_soup::email_thread::{SoupAttachment, SoupContact, SoupEmailThreadPreview, SoupEnrichedEmailThreadPreview, SoupLabel,SoupLabelListVisibility, SoupLabelType, SoupMessageListVisibility,};+use models_soup::foreign_entity::SoupForeignEntity;use models_soup::item::SoupItem;use models_soup::project::SoupProject;use soup::inbound::axum_router::{PostSoupRequest, SoupApiItem, SoupApiSort, SoupPage};@@ -360,6 +361,7 @@ use utoipa::OpenApi;SoupDocument,SoupChat,SoupProject,+ SoupForeignEntity,SoupApiSort,SoupPage,SoupEnrichedEmailThreadPreview,diff --git a/rust/cloud-storage/document_storage_service/src/main.rs b/rust/cloud-storage/document_storage_service/src/main.rsindex 5e8f1ea4ec..0569cf4587 100644--- a/rust/cloud-storage/document_storage_service/src/main.rs+++ b/rust/cloud-storage/document_storage_service/src/main.rs@@ -558,6 +558,8 @@ async fn main() -> anyhow::Result<()> {let call_record_query_service = call::domain::service::CallRecordQueryServiceImpl::new(PgCallRepo::new(readonly_db.clone()),);+ let foreign_entity_service_for_soup =+ ForeignEntityServiceImpl::new(PgForeignEntityRepo::new(readonly_db.clone()));let sqs_client = Arc::new(sqs_client);let conn_gateway_client = Arc::new(conn_gateway_client);@@ -584,6 +586,7 @@ async fn main() -> anyhow::Result<()> {readonly_email_service,channel_service_for_soup,call_record_query_service,+ foreign_entity_service_for_soup,),email_service,entity_access_service.clone(),diff --git a/rust/cloud-storage/entity_access/src/domain/service.rs b/rust/cloud-storage/entity_access/src/domain/service.rsindex 5fc5877169..e0cc0b7e37 100644--- a/rust/cloud-storage/entity_access/src/domain/service.rs+++ b/rust/cloud-storage/entity_access/src/domain/service.rs@@ -142,7 +142,7 @@ where// Static files are always viewable. This is wrong for ownersEntityType::StaticFile => Ok(Some(AccessLevel::View)),// These entity types don't have access checks implemented yet.- EntityType::Team | EntityType::User => Ok(None),+ EntityType::ForeignEntity | EntityType::Team | EntityType::User => Ok(None),}}diff --git a/rust/cloud-storage/entity_access_db_utils/src/lib.rs b/rust/cloud-storage/entity_access_db_utils/src/lib.rsindex 3d74967612..dd50071810 100644--- a/rust/cloud-storage/entity_access_db_utils/src/lib.rs+++ b/rust/cloud-storage/entity_access_db_utils/src/lib.rs@@ -220,7 +220,11 @@ pub async fn update_entity_access_channel_share_permissions(// We need to remove all required items from entity_access for the given entity id for all channelsif !remove_channel_ids.is_empty() {match entity_type {- EntityType::User | EntityType::Team | EntityType::Channel | EntityType::StaticFile => {+ EntityType::User+ | EntityType::Team+ | EntityType::Channel+ | EntityType::StaticFile+ | EntityType::ForeignEntity => {unreachable!()}EntityType::Project => {@@ -275,7 +279,11 @@ pub async fn update_entity_access_channel_share_permissions(// We need to upsert all required items into entity_access for all channels with the desired access levelif !upsert_channel_ids.is_empty() {match entity_type {- EntityType::User | EntityType::Team | EntityType::Channel | EntityType::StaticFile => {+ EntityType::User+ | EntityType::Team+ | EntityType::Channel+ | EntityType::StaticFile+ | EntityType::ForeignEntity => {unreachable!()}EntityType::Project => {diff --git a/rust/cloud-storage/foreign_entity/Cargo.toml b/rust/cloud-storage/foreign_entity/Cargo.tomlindex 303fd40d05..26862e0354 100644--- a/rust/cloud-storage/foreign_entity/Cargo.toml+++ b/rust/cloud-storage/foreign_entity/Cargo.toml@@ -6,14 +6,17 @@ version = "0.1.0"[features]default = ["outbound", "ports", "service"]-outbound = ["dep:sqlx", "ports"]-ports = ["dep:tokio"]+outbound = ["dep:filter_ast", "dep:sqlx", "ports"]+ports = ["dep:item_filters", "dep:models_pagination", "dep:tokio"]service = ["ports"][dependencies]anyhow = { workspace = true }chrono = { workspace = true }+filter_ast = { path = "../filter_ast", optional = true }+item_filters = { path = "../item_filters", optional = true }macro_uuid = { path = "../macro_uuid" }+models_pagination = { path = "../models_pagination", optional = true }serde = { workspace = true }serde_json = { workspace = true }sqlx = { workspace = true, optional = true }diff --git a/rust/cloud-storage/foreign_entity/src/domain/models.rs b/rust/cloud-storage/foreign_entity/src/domain/models.rsindex 2b4813f4ba..8df5009955 100644--- a/rust/cloud-storage/foreign_entity/src/domain/models.rs+++ b/rust/cloud-storage/foreign_entity/src/domain/models.rs@@ -4,6 +4,41 @@ use chrono::{DateTime, Utc};use serde_json::Value;use uuid::Uuid;+/// Identifies an internal source that can grant access to foreign entities.+#[derive(serde::Serialize, serde::Deserialize, Debug, Clone, PartialEq, Eq, Hash)]+#[serde(rename_all = "camelCase")]+pub struct SourceId {+ /// Internal entity identifier, stored in `foreign_entity.stored_for_id`.+ pub id: String,+ /// Internal auth entity namespace, stored in `foreign_entity.stored_for_auth_entity`.+ pub auth_entity: String,+}++impl SourceId {+ /// Create a source identifier from explicit stored-for values.+ pub fn new(id: impl Into<String>, auth_entity: impl Into<String>) -> Self {+ Self {+ id: id.into(),+ auth_entity: auth_entity.into(),+ }+ }++ /// Create a user-scoped source identifier.+ pub fn user(id: impl Into<String>) -> Self {+ Self::new(id, "user")+ }++ /// Create a team-scoped source identifier.+ pub fn team(id: Uuid) -> Self {+ Self::new(id.to_string(), "team")+ }++ pub(crate) fn validate(&self) -> Result<(), ForeignEntityError> {+ validate_non_blank("sourceId.id", &self.id)?;+ validate_non_blank("sourceId.authEntity", &self.auth_entity)+ }+}+/// A persisted mapping to an entity owned by an external system.#[derive(serde::Serialize, serde::Deserialize, Debug, Clone, PartialEq)]#[serde(rename_all = "camelCase")]diff --git a/rust/cloud-storage/foreign_entity/src/domain/ports.rs b/rust/cloud-storage/foreign_entity/src/domain/ports.rsindex dd4d6529c0..70c5388339 100644--- a/rust/cloud-storage/foreign_entity/src/domain/ports.rs+++ b/rust/cloud-storage/foreign_entity/src/domain/ports.rs@@ -4,9 +4,16 @@use std::future::Future;+use item_filters::ast::{LiteralTree, foreign_entity::ForeignEntityLiteral};+use models_pagination::{Query, SimpleSortMethod};use uuid::Uuid;-use super::models::{CreateForeignEntity, ForeignEntity, ForeignEntityError, PatchForeignEntity};+use super::models::{+ CreateForeignEntity, ForeignEntity, ForeignEntityError, PatchForeignEntity, SourceId,+};++/// Query type used when listing foreign entities for source ids.+pub type ForeignEntityListQuery = Query<Uuid, SimpleSortMethod, LiteralTree<ForeignEntityLiteral>>;/// Repository for persisting and fetching foreign entity records.///@@ -32,6 +39,14 @@ pub trait ForeignEntityRepository: Send + Sync + 'static {foreign_entity_source: Option<&str>,) -> impl Future<Output = Result<Vec<ForeignEntity>, Self::Err>> + Send;+ /// List foreign entities visible through the supplied source identifiers.+ fn get_foreign_entities_for_user(+ &self,+ source_ids: Vec<SourceId>,+ limit: u32,+ query: ForeignEntityListQuery,+ ) -> impl Future<Output = Result<Vec<ForeignEntity>, Self::Err>> + Send;+/// Create a foreign entity record using the supplied internal primary key.fn create_foreign_entity(&self,@@ -78,6 +93,14 @@ pub trait ForeignEntityService: Send + Sync + 'static {foreign_entity_source: Option<&str>,) -> impl Future<Output = Result<Vec<ForeignEntity>, ForeignEntityError>> + Send;+ /// List foreign entities visible through the supplied source identifiers.+ fn get_foreign_entities_for_user(+ &self,+ source_ids: Vec<SourceId>,+ limit: u32,+ query: ForeignEntityListQuery,+ ) -> impl Future<Output = Result<Vec<ForeignEntity>, ForeignEntityError>> + Send;+/// Create a foreign entity record.fn create_foreign_entity(&self,diff --git a/rust/cloud-storage/foreign_entity/src/domain/service.rs b/rust/cloud-storage/foreign_entity/src/domain/service.rsindex f95cb19b9f..cc6b9a5506 100644--- a/rust/cloud-storage/foreign_entity/src/domain/service.rs+++ b/rust/cloud-storage/foreign_entity/src/domain/service.rs@@ -6,10 +6,10 @@ mod tests;use uuid::Uuid;use super::models::{- CreateForeignEntity, ForeignEntity, ForeignEntityError, PatchForeignEntity,+ CreateForeignEntity, ForeignEntity, ForeignEntityError, PatchForeignEntity, SourceId,validate_foreign_entity_lookup,};-use super::ports::{ForeignEntityRepository, ForeignEntityService};+use super::ports::{ForeignEntityListQuery, ForeignEntityRepository, ForeignEntityService};/// Concrete foreign entity service implementation.pub struct ForeignEntityServiceImpl<R> {@@ -56,6 +56,27 @@ where.map_err(|error| ForeignEntityError::Internal(error.into()))}+ #[tracing::instrument(err, skip(self, source_ids, query))]+ async fn get_foreign_entities_for_user(+ &self,+ source_ids: Vec<SourceId>,+ limit: u32,+ query: ForeignEntityListQuery,+ ) -> Result<Vec<ForeignEntity>, ForeignEntityError> {+ if source_ids.is_empty() {+ return Ok(Vec::new());+ }++ for source_id in &source_ids {+ source_id.validate()?;+ }++ self.repo+ .get_foreign_entities_for_user(source_ids, limit, query)+ .await+ .map_err(|error| ForeignEntityError::Internal(error.into()))+ }+#[tracing::instrument(err, skip(self, create))]async fn create_foreign_entity(&self,diff --git a/rust/cloud-storage/foreign_entity/src/domain/service/tests.rs b/rust/cloud-storage/foreign_entity/src/domain/service/tests.rsindex 703bf0a511..43a7da57fd 100644--- a/rust/cloud-storage/foreign_entity/src/domain/service/tests.rs+++ b/rust/cloud-storage/foreign_entity/src/domain/service/tests.rs@@ -1,15 +1,31 @@use std::collections::HashMap;use std::sync::{Arc, Mutex};-use chrono::Utc;+use chrono::{DateTime, Utc};+use models_pagination::{Query, SimpleSortMethod};use serde_json::json;use uuid::Uuid;+use crate::domain::ports::ForeignEntityListQuery;+use super::*;+type CreateForeignEntityEdit = fn(&mut CreateForeignEntity);++#[derive(Debug, Clone)]+struct ListForeignEntitiesCall {+ source_ids: Vec<SourceId>,+ limit: u32,+ sort_method: String,+ cursor_id: Option<Uuid>,+ cursor_value: Option<DateTime<Utc>>,+}+#[derive(Clone, Default)]struct FakeForeignEntityRepository {records: Arc<Mutex<HashMap<Uuid, ForeignEntity>>>,+ list_calls: Arc<Mutex<Vec<ListForeignEntitiesCall>>>,+ fail_listings: Arc<Mutex<bool>>,}impl FakeForeignEntityRepository {@@ -18,6 +34,20 @@ impl FakeForeignEntityRepository {.lock().expect("fake foreign entity repository lock poisoned")}++ fn list_calls(&self) -> Vec<ListForeignEntitiesCall> {+ self.list_calls+ .lock()+ .expect("fake foreign entity repository list call lock poisoned")+ .clone()+ }++ fn fail_listings(&self) {+ *self+ .fail_listings+ .lock()+ .expect("fake foreign entity repository failure lock poisoned") = true;+ }}impl ForeignEntityRepository for FakeForeignEntityRepository {@@ -47,6 +77,48 @@ impl ForeignEntityRepository for FakeForeignEntityRepository {Ok(records)}+ async fn get_foreign_entities_for_user(+ &self,+ source_ids: Vec<SourceId>,+ limit: u32,+ query: ForeignEntityListQuery,+ ) -> Result<Vec<ForeignEntity>, Self::Err> {+ if *self+ .fail_listings+ .lock()+ .expect("fake foreign entity repository failure lock poisoned")+ {+ anyhow::bail!("listing failed");+ }++ let (cursor_id, cursor_value) = query.vals();+ self.list_calls+ .lock()+ .expect("fake foreign entity repository list call lock poisoned")+ .push(ListForeignEntitiesCall {+ source_ids: source_ids.clone(),+ limit,+ sort_method: query.sort_method().to_string(),+ cursor_id: cursor_id.copied(),+ cursor_value: cursor_value.copied(),+ });++ let records = self+ .records()+ .values()+ .filter(|record| {+ source_ids.iter().any(|source_id| {+ record.stored_for_id.as_str() == source_id.id.as_str()+ && record.stored_for_auth_entity.as_str() == source_id.auth_entity.as_str()+ })+ })+ .take(limit as usize)+ .cloned()+ .collect();++ Ok(records)+ }+async fn create_foreign_entity(&self,id: Uuid,@@ -119,6 +191,25 @@ fn valid_create() -> CreateForeignEntity {}}+fn foreign_entity_for_source(stored_for_id: &str, stored_for_auth_entity: &str) -> ForeignEntity {+ let now = Utc::now();++ ForeignEntity {+ id: Uuid::new_v4(),+ foreign_entity_id: format!("external-{stored_for_id}"),+ foreign_entity_source: "github_pull_request".to_string(),+ metadata: json!({}),+ stored_for_id: stored_for_id.to_string(),+ stored_for_auth_entity: stored_for_auth_entity.to_string(),+ created_at: now,+ updated_at: now,+ }+}++fn listing_query(sort_method: SimpleSortMethod) -> ForeignEntityListQuery {+ Query::Sort(sort_method, None)+}+fn assert_bad_request(error: ForeignEntityError, expected_message: &str) {let ForeignEntityError::BadRequest(message) = error else {panic!("expected bad request error, got {error:?}");@@ -191,6 +282,111 @@ async fn get_by_foreign_entity_id_returns_all_matching_records() {assert_eq!(source_matches[0].foreign_entity_source, "github");}+#[tokio::test]+async fn get_foreign_entities_for_user_returns_matching_sources() {+ let repo = FakeForeignEntityRepository::default();+ let matching_user = foreign_entity_for_source("macro|[email protected]", "user");+ let matching_team = foreign_entity_for_source("aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa", "team");+ let unrelated = foreign_entity_for_source("macro|[email protected]", "user");++ repo.records()+ .insert(matching_user.id, matching_user.clone());+ repo.records()+ .insert(matching_team.id, matching_team.clone());+ repo.records().insert(unrelated.id, unrelated);++ let service = ForeignEntityServiceImpl::new(repo);+ let entities = service+ .get_foreign_entities_for_user(+ vec![+ SourceId::user("macro|[email protected]"),+ SourceId::new("aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa", "team"),+ ],+ 10,+ listing_query(SimpleSortMethod::UpdatedAt),+ )+ .await+ .expect("matching foreign entities should be returned");++ let mut ids = entities.iter().map(|entity| entity.id).collect::<Vec<_>>();+ ids.sort_unstable();+ let mut expected_ids = vec![matching_user.id, matching_team.id];+ expected_ids.sort_unstable();++ assert_eq!(ids, expected_ids);+}++#[tokio::test]+async fn get_foreign_entities_for_user_empty_sources_returns_empty_without_repo_call() {+ let repo = FakeForeignEntityRepository::default();+ let service = ForeignEntityServiceImpl::new(repo.clone());++ let entities = service+ .get_foreign_entities_for_user(Vec::new(), 10, listing_query(SimpleSortMethod::UpdatedAt))+ .await+ .expect("empty source list should return an empty listing");++ assert!(entities.is_empty());+ assert!(repo.list_calls().is_empty());+}++#[tokio::test]+async fn get_foreign_entities_for_user_forwards_limit_and_query() {+ let repo = FakeForeignEntityRepository::default();+ let service = ForeignEntityServiceImpl::new(repo.clone());+ let cursor_id = Uuid::new_v4();+ let cursor_value = Utc::now();++ service+ .get_foreign_entities_for_user(+ vec![SourceId::user("macro|[email protected]")],+ 37,+ Query::Cursor(models_pagination::Cursor {+ id: cursor_id,+ limit: 37,+ val: models_pagination::CursorVal {+ sort_type: SimpleSortMethod::CreatedAt,+ last_val: cursor_value,+ },+ filter: None,+ }),+ )+ .await+ .expect("listing should be forwarded to repository");++ let calls = repo.list_calls();+ assert_eq!(calls.len(), 1);+ assert_eq!(+ calls[0].source_ids,+ vec![SourceId::user("macro|[email protected]")]+ );+ assert_eq!(calls[0].limit, 37);+ assert_eq!(calls[0].sort_method, "created_at");+ assert_eq!(calls[0].cursor_id, Some(cursor_id));+ assert_eq!(calls[0].cursor_value, Some(cursor_value));+}++#[tokio::test]+async fn get_foreign_entities_for_user_maps_repo_errors_to_internal() {+ let repo = FakeForeignEntityRepository::default();+ repo.fail_listings();+ let service = ForeignEntityServiceImpl::new(repo);++ let error = service+ .get_foreign_entities_for_user(+ vec![SourceId::user("macro|[email protected]")],+ 10,+ listing_query(SimpleSortMethod::UpdatedAt),+ )+ .await+ .expect_err("repository errors should map to internal errors");++ let ForeignEntityError::Internal(error) = error else {+ panic!("expected internal error, got {error:?}");+ };+ assert!(error.to_string().contains("listing failed"));+}+#[tokio::test]async fn get_missing_foreign_entity_by_id_returns_not_found() {let service = service();@@ -207,7 +403,7 @@ async fn get_missing_foreign_entity_by_id_returns_not_found() {#[tokio::test]async fn create_rejects_blank_required_fields() {let service = service();- let cases: Vec<(&str, fn(&mut CreateForeignEntity))> = vec![+ let cases: Vec<(&str, CreateForeignEntityEdit)> = vec![("foreignEntityId", |create| {create.foreign_entity_id = " \t".to_string();}),diff --git a/rust/cloud-storage/foreign_entity/src/outbound/pg_foreign_entity_repo.rs b/rust/cloud-storage/foreign_entity/src/outbound/pg_foreign_entity_repo.rsindex 18ef4f0697..4019b26e7b 100644--- a/rust/cloud-storage/foreign_entity/src/outbound/pg_foreign_entity_repo.rs+++ b/rust/cloud-storage/foreign_entity/src/outbound/pg_foreign_entity_repo.rs@@ -4,11 +4,68 @@mod tests;use chrono::{DateTime, Utc};+use filter_ast::Expr;+use item_filters::ast::{LiteralTree, foreign_entity::ForeignEntityLiteral};+use models_pagination::SimpleSortMethod;use sqlx::PgPool;use uuid::Uuid;-use crate::domain::models::{CreateForeignEntity, ForeignEntity, PatchForeignEntity};-use crate::domain::ports::ForeignEntityRepository;+use crate::domain::models::{CreateForeignEntity, ForeignEntity, PatchForeignEntity, SourceId};+use crate::domain::ports::{ForeignEntityListQuery, ForeignEntityRepository};++struct ForeignEntityBatchQuery<'a> {+ source_ids: &'a [String],+ source_auth_entities: &'a [String],+ sort_method: SimpleSortMethod,+ filter_jsonpath: Option<&'a str>,+ cursor_id: Option<Uuid>,+ cursor_value: Option<DateTime<Utc>>,+ limit: i64,+}++fn source_id_parts(source_ids: &[SourceId]) -> (Vec<String>, Vec<String>) {+ source_ids+ .iter()+ .map(|source_id| (source_id.id.clone(), source_id.auth_entity.clone()))+ .unzip()+}++fn foreign_entity_filter_jsonpath(filter: &LiteralTree<ForeignEntityLiteral>) -> Option<String> {+ filter.as_deref().map(foreign_entity_expr_jsonpath)+}++fn foreign_entity_expr_jsonpath(expr: &Expr<ForeignEntityLiteral>) -> String {+ match expr {+ Expr::And(left, right) => format!(+ "({} && {})",+ foreign_entity_expr_jsonpath(left),+ foreign_entity_expr_jsonpath(right)+ ),+ Expr::Or(left, right) => format!(+ "({} || {})",+ foreign_entity_expr_jsonpath(left),+ foreign_entity_expr_jsonpath(right)+ ),+ Expr::Not(inner) => format!("(!{})", foreign_entity_expr_jsonpath(inner)),+ Expr::Literal(literal) => foreign_entity_literal_jsonpath(literal),+ }+}++fn foreign_entity_literal_jsonpath(literal: &ForeignEntityLiteral) -> String {+ match literal {+ ForeignEntityLiteral::Id(id) => jsonpath_text_eq("id", &id.to_string()),+ ForeignEntityLiteral::ForeignEntityId(id) => jsonpath_text_eq("foreignEntityId", id),+ ForeignEntityLiteral::ForeignEntitySource(source) => {+ jsonpath_text_eq("foreignEntitySource", source)+ }+ }+}++fn jsonpath_text_eq(field_name: &str, expected_value: &str) -> String {+ let expected_value = serde_json::to_string(expected_value)+ .expect("serializing a string literal to JSON should not fail");+ format!("($.{field_name} == {expected_value})")+}/// PostgreSQL-backed foreign entity repository.#[derive(Clone)]@@ -21,6 +78,90 @@ impl PgForeignEntityRepo {pub fn new(pool: PgPool) -> Self {Self { pool }}++ async fn get_foreign_entities_for_user_batch(+ &self,+ query: ForeignEntityBatchQuery<'_>,+ ) -> Result<Vec<ForeignEntity>, sqlx::Error> {+ let ForeignEntityBatchQuery {+ source_ids,+ source_auth_entities,+ sort_method,+ filter_jsonpath,+ cursor_id,+ cursor_value,+ limit,+ } = query;+ let sort_method = sort_method.to_string();++ sqlx::query_as!(+ ForeignEntity,+ r#"+ WITH source_ids AS (+ SELECT DISTINCT stored_for_id, stored_for_auth_entity+ FROM UNNEST($1::text[], $2::text[])+ AS source_rows(stored_for_id, stored_for_auth_entity)+ ),+ deduped AS (+ SELECT DISTINCT ON (fe.foreign_entity_source, fe.foreign_entity_id)+ fe.id,+ fe.foreign_entity_id,+ fe.foreign_entity_source,+ fe.metadata,+ fe.stored_for_id,+ fe.stored_for_auth_entity,+ fe.created_at,+ fe.updated_at,+ CASE $3::text+ WHEN 'created_at' THEN fe.created_at+ ELSE fe.updated_at+ END AS sort_at+ FROM foreign_entity fe+ WHERE EXISTS (+ SELECT 1+ FROM source_ids s+ WHERE s.stored_for_id = fe.stored_for_id+ AND s.stored_for_auth_entity = fe.stored_for_auth_entity+ )+ AND (+ $4::text IS NULL+ OR jsonb_path_match(+ jsonb_build_object(+ 'id', fe.id::text,+ 'foreignEntityId', fe.foreign_entity_id,+ 'foreignEntitySource', fe.foreign_entity_source+ ),+ ($4::text)::jsonpath+ )+ )+ ORDER BY fe.foreign_entity_source, fe.foreign_entity_id, sort_at DESC, fe.id DESC+ )+ SELECT+ id as "id!: Uuid",+ foreign_entity_id as "foreign_entity_id!: String",+ foreign_entity_source as "foreign_entity_source!: String",+ metadata as "metadata!: serde_json::Value",+ stored_for_id as "stored_for_id!: String",+ stored_for_auth_entity as "stored_for_auth_entity!: String",+ created_at as "created_at!: DateTime<Utc>",+ updated_at as "updated_at!: DateTime<Utc>"+ FROM deduped+ WHERE $5::timestamptz IS NULL+ OR (sort_at, id) < ($5::timestamptz, $6::uuid)+ ORDER BY sort_at DESC, id DESC+ LIMIT $7+ "#,+ source_ids,+ source_auth_entities,+ sort_method,+ filter_jsonpath,+ cursor_value,+ cursor_id,+ limit,+ )+ .fetch_all(&self.pool)+ .await+ }}impl ForeignEntityRepository for PgForeignEntityRepo {@@ -80,6 +221,33 @@ impl ForeignEntityRepository for PgForeignEntityRepo {.await}+ #[tracing::instrument(err, skip(self, source_ids, query))]+ async fn get_foreign_entities_for_user(+ &self,+ source_ids: Vec<SourceId>,+ limit: u32,+ query: ForeignEntityListQuery,+ ) -> Result<Vec<ForeignEntity>, Self::Err> {+ if source_ids.is_empty() || limit == 0 {+ return Ok(Vec::new());+ }++ let (source_ids, source_auth_entities) = source_id_parts(&source_ids);+ let filter_jsonpath = foreign_entity_filter_jsonpath(query.filter());+ let (cursor_id, cursor_value) = query.vals();++ self.get_foreign_entities_for_user_batch(ForeignEntityBatchQuery {+ source_ids: &source_ids,+ source_auth_entities: &source_auth_entities,+ sort_method: *query.sort_method(),+ filter_jsonpath: filter_jsonpath.as_deref(),+ cursor_id: cursor_id.copied(),+ cursor_value: cursor_value.copied(),+ limit: limit as i64,+ })+ .await+ }+#[tracing::instrument(err, skip(self, create))]async fn create_foreign_entity(&self,diff --git a/rust/cloud-storage/foreign_entity/src/outbound/pg_foreign_entity_repo/tests.rs b/rust/cloud-storage/foreign_entity/src/outbound/pg_foreign_entity_repo/tests.rsindex 50123f161e..0d4a55ee45 100644--- a/rust/cloud-storage/foreign_entity/src/outbound/pg_foreign_entity_repo/tests.rs+++ b/rust/cloud-storage/foreign_entity/src/outbound/pg_foreign_entity_repo/tests.rs@@ -1,22 +1,30 @@+use std::sync::Arc;++use chrono::Utc;+use filter_ast::Expr;+use item_filters::ast::{LiteralTree, foreign_entity::ForeignEntityLiteral};use macro_db_migrator::MACRO_DB_MIGRATIONS;+use models_pagination::{Cursor, CursorVal, Query, SimpleSortMethod};use serde_json::json;use sqlx::PgPool;use uuid::Uuid;use super::PgForeignEntityRepo;-use crate::domain::models::{CreateForeignEntity, ForeignEntity, PatchForeignEntity};-use crate::domain::ports::ForeignEntityRepository;+use crate::domain::models::{CreateForeignEntity, ForeignEntity, PatchForeignEntity, SourceId};+use crate::domain::ports::{ForeignEntityListQuery, ForeignEntityRepository};-fn create_request(+fn create_request_for_source(foreign_entity_id: impl Into<String>,foreign_entity_source: impl Into<String>,+ stored_for_id: impl Into<String>,+ stored_for_auth_entity: impl Into<String>,) -> CreateForeignEntity {CreateForeignEntity {foreign_entity_id: foreign_entity_id.into(),foreign_entity_source: foreign_entity_source.into(),metadata: json!({ "origin": "test" }),- stored_for_id: "document-1".to_string(),- stored_for_auth_entity: "document".to_string(),+ stored_for_id: stored_for_id.into(),+ stored_for_auth_entity: stored_for_auth_entity.into(),}}@@ -24,15 +32,95 @@ async fn insert_foreign_entity(repo: &PgForeignEntityRepo,foreign_entity_id: &str,foreign_entity_source: &str,+) -> ForeignEntity {+ insert_foreign_entity_for_source(+ repo,+ foreign_entity_id,+ foreign_entity_source,+ "document-1",+ "document",+ )+ .await+}++async fn insert_foreign_entity_for_source(+ repo: &PgForeignEntityRepo,+ foreign_entity_id: &str,+ foreign_entity_source: &str,+ stored_for_id: &str,+ stored_for_auth_entity: &str,) -> ForeignEntity {repo.create_foreign_entity(Uuid::now_v7(),- create_request(foreign_entity_id, foreign_entity_source),+ create_request_for_source(+ foreign_entity_id,+ foreign_entity_source,+ stored_for_id,+ stored_for_auth_entity,+ ),).await.expect("foreign entity should be inserted")}+fn list_query(sort_method: SimpleSortMethod) -> ForeignEntityListQuery {+ Query::Sort(sort_method, None)+}++fn cursor_query(entity: &ForeignEntity, sort_method: SimpleSortMethod) -> ForeignEntityListQuery {+ let last_val = match sort_method {+ SimpleSortMethod::CreatedAt => entity.created_at,+ SimpleSortMethod::ViewedAt+ | SimpleSortMethod::UpdatedAt+ | SimpleSortMethod::ViewedUpdated => entity.updated_at,+ };++ Query::Cursor(Cursor {+ id: entity.id,+ limit: 2,+ val: CursorVal {+ sort_type: sort_method,+ last_val,+ },+ filter: None,+ })+}++fn filter_query(filter: LiteralTree<ForeignEntityLiteral>) -> ForeignEntityListQuery {+ Query::Sort(SimpleSortMethod::UpdatedAt, filter)+}++fn ids(entities: &[ForeignEntity]) -> Vec<Uuid> {+ entities.iter().map(|entity| entity.id).collect()+}++async fn set_timestamps(+ pool: &PgPool,+ repo: &PgForeignEntityRepo,+ entity: &ForeignEntity,+ created_at: chrono::DateTime<chrono::Utc>,+ updated_at: chrono::DateTime<chrono::Utc>,+) -> ForeignEntity {+ sqlx::query!(+ r#"+ UPDATE foreign_entity+ SET created_at = $2, updated_at = $3+ WHERE id = $1+ "#,+ entity.id,+ created_at,+ updated_at,+ )+ .execute(pool)+ .await+ .expect("foreign entity timestamps should be updated");++ repo.get_foreign_entity_by_id(entity.id)+ .await+ .expect("updated foreign entity lookup should succeed")+ .expect("updated foreign entity should exist")+}+#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]async fn create_inserts_row_and_returns_persisted_fields(pool: PgPool) {let repo = PgForeignEntityRepo::new(pool.clone());@@ -126,6 +214,326 @@ async fn get_by_foreign_entity_id_returns_all_matches_and_supports_source_filterassert!(missing_source_matches.is_empty());}+#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]+async fn get_for_user_returns_matching_user_and_team_sources(pool: PgPool) {+ let repo = PgForeignEntityRepo::new(pool);+ let team_id = Uuid::parse_str("aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa").unwrap();+ let user_entity = insert_foreign_entity_for_source(+ &repo,+ "user-visible-pr",+ "github_pull_request",+ "macro|[email protected]",+ "user",+ )+ .await;+ let team_entity = insert_foreign_entity_for_source(+ &repo,+ "team-visible-pr",+ "github_pull_request",+ &team_id.to_string(),+ "team",+ )+ .await;+ insert_foreign_entity_for_source(+ &repo,+ "unrelated-pr",+ "github_pull_request",+ "macro|[email protected]",+ "user",+ )+ .await;++ let entities = repo+ .get_foreign_entities_for_user(+ vec![+ SourceId::user("macro|[email protected]"),+ SourceId::team(team_id),+ ],+ 10,+ list_query(SimpleSortMethod::UpdatedAt),+ )+ .await+ .expect("foreign entities should be listed for matching sources");++ let mut actual_ids = ids(&entities);+ actual_ids.sort_unstable();+ let mut expected_ids = vec![user_entity.id, team_entity.id];+ expected_ids.sort_unstable();++ assert_eq!(actual_ids, expected_ids);+}++#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]+async fn get_for_user_empty_sources_returns_empty(pool: PgPool) {+ let repo = PgForeignEntityRepo::new(pool);+ insert_foreign_entity_for_source(+ &repo,+ "user-visible-pr",+ "github_pull_request",+ "macro|[email protected]",+ "user",+ )+ .await;++ let entities = repo+ .get_foreign_entities_for_user(Vec::new(), 10, list_query(SimpleSortMethod::UpdatedAt))+ .await+ .expect("empty source list should succeed");++ assert!(entities.is_empty());+}++#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]+async fn get_for_user_dedupes_duplicate_source_grants(pool: PgPool) {+ let repo = PgForeignEntityRepo::new(pool.clone());+ let team_id = Uuid::parse_str("bbbbbbbb-bbbb-bbbb-bbbb-bbbbbbbbbbbb").unwrap();+ let older = insert_foreign_entity_for_source(+ &repo,+ "shared-pr",+ "github_pull_request",+ "macro|[email protected]",+ "user",+ )+ .await;+ let newer = insert_foreign_entity_for_source(+ &repo,+ "shared-pr",+ "github_pull_request",+ &team_id.to_string(),+ "team",+ )+ .await;++ let now = Utc::now();+ let older = set_timestamps(+ &pool,+ &repo,+ &older,+ now - chrono::Duration::minutes(2),+ now - chrono::Duration::minutes(2),+ )+ .await;+ let newer = set_timestamps(+ &pool,+ &repo,+ &newer,+ now - chrono::Duration::minutes(1),+ now - chrono::Duration::minutes(1),+ )+ .await;++ let entities = repo+ .get_foreign_entities_for_user(+ vec![+ SourceId::user("macro|[email protected]"),+ SourceId::team(team_id),+ ],+ 10,+ list_query(SimpleSortMethod::UpdatedAt),+ )+ .await+ .expect("duplicate foreign entity grants should be listed once");++ assert_eq!(entities, vec![newer]);+ assert_ne!(entities[0].id, older.id);+}++#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]+async fn get_for_user_paginates_by_created_at(pool: PgPool) {+ let repo = PgForeignEntityRepo::new(pool.clone());+ let first = insert_foreign_entity_for_source(+ &repo,+ "first-pr",+ "github_pull_request",+ "macro|[email protected]",+ "user",+ )+ .await;+ let second = insert_foreign_entity_for_source(+ &repo,+ "second-pr",+ "github_pull_request",+ "macro|[email protected]",+ "user",+ )+ .await;+ let third = insert_foreign_entity_for_source(+ &repo,+ "third-pr",+ "github_pull_request",+ "macro|[email protected]",+ "user",+ )+ .await;+ let now = Utc::now();+ let first = set_timestamps(+ &pool,+ &repo,+ &first,+ now - chrono::Duration::minutes(1),+ now - chrono::Duration::minutes(30),+ )+ .await;+ let second = set_timestamps(+ &pool,+ &repo,+ &second,+ now - chrono::Duration::minutes(2),+ now - chrono::Duration::minutes(10),+ )+ .await;+ let third = set_timestamps(+ &pool,+ &repo,+ &third,+ now - chrono::Duration::minutes(3),+ now - chrono::Duration::minutes(20),+ )+ .await;++ let first_page = repo+ .get_foreign_entities_for_user(+ vec![SourceId::user("macro|[email protected]")],+ 2,+ list_query(SimpleSortMethod::CreatedAt),+ )+ .await+ .expect("first created_at page should be fetched");+ let second_page = repo+ .get_foreign_entities_for_user(+ vec![SourceId::user("macro|[email protected]")],+ 2,+ cursor_query(&first_page[1], SimpleSortMethod::CreatedAt),+ )+ .await+ .expect("second created_at page should be fetched");++ assert_eq!(first_page, vec![first, second]);+ assert_eq!(second_page, vec![third]);+}++#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]+async fn get_for_user_paginates_by_updated_at(pool: PgPool) {+ let repo = PgForeignEntityRepo::new(pool.clone());+ let first = insert_foreign_entity_for_source(+ &repo,+ "first-pr",+ "github_pull_request",+ "macro|[email protected]",+ "user",+ )+ .await;+ let second = insert_foreign_entity_for_source(+ &repo,+ "second-pr",+ "github_pull_request",+ "macro|[email protected]",+ "user",+ )+ .await;+ let third = insert_foreign_entity_for_source(+ &repo,+ "third-pr",+ "github_pull_request",+ "macro|[email protected]",+ "user",+ )+ .await;+ let now = Utc::now();+ let first = set_timestamps(+ &pool,+ &repo,+ &first,+ now - chrono::Duration::minutes(30),+ now - chrono::Duration::minutes(1),+ )+ .await;+ let second = set_timestamps(+ &pool,+ &repo,+ &second,+ now - chrono::Duration::minutes(10),+ now - chrono::Duration::minutes(2),+ )+ .await;+ let third = set_timestamps(+ &pool,+ &repo,+ &third,+ now - chrono::Duration::minutes(20),+ now - chrono::Duration::minutes(3),+ )+ .await;++ let first_page = repo+ .get_foreign_entities_for_user(+ vec![SourceId::user("macro|[email protected]")],+ 2,+ list_query(SimpleSortMethod::UpdatedAt),+ )+ .await+ .expect("first updated_at page should be fetched");+ let second_page = repo+ .get_foreign_entities_for_user(+ vec![SourceId::user("macro|[email protected]")],+ 2,+ cursor_query(&first_page[1], SimpleSortMethod::UpdatedAt),+ )+ .await+ .expect("second updated_at page should be fetched");++ assert_eq!(first_page, vec![first, second]);+ assert_eq!(second_page, vec![third]);+}++#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]+async fn get_for_user_applies_foreign_entity_filters(pool: PgPool) {+ let repo = PgForeignEntityRepo::new(pool);+ let github = insert_foreign_entity_for_source(+ &repo,+ "github-pr",+ "github_pull_request",+ "macro|[email protected]",+ "user",+ )+ .await;+ insert_foreign_entity_for_source(+ &repo,+ "linear-issue",+ "linear_issue",+ "macro|[email protected]",+ "user",+ )+ .await;++ let source_filter = Some(Arc::new(Expr::val(+ ForeignEntityLiteral::ForeignEntitySource("github_pull_request".to_string()),+ )));+ let source_matches = repo+ .get_foreign_entities_for_user(+ vec![SourceId::user("macro|[email protected]")],+ 10,+ filter_query(source_filter),+ )+ .await+ .expect("foreign entity source filter should be applied");++ let not_linear_filter = Some(Arc::new(Expr::is_not(Expr::val(+ ForeignEntityLiteral::ForeignEntityId("linear-issue".to_string()),+ ))));+ let not_linear_matches = repo+ .get_foreign_entities_for_user(+ vec![SourceId::user("macro|[email protected]")],+ 10,+ filter_query(not_linear_filter),+ )+ .await+ .expect("foreign entity negated filter should be applied");++ assert_eq!(source_matches, vec![github.clone()]);+ assert_eq!(not_linear_matches, vec![github]);+}+#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]async fn patch_updates_selected_fields_preserves_others_and_refreshes_updated_at(pool: PgPool) {let repo = PgForeignEntityRepo::new(pool.clone());diff --git a/rust/cloud-storage/frecency/src/outbound/postgres/dynamic_tests.rs b/rust/cloud-storage/frecency/src/outbound/postgres/dynamic_tests.rsindex 8a908e0a60..f2d24101d2 100644--- a/rust/cloud-storage/frecency/src/outbound/postgres/dynamic_tests.rs+++ b/rust/cloud-storage/frecency/src/outbound/postgres/dynamic_tests.rs@@ -959,6 +959,7 @@ async fn test_dynamic_filter_document_date_created_at_gt(pool: PgPool) {email_filter: item_filters::ast::EmailFilterAst::default(),channel_filter: None,call_filter: None,+ foreign_entity_filter: None,properties_filter: None,};@@ -1050,6 +1051,7 @@ async fn test_dynamic_filter_document_date_created_at_lt(pool: PgPool) {email_filter: item_filters::ast::EmailFilterAst::default(),channel_filter: None,call_filter: None,+ foreign_entity_filter: None,properties_filter: None,};@@ -1137,6 +1139,7 @@ async fn test_dynamic_filter_document_date_updated_at_gt(pool: PgPool) {email_filter: item_filters::ast::EmailFilterAst::default(),channel_filter: None,call_filter: None,+ foreign_entity_filter: None,properties_filter: None,};@@ -1229,6 +1232,7 @@ async fn test_dynamic_filter_document_date_updated_at_lt(pool: PgPool) {email_filter: item_filters::ast::EmailFilterAst::default(),channel_filter: None,call_filter: None,+ foreign_entity_filter: None,properties_filter: None,};diff --git a/rust/cloud-storage/github/src/domain/service/sync/test.rs b/rust/cloud-storage/github/src/domain/service/sync/test.rsindex f01c3bb572..68f7c123aa 100644--- a/rust/cloud-storage/github/src/domain/service/sync/test.rs+++ b/rust/cloud-storage/github/src/domain/service/sync/test.rs@@ -24,8 +24,10 @@ use entity_access::domain::models::{EditAccessLevel, EntityAccessReceipt, OwnerAccessLevel, ViewAccessLevel,};use foreign_entity::domain::{- models::{CreateForeignEntity, ForeignEntity, ForeignEntityError, PatchForeignEntity},- ports::ForeignEntityService,+ models::{+ CreateForeignEntity, ForeignEntity, ForeignEntityError, PatchForeignEntity, SourceId,+ },+ ports::{ForeignEntityListQuery, ForeignEntityService},};use macro_user_id::user_id::MacroUserIdStr;use model::document::{DocumentBasic, DocumentMetadata};@@ -573,6 +575,28 @@ impl ForeignEntityService for StubForeignEntityService {.collect())}+ async fn get_foreign_entities_for_user(+ &self,+ source_ids: Vec<SourceId>,+ limit: u32,+ _query: ForeignEntityListQuery,+ ) -> Result<Vec<ForeignEntity>, ForeignEntityError> {+ Ok(self+ .foreign_entities+ .lock()+ .unwrap()+ .iter()+ .filter(|entity| {+ source_ids.iter().any(|source_id| {+ entity.stored_for_id.as_str() == source_id.id.as_str()+ && entity.stored_for_auth_entity.as_str() == source_id.auth_entity.as_str()+ })+ })+ .take(limit as usize)+ .cloned()+ .collect())+ }+async fn create_foreign_entity(&self,create: CreateForeignEntity,diff --git a/rust/cloud-storage/item_filters/src/ast.rs b/rust/cloud-storage/item_filters/src/ast.rsindex ad4679a99d..51d5b74cc7 100644--- a/rust/cloud-storage/item_filters/src/ast.rs+++ b/rust/cloud-storage/item_filters/src/ast.rs@@ -3,12 +3,13 @@use crate::{CallFilters, ChannelFilters, ChatFilters, DocumentFilters, EmailFilters, EntityFilters,- ProjectFilters, PropertyFilter,+ ForeignEntityFilters, ProjectFilters, PropertyFilter,ast::{call::CallLiteral,channel::{ChannelLiteral, ChannelTypeFilter},chat::{ChatLiteral, ChatRole},email::EmailLiteral,+ foreign_entity::ForeignEntityLiteral,project::ProjectLiteral,properties::PropertiesLiteral,},@@ -32,6 +33,8 @@ pub mod date;pub mod document;/// contains the ast literal value for emailspub mod email;+/// contains the ast literal value for foreign entities+pub mod foreign_entity;/// contains the ast literal value for projectspub mod project;/// contains the ast literal value for property-based filtering@@ -193,6 +196,10 @@ pub struct EntityFilterAst {#[serde(default, rename = "callf")]#[cfg_attr(feature = "schema", schema(value_type = serde_json::Value))]pub call_filter: LiteralTree<CallLiteral>,+ /// the filters that should be applied to foreign entity records+ #[serde(default, rename = "fef")]+ #[cfg_attr(feature = "schema", schema(value_type = serde_json::Value))]+ pub foreign_entity_filter: LiteralTree<ForeignEntityLiteral>,/// the filters that should be applied based on entity properties#[serde(default, rename = "propf")]#[cfg_attr(feature = "schema", schema(value_type = serde_json::Value))]@@ -228,6 +235,10 @@ impl EntityFilterAst {channel_filter: ChannelFilters::expand_ast(entity_filter.channel_filters)?.map(Arc::new),call_filter: CallFilters::expand_ast(entity_filter.call_filters)?.map(Arc::new),+ foreign_entity_filter: ForeignEntityFilters::expand_ast(+ entity_filter.foreign_entity_filters,+ )?+ .map(Arc::new),properties_filter: Vec::<PropertyFilter>::expand_ast(entity_filter.property_filters)?.map(Arc::new),}))@@ -243,6 +254,7 @@ impl EntityFilterAst {email_filter: EmailFilterAst::default(),channel_filter: None,call_filter: None,+ foreign_entity_filter: None,properties_filter: None,}}@@ -257,6 +269,7 @@ impl IsEmpty for EntityFilterAst {email_filter,channel_filter,call_filter,+ foreign_entity_filter,properties_filter,} = self;document_filter.is_none()@@ -265,6 +278,7 @@ impl IsEmpty for EntityFilterAst {&& email_filter.is_empty()&& channel_filter.is_none()&& call_filter.is_none()+ && foreign_entity_filter.is_none()&& properties_filter.is_none()}}diff --git a/rust/cloud-storage/item_filters/src/ast/foreign_entity.rs b/rust/cloud-storage/item_filters/src/ast/foreign_entity.rsnew file mode 100644index 0000000000..00808f1d99--- /dev/null+++ b/rust/cloud-storage/item_filters/src/ast/foreign_entity.rs@@ -0,0 +1,50 @@+use filter_ast::{ExpandFrame, Expr, FoldTree, TryExpandNode};+use serde::{Deserialize, Serialize};+use uuid::Uuid;++use crate::{ForeignEntityFilters, ast::ExpandErr};++/// The possible literal values in a foreign entity filter AST.+#[derive(Debug, Serialize, Deserialize, Clone)]+pub enum ForeignEntityLiteral {+ /// Filter by the internal foreign entity record ID.+ #[serde(rename = "id")]+ Id(Uuid),+ /// Filter by the external entity identifier.+ #[serde(rename = "feid")]+ ForeignEntityId(String),+ /// Filter by the external source name.+ #[serde(rename = "fes")]+ ForeignEntitySource(String),+}++impl ExpandFrame<ForeignEntityLiteral> for ForeignEntityFilters {+ type Err = ExpandErr;++ fn expand_ast(+ filter_request: ForeignEntityFilters,+ ) -> Result<Option<Expr<ForeignEntityLiteral>>, Self::Err> {+ let ForeignEntityFilters {+ ids,+ foreign_entity_ids,+ foreign_entity_sources,+ } = filter_request;++ let ids = ids+ .iter()+ .map(|s| Uuid::parse_str(s))+ .try_expand(|r| r.map(ForeignEntityLiteral::Id), Expr::or)?;++ let foreign_entity_ids = foreign_entity_ids+ .into_iter()+ .expand(ForeignEntityLiteral::ForeignEntityId, Expr::or);++ let foreign_entity_sources = foreign_entity_sources+ .into_iter()+ .expand(ForeignEntityLiteral::ForeignEntitySource, Expr::or);++ Ok([ids, foreign_entity_ids, foreign_entity_sources]+ .into_iter()+ .fold_with(Expr::and))+ }+}diff --git a/rust/cloud-storage/item_filters/src/ast/tests.rs b/rust/cloud-storage/item_filters/src/ast/tests.rsindex bcdbf34cfd..a614ef40b6 100644--- a/rust/cloud-storage/item_filters/src/ast/tests.rs+++ b/rust/cloud-storage/item_filters/src/ast/tests.rs@@ -1,7 +1,7 @@use std::str::FromStr;use super::*;-use crate::{CallFilters, PropertyFilter};+use crate::{CallFilters, ForeignEntityFilters, PropertyFilter};use cool_asserts::assert_matches;use model_file_type::FileType;use serde_json::json;@@ -866,6 +866,116 @@ fn it_expands_call_filter_without_attended_is_none_when_empty() {assert!(ast.is_none(), "empty filter should expand to None");}+#[test]+fn foreign_entity_empty_filters_produce_no_ast() {+ let ast = ForeignEntityFilters::expand_ast(ForeignEntityFilters::default()).unwrap();+ assert!(ast.is_none(), "empty filter should expand to None");+}++#[test]+fn foreign_entity_ids_parse_as_uuid_literals() {+ let id = Uuid::new_v4();+ let f = EntityFilters {+ foreign_entity_filters: ForeignEntityFilters {+ ids: vec![id.to_string()],+ ..Default::default()+ },+ ..Default::default()+ };++ let ast = Arc::into_inner(+ EntityFilterAst::new_from_filters(f)+ .unwrap()+ .unwrap()+ .foreign_entity_filter+ .unwrap(),+ )+ .unwrap();++ let json = serde_json::to_value(ast).unwrap();+ let exp = json!({+ "l": {+ "id": id+ }+ });++ assert_eq!(json, exp);+}++#[test]+fn foreign_entity_external_ids_expand_as_or_tree() {+ let f = EntityFilters {+ foreign_entity_filters: ForeignEntityFilters {+ foreign_entity_ids: vec!["external-a".to_string(), "external-b".to_string()],+ ..Default::default()+ },+ ..Default::default()+ };++ let ast = Arc::into_inner(+ EntityFilterAst::new_from_filters(f)+ .unwrap()+ .unwrap()+ .foreign_entity_filter+ .unwrap(),+ )+ .unwrap();++ let json = serde_json::to_value(ast).unwrap();+ let exp = json!({+ "|": [+ { "l": { "feid": "external-a" } },+ { "l": { "feid": "external-b" } }+ ]+ });++ assert_eq!(json, exp);+}++#[test]+fn foreign_entity_sources_expand_as_or_tree() {+ let f = EntityFilters {+ foreign_entity_filters: ForeignEntityFilters {+ foreign_entity_sources: vec!["github".to_string(), "linear".to_string()],+ ..Default::default()+ },+ ..Default::default()+ };++ let ast = Arc::into_inner(+ EntityFilterAst::new_from_filters(f)+ .unwrap()+ .unwrap()+ .foreign_entity_filter+ .unwrap(),+ )+ .unwrap();++ let json = serde_json::to_value(ast).unwrap();+ let exp = json!({+ "|": [+ { "l": { "fes": "github" } },+ { "l": { "fes": "linear" } }+ ]+ });++ assert_eq!(json, exp);+}++#[test]+fn foreign_entity_invalid_id_returns_uuid_error() {+ let f = EntityFilters {+ foreign_entity_filters: ForeignEntityFilters {+ ids: vec!["not-a-uuid".to_string()],+ ..Default::default()+ },+ ..Default::default()+ };++ let err = EntityFilterAst::new_from_filters(f).unwrap_err();+ assert_matches!(err, ExpandErr::Uuid(_));+}+#[test]fn crm_domains_expand_to_any_direction_or() {let f = EntityFilters {diff --git a/rust/cloud-storage/item_filters/src/lib.rs b/rust/cloud-storage/item_filters/src/lib.rsindex ccaf8069b4..5ebb4c5f3e 100644--- a/rust/cloud-storage/item_filters/src/lib.rs+++ b/rust/cloud-storage/item_filters/src/lib.rs@@ -342,6 +342,32 @@ impl IsEmpty for CallFilters {}}+/// Filters for foreign entity records.+#[derive(Debug, Serialize, Deserialize, Default, PartialEq, Clone)]+#[cfg_attr(feature = "schema", derive(utoipa::ToSchema, schemars::JsonSchema))]+pub struct ForeignEntityFilters {+ /// Internal foreign entity record IDs to filter by. Empty to include all records.+ #[serde(default, skip_serializing_if = "Vec::is_empty")]+ pub ids: Vec<String>,+ /// External entity identifiers to filter by. Empty to include all external IDs.+ #[serde(default, skip_serializing_if = "Vec::is_empty")]+ pub foreign_entity_ids: Vec<String>,+ /// External source names to filter by. Empty to include all sources.+ #[serde(default, skip_serializing_if = "Vec::is_empty")]+ pub foreign_entity_sources: Vec<String>,+}++impl IsEmpty for ForeignEntityFilters {+ fn is_empty(&self) -> bool {+ let ForeignEntityFilters {+ ids,+ foreign_entity_ids,+ foreign_entity_sources,+ } = self;+ ids.is_empty() && foreign_entity_ids.is_empty() && foreign_entity_sources.is_empty()+ }+}+/// The channel message filters used to filter down what channel messages you search over.#[derive(Debug, Serialize, Deserialize, Default, PartialEq, Clone)]#[cfg_attr(feature = "schema", derive(utoipa::ToSchema, schemars::JsonSchema))]@@ -496,6 +522,9 @@ pub struct EntityFilters {/// the bundled [EmailFilters]#[serde(default)]pub email_filters: EmailFilters,+ /// the bundled [ForeignEntityFilters]+ #[serde(default)]+ pub foreign_entity_filters: ForeignEntityFilters,/// property-based filters applied across entity types#[serde(default, skip_serializing_if = "Vec::is_empty")]pub property_filters: Vec<PropertyFilter>,@@ -510,6 +539,7 @@ impl IsEmpty for EntityFilters {channel_filters,call_filters,email_filters,+ foreign_entity_filters,property_filters,} = self;project_filters.is_empty()@@ -518,6 +548,7 @@ impl IsEmpty for EntityFilters {&& channel_filters.is_empty()&& call_filters.is_empty()&& email_filters.is_empty()+ && foreign_entity_filters.is_empty()&& property_filters.iter().all(IsEmpty::is_empty)}}diff --git a/rust/cloud-storage/macro_db_client/src/item_access/delete.rs b/rust/cloud-storage/macro_db_client/src/item_access/delete.rsindex d6f10c24c3..b13f11e868 100644--- a/rust/cloud-storage/macro_db_client/src/item_access/delete.rs+++ b/rust/cloud-storage/macro_db_client/src/item_access/delete.rs@@ -33,7 +33,11 @@ pub async fn delete_user_entity_access_bulk(}let result = match entity_type {- EntityType::User | EntityType::Team | EntityType::Channel | EntityType::StaticFile => {+ EntityType::User+ | EntityType::Team+ | EntityType::Channel+ | EntityType::StaticFile+ | EntityType::ForeignEntity => {anyhow::bail!("invalid entity type")}EntityType::Project => {diff --git a/rust/cloud-storage/mcp_service/Cargo.toml b/rust/cloud-storage/mcp_service/Cargo.tomlindex d0dcac20f3..09c36a8fa4 100644--- a/rust/cloud-storage/mcp_service/Cargo.toml+++ b/rust/cloud-storage/mcp_service/Cargo.toml@@ -21,6 +21,7 @@ email = { path = "../email", features = ["outbound"] }email_service_client = { path = "../email_service_client" }entity_access = { path = "../entity_access" }entity_access_management = { path = "../entity_access_management" }+foreign_entity = { path = "../foreign_entity" }frecency = { path = "../frecency", features = ["outbound", "postgres"] }fusionauth = { path = "../fusionauth" }http = { workspace = true }diff --git a/rust/cloud-storage/mcp_service/src/context.rs b/rust/cloud-storage/mcp_service/src/context.rsindex de8a260b11..979e963fa5 100644--- a/rust/cloud-storage/mcp_service/src/context.rs+++ b/rust/cloud-storage/mcp_service/src/context.rs@@ -18,6 +18,10 @@ use email::domain::service::EmailServiceImpl;use email::outbound::EmailPgRepo;use email_service_client::{EmailServiceClient, EmailServiceClientExternal};use entity_access::{domain::service::EntityAccessServiceImpl, outbound::PgAccessRepository};+use foreign_entity::{+ domain::service::ForeignEntityServiceImpl,+ outbound::pg_foreign_entity_repo::PgForeignEntityRepo,+};use frecency::domain::services::FrecencyQueryServiceImpl;use frecency::outbound::postgres::FrecencyPgStorage;use macro_auth::middleware::decode_jwt::JwtValidationArgs;@@ -178,12 +182,15 @@ async fn build_tool_context(frecency_storage,);let email_service_for_tools: Arc<ai_tools::ToolEmailService> = Arc::new(email_service.clone());+ let foreign_entity_service =+ ForeignEntityServiceImpl::new(PgForeignEntityRepo::new(db.clone()));let soup_service = Arc::new(SoupImpl::new(PgSoupRepo::new(readonly_pool::ReadOnlyPool(db.clone())),frecency_service,ReadonlyEmailPreviewAdapter(email_service),channels_service,call::domain::ports::NoOpCallRecordQueryService,+ foreign_entity_service,));let s3_client = macro_aws_config::s3_client().await;diff --git a/rust/cloud-storage/memory/Cargo.toml b/rust/cloud-storage/memory/Cargo.tomlindex da92058f74..9ac51792f6 100644--- a/rust/cloud-storage/memory/Cargo.toml+++ b/rust/cloud-storage/memory/Cargo.toml@@ -36,6 +36,7 @@ email = { path = "../email" }email_service_client = { path = "../email_service_client" }entity_access = { path = "../entity_access" }entity_access_management = { path = "../entity_access_management" }+foreign_entity = { path = "../foreign_entity" }frecency = { path = "../frecency" }lexical_client = { path = "../lexical_client" }macro_aws_config = { path = "../macro_aws_config" }diff --git a/rust/cloud-storage/memory/src/context.rs b/rust/cloud-storage/memory/src/context.rsindex 18297272ab..00c7da9a06 100644--- a/rust/cloud-storage/memory/src/context.rs+++ b/rust/cloud-storage/memory/src/context.rs@@ -14,6 +14,10 @@ use email::outbound::EmailPgRepo;use email_service_client::EmailServiceClientExternal;use entity_access::domain::service::EntityAccessServiceImpl;use entity_access::outbound::PgAccessRepository;+use foreign_entity::{+ domain::service::ForeignEntityServiceImpl,+ outbound::pg_foreign_entity_repo::PgForeignEntityRepo,+};use frecency::domain::services::FrecencyQueryServiceImpl;use frecency::outbound::postgres::FrecencyPgStorage;use lexical_client::LexicalClient;@@ -83,12 +87,15 @@ pub async fn build_tool_service_context(frecency_storage,);let email_service_for_tools: Arc<ai_tools::ToolEmailService> = Arc::new(email_service.clone());+ let foreign_entity_service =+ ForeignEntityServiceImpl::new(PgForeignEntityRepo::new(pool.clone()));let soup_service = Arc::new(SoupImpl::new(PgSoupRepo::new(readonly_pool::ReadOnlyPool(pool.clone())),frecency_service,ReadonlyEmailPreviewAdapter(email_service),channels_service,call::domain::ports::NoOpCallRecordQueryService,+ foreign_entity_service,));// Document tool contextdiff --git a/rust/cloud-storage/model-entity/src/lib.rs b/rust/cloud-storage/model-entity/src/lib.rsindex 5d5ec2d59a..4dd1729a57 100644--- a/rust/cloud-storage/model-entity/src/lib.rs+++ b/rust/cloud-storage/model-entity/src/lib.rs@@ -48,6 +48,8 @@ pub enum EntityType {Team,/// The entity is a voice/video callCall,+ /// The entity is a foreign entity stored from an external system+ ForeignEntity,/// A public file in the static file serviceStaticFile,}@@ -67,6 +69,7 @@ impl EntityType {// Calls are handled by entity_access by resolving through the call's// owning channel (access is inherited from channel membership).EntityType::Call => true,+ EntityType::ForeignEntity => false,EntityType::StaticFile => false,}}diff --git a/rust/cloud-storage/models_soup/Cargo.toml b/rust/cloud-storage/models_soup/Cargo.tomlindex 596ec9015a..b7d5a38b00 100644--- a/rust/cloud-storage/models_soup/Cargo.toml+++ b/rust/cloud-storage/models_soup/Cargo.toml@@ -21,6 +21,7 @@ model-entity = { path = "../model-entity" }models_pagination = { path = "../models_pagination" }models_properties = { path = "../models_properties/" }serde = { workspace = true }+serde_json = { workspace = true }strum = { workspace = true }utoipa = { workspace = true, optional = true }uuid = { workspace = true }diff --git a/rust/cloud-storage/models_soup/src/foreign_entity.rs b/rust/cloud-storage/models_soup/src/foreign_entity.rsnew file mode 100644index 0000000000..ffd5b253d7--- /dev/null+++ b/rust/cloud-storage/models_soup/src/foreign_entity.rs@@ -0,0 +1,28 @@+use chrono::{DateTime, Utc};+use serde::{Deserialize, Serialize};+use serde_json::Value;+use uuid::Uuid;++/// A foreign entity record as displayed in Soup.+#[derive(Debug, Serialize, Deserialize)]+#[cfg_attr(feature = "schema", derive(utoipa::ToSchema))]+#[serde(rename_all = "camelCase")]+pub struct SoupForeignEntity {+ /// Internal primary key for this foreign entity record.+ pub id: Uuid,+ /// Identifier assigned by the external system.+ pub foreign_entity_id: String,+ /// Source system that owns the external identifier.+ pub foreign_entity_source: String,+ /// Arbitrary metadata stored with the mapping.+ #[cfg_attr(feature = "schema", schema(value_type = Object))]+ pub metadata: Value,+ /// Internal entity identifier this foreign entity is stored for.+ pub stored_for_id: String,+ /// Internal auth entity namespace this foreign entity is stored for.+ pub stored_for_auth_entity: String,+ /// Timestamp when the record was created.+ pub created_at: DateTime<Utc>,+ /// Timestamp when the record was last updated.+ pub updated_at: DateTime<Utc>,+}diff --git a/rust/cloud-storage/models_soup/src/item.rs b/rust/cloud-storage/models_soup/src/item.rsindex 743cfc2126..85867cd435 100644--- a/rust/cloud-storage/models_soup/src/item.rs+++ b/rust/cloud-storage/models_soup/src/item.rs@@ -1,6 +1,7 @@use crate::call_record::SoupCallRecord;use crate::document::SoupDocument;use crate::email_thread::SoupEnrichedEmailThreadPreview;+use crate::foreign_entity::SoupForeignEntity;use crate::project::SoupProject;use crate::{chat::SoupChat, comms::SoupChannel};use chrono::{DateTime, Utc};@@ -20,6 +21,7 @@ pub enum SoupItem {EmailThread(SoupEnrichedEmailThreadPreview),Channel(SoupChannel),Call(SoupCallRecord),+ ForeignEntity(SoupForeignEntity),}impl SoupItem {@@ -44,6 +46,9 @@ impl SoupItem {SoupItem::Call(record) => {EntityType::Call.with_entity_string(record.call_id.to_string())}+ SoupItem::ForeignEntity(foreign_entity) => {+ EntityType::ForeignEntity.with_entity_string(foreign_entity.id.to_string())+ }}}@@ -55,6 +60,7 @@ impl SoupItem {SoupItem::EmailThread(soup_thread) => soup_thread.thread.updated_at,SoupItem::Channel(soup_channel) => soup_channel.channel.channel.updated_at,SoupItem::Call(record) => record.ended_at.unwrap_or(record.started_at),+ SoupItem::ForeignEntity(foreign_entity) => foreign_entity.updated_at,}}}@@ -114,6 +120,10 @@ 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),+ (SoupItem::ForeignEntity(foreign_entity), SimpleSortMethod::CreatedAt) => {+ foreign_entity.created_at+ }+ (SoupItem::ForeignEntity(foreign_entity), _) => foreign_entity.updated_at,}}}@@ -129,6 +139,7 @@ impl Identify for SoupItem {SoupItem::EmailThread(thread) => thread.thread.id,SoupItem::Channel(soup_channel) => soup_channel.channel.channel.id.0,SoupItem::Call(record) => record.call_id,+ SoupItem::ForeignEntity(foreign_entity) => foreign_entity.id,}}}@@ -150,7 +161,8 @@ impl SortOn<SimpleSortMethod> for SoupItem {impl SoupItem {/// Converts this item to an [`EntityReference`] for property lookups.///- /// Returns `None` for item types that don't support properties (e.g., channels).+ /// Returns `None` for item types that don't support properties+ /// (e.g., channels, calls, foreign entities).pub fn to_entity_reference(&self) -> Option<EntityReference> {match self {SoupItem::Document(doc) => {@@ -170,6 +182,7 @@ impl SoupItem {)),SoupItem::Channel(_) => None,SoupItem::Call(_) => None,+ SoupItem::ForeignEntity(_) => None,}}}diff --git a/rust/cloud-storage/models_soup/src/lib.rs b/rust/cloud-storage/models_soup/src/lib.rsindex bab24a2da9..121c5d5b25 100644--- a/rust/cloud-storage/models_soup/src/lib.rs+++ b/rust/cloud-storage/models_soup/src/lib.rs@@ -3,6 +3,7 @@ pub mod chat;pub mod comms;pub mod document;pub mod email_thread;+pub mod foreign_entity;pub mod item;pub mod project;pub mod properties;diff --git a/rust/cloud-storage/soup/Cargo.toml b/rust/cloud-storage/soup/Cargo.tomlindex c0644c9886..eebe04ee12 100644--- a/rust/cloud-storage/soup/Cargo.toml+++ b/rust/cloud-storage/soup/Cargo.toml@@ -25,6 +25,7 @@ axum = ["dep:model_user","dep:utoipa","email/axum",+ "email/inbound","item_filters/schema","models_pagination/axum","models_soup/schema",@@ -51,6 +52,7 @@ either = { workspace = true }email = { path = "../email", features = ["ports"] }entity_access = { path = "../entity_access", default-features = false }filter_ast = { path = "../filter_ast" }+foreign_entity = { path = "../foreign_entity", default-features = false, features = ["ports"] }frecency = { path = "../frecency" }item_filters = { path = "../item_filters" }macro_user_id = { path = "../macro_user_id" }diff --git a/rust/cloud-storage/soup/src/domain/models.rs b/rust/cloud-storage/soup/src/domain/models.rsindex 0507fd55ec..66035928cc 100644--- a/rust/cloud-storage/soup/src/domain/models.rs+++ b/rust/cloud-storage/soup/src/domain/models.rs@@ -9,6 +9,10 @@ use call::domain::models::GetCallRecordsRequest;use comms::domain::models::GetChannelsRequest;use email::domain::models::{GetEmailsRequest, PreviewView};use entity_access::domain::models::{EntityAccessReceipt, MemberTeamRole};+use foreign_entity::domain::{+ models::{ForeignEntityError, SourceId},+ ports::ForeignEntityListQuery,+};use frecency::domain::models::{AggregateFrecency, FrecencyQueryErr};use item_filters::{EntityFilters,@@ -370,6 +374,44 @@ impl SoupRequest<Option<EntityFilterAst>> {}?,})}++ pub(crate) fn build_foreign_entity_query(&self) -> Option<ForeignEntityListQuery> {+ match &self.cursor {+ SoupQuery::Simple(SimpleQueryInner(Query::Sort(t, f))) => Some(Query::Sort(+ *t,+ f.as_ref()+ .and_then(|filter| filter.foreign_entity_filter.clone()),+ )),+ SoupQuery::Simple(SimpleQueryInner(Query::Cursor(CursorWithValAndFilter {+ id,+ limit,+ val,+ filter,+ }))) => Some(Query::Cursor(CursorWithValAndFilter {+ id: *id,+ limit: *limit,+ val: val.clone(),+ filter: filter+ .as_ref()+ .and_then(|filter| filter.foreign_entity_filter.clone()),+ })),+ // query by frecency is not implemented for foreign entities+ SoupQuery::Frecency(_) => None,+ }+ }++ pub(crate) fn build_foreign_entity_source_ids(+ &self,+ team_receipt: Option<&EntityAccessReceipt<MemberTeamRole>>,+ ) -> Vec<SourceId> {+ let mut source_ids = vec![SourceId::user(self.user.as_ref())];++ if let Some(receipt) = team_receipt {+ source_ids.push(SourceId::new(receipt.entity().entity_id.clone(), "team"));+ }++ source_ids+ }}/// a [SoupItem] with an associated frecency score@@ -451,5 +493,7 @@ pub enum SoupErr {#[error("A call error has occurred, see logs for more details")]CallErr,#[error(transparent)]+ ForeignEntityErr(#[from] ForeignEntityError),+ #[error(transparent)]AstErr(#[from] ExpandErr),}diff --git a/rust/cloud-storage/soup/src/domain/service.rs b/rust/cloud-storage/soup/src/domain/service.rsindex a09e8fcff1..5b3bd03531 100644--- a/rust/cloud-storage/soup/src/domain/service.rs+++ b/rust/cloud-storage/soup/src/domain/service.rs@@ -16,6 +16,10 @@ use email::domain::{ports::EmailPreviewServiceReadOnly,};use entity_access::domain::models::{EntityAccessReceipt, MemberTeamRole};+use foreign_entity::domain::{+ models::{ForeignEntity, SourceId},+ ports::{ForeignEntityListQuery, ForeignEntityService},+};use frecency::domain::{models::{AggregateId, FrecencyPageRequest, JoinFrecency},ports::FrecencyQueryService,@@ -32,6 +36,7 @@ use models_soup::{SoupAttachment, SoupContact, SoupEmailThreadPreview, SoupEnrichedEmailThreadPreview,SoupLabel,},+ foreign_entity::SoupForeignEntity,item::SoupItem,};use serde::Serialize;@@ -41,8 +46,21 @@ use uuid::Uuid;#[cfg(test)]mod tests;+fn foreign_entity_to_soup_item(entity: ForeignEntity) -> SoupItem {+ SoupItem::ForeignEntity(SoupForeignEntity {+ id: entity.id,+ foreign_entity_id: entity.foreign_entity_id,+ foreign_entity_source: entity.foreign_entity_source,+ metadata: entity.metadata,+ stored_for_id: entity.stored_for_id,+ stored_for_auth_entity: entity.stored_for_auth_entity,+ created_at: entity.created_at,+ updated_at: entity.updated_at,+ })+}+/// struct which handles the actual implementation of soup with abstracted interfaces for mocking-pub struct SoupImpl<T, U, V, C, K> {+pub struct SoupImpl<T, U, V, C, K, F> {/// the interface for interacting with the dbsoup_storage: T,/// the interface for interacting with frecency@@ -53,9 +71,11 @@ pub struct SoupImpl<T, U, V, C, K> {comms_service: C,/// the interface for interacting with call recordscall_record_service: K,+ /// the interface for interacting with foreign entities+ foreign_entity_service: F,}-impl<T, U, V, C, K> SoupImpl<T, U, V, C, K>+impl<T, U, V, C, K, F> SoupImpl<T, U, V, C, K, F>whereT: SoupRepo,anyhow::Error: From<T::Err>,@@ -63,6 +83,7 @@ whereV: EmailPreviewServiceReadOnly,C: ChannelsService,K: CallRecordQueryService,+ F: ForeignEntityService,{pub fn new(soup_storage: T,@@ -70,6 +91,7 @@ whereemail_service: V,comms_service: C,call_record_service: K,+ foreign_entity_service: F,) -> Self {SoupImpl {soup_storage,@@ -77,6 +99,7 @@ whereemail_service,comms_service,call_record_service,+ foreign_entity_service,}}@@ -396,9 +419,32 @@ where})?,))}++ #[tracing::instrument(err, skip(self, source_ids, query))]+ async fn handle_foreign_entity_request(+ &self,+ source_ids: Vec<SourceId>,+ limit: u32,+ query: Option<ForeignEntityListQuery>,+ ) -> Result<impl Iterator<Item = FrecencySoupItem>, SoupErr> {+ let Some(query) = query else {+ return Ok(Either::Left(None.into_iter()));+ };++ Ok(Either::Right(+ self.foreign_entity_service+ .get_foreign_entities_for_user(source_ids, limit, query)+ .await?+ .into_iter()+ .map(|entity| FrecencySoupItem {+ item: foreign_entity_to_soup_item(entity),+ frecency_score: None,+ }),+ ))+ }}-impl<T, U, V, C, K> SoupService for SoupImpl<T, U, V, C, K>+impl<T, U, V, C, K, F> SoupService for SoupImpl<T, U, V, C, K, F>whereT: SoupRepo,anyhow::Error: From<T::Err>,@@ -406,6 +452,7 @@ whereV: EmailPreviewServiceReadOnly,C: ChannelsService,K: CallRecordQueryService,+ F: ForeignEntityService,{#[tracing::instrument(err, skip(self, req, team_receipt))]async fn get_user_soup<R>(@@ -421,6 +468,8 @@ wherelet req = req.into_ast()?;let limit = req.limit.clamp(20, 500);+ let foreign_entity_source_ids = req.build_foreign_entity_source_ids(team_receipt.as_ref());+ let foreign_entity_query = req.build_foreign_entity_query();let email_request = req.build_email_request(team_receipt);let comms_request = req.build_comms_request();let call_request = req.build_call_request();@@ -444,13 +493,25 @@ wherelet call_soup_fut = self.handle_call_request(call_request);- let (main_soup, email_soup, comms_soup, call_soup) =- tokio::join!(main_soup_fut, email_soup_fut, comms_soup_fut, call_soup_fut);+ let foreign_entity_soup_fut = self.handle_foreign_entity_request(+ foreign_entity_source_ids,+ limit as u32,+ foreign_entity_query,+ );++ let (main_soup, email_soup, comms_soup, call_soup, foreign_entity_soup) = tokio::join!(+ main_soup_fut,+ email_soup_fut,+ comms_soup_fut,+ call_soup_fut,+ foreign_entity_soup_fut,+ );let page = main_soup?.chain(email_soup?).chain(comms_soup?).chain(call_soup?)+ .chain(foreign_entity_soup?).paginate_on(limit.into(), sort_method).filter_on(entity_filter.clone()).sort_desc()diff --git a/rust/cloud-storage/soup/src/domain/service/tests.rs b/rust/cloud-storage/soup/src/domain/service/tests.rsindex 6c0d8046bc..c557f00980 100644--- a/rust/cloud-storage/soup/src/domain/service/tests.rs+++ b/rust/cloud-storage/soup/src/domain/service/tests.rs@@ -5,11 +5,20 @@ use chrono::{DateTime, Utc};use comms::domain::models::GetChannelsRequest;use cool_asserts::assert_matches;use email::domain::models::{EnrichedEmailThreadPreview, PreviewView};+use filter_ast::Expr;+use foreign_entity::domain::{+ models::{+ CreateForeignEntity, ForeignEntity, ForeignEntityError, PatchForeignEntity, SourceId,+ },+ ports::{ForeignEntityListQuery, ForeignEntityService},+};use frecency::domain::models::{FrecencyPageRequest, FrecencyPageResponse};use frecency::domain::ports::MockFrecencyQueryService;use frecency::domain::services::FrecencyQueryServiceImpl;use frecency::{domain::models::AggregateFrecency, outbound::mock::MockFrecencyStorage};-use item_filters::EntityFilters;+use item_filters::{+ EntityFilters, ForeignEntityFilters, ast::foreign_entity::ForeignEntityLiteral,+};use model_entity::EntityType;use models_pagination::{Cursor, CursorVal, CursorWithValAndFilter, FrecencyValue, PaginatedCursor, SimpleSortMethod,@@ -18,6 +27,7 @@ use models_pagination::{use models_soup::document::{SoupDocument, SoupDocumentSubType};use ordered_float::OrderedFloat;use rootcause::Report;+use std::sync::{Arc, Mutex};use uuid::Uuid;use super::*;@@ -75,6 +85,207 @@ impl CallRecordQueryService for NoopCallRecordQueryService {}}+#[derive(Clone)]+struct NoopForeignEntityService;++impl ForeignEntityService for NoopForeignEntityService {+ async fn get_foreign_entity_by_id(+ &self,+ id: Uuid,+ ) -> Result<ForeignEntity, ForeignEntityError> {+ Err(ForeignEntityError::NotFound(id))+ }++ async fn get_foreign_entities_by_foreign_entity_id(+ &self,+ _foreign_entity_id: &str,+ _foreign_entity_source: Option<&str>,+ ) -> Result<Vec<ForeignEntity>, ForeignEntityError> {+ Ok(Vec::new())+ }++ async fn get_foreign_entities_for_user(+ &self,+ _source_ids: Vec<SourceId>,+ _limit: u32,+ _query: ForeignEntityListQuery,+ ) -> Result<Vec<ForeignEntity>, ForeignEntityError> {+ Ok(Vec::new())+ }++ async fn create_foreign_entity(+ &self,+ _create: CreateForeignEntity,+ ) -> Result<ForeignEntity, ForeignEntityError> {+ unreachable!("NoopForeignEntityService does not create foreign entities")+ }++ async fn delete_foreign_entity(&self, _id: Uuid) -> Result<(), ForeignEntityError> {+ unreachable!("NoopForeignEntityService does not delete foreign entities")+ }++ async fn patch_foreign_entity(+ &self,+ _id: Uuid,+ _patch: PatchForeignEntity,+ ) -> Result<ForeignEntity, ForeignEntityError> {+ unreachable!("NoopForeignEntityService does not patch foreign entities")+ }+}++#[derive(Clone)]+struct RecordingForeignEntityService {+ state: Arc<RecordingForeignEntityState>,+}++struct RecordingForeignEntityState {+ calls: Mutex<Vec<RecordedForeignEntityCall>>,+ entities: Vec<ForeignEntity>,+}++#[derive(Clone)]+struct RecordedForeignEntityCall {+ source_ids: Vec<SourceId>,+ limit: u32,+ query: ForeignEntityListQuery,+}++fn foreign_entity_matches_filter(+ entity: &ForeignEntity,+ filter: &Option<Arc<Expr<ForeignEntityLiteral>>>,+) -> bool {+ filter+ .as_deref()+ .map(|expr| foreign_entity_matches_expr(entity, expr))+ .unwrap_or(true)+}++fn foreign_entity_matches_expr(entity: &ForeignEntity, expr: &Expr<ForeignEntityLiteral>) -> bool {+ match expr {+ Expr::And(left, right) => {+ foreign_entity_matches_expr(entity, left) && foreign_entity_matches_expr(entity, right)+ }+ Expr::Or(left, right) => {+ foreign_entity_matches_expr(entity, left) || foreign_entity_matches_expr(entity, right)+ }+ Expr::Not(inner) => !foreign_entity_matches_expr(entity, inner),+ Expr::Literal(literal) => foreign_entity_matches_literal(entity, literal),+ }+}++fn foreign_entity_matches_literal(entity: &ForeignEntity, literal: &ForeignEntityLiteral) -> bool {+ match literal {+ ForeignEntityLiteral::Id(id) => entity.id == *id,+ ForeignEntityLiteral::ForeignEntityId(id) => {+ entity.foreign_entity_id.as_str() == id.as_str()+ }+ ForeignEntityLiteral::ForeignEntitySource(source) => {+ entity.foreign_entity_source.as_str() == source.as_str()+ }+ }+}++impl RecordingForeignEntityService {+ fn new(entities: Vec<ForeignEntity>) -> Self {+ Self {+ state: Arc::new(RecordingForeignEntityState {+ calls: Mutex::new(Vec::new()),+ entities,+ }),+ }+ }++ fn calls(&self) -> Vec<RecordedForeignEntityCall> {+ self.state.calls.lock().unwrap().clone()+ }+}++impl ForeignEntityService for RecordingForeignEntityService {+ async fn get_foreign_entity_by_id(+ &self,+ id: Uuid,+ ) -> Result<ForeignEntity, ForeignEntityError> {+ self.state+ .entities+ .iter()+ .find(|entity| entity.id == id)+ .cloned()+ .ok_or(ForeignEntityError::NotFound(id))+ }++ async fn get_foreign_entities_by_foreign_entity_id(+ &self,+ foreign_entity_id: &str,+ foreign_entity_source: Option<&str>,+ ) -> Result<Vec<ForeignEntity>, ForeignEntityError> {+ Ok(self+ .state+ .entities+ .iter()+ .filter(|entity| entity.foreign_entity_id == foreign_entity_id)+ .filter(|entity| {+ foreign_entity_source+ .map(|source| entity.foreign_entity_source == source)+ .unwrap_or(true)+ })+ .cloned()+ .collect())+ }++ async fn get_foreign_entities_for_user(+ &self,+ source_ids: Vec<SourceId>,+ limit: u32,+ query: ForeignEntityListQuery,+ ) -> Result<Vec<ForeignEntity>, ForeignEntityError> {+ let filter = query.filter().clone();++ self.state+ .calls+ .lock()+ .unwrap()+ .push(RecordedForeignEntityCall {+ source_ids: source_ids.clone(),+ limit,+ query,+ });++ Ok(self+ .state+ .entities+ .iter()+ .filter(|entity| {+ source_ids.iter().any(|source_id| {+ entity.stored_for_id.as_str() == source_id.id.as_str()+ && entity.stored_for_auth_entity.as_str() == source_id.auth_entity.as_str()+ })+ })+ .filter(|entity| foreign_entity_matches_filter(entity, &filter))+ .take(limit as usize)+ .cloned()+ .collect())+ }++ async fn create_foreign_entity(+ &self,+ _create: CreateForeignEntity,+ ) -> Result<ForeignEntity, ForeignEntityError> {+ unreachable!("RecordingForeignEntityService does not create foreign entities")+ }++ async fn delete_foreign_entity(&self, _id: Uuid) -> Result<(), ForeignEntityError> {+ unreachable!("RecordingForeignEntityService does not delete foreign entities")+ }++ async fn patch_foreign_entity(+ &self,+ _id: Uuid,+ _patch: PatchForeignEntity,+ ) -> Result<ForeignEntity, ForeignEntityError> {+ unreachable!("RecordingForeignEntityService does not patch foreign entities")+ }+}+fn soup_document(id: &str) -> SoupDocument {// Create a deterministic UUID from the string IDlet uuid = Uuid::parse_str(id).unwrap_or_else(|_| {@@ -134,6 +345,267 @@ fn soup_document_with_is_completed(}}+fn foreign_entity_for_source(+ id: Uuid,+ stored_for_id: impl Into<String>,+ stored_for_auth_entity: impl Into<String>,+ updated_at: DateTime<Utc>,+) -> ForeignEntity {+ ForeignEntity {+ id,+ foreign_entity_id: format!("external-{id}"),+ foreign_entity_source: "github".to_string(),+ metadata: serde_json::json!({}),+ stored_for_id: stored_for_id.into(),+ stored_for_auth_entity: stored_for_auth_entity.into(),+ created_at: DateTime::default(),+ updated_at,+ }+}++#[tokio::test]+async fn simple_soup_includes_foreign_entities() {+ let user = MacroUserIdStr::parse_from_str("macro|[email protected]").unwrap();+ let foreign_entity_id = Uuid::from_u128(2);+ let foreign_entity_service =+ RecordingForeignEntityService::new(vec![foreign_entity_for_source(+ foreign_entity_id,+ user.as_ref(),+ "user",+ DateTime::default() + Days::new(2),+ )]);++ let mut soup_mock = MockSoupRepo::new();+ soup_mock+ .expect_unexpanded_generic_cursor_soup()+ .times(1)+ .returning(|_params| {+ Box::pin(async move {+ Ok(vec![SoupItem::Document(soup_document_with_updated(+ "my-document-1",+ DateTime::default() + Days::new(1),+ ))])+ })+ });++ let page = SoupImpl::new(+ soup_mock,+ FrecencyQueryServiceImpl::new(MockFrecencyStorage::new()),+ NoopEmailPreviewService,+ NoopCommsService,+ NoopCallRecordQueryService,+ foreign_entity_service.clone(),+ )+ .get_user_soup(+ SoupRequest {+ email_preview_view: PreviewView::StandardLabel(+ email::domain::models::PreviewViewStandardLabel::Inbox,+ ),+ link_id: None,+ soup_type: SoupType::UnExpanded,+ limit: 20,+ cursor: SoupQuery::new_sort_simple(+ SimpleSortMethod::UpdatedAt,+ EntityFilters::default(),+ ),+ user: user.clone(),+ },+ None,+ )+ .await+ .unwrap()+ .unwrap_left();++ assert_eq!(page.items.len(), 2);+ assert_matches!(+ &page.items[0].item,+ SoupItem::ForeignEntity(entity) => assert_eq!(entity.id, foreign_entity_id)+ );+ assert_matches!(&page.items[1].item, SoupItem::Document(_));++ let calls = foreign_entity_service.calls();+ assert_eq!(calls.len(), 1);+ assert_eq!(calls[0].limit, 20);+ assert_eq!(calls[0].source_ids, vec![SourceId::user(user.as_ref())]);+ assert!(calls[0].query.filter().is_none());+}++#[tokio::test]+async fn frecency_soup_does_not_query_foreign_entities() {+ let user = MacroUserIdStr::parse_from_str("macro|[email protected]").unwrap();+ let foreign_entity_service =+ RecordingForeignEntityService::new(vec![foreign_entity_for_source(+ Uuid::from_u128(42),+ user.as_ref(),+ "user",+ DateTime::default(),+ )]);++ let mut frecency = MockFrecencyQueryService::new();+ frecency+ .expect_get_frecency_page()+ .times(1)+ .returning(|params| {+ let iter = (1..=params.limit).map(|v| {+ AggregateFrecency::new_mock(+ EntityType::Document.with_entity_string(Uuid::from_u128(v as u128).to_string()),+ v.into(),+ )+ });+ Box::pin(async move { Ok(FrecencyPageResponse::new_mock(iter)) })+ });++ let mut soup = MockSoupRepo::new();+ soup.expect_unexpanded_soup_by_ids()+ .times(1)+ .returning(|params| {+ let vec = params+ .entities+ .iter()+ .map(|entity| soup_document(&entity.entity_id))+ .map(SoupItem::Document)+ .collect();+ Box::pin(async move { Ok(vec) })+ });++ SoupImpl::new(+ soup,+ frecency,+ NoopEmailPreviewService,+ NoopCommsService,+ NoopCallRecordQueryService,+ foreign_entity_service.clone(),+ )+ .get_user_soup(+ SoupRequest {+ email_preview_view: PreviewView::StandardLabel(+ email::domain::models::PreviewViewStandardLabel::Inbox,+ ),+ link_id: None,+ soup_type: SoupType::UnExpanded,+ limit: 20,+ cursor: SoupQuery::new_sort_frecency(Frecency, EntityFilters::default()),+ user,+ },+ None,+ )+ .await+ .unwrap();++ assert!(foreign_entity_service.calls().is_empty());+}++#[tokio::test]+async fn team_receipt_contributes_team_foreign_entity_source_id() {+ let user = MacroUserIdStr::parse_from_str("macro|[email protected]").unwrap();+ let team_id = Uuid::from_u128(100);+ let foreign_entity_service = RecordingForeignEntityService::new(Vec::new());++ let mut soup_mock = MockSoupRepo::new();+ soup_mock+ .expect_unexpanded_generic_cursor_soup()+ .times(1)+ .returning(|_params| Box::pin(async move { Ok(Vec::new()) }));++ let team_receipt = entity_access::domain::models::EntityAccessReceipt::<MemberTeamRole>::dangerously_assert_authenticated_user(+ user.clone(),+ &team_id.to_string(),+ EntityType::Team,+ );++ SoupImpl::new(+ soup_mock,+ FrecencyQueryServiceImpl::new(MockFrecencyStorage::new()),+ NoopEmailPreviewService,+ NoopCommsService,+ NoopCallRecordQueryService,+ foreign_entity_service.clone(),+ )+ .get_user_soup(+ SoupRequest {+ email_preview_view: PreviewView::StandardLabel(+ email::domain::models::PreviewViewStandardLabel::Inbox,+ ),+ link_id: None,+ soup_type: SoupType::UnExpanded,+ limit: 20,+ cursor: SoupQuery::new_sort_simple(+ SimpleSortMethod::UpdatedAt,+ EntityFilters::default(),+ ),+ user: user.clone(),+ },+ Some(team_receipt),+ )+ .await+ .unwrap();++ let calls = foreign_entity_service.calls();+ assert_eq!(calls.len(), 1);+ assert_eq!(+ calls[0].source_ids,+ vec![+ SourceId::user(user.as_ref()),+ SourceId::new(team_id.to_string(), "team"),+ ]+ );+}++#[tokio::test]+async fn foreign_entity_filter_suppresses_non_matching_foreign_entities() {+ let user = MacroUserIdStr::parse_from_str("macro|[email protected]").unwrap();+ let foreign_entity_service =+ RecordingForeignEntityService::new(vec![foreign_entity_for_source(+ Uuid::from_u128(1),+ user.as_ref(),+ "user",+ DateTime::default(),+ )]);++ let mut soup_mock = MockSoupRepo::new();+ soup_mock+ .expect_unexpanded_generic_cursor_soup()+ .times(1)+ .returning(|_params| Box::pin(async move { Ok(Vec::new()) }));++ let page = SoupImpl::new(+ soup_mock,+ FrecencyQueryServiceImpl::new(MockFrecencyStorage::new()),+ NoopEmailPreviewService,+ NoopCommsService,+ NoopCallRecordQueryService,+ foreign_entity_service.clone(),+ )+ .get_user_soup(+ SoupRequest {+ email_preview_view: PreviewView::StandardLabel(+ email::domain::models::PreviewViewStandardLabel::Inbox,+ ),+ link_id: None,+ soup_type: SoupType::UnExpanded,+ limit: 20,+ cursor: SoupQuery::new_sort_simple(+ SimpleSortMethod::UpdatedAt,+ EntityFilters {+ foreign_entity_filters: ForeignEntityFilters {+ ids: vec![Uuid::from_u128(2).to_string()],+ ..Default::default()+ },+ ..Default::default()+ },+ ),+ user,+ },+ None,+ )+ .await+ .unwrap()+ .unwrap_left();++ assert!(page.items.is_empty());+ assert!(foreign_entity_service.calls()[0].query.filter().is_some());+}+#[tokio::test]async fn it_should_not_query_frecency() {let mut soup_mock = MockSoupRepo::new();@@ -174,6 +646,7 @@ async fn it_should_not_query_frecency() {NoopEmailPreviewService,NoopCommsService,NoopCallRecordQueryService,+ NoopForeignEntityService,).get_user_soup(SoupRequest {@@ -259,6 +732,7 @@ async fn it_should_query_frecency() {NoopEmailPreviewService,NoopCommsService,NoopCallRecordQueryService,+ NoopForeignEntityService,).get_user_soup(SoupRequest {@@ -341,6 +815,7 @@ async fn it_should_sort_frecency_descending() {NoopEmailPreviewService,NoopCommsService,NoopCallRecordQueryService,+ NoopForeignEntityService,).get_user_soup(SoupRequest {@@ -437,6 +912,7 @@ async fn frecency_should_fallback() {NoopEmailPreviewService,NoopCommsService,NoopCallRecordQueryService,+ NoopForeignEntityService,).get_user_soup(SoupRequest {@@ -517,6 +993,7 @@ async fn frecency_should_paginate() {NoopEmailPreviewService,NoopCommsService,NoopCallRecordQueryService,+ NoopForeignEntityService,).get_user_soup(SoupRequest {@@ -599,6 +1076,7 @@ async fn frecency_should_resume_cursor() {NoopEmailPreviewService,NoopCommsService,NoopCallRecordQueryService,+ NoopForeignEntityService,).get_user_soup(SoupRequest {@@ -697,6 +1175,7 @@ async fn frecency_fallback_cursor_should_resume() {NoopEmailPreviewService,NoopCommsService,NoopCallRecordQueryService,+ NoopForeignEntityService,).get_user_soup(SoupRequest {@@ -771,6 +1250,7 @@ async fn cursor_should_return_simple_sort() {NoopEmailPreviewService,NoopCommsService,NoopCallRecordQueryService,+ NoopForeignEntityService,).get_user_soup(SoupRequest {@@ -841,6 +1321,7 @@ async fn cursor_should_return_frecency() {NoopEmailPreviewService,NoopCommsService,NoopCallRecordQueryService,+ NoopForeignEntityService,).get_user_soup(SoupRequest {@@ -901,6 +1382,7 @@ async fn it_should_return_is_completed_true_for_completed_tasks() {NoopEmailPreviewService,NoopCommsService,NoopCallRecordQueryService,+ NoopForeignEntityService,).get_user_soup(SoupRequest {@@ -951,6 +1433,7 @@ async fn it_should_return_is_completed_false_for_incomplete_tasks() {NoopEmailPreviewService,NoopCommsService,NoopCallRecordQueryService,+ NoopForeignEntityService,).get_user_soup(SoupRequest {@@ -1001,6 +1484,7 @@ async fn it_should_return_is_completed_none_for_non_tasks() {NoopEmailPreviewService,NoopCommsService,NoopCallRecordQueryService,+ NoopForeignEntityService,).get_user_soup(SoupRequest {@@ -1063,6 +1547,7 @@ async fn it_should_preserve_is_completed_for_mixed_items() {NoopEmailPreviewService,NoopCommsService,NoopCallRecordQueryService,+ NoopForeignEntityService,).get_user_soup(SoupRequest {@@ -1144,6 +1629,7 @@ async fn it_should_preserve_is_completed_in_by_ids_queries() {NoopEmailPreviewService,NoopCommsService,NoopCallRecordQueryService,+ NoopForeignEntityService,).get_user_soup(SoupRequest {diff --git a/rust/cloud-storage/soup/src/inbound/axum_router.rs b/rust/cloud-storage/soup/src/inbound/axum_router.rsindex 5a00c4c318..887ba6362d 100644--- a/rust/cloud-storage/soup/src/inbound/axum_router.rs+++ b/rust/cloud-storage/soup/src/inbound/axum_router.rs@@ -40,6 +40,7 @@ use item_filters::{chat::ChatLiteral,document::DocumentLiteral,email::EmailLiteral,+ foreign_entity::ForeignEntityLiteral,project::ProjectLiteral,properties::{PropertiesLiteral, PropertyEntityType},},@@ -842,6 +843,10 @@ pub struct ApiEntityFilterAst {#[serde(default, rename = "chanf")]#[schema(value_type = serde_json::Value)]pub channel_filter: LiteralTree<ChannelLiteral>,+ /// the filters that should be applied to foreign entity records+ #[serde(default, rename = "fef")]+ #[schema(value_type = serde_json::Value)]+ pub foreign_entity_filter: LiteralTree<ForeignEntityLiteral>,/// the filters that should be applied to the call entity#[serde(default, rename = "callf")]#[schema(value_type = serde_json::Value)]@@ -926,6 +931,7 @@ impl ApiEntityFilterAst {chat_filter,email_filter,channel_filter,+ foreign_entity_filter,call_filter,properties_filter,email_crm_domains,@@ -991,6 +997,7 @@ impl ApiEntityFilterAst {},channel_filter,call_filter,+ foreign_entity_filter,properties_filter,})}diff --git a/rust/cloud-storage/soup/src/inbound/axum_router/tests.rs b/rust/cloud-storage/soup/src/inbound/axum_router/tests.rsindex 8a27dc761d..97c930573a 100644--- a/rust/cloud-storage/soup/src/inbound/axum_router/tests.rs+++ b/rust/cloud-storage/soup/src/inbound/axum_router/tests.rs@@ -13,8 +13,8 @@ use item_filters::EntityFilters;use macro_user_id::{email::EmailStr, user_id::MacroUserIdStr};use model_user::UserContext;use models_pagination::{- CursorVal, Frecency, FrecencyValue, Identify, PaginateOn, Query, SimpleSortMethod, SortOn,- TypeEraseCursor,+ CursorVal, CursorWithValAndFilter, Frecency, FrecencyValue, Identify, PaginateOn, Query,+ SimpleSortMethod, SortOn, TypeEraseCursor,};use serde::Serialize;use serde_json::json;@@ -1195,6 +1195,76 @@ async fn ast_endpoint_passes_through_plain_document_literal() {assert_eq!(doc_json, json!({ "l": { "id": doc_id.to_string() } }));}+#[tokio::test]+async fn ast_endpoint_passes_through_foreign_entity_filter() {+ let soup = MockSoup::new();+ let inner_counter = soup.called.clone();+ let router: Router = soup_router(SoupRouterState::new(+ soup,+ MockEmailLinkResult {+ get_link_result: Arc::new(|| Ok(None)),+ },+ Arc::new(MockEntityAccess),+ ))+ .layer(Extension(UserContext {+ user_id: "macro|[email protected]".to_string(),+ fusion_user_id: "1234".to_string(),+ permissions: None,+ organization_id: None,+ }));++ let request = Request::builder()+ .uri("/soup/ast")+ .method(Method::POST)+ .header("content-type", "application/json")+ .body(axum::body::Body::from(+ serde_json::to_vec(&json!({+ "fef": { "l": { "feid": "github:123" } }+ }))+ .unwrap(),+ ))+ .unwrap();++ let _res = router.oneshot(request).await.unwrap();++ let arg = {+ let mut guard = inner_counter.lock().unwrap();+ guard+ .pop()+ .expect("SoupService::handle should have been called")+ };++ let filter: EntityFilterAst = serde_json::from_value(arg.expanded_filter).unwrap();+ let foreign_entity_tree = filter+ .foreign_entity_filter+ .expect("foreign_entity_filter should be set");+ let foreign_entity_json = serde_json::to_value(foreign_entity_tree.as_ref()).unwrap();+ assert_eq!(+ foreign_entity_json,+ json!({ "l": { "feid": "github:123" } })+ );+}++#[test]+fn ast_cursor_without_foreign_entity_filter_deserializes() {+ let cursor_json = json!({+ "id": Uuid::new_v4(),+ "limit": 20,+ "val": {+ "sort_type": "updated_at",+ "last_val": Utc::now(),+ },+ "filter": {+ "df": { "l": { "id": Uuid::new_v4().to_string() } }+ }+ });++ let cursor: CursorWithValAndFilter<Uuid, SimpleSortMethod, ApiEntityFilterAst> =+ serde_json::from_value(cursor_json).unwrap();++ assert!(cursor.filter.foreign_entity_filter.is_none());+}+#[tokio::test]async fn ast_endpoint_expands_file_assoc_image_to_or_tree() {let soup = MockSoup::new();diff --git a/rust/cloud-storage/soup/src/inbound/toolset/list_entities.rs b/rust/cloud-storage/soup/src/inbound/toolset/list_entities.rsindex 9b589f1418..2690cbde22 100644--- a/rust/cloud-storage/soup/src/inbound/toolset/list_entities.rs+++ b/rust/cloud-storage/soup/src/inbound/toolset/list_entities.rs@@ -12,7 +12,8 @@ use item_filters::{SharedEmailFilter,ast::{EntityFilterAst, LiteralTree, call::CallLiteral, channel::ChannelLiteral,- chat::ChatLiteral, document::DocumentLiteral, email::EmailLiteral, project::ProjectLiteral,+ chat::ChatLiteral, document::DocumentLiteral, email::EmailLiteral,+ foreign_entity::ForeignEntityLiteral, project::ProjectLiteral,properties::PropertiesLiteral,},};@@ -76,6 +77,7 @@ pub enum ItemType {Email,Channel,Call,+ ForeignEntity,}#[derive(Debug, Serialize, JsonSchema)]@@ -93,6 +95,13 @@ pub enum EntityItem {Channel { id: Uuid, name: Option<String> },#[serde(rename_all = "camelCase")]Call { id: Uuid, created_by: String },+ #[serde(rename_all = "camelCase")]+ ForeignEntity {+ id: Uuid,+ foreign_entity_id: String,+ foreign_entity_source: String,+ metadata: serde_json::Value,+ },}impl From<SoupItem> for EntityItem {@@ -122,6 +131,12 @@ impl From<SoupItem> for EntityItem {id: record.call_id,created_by: record.created_by,},+ SoupItem::ForeignEntity(foreign_entity) => EntityItem::ForeignEntity {+ id: foreign_entity.id,+ foreign_entity_id: foreign_entity.foreign_entity_id,+ foreign_entity_source: foreign_entity.foreign_entity_source,+ metadata: foreign_entity.metadata,+ },}}}@@ -137,7 +152,7 @@ pub struct ListEntitiesResponse {#[serde(rename_all = "camelCase")]#[schemars(title = "ListEntities",- description = "Browse the user's workspace to see recent items they have access to. Returns documents, AI conversations, projects, emails, and chat channels. Use this to get an overview of what the user has been working on or to find items by type. For finding specific items by name or content, use the search tool instead."+ description = "Browse the user's workspace to see recent items they have access to. Returns documents, AI conversations, projects, emails, chat channels, call records, and foreign entities. Use this to get an overview of what the user has been working on or to find items by type. For finding specific items by name or content, use the search tool instead.")]pub struct ListEntities {#[schemars(@@ -200,6 +215,13 @@ pub struct ListEntities {#[serde(default, rename = "callf")]pub call_filter: LiteralTree<CallLiteral>,+ #[schemars(+ description = "Full soup AST foreign entity filter (fef).",+ with = "Option<serde_json::Value>"+ )]+ #[serde(default, rename = "fef")]+ pub foreign_entity_filter: LiteralTree<ForeignEntityLiteral>,+#[schemars(description = "Full soup AST property filter (propf).",with = "Option<serde_json::Value>"@@ -240,6 +262,7 @@ impl ListEntities {},channel_filter: self.channel_filter.clone(),call_filter: self.call_filter.clone(),+ foreign_entity_filter: self.foreign_entity_filter.clone(),properties_filter: self.properties_filter.clone(),};@@ -288,6 +311,11 @@ impl ListEntities {} else {Some(Arc::new(Expr::val(CallLiteral::CallId(Uuid::nil()))))},+ foreign_entity_filter: if include_types.contains(&ItemType::ForeignEntity) {+ ast.foreign_entity_filter+ } else {+ Some(Arc::new(Expr::val(ForeignEntityLiteral::Id(Uuid::nil()))))+ },properties_filter: ast.properties_filter,}}@@ -401,6 +429,7 @@ pub(super) fn build_summary(let mut emails = 0;let mut channels = 0;let mut call_records = 0;+ let mut foreign_entities = 0;for item in items {match item {@@ -410,6 +439,7 @@ pub(super) fn build_summary(EntityItem::Email { .. } => emails += 1,EntityItem::Channel { .. } => channels += 1,EntityItem::Call { .. } => call_records += 1,+ EntityItem::ForeignEntity { .. } => foreign_entities += 1,}}@@ -450,6 +480,14 @@ pub(super) fn build_summary(if call_records == 1 { "" } else { "s" }));}+ if foreign_entities > 0 {+ let label = if foreign_entities == 1 {+ "foreign entity"+ } else {+ "foreign entities"+ };+ parts.push(format!("{foreign_entities} {label}"));+ }let counts = parts.join(", ");if has_more {diff --git a/rust/cloud-storage/soup/src/inbound/toolset/test.rs b/rust/cloud-storage/soup/src/inbound/toolset/test.rsindex a14c31bdc7..d95ee49c07 100644--- a/rust/cloud-storage/soup/src/inbound/toolset/test.rs+++ b/rust/cloud-storage/soup/src/inbound/toolset/test.rs@@ -3,6 +3,8 @@ use super::list_entities::build_summary;use super::*;use ai_toolset::generate_tool_input_schema;use ai_toolset::tool_object::validate_tool_schema;+use chrono::Utc;+use models_soup::{foreign_entity::SoupForeignEntity, item::SoupItem};use non_empty::IsEmpty;use uuid::Uuid;@@ -43,15 +45,19 @@ fn test_full_ast_input_deserializes() {{"l": {"Shared": "exclude"}}]},"emailView": "inbox",+ "fef": {"l": {"feid": "github:123"}},"limit": 100,"pf": {"l": {"pid": "00000000-0000-0000-0000-000000000000"}},"sortBy": "recently_updated"});let list: ListEntities = serde_json::from_value(input).unwrap();+ let ast = list.entity_filter_ast();+assert_eq!(list.limit, Some(100));assert!(matches!(list.sort_by, SortBy::RecentlyUpdated));- assert!(!list.entity_filter_ast().is_empty());+ assert!(!ast.is_empty());+ assert!(ast.foreign_entity_filter.is_some());assert_eq!(list.email_view().unwrap(),email::domain::models::PreviewView::default()@@ -72,6 +78,7 @@ fn test_email_preset_defaults_to_email_results() {assert!(ast.chat_filter.is_some());assert!(ast.channel_filter.is_some());assert!(ast.call_filter.is_some());+ assert!(ast.foreign_entity_filter.is_some());assert_eq!(list.effective_include_types(), Some(vec![ItemType::Email]));}@@ -84,12 +91,34 @@ fn test_include_types_document_without_filter_keeps_document_unfiltered() {let ast = list.entity_filter_ast();assert!(ast.document_filter.is_none());+ assert!(ast.foreign_entity_filter.is_some());assert_eq!(list.effective_include_types(),Some(vec![ItemType::Document]));}+#[test]+fn test_include_types_foreign_entity_without_filter_keeps_foreign_entity_unfiltered() {+ let list: ListEntities = serde_json::from_value(serde_json::json!({+ "includeTypes": ["foreign_entity"]+ }))+ .unwrap();++ let ast = list.entity_filter_ast();+ assert!(ast.document_filter.is_some());+ assert!(ast.project_filter.is_some());+ assert!(ast.chat_filter.is_some());+ assert!(ast.email_filter.tree.is_some());+ assert!(ast.channel_filter.is_some());+ assert!(ast.call_filter.is_some());+ assert!(ast.foreign_entity_filter.is_none());+ assert_eq!(+ list.effective_include_types(),+ Some(vec![ItemType::ForeignEntity])+ );+}+#[test]fn test_build_summary_empty() {let summary = build_summary(&[], false, &None);@@ -114,17 +143,57 @@ fn test_build_summary_with_items() {id: Uuid::new_v4(),subject: Some("Hello".to_string()),},+ EntityItem::ForeignEntity {+ id: Uuid::new_v4(),+ foreign_entity_id: "github:123".to_string(),+ foreign_entity_source: "github".to_string(),+ metadata: serde_json::json!({ "name": "Issue 123" }),+ },];let summary = build_summary(&items, false, &None);assert!(summary.contains("2 documents"));assert!(summary.contains("1 email"));+ assert!(summary.contains("1 foreign entity"));assert!(summary.starts_with("Found"));let summary = build_summary(&items, true, &None);assert!(summary.contains("More items available"));}+#[test]+fn test_converts_foreign_entity_soup_item() {+ let id = Uuid::new_v4();+ let metadata = serde_json::json!({ "name": "Issue 123" });+ let item = SoupItem::ForeignEntity(SoupForeignEntity {+ id,+ foreign_entity_id: "github:123".to_string(),+ foreign_entity_source: "github".to_string(),+ metadata: metadata.clone(),+ stored_for_id: "team-123".to_string(),+ stored_for_auth_entity: "team".to_string(),+ created_at: Utc::now(),+ updated_at: Utc::now(),+ });++ let entity_item = EntityItem::from(item);++ match entity_item {+ EntityItem::ForeignEntity {+ id: actual_id,+ foreign_entity_id,+ foreign_entity_source,+ metadata: actual_metadata,+ } => {+ assert_eq!(actual_id, id);+ assert_eq!(foreign_entity_id, "github:123");+ assert_eq!(foreign_entity_source, "github");+ assert_eq!(actual_metadata, metadata);+ }+ other => panic!("expected foreign entity item, got {other:?}"),+ }+}+// run `cargo test -p soup inbound::toolset::test::print_input_schema -- --nocapture --include-ignored`#[test]#[ignore = "prints the input schema"]diff --git a/rust/cloud-storage/soup/src/outbound/pg_soup_repo.rs b/rust/cloud-storage/soup/src/outbound/pg_soup_repo.rsindex cd6ab72202..5e7c78d416 100644--- a/rust/cloud-storage/soup/src/outbound/pg_soup_repo.rs+++ b/rust/cloud-storage/soup/src/outbound/pg_soup_repo.rs@@ -198,7 +198,7 @@ pub(crate) async fn populate_properties(SoupItem::Project(x) => properties_map.get(&x.id.to_string()),SoupItem::EmailThread(x) => properties_map.get(&x.thread.id.to_string()),SoupItem::Chat(x) => properties_map.get(&x.id.to_string()),- SoupItem::Channel(_) | SoupItem::Call(_) => None,+ SoupItem::Channel(_) | SoupItem::Call(_) | SoupItem::ForeignEntity(_) => None,};if let Some(props) = props {let soup_props: Vec<SoupProperty> =@@ -208,7 +208,7 @@ pub(crate) async fn populate_properties(SoupItem::Project(x) => x.properties = soup_props,SoupItem::EmailThread(x) => x.properties = soup_props,SoupItem::Chat(x) => x.properties = soup_props,- SoupItem::Channel(_) | SoupItem::Call(_) => {}+ SoupItem::Channel(_) | SoupItem::Call(_) | SoupItem::ForeignEntity(_) => {}}}}diff --git a/rust/cloud-storage/soup/src/outbound/pg_soup_repo/expanded/tests.rs b/rust/cloud-storage/soup/src/outbound/pg_soup_repo/expanded/tests.rsindex c862d7cce4..e80d6198bf 100644--- a/rust/cloud-storage/soup/src/outbound/pg_soup_repo/expanded/tests.rs+++ b/rust/cloud-storage/soup/src/outbound/pg_soup_repo/expanded/tests.rs@@ -365,7 +365,8 @@ async fn test_expanded_soup_by_ids(pool: Pool<Postgres>) {| SoupItem::Project(_)| SoupItem::EmailThread(_)| SoupItem::Channel(_)- | SoupItem::Call(_) => None,+ | SoupItem::Call(_)+ | SoupItem::ForeignEntity(_) => None,}).expect("The document should exist");let expected_doc_id = Uuid::parse_str("11111111-aaaa-aaaa-aaaa-aaaaaaaaaaaa").unwrap(); // doc-in-A@@ -5454,6 +5455,7 @@ fn mock_empty_ast() -> EntityFilterAst {email_filter: item_filters::ast::EmailFilterAst::default(),channel_filter: None,call_filter: None,+ foreign_entity_filter: None,properties_filter: None,}}