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(crm): team-scoped email queries with CRM domain authorization (#3213)
Evan Hutnik5842da93a25e
diff --git a/js/app/packages/service-clients/service-search/generated/models/emailFilters.ts b/js/app/packages/service-clients/service-search/generated/models/emailFilters.tsindex 1559fa83b8..aa35d6c5fe 100644--- a/js/app/packages/service-clients/service-search/generated/models/emailFilters.ts+++ b/js/app/packages/service-clients/service-search/generated/models/emailFilters.ts@@ -44,4 +44,10 @@ Note: SPAM and TRASH emails are not indexed in OpenSearch, so they will never ap/** Controls whether shared email threads are included in results.Defaults to "exclude" (only the user's own threads). */shared?: SharedEmailFilter;+ /** When true, expand visibility to every teammate's mailbox: results may+include emails the requesting user is not a participant on, as long as+at least one of their teammates is. Requires every sender/cc/bcc/recipient+value to be a fully-qualified email address or a domain (no partial+substring matches). */+ team_scope?: boolean;}diff --git a/js/app/packages/service-clients/service-search/openapi.json b/js/app/packages/service-clients/service-search/openapi.jsonindex 07c7aea680..2bb077b613 100644--- a/js/app/packages/service-clients/service-search/openapi.json+++ b/js/app/packages/service-clients/service-search/openapi.json@@ -1165,6 +1165,10 @@"shared": {"$ref": "#/components/schemas/SharedEmailFilter","description": "Controls whether shared email threads are included in results.\nDefaults to \"exclude\" (only the user's own threads)."+ },+ "team_scope": {+ "type": "boolean",+ "description": "When true, expand visibility to every teammate's mailbox: results may\ninclude emails the requesting user is not a participant on, as long as\nat least one of their teammates is. Requires every sender/cc/bcc/recipient\nvalue to be a fully-qualified email address or a domain (no partial\nsubstring matches)."}}},diff --git a/js/app/packages/service-clients/service-storage/generated/schemas/emailFilters.ts b/js/app/packages/service-clients/service-storage/generated/schemas/emailFilters.tsindex 70e1bf9d43..7a5ac1419e 100644--- a/js/app/packages/service-clients/service-storage/generated/schemas/emailFilters.ts+++ b/js/app/packages/service-clients/service-storage/generated/schemas/emailFilters.ts@@ -44,4 +44,10 @@ Note: SPAM and TRASH emails are not indexed in OpenSearch, so they will never ap/** Controls whether shared email threads are included in results.Defaults to "exclude" (only the user's own threads). */shared?: SharedEmailFilter;+ /** When true, expand visibility to every teammate's mailbox: results may+include emails the requesting user is not a participant on, as long as+at least one of their teammates is. Requires every sender/cc/bcc/recipient+value to be a fully-qualified email address or a domain (no partial+substring matches). */+ team_scope?: boolean;}diff --git a/js/app/packages/service-clients/service-storage/generated/zod.ts b/js/app/packages/service-clients/service-storage/generated/zod.tsindex ce59dffc8f..f29ca3ed1f 100644--- a/js/app/packages/service-clients/service-storage/generated/zod.ts+++ b/js/app/packages/service-clients/service-storage/generated/zod.ts@@ -5879,6 +5879,12 @@ export const postItemsSoupBody = zod.describe('Controls whether shared email threads are included in results.'),+ team_scope: zod+ .boolean()+ .optional()+ .describe(+ "When true, expand visibility to every teammate's mailbox: results may\ninclude emails the requesting user is not a participant on, as long as\nat least one of their teammates is. Requires every sender\/cc\/bcc\/recipient\nvalue to be a fully-qualified email address or a domain (no partial\nsubstring matches)."+ ),}).optional().describe(diff --git a/js/app/packages/service-clients/service-storage/openapi.json b/js/app/packages/service-clients/service-storage/openapi.jsonindex fcb5960eac..29d990707f 100644--- a/js/app/packages/service-clients/service-storage/openapi.json+++ b/js/app/packages/service-clients/service-storage/openapi.json@@ -8760,6 +8760,10 @@"shared": {"$ref": "#/components/schemas/SharedEmailFilter","description": "Controls whether shared email threads are included in results.\nDefaults to \"exclude\" (only the user's own threads)."+ },+ "team_scope": {+ "type": "boolean",+ "description": "When true, expand visibility to every teammate's mailbox: results may\ninclude emails the requesting user is not a participant on, as long as\nat least one of their teammates is. Requires every sender/cc/bcc/recipient\nvalue to be a fully-qualified email address or a domain (no partial\nsubstring matches)."}}},diff --git a/rust/cloud-storage/.sqlx/query-03d9c7e2c8988471423626370441600e47fbaf2a4e9ce6bb287b116679248db8.json b/rust/cloud-storage/.sqlx/query-03d9c7e2c8988471423626370441600e47fbaf2a4e9ce6bb287b116679248db8.jsonnew file mode 100644index 0000000000..2c294472f3--- /dev/null+++ b/rust/cloud-storage/.sqlx/query-03d9c7e2c8988471423626370441600e47fbaf2a4e9ce6bb287b116679248db8.json@@ -0,0 +1,28 @@+{+ "db_name": "PostgreSQL",+ "query": "\n SELECT team_id, team_role::text as \"role!\"\n FROM team_user\n WHERE user_id = $1\n ORDER BY team_role DESC\n LIMIT 1\n ",+ "describe": {+ "columns": [+ {+ "ordinal": 0,+ "name": "team_id",+ "type_info": "Uuid"+ },+ {+ "ordinal": 1,+ "name": "role!",+ "type_info": "Text"+ }+ ],+ "parameters": {+ "Left": [+ "Text"+ ]+ },+ "nullable": [+ false,+ null+ ]+ },+ "hash": "03d9c7e2c8988471423626370441600e47fbaf2a4e9ce6bb287b116679248db8"+}diff --git a/rust/cloud-storage/.sqlx/query-124901aaedcea50030b2b8039c8ef509d980650a4c5d0fca7053cba0c2543155.json b/rust/cloud-storage/.sqlx/query-124901aaedcea50030b2b8039c8ef509d980650a4c5d0fca7053cba0c2543155.jsonnew file mode 100644index 0000000000..6923dd89fd--- /dev/null+++ b/rust/cloud-storage/.sqlx/query-124901aaedcea50030b2b8039c8ef509d980650a4c5d0fca7053cba0c2543155.json@@ -0,0 +1,29 @@+{+ "db_name": "PostgreSQL",+ "query": "\n SELECT c.id, LOWER(c.email_address) AS \"email_lower!\"\n FROM email_contacts c\n JOIN email_links el ON el.id = c.link_id\n JOIN team_user tu ON tu.user_id = el.macro_id\n WHERE tu.team_id = $1\n AND LOWER(c.email_address) = ANY($2)\n ",+ "describe": {+ "columns": [+ {+ "ordinal": 0,+ "name": "id",+ "type_info": "Uuid"+ },+ {+ "ordinal": 1,+ "name": "email_lower!",+ "type_info": "Text"+ }+ ],+ "parameters": {+ "Left": [+ "Uuid",+ "TextArray"+ ]+ },+ "nullable": [+ false,+ null+ ]+ },+ "hash": "124901aaedcea50030b2b8039c8ef509d980650a4c5d0fca7053cba0c2543155"+}diff --git a/rust/cloud-storage/.sqlx/query-2443fe54c4008a741bf932783b861f1049c87b024003d7a6781ed24d82f095e8.json b/rust/cloud-storage/.sqlx/query-2443fe54c4008a741bf932783b861f1049c87b024003d7a6781ed24d82f095e8.jsonnew file mode 100644index 0000000000..15f9c1c609--- /dev/null+++ b/rust/cloud-storage/.sqlx/query-2443fe54c4008a741bf932783b861f1049c87b024003d7a6781ed24d82f095e8.json@@ -0,0 +1,22 @@+{+ "db_name": "PostgreSQL",+ "query": "\n SELECT l.id\n FROM email_labels l\n JOIN email_links el ON el.id = l.link_id\n JOIN team_user tu ON tu.user_id = el.macro_id\n WHERE l.name = 'TRASH' AND tu.team_id = $1\n ",+ "describe": {+ "columns": [+ {+ "ordinal": 0,+ "name": "id",+ "type_info": "Uuid"+ }+ ],+ "parameters": {+ "Left": [+ "Uuid"+ ]+ },+ "nullable": [+ false+ ]+ },+ "hash": "2443fe54c4008a741bf932783b861f1049c87b024003d7a6781ed24d82f095e8"+}diff --git a/rust/cloud-storage/.sqlx/query-2b84b8b3f8249a00c5fdc077b6450804a38baa96682f5c6dc8bb95dddf25d037.json b/rust/cloud-storage/.sqlx/query-2b84b8b3f8249a00c5fdc077b6450804a38baa96682f5c6dc8bb95dddf25d037.jsonnew file mode 100644index 0000000000..93646d814b--- /dev/null+++ b/rust/cloud-storage/.sqlx/query-2b84b8b3f8249a00c5fdc077b6450804a38baa96682f5c6dc8bb95dddf25d037.json@@ -0,0 +1,40 @@+{+ "db_name": "PostgreSQL",+ "query": "\n SELECT id, company_id, domain, created_at\n FROM crm_domains\n WHERE company_id = $1\n ORDER BY created_at ASC\n ",+ "describe": {+ "columns": [+ {+ "ordinal": 0,+ "name": "id",+ "type_info": "Uuid"+ },+ {+ "ordinal": 1,+ "name": "company_id",+ "type_info": "Uuid"+ },+ {+ "ordinal": 2,+ "name": "domain",+ "type_info": "Text"+ },+ {+ "ordinal": 3,+ "name": "created_at",+ "type_info": "Timestamptz"+ }+ ],+ "parameters": {+ "Left": [+ "Uuid"+ ]+ },+ "nullable": [+ false,+ false,+ false,+ false+ ]+ },+ "hash": "2b84b8b3f8249a00c5fdc077b6450804a38baa96682f5c6dc8bb95dddf25d037"+}diff --git a/rust/cloud-storage/.sqlx/query-6595308af9962787ede1073451f3ad5a89769b6881f547898ac09a06db9aeb95.json b/rust/cloud-storage/.sqlx/query-6595308af9962787ede1073451f3ad5a89769b6881f547898ac09a06db9aeb95.jsonnew file mode 100644index 0000000000..fc6517d3fb--- /dev/null+++ b/rust/cloud-storage/.sqlx/query-6595308af9962787ede1073451f3ad5a89769b6881f547898ac09a06db9aeb95.json@@ -0,0 +1,47 @@+{+ "db_name": "PostgreSQL",+ "query": "\n SELECT c.id, c.team_id, c.name, c.email_sync, c.created_at\n FROM crm_companies c\n JOIN crm_domains d ON d.company_id = c.id\n WHERE c.team_id = $1\n AND LOWER(d.domain) = $2\n LIMIT 1\n ",+ "describe": {+ "columns": [+ {+ "ordinal": 0,+ "name": "id",+ "type_info": "Uuid"+ },+ {+ "ordinal": 1,+ "name": "team_id",+ "type_info": "Uuid"+ },+ {+ "ordinal": 2,+ "name": "name",+ "type_info": "Text"+ },+ {+ "ordinal": 3,+ "name": "email_sync",+ "type_info": "Bool"+ },+ {+ "ordinal": 4,+ "name": "created_at",+ "type_info": "Timestamptz"+ }+ ],+ "parameters": {+ "Left": [+ "Uuid",+ "Text"+ ]+ },+ "nullable": [+ false,+ false,+ false,+ false,+ false+ ]+ },+ "hash": "6595308af9962787ede1073451f3ad5a89769b6881f547898ac09a06db9aeb95"+}diff --git a/rust/cloud-storage/.sqlx/query-973d37572060a8cc387f72cf18688270bbb644e96783ac2364a2fee306b4dda6.json b/rust/cloud-storage/.sqlx/query-973d37572060a8cc387f72cf18688270bbb644e96783ac2364a2fee306b4dda6.jsonnew file mode 100644index 0000000000..8eef2d5952--- /dev/null+++ b/rust/cloud-storage/.sqlx/query-973d37572060a8cc387f72cf18688270bbb644e96783ac2364a2fee306b4dda6.json@@ -0,0 +1,22 @@+{+ "db_name": "PostgreSQL",+ "query": "\n SELECT id\n FROM email_labels\n WHERE link_id = $1 AND name = 'TRASH'\n ",+ "describe": {+ "columns": [+ {+ "ordinal": 0,+ "name": "id",+ "type_info": "Uuid"+ }+ ],+ "parameters": {+ "Left": [+ "Uuid"+ ]+ },+ "nullable": [+ false+ ]+ },+ "hash": "973d37572060a8cc387f72cf18688270bbb644e96783ac2364a2fee306b4dda6"+}diff --git a/rust/cloud-storage/.sqlx/query-9d603c81c30c562a69a53297e62fadec99a097e85feedfeea7c74383b6e1c302.json b/rust/cloud-storage/.sqlx/query-9d603c81c30c562a69a53297e62fadec99a097e85feedfeea7c74383b6e1c302.jsonnew file mode 100644index 0000000000..314d689c22--- /dev/null+++ b/rust/cloud-storage/.sqlx/query-9d603c81c30c562a69a53297e62fadec99a097e85feedfeea7c74383b6e1c302.json@@ -0,0 +1,47 @@+{+ "db_name": "PostgreSQL",+ "query": "\n SELECT o.id, o.team_id, o.name, o.email_sync, o.created_at\n FROM crm_organization o\n JOIN crm_organization_domain d ON d.crm_organization_id = o.id\n WHERE o.team_id = $1\n AND LOWER(d.domain) = $2\n LIMIT 1\n ",+ "describe": {+ "columns": [+ {+ "ordinal": 0,+ "name": "id",+ "type_info": "Uuid"+ },+ {+ "ordinal": 1,+ "name": "team_id",+ "type_info": "Uuid"+ },+ {+ "ordinal": 2,+ "name": "name",+ "type_info": "Text"+ },+ {+ "ordinal": 3,+ "name": "email_sync",+ "type_info": "Bool"+ },+ {+ "ordinal": 4,+ "name": "created_at",+ "type_info": "Timestamptz"+ }+ ],+ "parameters": {+ "Left": [+ "Uuid",+ "Text"+ ]+ },+ "nullable": [+ false,+ false,+ false,+ false,+ false+ ]+ },+ "hash": "9d603c81c30c562a69a53297e62fadec99a097e85feedfeea7c74383b6e1c302"+}diff --git a/rust/cloud-storage/.sqlx/query-d0e2c3d2bb2a42f3655e52bf8c4f92142542c3a0a9759d9729d8272e3f93edbe.json b/rust/cloud-storage/.sqlx/query-d0e2c3d2bb2a42f3655e52bf8c4f92142542c3a0a9759d9729d8272e3f93edbe.jsonnew file mode 100644index 0000000000..2a2787dbe2--- /dev/null+++ b/rust/cloud-storage/.sqlx/query-d0e2c3d2bb2a42f3655e52bf8c4f92142542c3a0a9759d9729d8272e3f93edbe.json@@ -0,0 +1,40 @@+{+ "db_name": "PostgreSQL",+ "query": "\n SELECT id, crm_organization_id, domain, created_at\n FROM crm_organization_domain\n WHERE crm_organization_id = $1\n ORDER BY created_at ASC\n ",+ "describe": {+ "columns": [+ {+ "ordinal": 0,+ "name": "id",+ "type_info": "Uuid"+ },+ {+ "ordinal": 1,+ "name": "crm_organization_id",+ "type_info": "Uuid"+ },+ {+ "ordinal": 2,+ "name": "domain",+ "type_info": "Text"+ },+ {+ "ordinal": 3,+ "name": "created_at",+ "type_info": "Timestamptz"+ }+ ],+ "parameters": {+ "Left": [+ "Uuid"+ ]+ },+ "nullable": [+ false,+ false,+ false,+ false+ ]+ },+ "hash": "d0e2c3d2bb2a42f3655e52bf8c4f92142542c3a0a9759d9729d8272e3f93edbe"+}diff --git a/rust/cloud-storage/.sqlx/query-d1e1c7c923f73496f7470173e0825641124ea6d4ca0bc37690c43f8d8f5a2661.json b/rust/cloud-storage/.sqlx/query-d1e1c7c923f73496f7470173e0825641124ea6d4ca0bc37690c43f8d8f5a2661.jsonnew file mode 100644index 0000000000..bd2714df55--- /dev/null+++ b/rust/cloud-storage/.sqlx/query-d1e1c7c923f73496f7470173e0825641124ea6d4ca0bc37690c43f8d8f5a2661.json@@ -0,0 +1,29 @@+{+ "db_name": "PostgreSQL",+ "query": "\n SELECT id, LOWER(email_address) AS \"email_lower!\"\n FROM email_contacts\n WHERE link_id = $1 AND LOWER(email_address) = ANY($2)\n ",+ "describe": {+ "columns": [+ {+ "ordinal": 0,+ "name": "id",+ "type_info": "Uuid"+ },+ {+ "ordinal": 1,+ "name": "email_lower!",+ "type_info": "Text"+ }+ ],+ "parameters": {+ "Left": [+ "Uuid",+ "TextArray"+ ]+ },+ "nullable": [+ false,+ null+ ]+ },+ "hash": "d1e1c7c923f73496f7470173e0825641124ea6d4ca0bc37690c43f8d8f5a2661"+}diff --git a/rust/cloud-storage/Cargo.lock b/rust/cloud-storage/Cargo.lockindex 79435cbd83..badd1adb46 100644--- a/rust/cloud-storage/Cargo.lock+++ b/rust/cloud-storage/Cargo.lock@@ -14,7 +14,7 @@ version = "0.5.2"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "d122413f284cf2d62fb1b7db97e02edb8cda96d769b16e443a4f6195e35662b0"dependencies = [- "crypto-common 0.1.7",+ "crypto-common 0.1.6","generic-array",]@@ -50,7 +50,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "e89da841a80418a9b391ebaea17f5c112ffaaa96f621d2c285b5174da76b9011"dependencies = ["cfg-if",- "getrandom 0.2.17",+ "getrandom 0.2.15","once_cell","version_check","zerocopy 0.7.35",@@ -81,7 +81,7 @@ dependencies = ["lazy_static","macro_user_id","model_file_type",- "rand 0.9.4",+ "rand 0.9.3","reqwest 0.13.3","schemars","secrecy",@@ -114,6 +114,7 @@ dependencies = ["comms","connection","cool_asserts",+ "crm","dateparser","documents","email",@@ -142,7 +143,7 @@ dependencies = ["non_empty","notification","properties",- "rand 0.9.4",+ "rand 0.9.3","readonly_pool","remote_env_var","rootcause",@@ -232,7 +233,7 @@ dependencies = ["reqwest 0.13.3","serde","serde_json",- "sha2 0.10.9",+ "sha2 0.10.8","tracing",]@@ -304,7 +305,7 @@ dependencies = ["chrono","futures","lazy_static",- "rand 0.9.4",+ "rand 0.9.3","regex","reqwest 0.13.3","schemars",@@ -457,8 +458,8 @@ dependencies = ["derive_builder","eventsource-stream","futures",- "getrandom 0.3.4",- "rand 0.9.4",+ "getrandom 0.3.1",+ "rand 0.9.3","reqwest 0.13.3","secrecy","serde",@@ -572,7 +573,7 @@ dependencies = ["hmac 0.12.1","miniserde","serde",- "sha2 0.10.9",+ "sha2 0.10.8","thiserror 2.0.17",]@@ -671,7 +672,7 @@ dependencies = ["native_app_service","non_empty","notification",- "rand 0.9.4",+ "rand 0.9.3","rate_limit","redis","referral",@@ -692,7 +693,7 @@ dependencies = ["thiserror 2.0.17","time","tokio",- "tower 0.5.3",+ "tower 0.5.2","tower-cookies","tower-http","tracing",@@ -718,9 +719,9 @@ dependencies = [[[package]]name = "autocfg"-version = "1.5.0"+version = "1.4.0"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "c08606f8c3cbf4ce6ec8e28fb0014a2c086708fe954eaa885384a6165172e7e8"+checksum = "ace50bade8e6234aa140d9a2f552bbee1db4d353f69b8217bc503490fc1a9f26"[[package]]name = "av-scenechange"@@ -784,9 +785,9 @@ dependencies = ["aws-smithy-types","aws-types","bytes",- "fastrand 2.4.1",+ "fastrand 2.3.0","hex",- "http 1.4.0",+ "http 1.3.1","sha1 0.10.6","time","tokio",@@ -809,9 +810,9 @@ dependencies = [[[package]]name = "aws-lc-rs"-version = "1.17.0"+version = "1.16.2"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "5ec2f1fc3ec205783a5da9a7e6c1509cc69dedf09a1949e412c1e18469326d00"+checksum = "a054912289d18629dc78375ba2c3726a3afe3ff71b4edba9dedfca0e3446d1fc"dependencies = ["aws-lc-sys","zeroize",@@ -819,9 +820,9 @@ dependencies = [[[package]]name = "aws-lc-sys"-version = "0.41.0"+version = "0.39.1"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "1a2f9779ce85b93ab6170dd940ad0169b5766ff848247aff13bb788b832fe3f4"+checksum = "83a25cf98105baa966497416dbd42565ce3a8cf8dbfd59803ec9ad46f3126399"dependencies = ["cc","cmake",@@ -846,9 +847,9 @@ dependencies = ["aws-types","bytes","bytes-utils",- "fastrand 2.4.1",+ "fastrand 2.3.0","http 0.2.12",- "http 1.4.0",+ "http 1.3.1","http-body 0.4.6","http-body 1.0.1","percent-encoding",@@ -874,9 +875,9 @@ dependencies = ["aws-smithy-types","aws-types","bytes",- "fastrand 2.4.1",+ "fastrand 2.3.0","http 0.2.12",- "http 1.4.0",+ "http 1.3.1","regex-lite","tracing",]@@ -898,9 +899,9 @@ dependencies = ["aws-smithy-types","aws-types","bytes",- "fastrand 2.4.1",+ "fastrand 2.3.0","http 0.2.12",- "http 1.4.0",+ "http 1.3.1","regex-lite","tracing",]@@ -923,9 +924,9 @@ dependencies = ["aws-smithy-types","aws-types","bytes",- "fastrand 2.4.1",+ "fastrand 2.3.0","http 0.2.12",- "http 1.4.0",+ "http 1.3.1","regex-lite","tracing",]@@ -951,11 +952,11 @@ dependencies = ["aws-smithy-xml","aws-types","bytes",- "fastrand 2.4.1",+ "fastrand 2.3.0","hex","hmac 0.13.0","http 0.2.12",- "http 1.4.0",+ "http 1.3.1","http-body 1.0.1","lru","percent-encoding",@@ -982,9 +983,9 @@ dependencies = ["aws-smithy-types","aws-types","bytes",- "fastrand 2.4.1",+ "fastrand 2.3.0","http 0.2.12",- "http 1.4.0",+ "http 1.3.1","regex-lite","tracing",]@@ -1006,9 +1007,9 @@ dependencies = ["aws-smithy-types","aws-types","bytes",- "fastrand 2.4.1",+ "fastrand 2.3.0","http 0.2.12",- "http 1.4.0",+ "http 1.3.1","regex-lite","tracing",]@@ -1031,9 +1032,9 @@ dependencies = ["aws-smithy-types","aws-smithy-xml","aws-types",- "fastrand 2.4.1",+ "fastrand 2.3.0","http 0.2.12",- "http 1.4.0",+ "http 1.3.1","regex-lite","tracing",]@@ -1055,9 +1056,9 @@ dependencies = ["aws-smithy-types","aws-types","bytes",- "fastrand 2.4.1",+ "fastrand 2.3.0","http 0.2.12",- "http 1.4.0",+ "http 1.3.1","regex-lite","tracing",]@@ -1079,9 +1080,9 @@ dependencies = ["aws-smithy-types","aws-types","bytes",- "fastrand 2.4.1",+ "fastrand 2.3.0","http 0.2.12",- "http 1.4.0",+ "http 1.3.1","regex-lite","tracing",]@@ -1103,9 +1104,9 @@ dependencies = ["aws-smithy-types","aws-types","bytes",- "fastrand 2.4.1",+ "fastrand 2.3.0","http 0.2.12",- "http 1.4.0",+ "http 1.3.1","regex-lite","tracing",]@@ -1128,9 +1129,9 @@ dependencies = ["aws-smithy-types","aws-smithy-xml","aws-types",- "fastrand 2.4.1",+ "fastrand 2.3.0","http 0.2.12",- "http 1.4.0",+ "http 1.3.1","regex-lite","tracing",]@@ -1152,7 +1153,7 @@ dependencies = ["hex","hmac 0.13.0","http 0.2.12",- "http 1.4.0",+ "http 1.3.1","p256 0.11.1","percent-encoding","ring",@@ -1176,16 +1177,16 @@ dependencies = [[[package]]name = "aws-smithy-checksums"-version = "0.64.7"+version = "0.64.8"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "10efbbcec1e044b81600e2fc562a391951d291152d95b482d5b7e7132299d762"+checksum = "e9e8e65f4f81fcccdeb6c3eca2af17ac21d421a1786a26a394aecf421d616d3a"dependencies = ["aws-smithy-http","aws-smithy-types","bytes","crc-fast","hex",- "http 1.4.0",+ "http 1.3.1","http-body 1.0.1","http-body-util","md-5 0.11.0",@@ -1219,7 +1220,7 @@ dependencies = ["bytes-utils","futures-core","futures-util",- "http 1.4.0",+ "http 1.3.1","http-body 1.0.1","http-body-util","percent-encoding",@@ -1237,33 +1238,35 @@ dependencies = ["aws-smithy-async","aws-smithy-runtime-api","aws-smithy-types",- "h2 0.3.27",- "h2 0.4.14",+ "h2 0.3.26",+ "h2 0.4.13","http 0.2.12",- "http 1.4.0",+ "http 1.3.1","http-body 0.4.6","hyper 0.14.32",- "hyper 1.9.0",+ "hyper 1.6.0","hyper-rustls 0.24.2",- "hyper-rustls 0.27.9",+ "hyper-rustls 0.27.5","hyper-util","pin-project-lite","rustls 0.21.12",- "rustls 0.23.40",+ "rustls 0.23.36","rustls-native-certs","rustls-pki-types","tokio","tokio-rustls 0.26.4",- "tower 0.5.3",+ "tower 0.5.2","tracing",][[package]]name = "aws-smithy-json"-version = "0.62.5"+version = "0.62.6"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "9648b0bb82a2eedd844052c6ad2a1a822d1f8e3adee5fbf668366717e428856a"+checksum = "517089205f18ab4adc5a3e02888cb139bbbbb2e168eac9f396216925d1fbeaf5"dependencies = [+ "aws-smithy-runtime-api",+ "aws-smithy-schema","aws-smithy-types",]@@ -1288,20 +1291,21 @@ dependencies = [[[package]]name = "aws-smithy-runtime"-version = "1.11.1"+version = "1.11.3"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "0504b1ab12debb5959e5165ee5fe97dd387e7aa7ea6a477bfd7635dfe769a4f5"+checksum = "b8e6f5caf6fea86f8c2206541ab5857cfcda9013426cdbe8fa0098b9e2d32182"dependencies = ["aws-smithy-async","aws-smithy-http","aws-smithy-http-client","aws-smithy-observability","aws-smithy-runtime-api",+ "aws-smithy-schema","aws-smithy-types","bytes",- "fastrand 2.4.1",+ "fastrand 2.3.0","http 0.2.12",- "http 1.4.0",+ "http 1.3.1","http-body 0.4.6","http-body 1.0.1","http-body-util",@@ -1313,16 +1317,16 @@ dependencies = [[[package]]name = "aws-smithy-runtime-api"-version = "1.12.0"+version = "1.12.1"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "b71a13df6ada0aafbf21a73bdfcdf9324cfa9df77d96b8446045be3cde61b42e"+checksum = "dc117c179ecf39a62a0a3f49f600e9ac26a7ad7dd172177999f83933af776c32"dependencies = ["aws-smithy-async","aws-smithy-runtime-api-macros","aws-smithy-types","bytes","http 0.2.12",- "http 1.4.0",+ "http 1.3.1","pin-project-lite","tokio","tracing",@@ -1340,18 +1344,29 @@ dependencies = ["syn 2.0.117",]+[[package]]+name = "aws-smithy-schema"+version = "0.1.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "7442cb268338f0eb8278140a107c046756aa01093d8ef5e99628d34ae09c94f5"+dependencies = [+ "aws-smithy-runtime-api",+ "aws-smithy-types",+ "http 1.3.1",+]+[[package]]name = "aws-smithy-types"-version = "1.4.7"+version = "1.4.8"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "9d73dbfbaa8e4bc57b9045137680b958d274823509a360abfd8e1d514d40c95c"+checksum = "056b66dbce2f81cc0c1e2b05bb402eb58f8a3530479d650efadd5bbae9a4050b"dependencies = ["base64-simd","bytes","bytes-utils","futures-core","http 0.2.12",- "http 1.4.0",+ "http 1.3.1","http-body 0.4.6","http-body 1.0.1","http-body-util",@@ -1398,7 +1413,7 @@ dependencies = ["base64 0.22.1","bytes","chrono",- "http 1.4.0",+ "http 1.3.1","http-body 1.0.1","http-serde","serde",@@ -1418,10 +1433,10 @@ dependencies = ["bytes","form_urlencoded","futures-util",- "http 1.4.0",+ "http 1.3.1","http-body 1.0.1","http-body-util",- "hyper 1.9.0",+ "hyper 1.6.0","hyper-util","itoa","matchit",@@ -1438,7 +1453,7 @@ dependencies = ["sync_wrapper","tokio","tokio-tungstenite 0.28.0",- "tower 0.5.3",+ "tower 0.5.2","tower-layer","tower-service","tracing",@@ -1452,7 +1467,7 @@ checksum = "08c78f31d7b1291f7ee735c1c6780ccde7785daae9a9206026862dab7d8792d1"dependencies = ["bytes","futures-core",- "http 1.4.0",+ "http 1.3.1","http-body 1.0.1","http-body-util","mime",@@ -1475,7 +1490,7 @@ dependencies = ["cookie","futures-util","headers",- "http 1.4.0",+ "http 1.3.1","http-body 1.0.1","http-body-util","mime",@@ -1518,7 +1533,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "b62ddb9cb1ec0a098ad4bbf9344d0713fa193ae1a80af55febcff2627b6a00c1"dependencies = ["futures-core",- "getrandom 0.2.17",+ "getrandom 0.2.15","instant","pin-project-lite","rand 0.8.5",@@ -1567,9 +1582,9 @@ dependencies = [[[package]]name = "base64ct"-version = "1.8.3"+version = "1.6.0"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "2af50177e190e07a26ab74f8b1efbfe2ef87da2116221318cb1c2e82baf7de06"+checksum = "8c3c1a368f70d6cf7302d78f8f7093da241fb8e8807c05cc9e51a125895a6d5b"[[package]]name = "basic-toml"@@ -1700,9 +1715,9 @@ checksum = "f4ad8f11f288f48ca24471bbd51ac257aaeaaa07adae295591266b792902ae64"[[package]]name = "bumpalo"-version = "3.20.2"+version = "3.17.0"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "5d20789868f4b01b2f2caec9f5c4e0213b41e3e5702a50157d699ae31ced2fcb"+checksum = "1628fb46dfa0b37568d12e5edd512553eccf6a22a78e8bde00bb4aed84d5bdbf"[[package]]name = "bytemuck"@@ -1810,7 +1825,7 @@ dependencies = ["rootcause","serde","serde_json",- "sha2 0.10.9",+ "sha2 0.10.8","thiserror 2.0.17","tracing","utoipa",@@ -1859,9 +1874,9 @@ dependencies = [[[package]]name = "cc"-version = "1.2.62"+version = "1.2.51"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "a1dce859f0832a7d088c4f1119888ab94ef4b5d6795d1ce05afb7fe159d79f98"+checksum = "7a0aeaff4ff1a90589618835a598e545176939b97874f7abc7851caa0618f203"dependencies = ["find-msvc-tools","jobserver",@@ -1897,9 +1912,9 @@ dependencies = [[[package]]name = "cfg-if"-version = "1.0.4"+version = "1.0.0"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "9330f8b2ff13f34540b44e946ef35111825727b38d33286ef986142615121801"+checksum = "baf1de4339761588bc0619e3cbc0120ee582ebb74b53b4efbf79117bd2da40fd"[[package]]name = "cfg_aliases"@@ -1915,7 +1930,7 @@ checksum = "6f8d983286843e49675a4b7a2d174efe136dc93a18d69130dd18198a6c167601"dependencies = ["cfg-if","cpufeatures 0.3.0",- "rand_core 0.10.1",+ "rand_core 0.10.0",][[package]]@@ -1941,7 +1956,7 @@ dependencies = ["sqlx","thiserror 2.0.17","tokio",- "tower 0.5.3",+ "tower 0.5.2","tracing","utoipa","uuid",@@ -1989,7 +2004,7 @@ dependencies = ["sqlx","thiserror 2.0.17","tokio",- "tower 0.5.3",+ "tower 0.5.2","tracing","unicode-segmentation","utoipa",@@ -2027,7 +2042,7 @@ version = "0.4.4"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "773f3b9af64447d2ce9850330c473515014aa235e6a783b02db81ff39e4a3dad"dependencies = [- "crypto-common 0.1.7",+ "crypto-common 0.1.6","inout",]@@ -2096,9 +2111,9 @@ dependencies = [[[package]]name = "cmake"-version = "0.1.58"+version = "0.1.57"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "c0f78a02292a74a88ac736019ab962ece0bc380e3f977bf72e376c5d78ff0678"+checksum = "75443c44cd6b379beb8c5b45d85d0773baf31cce901fe7bb252f4eff3008ef7d"dependencies = ["cc",]@@ -2239,7 +2254,7 @@ dependencies = ["sqs_client","thiserror 2.0.17","tokio",- "tower 0.5.3",+ "tower 0.5.2","tower-http","tracing","utoipa",@@ -2333,7 +2348,7 @@ dependencies = ["strum","strum_macros","tokio",- "tower 0.5.3",+ "tower 0.5.2","tower-http","tracing","tungstenite 0.28.0",@@ -2426,7 +2441,7 @@ dependencies = ["sqlx","sqs_worker","tokio",- "tower 0.5.3",+ "tower 0.5.2","tracing","utoipa",]@@ -2457,7 +2472,7 @@ dependencies = ["sqlx","sqs_worker","tokio",- "tower 0.5.3",+ "tower 0.5.2","tracing","utoipa","utoipa-swagger-ui",@@ -2496,7 +2511,7 @@ dependencies = ["sqs_client","sqs_worker","tokio",- "tower 0.5.3",+ "tower 0.5.2","tower-http","tracing","utoipa",@@ -2526,9 +2541,9 @@ dependencies = [[[package]]name = "core-foundation"-version = "0.10.1"+version = "0.10.0"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "b2a6cd9ae233e7f62ba4e9353e81a88df7fc8a5987b8d445b4d90c879bd156f6"+checksum = "b55271e5c8c478ad3f38ad24ef34923091e0548492a266d19b3c0b4d82574c63"dependencies = ["core-foundation-sys","libc",@@ -2582,9 +2597,9 @@ dependencies = [[[package]]name = "crc-catalog"-version = "2.5.0"+version = "2.4.0"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "217698eaf96b4a3f0bc4f3662aaa55bdf913cd54d7204591faa790070c6d0853"+checksum = "19d374276b40fb8bbdee95aef7c7fa6b5316ec764510eb64b8dd0e2ed0d7e7f5"[[package]]name = "crc-fast"@@ -2606,9 +2621,9 @@ checksum = "338089f42c427b86394a5ee60ff321da23a5c89c9d89514c829687b26359fcff"[[package]]name = "crc32fast"-version = "1.5.0"+version = "1.4.2"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "9481c1c90cbf2ac953f07c8d4a58aa3945c425b7185c9154d67a65e4230da511"+checksum = "a97769d94ddab943e4510d138150169a2758b5ef3eb191a9ee688de3e23ef7b3"dependencies = ["cfg-if",]@@ -2619,6 +2634,21 @@ version = "1.2.0"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "790eea4361631c5e7d22598ecd5723ff611904e3344ce8720784c93e3d83d40b"+[[package]]+name = "crm"+version = "0.1.0"+dependencies = [+ "anyhow",+ "chrono",+ "macro_db_migrator",+ "serde",+ "sqlx",+ "thiserror 2.0.17",+ "tokio",+ "tracing",+ "uuid",+]+[[package]]name = "cron"version = "0.16.0"@@ -2731,9 +2761,9 @@ dependencies = [[[package]]name = "crypto-common"-version = "0.1.7"+version = "0.1.6"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "78c8292055d1c1df0cce5d180393dc8cce0abec0a7102adb6c7b1eef6016d60a"+checksum = "1bfb12502f3fc46cca1bb51ac28df9d618d813cdc3d2f25b9fe775a34af26bb3"dependencies = ["generic-array","rand_core 0.6.4",@@ -2965,7 +2995,7 @@ dependencies = ["serde_json","serde_urlencoded","tokio",- "tower 0.5.3",+ "tower 0.5.2","tracing","url","urlencoding",@@ -3040,9 +3070,9 @@ dependencies = [[[package]]name = "deranged"-version = "0.5.8"+version = "0.5.5"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "7cd812cc2bc1d69d4764bd80df88b4317eaef9e773c75226407d9bc0876b211c"+checksum = "ececcb659e7ba858fb4f10388c250a7252eb0a27373f1a72b8748afdd248e587"dependencies = ["powerfmt","serde_core",@@ -3124,7 +3154,7 @@ checksum = "9ed9a281f7bc9b7576e61468ba615a66a5c8cfdff42420a70aa82701a3b1e292"dependencies = ["block-buffer 0.10.4","const-oid 0.9.6",- "crypto-common 0.1.7",+ "crypto-common 0.1.6","subtle",]@@ -3186,6 +3216,7 @@ dependencies = ["comms_service_client","connection_gateway","cookie",+ "crm","document_storage_service_client","documents","doppleganger",@@ -3195,7 +3226,7 @@ dependencies = ["entity_access_management","frecency","futures",- "http 1.4.0",+ "http 1.3.1","http-body-util","last_online_tracker","lazy_static",@@ -3245,7 +3276,7 @@ dependencies = ["time","tokio","tokio-util",- "tower 0.5.3",+ "tower 0.5.2","tower-http","tracing","unfurl_service",@@ -3284,6 +3315,7 @@ dependencies = ["contacts","cool_asserts","cowlike",+ "crm","document_sub_type","documents","dynamodb_client",@@ -3351,7 +3383,7 @@ dependencies = ["system_properties","thiserror 2.0.17","tokio",- "tower 0.5.3",+ "tower 0.5.2","tower-http","tracing","unicode-segmentation",@@ -3484,12 +3516,12 @@ dependencies = ["schemars","serde","serde_json",- "sha2 0.10.9",+ "sha2 0.10.8","sqlx","sync_service_client","thiserror 2.0.17","tokio",- "tower 0.5.3",+ "tower 0.5.2","tracing","unicode-segmentation","urlencoding",@@ -3523,7 +3555,7 @@ dependencies = ["s3_key","serde","serde_json",- "sha2 0.10.9",+ "sha2 0.10.8","sqlx","sqs_client","tokio",@@ -3675,7 +3707,7 @@ dependencies = ["curve25519-dalek","ed25519","serde",- "sha2 0.10.9",+ "sha2 0.10.8","subtle","zeroize",]@@ -3688,9 +3720,9 @@ checksum = "12a0bb14ac04a9fcf170d0bbbef949b44cc492f4452bd20c095636956f653642"[[package]]name = "either"-version = "1.15.0"+version = "1.13.0"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "48c757948c5ede0e46177b7add2e67155f70e33c07fea8284df6576da70b3719"+checksum = "60b1af1c220855b6ceac025d3f6ecdd2b7c4894bfe9cd9bda4fbb4bc7c0d4cf0"dependencies = ["serde",]@@ -3749,6 +3781,7 @@ dependencies = ["axum-extra","base64 0.22.1","chrono",+ "crm","doppleganger","either","email_utils",@@ -3817,7 +3850,7 @@ dependencies = ["notification","rootcause","serde",- "sha2 0.10.9",+ "sha2 0.10.8","tracing",]@@ -3881,6 +3914,7 @@ dependencies = ["cloudfront_sign","connection_gateway_client","contacts",+ "crm","document_storage_service_client","doppleganger","ego-tree",@@ -3929,7 +3963,7 @@ dependencies = ["secretsmanager_client","serde","serde_json",- "sha2 0.10.9",+ "sha2 0.10.8","sqlx","sqlx-core","sqs_client",@@ -3939,7 +3973,7 @@ dependencies = ["system_properties","thiserror 2.0.17","tokio",- "tower 0.5.3",+ "tower 0.5.2","tower-http","tracing","url",@@ -4137,15 +4171,15 @@ dependencies = [[[package]]name = "equivalent"-version = "1.0.2"+version = "1.0.1"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "877a4ace8713b0bcf2a4e7eec82529c029f1d0619886d18145fea96c3ffe5c0f"+checksum = "5443807d6dff69373d433ab9ef5378ad8df50ca6298caf15de6e52e24aaf54d5"[[package]]name = "errno"-version = "0.3.14"+version = "0.3.10"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "39cab71617ae0d63f51a36d69f866391735b51691dbda63cf6f96d042b63efeb"+checksum = "33d852cb9b869c2a9b3df2f71a3074817f01e1844f839a144f5fcef059a4eb5d"dependencies = ["libc","windows-sys 0.59.0",@@ -4232,9 +4266,9 @@ dependencies = [[[package]]name = "fastrand"-version = "2.4.1"+version = "2.3.0"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "9f1f227452a390804cdb637b74a86990f2a7d7ba4b7d5693aac9b4dd6defd8d6"+checksum = "37909eebbb50d72f9059c3b6d82c0463f2ff062c9e95845c43a6c9c0355411be"[[package]]name = "fax"@@ -4301,9 +4335,9 @@ dependencies = [[[package]]name = "find-msvc-tools"-version = "0.1.9"+version = "0.1.6"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "5baebc0774151f905a1a2cc41989300b1e6fbb29aff0ceffa1064fdd3088d582"+checksum = "645cbb3a84e60b7531617d5ae4e57f7e27308f6445f5abf653209ea76dec8dff"[[package]]name = "fixedbitset"@@ -4341,9 +4375,9 @@ checksum = "3f9eec918d3f24069decb9af1554cad7c880e2da24a9afd88aca000531ab82c1"[[package]]name = "foldhash"-version = "0.1.5"+version = "0.1.4"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "d9c4f5dac5e15c24eb999c26181a6ca40b39fe946cbe4c263c7209467bc83af2"+checksum = "a0d2fde1f7b3d48b8395d5f2de76c18a528bd6a9cdde438df747bfcba3e05d6f"[[package]]name = "foldhash"@@ -4353,9 +4387,9 @@ checksum = "77ce24cb58228fbb8aa041425bb1050850ac19177686ea6e0f41a70416f56fdb"[[package]]name = "form_urlencoded"-version = "1.2.2"+version = "1.2.1"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "cb4cb245038516f5f85277875cdaa4f7d2c9a0fa0468de06ed190163b1581fcf"+checksum = "e13624c2627564efccf4934284bdd98cbaa14e79b0b5a141218e507b3a823456"dependencies = ["percent-encoding",]@@ -4382,7 +4416,7 @@ dependencies = ["model-entity","num-traits","ordered-float",- "rand 0.9.4",+ "rand 0.9.3","recursion","serde","serde_json",@@ -4444,9 +4478,9 @@ dependencies = [[[package]]name = "futures-channel"-version = "0.3.32"+version = "0.3.31"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "07bbe89c50d7a535e539b8c17bc0b49bdb77747034daa8087407d655f3f7cc1d"+checksum = "2dff15bf788c671c1934e366d07e30c1814a8ef514e1af724a602e8a2fbe1b10"dependencies = ["futures-core","futures-sink",@@ -4454,9 +4488,9 @@ dependencies = [[[package]]name = "futures-core"-version = "0.3.32"+version = "0.3.31"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "7e3450815272ef58cec6d564423f6e755e25379b217b0bc688e295ba24df6b1d"+checksum = "05f29059c0c2090612e8d742178b0580d2dc940c837851ad723096f87af6663e"[[package]]name = "futures-executor"@@ -4482,9 +4516,9 @@ dependencies = [[[package]]name = "futures-io"-version = "0.3.32"+version = "0.3.31"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "cecba35d7ad927e23624b22ad55235f2239cfa44fd10428eecbeba6d6a717718"+checksum = "9e5c1b78ca4aae1ac06c48a526a655760685149f0d465d21f37abfe57ce075c6"[[package]]name = "futures-lite"@@ -4503,9 +4537,9 @@ dependencies = [[[package]]name = "futures-macro"-version = "0.3.32"+version = "0.3.31"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "e835b70203e41293343137df5c0664546da5745f82ec9b84d40be8336958447b"+checksum = "162ee34ebcb7c64a8abebc059ce0fee27c2262618d7b60ed8faf72fef13c3650"dependencies = ["proc-macro2","quote",@@ -4514,21 +4548,21 @@ dependencies = [[[package]]name = "futures-sink"-version = "0.3.32"+version = "0.3.31"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "c39754e157331b013978ec91992bde1ac089843443c49cbc7f46150b0fad0893"+checksum = "e575fab7d1e0dcb8d0c7bcf9a63ee213816ab51902e6d244a95819acacf1d4f7"[[package]]name = "futures-task"-version = "0.3.32"+version = "0.3.31"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "037711b3d59c33004d3856fbdc83b99d4ff37a24768fa1be9ce3538a1cde4393"+checksum = "f90f7dce0722e95104fcb095585910c0977252f286e354b5e3bd38902cd99988"[[package]]name = "futures-util"-version = "0.3.32"+version = "0.3.31"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "389ca41296e6190b48053de0321d02a77f32f8a5d2461dd38762c0593805c6d6"+checksum = "9fa08315bb612088cc391249efdc3bc77536f16c91f6cf495e6fbe85b20a4a81"dependencies = ["futures-channel","futures-core",@@ -4538,6 +4572,7 @@ dependencies = ["futures-task","memchr","pin-project-lite",+ "pin-utils","slab",]@@ -4602,29 +4637,29 @@ dependencies = [[[package]]name = "getrandom"-version = "0.2.17"+version = "0.2.15"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "ff2abc00be7fca6ebc474524697ae276ad847ad0a6b3faa4bcb027e9a4614ad0"+checksum = "c4567c8db10ae91089c99af84c68c38da3ec2f087c3f82960bcdbf3656b6f4d7"dependencies = ["cfg-if","js-sys","libc",- "wasi 0.11.1+wasi-snapshot-preview1",+ "wasi 0.11.0+wasi-snapshot-preview1","wasm-bindgen",][[package]]name = "getrandom"-version = "0.3.4"+version = "0.3.1"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "899def5c37c4fd7b2664648c28120ecec138e4d395b459e5ca34f9cce2dd77fd"+checksum = "43a49c392881ce6d5c3b8cb70f98717b7c07aabbdff06687b9030dbfbe2725f8"dependencies = ["cfg-if","js-sys","libc",- "r-efi 5.3.0",- "wasip2",+ "wasi 0.13.3+wasi-0.2.2","wasm-bindgen",+ "windows-targets 0.52.6",][[package]]@@ -4635,8 +4670,8 @@ checksum = "0de51e6874e94e7bf76d726fc5d13ba782deca734ff60d5bb2fb2607c7406555"dependencies = ["cfg-if","libc",- "r-efi 6.0.0",- "rand_core 0.10.1",+ "r-efi",+ "rand_core 0.10.0","wasip2","wasip3",]@@ -4692,12 +4727,12 @@ dependencies = ["reqwest 0.13.3","serde","serde_json",- "sha2 0.10.9",+ "sha2 0.10.8","sqlx","subtle","thiserror 2.0.17","tokio",- "tower 0.5.3",+ "tower 0.5.2","tracing","urlencoding","utoipa",@@ -4754,9 +4789,9 @@ dependencies = [[[package]]name = "h2"-version = "0.3.27"+version = "0.3.26"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "0beca50380b1fc32983fc1cb4587bfa4bb9e78fc259aad4a0032d2080309222d"+checksum = "81fe527a889e1532da5c525686d96d4c2e74cdd345badf8dfef9f6b39dd5f5e8"dependencies = ["bytes","fnv",@@ -4773,16 +4808,16 @@ dependencies = [[[package]]name = "h2"-version = "0.4.14"+version = "0.4.13"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "171fefbc92fe4a4de27e0698d6a5b392d6a0e333506bc49133760b3bcf948733"+checksum = "2f44da3a8150a6703ed5d34e164b875fd14c2cdab9af1252a9a1020bde2bdc54"dependencies = ["atomic-waker","bytes","fnv","futures-core","futures-sink",- "http 1.4.0",+ "http 1.3.1","indexmap 2.14.0","slab","tokio",@@ -4818,13 +4853,13 @@ dependencies = [[[package]]name = "hashbrown"-version = "0.15.5"+version = "0.15.2"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "9229cfe53dfd69f0609a49f65461bd93001ea1ef889cd5529dd176593f5338a1"+checksum = "bf151400ff0baff5465007dd2f3e717f3fe502074ca563069ce3a6629d07b289"dependencies = ["allocator-api2","equivalent",- "foldhash 0.1.5",+ "foldhash 0.1.4",][[package]]@@ -4840,9 +4875,9 @@ dependencies = [[[package]]name = "hashbrown"-version = "0.17.1"+version = "0.17.0"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "ed5909b6e89a2db4456e54cd5f673791d7eca6732202bbf2a9cc504fe2f9b84a"+checksum = "4f467dd6dccf739c208452f8014c75c18bb8301b050ad1cfb27153803edb0f51"[[package]]name = "hashlink"@@ -4850,7 +4885,7 @@ version = "0.10.0"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "7382cf6263419f2d8df38c55d7da83da5c18aef87fc7a7fc1fb1e344edfe14c1"dependencies = [- "hashbrown 0.15.5",+ "hashbrown 0.15.2",][[package]]@@ -4862,7 +4897,7 @@ dependencies = ["base64 0.22.1","bytes","headers-core",- "http 1.4.0",+ "http 1.3.1","httpdate","mime","sha1 0.10.6",@@ -4874,7 +4909,7 @@ version = "0.3.0"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "54b4a22553d4242c49fddb9ba998a99962b5cc6f22cb5a3482bec22522403ce4"dependencies = [- "http 1.4.0",+ "http 1.3.1",][[package]]@@ -4911,7 +4946,7 @@ dependencies = ["idna","ipnet","once_cell",- "rand 0.9.4",+ "rand 0.9.3","ring","thiserror 2.0.17","tinyvec",@@ -4933,7 +4968,7 @@ dependencies = ["moka","once_cell","parking_lot",- "rand 0.9.4",+ "rand 0.9.3","resolv-conf","smallvec","thiserror 2.0.17",@@ -5048,11 +5083,12 @@ dependencies = [[[package]]name = "http"-version = "1.4.0"+version = "1.3.1"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "e3ba2a386d7f85a81f119ad7498ebe444d2e22c2af0b86b069416ace48b3311a"+checksum = "f4a85d31aea989eead29a3aaf9e1115a180df8282431156e533de47660892565"dependencies = ["bytes",+ "fnv","itoa",]@@ -5074,7 +5110,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "1efedce1fb8e6913f23e0c92de8e62cd5b772a67e7b3946df930a62566c93184"dependencies = ["bytes",- "http 1.4.0",+ "http 1.3.1",][[package]]@@ -5085,7 +5121,7 @@ checksum = "b021d93e26becf5dc7e1b75b1bed1fd93124b374ceb73f43d4d4eafec896a64a"dependencies = ["bytes","futures-core",- "http 1.4.0",+ "http 1.3.1","http-body 1.0.1","pin-project-lite",]@@ -5102,7 +5138,7 @@ version = "2.1.1"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "0f056c8559e3757392c8d091e796416e4649d8e49e88b8d76df6c002f05027fd"dependencies = [- "http 1.4.0",+ "http 1.3.1","serde",]@@ -5129,9 +5165,9 @@ dependencies = [[[package]]name = "httparse"-version = "1.10.1"+version = "1.10.0"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "6dbf3de79e51f3d586ab4cb9d5c3e2c14aa28ed23d180cf89b4df0454a69cc87"+checksum = "f2d708df4e7140240a16cd6ab0ab65c972d7433ab77819ea693fde9c43811e2a"[[package]]name = "httpdate"@@ -5141,9 +5177,9 @@ checksum = "df3b46402a9d5adb4c86a0cf463f42e19994e3ee891101b1841f30a545cb49a9"[[package]]name = "hybrid-array"-version = "0.4.12"+version = "0.4.10"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "9155a582abd142abc056962c29e3ce5ff2ad5469f4246b537ed42c5deba857da"+checksum = "3944cf8cf766b40e2a1a333ee5e9b563f854d5fa49d6a8ca2764e97c6eddb214"dependencies = ["typenum",]@@ -5158,7 +5194,7 @@ dependencies = ["futures-channel","futures-core","futures-util",- "h2 0.3.27",+ "h2 0.3.26","http 0.2.12","http-body 0.4.6","httparse",@@ -5174,16 +5210,15 @@ dependencies = [[[package]]name = "hyper"-version = "1.9.0"+version = "1.6.0"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "6299f016b246a94207e63da54dbe807655bf9e00044f73ded42c3ac5305fbcca"+checksum = "cc2b571658e38e0c01b1fdca3bbbe93c00d3d71693ff2770043f8c29bc7d6f80"dependencies = [- "atomic-waker","bytes","futures-channel",- "futures-core",- "h2 0.4.14",- "http 1.4.0",+ "futures-util",+ "h2 0.4.13",+ "http 1.3.1","http-body 1.0.1","httparse","httpdate",@@ -5212,19 +5247,21 @@ dependencies = [[[package]]name = "hyper-rustls"-version = "0.27.9"+version = "0.27.5"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "33ca68d021ef39cf6463ab54c1d0f5daf03377b70561305bb89a8f83aab66e0f"+checksum = "2d191583f3da1305256f22463b9bb0471acad48a4e534a5218b9963e9c1f59b2"dependencies = [- "http 1.4.0",- "hyper 1.9.0",+ "futures-util",+ "http 1.3.1",+ "hyper 1.6.0","hyper-util",- "rustls 0.23.40",+ "rustls 0.23.36","rustls-native-certs",+ "rustls-pki-types","tokio","tokio-rustls 0.26.4","tower-service",- "webpki-roots 1.0.7",+ "webpki-roots 0.26.11",][[package]]@@ -5233,7 +5270,7 @@ version = "0.5.2"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "2b90d566bffbce6a75bd8b09a05aa8c2cb1fabb6cb348f8840c9e4c90a0d83b0"dependencies = [- "hyper 1.9.0",+ "hyper 1.6.0","hyper-util","pin-project-lite","tokio",@@ -5242,22 +5279,23 @@ dependencies = [[[package]]name = "hyper-util"-version = "0.1.20"+version = "0.1.17"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "96547c2556ec9d12fb1578c4eaf448b04993e7fb79cbaad930a656880a6bdfa0"+checksum = "3c6995591a8f1380fcb4ba966a252a4b29188d51d2b89e3a252f5305be65aea8"dependencies = ["base64 0.22.1","bytes","futures-channel",+ "futures-core","futures-util",- "http 1.4.0",+ "http 1.3.1","http-body 1.0.1",- "hyper 1.9.0",+ "hyper 1.6.0","ipnet","libc","percent-encoding","pin-project-lite",- "socket2 0.5.10",+ "socket2 0.6.1","tokio","tower-service","tracing",@@ -5288,23 +5326,21 @@ dependencies = [[[package]]name = "icu_collections"-version = "2.2.0"+version = "1.5.0"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "2984d1cd16c883d7935b9e07e44071dca8d917fd52ecc02c04d5fa0b5a3f191c"+checksum = "db2fa452206ebee18c4b5c2274dbf1de17008e874b4dc4f0aea9d01ca79e4526"dependencies = ["displaydoc",- "potential_utf",- "utf8_iter","yoke","zerofrom","zerovec",][[package]]-name = "icu_locale_core"-version = "2.2.0"+name = "icu_locid"+version = "1.5.0"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "92219b62b3e2b4d88ac5119f8904c10f8f61bf7e95b640d25ba3075e6cac2c29"+checksum = "13acbb8371917fc971be86fc8057c41a64b521c184808a698c02acc242dbf637"dependencies = ["displaydoc","litemap",@@ -5313,61 +5349,99 @@ dependencies = ["zerovec",]+[[package]]+name = "icu_locid_transform"+version = "1.5.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "01d11ac35de8e40fdeda00d9e1e9d92525f3f9d887cdd7aa81d727596788b54e"+dependencies = [+ "displaydoc",+ "icu_locid",+ "icu_locid_transform_data",+ "icu_provider",+ "tinystr",+ "zerovec",+]++[[package]]+name = "icu_locid_transform_data"+version = "1.5.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "fdc8ff3388f852bede6b579ad4e978ab004f139284d7b28715f773507b946f6e"+[[package]]name = "icu_normalizer"-version = "2.2.0"+version = "1.5.0"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "c56e5ee99d6e3d33bd91c5d85458b6005a22140021cc324cea84dd0e72cff3b4"+checksum = "19ce3e0da2ec68599d193c93d088142efd7f9c5d6fc9b803774855747dc6a84f"dependencies = [+ "displaydoc","icu_collections","icu_normalizer_data","icu_properties","icu_provider","smallvec",+ "utf16_iter",+ "utf8_iter",+ "write16","zerovec",][[package]]name = "icu_normalizer_data"-version = "2.2.0"+version = "1.5.0"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "da3be0ae77ea334f4da67c12f149704f19f81d1adf7c51cf482943e84a2bad38"+checksum = "f8cafbf7aa791e9b22bec55a167906f9e1215fd475cd22adfcf660e03e989516"[[package]]name = "icu_properties"-version = "2.2.0"+version = "1.5.1"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "bee3b67d0ea5c2cca5003417989af8996f8604e34fb9ddf96208a033901e70de"+checksum = "93d6020766cfc6302c15dbbc9c8778c37e62c14427cb7f6e601d849e092aeef5"dependencies = [+ "displaydoc","icu_collections",- "icu_locale_core",+ "icu_locid_transform","icu_properties_data","icu_provider",- "zerotrie",+ "tinystr","zerovec",][[package]]name = "icu_properties_data"-version = "2.2.0"+version = "1.5.0"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "8e2bbb201e0c04f7b4b3e14382af113e17ba4f63e2c9d2ee626b720cbce54a14"+checksum = "67a8effbc3dd3e4ba1afa8ad918d5684b8868b3b26500753effea8d2eed19569"[[package]]name = "icu_provider"-version = "2.2.0"+version = "1.5.0"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "139c4cf31c8b5f33d7e199446eff9c1e02decfc2f0eec2c8d71f65befa45b421"+checksum = "6ed421c8a8ef78d3e2dbc98a973be2f3770cb42b606e3ab18d6237c4dfde68d9"dependencies = ["displaydoc",- "icu_locale_core",+ "icu_locid",+ "icu_provider_macros",+ "stable_deref_trait",+ "tinystr","writeable","yoke","zerofrom",- "zerotrie","zerovec",]+[[package]]+name = "icu_provider_macros"+version = "1.5.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "1ec89e9337638ecdc08744df490b221a7399bf8d164eb52a665454e60e075ad6"+dependencies = [+ "proc-macro2",+ "quote",+ "syn 2.0.117",+]+[[package]]name = "id-arena"version = "2.3.0"@@ -5382,9 +5456,9 @@ checksum = "b9e0384b61958566e926dc50660321d12159025e767c18e043daf26b70104c39"[[package]]name = "idna"-version = "1.1.0"+version = "1.0.3"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "3b0875f23caa03898994f6ddc501886a45c7d3d62d04d2d90788d47be1b1e4de"+checksum = "686f825264d630750a544639377bae737628043f20d38bbc029e8f29ea968a7e"dependencies = ["idna_adapter","smallvec",@@ -5393,9 +5467,9 @@ dependencies = [[[package]]name = "idna_adapter"-version = "1.2.2"+version = "1.2.0"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "cb68373c0d6620ef8105e855e7745e18b0d00d3bdb07fb532e434244cdb9a714"+checksum = "daca1df1c957320b2cf139ac61e7bd64fed304c5040df000a745aa1de3b4ef71"dependencies = ["icu_normalizer","icu_properties",@@ -5477,7 +5551,7 @@ dependencies = ["serde","serde_json","tokio",- "tower 0.5.3",+ "tower 0.5.2","tower-http","tracing","url",@@ -5534,7 +5608,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "d466e9454f08e4a911e14806c24e16fba1b4c121d1ea474396f396069cf949d9"dependencies = ["equivalent",- "hashbrown 0.17.1",+ "hashbrown 0.17.0","serde","serde_core",]@@ -5632,7 +5706,7 @@ version = "0.3.4"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "4d40460c0ce33d6ce4b0630ad68ff63d6661961c48b6dba35e5a4d81cfb48222"dependencies = [- "socket2 0.6.3",+ "socket2 0.6.1","widestring","windows-registry","windows-result",@@ -5641,9 +5715,9 @@ dependencies = [[[package]]name = "ipnet"-version = "2.12.0"+version = "2.11.0"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "d98f6fed1fde3f8c21bc40a1abb88dd75e67924f9cffc3ef95607bad8017f8e2"+checksum = "469fb0b9cefa57e3ef31275ee7cacb78f2fdca44e4765491884a2b119d4eb130"[[package]]name = "iri-string"@@ -5793,11 +5867,10 @@ dependencies = [[[package]]name = "jobserver"-version = "0.1.34"+version = "0.1.32"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "9afb3de4395d6b3e67a780b6de64b51c978ecf11cb9a462c66be7d4ca9039d33"+checksum = "48d1dbcbbeb6a7fec7e059840aa538bd62aaccf972c7346c4d9d2059312853d0"dependencies = [- "getrandom 0.3.4","libc",]@@ -5821,7 +5894,7 @@ checksum = "0529410abe238729a60b108898784df8984c87f6054c9c4fcacc47e4803c1ce1"dependencies = ["base64 0.22.1","ed25519-dalek",- "getrandom 0.2.17",+ "getrandom 0.2.15","hmac 0.12.1","js-sys","p256 0.13.2",@@ -5830,7 +5903,7 @@ dependencies = ["rsa","serde","serde_json",- "sha2 0.10.9",+ "sha2 0.10.8","signature 2.2.0",]@@ -5841,7 +5914,7 @@ source = "git+https://github.com/whutchinson98/jsonwebtoken#c8c0d19511a0e7ba9d45dependencies = ["base64 0.22.1","ed25519-dalek",- "getrandom 0.2.17",+ "getrandom 0.2.15","hmac 0.12.1","js-sys","p256 0.13.2",@@ -5851,7 +5924,7 @@ dependencies = ["rsa","serde","serde_json",- "sha2 0.10.9",+ "sha2 0.10.8","signature 2.2.0","simple_asn1",]@@ -5878,11 +5951,11 @@ dependencies = ["base64 0.22.1","bytes","futures",- "http 1.4.0",+ "http 1.3.1","http-body 1.0.1","http-body-util","http-serde",- "hyper 1.9.0",+ "hyper 1.6.0","hyper-util","lambda_runtime_api_client","pin-project",@@ -5905,10 +5978,10 @@ dependencies = ["bytes","futures-channel","futures-util",- "http 1.4.0",+ "http 1.3.1","http-body 1.0.1","http-body-util",- "hyper 1.9.0",+ "hyper 1.6.0","hyper-util","tokio","tower 0.4.13",@@ -5971,9 +6044,9 @@ checksum = "0864a00c8d019e36216b69c2c4ce50b83b7bd966add3cf5ba554ec44f8bebcf5"[[package]]name = "libc"-version = "0.2.186"+version = "0.2.172"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "68ab91017fe16c622486840e4c83c9a37afeff978bd239b5293d61ece587de66"+checksum = "d750af042f7ef4f724306de029d18836c26c1765a54a6a3f094cbd23a7267ffa"[[package]]name = "libfuzzer-sys"@@ -5992,14 +6065,14 @@ source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "fc2f4eb4bc735547cfed7c0a4922cbd04a4655978c09b54f1f7b228750664c34"dependencies = ["cfg-if",- "windows-targets 0.48.5",+ "windows-targets 0.52.6",][[package]]name = "libm"-version = "0.2.16"+version = "0.2.11"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "b6d2cec3eae94f9f509c767b45932f1ada8350c4bdb85af2fcab4a3c14807981"+checksum = "8355be11b20d696c8f18f6cc018c4e372165b1fa8126cef092399c9951984ffa"[[package]]name = "libsqlite3-sys"@@ -6029,9 +6102,9 @@ checksum = "cd945864f07fe9f5371a27ad7b52a172b4b499999f1d97574c9fa68373937e12"[[package]]name = "litemap"-version = "0.8.2"+version = "0.7.4"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "92daf443525c4cce67b150400bc2316076100ce0b3686209eb8cf3c31612e6f0"+checksum = "4ee93343901ab17bd981295f2cf0026d4ad018c7c31ba84549a4ddbb47a45104"[[package]]name = "livekit-api"@@ -6041,7 +6114,7 @@ checksum = "900451a686a1ce8488c420e81a2135831383b03aade6bc3075cf80463d3dd6a4"dependencies = ["base64 0.21.7","device-info",- "http 1.4.0",+ "http 1.3.1","jsonwebtoken 10.3.0 (registry+https://github.com/rust-lang/crates.io-index)","livekit-protocol","log",@@ -6049,12 +6122,12 @@ dependencies = ["parking_lot","pbjson-types","prost 0.12.6",- "rand 0.9.4",+ "rand 0.9.3","reqwest 0.12.28","scopeguard","serde","serde_json",- "sha2 0.10.9",+ "sha2 0.10.8","thiserror 2.0.17","tokio-tungstenite 0.20.1","url",@@ -6093,7 +6166,7 @@ version = "0.1.0"dependencies = ["anyhow","futures",- "http 1.4.0",+ "http 1.3.1","reqwest 0.13.3","serde","serde_json",@@ -6130,10 +6203,11 @@ dependencies = [[[package]]name = "lock_api"-version = "0.4.14"+version = "0.4.12"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "224399e74b87b5f3557511d98dff8b14089b3dadafcab6bb93eab67d3aace965"+checksum = "07af8b9cdd281b7915f413fa73f29ebd5d55d0d3f0155584dade1ff18cea1b17"dependencies = [+ "autocfg","scopeguard",]@@ -6145,9 +6219,9 @@ checksum = "9374ef4228402d4b7e403e5838cb880d9ee663314b0a900d5a6aabf0c213552e"[[package]]name = "log"-version = "0.4.29"+version = "0.4.26"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "5e5032e24019045c762d3c0f28f5b6b8bbf38563a65908389bf7978758920897"+checksum = "30bde2b3dc3671ae49d8e2e9f044c7c005836e7a023ee57cffa25ab82764bb9e"[[package]]name = "lol_html"@@ -6159,7 +6233,7 @@ dependencies = ["cfg-if","cssparser 0.35.0","encoding_rs",- "hashbrown 0.15.5",+ "hashbrown 0.15.2","memchr","mime","precomputed-hash",@@ -6178,9 +6252,9 @@ dependencies = [[[package]]name = "lru"-version = "0.16.4"+version = "0.16.3"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "7f66e8d5d03f609abc3a39e6f08e4164ebf1447a732906d39eb9b99b7919ef39"+checksum = "a1dc47f592c06f33f8e3aea9591776ec7c9f9e4124778ff8a3c3b87159f7e593"dependencies = ["hashbrown 0.16.1",]@@ -6230,7 +6304,7 @@ dependencies = ["macro_env","macro_env_var","macro_user_id",- "rand 0.9.4",+ "rand 0.9.3","remote_env_var","serde","serde_json",@@ -6299,7 +6373,7 @@ dependencies = ["models_permissions","models_team","non_empty",- "rand 0.9.4",+ "rand 0.9.3","serde","serde_json","sqlx",@@ -6383,7 +6457,7 @@ dependencies = ["sqlx","thiserror 2.0.17","tokio",- "tower 0.5.3",+ "tower 0.5.2","tracing","url","urlencoding",@@ -6433,9 +6507,9 @@ dependencies = [name = "macro_tower_layers"version = "0.1.0"dependencies = [- "http 1.4.0",+ "http 1.3.1","tokio",- "tower 0.5.3",+ "tower 0.5.2","tower-http","tracing",]@@ -6611,9 +6685,9 @@ dependencies = ["redis","serde","serde_json",- "sha2 0.10.9",+ "sha2 0.10.8","thiserror 2.0.17",- "tower 0.5.3",+ "tower 0.5.2","tower-http","tracing","url",@@ -6663,6 +6737,7 @@ dependencies = ["call","chat","comms",+ "crm","documents","email","email_service_client",@@ -6670,7 +6745,7 @@ dependencies = ["entity_access_management","frecency","fusionauth",- "http 1.4.0",+ "http 1.3.1","lexical_client","macro_auth","macro_aws_config",@@ -6718,9 +6793,9 @@ dependencies = [[[package]]name = "memchr"-version = "2.8.0"+version = "2.7.4"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "f8ca58f447f06ed17d5fc4043ce1b10dd205e060fb3ce5b979b8ed8e59ff3f79"+checksum = "78ca9ab1a0babb1e7d5695e3530886289c18cf2f87ec19a575a0abdce112e3a3"[[package]]name = "memory"@@ -6734,6 +6809,7 @@ dependencies = ["call","chrono","comms",+ "crm","documents","email","email_service_client",@@ -6840,19 +6916,19 @@ checksum = "a4a650543ca06a924e8b371db273b2756685faae30f8487da1b56505a8f78b0c"dependencies = ["libc","log",- "wasi 0.11.1+wasi-snapshot-preview1",+ "wasi 0.11.0+wasi-snapshot-preview1","windows-sys 0.48.0",][[package]]name = "mio"-version = "1.2.0"+version = "1.0.3"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "50b7e5b27aa02a74bac8c3f23f448f8d87ff11f92d3aac1a6ed369ee08cc56c1"+checksum = "2886843bf800fba2e3377cff24abf6379b4c4d5c6681eaf9ea5b0d15090450bd"dependencies = ["libc",- "wasi 0.11.1+wasi-snapshot-preview1",- "windows-sys 0.61.2",+ "wasi 0.11.0+wasi-snapshot-preview1",+ "windows-sys 0.52.0",][[package]]@@ -7223,7 +7299,7 @@ dependencies = ["bytes","encoding_rs","futures-util",- "http 1.4.0",+ "http 1.3.1","httparse","memchr","mime",@@ -7271,7 +7347,7 @@ dependencies = ["native_app_service","rootcause","semver",- "sha2 0.10.9",+ "sha2 0.10.8","tokio","tower-http","tracing",@@ -7291,7 +7367,7 @@ dependencies = ["semver","serde","serde_json",- "sha2 0.10.9",+ "sha2 0.10.8","strum","thiserror 2.0.17","tokio",@@ -7410,12 +7486,12 @@ dependencies = ["schemars","serde","serde_json",- "sha2 0.10.9",+ "sha2 0.10.8","sqlx","strum","thiserror 2.0.17","tokio",- "tower 0.5.3",+ "tower 0.5.2","tracing","url","utoipa",@@ -7464,7 +7540,7 @@ dependencies = ["rootcause","serde","serde_json",- "sha2 0.10.9",+ "sha2 0.10.8","sqlx","tokio","tracing",@@ -7517,12 +7593,12 @@ dependencies = ["secretsmanager_client","serde","serde_json",- "sha2 0.10.9",+ "sha2 0.10.8","sns_client","sqlx","thiserror 2.0.17","tokio",- "tower 0.5.3",+ "tower 0.5.2","tower-http","tracing","url",@@ -7568,9 +7644,9 @@ dependencies = [[[package]]name = "num-conv"-version = "0.2.2"+version = "0.2.0"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "521739c6d2bac4aa25192232afe6841231376b2b26d4d9fae5ecf8ca5772e441"+checksum = "cf97ec579c3c42f953ef76dbf8d55ac91fb219dde70e49aa4a6b7d74e9919050"[[package]]name = "num-derive"@@ -7632,13 +7708,13 @@ checksum = "51e219e79014df21a225b1860a479e2dcd7cbd9130f4defd4bd0e191ea31d67d"dependencies = ["base64 0.22.1","chrono",- "getrandom 0.2.17",- "http 1.4.0",+ "getrandom 0.2.15",+ "http 1.3.1","rand 0.8.5","serde","serde_json","serde_path_to_error",- "sha2 0.10.9",+ "sha2 0.10.8","thiserror 1.0.69","url",]@@ -7804,9 +7880,9 @@ dependencies = [[[package]]name = "once_cell"-version = "1.21.4"+version = "1.21.3"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "9f7c3e4beb33f85d45ae3e3a1792185706c8e16d043238c593331cc7cd313b50"+checksum = "42f5e15c9953c5e4ccceeb2e7382a716482c34515315f7b03532b8b4e8393d2d"dependencies = ["critical-section","portable-atomic",@@ -7868,9 +7944,9 @@ dependencies = [[[package]]name = "openssl-probe"-version = "0.2.1"+version = "0.1.6"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "7c87def4c32ab89d880effc9e097653c8da5d6ef28e6b539d313baaacfbafcbe"+checksum = "d05e27ee213611ffe7d6348b942e8f942b37114c00cc03cec254295a4a17852e"[[package]]name = "opentelemetry"@@ -7894,7 +7970,7 @@ checksum = "d7a6d09a73194e6b66df7c8f1b680f156d916a1a942abf2de06823dd02b7855d"dependencies = ["async-trait","bytes",- "http 1.4.0",+ "http 1.3.1","opentelemetry",]@@ -7904,7 +7980,7 @@ version = "0.31.0"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "7a2366db2dca4d2ad033cad11e6ee42844fd727007af5ad04a1730f4cb8163bf"dependencies = [- "http 1.4.0",+ "http 1.3.1","opentelemetry","opentelemetry-http","opentelemetry-proto",@@ -7940,7 +8016,7 @@ dependencies = ["futures-util","opentelemetry","percent-encoding",- "rand 0.9.4",+ "rand 0.9.3","thiserror 2.0.17","tokio","tokio-stream",@@ -8018,7 +8094,7 @@ checksum = "51f44edd08f51e2ade572f141051021c5af22677e42b7dd28a88155151c33594"dependencies = ["ecdsa 0.14.8","elliptic-curve 0.12.3",- "sha2 0.10.9",+ "sha2 0.10.8",][[package]]@@ -8030,7 +8106,7 @@ dependencies = ["ecdsa 0.16.9","elliptic-curve 0.13.8","primeorder",- "sha2 0.10.9",+ "sha2 0.10.8",][[package]]@@ -8042,7 +8118,7 @@ dependencies = ["ecdsa 0.16.9","elliptic-curve 0.13.8","primeorder",- "sha2 0.10.9",+ "sha2 0.10.8",][[package]]@@ -8053,9 +8129,9 @@ checksum = "f38d5652c16fde515bb1ecef450ab0f6a219d619a7274976324d5e377f7dceba"[[package]]name = "parking_lot"-version = "0.12.5"+version = "0.12.3"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "93857453250e3077bd71ff98b6a65ea6621a19bb0f559a85248955ac12c45a1a"+checksum = "f1bf18183cf54e8d6059647fc3063646a1801cf30896933ec2311622cc4b9a27"dependencies = ["lock_api","parking_lot_core",@@ -8063,15 +8139,15 @@ dependencies = [[[package]]name = "parking_lot_core"-version = "0.9.12"+version = "0.9.10"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "2621685985a2ebf1c516881c026032ac7deafcda1a2c9b7850dc81e3dfcb64c1"+checksum = "1e401f977ab385c9e4e3ab30627d6f26d00e2c73eef317493c4ec6d468726cf8"dependencies = ["cfg-if","libc","redox_syscall","smallvec",- "windows-link",+ "windows-targets 0.52.6",][[package]]@@ -8186,9 +8262,9 @@ dependencies = [[[package]]name = "percent-encoding"-version = "2.3.2"+version = "2.3.1"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "9b4f627cb1b25917193a259e49bdad08f671f8d9708acfd5fe0a8c1455d87220"+checksum = "e3148f5046208a5d56bcfc03053e3ca6334e51da8dfb19b6cdc8b306fae3283e"[[package]]name = "petgraph"@@ -8341,9 +8417,9 @@ dependencies = [[[package]]name = "pin-project-lite"-version = "0.2.17"+version = "0.2.16"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "a89322df9ebe1c1578d689c92318e070967d1042b512afbe49518723f4e6d5cd"+checksum = "3b3cff922bd51709b605d9ead9aa71031d81447142d828eb4a6eba76fe619f9b"[[package]]name = "pin-utils"@@ -8438,7 +8514,7 @@ dependencies = ["hmac 0.13.0","md-5 0.11.0","memchr",- "rand 0.10.1",+ "rand 0.10.0","sha2 0.11.0","stringprep",]@@ -8454,15 +8530,6 @@ dependencies = ["postgres-protocol",]-[[package]]-name = "potential_utf"-version = "0.1.5"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "0103b1cef7ec0cf76490e969665504990193874ea05c85ff9bab8b911d0a0564"-dependencies = [- "zerovec",-]-[[package]]name = "powerfmt"version = "0.2.0"@@ -8471,11 +8538,11 @@ checksum = "439ee305def115ba05938db6eb1644ff94165c5ab5e9420d1c1bcedbba909391"[[package]]name = "ppv-lite86"-version = "0.2.21"+version = "0.2.20"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "85eae3c4ed2f50dcfe72643da4befc30deadb458a9b590d720cde2f2b1e97da9"+checksum = "77957b295656769bb8ad2b6a6b09d897d94f05c41b069aede1fcdaa675eaea04"dependencies = [- "zerocopy 0.8.48",+ "zerocopy 0.7.35",][[package]]@@ -8512,9 +8579,9 @@ dependencies = [[[package]]name = "prettyplease"-version = "0.2.37"+version = "0.2.32"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "479ca8adacdd7ce8f1fb39ce9ecccbfe93a3f1344b3d0d97f20bc0196208f62b"+checksum = "664ec5419c51e34154eec046ebcba56312d5a2fc3b09a06da188e1ad21afadf6"dependencies = ["proc-macro2","syn 2.0.117",@@ -8672,7 +8739,7 @@ dependencies = ["system_properties","thiserror 2.0.17","tokio",- "tower 0.5.3",+ "tower 0.5.2","tower-http","tracing","utoipa",@@ -8706,7 +8773,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "22505a5c94da8e3b7c2996394d1c933236c4d743e81a410bcca4e6989fc066a4"dependencies = ["bytes",- "heck 0.4.1",+ "heck 0.5.0","itertools 0.11.0","log","multimap",@@ -8790,7 +8857,7 @@ dependencies = ["quinn-proto","quinn-udp","rustc-hash 2.1.1",- "rustls 0.23.40",+ "rustls 0.23.36","socket2 0.5.10","thiserror 2.0.17","tokio",@@ -8805,12 +8872,12 @@ checksum = "434b42fec591c96ef50e21e886936e66d3cc3f737104fdb9b737c40ffb94c098"dependencies = ["aws-lc-rs","bytes",- "getrandom 0.3.4",+ "getrandom 0.3.1","lru-slab",- "rand 0.9.4",+ "rand 0.9.3","ring","rustc-hash 2.1.1",- "rustls 0.23.40",+ "rustls 0.23.36","rustls-pki-types","slab","thiserror 2.0.17",@@ -8848,12 +8915,6 @@ version = "0.5.1"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "640c9bd8497b02465aeef5375144c26062e0dcd5939dfcbb0f5db76cb8c17c73"-[[package]]-name = "r-efi"-version = "5.3.0"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "69cdb34c158ceb288df11e18b4bd39de994f6657d83847bdffdbd7f346754b0f"-[[package]]name = "r-efi"version = "6.0.0"@@ -8886,23 +8947,23 @@ dependencies = [[[package]]name = "rand"-version = "0.9.4"+version = "0.9.3"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "44c5af06bb1b7d3216d91932aed5265164bf384dc89cd6ba05cf59a35f5f76ea"+checksum = "7ec095654a25171c2124e9e3393a930bddbffdc939556c914957a4c3e0a87166"dependencies = ["rand_chacha 0.9.0",- "rand_core 0.9.5",+ "rand_core 0.9.0",][[package]]name = "rand"-version = "0.10.1"+version = "0.10.0"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "d2e8e8bcc7961af1fdac401278c6a831614941f6164ee3bf4ce61b7edb162207"+checksum = "bc266eb313df6c5c09c1c7b1fbe2510961e5bcd3add930c1e31f7ed9da0feff8"dependencies = ["chacha20","getrandom 0.4.2",- "rand_core 0.10.1",+ "rand_core 0.10.0",][[package]]@@ -8932,7 +8993,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "d3022b5f1df60f26e1ffddd6c66e8aa15de382ae63b3a0c1bfc0e4d3e3f325cb"dependencies = ["ppv-lite86",- "rand_core 0.9.5",+ "rand_core 0.9.0",][[package]]@@ -8950,23 +9011,24 @@ version = "0.6.4"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "ec0be4795e2f6a28069bec0b5ff3e2ac9bafc99e6a9a7dc3547996c5c816922c"dependencies = [- "getrandom 0.2.17",+ "getrandom 0.2.15",][[package]]name = "rand_core"-version = "0.9.5"+version = "0.9.0"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "76afc826de14238e6e8c374ddcc1fa19e374fd8dd986b0d2af0d02377261d83c"+checksum = "b08f3c9802962f7e1b25113931d94f43ed9725bebc59db9d0c3e9a23b67e15ff"dependencies = [- "getrandom 0.3.4",+ "getrandom 0.3.1",+ "zerocopy 0.8.17",][[package]]name = "rand_core"-version = "0.10.1"+version = "0.10.0"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "63b8176103e19a2643978565ca18b50549f6101881c443590420e4dc998a3c69"+checksum = "0c8d0fd677905edcbeedbf2edb6494d676f0e98d54d5cf9bda0b061cb8fb8aba"[[package]]name = "rand_hc"@@ -9021,7 +9083,7 @@ dependencies = ["num-traits","paste","profiling",- "rand 0.9.4",+ "rand 0.9.3","rand_chacha 0.9.0","simd_helpers","thiserror 2.0.17",@@ -9094,12 +9156,12 @@ dependencies = ["num-bigint","percent-encoding","pin-project-lite",- "rand 0.9.4",- "rustls 0.23.40",+ "rand 0.9.3",+ "rustls 0.23.36","rustls-native-certs","ryu","sha1_smol",- "socket2 0.6.3",+ "socket2 0.6.1","tokio","tokio-rustls 0.26.4","tokio-util",@@ -9109,9 +9171,9 @@ dependencies = [[[package]]name = "redox_syscall"-version = "0.5.18"+version = "0.5.8"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "ed2bf2547551a7053d6fdfafda3f938979645c44812fbfcda098faae3f1a362d"+checksum = "03a862b389f93e68874fbf580b9de08dd02facb9a788ebadaf4a3fd33cf58834"dependencies = ["bitflags 2.11.1",]@@ -9163,7 +9225,7 @@ dependencies = ["sqlx","thiserror 2.0.17","tokio",- "tower 0.5.3",+ "tower 0.5.2","tracing","url","urlencoding",@@ -9196,9 +9258,9 @@ dependencies = [[[package]]name = "regex-lite"-version = "0.1.9"+version = "0.1.6"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "cab834c73d247e67f4fae452806d17d3c7501756d98c8808d7c9c7aa7d18f973"+checksum = "53a49587ad06b26609c52e423de037e7f57f20d53535d66e08c695f347df952a"[[package]]name = "regex-syntax"@@ -9224,18 +9286,18 @@ dependencies = ["base64 0.22.1","bytes","futures-core",- "http 1.4.0",+ "http 1.3.1","http-body 1.0.1","http-body-util",- "hyper 1.9.0",- "hyper-rustls 0.27.9",+ "hyper 1.6.0",+ "hyper-rustls 0.27.5","hyper-util","js-sys","log","percent-encoding","pin-project-lite","quinn",- "rustls 0.23.40",+ "rustls 0.23.36","rustls-pki-types","serde","serde_json",@@ -9243,14 +9305,14 @@ dependencies = ["sync_wrapper","tokio","tokio-rustls 0.26.4",- "tower 0.5.3",+ "tower 0.5.2","tower-http","tower-service","url","wasm-bindgen","wasm-bindgen-futures","web-sys",- "webpki-roots 1.0.7",+ "webpki-roots 1.0.5",][[package]]@@ -9264,11 +9326,11 @@ dependencies = ["futures-core","futures-util","hickory-resolver",- "http 1.4.0",+ "http 1.3.1","http-body 1.0.1","http-body-util",- "hyper 1.9.0",- "hyper-rustls 0.27.9",+ "hyper 1.6.0",+ "hyper-rustls 0.27.5","hyper-util","js-sys","log",@@ -9277,7 +9339,7 @@ dependencies = ["percent-encoding","pin-project-lite","quinn",- "rustls 0.23.40",+ "rustls 0.23.36","rustls-pki-types","rustls-platform-verifier","serde",@@ -9287,7 +9349,7 @@ dependencies = ["tokio","tokio-rustls 0.26.4","tokio-util",- "tower 0.5.3",+ "tower 0.5.2","tower-http","tower-service","url",@@ -9338,7 +9400,7 @@ checksum = "a4689e6c2294d81e88dc6261c768b63bc4fcdb852be6d1352498b114f61383b7"dependencies = ["cc","cfg-if",- "getrandom 0.2.17",+ "getrandom 0.2.15","libc","untrusted","windows-sys 0.52.0",@@ -9346,22 +9408,22 @@ dependencies = [[[package]]name = "rmcp"-version = "1.6.0"+version = "1.7.0"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "e12ca9067b5ebfbd5b3fcdc4acfceb81aa7d5ab2a879dff7cb75d22434276aad"+checksum = "0810a9f717d9828f475fe1f629f4c305c8464b7f496c3a854b58d29e65f4058e"dependencies = ["async-trait","base64 0.22.1","bytes","chrono","futures",- "http 1.4.0",+ "http 1.3.1","http-body 1.0.1","http-body-util","oauth2","pastey 0.2.1","pin-project-lite",- "rand 0.10.1",+ "rand 0.10.0","reqwest 0.13.3","rmcp-macros","schemars",@@ -9380,9 +9442,9 @@ dependencies = [[[package]]name = "rmcp-macros"-version = "1.6.0"+version = "1.7.0"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "7caa6743cc0888e433105fe1bc551a7f607940b126a37bc97b478e86064627eb"+checksum = "6aefac48c364756e97f04c0401ba3231e8607882c7c1d92da0437dc16307904d"dependencies = ["darling 0.23.0","proc-macro2",@@ -9487,7 +9549,7 @@ version = "8.6.0"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "5a2fcdc9f40c8dc2922842ca9add611ad19f332227fc651d015881ad1552bd9a"dependencies = [- "sha2 0.10.9",+ "sha2 0.10.8","walkdir",]@@ -9539,24 +9601,24 @@ dependencies = [[[package]]name = "rustls"-version = "0.23.40"+version = "0.23.36"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "ef86cd5876211988985292b91c96a8f2d298df24e75989a43a3c73f2d4d8168b"+checksum = "c665f33d38cea657d9614f766881e4d510e0eda4239891eea56b4cadcf01801b"dependencies = ["aws-lc-rs","once_cell","ring","rustls-pki-types",- "rustls-webpki 0.103.13",+ "rustls-webpki 0.103.12","subtle","zeroize",][[package]]name = "rustls-native-certs"-version = "0.8.3"+version = "0.8.1"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "612460d5f7bea540c490b2b6395d8e34a953e52b491accd6c86c8164c5932a63"+checksum = "7fcff2dd52b58a8d98a70243663a0d234c4e2b79235637849d15913394a247d3"dependencies = ["openssl-probe","rustls-pki-types",@@ -9566,9 +9628,9 @@ dependencies = [[[package]]name = "rustls-pki-types"-version = "1.14.1"+version = "1.13.2"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "30a7197ae7eb376e574fe940d068c30fe0462554a3ddbe4eca7838e049c937a9"+checksum = "21e6f2ab2928ca4291b86736a8bd920a277a399bba1589409d72154ff87c1282"dependencies = ["web-time","zeroize",@@ -9585,14 +9647,14 @@ dependencies = ["jni 0.22.4","log","once_cell",- "rustls 0.23.40",+ "rustls 0.23.36","rustls-native-certs","rustls-platform-verifier-android",- "rustls-webpki 0.103.13",+ "rustls-webpki 0.103.12","security-framework","security-framework-sys","webpki-root-certs",- "windows-sys 0.59.0",+ "windows-sys 0.61.2",][[package]]@@ -9613,9 +9675,9 @@ dependencies = [[[package]]name = "rustls-webpki"-version = "0.103.13"+version = "0.103.12"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "61c429a8649f110dddef65e2a5ad240f747e85f7758a6bccc7e5777bd33f756e"+checksum = "8279bb85272c9f10811ae6a6c547ff594d6a7f3c6c6b02ee9726d1d0dcfcdd06"dependencies = ["aws-lc-rs","ring",@@ -9625,9 +9687,9 @@ dependencies = [[[package]]name = "rustversion"-version = "1.0.22"+version = "1.0.19"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "b39cdef0fa800fc44525c84ccb54a029961a8215f9619753635a9c0d2538d46d"+checksum = "f7c45b9784283f1b2e7fb61b42047c2fd678ef0960d4f6f1eba131594cc369d4"[[package]]name = "ryu"@@ -9688,11 +9750,11 @@ dependencies = [[[package]]name = "schannel"-version = "0.1.29"+version = "0.1.27"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "91c1b7e4904c873ef0710c1f407dde2e6287de2bebc1bbbf7d430bb7cbffd939"+checksum = "1f29ebaa345f945cec9fbbc532eb307f0fdad8161f281b6369539c8d84876b3d"dependencies = [- "windows-sys 0.61.2",+ "windows-sys 0.59.0",][[package]]@@ -9851,7 +9913,7 @@ dependencies = ["thiserror 2.0.17","tokio","tokio-util",- "tower 0.5.3",+ "tower 0.5.2","tower-http","tracing","utoipa",@@ -9899,7 +9961,7 @@ dependencies = ["strum","thiserror 2.0.17","tokio",- "tower 0.5.3",+ "tower 0.5.2","tower-http","tracing","utoipa",@@ -10030,7 +10092,7 @@ dependencies = ["model-entity","models_email","models_permissions",- "rand 0.9.4",+ "rand 0.9.3","reqwest 0.13.3","serde","serde_json",@@ -10082,12 +10144,11 @@ dependencies = [[[package]]name = "semver"-version = "1.0.28"+version = "1.0.25"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "8a7852d02fc848982e0c167ef163aaff9cd91dc640ba85e263cb1ce46fae51cd"+checksum = "f79dfe2d285b0488816f30e700a7438c5a73d816b5b7d3ac72fbc48b0d185e03"dependencies = ["serde",- "serde_core",][[package]]@@ -10144,26 +10205,24 @@ dependencies = [[[package]]name = "serde_json"-version = "1.0.149"+version = "1.0.141"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "83fc039473c5595ace860d8c4fafa220ff474b3fc6bfdb4293327f1a37e94d86"+checksum = "30b9eff21ebe718216c6ec64e1d9ac57087aad11efc64e32002bce4a0d4c03d3"dependencies = ["itoa","memchr",+ "ryu","serde",- "serde_core",- "zmij",][[package]]name = "serde_path_to_error"-version = "0.1.20"+version = "0.1.16"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "10a9ff822e371bb5403e391ecd83e182e0e77ba7f6fe0160b795797109d1b457"+checksum = "af99884400da37c88f5e9146b7f1fd0fbcae8f6eec4e9da38b67d05486f814a6"dependencies = ["itoa","serde",- "serde_core",][[package]]@@ -10337,9 +10396,9 @@ checksum = "bbfa15b3dddfee50a0fff136974b3e1bde555604ba463834a7eb7deb6417705d"[[package]]name = "sha2"-version = "0.10.9"+version = "0.10.8"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "a7507d819769d01a365ab707794a4084392c824f54a7a6a7862f8c3d0892b283"+checksum = "793db75ad2bcafc3ffa7c68b215fee268f537982cd901d132f89c6343f3a3dc8"dependencies = ["cfg-if","cpufeatures 0.2.17",@@ -10412,11 +10471,10 @@ dependencies = [[[package]]name = "signal-hook-registry"-version = "1.4.8"+version = "1.4.2"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "c4db69cba1110affc0e9f7bcd48bbf87b3f4fc7c61fc9155afd4c469eb3d6c1b"+checksum = "a9e9e0b4211b72e7b8b6e85c807d36c212bdb33ea8587f7569562a84df5465b1"dependencies = [- "errno","libc",]@@ -10497,15 +10555,18 @@ checksum = "56199f7ddabf13fe5074ce809e7d3f42b42ae711800501b5b16ea82ad029c39d"[[package]]name = "slab"-version = "0.4.12"+version = "0.4.9"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "0c790de23124f9ab44544d7ac05d60440adc586479ce501c1d6d7da3cd8c9cf5"+checksum = "8f92a496fb766b417c996b9c5e57daf2f7ad3b0bebe1ccfca4856390e3d3bb67"+dependencies = [+ "autocfg",+][[package]]name = "smallvec"-version = "1.15.1"+version = "1.13.2"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "67b1b7a3b5fe4f1376887184045fcf45c69e92af734b7aaddc05fb777b6fbd03"+checksum = "3c5e1a9a646d36c3599cd173a41282daf47c44583ad367b8e6837255952e5c67"dependencies = ["serde",]@@ -10563,12 +10624,12 @@ dependencies = [[[package]]name = "socket2"-version = "0.6.3"+version = "0.6.1"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "3a766e1110788c36f4fa1c2b71b387a7815aa65f88ce0229841826633d93723e"+checksum = "17129e116933cf371d018bb80ae557e889637989d8638274fb25622827b03881"dependencies = ["libc",- "windows-sys 0.61.2",+ "windows-sys 0.60.2",][[package]]@@ -10585,6 +10646,7 @@ dependencies = ["comms","cool_asserts","cowlike",+ "crm","document_sub_type","doppleganger","either",@@ -10618,7 +10680,7 @@ dependencies = ["system_properties","thiserror 2.0.17","tokio",- "tower 0.5.3",+ "tower 0.5.2","tracing","utoipa","uuid",@@ -10689,17 +10751,17 @@ dependencies = ["futures-intrusive","futures-io","futures-util",- "hashbrown 0.15.5",+ "hashbrown 0.15.2","hashlink","indexmap 2.14.0","log","memchr","once_cell","percent-encoding",- "rustls 0.23.40",+ "rustls 0.23.36","serde","serde_json",- "sha2 0.10.9",+ "sha2 0.10.8","smallvec","thiserror 2.0.17","tokio",@@ -10738,7 +10800,7 @@ dependencies = ["quote","serde","serde_json",- "sha2 0.10.9",+ "sha2 0.10.8","sqlx-core","sqlx-mysql","sqlx-postgres",@@ -10782,7 +10844,7 @@ dependencies = ["rsa","serde","sha1 0.10.6",- "sha2 0.10.9",+ "sha2 0.10.8","smallvec","sqlx-core","stringprep",@@ -10821,7 +10883,7 @@ dependencies = ["rand 0.8.5","serde","serde_json",- "sha2 0.10.9",+ "sha2 0.10.8","smallvec","sqlx-core","stringprep",@@ -10900,9 +10962,9 @@ dependencies = [[[package]]name = "stable_deref_trait"-version = "1.2.1"+version = "1.2.0"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "6ce2be8dc25455e1f91df71bfa12ad37d7af1092ae736f3a6cd0e37bc7810596"+checksum = "a8f112729512f8e442d81f95a8a7ddf2b7c6b8a1a6f509a95864142b30cab2d3"[[package]]name = "static_file"@@ -10946,7 +11008,7 @@ dependencies = ["strum_macros","thiserror 2.0.17","tokio",- "tower 0.5.3",+ "tower 0.5.2","tower-http","tracing","tracing-tree",@@ -11116,9 +11178,9 @@ dependencies = [[[package]]name = "synstructure"-version = "0.13.2"+version = "0.13.1"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "728a70f3dbaf5bab7f0c4b1ac8d7ae5ea60a4b5549c8a5914361c99147a709d2"+checksum = "c8af7666ab7b6390ab78131fb5b0fce11d6b7a6951602017c35fa82800708971"dependencies = ["proc-macro2","quote",@@ -11188,8 +11250,8 @@ version = "3.19.1"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "7437ac7763b9b123ccf33c338a5cc1bac6f69b45a136c19bdd8a65e3916435bf"dependencies = [- "fastrand 2.4.1",- "getrandom 0.3.4",+ "fastrand 2.3.0",+ "getrandom 0.3.1","once_cell","rustix","windows-sys 0.59.0",@@ -11324,9 +11386,9 @@ dependencies = [[[package]]name = "tinystr"-version = "0.8.3"+version = "0.7.6"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "c8323304221c2a851516f22236c5722a72eaa19749016521d6dff0824447d96d"+checksum = "9117f5d4db391c1cf6927e7bea3db74b9a1c1add8f7eda9ffd5364f40f57b82f"dependencies = ["displaydoc","zerovec",@@ -11349,26 +11411,26 @@ checksum = "1f3ccbac311fea05f86f61904b462b55fb3df8837a366dfc601a0161d0532f20"[[package]]name = "tokio"-version = "1.52.3"+version = "1.50.0"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "8fc7f01b389ac15039e4dc9531aa973a135d7a4135281b12d7c1bc79fd57fffe"+checksum = "27ad5e34374e03cfffefc301becb44e9dc3c17584f414349ebe29ed26661822d"dependencies = ["bytes","libc",- "mio 1.2.0",+ "mio 1.0.3","parking_lot","pin-project-lite","signal-hook-registry",- "socket2 0.6.3",+ "socket2 0.6.1","tokio-macros","windows-sys 0.61.2",][[package]]name = "tokio-macros"-version = "2.7.0"+version = "2.6.0"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "385a6cb71ab9ab790c5fe8d67f1645e6c450a7ce006a33de03daa956cf70a496"+checksum = "af407857209536a95c8e56f8231ef2c2e2aff839b22e07a1ffcbc617e9db9fa5"dependencies = ["proc-macro2","quote",@@ -11391,7 +11453,7 @@ version = "0.26.4"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "1729aa945f29d91ba541258c8df89027d5792d85a8841fb65e8bf0f4ede4ef61"dependencies = [- "rustls 0.23.40",+ "rustls 0.23.36","tokio",]@@ -11440,7 +11502,7 @@ checksum = "d25a406cddcc431a75d3d9afc6a7c0f7428d4891dd973e4d54c56b46127bf857"dependencies = ["futures-util","log",- "rustls 0.23.40",+ "rustls 0.23.36","rustls-pki-types","tokio","tokio-rustls 0.26.4",@@ -11470,10 +11532,10 @@ dependencies = ["async-trait","base64 0.22.1","bytes",- "http 1.4.0",+ "http 1.3.1","http-body 1.0.1","http-body-util",- "hyper 1.9.0",+ "hyper 1.6.0","hyper-timeout","hyper-util","percent-encoding",@@ -11481,7 +11543,7 @@ dependencies = ["sync_wrapper","tokio","tokio-stream",- "tower 0.5.3",+ "tower 0.5.2","tower-layer","tower-service","tracing",@@ -11515,9 +11577,9 @@ dependencies = [[[package]]name = "tower"-version = "0.5.3"+version = "0.5.2"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "ebe5ef63511595f1344e2d5cfa636d973292adc0eec1f0ad45fae9f0851ab1d4"+checksum = "d039ad9159c98b70ecfd540b2573b97f7f52c3e8d9f8ad57a24b916a536975f9"dependencies = ["futures-core","futures-util",@@ -11541,7 +11603,7 @@ dependencies = ["axum-core","cookie","futures-util",- "http 1.4.0",+ "http 1.3.1","parking_lot","pin-project-lite","tower-layer",@@ -11559,7 +11621,7 @@ dependencies = ["bytes","futures-core","futures-util",- "http 1.4.0",+ "http 1.3.1","http-body 1.0.1","http-body-util","http-range-header",@@ -11571,7 +11633,7 @@ dependencies = ["pin-project-lite","tokio","tokio-util",- "tower 0.5.3",+ "tower 0.5.2","tower-layer","tower-service","tracing",@@ -11743,11 +11805,11 @@ checksum = "8628dcc84e5a09eb3d8423d6cb682965dea9133204e8fb3efee74c2a0c259442"dependencies = ["bytes","data-encoding",- "http 1.4.0",+ "http 1.3.1","httparse","log",- "rand 0.9.4",- "rustls 0.23.40",+ "rand 0.9.3",+ "rustls 0.23.36","rustls-pki-types","sha1 0.10.6","thiserror 2.0.17",@@ -11761,14 +11823,14 @@ version = "2.1.2"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "9ea3136b675547379c4bd395ca6b938e5ad3c3d20fad76e7fe85f9e0d011419c"dependencies = [- "rand 0.9.4",+ "rand 0.9.3",][[package]]name = "typenum"-version = "1.20.0"+version = "1.17.0"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "40ce102ab67701b8526c123c1bab5cbe42d7040ccfd0f64af1a385808d2f43de"+checksum = "42ff0bf0c66b8238c6f3b578df37d0b7848e55df8577b3f74f92a69acceeb825"[[package]]name = "unfurl"@@ -11797,7 +11859,7 @@ dependencies = ["axum","bytes","futures",- "http 1.4.0",+ "http 1.3.1","http-body-util","macro_cors","macro_entrypoint",@@ -11807,7 +11869,7 @@ dependencies = ["serde","serde_json","tokio",- "tower 0.5.3",+ "tower 0.5.2","tower-http","tracing","unfurl",@@ -11830,9 +11892,9 @@ checksum = "5c1cb5db39152898a79168971543b1cb5020dff7fe43c8dc468b0885f5e29df5"[[package]]name = "unicode-ident"-version = "1.0.24"+version = "1.0.16"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "e6e4313cd5fcd3dad5cafa179702e2b244f760991f45397d14d4ebf38247da75"+checksum = "a210d160f08b701c8721ba1c726c11662f877ea6b7094007e1ca9a1041945034"[[package]]name = "unicode-normalization"@@ -11879,7 +11941,7 @@ version = "0.5.1"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "fc1de2c688dc15305988b563c3854064043356019f97a4b46276fe734c4f07ea"dependencies = [- "crypto-common 0.1.7",+ "crypto-common 0.1.6","subtle",]@@ -11921,7 +11983,7 @@ dependencies = ["models_bulk_upload","serde","serde_json",- "sha2 0.10.9",+ "sha2 0.10.8","sqs_client","tempfile","tokio",@@ -11954,15 +12016,14 @@ dependencies = [[[package]]name = "url"-version = "2.5.8"+version = "2.5.4"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "ff67a8a4397373c3ef660812acab3268222035010ab8680ec4215f38ba3d0eed"+checksum = "32f8b686cadd1473f4bd0117a5d28d36b1ade384ea9b5069a1c40aefed7fda60"dependencies = ["form_urlencoded","idna","percent-encoding","serde",- "serde_derive",][[package]]@@ -12003,6 +12064,12 @@ version = "0.7.6"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "09cc8ee72d2a9becf2f2febe0205bbed8fc6615b7cb429ad062dc7b7ddd036a9"+[[package]]+name = "utf16_iter"+version = "1.0.5"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "c8232dd3cdaed5356e0f716d285e4b40b932ac434100fe9b7e0e8e935b9e6246"+[[package]]name = "utf16string"version = "0.2.0"@@ -12082,14 +12149,14 @@ checksum = "e2eebbbfe4093922c2b6734d7c679ebfebd704a0d7e56dfcb0d05818ce28977d"[[package]]name = "uuid"-version = "1.23.1"+version = "1.18.1"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "ddd74a9687298c6858e9b88ec8935ec45d22e8fd5e6394fa1bd4e99a87789c76"+checksum = "2f87b8aa10b915a06587d0dec516c282ff295b475d94abf425d62b57710070a2"dependencies = [- "getrandom 0.4.2",+ "getrandom 0.3.1","js-sys",- "rand 0.10.1",- "serde_core",+ "rand 0.9.3",+ "serde","wasm-bindgen",]@@ -12176,17 +12243,26 @@ checksum = "cccddf32554fecc6acb585f82a32a72e28b48f8c4c1883ddfeeeaa96f7d8e519"[[package]]name = "wasi"-version = "0.11.1+wasi-snapshot-preview1"+version = "0.11.0+wasi-snapshot-preview1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "9c8d87e72b64a3b4db28d11ce29237c246188f4f51057d65a7eab63b7987e423"++[[package]]+name = "wasi"+version = "0.13.3+wasi-0.2.2"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "ccf3ec651a847eb01de73ccad15eb7d99f80485de043efb2f370cd654f4ea44b"+checksum = "26816d2e1a4a36a2940b96c5296ce403917633dff8f3440e9b236ed6f6bacad2"+dependencies = [+ "wit-bindgen-rt",+][[package]]name = "wasip2"-version = "1.0.3+wasi-0.2.9"+version = "1.0.2+wasi-0.2.9"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "20064672db26d7cdc89c7798c48a0fdfac8213434a1186e5ef29fd560ae223d6"+checksum = "9517f9239f02c069db75e65f174b3da828fe5f5b945c4dd26bd25d89c03ebcf5"dependencies = [- "wit-bindgen 0.57.1",+ "wit-bindgen",][[package]]@@ -12195,7 +12271,7 @@ version = "0.4.0+wasi-0.3.0-rc-2026-01-06"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "5428f8bf88ea5ddc08faddef2ac4a67e390b88186c703ce6dbd955e1c145aca5"dependencies = [- "wit-bindgen 0.51.0",+ "wit-bindgen",][[package]]@@ -12301,7 +12377,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "47b807c72e1bac69382b3a6fb3dbe8ea4c0ed87ff5629b8685ae6b9a611028fe"dependencies = ["bitflags 2.11.1",- "hashbrown 0.15.5",+ "hashbrown 0.15.2","indexmap 2.14.0","semver",]@@ -12369,14 +12445,14 @@ version = "0.26.11"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "521bc38abb08001b01866da9f51eb7c5d647a19260e00054a8c7fd5f9e57f7a9"dependencies = [- "webpki-roots 1.0.7",+ "webpki-roots 1.0.5",][[package]]name = "webpki-roots"-version = "1.0.7"+version = "1.0.5"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "52f5ee44c96cf55f1b349600768e3ece3a8f26010c05265ab73f945bb1a2eb9d"+checksum = "12bed680863276c63889429bfd6cab3b99943659923822de1c8a39c49e4d722c"dependencies = ["rustls-pki-types",]@@ -12425,7 +12501,7 @@ version = "0.1.9"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "cf221c93e13a30d793f7645a0e7762c55d169dbb0a49671918a2319d289b10bb"dependencies = [- "windows-sys 0.48.0",+ "windows-sys 0.59.0",][[package]]@@ -12514,6 +12590,15 @@ dependencies = ["windows-targets 0.52.6",]+[[package]]+name = "windows-sys"+version = "0.60.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "f2f500e4d28234f72040990ec9d39e3a6b950f9f22d3dba18416c35882612bcb"+dependencies = [+ "windows-targets 0.53.5",+]+[[package]]name = "windows-sys"version = "0.61.2"@@ -12562,13 +12647,30 @@ dependencies = ["windows_aarch64_gnullvm 0.52.6","windows_aarch64_msvc 0.52.6","windows_i686_gnu 0.52.6",- "windows_i686_gnullvm",+ "windows_i686_gnullvm 0.52.6","windows_i686_msvc 0.52.6","windows_x86_64_gnu 0.52.6","windows_x86_64_gnullvm 0.52.6","windows_x86_64_msvc 0.52.6",]+[[package]]+name = "windows-targets"+version = "0.53.5"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "4945f9f551b88e0d65f3db0bc25c33b8acea4d9e41163edf90dcd0b19f9069f3"+dependencies = [+ "windows-link",+ "windows_aarch64_gnullvm 0.53.1",+ "windows_aarch64_msvc 0.53.1",+ "windows_i686_gnu 0.53.1",+ "windows_i686_gnullvm 0.53.1",+ "windows_i686_msvc 0.53.1",+ "windows_x86_64_gnu 0.53.1",+ "windows_x86_64_gnullvm 0.53.1",+ "windows_x86_64_msvc 0.53.1",+]+[[package]]name = "windows_aarch64_gnullvm"version = "0.42.2"@@ -12587,6 +12689,12 @@ version = "0.52.6"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "32a4622180e7a0ec044bb555404c800bc9fd9ec262ec147edd5989ccd0c02cd3"+[[package]]+name = "windows_aarch64_gnullvm"+version = "0.53.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "a9d8416fa8b42f5c947f8482c43e7d89e73a173cead56d044f6a56104a6d1b53"+[[package]]name = "windows_aarch64_msvc"version = "0.42.2"@@ -12605,6 +12713,12 @@ version = "0.52.6"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "09ec2a7bb152e2252b53fa7803150007879548bc709c039df7627cabbd05d469"+[[package]]+name = "windows_aarch64_msvc"+version = "0.53.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "b9d782e804c2f632e395708e99a94275910eb9100b2114651e04744e9b125006"+[[package]]name = "windows_i686_gnu"version = "0.42.2"@@ -12623,12 +12737,24 @@ version = "0.52.6"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "8e9b5ad5ab802e97eb8e295ac6720e509ee4c243f69d781394014ebfe8bbfa0b"+[[package]]+name = "windows_i686_gnu"+version = "0.53.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "960e6da069d81e09becb0ca57a65220ddff016ff2d6af6a223cf372a506593a3"+[[package]]name = "windows_i686_gnullvm"version = "0.52.6"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "0eee52d38c090b3caa76c563b86c3a4bd71ef1a819287c19d586d7334ae8ed66"+[[package]]+name = "windows_i686_gnullvm"+version = "0.53.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "fa7359d10048f68ab8b09fa71c3daccfb0e9b559aed648a8f95469c27057180c"+[[package]]name = "windows_i686_msvc"version = "0.42.2"@@ -12647,6 +12773,12 @@ version = "0.52.6"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "240948bc05c5e7c6dabba28bf89d89ffce3e303022809e73deaefe4f6ec56c66"+[[package]]+name = "windows_i686_msvc"+version = "0.53.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "1e7ac75179f18232fe9c285163565a57ef8d3c89254a30685b57d83a38d326c2"+[[package]]name = "windows_x86_64_gnu"version = "0.42.2"@@ -12665,6 +12797,12 @@ version = "0.52.6"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "147a5c80aabfbf0c7d901cb5895d1de30ef2907eb21fbbab29ca94c5b08b1a78"+[[package]]+name = "windows_x86_64_gnu"+version = "0.53.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "9c3842cdd74a865a8066ab39c8a7a473c0778a3f29370b5fd6b4b9aa7df4a499"+[[package]]name = "windows_x86_64_gnullvm"version = "0.42.2"@@ -12683,6 +12821,12 @@ version = "0.52.6"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "24d5b23dc417412679681396f2b49f3de8c1473deb516bd34410872eff51ed0d"+[[package]]+name = "windows_x86_64_gnullvm"+version = "0.53.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "0ffa179e2d07eee8ad8f57493436566c7cc30ac536a3379fdf008f47f6bb7ae1"+[[package]]name = "windows_x86_64_msvc"version = "0.42.2"@@ -12701,6 +12845,12 @@ version = "0.52.6"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "589f6da84c646204747d1270a2a5661ea66ed1cced2631d546fdfb155959f9ec"+[[package]]+name = "windows_x86_64_msvc"+version = "0.53.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "d6bbff5f0aada427a1e5a6da5f1f98158182f26556f345ac9e04d36d0ebed650"+[[package]]name = "winnow"version = "0.7.14"@@ -12719,12 +12869,6 @@ dependencies = ["wit-bindgen-rust-macro",]-[[package]]-name = "wit-bindgen"-version = "0.57.1"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "1ebf944e87a7c253233ad6766e082e3cd714b5d03812acc24c318f549614536e"-[[package]]name = "wit-bindgen-core"version = "0.51.0"@@ -12736,6 +12880,15 @@ dependencies = ["wit-parser",]+[[package]]+name = "wit-bindgen-rt"+version = "0.33.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "3268f3d866458b787f390cf61f4bbb563b922d091359f9608842999eaee3943c"+dependencies = [+ "bitflags 2.11.1",+]+[[package]]name = "wit-bindgen-rust"version = "0.51.0"@@ -12821,11 +12974,17 @@ dependencies = ["tracing",]+[[package]]+name = "write16"+version = "1.0.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "d1890f4022759daae28ed4fe62859b1236caebfc61ede2f63ed4e695f3f6d936"+[[package]]name = "writeable"-version = "0.6.3"+version = "0.5.5"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "1ffae5123b2d3fc086436f8834ae3ab053a283cfac8fe0a0b8eaae044768a4c4"+checksum = "1e9df38ee2d2c3c5948ea468a8406ff0db0b29ae1ffde1bcf20ef305bcc95c51"[[package]]name = "xmlparser"@@ -12856,10 +13015,11 @@ checksum = "7a5a4b21e1a62b67a2970e6831bc091d7b87e119e7f9791aef9702e3bef04448"[[package]]name = "yoke"-version = "0.8.2"+version = "0.7.5"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "abe8c5fda708d9ca3df187cae8bfb9ceda00dd96231bed36e445a1a48e66f9ca"+checksum = "120e6aef9aa629e3d4f52dc8cc43a015c7724194c97dfaf45180d2daf2b77f40"dependencies = [+ "serde","stable_deref_trait","yoke-derive","zerofrom",@@ -12867,9 +13027,9 @@ dependencies = [[[package]]name = "yoke-derive"-version = "0.8.2"+version = "0.7.5"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "de844c262c8848816172cef550288e7dc6c7b7814b4ee56b3e1553f275f1858e"+checksum = "2380878cad4ac9aac1e2435f3eb4020e8374b5f13c296cb75b4620ff8e229154"dependencies = ["proc-macro2","quote",@@ -12883,16 +13043,17 @@ version = "0.7.35"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "1b9b4fd18abc82b8136838da5d50bae7bdea537c574d8dc1a34ed098d6c166f0"dependencies = [+ "byteorder","zerocopy-derive 0.7.35",][[package]]name = "zerocopy"-version = "0.8.48"+version = "0.8.17"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "eed437bf9d6692032087e337407a86f04cd8d6a16a37199ed57949d415bd68e9"+checksum = "aa91407dacce3a68c56de03abe2760159582b846c6a4acd2f456618087f12713"dependencies = [- "zerocopy-derive 0.8.48",+ "zerocopy-derive 0.8.17",][[package]]@@ -12908,9 +13069,9 @@ dependencies = [[[package]]name = "zerocopy-derive"-version = "0.8.48"+version = "0.8.17"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "70e3cd084b1788766f53af483dd21f93881ff30d7320490ec3ef7526d203bad4"+checksum = "06718a168365cad3d5ff0bb133aad346959a2074bd4a85c121255a11304a8626"dependencies = ["proc-macro2","quote",@@ -12919,18 +13080,18 @@ dependencies = [[[package]]name = "zerofrom"-version = "0.1.8"+version = "0.1.5"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "0ec05a11813ea801ff6d75110ad09cd0824ddba17dfe17128ea0d5f68e6c5272"+checksum = "cff3ee08c995dee1859d998dea82f7374f2826091dd9cd47def953cae446cd2e"dependencies = ["zerofrom-derive",][[package]]name = "zerofrom-derive"-version = "0.1.7"+version = "0.1.5"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "11532158c46691caf0f2593ea8358fed6bbf68a0315e80aae9bd41fbade684a1"+checksum = "595eed982f7d355beb85837f651fa22e90b3c044842dc7f2c2842c086f295808"dependencies = ["proc-macro2","quote",@@ -12940,40 +13101,29 @@ dependencies = [[[package]]name = "zeroize"-version = "1.8.2"+version = "1.8.1"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "b97154e67e32c85465826e8bcc1c59429aaaf107c1e4a9e53c8d8ccd5eff88d0"+checksum = "ced3678a2879b30306d323f4542626697a464a97c0a07c9aebf7ebca65cd4dde"dependencies = ["zeroize_derive",][[package]]name = "zeroize_derive"-version = "1.4.3"+version = "1.4.2"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "85a5b4158499876c763cb03bc4e49185d3cccbabb15b33c627f7884f43db852e"+checksum = "ce36e65b0d2999d2aafac989fb249189a141aee1f53c612c1f37d72631959f69"dependencies = ["proc-macro2","quote","syn 2.0.117",]-[[package]]-name = "zerotrie"-version = "0.2.4"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "0f9152d31db0792fa83f70fb2f83148effb5c1f5b8c7686c3459e361d9bc20bf"-dependencies = [- "displaydoc",- "yoke",- "zerofrom",-]-[[package]]name = "zerovec"-version = "0.11.6"+version = "0.10.4"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "90f911cbc359ab6af17377d242225f4d75119aec87ea711a880987b18cd7b239"+checksum = "aa2b893d79df23bfb12d5461018d408ea19dfafe76c2c7ef6d4eba614f8ff079"dependencies = ["yoke","zerofrom",@@ -12982,9 +13132,9 @@ dependencies = [[[package]]name = "zerovec-derive"-version = "0.11.3"+version = "0.10.3"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "625dc425cab0dca6dc3c3319506e6593dcb08a9f387ea3b284dbd52a92c40555"+checksum = "6eafa6dfb17584ea3e2bd6e76e0cc15ad7af12b09abdd1ca55961bed9b1063c6"dependencies = ["proc-macro2","quote",@@ -13006,7 +13156,7 @@ dependencies = ["deflate64","displaydoc","flate2",- "getrandom 0.3.4",+ "getrandom 0.3.1","hmac 0.12.1","indexmap 2.14.0","lzma-rs",diff --git a/rust/cloud-storage/Cargo.toml b/rust/cloud-storage/Cargo.tomlindex 868d9e485f..daeec3cc24 100644--- a/rust/cloud-storage/Cargo.toml+++ b/rust/cloud-storage/Cargo.toml@@ -8,6 +8,8 @@ members = ["connection_gateway","contacts_service","convert_service",+ "cowlike",+ "crm","dataloss_prevention_handler","delete_chat_handler","deleted_item_poller",diff --git a/rust/cloud-storage/ai_tools/Cargo.toml b/rust/cloud-storage/ai_tools/Cargo.tomlindex e5809156c2..1838f503bd 100644--- a/rust/cloud-storage/ai_tools/Cargo.toml+++ b/rust/cloud-storage/ai_tools/Cargo.toml@@ -26,6 +26,7 @@ comms = { path = "../comms", features = ["outbound"] }connection = { path = "../connection", default-features = false, features = ["ports",] }+crm = { path = "../crm" }documents = { path = "../documents", features = ["ai_tools"] }email = { path = "../email", features = ["ai_schema", "ai_tools", "axum", "outbound"] }email_service_client = { path = "../email_service_client" }diff --git a/rust/cloud-storage/ai_tools/src/build_context.rs b/rust/cloud-storage/ai_tools/src/build_context.rsindex 762f9d1b0e..b754f79f40 100644--- a/rust/cloud-storage/ai_tools/src/build_context.rs+++ b/rust/cloud-storage/ai_tools/src/build_context.rs@@ -148,10 +148,14 @@ pub async fn build_tool_service_context_from_env(let frecency_storage = FrecencyPgStorage::new(pool.clone());let frecency_service = FrecencyQueryServiceImpl::new(frecency_storage.clone());+ let crm_service = crm::domain::service::CrmServiceImpl::new(+ crm::outbound::companies_repo::CompaniesRepositoryImpl::new(pool.clone()),+ );let email_service = EmailServiceImpl::new(EmailPgRepo::new(pool.clone()),frecency_service.clone(),email::domain::ports::NoOpEnqueuer,+ crm_service.clone(),0,);let channels_service = ChannelServiceImpl::new(@@ -225,6 +229,7 @@ pub async fn build_tool_service_context_from_env(EmailPgRepo::new(pool.clone()),FrecencyQueryServiceImpl::new(FrecencyPgStorage::new(pool.clone())),sqs_client,+ crm_service.clone(),0,)),Arc::new(email::domain::ports::NoOpGmailTokenProvider),diff --git a/rust/cloud-storage/ai_tools/src/tool_context.rs b/rust/cloud-storage/ai_tools/src/tool_context.rsindex fc599c6b91..ce6fb066a9 100644--- a/rust/cloud-storage/ai_tools/src/tool_context.rs+++ b/rust/cloud-storage/ai_tools/src/tool_context.rs@@ -30,12 +30,21 @@ pub type ToolFrecencyService = frecency::domain::services::FrecencyQueryServiceIfrecency::outbound::postgres::FrecencyPgStorage,>;+/// Type alias for the CRM service implementation used by tools.+pub type ToolCrmService =+ crm::domain::service::CrmServiceImpl<crm::outbound::companies_repo::CompaniesRepositoryImpl>;+/// Type alias for the email service implementation-pub type ToolEmailService =- EmailServiceImpl<EmailPgRepo, ToolFrecencyService, email::domain::ports::NoOpEnqueuer>;+pub type ToolEmailService = EmailServiceImpl<+ EmailPgRepo,+ ToolFrecencyService,+ email::domain::ports::NoOpEnqueuer,+ ToolCrmService,+>;/// Type alias for the send-capable email service implementation used by user tools.-pub type ToolUserEmailService = EmailServiceImpl<EmailPgRepo, ToolFrecencyService, sqs_client::SQS>;+pub type ToolUserEmailService =+ EmailServiceImpl<EmailPgRepo, ToolFrecencyService, sqs_client::SQS, ToolCrmService>;/// Type alias for the comms/channels service implementationpub type ToolCommsService = comms::domain::service::ChannelServiceImpl<diff --git a/rust/cloud-storage/crm/Cargo.toml b/rust/cloud-storage/crm/Cargo.tomlnew file mode 100644index 0000000000..2f1b93c79e--- /dev/null+++ b/rust/cloud-storage/crm/Cargo.toml@@ -0,0 +1,25 @@+[package]+edition = "2024"+name = "crm"+publish = false+version = "0.1.0"++[features]+default = ["outbound", "ports"]+outbound = ["dep:sqlx", "ports"]+ports = []++[dependencies]+anyhow = { workspace = true }+chrono = { workspace = true }+serde = { workspace = true }+thiserror = { workspace = true }+tracing = { workspace = true }+uuid = { workspace = true }++# Outbound dependencies+sqlx = { workspace = true, optional = true }++[dev-dependencies]+macro_db_migrator = { path = "../macro_db_migrator" }+tokio = { workspace = true, features = ["macros"] }diff --git a/rust/cloud-storage/crm/src/domain.rs b/rust/cloud-storage/crm/src/domain.rsnew file mode 100644index 0000000000..797d9aba6c--- /dev/null+++ b/rust/cloud-storage/crm/src/domain.rs@@ -0,0 +1,9 @@+/// Domain models for CRM records+pub mod model;++/// Persistence port for CRM companies+#[cfg(feature = "ports")]+pub mod companies_repo;+/// The CRM service trait and implementation+#[cfg(feature = "ports")]+pub mod service;diff --git a/rust/cloud-storage/crm/src/domain/companies_repo.rs b/rust/cloud-storage/crm/src/domain/companies_repo.rsnew file mode 100644index 0000000000..b751f50351--- /dev/null+++ b/rust/cloud-storage/crm/src/domain/companies_repo.rs@@ -0,0 +1,17 @@+//! Port for persistence operations on CRM companies.++use crate::domain::model::{CrmCompany, CrmError};++/// The CompaniesRepository defines persistence operations for CRM+/// companies and their associated domains.+pub trait CompaniesRepository: Clone + Send + Sync + 'static {+ /// Fetches the company for the given team that has `domain` registered+ /// against it, hydrated with the full list of domains belonging to that+ /// company. Returns `Ok(None)` when no company in the team has the+ /// domain registered. Domain matching is case-insensitive.+ fn get_company_by_domain(+ &self,+ team_id: &uuid::Uuid,+ domain: &str,+ ) -> impl Future<Output = Result<Option<CrmCompany>, CrmError>> + Send;+}diff --git a/rust/cloud-storage/crm/src/domain/model.rs b/rust/cloud-storage/crm/src/domain/model.rsnew file mode 100644index 0000000000..1e4dd614a9--- /dev/null+++ b/rust/cloud-storage/crm/src/domain/model.rs@@ -0,0 +1,44 @@+//! Domain models for CRM companies and their related records.++use chrono::{DateTime, Utc};++/// A known external company tracked by a team (CRM-style record). A company+/// aggregates one or more email domains and individual contacts that are+/// considered to belong to the same external party.+#[derive(Debug, Clone, serde::Serialize)]+pub struct CrmCompany {+ /// The id of the company+ pub id: uuid::Uuid,+ /// The id of the team that owns this company record+ pub team_id: uuid::Uuid,+ /// The display name of the company+ pub name: String,+ /// Whether email sync is enabled for this company+ pub email_sync: bool,+ /// When the company was created+ pub created_at: DateTime<Utc>,+ /// All domains associated with this company+ pub domains: Vec<CrmDomain>,+}++/// A domain (e.g. "acme.com") associated with a [`CrmCompany`]. A company+/// may have many domains.+#[derive(Debug, Clone, serde::Serialize)]+pub struct CrmDomain {+ /// The id of the domain record+ pub id: uuid::Uuid,+ /// The id of the company the domain belongs to+ pub company_id: uuid::Uuid,+ /// The domain (e.g. "acme.com"). Stored lowercased.+ pub domain: String,+ /// When the domain record was created+ pub created_at: DateTime<Utc>,+}++/// Errors that can occur in the CRM domain.+#[derive(Debug, thiserror::Error)]+pub enum CrmError {+ /// Storage layer error+ #[error("Storage layer error {0}")]+ StorageLayerError(#[from] anyhow::Error),+}diff --git a/rust/cloud-storage/crm/src/domain/service.rs b/rust/cloud-storage/crm/src/domain/service.rsnew file mode 100644index 0000000000..6682c27bec--- /dev/null+++ b/rust/cloud-storage/crm/src/domain/service.rs@@ -0,0 +1,68 @@+//! The CrmService trait and its default implementation.++use crate::domain::{+ companies_repo::CompaniesRepository,+ model::{CrmCompany, CrmError},+};++/// The CrmService exposes operations over CRM records (companies, their+/// domains and contacts).+pub trait CrmService: Clone + Send + Sync + 'static {+ /// Fetches the company for the given team that has `domain` registered+ /// against it, hydrated with all of the company's domains. Returns+ /// `Ok(None)` when no company in the team has that domain.+ fn get_company_by_domain(+ &self,+ team_id: &uuid::Uuid,+ domain: &str,+ ) -> impl Future<Output = Result<Option<CrmCompany>, CrmError>> + Send;+}++/// Implementation of [`CrmService`] backed by a [`CompaniesRepository`].+#[derive(Debug)]+pub struct CrmServiceImpl<CR>+where+ CR: CompaniesRepository,+{+ /// The underlying companies repository+ companies_repository: CR,+}++impl<CR> Clone for CrmServiceImpl<CR>+where+ CR: CompaniesRepository,+{+ fn clone(&self) -> Self {+ Self {+ companies_repository: self.companies_repository.clone(),+ }+ }+}++impl<CR> CrmServiceImpl<CR>+where+ CR: CompaniesRepository,+{+ /// Creates a new CrmServiceImpl+ pub fn new(companies_repository: CR) -> Self {+ Self {+ companies_repository,+ }+ }+}++impl<CR> CrmService for CrmServiceImpl<CR>+where+ CR: CompaniesRepository,+{+ #[tracing::instrument(skip(self), err)]+ async fn get_company_by_domain(+ &self,+ team_id: &uuid::Uuid,+ domain: &str,+ ) -> Result<Option<CrmCompany>, CrmError> {+ self.companies_repository+ .get_company_by_domain(team_id, domain)+ .await+ }+}diff --git a/rust/cloud-storage/crm/src/lib.rs b/rust/cloud-storage/crm/src/lib.rsnew file mode 100644index 0000000000..cf6833fa03--- /dev/null+++ b/rust/cloud-storage/crm/src/lib.rs@@ -0,0 +1,17 @@+#![deny(missing_docs)]+//! CRM hexagonal architecture crate.+//!+//! Encapsulates CRM-style records (external organizations, their domains and+//! contacts) tracked by a team, using a ports-and-adapters pattern.+//!+//! # Architecture+//!+//! - **domain**: Contains domain models, ports (traits), and the service implementation+//! - **outbound**: Contains adapters for external dependencies (PostgreSQL)++/// The domain module contains the domain logic for CRM+pub mod domain;++/// The outbound module contains the outbound adapters for CRM+#[cfg(feature = "outbound")]+pub mod outbound;diff --git a/rust/cloud-storage/crm/src/outbound.rs b/rust/cloud-storage/crm/src/outbound.rsnew file mode 100644index 0000000000..c1e03765d7--- /dev/null+++ b/rust/cloud-storage/crm/src/outbound.rs@@ -0,0 +1,2 @@+/// Postgres implementation of the companies repository+pub mod companies_repo;diff --git a/rust/cloud-storage/crm/src/outbound/companies_repo.rs b/rust/cloud-storage/crm/src/outbound/companies_repo.rsnew file mode 100644index 0000000000..51cfa60704--- /dev/null+++ b/rust/cloud-storage/crm/src/outbound/companies_repo.rs@@ -0,0 +1,85 @@+//! Implementation of [`CompaniesRepository`] backed by MacroDB.++#[cfg(test)]+mod test;++use crate::domain::{+ companies_repo::CompaniesRepository,+ model::{CrmCompany, CrmDomain, CrmError},+};+use sqlx::PgPool;++/// PostgreSQL-backed [`CompaniesRepository`].+#[derive(Clone)]+pub struct CompaniesRepositoryImpl {+ /// The underlying sqlx::PgPool connected to macrodb.+ pool: PgPool,+}++impl CompaniesRepositoryImpl {+ /// Creates a new instance of CompaniesRepositoryImpl+ pub fn new(pool: PgPool) -> Self {+ Self { pool }+ }+}++impl CompaniesRepository for CompaniesRepositoryImpl {+ #[tracing::instrument(skip(self), err)]+ async fn get_company_by_domain(+ &self,+ team_id: &uuid::Uuid,+ domain: &str,+ ) -> Result<Option<CrmCompany>, CrmError> {+ let normalized_domain = domain.to_ascii_lowercase();++ let company = sqlx::query!(+ r#"+ SELECT c.id, c.team_id, c.name, c.email_sync, c.created_at+ FROM crm_companies c+ JOIN crm_domains d ON d.company_id = c.id+ WHERE c.team_id = $1+ AND LOWER(d.domain) = $2+ LIMIT 1+ "#,+ team_id,+ normalized_domain,+ )+ .fetch_optional(&self.pool)+ .await+ .map_err(|e| CrmError::StorageLayerError(e.into()))?;++ let Some(company) = company else {+ return Ok(None);+ };++ let domains = sqlx::query!(+ r#"+ SELECT id, company_id, domain, created_at+ FROM crm_domains+ WHERE company_id = $1+ ORDER BY created_at ASC+ "#,+ company.id,+ )+ .fetch_all(&self.pool)+ .await+ .map_err(|e| CrmError::StorageLayerError(e.into()))?+ .into_iter()+ .map(|row| CrmDomain {+ id: row.id,+ company_id: row.company_id,+ domain: row.domain,+ created_at: row.created_at,+ })+ .collect();++ Ok(Some(CrmCompany {+ id: company.id,+ team_id: company.team_id,+ name: company.name,+ email_sync: company.email_sync,+ created_at: company.created_at,+ domains,+ }))+ }+}diff --git a/rust/cloud-storage/crm/src/outbound/companies_repo/test.rs b/rust/cloud-storage/crm/src/outbound/companies_repo/test.rsnew file mode 100644index 0000000000..cd1045f94f--- /dev/null+++ b/rust/cloud-storage/crm/src/outbound/companies_repo/test.rs@@ -0,0 +1,151 @@+use super::*;+use macro_db_migrator::MACRO_DB_MIGRATIONS;+use sqlx::PgPool;+use uuid::Uuid;++async fn seed_team(pool: &PgPool, team_id: Uuid, owner_id: &str) -> sqlx::Result<()> {+ let macro_user_id = Uuid::now_v7();++ sqlx::query(+ r#"INSERT INTO macro_user (id, username, email, stripe_customer_id) VALUES ($1, $2, $3, $4)"#,+ )+ .bind(macro_user_id)+ .bind(owner_id)+ .bind(format!("{owner_id}@test.com"))+ .bind(format!("stripe_{macro_user_id}"))+ .execute(pool)+ .await?;++ sqlx::query(r#"INSERT INTO "User" (id, email, macro_user_id) VALUES ($1, $2, $3)"#)+ .bind(owner_id)+ .bind(format!("{owner_id}@test.com"))+ .bind(macro_user_id)+ .execute(pool)+ .await?;++ sqlx::query(r#"INSERT INTO team (id, name, owner_id) VALUES ($1, $2, $3)"#)+ .bind(team_id)+ .bind("test team")+ .bind(owner_id)+ .execute(pool)+ .await?;++ Ok(())+}++async fn insert_company(+ pool: &PgPool,+ team_id: Uuid,+ name: &str,+ email_sync: bool,+ domains: &[&str],+) -> sqlx::Result<Uuid> {+ let company_id = Uuid::now_v7();++ sqlx::query(+ r#"INSERT INTO crm_companies (id, team_id, name, email_sync) VALUES ($1, $2, $3, $4)"#,+ )+ .bind(company_id)+ .bind(team_id)+ .bind(name)+ .bind(email_sync)+ .execute(pool)+ .await?;++ for domain in domains {+ sqlx::query(r#"INSERT INTO crm_domains (company_id, domain) VALUES ($1, $2)"#)+ .bind(company_id)+ .bind(*domain)+ .execute(pool)+ .await?;+ }++ Ok(company_id)+}++#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]+async fn returns_none_when_no_company_for_domain(pool: PgPool) -> anyhow::Result<()> {+ let team_id = Uuid::now_v7();+ seed_team(&pool, team_id, "macro|[email protected]").await?;++ let repo = CompaniesRepositoryImpl::new(pool);+ let result = repo.get_company_by_domain(&team_id, "missing.com").await?;++ assert!(result.is_none());+ Ok(())+}++#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]+async fn returns_company_with_all_domains_when_match(pool: PgPool) -> anyhow::Result<()> {+ let team_id = Uuid::now_v7();+ seed_team(&pool, team_id, "macro|[email protected]").await?;+ let company_id = insert_company(&pool, team_id, "Acme", true, &["acme.com", "acme.io"]).await?;++ let repo = CompaniesRepositoryImpl::new(pool);+ let company = repo+ .get_company_by_domain(&team_id, "acme.com")+ .await?+ .expect("company should be returned");++ assert_eq!(company.id, company_id);+ assert_eq!(company.team_id, team_id);+ assert_eq!(company.name, "Acme");+ assert!(company.email_sync);++ let mut domains: Vec<_> = company.domains.iter().map(|d| d.domain.as_str()).collect();+ domains.sort();+ assert_eq!(domains, vec!["acme.com", "acme.io"]);+ Ok(())+}++#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]+async fn domain_lookup_is_case_insensitive(pool: PgPool) -> anyhow::Result<()> {+ let team_id = Uuid::now_v7();+ seed_team(&pool, team_id, "macro|[email protected]").await?;+ insert_company(&pool, team_id, "Acme", true, &["acme.com"]).await?;++ let repo = CompaniesRepositoryImpl::new(pool);++ assert!(+ repo.get_company_by_domain(&team_id, "ACME.COM")+ .await?+ .is_some()+ );+ assert!(+ repo.get_company_by_domain(&team_id, "Acme.Com")+ .await?+ .is_some()+ );+ Ok(())+}++#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]+async fn does_not_return_companies_from_other_teams(pool: PgPool) -> anyhow::Result<()> {+ let team_a = Uuid::now_v7();+ let team_b = Uuid::now_v7();+ seed_team(&pool, team_a, "macro|[email protected]").await?;+ seed_team(&pool, team_b, "macro|[email protected]").await?;+ insert_company(&pool, team_a, "Acme A", true, &["acme.com"]).await?;++ let repo = CompaniesRepositoryImpl::new(pool);+ let result = repo.get_company_by_domain(&team_b, "acme.com").await?;++ assert!(result.is_none());+ Ok(())+}++#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]+async fn returns_company_when_email_sync_is_false(pool: PgPool) -> anyhow::Result<()> {+ let team_id = Uuid::now_v7();+ seed_team(&pool, team_id, "macro|[email protected]").await?;+ insert_company(&pool, team_id, "Acme", false, &["acme.com"]).await?;++ let repo = CompaniesRepositoryImpl::new(pool);+ let company = repo+ .get_company_by_domain(&team_id, "acme.com")+ .await?+ .expect("company should be returned");++ assert!(!company.email_sync);+ Ok(())+}diff --git a/rust/cloud-storage/document_cognition_service/Cargo.toml b/rust/cloud-storage/document_cognition_service/Cargo.tomlindex 878d80702a..a202ad5205 100644--- a/rust/cloud-storage/document_cognition_service/Cargo.toml+++ b/rust/cloud-storage/document_cognition_service/Cargo.toml@@ -46,6 +46,7 @@ comms = { path = "../comms", features = ["outbound", "attachment"] }comms_service_client = { path = "../comms_service_client" }connection_gateway = { path = "../connection_gateway" }cookie = { workspace = true }+crm = { path = "../crm" }document_storage_service_client = { path = "../document_storage_service_client" }documents = { path = "../documents", features = ["ai_tools", "attachment"] }doppleganger = { 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 35c619ed21..e84d7367df 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@@ -159,10 +159,14 @@ pub async fn test_api_context(pool: sqlx::Pool<sqlx::Postgres>) -> std::sync::Ar// Build soup service dependencieslet frecency_storage = FrecencyPgStorage::new(pool.clone());let frecency_service = FrecencyQueryServiceImpl::new(frecency_storage.clone());+ let crm_service = crm::domain::service::CrmServiceImpl::new(+ crm::outbound::companies_repo::CompaniesRepositoryImpl::new(pool.clone()),+ );let email_service = EmailServiceImpl::new(EmailPgRepo::new(pool.clone()),frecency_service.clone(),email::domain::ports::NoOpEnqueuer,+ crm_service.clone(),0,);let user_repo = PgUserRepo::new(pool.clone());@@ -269,6 +273,7 @@ pub async fn test_api_context(pool: sqlx::Pool<sqlx::Postgres>) -> std::sync::Arfrecency::outbound::postgres::FrecencyPgStorage::new(pool.clone()),),sqs_client.clone(),+ crm_service.clone(),0,)),Arc::new(email::domain::ports::NoOpGmailTokenProvider),diff --git a/rust/cloud-storage/document_cognition_service/src/main.rs b/rust/cloud-storage/document_cognition_service/src/main.rsindex 8815b7b039..669758db35 100644--- a/rust/cloud-storage/document_cognition_service/src/main.rs+++ b/rust/cloud-storage/document_cognition_service/src/main.rs@@ -203,10 +203,14 @@ async fn main() -> anyhow::Result<()> {let frecency_storage = FrecencyPgStorage::new(db.clone());let frecency_service = FrecencyQueryServiceImpl::new(frecency_storage.clone());+ let crm_service = crm::domain::service::CrmServiceImpl::new(+ crm::outbound::companies_repo::CompaniesRepositoryImpl::new(db.clone()),+ );let email_service = EmailServiceImpl::new(EmailPgRepo::new(db.clone()),frecency_service.clone(),email::domain::ports::NoOpEnqueuer,+ crm_service.clone(),0,);let channels_service = ChannelServiceImpl::new(@@ -321,6 +325,7 @@ async fn main() -> anyhow::Result<()> {EmailPgRepo::new(db.clone()),FrecencyQueryServiceImpl::new(FrecencyPgStorage::new(db.clone())),sqs_client.clone(),+ crm_service.clone(),0,)),Arc::new(email::domain::ports::NoOpGmailTokenProvider),diff --git a/rust/cloud-storage/document_storage_service/Cargo.toml b/rust/cloud-storage/document_storage_service/Cargo.tomlindex 8516fd6f9b..72cb9a0841 100644--- a/rust/cloud-storage/document_storage_service/Cargo.toml+++ b/rust/cloud-storage/document_storage_service/Cargo.toml@@ -49,6 +49,7 @@ connection = { path = "../connection", default-features = false, features = [] }connection_gateway_client = { path = "../connection_gateway_client" }cowlike = { path = "../cowlike" }+crm = { path = "../crm" }document_sub_type = { path = "../document_sub_type" }documents_hex = { path = "../documents", package = "documents" }dynamodb_client = { path = "../dynamodb_client" }diff --git a/rust/cloud-storage/document_storage_service/src/api/context.rs b/rust/cloud-storage/document_storage_service/src/api/context.rsindex 5cbb10e4dc..582870beee 100644--- a/rust/cloud-storage/document_storage_service/src/api/context.rs+++ b/rust/cloud-storage/document_storage_service/src/api/context.rs@@ -76,6 +76,7 @@ type DssEmailService = EmailServiceImpl<EmailPgRepo,FrecencyQueryServiceImpl<FrecencyPgStorage>,email::domain::ports::NoOpEnqueuer,+ crm::domain::service::CrmServiceImpl<crm::outbound::companies_repo::CompaniesRepositoryImpl>,>;type DssSoupState = SoupRouterState<@@ -87,6 +88,7 @@ type DssSoupState = SoupRouterState<call::domain::service::CallRecordQueryServiceImpl<call::outbound::pg_call_repo::PgCallRepo>,>,DssEmailService,+ EntityAccessService,>;type SystemPropertiesService = SystemPropertiesServiceImpl<PgSystemPropertiesRepository>;diff --git a/rust/cloud-storage/document_storage_service/src/main.rs b/rust/cloud-storage/document_storage_service/src/main.rsindex ff60afb61d..c14f55beb6 100644--- a/rust/cloud-storage/document_storage_service/src/main.rs+++ b/rust/cloud-storage/document_storage_service/src/main.rs@@ -247,16 +247,21 @@ async fn main() -> anyhow::Result<()> {let frecency_storage = FrecencyPgStorage::new(db.clone());let frecency_service = FrecencyQueryServiceImpl::new(frecency_storage.clone());+ let crm_service = crm::domain::service::CrmServiceImpl::new(+ crm::outbound::companies_repo::CompaniesRepositoryImpl::new(db.clone()),+ );let email_service = EmailServiceImpl::new(EmailPgRepo::new(db.clone()),frecency_service.clone(),email::domain::ports::NoOpEnqueuer,+ crm_service.clone(),0,);let readonly_email_service = ReadonlyEmailPreviewAdapter(EmailServiceImpl::new(EmailPgRepo::new(readonly_db.clone()),frecency_service.clone(),email::domain::ports::NoOpEnqueuer,+ crm_service.clone(),0,));let system_properties_service =@@ -542,6 +547,7 @@ async fn main() -> anyhow::Result<()> {call_record_query_service,),email_service,+ entity_access_service.clone(),),github_sync_service: Arc::new(github_sync_service_impl),db: db.clone(),diff --git a/rust/cloud-storage/email/Cargo.toml b/rust/cloud-storage/email/Cargo.tomlindex 8b703ae845..c9525bbe6b 100644--- a/rust/cloud-storage/email/Cargo.toml+++ b/rust/cloud-storage/email/Cargo.toml@@ -36,7 +36,7 @@ axum = [gmail_token = ["dep:authentication_service_client", "dep:redis", "ports"]inbound = ["ports"]outbound = ["dep:sqlx", "ports"]-ports = ["dep:tokio", "frecency/ports"]+ports = ["crm/ports", "dep:tokio", "frecency/ports"][dependencies]ai = { path = "../ai", optional = true }@@ -49,6 +49,7 @@ futures = { workspace = true }axum = { workspace = true, optional = true }axum-extra = { workspace = true, optional = true }chrono = { workspace = true, features = ["serde"] }+crm = { path = "../crm", default-features = false }doppleganger = { workspace = true, features = ["chrono", "uuid"] }either = { workspace = true }email_utils = { path = "../email_utils" }diff --git a/rust/cloud-storage/email/examples/ai_tools_cli.rs b/rust/cloud-storage/email/examples/ai_tools_cli.rsindex 68863823a5..a47300fb06 100644--- a/rust/cloud-storage/email/examples/ai_tools_cli.rs+++ b/rust/cloud-storage/email/examples/ai_tools_cli.rs@@ -77,11 +77,15 @@ async fn main() {),);- let email_repo = EmailPgRepo::new(pool);+ let email_repo = EmailPgRepo::new(pool.clone());+ let crm_service = crm::domain::service::CrmServiceImpl::new(+ crm::outbound::companies_repo::CompaniesRepositoryImpl::new(pool),+ );let email_service = EmailServiceImpl::new(email_repo,frecency_service,email::domain::ports::NoOpEnqueuer,+ crm_service,0,);diff --git a/rust/cloud-storage/email/fixtures/email_dynamic_query_team_scope.sql b/rust/cloud-storage/email/fixtures/email_dynamic_query_team_scope.sqlnew file mode 100644index 0000000000..adbe03107a--- /dev/null+++ b/rust/cloud-storage/email/fixtures/email_dynamic_query_team_scope.sql@@ -0,0 +1,190 @@+-- Fixture for testing team_scope dynamic queries.+--+-- Sets up:+-- • Team Alpha with two members (Alice, Bob).+-- • Carol — a non-member with her own link/threads (must never appear in+-- team-scoped results).+-- • Each link has its OWN row in email_contacts for the same external+-- address "[email protected]" — different UUIDs per link. This is what+-- exercises the new multi-id `from_contact_id = ANY($ids)` predicate.+-- • Each link has a TRASH label with a different UUID. Some threads are+-- trashed in each link to exercise the multi-id trash exclusion.+-- • Threads on alice/bob's links from "[email protected]" (acme.com+-- domain) plus a thread on alice's link from a different sender,+-- plus a thread on carol's link that must be excluded.++-- == macro_user / User rows ==+INSERT INTO "macro_user" (id, username, email, stripe_customer_id)+VALUES+ ('a1111111-1111-1111-1111-111111111111', '[email protected]', '[email protected]', 'stripe_alice'),+ ('b1111111-1111-1111-1111-111111111111', '[email protected]', '[email protected]', 'stripe_bob'),+ ('c1111111-1111-1111-1111-111111111111', '[email protected]', '[email protected]', 'stripe_carol');++INSERT INTO "User" (id, email, name, macro_user_id)+VALUES+ ('macro|[email protected]', '[email protected]', 'Alice', 'a1111111-1111-1111-1111-111111111111'),+ ('macro|[email protected]', '[email protected]', 'Bob', 'b1111111-1111-1111-1111-111111111111'),+ ('macro|[email protected]', '[email protected]', 'Carol', 'c1111111-1111-1111-1111-111111111111');++-- == Team Alpha + memberships ==+INSERT INTO team (id, name, owner_id, seat_count)+VALUES+ ('e0000001-0000-0000-0000-000000000001', 'Team Alpha', 'macro|[email protected]', 2);++INSERT INTO team_user (team_id, user_id, team_role)+VALUES+ ('e0000001-0000-0000-0000-000000000001', 'macro|[email protected]', 'owner'),+ ('e0000001-0000-0000-0000-000000000001', 'macro|[email protected]', 'member');+-- Carol is intentionally NOT a member.++-- == Email links (one per user) ==+INSERT INTO email_links (id, macro_id, fusionauth_user_id, email_address, provider, is_sync_active, created_at, updated_at)+VALUES+ ('a0000001-0000-0000-0000-000000000001', 'macro|[email protected]', 'fa_alice', '[email protected]', 'GMAIL', true, NOW(), NOW()),+ ('a0000002-0000-0000-0000-000000000002', 'macro|[email protected]', 'fa_bob', '[email protected]', 'GMAIL', true, NOW(), NOW()),+ ('a0000003-0000-0000-0000-000000000003', 'macro|[email protected]', 'fa_carol', '[email protected]', 'GMAIL', true, NOW(), NOW());++-- == Contacts ==+-- Each link has its own row for the SAME external address. This is the+-- multi-id case the new resolution path is designed to handle.+INSERT INTO email_contacts (id, link_id, email_address, name, created_at, updated_at)+VALUES+ -- [email protected] — one contact row per link, different UUIDs+ ('c0000001-0000-0000-0000-000000000001', 'a0000001-0000-0000-0000-000000000001', '[email protected]', 'Outsider', NOW(), NOW()),+ ('c0000002-0000-0000-0000-000000000002', 'a0000002-0000-0000-0000-000000000002', '[email protected]', 'Outsider', NOW(), NOW()),+ ('c0000003-0000-0000-0000-000000000003', 'a0000003-0000-0000-0000-000000000003', '[email protected]', 'Outsider', NOW(), NOW()),+ -- a different sender on alice's link, for non-matching-filter assertions+ ('c0000004-0000-0000-0000-000000000004', 'a0000001-0000-0000-0000-000000000001', '[email protected]', 'Other', NOW(), NOW()),+ -- TO/CC/BCC recipient contacts — mirrored on both alice and bob's+ -- links (same address, different per-link UUIDs). Exercise multi-id+ -- ANY predicates on the recipient EXISTS subquery.+ ('c0000005-0000-0000-0000-000000000005', 'a0000001-0000-0000-0000-000000000001', '[email protected]', 'To Target', NOW(), NOW()),+ ('c0000006-0000-0000-0000-000000000006', 'a0000001-0000-0000-0000-000000000001', '[email protected]', 'Cc Target', NOW(), NOW()),+ ('c0000007-0000-0000-0000-000000000007', 'a0000001-0000-0000-0000-000000000001', '[email protected]', 'Bcc Target', NOW(), NOW()),+ ('c0000008-0000-0000-0000-000000000008', 'a0000002-0000-0000-0000-000000000002', '[email protected]', 'To Target', NOW(), NOW()),+ ('c0000009-0000-0000-0000-000000000009', 'a0000002-0000-0000-0000-000000000002', '[email protected]', 'Cc Target', NOW(), NOW()),+ ('c0000010-0000-0000-0000-000000000010', 'a0000002-0000-0000-0000-000000000002', '[email protected]', 'Bcc Target', NOW(), NOW()),+ -- Asymmetric: only Bob has a contact row for this address.+ -- `Sender(Complete("[email protected]"))` under team_scope should+ -- resolve to exactly one contact id and match only bob's thread.+ ('c0000011-0000-0000-0000-000000000011', 'a0000002-0000-0000-0000-000000000002', '[email protected]', 'BobOnly', NOW(), NOW());++-- == Labels — INBOX + TRASH per link ==+INSERT INTO email_labels (id, link_id, provider_label_id, name, message_list_visibility, label_list_visibility, type, created_at)+VALUES+ -- Alice's labels+ ('11110001-0000-0000-0000-000000000001', 'a0000001-0000-0000-0000-000000000001', 'INBOX', 'INBOX', 'Show', 'LabelShow', 'System', NOW()),+ ('11110001-0000-0000-0000-000000000002', 'a0000001-0000-0000-0000-000000000001', 'TRASH', 'TRASH', 'Hide', 'LabelHide', 'System', NOW()),+ -- Bob's labels+ ('11110002-0000-0000-0000-000000000001', 'a0000002-0000-0000-0000-000000000002', 'INBOX', 'INBOX', 'Show', 'LabelShow', 'System', NOW()),+ ('11110002-0000-0000-0000-000000000002', 'a0000002-0000-0000-0000-000000000002', 'TRASH', 'TRASH', 'Hide', 'LabelHide', 'System', NOW()),+ -- Carol's labels+ ('11110003-0000-0000-0000-000000000001', 'a0000003-0000-0000-0000-000000000003', 'INBOX', 'INBOX', 'Show', 'LabelShow', 'System', NOW()),+ ('11110003-0000-0000-0000-000000000002', 'a0000003-0000-0000-0000-000000000003', 'TRASH', 'TRASH', 'Hide', 'LabelHide', 'System', NOW());++-- == Threads ==+-- ta1: alice's inbox thread from [email protected] (will appear in team queries)+-- ta2: alice's TRASHED thread from [email protected] (must NOT appear)+-- ta3: alice's inbox thread from [email protected] (no acme match)+-- tb1: bob's inbox thread from [email protected] (will appear in team queries)+-- tb2: bob's TRASHED thread from [email protected] (must NOT appear)+-- tc1: carol's inbox thread from [email protected] (must NOT appear — not on team)+INSERT INTO email_threads (+ id, provider_id, link_id, inbox_visible, is_read,+ latest_inbound_message_ts, latest_outbound_message_ts, latest_non_spam_message_ts,+ created_at, updated_at+)+VALUES+ ('22220001-0000-0000-0000-000000000001', 'ta1', 'a0000001-0000-0000-0000-000000000001',+ true, false, '2026-04-01 10:00:00+00', NULL, '2026-04-01 10:00:00+00', NOW(), NOW()),+ ('22220001-0000-0000-0000-000000000002', 'ta2', 'a0000001-0000-0000-0000-000000000001',+ true, false, '2026-04-02 10:00:00+00', NULL, '2026-04-02 10:00:00+00', NOW(), NOW()),+ ('22220001-0000-0000-0000-000000000003', 'ta3', 'a0000001-0000-0000-0000-000000000001',+ true, false, '2026-04-03 10:00:00+00', NULL, '2026-04-03 10:00:00+00', NOW(), NOW()),+ ('22220002-0000-0000-0000-000000000001', 'tb1', 'a0000002-0000-0000-0000-000000000002',+ true, false, '2026-04-04 10:00:00+00', NULL, '2026-04-04 10:00:00+00', NOW(), NOW()),+ ('22220002-0000-0000-0000-000000000002', 'tb2', 'a0000002-0000-0000-0000-000000000002',+ true, false, '2026-04-05 10:00:00+00', NULL, '2026-04-05 10:00:00+00', NOW(), NOW()),+ ('22220003-0000-0000-0000-000000000001', 'tc1', 'a0000003-0000-0000-0000-000000000003',+ true, false, '2026-04-06 10:00:00+00', NULL, '2026-04-06 10:00:00+00', NOW(), NOW()),+ -- tb3: bob's inbox thread from [email protected] (asymmetric test).+ ('22220002-0000-0000-0000-000000000003', 'tb3', 'a0000002-0000-0000-0000-000000000002',+ true, false, '2026-04-07 10:00:00+00', NULL, '2026-04-07 10:00:00+00', NOW(), NOW());++-- == Messages ==+INSERT INTO email_messages (+ id, thread_id, link_id, provider_id, from_contact_id,+ subject, snippet, internal_date_ts,+ is_draft, is_sent, is_starred, is_read,+ created_at, updated_at+)+VALUES+ -- ta1 — alice's inbox, from [email protected] (alice's contact row)+ ('33330001-0000-0000-0000-000000000001', '22220001-0000-0000-0000-000000000001',+ 'a0000001-0000-0000-0000-000000000001', 'ma1', 'c0000001-0000-0000-0000-000000000001',+ 'Alice inbox acme', 'alice from acme', '2026-04-01 10:00:00+00',+ false, false, false, false, NOW(), NOW()),+ -- ta2 — alice's TRASHED, from [email protected] (alice's contact row)+ ('33330001-0000-0000-0000-000000000002', '22220001-0000-0000-0000-000000000002',+ 'a0000001-0000-0000-0000-000000000001', 'ma2', 'c0000001-0000-0000-0000-000000000001',+ 'Alice trash acme', 'alice trashed acme', '2026-04-02 10:00:00+00',+ false, false, false, false, NOW(), NOW()),+ -- ta3 — alice's inbox, from [email protected] (not an acme address)+ ('33330001-0000-0000-0000-000000000003', '22220001-0000-0000-0000-000000000003',+ 'a0000001-0000-0000-0000-000000000001', 'ma3', 'c0000004-0000-0000-0000-000000000004',+ 'Alice inbox other', 'alice from elsewhere', '2026-04-03 10:00:00+00',+ false, false, false, false, NOW(), NOW()),+ -- tb1 — bob's inbox, from [email protected] (bob's contact row)+ ('33330002-0000-0000-0000-000000000001', '22220002-0000-0000-0000-000000000001',+ 'a0000002-0000-0000-0000-000000000002', 'mb1', 'c0000002-0000-0000-0000-000000000002',+ 'Bob inbox acme', 'bob from acme', '2026-04-04 10:00:00+00',+ false, false, false, false, NOW(), NOW()),+ -- tb2 — bob's TRASHED, from [email protected] (bob's contact row)+ ('33330002-0000-0000-0000-000000000002', '22220002-0000-0000-0000-000000000002',+ 'a0000002-0000-0000-0000-000000000002', 'mb2', 'c0000002-0000-0000-0000-000000000002',+ 'Bob trash acme', 'bob trashed acme', '2026-04-05 10:00:00+00',+ false, false, false, false, NOW(), NOW()),+ -- tc1 — carol's inbox, from [email protected] (carol's contact row)+ ('33330003-0000-0000-0000-000000000001', '22220003-0000-0000-0000-000000000001',+ 'a0000003-0000-0000-0000-000000000003', 'mc1', 'c0000003-0000-0000-0000-000000000003',+ 'Carol inbox acme', 'carol from acme', '2026-04-06 10:00:00+00',+ false, false, false, false, NOW(), NOW()),+ -- mb3 — bob's inbox thread tb3, from [email protected] (only on bob's link)+ ('33330002-0000-0000-0000-000000000003', '22220002-0000-0000-0000-000000000003',+ 'a0000002-0000-0000-0000-000000000002', 'mb3', 'c0000011-0000-0000-0000-000000000011',+ 'Bob inbox bob-only', 'bob from bob-only', '2026-04-07 10:00:00+00',+ false, false, false, false, NOW(), NOW());++-- == Recipients ==+-- ta1 and tb1 both have the same TO/CC/BCC addresses, but each link has+-- its own contact row for those addresses (different UUIDs). The recipient+-- ANY-predicate must match both via multi-id resolution.+INSERT INTO email_message_recipients (message_id, contact_id, recipient_type)+VALUES+ -- ta1 recipients (alice's link)+ ('33330001-0000-0000-0000-000000000001', 'c0000005-0000-0000-0000-000000000005', 'TO'),+ ('33330001-0000-0000-0000-000000000001', 'c0000006-0000-0000-0000-000000000006', 'CC'),+ ('33330001-0000-0000-0000-000000000001', 'c0000007-0000-0000-0000-000000000007', 'BCC'),+ -- tb1 recipients (bob's link)+ ('33330002-0000-0000-0000-000000000001', 'c0000008-0000-0000-0000-000000000008', 'TO'),+ ('33330002-0000-0000-0000-000000000001', 'c0000009-0000-0000-0000-000000000009', 'CC'),+ ('33330002-0000-0000-0000-000000000001', 'c0000010-0000-0000-0000-000000000010', 'BCC');++-- == Message labels ==+-- Inbox label on the inbox threads (per-link INBOX label uuids)+-- TRASH label on the trashed threads (per-link TRASH label uuids)+INSERT INTO email_message_labels (message_id, label_id)+VALUES+ -- Alice INBOX+ ('33330001-0000-0000-0000-000000000001', '11110001-0000-0000-0000-000000000001'),+ ('33330001-0000-0000-0000-000000000003', '11110001-0000-0000-0000-000000000001'),+ -- Alice TRASH (ta2)+ ('33330001-0000-0000-0000-000000000002', '11110001-0000-0000-0000-000000000002'),+ -- Bob INBOX+ ('33330002-0000-0000-0000-000000000001', '11110002-0000-0000-0000-000000000001'),+ -- Bob INBOX (tb3, from [email protected])+ ('33330002-0000-0000-0000-000000000003', '11110002-0000-0000-0000-000000000001'),+ -- Bob TRASH (tb2)+ ('33330002-0000-0000-0000-000000000002', '11110002-0000-0000-0000-000000000002'),+ -- Carol INBOX+ ('33330003-0000-0000-0000-000000000001', '11110003-0000-0000-0000-000000000001');diff --git a/rust/cloud-storage/email/src/domain/models/error.rs b/rust/cloud-storage/email/src/domain/models/error.rsindex 5377e2f4eb..7bfee8eddb 100644--- a/rust/cloud-storage/email/src/domain/models/error.rs+++ b/rust/cloud-storage/email/src/domain/models/error.rs@@ -50,4 +50,12 @@ pub enum EmailErr {/// Invalid email filter input.#[error("{0}")]InvalidEmailFilter(String),+ /// A team-scoped query referenced an email domain that is either not+ /// tracked as a CRM organization for the team, or whose organization+ /// has `email_sync` disabled. Without email_sync, the team has not+ /// opted into sharing emails for that organization across members.+ #[error(+ "Domain {0} is not authorized for team-scoped email queries (no matching CRM organization, or organization has email_sync disabled)"+ )]+ DomainNotPermittedForTeamScope(String),}diff --git a/rust/cloud-storage/email/src/domain/models/preview.rs b/rust/cloud-storage/email/src/domain/models/preview.rsindex 5ea6ff1101..cf0d71a143 100644--- a/rust/cloud-storage/email/src/domain/models/preview.rs+++ b/rust/cloud-storage/email/src/domain/models/preview.rs@@ -1,4 +1,5 @@use chrono::{DateTime, Utc};+use entity_access::domain::models::{EntityAccessReceipt, MemberTeamRole};use frecency::domain::models::AggregateFrecency;use item_filters::ast::{LiteralTree, email::EmailLiteral};use macro_user_id::user_id::MacroUserIdStr;@@ -18,6 +19,11 @@ pub struct PreviewCursorQuery {pub link_id: Uuid,pub limit: u32,pub query: Query<Uuid, SimpleSortMethod, LiteralTree<EmailLiteral>>,+ /// When `Some(team_id)`, the dynamic query path expands the candidate+ /// thread set from "only this `link_id`" to "every `link_id` owned by+ /// any user on this team." Populated by the service after a successful+ /// team_scope validation (see `validate_team_scope`).+ pub team_id: Option<Uuid>,}#[derive(Debug, Clone, Copy, PartialEq, Eq, EnumString, Display)]@@ -135,4 +141,9 @@ pub struct GetEmailsRequest {pub macro_id: MacroUserIdStr<'static>,pub limit: Option<u32>,pub query: Query<Uuid, SimpleSortMethod, LiteralTree<EmailLiteral>>,+ /// Proof that the caller belongs to a team, when the query contains an+ /// `EmailLiteral::TeamScope` literal. The receipt's `entity()` is the+ /// team's UUID, which the query layer can use to expand visibility to+ /// teammate mailboxes.+ pub team_receipt: Option<EntityAccessReceipt<MemberTeamRole>>,}diff --git a/rust/cloud-storage/email/src/domain/service/draft.rs b/rust/cloud-storage/email/src/domain/service/draft.rsindex 8464dc4539..c4f0ba45df 100644--- a/rust/cloud-storage/email/src/domain/service/draft.rs+++ b/rust/cloud-storage/email/src/domain/service/draft.rs@@ -12,11 +12,12 @@ use uuid::Uuid;use super::EmailServiceImpl;-impl<T, U, E> EmailServiceImpl<T, U, E>+impl<T, U, E, CS> EmailServiceImpl<T, U, E, CS>whereT: EmailRepo,U: FrecencyQueryService,E: crate::domain::ports::EmailMessageEnqueuer,+ CS: crm::domain::service::CrmService,anyhow::Error: From<T::Err>,{#[tracing::instrument(err, skip(self, link, input))]diff --git a/rust/cloud-storage/email/src/domain/service/mod.rs b/rust/cloud-storage/email/src/domain/service/mod.rsindex 7bfc92308e..becc6a2dd8 100644--- a/rust/cloud-storage/email/src/domain/service/mod.rs+++ b/rust/cloud-storage/email/src/domain/service/mod.rs@@ -12,6 +12,7 @@ use crate::domain::{},ports::{EmailMessageEnqueuer, EmailRepo, EmailService},};+use crm::domain::service::CrmService;use entity_access::domain::models::{AccessLevel, EditAccessLevel, EntityAccessReceipt, EntityPermission, ViewAccessLevel,};@@ -20,35 +21,39 @@ use models_pagination::{PaginatedCursor, SimpleSortMethod};use uuid::Uuid;#[derive(Clone)]-pub struct EmailServiceImpl<T, U, E> {- email_repo: T,- frecency_service: U,- enqueuer: E,- sent_undo_delay_secs: u32,+pub struct EmailServiceImpl<T, U, E, CS> {+ pub(crate) email_repo: T,+ pub(crate) frecency_service: U,+ pub(crate) enqueuer: E,+ pub(crate) crm_service: CS,+ pub(crate) sent_undo_delay_secs: u32,}-impl<T, U, E> EmailServiceImpl<T, U, E>+impl<T, U, E, CS> EmailServiceImpl<T, U, E, CS>whereT: EmailRepo,U: FrecencyQueryService,E: EmailMessageEnqueuer,+ CS: CrmService,{pub fn new(email_repo: T,frecency_service: U,enqueuer: E,+ crm_service: CS,sent_undo_delay_secs: u32,- ) -> EmailServiceImpl<T, U, E> {+ ) -> EmailServiceImpl<T, U, E, CS> {EmailServiceImpl {email_repo,frecency_service,enqueuer,+ crm_service,sent_undo_delay_secs,}}}-impl<T, U, E> EmailServiceImpl<T, U, E> {+impl<T, U, E, CS> EmailServiceImpl<T, U, E, CS> {/// Validate and normalize email filter input.fn validate_email_filter_input(input: UpsertEmailFilterInput,@@ -108,11 +113,12 @@ impl<T, U, E> EmailServiceImpl<T, U, E> {}}-impl<T, U, E> EmailService for EmailServiceImpl<T, U, E>+impl<T, U, E, CS> EmailService for EmailServiceImpl<T, U, E, CS>whereT: EmailRepo,U: FrecencyQueryService,E: EmailMessageEnqueuer,+ CS: CrmService,anyhow::Error: From<T::Err>,anyhow::Error: From<E::Err>,{diff --git a/rust/cloud-storage/email/src/domain/service/previews.rs b/rust/cloud-storage/email/src/domain/service/previews.rsindex 6785b1141e..440af171a6 100644--- a/rust/cloud-storage/email/src/domain/service/previews.rs+++ b/rust/cloud-storage/email/src/domain/service/previews.rs@@ -1,3 +1,8 @@+use entity_access::domain::models::EntityAccessReceipt;+use entity_access::domain::models::MemberTeamRole;+use filter_ast::Expr;+use item_filters::ast::email::{Email, EmailLiteral};+use crate::domain::{models::{EmailErr, EnrichedEmailThreadPreview, GetEmailsRequest, PreviewCursorQuery, UserProvider,@@ -8,19 +13,22 @@ use frecency::domain::{models::{AggregateId, FrecencyByIdsRequest, FrecencyData},ports::FrecencyQueryService,};+use item_filters::ast::LiteralTree;use macro_user_id::cowlike::CowLike;+use macro_user_id::email::ReadEmailParts;use model_entity::EntityType;use models_pagination::{CollectBy, PaginateOn, PaginatedCursor, SimpleSortMethod};-use std::collections::HashMap;+use std::collections::{HashMap, HashSet};use uuid::Uuid;use super::EmailServiceImpl;-impl<T, U, E> EmailServiceImpl<T, U, E>+impl<T, U, E, CS> EmailServiceImpl<T, U, E, CS>whereT: EmailRepo,U: FrecencyQueryService,E: crate::domain::ports::EmailMessageEnqueuer,+ CS: crm::domain::service::CrmService,anyhow::Error: From<T::Err>,{#[tracing::instrument(err, skip(self, req))]@@ -35,7 +43,13 @@ wheremacro_id,limit,query,+ team_receipt,} = req;++ let team_id = self+ .validate_team_scope(team_receipt.as_ref(), query.filter())+ .await?;+let sort_method = *query.sort_method();const MIN_PAGE: u32 = 20;@@ -48,6 +62,7 @@ wherelink_id,limit,query,+ team_id,};let previews = self@@ -125,4 +140,156 @@ where.await.map_err(anyhow::Error::from)?)}++ /// Verify that a query is allowed to run team-scoped behavior.+ ///+ /// Three layered checks, in order:+ /// 1. Did the query actually request `EmailLiteral::TeamScope`? If not,+ /// this is a normal per-mailbox query — no further checks apply.+ /// 2. Is a team-membership receipt present? If not, the caller asked+ /// for team-wide visibility without proof of team membership —+ /// reject as `Unauthorized`. (This shouldn't happen via the soup+ /// handler, which 403s upstream, but the email service is the+ /// resource boundary and validates defensively.)+ /// 3. For each `Email::Domain(_)` literal in the AST, the team must+ /// have a CRM organization tracking that domain with+ /// `email_sync = true`. Otherwise the team has not opted into+ /// sharing emails for that domain — reject the query.+ ///+ /// Returns `Some(team_id)` when team_scope was requested AND the receipt+ /// passed all checks (membership, domain authorization). `None` when+ /// team_scope wasn't requested — the caller should run the normal+ /// per-link query path.+ async fn validate_team_scope(+ &self,+ team_receipt: Option<&EntityAccessReceipt<MemberTeamRole>>,+ filter: &LiteralTree<EmailLiteral>,+ ) -> Result<Option<Uuid>, EmailErr> {+ if !filter_requests_team_scope(filter) {+ return Ok(None);+ }++ // Reject any `Email::Partial(_)` address under team_scope. The typed+ // POST endpoint catches this at AST expansion via+ // `ExpandErr::TeamScopeRequiresQualifiedEmail`, but the raw AST+ // endpoint bypasses that path — a `Partial` would otherwise become+ // a team-wide `ILIKE` substring search across teammate mailboxes,+ // skipping the qualified-address rule and the CRM domain-consent+ // gate. Reject here defensively.+ if filter_contains_partial_address(filter) {+ return Err(EmailErr::Unauthorized);+ }++ let receipt = team_receipt.ok_or(EmailErr::Unauthorized)?;++ let team_id = Uuid::parse_str(&receipt.entity().entity_id).map_err(|e| {+ EmailErr::RepoErr(anyhow::anyhow!(+ "team_receipt entity_id is not a valid uuid: {e}"+ ))+ })?;++ let domains = collect_domain_literals(filter);+ if domains.is_empty() {+ return Ok(Some(team_id));+ }++ for domain in domains {+ let company = self+ .crm_service+ .get_company_by_domain(&team_id, &domain)+ .await+ .map_err(|e| EmailErr::RepoErr(anyhow::anyhow!("crm lookup failed: {e}")))?;++ match company {+ Some(company) if company.email_sync => {}+ _ => return Err(EmailErr::DomainNotPermittedForTeamScope(domain)),+ }+ }++ Ok(Some(team_id))+ }+}++/// Walks an email-filter AST and returns the deduped set of domains that+/// require CRM `email_sync` authorization under team_scope.+///+/// Sources:+/// - `Email::Domain(d)` → `d` directly. The literal IS a domain.+/// - `Email::Complete(addr)` → `addr.domain_part()`. The team_scope rule+/// is "the address's company must have email_sync enabled", so an exact+/// address like `[email protected]` is governed by acme.com's CRM company,+/// not by whether alice is individually in `crm_contacts`.+/// - `Email::Partial(_)` → not handled here. `validate_team_scope` rejects+/// Partial+team_scope upfront via `filter_contains_partial_address`, so+/// this walker only sees Domain/Complete by the time it runs.+fn collect_domain_literals(filter: &LiteralTree<EmailLiteral>) -> HashSet<String> {+ fn walk(expr: &Expr<EmailLiteral>, out: &mut HashSet<String>) {+ match expr {+ Expr::And(a, b) | Expr::Or(a, b) => {+ walk(a, out);+ walk(b, out);+ }+ Expr::Not(a) => walk(a, out),+ Expr::Literal(+ EmailLiteral::Sender(email)+ | EmailLiteral::Cc(email)+ | EmailLiteral::Bcc(email)+ | EmailLiteral::Recipient(email),+ ) => match email {+ Email::Domain(d) => {+ out.insert(d.to_ascii_lowercase());+ }+ Email::Complete(addr) => {+ out.insert(addr.0.domain_part().to_ascii_lowercase());+ }+ Email::Partial(_) => {}+ },+ Expr::Literal(_) => {}+ }+ }+ let mut out = HashSet::new();+ if let Some(expr) = filter.as_ref() {+ walk(expr, &mut out);+ }+ out+}++/// Walks an email-filter AST and returns true if any node is the+/// `EmailLiteral::TeamScope` literal. Used to gate team-scope-specific+/// validation/expansion: without this literal the caller is not asking for+/// team-wide visibility, so checks like CRM domain authorization don't apply.+fn filter_requests_team_scope(filter: &LiteralTree<EmailLiteral>) -> bool {+ fn walk(expr: &Expr<EmailLiteral>) -> bool {+ match expr {+ Expr::And(a, b) | Expr::Or(a, b) => walk(a) || walk(b),+ Expr::Not(a) => walk(a),+ Expr::Literal(EmailLiteral::TeamScope) => true,+ Expr::Literal(_) => false,+ }+ }+ filter.as_ref().map(|e| walk(e)).unwrap_or(false)+}++/// Walks an email-filter AST and returns true if any Sender/Cc/Bcc/Recipient+/// literal carries an `Email::Partial(_)`. Partial is a substring fragment+/// (the trigram-indexed ILIKE path) and must not appear under team_scope —+/// the typed POST endpoint already rejects this combination at AST+/// expansion (`ExpandErr::TeamScopeRequiresQualifiedEmail`), but the raw+/// AST endpoint bypasses that path, so this is the defensive check at the+/// email-service boundary.+fn filter_contains_partial_address(filter: &LiteralTree<EmailLiteral>) -> bool {+ fn walk(expr: &Expr<EmailLiteral>) -> bool {+ match expr {+ Expr::And(a, b) | Expr::Or(a, b) => walk(a) || walk(b),+ Expr::Not(a) => walk(a),+ Expr::Literal(+ EmailLiteral::Sender(Email::Partial(_))+ | EmailLiteral::Cc(Email::Partial(_))+ | EmailLiteral::Bcc(Email::Partial(_))+ | EmailLiteral::Recipient(Email::Partial(_)),+ ) => true,+ Expr::Literal(_) => false,+ }+ }+ filter.as_ref().map(|e| walk(e)).unwrap_or(false)}diff --git a/rust/cloud-storage/email/src/domain/service/send.rs b/rust/cloud-storage/email/src/domain/service/send.rsindex 13b281ce0c..bc1264a14f 100644--- a/rust/cloud-storage/email/src/domain/service/send.rs+++ b/rust/cloud-storage/email/src/domain/service/send.rs@@ -8,11 +8,12 @@ use frecency::domain::ports::FrecencyQueryService;use super::EmailServiceImpl;-impl<T, U, E> EmailServiceImpl<T, U, E>+impl<T, U, E, CS> EmailServiceImpl<T, U, E, CS>whereT: EmailRepo,U: FrecencyQueryService,E: EmailMessageEnqueuer,+ CS: crm::domain::service::CrmService,anyhow::Error: From<T::Err>,anyhow::Error: From<E::Err>,{diff --git a/rust/cloud-storage/email/src/domain/service/thread.rs b/rust/cloud-storage/email/src/domain/service/thread.rsindex e04036a666..adfe868ac7 100644--- a/rust/cloud-storage/email/src/domain/service/thread.rs+++ b/rust/cloud-storage/email/src/domain/service/thread.rs@@ -27,11 +27,12 @@ struct ThreadFetchResult {is_owner: bool,}-impl<T, U, E> EmailServiceImpl<T, U, E>+impl<T, U, E, CS> EmailServiceImpl<T, U, E, CS>whereT: EmailRepo,U: FrecencyQueryService,E: crate::domain::ports::EmailMessageEnqueuer,+ CS: crm::domain::service::CrmService,anyhow::Error: From<T::Err>,{/// Fetch thread row, paginated messages, and their core sub-resourcesdiff --git a/rust/cloud-storage/email/src/domain/service/thread_labels.rs b/rust/cloud-storage/email/src/domain/service/thread_labels.rsindex ec53e1750b..8d41c92401 100644--- a/rust/cloud-storage/email/src/domain/service/thread_labels.rs+++ b/rust/cloud-storage/email/src/domain/service/thread_labels.rs@@ -7,11 +7,12 @@ use uuid::Uuid;use super::EmailServiceImpl;-impl<T, U, E> EmailServiceImpl<T, U, E>+impl<T, U, E, CS> EmailServiceImpl<T, U, E, CS>whereT: EmailRepo,U: FrecencyQueryService,E: EmailMessageEnqueuer,+ CS: crm::domain::service::CrmService,anyhow::Error: From<T::Err>,anyhow::Error: From<E::Err>,{diff --git a/rust/cloud-storage/email/src/inbound/axum/previews_router.rs b/rust/cloud-storage/email/src/inbound/axum/previews_router.rsindex b8dedc8c8a..a6925ba6d9 100644--- a/rust/cloud-storage/email/src/inbound/axum/previews_router.rs+++ b/rust/cloud-storage/email/src/inbound/axum/previews_router.rs@@ -105,6 +105,7 @@ async fn cursor_handler<T: EmailService>((),).map_filter(|_| None),+ team_receipt: None,}).await?.type_erase(),diff --git a/rust/cloud-storage/email/src/outbound/email_pg_repo/dynamic/filters.rs b/rust/cloud-storage/email/src/outbound/email_pg_repo/dynamic/filters.rsindex 38bc4e16f1..31d5781c5e 100644--- a/rust/cloud-storage/email/src/outbound/email_pg_repo/dynamic/filters.rs+++ b/rust/cloud-storage/email/src/outbound/email_pg_repo/dynamic/filters.rs@@ -85,11 +85,12 @@ fn build_address_predicate_on_m(email: &Email,resolved: &ResolvedFilters,) -> SqlFragment {- match (resolved.contact_id_for(email), email) {- (Some(contact_id), _) => match kind {+ match (resolved.contact_ids_for(email), email) {+ (Some(contact_ids), _) => match kind {AddressKind::Sender => {- let mut f = SqlFragment::raw("m.from_contact_id = ");- f.extend(SqlFragment::bind_uuid(contact_id));+ let mut f = SqlFragment::raw("m.from_contact_id = ANY(");+ f.extend(SqlFragment::bind_uuid_array(contact_ids.to_vec()));+ f.push_raw(")");f}_ => {@@ -99,43 +100,71 @@ fn build_address_predicate_on_m(SELECT 1 FROM email_message_recipients mrWHERE mr.message_id = m.idAND mr.recipient_type = '{recipient_type}'- AND mr.contact_id = "#,+ AND mr.contact_id = ANY("#,));- f.extend(SqlFragment::bind_uuid(contact_id));- f.push_raw("\n )");+ f.extend(SqlFragment::bind_uuid_array(contact_ids.to_vec()));+ f.push_raw(")\n )");f}},(None, Email::Complete(_)) => SqlFragment::raw("FALSE"),+ // Partial: substring match against the full address text. Used for+ // fuzzy "type a fragment" lookups (e.g. searching "jo" → "john@..."+ // and "joe@..."). Rides the trigram index on email_address.(None, Email::Partial(s)) => {let pattern = format!("%{}%", escape_like_pattern(s));- match kind {- AddressKind::Sender => {- let mut f = SqlFragment::raw(- r#"EXISTS (+ build_address_text_match(kind, "c.email_address ILIKE ", pattern)+ }+ // Domain: exact match on the domain portion of the address. Backed+ // by the expression index on `LOWER(SPLIT_PART(email_address, '@', 2))`+ // so the lookup is an index seek rather than a trigram substring+ // scan, and there are no false positives like `macro.community`+ // matching the domain `macro.com`.+ (None, Email::Domain(s)) => {+ let domain = s.to_ascii_lowercase();+ build_address_text_match(+ kind,+ "LOWER(SPLIT_PART(c.email_address, '@', 2)) = ",+ domain,+ )+ }+ }+}++/// Shared shape for "join `email_contacts`, apply a single bound predicate+/// against `c.*`". `predicate_prefix` is the SQL up to the bind site+/// (e.g. `"c.email_address ILIKE "`), and `bind_value` is the string that+/// gets bound at that position.+fn build_address_text_match(+ kind: AddressKind,+ predicate_prefix: &str,+ bind_value: String,+) -> SqlFragment {+ match kind {+ AddressKind::Sender => {+ let mut f = SqlFragment::raw(format!(+ r#"EXISTS (SELECT 1 FROM email_contacts cWHERE c.id = m.from_contact_id- AND c.email_address ILIKE "#,- );- f.extend(SqlFragment::bind_string(pattern));- f.push_raw("\n )");- f- }- _ => {- let recipient_type = kind.recipient_type_sql().expect("non-sender kind");- let mut f = SqlFragment::raw(format!(- r#"EXISTS (+ AND {predicate_prefix}"#+ ));+ f.extend(SqlFragment::bind_string(bind_value));+ f.push_raw("\n )");+ f+ }+ _ => {+ let recipient_type = kind.recipient_type_sql().expect("non-sender kind");+ let mut f = SqlFragment::raw(format!(+ r#"EXISTS (SELECT 1 FROM email_message_recipients mrJOIN email_contacts c ON mr.contact_id = c.idWHERE mr.message_id = m.idAND mr.recipient_type = '{recipient_type}'- AND c.email_address ILIKE "#,- ));- f.extend(SqlFragment::bind_string(pattern));- f.push_raw("\n )");- f- }- }+ AND {predicate_prefix}"#,+ ));+ f.extend(SqlFragment::bind_string(bind_value));+ f.push_raw("\n )");+ f}}}@@ -287,6 +316,7 @@ pub(super) fn build_message_email_filter(SqlFragment::raw("TRUE")}filter_ast::ExprFrame::Literal(EmailLiteral::Shared(_)) => SqlFragment::raw("TRUE"),+ filter_ast::ExprFrame::Literal(EmailLiteral::TeamScope) => SqlFragment::raw("TRUE"),filter_ast::ExprFrame::Literal(EmailLiteral::CalendarOnly(_)) => SqlFragment::raw("TRUE"),filter_ast::ExprFrame::Literal(EmailLiteral::CreatedAt(_)) => SqlFragment::raw("TRUE"),filter_ast::ExprFrame::Literal(EmailLiteral::UpdatedAt(_)) => SqlFragment::raw("TRUE"),@@ -381,28 +411,28 @@ fn build_address_message_predicate(}/// Builds the `NOT EXISTS (… TRASH …)` fragment used inside the candidate-/// subquery. Uses a direct `ml.label_id = $trash_label_id` probe (full PK-/// match on `email_message_labels`) when the trash label is resolved.-/// Returns `TRUE` (no exclusion) when the link has no TRASH label —-/// callers must always pre-resolve via `resolve_filters`, and a missing-/// TRASH label means no message can be trashed in the first place.+/// subquery. Uses `ml.label_id = ANY($trash_label_ids)` so the probe+/// excludes TRASH messages across every link in scope (one link for+/// per-mailbox queries, all team links for team-scoped queries).+/// Returns `TRUE` (no exclusion) when no in-scope link has a TRASH label —+/// callers must always pre-resolve via `resolve_filters`, and an empty set+/// means no message can be trashed in the first place.fn build_trash_check(resolved: &ResolvedFilters) -> SqlFragment {- match resolved.trash_label_id() {- Some(id) => {- let mut f = SqlFragment::raw(- r#"NOT EXISTS (- SELECT 1 FROM email_message_labels ml- WHERE ml.message_id = m.id AND ml.label_id = "#,- );- f.extend(SqlFragment::bind_uuid(id));- f.push_raw(- r#"- )"#,- );- f- }- None => SqlFragment::raw("TRUE"),+ let ids = resolved.trash_label_ids();+ if ids.is_empty() {+ return SqlFragment::raw("TRUE");}+ let mut f = SqlFragment::raw(+ r#"NOT EXISTS (+ SELECT 1 FROM email_message_labels ml+ WHERE ml.message_id = m.id AND ml.label_id = ANY("#,+ );+ f.extend(SqlFragment::bind_uuid_array(ids.to_vec()));+ f.push_raw(+ r#")+ )"#,+ );+ f}/// True when the AST contains at least one pure-address top-level@@ -471,14 +501,15 @@ fn build_union_branch(resolved: &ResolvedFilters,) -> Option<SqlFragment> {let trash = build_trash_check(resolved);- match (resolved.contact_id_for(email), email) {- (Some(contact_id), _) => {+ match (resolved.contact_ids_for(email), email) {+ (Some(contact_ids), _) => {let mut f = match kind {AddressKind::Sender => {let mut f = SqlFragment::raw(- "SELECT m.thread_id FROM email_messages m WHERE m.from_contact_id = ",+ "SELECT m.thread_id FROM email_messages m WHERE m.from_contact_id = ANY(",);- f.extend(SqlFragment::bind_uuid(contact_id));+ f.extend(SqlFragment::bind_uuid_array(contact_ids.to_vec()));+ f.push_raw(")");f}_ => {@@ -486,10 +517,10 @@ fn build_union_branch(let mut f = SqlFragment::raw("SELECT m.thread_id FROM email_message_recipients mr \JOIN email_messages m ON m.id = mr.message_id \- WHERE mr.contact_id = ",+ WHERE mr.contact_id = ANY(",);- f.extend(SqlFragment::bind_uuid(contact_id));- f.push_raw(format!(" AND mr.recipient_type = '{recipient_type}'"));+ f.extend(SqlFragment::bind_uuid_array(contact_ids.to_vec()));+ f.push_raw(format!(") AND mr.recipient_type = '{recipient_type}'"));f}};@@ -500,29 +531,18 @@ fn build_union_branch((None, Email::Complete(_)) => None,(None, Email::Partial(s)) => {let pattern = format!("%{}%", escape_like_pattern(s));- let mut f = match kind {- AddressKind::Sender => {- let mut f = SqlFragment::raw(- "SELECT m.thread_id FROM email_contacts c \- JOIN email_messages m ON m.from_contact_id = c.id \- WHERE c.email_address ILIKE ",- );- f.extend(SqlFragment::bind_string(pattern));- f- }- _ => {- let recipient_type = kind.recipient_type_sql().expect("non-sender kind");- let mut f = SqlFragment::raw(- "SELECT m.thread_id FROM email_contacts c \- JOIN email_message_recipients mr ON mr.contact_id = c.id \- JOIN email_messages m ON m.id = mr.message_id \- WHERE c.email_address ILIKE ",- );- f.extend(SqlFragment::bind_string(pattern));- f.push_raw(format!(" AND mr.recipient_type = '{recipient_type}'"));- f- }- };+ let mut f = build_union_branch_text_match(kind, "c.email_address ILIKE ", pattern);+ f.push_raw(" AND ");+ f.extend(trash);+ Some(f)+ }+ (None, Email::Domain(s)) => {+ let domain = s.to_ascii_lowercase();+ let mut f = build_union_branch_text_match(+ kind,+ "LOWER(SPLIT_PART(c.email_address, '@', 2)) = ",+ domain,+ );f.push_raw(" AND ");f.extend(trash);Some(f)@@ -530,6 +550,38 @@ fn build_union_branch(}}+/// Shared shape for a union-branch SELECT that joins through+/// `email_contacts` with a single bound predicate against `c.*`.+fn build_union_branch_text_match(+ kind: AddressKind,+ predicate_prefix: &str,+ bind_value: String,+) -> SqlFragment {+ match kind {+ AddressKind::Sender => {+ let mut f = SqlFragment::raw(format!(+ "SELECT m.thread_id FROM email_contacts c \+ JOIN email_messages m ON m.from_contact_id = c.id \+ WHERE {predicate_prefix}"+ ));+ f.extend(SqlFragment::bind_string(bind_value));+ f+ }+ _ => {+ let recipient_type = kind.recipient_type_sql().expect("non-sender kind");+ let mut f = SqlFragment::raw(format!(+ "SELECT m.thread_id FROM email_contacts c \+ JOIN email_message_recipients mr ON mr.contact_id = c.id \+ JOIN email_messages m ON m.id = mr.message_id \+ WHERE {predicate_prefix}"+ ));+ f.extend(SqlFragment::bind_string(bind_value));+ f.push_raw(format!(" AND mr.recipient_type = '{recipient_type}'"));+ f+ }+ }+}+/// Builds the body of the `matching_threads` CTE — i.e., everything/// between `MATERIALIZED (` and `)`. Two shapes:///@@ -651,7 +703,8 @@ pub(super) fn build_thread_email_filter(| EmailLiteral::Importance(_)| EmailLiteral::NotificationDone(_)| EmailLiteral::NotificationSeen(_)- | EmailLiteral::Shared(_),+ | EmailLiteral::Shared(_)+ | EmailLiteral::TeamScope,) => SqlFragment::raw("TRUE"),});@@ -758,20 +811,19 @@ pub(super) fn get_sort_timestamp_field(view: &PreviewView) -> &'static str {/// means no message can be trashed. Anchored on `m.id` inside the LATERAL,/// so callers shouldn't add their own AND prefix.pub(super) fn build_lateral_trash_exclusion(resolved: &ResolvedFilters) -> SqlFragment {- match resolved.trash_label_id() {- Some(id) => {- let mut f = SqlFragment::raw(- r#"NOT EXISTS (- SELECT 1 FROM email_message_labels ml- WHERE ml.message_id = m.id AND ml.label_id = "#,- );- f.extend(SqlFragment::bind_uuid(id));- f.push_raw(- r#"- )"#,- );- f- }- None => SqlFragment::raw("TRUE"),+ let ids = resolved.trash_label_ids();+ if ids.is_empty() {+ return SqlFragment::raw("TRUE");}+ let mut f = SqlFragment::raw(+ r#"NOT EXISTS (+ SELECT 1 FROM email_message_labels ml+ WHERE ml.message_id = m.id AND ml.label_id = ANY("#,+ );+ f.extend(SqlFragment::bind_uuid_array(ids.to_vec()));+ f.push_raw(+ r#")+ )"#,+ );+ f}diff --git a/rust/cloud-storage/email/src/outbound/email_pg_repo/dynamic/mod.rs b/rust/cloud-storage/email/src/outbound/email_pg_repo/dynamic/mod.rsindex fb69f5eb31..a6496fe01c 100644--- a/rust/cloud-storage/email/src/outbound/email_pg_repo/dynamic/mod.rs+++ b/rust/cloud-storage/email/src/outbound/email_pg_repo/dynamic/mod.rs@@ -27,6 +27,7 @@ enum SqlSegment {Raw(String),BindString(String),BindUuid(Uuid),+ BindUuidArray(Vec<Uuid>),}struct SqlFragment {@@ -56,6 +57,12 @@ impl SqlFragment {}}+ fn bind_uuid_array(ids: impl Into<Vec<Uuid>>) -> Self {+ Self {+ segments: vec![SqlSegment::BindUuidArray(ids.into())],+ }+ }+fn is_empty(&self) -> bool {self.segments.is_empty()}@@ -114,6 +121,9 @@ impl SqlFragment {SqlSegment::BindUuid(u) => {builder.push_bind(u);}+ SqlSegment::BindUuidArray(ids) => {+ builder.push_bind(ids);+ }}}}@@ -135,6 +145,15 @@ impl SqlFragment {bind_idx += 1;result.push_str(&format!("${bind_idx}[uuid={u}]"));}+ SqlSegment::BindUuidArray(ids) => {+ bind_idx += 1;+ let joined = ids+ .iter()+ .map(|u| u.to_string())+ .collect::<Vec<_>>()+ .join(",");+ result.push_str(&format!("${bind_idx}[uuid_array=[{joined}]]"));+ }}}result@@ -146,10 +165,18 @@ impl SqlFragment {.any(|s| matches!(s, SqlSegment::BindString(v) if v == expected))}+ /// True if `expected` is bound somewhere in this fragment — either as a+ /// single-uuid bind or as an element of a uuid-array bind. The array+ /// case exists because address-id resolution now returns+ /// `Vec<Uuid>` (one entry per link in scope) and the predicate uses+ /// `= ANY($ids)`. Existing tests that assert "this contact id is in the+ /// query" should still pass without caring which shape it's bound as.fn has_bind_uuid(&self, expected: &Uuid) -> bool {- self.segments- .iter()- .any(|s| matches!(s, SqlSegment::BindUuid(v) if v == expected))+ self.segments.iter().any(|s| match s {+ SqlSegment::BindUuid(v) => v == expected,+ SqlSegment::BindUuidArray(vs) => vs.contains(expected),+ _ => false,+ })}fn has_no_raw_containing(&self, needle: &str) -> bool {diff --git a/rust/cloud-storage/email/src/outbound/email_pg_repo/dynamic/query.rs b/rust/cloud-storage/email/src/outbound/email_pg_repo/dynamic/query.rsindex 31b5161d42..d7daf0ad68 100644--- a/rust/cloud-storage/email/src/outbound/email_pg_repo/dynamic/query.rs+++ b/rust/cloud-storage/email/src/outbound/email_pg_repo/dynamic/query.rs@@ -22,6 +22,10 @@ struct QueryParams {shared: SharedEmailFilter,user_id: String,resolved: ResolvedFilters,+ /// When `Some(team_id)`, the "Owned" candidate source expands from+ /// `t.link_id = $link_id` to `t.link_id IN (links of every member of+ /// $team_id)`. Set only after team_scope has been validated upstream.+ team_id: Option<Uuid>,}enum ThreadCandidateSource {@@ -110,10 +114,27 @@ fn push_thread_candidate_select());match source {- ThreadCandidateSource::Owned => {- builder.push("t.link_id = ");- builder.push_bind(params.link_id);- }+ ThreadCandidateSource::Owned => match params.team_id {+ // Normal per-mailbox query.+ None => {+ builder.push("t.link_id = ");+ builder.push_bind(params.link_id);+ }+ // Team-scoped query: expand to every email_link owned by any+ // member of the team. The receipt has already been validated+ // upstream, so the team_id is trusted here.+ Some(team_id) => {+ builder.push(+ r#"t.link_id IN (+ SELECT el.id+ FROM email_links el+ JOIN team_user tu ON tu.user_id = el.macro_id+ WHERE tu.team_id = "#,+ );+ builder.push_bind(team_id);+ builder.push(")");+ }+ },ThreadCandidateSource::Shared => {builder.push("t.id IN (SELECT thread_id FROM SharedEmailThreads)");}@@ -373,6 +394,7 @@ pub(super) fn debug_build_query_sql_with_resolved(shared,user_id: "test-user".to_string(),resolved,+ team_id: None,},).build()@@ -427,6 +449,7 @@ pub(crate) async fn dynamic_email_thread_cursor(view: &PreviewView,query: Query<Uuid, SimpleSortMethod, Arc<Expr<EmailLiteral>>>,user_id: &str,+ team_id: Option<Uuid>,) -> Result<Vec<ThreadPreviewCursorDbRow>, sqlx::Error> {let query_limit = limit as i64;let sort_method_str = query.sort_method().to_string();@@ -445,7 +468,10 @@ pub(crate) async fn dynamic_email_thread_cursor(// Resolve Complete email addresses to contact ids and look up the TRASH// label id once, so the candidate WHERE can use direct id equality// instead of joining email_contacts/email_labels per message row.- let resolved = resolve_filters(pool, *link_id, email_filter).await?;+ //+ // When team_id is set, resolution spans every team-member's link so the+ // resulting contact_id / TRASH label_id sets cover all team mailboxes.+ let resolved = resolve_filters(pool, *link_id, team_id, email_filter).await?;if can_short_circuit(email_filter, &resolved) {return Ok(Vec::new());}@@ -463,6 +489,7 @@ pub(crate) async fn dynamic_email_thread_cursor(shared,user_id: user_id.to_string(),resolved,+ team_id,},);diff --git a/rust/cloud-storage/email/src/outbound/email_pg_repo/dynamic/resolve.rs b/rust/cloud-storage/email/src/outbound/email_pg_repo/dynamic/resolve.rsindex 9c51f4f602..8ee9ebb457 100644--- a/rust/cloud-storage/email/src/outbound/email_pg_repo/dynamic/resolve.rs+++ b/rust/cloud-storage/email/src/outbound/email_pg_repo/dynamic/resolve.rs@@ -5,53 +5,75 @@ use std::collections::HashMap;use uuid::Uuid;/// Caches lookups that are repeated thousands of times inside the address-/// filter — `email_contacts.id` for each Complete email referenced by the-/// AST, plus the `email_labels.id` for the per-link TRASH label. Resolving-/// once up front lets the candidate WHERE use direct id equality instead of-/// joining `email_contacts` / `email_labels` per message row.+/// filter — `email_contacts.id`s for each Complete email referenced by the+/// AST, plus the `email_labels.id`s for the TRASH label. Resolving once up+/// front lets the candidate WHERE use direct id equality instead of joining+/// `email_contacts` / `email_labels` per message row.+///+/// Both fields are Vec-valued to support team-scoped queries, where the same+/// email address may resolve to multiple `email_contacts` rows (one per team+/// member's `link_id`) and the TRASH label exists once per link. For the+/// normal per-link path the Vecs typically contain one element.pub(super) struct ResolvedFilters {- /// Lowercased email address → contact id, for every Complete address in- /// the AST that has a row in `email_contacts` for this link.- contact_ids: HashMap<String, Uuid>,- /// The TRASH label id for this link, if one exists.- trash_label_id: Option<Uuid>,+ /// Lowercased email address → all contact ids that match across the+ /// resolved scope (one link, or all team links). Empty Vec means the+ /// address has no matching contact anywhere in scope.+ contact_ids: HashMap<String, Vec<Uuid>>,+ /// All TRASH label ids in scope. One id per link with a TRASH label.+ /// Empty when no scope-relevant link has a TRASH label (rare).+ trash_label_ids: Vec<Uuid>,}impl ResolvedFilters {- /// Returns the resolved contact id for a Complete email, or `None` for- /// unresolved Completes and Partial emails. Unresolved Completes will- /// be emitted as `FALSE` by the SQL builder.- pub(super) fn contact_id_for(&self, email: &Email) -> Option<Uuid> {+ /// Returns the resolved contact ids for a Complete email, or `None` for+ /// unresolved Completes and Partial/Domain emails. Unresolved Completes+ /// will be emitted as `FALSE` by the SQL builder.+ pub(super) fn contact_ids_for(&self, email: &Email) -> Option<&[Uuid]> {match email {Email::Complete(e) => {let lowered = e.0.as_ref().to_lowercase();- self.contact_ids.get(&lowered).copied()+ self.contact_ids+ .get(&lowered)+ .filter(|ids| !ids.is_empty())+ .map(|ids| ids.as_slice())}- Email::Partial(_) => None,+ Email::Partial(_) | Email::Domain(_) => None,}}- pub(super) fn trash_label_id(&self) -> Option<Uuid> {- self.trash_label_id+ pub(super) fn trash_label_ids(&self) -> &[Uuid] {+ &self.trash_label_ids+ }++ /// True iff at least one Complete email address in the AST has any+ /// matching contact in the resolved scope. Used by `fold_unresolved`.+ fn has_contact_for(&self, lowered_email: &str) -> bool {+ self.contact_ids+ .get(lowered_email)+ .map(|ids| !ids.is_empty())+ .unwrap_or(false)}#[cfg(test)]pub(super) fn empty() -> Self {Self {contact_ids: HashMap::new(),- trash_label_id: None,+ trash_label_ids: Vec::new(),}}#[cfg(test)]pub(super) fn with_contact(mut self, lowered_email: impl Into<String>, id: Uuid) -> Self {- self.contact_ids.insert(lowered_email.into(), id);+ self.contact_ids+ .entry(lowered_email.into())+ .or_default()+ .push(id);self}#[cfg(test)]pub(super) fn with_trash(mut self, id: Uuid) -> Self {- self.trash_label_id = Some(id);+ self.trash_label_ids.push(id);self}}@@ -104,13 +126,13 @@ pub(super) fn fold_unresolved(match email {Email::Complete(e) => {let lowered = e.0.as_ref().to_lowercase();- if resolved.contact_ids.contains_key(&lowered) {+ if resolved.has_contact_for(&lowered) {None} else {Some(false)}}- Email::Partial(_) => None,+ Email::Partial(_) | Email::Domain(_) => None,}}@@ -138,48 +160,100 @@ pub(super) fn can_short_circuit(ast: &Expr<EmailLiteral>, resolved: &ResolvedFil}/// Resolves all Complete emails in the AST to `contact_id`s and looks up-/// the TRASH label id for the link in one (or two) DB round trip(s).+/// the TRASH label id(s) for the scope.+///+/// When `team_id` is `None`, the scope is the single `link_id` (normal+/// per-mailbox query) and each address resolves to at most one contact_id;+/// the TRASH lookup returns at most one label id.+///+/// When `team_id` is `Some`, the scope expands to every `link_id` owned by+/// any user on the team. The same email address may now resolve to multiple+/// contact_ids (one per team member who has corresponded with that address),+/// and the TRASH lookup returns one label id per team link. The SQL builder+/// uses `= ANY($ids)` predicates so messages in *any* team mailbox match.#[tracing::instrument(skip(pool, ast), err)]pub(super) async fn resolve_filters(pool: &PgPool,link_id: Uuid,+ team_id: Option<Uuid>,ast: &Expr<EmailLiteral>,) -> Result<ResolvedFilters, sqlx::Error> {- let trash_label_id: Option<Uuid> = sqlx::query_scalar!(- r#"- SELECT id- FROM email_labels- WHERE link_id = $1 AND name = 'TRASH'- LIMIT 1- "#,- link_id,- )- .fetch_optional(pool)- .await?;+ let trash_label_ids: Vec<Uuid> = match team_id {+ None => {+ sqlx::query_scalar!(+ r#"+ SELECT id+ FROM email_labels+ WHERE link_id = $1 AND name = 'TRASH'+ "#,+ link_id,+ )+ .fetch_all(pool)+ .await?+ }+ Some(team_id) => {+ sqlx::query_scalar!(+ r#"+ SELECT l.id+ FROM email_labels l+ JOIN email_links el ON el.id = l.link_id+ JOIN team_user tu ON tu.user_id = el.macro_id+ WHERE l.name = 'TRASH' AND tu.team_id = $1+ "#,+ team_id,+ )+ .fetch_all(pool)+ .await?+ }+ };let emails = collect_complete_emails(ast);- let contact_ids = if emails.is_empty() {- HashMap::new()- } else {- let rows = sqlx::query!(- r#"- SELECT id, LOWER(email_address) AS "email_lower!"- FROM email_contacts- WHERE link_id = $1 AND LOWER(email_address) = ANY($2)- "#,- link_id,- &emails,- )- .fetch_all(pool)- .await?;+ let mut contact_ids: HashMap<String, Vec<Uuid>> = HashMap::new();+ if !emails.is_empty() {+ // Project each arm's anonymous `Record` into a common `(Uuid, String)`+ // shape — `sqlx::query!` generates a distinct struct per call site, so+ // the `match` arms can't share a return type otherwise.+ let rows: Vec<(Uuid, String)> = match team_id {+ None => sqlx::query!(+ r#"+ SELECT id, LOWER(email_address) AS "email_lower!"+ FROM email_contacts+ WHERE link_id = $1 AND LOWER(email_address) = ANY($2)+ "#,+ link_id,+ &emails,+ )+ .fetch_all(pool)+ .await?+ .into_iter()+ .map(|r| (r.id, r.email_lower))+ .collect(),+ Some(team_id) => sqlx::query!(+ r#"+ SELECT c.id, LOWER(c.email_address) AS "email_lower!"+ FROM email_contacts c+ JOIN email_links el ON el.id = c.link_id+ JOIN team_user tu ON tu.user_id = el.macro_id+ WHERE tu.team_id = $1+ AND LOWER(c.email_address) = ANY($2)+ "#,+ team_id,+ &emails,+ )+ .fetch_all(pool)+ .await?+ .into_iter()+ .map(|r| (r.id, r.email_lower))+ .collect(),+ };- rows.into_iter()- .map(|r| (r.email_lower, r.id))- .collect::<HashMap<_, _>>()- };+ for (id, email_lower) in rows {+ contact_ids.entry(email_lower).or_default().push(id);+ }+ }Ok(ResolvedFilters {contact_ids,- trash_label_id,+ trash_label_ids,})}diff --git a/rust/cloud-storage/email/src/outbound/email_pg_repo/dynamic/tests.rs b/rust/cloud-storage/email/src/outbound/email_pg_repo/dynamic/tests.rsindex 7aa2f931f9..eac3c3ab59 100644--- a/rust/cloud-storage/email/src/outbound/email_pg_repo/dynamic/tests.rs+++ b/rust/cloud-storage/email/src/outbound/email_pg_repo/dynamic/tests.rs@@ -136,6 +136,123 @@ fn test_build_message_email_filter_sender_partial() {assert!(result.has_no_raw_containing("example"));}+// ---------------------------------------------------------------------------+// Email::Domain emits an exact-domain predicate, not an ILIKE substring+// ---------------------------------------------------------------------------+//+// `Email::Domain("acme.com")` must match contacts whose address ends in+// `@acme.com` exactly — not anything containing the substring "acme.com".+// The SQL predicate is `LOWER(SPLIT_PART(c.email_address, '@', 2)) = $domain`,+// backed by the expression index `idx_email_contacts_email_domain`.+// These tests guard against three regressions:+// 1. accidentally falling back to `ILIKE '%domain%'` (would re-introduce+// false positives like `macro.community` matching `macro.com`)+// 2. forgetting to lowercase the bound value before sending it (the index+// is built on `LOWER(...)`, so a mixed-case bind would miss the index)+// 3. leaking the domain into raw SQL instead of binding it (sql injection)++#[test]+fn test_build_message_email_filter_sender_domain_emits_split_part_eq() {+ let expr = Expr::Literal(EmailLiteral::Sender(Email::Domain("acme.com".to_string())));+ let result = build_message_email_filter(&expr, &ResolvedFilters::empty());+ let debug = result.to_debug_sql();++ assert!(+ debug.contains("LOWER(SPLIT_PART(c.email_address, '@', 2)) ="),+ "expected exact-domain predicate, got: {debug}"+ );+ assert!(!debug.contains("ILIKE"), "domain match must not use ILIKE");+ assert!(result.has_bind_string("acme.com"));+ // No `%domain%` wildcards — that would re-introduce the substring bug.+ assert!(!result.has_bind_string("%acme.com%"));+ assert!(result.has_no_raw_containing("acme.com"));+}++#[test]+fn test_build_message_email_filter_domain_lowercases_bind_value() {+ // The expression index is `LOWER(SPLIT_PART(email_address, '@', 2))`. If+ // we bind a mixed-case domain, the predicate becomes+ // `LOWER(SPLIT_PART(c.email_address, '@', 2)) = 'ACME.COM'`, which never+ // matches anything (LHS is lowercase, RHS isn't) AND can't use the+ // index. The fix is to lowercase the bound value.+ let expr = Expr::Literal(EmailLiteral::Sender(Email::Domain("AcMe.CoM".to_string())));+ let result = build_message_email_filter(&expr, &ResolvedFilters::empty());++ assert!(result.has_bind_string("acme.com"));+ assert!(!result.has_bind_string("AcMe.CoM"));+}++#[test]+fn test_build_message_email_filter_recipient_domain() {+ let expr = Expr::Literal(EmailLiteral::Recipient(Email::Domain(+ "acme.com".to_string(),+ )));+ let result = build_message_email_filter(&expr, &ResolvedFilters::empty());+ let debug = result.to_debug_sql();++ assert!(debug.contains("email_message_recipients"));+ assert!(debug.contains("recipient_type = 'TO'"));+ assert!(debug.contains("LOWER(SPLIT_PART(c.email_address, '@', 2)) ="));+ assert!(!debug.contains("ILIKE"));+ assert!(result.has_bind_string("acme.com"));+ assert!(result.has_no_raw_containing("acme.com"));+}++#[test]+fn test_build_message_email_filter_cc_domain() {+ let expr = Expr::Literal(EmailLiteral::Cc(Email::Domain("acme.com".to_string())));+ let result = build_message_email_filter(&expr, &ResolvedFilters::empty());+ let debug = result.to_debug_sql();++ assert!(debug.contains("recipient_type = 'CC'"));+ assert!(debug.contains("LOWER(SPLIT_PART(c.email_address, '@', 2)) ="));+ assert!(!debug.contains("ILIKE"));+ assert!(result.has_bind_string("acme.com"));+}++#[test]+fn test_build_message_email_filter_bcc_domain() {+ let expr = Expr::Literal(EmailLiteral::Bcc(Email::Domain("acme.com".to_string())));+ let result = build_message_email_filter(&expr, &ResolvedFilters::empty());+ let debug = result.to_debug_sql();++ assert!(debug.contains("recipient_type = 'BCC'"));+ assert!(debug.contains("LOWER(SPLIT_PART(c.email_address, '@', 2)) ="));+ assert!(!debug.contains("ILIKE"));+ assert!(result.has_bind_string("acme.com"));+}++#[test]+fn test_partial_and_domain_emit_different_predicates_for_same_string() {+ // A regression test: before the split, `Email::Partial("acme.com")` and+ // `Email::Domain("acme.com")` shared the same `ILIKE '%acme.com%'`+ // predicate. Splitting them is the whole point of the change — confirm+ // they now produce structurally different SQL even with identical input.+ let s = "acme.com";++ let partial = build_message_email_filter(+ &Expr::Literal(EmailLiteral::Sender(Email::Partial(s.to_string()))),+ &ResolvedFilters::empty(),+ );+ let domain = build_message_email_filter(+ &Expr::Literal(EmailLiteral::Sender(Email::Domain(s.to_string()))),+ &ResolvedFilters::empty(),+ );++ let partial_debug = partial.to_debug_sql();+ let domain_debug = domain.to_debug_sql();++ // Partial is a substring scan against the full address.+ assert!(partial_debug.contains("ILIKE"));+ assert!(!partial_debug.contains("SPLIT_PART"));+ assert!(partial.has_bind_string("%acme.com%"));++ // Domain is an exact match against the domain portion only.+ assert!(domain_debug.contains("SPLIT_PART"));+ assert!(!domain_debug.contains("ILIKE"));+ assert!(domain.has_bind_string("acme.com"));+}+#[test]fn test_build_message_email_filter_importance_true_includes_drafts() {let expr = Expr::Literal(EmailLiteral::Importance(true));@@ -758,6 +875,54 @@ fn test_matching_threads_cte_body_partial_emits_ilike_branch_with_email_contactsassert!(body.has_bind_string("%acme%"));}+#[test]+fn test_matching_threads_cte_body_domain_emits_split_part_branch() {+ // The union-branch path is the candidate-thread pushdown — it has its+ // own copy of the address-match SQL builder. Domain on this path must+ // also emit the exact-domain predicate, not ILIKE.+ let expr = Expr::Literal(EmailLiteral::Sender(Email::Domain("acme.com".into())));+ let body =+ build_matching_threads_cte_body(&expr, &ResolvedFilters::empty()).expect("body present");+ let debug = body.to_debug_sql();++ assert!(debug.contains("FROM email_contacts c"));+ assert!(+ debug.contains("LOWER(SPLIT_PART(c.email_address, '@', 2)) ="),+ "expected exact-domain predicate in CTE branch, got: {debug}"+ );+ assert!(!debug.contains("ILIKE"));+ assert!(body.has_bind_string("acme.com"));+ assert!(!body.has_bind_string("%acme.com%"));+ assert!(body.has_no_raw_containing("acme.com"));+}++#[test]+fn test_matching_threads_cte_body_domain_recipient_kind_uses_split_part() {+ // Recipient (and CC/BCC) go through the recipient join in the+ // union-branch builder. Verify the predicate shape is consistent across+ // address kinds.+ let expr = Expr::Literal(EmailLiteral::Recipient(Email::Domain("acme.com".into())));+ let body =+ build_matching_threads_cte_body(&expr, &ResolvedFilters::empty()).expect("body present");+ let debug = body.to_debug_sql();++ assert!(debug.contains("email_message_recipients"));+ assert!(debug.contains("mr.recipient_type = 'TO'"));+ assert!(debug.contains("LOWER(SPLIT_PART(c.email_address, '@', 2)) ="));+ assert!(!debug.contains("ILIKE"));+ assert!(body.has_bind_string("acme.com"));+}++#[test]+fn test_matching_threads_cte_body_domain_lowercases_bind_value() {+ let expr = Expr::Literal(EmailLiteral::Sender(Email::Domain("AcMe.CoM".into())));+ let body =+ build_matching_threads_cte_body(&expr, &ResolvedFilters::empty()).expect("body present");++ assert!(body.has_bind_string("acme.com"));+ assert!(!body.has_bind_string("AcMe.CoM"));+}+#[test]fn test_matching_threads_cte_body_and_of_conjuncts_uses_combined_predicate_form() {// `Sender(X) AND Recipient(Y)` requires single-message semantics —diff --git a/rust/cloud-storage/email/src/outbound/email_pg_repo/preview.rs b/rust/cloud-storage/email/src/outbound/email_pg_repo/preview.rsindex d35a1228d0..12a7132a7b 100644--- a/rust/cloud-storage/email/src/outbound/email_pg_repo/preview.rs+++ b/rust/cloud-storage/email/src/outbound/email_pg_repo/preview.rs@@ -21,6 +21,7 @@ pub(super) async fn previews_for_view_cursor(link_id,limit,query,+ team_id,} = query;let query = query.split_option();@@ -34,6 +35,7 @@ pub(super) async fn previews_for_view_cursor(&view,dynamic_query,user_id.as_ref(),+ team_id,).await?}diff --git a/rust/cloud-storage/email/src/outbound/email_pg_repo/test/dynamic_query.rs b/rust/cloud-storage/email/src/outbound/email_pg_repo/test/dynamic_query.rsindex ed481fe693..5b05642caa 100644--- a/rust/cloud-storage/email/src/outbound/email_pg_repo/test/dynamic_query.rs+++ b/rust/cloud-storage/email/src/outbound/email_pg_repo/test/dynamic_query.rs@@ -16,7 +16,8 @@ async fn test_dynamic_query_inbox_view(pool: Pool<Postgres>) -> anyhow::Result<(let query = Query::new(None, SimpleSortMethod::UpdatedAt, filter);let results =- dynamic::dynamic_email_thread_cursor(&pool, &link_id, limit, &view, query, "").await?;+ dynamic::dynamic_email_thread_cursor(&pool, &link_id, limit, &view, query, "", None)+ .await?;// Should get inbox messages (threads 1, 4, 5, 7)assert_eq!(@@ -50,7 +51,8 @@ async fn test_dynamic_query_sent_view(pool: Pool<Postgres>) -> anyhow::Result<()let query = Query::new(None, SimpleSortMethod::UpdatedAt, filter);let results =- dynamic::dynamic_email_thread_cursor(&pool, &link_id, limit, &view, query, "").await?;+ dynamic::dynamic_email_thread_cursor(&pool, &link_id, limit, &view, query, "", None)+ .await?;// Should get sent messages (thread 2)assert_eq!(results.len(), 1, "Sent view should return 1 thread");@@ -76,7 +78,8 @@ async fn test_dynamic_query_drafts_view(pool: Pool<Postgres>) -> anyhow::Result<let query = Query::new(None, SimpleSortMethod::UpdatedAt, filter);let results =- dynamic::dynamic_email_thread_cursor(&pool, &link_id, limit, &view, query, "").await?;+ dynamic::dynamic_email_thread_cursor(&pool, &link_id, limit, &view, query, "", None)+ .await?;// Should get draft messages (threads 3 and 8)assert_eq!(results.len(), 2, "Drafts view should return 2 threads");@@ -102,7 +105,8 @@ async fn test_dynamic_query_starred_view(pool: Pool<Postgres>) -> anyhow::Resultlet query = Query::new(None, SimpleSortMethod::UpdatedAt, filter);let results =- dynamic::dynamic_email_thread_cursor(&pool, &link_id, limit, &view, query, "").await?;+ dynamic::dynamic_email_thread_cursor(&pool, &link_id, limit, &view, query, "", None)+ .await?;// Should get starred messages (thread 4)assert_eq!(results.len(), 1, "Starred view should return 1 thread");@@ -128,7 +132,8 @@ async fn test_dynamic_query_important_view(pool: Pool<Postgres>) -> anyhow::Resulet query = Query::new(None, SimpleSortMethod::UpdatedAt, filter);let results =- dynamic::dynamic_email_thread_cursor(&pool, &link_id, limit, &view, query, "").await?;+ dynamic::dynamic_email_thread_cursor(&pool, &link_id, limit, &view, query, "", None)+ .await?;// Should get important messages and drafts (threads 3, 5, and 8)assert_eq!(results.len(), 3, "Important view should return 3 threads");@@ -206,7 +211,8 @@ async fn test_dynamic_query_user_label_view(pool: Pool<Postgres>) -> anyhow::Reslet query = Query::new(None, SimpleSortMethod::UpdatedAt, filter);let results =- dynamic::dynamic_email_thread_cursor(&pool, &link_id, limit, &view, query, "").await?;+ dynamic::dynamic_email_thread_cursor(&pool, &link_id, limit, &view, query, "", None)+ .await?;// Should get messages with "Work" label (thread 6)assert_eq!(results.len(), 1, "User label view should return 1 thread");@@ -234,7 +240,8 @@ async fn test_dynamic_query_with_sender_filter(pool: Pool<Postgres>) -> anyhow::let query = Query::new(None, SimpleSortMethod::UpdatedAt, email_filter);let results =- dynamic::dynamic_email_thread_cursor(&pool, &link_id, limit, &view, query, "").await?;+ dynamic::dynamic_email_thread_cursor(&pool, &link_id, limit, &view, query, "", None)+ .await?;// Should get messages from [email protected] (threads 1, 2, 5)assert!(@@ -268,7 +275,8 @@ async fn test_dynamic_query_with_partial_sender_filter(pool: Pool<Postgres>) ->let query = Query::new(None, SimpleSortMethod::UpdatedAt, email_filter);let results =- dynamic::dynamic_email_thread_cursor(&pool, &link_id, limit, &view, query, "").await?;+ dynamic::dynamic_email_thread_cursor(&pool, &link_id, limit, &view, query, "", None)+ .await?;// Should get all messages since all contacts are from example.comassert!(@@ -295,7 +303,8 @@ async fn test_dynamic_query_with_recipient_filter(pool: Pool<Postgres>) -> anyholet query = Query::new(None, SimpleSortMethod::UpdatedAt, email_filter);let results =- dynamic::dynamic_email_thread_cursor(&pool, &link_id, limit, &view, query, "").await?;+ dynamic::dynamic_email_thread_cursor(&pool, &link_id, limit, &view, query, "", None)+ .await?;// Should get messages to [email protected] (threads 1, 3, 5, 7)assert!(@@ -322,7 +331,8 @@ async fn test_dynamic_query_with_cc_filter(pool: Pool<Postgres>) -> anyhow::Resulet query = Query::new(None, SimpleSortMethod::UpdatedAt, email_filter);let results =- dynamic::dynamic_email_thread_cursor(&pool, &link_id, limit, &view, query, "").await?;+ dynamic::dynamic_email_thread_cursor(&pool, &link_id, limit, &view, query, "", None)+ .await?;// Should get messages with [email protected] in CC (thread 7)assert_eq!(results.len(), 1, "Should return 1 thread with CC to bob");@@ -350,7 +360,8 @@ async fn test_dynamic_query_inbox_with_sender_filter(pool: Pool<Postgres>) -> anlet query = Query::new(None, SimpleSortMethod::UpdatedAt, email_filter);let results =- dynamic::dynamic_email_thread_cursor(&pool, &link_id, limit, &view, query, "").await?;+ dynamic::dynamic_email_thread_cursor(&pool, &link_id, limit, &view, query, "", None)+ .await?;// Should get inbox messages from [email protected] (threads 1, 5)assert_eq!(@@ -388,7 +399,8 @@ async fn test_dynamic_query_drafts_with_recipient_filter(let query = Query::new(None, SimpleSortMethod::UpdatedAt, email_filter);let results =- dynamic::dynamic_email_thread_cursor(&pool, &link_id, limit, &view, query, "").await?;+ dynamic::dynamic_email_thread_cursor(&pool, &link_id, limit, &view, query, "", None)+ .await?;// Should get draft messages to [email protected] (threads 3 and 8)assert_eq!(@@ -422,7 +434,8 @@ async fn test_dynamic_query_with_and_filter(pool: Pool<Postgres>) -> anyhow::Reslet query = Query::new(None, SimpleSortMethod::UpdatedAt, email_filter);let results =- dynamic::dynamic_email_thread_cursor(&pool, &link_id, limit, &view, query, "").await?;+ dynamic::dynamic_email_thread_cursor(&pool, &link_id, limit, &view, query, "", None)+ .await?;// Should get messages from john to alice (threads 1, 5)assert!(@@ -454,7 +467,8 @@ async fn test_dynamic_query_with_or_filter(pool: Pool<Postgres>) -> anyhow::Resulet query = Query::new(None, SimpleSortMethod::UpdatedAt, email_filter);let results =- dynamic::dynamic_email_thread_cursor(&pool, &link_id, limit, &view, query, "").await?;+ dynamic::dynamic_email_thread_cursor(&pool, &link_id, limit, &view, query, "", None)+ .await?;// Should get messages from john or janeassert!(@@ -480,7 +494,8 @@ async fn test_dynamic_query_pagination(pool: Pool<Postgres>) -> anyhow::Result<())));let query = Query::new(None, SimpleSortMethod::UpdatedAt, filter1);let first_page =- dynamic::dynamic_email_thread_cursor(&pool, &link_id, limit, &view, query, "").await?;+ dynamic::dynamic_email_thread_cursor(&pool, &link_id, limit, &view, query, "", None)+ .await?;assert_eq!(first_page.len(), 2, "Should return 2 results");@@ -507,7 +522,8 @@ async fn test_dynamic_query_pagination(pool: Pool<Postgres>) -> anyhow::Result<(};let query2 = Query::new(Some(cursor), SimpleSortMethod::UpdatedAt, filter3);let second_page =- dynamic::dynamic_email_thread_cursor(&pool, &link_id, limit, &view, query2, "").await?;+ dynamic::dynamic_email_thread_cursor(&pool, &link_id, limit, &view, query2, "", None)+ .await?;assert!(second_page.len() > 0,@@ -551,7 +567,8 @@ async fn test_dynamic_query_with_importance_filter(pool: Pool<Postgres>) -> anyhlet query = Query::new(None, SimpleSortMethod::UpdatedAt, filter);let results =- dynamic::dynamic_email_thread_cursor(&pool, &link_id, limit, &view, query, "").await?;+ dynamic::dynamic_email_thread_cursor(&pool, &link_id, limit, &view, query, "", None)+ .await?;// Threads 1 (CATEGORY_PERSONAL), 2 (SENT), 3 (DRAFT), 4 (no depriority), 5 (no depriority), 8 (DRAFT overrides depriority)assert_eq!(@@ -605,7 +622,8 @@ async fn test_dynamic_query_with_importance_filter(pool: Pool<Postgres>) -> anyhlet query = Query::new(None, SimpleSortMethod::UpdatedAt, filter);let results =- dynamic::dynamic_email_thread_cursor(&pool, &link_id, limit, &view, query, "").await?;+ dynamic::dynamic_email_thread_cursor(&pool, &link_id, limit, &view, query, "", None)+ .await?;// Threads 6 (CATEGORY_UPDATES) and 7 (CATEGORY_PROMOTIONS)// Thread 8 has CATEGORY_UPDATES but is excluded because DRAFT is a priority label@@ -653,7 +671,8 @@ async fn test_dynamic_query_importance_true_email_filters_domain_with_address_ovlet query = Query::new(None, SimpleSortMethod::UpdatedAt, filter);let results =- dynamic::dynamic_email_thread_cursor(&pool, &link_id, limit, &view, query, "").await?;+ dynamic::dynamic_email_thread_cursor(&pool, &link_id, limit, &view, query, "", None)+ .await?;let result_ids: std::collections::HashSet<String> =results.iter().map(|r| r.id.to_string()).collect();@@ -688,7 +707,8 @@ async fn test_dynamic_query_importance_true_email_filters_excludes_trashed_messalet query = Query::new(None, SimpleSortMethod::UpdatedAt, filter);let results =- dynamic::dynamic_email_thread_cursor(&pool, &link_id, limit, &view, query, "").await?;+ dynamic::dynamic_email_thread_cursor(&pool, &link_id, limit, &view, query, "", None)+ .await?;let result_ids: std::collections::HashSet<String> =results.iter().map(|r| r.id.to_string()).collect();@@ -719,7 +739,8 @@ async fn test_dynamic_query_importance_false_email_filters_domain_with_address_olet query = Query::new(None, SimpleSortMethod::UpdatedAt, filter);let results =- dynamic::dynamic_email_thread_cursor(&pool, &link_id, limit, &view, query, "").await?;+ dynamic::dynamic_email_thread_cursor(&pool, &link_id, limit, &view, query, "", None)+ .await?;let result_ids: std::collections::HashSet<String> =results.iter().map(|r| r.id.to_string()).collect();@@ -754,7 +775,8 @@ async fn test_dynamic_query_with_single_project_id(pool: Pool<Postgres>) -> anyhlet query = Query::new(None, SimpleSortMethod::UpdatedAt, filter);let results =- dynamic::dynamic_email_thread_cursor(&pool, &link_id, limit, &view, query, "").await?;+ dynamic::dynamic_email_thread_cursor(&pool, &link_id, limit, &view, query, "", None)+ .await?;// Threads 1, 2, 5 are in Project Alphaassert_eq!(results.len(), 3, "Should return 3 threads in Project Alpha");@@ -790,7 +812,8 @@ async fn test_dynamic_query_with_multiple_project_ids(pool: Pool<Postgres>) -> alet query = Query::new(None, SimpleSortMethod::UpdatedAt, filter);let results =- dynamic::dynamic_email_thread_cursor(&pool, &link_id, limit, &view, query, "").await?;+ dynamic::dynamic_email_thread_cursor(&pool, &link_id, limit, &view, query, "", None)+ .await?;// Threads 1, 2, 5 (Alpha) + Thread 6 (Beta)assert_eq!(@@ -831,7 +854,8 @@ async fn test_dynamic_query_project_id_with_sender_filter(let query = Query::new(None, SimpleSortMethod::UpdatedAt, filter);let results =- dynamic::dynamic_email_thread_cursor(&pool, &link_id, limit, &view, query, "").await?;+ dynamic::dynamic_email_thread_cursor(&pool, &link_id, limit, &view, query, "", None)+ .await?;// All results should be in Project Alpha and from johnfor result in &results {@@ -864,7 +888,8 @@ async fn test_dynamic_query_project_id_with_inbox_view(pool: Pool<Postgres>) ->let query = Query::new(None, SimpleSortMethod::UpdatedAt, filter);let results =- dynamic::dynamic_email_thread_cursor(&pool, &link_id, limit, &view, query, "").await?;+ dynamic::dynamic_email_thread_cursor(&pool, &link_id, limit, &view, query, "", None)+ .await?;assert_eq!(results.len(),@@ -901,7 +926,8 @@ async fn test_dynamic_query_inbox_view_with_importance_false(let query = Query::new(None, SimpleSortMethod::UpdatedAt, filter);let results =- dynamic::dynamic_email_thread_cursor(&pool, &link_id, limit, &view, query, "").await?;+ dynamic::dynamic_email_thread_cursor(&pool, &link_id, limit, &view, query, "", None)+ .await?;// Only thread 7: inbox_visible=true AND importance=falseassert_eq!(@@ -941,7 +967,8 @@ async fn test_dynamic_query_with_single_thread_id(pool: Pool<Postgres>) -> anyholet query = Query::new(None, SimpleSortMethod::UpdatedAt, filter);let results =- dynamic::dynamic_email_thread_cursor(&pool, &link_id, limit, &view, query, "").await?;+ dynamic::dynamic_email_thread_cursor(&pool, &link_id, limit, &view, query, "", None)+ .await?;assert_eq!(results.len(), 1);assert_eq!(results[0].id, thread_id);@@ -977,7 +1004,8 @@ async fn test_dynamic_query_thread_id_with_sender_filter(let query = Query::new(None, SimpleSortMethod::UpdatedAt, filter);let results =- dynamic::dynamic_email_thread_cursor(&pool, &link_id, limit, &view, query, "").await?;+ dynamic::dynamic_email_thread_cursor(&pool, &link_id, limit, &view, query, "", None)+ .await?;assert_eq!(results.len(), 1);assert_eq!(results[0].id, id1);@@ -1004,7 +1032,8 @@ async fn test_importance_true_includes_drafts_with_depriority_label(let query = Query::new(None, SimpleSortMethod::UpdatedAt, filter);let results =- dynamic::dynamic_email_thread_cursor(&pool, &link_id, limit, &view, query, "").await?;+ dynamic::dynamic_email_thread_cursor(&pool, &link_id, limit, &view, query, "", None)+ .await?;let result_ids: std::collections::HashSet<String> =results.iter().map(|r| r.id.to_string()).collect();@@ -1040,7 +1069,8 @@ async fn test_importance_true_excludes_trashed_drafts(pool: Pool<Postgres>) -> alet query = Query::new(None, SimpleSortMethod::UpdatedAt, filter);let results =- dynamic::dynamic_email_thread_cursor(&pool, &link_id, limit, &view, query, "").await?;+ dynamic::dynamic_email_thread_cursor(&pool, &link_id, limit, &view, query, "", None)+ .await?;let result_ids: std::collections::HashSet<String> =results.iter().map(|r| r.id.to_string()).collect();@@ -1081,7 +1111,8 @@ async fn test_importance_false_excludes_drafts(pool: Pool<Postgres>) -> anyhow::let query = Query::new(None, SimpleSortMethod::UpdatedAt, filter);let results =- dynamic::dynamic_email_thread_cursor(&pool, &link_id, limit, &view, query, "").await?;+ dynamic::dynamic_email_thread_cursor(&pool, &link_id, limit, &view, query, "", None)+ .await?;let result_ids: std::collections::HashSet<String> =results.iter().map(|r| r.id.to_string()).collect();@@ -1270,6 +1301,7 @@ async fn test_shared_exclude_returns_only_own_threads(pool: Pool<Postgres>) -> a&view,query,"macro|[email protected]",+ None,).await?;@@ -1322,6 +1354,7 @@ async fn test_shared_only_returns_only_shared_threads(pool: Pool<Postgres>) -> a&view,query,"macro|[email protected]",+ None,).await?;@@ -1386,6 +1419,7 @@ async fn test_shared_include_returns_own_and_shared_threads(&view,query,"macro|[email protected]",+ None,).await?;@@ -1441,7 +1475,8 @@ async fn test_dynamic_query_calendar_only_filter(pool: Pool<Postgres>) -> anyhowlet query = Query::new(None, SimpleSortMethod::UpdatedAt, filter);let results =- dynamic::dynamic_email_thread_cursor(&pool, &link_id, limit, &view, query, "").await?;+ dynamic::dynamic_email_thread_cursor(&pool, &link_id, limit, &view, query, "", None)+ .await?;let result_ids: std::collections::HashSet<String> =results.iter().map(|r| r.id.to_string()).collect();@@ -1506,7 +1541,8 @@ async fn test_dynamic_query_calendar_only_inbox_view(pool: Pool<Postgres>) -> anlet query = Query::new(None, SimpleSortMethod::UpdatedAt, filter);let results =- dynamic::dynamic_email_thread_cursor(&pool, &link_id, limit, &view, query, "").await?;+ dynamic::dynamic_email_thread_cursor(&pool, &link_id, limit, &view, query, "", None)+ .await?;let result_ids: std::collections::HashSet<String> =results.iter().map(|r| r.id.to_string()).collect();@@ -1555,7 +1591,8 @@ async fn test_dynamic_query_calendar_only_combined_with_sender(let query = Query::new(None, SimpleSortMethod::UpdatedAt, filter);let results =- dynamic::dynamic_email_thread_cursor(&pool, &link_id, limit, &view, query, "").await?;+ dynamic::dynamic_email_thread_cursor(&pool, &link_id, limit, &view, query, "", None)+ .await?;let result_ids: std::collections::HashSet<String> =results.iter().map(|r| r.id.to_string()).collect();@@ -1596,14 +1633,14 @@ async fn test_dynamic_query_calendar_only_false_is_noop())),));let query = Query::new(None, SimpleSortMethod::UpdatedAt, filter);- dynamic::dynamic_email_thread_cursor(&pool, &link_id, limit, &view, query, "").await?+ dynamic::dynamic_email_thread_cursor(&pool, &link_id, limit, &view, query, "", None).await?};let baseline = {let filter = Arc::new(Expr::Literal(EmailLiteral::Sender(Email::Partial("example.com".to_string(),))));let query = Query::new(None, SimpleSortMethod::UpdatedAt, filter);- dynamic::dynamic_email_thread_cursor(&pool, &link_id, limit, &view, query, "").await?+ dynamic::dynamic_email_thread_cursor(&pool, &link_id, limit, &view, query, "", None).await?};let with_false_ids: std::collections::HashSet<_> = with_false.iter().map(|r| r.id).collect();@@ -1636,6 +1673,7 @@ async fn test_shared_only_returns_correct_owner_id(pool: Pool<Postgres>) -> anyh&view,query,"macro|[email protected]",+ None,).await?;@@ -1676,7 +1714,8 @@ async fn test_dynamic_query_short_circuits_on_unresolved_complete_email(let query = Query::new(None, SimpleSortMethod::UpdatedAt, filter);let results =- dynamic::dynamic_email_thread_cursor(&pool, &link_id, limit, &view, query, "").await?;+ dynamic::dynamic_email_thread_cursor(&pool, &link_id, limit, &view, query, "", None)+ .await?;assert!(results.is_empty(),@@ -1710,7 +1749,8 @@ async fn test_dynamic_query_with_bcc_filter(pool: Pool<Postgres>) -> anyhow::Reslet query = Query::new(None, SimpleSortMethod::UpdatedAt, email_filter);let results =- dynamic::dynamic_email_thread_cursor(&pool, &link_id, limit, &view, query, "").await?;+ dynamic::dynamic_email_thread_cursor(&pool, &link_id, limit, &view, query, "", None)+ .await?;let result_ids: std::collections::HashSet<String> =results.iter().map(|r| r.id.to_string()).collect();@@ -1764,7 +1804,8 @@ async fn test_dynamic_query_and_filter_uses_single_message_semantics())));let query = Query::new(None, SimpleSortMethod::UpdatedAt, filter);let results =- dynamic::dynamic_email_thread_cursor(&pool, &link_id, limit, &view, query, "").await?;+ dynamic::dynamic_email_thread_cursor(&pool, &link_id, limit, &view, query, "", None)+ .await?;let ids: std::collections::HashSet<String> =results.iter().map(|r| r.id.to_string()).collect();assert!(@@ -1785,7 +1826,8 @@ async fn test_dynamic_query_and_filter_uses_single_message_semantics());let query = Query::new(None, SimpleSortMethod::UpdatedAt, filter);let results =- dynamic::dynamic_email_thread_cursor(&pool, &link_id, limit, &view, query, "").await?;+ dynamic::dynamic_email_thread_cursor(&pool, &link_id, limit, &view, query, "", None)+ .await?;let ids: std::collections::HashSet<String> = results.iter().map(|r| r.id.to_string()).collect();assert!(@@ -1847,7 +1889,8 @@ async fn test_dynamic_query_updated_at_greater_than(pool: Pool<Postgres>) -> anylet query = Query::new(None, SimpleSortMethod::UpdatedAt, filter);let results =- dynamic::dynamic_email_thread_cursor(&pool, &link_id, limit, &view, query, "").await?;+ dynamic::dynamic_email_thread_cursor(&pool, &link_id, limit, &view, query, "", None)+ .await?;let result_ids: std::collections::HashSet<String> =results.iter().map(|r| r.id.to_string()).collect();@@ -1899,7 +1942,8 @@ async fn test_dynamic_query_updated_at_less_than(pool: Pool<Postgres>) -> anyhowlet query = Query::new(None, SimpleSortMethod::UpdatedAt, filter);let results =- dynamic::dynamic_email_thread_cursor(&pool, &link_id, limit, &view, query, "").await?;+ dynamic::dynamic_email_thread_cursor(&pool, &link_id, limit, &view, query, "", None)+ .await?;let result_ids: std::collections::HashSet<String> =results.iter().map(|r| r.id.to_string()).collect();@@ -1955,7 +1999,8 @@ async fn test_dynamic_query_updated_at_greater_than_or_equal(let query = Query::new(None, SimpleSortMethod::UpdatedAt, filter);let results =- dynamic::dynamic_email_thread_cursor(&pool, &link_id, limit, &view, query, "").await?;+ dynamic::dynamic_email_thread_cursor(&pool, &link_id, limit, &view, query, "", None)+ .await?;let result_ids: std::collections::HashSet<String> =results.iter().map(|r| r.id.to_string()).collect();@@ -2008,7 +2053,8 @@ async fn test_dynamic_query_updated_at_less_than_or_equal(let query = Query::new(None, SimpleSortMethod::UpdatedAt, filter);let results =- dynamic::dynamic_email_thread_cursor(&pool, &link_id, limit, &view, query, "").await?;+ dynamic::dynamic_email_thread_cursor(&pool, &link_id, limit, &view, query, "", None)+ .await?;let result_ids: std::collections::HashSet<String> =results.iter().map(|r| r.id.to_string()).collect();@@ -2053,7 +2099,8 @@ async fn test_dynamic_query_created_at_greater_than(pool: Pool<Postgres>) -> anylet query = Query::new(None, SimpleSortMethod::UpdatedAt, filter);let results =- dynamic::dynamic_email_thread_cursor(&pool, &link_id, limit, &view, query, "").await?;+ dynamic::dynamic_email_thread_cursor(&pool, &link_id, limit, &view, query, "", None)+ .await?;let result_ids: std::collections::HashSet<String> =results.iter().map(|r| r.id.to_string()).collect();@@ -2097,7 +2144,8 @@ async fn test_dynamic_query_created_at_less_than(pool: Pool<Postgres>) -> anyhowlet query = Query::new(None, SimpleSortMethod::UpdatedAt, filter);let results =- dynamic::dynamic_email_thread_cursor(&pool, &link_id, limit, &view, query, "").await?;+ dynamic::dynamic_email_thread_cursor(&pool, &link_id, limit, &view, query, "", None)+ .await?;let result_ids: std::collections::HashSet<String> =results.iter().map(|r| r.id.to_string()).collect();@@ -2156,7 +2204,8 @@ async fn test_dynamic_query_date_range_combined(pool: Pool<Postgres>) -> anyhow:let query = Query::new(None, SimpleSortMethod::UpdatedAt, filter);let results =- dynamic::dynamic_email_thread_cursor(&pool, &link_id, limit, &view, query, "").await?;+ dynamic::dynamic_email_thread_cursor(&pool, &link_id, limit, &view, query, "", None)+ .await?;let result_ids: std::collections::HashSet<String> =results.iter().map(|r| r.id.to_string()).collect();@@ -2220,7 +2269,8 @@ async fn test_dynamic_query_date_with_sender_filter(pool: Pool<Postgres>) -> anylet query = Query::new(None, SimpleSortMethod::UpdatedAt, filter);let results =- dynamic::dynamic_email_thread_cursor(&pool, &link_id, limit, &view, query, "").await?;+ dynamic::dynamic_email_thread_cursor(&pool, &link_id, limit, &view, query, "", None)+ .await?;let result_ids: std::collections::HashSet<String> =results.iter().map(|r| r.id.to_string()).collect();@@ -2269,7 +2319,8 @@ async fn test_dynamic_query_date_with_inbox_view(pool: Pool<Postgres>) -> anyhowlet query = Query::new(None, SimpleSortMethod::UpdatedAt, filter);let results =- dynamic::dynamic_email_thread_cursor(&pool, &link_id, limit, &view, query, "").await?;+ dynamic::dynamic_email_thread_cursor(&pool, &link_id, limit, &view, query, "", None)+ .await?;let result_ids: std::collections::HashSet<String> =results.iter().map(|r| r.id.to_string()).collect();@@ -2331,7 +2382,8 @@ async fn test_dynamic_query_created_at_and_updated_at_combined(let query = Query::new(None, SimpleSortMethod::UpdatedAt, filter);let results =- dynamic::dynamic_email_thread_cursor(&pool, &link_id, limit, &view, query, "").await?;+ dynamic::dynamic_email_thread_cursor(&pool, &link_id, limit, &view, query, "", None)+ .await?;let result_ids: std::collections::HashSet<String> =results.iter().map(|r| r.id.to_string()).collect();diff --git a/rust/cloud-storage/email/src/outbound/email_pg_repo/test/mod.rs b/rust/cloud-storage/email/src/outbound/email_pg_repo/test/mod.rsindex da85c9aa16..661bed560c 100644--- a/rust/cloud-storage/email/src/outbound/email_pg_repo/test/mod.rs+++ b/rust/cloud-storage/email/src/outbound/email_pg_repo/test/mod.rs@@ -4,6 +4,7 @@ mod labels;mod link;mod message;mod preview;+mod team_scope_dynamic_query;mod thread;mod thread_labels;diff --git a/rust/cloud-storage/email/src/outbound/email_pg_repo/test/team_scope_dynamic_query.rs b/rust/cloud-storage/email/src/outbound/email_pg_repo/test/team_scope_dynamic_query.rsnew file mode 100644index 0000000000..3c403d5678--- /dev/null+++ b/rust/cloud-storage/email/src/outbound/email_pg_repo/test/team_scope_dynamic_query.rs@@ -0,0 +1,721 @@+//! DB-backed tests for team-scoped dynamic email queries.+//!+//! These exercise the changes that wire `team_id: Option<Uuid>` from the+//! soup/email service down through `resolve_filters` and into the SQL+//! candidate-thread selection:+//!+//! • `dynamic/query.rs::push_thread_candidate_select` — `Owned` source's+//! `t.link_id = $link_id` swap to `t.link_id IN (links of team members)`+//! when `team_id` is `Some`.+//! • `dynamic/resolve.rs::resolve_filters` — contact_id resolution and+//! TRASH label resolution expand from one link to all team links.+//! • `dynamic/filters.rs::build_address_predicate_on_m` — emits+//! `m.from_contact_id = ANY($ids)` so messages in any team member's+//! mailbox match when the same address resolves to multiple contact+//! UUIDs (one per link).+//!+//! Fixture: `email/fixtures/email_dynamic_query_team_scope.sql`. Two team+//! members (Alice, Bob) and one non-member (Carol). Each link has its own+//! `email_contacts` row for `[email protected]` and its own TRASH label+//! UUID — both of which the new ANY-based resolution must cover.++use super::*;+use macro_user_id::cowlike::CowLike;++// === Constants matching the fixture ===++const ALICE_LINK_ID: &str = "a0000001-0000-0000-0000-000000000001";+const TEAM_ALPHA_ID: &str = "e0000001-0000-0000-0000-000000000001";++// Thread ids in the fixture+const TA1_ALICE_INBOX_ACME: &str = "22220001-0000-0000-0000-000000000001";+const TA2_ALICE_TRASH_ACME: &str = "22220001-0000-0000-0000-000000000002";+const TA3_ALICE_INBOX_OTHER: &str = "22220001-0000-0000-0000-000000000003";+const TB1_BOB_INBOX_ACME: &str = "22220002-0000-0000-0000-000000000001";+const TB2_BOB_TRASH_ACME: &str = "22220002-0000-0000-0000-000000000002";+const TB3_BOB_INBOX_ONLYBOB: &str = "22220002-0000-0000-0000-000000000003";+const TC1_CAROL_INBOX_ACME: &str = "22220003-0000-0000-0000-000000000001";++fn complete(s: &str) -> Email {+ Email::Complete(EmailStr::parse_from_str(s).unwrap().into_owned())+}++/// Run a query and return the set of result thread-id strings.+async fn run_and_collect_ids(+ pool: &Pool<Postgres>,+ filter: Arc<Expr<EmailLiteral>>,+ team_id: Option<Uuid>,+) -> anyhow::Result<std::collections::HashSet<String>> {+ let link_id = Uuid::parse_str(ALICE_LINK_ID)?;+ let view = PreviewView::StandardLabel(PreviewViewStandardLabel::Inbox);+ let limit = 100;+ let query = Query::new(None, SimpleSortMethod::UpdatedAt, filter);++ let results = dynamic::dynamic_email_thread_cursor(+ pool,+ &link_id,+ limit,+ &view,+ query,+ "macro|[email protected]",+ team_id,+ )+ .await?;++ Ok(results.into_iter().map(|r| r.id.to_string()).collect())+}++// =====================================================================+// 1. Regression check: team_scope OFF still only returns the caller's link.+// =====================================================================++#[sqlx::test(+ migrator = "MACRO_DB_MIGRATIONS",+ fixtures(+ path = "../../../../fixtures",+ scripts("email_dynamic_query_team_scope")+ )+)]+async fn team_scope_off_returns_only_callers_link(pool: Pool<Postgres>) -> anyhow::Result<()> {+ // Broad partial filter that matches both "[email protected]" and+ // "[email protected]" (their email_address strings contain "com").+ let filter = Arc::new(Expr::Literal(EmailLiteral::Sender(Email::Partial(+ "com".to_string(),+ ))));++ let ids = run_and_collect_ids(&pool, filter, None).await?;++ // Alice should see her two inbox threads (ta1, ta3). Her TRASH (ta2)+ // is excluded. No bob or carol threads.+ assert!(+ ids.contains(TA1_ALICE_INBOX_ACME),+ "alice's inbox acme thread should appear"+ );+ assert!(+ ids.contains(TA3_ALICE_INBOX_OTHER),+ "alice's inbox other thread should appear"+ );+ assert!(+ !ids.contains(TA2_ALICE_TRASH_ACME),+ "alice's TRASHED thread must not appear"+ );+ assert!(+ !ids.contains(TB1_BOB_INBOX_ACME),+ "bob's thread must not appear without team_scope"+ );+ assert!(+ !ids.contains(TC1_CAROL_INBOX_ACME),+ "carol's thread must not appear"+ );+ assert_eq!(ids.len(), 2, "expected exactly 2 threads, got: {:?}", ids);++ Ok(())+}++// =====================================================================+// 2. team_scope expands `Owned` to every team-member link.+// =====================================================================++#[sqlx::test(+ migrator = "MACRO_DB_MIGRATIONS",+ fixtures(+ path = "../../../../fixtures",+ scripts("email_dynamic_query_team_scope")+ )+)]+async fn team_scope_returns_all_team_member_threads(pool: Pool<Postgres>) -> anyhow::Result<()> {+ let team_id = Uuid::parse_str(TEAM_ALPHA_ID)?;+ // Broad partial match — should hit every acme/elsewhere thread on team+ // links (alice + bob), TRASH excluded, carol excluded.+ let filter = Arc::new(Expr::Literal(EmailLiteral::Sender(Email::Partial(+ "com".to_string(),+ ))));++ let ids = run_and_collect_ids(&pool, filter, Some(team_id)).await?;++ assert!(ids.contains(TA1_ALICE_INBOX_ACME));+ assert!(ids.contains(TA3_ALICE_INBOX_OTHER));+ assert!(ids.contains(TB1_BOB_INBOX_ACME));+ assert!(ids.contains(TB3_BOB_INBOX_ONLYBOB));+ assert!(+ !ids.contains(TA2_ALICE_TRASH_ACME),+ "alice's TRASHED must not appear"+ );+ assert!(+ !ids.contains(TB2_BOB_TRASH_ACME),+ "bob's TRASHED must not appear"+ );+ assert!(+ !ids.contains(TC1_CAROL_INBOX_ACME),+ "carol is not on the team"+ );+ assert_eq!(+ ids.len(),+ 4,+ "expected 4 team-member inbox threads, got: {:?}",+ ids+ );++ Ok(())+}++// =====================================================================+// 3. team_scope + `Sender(Domain(...))` filters across team links.+// =====================================================================++#[sqlx::test(+ migrator = "MACRO_DB_MIGRATIONS",+ fixtures(+ path = "../../../../fixtures",+ scripts("email_dynamic_query_team_scope")+ )+)]+async fn team_scope_with_domain_filter(pool: Pool<Postgres>) -> anyhow::Result<()> {+ let team_id = Uuid::parse_str(TEAM_ALPHA_ID)?;+ let filter = Arc::new(Expr::Literal(EmailLiteral::Sender(Email::Domain(+ "acme.com".to_string(),+ ))));++ let ids = run_and_collect_ids(&pool, filter, Some(team_id)).await?;++ // Both alice's and bob's acme inbox threads — that's it.+ assert!(ids.contains(TA1_ALICE_INBOX_ACME));+ assert!(ids.contains(TB1_BOB_INBOX_ACME));+ assert!(+ !ids.contains(TA3_ALICE_INBOX_OTHER),+ "non-acme sender must not match"+ );+ assert!(!ids.contains(TA2_ALICE_TRASH_ACME), "alice TRASH excluded");+ assert!(!ids.contains(TB2_BOB_TRASH_ACME), "bob TRASH excluded");+ assert!(!ids.contains(TC1_CAROL_INBOX_ACME), "carol excluded");+ assert_eq!(ids.len(), 2, "expected 2 acme threads, got: {:?}", ids);++ Ok(())+}++// =====================================================================+// 4. team_scope + `Sender(Complete(...))` resolves the address to ALL+// matching contact_ids across team links, not just the caller's link.+//+// This is the headline fix from option 2 — the same address has a+// different contact_id in alice's link vs bob's link, and the predicate+// must `= ANY($ids)` across both.+// =====================================================================++#[sqlx::test(+ migrator = "MACRO_DB_MIGRATIONS",+ fixtures(+ path = "../../../../fixtures",+ scripts("email_dynamic_query_team_scope")+ )+)]+async fn team_scope_with_complete_sender_resolves_across_links(+ pool: Pool<Postgres>,+) -> anyhow::Result<()> {+ let team_id = Uuid::parse_str(TEAM_ALPHA_ID)?;+ let filter = Arc::new(Expr::Literal(EmailLiteral::Sender(complete(+ "[email protected]",+ ))));++ let ids = run_and_collect_ids(&pool, filter, Some(team_id)).await?;++ // Bob's message references the bob_link contact_id, alice's message+ // references the alice_link contact_id. Both must match via ANY($ids).+ assert!(+ ids.contains(TA1_ALICE_INBOX_ACME),+ "alice's [email protected] thread must match (alice_link contact_id)"+ );+ assert!(+ ids.contains(TB1_BOB_INBOX_ACME),+ "bob's [email protected] thread must match (bob_link contact_id)"+ );+ assert!(+ !ids.contains(TA3_ALICE_INBOX_OTHER),+ "[email protected] is not [email protected]"+ );+ assert!(!ids.contains(TA2_ALICE_TRASH_ACME), "alice TRASH excluded");+ assert!(!ids.contains(TB2_BOB_TRASH_ACME), "bob TRASH excluded");+ assert!(+ !ids.contains(TC1_CAROL_INBOX_ACME),+ "carol excluded — not on team"+ );+ assert_eq!(ids.len(), 2, "expected 2 threads, got: {:?}", ids);++ Ok(())+}++// =====================================================================+// 5. team_scope's TRASH exclusion covers every team link's TRASH label.+// Each link has a different TRASH label UUID; the multi-id ANY probe+// must exclude trashed threads in every link, not just the caller's.+// =====================================================================++#[sqlx::test(+ migrator = "MACRO_DB_MIGRATIONS",+ fixtures(+ path = "../../../../fixtures",+ scripts("email_dynamic_query_team_scope")+ )+)]+async fn team_scope_excludes_trash_in_every_team_link(pool: Pool<Postgres>) -> anyhow::Result<()> {+ let team_id = Uuid::parse_str(TEAM_ALPHA_ID)?;+ // Match all acme threads across team links.+ let filter = Arc::new(Expr::Literal(EmailLiteral::Sender(Email::Domain(+ "acme.com".to_string(),+ ))));++ let ids = run_and_collect_ids(&pool, filter, Some(team_id)).await?;++ // ta2 (alice's TRASH) and tb2 (bob's TRASH) must NOT appear, even+ // though both message senders match the domain filter. Each link's+ // TRASH label has a different UUID — the test fails if the predicate+ // only excludes one link's TRASH ids.+ assert!(+ !ids.contains(TA2_ALICE_TRASH_ACME),+ "alice's TRASH excluded across team links"+ );+ assert!(+ !ids.contains(TB2_BOB_TRASH_ACME),+ "bob's TRASH excluded across team links"+ );+ // Sanity: the non-trashed acme threads still appear.+ assert!(ids.contains(TA1_ALICE_INBOX_ACME));+ assert!(ids.contains(TB1_BOB_INBOX_ACME));++ Ok(())+}++// =====================================================================+// 6. team_scope short-circuits when the Complete address has no matching+// contact in any team link (no rows in `contact_ids` map).+// =====================================================================++#[sqlx::test(+ migrator = "MACRO_DB_MIGRATIONS",+ fixtures(+ path = "../../../../fixtures",+ scripts("email_dynamic_query_team_scope")+ )+)]+async fn team_scope_with_unknown_complete_sender_short_circuits(+ pool: Pool<Postgres>,+) -> anyhow::Result<()> {+ let team_id = Uuid::parse_str(TEAM_ALPHA_ID)?;+ // Address not in any team link's email_contacts.+ let filter = Arc::new(Expr::Literal(EmailLiteral::Sender(complete(+ "[email protected]",+ ))));++ let ids = run_and_collect_ids(&pool, filter, Some(team_id)).await?;++ assert!(+ ids.is_empty(),+ "no team link has a contact row for [email protected], query must short-circuit; got: {:?}",+ ids+ );++ Ok(())+}++// =====================================================================+// 7. Caller is NOT on the team — but team_id is supplied anyway (e.g. a+// test scaffold or buggy caller bypassing soup's 403 check). Defensive+// check: the SQL still works, queries the team's mailboxes, and the+// caller's own non-team threads do NOT bleed in.+//+// Here we use carol's link_id as the caller — she's not on Team Alpha.+// The Owned source resolves to team Alpha's links (alice + bob), so+// carol's own thread (tc1) must NOT appear in the result.+// =====================================================================++#[sqlx::test(+ migrator = "MACRO_DB_MIGRATIONS",+ fixtures(+ path = "../../../../fixtures",+ scripts("email_dynamic_query_team_scope")+ )+)]+async fn team_scope_uses_team_mailboxes_not_caller_link(+ pool: Pool<Postgres>,+) -> anyhow::Result<()> {+ let team_id = Uuid::parse_str(TEAM_ALPHA_ID)?;+ let carol_link = Uuid::parse_str("a0000003-0000-0000-0000-000000000003")?;+ let view = PreviewView::StandardLabel(PreviewViewStandardLabel::Inbox);+ let filter = Arc::new(Expr::Literal(EmailLiteral::Sender(Email::Domain(+ "acme.com".to_string(),+ ))));+ let query = Query::new(None, SimpleSortMethod::UpdatedAt, filter);++ let results = dynamic::dynamic_email_thread_cursor(+ &pool,+ &carol_link,+ 100,+ &view,+ query,+ "macro|[email protected]",+ Some(team_id),+ )+ .await?;+ let ids: std::collections::HashSet<String> =+ results.into_iter().map(|r| r.id.to_string()).collect();++ assert!(+ !ids.contains(TC1_CAROL_INBOX_ACME),+ "carol's own thread must not leak in"+ );+ assert!(+ ids.contains(TA1_ALICE_INBOX_ACME),+ "team's mailbox content is returned"+ );+ assert!(+ ids.contains(TB1_BOB_INBOX_ACME),+ "team's mailbox content is returned"+ );++ Ok(())+}++// =====================================================================+// 8. Recipient (TO) under team_scope resolves across team links. The same+// address has one `email_contacts` row per link (different UUIDs); the+// `mr.contact_id = ANY($ids)` predicate must match the recipient row+// that points at the per-link contact row.+// =====================================================================++#[sqlx::test(+ migrator = "MACRO_DB_MIGRATIONS",+ fixtures(+ path = "../../../../fixtures",+ scripts("email_dynamic_query_team_scope")+ )+)]+async fn team_scope_with_complete_recipient_resolves_across_links(+ pool: Pool<Postgres>,+) -> anyhow::Result<()> {+ let team_id = Uuid::parse_str(TEAM_ALPHA_ID)?;+ let filter = Arc::new(Expr::Literal(EmailLiteral::Recipient(complete(+ "[email protected]",+ ))));++ let ids = run_and_collect_ids(&pool, filter, Some(team_id)).await?;++ // ta1 and tb1 both have [email protected] — but resolved to+ // different per-link contact UUIDs (c0000005 vs c0000008).+ assert!(ids.contains(TA1_ALICE_INBOX_ACME));+ assert!(ids.contains(TB1_BOB_INBOX_ACME));+ assert!(+ !ids.contains(TB3_BOB_INBOX_ONLYBOB),+ "tb3 has no recipient rows"+ );+ assert!(!ids.contains(TC1_CAROL_INBOX_ACME), "carol excluded");+ assert_eq!(ids.len(), 2, "expected 2 threads, got: {:?}", ids);++ Ok(())+}++// =====================================================================+// 9. CC across team links — same shape as #8 against the CC recipient_type.+// =====================================================================++#[sqlx::test(+ migrator = "MACRO_DB_MIGRATIONS",+ fixtures(+ path = "../../../../fixtures",+ scripts("email_dynamic_query_team_scope")+ )+)]+async fn team_scope_with_complete_cc_resolves_across_links(+ pool: Pool<Postgres>,+) -> anyhow::Result<()> {+ let team_id = Uuid::parse_str(TEAM_ALPHA_ID)?;+ let filter = Arc::new(Expr::Literal(EmailLiteral::Cc(complete(+ "[email protected]",+ ))));++ let ids = run_and_collect_ids(&pool, filter, Some(team_id)).await?;++ assert!(ids.contains(TA1_ALICE_INBOX_ACME));+ assert!(ids.contains(TB1_BOB_INBOX_ACME));+ assert_eq!(ids.len(), 2, "expected 2 threads, got: {:?}", ids);++ Ok(())+}++// =====================================================================+// 10. BCC across team links — same shape, BCC recipient_type.+// =====================================================================++#[sqlx::test(+ migrator = "MACRO_DB_MIGRATIONS",+ fixtures(+ path = "../../../../fixtures",+ scripts("email_dynamic_query_team_scope")+ )+)]+async fn team_scope_with_complete_bcc_resolves_across_links(+ pool: Pool<Postgres>,+) -> anyhow::Result<()> {+ let team_id = Uuid::parse_str(TEAM_ALPHA_ID)?;+ let filter = Arc::new(Expr::Literal(EmailLiteral::Bcc(complete(+ "[email protected]",+ ))));++ let ids = run_and_collect_ids(&pool, filter, Some(team_id)).await?;++ assert!(ids.contains(TA1_ALICE_INBOX_ACME));+ assert!(ids.contains(TB1_BOB_INBOX_ACME));+ assert_eq!(ids.len(), 2, "expected 2 threads, got: {:?}", ids);++ Ok(())+}++// =====================================================================+// 11. NOT operator under team_scope with an unresolved Complete sender.+// `fold_unresolved` reduces the inner literal to `Some(false)`, then+// `Not(Some(false)) -> Some(true)` — which is *not* a `Some(false)`+// constant, so `can_short_circuit` returns false and the query runs.+// The result should be every team-member inbox thread.+// =====================================================================++#[sqlx::test(+ migrator = "MACRO_DB_MIGRATIONS",+ fixtures(+ path = "../../../../fixtures",+ scripts("email_dynamic_query_team_scope")+ )+)]+async fn team_scope_not_unresolved_sender_does_not_short_circuit(+ pool: Pool<Postgres>,+) -> anyhow::Result<()> {+ let team_id = Uuid::parse_str(TEAM_ALPHA_ID)?;+ // No team link has a contact row for [email protected], so the inner+ // literal folds to FALSE. NOT FALSE = TRUE — the query proceeds and+ // returns every team-member inbox thread that isn't TRASHED.+ let filter = Arc::new(Expr::is_not(Expr::Literal(EmailLiteral::Sender(complete(+ "[email protected]",+ )))));++ let ids = run_and_collect_ids(&pool, filter, Some(team_id)).await?;++ assert!(ids.contains(TA1_ALICE_INBOX_ACME));+ assert!(ids.contains(TA3_ALICE_INBOX_OTHER));+ assert!(ids.contains(TB1_BOB_INBOX_ACME));+ assert!(ids.contains(TB3_BOB_INBOX_ONLYBOB));+ assert!(!ids.contains(TA2_ALICE_TRASH_ACME), "TRASH excluded");+ assert!(!ids.contains(TB2_BOB_TRASH_ACME), "TRASH excluded");+ assert!(!ids.contains(TC1_CAROL_INBOX_ACME), "carol excluded");+ assert_eq!(+ ids.len(),+ 4,+ "NOT of unresolved should not short-circuit, got: {:?}",+ ids+ );++ Ok(())+}++// =====================================================================+// 12. Asymmetric contact rows: only Bob has `[email protected]` as a+// contact. Resolution returns a single contact_id; the ANY($ids)+// predicate with a 1-element array still matches correctly, and only+// Bob's thread comes back.+// =====================================================================++#[sqlx::test(+ migrator = "MACRO_DB_MIGRATIONS",+ fixtures(+ path = "../../../../fixtures",+ scripts("email_dynamic_query_team_scope")+ )+)]+async fn team_scope_with_asymmetric_complete_sender(pool: Pool<Postgres>) -> anyhow::Result<()> {+ let team_id = Uuid::parse_str(TEAM_ALPHA_ID)?;+ let filter = Arc::new(Expr::Literal(EmailLiteral::Sender(complete(+ "[email protected]",+ ))));++ let ids = run_and_collect_ids(&pool, filter, Some(team_id)).await?;++ assert!(ids.contains(TB3_BOB_INBOX_ONLYBOB));+ assert!(+ !ids.contains(TA1_ALICE_INBOX_ACME),+ "alice has no such contact"+ );+ assert!(!ids.contains(TB1_BOB_INBOX_ACME), "different sender");+ assert_eq!(ids.len(), 1, "expected exactly tb3, got: {:?}", ids);++ Ok(())+}++// =====================================================================+// 13. OR of one known and one unknown Complete sender. The unknown branch+// folds to FALSE via `fold_unresolved`; the OR collapses to just the+// known branch's results. Verifies short-circuit + multi-id ANY+// resolution compose correctly under team_scope.+// =====================================================================++#[sqlx::test(+ migrator = "MACRO_DB_MIGRATIONS",+ fixtures(+ path = "../../../../fixtures",+ scripts("email_dynamic_query_team_scope")+ )+)]+async fn team_scope_or_of_known_and_unknown_complete_senders(+ pool: Pool<Postgres>,+) -> anyhow::Result<()> {+ let team_id = Uuid::parse_str(TEAM_ALPHA_ID)?;+ let filter = Arc::new(Expr::or(+ Expr::Literal(EmailLiteral::Sender(complete("[email protected]"))),+ Expr::Literal(EmailLiteral::Sender(complete("[email protected]"))),+ ));++ let ids = run_and_collect_ids(&pool, filter, Some(team_id)).await?;++ // Known branch resolves to multi-id; unknown branch collapses to FALSE.+ // OR result = matches of the known branch.+ assert!(ids.contains(TA1_ALICE_INBOX_ACME));+ assert!(ids.contains(TB1_BOB_INBOX_ACME));+ assert!(+ !ids.contains(TB3_BOB_INBOX_ONLYBOB),+ "bob-only is a different address"+ );+ assert_eq!(ids.len(), 2, "expected 2 threads, got: {:?}", ids);++ Ok(())+}++// =====================================================================+// 14. Composed AND of two address kinds (Domain sender + Domain+// recipient). Threads must satisfy BOTH constraints. Exercises the+// intersection of the candidate-thread CTE pushdown across address+// kinds under team_scope.+// =====================================================================++#[sqlx::test(+ migrator = "MACRO_DB_MIGRATIONS",+ fixtures(+ path = "../../../../fixtures",+ scripts("email_dynamic_query_team_scope")+ )+)]+async fn team_scope_composed_and_sender_domain_and_recipient_domain(+ pool: Pool<Postgres>,+) -> anyhow::Result<()> {+ let team_id = Uuid::parse_str(TEAM_ALPHA_ID)?;+ let filter = Arc::new(Expr::and(+ Expr::Literal(EmailLiteral::Sender(Email::Domain("acme.com".to_string()))),+ Expr::Literal(EmailLiteral::Recipient(Email::Domain(+ "elsewhere.com".to_string(),+ ))),+ ));++ let ids = run_and_collect_ids(&pool, filter, Some(team_id)).await?;++ // ta1 and tb1 both have sender@acme + [email protected].+ // tb3 is from [email protected] (sender doesn't match acme).+ // tc1 (carol) is excluded by team membership.+ // tb2 / ta2 are TRASHED.+ assert!(ids.contains(TA1_ALICE_INBOX_ACME));+ assert!(ids.contains(TB1_BOB_INBOX_ACME));+ assert!(!ids.contains(TB3_BOB_INBOX_ONLYBOB));+ assert!(!ids.contains(TC1_CAROL_INBOX_ACME));+ assert_eq!(ids.len(), 2, "expected 2 threads, got: {:?}", ids);++ Ok(())+}++// =====================================================================+// 15. Cursor-based pagination under team_scope: result set spans multiple+// team links. Page 1 + Page 2 must cover all 4 team-member inbox+// threads with no overlap and no missing rows.+// =====================================================================++#[sqlx::test(+ migrator = "MACRO_DB_MIGRATIONS",+ fixtures(+ path = "../../../../fixtures",+ scripts("email_dynamic_query_team_scope")+ )+)]+async fn team_scope_pagination_across_team_links(pool: Pool<Postgres>) -> anyhow::Result<()> {+ let team_id = Uuid::parse_str(TEAM_ALPHA_ID)?;+ let link_id = Uuid::parse_str(ALICE_LINK_ID)?;+ let view = PreviewView::StandardLabel(PreviewViewStandardLabel::Inbox);+ let limit = 2;++ // Broad filter to hit all 4 team inbox threads.+ let filter_p1 = Arc::new(Expr::Literal(EmailLiteral::Sender(Email::Partial(+ "com".to_string(),+ ))));+ let query_p1 = Query::new(None, SimpleSortMethod::UpdatedAt, filter_p1);+ let page1 = dynamic::dynamic_email_thread_cursor(+ &pool,+ &link_id,+ limit,+ &view,+ query_p1,+ "macro|[email protected]",+ Some(team_id),+ )+ .await?;+ assert_eq!(+ page1.len(),+ 2,+ "page 1 should be full, got: {}",+ page1.len()+ );++ // Cursor from the tail of page 1.+ let last = page1.last().unwrap();+ let cursor_ts = last.sort_ts;+ let cursor_id = last.id;+ let filter_p2 = Arc::new(Expr::Literal(EmailLiteral::Sender(Email::Partial(+ "com".to_string(),+ ))));+ let filter_p2_cursor = Arc::new(Expr::Literal(EmailLiteral::Sender(Email::Partial(+ "com".to_string(),+ ))));+ let cursor = Cursor {+ id: cursor_id,+ limit: limit as usize,+ val: CursorVal {+ sort_type: SimpleSortMethod::UpdatedAt,+ last_val: cursor_ts,+ },+ filter: filter_p2_cursor,+ };+ let query_p2 = Query::new(Some(cursor), SimpleSortMethod::UpdatedAt, filter_p2);+ let page2 = dynamic::dynamic_email_thread_cursor(+ &pool,+ &link_id,+ limit,+ &view,+ query_p2,+ "macro|[email protected]",+ Some(team_id),+ )+ .await?;++ // Union of pages must equal all 4 team-member inbox threads exactly.+ let mut all_ids: std::collections::HashSet<String> = std::collections::HashSet::new();+ for r in page1.iter().chain(page2.iter()) {+ assert!(+ all_ids.insert(r.id.to_string()),+ "page overlap on id {}",+ r.id+ );+ }+ assert!(all_ids.contains(TA1_ALICE_INBOX_ACME));+ assert!(all_ids.contains(TA3_ALICE_INBOX_OTHER));+ assert!(all_ids.contains(TB1_BOB_INBOX_ACME));+ assert!(all_ids.contains(TB3_BOB_INBOX_ONLYBOB));+ assert_eq!(+ all_ids.len(),+ 4,+ "pages 1+2 must cover all 4 inbox threads, got: {:?}",+ all_ids+ );++ Ok(())+}diff --git a/rust/cloud-storage/email_service/Cargo.toml b/rust/cloud-storage/email_service/Cargo.tomlindex 38f46ace03..05afbc1604 100644--- a/rust/cloud-storage/email_service/Cargo.toml+++ b/rust/cloud-storage/email_service/Cargo.toml@@ -78,6 +78,7 @@ bytes = { workspace = true }chrono = { workspace = true }cloudfront_sign = { workspace = true }connection_gateway_client = { path = "../connection_gateway_client" }+crm = { path = "../crm" }document_storage_service_client = { path = "../document_storage_service_client" }doppleganger = { workspace = true }ego-tree = { workspace = true }diff --git a/rust/cloud-storage/email_service/src/api/context.rs b/rust/cloud-storage/email_service/src/api/context.rsindex 4fb69bcdff..cf77d6de86 100644--- a/rust/cloud-storage/email_service/src/api/context.rs+++ b/rust/cloud-storage/email_service/src/api/context.rs@@ -21,8 +21,12 @@ use std::sync::Arc;use system_properties::{PgSystemPropertiesRepository, SystemPropertiesServiceImpl};pub(crate) type EmailEntityAccessService = EntityAccessServiceImpl<PgAccessRepository>;-pub(crate) type EmailSvc =- EmailServiceImpl<EmailPgRepo, FrecencyQueryServiceImpl<FrecencyPgStorage>, sqs_client::SQS>;+pub(crate) type EmailSvc = EmailServiceImpl<+ EmailPgRepo,+ FrecencyQueryServiceImpl<FrecencyPgStorage>,+ sqs_client::SQS,+ crm::domain::service::CrmServiceImpl<crm::outbound::companies_repo::CompaniesRepositoryImpl>,+>;#[derive(Clone, FromRef)]pub(crate) struct ApiContext {diff --git a/rust/cloud-storage/email_service/src/main.rs b/rust/cloud-storage/email_service/src/main.rsindex aa8ecc96dd..95320485e6 100644--- a/rust/cloud-storage/email_service/src/main.rs+++ b/rust/cloud-storage/email_service/src/main.rs@@ -129,10 +129,14 @@ async fn main() -> anyhow::Result<()> {let sqs_client = Arc::new(sqs_client);let gmail_client = Arc::new(gmail_client);+ let crm_service = crm::domain::service::CrmServiceImpl::new(+ crm::outbound::companies_repo::CompaniesRepositoryImpl::new(db.clone()),+ );let email_service = EmailRouterState::new(EmailServiceImpl::new(EmailPgRepo::new(db.clone()),FrecencyQueryServiceImpl::new(FrecencyPgStorage::new(db.clone())),(*sqs_client).clone(),+ crm_service,config.sent_undo_delay_secs,));let entity_access_service = Arc::new(EntityAccessServiceImpl::new(PgAccessRepository::new(diff --git a/rust/cloud-storage/email_service/src/pubsub/inbox_sync/operations/upsert_message.rs b/rust/cloud-storage/email_service/src/pubsub/inbox_sync/operations/upsert_message.rsindex b32590f11c..803defe490 100644--- a/rust/cloud-storage/email_service/src/pubsub/inbox_sync/operations/upsert_message.rs+++ b/rust/cloud-storage/email_service/src/pubsub/inbox_sync/operations/upsert_message.rs@@ -614,6 +614,7 @@ async fn filter_notifiable_message(models_pagination::SimpleSortMethod::UpdatedAt,Some(Arc::new(signal_filter)),),+ team_id: None,};let previews = EmailPgRepo::new(ctx.db.clone())diff --git a/rust/cloud-storage/item_filters/src/ast.rs b/rust/cloud-storage/item_filters/src/ast.rsindex bde916d25f..7fb1037849 100644--- a/rust/cloud-storage/item_filters/src/ast.rs+++ b/rust/cloud-storage/item_filters/src/ast.rs@@ -79,6 +79,11 @@ pub enum ExpandErr {/// invalid API AST expansion#[error("invalid API AST expansion: {0}")]ApiAst(String),+ /// team_scope requires fully-qualified email addresses or domains+ #[error(+ "team_scope=true requires all sender/recipient/cc/bcc values to be a complete email address or domain; partial matches are not allowed"+ )]+ TeamScopeRequiresQualifiedEmail,}/// type alias for a maybe empty, cheaply cloneable ast literal treediff --git a/rust/cloud-storage/item_filters/src/ast/email.rs b/rust/cloud-storage/item_filters/src/ast/email.rsindex 92f8968498..852f4ac7ba 100644--- a/rust/cloud-storage/item_filters/src/ast/email.rs+++ b/rust/cloud-storage/item_filters/src/ast/email.rs@@ -8,10 +8,27 @@ use crate::{EmailFilters, SharedEmailFilter, ast::ExpandErr, ast::date::DateLite/// Possible email values in the ast#[derive(Debug, Clone, Serialize, Deserialize)]pub enum Email {- /// A string which is not a valid fully qualified email+ /// A string which is not a valid fully qualified email or domainPartial(String),/// a fully valid qualified [EmailStr]Complete(EmailStr<'static>),+ /// a bare domain (e.g. "acme.com"), no local part+ Domain(String),+}++/// Returns true if `s` looks like a bare domain: no `@`, at least two+/// dot-separated segments, each made of alphanumeric or `-` characters.+fn looks_like_domain(s: &str) -> bool {+ if s.is_empty() || s.contains('@') {+ return false;+ }+ let segments: Vec<&str> = s.split('.').collect();+ if segments.len() < 2 {+ return false;+ }+ segments+ .iter()+ .all(|seg| !seg.is_empty() && seg.chars().all(|c| c.is_ascii_alphanumeric() || c == '-'))}/// The literal type that can appear in the item filter ast@@ -37,6 +54,10 @@ pub enum EmailLiteral {NotificationSeen(bool),/// Controls whether shared email threads are included in results.Shared(SharedEmailFilter),+ /// Expand visibility to every teammate's mailbox. Results may include+ /// emails the requesting user is not a participant on, as long as at+ /// least one teammate is.+ TeamScope,/// When true, only include threads that have at least one message with an/// `.ics` calendar attachment (filename or `application/ics` mime type)./// When false, no constraint is applied.@@ -64,31 +85,43 @@ impl ExpandFrame<EmailLiteral> for EmailFilters {include_labels: _,exclude_labels: _,shared,+ team_scope,calendar_only,} = input;fn map_email(s: String) -> Email {- match EmailStr::parse_from_str(&s) {- Ok(e) => Email::Complete(e.into_owned()),- Err(_) => Email::Partial(s),+ if let Ok(e) = EmailStr::parse_from_str(&s) {+ return Email::Complete(e.into_owned());+ }+ if looks_like_domain(&s) {+ return Email::Domain(s);}+ Email::Partial(s)}- let sender_nodes = senders+ let mapped_senders: Vec<Email> = senders.into_iter().map(map_email).collect();+ let mapped_cc: Vec<Email> = cc.into_iter().map(map_email).collect();+ let mapped_bcc: Vec<Email> = bcc.into_iter().map(map_email).collect();+ let mapped_recipients: Vec<Email> = recipients.into_iter().map(map_email).collect();++ if team_scope+ && mapped_senders+ .iter()+ .chain(&mapped_cc)+ .chain(&mapped_bcc)+ .chain(&mapped_recipients)+ .any(|e| matches!(e, Email::Partial(_)))+ {+ return Err(ExpandErr::TeamScopeRequiresQualifiedEmail);+ }++ let sender_nodes = mapped_senders.into_iter()- .map(map_email).expand(EmailLiteral::Sender, Expr::or);- let cc_nodes = cc- .into_iter()- .map(map_email)- .expand(EmailLiteral::Cc, Expr::or);- let bcc_nodes = bcc- .into_iter()- .map(map_email)- .expand(EmailLiteral::Bcc, Expr::or);- let recipient_nodes = recipients+ let cc_nodes = mapped_cc.into_iter().expand(EmailLiteral::Cc, Expr::or);+ let bcc_nodes = mapped_bcc.into_iter().expand(EmailLiteral::Bcc, Expr::or);+ let recipient_nodes = mapped_recipients.into_iter()- .map(map_email).expand(EmailLiteral::Recipient, Expr::or);let thread_id_nodes = email_thread_ids@@ -112,6 +145,7 @@ impl ExpandFrame<EmailLiteral> for EmailFilters {} else {Some(Expr::Literal(EmailLiteral::Shared(shared)))};+ let team_scope_node = team_scope.then_some(Expr::Literal(EmailLiteral::TeamScope));let calendar_only_node = calendar_only.filter(|v| *v).map(|v| Expr::Literal(EmailLiteral::CalendarOnly(v)));@@ -127,6 +161,7 @@ impl ExpandFrame<EmailLiteral> for EmailFilters {notification_done_node,notification_seen_node,shared_node,+ team_scope_node,calendar_only_node,].into_iter()diff --git a/rust/cloud-storage/item_filters/src/lib.rs b/rust/cloud-storage/item_filters/src/lib.rsindex d104584a72..4ab5b8e258 100644--- a/rust/cloud-storage/item_filters/src/lib.rs+++ b/rust/cloud-storage/item_filters/src/lib.rs@@ -247,6 +247,14 @@ pub struct EmailFilters {#[serde(default, skip_serializing_if = "SharedEmailFilter::is_default")]pub shared: SharedEmailFilter,+ /// When true, expand visibility to every teammate's mailbox: results may+ /// include emails the requesting user is not a participant on, as long as+ /// at least one of their teammates is. Requires every sender/cc/bcc/recipient+ /// value to be a fully-qualified email address or a domain (no partial+ /// substring matches).+ #[serde(default, skip_serializing_if = "std::ops::Not::not")]+ pub team_scope: bool,+/// When `Some(true)`, only include threads that have at least one message/// with an iCalendar attachment (`.ics` filename or `application/ics` mime/// type). `Some(false)` and `None` apply no constraint.@@ -268,6 +276,7 @@ impl IsEmpty for EmailFilters {include_labels,exclude_labels,shared,+ team_scope,calendar_only,} = self;senders.is_empty()@@ -281,6 +290,7 @@ impl IsEmpty for EmailFilters {&& include_labels.is_empty()&& exclude_labels.is_empty()&& shared.is_default()+ && !team_scope&& !calendar_only.unwrap_or(false)}}diff --git a/rust/cloud-storage/justfile b/rust/cloud-storage/justfileindex 68558bc145..4cb95eed5d 100644--- a/rust/cloud-storage/justfile+++ b/rust/cloud-storage/justfile@@ -99,6 +99,7 @@ setup_test_envs:echo "DATABASE_URL={{ DATABASE_URL }}" >> ./entity_access_db_utils/.envecho "DATABASE_URL={{ DATABASE_URL }}" >> ./mcp_client/.envecho "DATABASE_URL={{ DATABASE_URL }}" >> ./document_storage_service/.env+ echo "DATABASE_URL={{ DATABASE_URL }}" >> ./crm/.envsetup_macrodb:just macro_db_client/create_dbdiff --git a/rust/cloud-storage/macro_db_client/migrations/20260512120000_crm_tables.down.sql b/rust/cloud-storage/macro_db_client/migrations/20260512120000_crm_tables.down.sqlnew file mode 100644index 0000000000..d6661b6935--- /dev/null+++ b/rust/cloud-storage/macro_db_client/migrations/20260512120000_crm_tables.down.sql@@ -0,0 +1,10 @@+DROP INDEX IF EXISTS crm_contacts_email_idx;+DROP INDEX IF EXISTS crm_contacts_company_id_idx;+DROP TABLE IF EXISTS crm_contacts;++DROP INDEX IF EXISTS crm_domains_domain_idx;+DROP INDEX IF EXISTS crm_domains_company_id_idx;+DROP TABLE IF EXISTS crm_domains;++DROP INDEX IF EXISTS crm_companies_team_id_idx;+DROP TABLE IF EXISTS crm_companies;diff --git a/rust/cloud-storage/macro_db_client/migrations/20260512120000_crm_tables.up.sql b/rust/cloud-storage/macro_db_client/migrations/20260512120000_crm_tables.up.sqlnew file mode 100644index 0000000000..154a50f266--- /dev/null+++ b/rust/cloud-storage/macro_db_client/migrations/20260512120000_crm_tables.up.sql@@ -0,0 +1,41 @@+CREATE TABLE IF NOT EXISTS crm_companies+(+ id UUID PRIMARY KEY NOT NULL DEFAULT gen_random_uuid(),+ team_id UUID NOT NULL REFERENCES team (id) ON DELETE CASCADE,+ name TEXT NOT NULL,+ email_sync BOOLEAN NOT NULL DEFAULT true,+ created_at TIMESTAMPTZ NOT NULL DEFAULT now()+);++CREATE INDEX IF NOT EXISTS crm_companies_team_id_idx+ ON crm_companies (team_id);++CREATE TABLE IF NOT EXISTS crm_domains+(+ id UUID PRIMARY KEY NOT NULL DEFAULT gen_random_uuid(),+ company_id UUID NOT NULL REFERENCES crm_companies (id) ON DELETE CASCADE,+ domain TEXT NOT NULL,+ created_at TIMESTAMPTZ NOT NULL DEFAULT now(),+ UNIQUE (company_id, domain)+);++CREATE INDEX IF NOT EXISTS crm_domains_company_id_idx+ ON crm_domains (company_id);++CREATE INDEX IF NOT EXISTS crm_domains_domain_idx+ ON crm_domains (domain);++CREATE TABLE IF NOT EXISTS crm_contacts+(+ id UUID PRIMARY KEY NOT NULL DEFAULT gen_random_uuid(),+ company_id UUID NOT NULL REFERENCES crm_companies (id) ON DELETE CASCADE,+ email TEXT NOT NULL,+ created_at TIMESTAMPTZ NOT NULL DEFAULT now(),+ UNIQUE (company_id, email)+);++CREATE INDEX IF NOT EXISTS crm_contacts_company_id_idx+ ON crm_contacts (company_id);++CREATE INDEX IF NOT EXISTS crm_contacts_email_idx+ ON crm_contacts (email);diff --git a/rust/cloud-storage/macro_db_client/migrations/20260512130000_email_contacts_domain_index.sql b/rust/cloud-storage/macro_db_client/migrations/20260512130000_email_contacts_domain_index.sqlnew file mode 100644index 0000000000..be7e6da902--- /dev/null+++ b/rust/cloud-storage/macro_db_client/migrations/20260512130000_email_contacts_domain_index.sql@@ -0,0 +1,11 @@+-- no-transaction++-- Supports exact-domain matching for `Email::Domain(...)` filters in the+-- dynamic email-thread query. The dynamic predicate is+-- `LOWER(SPLIT_PART(c.email_address, '@', 2)) = $domain`, which without this+-- index degrades to a sequential scan over `email_contacts`. The previous+-- ILIKE `%domain%` predicate rode the trigram index but was both wrong+-- (substring false positives like `macro.community` matching `macro.com`)+-- and expensive when the match set was wide.+CREATE INDEX CONCURRENTLY IF NOT EXISTS idx_email_contacts_email_domain+ ON email_contacts (LOWER(SPLIT_PART(email_address, '@', 2)));diff --git a/rust/cloud-storage/mcp_service/Cargo.toml b/rust/cloud-storage/mcp_service/Cargo.tomlindex bba5225b88..0336383a85 100644--- a/rust/cloud-storage/mcp_service/Cargo.toml+++ b/rust/cloud-storage/mcp_service/Cargo.toml@@ -15,6 +15,7 @@ axum = { workspace = true, features = ["tower-log"] }call = { path = "../call", default-features = false, features = ["ports"] }chat = { path = "../chat", features = ["ai_tools", "outbound"] }comms = { path = "../comms", features = ["outbound"] }+crm = { path = "../crm" }documents = { path = "../documents", features = ["ai_tools"] }email = { path = "../email", features = ["outbound"] }email_service_client = { path = "../email_service_client" }diff --git a/rust/cloud-storage/mcp_service/src/context.rs b/rust/cloud-storage/mcp_service/src/context.rsindex a130fddb79..e19ed74677 100644--- a/rust/cloud-storage/mcp_service/src/context.rs+++ b/rust/cloud-storage/mcp_service/src/context.rs@@ -160,10 +160,14 @@ async fn build_tool_context(let frecency_storage = FrecencyPgStorage::new(db.clone());let frecency_service = FrecencyQueryServiceImpl::new(frecency_storage.clone());+ let crm_service = crm::domain::service::CrmServiceImpl::new(+ crm::outbound::companies_repo::CompaniesRepositoryImpl::new(db.clone()),+ );let email_service = EmailServiceImpl::new(EmailPgRepo::new(db.clone()),frecency_service.clone(),email::domain::ports::NoOpEnqueuer,+ crm_service.clone(),0,);let channels_service = ChannelServiceImpl::new(@@ -249,6 +253,7 @@ async fn build_tool_context(EmailPgRepo::new(db.clone()),FrecencyQueryServiceImpl::new(FrecencyPgStorage::new(db.clone())),sqs_client,+ crm_service.clone(),0,)),Arc::new(email::domain::ports::NoOpGmailTokenProvider),diff --git a/rust/cloud-storage/memory/Cargo.toml b/rust/cloud-storage/memory/Cargo.tomlindex 45fd71163d..bc17d99019 100644--- a/rust/cloud-storage/memory/Cargo.toml+++ b/rust/cloud-storage/memory/Cargo.toml@@ -30,6 +30,7 @@ utoipa = { workspace = true }# For building ToolServiceContextcomms = { path = "../comms" }+crm = { path = "../crm" }documents = { path = "../documents" }email = { path = "../email" }email_service_client = { path = "../email_service_client" }diff --git a/rust/cloud-storage/memory/src/context.rs b/rust/cloud-storage/memory/src/context.rsindex fd172ac191..26e115bac1 100644--- a/rust/cloud-storage/memory/src/context.rs+++ b/rust/cloud-storage/memory/src/context.rs@@ -68,10 +68,14 @@ pub async fn build_tool_service_context(// Soup servicelet frecency_storage = FrecencyPgStorage::new(pool.clone());let frecency_service = FrecencyQueryServiceImpl::new(frecency_storage.clone());+ let crm_service = crm::domain::service::CrmServiceImpl::new(+ crm::outbound::companies_repo::CompaniesRepositoryImpl::new(pool.clone()),+ );let email_service = EmailServiceImpl::new(EmailPgRepo::new(pool.clone()),frecency_service.clone(),email::domain::ports::NoOpEnqueuer,+ crm_service.clone(),0,);let channels_service = ChannelServiceImpl::new(@@ -147,6 +151,7 @@ pub async fn build_tool_service_context(EmailPgRepo::new(pool.clone()),FrecencyQueryServiceImpl::new(FrecencyPgStorage::new(pool.clone())),sqs_client,+ crm_service.clone(),0,)),Arc::new(email::domain::ports::NoOpGmailTokenProvider),diff --git a/rust/cloud-storage/soup/Cargo.toml b/rust/cloud-storage/soup/Cargo.tomlindex 9e059a1b0f..0bfd50a3a7 100644--- a/rust/cloud-storage/soup/Cargo.toml+++ b/rust/cloud-storage/soup/Cargo.toml@@ -29,7 +29,7 @@ axum = ["models_pagination/axum","models_soup/schema",]-inbound = ["email/inbound", "ports"]+inbound = ["email/inbound", "entity_access/inbound", "ports"]outbound = ["dep:readonly_pool", "dep:sqlx", "ports"]ports = ["dep:tokio", "frecency/ports"]@@ -44,10 +44,12 @@ call = { path = "../call", default-features = false, features = ["ports"] }chrono = { workspace = true }comms = { path = "../comms", default-features = false }cowlike = { path = "../cowlike" }+crm = { path = "../crm", default-features = false }document_sub_type = { path = "../document_sub_type" }doppleganger = { workspace = true, features = ["chrono", "uuid"] }either = { workspace = true }email = { path = "../email", features = ["ports"] }+entity_access = { path = "../entity_access", default-features = false }filter_ast = { path = "../filter_ast" }frecency = { path = "../frecency" }item_filters = { path = "../item_filters" }@@ -77,7 +79,6 @@ uuid = { workspace = true }[dev-dependencies]ai = { path = "../ai" }cool_asserts = "2"-entity_access = { path = "../entity_access" }filter_ast = { path = "../filter_ast" }frecency = { path = "../frecency", features = ["mock", "outbound"] }futures = { workspace = true }diff --git a/rust/cloud-storage/soup/examples/ai_tools_cli.rs b/rust/cloud-storage/soup/examples/ai_tools_cli.rsindex 5676c0556e..dc818911e6 100644--- a/rust/cloud-storage/soup/examples/ai_tools_cli.rs+++ b/rust/cloud-storage/soup/examples/ai_tools_cli.rs@@ -51,10 +51,14 @@ async fn main() {// Create the email service with real database connectionslet email_repo = EmailPgRepo::new(pool.clone());+ let crm_service = crm::domain::service::CrmServiceImpl::new(+ crm::outbound::companies_repo::CompaniesRepositoryImpl::new(pool.clone()),+ );let email_service = EmailServiceImpl::new(email_repo,frecency_service.clone(),email::domain::ports::NoOpEnqueuer,+ crm_service,0,);diff --git a/rust/cloud-storage/soup/src/domain/models.rs b/rust/cloud-storage/soup/src/domain/models.rsindex 94deb12acc..70078d5ca0 100644--- a/rust/cloud-storage/soup/src/domain/models.rs+++ b/rust/cloud-storage/soup/src/domain/models.rs@@ -8,6 +8,7 @@ pub use grouping::{use call::domain::models::GetCallRecordsRequest;use comms::domain::models::GetChannelsRequest;use email::domain::models::{GetEmailsRequest, PreviewView};+use entity_access::domain::models::{EntityAccessReceipt, MemberTeamRole};use frecency::domain::models::{AggregateFrecency, FrecencyQueryErr};use item_filters::{EntityFilters,@@ -270,8 +271,15 @@ impl<T> SoupRequest<T> {impl SoupRequest<Option<EntityFilterAst>> {/// take the parts of the [SoupRequest] that are only relevant to email- /// and move them into a [GetEmailsRequest] if it is possible to create one- pub(crate) fn build_email_request(&self) -> Option<GetEmailsRequest> {+ /// and move them into a [GetEmailsRequest] if it is possible to create one.+ ///+ /// `team_receipt` is forwarded onto the email request so the query layer+ /// can verify and use it when the email AST contains+ /// `EmailLiteral::TeamScope`.+ pub(crate) fn build_email_request(+ &self,+ team_receipt: Option<EntityAccessReceipt<MemberTeamRole>>,+ ) -> Option<GetEmailsRequest> {Some(GetEmailsRequest {view: self.email_preview_view.clone(),link_id: self.link_id?,@@ -296,6 +304,7 @@ impl SoupRequest<Option<EntityFilterAst>> {// we don't yet have sort by frecency implemented for emails yetSoupQuery::Frecency(_) => None,}?,+ team_receipt,})}diff --git a/rust/cloud-storage/soup/src/domain/ports.rs b/rust/cloud-storage/soup/src/domain/ports.rsindex d0ef12453c..161becea70 100644--- a/rust/cloud-storage/soup/src/domain/ports.rs+++ b/rust/cloud-storage/soup/src/domain/ports.rs@@ -3,6 +3,7 @@ use crate::domain::models::{SimpleSortRequest, SoupErr, SoupRequest,};use either::Either;+use entity_access::domain::models::{EntityAccessReceipt, MemberTeamRole};use models_pagination::{Frecency, PaginatedCursor, SimpleSortMethod};use models_soup::item::SoupItem;use serde::Serialize;@@ -55,9 +56,16 @@ pub type SoupOutput<T> = Either<>;pub trait SoupService: Send + Sync + 'static {+ /// Run a soup query for the authenticated user.+ ///+ /// `team_receipt` proves the user belongs to a team and may be used by+ /// filters that broaden visibility beyond the user's own mailboxes (e.g.+ /// `EmailLiteral::TeamScope`). Pass `None` when no team-scoped filter is+ /// active.fn get_user_soup<T>(&self,req: SoupRequest<T>,+ team_receipt: Option<EntityAccessReceipt<MemberTeamRole>>,) -> impl Future<Output = Result<SoupOutput<T>, SoupErr>> + SendwhereSoupRequest<T>: IntoSoupReqAst,diff --git a/rust/cloud-storage/soup/src/domain/service.rs b/rust/cloud-storage/soup/src/domain/service.rsindex 320a70c50f..a09e8fcff1 100644--- a/rust/cloud-storage/soup/src/domain/service.rs+++ b/rust/cloud-storage/soup/src/domain/service.rs@@ -15,6 +15,7 @@ use email::domain::{models::{EnrichedEmailThreadPreview, GetEmailsRequest},ports::EmailPreviewServiceReadOnly,};+use entity_access::domain::models::{EntityAccessReceipt, MemberTeamRole};use frecency::domain::{models::{AggregateId, FrecencyPageRequest, JoinFrecency},ports::FrecencyQueryService,@@ -406,8 +407,12 @@ whereC: ChannelsService,K: CallRecordQueryService,{- #[tracing::instrument(err, skip(self, req))]- async fn get_user_soup<R>(&self, req: SoupRequest<R>) -> Result<SoupOutput<R>, SoupErr>+ #[tracing::instrument(err, skip(self, req, team_receipt))]+ async fn get_user_soup<R>(+ &self,+ req: SoupRequest<R>,+ team_receipt: Option<EntityAccessReceipt<MemberTeamRole>>,+ ) -> Result<SoupOutput<R>, SoupErr>whereSoupRequest<R>: IntoSoupReqAst,R: Clone + Serialize + Send,@@ -416,7 +421,7 @@ wherelet req = req.into_ast()?;let limit = req.limit.clamp(20, 500);- let email_request = req.build_email_request();+ let email_request = req.build_email_request(team_receipt);let comms_request = req.build_comms_request();let call_request = req.build_call_request();diff --git a/rust/cloud-storage/soup/src/domain/service/tests.rs b/rust/cloud-storage/soup/src/domain/service/tests.rsindex aa53d9c457..6c0d8046bc 100644--- a/rust/cloud-storage/soup/src/domain/service/tests.rs+++ b/rust/cloud-storage/soup/src/domain/service/tests.rs@@ -175,19 +175,22 @@ async fn it_should_not_query_frecency() {NoopCommsService,NoopCallRecordQueryService,)- .get_user_soup(SoupRequest {- email_preview_view: PreviewView::StandardLabel(- email::domain::models::PreviewViewStandardLabel::Inbox,- ),- link_id: Some(Uuid::new_v4()),- soup_type: SoupType::UnExpanded,- limit: 0,- cursor: SoupQuery::new_sort_simple(- SimpleSortMethod::ViewedUpdated,- EntityFilters::default(),- ),- user: MacroUserIdStr::parse_from_str("macro|[email protected]").unwrap(),- })+ .get_user_soup(+ SoupRequest {+ email_preview_view: PreviewView::StandardLabel(+ email::domain::models::PreviewViewStandardLabel::Inbox,+ ),+ link_id: Some(Uuid::new_v4()),+ soup_type: SoupType::UnExpanded,+ limit: 0,+ cursor: SoupQuery::new_sort_simple(+ SimpleSortMethod::ViewedUpdated,+ EntityFilters::default(),+ ),+ user: MacroUserIdStr::parse_from_str("macro|[email protected]").unwrap(),+ },+ None,+ ).await.unwrap().type_erase();@@ -257,16 +260,19 @@ async fn it_should_query_frecency() {NoopCommsService,NoopCallRecordQueryService,)- .get_user_soup(SoupRequest {- email_preview_view: PreviewView::StandardLabel(- email::domain::models::PreviewViewStandardLabel::Inbox,- ),- link_id: Some(Uuid::new_v4()),- soup_type: SoupType::UnExpanded,- limit: u16::MAX,- cursor: SoupQuery::new_sort_frecency(Frecency, EntityFilters::default()),- user: MacroUserIdStr::parse_from_str("macro|[email protected]").unwrap(),- })+ .get_user_soup(+ SoupRequest {+ email_preview_view: PreviewView::StandardLabel(+ email::domain::models::PreviewViewStandardLabel::Inbox,+ ),+ link_id: Some(Uuid::new_v4()),+ soup_type: SoupType::UnExpanded,+ limit: u16::MAX,+ cursor: SoupQuery::new_sort_frecency(Frecency, EntityFilters::default()),+ user: MacroUserIdStr::parse_from_str("macro|[email protected]").unwrap(),+ },+ None,+ ).await.unwrap().type_erase();@@ -336,16 +342,19 @@ async fn it_should_sort_frecency_descending() {NoopCommsService,NoopCallRecordQueryService,)- .get_user_soup(SoupRequest {- email_preview_view: PreviewView::StandardLabel(- email::domain::models::PreviewViewStandardLabel::Inbox,- ),- link_id: Some(Uuid::new_v4()),- soup_type: SoupType::UnExpanded,- limit: u16::MAX,- cursor: SoupQuery::new_sort_frecency(Frecency, EntityFilters::default()),- user: MacroUserIdStr::parse_from_str("macro|[email protected]").unwrap(),- })+ .get_user_soup(+ SoupRequest {+ email_preview_view: PreviewView::StandardLabel(+ email::domain::models::PreviewViewStandardLabel::Inbox,+ ),+ link_id: Some(Uuid::new_v4()),+ soup_type: SoupType::UnExpanded,+ limit: u16::MAX,+ cursor: SoupQuery::new_sort_frecency(Frecency, EntityFilters::default()),+ user: MacroUserIdStr::parse_from_str("macro|[email protected]").unwrap(),+ },+ None,+ ).await.unwrap().type_erase();@@ -429,16 +438,19 @@ async fn frecency_should_fallback() {NoopCommsService,NoopCallRecordQueryService,)- .get_user_soup(SoupRequest {- email_preview_view: PreviewView::StandardLabel(- email::domain::models::PreviewViewStandardLabel::Inbox,- ),- link_id: Some(Uuid::new_v4()),- soup_type: SoupType::UnExpanded,- limit: 100,- cursor: SoupQuery::new_sort_frecency(Frecency, EntityFilters::default()),- user: MacroUserIdStr::parse_from_str("macro|[email protected]").unwrap(),- })+ .get_user_soup(+ SoupRequest {+ email_preview_view: PreviewView::StandardLabel(+ email::domain::models::PreviewViewStandardLabel::Inbox,+ ),+ link_id: Some(Uuid::new_v4()),+ soup_type: SoupType::UnExpanded,+ limit: 100,+ cursor: SoupQuery::new_sort_frecency(Frecency, EntityFilters::default()),+ user: MacroUserIdStr::parse_from_str("macro|[email protected]").unwrap(),+ },+ None,+ ).await.unwrap().unwrap_right();@@ -506,16 +518,19 @@ async fn frecency_should_paginate() {NoopCommsService,NoopCallRecordQueryService,)- .get_user_soup(SoupRequest {- email_preview_view: PreviewView::StandardLabel(- email::domain::models::PreviewViewStandardLabel::Inbox,- ),- link_id: Some(Uuid::new_v4()),- soup_type: SoupType::UnExpanded,- limit: 100,- cursor: SoupQuery::new_sort_frecency(Frecency, EntityFilters::default()),- user: MacroUserIdStr::parse_from_str("macro|[email protected]").unwrap(),- })+ .get_user_soup(+ SoupRequest {+ email_preview_view: PreviewView::StandardLabel(+ email::domain::models::PreviewViewStandardLabel::Inbox,+ ),+ link_id: Some(Uuid::new_v4()),+ soup_type: SoupType::UnExpanded,+ limit: 100,+ cursor: SoupQuery::new_sort_frecency(Frecency, EntityFilters::default()),+ user: MacroUserIdStr::parse_from_str("macro|[email protected]").unwrap(),+ },+ None,+ ).await.unwrap().unwrap_right();@@ -585,24 +600,27 @@ async fn frecency_should_resume_cursor() {NoopCommsService,NoopCallRecordQueryService,)- .get_user_soup(SoupRequest {- email_preview_view: PreviewView::StandardLabel(- email::domain::models::PreviewViewStandardLabel::Inbox,- ),- link_id: Some(Uuid::new_v4()),- soup_type: SoupType::UnExpanded,- limit: 100,- cursor: SoupQuery::new_cursor_frecency(CursorWithValAndFilter {- id: Uuid::from_u128(5),+ .get_user_soup(+ SoupRequest {+ email_preview_view: PreviewView::StandardLabel(+ email::domain::models::PreviewViewStandardLabel::Inbox,+ ),+ link_id: Some(Uuid::new_v4()),+ soup_type: SoupType::UnExpanded,limit: 100,- val: CursorVal {- sort_type: Frecency,- last_val: FrecencyValue::FrecencyScore(5.0),- },- filter: Default::default(),- }),- user: MacroUserIdStr::parse_from_str("macro|[email protected]").unwrap(),- })+ cursor: SoupQuery::new_cursor_frecency(CursorWithValAndFilter {+ id: Uuid::from_u128(5),+ limit: 100,+ val: CursorVal {+ sort_type: Frecency,+ last_val: FrecencyValue::FrecencyScore(5.0),+ },+ filter: Default::default(),+ }),+ user: MacroUserIdStr::parse_from_str("macro|[email protected]").unwrap(),+ },+ None,+ ).await.unwrap().unwrap_right();@@ -680,24 +698,27 @@ async fn frecency_fallback_cursor_should_resume() {NoopCommsService,NoopCallRecordQueryService,)- .get_user_soup(SoupRequest {- email_preview_view: PreviewView::StandardLabel(- email::domain::models::PreviewViewStandardLabel::Inbox,- ),- link_id: Some(Uuid::new_v4()),- soup_type: SoupType::UnExpanded,- limit: 100,- cursor: SoupQuery::new_cursor_frecency(CursorWithValAndFilter {- id: Uuid::from_u128(100),+ .get_user_soup(+ SoupRequest {+ email_preview_view: PreviewView::StandardLabel(+ email::domain::models::PreviewViewStandardLabel::Inbox,+ ),+ link_id: Some(Uuid::new_v4()),+ soup_type: SoupType::UnExpanded,limit: 100,- val: CursorVal {- sort_type: Frecency,- last_val: FrecencyValue::UpdatedAt(DateTime::default() + Days::new(5)),- },- filter: Default::default(),- }),- user: MacroUserIdStr::parse_from_str("macro|[email protected]").unwrap(),- })+ cursor: SoupQuery::new_cursor_frecency(CursorWithValAndFilter {+ id: Uuid::from_u128(100),+ limit: 100,+ val: CursorVal {+ sort_type: Frecency,+ last_val: FrecencyValue::UpdatedAt(DateTime::default() + Days::new(5)),+ },+ filter: Default::default(),+ }),+ user: MacroUserIdStr::parse_from_str("macro|[email protected]").unwrap(),+ },+ None,+ ).await.unwrap().unwrap_right();@@ -751,19 +772,22 @@ async fn cursor_should_return_simple_sort() {NoopCommsService,NoopCallRecordQueryService,)- .get_user_soup(SoupRequest {- email_preview_view: PreviewView::StandardLabel(- email::domain::models::PreviewViewStandardLabel::Inbox,- ),- link_id: Some(Uuid::new_v4()),- soup_type: SoupType::UnExpanded,- limit: 0,- cursor: SoupQuery::new_sort_simple(- SimpleSortMethod::ViewedUpdated,- EntityFilters::default(),- ),- user: MacroUserIdStr::parse_from_str("macro|[email protected]").unwrap(),- })+ .get_user_soup(+ SoupRequest {+ email_preview_view: PreviewView::StandardLabel(+ email::domain::models::PreviewViewStandardLabel::Inbox,+ ),+ link_id: Some(Uuid::new_v4()),+ soup_type: SoupType::UnExpanded,+ limit: 0,+ cursor: SoupQuery::new_sort_simple(+ SimpleSortMethod::ViewedUpdated,+ EntityFilters::default(),+ ),+ user: MacroUserIdStr::parse_from_str("macro|[email protected]").unwrap(),+ },+ None,+ ).await.unwrap();@@ -818,16 +842,19 @@ async fn cursor_should_return_frecency() {NoopCommsService,NoopCallRecordQueryService,)- .get_user_soup(SoupRequest {- email_preview_view: PreviewView::StandardLabel(- email::domain::models::PreviewViewStandardLabel::Inbox,- ),- link_id: Some(Uuid::new_v4()),- soup_type: SoupType::UnExpanded,- limit: 100,- cursor: SoupQuery::new_sort_frecency(Frecency, EntityFilters::default()),- user: MacroUserIdStr::parse_from_str("macro|[email protected]").unwrap(),- })+ .get_user_soup(+ SoupRequest {+ email_preview_view: PreviewView::StandardLabel(+ email::domain::models::PreviewViewStandardLabel::Inbox,+ ),+ link_id: Some(Uuid::new_v4()),+ soup_type: SoupType::UnExpanded,+ limit: 100,+ cursor: SoupQuery::new_sort_frecency(Frecency, EntityFilters::default()),+ user: MacroUserIdStr::parse_from_str("macro|[email protected]").unwrap(),+ },+ None,+ ).await.unwrap();@@ -875,19 +902,22 @@ async fn it_should_return_is_completed_true_for_completed_tasks() {NoopCommsService,NoopCallRecordQueryService,)- .get_user_soup(SoupRequest {- email_preview_view: PreviewView::StandardLabel(- email::domain::models::PreviewViewStandardLabel::Inbox,- ),- link_id: Some(Uuid::new_v4()),- soup_type: SoupType::UnExpanded,- limit: 0,- cursor: SoupQuery::new_sort_simple(- SimpleSortMethod::ViewedUpdated,- EntityFilters::default(),- ),- user: MacroUserIdStr::parse_from_str("macro|[email protected]").unwrap(),- })+ .get_user_soup(+ SoupRequest {+ email_preview_view: PreviewView::StandardLabel(+ email::domain::models::PreviewViewStandardLabel::Inbox,+ ),+ link_id: Some(Uuid::new_v4()),+ soup_type: SoupType::UnExpanded,+ limit: 0,+ cursor: SoupQuery::new_sort_simple(+ SimpleSortMethod::ViewedUpdated,+ EntityFilters::default(),+ ),+ user: MacroUserIdStr::parse_from_str("macro|[email protected]").unwrap(),+ },+ None,+ ).await.unwrap().type_erase();@@ -922,19 +952,22 @@ async fn it_should_return_is_completed_false_for_incomplete_tasks() {NoopCommsService,NoopCallRecordQueryService,)- .get_user_soup(SoupRequest {- email_preview_view: PreviewView::StandardLabel(- email::domain::models::PreviewViewStandardLabel::Inbox,- ),- link_id: Some(Uuid::new_v4()),- soup_type: SoupType::UnExpanded,- limit: 0,- cursor: SoupQuery::new_sort_simple(- SimpleSortMethod::ViewedUpdated,- EntityFilters::default(),- ),- user: MacroUserIdStr::parse_from_str("macro|[email protected]").unwrap(),- })+ .get_user_soup(+ SoupRequest {+ email_preview_view: PreviewView::StandardLabel(+ email::domain::models::PreviewViewStandardLabel::Inbox,+ ),+ link_id: Some(Uuid::new_v4()),+ soup_type: SoupType::UnExpanded,+ limit: 0,+ cursor: SoupQuery::new_sort_simple(+ SimpleSortMethod::ViewedUpdated,+ EntityFilters::default(),+ ),+ user: MacroUserIdStr::parse_from_str("macro|[email protected]").unwrap(),+ },+ None,+ ).await.unwrap().type_erase();@@ -969,19 +1002,22 @@ async fn it_should_return_is_completed_none_for_non_tasks() {NoopCommsService,NoopCallRecordQueryService,)- .get_user_soup(SoupRequest {- email_preview_view: PreviewView::StandardLabel(- email::domain::models::PreviewViewStandardLabel::Inbox,- ),- link_id: Some(Uuid::new_v4()),- soup_type: SoupType::UnExpanded,- limit: 0,- cursor: SoupQuery::new_sort_simple(- SimpleSortMethod::ViewedUpdated,- EntityFilters::default(),- ),- user: MacroUserIdStr::parse_from_str("macro|[email protected]").unwrap(),- })+ .get_user_soup(+ SoupRequest {+ email_preview_view: PreviewView::StandardLabel(+ email::domain::models::PreviewViewStandardLabel::Inbox,+ ),+ link_id: Some(Uuid::new_v4()),+ soup_type: SoupType::UnExpanded,+ limit: 0,+ cursor: SoupQuery::new_sort_simple(+ SimpleSortMethod::ViewedUpdated,+ EntityFilters::default(),+ ),+ user: MacroUserIdStr::parse_from_str("macro|[email protected]").unwrap(),+ },+ None,+ ).await.unwrap().type_erase();@@ -1028,19 +1064,22 @@ async fn it_should_preserve_is_completed_for_mixed_items() {NoopCommsService,NoopCallRecordQueryService,)- .get_user_soup(SoupRequest {- email_preview_view: PreviewView::StandardLabel(- email::domain::models::PreviewViewStandardLabel::Inbox,- ),- link_id: Some(Uuid::new_v4()),- soup_type: SoupType::UnExpanded,- limit: 0,- cursor: SoupQuery::new_sort_simple(- SimpleSortMethod::ViewedUpdated,- EntityFilters::default(),- ),- user: MacroUserIdStr::parse_from_str("macro|[email protected]").unwrap(),- })+ .get_user_soup(+ SoupRequest {+ email_preview_view: PreviewView::StandardLabel(+ email::domain::models::PreviewViewStandardLabel::Inbox,+ ),+ link_id: Some(Uuid::new_v4()),+ soup_type: SoupType::UnExpanded,+ limit: 0,+ cursor: SoupQuery::new_sort_simple(+ SimpleSortMethod::ViewedUpdated,+ EntityFilters::default(),+ ),+ user: MacroUserIdStr::parse_from_str("macro|[email protected]").unwrap(),+ },+ None,+ ).await.unwrap().type_erase();@@ -1106,16 +1145,19 @@ async fn it_should_preserve_is_completed_in_by_ids_queries() {NoopCommsService,NoopCallRecordQueryService,)- .get_user_soup(SoupRequest {- email_preview_view: PreviewView::StandardLabel(- email::domain::models::PreviewViewStandardLabel::Inbox,- ),- link_id: Some(Uuid::new_v4()),- soup_type: SoupType::UnExpanded,- limit: 3,- cursor: SoupQuery::new_sort_frecency(Frecency, EntityFilters::default()),- user: MacroUserIdStr::parse_from_str("macro|[email protected]").unwrap(),- })+ .get_user_soup(+ SoupRequest {+ email_preview_view: PreviewView::StandardLabel(+ email::domain::models::PreviewViewStandardLabel::Inbox,+ ),+ link_id: Some(Uuid::new_v4()),+ soup_type: SoupType::UnExpanded,+ limit: 3,+ cursor: SoupQuery::new_sort_frecency(Frecency, EntityFilters::default()),+ user: MacroUserIdStr::parse_from_str("macro|[email protected]").unwrap(),+ },+ None,+ ).await.unwrap().unwrap_right();diff --git a/rust/cloud-storage/soup/src/inbound/axum_router.rs b/rust/cloud-storage/soup/src/inbound/axum_router.rsindex 28ca8bbab4..24a5d6080c 100644--- a/rust/cloud-storage/soup/src/inbound/axum_router.rs+++ b/rust/cloud-storage/soup/src/inbound/axum_router.rs@@ -23,6 +23,13 @@ use email::{previews_router::EmailRouterState,},};+use entity_access::{+ domain::{+ models::{EntityAccessReceipt, MemberTeamRole},+ ports::EntityAccessService,+ },+ inbound::axum_extractors::OptionalMacroUserTeamExtractor,+};use filter_ast::{Expr, ExprFrame};use item_filters::{EntityFilters,@@ -259,35 +266,45 @@ pub struct GroupedSoupPage {pub groups: Option<Vec<ApiGroupMeta>>,}-pub struct SoupRouterState<T, U> {+pub struct SoupRouterState<T, U, EAS> {service: Arc<T>,email: EmailRouterState<U>,+ entity_access_service: Arc<EAS>,}-impl<T, U> Clone for SoupRouterState<T, U> {+impl<T, U, EAS> Clone for SoupRouterState<T, U, EAS> {fn clone(&self) -> Self {Self {service: self.service.clone(),email: self.email.clone(),+ entity_access_service: self.entity_access_service.clone(),}}}-impl<T, U> FromRef<SoupRouterState<T, U>> for EmailRouterState<U> {- fn from_ref(input: &SoupRouterState<T, U>) -> Self {+impl<T, U, EAS> FromRef<SoupRouterState<T, U, EAS>> for EmailRouterState<U> {+ fn from_ref(input: &SoupRouterState<T, U, EAS>) -> Self {input.email.clone()}}-impl<T, U> SoupRouterState<T, U>+impl<T, U, EAS> FromRef<SoupRouterState<T, U, EAS>> for Arc<EAS> {+ fn from_ref(input: &SoupRouterState<T, U, EAS>) -> Self {+ input.entity_access_service.clone()+ }+}++impl<T, U, EAS> SoupRouterState<T, U, EAS>whereT: SoupService,U: EmailService,+ EAS: entity_access::domain::ports::EntityAccessService,{- pub fn new(service: T, email: U) -> Self {+ pub fn new(service: T, email: U, entity_access_service: Arc<EAS>) -> Self {SoupRouterState {service: Arc::new(service),email: EmailRouterState::new(email),+ entity_access_service,}}@@ -295,6 +312,7 @@ where&self,macro_user_id: MacroUserIdStr<'static>,email_link: Option<Link>,+ team_receipt_option: Option<EntityAccessReceipt<MemberTeamRole>>,ApiSoupRequestInner {filters,params,@@ -304,7 +322,7 @@ where) -> Result<Json<PaginatedOpaqueCursor<SoupApiItem>>, SoupHandlerErr>whereSoupRequest<R>: IntoSoupReqAst,- R: Clone + Serialize + Send,+ R: Clone + Serialize + Send + RequestsTeamScope,{let create_fallback = move || -> SoupQuery<R> {let params_sort = params@@ -328,19 +346,30 @@ where.unwrap_or_else(create_fallback),};+ // Derive team_scope authorization from the *effective* filter (the+ // one embedded in the resolved SoupQuery), not the raw request body.+ // For cursor-paginated requests the body's filters may be empty and+ // the real filter lives inside the cursor — checking the body would+ // miss team_scope on follow-up pages.+ let team_receipt =+ resolve_team_receipt(cursor.filter().requests_team_scope(), team_receipt_option)?;+let res = self.service- .get_user_soup(SoupRequest {- soup_type: match params.expand {- Some(true) | None => SoupType::Expanded,- Some(false) => SoupType::UnExpanded,+ .get_user_soup(+ SoupRequest {+ soup_type: match params.expand {+ Some(true) | None => SoupType::Expanded,+ Some(false) => SoupType::UnExpanded,+ },+ limit: params.limit.unwrap_or(20),+ cursor,+ user: macro_user_id,+ email_preview_view: email_view,+ link_id: email_link.map(|l| l.id),},- limit: params.limit.unwrap_or(20),- cursor,- user: macro_user_id,- email_preview_view: email_view,- link_id: email_link.map(|l| l.id),- })+ team_receipt,+ ).await?;Ok(Json(@@ -409,10 +438,34 @@ where}}-pub fn soup_router<T, U, S>(state: SoupRouterState<T, U>) -> Router<S>+/// Probe applied to whichever filter type a soup endpoint accepts+/// (`EntityFilters` for the typed POST, `ApiEntityFilterAst` for the AST+/// endpoint). Lets `handle` inspect the *materialized* SoupQuery's filter+/// — which may have come from the request body or from the cursor — and+/// decide whether team_scope is in play.+pub trait RequestsTeamScope {+ /// True when this filter asks the query to expand visibility across+ /// the requesting user's team.+ fn requests_team_scope(&self) -> bool;+}++impl RequestsTeamScope for EntityFilters {+ fn requests_team_scope(&self) -> bool {+ self.email_filters.team_scope+ }+}++impl RequestsTeamScope for ApiEntityFilterAst {+ fn requests_team_scope(&self) -> bool {+ email_filter_contains_team_scope(&self.email_filter)+ }+}++pub fn soup_router<T, U, EAS, S>(state: SoupRouterState<T, U, EAS>) -> Router<S>whereT: SoupService,U: EmailService,+ EAS: EntityAccessService,S: Send + Sync,{Router::new()@@ -455,6 +508,8 @@ pub enum SoupHandlerErr {ExpandErr(ExpandErr),#[error("Invalid compound filter could not be expanded")]Expand,+ #[error("team_scope requires team membership")]+ TeamScopeForbidden,}impl From<SoupErr> for SoupHandlerErr {@@ -470,6 +525,7 @@ impl IntoResponse for SoupHandlerErr {fn into_response(self) -> axum::response::Response {let status_code = match &self {SoupHandlerErr::ExpandErr(_) | SoupHandlerErr::Expand => StatusCode::BAD_REQUEST,+ SoupHandlerErr::TeamScopeForbidden => StatusCode::FORBIDDEN,_ => StatusCode::INTERNAL_SERVER_ERROR,};(@@ -496,26 +552,32 @@ impl IntoResponse for SoupHandlerErr {(status = 500, body=ErrorResponse),))]-pub async fn get_soup_handler<T, U>(- State(service): State<SoupRouterState<T, U>>,+pub async fn get_soup_handler<T, U, EAS>(+ State(service): State<SoupRouterState<T, U, EAS>>,Cached(MacroUserExtractor { macro_user_id, .. }): Cached<MacroUserExtractor>,email_link: Result<Cached<EmailLinkExtractor<U>>, EmailLinkErr>,+ team: OptionalMacroUserTeamExtractor<MemberTeamRole, EAS>,Query(params): Query<Params>,cursor: SoupCursor<EntityFilters>,) -> Result<Json<PaginatedOpaqueCursor<SoupApiItem>>, SoupHandlerErr>whereT: SoupService,U: EmailService,+ EAS: EntityAccessService,{let link = match email_link {Ok(l) => Some(l.0.0),Err(EmailLinkErr::NotFound) => None,Err(e) => Err(e)?,};+ // Team receipt is plumbed through even for GET so that paginating a+ // team-scoped query via a cursor (which carries the original filter)+ // continues to authorize correctly.service.handle(macro_user_id,link,+ team.entity_access_receipt,ApiSoupRequestInner {params,filters: EntityFilters::default(),@@ -564,10 +626,11 @@ type SoupCursor<R> = axum_extra::either::Either<))]#[tracing::instrument(err, skip_all)]-pub async fn post_soup_handler<T, U>(- State(service): State<SoupRouterState<T, U>>,+pub async fn post_soup_handler<T, U, EAS>(+ State(service): State<SoupRouterState<T, U, EAS>>,Cached(MacroUserExtractor { macro_user_id, .. }): Cached<MacroUserExtractor>,email_link: Result<Cached<EmailLinkExtractor<U>>, EmailLinkErr>,+ team: OptionalMacroUserTeamExtractor<MemberTeamRole, EAS>,cursor: SoupCursor<EntityFilters>,Json(PostSoupRequest {filters,@@ -578,16 +641,21 @@ pub async fn post_soup_handler<T, U>(whereT: SoupService,U: EmailService,+ EAS: EntityAccessService,{let link = match email_link {Ok(l) => Some(l.0.0),Err(EmailLinkErr::NotFound) => None,Err(e) => Err(e)?,};+ // Pass the raw extractor receipt through — `handle` resolves the+ // team_scope check against the *effective* filter (which may come from+ // the cursor on follow-up pages), not the request body.service.handle(macro_user_id,link,+ team.entity_access_receipt,ApiSoupRequestInner {filters,params,@@ -627,10 +695,11 @@ pub struct PostSoupAstRequest {))]#[tracing::instrument(err, skip_all)]-pub async fn post_soup_ast_handler<T, U>(- State(service): State<SoupRouterState<T, U>>,+pub async fn post_soup_ast_handler<T, U, EAS>(+ State(service): State<SoupRouterState<T, U, EAS>>,Cached(MacroUserExtractor { macro_user_id, .. }): Cached<MacroUserExtractor>,email_link: Result<Cached<EmailLinkExtractor<U>>, EmailLinkErr>,+ team: OptionalMacroUserTeamExtractor<MemberTeamRole, EAS>,cursor: SoupCursor<ApiEntityFilterAst>,Json(PostSoupAstRequest {filters,@@ -641,16 +710,21 @@ pub async fn post_soup_ast_handler<T, U>(whereT: SoupService,U: EmailService,+ EAS: EntityAccessService,{let link = match email_link {Ok(l) => Some(l.0.0),Err(EmailLinkErr::NotFound) => None,Err(e) => Err(e)?,};+ // Pass the raw extractor receipt through — `handle` resolves the+ // team_scope check against the *effective* filter (which may come from+ // the cursor on follow-up pages), not the request body.service.handle(macro_user_id,link,+ team.entity_access_receipt,ApiSoupRequestInner {filters,params,@@ -689,8 +763,8 @@ pub struct PostGroupedSoupAstRequest {))]#[tracing::instrument(err, skip_all)]-pub async fn post_grouped_soup_ast_handler<T, U>(- State(service): State<SoupRouterState<T, U>>,+pub async fn post_grouped_soup_ast_handler<T, U, EAS>(+ State(service): State<SoupRouterState<T, U, EAS>>,Cached(MacroUserExtractor { macro_user_id, .. }): Cached<MacroUserExtractor>,cursor: Option<CursorWithValAndFilter<Uuid, SimpleSortMethod, ApiEntityFilterAst>>,Json(PostGroupedSoupAstRequest { filters, params }): Json<PostGroupedSoupAstRequest>,@@ -698,6 +772,7 @@ pub async fn post_grouped_soup_ast_handler<T, U>(whereT: SoupService,U: EmailService,+ EAS: EntityAccessService,{let filters = filters.into_entity_ast()@@ -728,6 +803,35 @@ where.await}+/// Returns the team receipt to use when team-scoped visibility is required.+/// `team_scope_requested` is true when the request body asks for team_scope+/// (via the typed flag on POST or the `EmailLiteral::TeamScope` literal on+/// the AST endpoint). Returns `Err(TeamScopeForbidden)` when team_scope was+/// requested but the user has no qualifying team membership.+fn resolve_team_receipt(+ team_scope_requested: bool,+ receipt: Option<EntityAccessReceipt<MemberTeamRole>>,+) -> Result<Option<EntityAccessReceipt<MemberTeamRole>>, SoupHandlerErr> {+ if team_scope_requested && receipt.is_none() {+ return Err(SoupHandlerErr::TeamScopeForbidden);+ }+ Ok(receipt)+}++/// Walks an AST email filter tree and returns true if any node is the+/// `TeamScope` literal.+fn email_filter_contains_team_scope(filter: &LiteralTree<EmailLiteral>) -> bool {+ fn walk(expr: &Expr<EmailLiteral>) -> bool {+ match expr {+ Expr::And(a, b) | Expr::Or(a, b) => walk(a) || walk(b),+ Expr::Not(a) => walk(a),+ Expr::Literal(EmailLiteral::TeamScope) => true,+ Expr::Literal(_) => false,+ }+ }+ filter.as_ref().map(|e| walk(e)).unwrap_or(false)+}+#[derive(Debug, Default, Serialize, Deserialize, Clone)]pub struct ApiEntityFilterAst {/// the filters that should be applied to the document entitydiff --git a/rust/cloud-storage/soup/src/inbound/axum_router/tests.rs b/rust/cloud-storage/soup/src/inbound/axum_router/tests.rsindex d3356a649a..03ef9a3ed8 100644--- a/rust/cloud-storage/soup/src/inbound/axum_router/tests.rs+++ b/rust/cloud-storage/soup/src/inbound/axum_router/tests.rs@@ -70,7 +70,15 @@ impl MockSoup {}impl SoupService for MockSoup {- async fn get_user_soup<T>(&self, req: SoupRequest<T>) -> Result<SoupOutput<T>, SoupErr>+ async fn get_user_soup<T>(+ &self,+ req: SoupRequest<T>,+ _team_receipt: Option<+ entity_access::domain::models::EntityAccessReceipt<+ entity_access::domain::models::MemberTeamRole,+ >,+ >,+ ) -> Result<SoupOutput<T>, SoupErr>whereSoupRequest<T>: IntoSoupReqAst,T: Clone + Serialize + Send,@@ -238,8 +246,127 @@ impl EmailService for MockEmail {}}+#[derive(Clone)]+struct MockEntityAccess;++impl entity_access::domain::ports::EntityAccessService for MockEntityAccess {+ async fn generate_entity_access_receipt<+ T: entity_access::domain::models::RequiredPermission,+ >(+ &self,+ _user_id: ¯o_user_id::user_id::MacroUserId<macro_user_id::lowercased::Lowercase<'_>>,+ _user_org_id: Option<i64>,+ _entity_id: &str,+ _entity_type: entity_access::domain::models::EntityType,+ ) -> Result<+ entity_access::domain::models::EntityAccessReceipt<T>,+ entity_access::domain::models::AccessError,+ > {+ unimplemented!()+ }++ async fn get_access_level(+ &self,+ _user_id: Option<+ ¯o_user_id::user_id::MacroUserId<macro_user_id::lowercased::Lowercase<'_>>,+ >,+ _entity_id: &str,+ _entity_type: entity_access::domain::models::EntityType,+ ) -> Result<+ Option<entity_access::domain::models::AccessLevel>,+ entity_access::domain::models::AccessError,+ > {+ unimplemented!()+ }++ async fn check_access(+ &self,+ _user_id: Option<+ ¯o_user_id::user_id::MacroUserId<macro_user_id::lowercased::Lowercase<'_>>,+ >,+ _entity_id: &str,+ _entity_type: entity_access::domain::models::EntityType,+ _required_level: entity_access::domain::models::AccessLevel,+ ) -> Result<+ entity_access::domain::models::AccessLevel,+ entity_access::domain::models::AccessError,+ > {+ unimplemented!()+ }++ async fn check_public_access(+ &self,+ _entity_id: &str,+ _entity_type: entity_access::domain::models::EntityType,+ _required_level: entity_access::domain::models::AccessLevel,+ ) -> Result<+ entity_access::domain::models::AccessLevel,+ entity_access::domain::models::AccessError,+ > {+ unimplemented!()+ }++ async fn get_entity_permission(+ &self,+ _user_id: Option<+ ¯o_user_id::user_id::MacroUserId<macro_user_id::lowercased::Lowercase<'_>>,+ >,+ _entity_id: &str,+ _entity_type: entity_access::domain::models::EntityType,+ _user_org_id: Option<i64>,+ ) -> Result<+ entity_access::domain::models::EntityPermission,+ entity_access::domain::models::AccessError,+ > {+ unimplemented!()+ }++ async fn get_users_by_entity(+ &self,+ _entity_id: &str,+ _entity_type: entity_access::domain::models::EntityType,+ ) -> Result<Vec<MacroUserIdStr<'static>>, entity_access::domain::models::AccessError> {+ unimplemented!()+ }++ async fn get_call_channel(+ &self,+ _call_id: &Uuid,+ ) -> Result<+ Option<entity_access::domain::models::CallChannelInfo>,+ entity_access::domain::models::AccessError,+ > {+ unimplemented!()+ }++ async fn get_call_channel_by_channel_id(+ &self,+ _channel_id: &Uuid,+ ) -> Result<+ Option<entity_access::domain::models::CallChannelInfo>,+ entity_access::domain::models::AccessError,+ > {+ unimplemented!()+ }++ async fn get_user_team(+ &self,+ _user_id: ¯o_user_id::user_id::MacroUserId<macro_user_id::lowercased::Lowercase<'_>>,+ ) -> Result<+ Option<entity_access::domain::models::UserTeamInfo>,+ entity_access::domain::models::AccessError,+ > {+ Ok(None)+ }+}+fn mock_router() -> Router {- soup_router(SoupRouterState::new(MockSoup::new(), MockEmail)).layer(Extension(UserContext {+ soup_router(SoupRouterState::new(+ MockSoup::new(),+ MockEmail,+ Arc::new(MockEntityAccess),+ ))+ .layer(Extension(UserContext {user_id: "macro|[email protected]".to_string(),fusion_user_id: "1234".to_string(),permissions: None,@@ -402,6 +529,7 @@ async fn it_calls_soup_with_missing_link() {MockEmailLinkResult {get_link_result: Arc::new(|| Ok(None)),},+ Arc::new(MockEntityAccess),)).layer(Extension(UserContext {user_id: "macro|[email protected]".to_string(),@@ -434,6 +562,7 @@ async fn it_does_not_call_soup_with_db_err() {Err(EmailErr::RepoErr(anyhow::anyhow!("failed to fetch")))}),},+ Arc::new(MockEntityAccess),)).layer(Extension(UserContext {user_id: "macro|[email protected]".to_string(),@@ -463,6 +592,7 @@ async fn it_loads_email_all_view() {MockEmailLinkResult {get_link_result: Arc::new(|| Ok(None)),},+ Arc::new(MockEntityAccess),)).layer(Extension(UserContext {user_id: "macro|[email protected]".to_string(),@@ -503,6 +633,7 @@ async fn it_loads_email_sent_view() {MockEmailLinkResult {get_link_result: Arc::new(|| Ok(None)),},+ Arc::new(MockEntityAccess),)).layer(Extension(UserContext {user_id: "macro|[email protected]".to_string(),@@ -543,6 +674,7 @@ async fn it_parses_file_assoc_filters() {MockEmailLinkResult {get_link_result: Arc::new(|| Ok(None)),},+ Arc::new(MockEntityAccess),)).layer(Extension(UserContext {user_id: "macro|[email protected]".to_string(),@@ -582,6 +714,7 @@ async fn cursor_with_assoc_works() {MockEmailLinkResult {get_link_result: Arc::new(|| Ok(None)),},+ Arc::new(MockEntityAccess),)).layer(Extension(UserContext {user_id: "macro|[email protected]".to_string(),@@ -656,6 +789,7 @@ async fn cursor_with_assoc_works() {MockEmailLinkResult {get_link_result: Arc::new(|| Ok(None)),},+ Arc::new(MockEntityAccess),)).layer(Extension(UserContext {user_id: "macro|[email protected]".to_string(),@@ -679,6 +813,7 @@ async fn cursor_with_all_works() {MockEmailLinkResult {get_link_result: Arc::new(|| Ok(None)),},+ Arc::new(MockEntityAccess),)).layer(Extension(UserContext {user_id: "macro|[email protected]".to_string(),@@ -753,6 +888,7 @@ async fn cursor_with_all_works() {MockEmailLinkResult {get_link_result: Arc::new(|| Ok(None)),},+ Arc::new(MockEntityAccess),)).layer(Extension(UserContext {user_id: "macro|[email protected]".to_string(),@@ -776,6 +912,7 @@ async fn it_parses_channel_filters() {MockEmailLinkResult {get_link_result: Arc::new(|| Ok(None)),},+ Arc::new(MockEntityAccess),)).layer(Extension(UserContext {user_id: "macro|[email protected]".to_string(),@@ -820,6 +957,7 @@ async fn it_parses_notification_and_task_filters() {MockEmailLinkResult {get_link_result: Arc::new(|| Ok(None)),},+ Arc::new(MockEntityAccess),)).layer(Extension(UserContext {user_id: "macro|[email protected]".to_string(),@@ -932,6 +1070,7 @@ async fn it_can_filter_chat_owners() {MockEmailLinkResult {get_link_result: Arc::new(|| Ok(None)),},+ Arc::new(MockEntityAccess),)).layer(Extension(UserContext {user_id: "macro|[email protected]".to_string(),@@ -970,6 +1109,7 @@ async fn ast_endpoint_expands_file_assoc_pdf() {MockEmailLinkResult {get_link_result: Arc::new(|| Ok(None)),},+ Arc::new(MockEntityAccess),)).layer(Extension(UserContext {user_id: "macro|[email protected]".to_string(),@@ -1016,6 +1156,7 @@ async fn ast_endpoint_passes_through_plain_document_literal() {MockEmailLinkResult {get_link_result: Arc::new(|| Ok(None)),},+ Arc::new(MockEntityAccess),)).layer(Extension(UserContext {user_id: "macro|[email protected]".to_string(),@@ -1063,6 +1204,7 @@ async fn ast_endpoint_expands_file_assoc_image_to_or_tree() {MockEmailLinkResult {get_link_result: Arc::new(|| Ok(None)),},+ Arc::new(MockEntityAccess),)).layer(Extension(UserContext {user_id: "macro|[email protected]".to_string(),@@ -1200,6 +1342,7 @@ async fn it_can_expand_assoc_ast() {MockEmailLinkResult {get_link_result: Arc::new(|| Ok(None)),},+ Arc::new(MockEntityAccess),)).layer(Extension(UserContext {user_id: "macro|[email protected]".to_string(),@@ -1271,6 +1414,7 @@ async fn it_can_expand_assoc_ast() {MockEmailLinkResult {get_link_result: Arc::new(|| Ok(None)),},+ Arc::new(MockEntityAccess),)).layer(Extension(UserContext {user_id: "macro|[email protected]".to_string(),diff --git a/rust/cloud-storage/soup/src/inbound/toolset/list_entities.rs b/rust/cloud-storage/soup/src/inbound/toolset/list_entities.rsindex 85cb2cc8db..bab48e3992 100644--- a/rust/cloud-storage/soup/src/inbound/toolset/list_entities.rs+++ b/rust/cloud-storage/soup/src/inbound/toolset/list_entities.rs@@ -169,14 +169,17 @@ wherelet result = service_context.service- .get_user_soup(SoupRequest {- soup_type: SoupType::Expanded,- limit: RESULT_LIMIT,- cursor: SoupQuery::new_sort_simple(sort_method, EntityFilters::default()),- user: request_context.user_id,- email_preview_view: PreviewView::default(),- link_id,- })+ .get_user_soup(+ SoupRequest {+ soup_type: SoupType::Expanded,+ limit: RESULT_LIMIT,+ cursor: SoupQuery::new_sort_simple(sort_method, EntityFilters::default()),+ user: request_context.user_id,+ email_preview_view: PreviewView::default(),+ link_id,+ },+ None,+ ).await.map_err(|e| ToolCallError {description: format!("Failed to list entities: {e}"),