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(calendar): add read-only team sharing and availability (#7741)
gbirman0a2691ea27e5
diff --git a/.sqlx/query-048d7c334accc1492f9c8e544a35910f9c747f1d5fbdbb891ade13d89c649939.json b/.sqlx/query-048d7c334accc1492f9c8e544a35910f9c747f1d5fbdbb891ade13d89c649939.jsonnew file mode 100644index 0000000000..39c8425243--- /dev/null+++ b/.sqlx/query-048d7c334accc1492f9c8e544a35910f9c747f1d5fbdbb891ade13d89c649939.json@@ -0,0 +1,14 @@+{+ "db_name": "PostgreSQL",+ "query": "UPDATE calendars SET access_role='freeBusyReader' WHERE id=$1",+ "describe": {+ "columns": [],+ "parameters": {+ "Left": [+ "Uuid"+ ]+ },+ "nullable": []+ },+ "hash": "048d7c334accc1492f9c8e544a35910f9c747f1d5fbdbb891ade13d89c649939"+}diff --git a/.sqlx/query-05016877d16bc358544653739ae4049e57e021d1bcfdc0dcfa506ff1d9eaaa50.json b/.sqlx/query-05016877d16bc358544653739ae4049e57e021d1bcfdc0dcfa506ff1d9eaaa50.jsonnew file mode 100644index 0000000000..2a9015f3fa--- /dev/null+++ b/.sqlx/query-05016877d16bc358544653739ae4049e57e021d1bcfdc0dcfa506ff1d9eaaa50.json@@ -0,0 +1,14 @@+{+ "db_name": "PostgreSQL",+ "query": "UPDATE calendars SET sync_token = 'old-token', synced_at = now(), materialized_starts_at = now(), materialized_ends_at = now() + interval '1 day', materialized_start_date = current_date, materialized_end_date = current_date + 1 WHERE id = $1",+ "describe": {+ "columns": [],+ "parameters": {+ "Left": [+ "Uuid"+ ]+ },+ "nullable": []+ },+ "hash": "05016877d16bc358544653739ae4049e57e021d1bcfdc0dcfa506ff1d9eaaa50"+}diff --git a/.sqlx/query-0b70e5ea741ce33ef5347fcdd0ad63c7f57c0a627ec7eeb6d97995d144d05ba2.json b/.sqlx/query-0b70e5ea741ce33ef5347fcdd0ad63c7f57c0a627ec7eeb6d97995d144d05ba2.jsonnew file mode 100644index 0000000000..c0095f6ebd--- /dev/null+++ b/.sqlx/query-0b70e5ea741ce33ef5347fcdd0ad63c7f57c0a627ec7eeb6d97995d144d05ba2.json@@ -0,0 +1,14 @@+{+ "db_name": "PostgreSQL",+ "query": "INSERT INTO calendar_team_sharing(user_id,sharing) SELECT unnest($1::text[]),'all' ON CONFLICT(user_id) DO UPDATE SET sharing='all'",+ "describe": {+ "columns": [],+ "parameters": {+ "Left": [+ "TextArray"+ ]+ },+ "nullable": []+ },+ "hash": "0b70e5ea741ce33ef5347fcdd0ad63c7f57c0a627ec7eeb6d97995d144d05ba2"+}diff --git a/.sqlx/query-122f8321d98595e2ce5114364181264de62860e7817195eb7c002d2a6c3f8443.json b/.sqlx/query-122f8321d98595e2ce5114364181264de62860e7817195eb7c002d2a6c3f8443.jsonnew file mode 100644index 0000000000..603b2098f9--- /dev/null+++ b/.sqlx/query-122f8321d98595e2ce5114364181264de62860e7817195eb7c002d2a6c3f8443.json@@ -0,0 +1,22 @@+{+ "db_name": "PostgreSQL",+ "query": "SELECT provider_access_role FROM calendar_event_sources WHERE event_id = $1",+ "describe": {+ "columns": [+ {+ "ordinal": 0,+ "name": "provider_access_role",+ "type_info": "Text"+ }+ ],+ "parameters": {+ "Left": [+ "Uuid"+ ]+ },+ "nullable": [+ true+ ]+ },+ "hash": "122f8321d98595e2ce5114364181264de62860e7817195eb7c002d2a6c3f8443"+}diff --git a/.sqlx/query-14ee02554114e96cd83c22256cf9673693423f7041b5cfa01e0ee69065b9809a.json b/.sqlx/query-14ee02554114e96cd83c22256cf9673693423f7041b5cfa01e0ee69065b9809a.jsonnew file mode 100644index 0000000000..8ff1f0995f--- /dev/null+++ b/.sqlx/query-14ee02554114e96cd83c22256cf9673693423f7041b5cfa01e0ee69065b9809a.json@@ -0,0 +1,22 @@+{+ "db_name": "PostgreSQL",+ "query": "SELECT extracted_count FROM calendar_backfill_jobs WHERE id = $1",+ "describe": {+ "columns": [+ {+ "ordinal": 0,+ "name": "extracted_count",+ "type_info": "Int8"+ }+ ],+ "parameters": {+ "Left": [+ "Uuid"+ ]+ },+ "nullable": [+ false+ ]+ },+ "hash": "14ee02554114e96cd83c22256cf9673693423f7041b5cfa01e0ee69065b9809a"+}diff --git a/.sqlx/query-15801664350470a713a8d4aac0cc7baa4b789c57c02b8814dcc318f84cd1b134.json b/.sqlx/query-15801664350470a713a8d4aac0cc7baa4b789c57c02b8814dcc318f84cd1b134.jsonnew file mode 100644index 0000000000..3be1ab553c--- /dev/null+++ b/.sqlx/query-15801664350470a713a8d4aac0cc7baa4b789c57c02b8814dcc318f84cd1b134.json@@ -0,0 +1,22 @@+{+ "db_name": "PostgreSQL",+ "query": "SELECT count(*) AS \"count!\" FROM calendar_accounts WHERE email_link_id = $1",+ "describe": {+ "columns": [+ {+ "ordinal": 0,+ "name": "count!",+ "type_info": "Int8"+ }+ ],+ "parameters": {+ "Left": [+ "Uuid"+ ]+ },+ "nullable": [+ null+ ]+ },+ "hash": "15801664350470a713a8d4aac0cc7baa4b789c57c02b8814dcc318f84cd1b134"+}diff --git a/.sqlx/query-16376437fec571254c20bc47e4cbbc5a5e13bb90651ad24c2281b2154f10dea3.json b/.sqlx/query-16376437fec571254c20bc47e4cbbc5a5e13bb90651ad24c2281b2154f10dea3.jsonnew file mode 100644index 0000000000..8588e42975--- /dev/null+++ b/.sqlx/query-16376437fec571254c20bc47e4cbbc5a5e13bb90651ad24c2281b2154f10dea3.json@@ -0,0 +1,14 @@+{+ "db_name": "PostgreSQL",+ "query": "UPDATE calendars SET sync_token='legacy',synced_at=now(),materialized_starts_at='2026-07-01',materialized_ends_at='2026-08-01',materialized_start_date='2026-07-01',materialized_end_date='2026-08-01' WHERE id=$1",+ "describe": {+ "columns": [],+ "parameters": {+ "Left": [+ "Uuid"+ ]+ },+ "nullable": []+ },+ "hash": "16376437fec571254c20bc47e4cbbc5a5e13bb90651ad24c2281b2154f10dea3"+}diff --git a/.sqlx/query-16d72a752357648effb2327791a771b02d72dd71725f71a90b4e7f05d87f2644.json b/.sqlx/query-16d72a752357648effb2327791a771b02d72dd71725f71a90b4e7f05d87f2644.jsonnew file mode 100644index 0000000000..03b1b3fb24--- /dev/null+++ b/.sqlx/query-16d72a752357648effb2327791a771b02d72dd71725f71a90b4e7f05d87f2644.json@@ -0,0 +1,15 @@+{+ "db_name": "PostgreSQL",+ "query": "INSERT INTO team_user (user_id, team_id, team_role) VALUES ($1, $2, 'member')",+ "describe": {+ "columns": [],+ "parameters": {+ "Left": [+ "Text",+ "Uuid"+ ]+ },+ "nullable": []+ },+ "hash": "16d72a752357648effb2327791a771b02d72dd71725f71a90b4e7f05d87f2644"+}diff --git a/.sqlx/query-cd53c7cf9b8aac6edf83e11fde6db0b391c0c3fa30c76a581c9b6a891220f49a.json b/.sqlx/query-17090b38abc7076647ca9d230465f4c9879f75e2c606678904ca5e3206e4e763.jsonsimilarity index 59%rename from .sqlx/query-cd53c7cf9b8aac6edf83e11fde6db0b391c0c3fa30c76a581c9b6a891220f49a.jsonrename to .sqlx/query-17090b38abc7076647ca9d230465f4c9879f75e2c606678904ca5e3206e4e763.jsonindex 6fdcf5c48b..fb9ed4a5bd 100644--- a/.sqlx/query-cd53c7cf9b8aac6edf83e11fde6db0b391c0c3fa30c76a581c9b6a891220f49a.json+++ b/.sqlx/query-17090b38abc7076647ca9d230465f4c9879f75e2c606678904ca5e3206e4e763.json@@ -1,6 +1,6 @@{"db_name": "PostgreSQL",- "query": "\n SELECT\n time_zone, default_reminders, name, color, access_role, is_primary, is_deleted\n FROM calendars\n WHERE account_id = $1 AND provider_calendar_id = $2\n ",+ "query": "\n SELECT\n time_zone, default_reminders, name, color, access_role, is_primary, is_deleted,\n (snapshot_normalization_version < 1 OR EXISTS (\n SELECT 1 FROM calendar_event_sources source\n WHERE source.calendar_id = calendars.id\n AND source.provider_access_role IS DISTINCT FROM calendars.access_role\n )) AS \"needs_verification!\"\n FROM calendars\n WHERE account_id = $1 AND provider_calendar_id = $2\n ","describe": {"columns": [{@@ -37,6 +37,11 @@"ordinal": 6,"name": "is_deleted","type_info": "Bool"+ },+ {+ "ordinal": 7,+ "name": "needs_verification!",+ "type_info": "Bool"}],"parameters": {@@ -52,8 +57,9 @@true,true,false,- false+ false,+ null]},- "hash": "cd53c7cf9b8aac6edf83e11fde6db0b391c0c3fa30c76a581c9b6a891220f49a"+ "hash": "17090b38abc7076647ca9d230465f4c9879f75e2c606678904ca5e3206e4e763"}diff --git a/.sqlx/query-177b005aa26af6953e523b6f53355b396bef5ed052e2aabdc3bed06a80389779.json b/.sqlx/query-177b005aa26af6953e523b6f53355b396bef5ed052e2aabdc3bed06a80389779.jsonnew file mode 100644index 0000000000..2ac543b204--- /dev/null+++ b/.sqlx/query-177b005aa26af6953e523b6f53355b396bef5ed052e2aabdc3bed06a80389779.json@@ -0,0 +1,22 @@+{+ "db_name": "PostgreSQL",+ "query": "\n SELECT content_source_id = calendar_event_canonical_source_id(id) AS \"mirrors!\"\n FROM calendar_events\n WHERE id = $1\n ",+ "describe": {+ "columns": [+ {+ "ordinal": 0,+ "name": "mirrors!",+ "type_info": "Bool"+ }+ ],+ "parameters": {+ "Left": [+ "Uuid"+ ]+ },+ "nullable": [+ null+ ]+ },+ "hash": "177b005aa26af6953e523b6f53355b396bef5ed052e2aabdc3bed06a80389779"+}diff --git a/.sqlx/query-1d44982cbdaf17e6586a5fc0b71ad09152b5ee540880848168c842f6e6dc2aa3.json b/.sqlx/query-1d44982cbdaf17e6586a5fc0b71ad09152b5ee540880848168c842f6e6dc2aa3.jsonnew file mode 100644index 0000000000..7620aa97ce--- /dev/null+++ b/.sqlx/query-1d44982cbdaf17e6586a5fc0b71ad09152b5ee540880848168c842f6e6dc2aa3.json@@ -0,0 +1,14 @@+{+ "db_name": "PostgreSQL",+ "query": "UPDATE calendar_accounts SET sync_status = 'ready' WHERE id = $1",+ "describe": {+ "columns": [],+ "parameters": {+ "Left": [+ "Uuid"+ ]+ },+ "nullable": []+ },+ "hash": "1d44982cbdaf17e6586a5fc0b71ad09152b5ee540880848168c842f6e6dc2aa3"+}diff --git a/.sqlx/query-1dd792d6ed050b56a4831387b67941bf86b5dcb717bf6ea72ab71762cf0ff84d.json b/.sqlx/query-1dd792d6ed050b56a4831387b67941bf86b5dcb717bf6ea72ab71762cf0ff84d.jsonnew file mode 100644index 0000000000..463c89b3f6--- /dev/null+++ b/.sqlx/query-1dd792d6ed050b56a4831387b67941bf86b5dcb717bf6ea72ab71762cf0ff84d.json@@ -0,0 +1,54 @@+{+ "db_name": "PostgreSQL",+ "query": "\n SELECT\n account.sync_status,\n calendar.is_deleted,\n google_job.status AS google_job_status,\n google_job.lease_token,\n (SELECT count(*) FROM calendar_event_sources WHERE event_id = $3) AS \"source_count!\",\n (SELECT count(*) FROM calendar_events WHERE id = $3) AS \"event_count!\"\n FROM calendar_accounts account\n JOIN calendars calendar ON calendar.account_id = account.id\n JOIN calendar_backfill_jobs google_job ON google_job.id = $2\n WHERE account.id = $1\n ",+ "describe": {+ "columns": [+ {+ "ordinal": 0,+ "name": "sync_status",+ "type_info": "Text"+ },+ {+ "ordinal": 1,+ "name": "is_deleted",+ "type_info": "Bool"+ },+ {+ "ordinal": 2,+ "name": "google_job_status",+ "type_info": "Text"+ },+ {+ "ordinal": 3,+ "name": "lease_token",+ "type_info": "Uuid"+ },+ {+ "ordinal": 4,+ "name": "source_count!",+ "type_info": "Int8"+ },+ {+ "ordinal": 5,+ "name": "event_count!",+ "type_info": "Int8"+ }+ ],+ "parameters": {+ "Left": [+ "Uuid",+ "Uuid",+ "Uuid"+ ]+ },+ "nullable": [+ false,+ false,+ false,+ true,+ null,+ null+ ]+ },+ "hash": "1dd792d6ed050b56a4831387b67941bf86b5dcb717bf6ea72ab71762cf0ff84d"+}diff --git a/.sqlx/query-1fb5efa6c440e451ded7952583828fe22b246cc085e1317004d4b5fd61b4ccf8.json b/.sqlx/query-1fb5efa6c440e451ded7952583828fe22b246cc085e1317004d4b5fd61b4ccf8.jsonnew file mode 100644index 0000000000..e7e27cd21e--- /dev/null+++ b/.sqlx/query-1fb5efa6c440e451ded7952583828fe22b246cc085e1317004d4b5fd61b4ccf8.json@@ -0,0 +1,22 @@+{+ "db_name": "PostgreSQL",+ "query": "SELECT email_link_id FROM calendar_accounts WHERE id = $1",+ "describe": {+ "columns": [+ {+ "ordinal": 0,+ "name": "email_link_id",+ "type_info": "Uuid"+ }+ ],+ "parameters": {+ "Left": [+ "Uuid"+ ]+ },+ "nullable": [+ false+ ]+ },+ "hash": "1fb5efa6c440e451ded7952583828fe22b246cc085e1317004d4b5fd61b4ccf8"+}diff --git a/.sqlx/query-200af5f502688067fe0ee28203bb8090cda1461c32835333250789b8bd1bf1a6.json b/.sqlx/query-200af5f502688067fe0ee28203bb8090cda1461c32835333250789b8bd1bf1a6.jsonnew file mode 100644index 0000000000..f6da207cdc--- /dev/null+++ b/.sqlx/query-200af5f502688067fe0ee28203bb8090cda1461c32835333250789b8bd1bf1a6.json@@ -0,0 +1,14 @@+{+ "db_name": "PostgreSQL",+ "query": "UPDATE calendar_backfill_jobs SET status = 'failed' WHERE id = $1",+ "describe": {+ "columns": [],+ "parameters": {+ "Left": [+ "Uuid"+ ]+ },+ "nullable": []+ },+ "hash": "200af5f502688067fe0ee28203bb8090cda1461c32835333250789b8bd1bf1a6"+}diff --git a/.sqlx/query-20d5598c949a2bc87254a7216d6f7111a30b47706466c50aa24f365c18456ec4.json b/.sqlx/query-20d5598c949a2bc87254a7216d6f7111a30b47706466c50aa24f365c18456ec4.jsonnew file mode 100644index 0000000000..b1600d87dc--- /dev/null+++ b/.sqlx/query-20d5598c949a2bc87254a7216d6f7111a30b47706466c50aa24f365c18456ec4.json@@ -0,0 +1,14 @@+{+ "db_name": "PostgreSQL",+ "query": "DELETE FROM email_link_google_scopes WHERE link_id = $1",+ "describe": {+ "columns": [],+ "parameters": {+ "Left": [+ "Uuid"+ ]+ },+ "nullable": []+ },+ "hash": "20d5598c949a2bc87254a7216d6f7111a30b47706466c50aa24f365c18456ec4"+}diff --git a/.sqlx/query-21ff1136b1a1f1ca264f4a651d6d84da2800b4109928023c81f7bfd2bb9e5749.json b/.sqlx/query-21ff1136b1a1f1ca264f4a651d6d84da2800b4109928023c81f7bfd2bb9e5749.jsondeleted file mode 100644index a900455795..0000000000--- a/.sqlx/query-21ff1136b1a1f1ca264f4a651d6d84da2800b4109928023c81f7bfd2bb9e5749.json+++ /dev/null@@ -1,44 +0,0 @@-{- "db_name": "PostgreSQL",- "query": "\n INSERT INTO calendar_event_sources (\n id, event_id, source_link_id, source_kind, account_id, calendar_id,\n provider_event_id, provider_recurring_event_id,\n provider_etag, raw_payload, source_sequence,\n source_updated_at, normalized_payload,\n title, description, location, event_type, visibility, transparency,\n is_read_only, reminders_use_default, reminder_overrides,\n creator_email, creator_name\n )\n VALUES (\n $1, $2, $3, 'google', $4, $5, $6, $7, $8, $9,\n $10, $11, $12,\n $13, $14, $15, $16, $17, $18,\n $19, $20, $21,\n $22, $23\n )\n ON CONFLICT (account_id, calendar_id, provider_event_id)\n WHERE source_kind = 'google'\n DO UPDATE SET\n event_id = EXCLUDED.event_id,\n provider_recurring_event_id = EXCLUDED.provider_recurring_event_id,\n provider_etag = EXCLUDED.provider_etag,\n raw_payload = EXCLUDED.raw_payload,\n source_sequence = EXCLUDED.source_sequence,\n source_updated_at = EXCLUDED.source_updated_at,\n normalized_payload = EXCLUDED.normalized_payload,\n title = EXCLUDED.title,\n description = EXCLUDED.description,\n location = EXCLUDED.location,\n event_type = EXCLUDED.event_type,\n visibility = EXCLUDED.visibility,\n transparency = EXCLUDED.transparency,\n is_read_only = EXCLUDED.is_read_only,\n reminders_use_default = EXCLUDED.reminders_use_default,\n reminder_overrides = EXCLUDED.reminder_overrides,\n creator_email = EXCLUDED.creator_email,\n creator_name = EXCLUDED.creator_name,\n last_seen_at = now()\n WHERE\n EXCLUDED.source_sequence > calendar_event_sources.source_sequence\n OR (\n EXCLUDED.source_sequence = calendar_event_sources.source_sequence\n AND EXCLUDED.source_updated_at >= calendar_event_sources.source_updated_at\n )\n RETURNING id\n ",- "describe": {- "columns": [- {- "ordinal": 0,- "name": "id",- "type_info": "Uuid"- }- ],- "parameters": {- "Left": [- "Uuid",- "Uuid",- "Uuid",- "Uuid",- "Uuid",- "Text",- "Text",- "Text",- "Jsonb",- "Int4",- "Timestamptz",- "Jsonb",- "Text",- "Text",- "Text",- "Text",- "Text",- "Text",- "Bool",- "Bool",- "Jsonb",- "Text",- "Text"- ]- },- "nullable": [- false- ]- },- "hash": "21ff1136b1a1f1ca264f4a651d6d84da2800b4109928023c81f7bfd2bb9e5749"-}diff --git a/.sqlx/query-23a5ade6bad11749a69aebfee0b259db5d80daeb2ca9afb0daeca5273e494869.json b/.sqlx/query-23a5ade6bad11749a69aebfee0b259db5d80daeb2ca9afb0daeca5273e494869.jsonnew file mode 100644index 0000000000..5c9d683260--- /dev/null+++ b/.sqlx/query-23a5ade6bad11749a69aebfee0b259db5d80daeb2ca9afb0daeca5273e494869.json@@ -0,0 +1,28 @@+{+ "db_name": "PostgreSQL",+ "query": "SELECT sync_status, last_sync_error FROM calendar_accounts WHERE id = $1",+ "describe": {+ "columns": [+ {+ "ordinal": 0,+ "name": "sync_status",+ "type_info": "Text"+ },+ {+ "ordinal": 1,+ "name": "last_sync_error",+ "type_info": "Text"+ }+ ],+ "parameters": {+ "Left": [+ "Uuid"+ ]+ },+ "nullable": [+ false,+ true+ ]+ },+ "hash": "23a5ade6bad11749a69aebfee0b259db5d80daeb2ca9afb0daeca5273e494869"+}diff --git a/.sqlx/query-23d9f97b2e79c6cb15fc6cf68e74c892f7e0d561597bd7aaac3b7cb8694a4522.json b/.sqlx/query-23d9f97b2e79c6cb15fc6cf68e74c892f7e0d561597bd7aaac3b7cb8694a4522.jsonnew file mode 100644index 0000000000..5d0ad6f28b--- /dev/null+++ b/.sqlx/query-23d9f97b2e79c6cb15fc6cf68e74c892f7e0d561597bd7aaac3b7cb8694a4522.json@@ -0,0 +1,16 @@+{+ "db_name": "PostgreSQL",+ "query": "\n INSERT INTO macro_user_links (primary_macro_id, child_macro_id, link_id)\n VALUES ($1, $2, $3)\n ",+ "describe": {+ "columns": [],+ "parameters": {+ "Left": [+ "Text",+ "Text",+ "Uuid"+ ]+ },+ "nullable": []+ },+ "hash": "23d9f97b2e79c6cb15fc6cf68e74c892f7e0d561597bd7aaac3b7cb8694a4522"+}diff --git a/.sqlx/query-26f0041032093a4f2feb8b03220d11a3a22170973971724deb216fd7a03c144d.json b/.sqlx/query-26f0041032093a4f2feb8b03220d11a3a22170973971724deb216fd7a03c144d.jsonnew file mode 100644index 0000000000..a0e101f43b--- /dev/null+++ b/.sqlx/query-26f0041032093a4f2feb8b03220d11a3a22170973971724deb216fd7a03c144d.json@@ -0,0 +1,39 @@+{+ "db_name": "PostgreSQL",+ "query": "\n WITH members AS (\n SELECT teammate.user_id\n FROM team_user viewer JOIN team_user teammate ON teammate.team_id = viewer.team_id\n WHERE viewer.user_id = $1 AND teammate.user_id <> $1\n UNION SELECT $1::text WHERE $2\n ), visible_accounts AS MATERIALIZED (\n SELECT members.user_id, account.id AS account_id\n FROM members JOIN calendar_accounts account ON account.owner_id = members.user_id\n WHERE account.sync_status <> 'disabled'\n UNION\n SELECT members.user_id, account.id AS account_id\n FROM members\n JOIN macro_user_links link ON link.primary_macro_id = members.user_id\n JOIN calendar_accounts account ON account.email_link_id = link.link_id\n WHERE account.sync_status <> 'disabled'\n )\n SELECT members.user_id AS \"user_id!\",\n COALESCE(policy.sharing, 'busy_only') AS \"sharing!\",\n COALESCE(bool_and(\n account.sync_status IN ('ready', 'syncing') AND account.last_sync_error IS NULL\n AND COALESCE(account.last_synced_at > now() - interval '15 minutes', false)\n AND calendar.last_sync_error IS NULL\n AND COALESCE(calendar.materialized_starts_at <= $3 AND calendar.materialized_ends_at >= $4\n AND calendar.materialized_start_date <= $5 AND calendar.materialized_end_date >= $6, false)\n AND calendar.synced_at IS NOT NULL AND calendar.snapshot_normalization_version >= 1\n AND NOT EXISTS (\n SELECT 1 FROM calendar_event_sources pending_source\n WHERE pending_source.calendar_id = calendar.id\n AND (pending_source.provider_access_role IS NULL\n OR pending_source.provider_access_role IS DISTINCT FROM calendar.access_role)\n )\n ), false) AS \"ready!\"\n FROM members LEFT JOIN calendar_team_sharing policy ON policy.user_id = members.user_id\n LEFT JOIN visible_accounts visible ON visible.user_id = members.user_id\n LEFT JOIN calendar_accounts account ON account.id = visible.account_id\n LEFT JOIN calendars calendar ON calendar.account_id = account.id AND NOT calendar.is_deleted\n GROUP BY members.user_id, policy.sharing\n ORDER BY members.user_id\n ",+ "describe": {+ "columns": [+ {+ "ordinal": 0,+ "name": "user_id!",+ "type_info": "Text"+ },+ {+ "ordinal": 1,+ "name": "sharing!",+ "type_info": "Text"+ },+ {+ "ordinal": 2,+ "name": "ready!",+ "type_info": "Bool"+ }+ ],+ "parameters": {+ "Left": [+ "Text",+ "Bool",+ "Timestamptz",+ "Timestamptz",+ "Date",+ "Date"+ ]+ },+ "nullable": [+ null,+ null,+ null+ ]+ },+ "hash": "26f0041032093a4f2feb8b03220d11a3a22170973971724deb216fd7a03c144d"+}diff --git a/.sqlx/query-271cabf16f8165dbf9cfe5fdb4dbea06aed255f7435ab325972cce7e5f118a9f.json b/.sqlx/query-271cabf16f8165dbf9cfe5fdb4dbea06aed255f7435ab325972cce7e5f118a9f.jsonnew file mode 100644index 0000000000..8efb137671--- /dev/null+++ b/.sqlx/query-271cabf16f8165dbf9cfe5fdb4dbea06aed255f7435ab325972cce7e5f118a9f.json@@ -0,0 +1,34 @@+{+ "db_name": "PostgreSQL",+ "query": "\n SELECT\n granted_scopes,\n grant_version,\n (calendar_disabled_at IS NOT NULL) AS \"opted_out!\"\n FROM email_link_google_scopes\n WHERE link_id = $1\n ",+ "describe": {+ "columns": [+ {+ "ordinal": 0,+ "name": "granted_scopes",+ "type_info": "TextArray"+ },+ {+ "ordinal": 1,+ "name": "grant_version",+ "type_info": "Int8"+ },+ {+ "ordinal": 2,+ "name": "opted_out!",+ "type_info": "Bool"+ }+ ],+ "parameters": {+ "Left": [+ "Uuid"+ ]+ },+ "nullable": [+ false,+ false,+ null+ ]+ },+ "hash": "271cabf16f8165dbf9cfe5fdb4dbea06aed255f7435ab325972cce7e5f118a9f"+}diff --git a/.sqlx/query-2c86898008635070716de7fdbcbbcab822deaf422c400722f74fc7a586955421.json b/.sqlx/query-2c86898008635070716de7fdbcbbcab822deaf422c400722f74fc7a586955421.jsondeleted file mode 100644index a717c9b91d..0000000000--- a/.sqlx/query-2c86898008635070716de7fdbcbbcab822deaf422c400722f74fc7a586955421.json+++ /dev/null@@ -1,14 +0,0 @@-{- "db_name": "PostgreSQL",- "query": "\n UPDATE calendar_accounts\n SET sync_status = 'syncing',\n last_sync_error = NULL,\n updated_at = now()\n WHERE email_link_id = $1\n ",- "describe": {- "columns": [],- "parameters": {- "Left": [- "Uuid"- ]- },- "nullable": []- },- "hash": "2c86898008635070716de7fdbcbbcab822deaf422c400722f74fc7a586955421"-}diff --git a/.sqlx/query-2e37770ebdaebc9783b9151906507abeafbfe023185b1dfd99ec8359863eadc8.json b/.sqlx/query-2e37770ebdaebc9783b9151906507abeafbfe023185b1dfd99ec8359863eadc8.jsonnew file mode 100644index 0000000000..357db13e7e--- /dev/null+++ b/.sqlx/query-2e37770ebdaebc9783b9151906507abeafbfe023185b1dfd99ec8359863eadc8.json@@ -0,0 +1,17 @@+{+ "db_name": "PostgreSQL",+ "query": "UPDATE calendar_accounts SET sync_status=$2,last_synced_at=CASE WHEN $3 THEN now()-interval '16 minutes' ELSE now() END,last_sync_error=$4 WHERE id=$1",+ "describe": {+ "columns": [],+ "parameters": {+ "Left": [+ "Uuid",+ "Text",+ "Bool",+ "Text"+ ]+ },+ "nullable": []+ },+ "hash": "2e37770ebdaebc9783b9151906507abeafbfe023185b1dfd99ec8359863eadc8"+}diff --git a/.sqlx/query-2fb0911e795e7c12298a5b1ee3b9a532c4f336ee483fa5219d8e27848854812b.json b/.sqlx/query-2fb0911e795e7c12298a5b1ee3b9a532c4f336ee483fa5219d8e27848854812b.jsonnew file mode 100644index 0000000000..f076f1e3da--- /dev/null+++ b/.sqlx/query-2fb0911e795e7c12298a5b1ee3b9a532c4f336ee483fa5219d8e27848854812b.json@@ -0,0 +1,34 @@+{+ "db_name": "PostgreSQL",+ "query": "\n SELECT\n l.updated_at AS \"link_updated_at!\",\n g.granted_scopes AS \"side_scopes!\",\n g.grant_version AS \"side_version!\"\n FROM email_links l\n JOIN email_link_google_scopes g ON g.link_id = l.id\n WHERE l.id = $1\n ",+ "describe": {+ "columns": [+ {+ "ordinal": 0,+ "name": "link_updated_at!",+ "type_info": "Timestamptz"+ },+ {+ "ordinal": 1,+ "name": "side_scopes!",+ "type_info": "TextArray"+ },+ {+ "ordinal": 2,+ "name": "side_version!",+ "type_info": "Int8"+ }+ ],+ "parameters": {+ "Left": [+ "Uuid"+ ]+ },+ "nullable": [+ false,+ false,+ false+ ]+ },+ "hash": "2fb0911e795e7c12298a5b1ee3b9a532c4f336ee483fa5219d8e27848854812b"+}diff --git a/.sqlx/query-32a3fe8bf63bb740886a60758461b4b7e2f0c1c5ac6dcab392bae63d69b584d0.json b/.sqlx/query-32a3fe8bf63bb740886a60758461b4b7e2f0c1c5ac6dcab392bae63d69b584d0.jsonnew file mode 100644index 0000000000..e1e3810f6e--- /dev/null+++ b/.sqlx/query-32a3fe8bf63bb740886a60758461b4b7e2f0c1c5ac6dcab392bae63d69b584d0.json@@ -0,0 +1,14 @@+{+ "db_name": "PostgreSQL",+ "query": "UPDATE calendars SET snapshot_normalization_version=1 WHERE account_id=$1",+ "describe": {+ "columns": [],+ "parameters": {+ "Left": [+ "Uuid"+ ]+ },+ "nullable": []+ },+ "hash": "32a3fe8bf63bb740886a60758461b4b7e2f0c1c5ac6dcab392bae63d69b584d0"+}diff --git a/.sqlx/query-34522f084618ec8c439d4d7141f855519abb2e8789e29b68e31fe07037eaebaa.json b/.sqlx/query-34522f084618ec8c439d4d7141f855519abb2e8789e29b68e31fe07037eaebaa.jsonnew file mode 100644index 0000000000..e9cbd2ca63--- /dev/null+++ b/.sqlx/query-34522f084618ec8c439d4d7141f855519abb2e8789e29b68e31fe07037eaebaa.json@@ -0,0 +1,14 @@+{+ "db_name": "PostgreSQL",+ "query": "UPDATE calendars SET snapshot_normalization_version=1 WHERE account_id IN (SELECT id FROM calendar_accounts WHERE owner_id=ANY($1::text[]))",+ "describe": {+ "columns": [],+ "parameters": {+ "Left": [+ "TextArray"+ ]+ },+ "nullable": []+ },+ "hash": "34522f084618ec8c439d4d7141f855519abb2e8789e29b68e31fe07037eaebaa"+}diff --git a/.sqlx/query-34c9000fb1ca9c78cae15dab3b65da27d1f89f1a2cf825523cb96315f38ba850.json b/.sqlx/query-34c9000fb1ca9c78cae15dab3b65da27d1f89f1a2cf825523cb96315f38ba850.jsonnew file mode 100644index 0000000000..86c2f86be9--- /dev/null+++ b/.sqlx/query-34c9000fb1ca9c78cae15dab3b65da27d1f89f1a2cf825523cb96315f38ba850.json@@ -0,0 +1,22 @@+{+ "db_name": "PostgreSQL",+ "query": "\n SELECT DISTINCT teammate.user_id\n FROM team_user membership\n JOIN team_user teammate ON teammate.team_id = membership.team_id\n WHERE membership.user_id = ANY($1::text[])\n UNION\n SELECT unnest($1::text[])\n ",+ "describe": {+ "columns": [+ {+ "ordinal": 0,+ "name": "user_id",+ "type_info": "Text"+ }+ ],+ "parameters": {+ "Left": [+ "TextArray"+ ]+ },+ "nullable": [+ null+ ]+ },+ "hash": "34c9000fb1ca9c78cae15dab3b65da27d1f89f1a2cf825523cb96315f38ba850"+}diff --git a/.sqlx/query-354282687eab48f146f07c5645e912454428fd700d977d2154f1ed2f48cd242d.json b/.sqlx/query-354282687eab48f146f07c5645e912454428fd700d977d2154f1ed2f48cd242d.jsonnew file mode 100644index 0000000000..399bd1007e--- /dev/null+++ b/.sqlx/query-354282687eab48f146f07c5645e912454428fd700d977d2154f1ed2f48cd242d.json@@ -0,0 +1,22 @@+{+ "db_name": "PostgreSQL",+ "query": "SELECT source.provider_access_role = calendar.access_role AS \"eligible!\" FROM calendar_event_sources source JOIN calendars calendar ON calendar.id=source.calendar_id WHERE source.event_id=$1",+ "describe": {+ "columns": [+ {+ "ordinal": 0,+ "name": "eligible!",+ "type_info": "Bool"+ }+ ],+ "parameters": {+ "Left": [+ "Uuid"+ ]+ },+ "nullable": [+ null+ ]+ },+ "hash": "354282687eab48f146f07c5645e912454428fd700d977d2154f1ed2f48cd242d"+}diff --git a/.sqlx/query-35dfe22e0fef3729d34e6e767abbaeb356c636818204b2e858f9498f504e077e.json b/.sqlx/query-35dfe22e0fef3729d34e6e767abbaeb356c636818204b2e858f9498f504e077e.jsonnew file mode 100644index 0000000000..d2f3870625--- /dev/null+++ b/.sqlx/query-35dfe22e0fef3729d34e6e767abbaeb356c636818204b2e858f9498f504e077e.json@@ -0,0 +1,14 @@+{+ "db_name": "PostgreSQL",+ "query": "UPDATE calendars SET is_deleted = true WHERE id = $1",+ "describe": {+ "columns": [],+ "parameters": {+ "Left": [+ "Uuid"+ ]+ },+ "nullable": []+ },+ "hash": "35dfe22e0fef3729d34e6e767abbaeb356c636818204b2e858f9498f504e077e"+}diff --git a/.sqlx/query-3673d629b8923763a5e72e25dadd558ade112c8142bb86ca6b87585b1c126573.json b/.sqlx/query-3673d629b8923763a5e72e25dadd558ade112c8142bb86ca6b87585b1c126573.jsonnew file mode 100644index 0000000000..44a03efc03--- /dev/null+++ b/.sqlx/query-3673d629b8923763a5e72e25dadd558ade112c8142bb86ca6b87585b1c126573.json@@ -0,0 +1,22 @@+{+ "db_name": "PostgreSQL",+ "query": "SELECT title FROM calendar_events WHERE id = $1",+ "describe": {+ "columns": [+ {+ "ordinal": 0,+ "name": "title",+ "type_info": "Text"+ }+ ],+ "parameters": {+ "Left": [+ "Uuid"+ ]+ },+ "nullable": [+ false+ ]+ },+ "hash": "3673d629b8923763a5e72e25dadd558ade112c8142bb86ca6b87585b1c126573"+}diff --git a/.sqlx/query-36b5dba37448891e85fe3816fe8eee004599d915ecf96708150ba484cb2ac36a.json b/.sqlx/query-36b5dba37448891e85fe3816fe8eee004599d915ecf96708150ba484cb2ac36a.jsonnew file mode 100644index 0000000000..068782e3dd--- /dev/null+++ b/.sqlx/query-36b5dba37448891e85fe3816fe8eee004599d915ecf96708150ba484cb2ac36a.json@@ -0,0 +1,22 @@+{+ "db_name": "PostgreSQL",+ "query": "SELECT email_address FROM email_links WHERE id = $1",+ "describe": {+ "columns": [+ {+ "ordinal": 0,+ "name": "email_address",+ "type_info": "Varchar"+ }+ ],+ "parameters": {+ "Left": [+ "Uuid"+ ]+ },+ "nullable": [+ false+ ]+ },+ "hash": "36b5dba37448891e85fe3816fe8eee004599d915ecf96708150ba484cb2ac36a"+}diff --git a/.sqlx/query-37f6d5aaa0bdb275bbeb0d9939007dbdf9e08508af65b18fcbfe63417791741f.json b/.sqlx/query-37f6d5aaa0bdb275bbeb0d9939007dbdf9e08508af65b18fcbfe63417791741f.jsonnew file mode 100644index 0000000000..0c9fc51736--- /dev/null+++ b/.sqlx/query-37f6d5aaa0bdb275bbeb0d9939007dbdf9e08508af65b18fcbfe63417791741f.json@@ -0,0 +1,14 @@+{+ "db_name": "PostgreSQL",+ "query": "UPDATE calendars SET synced_at=now() WHERE account_id IN (SELECT id FROM calendar_accounts WHERE owner_id=ANY($1::text[]))",+ "describe": {+ "columns": [],+ "parameters": {+ "Left": [+ "TextArray"+ ]+ },+ "nullable": []+ },+ "hash": "37f6d5aaa0bdb275bbeb0d9939007dbdf9e08508af65b18fcbfe63417791741f"+}diff --git a/.sqlx/query-3947c3b25e46cc39c6f42d206d51cf8ad81380582634217b037bb56aee69e39a.json b/.sqlx/query-3947c3b25e46cc39c6f42d206d51cf8ad81380582634217b037bb56aee69e39a.jsonnew file mode 100644index 0000000000..3b1be0f346--- /dev/null+++ b/.sqlx/query-3947c3b25e46cc39c6f42d206d51cf8ad81380582634217b037bb56aee69e39a.json@@ -0,0 +1,34 @@+{+ "db_name": "PostgreSQL",+ "query": "\n SELECT\n (SELECT title FROM calendar_events WHERE id = $1) AS \"title!\",\n (SELECT calendar_id FROM calendar_event_sources WHERE event_id = $1) AS \"calendar_id\",\n (SELECT count(*) FROM calendar_event_sources WHERE event_id = $1) AS \"sources!\"\n ",+ "describe": {+ "columns": [+ {+ "ordinal": 0,+ "name": "title!",+ "type_info": "Text"+ },+ {+ "ordinal": 1,+ "name": "calendar_id",+ "type_info": "Uuid"+ },+ {+ "ordinal": 2,+ "name": "sources!",+ "type_info": "Int8"+ }+ ],+ "parameters": {+ "Left": [+ "Uuid"+ ]+ },+ "nullable": [+ null,+ null,+ null+ ]+ },+ "hash": "3947c3b25e46cc39c6f42d206d51cf8ad81380582634217b037bb56aee69e39a"+}diff --git a/.sqlx/query-3b2dbc5b0affbcf53cfe76fe5210b7e4d96dad61a84d4a87dced9d2f66dc6ff1.json b/.sqlx/query-3b2dbc5b0affbcf53cfe76fe5210b7e4d96dad61a84d4a87dced9d2f66dc6ff1.jsonnew file mode 100644index 0000000000..53c3c181dc--- /dev/null+++ b/.sqlx/query-3b2dbc5b0affbcf53cfe76fe5210b7e4d96dad61a84d4a87dced9d2f66dc6ff1.json@@ -0,0 +1,15 @@+{+ "db_name": "PostgreSQL",+ "query": "INSERT INTO team (id, name, owner_id) VALUES ($1, 'Team', $2)",+ "describe": {+ "columns": [],+ "parameters": {+ "Left": [+ "Uuid",+ "Text"+ ]+ },+ "nullable": []+ },+ "hash": "3b2dbc5b0affbcf53cfe76fe5210b7e4d96dad61a84d4a87dced9d2f66dc6ff1"+}diff --git a/.sqlx/query-3ba0c278a5da5c6d0c96ce0a8582fb9a15268c8e06d63ad779502d7ef363d04a.json b/.sqlx/query-3ba0c278a5da5c6d0c96ce0a8582fb9a15268c8e06d63ad779502d7ef363d04a.jsonnew file mode 100644index 0000000000..059321cdac--- /dev/null+++ b/.sqlx/query-3ba0c278a5da5c6d0c96ce0a8582fb9a15268c8e06d63ad779502d7ef363d04a.json@@ -0,0 +1,14 @@+{+ "db_name": "PostgreSQL",+ "query": "UPDATE calendars SET sync_token='legacy-after-strict',synced_at=now() WHERE id=$1",+ "describe": {+ "columns": [],+ "parameters": {+ "Left": [+ "Uuid"+ ]+ },+ "nullable": []+ },+ "hash": "3ba0c278a5da5c6d0c96ce0a8582fb9a15268c8e06d63ad779502d7ef363d04a"+}diff --git a/.sqlx/query-3ca251d8dd2b823ddc85a8c7a2b88b6769ba94f57ac9f4f9d61008cfcce01bfc.json b/.sqlx/query-3ca251d8dd2b823ddc85a8c7a2b88b6769ba94f57ac9f4f9d61008cfcce01bfc.jsonnew file mode 100644index 0000000000..3fd610668f--- /dev/null+++ b/.sqlx/query-3ca251d8dd2b823ddc85a8c7a2b88b6769ba94f57ac9f4f9d61008cfcce01bfc.json@@ -0,0 +1,76 @@+{+ "db_name": "PostgreSQL",+ "query": "\n SELECT title, event_type, is_read_only, transparency, visibility,\n reminders_use_default, reminder_overrides, creator_email,\n sequence, schedule_updated_at\n FROM calendar_events WHERE id = $1\n ",+ "describe": {+ "columns": [+ {+ "ordinal": 0,+ "name": "title",+ "type_info": "Text"+ },+ {+ "ordinal": 1,+ "name": "event_type",+ "type_info": "Text"+ },+ {+ "ordinal": 2,+ "name": "is_read_only",+ "type_info": "Bool"+ },+ {+ "ordinal": 3,+ "name": "transparency",+ "type_info": "Text"+ },+ {+ "ordinal": 4,+ "name": "visibility",+ "type_info": "Text"+ },+ {+ "ordinal": 5,+ "name": "reminders_use_default",+ "type_info": "Bool"+ },+ {+ "ordinal": 6,+ "name": "reminder_overrides",+ "type_info": "Jsonb"+ },+ {+ "ordinal": 7,+ "name": "creator_email",+ "type_info": "Text"+ },+ {+ "ordinal": 8,+ "name": "sequence",+ "type_info": "Int4"+ },+ {+ "ordinal": 9,+ "name": "schedule_updated_at",+ "type_info": "Timestamptz"+ }+ ],+ "parameters": {+ "Left": [+ "Uuid"+ ]+ },+ "nullable": [+ false,+ false,+ false,+ false,+ false,+ false,+ false,+ true,+ false,+ false+ ]+ },+ "hash": "3ca251d8dd2b823ddc85a8c7a2b88b6769ba94f57ac9f4f9d61008cfcce01bfc"+}diff --git a/.sqlx/query-3d43ebebe0fd380b70637a89ad566414140d126a3d1993515199fbe2112409af.json b/.sqlx/query-3d43ebebe0fd380b70637a89ad566414140d126a3d1993515199fbe2112409af.jsonnew file mode 100644index 0000000000..a9c2733911--- /dev/null+++ b/.sqlx/query-3d43ebebe0fd380b70637a89ad566414140d126a3d1993515199fbe2112409af.json@@ -0,0 +1,22 @@+{+ "db_name": "PostgreSQL",+ "query": "SELECT email_address::text AS \"email!\" FROM email_links WHERE macro_id = $1",+ "describe": {+ "columns": [+ {+ "ordinal": 0,+ "name": "email!",+ "type_info": "Text"+ }+ ],+ "parameters": {+ "Left": [+ "Text"+ ]+ },+ "nullable": [+ null+ ]+ },+ "hash": "3d43ebebe0fd380b70637a89ad566414140d126a3d1993515199fbe2112409af"+}diff --git a/.sqlx/query-3deead68fac93d24fea0bdab60d12eed72e8ae64467266a23a298460bbffeafa.json b/.sqlx/query-3deead68fac93d24fea0bdab60d12eed72e8ae64467266a23a298460bbffeafa.jsonnew file mode 100644index 0000000000..89625d37fc--- /dev/null+++ b/.sqlx/query-3deead68fac93d24fea0bdab60d12eed72e8ae64467266a23a298460bbffeafa.json@@ -0,0 +1,14 @@+{+ "db_name": "PostgreSQL",+ "query": "UPDATE calendar_accounts SET sync_status='ready',last_synced_at=now(),last_sync_error=NULL WHERE owner_id=ANY($1::text[]) AND sync_status<>'disabled'",+ "describe": {+ "columns": [],+ "parameters": {+ "Left": [+ "TextArray"+ ]+ },+ "nullable": []+ },+ "hash": "3deead68fac93d24fea0bdab60d12eed72e8ae64467266a23a298460bbffeafa"+}diff --git a/.sqlx/query-41f742e117f90b536a9e5b1780188d69354cbffb1f779e9bccc874613d6287d3.json b/.sqlx/query-41f742e117f90b536a9e5b1780188d69354cbffb1f779e9bccc874613d6287d3.jsonnew file mode 100644index 0000000000..b48fdcf509--- /dev/null+++ b/.sqlx/query-41f742e117f90b536a9e5b1780188d69354cbffb1f779e9bccc874613d6287d3.json@@ -0,0 +1,60 @@+{+ "db_name": "PostgreSQL",+ "query": "\n SELECT\n (SELECT count(*) FROM calendar_accounts WHERE email_link_id = $1) AS \"accounts!\",\n (SELECT count(*) FROM calendars WHERE account_id = $2) AS \"calendars!\",\n (SELECT count(*) FROM calendar_events WHERE source_link_id = $1) AS \"events!\",\n (SELECT count(*) FROM calendar_event_sources WHERE source_link_id = $1) AS \"sources!\",\n (SELECT count(*) FROM calendar_event_occurrences WHERE event_id = $3) AS \"occurrences!\",\n (SELECT count(*) FROM calendar_event_reminder_deliveries WHERE event_id = $3) AS \"deliveries!\",\n (SELECT count(*) FROM calendar_backfill_jobs WHERE email_link_id = $1) AS \"jobs!\"\n ",+ "describe": {+ "columns": [+ {+ "ordinal": 0,+ "name": "accounts!",+ "type_info": "Int8"+ },+ {+ "ordinal": 1,+ "name": "calendars!",+ "type_info": "Int8"+ },+ {+ "ordinal": 2,+ "name": "events!",+ "type_info": "Int8"+ },+ {+ "ordinal": 3,+ "name": "sources!",+ "type_info": "Int8"+ },+ {+ "ordinal": 4,+ "name": "occurrences!",+ "type_info": "Int8"+ },+ {+ "ordinal": 5,+ "name": "deliveries!",+ "type_info": "Int8"+ },+ {+ "ordinal": 6,+ "name": "jobs!",+ "type_info": "Int8"+ }+ ],+ "parameters": {+ "Left": [+ "Uuid",+ "Uuid",+ "Uuid"+ ]+ },+ "nullable": [+ null,+ null,+ null,+ null,+ null,+ null,+ null+ ]+ },+ "hash": "41f742e117f90b536a9e5b1780188d69354cbffb1f779e9bccc874613d6287d3"+}diff --git a/.sqlx/query-44aa6e5bbd1c218a0ba6e8678544e31058c23466c4de3168ea0adef13e060b5c.json b/.sqlx/query-44aa6e5bbd1c218a0ba6e8678544e31058c23466c4de3168ea0adef13e060b5c.jsonnew file mode 100644index 0000000000..6dda114ff7--- /dev/null+++ b/.sqlx/query-44aa6e5bbd1c218a0ba6e8678544e31058c23466c4de3168ea0adef13e060b5c.json@@ -0,0 +1,22 @@+{+ "db_name": "PostgreSQL",+ "query": "SELECT snapshot_normalization_version FROM calendars WHERE id=$1",+ "describe": {+ "columns": [+ {+ "ordinal": 0,+ "name": "snapshot_normalization_version",+ "type_info": "Int4"+ }+ ],+ "parameters": {+ "Left": [+ "Uuid"+ ]+ },+ "nullable": [+ false+ ]+ },+ "hash": "44aa6e5bbd1c218a0ba6e8678544e31058c23466c4de3168ea0adef13e060b5c"+}diff --git a/.sqlx/query-47c1191b50d81a7933e3b9680808ab9ed74dd974cdbdad74b3e2b9e1bc9b5778.json b/.sqlx/query-47c1191b50d81a7933e3b9680808ab9ed74dd974cdbdad74b3e2b9e1bc9b5778.jsonnew file mode 100644index 0000000000..4d7e66d596--- /dev/null+++ b/.sqlx/query-47c1191b50d81a7933e3b9680808ab9ed74dd974cdbdad74b3e2b9e1bc9b5778.json@@ -0,0 +1,28 @@+{+ "db_name": "PostgreSQL",+ "query": "SELECT sync_token, synced_at FROM calendars WHERE id = $1",+ "describe": {+ "columns": [+ {+ "ordinal": 0,+ "name": "sync_token",+ "type_info": "Text"+ },+ {+ "ordinal": 1,+ "name": "synced_at",+ "type_info": "Timestamptz"+ }+ ],+ "parameters": {+ "Left": [+ "Uuid"+ ]+ },+ "nullable": [+ true,+ true+ ]+ },+ "hash": "47c1191b50d81a7933e3b9680808ab9ed74dd974cdbdad74b3e2b9e1bc9b5778"+}diff --git a/.sqlx/query-4a06ad42fcddd9cbefe1d087bba871552c8dbb81f8350feac05fa5a02c10e21c.json b/.sqlx/query-4a06ad42fcddd9cbefe1d087bba871552c8dbb81f8350feac05fa5a02c10e21c.jsondeleted file mode 100644index 613507f1aa..0000000000--- a/.sqlx/query-4a06ad42fcddd9cbefe1d087bba871552c8dbb81f8350feac05fa5a02c10e21c.json+++ /dev/null@@ -1,87 +0,0 @@-{- "db_name": "PostgreSQL",- "query": "\n SELECT\n owner_id AS \"owner_id!\",\n event_id AS \"event_id!\",\n ical_uid AS \"ical_uid!\",\n occurrence_key AS \"occurrence_key!\",\n title AS \"title!\",\n visibility AS \"visibility!\",\n time_zone,\n occurrence_starts_at AS \"occurrence_starts_at?\",\n occurrence_ends_at AS \"occurrence_ends_at?\",\n occurrence_start_date AS \"occurrence_start_date?\",\n occurrence_end_date AS \"occurrence_end_date?\"\n FROM (\n SELECT DISTINCT ON (event.owner_id, event.ical_uid, occurrence.occurrence_key)\n event.owner_id,\n occurrence.event_id,\n event.ical_uid,\n occurrence.occurrence_key,\n source.title,\n source.visibility,\n event.time_zone,\n occurrence.starts_at AS occurrence_starts_at,\n occurrence.ends_at AS occurrence_ends_at,\n occurrence.start_date AS occurrence_start_date,\n occurrence.end_date AS occurrence_end_date,\n COALESCE(\n occurrence.starts_at,\n occurrence.start_date::timestamp AT TIME ZONE 'UTC'\n ) AS occurrence_ordering\n FROM calendar_event_occurrences occurrence\n JOIN calendar_events event ON event.id = occurrence.event_id\n JOIN calendar_event_sources source ON source.event_id = event.id\n JOIN calendars calendar\n ON calendar.id = source.calendar_id\n AND calendar.is_primary\n AND NOT calendar.is_deleted\n JOIN calendar_accounts account\n ON account.id = source.account_id\n AND account.sync_status <> 'disabled'\n WHERE occurrence.owner_id IN (\n SELECT teammate.user_id\n FROM team_user membership\n JOIN team_user teammate ON teammate.team_id = membership.team_id\n WHERE membership.user_id = $1\n AND teammate.user_id <> $1\n )\n AND source.event_type = 'out_of_office'\n AND event.status <> 'cancelled'\n AND NOT occurrence.is_cancelled\n AND (\n occurrence.timed_span && tstzrange($2, $3, '[)')\n OR occurrence.day_span && daterange($4, $5, '[)')\n )\n ORDER BY\n event.owner_id,\n event.ical_uid,\n occurrence.occurrence_key,\n occurrence.event_id,\n source.source_sequence DESC,\n source.source_updated_at DESC,\n source.id DESC\n ) occurrence\n ORDER BY\n occurrence.occurrence_ordering,\n occurrence.event_id,\n occurrence.occurrence_key\n LIMIT $6\n ",- "describe": {- "columns": [- {- "ordinal": 0,- "name": "owner_id!",- "type_info": "Text"- },- {- "ordinal": 1,- "name": "event_id!",- "type_info": "Uuid"- },- {- "ordinal": 2,- "name": "ical_uid!",- "type_info": "Text"- },- {- "ordinal": 3,- "name": "occurrence_key!",- "type_info": "Text"- },- {- "ordinal": 4,- "name": "title!",- "type_info": "Text"- },- {- "ordinal": 5,- "name": "visibility!",- "type_info": "Text"- },- {- "ordinal": 6,- "name": "time_zone",- "type_info": "Text"- },- {- "ordinal": 7,- "name": "occurrence_starts_at?",- "type_info": "Timestamptz"- },- {- "ordinal": 8,- "name": "occurrence_ends_at?",- "type_info": "Timestamptz"- },- {- "ordinal": 9,- "name": "occurrence_start_date?",- "type_info": "Date"- },- {- "ordinal": 10,- "name": "occurrence_end_date?",- "type_info": "Date"- }- ],- "parameters": {- "Left": [- "Text",- "Timestamptz",- "Timestamptz",- "Date",- "Date",- "Int8"- ]- },- "nullable": [- false,- false,- false,- false,- false,- false,- true,- true,- true,- true,- true- ]- },- "hash": "4a06ad42fcddd9cbefe1d087bba871552c8dbb81f8350feac05fa5a02c10e21c"-}diff --git a/.sqlx/query-4a3f534eec6987607f0bc891fe69614811cd059ee8ead90f8f54113cb3285304.json b/.sqlx/query-4a3f534eec6987607f0bc891fe69614811cd059ee8ead90f8f54113cb3285304.jsonnew file mode 100644index 0000000000..c46cc487f6--- /dev/null+++ b/.sqlx/query-4a3f534eec6987607f0bc891fe69614811cd059ee8ead90f8f54113cb3285304.json@@ -0,0 +1,14 @@+{+ "db_name": "PostgreSQL",+ "query": "UPDATE calendar_backfill_jobs SET started_at = now() - interval '25 minutes', updated_at = now() - interval '20 minutes' WHERE id = $1",+ "describe": {+ "columns": [],+ "parameters": {+ "Left": [+ "Uuid"+ ]+ },+ "nullable": []+ },+ "hash": "4a3f534eec6987607f0bc891fe69614811cd059ee8ead90f8f54113cb3285304"+}diff --git a/.sqlx/query-4b6fda6b40a7d2ba17f60eedb86f200b4b7528d27f23abbc34ce90c8d23a4680.json b/.sqlx/query-4b6fda6b40a7d2ba17f60eedb86f200b4b7528d27f23abbc34ce90c8d23a4680.jsonnew file mode 100644index 0000000000..faa3bd5e34--- /dev/null+++ b/.sqlx/query-4b6fda6b40a7d2ba17f60eedb86f200b4b7528d27f23abbc34ce90c8d23a4680.json@@ -0,0 +1,14 @@+{+ "db_name": "PostgreSQL",+ "query": "UPDATE calendar_accounts SET sync_status = 'disabled' WHERE id = $1",+ "describe": {+ "columns": [],+ "parameters": {+ "Left": [+ "Uuid"+ ]+ },+ "nullable": []+ },+ "hash": "4b6fda6b40a7d2ba17f60eedb86f200b4b7528d27f23abbc34ce90c8d23a4680"+}diff --git a/.sqlx/query-0523298143e4bd07530dd043ca9ab5db805a5f383023b5d60bb0fa1f0291b870.json b/.sqlx/query-4d90f1f0cb5380c30beb89d71b8cc0955931f96e2c94af1aa69abdb99a7b636c.jsonsimilarity index 51%rename from .sqlx/query-0523298143e4bd07530dd043ca9ab5db805a5f383023b5d60bb0fa1f0291b870.jsonrename to .sqlx/query-4d90f1f0cb5380c30beb89d71b8cc0955931f96e2c94af1aa69abdb99a7b636c.jsonindex b8fca9e0ab..548b8ea804 100644--- a/.sqlx/query-0523298143e4bd07530dd043ca9ab5db805a5f383023b5d60bb0fa1f0291b870.json+++ b/.sqlx/query-4d90f1f0cb5380c30beb89d71b8cc0955931f96e2c94af1aa69abdb99a7b636c.json@@ -1,6 +1,6 @@{"db_name": "PostgreSQL",- "query": "\n SELECT\n event.id AS event_id,\n event.owner_id,\n source.is_read_only,\n source.provider_event_id AS \"provider_event_id!\",\n source.provider_recurring_event_id,\n source.account_id AS \"account_id!\",\n source.calendar_id AS \"calendar_id!\",\n calendar.provider_calendar_id,\n account.email_link_id,\n link.fusionauth_user_id,\n link.email_address,\n link.provider::text AS \"provider!\"\n FROM calendar_events event\n JOIN calendar_event_sources source\n ON source.event_id = event.id\n AND source.source_kind = 'google'\n JOIN calendars calendar ON calendar.id = source.calendar_id\n JOIN calendar_accounts account ON account.id = source.account_id\n JOIN email_links link ON link.id = account.email_link_id\n WHERE event.id = $1\n AND NOT calendar.is_deleted\n AND account.sync_status <> 'disabled'\n AND CASE\n WHEN $3::uuid IS NULL\n THEN source.id = calendar_event_canonical_source_id(event.id)\n ELSE source.calendar_id = $3\n END\n AND (\n event.owner_id = $2\n OR EXISTS (\n SELECT 1\n FROM macro_user_links delegation\n WHERE delegation.link_id = event.source_link_id\n AND delegation.primary_macro_id = $2\n )\n )\n ORDER BY\n source.source_sequence DESC,\n source.source_updated_at DESC,\n source.id DESC\n LIMIT 1\n ",+ "query": "\n SELECT\n event.id AS event_id,\n event.owner_id,\n source.is_read_only,\n source.provider_event_id AS \"provider_event_id!\",\n source.provider_recurring_event_id,\n source.account_id AS \"account_id!\",\n source.calendar_id AS \"calendar_id!\",\n calendar.provider_calendar_id,\n calendar.access_role,\n account.email_link_id,\n link.fusionauth_user_id,\n link.email_address,\n link.provider::text AS \"provider!\"\n FROM calendar_events event\n JOIN calendar_event_sources source\n ON source.event_id = event.id\n AND source.source_kind = 'google'\n JOIN calendars calendar ON calendar.id = source.calendar_id\n AND calendar.account_id = source.account_id\n JOIN calendar_accounts account ON account.id = source.account_id\n JOIN email_links link ON link.id = account.email_link_id\n WHERE event.id = $1\n AND NOT calendar.is_deleted\n AND account.sync_status <> 'disabled'\n AND CASE\n WHEN $3::uuid IS NULL\n THEN source.id = calendar_event_canonical_source_id(event.id)\n ELSE source.calendar_id = $3\n END\n AND (\n event.owner_id = $2\n OR EXISTS (\n SELECT 1\n FROM macro_user_links delegation\n WHERE delegation.link_id = event.source_link_id\n AND delegation.primary_macro_id = $2\n )\n )\n ORDER BY\n source.source_sequence DESC,\n source.source_updated_at DESC,\n source.id DESC\n LIMIT 1\n ","describe": {"columns": [{@@ -45,21 +45,26 @@},{"ordinal": 8,+ "name": "access_role",+ "type_info": "Text"+ },+ {+ "ordinal": 9,"name": "email_link_id","type_info": "Uuid"},{- "ordinal": 9,+ "ordinal": 10,"name": "fusionauth_user_id","type_info": "Text"},{- "ordinal": 10,+ "ordinal": 11,"name": "email_address","type_info": "Varchar"},{- "ordinal": 11,+ "ordinal": 12,"name": "provider!","type_info": "Text"}@@ -80,11 +85,12 @@true,true,false,+ true,false,false,false,null]},- "hash": "0523298143e4bd07530dd043ca9ab5db805a5f383023b5d60bb0fa1f0291b870"+ "hash": "4d90f1f0cb5380c30beb89d71b8cc0955931f96e2c94af1aa69abdb99a7b636c"}diff --git a/.sqlx/query-4fc233f6f1e289e9acb848611c00b92d5c783802d3df1ff5a2893888246a960d.json b/.sqlx/query-4fc233f6f1e289e9acb848611c00b92d5c783802d3df1ff5a2893888246a960d.jsonnew file mode 100644index 0000000000..71d62aeb00--- /dev/null+++ b/.sqlx/query-4fc233f6f1e289e9acb848611c00b92d5c783802d3df1ff5a2893888246a960d.json@@ -0,0 +1,15 @@+{+ "db_name": "PostgreSQL",+ "query": "UPDATE comms_channel_participants SET left_at = now() WHERE channel_id = $1 AND user_id = $2",+ "describe": {+ "columns": [],+ "parameters": {+ "Left": [+ "Uuid",+ "Text"+ ]+ },+ "nullable": []+ },+ "hash": "4fc233f6f1e289e9acb848611c00b92d5c783802d3df1ff5a2893888246a960d"+}diff --git a/.sqlx/query-5075777473ea8c0fcdcb24f0d876b841d60ca91a56fb7c0e554a307b74f01e10.json b/.sqlx/query-5075777473ea8c0fcdcb24f0d876b841d60ca91a56fb7c0e554a307b74f01e10.jsonnew file mode 100644index 0000000000..2974333520--- /dev/null+++ b/.sqlx/query-5075777473ea8c0fcdcb24f0d876b841d60ca91a56fb7c0e554a307b74f01e10.json@@ -0,0 +1,15 @@+{+ "db_name": "PostgreSQL",+ "query": "INSERT INTO calendar_team_sharing(user_id,sharing) VALUES($1,$2)\n ON CONFLICT(user_id) DO UPDATE SET sharing=EXCLUDED.sharing, updated_at=now()",+ "describe": {+ "columns": [],+ "parameters": {+ "Left": [+ "Text",+ "Text"+ ]+ },+ "nullable": []+ },+ "hash": "5075777473ea8c0fcdcb24f0d876b841d60ca91a56fb7c0e554a307b74f01e10"+}diff --git a/.sqlx/query-5244b960cd63a70408aef8ba2b4bc5a8c78819f16c5ff4dbd9dcc5525d3da5ee.json b/.sqlx/query-5244b960cd63a70408aef8ba2b4bc5a8c78819f16c5ff4dbd9dcc5525d3da5ee.jsonnew file mode 100644index 0000000000..43c54438a5--- /dev/null+++ b/.sqlx/query-5244b960cd63a70408aef8ba2b4bc5a8c78819f16c5ff4dbd9dcc5525d3da5ee.json@@ -0,0 +1,17 @@+{+ "db_name": "PostgreSQL",+ "query": "\n INSERT INTO calendar_accounts (\n id, owner_id, email_link_id, provider, provider_account_id\n )\n VALUES ($1, $2, $3, 'google', $4)\n ",+ "describe": {+ "columns": [],+ "parameters": {+ "Left": [+ "Uuid",+ "Text",+ "Uuid",+ "Text"+ ]+ },+ "nullable": []+ },+ "hash": "5244b960cd63a70408aef8ba2b4bc5a8c78819f16c5ff4dbd9dcc5525d3da5ee"+}diff --git a/.sqlx/query-5876b5c9567bd545e7d989557758f66640c38398431fa0cc9d696cdb31844abc.json b/.sqlx/query-5876b5c9567bd545e7d989557758f66640c38398431fa0cc9d696cdb31844abc.jsonnew file mode 100644index 0000000000..1afcc090da--- /dev/null+++ b/.sqlx/query-5876b5c9567bd545e7d989557758f66640c38398431fa0cc9d696cdb31844abc.json@@ -0,0 +1,14 @@+{+ "db_name": "PostgreSQL",+ "query": "UPDATE calendar_accounts SET last_sync_error='provider failure' WHERE id=$1",+ "describe": {+ "columns": [],+ "parameters": {+ "Left": [+ "Uuid"+ ]+ },+ "nullable": []+ },+ "hash": "5876b5c9567bd545e7d989557758f66640c38398431fa0cc9d696cdb31844abc"+}diff --git a/.sqlx/query-5acf6bc7936e4f8ffc693b139cd03c020effbdcd44be2c7cf13a11be639b1bee.json b/.sqlx/query-5acf6bc7936e4f8ffc693b139cd03c020effbdcd44be2c7cf13a11be639b1bee.jsonnew file mode 100644index 0000000000..20a69e65d1--- /dev/null+++ b/.sqlx/query-5acf6bc7936e4f8ffc693b139cd03c020effbdcd44be2c7cf13a11be639b1bee.json@@ -0,0 +1,34 @@+{+ "db_name": "PostgreSQL",+ "query": "\n SELECT title, schedule_updated_at, updated_at\n FROM calendar_events\n WHERE id = $1\n ",+ "describe": {+ "columns": [+ {+ "ordinal": 0,+ "name": "title",+ "type_info": "Text"+ },+ {+ "ordinal": 1,+ "name": "schedule_updated_at",+ "type_info": "Timestamptz"+ },+ {+ "ordinal": 2,+ "name": "updated_at",+ "type_info": "Timestamptz"+ }+ ],+ "parameters": {+ "Left": [+ "Uuid"+ ]+ },+ "nullable": [+ false,+ false,+ false+ ]+ },+ "hash": "5acf6bc7936e4f8ffc693b139cd03c020effbdcd44be2c7cf13a11be639b1bee"+}diff --git a/.sqlx/query-5b45457b0629b66ab1694e99d7ef5119f136035f6b8489934c845c7321eade6e.json b/.sqlx/query-5b45457b0629b66ab1694e99d7ef5119f136035f6b8489934c845c7321eade6e.jsonnew file mode 100644index 0000000000..443cd1a93f--- /dev/null+++ b/.sqlx/query-5b45457b0629b66ab1694e99d7ef5119f136035f6b8489934c845c7321eade6e.json@@ -0,0 +1,14 @@+{+ "db_name": "PostgreSQL",+ "query": "DELETE FROM email_links WHERE id = $1",+ "describe": {+ "columns": [],+ "parameters": {+ "Left": [+ "Uuid"+ ]+ },+ "nullable": []+ },+ "hash": "5b45457b0629b66ab1694e99d7ef5119f136035f6b8489934c845c7321eade6e"+}diff --git a/.sqlx/query-5f3465c9fc4de01bd3f5625f973b36d04c60756d551cf3283e72f930820212e7.json b/.sqlx/query-5f3465c9fc4de01bd3f5625f973b36d04c60756d551cf3283e72f930820212e7.jsonnew file mode 100644index 0000000000..fde18c0d90--- /dev/null+++ b/.sqlx/query-5f3465c9fc4de01bd3f5625f973b36d04c60756d551cf3283e72f930820212e7.json@@ -0,0 +1,34 @@+{+ "db_name": "PostgreSQL",+ "query": "\n SELECT\n (SELECT title FROM calendar_events WHERE id = $1) AS \"title!\",\n (SELECT count(*) FROM calendar_event_occurrences WHERE event_id = $1) AS \"occurrences!\",\n (SELECT count(*) FROM calendar_event_sources WHERE event_id = $1 AND source_kind = 'google') AS \"sources!\"\n ",+ "describe": {+ "columns": [+ {+ "ordinal": 0,+ "name": "title!",+ "type_info": "Text"+ },+ {+ "ordinal": 1,+ "name": "occurrences!",+ "type_info": "Int8"+ },+ {+ "ordinal": 2,+ "name": "sources!",+ "type_info": "Int8"+ }+ ],+ "parameters": {+ "Left": [+ "Uuid"+ ]+ },+ "nullable": [+ null,+ null,+ null+ ]+ },+ "hash": "5f3465c9fc4de01bd3f5625f973b36d04c60756d551cf3283e72f930820212e7"+}diff --git a/.sqlx/query-6024c12e588ebafc6003c0c003f042457a3ff3dbd83da2c22073c848cf21990a.json b/.sqlx/query-6024c12e588ebafc6003c0c003f042457a3ff3dbd83da2c22073c848cf21990a.jsonnew file mode 100644index 0000000000..100186d5a5--- /dev/null+++ b/.sqlx/query-6024c12e588ebafc6003c0c003f042457a3ff3dbd83da2c22073c848cf21990a.json@@ -0,0 +1,14 @@+{+ "db_name": "PostgreSQL",+ "query": "UPDATE calendars SET synced_at=now(),materialized_starts_at='2026-07-01',materialized_ends_at='2026-08-01',materialized_start_date='2026-07-01',materialized_end_date='2026-08-01' WHERE account_id=$1",+ "describe": {+ "columns": [],+ "parameters": {+ "Left": [+ "Uuid"+ ]+ },+ "nullable": []+ },+ "hash": "6024c12e588ebafc6003c0c003f042457a3ff3dbd83da2c22073c848cf21990a"+}diff --git a/.sqlx/query-61f112ac14be228793a81deb0a0bc6b88234ed5758a17953d5a3c5cf23b2a76b.json b/.sqlx/query-61f112ac14be228793a81deb0a0bc6b88234ed5758a17953d5a3c5cf23b2a76b.jsonnew file mode 100644index 0000000000..5702554978--- /dev/null+++ b/.sqlx/query-61f112ac14be228793a81deb0a0bc6b88234ed5758a17953d5a3c5cf23b2a76b.json@@ -0,0 +1,15 @@+{+ "db_name": "PostgreSQL",+ "query": "\n INSERT INTO calendar_backfill_jobs (\n id, email_link_id, kind, grant_version, status\n )\n VALUES ($1, $2, 'google_calendar', 1, 'pending')\n ",+ "describe": {+ "columns": [],+ "parameters": {+ "Left": [+ "Uuid",+ "Uuid"+ ]+ },+ "nullable": []+ },+ "hash": "61f112ac14be228793a81deb0a0bc6b88234ed5758a17953d5a3c5cf23b2a76b"+}diff --git a/.sqlx/query-62904494eba0dd7207fa568280deae7eb1212e330a30ea701967fb90e4bf7c36.json b/.sqlx/query-62904494eba0dd7207fa568280deae7eb1212e330a30ea701967fb90e4bf7c36.jsonnew file mode 100644index 0000000000..99a8de9f7c--- /dev/null+++ b/.sqlx/query-62904494eba0dd7207fa568280deae7eb1212e330a30ea701967fb90e4bf7c36.json@@ -0,0 +1,14 @@+{+ "db_name": "PostgreSQL",+ "query": "UPDATE calendars SET sync_token = 'old-token', synced_at = now() WHERE id = $1",+ "describe": {+ "columns": [],+ "parameters": {+ "Left": [+ "Uuid"+ ]+ },+ "nullable": []+ },+ "hash": "62904494eba0dd7207fa568280deae7eb1212e330a30ea701967fb90e4bf7c36"+}diff --git a/.sqlx/query-639a5fa6d94f204324811e82dd37ebe6d39b2f83f33b1dbc21b0654113338e50.json b/.sqlx/query-639a5fa6d94f204324811e82dd37ebe6d39b2f83f33b1dbc21b0654113338e50.jsonnew file mode 100644index 0000000000..86ef49b05c--- /dev/null+++ b/.sqlx/query-639a5fa6d94f204324811e82dd37ebe6d39b2f83f33b1dbc21b0654113338e50.json@@ -0,0 +1,23 @@+{+ "db_name": "PostgreSQL",+ "query": "SELECT title FROM calendar_event_sources WHERE event_id = $1 AND calendar_id = $2",+ "describe": {+ "columns": [+ {+ "ordinal": 0,+ "name": "title",+ "type_info": "Text"+ }+ ],+ "parameters": {+ "Left": [+ "Uuid",+ "Uuid"+ ]+ },+ "nullable": [+ false+ ]+ },+ "hash": "639a5fa6d94f204324811e82dd37ebe6d39b2f83f33b1dbc21b0654113338e50"+}diff --git a/.sqlx/query-67d7e1d8c8fbdb033d85f41e6afbe24ab1ec1e99c282c8b3a95e62d50ee034af.json b/.sqlx/query-664bc570ce4f6598ee989a209b3ad1f5b84d57bb01c300e0835b212582dac9ce.jsonsimilarity index 81%rename from .sqlx/query-67d7e1d8c8fbdb033d85f41e6afbe24ab1ec1e99c282c8b3a95e62d50ee034af.jsonrename to .sqlx/query-664bc570ce4f6598ee989a209b3ad1f5b84d57bb01c300e0835b212582dac9ce.jsonindex ecb815a57f..73f48b86f2 100644--- a/.sqlx/query-67d7e1d8c8fbdb033d85f41e6afbe24ab1ec1e99c282c8b3a95e62d50ee034af.json+++ b/.sqlx/query-664bc570ce4f6598ee989a209b3ad1f5b84d57bb01c300e0835b212582dac9ce.json@@ -1,6 +1,6 @@{"db_name": "PostgreSQL",- "query": "\n INSERT INTO calendars (\n id, account_id, provider_calendar_id, name, description,\n time_zone, color, access_role, is_primary, is_selected,\n default_reminders\n )\n VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11)\n ON CONFLICT (account_id, provider_calendar_id) DO UPDATE SET\n name = EXCLUDED.name,\n description = EXCLUDED.description,\n time_zone = EXCLUDED.time_zone,\n color = EXCLUDED.color,\n access_role = EXCLUDED.access_role,\n is_primary = EXCLUDED.is_primary,\n is_selected = EXCLUDED.is_selected,\n is_deleted = false,\n default_reminders = EXCLUDED.default_reminders,\n last_sync_error = CASE\n WHEN calendars.is_deleted THEN NULL\n ELSE calendars.last_sync_error\n END,\n last_sync_error_at = CASE\n WHEN calendars.is_deleted THEN NULL\n ELSE calendars.last_sync_error_at\n END,\n consecutive_sync_failures = CASE\n WHEN calendars.is_deleted THEN 0\n ELSE calendars.consecutive_sync_failures\n END,\n updated_at = now()\n RETURNING\n id,\n sync_token,\n materialized_starts_at,\n materialized_ends_at,\n materialized_start_date,\n materialized_end_date,\n synced_at,\n watch_expires_at,\n watch_unsupported_at\n ",+ "query": "\n INSERT INTO calendars (\n id, account_id, provider_calendar_id, name, description,\n time_zone, color, access_role, is_primary, is_selected,\n default_reminders\n )\n VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11)\n ON CONFLICT (account_id, provider_calendar_id) DO UPDATE SET\n name = EXCLUDED.name,\n description = EXCLUDED.description,\n time_zone = EXCLUDED.time_zone,\n color = EXCLUDED.color,\n access_role = EXCLUDED.access_role,\n sync_token = CASE WHEN $12 THEN NULL ELSE calendars.sync_token END,\n materialized_starts_at = CASE WHEN $12 THEN NULL ELSE calendars.materialized_starts_at END,\n materialized_ends_at = CASE WHEN $12 THEN NULL ELSE calendars.materialized_ends_at END,\n materialized_start_date = CASE WHEN $12 THEN NULL ELSE calendars.materialized_start_date END,\n materialized_end_date = CASE WHEN $12 THEN NULL ELSE calendars.materialized_end_date END,\n synced_at = CASE WHEN $12 THEN NULL ELSE calendars.synced_at END,\n is_primary = EXCLUDED.is_primary,\n is_selected = EXCLUDED.is_selected,\n is_deleted = false,\n default_reminders = EXCLUDED.default_reminders,\n last_sync_error = CASE\n WHEN calendars.is_deleted THEN NULL\n ELSE calendars.last_sync_error\n END,\n last_sync_error_at = CASE\n WHEN calendars.is_deleted THEN NULL\n ELSE calendars.last_sync_error_at\n END,\n consecutive_sync_failures = CASE\n WHEN calendars.is_deleted THEN 0\n ELSE calendars.consecutive_sync_failures\n END,\n updated_at = now()\n RETURNING\n id,\n sync_token,\n materialized_starts_at,\n materialized_ends_at,\n materialized_start_date,\n materialized_end_date,\n synced_at,\n watch_expires_at,\n watch_unsupported_at\n ","describe": {"columns": [{@@ -61,7 +61,8 @@"Text","Bool","Bool",- "Jsonb"+ "Jsonb",+ "Bool"]},"nullable": [@@ -76,5 +77,5 @@true]},- "hash": "67d7e1d8c8fbdb033d85f41e6afbe24ab1ec1e99c282c8b3a95e62d50ee034af"+ "hash": "664bc570ce4f6598ee989a209b3ad1f5b84d57bb01c300e0835b212582dac9ce"}diff --git a/.sqlx/query-7469c3291a182cf35af872cc36c7bd1eab4e940fc56f6c8bb5b7b61685ee4c66.json b/.sqlx/query-7469c3291a182cf35af872cc36c7bd1eab4e940fc56f6c8bb5b7b61685ee4c66.jsonnew file mode 100644index 0000000000..7d1ebe02d6--- /dev/null+++ b/.sqlx/query-7469c3291a182cf35af872cc36c7bd1eab4e940fc56f6c8bb5b7b61685ee4c66.json@@ -0,0 +1,15 @@+{+ "db_name": "PostgreSQL",+ "query": "UPDATE email_links SET updated_at = $2 WHERE id = $1",+ "describe": {+ "columns": [],+ "parameters": {+ "Left": [+ "Uuid",+ "Timestamptz"+ ]+ },+ "nullable": []+ },+ "hash": "7469c3291a182cf35af872cc36c7bd1eab4e940fc56f6c8bb5b7b61685ee4c66"+}diff --git a/.sqlx/query-74eb3ef60e03b3c455292ed9ce25be971542e2643c673e169c55a3e033fba3f1.json b/.sqlx/query-74eb3ef60e03b3c455292ed9ce25be971542e2643c673e169c55a3e033fba3f1.jsonnew file mode 100644index 0000000000..8fa9ba3613--- /dev/null+++ b/.sqlx/query-74eb3ef60e03b3c455292ed9ce25be971542e2643c673e169c55a3e033fba3f1.json@@ -0,0 +1,22 @@+{+ "db_name": "PostgreSQL",+ "query": "SELECT sharing FROM calendar_team_sharing WHERE user_id = $1",+ "describe": {+ "columns": [+ {+ "ordinal": 0,+ "name": "sharing",+ "type_info": "Text"+ }+ ],+ "parameters": {+ "Left": [+ "Text"+ ]+ },+ "nullable": [+ false+ ]+ },+ "hash": "74eb3ef60e03b3c455292ed9ce25be971542e2643c673e169c55a3e033fba3f1"+}diff --git a/.sqlx/query-78075ab1bd6765213dde800c9533bb0f9d0c4f9b7792a8bb5a4f881c5d324b58.json b/.sqlx/query-78075ab1bd6765213dde800c9533bb0f9d0c4f9b7792a8bb5a4f881c5d324b58.jsonnew file mode 100644index 0000000000..40ebdb5968--- /dev/null+++ b/.sqlx/query-78075ab1bd6765213dde800c9533bb0f9d0c4f9b7792a8bb5a4f881c5d324b58.json@@ -0,0 +1,14 @@+{+ "db_name": "PostgreSQL",+ "query": "DELETE FROM team_user WHERE user_id=$1",+ "describe": {+ "columns": [],+ "parameters": {+ "Left": [+ "Text"+ ]+ },+ "nullable": []+ },+ "hash": "78075ab1bd6765213dde800c9533bb0f9d0c4f9b7792a8bb5a4f881c5d324b58"+}diff --git a/.sqlx/query-79ca419032c3b6ad11766f3fee3dcaf7efae6f0205ff91ffe81557c6573bf0ba.json b/.sqlx/query-79ca419032c3b6ad11766f3fee3dcaf7efae6f0205ff91ffe81557c6573bf0ba.jsonnew file mode 100644index 0000000000..4e0e60fc3c--- /dev/null+++ b/.sqlx/query-79ca419032c3b6ad11766f3fee3dcaf7efae6f0205ff91ffe81557c6573bf0ba.json@@ -0,0 +1,14 @@+{+ "db_name": "PostgreSQL",+ "query": "UPDATE calendars SET sync_token='keep-token', synced_at=now(), materialized_starts_at='2026-07-01', materialized_ends_at='2026-08-01', materialized_start_date='2026-07-01', materialized_end_date='2026-08-01' WHERE id=$1",+ "describe": {+ "columns": [],+ "parameters": {+ "Left": [+ "Uuid"+ ]+ },+ "nullable": []+ },+ "hash": "79ca419032c3b6ad11766f3fee3dcaf7efae6f0205ff91ffe81557c6573bf0ba"+}diff --git a/.sqlx/query-7d095cecaa0bd15f4fda597b795b24af5ac726593918e2e3f04f458c30e6ee77.json b/.sqlx/query-7d095cecaa0bd15f4fda597b795b24af5ac726593918e2e3f04f458c30e6ee77.jsonnew file mode 100644index 0000000000..27051ac468--- /dev/null+++ b/.sqlx/query-7d095cecaa0bd15f4fda597b795b24af5ac726593918e2e3f04f458c30e6ee77.json@@ -0,0 +1,14 @@+{+ "db_name": "PostgreSQL",+ "query": "UPDATE calendar_accounts SET sync_status='ready',last_synced_at=now() WHERE id=$1",+ "describe": {+ "columns": [],+ "parameters": {+ "Left": [+ "Uuid"+ ]+ },+ "nullable": []+ },+ "hash": "7d095cecaa0bd15f4fda597b795b24af5ac726593918e2e3f04f458c30e6ee77"+}diff --git a/.sqlx/query-7df7e6ffaab6df69c19b2a295bba31f7cc43ddc8323a4db715e726bf9d21b864.json b/.sqlx/query-7df7e6ffaab6df69c19b2a295bba31f7cc43ddc8323a4db715e726bf9d21b864.jsonnew file mode 100644index 0000000000..183e9037a5--- /dev/null+++ b/.sqlx/query-7df7e6ffaab6df69c19b2a295bba31f7cc43ddc8323a4db715e726bf9d21b864.json@@ -0,0 +1,28 @@+{+ "db_name": "PostgreSQL",+ "query": "\n SELECT status, lease_token\n FROM calendar_backfill_jobs\n WHERE id = $1\n ",+ "describe": {+ "columns": [+ {+ "ordinal": 0,+ "name": "status",+ "type_info": "Text"+ },+ {+ "ordinal": 1,+ "name": "lease_token",+ "type_info": "Uuid"+ }+ ],+ "parameters": {+ "Left": [+ "Uuid"+ ]+ },+ "nullable": [+ false,+ true+ ]+ },+ "hash": "7df7e6ffaab6df69c19b2a295bba31f7cc43ddc8323a4db715e726bf9d21b864"+}diff --git a/.sqlx/query-84a0caa16b36a307900e65f8f02558b181bb65826be26f70de9eb6fe2c7a4b67.json b/.sqlx/query-84a0caa16b36a307900e65f8f02558b181bb65826be26f70de9eb6fe2c7a4b67.jsonnew file mode 100644index 0000000000..e674904a54--- /dev/null+++ b/.sqlx/query-84a0caa16b36a307900e65f8f02558b181bb65826be26f70de9eb6fe2c7a4b67.json@@ -0,0 +1,16 @@+{+ "db_name": "PostgreSQL",+ "query": "\n INSERT INTO calendar_availability_preferences(user_id,calendar_id,contributes_to_availability)\n SELECT $1, calendar.id, $3 FROM calendars calendar\n JOIN calendar_accounts account ON account.id = calendar.account_id\n WHERE calendar.id = $2 AND NOT calendar.is_deleted AND account.sync_status <> 'disabled'\n AND (account.owner_id = $1 OR EXISTS (SELECT 1 FROM macro_user_links link WHERE link.link_id = account.email_link_id AND link.primary_macro_id = $1))\n ON CONFLICT(user_id,calendar_id) DO UPDATE SET contributes_to_availability=EXCLUDED.contributes_to_availability\n ",+ "describe": {+ "columns": [],+ "parameters": {+ "Left": [+ "Text",+ "Uuid",+ "Bool"+ ]+ },+ "nullable": []+ },+ "hash": "84a0caa16b36a307900e65f8f02558b181bb65826be26f70de9eb6fe2c7a4b67"+}diff --git a/.sqlx/query-85491b3f376f100fa76950379e427e044606c4f50b0a5d3ee5909d0551079613.json b/.sqlx/query-85491b3f376f100fa76950379e427e044606c4f50b0a5d3ee5909d0551079613.jsonnew file mode 100644index 0000000000..97195370e0--- /dev/null+++ b/.sqlx/query-85491b3f376f100fa76950379e427e044606c4f50b0a5d3ee5909d0551079613.json@@ -0,0 +1,22 @@+{+ "db_name": "PostgreSQL",+ "query": "SELECT published_at FROM calendar_sync_outbox WHERE backfill_job_id = $1",+ "describe": {+ "columns": [+ {+ "ordinal": 0,+ "name": "published_at",+ "type_info": "Timestamptz"+ }+ ],+ "parameters": {+ "Left": [+ "Uuid"+ ]+ },+ "nullable": [+ true+ ]+ },+ "hash": "85491b3f376f100fa76950379e427e044606c4f50b0a5d3ee5909d0551079613"+}diff --git a/.sqlx/query-8562a5a683259d3412c0d5cc58cc526dab7551296d96564fab4bdd44dbed43c5.json b/.sqlx/query-8562a5a683259d3412c0d5cc58cc526dab7551296d96564fab4bdd44dbed43c5.jsonnew file mode 100644index 0000000000..4f0279e537--- /dev/null+++ b/.sqlx/query-8562a5a683259d3412c0d5cc58cc526dab7551296d96564fab4bdd44dbed43c5.json@@ -0,0 +1,16 @@+{+ "db_name": "PostgreSQL",+ "query": "INSERT INTO macro_user_links(primary_macro_id,child_macro_id,link_id) VALUES($1,$2,$3)",+ "describe": {+ "columns": [],+ "parameters": {+ "Left": [+ "Text",+ "Text",+ "Uuid"+ ]+ },+ "nullable": []+ },+ "hash": "8562a5a683259d3412c0d5cc58cc526dab7551296d96564fab4bdd44dbed43c5"+}diff --git a/.sqlx/query-8650d517d70e42d44b79ff07108b88215261a0d602d592bdc80cd73334dc3551.json b/.sqlx/query-8650d517d70e42d44b79ff07108b88215261a0d602d592bdc80cd73334dc3551.jsonnew file mode 100644index 0000000000..10cf31afbb--- /dev/null+++ b/.sqlx/query-8650d517d70e42d44b79ff07108b88215261a0d602d592bdc80cd73334dc3551.json@@ -0,0 +1,34 @@+{+ "db_name": "PostgreSQL",+ "query": "SELECT sync_status,last_sync_error,last_synced_at FROM calendar_accounts WHERE id=$1",+ "describe": {+ "columns": [+ {+ "ordinal": 0,+ "name": "sync_status",+ "type_info": "Text"+ },+ {+ "ordinal": 1,+ "name": "last_sync_error",+ "type_info": "Text"+ },+ {+ "ordinal": 2,+ "name": "last_synced_at",+ "type_info": "Timestamptz"+ }+ ],+ "parameters": {+ "Left": [+ "Uuid"+ ]+ },+ "nullable": [+ false,+ true,+ true+ ]+ },+ "hash": "8650d517d70e42d44b79ff07108b88215261a0d602d592bdc80cd73334dc3551"+}diff --git a/.sqlx/query-88e6765ad8271d0c4c3c1043a00b76f649018ec5b34293bd4391f3aae672c39c.json b/.sqlx/query-88e6765ad8271d0c4c3c1043a00b76f649018ec5b34293bd4391f3aae672c39c.jsonnew file mode 100644index 0000000000..9105dc7774--- /dev/null+++ b/.sqlx/query-88e6765ad8271d0c4c3c1043a00b76f649018ec5b34293bd4391f3aae672c39c.json@@ -0,0 +1,15 @@+{+ "db_name": "PostgreSQL",+ "query": "DELETE FROM macro_user_links WHERE primary_macro_id=$1 AND link_id=$2",+ "describe": {+ "columns": [],+ "parameters": {+ "Left": [+ "Text",+ "Uuid"+ ]+ },+ "nullable": []+ },+ "hash": "88e6765ad8271d0c4c3c1043a00b76f649018ec5b34293bd4391f3aae672c39c"+}diff --git a/.sqlx/query-893970f8005d7fbaaa3da2a1a5c8507f2a43d141c568d9c70b9a954c86285b6c.json b/.sqlx/query-893970f8005d7fbaaa3da2a1a5c8507f2a43d141c568d9c70b9a954c86285b6c.jsonnew file mode 100644index 0000000000..3a21d653dd--- /dev/null+++ b/.sqlx/query-893970f8005d7fbaaa3da2a1a5c8507f2a43d141c568d9c70b9a954c86285b6c.json@@ -0,0 +1,79 @@+{+ "db_name": "PostgreSQL",+ "query": "\n WITH eligible AS (\n SELECT teammate.user_id FROM team_user viewer\n JOIN team_user teammate ON teammate.team_id = viewer.team_id\n LEFT JOIN calendar_team_sharing policy ON policy.user_id = teammate.user_id\n WHERE viewer.user_id = $1 AND COALESCE(policy.sharing, 'busy_only') <> 'none'\n UNION SELECT $1::text\n ), visible_accounts AS MATERIALIZED (\n SELECT eligible.user_id, account.id AS account_id\n FROM eligible JOIN calendar_accounts account ON account.owner_id = eligible.user_id\n WHERE eligible.user_id = ANY($2::text[])\n UNION\n SELECT eligible.user_id, account.id AS account_id\n FROM eligible\n JOIN macro_user_links link ON link.primary_macro_id = eligible.user_id\n JOIN calendar_accounts account ON account.email_link_id = link.link_id\n WHERE eligible.user_id = ANY($2::text[])\n ), authorized_sources AS MATERIALIZED (\n SELECT eligible.user_id AS shared_by, source.id AS source_id,\n calendar.id AS calendar_id, calendar.name AS calendar_name, calendar.time_zone,\n COALESCE(preference.contributes_to_availability,\n account.owner_id = eligible.user_id AND calendar.is_primary) AS contributes,\n source.normalized_payload\n FROM visible_accounts eligible\n JOIN calendar_accounts account ON account.id = eligible.account_id\n AND account.sync_status IN ('ready', 'syncing')\n AND account.last_sync_error IS NULL\n AND account.last_synced_at > now() - interval '15 minutes'\n JOIN calendars calendar ON calendar.account_id = account.id AND NOT calendar.is_deleted\n AND calendar.synced_at IS NOT NULL AND calendar.last_sync_error IS NULL\n AND calendar.snapshot_normalization_version >= 1\n JOIN calendar_event_sources source ON source.calendar_id = calendar.id AND source.account_id = account.id\n AND source.provider_access_role IS NOT NULL\n AND source.provider_access_role IS NOT DISTINCT FROM calendar.access_role\n LEFT JOIN calendar_availability_preferences preference ON preference.user_id = eligible.user_id AND preference.calendar_id = calendar.id\n WHERE ($7::text IS NULL OR (eligible.user_id, source.id) >= ($7,$8))\n )\n SELECT shared_by AS \"shared_by!\", source_id AS \"source_id!\",\n calendar_id AS \"calendar_id!\", calendar_name AS \"calendar_name!\", time_zone,\n contributes AS \"contributes!\",\n ARRAY(SELECT owned.email_address::text FROM email_links owned WHERE owned.macro_id = shared_by) AS \"owner_emails!\",\n (normalized_payload - 'occurrences') AS \"snapshot!\", occurrence.value AS \"occurrence!\"\n FROM authorized_sources\n CROSS JOIN LATERAL jsonb_array_elements(normalized_payload->'occurrences') occurrence(value)\n WHERE (normalized_payload->'event'->>'status') <> 'cancelled'\n AND NOT COALESCE((occurrence.value->>'isCancelled')::boolean, false)\n AND (\n ((occurrence.value->'time'->>'kind') = 'timed'\n AND (occurrence.value->'time'->>'startsAt')::timestamptz < $4\n AND (occurrence.value->'time'->>'endsAt')::timestamptz > $3)\n OR ((occurrence.value->'time'->>'kind') = 'allDay'\n AND (occurrence.value->'time'->>'startDate')::date < $6\n AND (occurrence.value->'time'->>'endDate')::date > $5)\n )\n AND ($7::text IS NULL OR (shared_by, source_id, occurrence.value->>'occurrenceKey') > ($7,$8,$9))\n ORDER BY shared_by, source_id, occurrence.value->>'occurrenceKey'\n LIMIT $10\n ",+ "describe": {+ "columns": [+ {+ "ordinal": 0,+ "name": "shared_by!",+ "type_info": "Text"+ },+ {+ "ordinal": 1,+ "name": "source_id!",+ "type_info": "Uuid"+ },+ {+ "ordinal": 2,+ "name": "calendar_id!",+ "type_info": "Uuid"+ },+ {+ "ordinal": 3,+ "name": "calendar_name!",+ "type_info": "Text"+ },+ {+ "ordinal": 4,+ "name": "time_zone",+ "type_info": "Text"+ },+ {+ "ordinal": 5,+ "name": "contributes!",+ "type_info": "Bool"+ },+ {+ "ordinal": 6,+ "name": "owner_emails!",+ "type_info": "TextArray"+ },+ {+ "ordinal": 7,+ "name": "snapshot!",+ "type_info": "Jsonb"+ },+ {+ "ordinal": 8,+ "name": "occurrence!",+ "type_info": "Jsonb"+ }+ ],+ "parameters": {+ "Left": [+ "Text",+ "TextArray",+ "Timestamptz",+ "Timestamptz",+ "Date",+ "Date",+ "Text",+ "Uuid",+ "Text",+ "Int8"+ ]+ },+ "nullable": [+ null,+ false,+ false,+ false,+ true,+ null,+ null,+ null,+ null+ ]+ },+ "hash": "893970f8005d7fbaaa3da2a1a5c8507f2a43d141c568d9c70b9a954c86285b6c"+}diff --git a/.sqlx/query-8b1aaa5843030fdc4f14ef08ee1e253c42326a6353aacba9408fb22931c13b5e.json b/.sqlx/query-8b1aaa5843030fdc4f14ef08ee1e253c42326a6353aacba9408fb22931c13b5e.jsonnew file mode 100644index 0000000000..b1ddefa95e--- /dev/null+++ b/.sqlx/query-8b1aaa5843030fdc4f14ef08ee1e253c42326a6353aacba9408fb22931c13b5e.json@@ -0,0 +1,23 @@+{+ "db_name": "PostgreSQL",+ "query": "SELECT snapshot_normalization_version >= 1 AS \"verified!\" FROM calendars WHERE id=$1 AND account_id=$2 AND NOT is_deleted FOR UPDATE",+ "describe": {+ "columns": [+ {+ "ordinal": 0,+ "name": "verified!",+ "type_info": "Bool"+ }+ ],+ "parameters": {+ "Left": [+ "Uuid",+ "Uuid"+ ]+ },+ "nullable": [+ null+ ]+ },+ "hash": "8b1aaa5843030fdc4f14ef08ee1e253c42326a6353aacba9408fb22931c13b5e"+}diff --git a/.sqlx/query-8f2fa6e97f58f901103c09678bcb4be646c03cb3fa63be7b2e86e14628812df3.json b/.sqlx/query-8f2fa6e97f58f901103c09678bcb4be646c03cb3fa63be7b2e86e14628812df3.jsonnew file mode 100644index 0000000000..667dcf2bbc--- /dev/null+++ b/.sqlx/query-8f2fa6e97f58f901103c09678bcb4be646c03cb3fa63be7b2e86e14628812df3.json@@ -0,0 +1,34 @@+{+ "db_name": "PostgreSQL",+ "query": "\n SELECT job.status, job.lease_token, outbox.published_at\n FROM calendar_backfill_jobs job\n JOIN calendar_sync_outbox outbox ON outbox.backfill_job_id = job.id\n WHERE job.id = $1\n ",+ "describe": {+ "columns": [+ {+ "ordinal": 0,+ "name": "status",+ "type_info": "Text"+ },+ {+ "ordinal": 1,+ "name": "lease_token",+ "type_info": "Uuid"+ },+ {+ "ordinal": 2,+ "name": "published_at",+ "type_info": "Timestamptz"+ }+ ],+ "parameters": {+ "Left": [+ "Uuid"+ ]+ },+ "nullable": [+ false,+ true,+ true+ ]+ },+ "hash": "8f2fa6e97f58f901103c09678bcb4be646c03cb3fa63be7b2e86e14628812df3"+}diff --git a/.sqlx/query-91371030c79e2a96270b623b963c87bafe771a13486bff84ead90b22f308f2a0.json b/.sqlx/query-91371030c79e2a96270b623b963c87bafe771a13486bff84ead90b22f308f2a0.jsonnew file mode 100644index 0000000000..e166405d9a--- /dev/null+++ b/.sqlx/query-91371030c79e2a96270b623b963c87bafe771a13486bff84ead90b22f308f2a0.json@@ -0,0 +1,22 @@+{+ "db_name": "PostgreSQL",+ "query": "SELECT count(*) AS \"count!\" FROM calendar_events WHERE id = $1",+ "describe": {+ "columns": [+ {+ "ordinal": 0,+ "name": "count!",+ "type_info": "Int8"+ }+ ],+ "parameters": {+ "Left": [+ "Uuid"+ ]+ },+ "nullable": [+ null+ ]+ },+ "hash": "91371030c79e2a96270b623b963c87bafe771a13486bff84ead90b22f308f2a0"+}diff --git a/.sqlx/query-93900b6249dc8886def225c9871cb6737ced49ffe8e72691b773ea128b4f52bc.json b/.sqlx/query-93900b6249dc8886def225c9871cb6737ced49ffe8e72691b773ea128b4f52bc.jsonnew file mode 100644index 0000000000..b581b4e292--- /dev/null+++ b/.sqlx/query-93900b6249dc8886def225c9871cb6737ced49ffe8e72691b773ea128b4f52bc.json@@ -0,0 +1,46 @@+{+ "db_name": "PostgreSQL",+ "query": "SELECT calendar.sync_token, calendar.synced_at, calendar.materialized_starts_at, source.provider_access_role, source.title FROM calendars calendar JOIN calendar_event_sources source ON source.calendar_id=calendar.id WHERE source.event_id=$1",+ "describe": {+ "columns": [+ {+ "ordinal": 0,+ "name": "sync_token",+ "type_info": "Text"+ },+ {+ "ordinal": 1,+ "name": "synced_at",+ "type_info": "Timestamptz"+ },+ {+ "ordinal": 2,+ "name": "materialized_starts_at",+ "type_info": "Timestamptz"+ },+ {+ "ordinal": 3,+ "name": "provider_access_role",+ "type_info": "Text"+ },+ {+ "ordinal": 4,+ "name": "title",+ "type_info": "Text"+ }+ ],+ "parameters": {+ "Left": [+ "Uuid"+ ]+ },+ "nullable": [+ true,+ true,+ true,+ true,+ false+ ]+ },+ "hash": "93900b6249dc8886def225c9871cb6737ced49ffe8e72691b773ea128b4f52bc"+}diff --git a/.sqlx/query-9431a8d5774a696946810c2bc1c68fc37192b42cf8b7d81ce0eba9b446cedfcb.json b/.sqlx/query-9431a8d5774a696946810c2bc1c68fc37192b42cf8b7d81ce0eba9b446cedfcb.jsonnew file mode 100644index 0000000000..03cff08e62--- /dev/null+++ b/.sqlx/query-9431a8d5774a696946810c2bc1c68fc37192b42cf8b7d81ce0eba9b446cedfcb.json@@ -0,0 +1,15 @@+{+ "db_name": "PostgreSQL",+ "query": "\n INSERT INTO calendar_event_reminder_deliveries (\n id, event_id, occurrence_key, minutes_before, fire_at\n )\n VALUES ($1, $2, 'key', 10, now())\n ",+ "describe": {+ "columns": [],+ "parameters": {+ "Left": [+ "Uuid",+ "Uuid"+ ]+ },+ "nullable": []+ },+ "hash": "9431a8d5774a696946810c2bc1c68fc37192b42cf8b7d81ce0eba9b446cedfcb"+}diff --git a/.sqlx/query-9488ee6964d91adc899244314f268e409df4b474d99b458dae05fe134e11827c.json b/.sqlx/query-9488ee6964d91adc899244314f268e409df4b474d99b458dae05fe134e11827c.jsonnew file mode 100644index 0000000000..19f56b3efe--- /dev/null+++ b/.sqlx/query-9488ee6964d91adc899244314f268e409df4b474d99b458dae05fe134e11827c.json@@ -0,0 +1,14 @@+{+ "db_name": "PostgreSQL",+ "query": "UPDATE calendar_accounts SET last_sync_error=NULL,last_synced_at=now()-interval '16 minutes' WHERE id=$1",+ "describe": {+ "columns": [],+ "parameters": {+ "Left": [+ "Uuid"+ ]+ },+ "nullable": []+ },+ "hash": "9488ee6964d91adc899244314f268e409df4b474d99b458dae05fe134e11827c"+}diff --git a/.sqlx/query-9670211667c01900383684234af23552d2895473c63b61e1cbb3dbb630ccdb27.json b/.sqlx/query-9670211667c01900383684234af23552d2895473c63b61e1cbb3dbb630ccdb27.jsonnew file mode 100644index 0000000000..c62c021131--- /dev/null+++ b/.sqlx/query-9670211667c01900383684234af23552d2895473c63b61e1cbb3dbb630ccdb27.json@@ -0,0 +1,14 @@+{+ "db_name": "PostgreSQL",+ "query": "UPDATE calendar_accounts SET sync_status='disabled' WHERE id=$1",+ "describe": {+ "columns": [],+ "parameters": {+ "Left": [+ "Uuid"+ ]+ },+ "nullable": []+ },+ "hash": "9670211667c01900383684234af23552d2895473c63b61e1cbb3dbb630ccdb27"+}diff --git a/.sqlx/query-97d88f069366a5b0ecf1ae8d4dd9aaff262513601f56b636ced612799b3e1958.json b/.sqlx/query-97d88f069366a5b0ecf1ae8d4dd9aaff262513601f56b636ced612799b3e1958.jsonnew file mode 100644index 0000000000..d13027b155--- /dev/null+++ b/.sqlx/query-97d88f069366a5b0ecf1ae8d4dd9aaff262513601f56b636ced612799b3e1958.json@@ -0,0 +1,16 @@+{+ "db_name": "PostgreSQL",+ "query": "\n INSERT INTO calendar_backfill_jobs (\n id, email_link_id, account_id, kind, grant_version, status\n )\n VALUES ($1, $2, $3, 'google_calendar', 1, 'pending')\n ",+ "describe": {+ "columns": [],+ "parameters": {+ "Left": [+ "Uuid",+ "Uuid",+ "Uuid"+ ]+ },+ "nullable": []+ },+ "hash": "97d88f069366a5b0ecf1ae8d4dd9aaff262513601f56b636ced612799b3e1958"+}diff --git a/.sqlx/query-9b10ea76482f6b7050a46ecfce38203c1771809a581c80531bb99b78bba46c11.json b/.sqlx/query-9b10ea76482f6b7050a46ecfce38203c1771809a581c80531bb99b78bba46c11.jsonnew file mode 100644index 0000000000..0614e8a54b--- /dev/null+++ b/.sqlx/query-9b10ea76482f6b7050a46ecfce38203c1771809a581c80531bb99b78bba46c11.json@@ -0,0 +1,22 @@+{+ "db_name": "PostgreSQL",+ "query": "SELECT sync_token FROM calendars WHERE id = $1",+ "describe": {+ "columns": [+ {+ "ordinal": 0,+ "name": "sync_token",+ "type_info": "Text"+ }+ ],+ "parameters": {+ "Left": [+ "Uuid"+ ]+ },+ "nullable": [+ true+ ]+ },+ "hash": "9b10ea76482f6b7050a46ecfce38203c1771809a581c80531bb99b78bba46c11"+}diff --git a/.sqlx/query-9da658a7d5907f15c324ab6c8587ba1203e33aa3539d9c82758148c4dbaeb238.json b/.sqlx/query-9da658a7d5907f15c324ab6c8587ba1203e33aa3539d9c82758148c4dbaeb238.jsonnew file mode 100644index 0000000000..203be4f048--- /dev/null+++ b/.sqlx/query-9da658a7d5907f15c324ab6c8587ba1203e33aa3539d9c82758148c4dbaeb238.json@@ -0,0 +1,14 @@+{+ "db_name": "PostgreSQL",+ "query": "UPDATE calendars SET synced_at=now() WHERE id=$1",+ "describe": {+ "columns": [],+ "parameters": {+ "Left": [+ "Uuid"+ ]+ },+ "nullable": []+ },+ "hash": "9da658a7d5907f15c324ab6c8587ba1203e33aa3539d9c82758148c4dbaeb238"+}diff --git a/.sqlx/query-9e3e9a5ba74600ee544a3a930bf54da41abaed6e7d7695e7fac88b65c4a3361e.json b/.sqlx/query-9e3e9a5ba74600ee544a3a930bf54da41abaed6e7d7695e7fac88b65c4a3361e.jsonnew file mode 100644index 0000000000..4aff03b59d--- /dev/null+++ b/.sqlx/query-9e3e9a5ba74600ee544a3a930bf54da41abaed6e7d7695e7fac88b65c4a3361e.json@@ -0,0 +1,46 @@+{+ "db_name": "PostgreSQL",+ "query": "\n SELECT\n l.macro_id,\n l.email_address::text AS \"email_address!\",\n COALESCE(g.granted_scopes, '{}') AS \"granted_scopes!\",\n COALESCE(g.grant_version, 0) AS \"grant_version!\",\n g.calendar_disabled_at\n FROM email_links l\n LEFT JOIN email_link_google_scopes g ON g.link_id = l.id\n WHERE l.id = $1\n ",+ "describe": {+ "columns": [+ {+ "ordinal": 0,+ "name": "macro_id",+ "type_info": "Text"+ },+ {+ "ordinal": 1,+ "name": "email_address!",+ "type_info": "Text"+ },+ {+ "ordinal": 2,+ "name": "granted_scopes!",+ "type_info": "TextArray"+ },+ {+ "ordinal": 3,+ "name": "grant_version!",+ "type_info": "Int8"+ },+ {+ "ordinal": 4,+ "name": "calendar_disabled_at",+ "type_info": "Timestamptz"+ }+ ],+ "parameters": {+ "Left": [+ "Uuid"+ ]+ },+ "nullable": [+ false,+ null,+ null,+ null,+ true+ ]+ },+ "hash": "9e3e9a5ba74600ee544a3a930bf54da41abaed6e7d7695e7fac88b65c4a3361e"+}diff --git a/.sqlx/query-a3f970587e572b50b2760c191d83bc1845a4c1d1d9f7c926855fa8dee6690810.json b/.sqlx/query-a3f970587e572b50b2760c191d83bc1845a4c1d1d9f7c926855fa8dee6690810.jsonnew file mode 100644index 0000000000..cc1f8f09e3--- /dev/null+++ b/.sqlx/query-a3f970587e572b50b2760c191d83bc1845a4c1d1d9f7c926855fa8dee6690810.json@@ -0,0 +1,14 @@+{+ "db_name": "PostgreSQL",+ "query": "UPDATE calendar_backfill_jobs SET updated_at = now() - interval '30 minutes' WHERE id = $1",+ "describe": {+ "columns": [],+ "parameters": {+ "Left": [+ "Uuid"+ ]+ },+ "nullable": []+ },+ "hash": "a3f970587e572b50b2760c191d83bc1845a4c1d1d9f7c926855fa8dee6690810"+}diff --git a/.sqlx/query-a59419c189f7d54eaeb4dfde64f4ca7f7eeff827d9865bd5566772a2c1b60276.json b/.sqlx/query-a59419c189f7d54eaeb4dfde64f4ca7f7eeff827d9865bd5566772a2c1b60276.jsonnew file mode 100644index 0000000000..2c3d6128ed--- /dev/null+++ b/.sqlx/query-a59419c189f7d54eaeb4dfde64f4ca7f7eeff827d9865bd5566772a2c1b60276.json@@ -0,0 +1,28 @@+{+ "db_name": "PostgreSQL",+ "query": "\n SELECT title,\n (SELECT count(*) FROM calendar_event_sources WHERE event_id = $1) AS \"source_count!\"\n FROM calendar_events\n WHERE id = $1\n ",+ "describe": {+ "columns": [+ {+ "ordinal": 0,+ "name": "title",+ "type_info": "Text"+ },+ {+ "ordinal": 1,+ "name": "source_count!",+ "type_info": "Int8"+ }+ ],+ "parameters": {+ "Left": [+ "Uuid"+ ]+ },+ "nullable": [+ false,+ null+ ]+ },+ "hash": "a59419c189f7d54eaeb4dfde64f4ca7f7eeff827d9865bd5566772a2c1b60276"+}diff --git a/.sqlx/query-a80af1e649658d0f93352dba62789fe3cf2ab557d512e6f03f5d44a3ed05cb27.json b/.sqlx/query-a80af1e649658d0f93352dba62789fe3cf2ab557d512e6f03f5d44a3ed05cb27.jsonnew file mode 100644index 0000000000..8970419822--- /dev/null+++ b/.sqlx/query-a80af1e649658d0f93352dba62789fe3cf2ab557d512e6f03f5d44a3ed05cb27.json@@ -0,0 +1,57 @@+{+ "db_name": "PostgreSQL",+ "query": "\n SELECT owner_id AS \"owner_id!\", event_id AS \"event_id!\", ical_uid AS \"ical_uid!\",\n occurrence_key AS \"occurrence_key!\", title AS \"title!\", time AS \"time!\"\n FROM (\n SELECT DISTINCT ON (event.owner_id,event.ical_uid,occurrence.value->>'occurrenceKey')\n event.owner_id, event.id AS event_id, event.ical_uid,\n occurrence.value->>'occurrenceKey' AS occurrence_key,\n COALESCE(exception.value->>'title',source.normalized_payload->'event'->>'title') AS title,\n occurrence.value->'time' AS time\n FROM calendar_event_sources source\n JOIN calendar_events event ON event.id=source.event_id\n JOIN calendars calendar ON calendar.id=source.calendar_id AND calendar.is_primary\n AND NOT calendar.is_deleted AND calendar.synced_at IS NOT NULL AND calendar.last_sync_error IS NULL\n AND calendar.snapshot_normalization_version >= 1\n JOIN calendar_accounts account ON account.id=source.account_id\n AND account.owner_id=event.owner_id\n AND account.sync_status IN ('ready','syncing') AND account.last_sync_error IS NULL\n AND account.last_synced_at > now() - interval '15 minutes'\n JOIN calendar_team_sharing sharing ON sharing.user_id=event.owner_id AND sharing.sharing='all'\n CROSS JOIN LATERAL jsonb_array_elements(source.normalized_payload->'occurrences') occurrence(value)\n LEFT JOIN LATERAL (\n SELECT candidate.value FROM jsonb_array_elements(source.normalized_payload->'overrides') candidate(value)\n WHERE candidate.value->>'recurrenceId'=occurrence.value->>'recurrenceId'\n LIMIT 1\n ) exception ON true\n WHERE event.owner_id IN (\n SELECT teammate.user_id FROM team_user viewer JOIN team_user teammate ON teammate.team_id=viewer.team_id\n WHERE viewer.user_id=$1 AND teammate.user_id<>$1\n )\n AND source.provider_access_role = calendar.access_role\n AND source.normalized_payload->'event'->>'eventType'='out_of_office'\n AND source.normalized_payload->'event'->>'visibility' IN ('default','public')\n AND COALESCE(exception.value->>'visibility','default') IN ('default','public')\n AND source.normalized_payload->'event'->>'status'<>'cancelled'\n AND COALESCE(exception.value->>'status','confirmed')<>'cancelled'\n AND NOT COALESCE((occurrence.value->>'isCancelled')::boolean,false)\n AND (\n (occurrence.value->'time'->>'kind'='timed'\n AND (occurrence.value->'time'->>'startsAt')::timestamptz<$3\n AND (occurrence.value->'time'->>'endsAt')::timestamptz>$2)\n OR (occurrence.value->'time'->>'kind'='allDay'\n AND (occurrence.value->'time'->>'startDate')::date<$5\n AND (occurrence.value->'time'->>'endDate')::date>$4)\n )\n ORDER BY event.owner_id,event.ical_uid,occurrence.value->>'occurrenceKey',source.source_updated_at DESC,source.id DESC\n ) sources\n ORDER BY COALESCE((time->>'startsAt')::timestamptz,(time->>'startDate')::date::timestamp AT TIME ZONE 'UTC'),event_id,occurrence_key\n LIMIT $6\n ",+ "describe": {+ "columns": [+ {+ "ordinal": 0,+ "name": "owner_id!",+ "type_info": "Text"+ },+ {+ "ordinal": 1,+ "name": "event_id!",+ "type_info": "Uuid"+ },+ {+ "ordinal": 2,+ "name": "ical_uid!",+ "type_info": "Text"+ },+ {+ "ordinal": 3,+ "name": "occurrence_key!",+ "type_info": "Text"+ },+ {+ "ordinal": 4,+ "name": "title!",+ "type_info": "Text"+ },+ {+ "ordinal": 5,+ "name": "time!",+ "type_info": "Jsonb"+ }+ ],+ "parameters": {+ "Left": [+ "Text",+ "Timestamptz",+ "Timestamptz",+ "Date",+ "Date",+ "Int8"+ ]+ },+ "nullable": [+ false,+ false,+ false,+ null,+ null,+ null+ ]+ },+ "hash": "a80af1e649658d0f93352dba62789fe3cf2ab557d512e6f03f5d44a3ed05cb27"+}diff --git a/.sqlx/query-ab92e3babbad2d74b9f47db60cf48c301df2ca353b76e7dbd9170adfaa21031d.json b/.sqlx/query-ab92e3babbad2d74b9f47db60cf48c301df2ca353b76e7dbd9170adfaa21031d.jsonnew file mode 100644index 0000000000..6753227c63--- /dev/null+++ b/.sqlx/query-ab92e3babbad2d74b9f47db60cf48c301df2ca353b76e7dbd9170adfaa21031d.json@@ -0,0 +1,14 @@+{+ "db_name": "PostgreSQL",+ "query": "UPDATE calendar_change_log SET created_at = now() - interval '40 days' WHERE link_id = $1",+ "describe": {+ "columns": [],+ "parameters": {+ "Left": [+ "Uuid"+ ]+ },+ "nullable": []+ },+ "hash": "ab92e3babbad2d74b9f47db60cf48c301df2ca353b76e7dbd9170adfaa21031d"+}diff --git a/.sqlx/query-acd569257805385d6626989e4056a23ef16e173539005e42642a7d457f698abc.json b/.sqlx/query-acd569257805385d6626989e4056a23ef16e173539005e42642a7d457f698abc.jsonnew file mode 100644index 0000000000..6eccf8e27f--- /dev/null+++ b/.sqlx/query-acd569257805385d6626989e4056a23ef16e173539005e42642a7d457f698abc.json@@ -0,0 +1,22 @@+{+ "db_name": "PostgreSQL",+ "query": "SELECT seq FROM calendar_change_counters WHERE link_id = $1",+ "describe": {+ "columns": [+ {+ "ordinal": 0,+ "name": "seq",+ "type_info": "Int8"+ }+ ],+ "parameters": {+ "Left": [+ "Uuid"+ ]+ },+ "nullable": [+ false+ ]+ },+ "hash": "acd569257805385d6626989e4056a23ef16e173539005e42642a7d457f698abc"+}diff --git a/.sqlx/query-ad3282ea97b12bd71d1d6330d7e59aaf8df87e6dad7a52c12d143f03d573b757.json b/.sqlx/query-ad3282ea97b12bd71d1d6330d7e59aaf8df87e6dad7a52c12d143f03d573b757.jsonnew file mode 100644index 0000000000..fb2840ec1e--- /dev/null+++ b/.sqlx/query-ad3282ea97b12bd71d1d6330d7e59aaf8df87e6dad7a52c12d143f03d573b757.json@@ -0,0 +1,14 @@+{+ "db_name": "PostgreSQL",+ "query": "UPDATE calendar_accounts SET sync_status = 'disabled' WHERE email_link_id = $1",+ "describe": {+ "columns": [],+ "parameters": {+ "Left": [+ "Uuid"+ ]+ },+ "nullable": []+ },+ "hash": "ad3282ea97b12bd71d1d6330d7e59aaf8df87e6dad7a52c12d143f03d573b757"+}diff --git a/.sqlx/query-ae3debae48c69dd06757b4f8c07a5940485944f7b47ea47a49562ee7ca162848.json b/.sqlx/query-ae3debae48c69dd06757b4f8c07a5940485944f7b47ea47a49562ee7ca162848.jsonnew file mode 100644index 0000000000..9f12e10ab2--- /dev/null+++ b/.sqlx/query-ae3debae48c69dd06757b4f8c07a5940485944f7b47ea47a49562ee7ca162848.json@@ -0,0 +1,14 @@+{+ "db_name": "PostgreSQL",+ "query": "UPDATE calendars SET snapshot_normalization_version=0 WHERE account_id=$1",+ "describe": {+ "columns": [],+ "parameters": {+ "Left": [+ "Uuid"+ ]+ },+ "nullable": []+ },+ "hash": "ae3debae48c69dd06757b4f8c07a5940485944f7b47ea47a49562ee7ca162848"+}diff --git a/.sqlx/query-afed14d65b93dc016921f0c3842f0ed3546a051fdefc397e0130e5617148d7d9.json b/.sqlx/query-afed14d65b93dc016921f0c3842f0ed3546a051fdefc397e0130e5617148d7d9.jsonnew file mode 100644index 0000000000..70a75d59f9--- /dev/null+++ b/.sqlx/query-afed14d65b93dc016921f0c3842f0ed3546a051fdefc397e0130e5617148d7d9.json@@ -0,0 +1,40 @@+{+ "db_name": "PostgreSQL",+ "query": "\n SELECT\n job.status AS job_status,\n account.sync_status AS account_status,\n link.needs_reauth,\n link.last_sync_error_at\n FROM calendar_backfill_jobs job\n JOIN calendar_accounts account ON account.id = job.account_id\n JOIN email_links link ON link.id = job.email_link_id\n WHERE job.id = $1\n ",+ "describe": {+ "columns": [+ {+ "ordinal": 0,+ "name": "job_status",+ "type_info": "Text"+ },+ {+ "ordinal": 1,+ "name": "account_status",+ "type_info": "Text"+ },+ {+ "ordinal": 2,+ "name": "needs_reauth",+ "type_info": "Bool"+ },+ {+ "ordinal": 3,+ "name": "last_sync_error_at",+ "type_info": "Timestamptz"+ }+ ],+ "parameters": {+ "Left": [+ "Uuid"+ ]+ },+ "nullable": [+ false,+ false,+ false,+ true+ ]+ },+ "hash": "afed14d65b93dc016921f0c3842f0ed3546a051fdefc397e0130e5617148d7d9"+}diff --git a/.sqlx/query-b213c1e58d762fa44747443ae41e18e1fc8007787953838822a0f46005bfbd6d.json b/.sqlx/query-b213c1e58d762fa44747443ae41e18e1fc8007787953838822a0f46005bfbd6d.jsonnew file mode 100644index 0000000000..88e749a69f--- /dev/null+++ b/.sqlx/query-b213c1e58d762fa44747443ae41e18e1fc8007787953838822a0f46005bfbd6d.json@@ -0,0 +1,14 @@+{+ "db_name": "PostgreSQL",+ "query": "UPDATE calendar_backfill_jobs SET lease_expires_at = now() - interval '20 minutes' WHERE id = $1",+ "describe": {+ "columns": [],+ "parameters": {+ "Left": [+ "Uuid"+ ]+ },+ "nullable": []+ },+ "hash": "b213c1e58d762fa44747443ae41e18e1fc8007787953838822a0f46005bfbd6d"+}diff --git a/.sqlx/query-b37f4a45679755c7321b5209cc0c53726df450e36b3532008e9d6a0943f26603.json b/.sqlx/query-b37f4a45679755c7321b5209cc0c53726df450e36b3532008e9d6a0943f26603.jsonnew file mode 100644index 0000000000..5c35a73b72--- /dev/null+++ b/.sqlx/query-b37f4a45679755c7321b5209cc0c53726df450e36b3532008e9d6a0943f26603.json@@ -0,0 +1,22 @@+{+ "db_name": "PostgreSQL",+ "query": "SELECT sync_status FROM calendar_accounts WHERE id = $1",+ "describe": {+ "columns": [+ {+ "ordinal": 0,+ "name": "sync_status",+ "type_info": "Text"+ }+ ],+ "parameters": {+ "Left": [+ "Uuid"+ ]+ },+ "nullable": [+ false+ ]+ },+ "hash": "b37f4a45679755c7321b5209cc0c53726df450e36b3532008e9d6a0943f26603"+}diff --git a/.sqlx/query-b4231a071d13eae93e1349628ec9a214027d0df707513c20cc70f3f9aa75b01b.json b/.sqlx/query-b4231a071d13eae93e1349628ec9a214027d0df707513c20cc70f3f9aa75b01b.jsonnew file mode 100644index 0000000000..5b80a39283--- /dev/null+++ b/.sqlx/query-b4231a071d13eae93e1349628ec9a214027d0df707513c20cc70f3f9aa75b01b.json@@ -0,0 +1,14 @@+{+ "db_name": "PostgreSQL",+ "query": "\n UPDATE calendar_accounts\n SET last_synced_at = now() - interval '10 minutes'\n WHERE id = $1\n ",+ "describe": {+ "columns": [],+ "parameters": {+ "Left": [+ "Uuid"+ ]+ },+ "nullable": []+ },+ "hash": "b4231a071d13eae93e1349628ec9a214027d0df707513c20cc70f3f9aa75b01b"+}diff --git a/.sqlx/query-b686dd32c4ce2ee977aff0ccdf0ca18985be170631af2ddcc2caaac151904fde.json b/.sqlx/query-b686dd32c4ce2ee977aff0ccdf0ca18985be170631af2ddcc2caaac151904fde.jsonnew file mode 100644index 0000000000..3590d57838--- /dev/null+++ b/.sqlx/query-b686dd32c4ce2ee977aff0ccdf0ca18985be170631af2ddcc2caaac151904fde.json@@ -0,0 +1,14 @@+{+ "db_name": "PostgreSQL",+ "query": "\n UPDATE calendar_accounts\n SET sync_status = 'syncing',\n updated_at = now()\n WHERE email_link_id = $1\n ",+ "describe": {+ "columns": [],+ "parameters": {+ "Left": [+ "Uuid"+ ]+ },+ "nullable": []+ },+ "hash": "b686dd32c4ce2ee977aff0ccdf0ca18985be170631af2ddcc2caaac151904fde"+}diff --git a/.sqlx/query-b6d4625b6d4c058116feded96e97884cc7a7717ed4a5700966a3d23c674cce21.json b/.sqlx/query-b6d4625b6d4c058116feded96e97884cc7a7717ed4a5700966a3d23c674cce21.jsonnew file mode 100644index 0000000000..6e6a41a37d--- /dev/null+++ b/.sqlx/query-b6d4625b6d4c058116feded96e97884cc7a7717ed4a5700966a3d23c674cce21.json@@ -0,0 +1,40 @@+{+ "db_name": "PostgreSQL",+ "query": "\n SELECT calendar.id, calendar.name, calendar.is_primary,\n COALESCE(preference.contributes_to_availability,\n account.owner_id = $1 AND calendar.is_primary) AS \"contributes!\"\n FROM calendars calendar JOIN calendar_accounts account ON account.id = calendar.account_id\n LEFT JOIN calendar_availability_preferences preference ON preference.calendar_id = calendar.id AND preference.user_id = $1\n WHERE NOT calendar.is_deleted AND account.sync_status <> 'disabled'\n AND (account.owner_id = $1 OR EXISTS (SELECT 1 FROM macro_user_links link WHERE link.link_id = account.email_link_id AND link.primary_macro_id = $1))\n ORDER BY calendar.name, calendar.id\n ",+ "describe": {+ "columns": [+ {+ "ordinal": 0,+ "name": "id",+ "type_info": "Uuid"+ },+ {+ "ordinal": 1,+ "name": "name",+ "type_info": "Text"+ },+ {+ "ordinal": 2,+ "name": "is_primary",+ "type_info": "Bool"+ },+ {+ "ordinal": 3,+ "name": "contributes!",+ "type_info": "Bool"+ }+ ],+ "parameters": {+ "Left": [+ "Text"+ ]+ },+ "nullable": [+ false,+ false,+ false,+ null+ ]+ },+ "hash": "b6d4625b6d4c058116feded96e97884cc7a7717ed4a5700966a3d23c674cce21"+}diff --git a/.sqlx/query-b9931658292b2c291424844093c49f4ee11a78c3f0c48b06683723ff9ad99508.json b/.sqlx/query-b9931658292b2c291424844093c49f4ee11a78c3f0c48b06683723ff9ad99508.jsonnew file mode 100644index 0000000000..916a218a70--- /dev/null+++ b/.sqlx/query-b9931658292b2c291424844093c49f4ee11a78c3f0c48b06683723ff9ad99508.json@@ -0,0 +1,14 @@+{+ "db_name": "PostgreSQL",+ "query": "UPDATE calendar_event_sources SET provider_access_role = NULL WHERE event_id = $1",+ "describe": {+ "columns": [],+ "parameters": {+ "Left": [+ "Uuid"+ ]+ },+ "nullable": []+ },+ "hash": "b9931658292b2c291424844093c49f4ee11a78c3f0c48b06683723ff9ad99508"+}diff --git a/.sqlx/query-bd37a33a82a494a2fe668169d07d22ea805b30ffd34e53c9407b0ed04ee43654.json b/.sqlx/query-bd37a33a82a494a2fe668169d07d22ea805b30ffd34e53c9407b0ed04ee43654.jsonnew file mode 100644index 0000000000..9c45666aca--- /dev/null+++ b/.sqlx/query-bd37a33a82a494a2fe668169d07d22ea805b30ffd34e53c9407b0ed04ee43654.json@@ -0,0 +1,15 @@+{+ "db_name": "PostgreSQL",+ "query": "INSERT INTO comms_channel_participants (channel_id, user_id, role) VALUES ($1, $2, 'member')",+ "describe": {+ "columns": [],+ "parameters": {+ "Left": [+ "Uuid",+ "Text"+ ]+ },+ "nullable": []+ },+ "hash": "bd37a33a82a494a2fe668169d07d22ea805b30ffd34e53c9407b0ed04ee43654"+}diff --git a/.sqlx/query-be31a5baca5e5f0265f9987bdaf230238454be9fa8cd0135c5892f297d3b0c50.json b/.sqlx/query-be31a5baca5e5f0265f9987bdaf230238454be9fa8cd0135c5892f297d3b0c50.jsonnew file mode 100644index 0000000000..2a3d110c2a--- /dev/null+++ b/.sqlx/query-be31a5baca5e5f0265f9987bdaf230238454be9fa8cd0135c5892f297d3b0c50.json@@ -0,0 +1,28 @@+{+ "db_name": "PostgreSQL",+ "query": "\n SELECT\n (SELECT count(*) FROM calendar_events WHERE id = $1) AS \"event_count!\",\n (SELECT count(*) FROM calendar_event_sources WHERE event_id = $1) AS \"source_count!\"\n ",+ "describe": {+ "columns": [+ {+ "ordinal": 0,+ "name": "event_count!",+ "type_info": "Int8"+ },+ {+ "ordinal": 1,+ "name": "source_count!",+ "type_info": "Int8"+ }+ ],+ "parameters": {+ "Left": [+ "Uuid"+ ]+ },+ "nullable": [+ null,+ null+ ]+ },+ "hash": "be31a5baca5e5f0265f9987bdaf230238454be9fa8cd0135c5892f297d3b0c50"+}diff --git a/.sqlx/query-c01ca10561801578ddc5ca42f62f3cad73c845e381c7222168d8c2beab3cdd2e.json b/.sqlx/query-c01ca10561801578ddc5ca42f62f3cad73c845e381c7222168d8c2beab3cdd2e.jsonnew file mode 100644index 0000000000..68a2d42cf9--- /dev/null+++ b/.sqlx/query-c01ca10561801578ddc5ca42f62f3cad73c845e381c7222168d8c2beab3cdd2e.json@@ -0,0 +1,14 @@+{+ "db_name": "PostgreSQL",+ "query": "UPDATE calendars SET access_role = 'writer' WHERE id = $1",+ "describe": {+ "columns": [],+ "parameters": {+ "Left": [+ "Uuid"+ ]+ },+ "nullable": []+ },+ "hash": "c01ca10561801578ddc5ca42f62f3cad73c845e381c7222168d8c2beab3cdd2e"+}diff --git a/.sqlx/query-c465c86774a284bbc52cd251fc869d61520e0b29e58a73d21bfc138e6e8c29cc.json b/.sqlx/query-c465c86774a284bbc52cd251fc869d61520e0b29e58a73d21bfc138e6e8c29cc.jsonnew file mode 100644index 0000000000..f7317cb4c5--- /dev/null+++ b/.sqlx/query-c465c86774a284bbc52cd251fc869d61520e0b29e58a73d21bfc138e6e8c29cc.json@@ -0,0 +1,22 @@+{+ "db_name": "PostgreSQL",+ "query": "\n SELECT count(*) AS \"count!\"\n FROM calendar_events\n WHERE owner_id = $1\n AND ical_uid = '[email protected]'\n ",+ "describe": {+ "columns": [+ {+ "ordinal": 0,+ "name": "count!",+ "type_info": "Int8"+ }+ ],+ "parameters": {+ "Left": [+ "Text"+ ]+ },+ "nullable": [+ null+ ]+ },+ "hash": "c465c86774a284bbc52cd251fc869d61520e0b29e58a73d21bfc138e6e8c29cc"+}diff --git a/.sqlx/query-c607a885b975f97c31292631a354ff4f0b83210d1849bcf0901651469242d6ec.json b/.sqlx/query-c607a885b975f97c31292631a354ff4f0b83210d1849bcf0901651469242d6ec.jsonnew file mode 100644index 0000000000..72cd4fc950--- /dev/null+++ b/.sqlx/query-c607a885b975f97c31292631a354ff4f0b83210d1849bcf0901651469242d6ec.json@@ -0,0 +1,14 @@+{+ "db_name": "PostgreSQL",+ "query": "\n UPDATE calendar_backfill_jobs\n SET lease_expires_at = now() - interval '1 second'\n WHERE id = $1\n ",+ "describe": {+ "columns": [],+ "parameters": {+ "Left": [+ "Uuid"+ ]+ },+ "nullable": []+ },+ "hash": "c607a885b975f97c31292631a354ff4f0b83210d1849bcf0901651469242d6ec"+}diff --git a/.sqlx/query-cd478841e1611f4d25a337ae745091e4bee407a73708b784395e38133e00ee72.json b/.sqlx/query-cd478841e1611f4d25a337ae745091e4bee407a73708b784395e38133e00ee72.jsonnew file mode 100644index 0000000000..4de8e6b36a--- /dev/null+++ b/.sqlx/query-cd478841e1611f4d25a337ae745091e4bee407a73708b784395e38133e00ee72.json@@ -0,0 +1,22 @@+{+ "db_name": "PostgreSQL",+ "query": "SELECT count(*) AS \"count!\" FROM calendar_events WHERE owner_id = $1",+ "describe": {+ "columns": [+ {+ "ordinal": 0,+ "name": "count!",+ "type_info": "Int8"+ }+ ],+ "parameters": {+ "Left": [+ "Text"+ ]+ },+ "nullable": [+ null+ ]+ },+ "hash": "cd478841e1611f4d25a337ae745091e4bee407a73708b784395e38133e00ee72"+}diff --git a/.sqlx/query-cd9f3727ba0ddd65fd1de9ab8cab0c8b085ab3b3731446ada9a761bd9e008b5d.json b/.sqlx/query-cd9f3727ba0ddd65fd1de9ab8cab0c8b085ab3b3731446ada9a761bd9e008b5d.jsonnew file mode 100644index 0000000000..afe534ea30--- /dev/null+++ b/.sqlx/query-cd9f3727ba0ddd65fd1de9ab8cab0c8b085ab3b3731446ada9a761bd9e008b5d.json@@ -0,0 +1,16 @@+{+ "db_name": "PostgreSQL",+ "query": "\n INSERT INTO email_link_google_scopes (link_id, granted_scopes, grant_version)\n VALUES ($1, $2, $3)\n ON CONFLICT (link_id) DO UPDATE\n SET granted_scopes = EXCLUDED.granted_scopes,\n grant_version = EXCLUDED.grant_version,\n updated_at = now()\n ",+ "describe": {+ "columns": [],+ "parameters": {+ "Left": [+ "Uuid",+ "TextArray",+ "Int8"+ ]+ },+ "nullable": []+ },+ "hash": "cd9f3727ba0ddd65fd1de9ab8cab0c8b085ab3b3731446ada9a761bd9e008b5d"+}diff --git a/.sqlx/query-cea2f2d45f2a0b58185e0f3616320e95cb474c36c45fe69c82e676daf57d30b4.json b/.sqlx/query-cea2f2d45f2a0b58185e0f3616320e95cb474c36c45fe69c82e676daf57d30b4.jsonnew file mode 100644index 0000000000..4a7f7513af--- /dev/null+++ b/.sqlx/query-cea2f2d45f2a0b58185e0f3616320e95cb474c36c45fe69c82e676daf57d30b4.json@@ -0,0 +1,45 @@+{+ "db_name": "PostgreSQL",+ "query": "\n INSERT INTO calendar_event_sources (\n id, event_id, source_link_id, source_kind, account_id, calendar_id,\n provider_event_id, provider_recurring_event_id,\n provider_etag, raw_payload, source_sequence,\n source_updated_at, normalized_payload, provider_access_role,\n title, description, location, event_type, visibility, transparency,\n is_read_only, reminders_use_default, reminder_overrides,\n creator_email, creator_name\n )\n VALUES (\n $1, $2, $3, 'google', $4, $5, $6, $7, $8, $9,\n $10, $11, $12,\n $24,\n $13, $14, $15, $16, $17, $18,\n $19, $20, $21,\n $22, $23\n )\n ON CONFLICT (account_id, calendar_id, provider_event_id)\n WHERE source_kind = 'google'\n DO UPDATE SET\n event_id = EXCLUDED.event_id,\n provider_recurring_event_id = EXCLUDED.provider_recurring_event_id,\n provider_etag = EXCLUDED.provider_etag,\n raw_payload = EXCLUDED.raw_payload,\n source_sequence = EXCLUDED.source_sequence,\n source_updated_at = EXCLUDED.source_updated_at,\n normalized_payload = EXCLUDED.normalized_payload,\n provider_access_role = EXCLUDED.provider_access_role,\n title = EXCLUDED.title,\n description = EXCLUDED.description,\n location = EXCLUDED.location,\n event_type = EXCLUDED.event_type,\n visibility = EXCLUDED.visibility,\n transparency = EXCLUDED.transparency,\n is_read_only = EXCLUDED.is_read_only,\n reminders_use_default = EXCLUDED.reminders_use_default,\n reminder_overrides = EXCLUDED.reminder_overrides,\n creator_email = EXCLUDED.creator_email,\n creator_name = EXCLUDED.creator_name,\n last_seen_at = now()\n WHERE\n EXCLUDED.source_sequence > calendar_event_sources.source_sequence\n OR (\n EXCLUDED.source_sequence = calendar_event_sources.source_sequence\n AND EXCLUDED.source_updated_at >= calendar_event_sources.source_updated_at\n )\n RETURNING id\n ",+ "describe": {+ "columns": [+ {+ "ordinal": 0,+ "name": "id",+ "type_info": "Uuid"+ }+ ],+ "parameters": {+ "Left": [+ "Uuid",+ "Uuid",+ "Uuid",+ "Uuid",+ "Uuid",+ "Text",+ "Text",+ "Text",+ "Jsonb",+ "Int4",+ "Timestamptz",+ "Jsonb",+ "Text",+ "Text",+ "Text",+ "Text",+ "Text",+ "Text",+ "Bool",+ "Bool",+ "Jsonb",+ "Text",+ "Text",+ "Text"+ ]+ },+ "nullable": [+ false+ ]+ },+ "hash": "cea2f2d45f2a0b58185e0f3616320e95cb474c36c45fe69c82e676daf57d30b4"+}diff --git a/.sqlx/query-cec2290034dfc1eb6b928b4241895d106c8dc8d5ef51a4acd361eade3692b8ad.json b/.sqlx/query-cec2290034dfc1eb6b928b4241895d106c8dc8d5ef51a4acd361eade3692b8ad.jsonnew file mode 100644index 0000000000..f7b0af1412--- /dev/null+++ b/.sqlx/query-cec2290034dfc1eb6b928b4241895d106c8dc8d5ef51a4acd361eade3692b8ad.json@@ -0,0 +1,14 @@+{+ "db_name": "PostgreSQL",+ "query": "UPDATE calendars SET access_role = 'reader', synced_at = now() WHERE id = $1",+ "describe": {+ "columns": [],+ "parameters": {+ "Left": [+ "Uuid"+ ]+ },+ "nullable": []+ },+ "hash": "cec2290034dfc1eb6b928b4241895d106c8dc8d5ef51a4acd361eade3692b8ad"+}diff --git a/.sqlx/query-d0758035f94c3b764b2258a9bf902da79b23301f609941a29b856a522d3a2912.json b/.sqlx/query-d0758035f94c3b764b2258a9bf902da79b23301f609941a29b856a522d3a2912.jsonnew file mode 100644index 0000000000..8367fe319b--- /dev/null+++ b/.sqlx/query-d0758035f94c3b764b2258a9bf902da79b23301f609941a29b856a522d3a2912.json@@ -0,0 +1,22 @@+{+ "db_name": "PostgreSQL",+ "query": "\n WITH members AS (\n SELECT teammate.user_id FROM team_user viewer JOIN team_user teammate ON teammate.team_id = viewer.team_id WHERE viewer.user_id = $1\n UNION SELECT $1::text\n )\n SELECT md5(COALESCE(string_agg(jsonb_build_array(members.user_id, policy.sharing, policy.updated_at,\n account.id, account.sync_status IN ('ready','syncing'), account.last_sync_error IS NULL,\n COALESCE(account.last_synced_at > now() - interval '15 minutes', false), calendar.id, calendar.access_role,\n calendar.synced_at IS NULL, calendar.snapshot_normalization_version, calendar.is_deleted, calendar.is_primary, calendar.name, calendar.time_zone,\n calendar.last_sync_error IS NULL, calendar.materialized_starts_at, calendar.materialized_ends_at,\n calendar.materialized_start_date, calendar.materialized_end_date,\n preference.contributes_to_availability, counter.seq)::text, '|' ORDER BY members.user_id, account.id, calendar.id), '')) AS \"revision!\"\n FROM members LEFT JOIN calendar_team_sharing policy ON policy.user_id = members.user_id\n LEFT JOIN calendar_accounts account ON (account.owner_id = members.user_id OR EXISTS (\n SELECT 1 FROM macro_user_links link WHERE link.link_id = account.email_link_id AND link.primary_macro_id = members.user_id\n ))\n LEFT JOIN calendars calendar ON calendar.account_id = account.id\n LEFT JOIN calendar_availability_preferences preference ON preference.calendar_id = calendar.id AND preference.user_id = members.user_id\n LEFT JOIN calendar_change_counters counter ON counter.link_id = account.email_link_id\n ",+ "describe": {+ "columns": [+ {+ "ordinal": 0,+ "name": "revision!",+ "type_info": "Text"+ }+ ],+ "parameters": {+ "Left": [+ "Text"+ ]+ },+ "nullable": [+ null+ ]+ },+ "hash": "d0758035f94c3b764b2258a9bf902da79b23301f609941a29b856a522d3a2912"+}diff --git a/.sqlx/query-d224fec1fc8eaa6bc13b523178367e1df94ebb30c2c91900356489f17bab3e50.json b/.sqlx/query-d224fec1fc8eaa6bc13b523178367e1df94ebb30c2c91900356489f17bab3e50.jsonnew file mode 100644index 0000000000..79887a0bcb--- /dev/null+++ b/.sqlx/query-d224fec1fc8eaa6bc13b523178367e1df94ebb30c2c91900356489f17bab3e50.json@@ -0,0 +1,14 @@+{+ "db_name": "PostgreSQL",+ "query": "UPDATE calendar_sync_outbox SET published_at = now() - interval '30 minutes' WHERE backfill_job_id = $1",+ "describe": {+ "columns": [],+ "parameters": {+ "Left": [+ "Uuid"+ ]+ },+ "nullable": []+ },+ "hash": "d224fec1fc8eaa6bc13b523178367e1df94ebb30c2c91900356489f17bab3e50"+}diff --git a/.sqlx/query-d2f4f0047dc35fa1fa49e851a3693afce63ea36e15797fb97d80629a9e56030e.json b/.sqlx/query-d2f4f0047dc35fa1fa49e851a3693afce63ea36e15797fb97d80629a9e56030e.jsonnew file mode 100644index 0000000000..2a80439c97--- /dev/null+++ b/.sqlx/query-d2f4f0047dc35fa1fa49e851a3693afce63ea36e15797fb97d80629a9e56030e.json@@ -0,0 +1,28 @@+{+ "db_name": "PostgreSQL",+ "query": "\n SELECT account.sync_status, link.needs_reauth\n FROM calendar_accounts account\n JOIN email_links link ON link.id = account.email_link_id\n WHERE account.id = $1\n ",+ "describe": {+ "columns": [+ {+ "ordinal": 0,+ "name": "sync_status",+ "type_info": "Text"+ },+ {+ "ordinal": 1,+ "name": "needs_reauth",+ "type_info": "Bool"+ }+ ],+ "parameters": {+ "Left": [+ "Uuid"+ ]+ },+ "nullable": [+ false,+ false+ ]+ },+ "hash": "d2f4f0047dc35fa1fa49e851a3693afce63ea36e15797fb97d80629a9e56030e"+}diff --git a/.sqlx/query-d5d483fa9a3fd3d6e8cf519d259dc78cf5a9e5aa0920b944969964501f2fb728.json b/.sqlx/query-d5d483fa9a3fd3d6e8cf519d259dc78cf5a9e5aa0920b944969964501f2fb728.jsonnew file mode 100644index 0000000000..07d59b4860--- /dev/null+++ b/.sqlx/query-d5d483fa9a3fd3d6e8cf519d259dc78cf5a9e5aa0920b944969964501f2fb728.json@@ -0,0 +1,14 @@+{+ "db_name": "PostgreSQL",+ "query": "UPDATE calendars SET access_role = 'reader' WHERE id = $1",+ "describe": {+ "columns": [],+ "parameters": {+ "Left": [+ "Uuid"+ ]+ },+ "nullable": []+ },+ "hash": "d5d483fa9a3fd3d6e8cf519d259dc78cf5a9e5aa0920b944969964501f2fb728"+}diff --git a/.sqlx/query-d6c9b446490cccb56361011d8d87a4d8cf6cd383abbb39ab45db1d5b5b6645f9.json b/.sqlx/query-d6c9b446490cccb56361011d8d87a4d8cf6cd383abbb39ab45db1d5b5b6645f9.jsonnew file mode 100644index 0000000000..e6a7abe5f4--- /dev/null+++ b/.sqlx/query-d6c9b446490cccb56361011d8d87a4d8cf6cd383abbb39ab45db1d5b5b6645f9.json@@ -0,0 +1,14 @@+{+ "db_name": "PostgreSQL",+ "query": "UPDATE calendars SET snapshot_normalization_version=1 WHERE id=$1",+ "describe": {+ "columns": [],+ "parameters": {+ "Left": [+ "Uuid"+ ]+ },+ "nullable": []+ },+ "hash": "d6c9b446490cccb56361011d8d87a4d8cf6cd383abbb39ab45db1d5b5b6645f9"+}diff --git a/.sqlx/query-dc511ec624bddfb5cd7b83decafb90b0cb9bb80c96da5943805a76f01e34eb40.json b/.sqlx/query-dc511ec624bddfb5cd7b83decafb90b0cb9bb80c96da5943805a76f01e34eb40.jsonnew file mode 100644index 0000000000..638ccf15eb--- /dev/null+++ b/.sqlx/query-dc511ec624bddfb5cd7b83decafb90b0cb9bb80c96da5943805a76f01e34eb40.json@@ -0,0 +1,14 @@+{+ "db_name": "PostgreSQL",+ "query": "UPDATE calendar_accounts SET last_synced_at=NULL WHERE id=$1 AND last_synced_at IS NOT NULL",+ "describe": {+ "columns": [],+ "parameters": {+ "Left": [+ "Uuid"+ ]+ },+ "nullable": []+ },+ "hash": "dc511ec624bddfb5cd7b83decafb90b0cb9bb80c96da5943805a76f01e34eb40"+}diff --git a/.sqlx/query-e18bdb73d69d37ea32745f55c613dc74c98c82cfd7c7bf32cd683b160823e8ac.json b/.sqlx/query-e18bdb73d69d37ea32745f55c613dc74c98c82cfd7c7bf32cd683b160823e8ac.jsonnew file mode 100644index 0000000000..fb7ff9f34d--- /dev/null+++ b/.sqlx/query-e18bdb73d69d37ea32745f55c613dc74c98c82cfd7c7bf32cd683b160823e8ac.json@@ -0,0 +1,15 @@+{+ "db_name": "PostgreSQL",+ "query": "INSERT INTO comms_channels (id, channel_type, owner_id) VALUES ($1, 'private', $2)",+ "describe": {+ "columns": [],+ "parameters": {+ "Left": [+ "Uuid",+ "Text"+ ]+ },+ "nullable": []+ },+ "hash": "e18bdb73d69d37ea32745f55c613dc74c98c82cfd7c7bf32cd683b160823e8ac"+}diff --git a/.sqlx/query-e2e897244504a70648f99e3273a2b1dae62cd13c2bd642d31dfbdc4dcef65101.json b/.sqlx/query-e2e897244504a70648f99e3273a2b1dae62cd13c2bd642d31dfbdc4dcef65101.jsonnew file mode 100644index 0000000000..946e24c10c--- /dev/null+++ b/.sqlx/query-e2e897244504a70648f99e3273a2b1dae62cd13c2bd642d31dfbdc4dcef65101.json@@ -0,0 +1,22 @@+{+ "db_name": "PostgreSQL",+ "query": "SELECT status FROM calendar_backfill_jobs WHERE id = $1",+ "describe": {+ "columns": [+ {+ "ordinal": 0,+ "name": "status",+ "type_info": "Text"+ }+ ],+ "parameters": {+ "Left": [+ "Uuid"+ ]+ },+ "nullable": [+ false+ ]+ },+ "hash": "e2e897244504a70648f99e3273a2b1dae62cd13c2bd642d31dfbdc4dcef65101"+}diff --git a/.sqlx/query-e35afcf3f15eeaa81c9caf8fdae2e7bbac901d5b7549ffd52b81ab1892f1e916.json b/.sqlx/query-e35afcf3f15eeaa81c9caf8fdae2e7bbac901d5b7549ffd52b81ab1892f1e916.jsonnew file mode 100644index 0000000000..f30bfbcce2--- /dev/null+++ b/.sqlx/query-e35afcf3f15eeaa81c9caf8fdae2e7bbac901d5b7549ffd52b81ab1892f1e916.json@@ -0,0 +1,28 @@+{+ "db_name": "PostgreSQL",+ "query": "\n SELECT granted_scopes, (calendar_disabled_at IS NOT NULL) AS \"opted_out!\"\n FROM email_link_google_scopes WHERE link_id = $1\n ",+ "describe": {+ "columns": [+ {+ "ordinal": 0,+ "name": "granted_scopes",+ "type_info": "TextArray"+ },+ {+ "ordinal": 1,+ "name": "opted_out!",+ "type_info": "Bool"+ }+ ],+ "parameters": {+ "Left": [+ "Uuid"+ ]+ },+ "nullable": [+ false,+ null+ ]+ },+ "hash": "e35afcf3f15eeaa81c9caf8fdae2e7bbac901d5b7549ffd52b81ab1892f1e916"+}diff --git a/.sqlx/query-e75789d447c4edd55bfbc8d3eda1dbfae2a8ba4809e9955ab9950e2f42079733.json b/.sqlx/query-e75789d447c4edd55bfbc8d3eda1dbfae2a8ba4809e9955ab9950e2f42079733.jsonnew file mode 100644index 0000000000..2b23478d95--- /dev/null+++ b/.sqlx/query-e75789d447c4edd55bfbc8d3eda1dbfae2a8ba4809e9955ab9950e2f42079733.json@@ -0,0 +1,15 @@+{+ "db_name": "PostgreSQL",+ "query": "UPDATE calendars SET snapshot_normalization_version=1 WHERE id=$1 AND account_id=$2 AND NOT is_deleted",+ "describe": {+ "columns": [],+ "parameters": {+ "Left": [+ "Uuid",+ "Uuid"+ ]+ },+ "nullable": []+ },+ "hash": "e75789d447c4edd55bfbc8d3eda1dbfae2a8ba4809e9955ab9950e2f42079733"+}diff --git a/.sqlx/query-e89cf7546c3aa6739811ef59282d928ddac771af6143dd331c6ff7122990145e.json b/.sqlx/query-e89cf7546c3aa6739811ef59282d928ddac771af6143dd331c6ff7122990145e.jsonnew file mode 100644index 0000000000..2a64486cd7--- /dev/null+++ b/.sqlx/query-e89cf7546c3aa6739811ef59282d928ddac771af6143dd331c6ff7122990145e.json@@ -0,0 +1,34 @@+{+ "db_name": "PostgreSQL",+ "query": "SELECT title, description, provider_access_role FROM calendar_event_sources WHERE event_id = $1",+ "describe": {+ "columns": [+ {+ "ordinal": 0,+ "name": "title",+ "type_info": "Text"+ },+ {+ "ordinal": 1,+ "name": "description",+ "type_info": "Text"+ },+ {+ "ordinal": 2,+ "name": "provider_access_role",+ "type_info": "Text"+ }+ ],+ "parameters": {+ "Left": [+ "Uuid"+ ]+ },+ "nullable": [+ false,+ true,+ true+ ]+ },+ "hash": "e89cf7546c3aa6739811ef59282d928ddac771af6143dd331c6ff7122990145e"+}diff --git a/.sqlx/query-edaea28192b00cb0886f13d5fabbc39e475970abae720c14424bb3d94cea362d.json b/.sqlx/query-edaea28192b00cb0886f13d5fabbc39e475970abae720c14424bb3d94cea362d.jsonnew file mode 100644index 0000000000..195c6b87bb--- /dev/null+++ b/.sqlx/query-edaea28192b00cb0886f13d5fabbc39e475970abae720c14424bb3d94cea362d.json@@ -0,0 +1,16 @@+{+ "db_name": "PostgreSQL",+ "query": "UPDATE calendars SET last_sync_error=$2,snapshot_normalization_version=$3 WHERE id=$1",+ "describe": {+ "columns": [],+ "parameters": {+ "Left": [+ "Uuid",+ "Text",+ "Int4"+ ]+ },+ "nullable": []+ },+ "hash": "edaea28192b00cb0886f13d5fabbc39e475970abae720c14424bb3d94cea362d"+}diff --git a/.sqlx/query-f1cc2af79f3b8088623953af157d62cf79a1a8deabdeb17b8c6dae489c2917fc.json b/.sqlx/query-f1cc2af79f3b8088623953af157d62cf79a1a8deabdeb17b8c6dae489c2917fc.jsonnew file mode 100644index 0000000000..c8e87c6892--- /dev/null+++ b/.sqlx/query-f1cc2af79f3b8088623953af157d62cf79a1a8deabdeb17b8c6dae489c2917fc.json@@ -0,0 +1,34 @@+{+ "db_name": "PostgreSQL",+ "query": "\n SELECT occurrence_key, minutes_before, fire_at\n FROM calendar_event_reminder_firings\n WHERE event_id = $1\n ORDER BY fire_at, minutes_before\n ",+ "describe": {+ "columns": [+ {+ "ordinal": 0,+ "name": "occurrence_key",+ "type_info": "Text"+ },+ {+ "ordinal": 1,+ "name": "minutes_before",+ "type_info": "Int4"+ },+ {+ "ordinal": 2,+ "name": "fire_at",+ "type_info": "Timestamptz"+ }+ ],+ "parameters": {+ "Left": [+ "Uuid"+ ]+ },+ "nullable": [+ false,+ false,+ false+ ]+ },+ "hash": "f1cc2af79f3b8088623953af157d62cf79a1a8deabdeb17b8c6dae489c2917fc"+}diff --git a/.sqlx/query-f1db2512e038a8e0e29fa95227ca9540c61a539b8d2986cba1bb42259d113006.json b/.sqlx/query-f1db2512e038a8e0e29fa95227ca9540c61a539b8d2986cba1bb42259d113006.jsonnew file mode 100644index 0000000000..01750344c8--- /dev/null+++ b/.sqlx/query-f1db2512e038a8e0e29fa95227ca9540c61a539b8d2986cba1bb42259d113006.json@@ -0,0 +1,22 @@+{+ "db_name": "PostgreSQL",+ "query": "SELECT is_deleted AS \"is_deleted!\" FROM calendars WHERE id = $1",+ "describe": {+ "columns": [+ {+ "ordinal": 0,+ "name": "is_deleted!",+ "type_info": "Bool"+ }+ ],+ "parameters": {+ "Left": [+ "Uuid"+ ]+ },+ "nullable": [+ false+ ]+ },+ "hash": "f1db2512e038a8e0e29fa95227ca9540c61a539b8d2986cba1bb42259d113006"+}diff --git a/.sqlx/query-f2dcd3ac39e87492a62691d87a12e92fcacb72f447475742f1f71c7ce817d2ee.json b/.sqlx/query-f2dcd3ac39e87492a62691d87a12e92fcacb72f447475742f1f71c7ce817d2ee.jsonnew file mode 100644index 0000000000..c773a0061c--- /dev/null+++ b/.sqlx/query-f2dcd3ac39e87492a62691d87a12e92fcacb72f447475742f1f71c7ce817d2ee.json@@ -0,0 +1,15 @@+{+ "db_name": "PostgreSQL",+ "query": "INSERT INTO team_user(user_id,team_id,team_role) VALUES($1,$2,'member')",+ "describe": {+ "columns": [],+ "parameters": {+ "Left": [+ "Text",+ "Uuid"+ ]+ },+ "nullable": []+ },+ "hash": "f2dcd3ac39e87492a62691d87a12e92fcacb72f447475742f1f71c7ce817d2ee"+}diff --git a/.sqlx/query-f301b9913cdf0bac23f3ae299fa85013d82038c7610a45f0035877031f2ff69c.json b/.sqlx/query-f301b9913cdf0bac23f3ae299fa85013d82038c7610a45f0035877031f2ff69c.jsonnew file mode 100644index 0000000000..e2bd39dd34--- /dev/null+++ b/.sqlx/query-f301b9913cdf0bac23f3ae299fa85013d82038c7610a45f0035877031f2ff69c.json@@ -0,0 +1,40 @@+{+ "db_name": "PostgreSQL",+ "query": "\n SELECT seq, kind, event_id, calendar_id\n FROM calendar_change_log\n WHERE link_id = $1\n ORDER BY seq\n ",+ "describe": {+ "columns": [+ {+ "ordinal": 0,+ "name": "seq",+ "type_info": "Int8"+ },+ {+ "ordinal": 1,+ "name": "kind",+ "type_info": "Int2"+ },+ {+ "ordinal": 2,+ "name": "event_id",+ "type_info": "Uuid"+ },+ {+ "ordinal": 3,+ "name": "calendar_id",+ "type_info": "Uuid"+ }+ ],+ "parameters": {+ "Left": [+ "Uuid"+ ]+ },+ "nullable": [+ false,+ false,+ true,+ true+ ]+ },+ "hash": "f301b9913cdf0bac23f3ae299fa85013d82038c7610a45f0035877031f2ff69c"+}diff --git a/.sqlx/query-f400e52fd81e057c31a80c0bb4f4835481bf9952c8e4518d927f05212457585c.json b/.sqlx/query-f400e52fd81e057c31a80c0bb4f4835481bf9952c8e4518d927f05212457585c.jsonnew file mode 100644index 0000000000..ab57db9444--- /dev/null+++ b/.sqlx/query-f400e52fd81e057c31a80c0bb4f4835481bf9952c8e4518d927f05212457585c.json@@ -0,0 +1,16 @@+{+ "db_name": "PostgreSQL",+ "query": "\n INSERT INTO \"User\" (id, email, macro_user_id)\n VALUES ($1, $2, $3)\n ",+ "describe": {+ "columns": [],+ "parameters": {+ "Left": [+ "Text",+ "Text",+ "Uuid"+ ]+ },+ "nullable": []+ },+ "hash": "f400e52fd81e057c31a80c0bb4f4835481bf9952c8e4518d927f05212457585c"+}diff --git a/.sqlx/query-f551e38b0818512f71bfa817b48835410d809622c26c6f8bf238eccc60454089.json b/.sqlx/query-f551e38b0818512f71bfa817b48835410d809622c26c6f8bf238eccc60454089.jsonnew file mode 100644index 0000000000..32f5fae4d2--- /dev/null+++ b/.sqlx/query-f551e38b0818512f71bfa817b48835410d809622c26c6f8bf238eccc60454089.json@@ -0,0 +1,16 @@+{+ "db_name": "PostgreSQL",+ "query": "\n INSERT INTO email_links (\n id, macro_id, fusionauth_user_id, email_address, provider\n )\n VALUES ($1, $2, $2, $3, 'GMAIL')\n ",+ "describe": {+ "columns": [],+ "parameters": {+ "Left": [+ "Uuid",+ "Text",+ "Varchar"+ ]+ },+ "nullable": []+ },+ "hash": "f551e38b0818512f71bfa817b48835410d809622c26c6f8bf238eccc60454089"+}diff --git a/.sqlx/query-f56c86535a53feba7824d0af28e64d3502734254a2585a6bd1bbbe9be38c9a32.json b/.sqlx/query-f56c86535a53feba7824d0af28e64d3502734254a2585a6bd1bbbe9be38c9a32.jsonnew file mode 100644index 0000000000..354cf416b4--- /dev/null+++ b/.sqlx/query-f56c86535a53feba7824d0af28e64d3502734254a2585a6bd1bbbe9be38c9a32.json@@ -0,0 +1,17 @@+{+ "db_name": "PostgreSQL",+ "query": "\n UPDATE calendar_event_sources source\n SET provider_access_role = $4\n FROM calendars calendar\n WHERE source.calendar_id = calendar.id\n AND calendar.account_id = $1\n AND source.account_id = $1\n AND source.calendar_id = $2\n AND source.provider_event_id = $3\n AND $4::text IS NOT NULL\n AND calendar.access_role = $4\n AND source.provider_access_role IS DISTINCT FROM $4\n ",+ "describe": {+ "columns": [],+ "parameters": {+ "Left": [+ "Uuid",+ "Uuid",+ "Text",+ "Text"+ ]+ },+ "nullable": []+ },+ "hash": "f56c86535a53feba7824d0af28e64d3502734254a2585a6bd1bbbe9be38c9a32"+}diff --git a/.sqlx/query-f6992f796a1c21b672fd36d7eeaa592486d24b773775d26865ff64d4831447d6.json b/.sqlx/query-f6992f796a1c21b672fd36d7eeaa592486d24b773775d26865ff64d4831447d6.jsonnew file mode 100644index 0000000000..1fabb12b7e--- /dev/null+++ b/.sqlx/query-f6992f796a1c21b672fd36d7eeaa592486d24b773775d26865ff64d4831447d6.json@@ -0,0 +1,28 @@+{+ "db_name": "PostgreSQL",+ "query": "SELECT title, provider_access_role FROM calendar_event_sources WHERE event_id = $1",+ "describe": {+ "columns": [+ {+ "ordinal": 0,+ "name": "title",+ "type_info": "Text"+ },+ {+ "ordinal": 1,+ "name": "provider_access_role",+ "type_info": "Text"+ }+ ],+ "parameters": {+ "Left": [+ "Uuid"+ ]+ },+ "nullable": [+ false,+ true+ ]+ },+ "hash": "f6992f796a1c21b672fd36d7eeaa592486d24b773775d26865ff64d4831447d6"+}diff --git a/.sqlx/query-faf4e7eeb01e297390c6d77e3f4e4b2aebd90c7f4c75342ed92bd3dd5a2ffb7b.json b/.sqlx/query-faf4e7eeb01e297390c6d77e3f4e4b2aebd90c7f4c75342ed92bd3dd5a2ffb7b.jsonnew file mode 100644index 0000000000..c147db315b--- /dev/null+++ b/.sqlx/query-faf4e7eeb01e297390c6d77e3f4e4b2aebd90c7f4c75342ed92bd3dd5a2ffb7b.json@@ -0,0 +1,40 @@+{+ "db_name": "PostgreSQL",+ "query": "SELECT calendar.sync_token, calendar.synced_at, calendar.materialized_starts_at, source.provider_access_role FROM calendars calendar JOIN calendar_event_sources source ON source.calendar_id = calendar.id WHERE source.event_id = $1",+ "describe": {+ "columns": [+ {+ "ordinal": 0,+ "name": "sync_token",+ "type_info": "Text"+ },+ {+ "ordinal": 1,+ "name": "synced_at",+ "type_info": "Timestamptz"+ },+ {+ "ordinal": 2,+ "name": "materialized_starts_at",+ "type_info": "Timestamptz"+ },+ {+ "ordinal": 3,+ "name": "provider_access_role",+ "type_info": "Text"+ }+ ],+ "parameters": {+ "Left": [+ "Uuid"+ ]+ },+ "nullable": [+ true,+ true,+ true,+ true+ ]+ },+ "hash": "faf4e7eeb01e297390c6d77e3f4e4b2aebd90c7f4c75342ed92bd3dd5a2ffb7b"+}diff --git a/.sqlx/query-fd0d9b58f20c4bfc60af79e891b9ffdd72c072b119822dffc73acb88221fc65a.json b/.sqlx/query-fd0d9b58f20c4bfc60af79e891b9ffdd72c072b119822dffc73acb88221fc65a.jsonnew file mode 100644index 0000000000..cec53fe0f7--- /dev/null+++ b/.sqlx/query-fd0d9b58f20c4bfc60af79e891b9ffdd72c072b119822dffc73acb88221fc65a.json@@ -0,0 +1,22 @@+{+ "db_name": "PostgreSQL",+ "query": "SELECT max(generated_at) AS \"max!\" FROM calendar_event_occurrences WHERE event_id = $1",+ "describe": {+ "columns": [+ {+ "ordinal": 0,+ "name": "max!",+ "type_info": "Timestamptz"+ }+ ],+ "parameters": {+ "Left": [+ "Uuid"+ ]+ },+ "nullable": [+ null+ ]+ },+ "hash": "fd0d9b58f20c4bfc60af79e891b9ffdd72c072b119822dffc73acb88221fc65a"+}diff --git a/.sqlx/query-fd36eb70805edee5f09027ab688337222f62cdba931937ad3a5989a43a3ad47f.json b/.sqlx/query-fd36eb70805edee5f09027ab688337222f62cdba931937ad3a5989a43a3ad47f.jsonnew file mode 100644index 0000000000..8be07d3b6d--- /dev/null+++ b/.sqlx/query-fd36eb70805edee5f09027ab688337222f62cdba931937ad3a5989a43a3ad47f.json@@ -0,0 +1,14 @@+{+ "db_name": "PostgreSQL",+ "query": "UPDATE calendar_change_log SET created_at = now() - interval '40 days' WHERE link_id = $1 AND seq <= 2",+ "describe": {+ "columns": [],+ "parameters": {+ "Left": [+ "Uuid"+ ]+ },+ "nullable": []+ },+ "hash": "fd36eb70805edee5f09027ab688337222f62cdba931937ad3a5989a43a3ad47f"+}diff --git a/.sqlx/query-fd3fb1e2ffd254f9bbfb7ab02584152267a70f0f4eb8b37d3434231c4e003d46.json b/.sqlx/query-fd3fb1e2ffd254f9bbfb7ab02584152267a70f0f4eb8b37d3434231c4e003d46.jsonnew file mode 100644index 0000000000..398b0b8121--- /dev/null+++ b/.sqlx/query-fd3fb1e2ffd254f9bbfb7ab02584152267a70f0f4eb8b37d3434231c4e003d46.json@@ -0,0 +1,14 @@+{+ "db_name": "PostgreSQL",+ "query": "UPDATE calendar_sync_outbox SET published_at = now() WHERE backfill_job_id = $1",+ "describe": {+ "columns": [],+ "parameters": {+ "Left": [+ "Uuid"+ ]+ },+ "nullable": []+ },+ "hash": "fd3fb1e2ffd254f9bbfb7ab02584152267a70f0f4eb8b37d3434231c4e003d46"+}diff --git a/.sqlx/query-fda562d30ca57ca7b5b112f2414f38f809e78207c82ed1fb32fcb01ef7864433.json b/.sqlx/query-fda562d30ca57ca7b5b112f2414f38f809e78207c82ed1fb32fcb01ef7864433.jsonnew file mode 100644index 0000000000..ad01379f13--- /dev/null+++ b/.sqlx/query-fda562d30ca57ca7b5b112f2414f38f809e78207c82ed1fb32fcb01ef7864433.json@@ -0,0 +1,14 @@+{+ "db_name": "PostgreSQL",+ "query": "UPDATE comms_channel_participants SET left_at = now() WHERE channel_id = $1",+ "describe": {+ "columns": [],+ "parameters": {+ "Left": [+ "Uuid"+ ]+ },+ "nullable": []+ },+ "hash": "fda562d30ca57ca7b5b112f2414f38f809e78207c82ed1fb32fcb01ef7864433"+}diff --git a/Cargo.lock b/Cargo.lockindex 761c4dddd5..99492b0ace 100644--- a/Cargo.lock+++ b/Cargo.lock@@ -3536,6 +3536,7 @@ dependencies = ["aws-sdk-sqs","axum","chrono",+ "chrono-tz","futures","macro_authorization","macro_db_migrator",diff --git a/apps/docs/AI/mcp/tools/get-team-availability.mdx b/apps/docs/AI/mcp/tools/get-team-availability.mdxnew file mode 100644index 0000000000..7a980ca7ce--- /dev/null+++ b/apps/docs/AI/mcp/tools/get-team-availability.mdx@@ -0,0 +1,18 @@+---+title: GetTeamAvailability+description: >-+ Check personal busy time for you and your current teammates in a bounded UTC+ time window.+---++# GetTeamAvailability++Check personal busy time for you and your current teammates in a bounded UTC time window. Always includes you, even when userIds selects particular teammates. Omit userIds for the whole team, or use ids from ListTeamMembers for specific people. An empty list checks only you. Returns merged busy intervals without event titles, plus coverage and unknown reasons. Subscribed coworkers' events do not block a person's time unless they attend or included that calendar. Common freeWindows are present only when every requested person's data is complete and current. When freeWindows is absent, report uncertainty and never infer free time from missing busy blocks. Free windows cover the requested range only; working hours are not applied. Prefer a day or a week; the maximum is 370 days within one year past to two years future. This tool grants no Google Calendar access and does not invite, RSVP, or modify events.++## Parameters++| Parameter | Type | Required | Description |+| --- | --- | --- | --- |+| `start` | string | Yes | Inclusive start, RFC 3339 UTC (for example 2026-10-07T09:00:00Z). |+| `end` | string | Yes | Exclusive end, RFC 3339 UTC. Must be later than start. |+| `userIds` | string[] | No | At most 100 Macro user ids from ListTeamMembers. Omit for the whole team; an empty list checks only you. Unknown ids never expand access and suppress common free windows. |diff --git a/apps/docs/AI/mcp/tools/index.mdx b/apps/docs/AI/mcp/tools/index.mdxindex 25050c6a8b..df2afc7998 100644--- a/apps/docs/AI/mcp/tools/index.mdx+++ b/apps/docs/AI/mcp/tools/index.mdx@@ -48,6 +48,7 @@ These pages are generated from Macro's Rust MCP tool registry.- [GetBotWebhooks](/AI/mcp/tools/get-bot-webhooks)- [GetCompany](/AI/mcp/tools/get-company)- [GetEntityProperties](/AI/mcp/tools/get-entity-properties)+- [GetTeamAvailability](/AI/mcp/tools/get-team-availability)- [GetThread](/AI/mcp/tools/get-thread)- [ImportNotionPage](/AI/mcp/tools/import-notion-page)- [IssueBotCredential](/AI/mcp/tools/issue-bot-credential)diff --git a/apps/docs/config/tool-pages.json b/apps/docs/config/tool-pages.jsonindex f9717cf5c1..c6fa1a3481 100644--- a/apps/docs/config/tool-pages.json+++ b/apps/docs/config/tool-pages.json@@ -39,6 +39,7 @@"AI/mcp/tools/get-bot-webhooks","AI/mcp/tools/get-company","AI/mcp/tools/get-entity-properties",+ "AI/mcp/tools/get-team-availability","AI/mcp/tools/get-thread","AI/mcp/tools/import-notion-page","AI/mcp/tools/issue-bot-credential",diff --git a/apps/docs/docs.json b/apps/docs/docs.jsonindex 88bf050c42..2c35aa6780 100644--- a/apps/docs/docs.json+++ b/apps/docs/docs.json@@ -110,6 +110,7 @@"AI/mcp/tools/get-bot-webhooks","AI/mcp/tools/get-company","AI/mcp/tools/get-entity-properties",+ "AI/mcp/tools/get-team-availability","AI/mcp/tools/get-thread","AI/mcp/tools/import-notion-page","AI/mcp/tools/issue-bot-credential",diff --git a/apps/web/src/features/block-agent/state/tool-approval-wording.ts b/apps/web/src/features/block-agent/state/tool-approval-wording.tsindex dbd764412f..551039696c 100644--- a/apps/web/src/features/block-agent/state/tool-approval-wording.ts+++ b/apps/web/src/features/block-agent/state/tool-approval-wording.ts@@ -53,6 +53,7 @@ const MACRO_TOOLS: Record<MacroToolName, Wording | null> = {GetBotWebhooks: (whose) => `read ${whose} bot webhooks`,GetCompany: (whose) => `look up companies in ${whose} workspace`,GetEntityProperties: (whose) => `read properties in ${whose} workspace`,+ GetTeamAvailability: (whose) => `check availability for ${whose} team`,GetThread: (whose) => `read ${whose} email`,ImportNotionPage: (whose) => `import a Notion page into ${whose} workspace`,IssueBotCredential: (whose) => `issue credentials for ${whose} bots`,diff --git a/apps/web/src/features/calendar-team/calendar-team.tsx b/apps/web/src/features/calendar-team/calendar-team.tsxnew file mode 100644index 0000000000..8a1639823e--- /dev/null+++ b/apps/web/src/features/calendar-team/calendar-team.tsx@@ -0,0 +1,262 @@+import { CollapsibleSection } from '@app/components/view-shell';+import { toast } from '@core/component/Toast/Toast';+import { useUserId } from '@core/context/user';+import { getDisplayName, tryMacroId } from '@core/user';+import type { CalendarOccurrenceQueryRange } from '@queries/calendar/occurrences';+import {+ useAvailabilityCalendarsQuery,+ useCalendarTeamIdentityQuery,+ useSetAvailabilityCalendarMutation,+ useSetTeamCalendarSharingMutation,+ useTeamCalendarMembersQuery,+ useTeamCalendarQuery,+ useTeamCalendarSharingQuery,+} from '@queries/calendar/team';+import type { CalendarTeamIdentity } from '@queries/calendar/team-keys';+import {+ type Accessor,+ createMemo,+ createSignal,+ Show,+ Suspense,+} from 'solid-js';+import { useCalendarView } from '../calendar/components/CalendarViewContext';+import { useCalendarTeamSharingFlag } from '../calendar/hooks/use-calendar-ui-flag';+import { isCalendarRangeSupported } from '../calendar/utils/calendar-supported-range';+import { useCalendarPreferences } from '../calendar/utils/preferences';+import { TeamCalendarControls } from './components/team-calendar-controls';+import { TeamSharingSettings } from './components/team-sharing-settings';+import {+ type CalendarTeamMemberDisplay,+ teamCalendarColor,+ teamCalendarSourceId,+} from './core/model';+import { createTeamCalendarState } from './primitives/create-team-calendar-state';+import { mapTeamCalendarItem } from './queries/map';++const teammateName = (id: string) =>+ getDisplayName(tryMacroId(id)) || 'Teammate';++function useCalendarTeamIdentity(enabled: Accessor<boolean>) {+ const userId = useUserId();+ const query = useCalendarTeamIdentityQuery(userId, enabled);+ const identity = (): CalendarTeamIdentity | undefined => {+ if (!enabled() || !query.isSuccess || query.isPaused) return undefined;+ const team = query.data;+ const user = userId();+ if (!user || !team?.members.some((member) => member.user_id === user))+ return undefined;+ return { userId: user, teamId: team.team.id };+ };+ return { identity, query };+}++/** Production wiring for the isolated, read-only team overlay. */+export function useTeamCalendarOverlay(options: {+ range: Accessor<CalendarOccurrenceQueryRange | undefined>;+ enabled: Accessor<boolean>;+ isSourceVisible: (sourceId: string) => boolean;+}) {+ const flag = useCalendarTeamSharingFlag();+ const enabled = () =>+ flag() &&+ options.enabled() &&+ options.range() !== undefined &&+ isCalendarRangeSupported(options.range()!);+ const { identity, query: identityQuery } = useCalendarTeamIdentity(enabled);+ const query = useTeamCalendarQuery(identity, options.range, enabled);+ const state = createTeamCalendarState(+ {+ data: () =>+ identity() && query.isSuccess ? query.data.items : undefined,+ isPending: () =>+ identityQuery.isPending ||+ (identity() !== undefined && query.isPending),+ isError: () => identityQuery.isError || query.isError,+ isPaused: () => identityQuery.isPaused || query.isPaused,+ },+ enabled+ );+ const events = createMemo(() =>+ state+ .items()+ .map((item) => mapTeamCalendarItem(item, teammateName(item.ownerId)))+ .filter((event) => options.isSourceVisible(event.calendar.id))+ );+ return {+ events,+ isLoading: state.isLoading,+ isError: state.isError,+ retry: () => {+ void identityQuery.refetch();+ void query.refetch();+ },+ };+}++function TeamCalendarControlsConnected(props: {+ enabled: boolean;+ onEnabledChange: (enabled: boolean) => void;+ isVisible: (sourceId: string) => boolean;+ onVisibilityChange: (sourceId: string, visible: boolean) => void;+}) {+ const flag = useCalendarTeamSharingFlag();+ const { identity, query: identityQuery } = useCalendarTeamIdentity(flag);+ const query = useTeamCalendarMembersQuery(identity);+ const members = createMemo<CalendarTeamMemberDisplay[]>(() =>+ identity() && query.isSuccess && !query.isPaused+ ? query.data.map((member) => ({+ ...member,+ name: teammateName(member.userId),+ color: teamCalendarColor(member.userId),+ sourceId: teamCalendarSourceId(member.userId),+ }))+ : []+ );+ return (+ <Show+ when={+ identity() ||+ identityQuery.isPending ||+ identityQuery.isError ||+ identityQuery.isPaused+ }+ >+ <TeamCalendarControls+ {...props}+ members={members()}+ loading={+ identityQuery.isPending ||+ (identity() !== undefined && query.isPending)+ }+ error={+ query.isError ||+ identityQuery.isError ||+ query.isPaused ||+ identityQuery.isPaused+ }+ onRetry={() => {+ void identityQuery.refetch();+ void query.refetch();+ }}+ />+ </Show>+ );+}++export function CalendarTeamSidebar() {+ const enabled = useCalendarTeamSharingFlag();+ const calendar = useCalendarView();+ const [open, setOpen] = createSignal(true);+ return (+ <Show when={enabled()}>+ <Suspense+ fallback={+ <p class="px-2 text-xs text-ink-muted">Loading team calendars…</p>+ }+ >+ <CollapsibleSection.Root open={open()} onOpenChange={setOpen}>+ <CollapsibleSection.Trigger>+ <span>Team calendars</span>+ <CollapsibleSection.Indicator />+ </CollapsibleSection.Trigger>+ <CollapsibleSection.Content>+ <TeamCalendarControlsConnected+ enabled={calendar.displaySettings.showTeamCalendars}+ onEnabledChange={calendar.setShowTeamCalendars}+ isVisible={calendar.isSourceVisible}+ onVisibilityChange={calendar.setSourceVisibility}+ />+ </CollapsibleSection.Content>+ </CollapsibleSection.Root>+ </Suspense>+ </Show>+ );+}++function CalendarTeamSettingsContent() {+ const flag = useCalendarTeamSharingFlag();+ const { identity, query: identityQuery } = useCalendarTeamIdentity(flag);+ const sharing = useTeamCalendarSharingQuery(identity);+ const calendars = useAvailabilityCalendarsQuery(identity);+ const setSharing = useSetTeamCalendarSharingMutation();+ const setCalendar = useSetAvailabilityCalendarMutation();+ const [preferences, setPreferences] = useCalendarPreferences();+ return (+ <>+ <TeamSharingSettings+ hasTeam={identity() !== undefined}+ teamLoading={identityQuery.isPending}+ sharing={+ sharing.isSuccess && !sharing.isPaused+ ? sharing.data.sharing+ : undefined+ }+ saving={setSharing.isPending}+ error={+ sharing.isError ||+ identityQuery.isError ||+ sharing.isPaused ||+ identityQuery.isPaused+ }+ onChange={(value) =>+ setSharing.mutate(value, {+ onError: () => toast.failure('Could not update calendar sharing'),+ })+ }+ onRetry={() => {+ void identityQuery.refetch();+ void sharing.refetch();+ }}+ calendars={+ calendars.isSuccess && !calendars.isPaused+ ? calendars.data.calendars+ : []+ }+ calendarsLoading={identity() !== undefined && calendars.isPending}+ calendarsError={calendars.isError || calendars.isPaused}+ calendarSaving={setCalendar.isPending}+ onCalendarChange={(calendarId, contributesToAvailability) =>+ setCalendar.mutate(+ { calendarId, contributesToAvailability },+ {+ onError: () =>+ toast.failure('Could not update availability calendar'),+ }+ )+ }+ />+ <TeamCalendarControlsConnected+ enabled={preferences.showTeamCalendars}+ onEnabledChange={(visible) =>+ setPreferences('showTeamCalendars', visible)+ }+ isVisible={(id) => !preferences.hiddenSourceIds.includes(id)}+ onVisibilityChange={(id, visible) =>+ setPreferences('hiddenSourceIds', (ids) =>+ visible+ ? ids.filter((source) => source !== id)+ : [...new Set([...ids, id])]+ )+ }+ />+ </>+ );+}++export function CalendarTeamSettings() {+ const enabled = useCalendarTeamSharingFlag();+ return (+ <Show when={enabled()}>+ <Suspense+ fallback={+ <p class="px-6 text-sm text-ink-muted">+ Loading team calendar settings…+ </p>+ }+ >+ <CalendarTeamSettingsContent />+ </Suspense>+ </Show>+ );+}diff --git a/apps/web/src/features/calendar-team/components/team-calendar-controls.tsx b/apps/web/src/features/calendar-team/components/team-calendar-controls.tsxnew file mode 100644index 0000000000..76b99d0f26--- /dev/null+++ b/apps/web/src/features/calendar-team/components/team-calendar-controls.tsx@@ -0,0 +1,78 @@+import { Checkbox, ToggleSwitch } from '@ui';+import { For, Show } from 'solid-js';+import {+ type CalendarTeamMemberDisplay,+ canShowTeamMember,+ teamMemberStatus,+} from '../core/model';++export function TeamCalendarControls(props: {+ enabled: boolean;+ onEnabledChange: (enabled: boolean) => void;+ members: CalendarTeamMemberDisplay[];+ loading: boolean;+ error: boolean;+ onRetry: () => void;+ isVisible: (sourceId: string) => boolean;+ onVisibilityChange: (sourceId: string, visible: boolean) => void;+}) {+ return (+ <div class="flex flex-col gap-2">+ <div class="flex items-center justify-between gap-3 px-2 text-xs text-ink">+ Show team calendars+ <ToggleSwitch+ checked={props.enabled}+ onChange={props.onEnabledChange}+ label="Show team calendars"+ labelClass="sr-only"+ />+ </div>+ <p class="px-2 text-xs text-ink-muted">+ Shared event details can include calendars a teammate follows. Those+ events do not necessarily mean they are busy.+ </p>+ <Show when={props.loading}>+ <p role="status" class="px-2 text-xs text-ink-muted">+ Loading team calendars…+ </p>+ </Show>+ <Show when={props.error}>+ <div role="status" class="px-2 text-xs text-ink-muted">+ Team calendars unavailable.{' '}+ <button type="button" class="underline" onClick={props.onRetry}>+ Retry+ </button>+ </div>+ </Show>+ <For each={props.members}>+ {(member) => (+ <Checkbox+ checked={+ canShowTeamMember(member) && props.isVisible(member.sourceId)+ }+ disabled={!props.enabled || !canShowTeamMember(member)}+ onChange={(visible) =>+ props.onVisibilityChange(member.sourceId, visible)+ }+ class="flex w-full items-center gap-2 rounded-lg px-2 py-1.5 text-xs text-ink hover:bg-hover data-disabled:opacity-60"+ >+ <Checkbox.Control />+ <Checkbox.Label class="flex min-w-0 flex-1 items-center gap-2">+ <span+ aria-hidden="true"+ class="size-2.5 shrink-0 rounded-sm"+ style={{ 'background-color': member.color }}+ />+ <span class="min-w-0 flex-1 truncate" title={member.name}>+ {member.name}+ </span>+ <span class="shrink-0 text-ink-muted">+ {teamMemberStatus(member)}+ </span>+ </Checkbox.Label>+ </Checkbox>+ )}+ </For>+ </div>+ );+}diff --git a/apps/web/src/features/calendar-team/components/team-event-details.tsx b/apps/web/src/features/calendar-team/components/team-event-details.tsxnew file mode 100644index 0000000000..6b58aebec0--- /dev/null+++ b/apps/web/src/features/calendar-team/components/team-event-details.tsx@@ -0,0 +1,113 @@+import { createMemo, For, Show } from 'solid-js';+import type { CalendarEvent, CalendarTimeFormat } from '../../calendar/types';+import { parseLocalDate } from '../../calendar/utils/calendar-date';+import { sanitizeCalendarDescription } from '../../calendar/utils/calendar-description';+import { safeConferenceUrl } from '../../calendar/utils/conference-link';++/** A separate content surface deliberately exposes no event mutation or mention actions. */+export function TeamEventDetails(props: {+ event: CalendarEvent;+ timeFormat: CalendarTimeFormat;+ onOpenLink: (url: string) => void;+}) {+ const description = createMemo(() =>+ sanitizeCalendarDescription(props.event.description ?? '')+ );+ const conference = () => safeConferenceUrl(props.event.conferenceUrl);+ const schedule = () => {+ const event = props.event;+ const start = event.allDay+ ? parseLocalDate(event.start)+ : new Date(event.start);+ const endDate = event.allDay+ ? parseLocalDate(event.end)+ : new Date(event.end);+ if (+ !start ||+ !endDate ||+ Number.isNaN(start.getTime()) ||+ Number.isNaN(endDate.getTime())+ )+ return 'Time unavailable';+ const end = event.allDay ? new Date(endDate.getTime() - 1) : endDate;+ const format = new Intl.DateTimeFormat(undefined, {+ dateStyle: 'medium',+ ...(event.allDay+ ? {}+ : {+ timeStyle: 'short' as const,+ hour12: props.timeFormat === '12-hour',+ }),+ });+ return `${format.format(start)} – ${format.format(end)}${event.allDay ? ' · All day' : ''}`;+ };+ return (+ <section+ aria-label="Shared event details"+ class="flex flex-col gap-3 p-2 text-sm text-ink"+ >+ <h2 class="select-text text-lg font-semibold">{props.event.title}</h2>+ <p class="select-text text-xs text-ink-muted">{schedule()}</p>+ <p class="text-xs text-ink-muted">Shared in Macro · Read only</p>+ <Show+ when={+ props.event.teamProjection?.contributesToAvailability !== undefined+ }+ >+ <p class="text-xs text-ink-muted">+ {props.event.teamProjection?.contributesToAvailability+ ? "Counts toward this teammate's busy time."+ : 'From a calendar this teammate can access. Does not count toward their busy time.'}+ </p>+ </Show>+ <Show when={props.event.location}>+ <p class="select-text">{props.event.location}</p>+ </Show>+ <Show when={conference()}>+ {(url) => (+ <button+ type="button"+ class="self-start text-accent underline"+ onClick={() => props.onOpenLink(url())}+ >+ Join meeting+ </button>+ )}+ </Show>+ <Show when={description()}>+ {(html) => (+ <div+ class="select-text text-ink-muted [&_a]:text-accent [&_a]:underline"+ innerHTML={html()}+ onClick={(event) => {+ const anchor = (event.target as Element | null)?.closest(+ 'a[href]'+ );+ if (!(anchor instanceof HTMLAnchorElement)) return;+ event.preventDefault();+ props.onOpenLink(anchor.href);+ }}+ />+ )}+ </Show>+ <Show when={props.event.organizerName || props.event.organizerEmail}>+ <p class="select-text text-xs text-ink-muted">+ Organizer: {props.event.organizerName || props.event.organizerEmail}+ </p>+ </Show>+ <Show when={props.event.attendees.length > 0}>+ <div class="flex flex-col gap-1 border-t border-edge-muted pt-3 text-xs">+ <p class="text-ink-muted">Guests</p>+ <For each={props.event.attendees}>+ {(attendee) => (+ <p class="select-text">+ {attendee.displayName || attendee.email}+ {attendee.isSelf ? ' (you)' : ''}+ </p>+ )}+ </For>+ </div>+ </Show>+ </section>+ );+}diff --git a/apps/web/src/features/calendar-team/components/team-sharing-settings.tsx b/apps/web/src/features/calendar-team/components/team-sharing-settings.tsxnew file mode 100644index 0000000000..c948c78a34--- /dev/null+++ b/apps/web/src/features/calendar-team/components/team-sharing-settings.tsx@@ -0,0 +1,158 @@+import { ToggleSwitch } from '@ui';+import { For, Show } from 'solid-js';+import {+ ChoiceRow,+ SettingsCard,+ SettingsRow,+ SettingsSection,+} from '../../settings/primitives';+import type { CalendarSharing } from '../core/model';++const choices: {+ value: CalendarSharing;+ title: string;+ description: string;+}[] = [+ {+ value: 'busy_only',+ title: 'Busy blocks',+ description:+ 'Share time blocks from all synced calendars without event details. Calendars you follow are distinguished from your own availability. This is the default.',+ },+ {+ value: 'all',+ title: 'Event details',+ description:+ 'Share details from every calendar synced to Macro, including subscribed or delegated calendars, birthdays and holidays. Calendars unchecked in Google Calendar are included if synced. Private and confidential events share only busy blocks when they block time. This does not change Google Calendar permissions.',+ },+ {+ value: 'none',+ title: 'Nothing',+ description:+ 'Hide your calendar and availability from teammates in Macro, including team out of office.',+ },+];++export interface AvailabilityCalendarDisplay {+ calendarId: string;+ name: string;+ contributesToAvailability: boolean;+ isPrimary: boolean;+}++export function TeamSharingSettings(props: {+ hasTeam: boolean;+ teamLoading: boolean;+ sharing: CalendarSharing | undefined;+ saving: boolean;+ error: boolean;+ onChange: (sharing: CalendarSharing) => void;+ onRetry: () => void;+ calendars: AvailabilityCalendarDisplay[];+ calendarsLoading: boolean;+ calendarsError: boolean;+ calendarSaving: boolean;+ onCalendarChange: (+ calendarId: string,+ contributesToAvailability: boolean+ ) => void;+}) {+ return (+ <>+ <SettingsSection+ title="Team sharing"+ description="Choose what teammates can read in Macro. Hiding a calendar in your Macro view does not change sharing. Sharing does not invite them to events or give them Google Calendar access."+ >+ <SettingsCard>+ <Show+ when={props.hasTeam}+ fallback={+ <SettingsRow+ label={+ props.teamLoading+ ? 'Loading your team…'+ : props.error+ ? 'Team sharing unavailable'+ : 'Join a team to share your calendar'+ }+ >+ <Show when={props.error}>+ <button+ type="button"+ class="text-xs underline"+ onClick={props.onRetry}+ >+ Retry+ </button>+ </Show>+ </SettingsRow>+ }+ >+ <div class="flex flex-col gap-2 px-6 py-4">+ <For each={choices}>+ {(choice) => (+ <ChoiceRow+ name="calendar-team-sharing"+ value={choice.value}+ title={choice.title}+ description={choice.description}+ checked={props.sharing === choice.value}+ disabled={props.sharing === undefined || props.saving}+ onChange={() => props.onChange(choice.value)}+ />+ )}+ </For>+ <Show when={props.error}>+ <p role="status" class="text-xs text-failure">+ Could not load your sharing setting.{' '}+ <button+ type="button"+ class="underline"+ onClick={props.onRetry}+ >+ Retry+ </button>+ </p>+ </Show>+ </div>+ </Show>+ </SettingsCard>+ </SettingsSection>+ <Show when={props.hasTeam}>+ <SettingsSection+ title="Calendars that count as busy"+ description="By default, your primary calendars and meetings you attend count toward your availability. Following someone else's calendar does not make their meetings block your time. Choose any additional calendars that represent your schedule."+ >+ <SettingsCard>+ <Show when={props.calendarsLoading}>+ <SettingsRow label="Loading calendars…" />+ </Show>+ <Show when={props.calendarsError}>+ <SettingsRow label="Could not load availability calendars" />+ </Show>+ <For each={props.calendars}>+ {(calendar) => (+ <SettingsRow+ label={calendar.name}+ description={+ calendar.isPrimary ? 'Primary calendar' : undefined+ }+ >+ <ToggleSwitch+ checked={calendar.contributesToAvailability}+ disabled={props.calendarSaving}+ onChange={(included) =>+ props.onCalendarChange(calendar.calendarId, included)+ }+ label={`Count ${calendar.name} toward my availability`}+ labelClass="sr-only"+ />+ </SettingsRow>+ )}+ </For>+ </SettingsCard>+ </SettingsSection>+ </Show>+ </>+ );+}diff --git a/apps/web/src/features/calendar-team/core/merge.test.ts b/apps/web/src/features/calendar-team/core/merge.test.tsnew file mode 100644index 0000000000..f0399de4b8--- /dev/null+++ b/apps/web/src/features/calendar-team/core/merge.test.ts@@ -0,0 +1,28 @@+import { describe, expect, it } from 'vitest';+import { mergeCalendarOverlays } from './merge';++describe('calendar overlay composition', () => {+ it('keeps a directly accessible occurrence authoritative', () => {+ const own = { id: 'meeting', calendar: { id: 'own' }, isReadOnly: false };+ const team = { id: 'meeting', calendar: { id: 'team' }, isReadOnly: true };+ expect(mergeCalendarOverlays([own], [team], [team])).toEqual([own]);+ });++ it('replaces a shown teammate OOO source with their shared source only', () => {+ const aliceOoo = { id: 'alice-ooo', calendar: { id: 'team-ooo:alice' } };+ const bobOoo = { id: 'bob-ooo', calendar: { id: 'team-ooo:bob' } };+ const alice = {+ id: 'alice-team',+ calendar: { id: 'team-calendar:alice' },+ teamProjection: { ownerId: 'alice' },+ };+ expect(mergeCalendarOverlays([], [aliceOoo, bobOoo], [alice])).toEqual([+ bobOoo,+ alice,+ ]);+ expect(mergeCalendarOverlays([], [aliceOoo, bobOoo], [])).toEqual([+ aliceOoo,+ bobOoo,+ ]);+ });+});diff --git a/apps/web/src/features/calendar-team/core/merge.ts b/apps/web/src/features/calendar-team/core/merge.tsnew file mode 100644index 0000000000..e8051bc1eb--- /dev/null+++ b/apps/web/src/features/calendar-team/core/merge.ts@@ -0,0 +1,28 @@+interface DisplayEvent {+ id: string;+ calendar: { id: string };+ teamProjection?: { ownerId: string };+}++/** Keep direct-copy interactions authoritative; the team source supersedes its OOO overlay. */+export function mergeCalendarOverlays<T extends DisplayEvent>(+ own: T[],+ outOfOffice: T[],+ shared: T[]+): T[] {+ const ownIds = new Set(own.map((event) => event.id));+ const sharedOwners = new Set(+ shared.flatMap((event) =>+ event.teamProjection ? [event.teamProjection.ownerId] : []+ )+ );+ return [+ ...own,+ ...outOfOffice.filter(+ (event) =>+ !ownIds.has(event.id) &&+ !sharedOwners.has(event.calendar.id.replace(/^team-ooo:/, ''))+ ),+ ...shared.filter((event) => !ownIds.has(event.id)),+ ];+}diff --git a/apps/web/src/features/calendar-team/core/model.ts b/apps/web/src/features/calendar-team/core/model.tsnew file mode 100644index 0000000000..7f7402fa33--- /dev/null+++ b/apps/web/src/features/calendar-team/core/model.ts@@ -0,0 +1,49 @@+/** Team sharing is a Macro read permission, separate from Google permissions. */+export type CalendarSharing = 'busy_only' | 'all' | 'none';++export interface CalendarTeamMember {+ userId: string;+ sharing: CalendarSharing;+ coverage: 'ready' | 'unavailable' | 'hidden';+}++export interface CalendarTeamMemberDisplay extends CalendarTeamMember {+ name: string;+ color: string;+ sourceId: string;+}++export const TEAM_CALENDAR_SOURCE = 'team-calendar';++export function teamCalendarSourceId(ownerId: string) {+ return `${TEAM_CALENDAR_SOURCE}:${ownerId}`;+}++/** The source and owner scope prevent collisions with a directly accessible copy. */+export function teamCalendarRenderId(ownerId: string, projectionId: string) {+ return JSON.stringify([TEAM_CALENDAR_SOURCE, ownerId, projectionId]);+}++export function teamCalendarColor(ownerId: string) {+ const colors = [+ 'var(--color-accent)',+ 'var(--color-ink-muted)',+ 'var(--color-success)',+ 'var(--color-alert)',+ ];+ let hash = 0;+ for (const character of ownerId)+ hash = (hash * 31 + character.charCodeAt(0)) >>> 0;+ return colors[hash % colors.length];+}++export function teamMemberStatus(member: CalendarTeamMember): string {+ if (member.coverage === 'hidden' || member.sharing === 'none')+ return 'Not shared';+ if (member.coverage === 'unavailable') return 'Calendar unavailable';+ return member.sharing === 'all' ? 'Event details' : 'Busy blocks';+}++export function canShowTeamMember(member: CalendarTeamMember) {+ return member.coverage === 'ready' && member.sharing !== 'none';+}diff --git a/apps/web/src/features/calendar-team/primitives/create-team-calendar-state.test.ts b/apps/web/src/features/calendar-team/primitives/create-team-calendar-state.test.tsnew file mode 100644index 0000000000..6428be8216--- /dev/null+++ b/apps/web/src/features/calendar-team/primitives/create-team-calendar-state.test.ts@@ -0,0 +1,48 @@+import { createRoot, createSignal } from 'solid-js';+import { describe, expect, it } from 'vitest';+import { createTeamCalendarState } from './create-team-calendar-state';++describe('team calendar state', () => {+ it('drops stale details on a denied refresh and on a disabled identity', () => {+ createRoot((dispose) => {+ const [error, setError] = createSignal(false);+ const [enabled, setEnabled] = createSignal(true);+ const state = createTeamCalendarState(+ {+ data: () => ['Previously authorized title'],+ isPending: () => false,+ isError: error,+ },+ enabled+ );+ expect(state.items()).toEqual(['Previously authorized title']);+ setError(true);+ expect(state.items()).toEqual([]);+ expect(state.isError()).toBe(true);+ setEnabled(false);+ setError(false);+ expect(state.items()).toEqual([]);+ dispose();+ });+ });+});++it('hides retained details when an offline refresh is paused', () => {+ createRoot((dispose) => {+ const [paused, setPaused] = createSignal(false);+ const state = createTeamCalendarState(+ {+ data: () => ['Previously authorized title'],+ isPending: () => false,+ isError: () => false,+ isPaused: paused,+ },+ () => true+ );+ expect(state.items()).toHaveLength(1);+ setPaused(true);+ expect(state.items()).toEqual([]);+ expect(state.isError()).toBe(true);+ dispose();+ });+});diff --git a/apps/web/src/features/calendar-team/primitives/create-team-calendar-state.ts b/apps/web/src/features/calendar-team/primitives/create-team-calendar-state.tsnew file mode 100644index 0000000000..0a2bf7a15e--- /dev/null+++ b/apps/web/src/features/calendar-team/primitives/create-team-calendar-state.ts@@ -0,0 +1,26 @@+import { type Accessor, createMemo } from 'solid-js';++export interface TeamCalendarSource<T> {+ data: Accessor<T[] | undefined>;+ isPending: Accessor<boolean>;+ isError: Accessor<boolean>;+ isPaused?: Accessor<boolean>;+}++/** Permission errors and scope changes must hide old payloads, even during failed refreshes. */+export function createTeamCalendarState<T>(+ source: TeamCalendarSource<T>,+ enabled: Accessor<boolean>+) {+ const items = createMemo(() =>+ enabled() && !source.isError() && !source.isPaused?.()+ ? (source.data() ?? [])+ : []+ );+ return {+ items,+ isLoading: () => enabled() && source.isPending() && !source.isPaused?.(),+ isError: () =>+ enabled() && (source.isError() || Boolean(source.isPaused?.())),+ };+}diff --git a/apps/web/src/features/calendar-team/queries/map.test.ts b/apps/web/src/features/calendar-team/queries/map.test.tsnew file mode 100644index 0000000000..330d092e52--- /dev/null+++ b/apps/web/src/features/calendar-team/queries/map.test.ts@@ -0,0 +1,114 @@+import type { TeamCalendarItem } from '@service-storage/generated/schemas/teamCalendarItem';+import { describe, expect, it } from 'vitest';+import { canEditCalendarEventTime } from '../../calendar/utils/event-interaction';+import { mergeCalendarOverlays } from '../core/merge';+import { mapTeamCalendarItem } from './map';++const busy = {+ id: 'opaque',+ ownerId: 'alice',+ kind: 'busy',+ contributesToAvailability: true,+ time: {+ kind: 'timed',+ startsAt: '2026-10-07T12:00:00Z',+ endsAt: '2026-10-07T13:00:00Z',+ timeZone: null,+ },+} satisfies TeamCalendarItem;++describe('team calendar grid projection', () => {+ it('keeps redacted blocks separate from canonical event identities and provider actions', () => {+ const event = mapTeamCalendarItem(busy, 'Alice');+ expect(event.id).toBe(JSON.stringify(['team-calendar', 'alice', 'opaque']));+ expect(event.isReadOnly).toBe(true);+ expect(event.calendarId).toBeUndefined();+ expect(event.title).toBe('Alice: Busy');+ expect(event.attendees).toEqual([]);+ expect(event.description).toBeUndefined();+ expect(event.conferenceUrl).toBeUndefined();+ expect(event.eventType).toBeUndefined();+ expect(canEditCalendarEventTime({ ...event, isReadOnly: false })).toBe(+ false+ );+ });++ it('does not describe a followed calendar as the sharer being busy', () => {+ const event = mapTeamCalendarItem(+ { ...busy, contributesToAvailability: false },+ 'Alice'+ );+ expect(event.title).toBe('Alice: Shared calendar block');+ expect(event.teamProjection?.contributesToAvailability).toBe(false);+ });++ it('does not let another sharer overwrite the first sharer', () => {+ expect(mapTeamCalendarItem(busy, 'Alice').id).not.toBe(+ mapTeamCalendarItem({ ...busy, ownerId: 'bob' }, 'Bob').id+ );+ });++ it('preserves source-specific masking and busy status when copies share a time', () => {+ const personal = mapTeamCalendarItem(+ { ...busy, id: 'opaque-personal-source' },+ 'Alice'+ );+ const followed = mapTeamCalendarItem(+ {+ ...busy,+ id: 'opaque-followed-source',+ kind: 'details',+ contributesToAvailability: false,+ details: {+ title: 'Shared calendar meeting',+ description: 'Visible on the followed source',+ location: null,+ conferenceUrl: null,+ organizerEmail: null,+ organizerName: null,+ attendees: [],+ calendarName: 'Followed calendar',+ },+ },+ 'Alice'+ );+ const own = {+ ...personal,+ id: 'direct-copy',+ eventId: 'canonical-event',+ teamProjection: undefined,+ isReadOnly: false,+ };++ const events = mergeCalendarOverlays([own], [], [personal, followed]);++ expect(events).toEqual([own, personal, followed]);+ expect(new Set(events.map((event) => event.id)).size).toBe(3);+ expect(personal.start).toBe(followed.start);+ expect(personal.end).toBe(followed.end);+ expect(personal.title).toBe('Alice: Busy');+ expect(personal.description).toBeUndefined();+ expect(personal.teamProjection?.contributesToAvailability).toBe(true);+ expect(followed.title).toBe('Alice: Shared calendar meeting');+ expect(followed.teamProjection?.contributesToAvailability).toBe(false);+ expect(events[0].isReadOnly).toBe(false);+ expect(canEditCalendarEventTime(personal)).toBe(false);+ expect(canEditCalendarEventTime(followed)).toBe(false);+ });++ it('ignores any accidental detail fields on the busy variant', () => {+ const withUnexpectedDetails = {+ ...busy,+ details: {+ title: 'Secret',+ attendees: [],+ description: 'Hidden body',+ conferenceUrl: 'https://example.com',+ },+ };+ const event = mapTeamCalendarItem(withUnexpectedDetails, 'Alice');+ expect(event.title).toBe('Alice: Busy');+ expect(event.description).toBeUndefined();+ expect(event.conferenceUrl).toBeUndefined();+ });+});diff --git a/apps/web/src/features/calendar-team/queries/map.ts b/apps/web/src/features/calendar-team/queries/map.tsnew file mode 100644index 0000000000..a2def4ac39--- /dev/null+++ b/apps/web/src/features/calendar-team/queries/map.ts@@ -0,0 +1,52 @@+import type { TeamCalendarItem } from '@service-storage/generated/schemas/teamCalendarItem';+import type { CalendarEvent } from '../../calendar/types';+import {+ teamCalendarColor,+ teamCalendarRenderId,+ teamCalendarSourceId,+} from '../core/model';++/** Only the server-authorized DTO enters this adapter; never normalize it as an own event. */+export function mapTeamCalendarItem(+ item: TeamCalendarItem,+ ownerName: string+): CalendarEvent {+ const time = item.time;+ const details = item.kind === 'details' ? item.details : undefined;+ const calendar = {+ id: teamCalendarSourceId(item.ownerId),+ name: ownerName,+ color: teamCalendarColor(item.ownerId),+ };+ const renderId = teamCalendarRenderId(item.ownerId, item.id);+ return {+ id: renderId,+ // These opaque placeholders satisfy the grid contract; teamProjection+ // prevents every canonical-event action and navigation path from using them.+ eventId: renderId,+ occurrenceKey: item.id,+ teamProjection: {+ ownerId: item.ownerId,+ kind: item.kind,+ contributesToAvailability: item.contributesToAvailability,+ },+ ...(time.kind === 'timed'+ ? { allDay: false, start: time.startsAt, end: time.endsAt }+ : { allDay: true, start: time.startDate, end: time.endDate }),+ timeZone: time.kind === 'timed' ? (time.timeZone ?? undefined) : undefined,+ isCancelled: false,+ isReadOnly: true,+ // The endpoint recomputes these flags for the requesting viewer.+ attendees: details?.attendees ?? [],+ recurrenceLines: [],+ sourceCalendarIds: [calendar.id],+ calendar,+ visibleCalendars: [calendar],+ title: `${ownerName}: ${details?.title ?? (item.contributesToAvailability ? 'Busy' : 'Shared calendar block')}`,+ description: details?.description ?? undefined,+ location: details?.location ?? undefined,+ conferenceUrl: details?.conferenceUrl ?? undefined,+ organizerEmail: details?.organizerEmail ?? undefined,+ organizerName: details?.organizerName ?? undefined,+ };+}diff --git a/apps/web/src/features/calendar-view/components/CalendarSidebar.tsx b/apps/web/src/features/calendar-view/components/CalendarSidebar.tsxindex 1e177d5577..fc42765e61 100644--- a/apps/web/src/features/calendar-view/components/CalendarSidebar.tsx+++ b/apps/web/src/features/calendar-view/components/CalendarSidebar.tsx@@ -14,6 +14,7 @@ import {useHasTeammates,useUpcomingTeamOoo,} from '@app/features/calendar/hooks/use-team-ooo';+import { CalendarTeamSidebar } from '@app/features/calendar-team/calendar-team';import { ShowFeatureFlag } from '@app/lib/analytics/posthog';import { UserIcon } from '@core/component/UserIcon';import { enableCalendarTeamOoo } from '@core/constant/featureFlags';@@ -174,7 +175,7 @@ function TeamOooUpcomingList() {</Match><Match when={windows().length === 0}><span class="px-2 py-1 text-xs text-ink-muted">- No time off in the next 90 days+ No shared time off in the next 90 days</span></Match><Match when={windows().length > 0}>@@ -317,6 +318,7 @@ export function CalendarSidebar() {<CalendarMiniCalendar /><UpcomingEventsSection /><CalendarSourcesSection />+ <CalendarTeamSidebar /><ShowFeatureFlag flag={enableCalendarTeamOoo}><CalendarTeamOooSection /></ShowFeatureFlag>diff --git a/apps/web/src/features/calendar-view/components/Page.tsx b/apps/web/src/features/calendar-view/components/Page.tsxindex ca2df1be16..21c5c651f2 100644--- a/apps/web/src/features/calendar-view/components/Page.tsx+++ b/apps/web/src/features/calendar-view/components/Page.tsx@@ -29,6 +29,8 @@ import {scrollEventChipIntoView,timeGridScroller,} from '@app/features/calendar/utils/time-grid-scroller';+import { useTeamCalendarOverlay } from '@app/features/calendar-team/calendar-team';+import { mergeCalendarOverlays } from '@app/features/calendar-team/core/merge';import { useOpenEventComposer } from '@app/features/calendar-view/components/use-open-event-composer';import { useQuickCallsFlag } from '@app/features/meetings/use-quick-calls-flag';import { toast } from '@core/component/Toast/Toast';@@ -235,14 +237,24 @@ export function Page(props: {isSourceVisible: isRenderedSourceVisible,refetchOnWindowFocus: isActive,});- const visibleEvents = createMemo(() => [- ...data.visibleEvents(),- ...teamOoo.visibleEvents(),- ]);- const eventsById = createMemo(() =>- teamOoo.eventsById().size === 0- ? data.eventsById()- : new Map([...data.eventsById(), ...teamOoo.eventsById()])+ const teamCalendar = useTeamCalendarOverlay({+ range,+ enabled: () => calendarView.displaySettings.showTeamCalendars,+ // Hide sensitive shared payloads immediately, before the deferred grid redraw.+ isSourceVisible: calendarView.isSourceVisible,+ });+ const teamEvents = createMemo(() =>+ mergeCalendarOverlays([], teamOoo.visibleEvents(), teamCalendar.events())+ );+ const visibleEvents = createMemo(() =>+ mergeCalendarOverlays(+ data.visibleEvents(),+ teamOoo.visibleEvents(),+ teamCalendar.events()+ )+ );+ const eventsById = createMemo(+ () => new Map(visibleEvents().map((event) => [event.id, event])));const updateEventTime = useUpdateCalendarEventMutation();const handleSelect = (selection: DateSelectArg) => {@@ -357,13 +369,32 @@ export function Page(props: {<CalendarPageHostid={props.id}data={data}- teamEvents={teamOoo.visibleEvents}+ teamEvents={teamEvents}eventsById={eventsById}grid={grid}onLoadingBlockingChange={setLoadingDecorationBlocking}/>)}</CalendarGrid>+ <Show when={teamCalendar.isError()}>+ <div+ role="status"+ class="absolute bottom-2 right-2 z-10 max-w-sm rounded-lg border border-edge-muted bg-surface px-3 py-2 text-xs text-ink-muted"+ >+ Team calendars unavailable. Availability is unknown.{' '}+ <button type="button" class="underline" onClick={teamCalendar.retry}>+ Retry+ </button>+ </div>+ </Show>+ <Show when={teamCalendar.isLoading()}>+ <div+ role="status"+ class="absolute bottom-2 right-2 z-10 rounded-lg border border-edge-muted bg-surface px-3 py-2 text-xs text-ink-muted"+ >+ Loading team calendars…+ </div>+ </Show></div>);}diff --git a/apps/web/src/features/calendar-view/components/SelectedEventDetails.tsx b/apps/web/src/features/calendar-view/components/SelectedEventDetails.tsxindex 2f916fa574..00aad37566 100644--- a/apps/web/src/features/calendar-view/components/SelectedEventDetails.tsx+++ b/apps/web/src/features/calendar-view/components/SelectedEventDetails.tsx@@ -13,6 +13,7 @@ import {guestEmails,} from '@app/features/calendar/utils/guest-emails';import { handleOpenEventOutsidePress } from '@app/features/calendar/utils/open-event-outside-press';+import { TeamEventDetails } from '@app/features/calendar-team/components/team-event-details';import { EventRsvpSection } from '@app/features/calendar-view/components/EventRsvpSection';import { useOpenEventComposer } from '@app/features/calendar-view/components/use-open-event-composer';import { useOpenEventEmail } from '@app/features/calendar-view/components/use-open-event-email';@@ -21,6 +22,7 @@ import { copyGuestEmails } from '@app/features/calendar-view/copy-guest-emails';import { MobileDrawer } from '@components/app/mobile/MobileDrawer';import { toast } from '@core/component/Toast/Toast';import { isMobile } from '@core/mobile/isMobile';+import { openExternalUrl } from '@core/util/url';import { Popover } from '@kobalte/core/popover';import CopyIcon from '@phosphor/copy.svg';import EnvelopeIcon from '@phosphor/envelope.svg';@@ -142,7 +144,9 @@ function EveryoneElseDeclinedNotice(props: {onReschedule: () => void;}) {return (- <Show when={hasEveryoneElseDeclined(props.event)}>+ <Show+ when={!props.event.teamProjection && hasEveryoneElseDeclined(props.event)}+ ><div class="border-edge-muted mx-3 mb-3 grid grid-cols-[1.25rem_minmax(0,1fr)] gap-x-4 rounded-lg border bg-active p-3 text-sm text-ink-muted sm:mt-2 sm:grid-cols-[1rem_minmax(0,1fr)] sm:gap-x-3 sm:text-xs"><spanaria-hidden="true"@@ -183,7 +187,7 @@ function EventGuestActions(props: {const openEventEmail = useOpenEventEmail();return (- <>+ <Show when={!props.event.teamProjection}><Buttonlabel="Copy guest emails"variant="ghost"@@ -210,7 +214,7 @@ function EventGuestActions(props: {<EnvelopeIcon /></Button></Show>- </>+ </Show>);}@@ -220,7 +224,10 @@ function EventDetailsDrawer(props: EventDetailsOverlayProps) {event: () => props.event,onDeleted: () => props.onOpenChange(false),});- const canModify = () => !props.event.isReadOnly && !props.event.isCancelled;+ const canModify = () =>+ !props.event.teamProjection &&+ !props.event.isReadOnly &&+ !props.event.isCancelled;const openEditor = () => {openEventComposer({ event: props.event });props.onOpenChange(false);@@ -256,16 +263,18 @@ function EventDetailsDrawer(props: EventDetailsOverlayProps) {<CloseIcon /></MobileDrawer.Close><div class="flex items-center gap-1">- <Button- aria-label="Copy event"- variant="ghost"- size="icon-md"- depth={3}- class="size-11 bg-ink/6 text-ink-muted [&_svg]:size-5"- onClick={() => copyCalendarEventMention(props.event)}- >- <LinkIcon />- </Button>+ <Show when={!props.event.teamProjection}>+ <Button+ aria-label="Copy event"+ variant="ghost"+ size="icon-md"+ depth={3}+ class="size-11 bg-ink/6 text-ink-muted [&_svg]:size-5"+ onClick={() => copyCalendarEventMention(props.event)}+ >+ <LinkIcon />+ </Button>+ </Show><Show when={canModify()}><Buttonaria-label="Edit event"@@ -298,22 +307,37 @@ function EventDetailsDrawer(props: EventDetailsOverlayProps) {onReschedule={openEditor}/><div class="px-3">- <EventDetails- event={props.event}- timeFormat={props.timeFormat}- defaultReminders={props.defaultReminders}- />- </div>- <EventAttendeesSection- attendees={props.event.attendees}- actions={- <EventGuestActions+ <Show+ when={props.event.teamProjection}+ fallback={+ <EventDetails+ event={props.event}+ timeFormat={props.timeFormat}+ defaultReminders={props.defaultReminders}+ />+ }+ >+ <TeamEventDetailsevent={props.event}- closeDetails={() => props.onOpenChange(false)}+ timeFormat={props.timeFormat}+ onOpenLink={openExternalUrl}/>- }- />- <EventRsvpSection event={props.event} buttonSize="md" />+ </Show>+ </div>+ <Show when={!props.event.teamProjection}>+ <EventAttendeesSection+ attendees={props.event.attendees}+ actions={+ <EventGuestActions+ event={props.event}+ closeDetails={() => props.onOpenChange(false)}+ />+ }+ />+ </Show>+ <Show when={!props.event.teamProjection}>+ <EventRsvpSection event={props.event} buttonSize="md" />+ </Show></MobileDrawer.ScrollBody></MobileDrawer.Content></MobileDrawer.Portal>@@ -438,7 +462,10 @@ function EventDetailsPopover(props: EventDetailsPopoverProps) {event: () => props.event,onDeleted: () => props.onOpenChange(false),});- const canModify = () => !props.event.isReadOnly && !props.event.isCancelled;+ const canModify = () =>+ !props.event.teamProjection &&+ !props.event.isReadOnly &&+ !props.event.isCancelled;const openEditor = () => {openEventComposer({ event: props.event });props.onOpenChange(false);@@ -494,16 +521,18 @@ function EventDetailsPopover(props: EventDetailsPopoverProps) {<div class="flex max-h-[min(32rem,var(--kb-popper-content-available-height,32rem))] w-fit min-w-[min(20rem,var(--kb-popper-content-available-width,20rem))] max-w-[min(24rem,var(--kb-popper-content-available-width,24rem))] flex-col overflow-hidden rounded-xl glass bg-menu-glass text-ink"><Popover.Title class="sr-only">{props.event.title}</Popover.Title><div class="flex shrink-0 items-center justify-end gap-1 px-2 pt-2">- <Button- aria-label="Copy event"- variant="ghost"- size="icon-sm"- depth={3}- class="text-ink-muted [&_svg]:size-4"- onClick={() => copyCalendarEventMention(props.event)}- >- <LinkIcon />- </Button>+ <Show when={!props.event.teamProjection}>+ <Button+ aria-label="Copy event"+ variant="ghost"+ size="icon-sm"+ depth={3}+ class="text-ink-muted [&_svg]:size-4"+ onClick={() => copyCalendarEventMention(props.event)}+ >+ <LinkIcon />+ </Button>+ </Show><Show when={canModify()}><Buttonaria-label="Edit event"@@ -545,24 +574,39 @@ function EventDetailsPopover(props: EventDetailsPopoverProps) {onReschedule={openEditor}/><div class="px-3 pb-3">- <EventDetails- event={props.event}- timeFormat={props.timeFormat}- defaultReminders={props.defaultReminders}- />- </div>- <EventAttendeesSection- attendees={props.event.attendees}- actions={- <EventGuestActions+ <Show+ when={props.event.teamProjection}+ fallback={+ <EventDetails+ event={props.event}+ timeFormat={props.timeFormat}+ defaultReminders={props.defaultReminders}+ />+ }+ >+ <TeamEventDetailsevent={props.event}- closeDetails={() => props.onOpenChange(false)}+ timeFormat={props.timeFormat}+ onOpenLink={openExternalUrl}/>- }- />+ </Show>+ </div>+ <Show when={!props.event.teamProjection}>+ <EventAttendeesSection+ attendees={props.event.attendees}+ actions={+ <EventGuestActions+ event={props.event}+ closeDetails={() => props.onOpenChange(false)}+ />+ }+ />+ </Show></div><div class="shrink-0">- <EventRsvpSection event={props.event} />+ <Show when={!props.event.teamProjection}>+ <EventRsvpSection event={props.event} />+ </Show></div></div></Popover.Content>diff --git a/apps/web/src/features/calendar-view/copy-event-mention.test.ts b/apps/web/src/features/calendar-view/copy-event-mention.test.tsindex 2bae8cea5f..07d20eb6cf 100644--- a/apps/web/src/features/calendar-view/copy-event-mention.test.ts+++ b/apps/web/src/features/calendar-view/copy-event-mention.test.ts@@ -1,5 +1,9 @@import { beforeEach, describe, expect, it, vi } from 'vitest';-import { copyCalendarEventMentionTarget } from './copy-event-mention';+import { mapTeamCalendarItem } from '../calendar-team/queries/map';+import {+ copyCalendarEventMention,+ copyCalendarEventMentionTarget,+} from './copy-event-mention';const writeClipboardData = vi.hoisted(() =>vi.fn(async (_data: Record<string, string | undefined>) => true)@@ -15,6 +19,25 @@ const written = () => writeClipboardData.mock.calls[0]?.[0];describe('copyCalendarEventMentionTarget', () => {beforeEach(() => writeClipboardData.mockClear());+ it('never copies a team projection as an independently resolvable event', async () => {+ const event = mapTeamCalendarItem(+ {+ id: 'opaque',+ ownerId: 'alice',+ kind: 'busy',+ contributesToAvailability: true,+ time: {+ kind: 'timed',+ startsAt: '2026-10-07T10:00:00Z',+ endsAt: '2026-10-07T11:00:00Z',+ },+ },+ 'Alice'+ );+ await copyCalendarEventMention(event);+ expect(writeClipboardData).not.toHaveBeenCalled();+ });+it('writes a mention span an editor can import', async () => {await copyCalendarEventMentionTarget({eventId: 'event-1',diff --git a/apps/web/src/features/calendar-view/copy-event-mention.ts b/apps/web/src/features/calendar-view/copy-event-mention.tsindex da2680f2c7..2073d204d8 100644--- a/apps/web/src/features/calendar-view/copy-event-mention.ts+++ b/apps/web/src/features/calendar-view/copy-event-mention.ts@@ -80,6 +80,7 @@ export async function copyCalendarEventMentionTarget(/** Copy a calendar-grid event, pinning the instance when it repeats. */export async function copyCalendarEventMention(event: CalendarEvent) {+ if (event.teamProjection) return;await copyCalendarEventMentionTarget({eventId: event.eventId,title: event.title,diff --git a/apps/web/src/features/calendar/calendar-settings.tsx b/apps/web/src/features/calendar/calendar-settings.tsxindex 14760ccdcf..ac13af1005 100644--- a/apps/web/src/features/calendar/calendar-settings.tsx+++ b/apps/web/src/features/calendar/calendar-settings.tsx@@ -5,6 +5,7 @@ import { useUserId } from '@core/context/user';import { useAddInboxFlow } from '@core/email-link';import { useEmailLinksQuery } from '@queries/email/link';import { createSignal, Suspense } from 'solid-js';+import { CalendarTeamSettings } from '../calendar-team/calendar-team';import { SettingsPage } from '../settings/primitives';import {type ConnectedCalendarAccount,@@ -133,6 +134,7 @@ export function CalendarSettings() {description="Manage your connected accounts, calendar visibility, and colors."><CalendarConnectionSettings />+ <CalendarTeamSettings /></SettingsPage>);}diff --git a/apps/web/src/features/calendar/components/CalendarViewContext.tsx b/apps/web/src/features/calendar/components/CalendarViewContext.tsxindex 3640a84f69..fff3b7126c 100644--- a/apps/web/src/features/calendar/components/CalendarViewContext.tsx+++ b/apps/web/src/features/calendar/components/CalendarViewContext.tsx@@ -1,10 +1,12 @@import { createAssertedContextProvider } from '@core/context/createContext';+import { subscribeToTeamCalendarReset } from '@queries/calendar/team-cache';import {batch,createEffect,createMemo,createSignal,on,+ onCleanup,type ParentProps,} from 'solid-js';import { useCalendarSources } from '../hooks/use-calendar-sources';@@ -22,6 +24,7 @@ interface CalendarDisplaySettings {readonly showWeekends: boolean;readonly weekStartsOn: CalendarWeekStart;readonly timeFormat: CalendarTimeFormat;+ readonly showTeamCalendars: boolean;}type CalendarViewContextProps = ParentProps<{@@ -56,7 +59,10 @@ function createCalendarEventSelection(setAnchor(nextAnchor);setOrigin(nextOrigin);});- onFocusedEventIdChange?.(nextEvent.eventId);+ // Opaque team projections have no direct-event navigation capability.+ onFocusedEventIdChange?.(+ nextEvent.teamProjection ? undefined : nextEvent.eventId+ );};const refresh = (nextEvent: CalendarEvent) => {if (event()?.id === nextEvent.id) setEvent(nextEvent);@@ -83,6 +89,17 @@ export const [CalendarViewContextProvider, useCalendarView] =const selection = createCalendarEventSelection(props.onFocusedEventIdChange);+ // A revoked OOO agenda entry can lie outside every mounted viewport.+ // Close detached selections synchronously when authorization resets data.+ const unsubscribeTeamReset = subscribeToTeamCalendarReset(() => {+ const selected = selection.event();+ if (+ selected?.teamProjection ||+ selected?.calendar.id.startsWith('team-ooo:')+ )+ selection.close();+ });+ onCleanup(unsubscribeTeamReset);// Preferences are shared across providers; track only this route's period// so two mounted calendars never overwrite each other in a loop.createEffect(@@ -102,6 +119,7 @@ export const [CalendarViewContextProvider, useCalendarView] =previousEventId !== undefined &&focusedEventId !== previousEventId &&selectedEvent &&+ !selectedEvent.teamProjection &&selectedEvent.eventId !== focusedEventId) {selection.close(false);@@ -122,6 +140,9 @@ export const [CalendarViewContextProvider, useCalendarView] =get timeFormat() {return preferences.timeFormat;},+ get showTeamCalendars() {+ return preferences.showTeamCalendars;+ },};const closeEventDetails = () => selection.close();@@ -137,7 +158,10 @@ export const [CalendarViewContextProvider, useCalendarView] =if (isCalendarEventVisible(event, isSourceVisible))selection.refresh(event);else closeEventDetails();- } else if (rangeIsCurrent && selection.origin() === 'grid') {+ } else if (+ (rangeIsCurrent || selected.teamProjection) &&+ selection.origin() === 'grid'+ ) {// Agenda selections can be outside the visible grid's date range.closeEventDetails();}@@ -192,6 +216,11 @@ export const [CalendarViewContextProvider, useCalendarView] =setPreferences('weekStartsOn', weekStartsOn),setTimeFormat: (timeFormat: CalendarTimeFormat) =>setPreferences('timeFormat', timeFormat),+ setShowTeamCalendars: (visible: boolean) => {+ setPreferences('showTeamCalendars', visible);+ if (!visible && selection.event()?.teamProjection)+ closeEventDetails();+ },closeEventDetails,selectEvent: selection.select,refreshSelectedEvent: selection.refresh,diff --git a/apps/web/src/features/calendar/hooks/use-calendar-ui-flag.ts b/apps/web/src/features/calendar/hooks/use-calendar-ui-flag.tsindex 2ae80be7af..6e422b4678 100644--- a/apps/web/src/features/calendar/hooks/use-calendar-ui-flag.ts+++ b/apps/web/src/features/calendar/hooks/use-calendar-ui-flag.ts@@ -4,6 +4,7 @@ import {enableCalendarPromptWeb,enableCalendarSearchUi,enableCalendarTeamOoo,+ enableCalendarTeamSharing,enableCalendarUi,} from '@core/constant/featureFlags';import { isMobile } from '@core/mobile/isMobile';@@ -47,3 +48,9 @@ export function useCalendarTeamOooFlag(): Accessor<boolean> {const flag = useFeatureFlag(enableCalendarTeamOoo);return () => flag().enabled;}++export function useCalendarTeamSharingFlag(): Accessor<boolean> {+ const calendarUi = useCalendarUiFlag();+ const flag = useFeatureFlag(enableCalendarTeamSharing);+ return () => calendarUi() && flag().enabled;+}diff --git a/apps/web/src/features/calendar/hooks/use-team-ooo.ts b/apps/web/src/features/calendar/hooks/use-team-ooo.tsindex 015146815d..9b1d6f7d7b 100644--- a/apps/web/src/features/calendar/hooks/use-team-ooo.ts+++ b/apps/web/src/features/calendar/hooks/use-team-ooo.ts@@ -59,6 +59,7 @@ function mapTeamOooItem(item: TeamOutOfOfficeItem): CalendarEvent {id: JSON.stringify([item.eventId, item.occurrenceKey]),eventId: item.eventId,occurrenceKey: item.occurrenceKey,+ teamProjection: { ownerId: item.ownerId, kind: 'details' },isCancelled: false,isReadOnly: true,attendees: [],@@ -110,6 +111,7 @@ export function useTeamOooEvents(!teamOooEnabled() ||!isRangeSupported() ||!query.isSuccess ||+ query.isPaused ||query.isPlaceholderData) {return [];@@ -165,7 +167,7 @@ export function useUpcomingTeamOoo(): UpcomingTeamOoo {const windows = createMemo<TeamOooWindow[]>(() => {// Read data only on success so a pending query never hits the suspending// resource read and an errored refetch never surfaces stale rows.- if (!query.isSuccess) return [];+ if (!query.isSuccess || query.isPaused) return [];return query.data.map((item) => {const time = item.time;const [start, end, allDay] =@@ -189,6 +191,6 @@ export function useUpcomingTeamOoo(): UpcomingTeamOoo {return {windows,isPending: () => query.isPending,- isError: () => query.isError,+ isError: () => query.isError || query.isPaused,};}diff --git a/apps/web/src/features/calendar/types.ts b/apps/web/src/features/calendar/types.tsindex 57ddf48552..78e746e6b8 100644--- a/apps/web/src/features/calendar/types.ts+++ b/apps/web/src/features/calendar/types.ts@@ -44,6 +44,13 @@ export interface CalendarSource {/** Calendar occurrence data, independent from FullCalendar. */export interface CalendarEvent {+ /** A sanitized team projection grants read access only, never provider actions. */+ teamProjection?: {+ ownerId: string;+ kind: 'busy' | 'details';+ /** Legacy OOO status does not carry an availability classification. */+ contributesToAvailability?: boolean;+ };/** Stable identifier for this rendered occurrence. */id: string;/** Stable canonical calendar event identifier. */diff --git a/apps/web/src/features/calendar/utils/event-interaction.ts b/apps/web/src/features/calendar/utils/event-interaction.tsindex 6f69db8cde..f617acdc62 100644--- a/apps/web/src/features/calendar/utils/event-interaction.ts+++ b/apps/web/src/features/calendar/utils/event-interaction.ts@@ -34,6 +34,7 @@ export function calendarEventRenderIds(/** Whether an occurrence can safely be moved or resized from the calendar. */export function canEditCalendarEventTime(event: CalendarEvent) {return (+ !event.teamProjection &&!event.isReadOnly &&!event.isCancelled &&event.recurrenceLines.length === 0 &&diff --git a/apps/web/src/features/calendar/utils/preferences.ts b/apps/web/src/features/calendar/utils/preferences.tsindex 6f7551e034..421e7335c2 100644--- a/apps/web/src/features/calendar/utils/preferences.ts+++ b/apps/web/src/features/calendar/utils/preferences.ts@@ -20,6 +20,7 @@ interface CalendarPreferences {showWeekends: boolean;weekStartsOn: CalendarWeekStart;timeFormat: CalendarTimeFormat;+ showTeamCalendars: boolean;}/** One persisted store, so preference changes reach invitation cards outside the calendar. */@@ -32,6 +33,7 @@ export const useCalendarPreferences = createSharedRoot(() => {showWeekends: true,weekStartsOn: 0,timeFormat: getDefaultCalendarTimeFormat(),+ showTeamCalendars: false,};const [preferences, setPreferences] = makePersisted(createStore<CalendarPreferences>(defaultPreferences),diff --git a/apps/web/src/lib/core/auth/logout.ts b/apps/web/src/lib/core/auth/logout.tsindex a3e92a1563..046513a812 100644--- a/apps/web/src/lib/core/auth/logout.ts+++ b/apps/web/src/lib/core/auth/logout.ts@@ -6,6 +6,7 @@ import { syncLoginStorage } from '@core/util/cookies';import { clearPostLoginRedirect } from '@core/util/postLoginRedirect';import { clearRegisteredCaches } from '@graphql-cache/lifecycle';import { authKeys, type UserInfoData } from '@queries/auth/user-info';+import { clearTeamCalendarQueries } from '@queries/calendar/team-cache';import { queryClient } from '@queries/client';import { emailKeys } from '@queries/email/keys';import {@@ -49,6 +50,7 @@ export async function clearLocalAuthSession() {syncLoginStorage(false);const documentContextsCleared = clearOfflineDocumentContexts();clearDocumentQueryCache(queryClient);+ clearTeamCalendarQueries();queryClient.setQueryData(authKeys.userInfo.queryKey, unauthenticatedUserInfo);queryClient.removeQueries({ queryKey: emailKeys.links.queryKey });queryClient.removeQueries({ queryKey: notificationKeys._def });diff --git a/apps/web/src/lib/core/component/AI/component/tool/TeamAvailability.tsx b/apps/web/src/lib/core/component/AI/component/tool/TeamAvailability.tsxnew file mode 100644index 0000000000..61dbaf6338--- /dev/null+++ b/apps/web/src/lib/core/component/AI/component/tool/TeamAvailability.tsx@@ -0,0 +1,70 @@+import { getDisplayName, tryMacroId } from '@core/user';+import CalendarCheck from '@phosphor-icons/core/regular/calendar-check.svg';+import type { NamedTool } from '@service-cognition/generated/tools/tool';+import { format } from 'date-fns';+import { For, Show } from 'solid-js';+import { BaseTool } from './BaseTool';+import { Tool } from './Tool';+import { createToolRenderer } from './ToolRenderer';++type Availability = NamedTool<'GetTeamAvailability', 'response'>['data'];++function AvailabilityResponse(props: { data: Availability }) {+ return (+ <Tool.List>+ <For each={props.data.members}>+ {(member) => (+ <Tool.ListItem>+ <span class="min-w-0 flex-1 truncate text-xs text-ink">+ {getDisplayName(tryMacroId(member.userId)) || 'Teammate'}+ </span>+ <span class="text-xs text-ink-muted">+ {member.coverage === 'unknown'+ ? 'Availability unknown'+ : `${member.busy.length} busy blocks`}+ </span>+ </Tool.ListItem>+ )}+ </For>+ <Show when={!props.data.complete}>+ <Tool.ListItem>+ Some availability is unknown. No shared free time can be confirmed.+ </Tool.ListItem>+ </Show>+ <Show+ when={props.data.complete && (props.data.freeWindows?.length ?? 0) > 0}+ >+ <Tool.ListItem>Free for everyone checked, including you</Tool.ListItem>+ <For each={props.data.freeWindows}>+ {(window) => (+ <Tool.ListItem>+ {format(new Date(window.start), 'EEE MMM d, h:mm a')} –{' '}+ {format(new Date(window.end), 'EEE MMM d, h:mm a')}+ </Tool.ListItem>+ )}+ </For>+ </Show>+ <Show when={props.data.complete && props.data.freeWindows?.length === 0}>+ <Tool.ListItem>No shared free time in this window.</Tool.ListItem>+ </Show>+ </Tool.List>+ );+}++export const getTeamAvailabilityHandler = createToolRenderer({+ name: 'GetTeamAvailability',+ render: (ctx) => (+ <BaseTool+ icon={CalendarCheck}+ renderContext={ctx.renderContext}+ type="call"+ response={+ ctx.response?.data ? (+ <AvailabilityResponse data={ctx.response.data} />+ ) : undefined+ }+ >+ Check team availability+ </BaseTool>+ ),+});diff --git a/apps/web/src/lib/core/component/AI/component/tool/handler.tsx b/apps/web/src/lib/core/component/AI/component/tool/handler.tsxindex 02996f6c4a..e66d2730bf 100644--- a/apps/web/src/lib/core/component/AI/component/tool/handler.tsx+++ b/apps/web/src/lib/core/component/AI/component/tool/handler.tsx@@ -131,6 +131,7 @@ import {readSpreadsheetHandler,} from './Spreadsheet';import { subagentHandler } from './Subagent';+import { getTeamAvailabilityHandler } from './TeamAvailability';import { textEditorCodeExecutionHandler } from './TextEditorCodeExecution';import {type RenderContext,@@ -182,6 +183,7 @@ const toolHandlers: ToolHandlerMap<RenderContext> = {DeleteCalendarEvent: deleteCalendarEventHandler,ListCalendarEvents: listCalendarEventsHandler,ListCalendars: listCalendarsHandler,+ GetTeamAvailability: getTeamAvailabilityHandler,CreateImportEntity: createImportEntityHandler,DeleteImportEntity: deleteImportEntityHandler,ImportNotionPage: importNotionPageHandler,diff --git a/apps/web/src/lib/core/constant/featureFlags.ts b/apps/web/src/lib/core/constant/featureFlags.tsindex 30c512bead..afb24f472b 100644--- a/apps/web/src/lib/core/constant/featureFlags.ts+++ b/apps/web/src/lib/core/constant/featureFlags.ts@@ -672,6 +672,13 @@ export const enableCalendarTeamOoo = defineFlag({default: onInDev,});+// Read-only team calendar projections; the server separately controls rollout.+export const enableCalendarTeamSharing = defineFlag({+ key: 'enable-calendar-team-sharing',+ env: 'ENABLE_CALENDAR_TEAM_SHARING',+ default: onInDev,+});+// Sharing a personal tag with the team: the "Share with team" action on// personal tags in Settings › Tags, and the prompt that merges into an// existing team label when the names collide. The backend endpoints shipdiff --git a/apps/web/src/lib/queries/auth/user-info.test.ts b/apps/web/src/lib/queries/auth/user-info.test.tsindex 2641f64dd9..ece237f03a 100644--- a/apps/web/src/lib/queries/auth/user-info.test.ts+++ b/apps/web/src/lib/queries/auth/user-info.test.ts@@ -1,4 +1,4 @@-import { QueryClient } from '@tanstack/solid-query';+import { QueryClient, QueryObserver } from '@tanstack/solid-query';import { afterEach, describe, expect, it, vi } from 'vitest';const client = vi.hoisted(() => ({@@ -19,6 +19,9 @@ vi.mock('@core/context/user-info-gate', () => ({vi.mock('@core/util/cookies', () => ({ hasLoginCookie: () => true }));vi.mock('@service-auth/client', () => ({ authServiceClient: {} }));+import { calendarKeys } from '../calendar/keys';+import { subscribeToTeamCalendarReset } from '../calendar/team-cache';+import { calendarTeamKeys } from '../calendar/team-keys';import { graphqlSoupKeys } from '../soup/graphql/keys';import { authKeys } from './keys';import { invalidateAllAfterLogin } from './user-info';@@ -28,6 +31,46 @@ afterEach(() => {});describe('login display-intent lifetime', () => {+ it('removes team payloads and closes detached selections before a replacement session refetch settles', async () => {+ const queryClient = new QueryClient();+ client.current = queryClient;+ const identity = { userId: 'old-viewer', authenticated: true };+ queryClient.setQueryData(authKeys.userInfo.queryKey, identity);+ const teamKeys = [+ calendarTeamKeys.events(+ { userId: 'old-viewer', teamId: 'old-team' },+ undefined+ ).queryKey,+ calendarKeys.teamOutOfOffice('old-viewer', undefined, 'old-team')+ .queryKey,+ ];+ const observers = teamKeys.map((queryKey) => {+ queryClient.setQueryData(queryKey, { title: 'Old private title' });+ return new QueryObserver(queryClient, {+ queryKey,+ queryFn: () => new Promise<never>(() => {}),+ staleTime: Infinity,+ });+ });+ const subscriptions = observers.map((observer) =>+ observer.subscribe(() => {})+ );+ const closeSelection = vi.fn();+ const unsubscribeReset = subscribeToTeamCalendarReset(closeSelection);++ const invalidated = invalidateAllAfterLogin();++ // User-info can still show the old viewer while its auth request settles.+ expect(queryClient.getQueryData(authKeys.userInfo.queryKey)).toBe(identity);+ for (const observer of observers)+ expect(observer.getCurrentResult().data).toBeUndefined();+ expect(closeSelection).toHaveBeenCalledTimes(2);+ unsubscribeReset();+ subscriptions.forEach((unsubscribe) => unsubscribe());+ await queryClient.cancelQueries();+ await invalidated;+ });+it('retires old intent even when native login keeps the same viewer and mounted app', async () => {const queryClient = new QueryClient();client.current = queryClient;diff --git a/apps/web/src/lib/queries/auth/user-info.ts b/apps/web/src/lib/queries/auth/user-info.tsindex f3d754f312..84098905c3 100644--- a/apps/web/src/lib/queries/auth/user-info.ts+++ b/apps/web/src/lib/queries/auth/user-info.ts@@ -4,6 +4,7 @@ import { hasLoginCookie } from '@core/util/cookies';import { catchToResult, type ResultType, throwOnErr } from '@core/util/result';import { authServiceClient } from '@service-auth/client';import { useQuery } from '@tanstack/solid-query';+import { resetTeamCalendarSession } from '../calendar/team-cache';import { queryClient, queryPersistence } from '../client';import { resetGraphqlSoupDoneSession } from '../soup/graphql/done-session';import { authKeys } from './keys';@@ -63,6 +64,7 @@ export function invalidateAllAfterLogin() {// Login may replace a session without visiting logout (including native auth).// Invalidate old display-intent handles before refetching the new identity.resetGraphqlSoupDoneSession();+ resetTeamCalendarSession();enableUserInfoQuery();const invalidated = queryClient.invalidateQueries();// Rebind this device's push registrations once the refetches above havediff --git a/apps/web/src/lib/queries/calendar/keys.ts b/apps/web/src/lib/queries/calendar/keys.tsindex 85ecb2a4ee..1e705eef7f 100644--- a/apps/web/src/lib/queries/calendar/keys.ts+++ b/apps/web/src/lib/queries/calendar/keys.ts@@ -33,9 +33,10 @@ export const calendarKeys = createQueryKeys('calendar', {}),teamOutOfOffice: (userId: string,- range: CalendarOccurrenceQueryRange | undefined+ range: CalendarOccurrenceQueryRange | undefined,+ teamId?: string) => ({- queryKey: [userId, range],+ queryKey: [userId, range, teamId],}),mentionPreview: (eventId: string, occurrenceKey: string | undefined) => ({queryKey: [eventId, occurrenceKey],diff --git a/apps/web/src/lib/queries/calendar/sync.ts b/apps/web/src/lib/queries/calendar/sync.tsindex ed56f006db..7a11a7cb44 100644--- a/apps/web/src/lib/queries/calendar/sync.ts+++ b/apps/web/src/lib/queries/calendar/sync.ts@@ -3,6 +3,7 @@ import { invalidateCalendarInvitations } from './invitations';import { calendarKeys, RSVP_MUTATION_KEY } from './keys';import { invalidateCalendarEventPreviews } from './mention-preview';import { invalidateCalendarOccurrences } from './occurrences';+import { resetTeamCalendarQueries } from './team-cache';import { invalidateTeamOutOfOffice } from './team-ooo';/**@@ -12,6 +13,7 @@ import { invalidateTeamOutOfOffice } from './team-ooo';* calendar mention chips.*/export function invalidateCalendarViews(): void {+ void resetTeamCalendarQueries();void invalidateCalendarInvitations();invalidateCalendarOccurrences();invalidateCalendarEventPreviews();@@ -34,7 +36,12 @@ export function handleRefreshCalendar(payload: unknown): void {typeof payload === 'object' && payload !== null? (payload as { event?: unknown; link_id?: unknown }): undefined;+ if (event?.event === 'team_sharing_changed') {+ void resetTeamCalendarQueries();+ return;+ }if (event?.event !== 'synced' || typeof event.link_id !== 'string') return;+ void resetTeamCalendarQueries();// An in-flight RSVP holds optimistic occurrence state a refetch would// clobber; the last RSVP to settle re-invalidates occurrences itself, sodiff --git a/apps/web/src/lib/queries/calendar/team-cache.ts b/apps/web/src/lib/queries/calendar/team-cache.tsnew file mode 100644index 0000000000..cb1c347e5c--- /dev/null+++ b/apps/web/src/lib/queries/calendar/team-cache.ts@@ -0,0 +1,93 @@+import type { Query, QueryKey } from '@tanstack/solid-query';+import { queryClient } from '../client';+import { calendarKeys } from './keys';+import { calendarTeamKeys } from './team-keys';++/** A missed poll may retain data briefly, but a hung request cannot retain it. */+export const TEAM_CALENDAR_MAX_DATA_AGE_MS = 60_000;++function isTeamCalendarKey(key: QueryKey) {+ return (+ key[0] === calendarTeamKeys._def[0] ||+ (key[0] === calendarKeys.teamOutOfOffice._def[0] &&+ key[1] === calendarKeys.teamOutOfOffice._def[1])+ );+}++let expiryInstalled = false;++/** Start with the first team observer, avoiding work in unrelated app views. */+export function ensureTeamCalendarExpiry() {+ if (expiryInstalled) return;+ expiryInstalled = true;+ const expirations = new Map<+ Query,+ { deadline: number; timer: ReturnType<typeof setTimeout> }+ >();+ queryClient.getQueryCache().subscribe((event) => {+ const query = event.query;+ if (!isTeamCalendarKey(query.queryKey)) return;+ if (!['added', 'updated', 'removed'].includes(event.type)) return;+ const previous = expirations.get(query);+ if (previous) clearTimeout(previous.timer);+ expirations.delete(query);+ if (event.type === 'removed') return;+ const { data, dataUpdatedAt, fetchStatus } = query.state;+ if (data === undefined && fetchStatus === 'idle') return;+ // Fetch/invalidation notifications do not extend an existing lease. Bound+ // initial requests too, so a delayed response cannot install old permissions.+ const deadline =+ data !== undefined+ ? dataUpdatedAt + TEAM_CALENDAR_MAX_DATA_AGE_MS+ : (previous?.deadline ?? Date.now() + TEAM_CALENDAR_MAX_DATA_AGE_MS);+ const timer = setTimeout(+ () => {+ expirations.delete(query);+ // Query.reset cancels its retryer before notifying active observers. A+ // late response cannot restore the expired payload or detached selection.+ query.reset();+ },+ Math.max(0, deadline - Date.now())+ );+ expirations.set(query, { deadline, timer });+ });+}++/** Session replacement must clear active observers before any new auth fetch. */+export function resetTeamCalendarSession() {+ for (const query of queryClient.getQueryCache().findAll({+ predicate: (query) => isTeamCalendarKey(query.queryKey),+ })) {+ // Do not refetch here: the caller controls the new session's request order.+ query.reset();+ }+}++/** Clear payloads first: a revoked title must disappear even if refetch fails. */+export async function resetTeamCalendarQueries() {+ await Promise.all([+ queryClient.resetQueries({ queryKey: calendarTeamKeys._def }),+ queryClient.resetQueries({ queryKey: calendarKeys.teamOutOfOffice._def }),+ ]);+}++export function clearTeamCalendarQueries() {+ resetTeamCalendarSession();+ queryClient.removeQueries({ queryKey: calendarTeamKeys._def });+ queryClient.removeQueries({ queryKey: calendarKeys.teamOutOfOffice._def });+}++/** Calendar selections are detached objects, including OOO agenda selections. */+export function subscribeToTeamCalendarReset(onReset: () => void) {+ return queryClient.getQueryCache().subscribe((event) => {+ if (+ isTeamCalendarKey(event.query.queryKey) &&+ event.type === 'updated' &&+ ((event.action.type === 'setState' &&+ event.query.state.data === undefined) ||+ event.action.type === 'error' ||+ event.query.state.fetchStatus === 'paused')+ )+ onReset();+ });+}diff --git a/apps/web/src/lib/queries/calendar/team-keys.ts b/apps/web/src/lib/queries/calendar/team-keys.tsnew file mode 100644index 0000000000..609c9de44d--- /dev/null+++ b/apps/web/src/lib/queries/calendar/team-keys.ts@@ -0,0 +1,21 @@+import { createQueryKeys } from '@lukemorales/query-key-factory';+import type { CalendarOccurrenceQueryRange } from './keys';++export interface CalendarTeamIdentity {+ userId: string;+ teamId: string;+}++/** Never normalized into the viewer's own-event GraphQL cache. */+export const calendarTeamKeys = createQueryKeys('calendar-team', {+ identity: (userId: string) => [userId],+ sharing: (identity: CalendarTeamIdentity | undefined) => [identity],+ members: (identity: CalendarTeamIdentity | undefined) => [identity],+ availabilityCalendars: (identity: CalendarTeamIdentity | undefined) => [+ identity,+ ],+ events: (+ identity: CalendarTeamIdentity | undefined,+ range: CalendarOccurrenceQueryRange | undefined+ ) => [identity, range],+});diff --git a/apps/web/src/lib/queries/calendar/team-ooo.ts b/apps/web/src/lib/queries/calendar/team-ooo.tsindex 1e3636e24c..b9c7e25db7 100644--- a/apps/web/src/lib/queries/calendar/team-ooo.ts+++ b/apps/web/src/lib/queries/calendar/team-ooo.ts@@ -5,9 +5,9 @@ import type { TeamOutOfOfficeItem } from '@service-storage/generated/schemas/teaimport { useQuery } from '@tanstack/solid-query';import type { Accessor } from 'solid-js';import { type CalendarOccurrenceQueryRange, calendarKeys } from './keys';+import { useCalendarTeamIdentityQuery } from './team';const TEAM_OOO_PAGE_SIZE = 2000;-const TEAM_OOO_STALE_TIME = 60_000;export interface TeamOutOfOfficeQueryInput {userId: string | undefined;@@ -38,11 +38,21 @@ export function useTeamOutOfOfficeQuery(input: Accessor<TeamOutOfOfficeQueryInput>,options?: Accessor<TeamOutOfOfficeQueryOptions>) {+ const identity = useCalendarTeamIdentityQuery(+ () => input().userId,+ () => options?.().enabled !== false+ );return useQuery(() => {const { userId, range } = input();+ const team =+ identity.isSuccess && !identity.isPaused ? identity.data : undefined;+ const teamId = team?.members.some((member) => member.user_id === userId)+ ? team.team.id+ : undefined;return {- queryKey: calendarKeys.teamOutOfOffice(userId ?? '', range).queryKey,+ queryKey: calendarKeys.teamOutOfOffice(userId ?? '', range, teamId)+ .queryKey,queryFn: ({ signal }: { signal?: AbortSignal }) => {if (!range) {throw new Error('Team out-of-office range is unavailable');@@ -51,9 +61,14 @@ export function useTeamOutOfOfficeQuery(return fetchTeamOutOfOffice(range, signal);},enabled:- Boolean(userId) && range !== undefined && options?.().enabled !== false,- staleTime: TEAM_OOO_STALE_TIME,- placeholderData: (p: TeamOutOfOfficeItem[] | undefined) => p,+ Boolean(userId) &&+ Boolean(teamId) &&+ range !== undefined &&+ options?.().enabled !== false,+ staleTime: 0,+ gcTime: 0,+ refetchInterval: 30_000,+ refetchOnReconnect: 'always',refetchOnWindowFocus: options?.().refetchOnWindowFocus ?? true,};});diff --git a/apps/web/src/lib/queries/calendar/team.ts b/apps/web/src/lib/queries/calendar/team.tsnew file mode 100644index 0000000000..9d5b722bbc--- /dev/null+++ b/apps/web/src/lib/queries/calendar/team.ts@@ -0,0 +1,161 @@+import type { CalendarSharing } from '@app/features/calendar-team/core/model';+import { throwOnErr } from '@core/util/result';+import { authServiceClient } from '@service-auth/client';+import { emailClient } from '@service-email/client';+import { storageServiceClient } from '@service-storage/client';+import type { TeamCalendarPage } from '@service-storage/generated/schemas/teamCalendarPage';+import { useMutation, useQuery } from '@tanstack/solid-query';+import type { Accessor } from 'solid-js';+import type { CalendarOccurrenceQueryRange } from './keys';+import {+ ensureTeamCalendarExpiry,+ resetTeamCalendarQueries,+} from './team-cache';+import { type CalendarTeamIdentity, calendarTeamKeys } from './team-keys';++const REFRESH_INTERVAL = 30_000;+const freshness = {+ staleTime: 0,+ gcTime: 0,+ refetchInterval: REFRESH_INTERVAL,+ refetchOnWindowFocus: true,+ refetchOnReconnect: 'always' as const,+};++/** A viewer-scoped roster read avoids the legacy current-team singleton cache. */+export function useCalendarTeamIdentityQuery(+ userId: Accessor<string | undefined>,+ enabled: Accessor<boolean>+) {+ ensureTeamCalendarExpiry();+ return useQuery(() => ({+ queryKey: calendarTeamKeys.identity(userId() ?? '').queryKey,+ queryFn: () => throwOnErr(() => authServiceClient.getTeam()),+ enabled: Boolean(userId()) && enabled(),+ ...freshness,+ }));+}++/** Read every page. A failed or cyclic continuation never looks like empty time. */+export async function fetchTeamCalendar(+ range: CalendarOccurrenceQueryRange,+ signal?: AbortSignal+): Promise<TeamCalendarPage> {+ const items = new Map<string, TeamCalendarPage['items'][number]>();+ const cursors = new Set<string>();+ let cursor: string | undefined;+ let members: TeamCalendarPage['members'] = [];+ do {+ const page = await throwOnErr(() =>+ storageServiceClient.listTeamCalendar({+ start: range.start,+ end: range.end,+ limit: 500,+ cursor,+ signal,+ })+ );+ members = page.members;+ for (const item of page.items)+ items.set(JSON.stringify([item.ownerId, item.id]), item);+ if (!page.nextCursor) break;+ if (cursors.has(page.nextCursor))+ throw new Error('Team calendar returned a repeated cursor');+ cursors.add(page.nextCursor);+ cursor = page.nextCursor;+ } while (cursor);+ return { members, items: [...items.values()], nextCursor: null };+}++export function useTeamCalendarQuery(+ identity: Accessor<CalendarTeamIdentity | undefined>,+ range: Accessor<CalendarOccurrenceQueryRange | undefined>,+ enabled: Accessor<boolean>+) {+ return useQuery(() => ({+ queryKey: calendarTeamKeys.events(identity(), range()).queryKey,+ queryFn: ({ signal }) => {+ const current = range();+ if (!current) throw new Error('Calendar range unavailable');+ return fetchTeamCalendar(current, signal);+ },+ enabled: identity() !== undefined && range() !== undefined && enabled(),+ ...freshness,+ }));+}++export function useTeamCalendarSharingQuery(+ identity: Accessor<CalendarTeamIdentity | undefined>+) {+ return useQuery(() => ({+ queryKey: calendarTeamKeys.sharing(identity()).queryKey,+ queryFn: ({ signal }) =>+ throwOnErr(() => emailClient.getTeamCalendarSharing(signal)),+ enabled: identity() !== undefined,+ ...freshness,+ }));+}++export function useAvailabilityCalendarsQuery(+ identity: Accessor<CalendarTeamIdentity | undefined>+) {+ return useQuery(() => ({+ queryKey: calendarTeamKeys.availabilityCalendars(identity()).queryKey,+ queryFn: ({ signal }) =>+ throwOnErr(() => emailClient.getAvailabilityCalendars(signal)),+ enabled: identity() !== undefined,+ ...freshness,+ }));+}++/** A zero-limit read authorizes the roster without scanning source events. */+export async function fetchTeamCalendarMembers(signal?: AbortSignal) {+ const start = new Date();+ start.setUTCHours(0, 0, 0, 0);+ const end = new Date(start);+ end.setUTCDate(end.getUTCDate() + 1);+ const page = await throwOnErr(() =>+ storageServiceClient.listTeamCalendar({+ start: start.toISOString(),+ end: end.toISOString(),+ limit: 0,+ signal,+ })+ );+ return page.members;+}++/** The roster is present even in an empty viewport; retain no event payload. */+export function useTeamCalendarMembersQuery(+ identity: Accessor<CalendarTeamIdentity | undefined>+) {+ return useQuery(() => ({+ queryKey: calendarTeamKeys.members(identity()).queryKey,+ queryFn: ({ signal }) => fetchTeamCalendarMembers(signal),+ enabled: identity() !== undefined,+ ...freshness,+ }));+}++export function useSetTeamCalendarSharingMutation() {+ return useMutation(() => ({+ mutationFn: (sharing: CalendarSharing) =>+ throwOnErr(() => emailClient.setTeamCalendarSharing({ sharing })),+ onSuccess: resetTeamCalendarQueries,+ }));+}++export function useSetAvailabilityCalendarMutation() {+ return useMutation(() => ({+ mutationFn: (args: {+ calendarId: string;+ contributesToAvailability: boolean;+ }) =>+ throwOnErr(() =>+ emailClient.setAvailabilityCalendar(args.calendarId, {+ contributesToAvailability: args.contributesToAvailability,+ })+ ),+ onSuccess: resetTeamCalendarQueries,+ }));+}diff --git a/apps/web/src/lib/queries/calendar/tests/sync.test.ts b/apps/web/src/lib/queries/calendar/tests/sync.test.tsindex 289c4df831..4ff8f05282 100644--- a/apps/web/src/lib/queries/calendar/tests/sync.test.ts+++ b/apps/web/src/lib/queries/calendar/tests/sync.test.ts@@ -5,6 +5,11 @@ import { handleRefreshCalendar } from '../sync';const invalidateQueriesMock = vi.hoisted(() => vi.fn());const isMutatingMock = vi.hoisted(() => vi.fn());const invalidateCalendarOccurrencesMock = vi.hoisted(() => vi.fn());+const resetTeamCalendarQueriesMock = vi.hoisted(() => vi.fn());++vi.mock('../team-cache', () => ({+ resetTeamCalendarQueries: resetTeamCalendarQueriesMock,+}));vi.mock('../../client', () => ({queryClient: {@@ -30,6 +35,7 @@ describe('handleRefreshCalendar', () => {});expect(invalidateCalendarOccurrencesMock).toHaveBeenCalledTimes(1);+ expect(resetTeamCalendarQueriesMock).toHaveBeenCalledTimes(1);expect(invalidateQueriesMock).toHaveBeenCalledWith({queryKey: calendarKeys.invitations._def,});@@ -72,4 +78,10 @@ describe('handleRefreshCalendar', () => {expect(invalidateCalendarOccurrencesMock).not.toHaveBeenCalled();expect(invalidateQueriesMock).not.toHaveBeenCalled();});++ it('clears team projections on sharing changes without touching own optimistic events', () => {+ handleRefreshCalendar({ event: 'team_sharing_changed' });+ expect(resetTeamCalendarQueriesMock).toHaveBeenCalledTimes(1);+ expect(invalidateCalendarOccurrencesMock).not.toHaveBeenCalled();+ });});diff --git a/apps/web/src/lib/queries/calendar/tests/team-cache.test.ts b/apps/web/src/lib/queries/calendar/tests/team-cache.test.tsnew file mode 100644index 0000000000..3a9bc5c28d--- /dev/null+++ b/apps/web/src/lib/queries/calendar/tests/team-cache.test.ts@@ -0,0 +1,176 @@+import { QueryClient, QueryObserver } from '@tanstack/solid-query';+import { afterEach, describe, expect, it, vi } from 'vitest';+import { queryClient } from '../../client';+import { calendarKeys } from '../keys';+import {+ clearTeamCalendarQueries,+ ensureTeamCalendarExpiry,+ resetTeamCalendarQueries,+ resetTeamCalendarSession,+ subscribeToTeamCalendarReset,+ TEAM_CALENDAR_MAX_DATA_AGE_MS,+} from '../team-cache';+import { calendarTeamKeys } from '../team-keys';++vi.mock('../../client', () => ({+ queryClient: new QueryClient({+ defaultOptions: { queries: { retry: false } },+ }),+}));++describe('team authorization invalidation', () => {+ afterEach(() => {+ queryClient.clear();+ vi.useRealTimers();+ });++ it('removes already rendered data before a failing refetch settles', async () => {+ const queryKey = calendarTeamKeys.sharing({+ userId: 'alice',+ teamId: 'team',+ }).queryKey;+ queryClient.setQueryData(queryKey, { sharing: 'all' });+ const observer = new QueryObserver(queryClient, {+ queryKey,+ queryFn: async () => {+ throw new Error('revoked');+ },+ staleTime: Infinity,+ });+ const unsubscribe = observer.subscribe(() => {});+ const reset = resetTeamCalendarQueries();+ expect(observer.getCurrentResult().data).toBeUndefined();+ await reset;+ expect(observer.getCurrentResult().isError).toBe(true);+ expect(observer.getCurrentResult().data).toBeUndefined();+ unsubscribe();+ });++ it('purges all team scopes on logout while preserving own occurrences', () => {+ const first = calendarTeamKeys.sharing({+ userId: 'alice',+ teamId: 'one',+ }).queryKey;+ const second = calendarTeamKeys.sharing({+ userId: 'bob',+ teamId: 'two',+ }).queryKey;+ const own = calendarKeys.occurrences('alice', undefined).queryKey;+ queryClient.setQueryData(first, 'all');+ queryClient.setQueryData(second, 'none');+ queryClient.setQueryData(own, 'own');+ clearTeamCalendarQueries();+ expect(queryClient.getQueryData(first)).toBeUndefined();+ expect(queryClient.getQueryData(second)).toBeUndefined();+ expect(queryClient.getQueryData(own)).toBe('own');+ });++ it('resets mounted observers and detached selections synchronously without starting requests', () => {+ const queryKey = calendarTeamKeys.sharing({+ userId: 'alice',+ teamId: 'team',+ }).queryKey;+ queryClient.setQueryData(queryKey, { sharing: 'all' });+ const queryFn = vi.fn(async () => ({ sharing: 'none' }));+ const observer = new QueryObserver(queryClient, {+ queryKey,+ queryFn,+ staleTime: Infinity,+ });+ const unsubscribe = observer.subscribe(() => {});+ const closeSelection = vi.fn();+ const unsubscribeReset = subscribeToTeamCalendarReset(closeSelection);+ resetTeamCalendarSession();+ expect(observer.getCurrentResult().data).toBeUndefined();+ expect(closeSelection).toHaveBeenCalledOnce();+ expect(queryFn).not.toHaveBeenCalled();+ unsubscribeReset();+ unsubscribe();+ });++ it('expires a successful payload while a refetch hangs and rejects its late response', async () => {+ vi.useFakeTimers();+ ensureTeamCalendarExpiry();+ const queryKey = calendarTeamKeys.sharing({+ userId: 'alice',+ teamId: 'team',+ }).queryKey;+ const own = calendarKeys.occurrences('alice', undefined).queryKey;+ queryClient.setQueryData(queryKey, { sharing: 'all' });+ queryClient.setQueryData(own, 'own');+ let resolveRequest!: (data: { sharing: string }) => void;+ const observer = new QueryObserver(queryClient, {+ queryKey,+ queryFn: () =>+ new Promise<{ sharing: string }>((resolve) => {+ resolveRequest = resolve;+ }),+ staleTime: Infinity,+ });+ const unsubscribe = observer.subscribe(() => {});+ const closeSelection = vi.fn();+ const unsubscribeReset = subscribeToTeamCalendarReset(closeSelection);+ await vi.advanceTimersByTimeAsync(30_000);+ const refetch = observer.refetch();+ expect(observer.getCurrentResult().isFetching).toBe(true);+ await vi.advanceTimersByTimeAsync(TEAM_CALENDAR_MAX_DATA_AGE_MS - 30_001);+ expect(observer.getCurrentResult().data).toEqual({ sharing: 'all' });+ await vi.advanceTimersByTimeAsync(1);+ expect(observer.getCurrentResult().data).toBeUndefined();+ expect(closeSelection).toHaveBeenCalledOnce();+ resolveRequest({ sharing: 'all' });+ await refetch;+ expect(observer.getCurrentResult().data).toBeUndefined();+ expect(queryClient.getQueryData(own)).toBe('own');+ unsubscribeReset();+ unsubscribe();+ });++ it('bounds an initial request and grants a new lease only for a successful response', async () => {+ vi.useFakeTimers();+ ensureTeamCalendarExpiry();+ const queryKey = calendarTeamKeys.identity('alice').queryKey;+ let resolveRequest!: (data: string) => void;+ const observer = new QueryObserver(queryClient, {+ queryKey,+ queryFn: () =>+ new Promise<string>((resolve) => {+ resolveRequest = resolve;+ }),+ });+ const unsubscribe = observer.subscribe(() => {});+ expect(observer.getCurrentResult().isFetching).toBe(true);+ await vi.advanceTimersByTimeAsync(TEAM_CALENDAR_MAX_DATA_AGE_MS);+ expect(observer.getCurrentResult().fetchStatus).toBe('idle');+ resolveRequest('expired');+ await Promise.resolve();+ expect(observer.getCurrentResult().data).toBeUndefined();++ const refetch = observer.refetch();+ resolveRequest('fresh');+ await refetch;+ await vi.advanceTimersByTimeAsync(TEAM_CALENDAR_MAX_DATA_AGE_MS - 1);+ expect(observer.getCurrentResult().data).toBe('fresh');+ await vi.advanceTimersByTimeAsync(1);+ expect(observer.getCurrentResult().data).toBeUndefined();+ unsubscribe();+ });++ it('clears detached selections on authorization reset, not ordinary cache writes', async () => {+ const onReset = vi.fn();+ const unsubscribe = subscribeToTeamCalendarReset(onReset);+ const team = calendarTeamKeys.sharing({+ userId: 'alice',+ teamId: 'team',+ }).queryKey;+ const own = calendarKeys.occurrences('alice', undefined).queryKey;+ queryClient.setQueryData(team, { sharing: 'all' });+ queryClient.setQueryData(own, []);+ expect(onReset).not.toHaveBeenCalled();+ await queryClient.resetQueries({ queryKey: own });+ expect(onReset).not.toHaveBeenCalled();+ await resetTeamCalendarQueries();+ expect(onReset).toHaveBeenCalledOnce();+ unsubscribe();+ });+});diff --git a/apps/web/src/lib/queries/calendar/tests/team.test.ts b/apps/web/src/lib/queries/calendar/tests/team.test.tsnew file mode 100644index 0000000000..d533a0374b--- /dev/null+++ b/apps/web/src/lib/queries/calendar/tests/team.test.ts@@ -0,0 +1,143 @@+import { storageServiceClient } from '@service-storage/client';+import { err, ok } from 'neverthrow';+import { beforeEach, describe, expect, it, vi } from 'vitest';+import { fetchTeamCalendar, fetchTeamCalendarMembers } from '../team';+import { calendarTeamKeys } from '../team-keys';++vi.mock('@service-storage/client', () => ({+ storageServiceClient: { listTeamCalendar: vi.fn() },+}));+vi.mock('@service-auth/client', () => ({ authServiceClient: {} }));+vi.mock('@service-email/client', () => ({ emailClient: {} }));+vi.mock('../team-cache', () => ({ resetTeamCalendarQueries: vi.fn() }));++const range = {+ start: '2026-10-07T00:00:00Z',+ end: '2026-10-08T00:00:00Z',+ startDate: '2026-10-07',+ endDate: '2026-10-08',+};+const item = {+ id: 'opaque',+ ownerId: 'alice',+ kind: 'busy' as const,+ contributesToAvailability: true,+ time: {+ kind: 'timed' as const,+ startsAt: range.start,+ endsAt: range.end,+ timeZone: null,+ },+};++describe('team calendar query boundaries', () => {+ beforeEach(() => vi.clearAllMocks());++ it('partitions every policy and event query by viewer and team', () => {+ const first = { userId: 'alice', teamId: 'team-a' };+ const otherUser = { ...first, userId: 'bob' };+ const otherTeam = { ...first, teamId: 'team-b' };+ for (const key of [+ calendarTeamKeys.sharing,+ calendarTeamKeys.availabilityCalendars,+ ]) {+ expect(key(first).queryKey).not.toEqual(key(otherUser).queryKey);+ expect(key(first).queryKey).not.toEqual(key(otherTeam).queryKey);+ }+ expect(calendarTeamKeys.events(first, range).queryKey).not.toEqual(+ calendarTeamKeys.events(otherTeam, range).queryKey+ );+ });++ it('follows all pages and replaces a duplicate projection whole', async () => {+ const updated = { ...item, contributesToAvailability: false };+ vi.mocked(storageServiceClient.listTeamCalendar)+ .mockResolvedValueOnce(+ ok({ members: [], items: [item], nextCursor: 'cursor' })+ )+ .mockResolvedValueOnce(+ ok({ members: [], items: [updated], nextCursor: null })+ );+ const controller = new AbortController();+ expect((await fetchTeamCalendar(range, controller.signal)).items).toEqual([+ updated,+ ]);+ expect(storageServiceClient.listTeamCalendar).toHaveBeenLastCalledWith({+ start: range.start,+ end: range.end,+ cursor: 'cursor',+ limit: 500,+ signal: controller.signal,+ });+ });++ it('retains distinct source copies across pages without combining masking or availability', async () => {+ const followed = {+ ...item,+ id: 'opaque-followed-source',+ kind: 'details' as const,+ contributesToAvailability: false,+ details: {+ title: 'Shared calendar meeting',+ description: 'Visible on the followed source',+ location: null,+ conferenceUrl: null,+ organizerEmail: null,+ organizerName: null,+ attendees: [],+ calendarName: 'Followed calendar',+ },+ };+ const personal = { ...item, id: 'opaque-personal-source' };+ vi.mocked(storageServiceClient.listTeamCalendar)+ .mockResolvedValueOnce(+ ok({ members: [], items: [followed], nextCursor: 'next-source' })+ )+ .mockResolvedValueOnce(+ ok({ members: [], items: [personal], nextCursor: null })+ );++ const page = await fetchTeamCalendar(range);++ expect(page.items).toEqual([followed, personal]);+ expect(page.items[1]).not.toHaveProperty('details');+ });++ it('loads the roster without asking the server to scan source events', async () => {+ const members = [+ {+ userId: 'alice',+ sharing: 'busy_only' as const,+ coverage: 'ready' as const,+ },+ ];+ vi.mocked(storageServiceClient.listTeamCalendar).mockResolvedValueOnce(+ ok({ members, items: [], nextCursor: null })+ );+ const controller = new AbortController();++ expect(await fetchTeamCalendarMembers(controller.signal)).toEqual(members);+ expect(storageServiceClient.listTeamCalendar).toHaveBeenCalledTimes(1);+ expect(storageServiceClient.listTeamCalendar).toHaveBeenCalledWith({+ start: expect.stringMatching(/T00:00:00\.000Z$/),+ end: expect.stringMatching(/T00:00:00\.000Z$/),+ limit: 0,+ signal: controller.signal,+ });+ });++ it('rejects a partial range when access changes or continuation repeats', async () => {+ vi.mocked(storageServiceClient.listTeamCalendar)+ .mockResolvedValueOnce(+ ok({ members: [], items: [item], nextCursor: 'cursor' })+ )+ .mockResolvedValueOnce(+ err([{ code: 'FORBIDDEN' as const, message: 'Access changed' }])+ );+ await expect(fetchTeamCalendar(range)).rejects.toThrow();+ vi.mocked(storageServiceClient.listTeamCalendar).mockResolvedValue(+ ok({ members: [], items: [item], nextCursor: 'cursor' })+ );+ await expect(fetchTeamCalendar(range)).rejects.toThrow('repeated cursor');+ });+});diff --git a/apps/web/src/lib/service-clients/service-calendar/generated/client.ts b/apps/web/src/lib/service-clients/service-calendar/generated/client.tsindex 795cafbed9..541d27e7d2 100644--- a/apps/web/src/lib/service-clients/service-calendar/generated/client.ts+++ b/apps/web/src/lib/service-clients/service-calendar/generated/client.ts@@ -5,15 +5,102 @@* OpenAPI spec version: 0.1.0*/import type {+ AvailabilityCalendarBody,+ AvailabilityCalendarsResponse,CalendarEvent,CalendarMutationApiError,CreateCalendarEventRequest,DeleteCalendarEventParams,ListCalendarsResponse,RsvpCalendarEventRequest,+ TeamCalendarSharingBody,UpdateCalendarEventRequest,} from './schemas';+/**+ * @summary List calendars and their personal-availability inclusion.+ */+export type getAvailabilityCalendarsResponse200 = {+ data: AvailabilityCalendarsResponse;+ status: 200;+};++export type getAvailabilityCalendarsResponseSuccess =+ getAvailabilityCalendarsResponse200 & {+ headers: Headers;+ };++export type getAvailabilityCalendarsResponse =+ getAvailabilityCalendarsResponseSuccess;++export const getGetAvailabilityCalendarsUrl = () => {+ return `/availability-calendars`;+};++export const getAvailabilityCalendars = async (+ options?: RequestInit+): Promise<getAvailabilityCalendarsResponse> => {+ const res = await fetch(getGetAvailabilityCalendarsUrl(), {+ ...options,+ method: 'GET',+ });++ const body = [204, 205, 304].includes(res.status) ? null : await res.text();++ const data: getAvailabilityCalendarsResponse['data'] = body+ ? JSON.parse(body)+ : {};+ return {+ data,+ status: res.status,+ headers: res.headers,+ } as getAvailabilityCalendarsResponse;+};++/**+ * @summary Change which source calendars normally occupy this user's time.+ */+export type setAvailabilityCalendarResponse204 = {+ data: void;+ status: 204;+};++export type setAvailabilityCalendarResponseSuccess =+ setAvailabilityCalendarResponse204 & {+ headers: Headers;+ };++export type setAvailabilityCalendarResponse =+ setAvailabilityCalendarResponseSuccess;++export const getSetAvailabilityCalendarUrl = (calendarId: string) => {+ return `/availability-calendars/${calendarId}`;+};++export const setAvailabilityCalendar = async (+ calendarId: string,+ availabilityCalendarBody: AvailabilityCalendarBody,+ options?: RequestInit+): Promise<setAvailabilityCalendarResponse> => {+ const res = await fetch(getSetAvailabilityCalendarUrl(calendarId), {+ ...options,+ method: 'PUT',+ headers: { 'Content-Type': 'application/json', ...options?.headers },+ body: JSON.stringify(availabilityCalendarBody),+ });++ const body = [204, 205, 304].includes(res.status) ? null : await res.text();++ const data: setAvailabilityCalendarResponse['data'] = body+ ? JSON.parse(body)+ : {};+ return {+ data,+ status: res.status,+ headers: res.headers,+ } as setAvailabilityCalendarResponse;+};+/*** @summary List the requester's visible calendars for pickers and filters.*/@@ -434,3 +521,78 @@ export const healthHandler = async (headers: res.headers,} as healthHandlerResponse;};++/**+ * @summary Read the authenticated user's sharing choice.+ */+export type getTeamSharingResponse200 = {+ data: TeamCalendarSharingBody;+ status: 200;+};++export type getTeamSharingResponseSuccess = getTeamSharingResponse200 & {+ headers: Headers;+};++export type getTeamSharingResponse = getTeamSharingResponseSuccess;++export const getGetTeamSharingUrl = () => {+ return `/team-sharing`;+};++export const getTeamSharing = async (+ options?: RequestInit+): Promise<getTeamSharingResponse> => {+ const res = await fetch(getGetTeamSharingUrl(), {+ ...options,+ method: 'GET',+ });++ const body = [204, 205, 304].includes(res.status) ? null : await res.text();++ const data: getTeamSharingResponse['data'] = body ? JSON.parse(body) : {};+ return {+ data,+ status: res.status,+ headers: res.headers,+ } as getTeamSharingResponse;+};++/**+ * @summary Set the authenticated user's sharing choice.+ */+export type setTeamSharingResponse200 = {+ data: TeamCalendarSharingBody;+ status: 200;+};++export type setTeamSharingResponseSuccess = setTeamSharingResponse200 & {+ headers: Headers;+};++export type setTeamSharingResponse = setTeamSharingResponseSuccess;++export const getSetTeamSharingUrl = () => {+ return `/team-sharing`;+};++export const setTeamSharing = async (+ teamCalendarSharingBody: TeamCalendarSharingBody,+ options?: RequestInit+): Promise<setTeamSharingResponse> => {+ const res = await fetch(getSetTeamSharingUrl(), {+ ...options,+ method: 'PUT',+ headers: { 'Content-Type': 'application/json', ...options?.headers },+ body: JSON.stringify(teamCalendarSharingBody),+ });++ const body = [204, 205, 304].includes(res.status) ? null : await res.text();++ const data: setTeamSharingResponse['data'] = body ? JSON.parse(body) : {};+ return {+ data,+ status: res.status,+ headers: res.headers,+ } as setTeamSharingResponse;+};diff --git a/apps/web/src/lib/service-clients/service-calendar/generated/schemas/availabilityCalendar.ts b/apps/web/src/lib/service-clients/service-calendar/generated/schemas/availabilityCalendar.tsnew file mode 100644index 0000000000..1358b29c9a--- /dev/null+++ b/apps/web/src/lib/service-clients/service-calendar/generated/schemas/availabilityCalendar.ts@@ -0,0 +1,20 @@+/**+ * Generated by orval v7.21.0 🍺+ * Do not edit manually.+ * calendar_service+ * OpenAPI spec version: 0.1.0+ */++/**+ * Per-user inclusion of a source calendar in personal availability.+ */+export interface AvailabilityCalendar {+ /** Visible source calendar. */+ calendarId: string;+ /** Whether its events normally block the user's time. */+ contributesToAvailability: boolean;+ /** Whether this is the connected account's primary calendar. */+ isPrimary: boolean;+ /** Source name. */+ name: string;+}diff --git a/apps/web/src/lib/service-clients/service-calendar/generated/schemas/availabilityCalendarBody.ts b/apps/web/src/lib/service-clients/service-calendar/generated/schemas/availabilityCalendarBody.tsnew file mode 100644index 0000000000..e5df297dff--- /dev/null+++ b/apps/web/src/lib/service-clients/service-calendar/generated/schemas/availabilityCalendarBody.ts@@ -0,0 +1,14 @@+/**+ * Generated by orval v7.21.0 🍺+ * Do not edit manually.+ * calendar_service+ * OpenAPI spec version: 0.1.0+ */++/**+ * Own-user source inclusion preference.+ */+export interface AvailabilityCalendarBody {+ /** Whether this calendar contributes to personal availability. */+ contributesToAvailability: boolean;+}diff --git a/apps/web/src/lib/service-clients/service-calendar/generated/schemas/availabilityCalendarsResponse.ts b/apps/web/src/lib/service-clients/service-calendar/generated/schemas/availabilityCalendarsResponse.tsnew file mode 100644index 0000000000..d0687a10c9--- /dev/null+++ b/apps/web/src/lib/service-clients/service-calendar/generated/schemas/availabilityCalendarsResponse.ts@@ -0,0 +1,15 @@+/**+ * Generated by orval v7.21.0 🍺+ * Do not edit manually.+ * calendar_service+ * OpenAPI spec version: 0.1.0+ */+import type { AvailabilityCalendar } from './availabilityCalendar';++/**+ * Source calendar settings returned to their viewer.+ */+export interface AvailabilityCalendarsResponse {+ /** Directly visible source calendars. */+ calendars: AvailabilityCalendar[];+}diff --git a/apps/web/src/lib/service-clients/service-calendar/generated/schemas/index.ts b/apps/web/src/lib/service-clients/service-calendar/generated/schemas/index.tsindex 50c757549f..f3558ec7de 100644--- a/apps/web/src/lib/service-clients/service-calendar/generated/schemas/index.ts+++ b/apps/web/src/lib/service-clients/service-calendar/generated/schemas/index.ts@@ -6,6 +6,9 @@*/export * from './attendeeResponseStatus';+export * from './availabilityCalendar';+export * from './availabilityCalendarBody';+export * from './availabilityCalendarsResponse';export * from './calendarAttendee';export * from './calendarAttendeeComment';export * from './calendarAttendeeDisplayName';@@ -63,11 +66,15 @@ export * from './outOfOfficePropertiesDeclineMessage';export * from './refreshCalendarEvent';export * from './refreshCalendarEventOneOf';export * from './refreshCalendarEventOneOfEvent';+export * from './refreshCalendarEventOneOfThree';+export * from './refreshCalendarEventOneOfThreeEvent';export * from './rsvpCalendarEventRequest';export * from './rsvpCalendarEventRequestCalendarId';export * from './rsvpCalendarEventRequestRecurrenceId';export * from './rsvpCalendarEventRequestRespondingEmail';export * from './rsvpCalendarEventRequestScope';+export * from './teamCalendarSharing';+export * from './teamCalendarSharingBody';export * from './updateCalendarEventRequest';export * from './updateCalendarEventRequestAttendees';export * from './updateCalendarEventRequestCalendarId';diff --git a/apps/web/src/lib/service-clients/service-calendar/generated/schemas/refreshCalendarEvent.ts b/apps/web/src/lib/service-clients/service-calendar/generated/schemas/refreshCalendarEvent.tsindex d448fac44c..d346a8d0d9 100644--- a/apps/web/src/lib/service-clients/service-calendar/generated/schemas/refreshCalendarEvent.ts+++ b/apps/web/src/lib/service-clients/service-calendar/generated/schemas/refreshCalendarEvent.ts@@ -5,8 +5,11 @@* OpenAPI spec version: 0.1.0*/import type { RefreshCalendarEventOneOf } from './refreshCalendarEventOneOf';+import type { RefreshCalendarEventOneOfThree } from './refreshCalendarEventOneOfThree';/*** Realtime signal that a connected inbox's calendar projection changed.*/-export type RefreshCalendarEvent = RefreshCalendarEventOneOf;+export type RefreshCalendarEvent =+ | RefreshCalendarEventOneOf+ | RefreshCalendarEventOneOfThree;diff --git a/apps/web/src/lib/service-clients/service-calendar/generated/schemas/refreshCalendarEventOneOfThree.ts b/apps/web/src/lib/service-clients/service-calendar/generated/schemas/refreshCalendarEventOneOfThree.tsnew file mode 100644index 0000000000..a7947f5285--- /dev/null+++ b/apps/web/src/lib/service-clients/service-calendar/generated/schemas/refreshCalendarEventOneOfThree.ts@@ -0,0 +1,14 @@+/**+ * Generated by orval v7.21.0 🍺+ * Do not edit manually.+ * calendar_service+ * OpenAPI spec version: 0.1.0+ */+import type { RefreshCalendarEventOneOfThreeEvent } from './refreshCalendarEventOneOfThreeEvent';++/**+ * A team entitlement changed; discard cached team projections before refetching.+ */+export type RefreshCalendarEventOneOfThree = {+ event: RefreshCalendarEventOneOfThreeEvent;+};diff --git a/apps/web/src/lib/service-clients/service-calendar/generated/schemas/refreshCalendarEventOneOfThreeEvent.ts b/apps/web/src/lib/service-clients/service-calendar/generated/schemas/refreshCalendarEventOneOfThreeEvent.tsnew file mode 100644index 0000000000..c95e1beb10--- /dev/null+++ b/apps/web/src/lib/service-clients/service-calendar/generated/schemas/refreshCalendarEventOneOfThreeEvent.ts@@ -0,0 +1,14 @@+/**+ * Generated by orval v7.21.0 🍺+ * Do not edit manually.+ * calendar_service+ * OpenAPI spec version: 0.1.0+ */++export type RefreshCalendarEventOneOfThreeEvent =+ (typeof RefreshCalendarEventOneOfThreeEvent)[keyof typeof RefreshCalendarEventOneOfThreeEvent];++// eslint-disable-next-line @typescript-eslint/no-redeclare+export const RefreshCalendarEventOneOfThreeEvent = {+ team_sharing_changed: 'team_sharing_changed',+} as const;diff --git a/apps/web/src/lib/service-clients/service-calendar/generated/schemas/teamCalendarSharing.ts b/apps/web/src/lib/service-clients/service-calendar/generated/schemas/teamCalendarSharing.tsnew file mode 100644index 0000000000..d9badc391b--- /dev/null+++ b/apps/web/src/lib/service-clients/service-calendar/generated/schemas/teamCalendarSharing.ts@@ -0,0 +1,19 @@+/**+ * Generated by orval v7.21.0 🍺+ * Do not edit manually.+ * calendar_service+ * OpenAPI spec version: 0.1.0+ */++/**+ * What a user exposes through their team membership.+ */+export type TeamCalendarSharing =+ (typeof TeamCalendarSharing)[keyof typeof TeamCalendarSharing];++// eslint-disable-next-line @typescript-eslint/no-redeclare+export const TeamCalendarSharing = {+ all: 'all',+ busy_only: 'busy_only',+ none: 'none',+} as const;diff --git a/apps/web/src/lib/service-clients/service-calendar/generated/schemas/teamCalendarSharingBody.ts b/apps/web/src/lib/service-clients/service-calendar/generated/schemas/teamCalendarSharingBody.tsnew file mode 100644index 0000000000..7e100afbc7--- /dev/null+++ b/apps/web/src/lib/service-clients/service-calendar/generated/schemas/teamCalendarSharingBody.ts@@ -0,0 +1,15 @@+/**+ * Generated by orval v7.21.0 🍺+ * Do not edit manually.+ * calendar_service+ * OpenAPI spec version: 0.1.0+ */+import type { TeamCalendarSharing } from './teamCalendarSharing';++/**+ * Own-user sharing preference.+ */+export interface TeamCalendarSharingBody {+ /** Busy-only is the default, including when no setting has been saved. */+ sharing: TeamCalendarSharing;+}diff --git a/apps/web/src/lib/service-clients/service-calendar/openapi.json b/apps/web/src/lib/service-clients/service-calendar/openapi.jsonindex 6a807ef493..6acb6ba900 100644--- a/apps/web/src/lib/service-clients/service-calendar/openapi.json+++ b/apps/web/src/lib/service-clients/service-calendar/openapi.json@@ -9,6 +9,58 @@"version": "0.1.0"},"paths": {+ "/availability-calendars": {+ "get": {+ "tags": ["calendar_events"],+ "summary": "List calendars and their personal-availability inclusion.",+ "operationId": "get_availability_calendars",+ "responses": {+ "200": {+ "description": "",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/AvailabilityCalendarsResponse"+ }+ }+ }+ }+ }+ }+ },+ "/availability-calendars/{calendar_id}": {+ "put": {+ "tags": ["calendar_events"],+ "summary": "Change which source calendars normally occupy this user's time.",+ "operationId": "set_availability_calendar",+ "parameters": [+ {+ "name": "calendar_id",+ "in": "path",+ "required": true,+ "schema": {+ "type": "string",+ "format": "uuid"+ }+ }+ ],+ "requestBody": {+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/AvailabilityCalendarBody"+ }+ }+ },+ "required": true+ },+ "responses": {+ "204": {+ "description": ""+ }+ }+ }+ },"/calendars": {"get": {"tags": ["calendar_events"],@@ -402,6 +454,52 @@}}}+ },+ "/team-sharing": {+ "get": {+ "tags": ["calendar_events"],+ "summary": "Read the authenticated user's sharing choice.",+ "operationId": "get_team_sharing",+ "responses": {+ "200": {+ "description": "",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/TeamCalendarSharingBody"+ }+ }+ }+ }+ }+ },+ "put": {+ "tags": ["calendar_events"],+ "summary": "Set the authenticated user's sharing choice.",+ "operationId": "set_team_sharing",+ "requestBody": {+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/TeamCalendarSharingBody"+ }+ }+ },+ "required": true+ },+ "responses": {+ "200": {+ "description": "",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/TeamCalendarSharingBody"+ }+ }+ }+ }+ }+ }}},"components": {@@ -411,6 +509,60 @@"description": "RSVP state for an attendee.","enum": ["needs_action", "accepted", "declined", "tentative"]},+ "AvailabilityCalendar": {+ "type": "object",+ "description": "Per-user inclusion of a source calendar in personal availability.",+ "required": [+ "calendarId",+ "name",+ "contributesToAvailability",+ "isPrimary"+ ],+ "properties": {+ "calendarId": {+ "type": "string",+ "format": "uuid",+ "description": "Visible source calendar."+ },+ "contributesToAvailability": {+ "type": "boolean",+ "description": "Whether its events normally block the user's time."+ },+ "isPrimary": {+ "type": "boolean",+ "description": "Whether this is the connected account's primary calendar."+ },+ "name": {+ "type": "string",+ "description": "Source name."+ }+ }+ },+ "AvailabilityCalendarBody": {+ "type": "object",+ "description": "Own-user source inclusion preference.",+ "required": ["contributesToAvailability"],+ "properties": {+ "contributesToAvailability": {+ "type": "boolean",+ "description": "Whether this calendar contributes to personal availability."+ }+ }+ },+ "AvailabilityCalendarsResponse": {+ "type": "object",+ "description": "Source calendar settings returned to their viewer.",+ "required": ["calendars"],+ "properties": {+ "calendars": {+ "type": "array",+ "items": {+ "$ref": "#/components/schemas/AvailabilityCalendar"+ },+ "description": "Directly visible source calendars."+ }+ }+ },"CalendarAttendee": {"type": "object","description": "An attendee on a calendar event.",@@ -1005,6 +1157,17 @@"description": "Connected inbox whose calendars changed."}}+ },+ {+ "type": "object",+ "description": "A team entitlement changed; discard cached team projections before refetching.",+ "required": ["event"],+ "properties": {+ "event": {+ "type": "string",+ "enum": ["team_sharing_changed"]+ }+ }}],"description": "Realtime signal that a connected inbox's calendar projection changed."@@ -1044,6 +1207,22 @@}}},+ "TeamCalendarSharing": {+ "type": "string",+ "description": "What a user exposes through their team membership.",+ "enum": ["all", "busy_only", "none"]+ },+ "TeamCalendarSharingBody": {+ "type": "object",+ "description": "Own-user sharing preference.",+ "required": ["sharing"],+ "properties": {+ "sharing": {+ "$ref": "#/components/schemas/TeamCalendarSharing",+ "description": "Busy-only is the default, including when no setting has been saved."+ }+ }+ },"UpdateCalendarEventRequest": {"type": "object","description": "Request body patching an event; omitted fields are left untouched.",diff --git a/apps/web/src/lib/service-clients/service-cognition/generated/tools/schemas.ts b/apps/web/src/lib/service-clients/service-cognition/generated/tools/schemas.tsindex f256961db9..2f6fe11c34 100644--- a/apps/web/src/lib/service-clients/service-cognition/generated/tools/schemas.ts+++ b/apps/web/src/lib/service-clients/service-cognition/generated/tools/schemas.ts@@ -7854,6 +7854,88 @@ export const GetEntityPropertiesResponse = z.object({summary: z.string(),});+export const GetTeamAvailability = z.object({+ start: z.string().datetime({ offset: true }),+ end: z.string().datetime({ offset: true }),+ userIds: z.union([z.array(z.string()), z.null()]).optional(),+});++export const TeamAvailability = z.object({+ start: z.string().datetime({ offset: true }),+ end: z.string().datetime({ offset: true }),+ members: z.array(+ z.object({+ userId: z.string(),+ busy: z.array(+ z.object({+ start: z.string().datetime({ offset: true }),+ end: z.string().datetime({ offset: true }),+ })+ ),+ coverage: z.any().superRefine((x, ctx) => {+ const schemas = [z.literal('complete'), z.literal('unknown')];+ const errors = schemas.reduce<z.ZodError[]>(+ (errors, schema) =>+ ((result) => (result.error ? [...errors, result.error] : errors))(+ schema.safeParse(x)+ ),+ []+ );+ if (schemas.length - errors.length !== 1) {+ ctx.addIssue({+ path: ctx.path,+ code: 'invalid_union',+ unionErrors: errors,+ message: 'Invalid input: Should pass single schema',+ });+ }+ }),+ unknownReasons: z.array(+ z.any().superRefine((x, ctx) => {+ const schemas = [+ z.literal('hidden'),+ z.literal('unavailable'),+ z.literal('truncated'),+ z.literal('missing_time_zone'),+ z.literal('invalid_time_zone'),+ z.literal('invalid_interval'),+ z.literal('conflicting_copies'),+ ];+ const errors = schemas.reduce<z.ZodError[]>(+ (errors, schema) =>+ ((result) => (result.error ? [...errors, result.error] : errors))(+ schema.safeParse(x)+ ),+ []+ );+ if (schemas.length - errors.length !== 1) {+ ctx.addIssue({+ path: ctx.path,+ code: 'invalid_union',+ unionErrors: errors,+ message: 'Invalid input: Should pass single schema',+ });+ }+ })+ ),+ })+ ),+ freeWindows: z+ .union([+ z.array(+ z.object({+ start: z.string().datetime({ offset: true }),+ end: z.string().datetime({ offset: true }),+ })+ ),+ z.null(),+ ])+ .optional(),+ unknownUserIds: z.array(z.string()),+ complete: z.boolean(),+ summary: z.string(),+});+export const GetThread = z.object({threadId: z.string().uuid(),limit: z.union([z.number().int(), z.null()]).optional(),diff --git a/apps/web/src/lib/service-clients/service-cognition/generated/tools/tool.ts b/apps/web/src/lib/service-clients/service-cognition/generated/tools/tool.tsindex ddef50c033..3f547002a9 100644--- a/apps/web/src/lib/service-clients/service-cognition/generated/tools/tool.ts+++ b/apps/web/src/lib/service-clients/service-cognition/generated/tools/tool.ts@@ -138,6 +138,10 @@ type ToolParserMap = {call: types.GetEntityProperties;response: types.GetEntityPropertiesResponse;};+ GetTeamAvailability: {+ call: types.GetTeamAvailability;+ response: types.TeamAvailability;+ };GetThread: { call: types.GetThread; response: types.GetThreadResponse };ImportNotionPage: {call: types.ImportNotionPage;@@ -495,6 +499,10 @@ const toolParserMap = {call: schemas.GetEntityProperties,response: schemas.GetEntityPropertiesResponse,},+ GetTeamAvailability: {+ call: schemas.GetTeamAvailability,+ response: schemas.TeamAvailability,+ },GetThread: { call: schemas.GetThread, response: schemas.GetThreadResponse },ImportNotionPage: {call: schemas.ImportNotionPage,@@ -890,6 +898,10 @@ type ToolDataMap = {call: types.GetEntityProperties;response: types.GetEntityPropertiesResponse;};+ GetTeamAvailability: {+ call: types.GetTeamAvailability;+ response: types.TeamAvailability;+ };GetThread: { call: types.GetThread; response: types.GetThreadResponse };ImportNotionPage: {call: types.ImportNotionPage;diff --git a/apps/web/src/lib/service-clients/service-cognition/generated/tools/types.ts b/apps/web/src/lib/service-clients/service-cognition/generated/tools/types.tsindex 03d4b90a5e..a647f3a0c1 100644--- a/apps/web/src/lib/service-clients/service-cognition/generated/tools/types.ts+++ b/apps/web/src/lib/service-clients/service-cognition/generated/tools/types.ts@@ -3347,6 +3347,21 @@ export type ImageReferenceInput =id: string;type: 'staticFile';};+/**+ * Whether missing busy blocks can safely be interpreted as free time.+ */+export type AvailabilityCoverage = 'complete' | 'unknown';+/**+ * Why a person's unoccupied intervals cannot establish availability.+ */+export type AvailabilityUnknownReason =+ | 'hidden'+ | 'unavailable'+ | 'truncated'+ | 'missing_time_zone'+ | 'invalid_time_zone'+ | 'invalid_interval'+ | 'conflicting_copies';/*** Entity types that can be returned by the list entities AI tool.*/@@ -8477,6 +8492,89 @@ export interface ToolPropertyOption {*/displayValue: string;}+/**+ * Check personal busy time for you and your current teammates in a bounded UTC time window. Always includes you, even when userIds selects particular teammates. Omit userIds for the whole team, or use ids from ListTeamMembers for specific people. An empty list checks only you. Returns merged busy intervals without event titles, plus coverage and unknown reasons. Subscribed coworkers' events do not block a person's time unless they attend or included that calendar. Common freeWindows are present only when every requested person's data is complete and current. When freeWindows is absent, report uncertainty and never infer free time from missing busy blocks. Free windows cover the requested range only; working hours are not applied. Prefer a day or a week; the maximum is 370 days within one year past to two years future. This tool grants no Google Calendar access and does not invite, RSVP, or modify events.+ */+export interface GetTeamAvailability {+ /**+ * Inclusive start, RFC 3339 UTC (for example 2026-10-07T09:00:00Z).+ */+ start: string;+ /**+ * Exclusive end, RFC 3339 UTC. Must be later than start.+ */+ end: string;+ /**+ * At most 100 Macro user ids from ListTeamMembers. Omit for the whole team; an empty list checks only you. Unknown ids never expand access and suppress common free windows.+ */+ userIds?: string[] | null;+}+/**+ * Availability for exactly the members selected by the domain service.+ */+export interface TeamAvailability {+ /**+ * Inclusive requested start.+ */+ start: string;+ /**+ * Exclusive requested end.+ */+ end: string;+ /**+ * Included people, always including the requester.+ */+ members: TeamMemberAvailability[];+ /**+ * Common calendar gaps for every included person, present only with+ * complete coverage. These are not working-hours or booking guarantees.+ */+ freeWindows?: AvailabilityInterval[] | null;+ /**+ * Requested identifiers without a current team relationship. No profile+ * or calendar data about those identifiers is disclosed.+ */+ unknownUserIds: string[];+ /**+ * True only when all requested people and source intervals were covered.+ */+ complete: boolean;+ /**+ * A concise explanation that does not overstate incomplete results.+ */+ summary: string;+}+/**+ * Busy time and confidence for one explicitly included person.+ */+export interface TeamMemberAvailability {+ /**+ * Macro identifier of the included person.+ */+ userId: string;+ /**+ * Merged known busy intervals clipped to the requested range.+ */+ busy: AvailabilityInterval[];+ coverage: AvailabilityCoverage;+ /**+ * Reasons gaps in the busy intervals cannot be called free.+ */+ unknownReasons: AvailabilityUnknownReason[];+}+/**+ * An exact, half-open interval of UTC instants, without event metadata.+ */+export interface AvailabilityInterval {+ /**+ * Inclusive start.+ */+ start: string;+ /**+ * Exclusive end.+ */+ end: string;+}/*** Retrieve an email thread and its messages. Returns the thread metadata, the labels applied to the thread (e.g. INBOX, UNREAD, STARRED, and any custom labels), and message contents including sender, recipients, subject, body text, and the labels on each individual message. Use this to read the contents of a specific email conversation or to see which labels a thread or message has.*/diff --git a/apps/web/src/lib/service-clients/service-email/client.ts b/apps/web/src/lib/service-clients/service-email/client.tsindex 877ced3d6b..8905c8964b 100644--- a/apps/web/src/lib/service-clients/service-email/client.ts+++ b/apps/web/src/lib/service-clients/service-email/client.ts@@ -12,7 +12,10 @@ import type {RsvpCalendarEventRequest,UpdateCalendarEventRequest,} from '@service-calendar/generated/schemas';+import type { AvailabilityCalendarBody } from '@service-calendar/generated/schemas/availabilityCalendarBody';+import type { AvailabilityCalendarsResponse } from '@service-calendar/generated/schemas/availabilityCalendarsResponse';import { CalendarMutationErrorCode } from '@service-calendar/generated/schemas/calendarMutationErrorCode';+import type { TeamCalendarSharingBody } from '@service-calendar/generated/schemas/teamCalendarSharingBody';import type { Result } from 'neverthrow';import type {AddDraftAttachmentRequest,@@ -618,6 +621,37 @@ export const emailClient = {method: 'GET',});},++ async getTeamCalendarSharing(signal?: AbortSignal) {+ return fetchWithToken<TeamCalendarSharingBody>(+ `${calendarHost}/team-sharing`,+ { method: 'GET', signal }+ );+ },++ async setTeamCalendarSharing(body: TeamCalendarSharingBody) {+ return fetchWithToken<TeamCalendarSharingBody>(+ `${calendarHost}/team-sharing`,+ { method: 'PUT', body: JSON.stringify(body) }+ );+ },++ async getAvailabilityCalendars(signal?: AbortSignal) {+ return fetchWithToken<AvailabilityCalendarsResponse>(+ `${calendarHost}/availability-calendars`,+ { method: 'GET', signal }+ );+ },++ async setAvailabilityCalendar(+ calendarId: string,+ body: AvailabilityCalendarBody+ ) {+ return fetchWithToken<EmptyResponse>(+ `${calendarHost}/availability-calendars/${encodeURIComponent(calendarId)}`,+ { method: 'PUT', body: JSON.stringify(body) }+ );+ },async createCalendarEvent(args: CreateCalendarEventRequest) {return fetchWithToken<CalendarEvent, CalendarMutationErrorCode>(`${calendarHost}/events`,diff --git a/apps/web/src/lib/service-clients/service-storage/client.ts b/apps/web/src/lib/service-clients/service-storage/client.tsindex 4f92a6c26a..222014e36c 100644--- a/apps/web/src/lib/service-clients/service-storage/client.ts+++ b/apps/web/src/lib/service-clients/service-storage/client.ts@@ -168,6 +168,7 @@ import type { StorageRowsQuery } from './generated/schemas/storageRowsQuery';import type { StoredGithubPullRequest } from './generated/schemas/storedGithubPullRequest';import type { SyncServiceVersionID } from './generated/schemas/syncServiceVersionID';import type { TableDetail } from './generated/schemas/tableDetail';+import type { TeamCalendarPage } from './generated/schemas/teamCalendarPage';import type { TeamOutOfOfficeResponse } from './generated/schemas/teamOutOfOfficeResponse';import type { TypedSuccessResponse } from './generated/schemas/typedSuccessResponse';import type { UpdateAgentRequest } from './generated/schemas/updateAgentRequest';@@ -581,6 +582,22 @@ export const storageServiceClient = {).map((result) => result);},+ async listTeamCalendar(args: {+ start: string;+ end: string;+ cursor?: string;+ limit?: number;+ signal?: AbortSignal;+ }) {+ const params = new URLSearchParams({ start: args.start, end: args.end });+ if (args.cursor) params.set('cursor', args.cursor);+ if (args.limit !== undefined) params.set('limit', String(args.limit));+ return dssFetch<TeamCalendarPage>(+ `/calendar-events/team?${params.toString()}`,+ { method: 'GET', signal: args.signal }+ );+ },+async getBatchCalendarEventPreviews(args: CalendarMentionPreviewRequest) {return (await dssFetch<CalendarMentionPreviewResponse>(diff --git a/apps/web/src/lib/service-clients/service-storage/generated/schemas/index.ts b/apps/web/src/lib/service-clients/service-storage/generated/schemas/index.tsindex 4d3318007a..d12def2cb2 100644--- a/apps/web/src/lib/service-clients/service-storage/generated/schemas/index.ts+++ b/apps/web/src/lib/service-clients/service-storage/generated/schemas/index.ts@@ -1130,6 +1130,7 @@ export * from './listFavoritesParams';export * from './listFormsParams';export * from './listOccurrencesParams';export * from './listSlackImportsParams';+export * from './listTeamCalendarParams';export * from './listTeamOutOfOfficeParams';export * from './listWebhooksResponse';export * from './locationResponseData';@@ -1836,6 +1837,24 @@ export * from './tallyValueOneOfThree';export * from './tallyValueOneOfThreeKind';export * from './taskFilters';export * from './taskFiltersIncludeCbmAtmNc';+export * from './teamCalendarContent';+export * from './teamCalendarContentOneOf';+export * from './teamCalendarContentOneOfKind';+export * from './teamCalendarContentOneOfThree';+export * from './teamCalendarContentOneOfThreeKind';+export * from './teamCalendarCoverage';+export * from './teamCalendarDetails';+export * from './teamCalendarDetailsConferenceUrl';+export * from './teamCalendarDetailsDescription';+export * from './teamCalendarDetailsLocation';+export * from './teamCalendarDetailsOrganizerEmail';+export * from './teamCalendarDetailsOrganizerName';+export * from './teamCalendarItem';+export * from './teamCalendarItemAllOf';+export * from './teamCalendarMember';+export * from './teamCalendarPage';+export * from './teamCalendarPageNextCursor';+export * from './teamCalendarSharing';export * from './teamOutOfOfficeItem';export * from './teamOutOfOfficeItemTitle';export * from './teamOutOfOfficeResponse';diff --git a/apps/web/src/lib/service-clients/service-storage/generated/schemas/listTeamCalendarParams.ts b/apps/web/src/lib/service-clients/service-storage/generated/schemas/listTeamCalendarParams.tsnew file mode 100644index 0000000000..c0cd7eb3e1--- /dev/null+++ b/apps/web/src/lib/service-clients/service-storage/generated/schemas/listTeamCalendarParams.ts@@ -0,0 +1,26 @@+/**+ * Generated by orval v7.21.0 🍺+ * Do not edit manually.+ * document_storage_service+ * OpenAPI spec version: 0.1.0+ */++export type ListTeamCalendarParams = {+ /**+ * Inclusive instant.+ */+ start: string;+ /**+ * Exclusive instant.+ */+ end: string;+ /**+ * Continuation returned by the preceding page.+ */+ cursor?: string | null;+ /**+ * Maximum source occurrences, at most 2,000. Zero returns the roster only.+ * @minimum 0+ */+ limit?: number | null;+};diff --git a/apps/web/src/lib/service-clients/service-storage/generated/schemas/teamCalendarContent.ts b/apps/web/src/lib/service-clients/service-storage/generated/schemas/teamCalendarContent.tsnew file mode 100644index 0000000000..d7e9fc4f46--- /dev/null+++ b/apps/web/src/lib/service-clients/service-storage/generated/schemas/teamCalendarContent.ts@@ -0,0 +1,15 @@+/**+ * Generated by orval v7.21.0 🍺+ * Do not edit manually.+ * document_storage_service+ * OpenAPI spec version: 0.1.0+ */+import type { TeamCalendarContentOneOf } from './teamCalendarContentOneOf';+import type { TeamCalendarContentOneOfThree } from './teamCalendarContentOneOfThree';++/**+ * Disjoint busy/detail shapes prevent new event fields leaking by default.+ */+export type TeamCalendarContent =+ | TeamCalendarContentOneOf+ | TeamCalendarContentOneOfThree;diff --git a/apps/web/src/lib/service-clients/service-storage/generated/schemas/teamCalendarContentOneOf.ts b/apps/web/src/lib/service-clients/service-storage/generated/schemas/teamCalendarContentOneOf.tsnew file mode 100644index 0000000000..c7968d59ae--- /dev/null+++ b/apps/web/src/lib/service-clients/service-storage/generated/schemas/teamCalendarContentOneOf.ts@@ -0,0 +1,14 @@+/**+ * Generated by orval v7.21.0 🍺+ * Do not edit manually.+ * document_storage_service+ * OpenAPI spec version: 0.1.0+ */+import type { TeamCalendarContentOneOfKind } from './teamCalendarContentOneOfKind';++/**+ * No provider or event metadata.+ */+export type TeamCalendarContentOneOf = {+ kind: TeamCalendarContentOneOfKind;+};diff --git a/apps/web/src/lib/service-clients/service-storage/generated/schemas/teamCalendarContentOneOfKind.ts b/apps/web/src/lib/service-clients/service-storage/generated/schemas/teamCalendarContentOneOfKind.tsnew file mode 100644index 0000000000..ae719145df--- /dev/null+++ b/apps/web/src/lib/service-clients/service-storage/generated/schemas/teamCalendarContentOneOfKind.ts@@ -0,0 +1,14 @@+/**+ * Generated by orval v7.21.0 🍺+ * Do not edit manually.+ * document_storage_service+ * OpenAPI spec version: 0.1.0+ */++export type TeamCalendarContentOneOfKind =+ (typeof TeamCalendarContentOneOfKind)[keyof typeof TeamCalendarContentOneOfKind];++// eslint-disable-next-line @typescript-eslint/no-redeclare+export const TeamCalendarContentOneOfKind = {+ busy: 'busy',+} as const;diff --git a/apps/web/src/lib/service-clients/service-storage/generated/schemas/teamCalendarContentOneOfThree.ts b/apps/web/src/lib/service-clients/service-storage/generated/schemas/teamCalendarContentOneOfThree.tsnew file mode 100644index 0000000000..9ae63adc54--- /dev/null+++ b/apps/web/src/lib/service-clients/service-storage/generated/schemas/teamCalendarContentOneOfThree.ts@@ -0,0 +1,18 @@+/**+ * Generated by orval v7.21.0 🍺+ * Do not edit manually.+ * document_storage_service+ * OpenAPI spec version: 0.1.0+ */++import type { TeamCalendarContentOneOfThreeKind } from './teamCalendarContentOneOfThreeKind';+import type { TeamCalendarDetails } from './teamCalendarDetails';++/**+ * Explicitly authorized source content.+ */+export type TeamCalendarContentOneOfThree = {+ /** Detail projection. */+ details: TeamCalendarDetails;+ kind: TeamCalendarContentOneOfThreeKind;+};diff --git a/apps/web/src/lib/service-clients/service-storage/generated/schemas/teamCalendarContentOneOfThreeKind.ts b/apps/web/src/lib/service-clients/service-storage/generated/schemas/teamCalendarContentOneOfThreeKind.tsnew file mode 100644index 0000000000..73c317e826--- /dev/null+++ b/apps/web/src/lib/service-clients/service-storage/generated/schemas/teamCalendarContentOneOfThreeKind.ts@@ -0,0 +1,14 @@+/**+ * Generated by orval v7.21.0 🍺+ * Do not edit manually.+ * document_storage_service+ * OpenAPI spec version: 0.1.0+ */++export type TeamCalendarContentOneOfThreeKind =+ (typeof TeamCalendarContentOneOfThreeKind)[keyof typeof TeamCalendarContentOneOfThreeKind];++// eslint-disable-next-line @typescript-eslint/no-redeclare+export const TeamCalendarContentOneOfThreeKind = {+ details: 'details',+} as const;diff --git a/apps/web/src/lib/service-clients/service-storage/generated/schemas/teamCalendarCoverage.ts b/apps/web/src/lib/service-clients/service-storage/generated/schemas/teamCalendarCoverage.tsnew file mode 100644index 0000000000..43c0f20600--- /dev/null+++ b/apps/web/src/lib/service-clients/service-storage/generated/schemas/teamCalendarCoverage.ts@@ -0,0 +1,19 @@+/**+ * Generated by orval v7.21.0 🍺+ * Do not edit manually.+ * document_storage_service+ * OpenAPI spec version: 0.1.0+ */++/**+ * Whether a member's calendar projection can establish availability.+ */+export type TeamCalendarCoverage =+ (typeof TeamCalendarCoverage)[keyof typeof TeamCalendarCoverage];++// eslint-disable-next-line @typescript-eslint/no-redeclare+export const TeamCalendarCoverage = {+ ready: 'ready',+ unavailable: 'unavailable',+ hidden: 'hidden',+} as const;diff --git a/apps/web/src/lib/service-clients/service-storage/generated/schemas/teamCalendarDetails.ts b/apps/web/src/lib/service-clients/service-storage/generated/schemas/teamCalendarDetails.tsnew file mode 100644index 0000000000..7ec17cf7b4--- /dev/null+++ b/apps/web/src/lib/service-clients/service-storage/generated/schemas/teamCalendarDetails.ts@@ -0,0 +1,34 @@+/**+ * Generated by orval v7.21.0 🍺+ * Do not edit manually.+ * document_storage_service+ * OpenAPI spec version: 0.1.0+ */+import type { CalendarAttendee } from './calendarAttendee';+import type { TeamCalendarDetailsConferenceUrl } from './teamCalendarDetailsConferenceUrl';+import type { TeamCalendarDetailsDescription } from './teamCalendarDetailsDescription';+import type { TeamCalendarDetailsLocation } from './teamCalendarDetailsLocation';+import type { TeamCalendarDetailsOrganizerEmail } from './teamCalendarDetailsOrganizerEmail';+import type { TeamCalendarDetailsOrganizerName } from './teamCalendarDetailsOrganizerName';++/**+ * Safe details from a single authorized source.+ */+export interface TeamCalendarDetails {+ /** Attendees; self flags are relative to the requesting viewer. */+ attendees: CalendarAttendee[];+ /** Source calendar name, shown only with details. */+ calendarName: string;+ /** Join URL, if supplied by this source. */+ conferenceUrl?: TeamCalendarDetailsConferenceUrl;+ /** Body, if supplied by this source. */+ description?: TeamCalendarDetailsDescription;+ /** Location, if supplied by this source. */+ location?: TeamCalendarDetailsLocation;+ /** Organizer address from this source. */+ organizerEmail?: TeamCalendarDetailsOrganizerEmail;+ /** Organizer name from this source. */+ organizerName?: TeamCalendarDetailsOrganizerName;+ /** Display title. */+ title: string;+}diff --git a/apps/web/src/lib/service-clients/service-storage/generated/schemas/teamCalendarDetailsConferenceUrl.ts b/apps/web/src/lib/service-clients/service-storage/generated/schemas/teamCalendarDetailsConferenceUrl.tsnew file mode 100644index 0000000000..c68f8d086a--- /dev/null+++ b/apps/web/src/lib/service-clients/service-storage/generated/schemas/teamCalendarDetailsConferenceUrl.ts@@ -0,0 +1,11 @@+/**+ * Generated by orval v7.21.0 🍺+ * Do not edit manually.+ * document_storage_service+ * OpenAPI spec version: 0.1.0+ */++/**+ * Join URL, if supplied by this source.+ */+export type TeamCalendarDetailsConferenceUrl = string | null;diff --git a/apps/web/src/lib/service-clients/service-storage/generated/schemas/teamCalendarDetailsDescription.ts b/apps/web/src/lib/service-clients/service-storage/generated/schemas/teamCalendarDetailsDescription.tsnew file mode 100644index 0000000000..2858825227--- /dev/null+++ b/apps/web/src/lib/service-clients/service-storage/generated/schemas/teamCalendarDetailsDescription.ts@@ -0,0 +1,11 @@+/**+ * Generated by orval v7.21.0 🍺+ * Do not edit manually.+ * document_storage_service+ * OpenAPI spec version: 0.1.0+ */++/**+ * Body, if supplied by this source.+ */+export type TeamCalendarDetailsDescription = string | null;diff --git a/apps/web/src/lib/service-clients/service-storage/generated/schemas/teamCalendarDetailsLocation.ts b/apps/web/src/lib/service-clients/service-storage/generated/schemas/teamCalendarDetailsLocation.tsnew file mode 100644index 0000000000..f189e947e5--- /dev/null+++ b/apps/web/src/lib/service-clients/service-storage/generated/schemas/teamCalendarDetailsLocation.ts@@ -0,0 +1,11 @@+/**+ * Generated by orval v7.21.0 🍺+ * Do not edit manually.+ * document_storage_service+ * OpenAPI spec version: 0.1.0+ */++/**+ * Location, if supplied by this source.+ */+export type TeamCalendarDetailsLocation = string | null;diff --git a/apps/web/src/lib/service-clients/service-storage/generated/schemas/teamCalendarDetailsOrganizerEmail.ts b/apps/web/src/lib/service-clients/service-storage/generated/schemas/teamCalendarDetailsOrganizerEmail.tsnew file mode 100644index 0000000000..b44e292507--- /dev/null+++ b/apps/web/src/lib/service-clients/service-storage/generated/schemas/teamCalendarDetailsOrganizerEmail.ts@@ -0,0 +1,11 @@+/**+ * Generated by orval v7.21.0 🍺+ * Do not edit manually.+ * document_storage_service+ * OpenAPI spec version: 0.1.0+ */++/**+ * Organizer address from this source.+ */+export type TeamCalendarDetailsOrganizerEmail = string | null;diff --git a/apps/web/src/lib/service-clients/service-storage/generated/schemas/teamCalendarDetailsOrganizerName.ts b/apps/web/src/lib/service-clients/service-storage/generated/schemas/teamCalendarDetailsOrganizerName.tsnew file mode 100644index 0000000000..21518ccc94--- /dev/null+++ b/apps/web/src/lib/service-clients/service-storage/generated/schemas/teamCalendarDetailsOrganizerName.ts@@ -0,0 +1,11 @@+/**+ * Generated by orval v7.21.0 🍺+ * Do not edit manually.+ * document_storage_service+ * OpenAPI spec version: 0.1.0+ */++/**+ * Organizer name from this source.+ */+export type TeamCalendarDetailsOrganizerName = string | null;diff --git a/apps/web/src/lib/service-clients/service-storage/generated/schemas/teamCalendarItem.ts b/apps/web/src/lib/service-clients/service-storage/generated/schemas/teamCalendarItem.tsnew file mode 100644index 0000000000..3839a7e088--- /dev/null+++ b/apps/web/src/lib/service-clients/service-storage/generated/schemas/teamCalendarItem.ts@@ -0,0 +1,13 @@+/**+ * Generated by orval v7.21.0 🍺+ * Do not edit manually.+ * document_storage_service+ * OpenAPI spec version: 0.1.0+ */+import type { TeamCalendarContent } from './teamCalendarContent';+import type { TeamCalendarItemAllOf } from './teamCalendarItemAllOf';++/**+ * A read-only team calendar occurrence.+ */+export type TeamCalendarItem = TeamCalendarContent & TeamCalendarItemAllOf;diff --git a/apps/web/src/lib/service-clients/service-storage/generated/schemas/teamCalendarItemAllOf.ts b/apps/web/src/lib/service-clients/service-storage/generated/schemas/teamCalendarItemAllOf.tsnew file mode 100644index 0000000000..b3ff0bb529--- /dev/null+++ b/apps/web/src/lib/service-clients/service-storage/generated/schemas/teamCalendarItemAllOf.ts@@ -0,0 +1,19 @@+/**+ * Generated by orval v7.21.0 🍺+ * Do not edit manually.+ * document_storage_service+ * OpenAPI spec version: 0.1.0+ */+import type { EventTime } from './eventTime';++export type TeamCalendarItemAllOf = {+ /** Whether this occurrence blocks the sharer's personal availability.+A subscribed calendar's block can be shared without occupying the sharer. */+ contributesToAvailability: boolean;+ /** Stable opaque projection identity, never an event entity id. */+ id: string;+ /** The person sharing access to the source. */+ ownerId: string;+ /** Occurrence interval. */+ time: EventTime;+};diff --git a/apps/web/src/lib/service-clients/service-storage/generated/schemas/teamCalendarMember.ts b/apps/web/src/lib/service-clients/service-storage/generated/schemas/teamCalendarMember.tsnew file mode 100644index 0000000000..7ba77a5ca6--- /dev/null+++ b/apps/web/src/lib/service-clients/service-storage/generated/schemas/teamCalendarMember.ts@@ -0,0 +1,20 @@+/**+ * Generated by orval v7.21.0 🍺+ * Do not edit manually.+ * document_storage_service+ * OpenAPI spec version: 0.1.0+ */+import type { TeamCalendarCoverage } from './teamCalendarCoverage';+import type { TeamCalendarSharing } from './teamCalendarSharing';++/**+ * A current member of the requester's team.+ */+export interface TeamCalendarMember {+ /** Coverage available for a trustworthy calculation. */+ coverage: TeamCalendarCoverage;+ /** Current team-sharing policy. */+ sharing: TeamCalendarSharing;+ /** Macro user identifier. */+ userId: string;+}diff --git a/apps/web/src/lib/service-clients/service-storage/generated/schemas/teamCalendarPage.ts b/apps/web/src/lib/service-clients/service-storage/generated/schemas/teamCalendarPage.tsnew file mode 100644index 0000000000..b8cb12a382--- /dev/null+++ b/apps/web/src/lib/service-clients/service-storage/generated/schemas/teamCalendarPage.ts@@ -0,0 +1,21 @@+/**+ * Generated by orval v7.21.0 🍺+ * Do not edit manually.+ * document_storage_service+ * OpenAPI spec version: 0.1.0+ */+import type { TeamCalendarItem } from './teamCalendarItem';+import type { TeamCalendarMember } from './teamCalendarMember';+import type { TeamCalendarPageNextCursor } from './teamCalendarPageNextCursor';++/**+ * A bounded page of team calendar projections.+ */+export interface TeamCalendarPage {+ /** Authorized read-only projections. */+ items: TeamCalendarItem[];+ /** Current membership and sharing policies. */+ members: TeamCalendarMember[];+ /** Opaque continuation token; null after the last source occurrence. */+ nextCursor?: TeamCalendarPageNextCursor;+}diff --git a/apps/web/src/lib/service-clients/service-storage/generated/schemas/teamCalendarPageNextCursor.ts b/apps/web/src/lib/service-clients/service-storage/generated/schemas/teamCalendarPageNextCursor.tsnew file mode 100644index 0000000000..bf07894bef--- /dev/null+++ b/apps/web/src/lib/service-clients/service-storage/generated/schemas/teamCalendarPageNextCursor.ts@@ -0,0 +1,11 @@+/**+ * Generated by orval v7.21.0 🍺+ * Do not edit manually.+ * document_storage_service+ * OpenAPI spec version: 0.1.0+ */++/**+ * Opaque continuation token; null after the last source occurrence.+ */+export type TeamCalendarPageNextCursor = string | null;diff --git a/apps/web/src/lib/service-clients/service-storage/generated/schemas/teamCalendarSharing.ts b/apps/web/src/lib/service-clients/service-storage/generated/schemas/teamCalendarSharing.tsnew file mode 100644index 0000000000..863b35574e--- /dev/null+++ b/apps/web/src/lib/service-clients/service-storage/generated/schemas/teamCalendarSharing.ts@@ -0,0 +1,19 @@+/**+ * Generated by orval v7.21.0 🍺+ * Do not edit manually.+ * document_storage_service+ * OpenAPI spec version: 0.1.0+ */++/**+ * What a user exposes through their team membership.+ */+export type TeamCalendarSharing =+ (typeof TeamCalendarSharing)[keyof typeof TeamCalendarSharing];++// eslint-disable-next-line @typescript-eslint/no-redeclare+export const TeamCalendarSharing = {+ all: 'all',+ busy_only: 'busy_only',+ none: 'none',+} as const;diff --git a/apps/web/src/lib/service-clients/service-storage/generated/zod.ts b/apps/web/src/lib/service-clients/service-storage/generated/zod.tsindex 39e49934a9..bd475e553f 100644--- a/apps/web/src/lib/service-clients/service-storage/generated/zod.ts+++ b/apps/web/src/lib/service-clients/service-storage/generated/zod.ts@@ -1427,6 +1427,201 @@ export const mentionPreviewsResponse = zod}).describe('Batch calendar mention preview response.');+/**+ * @summary Query authorized projections in a bounded viewport.+ */+export const listTeamCalendarQueryLimitMin = 0;++export const listTeamCalendarQueryParams = zod.object({+ start: zod.iso.datetime({}).describe('Inclusive instant.'),+ end: zod.iso.datetime({}).describe('Exclusive instant.'),+ cursor: zod+ .string()+ .nullish()+ .describe('Continuation returned by the preceding page.'),+ limit: zod+ .number()+ .min(listTeamCalendarQueryLimitMin)+ .nullish()+ .describe(+ 'Maximum source occurrences, at most 2,000. Zero returns the roster only.'+ ),+});++export const listTeamCalendarResponse = zod+ .object({+ items: zod+ .array(+ zod+ .union([+ zod+ .object({+ kind: zod.enum(['busy']),+ })+ .describe('No provider or event metadata.'),+ zod+ .object({+ details: zod+ .object({+ attendees: zod+ .array(+ zod+ .object({+ comment: zod+ .string()+ .nullish()+ .describe('Optional attendee comment.'),+ displayName: zod+ .string()+ .nullish()+ .describe('Provider display name.'),+ email: zod+ .string()+ .describe('Normalized email address.'),+ isOptional: zod+ .boolean()+ .describe('Whether attendance is optional.'),+ isOrganizer: zod+ .boolean()+ .describe(+ 'Whether this attendee is the organizer.'+ ),+ isSelf: zod+ .boolean()+ .describe(+ "Whether this attendee is one of the viewing requester's inboxes."+ ),+ responseStatus: zod+ .enum([+ 'needs_action',+ 'accepted',+ 'declined',+ 'tentative',+ ])+ .describe('RSVP state for an attendee.'),+ })+ .describe('An attendee on a calendar event.')+ )+ .describe(+ 'Attendees; self flags are relative to the requesting viewer.'+ ),+ calendarName: zod+ .string()+ .describe(+ 'Source calendar name, shown only with details.'+ ),+ conferenceUrl: zod+ .string()+ .nullish()+ .describe('Join URL, if supplied by this source.'),+ description: zod+ .string()+ .nullish()+ .describe('Body, if supplied by this source.'),+ location: zod+ .string()+ .nullish()+ .describe('Location, if supplied by this source.'),+ organizerEmail: zod+ .string()+ .nullish()+ .describe('Organizer address from this source.'),+ organizerName: zod+ .string()+ .nullish()+ .describe('Organizer name from this source.'),+ title: zod.string().describe('Display title.'),+ })+ .describe('Safe details from a single authorized source.'),+ kind: zod.enum(['details']),+ })+ .describe('Explicitly authorized source content.'),+ ])+ .describe(+ 'Disjoint busy\/detail shapes prevent new event fields leaking by default.'+ )+ .and(+ zod.object({+ contributesToAvailability: zod+ .boolean()+ .describe(+ "Whether this occurrence blocks the sharer's personal availability.\nA subscribed calendar's block can be shared without occupying the sharer."+ ),+ id: zod+ .string()+ .describe(+ 'Stable opaque projection identity, never an event entity id.'+ ),+ ownerId: zod+ .string()+ .describe('The person sharing access to the source.'),+ time: zod+ .union([+ zod+ .object({+ endsAt: zod.iso+ .datetime({})+ .describe('Exclusive end instant.'),+ kind: zod.enum(['timed']),+ startsAt: zod.iso+ .datetime({})+ .describe('Inclusive start instant.'),+ timeZone: zod+ .string()+ .nullish()+ .describe(+ 'Original IANA time-zone identifier, when supplied.'+ ),+ })+ .describe('An event with absolute instants.'),+ zod+ .object({+ endDate: zod.iso+ .date()+ .describe('Exclusive local end date.'),+ kind: zod.enum(['allDay']),+ startDate: zod.iso+ .date()+ .describe('Inclusive local start date.'),+ })+ .describe(+ "An all-day event using RFC 5545's exclusive end date."+ ),+ ])+ .describe(+ 'The mutually exclusive time shape of a calendar event.\n\nFields are renamed per variant rather than with `rename_all_fields`\nbecause utoipa only honors variant-level serde renames when it\nderives the OpenAPI schema.'+ ),+ })+ )+ .describe('A read-only team calendar occurrence.')+ )+ .describe('Authorized read-only projections.'),+ members: zod+ .array(+ zod+ .object({+ coverage: zod+ .enum(['ready', 'unavailable', 'hidden'])+ .describe(+ "Whether a member's calendar projection can establish availability."+ ),+ sharing: zod+ .enum(['all', 'busy_only', 'none'])+ .describe('What a user exposes through their team membership.'),+ userId: zod.string().describe('Macro user identifier.'),+ })+ .describe("A current member of the requester's team.")+ )+ .describe('Current membership and sharing policies.'),+ nextCursor: zod+ .string()+ .nullish()+ .describe(+ 'Opaque continuation token; null after the last source occurrence.'+ ),+ })+ .describe('A bounded page of team calendar projections.');+/*** @summary Return teammates' out-of-office occurrences in the requested viewport.*/diff --git a/apps/web/src/lib/service-clients/service-storage/openapi.json b/apps/web/src/lib/service-clients/service-storage/openapi.jsonindex 904516377a..a3a16aa98c 100644--- a/apps/web/src/lib/service-clients/service-storage/openapi.json+++ b/apps/web/src/lib/service-clients/service-storage/openapi.json@@ -816,6 +816,67 @@}}},+ "/calendar-events/team": {+ "get": {+ "tags": ["calendar_events"],+ "summary": "Query authorized projections in a bounded viewport.",+ "operationId": "list_team_calendar",+ "parameters": [+ {+ "name": "start",+ "in": "query",+ "description": "Inclusive instant.",+ "required": true,+ "schema": {+ "type": "string",+ "format": "date-time"+ }+ },+ {+ "name": "end",+ "in": "query",+ "description": "Exclusive instant.",+ "required": true,+ "schema": {+ "type": "string",+ "format": "date-time"+ }+ },+ {+ "name": "cursor",+ "in": "query",+ "description": "Continuation returned by the preceding page.",+ "required": false,+ "schema": {+ "type": ["string", "null"]+ }+ },+ {+ "name": "limit",+ "in": "query",+ "description": "Maximum source occurrences, at most 2,000. Zero returns the roster only.",+ "required": false,+ "schema": {+ "type": ["integer", "null"],+ "format": "int32",+ "minimum": 0+ }+ }+ ],+ "responses": {+ "200": {+ "description": "",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/TeamCalendarPage"+ }+ }+ }+ }+ }+ }+ },"/calendar-events/team-out-of-office": {"get": {"tags": ["calendar_events"],@@ -37802,6 +37863,164 @@}}},+ "TeamCalendarContent": {+ "oneOf": [+ {+ "type": "object",+ "description": "No provider or event metadata.",+ "required": ["kind"],+ "properties": {+ "kind": {+ "type": "string",+ "enum": ["busy"]+ }+ }+ },+ {+ "type": "object",+ "description": "Explicitly authorized source content.",+ "required": ["details", "kind"],+ "properties": {+ "details": {+ "$ref": "#/components/schemas/TeamCalendarDetails",+ "description": "Detail projection."+ },+ "kind": {+ "type": "string",+ "enum": ["details"]+ }+ }+ }+ ],+ "description": "Disjoint busy/detail shapes prevent new event fields leaking by default."+ },+ "TeamCalendarCoverage": {+ "type": "string",+ "description": "Whether a member's calendar projection can establish availability.",+ "enum": ["ready", "unavailable", "hidden"]+ },+ "TeamCalendarDetails": {+ "type": "object",+ "description": "Safe details from a single authorized source.",+ "required": ["title", "attendees", "calendarName"],+ "properties": {+ "attendees": {+ "type": "array",+ "items": {+ "$ref": "#/components/schemas/CalendarAttendee"+ },+ "description": "Attendees; self flags are relative to the requesting viewer."+ },+ "calendarName": {+ "type": "string",+ "description": "Source calendar name, shown only with details."+ },+ "conferenceUrl": {+ "type": ["string", "null"],+ "description": "Join URL, if supplied by this source."+ },+ "description": {+ "type": ["string", "null"],+ "description": "Body, if supplied by this source."+ },+ "location": {+ "type": ["string", "null"],+ "description": "Location, if supplied by this source."+ },+ "organizerEmail": {+ "type": ["string", "null"],+ "description": "Organizer address from this source."+ },+ "organizerName": {+ "type": ["string", "null"],+ "description": "Organizer name from this source."+ },+ "title": {+ "type": "string",+ "description": "Display title."+ }+ }+ },+ "TeamCalendarItem": {+ "allOf": [+ {+ "$ref": "#/components/schemas/TeamCalendarContent",+ "description": "Authorized content variant."+ },+ {+ "type": "object",+ "required": ["id", "ownerId", "time", "contributesToAvailability"],+ "properties": {+ "contributesToAvailability": {+ "type": "boolean",+ "description": "Whether this occurrence blocks the sharer's personal availability.\nA subscribed calendar's block can be shared without occupying the sharer."+ },+ "id": {+ "type": "string",+ "description": "Stable opaque projection identity, never an event entity id."+ },+ "ownerId": {+ "type": "string",+ "description": "The person sharing access to the source."+ },+ "time": {+ "$ref": "#/components/schemas/EventTime",+ "description": "Occurrence interval."+ }+ }+ }+ ],+ "description": "A read-only team calendar occurrence."+ },+ "TeamCalendarMember": {+ "type": "object",+ "description": "A current member of the requester's team.",+ "required": ["userId", "sharing", "coverage"],+ "properties": {+ "coverage": {+ "$ref": "#/components/schemas/TeamCalendarCoverage",+ "description": "Coverage available for a trustworthy calculation."+ },+ "sharing": {+ "$ref": "#/components/schemas/TeamCalendarSharing",+ "description": "Current team-sharing policy."+ },+ "userId": {+ "type": "string",+ "description": "Macro user identifier."+ }+ }+ },+ "TeamCalendarPage": {+ "type": "object",+ "description": "A bounded page of team calendar projections.",+ "required": ["members", "items"],+ "properties": {+ "items": {+ "type": "array",+ "items": {+ "$ref": "#/components/schemas/TeamCalendarItem"+ },+ "description": "Authorized read-only projections."+ },+ "members": {+ "type": "array",+ "items": {+ "$ref": "#/components/schemas/TeamCalendarMember"+ },+ "description": "Current membership and sharing policies."+ },+ "nextCursor": {+ "type": ["string", "null"],+ "description": "Opaque continuation token; null after the last source occurrence."+ }+ }+ },+ "TeamCalendarSharing": {+ "type": "string",+ "description": "What a user exposes through their team membership.",+ "enum": ["all", "busy_only", "none"]+ },"TeamOutOfOfficeItem": {"type": "object","description": "One teammate's out-of-office occurrence.",diff --git a/apps/web/tests/calendar-team/README.md b/apps/web/tests/calendar-team/README.mdnew file mode 100644index 0000000000..2dae7d63ce--- /dev/null+++ b/apps/web/tests/calendar-team/README.md@@ -0,0 +1,17 @@+# Team calendar browser verification++This harness loads the complete bundled app and intercepts auth, team, and calendar HTTP traffic with synthetic identities. It blocks nonlocal requests and websocket traffic. It does not verify the Rust service or Google permissions. Own-calendar reads use the existing REST fallback; team projections use their production REST query, mapping, and UI paths.++It uses a live clock and checks that loading placeholders disappear and event chips are opaque and in the viewport before capture. It exercises sharing and availability settings, read-only event details, revocation, membership loss, a viewer without any connected Google account, and automatic data/popover expiry while refresh requests hang. The expiry check waits up to 65 seconds with the browser clock running normally.++From `apps/web`, with Chromium installed:++```sh+MODE=development bunx vite build -c tests/calendar-team/vite.config.ts+bunx vite preview -c tests/calendar-team/vite.config.ts --outDir /tmp/calendar-team-browser-dist --base /app --port 3037+# In another terminal:+bun build tests/calendar-team/browser.ts --target=node --packages=external --outfile=node_modules/.calendar-team-browser/browser.mjs+node node_modules/.calendar-team-browser/browser.mjs+```++Use `CHROMIUM_PATH` for an alternative binary. `CALENDAR_TEAM_BROWSER_CDP=http://127.0.0.1:9222` uses a new isolated context in an existing browser and closes only that context. `CALENDAR_TEAM_BROWSER_URL` overrides the preview origin. No existing browser contexts, sessions, or stacks are modified. Screenshots go to `/tmp/calendar-team-*.png`.diff --git a/apps/web/tests/calendar-team/browser.ts b/apps/web/tests/calendar-team/browser.tsnew file mode 100644index 0000000000..aded92e1e3--- /dev/null+++ b/apps/web/tests/calendar-team/browser.ts@@ -0,0 +1,476 @@+import assert from 'node:assert/strict';+import { chromium, expect } from '@playwright/test';+import { bootstrapResponses } from '../native/fixtures/bootstrap';+import { USER_ID } from '../native/fixtures/mail';++// Full production components and routing, with API transport intercepted. Never uses real sessions.+const origin = process.env.CALENDAR_TEAM_BROWSER_URL ?? 'http://127.0.0.1:3037';+const sharedCdp = process.env.CALENDAR_TEAM_BROWSER_CDP;+const browser = sharedCdp+ ? await chromium.connectOverCDP(sharedCdp)+ : await chromium.launch({+ executablePath: process.env.CHROMIUM_PATH ?? '/usr/bin/chromium',+ headless: true,+ args: ['--no-sandbox'],+ });+const context = await browser.newContext({+ viewport: { width: 1500, height: 1100 },+ timezoneId: 'UTC',+ serviceWorkers: 'block',+});+const page = await context.newPage();+page.setDefaultTimeout(15000);+const errors: string[] = [];+const requestFailures: string[] = [];+const unknown: string[] = [];+page.on('pageerror', (error) => errors.push(error.message));++page.on('requestfailed', (request) => {+ const failure = request.failure()?.errorText;+ // Navigation and the deliberate expiry checks cancel fetches. Nonlocal+ // traffic is explicitly blocked by this synthetic harness below.+ if (!request.url().startsWith(origin) || failure === 'net::ERR_ABORTED')+ return;+ requestFailures.push(`${request.url()}: ${failure}`);+});+await context.addCookies([{ name: 'login', value: 'true', url: origin }]);+await page.addInitScript(() =>+ localStorage.setItem(+ 'macro:pref:calendar:settings',+ JSON.stringify({+ periodView: 'timeGridWeek',+ showTeamCalendars: true,+ hiddenSourceIds: [],+ sourceColors: {},+ accountColors: {},+ showWeekends: true,+ weekStartsOn: 0,+ timeFormat: '24-hour',+ })+ )+);+await page.routeWebSocket('**/*', (socket) => socket.close());+const ALICE = 'macro|[email protected]';+const BOB = 'macro|[email protected]';+const TEAM = '00000000-0000-0000-0000-000000001111';+let sharing = 'busy_only';+let included = false;+let revoked = false;+let member = true;+let connected = true;+let hangTeamRequests = false;+const mutations: unknown[] = [];+const teamReadLimits: string[] = [];+const teamMembers = [+ { userId: ALICE, sharing: 'all', coverage: 'ready' },+ { userId: BOB, sharing: 'busy_only', coverage: 'ready' },+];+// Keep the browser clock live: calendar loading transitions compare elapsed time.+const fixtureDate = new Date().toISOString().slice(0, 10);+const time = (hour: number) => ({+ kind: 'timed',+ startsAt: `${fixtureDate}T${hour}:00:00Z`,+ endsAt: `${fixtureDate}T${hour + 1}:00:00Z`,+ timeZone: 'UTC',+});+const items = [+ {+ id: 'opaque-details',+ ownerId: ALICE,+ kind: 'details',+ time: time(10),+ contributesToAvailability: true,+ details: {+ title: 'Team planning',+ description: '<p>Review roadmap</p>',+ location: 'Room 2',+ conferenceUrl: 'https://meet.google.com/abc-defg-hij',+ organizerEmail: '[email protected]',+ organizerName: 'Alice',+ attendees: [+ {+ email: '[email protected]',+ displayName: 'Offline Fixture',+ isSelf: true,+ isOrganizer: false,+ responseStatus: 'accepted',+ },+ ],+ calendarName: 'Alice primary',+ },+ },+ {+ id: 'opaque-busy',+ ownerId: BOB,+ kind: 'busy',+ time: time(12),+ contributesToAvailability: true,+ },+ {+ id: 'opaque-followed',+ ownerId: BOB,+ kind: 'busy',+ time: time(14),+ contributesToAvailability: false,+ },+];+await page.route('**/*', async (route) => {+ const request = route.request();+ const url = new URL(request.url());+ const path = url.pathname;+ const respond = (body: unknown, status = 200) =>+ route.fulfill({+ status,+ contentType: 'application/json',+ body: JSON.stringify(body),+ });+ if (url.origin !== origin) return route.abort();+ if (path.startsWith('/app') || path === '/') return route.continue();+ if (path === '/auth/jwt/refresh') return respond({});+ if (!connected && path === '/email/email/links')+ return respond({ links: [] });+ if (!connected && path === '/calendar/calendars')+ return respond({ calendars: [] });+ if (path === '/auth/team')+ return member+ ? respond({+ team: {+ id: TEAM,+ name: 'Calendar fixtures',+ owner_id: USER_ID,+ slug: 'fixture',+ enterprise: false,+ crm_enabled: false,+ allow_non_admin_invites: true,+ },+ members: [USER_ID, ALICE, BOB].map((user_id) => ({+ user_id,+ team_id: TEAM,+ role: 'member',+ plan: 'free',+ })),+ })+ : respond({}, 404);+ if (path === '/auth/user/get_names_with_email')+ return respond({+ names: [+ { id: USER_ID, first_name: 'Offline', last_name: 'Fixture' },+ { id: ALICE, first_name: 'Alice', last_name: 'Fixture' },+ { id: BOB, first_name: 'Bob', last_name: 'Fixture' },+ ],+ });+ if (path === '/calendar/team-sharing') {+ if (request.method() === 'PUT') {+ sharing = request.postDataJSON().sharing;+ mutations.push(request.postDataJSON());+ }+ return respond({ sharing });+ }+ if (path === '/calendar/availability-calendars')+ return respond({+ calendars: [+ {+ calendarId: 'primary',+ name: 'My primary',+ isPrimary: true,+ contributesToAvailability: true,+ },+ {+ calendarId: 'followed',+ name: 'Subscribed coworker',+ isPrimary: false,+ contributesToAvailability: included,+ },+ ],+ });+ if (path === '/calendar/availability-calendars/followed') {+ included = request.postDataJSON().contributesToAvailability;+ mutations.push(request.postDataJSON());+ return route.fulfill({ status: 204 });+ }+ if (path === '/calendar/calendars')+ return respond({+ calendars: [+ {+ id: 'primary',+ emailAddress: '[email protected]',+ emailLinkId: '00000000-0000-0000-0000-000000001000',+ name: 'My primary',+ isPrimary: true,+ isWritable: true,+ isSubscription: false,+ defaultReminders: [],+ },+ ],+ });+ if (path === '/dss/calendar-events/team') {+ teamReadLimits.push(url.searchParams.get('limit') ?? 'default');+ if (hangTeamRequests) return new Promise<void>(() => {});+ return revoked+ ? respond({ message: 'Access revoked' }, 403)+ : respond({+ members: teamMembers,+ items: url.searchParams.get('limit') === '0' ? [] : items,+ nextCursor: null,+ });+ }+ if (path === '/dss/calendar-events/team-out-of-office')+ return respond({ items: [], hasMore: false });+ if (path === '/dss/calendar-events')+ return respond({+ items: [],+ hasMore: false,+ nextCursor: null,+ syncStatus: 'ready',+ });+ const fixture = bootstrapResponses.get(`${request.method()} ${path}`);+ if (fixture) return respond(fixture.body, fixture.status);+ unknown.push(`${request.method()} ${path}`);+ return respond({}, 404);+});++async function expectRevealedCalendar() {+ const activePage = page+ .getByRole('region', { name: 'Calendar periods' })+ .locator('.pager-page[aria-hidden="false"]');+ // Playwright visibility checks accept opacity:0, so a DOM-only title assertion+ // can pass while FullCalendar intentionally conceals chips under its skeleton.+ await expect(+ activePage.locator('[data-calendar-loading-skeleton]')+ ).toHaveCount(0, { timeout: 15000 });+ await expect(+ activePage.locator(+ '[data-calendar-loading-state]:not([data-calendar-loading-state="hidden"])'+ )+ ).toHaveCount(0, { timeout: 15000 });+ const titles = [+ 'Alice Fixture: Team planning',+ 'Bob Fixture: Busy',+ 'Bob Fixture: Shared calendar block',+ ];+ await activePage+ .getByText(titles[2], { exact: true })+ .scrollIntoViewIfNeeded();+ for (const title of titles) {+ const chip = activePage.getByText(title, { exact: true });+ await expect(chip).toBeInViewport();+ await expect+ .poll(() =>+ chip.evaluate((element) => {+ for (+ let parent: Element | null = element;+ parent;+ parent = parent.parentElement+ ) {+ const style = getComputedStyle(parent);+ if (Number(style.opacity) === 0 || style.visibility === 'hidden')+ return false;+ }+ return true;+ })+ )+ .toBe(true);+ }+}++try {+ await page.goto(`${origin}/app/calendar/week`, {+ waitUntil: 'domcontentloaded',+ });+ await page+ .getByText('Team planning', { exact: false })+ .first()+ .waitFor({ timeout: 60000 });+ await expectRevealedCalendar();+ await expect.poll(() => teamReadLimits.includes('0')).toBe(true);+ assert.equal(teamReadLimits.includes('500'), true);+ assert.equal(teamReadLimits.includes('1'), false);+ await page.screenshot({+ path: '/tmp/calendar-team-grid.png',+ fullPage: true,+ });+ await page.getByText('Team planning', { exact: false }).first().click();+ const detail = page.locator('section[aria-label="Shared event details"]');+ await expect(detail).toContainText('Shared in Macro · Read only');+ await expect(detail).toContainText('Offline Fixture (you)');+ for (const name of [+ 'Edit event',+ 'Delete event',+ 'Copy event',+ 'Copy guest emails',+ 'Email guests',+ ]) {+ await expect(page.getByRole('button', { name, exact: true })).toHaveCount(+ 0+ );+ }+ assert.equal(+ new URL(page.url()).searchParams.has('s0.calendar.eventId'),+ false+ );+ await page.screenshot({+ path: '/tmp/calendar-team-details.png',+ fullPage: true,+ });+ await page.keyboard.press('Escape');+ await page+ .getByText(/: Busy$/, { exact: false })+ .first()+ .click();+ await expect(detail).toContainText('Counts toward this teammate');+ await expect(detail).not.toContainText('Organizer:');+ await expect(+ detail.getByRole('button', { name: 'Join meeting' })+ ).toHaveCount(0);+ await page.keyboard.press('Escape');+ await page+ .getByText(/: Shared calendar block$/, { exact: false })+ .first()+ .click();+ await expect(detail).toContainText('Does not count toward their busy time');+ await page.keyboard.press('Escape');++ await page.goto(`${origin}/app/settings/calendar`, {+ waitUntil: 'domcontentloaded',+ });+ await expect(+ page.getByRole('radio', { name: 'Busy blocks', exact: true })+ ).toBeChecked({ timeout: 30000 });+ await expect(+ page.getByText(+ 'including subscribed or delegated calendars, birthdays and holidays',+ {+ exact: false,+ }+ )+ ).toBeVisible();+ await expect(+ page.getByText(+ 'Calendars unchecked in Google Calendar are included if synced.',+ {+ exact: false,+ }+ )+ ).toBeVisible();+ await expect(+ page.getByText(+ 'Hiding a calendar in your Macro view does not change sharing.',+ {+ exact: false,+ }+ )+ ).toBeVisible();+ await page.screenshot({+ path: '/tmp/calendar-team-settings.png',+ fullPage: true,+ });+ await page.getByRole('radio', { name: 'Event details', exact: true }).check();+ await expect(+ page.getByRole('radio', { name: 'Event details', exact: true })+ ).toBeChecked();+ assert.equal(sharing, 'all');+ const availabilityToggle = page.getByRole('switch', {+ name: 'Count Subscribed coworker toward my availability',+ });+ await availabilityToggle.press('Space');+ await expect.poll(() => included).toBe(true);+ await expect(availabilityToggle).toBeChecked();+ await expect(availabilityToggle).toBeEnabled();+ await page.getByRole('radio', { name: 'Nothing', exact: true }).check();+ await expect.poll(() => sharing).toBe('none');+ await page.getByRole('radio', { name: 'Busy blocks', exact: true }).check();+ await expect.poll(() => sharing).toBe('busy_only');++ await page.goto(`${origin}/app/calendar/week`, {+ waitUntil: 'domcontentloaded',+ });+ await page.getByText('Team planning', { exact: false }).first().click();+ await expect(detail).toBeVisible();+ revoked = true;+ // A normal focus refresh must discard a now-forbidden range and detached popover.+ const focusTab = await context.newPage();+ await focusTab.bringToFront();+ await page.bringToFront();+ await focusTab.close();+ await expect(detail).toHaveCount(0, { timeout: 40000 });+ await expect(page.getByText('Team planning', { exact: false })).toHaveCount(+ 0+ );+ await expect(+ page+ .getByText('Team calendars unavailable. Availability is unknown.', {+ exact: false,+ })+ .filter({ visible: true })+ .first()+ ).toBeVisible();+ revoked = false;+ await page.reload({ waitUntil: 'domcontentloaded' });+ await page.getByText('Team planning', { exact: false }).first().click();+ await expect(detail).toBeVisible();+ member = false;+ const membershipTab = await context.newPage();+ await membershipTab.bringToFront();+ await page.bringToFront();+ await membershipTab.close();+ await expect(detail).toHaveCount(0, { timeout: 40000 });+ await expect(page.getByText('Team planning', { exact: false })).toHaveCount(+ 0+ );+ assert.deepEqual(errors, []);+ member = true;+ connected = false;+ await page.reload({ waitUntil: 'domcontentloaded' });+ await expect(+ page.getByText('Team planning', { exact: false }).first()+ ).toBeVisible({ timeout: 30000 });+ await expectRevealedCalendar();+ await page.getByText('Team planning', { exact: false }).first().click();+ await expect(detail).toContainText('Shared in Macro · Read only');+ await page.screenshot({+ path: '/tmp/calendar-team-no-google.png',+ fullPage: true,+ });+ // Stay online but leave every new team read unresolved. The independent+ // expiry must remove already visible data and the detached popover anyway.+ hangTeamRequests = true;+ await expect(detail).toHaveCount(0, { timeout: 65000 });+ await expect(page.getByText('Team planning', { exact: false })).toHaveCount(+ 0+ );+ assert.deepEqual(errors, []);+ assert.deepEqual(requestFailures, []);+ console.log(+ 'PASS: full-app team settings, sanitized blocks, read-only details, revoked-data removal, membership loss, viewer without Google, and expiry during hung refresh'+ );+} catch (error) {+ console.error(error);+ process.exitCode = 1;+} finally {+ console.log(+ JSON.stringify(+ {+ errors,+ requestFailures,+ unknown: [...new Set(unknown)],+ teamReadLimits: [...new Set(teamReadLimits)],+ mutations,+ },+ null,+ 2+ )+ );+ try {+ await page.screenshot({+ path: '/tmp/calendar-team-final.png',+ fullPage: true,+ });+ } finally {+ // Closing a context cancels unrelated app preloads; those are cleanup, not+ // failures of the browser checks above.+ page.removeAllListeners('requestfailed');+ await context.close();+ if (!sharedCdp) await browser.close();+ else process.exit(process.exitCode ?? 0);+ }+}diff --git a/apps/web/tests/calendar-team/vite.config.ts b/apps/web/tests/calendar-team/vite.config.tsnew file mode 100644index 0000000000..646d75e74c--- /dev/null+++ b/apps/web/tests/calendar-team/vite.config.ts@@ -0,0 +1,24 @@+import { defineConfig, mergeConfig } from 'vite';+import { createAppViteConfig } from '../../vite.base';++// Pin a synthetic local environment without loading developer credentials or hosted origins.+Object.assign(process.env, {+ MODE: 'development',+ VITE_LOCAL_SERVERS: 'ALL',+ VITE_LOCAL_BACKEND_ORIGIN: 'same-origin',+ VITE_ENABLE_CALENDAR_UI: 'true',+ VITE_ENABLE_CALENDAR_TEAM_SHARING: 'true',+ VITE_ENABLE_CALENDAR_TEAM_OOO: 'true',+ VITE_ENABLE_GRAPHQL_CALENDAR: 'false',+ VITE_DISABLE_BROWSER_TURSO_CACHE: 'true',+ VITE_ENABLE_IN_APP_TOURS: 'false',+ VITE_ENABLE_BROWSER_OTEL: 'false',+});+export default defineConfig((env) =>+ mergeConfig(createAppViteConfig()(env), {+ envDir: import.meta.dirname,+ cacheDir: 'node_modules/.vite-calendar-team-browser',+ build: { outDir: '/tmp/calendar-team-browser-dist', sourcemap: false },+ preview: { host: '127.0.0.1', port: 3037, strictPort: true },+ })+);diff --git a/crates/ai_tools/src/build_context.rs b/crates/ai_tools/src/build_context.rsindex ca8e7b40c1..61d2a82996 100644--- a/crates/ai_tools/src/build_context.rs+++ b/crates/ai_tools/src/build_context.rs@@ -518,6 +518,12 @@ pub async fn build_tool_service_context_from_env(email_tool_context,call_tool_context,calendar_tool_context,+ team_calendar_tool_context: crate::tool_context::build_team_calendar_tool_context(+ pool.clone(),+ macro_env_var::maybe_read_env("CALENDAR_TEAM_SHARING_ENABLED")+ .and_then(|value| value.parse::<bool>().ok())+ .unwrap_or(false),+ ),booking_link_tool_context: crate::tool_context::build_booking_link_tool_context(pool.clone(),environment,diff --git a/crates/ai_tools/src/lib.rs b/crates/ai_tools/src/lib.rsindex e797f84045..eb82dddd8c 100644--- a/crates/ai_tools/src/lib.rs+++ b/crates/ai_tools/src/lib.rs@@ -26,6 +26,7 @@ pub mod user_tool_review;pub use anthropic::toolset::AnthropicToolContext;use anthropic::toolset::anthropic_toolset;use bots::inbound::toolset::bot_toolset;+use calendar_events::inbound::team_toolset::team_calendar_toolset;use calendar_events::inbound::toolset::{calendar_toolset, mcp_toolset as calendar_mcp_toolset};use calendar_scheduling::inbound::toolset::{booking_link_toolset, mcp_toolset as booking_link_mcp_toolset,@@ -81,8 +82,9 @@ pub use tool_context::{ToolNotificationService, ToolNotificationToolContext, ToolPipedreamConnection,ToolProjectService, ToolProjectToolContext, ToolPropertiesService, ToolPropertiesToolContext,ToolServiceContext, ToolSkillService, ToolSkillToolContext, ToolSoupService,- ToolSystemPropertiesService, ToolTableEventPublisher, ToolTeamService, ToolTeamToolContext,- ToolUserEmailService, ToolViewOnlyDatabasesSqlToolContext, build_activity_tool_context,+ ToolSystemPropertiesService, ToolTableEventPublisher, ToolTeamCalendarService,+ ToolTeamCalendarToolContext, ToolTeamService, ToolTeamToolContext, ToolUserEmailService,+ ToolViewOnlyDatabasesSqlToolContext, build_activity_tool_context,build_booking_link_tool_context, build_bot_tool_context, build_calendar_tool_context,build_channel_tool_context_with_dispatcher, build_channel_tool_context_with_side_effects,build_channel_tool_context_without_side_effects, build_coding_agent_tool_context,@@ -91,7 +93,8 @@ pub use tool_context::{build_message_service_with_side_effects, build_message_service_without_side_effects,build_project_tool_context, build_properties_service, build_properties_service_with_broker,build_properties_tool_context, build_routine_tool_context, build_skill_tool_context,- build_task_properties_adapter, build_team_repository, build_team_tool_context,+ build_task_properties_adapter, build_team_calendar_tool_context, build_team_repository,+ build_team_tool_context,};#[cfg(any(test, feature = "test-support"))]pub use tool_context::{build_image_generation_tool_context_test, no_op_schedule_context};@@ -228,6 +231,7 @@ pub const EAGER_TOOLS: &[&str] = &[pub fn tools_for(host: AiHost) -> ToolSetWithPrompt {let toolset = subagent_toolset().add_subtoolset::<ToolNotificationToolContext>(notification_toolset())+ .add_subtoolset::<ToolTeamCalendarToolContext>(team_calendar_toolset()).add_subtoolset::<RoutineToolContext>(routines::inbound::routine_toolset());let toolset = match host {AiHost::Chat | AiHost::AgentSession => toolsetdiff --git a/crates/ai_tools/src/tool_context.rs b/crates/ai_tools/src/tool_context.rsindex 85d300ca88..23b69fb4a0 100644--- a/crates/ai_tools/src/tool_context.rs+++ b/crates/ai_tools/src/tool_context.rs@@ -4,6 +4,7 @@ use bots::{domain::service::BotServiceImpl, inbound::toolset::BotToolContext,outbound::pg_bots_repo::PgBotsRepo,};+use calendar_events::inbound::team_toolset::TeamCalendarToolContext;use calendar_events::inbound::toolset::CalendarToolContext;use call::domain::models::{CallError, CallWebhookEvent, EgressS3Config};use call::domain::ports::CallRtcClient;@@ -449,6 +450,27 @@ pub type ToolCalendarMutationService =pub type ToolCalendarToolContext =CalendarToolContext<ToolCalendarMutationService, ToolCalendarReadService>;+/// Source-scoped team calendar domain service for read-only AI availability.+pub type ToolTeamCalendarService = calendar_events::domain::team::CalendarTeamServiceImpl<+ calendar_events::outbound::pg_team::PgCalendarTeamRepository,+>;++/// Team availability tool dependencies, separate from provider mutation access.+pub type ToolTeamCalendarToolContext = TeamCalendarToolContext<ToolTeamCalendarService>;++/// Construct the authorized availability service at the AI composition root.+pub fn build_team_calendar_tool_context(+ pool: sqlx::PgPool,+ enabled: bool,+) -> ToolTeamCalendarToolContext {+ TeamCalendarToolContext {+ service: Arc::new(calendar_events::domain::team::CalendarTeamServiceImpl::new(+ calendar_events::outbound::pg_team::PgCalendarTeamRepository::new(pool),+ enabled,+ )),+ }+}+/// Build the calendar AI tool context: reads query the local occurrence/// projections from `pool`; mutations call the calendar service at/// `calendar_service_url` with the shared internal API key.@@ -1592,6 +1614,7 @@ pub struct ToolServiceContext {pub email_tool_context: ToolEmailToolContext,pub call_tool_context: ToolCallToolContext,pub calendar_tool_context: ToolCalendarToolContext,+ pub team_calendar_tool_context: ToolTeamCalendarToolContext,pub booking_link_tool_context: ToolBookingLinkToolContext,pub notification_tool_context: ToolNotificationToolContext,pub databases_tool_context: ToolDatabasesToolContext,diff --git a/crates/calendar_events/Cargo.toml b/crates/calendar_events/Cargo.tomlindex df0c948468..666fe92c91 100644--- a/crates/calendar_events/Cargo.toml+++ b/crates/calendar_events/Cargo.toml@@ -35,6 +35,7 @@ async-trait = { workspace = true, optional = true }aws-sdk-sqs = { workspace = true, optional = true }axum = { workspace = true, optional = true }chrono = { workspace = true }+chrono-tz = { workspace = true }futures = { workspace = true }macro_authorization = { path = "../macro_authorization", default-features = false, features = ["axum",diff --git a/crates/calendar_events/src/domain/mod.rs b/crates/calendar_events/src/domain/mod.rsindex fde8589540..261f3546af 100644--- a/crates/calendar_events/src/domain/mod.rs+++ b/crates/calendar_events/src/domain/mod.rs@@ -18,3 +18,7 @@ pub mod ports;pub mod reminder_dispatch;/// Calendar business policy.pub mod service;+/// Source-aware, read-only team calendar sharing.+pub mod team;+/// Coverage-aware personal availability from authorized team sources.+pub mod team_availability;diff --git a/crates/calendar_events/src/domain/models.rs b/crates/calendar_events/src/domain/models.rsindex a5e2274ee2..f820142a1e 100644--- a/crates/calendar_events/src/domain/models.rs+++ b/crates/calendar_events/src/domain/models.rs@@ -665,6 +665,13 @@ pub struct CalendarEventOverride {pub location: Option<String>,/// Optional replacement status.pub status: Option<EventStatus>,+ /// Instance visibility, when explicitly supplied by the provider. Kept+ /// on the source snapshot so team views do not lose privacy information.+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub visibility: Option<EventVisibility>,+ /// Instance availability, when explicitly supplied by the provider.+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub transparency: Option<EventTransparency>,/// Replacement attendee list for this occurrence alone. `None` inherits/// the series attendees. Google carries the complete list on every/// exception it returns, so a single instance-scoped RSVP — including the@@ -690,6 +697,12 @@ impl CalendarEventOverride {pub fn apply_to(&self, event: &mut CalendarEvent) {event.apply_occurrence_content(self.content());event.time = self.time.clone();+ if let Some(visibility) = self.visibility {+ event.visibility = visibility;+ }+ if let Some(transparency) = self.transparency {+ event.transparency = transparency;+ }if let Some(attendees) = &self.attendees {event.attendees = attendees.clone();}@@ -1066,6 +1079,9 @@ pub struct GoogleEventSource {pub account_id: Uuid,/// Calendar containing the source event.pub calendar_id: Uuid,+ /// Calendar role observed for this account before the provider request.+ /// Never substitute a newer stored role when persisting its response.+ pub observed_access_role: Option<String>,/// Google event identifier.pub provider_event_id: String,/// Google recurring master identifier for an instance.@@ -1109,6 +1125,8 @@ pub struct GoogleCalendarTarget {pub calendar_id: Uuid,/// Provider calendar identifier used in Google API paths.pub provider_calendar_id: String,+ /// Calendar role captured before this target is sent to the provider.+ pub observed_access_role: Option<String>,/// Whether the provider role prohibits event mutation.pub is_read_only: bool,/// Occurrence window to materialize.@@ -1227,6 +1245,8 @@ pub struct CalendarEventMutationTarget {pub calendar_id: Uuid,/// Provider calendar identifier used in Google API paths.pub provider_calendar_id: String,+ /// This account's role on the addressed calendar before the provider call.+ pub observed_access_role: Option<String>,/// Grant of the connected inbox this calendar belongs to.pub token_identity: CalendarLinkTokenIdentity,/// The clicker's owned inboxes. `None` when they own none.@@ -1250,6 +1270,7 @@ impl CalendarEventMutationTarget {account_id: self.account_id,calendar_id: self.calendar_id,provider_calendar_id: self.provider_calendar_id.clone(),+ observed_access_role: self.observed_access_role.clone(),is_read_only: self.is_read_only,range,}@@ -1299,6 +1320,8 @@ pub struct CalendarCreationTarget {pub calendar_id: Uuid,/// Provider calendar identifier used in Google API paths.pub provider_calendar_id: String,+ /// This account's role on the addressed calendar before the provider call.+ pub observed_access_role: Option<String>,/// Whether the provider role prohibits event creation.pub is_read_only: bool,/// Whether this is its account's primary calendar. Out-of-office events@@ -1319,6 +1342,7 @@ impl CalendarCreationTarget {account_id: self.account_id,calendar_id: self.calendar_id,provider_calendar_id: self.provider_calendar_id.clone(),+ observed_access_role: self.observed_access_role.clone(),is_read_only: self.is_read_only,range,}@@ -1523,6 +1547,8 @@ pub enum RefreshCalendarEvent {/// Connected inbox whose calendars changed.link_id: Uuid,},+ /// A team entitlement changed; discard cached team projections before refetching.+ TeamSharingChanged,}/// Identity of one scheduled reminder firing: an occurrence, an offset, anddiff --git a/crates/calendar_events/src/domain/mutations/test.rs b/crates/calendar_events/src/domain/mutations/test.rsindex 18e0f42ac3..72c5e9204d 100644--- a/crates/calendar_events/src/domain/mutations/test.rs+++ b/crates/calendar_events/src/domain/mutations/test.rs@@ -22,6 +22,7 @@ fn token_identity() -> CalendarLinkTokenIdentity {fn mutation_target(is_read_only: bool) -> CalendarEventMutationTarget {CalendarEventMutationTarget {+ observed_access_role: Some(if is_read_only { "reader" } else { "owner" }.to_owned()),event_id: Uuid::now_v7(),is_read_only,provider_event_id: "instance-id".to_string(),@@ -50,6 +51,7 @@ fn echo_attendee(email: &str, is_self: bool) -> CalendarAttendee {fn creation_target(is_read_only: bool) -> CalendarCreationTarget {CalendarCreationTarget {+ observed_access_role: Some(if is_read_only { "reader" } else { "owner" }.to_owned()),owner_id: "macro|[email protected]".to_string(),email_link_id: Uuid::now_v7(),account_id: Uuid::now_v7(),@@ -103,6 +105,7 @@ fn echo_upsert(target_owner: &str) -> CalendarEventUpsert {updated_at: Utc::now(),},source: CalendarEventSource::Google(GoogleEventSource {+ observed_access_role: Some("owner".to_owned()),email_link_id: Uuid::now_v7(),account_id: Uuid::now_v7(),calendar_id: Uuid::now_v7(),@@ -1655,6 +1658,8 @@ fn echo_override() -> CalendarEventOverride {let original_start = Utc.with_ymd_and_hms(2026, 8, 18, 20, 0, 0).unwrap();CalendarEventOverride {+ visibility: None,+ transparency: None,sequence: None,source_updated_at: None,recurrence_id: recurrence_id.to_string(),diff --git a/crates/calendar_events/src/domain/ports.rs b/crates/calendar_events/src/domain/ports.rsindex 91d31cfd95..97bb219b50 100644--- a/crates/calendar_events/src/domain/ports.rs+++ b/crates/calendar_events/src/domain/ports.rs@@ -822,7 +822,8 @@ pub trait CalendarBackfillRepository: Send + Sync + 'static {key: CalendarBackfillJobKey,) -> impl Future<Output = Result<CalendarBackfillClaim, Report>> + Send;- /// Mark the account as actively syncing after a successful claim.+ /// Mark the account as actively syncing after a successful claim, preserving+ /// any prior failure until successful completion establishes healthy coverage.fn mark_google_account_syncing(&self,key: CalendarBackfillJobKey,diff --git a/crates/calendar_events/src/domain/service.rs b/crates/calendar_events/src/domain/service.rsindex e8dec5b778..5e058da900 100644--- a/crates/calendar_events/src/domain/service.rs+++ b/crates/calendar_events/src/domain/service.rs@@ -51,6 +51,7 @@ pub const MENTION_PREVIEWS_MAX: usize = 100;/// Calendar use cases with provider and persistence details behind ports.pub struct CalendarService<R> {repository: R,+ team_sharing_enabled: bool,}impl<R> CalendarService<R>@@ -59,7 +60,16 @@ where{/// Construct the service.pub fn new(repository: R) -> Self {- Self { repository }+ Self {+ repository,+ team_sharing_enabled: false,+ }+ }++ /// Enable legacy team status reads together with the team sharing rollout.+ pub fn with_team_sharing_enabled(mut self, enabled: bool) -> Self {+ self.team_sharing_enabled = enabled;+ self}/// Apply an OAuth grant using actual scopes returned by Google.@@ -109,11 +119,10 @@ where/// Query teammates' out-of-office occurrences in a bounded viewport.///- /// Teammates learn when — not necessarily why — each other are out: an- /// event marked private or confidential keeps its title withheld,- /// mirroring what Google shows viewers without full detail access. The- /// same provider event synced through more than one of a teammate's- /// connected inboxes collapses to one occurrence.+ /// This compatibility view requires explicit detail sharing. Private and+ /// confidential events are omitted because even their out-of-office type+ /// would disclose metadata beyond a generic busy block. Provider copies+ /// synced through multiple connected inboxes collapse to one occurrence.#[tracing::instrument(skip(self, requester_id, range), err)]pub async fn list_team_out_of_office(&self,@@ -122,6 +131,9 @@ wherelimit: u16,) -> Result<Vec<super::models::TeamOutOfOffice>, Report> {validate_query(&range, limit)?;+ if !self.team_sharing_enabled {+ return Ok(Vec::new());+ }let rows = self.repository.list_team_out_of_office(requester_id, range, limit)@@ -725,6 +737,7 @@ wherefor provider_calendar in calendars {let provider_calendar_id = provider_calendar.provider_calendar_id.clone();let watch_provider_calendar_id = provider_calendar.provider_calendar_id.clone();+ let observed_access_role = provider_calendar.access_role.clone();let is_read_only = !matches!(provider_calendar.access_role.as_deref(),Some("owner" | "writer")@@ -755,6 +768,7 @@ whereaccount_id,calendar_id,provider_calendar_id,+ observed_access_role,is_read_only,range: range.clone(),},@@ -763,7 +777,26 @@ where},).await- {+ .and_then(|batch| {+ // Coverage is trustworthy only if every normalized event+ // is usable. Reject before committing any part of this+ // calendar so its token cannot skip an omitted event.+ for upsert in &batch.upserts {+ validate_upsert(upsert).map_err(|error| {+ tracing::warn!(+ error=?error,+ calendar_id=%calendar_id,+ ical_uid=%upsert.event.ical_uid,+ "rejecting incomplete normalized Google Calendar batch"+ );+ GoogleProviderError::new(+ GoogleProviderErrorKind::Transient,+ "Google Calendar returned an invalid normalized event",+ )+ })?;+ }+ Ok(batch)+ }) {Ok(batch) => batch,Err(error) => {// A bad or insufficient grant is account-wide, not@@ -793,15 +826,6 @@ whereany_calendar_healthy = true;let mut calendar_count = 0;for upsert in batch.upserts {- if let Err(error) = validate_upsert(&upsert) {- tracing::warn!(- error=?error,- calendar_id=%calendar_id,- ical_uid=%upsert.event.ical_uid,- "skipping invalid normalized Google Calendar event"- );- continue;- }let super::models::CalendarEventSource::Google(source) = &upsert.source;debug_assert_eq!(source.calendar_id, calendar_id);let outcome = self@@ -920,7 +944,8 @@ where}// Record each isolated failure for the settings badge, leaving the- // calendar's sync state untouched so the next poll retries it.+ // calendar's sync state untouched so the next poll retries it. This+ // write must succeed before the account can report healthy coverage.for (calendar_id, message) in isolated_failures {self.repository.record_google_calendar_sync_error(@@ -930,15 +955,7 @@ wherecalendar_id,&message,)- .await- .inspect_err(|error| {- tracing::warn!(- error=?error,- calendar_id=%calendar_id,- "failed to record isolated Google Calendar sync error"- );- })- .ok();+ .await?;}// A calendar dropped from the provider's list retires its sources, sodiff --git a/crates/calendar_events/src/domain/service/test.rs b/crates/calendar_events/src/domain/service/test.rsindex f1294e0018..0473a7d744 100644--- a/crates/calendar_events/src/domain/service/test.rs+++ b/crates/calendar_events/src/domain/service/test.rs@@ -24,6 +24,8 @@ use std::sync::{Arc, Mutex};struct FakeRepo {upserts: Arc<Mutex<Vec<CalendarEventUpsert>>>,stored_synced_at: Option<chrono::DateTime<Utc>>,+ sync_snapshots: Arc<Mutex<Vec<GoogleCalendarSyncSnapshot>>>,+ fail_sync_error_recording: bool,/// Retirements the snapshot commit reports back, standing in for sources/// the change feed cancelled or a full snapshot no longer observed.sync_retirements: Vec<RetiredCalendarEvent>,@@ -182,9 +184,10 @@ impl CalendarRepository for FakeRepo {_key: CalendarBackfillJobKey,_lease_token: Uuid,_account_id: Uuid,- _sync: GoogleCalendarSyncSnapshot,+ sync: GoogleCalendarSyncSnapshot,_events_upserted: usize,) -> Result<Vec<RetiredCalendarEvent>, Report> {+ self.sync_snapshots.lock().unwrap().push(sync);Ok(self.sync_retirements.clone())}@@ -206,6 +209,9 @@ impl CalendarRepository for FakeRepo {_calendar_id: Uuid,message: &str,) -> Result<(), Report> {+ if self.fail_sync_error_recording {+ return Err(rootcause::report!("cannot persist calendar coverage error"));+ }self.recorded_sync_errors.lock().unwrap()@@ -318,6 +324,7 @@ fn valid_upsert() -> CalendarEventUpsert {updated_at: starts_at,},source: CalendarEventSource::Google(GoogleEventSource {+ observed_access_role: Some("owner".to_owned()),email_link_id: Uuid::now_v7(),account_id: Uuid::now_v7(),calendar_id: Uuid::now_v7(),@@ -1573,3 +1580,137 @@ async fn reauth_announcer_swallows_a_failing_notifier() {assert_eq!(notifier.notified.lock().unwrap().as_slice(), &[link]);}++/// Returns a valid event before an invalid one on a second calendar, so the+/// service must validate the whole calendar before accepting any of its rows.+#[derive(Clone)]+struct InvalidNormalizedGoogleProvider;++impl GoogleCalendarProvider for InvalidNormalizedGoogleProvider {+ async fn list_calendars(+ &self,+ _access_token: &str,+ _email_link_id: Uuid,+ ) -> Result<Vec<ProviderCalendar>, GoogleProviderError> {+ Ok(two_calendars())+ }++ async fn sync_events(+ &self,+ _access_token: &str,+ context: GoogleEventSyncContext,+ ) -> Result<GoogleEventSyncBatch, GoogleProviderError> {+ let mut valid = valid_upsert();+ let CalendarEventSource::Google(source) = &mut valid.source;+ source.calendar_id = context.target.calendar_id;+ let mut upserts = vec![valid.clone()];+ if context.target.provider_calendar_id == "team" {+ let start = Utc.with_ymd_and_hms(2026, 7, 24, 14, 0, 0).unwrap();+ valid.occurrences[0].time = EventTime::Timed {+ starts_at: start,+ ends_at: start,+ time_zone: None,+ };+ upserts.push(valid);+ }+ Ok(GoogleEventSyncBatch {+ upserts,+ observed_provider_event_ids: Some(vec!["provider-event".to_owned()]),+ next_sync_token: format!("next-{}", context.target.provider_calendar_id),+ materialized_range: Some(context.target.range),+ cancelled_provider_event_ids: Vec::new(),+ })+ }++ async fn watch_calendar(+ &self,+ _access_token: &str,+ _email_link_id: Uuid,+ _provider_calendar_id: &str,+ _channel_id: Uuid,+ _config: &GoogleWatchConfig,+ ) -> Result<GoogleWatchChannel, GoogleProviderError> {+ unreachable!("watch is disabled in these tests")+ }+}++#[tokio::test]+async fn invalid_normalized_calendar_never_commits_coverage_or_its_token() {+ let lifecycle = FakeLifecycle::claimed();+ let repository = FakeRepo::default();+ let upserts = repository.upserts.clone();+ let snapshots = repository.sync_snapshots.clone();+ let errors = repository.recorded_sync_errors.clone();+ let coordinator = GoogleCalendarBackfillCoordinator::new(+ repository,+ InvalidNormalizedGoogleProvider,+ lifecycle.clone(),+ NoopMacroEventBroker,+ None,+ );+ let key = CalendarBackfillJobKey {+ job_id: Uuid::now_v7(),+ email_link_id: Uuid::now_v7(),+ };+ for _ in 0..2 {+ let mut report = GoogleBackfillRunReport::default();+ coordinator+ .run(+ key,+ "macro|[email protected]",+ "secret",+ OccurrenceRange::maintenance_horizon(Utc::now()),+ &mut report,+ )+ .await+ .unwrap();+ assert_eq!(report.events_upserted, 1, "only the healthy calendar lands");+ }+ assert_eq!(upserts.lock().unwrap().len(), 2);+ let snapshots = snapshots.lock().unwrap();+ assert_eq!(snapshots.len(), 2);+ assert!(+ snapshots+ .iter()+ .all(|snapshot| snapshot.next_sync_token == "next-primary")+ );+ assert_eq!(+ errors.lock().unwrap().len(),+ 2,+ "a retry cannot erase the known coverage gap"+ );+ assert_eq!(lifecycle.completions.lock().unwrap().len(), 2);+}++#[tokio::test]+async fn failure_to_persist_calendar_quarantine_fails_the_account_run() {+ let lifecycle = FakeLifecycle::claimed();+ let coordinator = GoogleCalendarBackfillCoordinator::new(+ FakeRepo {+ fail_sync_error_recording: true,+ ..Default::default()+ },+ PartialFailureGoogleProvider,+ lifecycle.clone(),+ NoopMacroEventBroker,+ None,+ );+ let mut report = GoogleBackfillRunReport::default();+ assert!(+ coordinator+ .run(+ CalendarBackfillJobKey {+ job_id: Uuid::now_v7(),+ email_link_id: Uuid::now_v7(),+ },+ "macro|[email protected]",+ "secret",+ OccurrenceRange::maintenance_horizon(Utc::now()),+ &mut report,+ )+ .await+ .is_err()+ );+ assert!(lifecycle.completions.lock().unwrap().is_empty());+ assert_eq!(lifecycle.failures.lock().unwrap().len(), 1);+}diff --git a/crates/calendar_events/src/domain/team.rs b/crates/calendar_events/src/domain/team.rsnew file mode 100644index 0000000000..ff5d218cd3--- /dev/null+++ b/crates/calendar_events/src/domain/team.rs@@ -0,0 +1,9 @@+//! Source-scoped, read-only team calendar sharing.++mod models;+mod ports;+mod service;++pub use models::*;+pub use ports::*;+pub use service::{CalendarTeamServiceImpl, TeamCalendarError};diff --git a/crates/calendar_events/src/domain/team/models.rs b/crates/calendar_events/src/domain/team/models.rsnew file mode 100644index 0000000000..33d2208dc9--- /dev/null+++ b/crates/calendar_events/src/domain/team/models.rs@@ -0,0 +1,272 @@+//! Team projections and the source facts used to authorize them.++use serde::{Deserialize, Serialize};+use uuid::Uuid;++use crate::domain::models::{+ AttendeeResponseStatus, CalendarAttendee, CalendarEvent, CalendarEventOverride,+ CalendarOccurrence, EventStatus, EventTime, EventTransparency, EventType, EventVisibility,+};++/// Maximum source occurrences loaded for an availability calculation.+pub const TEAM_AVAILABILITY_LIMIT: u32 = 20_000;++/// What a user exposes through their team membership.+#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]+#[cfg_attr(feature = "schema", derive(utoipa::ToSchema))]+#[serde(rename_all = "snake_case")]+pub enum TeamCalendarSharing {+ /// Non-private event details from every synced calendar.+ All,+ /// Generic occupied intervals without event metadata.+ #[default]+ BusyOnly,+ /// No team-derived calendar access.+ None,+}++impl TeamCalendarSharing {+ /// Stored representation.+ pub fn as_str(self) -> &'static str {+ match self {+ Self::All => "all",+ Self::BusyOnly => "busy_only",+ Self::None => "none",+ }+ }+}++/// Whether a member's calendar projection can establish availability.+#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]+#[cfg_attr(feature = "schema", derive(utoipa::ToSchema))]+#[serde(rename_all = "snake_case")]+pub enum TeamCalendarCoverage {+ /// Every source has a recent, successful sync.+ Ready,+ /// No usable connected calendar or incomplete sync.+ Unavailable,+ /// The member does not share calendar data.+ Hidden,+}++/// A current member of the requester's team.+#[derive(Clone, Debug, Serialize, Deserialize)]+#[cfg_attr(feature = "schema", derive(utoipa::ToSchema))]+#[serde(rename_all = "camelCase")]+pub struct TeamCalendarMember {+ /// Macro user identifier.+ pub user_id: String,+ /// Current team-sharing policy.+ pub sharing: TeamCalendarSharing,+ /// Coverage available for a trustworthy calculation.+ pub coverage: TeamCalendarCoverage,+}++/// Content from exactly one authorized provider source; never a canonical merge.+#[derive(Clone, Debug)]+pub struct TeamSourceOccurrence {+ /// User whose current source access permits the team read.+ pub shared_by: String,+ /// Opaque provider-copy identifier internal to Macro.+ pub source_id: Uuid,+ /// Calendar containing this exact provider copy.+ pub calendar_id: Uuid,+ /// Name of this source calendar.+ pub calendar_name: String,+ /// Zone interpreting all-day dates on this source.+ pub calendar_time_zone: Option<String>,+ /// Whether this calendar was included in this user's personal availability.+ pub contributes_to_availability: bool,+ /// Addresses the sharing user owns, never delegated addresses.+ pub owner_emails: Vec<String>,+ /// Exact provider source's event snapshot.+ pub event: CalendarEvent,+ /// Exact provider source's occurrence snapshot.+ pub occurrence: CalendarOccurrence,+ /// Exact provider source's recurrence overrides.+ pub overrides: Vec<CalendarEventOverride>,+}++impl TeamSourceOccurrence {+ /// Visibility used by a team view. An instance can restrict disclosure,+ /// but cannot unhide content from a private series snapshot.+ pub fn visibility(&self) -> EventVisibility {+ if matches!(+ self.event.visibility,+ EventVisibility::Private | EventVisibility::Confidential+ ) {+ return self.event.visibility;+ }+ self.exception()+ .and_then(|exception| exception.visibility)+ .unwrap_or(self.event.visibility)+ }++ /// The occurrence's availability, including a provider exception.+ pub fn transparency(&self) -> EventTransparency {+ self.exception()+ .and_then(|exception| exception.transparency)+ .unwrap_or(self.event.transparency)+ }++ /// Whether this source occurrence blocks its source calendar at all.+ pub fn is_busy(&self) -> bool {+ !self.occurrence.is_cancelled+ && self.event.status != EventStatus::Cancelled+ && self.exception().and_then(|item| item.status) != Some(EventStatus::Cancelled)+ && self.transparency() != EventTransparency::Transparent+ && !matches!(+ self.event.event_type,+ EventType::Birthday | EventType::WorkingLocation+ )+ }+ /// The source's exception for this occurrence.+ pub fn exception(&self) -> Option<&CalendarEventOverride> {+ let key = self.occurrence.recurrence_id.as_ref()?;+ self.overrides+ .iter()+ .find(|item| &item.recurrence_id == key)+ }++ /// Attendees with an occurrence-scoped response applied.+ pub fn attendees(&self) -> &[CalendarAttendee] {+ self.exception()+ .and_then(|item| item.attendees.as_deref())+ .unwrap_or(&self.event.attendees)+ }++ /// Whether the occurrence represents this person's busy time.+ pub fn is_personally_busy(&self) -> bool {+ if !self.is_busy() {+ return false;+ }+ let owned: Vec<_> = self+ .attendees()+ .iter()+ .filter(|attendee| {+ self.owner_emails+ .iter()+ .any(|email| email.eq_ignore_ascii_case(&attendee.email))+ })+ .collect();+ if !owned.is_empty()+ && owned+ .iter()+ .all(|attendee| attendee.response_status == AttendeeResponseStatus::Declined)+ {+ return false;+ }+ self.contributes_to_availability || !owned.is_empty()+ }+}++/// Authorized input for a domain availability calculation; never serialized.+#[derive(Clone, Debug)]+pub struct TeamAvailabilitySources {+ /// Selected known members, including the requester.+ pub members: Vec<TeamCalendarMember>,+ /// Same-source event snapshots authorized for the calculation.+ pub sources: Vec<TeamSourceOccurrence>,+ /// Whether every contributing row was loaded.+ pub complete: bool,+ /// Requested identifiers without a current team relationship.+ pub unknown_user_ids: Vec<String>,+}++/// Keyset position over authorized provider sources and their occurrences.+#[derive(Clone, Debug, Serialize, Deserialize)]+#[serde(rename_all = "camelCase")]+pub struct TeamCalendarCursor {+ /// Entitlement/source revision at the start of pagination.+ pub revision: String,+ /// Last sharing member.+ pub user_id: String,+ /// Last source snapshot.+ pub source_id: Uuid,+ /// Last occurrence within that source.+ pub occurrence_key: String,+}++/// Safe details from a single authorized source.+#[derive(Clone, Debug, Serialize, Deserialize)]+#[cfg_attr(feature = "schema", derive(utoipa::ToSchema))]+#[serde(rename_all = "camelCase")]+pub struct TeamCalendarDetails {+ /// Display title.+ pub title: String,+ /// Body, if supplied by this source.+ pub description: Option<String>,+ /// Location, if supplied by this source.+ pub location: Option<String>,+ /// Join URL, if supplied by this source.+ pub conference_url: Option<String>,+ /// Organizer address from this source.+ pub organizer_email: Option<String>,+ /// Organizer name from this source.+ pub organizer_name: Option<String>,+ /// Attendees; self flags are relative to the requesting viewer.+ pub attendees: Vec<CalendarAttendee>,+ /// Source calendar name, shown only with details.+ pub calendar_name: String,+}++/// Disjoint busy/detail shapes prevent new event fields leaking by default.+#[derive(Clone, Debug, Serialize, Deserialize)]+#[cfg_attr(feature = "schema", derive(utoipa::ToSchema))]+#[serde(tag = "kind", rename_all = "snake_case")]+pub enum TeamCalendarContent {+ /// No provider or event metadata.+ Busy,+ /// Explicitly authorized source content.+ Details {+ /// Detail projection.+ details: TeamCalendarDetails,+ },+}++/// A read-only team calendar occurrence.+#[derive(Clone, Debug, Serialize, Deserialize)]+#[cfg_attr(feature = "schema", derive(utoipa::ToSchema))]+#[serde(rename_all = "camelCase")]+pub struct TeamCalendarItem {+ /// Stable opaque projection identity, never an event entity id.+ pub id: String,+ /// The person sharing access to the source.+ pub owner_id: String,+ /// Occurrence interval.+ pub time: EventTime,+ /// Whether this occurrence blocks the sharer's personal availability.+ /// A subscribed calendar's block can be shared without occupying the sharer.+ pub contributes_to_availability: bool,+ /// Authorized content variant.+ #[serde(flatten)]+ pub content: TeamCalendarContent,+}++/// A bounded page of team calendar projections.+#[derive(Clone, Debug, Serialize, Deserialize)]+#[cfg_attr(feature = "schema", derive(utoipa::ToSchema))]+#[serde(rename_all = "camelCase")]+pub struct TeamCalendarPage {+ /// Current membership and sharing policies.+ pub members: Vec<TeamCalendarMember>,+ /// Authorized read-only projections.+ pub items: Vec<TeamCalendarItem>,+ /// Opaque continuation token; null after the last source occurrence.+ pub next_cursor: Option<String>,+}++/// Per-user inclusion of a source calendar in personal availability.+#[derive(Clone, Debug, Serialize, Deserialize)]+#[cfg_attr(feature = "schema", derive(utoipa::ToSchema))]+#[serde(rename_all = "camelCase")]+pub struct AvailabilityCalendar {+ /// Visible source calendar.+ pub calendar_id: Uuid,+ /// Source name.+ pub name: String,+ /// Whether its events normally block the user's time.+ pub contributes_to_availability: bool,+ /// Whether this is the connected account's primary calendar.+ pub is_primary: bool,+}diff --git a/crates/calendar_events/src/domain/team/ports.rs b/crates/calendar_events/src/domain/team/ports.rsnew file mode 100644index 0000000000..add6db7635--- /dev/null+++ b/crates/calendar_events/src/domain/team/ports.rs@@ -0,0 +1,116 @@+//! Domain ports for team projections and sharing policy.++use super::*;+use crate::domain::{models::OccurrenceRange, team_availability::TeamAvailability};+use rootcause::Report;+use std::future::Future;+use uuid::Uuid;++/// Repository facts scoped to current membership and direct synced-source access.+pub trait CalendarTeamRepository: Send + Sync + 'static {+ /// Changes when membership, policy, source access, or source content changes.+ fn projection_revision(+ &self,+ requester: &str,+ ) -> impl Future<Output = Result<String, Report>> + Send;+ /// Current teammates; include_self adds the requester's direct source context.+ /// A routine refresh keeps a recent, verified successful snapshot usable;+ /// stale, failed, unverified, or incomplete source coverage remains unknown.+ fn members(+ &self,+ requester: &str,+ include_self: bool,+ range: &OccurrenceRange,+ ) -> impl Future<Output = Result<Vec<TeamCalendarMember>, Report>> + Send;+ /// Read one bounded page; selected owners can only narrow current membership.+ fn sources(+ &self,+ requester: &str,+ range: OccurrenceRange,+ owners: &[String],+ cursor: Option<&TeamCalendarCursor>,+ limit: u32,+ ) -> impl Future<Output = Result<Vec<TeamSourceOccurrence>, Report>> + Send;+ /// Addresses owned by this viewer for requester-relative attendee flags.+ fn owned_emails(+ &self,+ requester: &str,+ ) -> impl Future<Output = Result<Vec<String>, Report>> + Send;+ /// Stored or default sharing policy.+ fn sharing(+ &self,+ requester: &str,+ ) -> impl Future<Output = Result<TeamCalendarSharing, Report>> + Send;+ /// Set only the authenticated user's own policy.+ fn set_sharing(+ &self,+ requester: &str,+ sharing: TeamCalendarSharing,+ ) -> impl Future<Output = Result<(), Report>> + Send;+ /// Visible source calendars and their personal availability inclusion.+ fn availability_calendars(+ &self,+ requester: &str,+ ) -> impl Future<Output = Result<Vec<AvailabilityCalendar>, Report>> + Send;+ /// Change inclusion if this source is still directly visible; false if access vanished.+ fn set_availability_calendar(+ &self,+ requester: &str,+ calendar: Uuid,+ contributes: bool,+ ) -> impl Future<Output = Result<bool, Report>> + Send;+}++/// Notify current viewers after changing a sharing entitlement.+pub trait CalendarTeamNotifier: Send + Sync + 'static {+ /// Promptly purge/refetch projections derived from this user's policy.+ fn sharing_changed(&self, user_id: &str) -> impl Future<Output = ()> + Send;+}++/// No notifications for services exposing reads only.+pub struct NoopTeamNotifier;+impl CalendarTeamNotifier for NoopTeamNotifier {+ async fn sharing_changed(&self, _user_id: &str) {}+}++/// Team calendar use cases. Provider writes are deliberately absent.+pub trait CalendarTeamService: Send + Sync + 'static {+ /// Paginated read-only team calendar projections; limit zero reads only the roster.+ fn list_team_calendar(+ &self,+ requester: &str,+ range: OccurrenceRange,+ cursor: Option<TeamCalendarCursor>,+ limit: u16,+ ) -> impl Future<Output = Result<TeamCalendarPage, Report>> + Send;+ /// Policy for the authenticated user.+ fn team_sharing(+ &self,+ requester: &str,+ ) -> impl Future<Output = Result<TeamCalendarSharing, Report>> + Send;+ /// Set the authenticated user's policy without changing Google permissions.+ fn set_team_sharing(+ &self,+ requester: &str,+ sharing: TeamCalendarSharing,+ ) -> impl Future<Output = Result<TeamCalendarSharing, Report>> + Send;+ /// Calendars contributing to personal availability.+ fn availability_calendars(+ &self,+ requester: &str,+ ) -> impl Future<Output = Result<Vec<AvailabilityCalendar>, Report>> + Send;+ /// Change the inclusion of a directly visible source.+ fn set_availability_calendar(+ &self,+ requester: &str,+ calendar: Uuid,+ contributes: bool,+ ) -> impl Future<Output = Result<(), Report>> + Send;+ /// Compute coverage-aware availability using authorized source snapshots.+ fn get_team_availability(+ &self,+ requester: &str,+ range: OccurrenceRange,+ user_ids: Option<&[String]>,+ ) -> impl Future<Output = Result<TeamAvailability, Report>> + Send;+}diff --git a/crates/calendar_events/src/domain/team/service.rs b/crates/calendar_events/src/domain/team/service.rsnew file mode 100644index 0000000000..3a2bb8c9ea--- /dev/null+++ b/crates/calendar_events/src/domain/team/service.rs@@ -0,0 +1,344 @@+//! Team policy is applied before data reaches any transport adapter.++use super::*;+use crate::domain::{+ models::{EventVisibility, OccurrenceRange},+ team_availability::{self, TeamAvailability},+};+use chrono::Utc;+use rootcause::Report;+use std::collections::{HashMap, HashSet};+use uuid::Uuid;++/// Invalid team-calendar request or unavailable source access.+#[derive(Debug, thiserror::Error)]+pub enum TeamCalendarError {+ /// The bounded query is outside supported limits.+ #[error("invalid calendar range, cursor, or page size")]+ InvalidQuery,+ /// The requested availability selection exceeds the supported member bound.+ #[error("too many people selected; choose at most 100 teammates using userIds")]+ TooManyMembers,+ /// The source calendar is no longer directly visible to the requester.+ #[error("calendar not found")]+ NotFound,+ /// Team data reads have not been enabled for this deployment.+ #[error("team calendar sharing is not enabled")]+ Disabled,+}++/// Source-aware team calendar domain implementation.+pub struct CalendarTeamServiceImpl<R, N = NoopTeamNotifier> {+ repository: R,+ notifier: N,+ enabled: bool,+}++impl<R> CalendarTeamServiceImpl<R> {+ /// Construct a read-only host's service.+ pub fn new(repository: R, enabled: bool) -> Self {+ Self {+ repository,+ notifier: NoopTeamNotifier,+ enabled,+ }+ }+}++impl<R, N> CalendarTeamServiceImpl<R, N> {+ /// Construct the write authority with entitlement-change notifications.+ pub fn with_notifier(repository: R, notifier: N, enabled: bool) -> Self {+ Self {+ repository,+ notifier,+ enabled,+ }+ }+}++fn validate_range(range: &OccurrenceRange) -> Result<(), Report> {+ if !range.is_valid() || !range.is_materialized_at(Utc::now()) {+ return Err(rootcause::report!(TeamCalendarError::InvalidQuery).into());+ }+ Ok(())+}++impl<R: CalendarTeamRepository, N: CalendarTeamNotifier> CalendarTeamService+ for CalendarTeamServiceImpl<R, N>+{+ async fn list_team_calendar(+ &self,+ requester: &str,+ range: OccurrenceRange,+ cursor: Option<TeamCalendarCursor>,+ limit: u16,+ ) -> Result<TeamCalendarPage, Report> {+ if !self.enabled {+ return Err(rootcause::report!(TeamCalendarError::Disabled).into());+ }+ validate_range(&range)?;+ if limit > 2000 || (limit == 0 && cursor.is_some()) {+ return Err(rootcause::report!(TeamCalendarError::InvalidQuery).into());+ }+ let revision = self.repository.projection_revision(requester).await?;+ if cursor+ .as_ref()+ .is_some_and(|cursor| cursor.revision != revision)+ {+ return Err(rootcause::report!(TeamCalendarError::InvalidQuery).into());+ }+ let members = self.repository.members(requester, false, &range).await?;+ if limit == 0 {+ if self.repository.projection_revision(requester).await? != revision {+ return Err(rootcause::report!(TeamCalendarError::InvalidQuery).into());+ }+ return Ok(TeamCalendarPage {+ members,+ items: vec![],+ next_cursor: None,+ });+ }+ let owners: Vec<_> = members+ .iter()+ .filter(|member| member.sharing != TeamCalendarSharing::None)+ .map(|member| member.user_id.clone())+ .collect();+ let mut sources = self+ .repository+ .sources(+ requester,+ range,+ &owners,+ cursor.as_ref(),+ u32::from(limit) + 1,+ )+ .await?;+ let more = sources.len() > usize::from(limit);+ sources.truncate(usize::from(limit));+ let next_cursor = if more {+ sources+ .last()+ .map(|row| {+ serde_json::to_string(&TeamCalendarCursor {+ revision: revision.clone(),+ user_id: row.shared_by.clone(),+ source_id: row.source_id,+ occurrence_key: row.occurrence.occurrence_key.clone(),+ })+ })+ .transpose()+ .map_err(|error| rootcause::report!(error))?+ } else {+ None+ };+ let policies: HashMap<_, _> = members+ .iter()+ .map(|member| (member.user_id.as_str(), member.sharing))+ .collect();+ let viewer_emails = self.repository.owned_emails(requester).await?;+ let items = sources+ .into_iter()+ .filter_map(|source| {+ let sharing = policies.get(source.shared_by.as_str()).copied()?;+ // Keep deterministic source order across page boundaries. The+ // consumer replaces whole projections with equal opaque ids;+ // collapsing only within a page would make the selected copy+ // depend on page size. No fields from different sources merge.+ project(&source, sharing, &viewer_emails)+ })+ .collect();+ if self.repository.projection_revision(requester).await? != revision {+ return Err(rootcause::report!(TeamCalendarError::InvalidQuery).into());+ }+ Ok(TeamCalendarPage {+ members,+ items,+ next_cursor,+ })+ }++ async fn team_sharing(&self, requester: &str) -> Result<TeamCalendarSharing, Report> {+ self.repository.sharing(requester).await+ }++ async fn set_team_sharing(+ &self,+ requester: &str,+ sharing: TeamCalendarSharing,+ ) -> Result<TeamCalendarSharing, Report> {+ self.repository.set_sharing(requester, sharing).await?;+ self.notifier.sharing_changed(requester).await;+ Ok(sharing)+ }++ async fn availability_calendars(+ &self,+ requester: &str,+ ) -> Result<Vec<AvailabilityCalendar>, Report> {+ self.repository.availability_calendars(requester).await+ }++ async fn set_availability_calendar(+ &self,+ requester: &str,+ calendar: Uuid,+ contributes: bool,+ ) -> Result<(), Report> {+ if !self+ .repository+ .set_availability_calendar(requester, calendar, contributes)+ .await?+ {+ return Err(rootcause::report!(TeamCalendarError::NotFound).into());+ }+ self.notifier.sharing_changed(requester).await;+ Ok(())+ }++ async fn get_team_availability(+ &self,+ requester: &str,+ range: OccurrenceRange,+ user_ids: Option<&[String]>,+ ) -> Result<TeamAvailability, Report> {+ if !self.enabled {+ return Err(rootcause::report!(TeamCalendarError::Disabled).into());+ }+ validate_range(&range)?;+ if user_ids.is_some_and(|ids| ids.len() > 100) {+ return Err(rootcause::report!(TeamCalendarError::TooManyMembers).into());+ }+ let revision = self.repository.projection_revision(requester).await?;+ let mut source_range = range.clone();+ source_range.start_date = range+ .starts_at+ .date_naive()+ .pred_opt()+ .ok_or_else(|| rootcause::report!(TeamCalendarError::InvalidQuery))?;+ source_range.end_date = range+ .ends_at+ .date_naive()+ .checked_add_days(chrono::Days::new(2))+ .ok_or_else(|| rootcause::report!(TeamCalendarError::InvalidQuery))?;+ let mut members = self+ .repository+ .members(requester, true, &source_range)+ .await?;+ let known: HashSet<_> = members+ .iter()+ .map(|member| member.user_id.clone())+ .collect();+ let unknown_user_ids: Vec<_> = user_ids+ .unwrap_or_default()+ .iter()+ .filter(|id| !known.contains(*id))+ .cloned()+ .collect();+ members.retain(|member| {+ member.user_id == requester || user_ids.is_none_or(|ids| ids.contains(&member.user_id))+ });+ if members.len() > 101 {+ return Err(rootcause::report!(TeamCalendarError::TooManyMembers).into());+ }+ let owners: Vec<_> = members+ .iter()+ .filter(|member| {+ member.user_id == requester || member.sharing != TeamCalendarSharing::None+ })+ .map(|member| member.user_id.clone())+ .collect();+ let mut sources = self+ .repository+ .sources(+ requester,+ source_range,+ &owners,+ None,+ TEAM_AVAILABILITY_LIMIT + 1,+ )+ .await?;+ let complete = sources.len() <= TEAM_AVAILABILITY_LIMIT as usize;+ sources.truncate(TEAM_AVAILABILITY_LIMIT as usize);+ if self.repository.projection_revision(requester).await? != revision {+ return Err(rootcause::report!(TeamCalendarError::InvalidQuery).into());+ }+ Ok(team_availability::calculate(+ range,+ TeamAvailabilitySources {+ members,+ sources,+ complete,+ unknown_user_ids,+ },+ ))+ }+}++fn project(+ source: &TeamSourceOccurrence,+ sharing: TeamCalendarSharing,+ viewer_emails: &[String],+) -> Option<TeamCalendarItem> {+ if sharing == TeamCalendarSharing::None+ || source.occurrence.is_cancelled+ || source.event.status == crate::domain::models::EventStatus::Cancelled+ || source.exception().and_then(|item| item.status)+ == Some(crate::domain::models::EventStatus::Cancelled)+ {+ return None;+ }+ let may_show_details = sharing == TeamCalendarSharing::All+ && matches!(+ source.visibility(),+ EventVisibility::Default | EventVisibility::Public+ );+ let content = if may_show_details {+ let exception = source.exception();+ let mut attendees = source.attendees().to_vec();+ for attendee in &mut attendees {+ attendee.is_self = viewer_emails+ .iter()+ .any(|email| email.eq_ignore_ascii_case(&attendee.email));+ }+ TeamCalendarContent::Details {+ details: TeamCalendarDetails {+ title: exception+ .and_then(|item| item.title.clone())+ .unwrap_or_else(|| source.event.title.clone()),+ description: exception+ .and_then(|item| item.description.clone())+ .or_else(|| source.event.description.clone()),+ location: exception+ .and_then(|item| item.location.clone())+ .or_else(|| source.event.location.clone()),+ conference_url: source.event.conference_url.clone(),+ organizer_email: source.event.organizer_email.clone(),+ organizer_name: source.event.organizer_name.clone(),+ attendees,+ calendar_name: source.calendar_name.clone(),+ },+ }+ } else {+ if !source.is_busy() {+ return None;+ }+ TeamCalendarContent::Busy+ };+ let identity = serde_json::to_vec(&(+ &source.shared_by,+ source.source_id,+ &source.event.ical_uid,+ &source.occurrence.occurrence_key,+ ))+ .ok()?;+ Some(TeamCalendarItem {+ id: Uuid::new_v5(&Uuid::NAMESPACE_OID, &identity).to_string(),+ owner_id: source.shared_by.clone(),+ time: source.occurrence.time.clone(),+ contributes_to_availability: source.is_personally_busy(),+ content,+ })+}++#[cfg(test)]+mod test;diff --git a/crates/calendar_events/src/domain/team/service/test.rs b/crates/calendar_events/src/domain/team/service/test.rsnew file mode 100644index 0000000000..016b0a1df9--- /dev/null+++ b/crates/calendar_events/src/domain/team/service/test.rs@@ -0,0 +1,499 @@+use super::*;+use crate::domain::models::{+ CalendarEvent, CalendarEventOverride, CalendarOccurrence, EventStart, EventTime, EventType,+ EventVisibility,+};+use std::sync::{+ Mutex,+ atomic::{AtomicUsize, Ordering},+};++fn source() -> TeamSourceOccurrence {+ let id = Uuid::now_v7();+ let time = EventTime::Timed {+ starts_at: Utc::now(),+ ends_at: Utc::now() + chrono::Duration::hours(1),+ time_zone: Some("UTC".into()),+ };+ let event: CalendarEvent = serde_json::from_value(serde_json::json!({+ "id": id, "ownerId": "owner", "icalUid": "sensitive-provider-uid", "title": "Sensitive appointment",+ "description": "Sensitive body", "location": "Sensitive location", "status": "confirmed",+ "visibility": "default", "transparency": "opaque", "eventType": "focus_time", "time": time,+ "recurrenceLines": [], "organizerEmail": "[email protected]", "organizerName": "Owner",+ "conferenceUrl": "https://meet.example.com/private", "sequence": 1, "isReadOnly": false,+ "attendees": [{"email":"[email protected]","displayName":"Owner","responseStatus":"accepted","isOrganizer":true,"isOptional":false,"isSelf":true}],+ "createdAt": Utc::now(), "updatedAt": Utc::now()+ })).unwrap();+ TeamSourceOccurrence {+ shared_by: "owner".into(),+ source_id: Uuid::now_v7(),+ calendar_id: Uuid::now_v7(),+ calendar_name: "Sensitive calendar".into(),+ calendar_time_zone: Some("UTC".into()),+ contributes_to_availability: true,+ owner_emails: vec!["[email protected]".into()],+ occurrence: CalendarOccurrence {+ event_id: id,+ occurrence_key: "instance".into(),+ recurrence_id: None,+ time,+ is_cancelled: false,+ },+ event,+ overrides: vec![],+ }+}++fn range() -> OccurrenceRange {+ let now = Utc::now();+ OccurrenceRange {+ starts_at: now,+ ends_at: now + chrono::Duration::days(1),+ start_date: now.date_naive(),+ end_date: now.date_naive().succ_opt().unwrap(),+ }+}++#[test]+fn busy_and_private_projection_has_no_event_content_or_ids() {+ let mut row = source();+ for (sharing, visibility) in [+ (TeamCalendarSharing::BusyOnly, EventVisibility::Default),+ (TeamCalendarSharing::All, EventVisibility::Private),+ (TeamCalendarSharing::All, EventVisibility::Confidential),+ ] {+ row.event.visibility = visibility;+ let json = serde_json::to_value(project(&row, sharing, &[]).unwrap()).unwrap();+ assert_eq!(json["kind"], "busy");+ let serialized = json.to_string();+ for forbidden in [+ "Sensitive",+ "focus_time",+ "sensitive-provider-uid",+ "[email protected]",+ "meet.example",+ &row.event.id.to_string(),+ ] {+ assert!(!serialized.contains(forbidden), "leaked {forbidden}");+ }+ assert_eq!(json.as_object().unwrap().len(), 5);+ }+ assert!(project(&row, TeamCalendarSharing::None, &[]).is_none());+}++#[test]+fn subscribed_busy_block_is_shared_without_claiming_personal_busyness() {+ let mut row = source();+ row.contributes_to_availability = false;+ row.owner_emails = vec!["[email protected]".into()];+ let item = project(&row, TeamCalendarSharing::BusyOnly, &[]).unwrap();+ assert!(!item.contributes_to_availability);+ row.event.event_type = EventType::WorkingLocation;+ assert!(project(&row, TeamCalendarSharing::BusyOnly, &[]).is_none());+}++#[test]+fn detailed_attendee_flags_are_viewer_relative() {+ let row = source();+ let item = project(+ &row,+ TeamCalendarSharing::All,+ &["[email protected]".into()],+ )+ .unwrap();+ let TeamCalendarContent::Details { details } = item.content else {+ panic!("expected details")+ };+ assert!(!details.attendees[0].is_self);+}++#[test]+fn projection_identity_is_stable_per_source_and_distinct_across_provider_copies() {+ let row = source();+ let mut other_source = row.clone();+ other_source.source_id = Uuid::now_v7();+ other_source.event.id = Uuid::now_v7();+ other_source.calendar_id = Uuid::now_v7();+ other_source.event.title = "Different source details".into();+ other_source.contributes_to_availability = false;+ other_source.owner_emails = vec!["[email protected]".into()];+ for sharing in [TeamCalendarSharing::BusyOnly, TeamCalendarSharing::All] {+ let first = project(&row, sharing, &[]).unwrap();+ let repeated = project(&row, sharing, &[]).unwrap();+ let other = project(&other_source, sharing, &[]).unwrap();+ assert_eq!(first.id, repeated.id);+ assert_ne!(first.id, other.id);+ assert!(first.contributes_to_availability);+ assert!(!other.contributes_to_availability);+ assert_ne!(first.id, row.source_id.to_string());+ }+ assert_eq!(+ project(&row, TeamCalendarSharing::BusyOnly, &[])+ .unwrap()+ .id,+ project(&row, TeamCalendarSharing::All, &[]).unwrap().id,+ "a policy change must update the same source projection"+ );+}++#[test]+fn a_private_exception_cannot_expose_its_replacement_title() {+ let mut row = source();+ row.occurrence.recurrence_id = Some("original".into());+ row.overrides.push(CalendarEventOverride {+ sequence: None,+ source_updated_at: None,+ recurrence_id: "original".into(),+ original_time: EventStart::Timed(Utc::now()),+ time: row.occurrence.time.clone(),+ title: Some("Private exception appointment".into()),+ description: None,+ location: None,+ status: None,+ visibility: Some(EventVisibility::Private),+ transparency: None,+ attendees: None,+ });+ let item = project(&row, TeamCalendarSharing::All, &[]).unwrap();+ assert!(matches!(item.content, TeamCalendarContent::Busy));+ let serialized = serde_json::to_string(&item).unwrap();+ assert!(!serialized.contains("Private exception"));+ assert!(!serialized.contains("Sensitive"));+}++#[derive(Default)]+struct Repository {+ owners: Mutex<Vec<String>>,+ additional_members: usize,+ rows: Vec<TeamSourceOccurrence>,+ forbid_event_reads: bool,+ change_revision: bool,+ revision_reads: AtomicUsize,+}+impl CalendarTeamRepository for Repository {+ async fn projection_revision(&self, _: &str) -> Result<String, Report> {+ if self.revision_reads.fetch_add(1, Ordering::Relaxed) > 0 && self.change_revision {+ return Ok("changed".into());+ }+ Ok("current".into())+ }+ async fn members(+ &self,+ requester: &str,+ include_self: bool,+ _: &OccurrenceRange,+ ) -> Result<Vec<TeamCalendarMember>, Report> {+ let mut members = vec![TeamCalendarMember {+ user_id: "owner".into(),+ sharing: TeamCalendarSharing::BusyOnly,+ coverage: TeamCalendarCoverage::Ready,+ }];+ members.extend(+ (0..self.additional_members).map(|index| TeamCalendarMember {+ user_id: format!("teammate-{index}"),+ sharing: TeamCalendarSharing::BusyOnly,+ coverage: TeamCalendarCoverage::Ready,+ }),+ );+ if include_self {+ members.push(TeamCalendarMember {+ user_id: requester.into(),+ sharing: TeamCalendarSharing::All,+ coverage: TeamCalendarCoverage::Ready,+ });+ }+ Ok(members)+ }+ async fn sources(+ &self,+ _: &str,+ _: OccurrenceRange,+ owners: &[String],+ cursor: Option<&TeamCalendarCursor>,+ limit: u32,+ ) -> Result<Vec<TeamSourceOccurrence>, Report> {+ assert!(!self.forbid_event_reads, "roster must not load occurrences");+ *self.owners.lock().unwrap() = owners.to_vec();+ let mut rows: Vec<_> = self+ .rows+ .iter()+ .filter(|row| owners.contains(&row.shared_by))+ .filter(|row| {+ cursor.is_none_or(|cursor| {+ (+ &row.shared_by,+ row.source_id,+ &row.occurrence.occurrence_key,+ ) > (&cursor.user_id, cursor.source_id, &cursor.occurrence_key)+ })+ })+ .cloned()+ .collect();+ rows.sort_by_key(|row| {+ (+ row.shared_by.clone(),+ row.source_id,+ row.occurrence.occurrence_key.clone(),+ )+ });+ rows.truncate(limit as usize);+ Ok(rows)+ }+ async fn owned_emails(&self, _: &str) -> Result<Vec<String>, Report> {+ assert!(+ !self.forbid_event_reads,+ "roster must not load owned emails"+ );+ Ok(vec![])+ }+ async fn sharing(&self, _: &str) -> Result<TeamCalendarSharing, Report> {+ Ok(TeamCalendarSharing::default())+ }+ async fn set_sharing(&self, _: &str, _: TeamCalendarSharing) -> Result<(), Report> {+ Ok(())+ }+ async fn availability_calendars(&self, _: &str) -> Result<Vec<AvailabilityCalendar>, Report> {+ Ok(vec![])+ }+ async fn set_availability_calendar(&self, _: &str, _: Uuid, _: bool) -> Result<bool, Report> {+ Ok(false)+ }+}++#[tokio::test]+async fn roster_only_skips_event_reads_and_rejects_cursors_or_invalid_ranges() {+ let service = CalendarTeamServiceImpl::new(+ Repository {+ forbid_event_reads: true,+ ..Repository::default()+ },+ true,+ );+ let page = service+ .list_team_calendar("viewer", range(), None, 0)+ .await+ .unwrap();+ assert_eq!(page.members.len(), 1);+ assert_eq!(page.members[0].user_id, "owner");+ assert!(page.items.is_empty());+ assert!(page.next_cursor.is_none());+ assert_eq!(service.repository.revision_reads.load(Ordering::Relaxed), 2);++ let cursor = TeamCalendarCursor {+ revision: "current".into(),+ user_id: "owner".into(),+ source_id: Uuid::now_v7(),+ occurrence_key: "x".into(),+ };+ assert!(+ service+ .list_team_calendar("viewer", range(), Some(cursor), 0)+ .await+ .is_err()+ );+ let mut invalid_range = range();+ invalid_range.ends_at = invalid_range.starts_at;+ assert!(+ service+ .list_team_calendar("viewer", invalid_range, None, 0)+ .await+ .is_err()+ );+ assert_eq!(service.repository.revision_reads.load(Ordering::Relaxed), 2);+}++#[tokio::test]+async fn roster_only_enforces_the_gate_and_rechecks_authorization_revision() {+ for (enabled, change_revision) in [(false, false), (true, true)] {+ let service = CalendarTeamServiceImpl::new(+ Repository {+ forbid_event_reads: true,+ change_revision,+ ..Repository::default()+ },+ enabled,+ );+ assert!(+ service+ .list_team_calendar("viewer", range(), None, 0)+ .await+ .is_err()+ );+ assert_eq!(+ service.repository.revision_reads.load(Ordering::Relaxed),+ if enabled { 2 } else { 0 }+ );+ }+}++#[tokio::test]+async fn disabled_reads_and_stale_cursor_fail_closed() {+ let service = CalendarTeamServiceImpl::new(Repository::default(), false);+ assert!(+ service+ .list_team_calendar("viewer", range(), None, 10)+ .await+ .is_err()+ );+ assert!(+ service+ .get_team_availability("viewer", range(), None)+ .await+ .is_err()+ );+ assert_eq!(+ service.team_sharing("viewer").await.unwrap(),+ TeamCalendarSharing::BusyOnly+ );+ let service = CalendarTeamServiceImpl::new(Repository::default(), true);+ let cursor = TeamCalendarCursor {+ revision: "old".into(),+ user_id: "owner".into(),+ source_id: Uuid::now_v7(),+ occurrence_key: "x".into(),+ };+ assert!(+ service+ .list_team_calendar("viewer", range(), Some(cursor), 10)+ .await+ .is_err()+ );+}++#[tokio::test]+async fn selected_unknown_ids_do_not_broaden_and_requester_is_always_included() {+ let service = CalendarTeamServiceImpl::new(Repository::default(), true);+ let result = service+ .get_team_availability("viewer", range(), Some(&["outsider".into()]))+ .await+ .unwrap();+ assert_eq!(+ service.repository.owners.lock().unwrap().as_slice(),+ &["viewer"]+ );+ assert_eq!(result.unknown_user_ids, vec!["outsider"]);+ assert!(!result.complete);+ assert!(result.free_windows.is_none());+ let result = service+ .get_team_availability("viewer", range(), Some(&[]))+ .await+ .unwrap();+ assert_eq!(result.members.len(), 1);+ assert_eq!(result.members[0].user_id, "viewer");+}++#[tokio::test]+async fn oversized_availability_selection_returns_actionable_error_without_loading_sources() {+ let service = CalendarTeamServiceImpl::new(+ Repository {+ additional_members: 100,+ forbid_event_reads: true,+ ..Repository::default()+ },+ true,+ );+ let explicit = (0..101)+ .map(|index| format!("teammate-{index}"))+ .collect::<Vec<_>>();+ for selection in [None, Some(explicit.as_slice())] {+ let error = service+ .get_team_availability("viewer", range(), selection)+ .await+ .unwrap_err();+ assert!(matches!(+ error+ .as_ref()+ .downcast_current_context::<TeamCalendarError>(),+ Some(TeamCalendarError::TooManyMembers)+ ));+ assert!(+ error+ .to_string()+ .contains("choose at most 100 teammates using userIds")+ );+ }+ assert!(service.repository.owners.lock().unwrap().is_empty());+}++#[tokio::test]+async fn availability_accepts_exact_member_limit_and_explicit_subset_of_larger_team() {+ let service = CalendarTeamServiceImpl::new(+ Repository {+ additional_members: 99,+ ..Repository::default()+ },+ true,+ );+ let result = service+ .get_team_availability("viewer", range(), None)+ .await+ .unwrap();+ assert_eq!(result.members.len(), 101);+ assert_eq!(service.repository.owners.lock().unwrap().len(), 101);++ let service = CalendarTeamServiceImpl::new(+ Repository {+ additional_members: 100,+ ..Repository::default()+ },+ true,+ );+ let result = service+ .get_team_availability("viewer", range(), Some(&["owner".into()]))+ .await+ .unwrap();+ assert_eq!(result.members.len(), 2);+ assert_eq!(+ service.repository.owners.lock().unwrap().as_slice(),+ &["owner", "viewer"]+ );+}++#[tokio::test]+async fn distinct_source_projections_are_preserved_independent_of_page_size() {+ let first = source();+ let mut second = first.clone();+ second.source_id = Uuid::now_v7();+ second.occurrence.time = EventTime::Timed {+ starts_at: Utc::now() + chrono::Duration::hours(2),+ ends_at: Utc::now() + chrono::Duration::hours(3),+ time_zone: None,+ };+ let service = CalendarTeamServiceImpl::new(+ Repository {+ rows: vec![first, second],+ ..Repository::default()+ },+ true,+ );+ let all = service+ .list_team_calendar("viewer", range(), None, 100)+ .await+ .unwrap();+ let mut paged = service+ .list_team_calendar("viewer", range(), None, 1)+ .await+ .unwrap();+ let cursor = serde_json::from_str(paged.next_cursor.as_ref().unwrap()).unwrap();+ paged.items.extend(+ service+ .list_team_calendar("viewer", range(), Some(cursor), 1)+ .await+ .unwrap()+ .items,+ );+ let collect = |items: Vec<TeamCalendarItem>| {+ items+ .into_iter()+ .map(|item| (item.id.clone(), serde_json::to_value(item).unwrap()))+ .collect::<HashMap<_, _>>()+ };+ let all = collect(all.items);+ let paged = collect(paged.items);+ assert_eq!(+ all.len(),+ 2,+ "source identities must not collapse distinct copies"+ );+ assert_eq!(all, paged);+}diff --git a/crates/calendar_events/src/domain/team_availability.rs b/crates/calendar_events/src/domain/team_availability.rsnew file mode 100644index 0000000000..5e2449315c--- /dev/null+++ b/crates/calendar_events/src/domain/team_availability.rs@@ -0,0 +1,349 @@+//! Personal availability calculated from individually authorized source copies.++use std::collections::{BTreeMap, BTreeSet};++use chrono::{DateTime, NaiveDate, TimeZone, Utc};+use chrono_tz::{GapInfo, Tz};+use serde::{Deserialize, Serialize};++use super::{+ models::{EventTime, OccurrenceRange},+ team::{TeamAvailabilitySources, TeamCalendarCoverage, TeamSourceOccurrence},+};++/// Maximum merged intervals exposed for one person in a single response.+const BUSY_INTERVALS_MAX: usize = 100;+/// Maximum common free intervals exposed in a single response.+const FREE_INTERVALS_MAX: usize = 100;++/// An exact, half-open interval of UTC instants, without event metadata.+#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]+#[cfg_attr(feature = "schema", derive(utoipa::ToSchema))]+#[cfg_attr(feature = "ai_tools", derive(schemars::JsonSchema))]+#[serde(rename_all = "camelCase")]+pub struct AvailabilityInterval {+ /// Inclusive start.+ pub start: DateTime<Utc>,+ /// Exclusive end.+ pub end: DateTime<Utc>,+}++/// Whether missing busy blocks can safely be interpreted as free time.+#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]+#[cfg_attr(feature = "schema", derive(utoipa::ToSchema))]+#[cfg_attr(feature = "ai_tools", derive(schemars::JsonSchema))]+#[serde(rename_all = "snake_case")]+pub enum AvailabilityCoverage {+ /// All selected source data was current and completely evaluated.+ Complete,+ /// Known busy blocks are useful, but gaps cannot establish availability.+ Unknown,+}++/// Why a person's unoccupied intervals cannot establish availability.+#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]+#[cfg_attr(feature = "schema", derive(utoipa::ToSchema))]+#[cfg_attr(feature = "ai_tools", derive(schemars::JsonSchema))]+#[serde(rename_all = "snake_case")]+pub enum AvailabilityUnknownReason {+ /// The person has not shared their calendar with the requester.+ Hidden,+ /// A source is absent, not fully synced, stale, or otherwise unavailable.+ Unavailable,+ /// The source or result bound prevented complete evaluation or reporting.+ Truncated,+ /// An all-day source did not provide a calendar time zone.+ MissingTimeZone,+ /// An all-day source's time zone could not be interpreted.+ InvalidTimeZone,+ /// A source interval or local-date boundary could not be interpreted.+ InvalidInterval,+ /// Authorized copies of one occurrence disagree about its busy interval.+ ConflictingCopies,+}++/// Busy time and confidence for one explicitly included person.+#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]+#[cfg_attr(feature = "schema", derive(utoipa::ToSchema))]+#[cfg_attr(feature = "ai_tools", derive(schemars::JsonSchema))]+#[serde(rename_all = "camelCase")]+pub struct TeamMemberAvailability {+ /// Macro identifier of the included person.+ pub user_id: String,+ /// Merged known busy intervals clipped to the requested range.+ pub busy: Vec<AvailabilityInterval>,+ /// Whether the whole requested range was established.+ pub coverage: AvailabilityCoverage,+ /// Reasons gaps in the busy intervals cannot be called free.+ pub unknown_reasons: Vec<AvailabilityUnknownReason>,+}++/// Availability for exactly the members selected by the domain service.+#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]+#[cfg_attr(feature = "schema", derive(utoipa::ToSchema))]+#[cfg_attr(feature = "ai_tools", derive(schemars::JsonSchema))]+#[serde(rename_all = "camelCase")]+pub struct TeamAvailability {+ /// Inclusive requested start.+ pub start: DateTime<Utc>,+ /// Exclusive requested end.+ pub end: DateTime<Utc>,+ /// Included people, always including the requester.+ pub members: Vec<TeamMemberAvailability>,+ /// Common calendar gaps for every included person, present only with+ /// complete coverage. These are not working-hours or booking guarantees.+ #[serde(skip_serializing_if = "Option::is_none")]+ pub free_windows: Option<Vec<AvailabilityInterval>>,+ /// Requested identifiers without a current team relationship. No profile+ /// or calendar data about those identifiers is disclosed.+ pub unknown_user_ids: Vec<String>,+ /// True only when all requested people and source intervals were covered.+ pub complete: bool,+ /// A concise explanation that does not overstate incomplete results.+ pub summary: String,+}++#[derive(Default)]+struct MemberIntervals {+ reasons: BTreeSet<AvailabilityUnknownReason>,+ occurrences: BTreeMap<(String, String), BTreeSet<AvailabilityInterval>>,+}++/// Calculate personal busy time after the team service has authorized and+/// selected the sources. No event text, identifiers, or invitees leave this+/// calculation. Unknown coverage suppresses common free windows entirely.+pub fn calculate(range: OccurrenceRange, sources: TeamAvailabilitySources) -> TeamAvailability {+ let mut by_owner: BTreeMap<String, MemberIntervals> = BTreeMap::new();+ for member in &sources.members {+ let intervals = by_owner.entry(member.user_id.clone()).or_default();+ match member.coverage {+ TeamCalendarCoverage::Ready => {}+ TeamCalendarCoverage::Unavailable => {+ intervals+ .reasons+ .insert(AvailabilityUnknownReason::Unavailable);+ }+ TeamCalendarCoverage::Hidden => {+ intervals.reasons.insert(AvailabilityUnknownReason::Hidden);+ }+ }+ if !sources.complete {+ intervals+ .reasons+ .insert(AvailabilityUnknownReason::Truncated);+ }+ if range.ends_at <= range.starts_at {+ intervals+ .reasons+ .insert(AvailabilityUnknownReason::InvalidInterval);+ }+ }++ for source in &sources.sources {+ let Some(member) = by_owner.get_mut(&source.shared_by) else {+ continue;+ };+ if member.reasons.contains(&AvailabilityUnknownReason::Hidden)+ || !source.is_personally_busy()+ {+ continue;+ }+ let time = source+ .exception()+ .map(|exception| &exception.time)+ .unwrap_or(&source.occurrence.time);+ let interval = match interval(time, source.calendar_time_zone.as_deref()) {+ Ok(interval) => interval,+ Err(reason) => {+ member.reasons.insert(reason);+ continue;+ }+ };+ if interval.end <= range.starts_at || interval.start >= range.ends_at {+ continue;+ }+ member+ .occurrences+ .entry((source.event.ical_uid.clone(), original_identity(source)))+ .or_default()+ .insert(interval);+ }++ let mut all_busy = Vec::new();+ let mut members = Vec::with_capacity(by_owner.len());+ for (user_id, mut intervals) in by_owner {+ let mut busy = Vec::new();+ for copies in intervals.occurrences.into_values() {+ if copies.len() > 1 {+ intervals+ .reasons+ .insert(AvailabilityUnknownReason::ConflictingCopies);+ }+ busy.extend(copies);+ }+ let mut busy = merge_intervals(busy, &range);+ all_busy.extend(busy.iter().cloned());+ if busy.len() > BUSY_INTERVALS_MAX {+ busy.truncate(BUSY_INTERVALS_MAX);+ intervals+ .reasons+ .insert(AvailabilityUnknownReason::Truncated);+ }+ members.push(TeamMemberAvailability {+ user_id,+ busy,+ coverage: if intervals.reasons.is_empty() {+ AvailabilityCoverage::Complete+ } else {+ AvailabilityCoverage::Unknown+ },+ unknown_reasons: intervals.reasons.into_iter().collect(),+ });+ }++ let mut unknown_user_ids = sources.unknown_user_ids;+ unknown_user_ids.sort();+ unknown_user_ids.dedup();+ let mut complete = sources.complete+ && unknown_user_ids.is_empty()+ && !members.is_empty()+ && range.ends_at > range.starts_at+ && members+ .iter()+ .all(|member| member.coverage == AvailabilityCoverage::Complete);+ let mut free_windows = complete.then(|| gaps(merge_intervals(all_busy, &range), &range));+ if free_windows+ .as_ref()+ .is_some_and(|windows| windows.len() > FREE_INTERVALS_MAX)+ {+ free_windows = None;+ complete = false;+ for member in &mut members {+ member.coverage = AvailabilityCoverage::Unknown;+ member+ .unknown_reasons+ .push(AvailabilityUnknownReason::Truncated);+ }+ }+ let summary = if complete {+ format!(+ "Checked {} people, including you. Common free windows cover only the requested calendar range; working hours are not applied.",+ members.len()+ )+ } else {+ format!(+ "Checked {} people, including you. Coverage is incomplete; known busy intervals do not establish when everyone is free.",+ members.len()+ )+ };+ TeamAvailability {+ start: range.starts_at,+ end: range.ends_at,+ members,+ free_windows,+ unknown_user_ids,+ complete,+ summary,+ }+}++fn original_identity(source: &TeamSourceOccurrence) -> String {+ if let Some(exception) = source.exception() {+ return exception.original_time.occurrence_key();+ }+ if source.occurrence.recurrence_id.is_none() && source.event.recurrence_lines.is_empty() {+ return String::new();+ }+ // The materialized occurrence key identifies the original occurrence;+ // the current start may change when a single instance is moved.+ source.occurrence.occurrence_key.clone()+}++fn interval(+ time: &EventTime,+ calendar_zone: Option<&str>,+) -> Result<AvailabilityInterval, AvailabilityUnknownReason> {+ let (start, end) = match time {+ EventTime::Timed {+ starts_at, ends_at, ..+ } => (*starts_at, *ends_at),+ EventTime::AllDay {+ start_date,+ end_date,+ } => {+ let zone = calendar_zone.ok_or(AvailabilityUnknownReason::MissingTimeZone)?;+ let zone: Tz = zone+ .parse()+ .map_err(|_| AvailabilityUnknownReason::InvalidTimeZone)?;+ (+ day_boundary(*start_date, zone)?,+ day_boundary(*end_date, zone)?,+ )+ }+ };+ if end <= start {+ return Err(AvailabilityUnknownReason::InvalidInterval);+ }+ Ok(AvailabilityInterval { start, end })+}++fn day_boundary(date: NaiveDate, zone: Tz) -> Result<DateTime<Utc>, AvailabilityUnknownReason> {+ let midnight = date.and_time(chrono::NaiveTime::MIN);+ // Civil dates begin at the earliest midnight during a repeated hour, or+ // at the first valid instant after a gap when midnight was skipped.+ zone.from_local_datetime(&midnight)+ .earliest()+ .or_else(|| GapInfo::new(&midnight, &zone).and_then(|gap| gap.end))+ .map(|instant| instant.with_timezone(&Utc))+ .ok_or(AvailabilityUnknownReason::InvalidInterval)+}++fn merge_intervals(+ intervals: Vec<AvailabilityInterval>,+ range: &OccurrenceRange,+) -> Vec<AvailabilityInterval> {+ let mut intervals: Vec<_> = intervals+ .into_iter()+ .filter_map(|interval| {+ let start = interval.start.max(range.starts_at);+ let end = interval.end.min(range.ends_at);+ (start < end).then_some(AvailabilityInterval { start, end })+ })+ .collect();+ intervals.sort();+ let mut merged: Vec<AvailabilityInterval> = Vec::new();+ for interval in intervals {+ if let Some(previous) = merged.last_mut()+ && interval.start <= previous.end+ {+ previous.end = previous.end.max(interval.end);+ } else {+ merged.push(interval);+ }+ }+ merged+}++fn gaps(busy: Vec<AvailabilityInterval>, range: &OccurrenceRange) -> Vec<AvailabilityInterval> {+ let mut free = Vec::new();+ let mut cursor = range.starts_at;+ for interval in busy {+ if cursor < interval.start {+ free.push(AvailabilityInterval {+ start: cursor,+ end: interval.start,+ });+ }+ cursor = cursor.max(interval.end);+ }+ if cursor < range.ends_at {+ free.push(AvailabilityInterval {+ start: cursor,+ end: range.ends_at,+ });+ }+ free+}++#[cfg(test)]+mod test;diff --git a/crates/calendar_events/src/domain/team_availability/test.rs b/crates/calendar_events/src/domain/team_availability/test.rsnew file mode 100644index 0000000000..ff73235661--- /dev/null+++ b/crates/calendar_events/src/domain/team_availability/test.rs@@ -0,0 +1,477 @@+use super::*;+use crate::domain::{+ models::{+ AttendeeResponseStatus, CalendarAttendee, CalendarEvent, CalendarEventOverride,+ CalendarOccurrence, EventReminders, EventStart, EventStatus, EventTransparency, EventType,+ EventVisibility,+ },+ team::{TeamCalendarMember, TeamCalendarSharing},+};+use chrono::Duration;+use uuid::Uuid;++fn instant(value: &str) -> DateTime<Utc> {+ value.parse().unwrap()+}++fn range(start: &str, end: &str) -> OccurrenceRange {+ let starts_at = instant(start);+ let ends_at = instant(end);+ OccurrenceRange {+ starts_at,+ ends_at,+ start_date: starts_at.date_naive(),+ end_date: ends_at.date_naive().succ_opt().unwrap(),+ }+}++fn window() -> OccurrenceRange {+ range("2026-10-07T09:00:00Z", "2026-10-07T17:00:00Z")+}++fn timed(start: &str, end: &str) -> EventTime {+ EventTime::Timed {+ starts_at: instant(start),+ ends_at: instant(end),+ time_zone: None,+ }+}++fn all_day(start: &str, end: &str) -> EventTime {+ EventTime::AllDay {+ start_date: start.parse().unwrap(),+ end_date: end.parse().unwrap(),+ }+}++fn span(start: &str, end: &str) -> AvailabilityInterval {+ AvailabilityInterval {+ start: instant(start),+ end: instant(end),+ }+}++fn member(user_id: &str) -> TeamCalendarMember {+ TeamCalendarMember {+ user_id: user_id.to_string(),+ sharing: TeamCalendarSharing::BusyOnly,+ coverage: TeamCalendarCoverage::Ready,+ }+}++fn source(user_id: &str, uid: &str, time: EventTime) -> TeamSourceOccurrence {+ let id = Uuid::now_v7();+ let calendar_id = Uuid::now_v7();+ let event = CalendarEvent {+ id,+ owner_id: user_id.into(),+ ical_uid: uid.into(),+ calendar_id: Some(calendar_id),+ sources: vec![],+ title: "Sensitive title that availability must not expose".into(),+ description: Some("Sensitive description".into()),+ location: Some("Sensitive location".into()),+ status: EventStatus::Confirmed,+ visibility: EventVisibility::Private,+ transparency: EventTransparency::Opaque,+ event_type: EventType::Default,+ time: time.clone(),+ recurrence_lines: vec![],+ organizer_email: None,+ organizer_name: None,+ creator_email: None,+ creator_name: None,+ conference_url: None,+ conference_provider: None,+ sequence: 0,+ is_read_only: false,+ attendees: vec![],+ reminders: EventReminders::default(),+ created_at: instant("2026-10-01T00:00:00Z"),+ updated_at: instant("2026-10-01T00:00:00Z"),+ };+ TeamSourceOccurrence {+ shared_by: user_id.into(),+ source_id: Uuid::now_v7(),+ calendar_id,+ calendar_name: "Source name must not escape".into(),+ calendar_time_zone: Some("UTC".into()),+ contributes_to_availability: true,+ owner_emails: vec![format!("{user_id}@example.com")],+ occurrence: CalendarOccurrence {+ event_id: id,+ occurrence_key: time.occurrence_key(),+ recurrence_id: None,+ time,+ is_cancelled: false,+ },+ event,+ overrides: vec![],+ }+}++fn attendee(email: &str, response_status: AttendeeResponseStatus) -> CalendarAttendee {+ CalendarAttendee {+ email: email.into(),+ display_name: None,+ response_status,+ is_organizer: false,+ is_optional: false,+ is_self: true,+ comment: None,+ }+}++fn inputs(+ members: Vec<TeamCalendarMember>,+ sources: Vec<TeamSourceOccurrence>,+) -> TeamAvailabilitySources {+ TeamAvailabilitySources {+ members,+ sources,+ complete: true,+ unknown_user_ids: vec![],+ }+}++#[test]+fn merges_busy_copies_and_clips_common_free_to_requested_range() {+ let first = source(+ "a",+ "one",+ timed("2026-10-07T08:00:00Z", "2026-10-07T10:00:00Z"),+ );+ let duplicate = first.clone();+ let second = source(+ "b",+ "two",+ timed("2026-10-07T10:00:00Z", "2026-10-07T11:00:00Z"),+ );+ let last = source(+ "a",+ "three",+ timed("2026-10-07T16:00:00Z", "2026-10-07T18:00:00Z"),+ );+ let result = calculate(+ window(),+ inputs(+ vec![member("a"), member("b")],+ vec![first, duplicate, second, last],+ ),+ );+ assert!(result.complete);+ assert_eq!(+ result.members[0].busy,+ vec![+ span("2026-10-07T09:00:00Z", "2026-10-07T10:00:00Z"),+ span("2026-10-07T16:00:00Z", "2026-10-07T17:00:00Z")+ ]+ );+ assert_eq!(+ result.free_windows,+ Some(vec![span("2026-10-07T11:00:00Z", "2026-10-07T16:00:00Z")])+ );+ let serialized = serde_json::to_string(&result).unwrap();+ assert!(!serialized.contains("Sensitive"));+ assert!(!serialized.contains("Source name"));+}++#[test]+fn subscriptions_do_not_block_owner_but_owned_attendance_does() {+ let mut subscribed = source(+ "a",+ "coworker",+ timed("2026-10-07T09:00:00Z", "2026-10-07T10:00:00Z"),+ );+ subscribed.contributes_to_availability = false;+ // Provider self refers to the subscribed calendar, not necessarily its+ // Macro viewer. Only an owned address establishes personal attendance.+ subscribed.event.attendees = vec![attendee(+ "[email protected]",+ AttendeeResponseStatus::Accepted,+ )];+ let mut attending = subscribed.clone();+ attending.event.ical_uid = "attending".into();+ attending.event.attendees = vec![attendee("[email protected]", AttendeeResponseStatus::Accepted)];+ attending.occurrence.time = timed("2026-10-07T12:00:00Z", "2026-10-07T13:00:00Z");+ let result = calculate(+ window(),+ inputs(vec![member("a")], vec![subscribed, attending]),+ );+ assert_eq!(+ result.members[0].busy,+ vec![span("2026-10-07T12:00:00Z", "2026-10-07T13:00:00Z")]+ );+}++#[test]+fn declined_cancelled_transparent_and_informational_events_do_not_block() {+ let base = source(+ "a",+ "event",+ timed("2026-10-07T09:00:00Z", "2026-10-07T10:00:00Z"),+ );+ let mut declined = base.clone();+ declined.event.attendees = vec![attendee("[email protected]", AttendeeResponseStatus::Declined)];+ let mut cancelled = base.clone();+ cancelled.occurrence.is_cancelled = true;+ let mut transparent = base.clone();+ transparent.event.transparency = EventTransparency::Transparent;+ let mut working_location = base.clone();+ working_location.event.event_type = EventType::WorkingLocation;+ let mut birthday = base;+ birthday.event.event_type = EventType::Birthday;+ let result = calculate(+ window(),+ inputs(+ vec![member("a")],+ vec![declined, cancelled, transparent, working_location, birthday],+ ),+ );+ assert!(result.members[0].busy.is_empty());+ assert_eq!(+ result.free_windows,+ Some(vec![span("2026-10-07T09:00:00Z", "2026-10-07T17:00:00Z")])+ );+}++#[test]+fn occurrence_response_overrides_master_response() {+ let mut row = source(+ "a",+ "series",+ timed("2026-10-07T09:00:00Z", "2026-10-07T10:00:00Z"),+ );+ row.event.attendees = vec![attendee("[email protected]", AttendeeResponseStatus::Accepted)];+ row.occurrence.recurrence_id = Some("2026-10-07T09:00:00+00:00".into());+ row.overrides = vec![CalendarEventOverride {+ visibility: None,+ transparency: None,+ sequence: None,+ source_updated_at: None,+ recurrence_id: row.occurrence.recurrence_id.clone().unwrap(),+ original_time: EventStart::Timed(instant("2026-10-07T09:00:00Z")),+ time: row.occurrence.time.clone(),+ title: None,+ description: None,+ location: None,+ status: None,+ attendees: Some(vec![attendee(+ "[email protected]",+ AttendeeResponseStatus::Declined,+ )]),+ }];+ let result = calculate(window(), inputs(vec![member("a")], vec![row]));+ assert!(result.complete);+ assert!(result.members[0].busy.is_empty());+}++#[test]+fn instance_transparency_controls_busy_time_and_private_series_stays_private() {+ let mut row = source(+ "a",+ "series",+ timed("2026-10-07T09:00:00Z", "2026-10-07T10:00:00Z"),+ );+ let original = EventStart::Timed(instant("2026-10-07T09:00:00Z"));+ row.occurrence.recurrence_id = Some(original.occurrence_key());+ row.overrides = vec![CalendarEventOverride {+ sequence: None,+ source_updated_at: None,+ recurrence_id: original.occurrence_key(),+ original_time: original,+ time: row.occurrence.time.clone(),+ title: None,+ description: None,+ location: None,+ status: None,+ visibility: Some(EventVisibility::Public),+ transparency: Some(EventTransparency::Transparent),+ attendees: None,+ }];+ assert_eq!(row.visibility(), EventVisibility::Private);+ let result = calculate(window(), inputs(vec![member("a")], vec![row.clone()]));+ assert!(result.complete);+ assert!(result.members[0].busy.is_empty());+ row.event.transparency = EventTransparency::Transparent;+ row.overrides[0].transparency = Some(EventTransparency::Opaque);+ let result = calculate(window(), inputs(vec![member("a")], vec![row]));+ assert_eq!(result.members[0].busy.len(), 1);+}++#[test]+fn all_day_uses_each_sources_zone_and_dst_duration() {+ let range = range("2026-03-07T00:00:00Z", "2026-03-10T00:00:00Z");+ let mut la = source("a", "la", all_day("2026-03-08", "2026-03-09"));+ la.calendar_time_zone = Some("America/Los_Angeles".into());+ let mut tokyo = source("b", "tokyo", all_day("2026-03-08", "2026-03-09"));+ tokyo.calendar_time_zone = Some("Asia/Tokyo".into());+ let result = calculate(+ range,+ inputs(vec![member("a"), member("b")], vec![la, tokyo]),+ );+ assert_eq!(+ result.members[0].busy,+ vec![span("2026-03-08T08:00:00Z", "2026-03-09T07:00:00Z")]+ );+ assert_eq!(+ result.members[1].busy,+ vec![span("2026-03-07T15:00:00Z", "2026-03-08T15:00:00Z")]+ );+}++#[test]+fn civil_midnight_gap_and_fall_back_are_exact() {+ let gap = interval(+ &all_day("2018-11-04", "2018-11-05"),+ Some("America/Sao_Paulo"),+ )+ .unwrap();+ assert_eq!(gap, span("2018-11-04T03:00:00Z", "2018-11-05T02:00:00Z"));+ let fall = interval(+ &all_day("2026-11-01", "2026-11-02"),+ Some("America/Los_Angeles"),+ )+ .unwrap();+ assert_eq!(fall, span("2026-11-01T07:00:00Z", "2026-11-02T08:00:00Z"));+}++#[test]+fn missing_or_invalid_source_zones_prevent_free_claims() {+ for (zone, reason) in [+ (None, AvailabilityUnknownReason::MissingTimeZone),+ (+ Some("not/a-zone"),+ AvailabilityUnknownReason::InvalidTimeZone,+ ),+ ] {+ let mut row = source("a", "all-day", all_day("2026-10-07", "2026-10-08"));+ row.calendar_time_zone = zone.map(str::to_string);+ let result = calculate(window(), inputs(vec![member("a")], vec![row]));+ assert!(!result.complete);+ assert_eq!(result.free_windows, None);+ assert_eq!(result.members[0].unknown_reasons, vec![reason]);+ assert!(+ !serde_json::to_value(&result)+ .unwrap()+ .as_object()+ .unwrap()+ .contains_key("freeWindows")+ );+ }+}++#[test]+fn hidden_unavailable_unknown_and_truncated_never_produce_free_windows() {+ for coverage in [+ TeamCalendarCoverage::Hidden,+ TeamCalendarCoverage::Unavailable,+ ] {+ let mut person = member("a");+ person.coverage = coverage;+ let result = calculate(window(), inputs(vec![person], vec![]));+ assert!(!result.complete);+ assert!(result.free_windows.is_none());+ }+ let mut unknown = inputs(vec![member("a")], vec![]);+ unknown.unknown_user_ids = vec!["outside-team".into()];+ let result = calculate(window(), unknown);+ assert!(result.free_windows.is_none());+ assert!(result.members[0].unknown_reasons.is_empty());+ let mut truncated = inputs(vec![member("a")], vec![]);+ truncated.complete = false;+ let result = calculate(window(), truncated);+ assert!(result.free_windows.is_none());+ assert_eq!(+ result.members[0].unknown_reasons,+ vec![AvailabilityUnknownReason::Truncated]+ );+ assert!(+ calculate(window(), inputs(vec![], vec![]))+ .free_windows+ .is_none()+ );+}++#[test]+fn self_sharing_none_does_not_hide_a_direct_ready_source() {+ let mut person = member("a");+ person.sharing = TeamCalendarSharing::None;+ let row = source(+ "a",+ "event",+ timed("2026-10-07T12:00:00Z", "2026-10-07T13:00:00Z"),+ );+ let result = calculate(window(), inputs(vec![person], vec![row]));+ assert!(result.complete);+ assert_eq!(result.members[0].busy.len(), 1);+}++#[test]+fn source_rows_cannot_expand_the_authorized_member_set() {+ let row = source(+ "outsider",+ "secret",+ timed("2026-10-07T09:00:00Z", "2026-10-07T17:00:00Z"),+ );+ let result = calculate(window(), inputs(vec![member("a")], vec![row]));+ assert_eq!(result.members.len(), 1);+ assert!(result.members[0].busy.is_empty());+}++#[test]+fn moved_copies_deduplicate_by_original_occurrence_and_conflicts_are_unknown() {+ let mut first = source(+ "a",+ "series",+ timed("2026-10-07T12:00:00Z", "2026-10-07T13:00:00Z"),+ );+ first.event.recurrence_lines = vec!["RRULE:FREQ=DAILY".into()];+ first.occurrence.occurrence_key = "2026-10-07T09:00:00+00:00".into();+ first.occurrence.recurrence_id = Some(first.occurrence.occurrence_key.clone());+ let second = first.clone();+ let result = calculate(+ window(),+ inputs(vec![member("a")], vec![first.clone(), second]),+ );+ assert!(result.complete);+ assert_eq!(result.members[0].busy.len(), 1);+ let mut conflicting = first.clone();+ conflicting.occurrence.time = timed("2026-10-07T14:00:00Z", "2026-10-07T15:00:00Z");+ let result = calculate(+ window(),+ inputs(vec![member("a")], vec![first, conflicting]),+ );+ assert_eq!(result.members[0].busy.len(), 2);+ assert_eq!(+ result.members[0].unknown_reasons,+ vec![AvailabilityUnknownReason::ConflictingCopies]+ );+ assert!(result.free_windows.is_none());+}++#[test]+fn output_truncation_preserves_known_busy_but_never_claims_free() {+ let range = range("2026-10-07T00:00:00Z", "2026-10-08T00:00:00Z");+ let rows = (0..=BUSY_INTERVALS_MAX)+ .map(|index| {+ let start = range.starts_at + Duration::minutes(index as i64 * 2);+ source(+ "a",+ &format!("event-{index}"),+ EventTime::Timed {+ starts_at: start,+ ends_at: start + Duration::minutes(1),+ time_zone: None,+ },+ )+ })+ .collect();+ let result = calculate(range, inputs(vec![member("a")], rows));+ assert_eq!(result.members[0].busy.len(), BUSY_INTERVALS_MAX);+ assert_eq!(+ result.members[0].unknown_reasons,+ vec![AvailabilityUnknownReason::Truncated]+ );+ assert!(result.free_windows.is_none());+}diff --git a/crates/calendar_events/src/inbound/mod.rs b/crates/calendar_events/src/inbound/mod.rsindex 749ecb0480..74c24cfeb6 100644--- a/crates/calendar_events/src/inbound/mod.rs+++ b/crates/calendar_events/src/inbound/mod.rs@@ -11,7 +11,14 @@ pub mod dispatch_worker;/// Axum routes for authenticated calendar event mutations.#[cfg(feature = "inbound")]pub mod mutation_router;+/// Read-only team sharing and personal availability settings.+#[cfg(feature = "inbound")]+pub mod team_router;/// AI toolset adapter exposing calendar CRUD to agents.#[cfg(feature = "ai_tools")]pub mod toolset;++/// AI adapter for coverage-aware team calendar availability.+#[cfg(feature = "ai_tools")]+pub mod team_toolset;diff --git a/crates/calendar_events/src/inbound/team_router.rs b/crates/calendar_events/src/inbound/team_router.rsnew file mode 100644index 0000000000..105437cda8--- /dev/null+++ b/crates/calendar_events/src/inbound/team_router.rs@@ -0,0 +1,258 @@+//! Thin HTTP adapters for team projections and personal sharing preferences.++use crate::domain::{models::OccurrenceRange, team::*};+use axum::{+ Json, Router,+ extract::{FromRef, Path, Query, State},+ http::{HeaderValue, StatusCode, header::CACHE_CONTROL},+ middleware::map_response,+ response::{IntoResponse, Response},+ routing::{get, put},+};+use chrono::{DateTime, Utc};+use macro_authorization::{+ MacroAuthorizationExtractor, MacroAuthorizationService, MacroAuthorizationState, UserOrInternal,+};+use serde::{Deserialize, Serialize};+use std::sync::Arc;+use uuid::Uuid;++/// Shared services for either read or settings routes.+pub struct CalendarTeamRouterState<S, A> {+ service: Arc<S>,+ authorization_state: MacroAuthorizationState<A>,+}+impl<S, A> Clone for CalendarTeamRouterState<S, A> {+ fn clone(&self) -> Self {+ Self {+ service: self.service.clone(),+ authorization_state: self.authorization_state.clone(),+ }+ }+}+impl<S, A> CalendarTeamRouterState<S, A> {+ /// Compose the domain service and authentication boundary.+ pub fn new(service: Arc<S>, authorization_state: MacroAuthorizationState<A>) -> Self {+ Self {+ service,+ authorization_state,+ }+ }+}+impl<S, A> FromRef<CalendarTeamRouterState<S, A>> for MacroAuthorizationState<A> {+ fn from_ref(state: &CalendarTeamRouterState<S, A>) -> Self {+ state.authorization_state.clone()+ }+}++/// Storage-service reads; all masking is performed by the domain service.+pub fn team_calendar_router<+ S: CalendarTeamService,+ A: MacroAuthorizationService,+ T: Send + Sync + 'static,+>(+ state: CalendarTeamRouterState<S, A>,+) -> Router<T> {+ Router::new()+ .route("/calendar-events/team", get(list_team_calendar::<S, A>))+ .layer(map_response(private_no_store))+ .with_state(state)+}++/// Calendar-service settings; no Google ACL or provider event writes.+pub fn team_calendar_settings_router<+ S: CalendarTeamService,+ A: MacroAuthorizationService,+ T: Send + Sync + 'static,+>(+ state: CalendarTeamRouterState<S, A>,+) -> Router<T> {+ Router::new()+ .route(+ "/team-sharing",+ get(get_team_sharing::<S, A>).put(set_team_sharing::<S, A>),+ )+ .route(+ "/availability-calendars",+ get(get_availability_calendars::<S, A>),+ )+ .route(+ "/availability-calendars/{calendar_id}",+ put(set_availability_calendar::<S, A>),+ )+ .layer(map_response(private_no_store))+ .with_state(state)+}++async fn private_no_store(mut response: Response) -> Response {+ response+ .headers_mut()+ .insert(CACHE_CONTROL, HeaderValue::from_static("private, no-store"));+ response+}++/// Viewport and opaque continuation token.+#[derive(Deserialize, utoipa::IntoParams)]+#[serde(rename_all = "camelCase")]+pub struct TeamCalendarQuery {+ /// Inclusive instant.+ pub start: DateTime<Utc>,+ /// Exclusive instant.+ pub end: DateTime<Utc>,+ /// Continuation returned by the preceding page.+ pub cursor: Option<String>,+ /// Maximum source occurrences, at most 2,000. Zero returns the roster only.+ pub limit: Option<u16>,+}++/// Own-user sharing preference.+#[derive(Deserialize, Serialize, utoipa::ToSchema)]+pub struct TeamCalendarSharingBody {+ /// Busy-only is the default, including when no setting has been saved.+ pub sharing: TeamCalendarSharing,+}++/// Own-user source inclusion preference.+#[derive(Deserialize, Serialize, utoipa::ToSchema)]+#[serde(rename_all = "camelCase")]+pub struct AvailabilityCalendarBody {+ /// Whether this calendar contributes to personal availability.+ pub contributes_to_availability: bool,+}++/// Source calendar settings returned to their viewer.+#[derive(Serialize, utoipa::ToSchema)]+pub struct AvailabilityCalendarsResponse {+ /// Directly visible source calendars.+ pub calendars: Vec<AvailabilityCalendar>,+}++/// Adapter error without internal/provider details.+#[derive(Debug)]+pub struct TeamCalendarApiError(StatusCode);+impl IntoResponse for TeamCalendarApiError {+ fn into_response(self) -> Response {+ (self.0, Json(serde_json::json!({"message": self.0.canonical_reason().unwrap_or("calendar request failed")}))).into_response()+ }+}+impl From<rootcause::Report> for TeamCalendarApiError {+ fn from(error: rootcause::Report) -> Self {+ let status = match error+ .as_ref()+ .downcast_current_context::<TeamCalendarError>()+ {+ Some(TeamCalendarError::InvalidQuery | TeamCalendarError::TooManyMembers) => {+ StatusCode::BAD_REQUEST+ }+ Some(TeamCalendarError::NotFound | TeamCalendarError::Disabled) => {+ StatusCode::NOT_FOUND+ }+ None => {+ tracing::error!(error=?error, "team calendar request failed");+ StatusCode::INTERNAL_SERVER_ERROR+ }+ };+ Self(status)+ }+}++/// Query authorized projections in a bounded viewport.+#[utoipa::path(get, path="/calendar-events/team", params(TeamCalendarQuery), responses((status=200, body=TeamCalendarPage)), tag="calendar_events")]+pub async fn list_team_calendar<S: CalendarTeamService, A: MacroAuthorizationService>(+ State(state): State<CalendarTeamRouterState<S, A>>,+ user: MacroAuthorizationExtractor<A, UserOrInternal>,+ Query(query): Query<TeamCalendarQuery>,+) -> Result<Json<TeamCalendarPage>, TeamCalendarApiError> {+ let cursor = query+ .cursor+ .map(|cursor| serde_json::from_str(&cursor))+ .transpose()+ .map_err(|_| TeamCalendarApiError(StatusCode::BAD_REQUEST))?;+ let range = OccurrenceRange {+ starts_at: query.start,+ ends_at: query.end,+ start_date: query.start.date_naive(),+ end_date: if query.end.time() == chrono::NaiveTime::MIN {+ query.end.date_naive()+ } else {+ query+ .end+ .date_naive()+ .succ_opt()+ .ok_or(TeamCalendarApiError(StatusCode::BAD_REQUEST))?+ },+ };+ Ok(Json(+ state+ .service+ .list_team_calendar(+ user.authorization.user.macro_user_id.as_ref(),+ range,+ cursor,+ query.limit.unwrap_or(500),+ )+ .await?,+ ))+}++/// Read the authenticated user's sharing choice.+#[utoipa::path(get, path="/team-sharing", responses((status=200, body=TeamCalendarSharingBody)), tag="calendar_events")]+pub async fn get_team_sharing<S: CalendarTeamService, A: MacroAuthorizationService>(+ State(state): State<CalendarTeamRouterState<S, A>>,+ user: MacroAuthorizationExtractor<A, UserOrInternal>,+) -> Result<Json<TeamCalendarSharingBody>, TeamCalendarApiError> {+ Ok(Json(TeamCalendarSharingBody {+ sharing: state+ .service+ .team_sharing(user.authorization.user.macro_user_id.as_ref())+ .await?,+ }))+}++/// Set the authenticated user's sharing choice.+#[utoipa::path(put, path="/team-sharing", request_body=TeamCalendarSharingBody, responses((status=200, body=TeamCalendarSharingBody)), tag="calendar_events")]+pub async fn set_team_sharing<S: CalendarTeamService, A: MacroAuthorizationService>(+ State(state): State<CalendarTeamRouterState<S, A>>,+ user: MacroAuthorizationExtractor<A, UserOrInternal>,+ Json(body): Json<TeamCalendarSharingBody>,+) -> Result<Json<TeamCalendarSharingBody>, TeamCalendarApiError> {+ Ok(Json(TeamCalendarSharingBody {+ sharing: state+ .service+ .set_team_sharing(user.authorization.user.macro_user_id.as_ref(), body.sharing)+ .await?,+ }))+}++/// List calendars and their personal-availability inclusion.+#[utoipa::path(get, path="/availability-calendars", responses((status=200, body=AvailabilityCalendarsResponse)), tag="calendar_events")]+pub async fn get_availability_calendars<S: CalendarTeamService, A: MacroAuthorizationService>(+ State(state): State<CalendarTeamRouterState<S, A>>,+ user: MacroAuthorizationExtractor<A, UserOrInternal>,+) -> Result<Json<AvailabilityCalendarsResponse>, TeamCalendarApiError> {+ Ok(Json(AvailabilityCalendarsResponse {+ calendars: state+ .service+ .availability_calendars(user.authorization.user.macro_user_id.as_ref())+ .await?,+ }))+}++/// Change which source calendars normally occupy this user's time.+#[utoipa::path(put, path="/availability-calendars/{calendar_id}", params(("calendar_id"=Uuid, Path)), request_body=AvailabilityCalendarBody, responses((status=204)), tag="calendar_events")]+pub async fn set_availability_calendar<S: CalendarTeamService, A: MacroAuthorizationService>(+ State(state): State<CalendarTeamRouterState<S, A>>,+ user: MacroAuthorizationExtractor<A, UserOrInternal>,+ Path(calendar): Path<Uuid>,+ Json(body): Json<AvailabilityCalendarBody>,+) -> Result<StatusCode, TeamCalendarApiError> {+ state+ .service+ .set_availability_calendar(+ user.authorization.user.macro_user_id.as_ref(),+ calendar,+ body.contributes_to_availability,+ )+ .await?;+ Ok(StatusCode::NO_CONTENT)+}diff --git a/crates/calendar_events/src/inbound/team_toolset.rs b/crates/calendar_events/src/inbound/team_toolset.rsnew file mode 100644index 0000000000..2f77037cef--- /dev/null+++ b/crates/calendar_events/src/inbound/team_toolset.rs@@ -0,0 +1,136 @@+//! Thin AI adapter for the team calendar domain service.++use std::sync::Arc;++use ai_toolset::{+ AsyncTool, AsyncToolCollection, RequestContext, ServiceContext, ToolAnnotated, ToolAnnotations,+ ToolCallError, ToolResult,+};+use async_trait::async_trait;+use chrono::{DateTime, NaiveTime, Utc};+use rootcause::compat::boxed_error::IntoBoxedError;+use schemars::JsonSchema;+use serde::Deserialize;++use crate::domain::{+ models::OccurrenceRange,+ team::{CalendarTeamService, TeamCalendarError},+ team_availability::TeamAvailability,+};++/// Dependencies for the read-only team availability tool.+pub struct TeamCalendarToolContext<T: CalendarTeamService> {+ /// Domain service owning authorization, coverage, and busy-time policy.+ pub service: Arc<T>,+}++impl<T: CalendarTeamService> Clone for TeamCalendarToolContext<T> {+ fn clone(&self) -> Self {+ Self {+ service: Arc::clone(&self.service),+ }+ }+}++/// Read-only availability tools shared by chat, agents, and MCP hosts.+pub fn team_calendar_toolset<T: CalendarTeamService>()+-> AsyncToolCollection<TeamCalendarToolContext<T>> {+ AsyncToolCollection::new().add_tool::<GetTeamAvailability, TeamCalendarToolContext<T>>()+}++/// Ask when the requester and selected current teammates have calendar gaps.+#[derive(Debug, Clone, Deserialize, JsonSchema)]+#[serde(rename_all = "camelCase")]+#[schemars(+ title = "GetTeamAvailability",+ description = "Check personal busy time for you and your current teammates in a bounded UTC time window. \+Always includes you, even when userIds selects particular teammates. Omit userIds for the whole team, \+or use ids from ListTeamMembers for specific people. An empty list checks only you. \+Returns merged busy intervals without event titles, plus coverage and unknown reasons. \+Subscribed coworkers' events do not block a person's time unless they attend or included that calendar. \+Common freeWindows are present only when every requested person's data is complete and current. \+When freeWindows is absent, report uncertainty and never infer free time from missing busy blocks. \+Free windows cover the requested range only; working hours are not applied. Prefer a day or a week; \+the maximum is 370 days within one year past to two years future. This tool grants no Google Calendar \+access and does not invite, RSVP, or modify events."+)]+pub struct GetTeamAvailability {+ /// Inclusive start of the requested window.+ #[schemars(description = "Inclusive start, RFC 3339 UTC (for example 2026-10-07T09:00:00Z).")]+ pub start: DateTime<Utc>,+ /// Exclusive end of the requested window.+ #[schemars(description = "Exclusive end, RFC 3339 UTC. Must be later than start.")]+ pub end: DateTime<Utc>,+ /// Selected current teammates; the requester is always added by the domain.+ #[schemars(+ description = "At most 100 Macro user ids from ListTeamMembers. Omit for the whole team; an empty list checks only you. Unknown ids never expand access and suppress common free windows."+ )]+ pub user_ids: Option<Vec<String>>,+}++impl ToolAnnotated for GetTeamAvailability {+ const ANNOTATIONS: ToolAnnotations = ToolAnnotations::read_only("Get team availability");+}++#[async_trait]+impl<T: CalendarTeamService> AsyncTool<TeamCalendarToolContext<T>> for GetTeamAvailability {+ type Output = TeamAvailability;++ #[tracing::instrument(skip_all, err)]+ async fn call(+ &self,+ service_context: ServiceContext<TeamCalendarToolContext<T>>,+ request_context: RequestContext,+ ) -> ToolResult<Self::Output> {+ let end_date = if self.end.time() == NaiveTime::MIN {+ self.end.date_naive()+ } else {+ self.end+ .date_naive()+ .succ_opt()+ .unwrap_or(self.end.date_naive())+ };+ service_context+ .service+ .get_team_availability(+ request_context.user_id.as_ref(),+ OccurrenceRange {+ starts_at: self.start,+ ends_at: self.end,+ start_date: self.start.date_naive(),+ end_date,+ },+ self.user_ids.as_deref(),+ )+ .await+ .map_err(tool_error)+ }+}++fn tool_error(error: rootcause::Report) -> ToolCallError {+ let description = match error+ .as_ref()+ .downcast_current_context::<TeamCalendarError>()+ {+ Some(TeamCalendarError::InvalidQuery) => {+ "The window must be positive, at most 370 days, and within one year past to two years future."+ }+ Some(TeamCalendarError::TooManyMembers) => {+ "Too many people selected. Choose at most 100 teammates using userIds; the requester is always included. Omitting userIds selects the whole team."+ }+ Some(TeamCalendarError::Disabled) => {+ "Team calendar sharing is not enabled for this deployment."+ }+ Some(TeamCalendarError::NotFound) => "The requested calendar is no longer accessible.",+ None => {+ "Could not establish team availability. Try again shortly; missing results do not mean people are free."+ }+ };+ ToolCallError {+ description: description.to_string(),+ internal_error: anyhow::Error::from_boxed(error.into_boxed_error()),+ }+}++#[cfg(test)]+mod test;diff --git a/crates/calendar_events/src/inbound/team_toolset/test.rs b/crates/calendar_events/src/inbound/team_toolset/test.rsnew file mode 100644index 0000000000..0bd43c5528--- /dev/null+++ b/crates/calendar_events/src/inbound/team_toolset/test.rs@@ -0,0 +1,125 @@+use super::*;+use std::sync::Mutex;++use ai_toolset::{ToolSet, schema::generate_validated_input_schema};+use macro_user_id::user_id::MacroUserIdStr;+use rootcause::Report;+use uuid::Uuid;++use crate::domain::team::{+ AvailabilityCalendar, TeamCalendarCursor, TeamCalendarPage, TeamCalendarSharing,+};++#[derive(Default)]+struct FakeService {+ requests: Mutex<Vec<(String, OccurrenceRange, Option<Vec<String>>)>>,+ fail: bool,+}++impl CalendarTeamService for FakeService {+ async fn list_team_calendar(+ &self,+ _: &str,+ _: OccurrenceRange,+ _: Option<TeamCalendarCursor>,+ _: u16,+ ) -> Result<TeamCalendarPage, Report> {+ unreachable!("availability tool does not browse team content")+ }++ async fn team_sharing(&self, _: &str) -> Result<TeamCalendarSharing, Report> {+ unreachable!("availability policy belongs in the domain")+ }++ async fn set_team_sharing(+ &self,+ _: &str,+ _: TeamCalendarSharing,+ ) -> Result<TeamCalendarSharing, Report> {+ unreachable!("availability tool cannot change permissions")+ }++ async fn availability_calendars(&self, _: &str) -> Result<Vec<AvailabilityCalendar>, Report> {+ unreachable!("availability policy belongs in the domain")+ }++ async fn set_availability_calendar(&self, _: &str, _: Uuid, _: bool) -> Result<(), Report> {+ unreachable!("availability tool cannot change source inclusion")+ }++ async fn get_team_availability(+ &self,+ requester: &str,+ range: OccurrenceRange,+ user_ids: Option<&[String]>,+ ) -> Result<TeamAvailability, Report> {+ self.requests.lock().unwrap().push((+ requester.to_owned(),+ range.clone(),+ user_ids.map(<[String]>::to_vec),+ ));+ if self.fail {+ return Err(rootcause::report!(TeamCalendarError::Disabled).into());+ }+ Ok(TeamAvailability {+ start: range.starts_at,+ end: range.ends_at,+ members: vec![],+ free_windows: None,+ unknown_user_ids: vec!["unknown-person".into()],+ complete: false,+ summary: "Coverage is incomplete".into(),+ })+ }+}++fn request() -> RequestContext {+ RequestContext::new(+ MacroUserIdStr::try_from("macro|[email protected]".to_string()).unwrap(),+ )+}++fn tool() -> GetTeamAvailability {+ GetTeamAvailability {+ start: "2026-10-07T09:00:00Z".parse().unwrap(),+ end: "2026-10-07T17:00:00Z".parse().unwrap(),+ user_ids: Some(vec!["unknown-person".into()]),+ }+}++#[test]+fn input_schema_is_strict_and_tool_is_registered() {+ let schema = generate_validated_input_schema::<GetTeamAvailability>().unwrap();+ assert_eq!(schema.name, "GetTeamAvailability");+ let set = team_calendar_toolset::<FakeService>();+ let schemas = set.request_schemas().unwrap();+ assert_eq!(schemas.len(), 1);+ assert_eq!(schemas[0].name, "GetTeamAvailability");+}++#[tokio::test]+async fn delegates_identity_and_selection_without_inventing_free_windows() {+ let service = Arc::new(FakeService::default());+ let context = ServiceContext(TeamCalendarToolContext {+ service: service.clone(),+ });+ let result = tool().call(context, request()).await.unwrap();+ assert!(!result.complete);+ assert!(result.free_windows.is_none());+ assert_eq!(result.unknown_user_ids, vec!["unknown-person"]);+ let requests = service.requests.lock().unwrap();+ assert_eq!(requests[0].0, "macro|[email protected]");+ assert_eq!(requests[0].2, Some(vec!["unknown-person".to_string()]));+}++#[tokio::test]+async fn service_denial_remains_an_error() {+ let context = ServiceContext(TeamCalendarToolContext {+ service: Arc::new(FakeService {+ fail: true,+ ..Default::default()+ }),+ });+ let error = tool().call(context, request()).await.unwrap_err();+ assert!(error.description.contains("not enabled"));+}diff --git a/crates/calendar_events/src/outbound/google.rs b/crates/calendar_events/src/outbound/google.rsindex 4539921d11..618b4150b4 100644--- a/crates/calendar_events/src/outbound/google.rs+++ b/crates/calendar_events/src/outbound/google.rs@@ -538,7 +538,8 @@ impl<G: GoogleRequestGate> GoogleCalendarProvider for GoogleCalendarClient<G> {).await?;- let mapped = map_snapshot(target, canonical_events, instances);+ let mapped = map_snapshot(target, canonical_events, instances)+ .map_err(sync_normalization_error)?;return Ok(GoogleEventSyncBatch {upserts: mapped.upserts,@@ -647,20 +648,10 @@ impl<G: GoogleRequestGate> GoogleCalendarClient<G> {for single in classified.single_upserts {let provider_event_id = single.id.clone();- match map_upsert(target, single.clone(), Vec::new(), vec![single]) {- Ok(upsert) => {- applied.upserts.push(upsert);- applied.upserted_singles.insert(provider_event_id);- }- Err(error) => {- tracing::warn!(- error=?error,- provider_calendar_id=%target.provider_calendar_id,- provider_event_id,- "skipping malformed changed Google Calendar event"- );- }- }+ let upsert = map_upsert(target, single.clone(), Vec::new(), vec![single])+ .map_err(sync_normalization_error)?;+ applied.upserts.push(upsert);+ applied.upserted_singles.insert(provider_event_id);}// One bounded refresh per changed series keeps Google authoritative@@ -678,7 +669,9 @@ impl<G: GoogleRequestGate> GoogleCalendarClient<G> {applied.cancelled.insert(master_id);}SeriesOutcome::Malformed => {- applied.refreshed_series.insert(master_id);+ return Err(sync_normalization_error(rootcause::report!(+ "Google Calendar returned a malformed changed series"+ )));}}}@@ -742,7 +735,7 @@ impl<G: GoogleRequestGate> GoogleCalendarClient<G> {error=?error,provider_calendar_id=%target.provider_calendar_id,provider_event_id,- "skipping malformed changed Google Calendar series"+ "rejecting malformed changed Google Calendar series");Ok(SeriesOutcome::Malformed)}@@ -782,20 +775,10 @@ impl<G: GoogleRequestGate> GoogleCalendarClient<G> {for single in tail_singles {let provider_event_id = single.id.clone();- match map_upsert(target, single.clone(), Vec::new(), vec![single]) {- Ok(upsert) => {- applied.upserts.push(upsert);- applied.upserted_singles.insert(provider_event_id);- }- Err(error) => {- tracing::warn!(- error=?error,- provider_calendar_id=%target.provider_calendar_id,- provider_event_id,- "skipping malformed Google Calendar event in the coverage tail"- );- }- }+ let upsert = map_upsert(target, single.clone(), Vec::new(), vec![single])+ .map_err(sync_normalization_error)?;+ applied.upserts.push(upsert);+ applied.upserted_singles.insert(provider_event_id);}for master_id in tail_series {@@ -811,7 +794,9 @@ impl<G: GoogleRequestGate> GoogleCalendarClient<G> {applied.cancelled.insert(master_id);}SeriesOutcome::Malformed => {- applied.refreshed_series.insert(master_id);+ return Err(sync_normalization_error(rootcause::report!(+ "Google Calendar returned a malformed series in the coverage tail"+ )));}}}@@ -1614,6 +1599,15 @@ fn mutation_normalization_error(error: Report) -> GoogleProviderError {)}+/// Reject the whole calendar batch so neither its token nor its coverage can+/// advance past an event that has not been represented successfully.+fn sync_normalization_error(error: Report) -> GoogleProviderError {+ GoogleProviderError::new(+ GoogleProviderErrorKind::Transient,+ format!("Google Calendar snapshot could not be fully normalized: {error:?}"),+ )+}+fn google_response_status(status: AttendeeResponseStatus) -> &'static str {match status {AttendeeResponseStatus::NeedsAction => "needsAction",@@ -1921,9 +1915,12 @@ fn map_snapshot(target: &GoogleCalendarTarget,canonical_events: Vec<GoogleEvent>,instances: Vec<GoogleEvent>,-) -> MappedGoogleSnapshot {+) -> Result<MappedGoogleSnapshot, Report> {let mut occurrences: BTreeMap<String, Vec<GoogleEvent>> = BTreeMap::new();for instance in instances {+ if instance.status.as_deref() == Some("cancelled") {+ continue;+ }occurrences.entry(instance.ical_uid.clone()).or_default()@@ -1933,6 +1930,9 @@ fn map_snapshot(let mut exceptions: BTreeMap<String, Vec<GoogleEvent>> = BTreeMap::new();let mut masters = BTreeMap::new();for event in canonical_events {+ if event.status.as_deref() == Some("cancelled") {+ continue;+ }if event.recurring_event_id.is_some() {exceptions.entry(event.ical_uid.clone())@@ -1960,29 +1960,29 @@ fn map_snapshot(.collect::<Vec<_>>();let upserts = masters.into_iter()- .filter_map(|(uid, master)| {- let provider_event_id = master.id.clone();+ .map(|(uid, master)| {map_upsert(target,master,exceptions.remove(&uid).unwrap_or_default(),occurrences.remove(&uid).unwrap_or_default(),)- .inspect_err(|error| {- tracing::warn!(- error=?error,- provider_calendar_id=%target.provider_calendar_id,- provider_event_id,- "skipping malformed Google Calendar master"- );- })- .ok()})- .collect();- MappedGoogleSnapshot {+ .collect::<Result<Vec<_>, _>>()?;+ for exception in exceptions.into_values().flatten() {+ // A moved exception can be returned by the unexpanded feed even when+ // its current interval is outside the expanded window. Its absence+ // there is expected; an in-window orphan is missing coverage.+ if google_time(&exception)?.overlaps(&target.range) {+ return Err(rootcause::report!(+ "Google Calendar snapshot has an in-window exception without a master or expanded instance"+ ));+ }+ }+ Ok(MappedGoogleSnapshot {upserts,observed_provider_event_ids,- }+ })}fn map_upsert(@@ -1999,6 +1999,7 @@ fn map_upsert(email_link_id: target.email_link_id,account_id: target.account_id,calendar_id: target.calendar_id,+ observed_access_role: target.observed_access_role.clone(),provider_event_id: master.id.clone(),provider_recurring_event_id: master.recurring_event_id.clone(),provider_etag: master.etag.clone(),@@ -2058,113 +2059,93 @@ fn map_upsert(updated_at,};- let overrides = exceptions- .into_iter()- .filter_map(|exception| {- // Cancelled exceptions arrive without times; the occurrence- // replace already removes them, so there is no override to keep.- if exception.status.as_deref() == Some("cancelled") {- return None;- }- let provider_event_id = exception.id.clone();- (|| -> Result<CalendarEventOverride, Report> {- let original = exception- .original_start_time- .as_ref()- .and_then(google_start)- .ok_or_else(|| {- rootcause::report!(- "Google recurring exception {} has an invalid original start",- exception.id- )- })?;- let time = google_time(&exception)?;- Ok(CalendarEventOverride {- sequence: exception.sequence,- source_updated_at: parse_datetime(exception.updated.as_deref()),- recurrence_id: original.occurrence_key(),- original_time: original,- time,- title: exception.summary,- description: exception.description,- location: exception.location,- status: Some(google_status(exception.status.as_deref())),- attendees: exception- .attendees- .map(|attendees| attendees.into_iter().filter_map(map_attendee).collect()),- })- })()- .inspect_err(|error| {- tracing::warn!(- error=?error,- provider_calendar_id=%target.provider_calendar_id,- provider_event_id,- "skipping malformed Google Calendar recurrence exception"- );- })- .ok()- })- .collect();+ let mut overrides = Vec::new();+ for exception in exceptions {+ // Google omits times on cancelled exceptions. The occurrence snapshot+ // already excludes them, so a cancellation is not a coverage gap.+ if exception.status.as_deref() == Some("cancelled") {+ continue;+ }+ let original = exception+ .original_start_time+ .as_ref()+ .and_then(google_start)+ .ok_or_else(|| {+ rootcause::report!(+ "Google recurring exception {} has an invalid original start",+ exception.id+ )+ })?;+ let time = google_time(&exception)?;+ overrides.push(CalendarEventOverride {+ sequence: exception.sequence,+ source_updated_at: parse_datetime(exception.updated.as_deref()),+ recurrence_id: original.occurrence_key(),+ original_time: original,+ time,+ title: exception.summary,+ description: exception.description,+ location: exception.location,+ status: Some(google_status(exception.status.as_deref())),+ visibility: exception+ .visibility+ .as_deref()+ .map(|value| google_visibility(Some(value))),+ transparency: exception+ .transparency+ .as_deref()+ .map(|value| google_transparency(Some(value))),+ attendees: exception+ .attendees+ .map(|attendees| attendees.into_iter().filter_map(map_attendee).collect()),+ });+ }- let occurrences = instances- .into_iter()- .filter_map(|instance| {- let provider_event_id = instance.id.clone();- (|| -> Result<Option<CalendarOccurrence>, Report> {- let time = google_time(&instance)?;- let original_start = instance- .original_start_time- .as_ref()- .map(|value| {- google_start(value).ok_or_else(|| {- rootcause::report!(- "Google recurring instance {} has an invalid original start",- instance.id- )- })- })- .transpose()?;- Ok(time.overlaps(&target.range).then(|| CalendarOccurrence {- event_id,- occurrence_key: original_start- .as_ref()- .map(|start| start.occurrence_key())- .unwrap_or_else(|| time.occurrence_key()),- recurrence_id: original_start.map(|start| start.occurrence_key()),- time,- is_cancelled: instance.status.as_deref() == Some("cancelled"),- }))- })()- .inspect_err(|error| {- tracing::warn!(- error=?error,- provider_calendar_id=%target.provider_calendar_id,- provider_event_id,- "skipping malformed Google Calendar recurrence instance"- );+ let mut occurrences = BTreeMap::<String, CalendarOccurrence>::new();+ for instance in instances {+ // Cancellation tombstones need no interval and never block time.+ if instance.status.as_deref() == Some("cancelled") {+ continue;+ }+ let time = google_time(&instance)?;+ let original_start = instance+ .original_start_time+ .as_ref()+ .map(|value| {+ google_start(value).ok_or_else(|| {+ rootcause::report!(+ "Google recurring instance {} has an invalid original start",+ instance.id+ )+ })})- .ok()- .flatten()- })- .fold(- BTreeMap::<String, CalendarOccurrence>::new(),- |mut deduped, occurrence| {- // Google can expand two instances onto one occurrence key — a- // moved exception whose original start still lands on the series- // slot, a DST boundary, a pagination overlap. Both would carry- // the same (event_id, occurrence_key) primary key, so collapse- // them here and keep the live instance over a cancelled tombstone.- let replace = deduped- .get(&occurrence.occurrence_key)- .is_none_or(|existing| existing.is_cancelled && !occurrence.is_cancelled);- if replace {- deduped.insert(occurrence.occurrence_key.clone(), occurrence);- }- deduped- },- )- .into_values()- .collect();+ .transpose()?;+ if instance.recurring_event_id.is_some() && original_start.is_none() {+ return Err(rootcause::report!(+ "Google recurring instance {} has no original start",+ instance.id+ ));+ }+ if !time.overlaps(&target.range) {+ continue;+ }+ let occurrence_key = original_start+ .as_ref()+ .map(|start| start.occurrence_key())+ .unwrap_or_else(|| time.occurrence_key());+ // Repeated live instances can result from pagination overlap. Keep+ // the first representation of an original occurrence as before.+ occurrences+ .entry(occurrence_key.clone())+ .or_insert(CalendarOccurrence {+ event_id,+ occurrence_key,+ recurrence_id: original_start.map(|start| start.occurrence_key()),+ time,+ is_cancelled: false,+ });+ }+ let occurrences = occurrences.into_values().collect();Ok(CalendarEventUpsert {event,@@ -2183,34 +2164,39 @@ fn google_time(event: &GoogleEvent) -> Result<EventTime, Report> {.end.as_ref().ok_or_else(|| rootcause::report!("Google event {} has no end", event.id))?;- match (+ let time = match (start.date_time.as_deref(),end.date_time.as_deref(),start.date.as_deref(),end.date.as_deref(),) {- (Some(start_value), Some(end_value), _, _) => {- let starts_at = DateTime::parse_from_rfc3339(start_value)+ (Some(start_value), Some(end_value), _, _) => EventTime::Timed {+ starts_at: DateTime::parse_from_rfc3339(start_value).map_err(report)?- .with_timezone(&Utc);- let ends_at = DateTime::parse_from_rfc3339(end_value)+ .with_timezone(&Utc),+ ends_at: DateTime::parse_from_rfc3339(end_value).map_err(report)?- .with_timezone(&Utc);- Ok(EventTime::Timed {- starts_at,- ends_at,- time_zone: start.time_zone.clone(),- })- }- (_, _, Some(start_value), Some(end_value)) => Ok(EventTime::AllDay {+ .with_timezone(&Utc),+ time_zone: start.time_zone.clone(),+ },+ (_, _, Some(start_value), Some(end_value)) => EventTime::AllDay {start_date: NaiveDate::parse_from_str(start_value, "%Y-%m-%d").map_err(report)?,end_date: NaiveDate::parse_from_str(end_value, "%Y-%m-%d").map_err(report)?,- }),- _ => Err(rootcause::report!(- "Google event {} has mixed or missing time fields",+ },+ _ => {+ return Err(rootcause::report!(+ "Google event {} has mixed or missing time fields",+ event.id+ ));+ }+ };+ if !time.is_valid() {+ return Err(rootcause::report!(+ "Google event {} has an invalid interval",event.id- )),+ ));}+ Ok(time)}fn google_start(value: &GoogleEventDateTime) -> Option<EventStart> {diff --git a/crates/calendar_events/src/outbound/google/test.rs b/crates/calendar_events/src/outbound/google/test.rsindex 760badef5c..301ad3685d 100644--- a/crates/calendar_events/src/outbound/google/test.rs+++ b/crates/calendar_events/src/outbound/google/test.rs@@ -24,6 +24,7 @@ fn calendar_access_role_is_reflected_on_mapped_events() {};let target = GoogleCalendarTarget {+ observed_access_role: Some("reader".to_owned()),owner_id: "macro|[email protected]".to_string(),email_link_id: Uuid::now_v7(),account_id: Uuid::now_v7(),@@ -35,6 +36,11 @@ fn calendar_access_role_is_reflected_on_mapped_events() {let upsert = map_upsert(&target, master, Vec::new(), Vec::new()).unwrap();assert!(upsert.event.is_read_only);+ let CalendarEventSource::Google(source) = &upsert.source;+ assert_eq!(source.observed_access_role.as_deref(), Some("reader"));+ assert_eq!(source.account_id, target.account_id);+ assert_eq!(source.calendar_id, target.calendar_id);+ assert_eq!(source.email_link_id, target.email_link_id);}#[test]@@ -50,6 +56,7 @@ fn event_type_is_mapped_with_an_unknown_fallback() {end_date: NaiveDate::from_ymd_opt(2026, 9, 1).unwrap(),};let target = GoogleCalendarTarget {+ observed_access_role: Some("owner".to_owned()),owner_id: "macro|[email protected]".to_string(),email_link_id: Uuid::now_v7(),account_id: Uuid::now_v7(),@@ -114,6 +121,7 @@ fn creator_is_mapped_separately_from_the_organizer() {end_date: NaiveDate::from_ymd_opt(2026, 9, 1).unwrap(),};let target = GoogleCalendarTarget {+ observed_access_role: Some("owner".to_owned()),owner_id: "macro|[email protected]".to_string(),email_link_id: Uuid::now_v7(),account_id: Uuid::now_v7(),@@ -172,6 +180,7 @@ fn malformed_recurring_instance_does_not_overstate_snapshot_coverage() {end_date: NaiveDate::from_ymd_opt(2026, 8, 1).unwrap(),};let target = GoogleCalendarTarget {+ observed_access_role: Some("owner".to_owned()),owner_id: "macro|[email protected]".to_string(),email_link_id: Uuid::now_v7(),account_id: Uuid::now_v7(),@@ -181,8 +190,42 @@ fn malformed_recurring_instance_does_not_overstate_snapshot_coverage() {range,};- let upsert = map_upsert(&target, master, Vec::new(), vec![malformed_instance]).unwrap();- assert!(upsert.occurrences.is_empty());+ assert!(+ map_upsert(+ &target,+ master.clone(),+ Vec::new(),+ vec![malformed_instance.clone()]+ )+ .is_err()+ );+ assert!(+ map_upsert(+ &target,+ master.clone(),+ vec![malformed_instance.clone()],+ Vec::new()+ )+ .is_err(),+ "an invalid exception cannot disappear from a complete snapshot"+ );++ let mut invalid_interval = malformed_instance.clone();+ invalid_interval.end = invalid_interval.start.clone();+ assert!(map_upsert(&target, master.clone(), Vec::new(), vec![invalid_interval]).is_err());++ let mut missing_identity = malformed_instance.clone();+ missing_identity.end = master.end.clone();+ missing_identity.original_start_time = None;+ assert!(map_upsert(&target, master.clone(), Vec::new(), vec![missing_identity]).is_err());++ let mut tombstone = malformed_instance;+ tombstone.status = Some("cancelled".to_owned());+ let upsert = map_upsert(&target, master, vec![tombstone.clone()], vec![tombstone]).unwrap();+ assert!(+ upsert.occurrences.is_empty(),+ "cancelled tombstones need no end time"+ );}/// Google's `instances` feed can return two entries that resolve to the same@@ -235,6 +278,7 @@ fn duplicate_instances_collapse_to_one_live_occurrence() {end_date: NaiveDate::from_ymd_opt(2026, 8, 1).unwrap(),};let target = GoogleCalendarTarget {+ observed_access_role: Some("owner".to_owned()),owner_id: "macro|[email protected]".to_string(),email_link_id: Uuid::now_v7(),account_id: Uuid::now_v7(),@@ -276,8 +320,8 @@ fn duplicate_instances_collapse_to_one_live_occurrence() {);}-#[test]-fn malformed_master_is_quarantined_without_deleting_its_provider_identity() {+#[tokio::test]+async fn malformed_master_rejects_snapshot_and_incremental_batch_until_repaired() {let valid: GoogleEvent = serde_json::from_value(serde_json::json!({"id": "valid-provider-event","iCalUID": "[email protected]",@@ -298,6 +342,7 @@ fn malformed_master_is_quarantined_without_deleting_its_provider_identity() {.unwrap().with_timezone(&Utc);let target = GoogleCalendarTarget {+ observed_access_role: Some("owner".to_owned()),owner_id: "macro|[email protected]".to_string(),email_link_id: Uuid::now_v7(),account_id: Uuid::now_v7(),@@ -312,16 +357,37 @@ fn malformed_master_is_quarantined_without_deleting_its_provider_identity() {},};- let mapped = map_snapshot(&target, vec![valid, malformed], Vec::new());-- assert_eq!(mapped.upserts.len(), 1);- assert_eq!(- mapped.observed_provider_event_ids,- vec![- "malformed-provider-event".to_string(),- "valid-provider-event".to_string()- ]+ assert!(map_snapshot(&target, vec![valid.clone(), malformed.clone()], Vec::new()).is_err());+ let client = GoogleCalendarClient::new(Client::new());+ let result = client+ .apply_change_feed("unused", &target, vec![valid.clone(), malformed.clone()])+ .await;+ assert!(matches!(result, Err(error) if error.kind() == GoogleProviderErrorKind::Transient));++ let mut repaired = malformed;+ repaired.end = valid.end.clone();+ let mapped = map_snapshot(&target, vec![valid.clone(), repaired.clone()], Vec::new()).unwrap();+ assert_eq!(mapped.upserts.len(), 2);++ let mut orphan = valid.clone();+ orphan.recurring_event_id = Some("unreturned-master".to_owned());+ orphan.original_start_time = orphan.start.clone();+ assert!(map_snapshot(&target, vec![orphan.clone()], Vec::new()).is_err());+ orphan.start.as_mut().unwrap().date_time =+ Some((target.range.ends_at + chrono::Duration::hours(1)).to_rfc3339());+ orphan.end.as_mut().unwrap().date_time =+ Some((target.range.ends_at + chrono::Duration::hours(2)).to_rfc3339());+ let outside = map_snapshot(&target, vec![orphan], Vec::new()).unwrap();+ assert!(+ outside.upserts.is_empty(),+ "an exception moved outside the window needs no in-window occurrence");++ let applied = client+ .apply_change_feed("unused", &target, vec![valid, repaired])+ .await+ .unwrap();+ assert_eq!(applied.upserts.len(), 2);}#[test]@@ -752,7 +818,7 @@ fn occurrence_keys_parse_back_to_starts() {/// the decline onto the exception instance, so the exception's attendee list/// must survive mapping — it is the only record that the occurrence changed.#[test]-fn exception_attendees_are_carried_onto_the_override() {+fn exception_attendees_and_access_fields_are_carried_onto_the_override() {let master: GoogleEvent = serde_json::from_value(serde_json::json!({"id": "provider-master","iCalUID": "[email protected]",@@ -777,6 +843,8 @@ fn exception_attendees_are_carried_onto_the_override() {"start": {"dateTime": "2026-08-14T22:00:00Z", "timeZone": "UTC"},"end": {"dateTime": "2026-08-14T22:30:00Z", "timeZone": "UTC"},"status": "confirmed",+ "visibility": "private",+ "transparency": "transparent","attendees": [{"email": "[email protected]",@@ -801,6 +869,7 @@ fn exception_attendees_are_carried_onto_the_override() {end_date: NaiveDate::from_ymd_opt(2026, 9, 1).unwrap(),};let target = GoogleCalendarTarget {+ observed_access_role: Some("owner".to_owned()),owner_id: "macro|[email protected]".to_string(),email_link_id: Uuid::now_v7(),account_id: Uuid::now_v7(),@@ -812,6 +881,15 @@ fn exception_attendees_are_carried_onto_the_override() {let upsert = map_upsert(&target, master, vec![exception], Vec::new()).unwrap();+ assert_eq!(+ upsert.overrides[0].visibility,+ Some(EventVisibility::Private)+ );+ assert_eq!(+ upsert.overrides[0].transparency,+ Some(EventTransparency::Transparent)+ );+// The series answer is unchanged: only the one occurrence declined.let series_self = upsert.event@@ -952,6 +1030,7 @@ fn reminders_round_trip_between_google_and_the_domain() {end_date: NaiveDate::from_ymd_opt(2026, 8, 1).unwrap(),};let target = GoogleCalendarTarget {+ observed_access_role: Some("owner".to_owned()),owner_id: "macro|[email protected]".to_string(),email_link_id: Uuid::now_v7(),account_id: Uuid::now_v7(),@@ -1433,6 +1512,7 @@ async fn keyed_create_recovers_lost_response_and_duplicate_conflict_without_secoapi_base: endpoint,};let target = GoogleCalendarTarget {+ observed_access_role: Some("owner".to_owned()),owner_id: "macro|[email protected]".into(),email_link_id: Uuid::now_v7(),account_id: Uuid::now_v7(),diff --git a/crates/calendar_events/src/outbound/mod.rs b/crates/calendar_events/src/outbound/mod.rsindex ef119604a0..6e7d298a3c 100644--- a/crates/calendar_events/src/outbound/mod.rs+++ b/crates/calendar_events/src/outbound/mod.rs@@ -12,6 +12,9 @@ pub mod notification_notifier;/// PostgreSQL calendar repository.#[cfg(feature = "postgres")]pub mod pg;+/// PostgreSQL facts for team-calendar sharing.+#[cfg(feature = "postgres")]+pub mod pg_team;/// SQS calendar reminder dispatch queue.#[cfg(feature = "dispatch-sqs")]pub mod sqs_dispatch_queue;diff --git a/crates/calendar_events/src/outbound/pg.rs b/crates/calendar_events/src/outbound/pg.rsindex 1782835aa4..8bdf0451d9 100644--- a/crates/calendar_events/src/outbound/pg.rs+++ b/crates/calendar_events/src/outbound/pg.rs@@ -2,6 +2,7 @@mod change_log;mod changes;mod invitations;+mod source_access;use change_log::ChangeLogBatch;@@ -237,9 +238,16 @@ impl PgCalendarRepository {.map_err(report)?;let mut tx = self.pool.begin().await.map_err(report)?;let mut log = ChangeLogBatch::default();- let id = upsert_calendar_tx(&mut tx, &mut log, email_link_id, account_id, calendar)- .await?- .id;+ let id = upsert_calendar_tx(+ &mut tx,+ &mut log,+ email_link_id,+ account_id,+ calendar,+ false,+ )+ .await?+ .id;log.commit(tx).await?;Ok(id)}@@ -706,6 +714,7 @@ impl CalendarRepository for PgCalendarRepository {) -> Result<CalendarEventWriteOutcome, Report> {let mut tx = self.pool.begin().await.map_err(report)?;let user_mutation = matches!(write, CalendarEventWrite::UserMutation(_));+ let provider_sync = matches!(write, CalendarEventWrite::GoogleBackfill { .. });let upsert = match write {CalendarEventWrite::GoogleBackfill {key,@@ -761,6 +770,7 @@ impl CalendarRepository for PgCalendarRepository {let incoming =serde_json::to_value(StoredSourceProjection::from(&upsert)).map_err(report)?;if canonical_projection(&row.normalized_payload) == canonical_projection(&incoming) {+ source_access::verify_source_access(&mut tx, source).await?;tx.commit().await.map_err(report)?;return Ok(CalendarEventWriteOutcome {event_id: row.event_id,@@ -869,6 +879,9 @@ impl CalendarRepository for PgCalendarRepository {change: CalendarEventChange::Unchanged,});};+ if provider_sync {+ source_access::invalidate_account_freshness(&mut tx, source.account_id).await?;+ }// Content always follows the canonical copy. The schedule follows// whichever copy last wrote it: the canonical copy takes it when that@@ -1078,113 +1091,9 @@ impl CalendarRepository for PgCalendarRepository {range: OccurrenceRange,limit: u16,) -> Result<Vec<TeamOutOfOffice>, Report> {- // Type, title, and visibility come from the teammate's primary- // calendar copy, so a shared calendar's re-import of the event (which- // flattens the type and brackets the title) neither hides their status- // nor renames it, and an out-of-office event on a calendar they merely- // subscribe to belongs to that calendar's owner, not to them. DISTINCT- // ON collapses the same provider event synced through more than one of- // the teammate's inboxes before the limit, so duplicates never eat- // page slots or skew the caller's truncation detection.- let rows = sqlx::query!(- r#"- SELECT- owner_id AS "owner_id!",- event_id AS "event_id!",- ical_uid AS "ical_uid!",- occurrence_key AS "occurrence_key!",- title AS "title!",- visibility AS "visibility!",- time_zone,- occurrence_starts_at AS "occurrence_starts_at?",- occurrence_ends_at AS "occurrence_ends_at?",- occurrence_start_date AS "occurrence_start_date?",- occurrence_end_date AS "occurrence_end_date?"- FROM (- SELECT DISTINCT ON (event.owner_id, event.ical_uid, occurrence.occurrence_key)- event.owner_id,- occurrence.event_id,- event.ical_uid,- occurrence.occurrence_key,- source.title,- source.visibility,- event.time_zone,- occurrence.starts_at AS occurrence_starts_at,- occurrence.ends_at AS occurrence_ends_at,- occurrence.start_date AS occurrence_start_date,- occurrence.end_date AS occurrence_end_date,- COALESCE(- occurrence.starts_at,- occurrence.start_date::timestamp AT TIME ZONE 'UTC'- ) AS occurrence_ordering- FROM calendar_event_occurrences occurrence- JOIN calendar_events event ON event.id = occurrence.event_id- JOIN calendar_event_sources source ON source.event_id = event.id- JOIN calendars calendar- ON calendar.id = source.calendar_id- AND calendar.is_primary- AND NOT calendar.is_deleted- JOIN calendar_accounts account- ON account.id = source.account_id- AND account.sync_status <> 'disabled'- WHERE occurrence.owner_id IN (- SELECT teammate.user_id- FROM team_user membership- JOIN team_user teammate ON teammate.team_id = membership.team_id- WHERE membership.user_id = $1- AND teammate.user_id <> $1- )- AND source.event_type = 'out_of_office'- AND event.status <> 'cancelled'- AND NOT occurrence.is_cancelled- AND (- occurrence.timed_span && tstzrange($2, $3, '[)')- OR occurrence.day_span && daterange($4, $5, '[)')- )- ORDER BY- event.owner_id,- event.ical_uid,- occurrence.occurrence_key,- occurrence.event_id,- source.source_sequence DESC,- source.source_updated_at DESC,- source.id DESC- ) occurrence- ORDER BY- occurrence.occurrence_ordering,- occurrence.event_id,- occurrence.occurrence_key- LIMIT $6- "#,- requester_id,- range.starts_at,- range.ends_at,- range.start_date,- range.end_date,- i64::from(limit),- )- .fetch_all(&self.pool)- .await- .map_err(report)?;- rows.into_iter()- .map(|row| {- Ok(TeamOutOfOffice {- owner_id: row.owner_id,- event_id: row.event_id,- ical_uid: row.ical_uid,- occurrence_key: row.occurrence_key,- title: Some(row.title),- visibility: event_visibility(&row.visibility),- time: row_time(- row.occurrence_starts_at,- row.occurrence_ends_at,- row.occurrence_start_date,- row.occurrence_end_date,- row.time_zone,- )?,- })- })- .collect()+ // Compatibility OOO reads use the same verified source snapshots as+ // team projections; canonical content never supplies private details.+ super::pg_team::list_team_out_of_office(&self.pool, requester_id, range, limit).await}#[tracing::instrument(skip(self, requester_id, items), err)]@@ -1403,8 +1312,15 @@ impl CalendarRepository for PgCalendarRepository {let mut tx = self.pool.begin().await.map_err(report)?;fence_google_mutation_tx(&mut tx, key, lease_token, Some(account_id)).await?;let mut log = ChangeLogBatch::default();- let calendar =- upsert_calendar_tx(&mut tx, &mut log, key.email_link_id, account_id, calendar).await?;+ let calendar = upsert_calendar_tx(+ &mut tx,+ &mut log,+ key.email_link_id,+ account_id,+ calendar,+ true,+ )+ .await?;log.commit(tx).await?;stored_google_calendar(calendar)}@@ -1422,6 +1338,8 @@ impl CalendarRepository for PgCalendarRepository {let mut log = ChangeLogBatch::default();let mut tx = self.pool.begin().await.map_err(report)?;fence_google_mutation_tx(&mut tx, key, lease_token, Some(account_id)).await?;+ let previously_verified =+ source_access::snapshot_is_verified(&mut tx, account_id, sync.calendar_id).await?;if events_upserted > 0 {sqlx::query!(@@ -1471,6 +1389,9 @@ impl CalendarRepository for PgCalendarRepository {.fetch_all(&mut *tx).await.map_err(report)?;+ if !affected_event_ids.is_empty() {+ source_access::invalidate_account_freshness(&mut tx, account_id).await?;+ }for event_id in affected_event_ids {if let Some(outcome) =restore_best_source_or_delete(&mut tx, &mut log, event_id).await?@@ -1501,6 +1422,9 @@ impl CalendarRepository for PgCalendarRepository {.fetch_all(&mut *tx).await.map_err(report)?;+ if !affected_event_ids.is_empty() {+ source_access::invalidate_account_freshness(&mut tx, account_id).await?;+ }for event_id in affected_event_ids {if let Some(outcome) =restore_best_source_or_delete(&mut tx, &mut log, event_id).await?@@ -1568,6 +1492,15 @@ impl CalendarRepository for PgCalendarRepository {"provider calendar disappeared before sync state was committed"));}+ // The database trigger invalidates certification whenever snapshot+ // state changes, including writes from a worker predating this code.+ // Only a strict complete snapshot may upgrade an unverified calendar;+ // ordinary strict incremental polls preserve an existing certificate.+ if previously_verified+ || (has_materialized_range && sync.observed_provider_event_ids.is_some())+ {+ source_access::verify_calendar_snapshot(&mut tx, account_id, sync.calendar_id).await?;+ }if badged.is_some() {log.record(key.email_link_id,@@ -1789,6 +1722,9 @@ impl CalendarRepository for PgCalendarRepository {.fetch_all(&mut *tx).await.map_err(report)?;+ if !affected_event_ids.is_empty() {+ source_access::invalidate_account_freshness(&mut tx, account_id).await?;+ }for event_id in affected_event_ids {if let Some(outcome) =restore_best_source_or_delete(&mut tx, &mut log, event_id).await?@@ -1832,6 +1768,9 @@ impl CalendarRepository for PgCalendarRepository {.fetch_all(&mut *tx).await.map_err(report)?;+ if !flipped_calendars.is_empty() {+ source_access::invalidate_account_freshness(&mut tx, account_id).await?;+ }for calendar in flipped_calendars {log.record(key.email_link_id,@@ -1875,6 +1814,9 @@ impl CalendarRepository for PgCalendarRepository {.fetch_all(&mut *tx).await.map_err(report)?;+ if !refreshed_copies.is_empty() {+ source_access::invalidate_account_freshness(&mut tx, account_id).await?;+ }for copy in refreshed_copies {log.record(copy.source_link_id,@@ -1962,6 +1904,7 @@ impl CalendarRepository for PgCalendarRepository {source.account_id AS "account_id!",source.calendar_id AS "calendar_id!",calendar.provider_calendar_id,+ calendar.access_role,account.email_link_id,link.fusionauth_user_id,link.email_address,@@ -1971,6 +1914,7 @@ impl CalendarRepository for PgCalendarRepository {ON source.event_id = event.idAND source.source_kind = 'google'JOIN calendars calendar ON calendar.id = source.calendar_id+ AND calendar.account_id = source.account_idJOIN calendar_accounts account ON account.id = source.account_idJOIN email_links link ON link.id = account.email_link_idWHERE event.id = $1@@ -2022,6 +1966,7 @@ impl CalendarRepository for PgCalendarRepository {account_id: row.account_id,calendar_id: row.calendar_id,provider_calendar_id: row.provider_calendar_id,+ observed_access_role: row.access_role,token_identity,actor,}))@@ -2114,6 +2059,7 @@ impl CalendarRepository for PgCalendarRepository {calendar_id: row.calendar_id,provider_calendar_id: row.provider_calendar_id,is_read_only: !matches!(row.access_role.as_deref(), Some("owner" | "writer")),+ observed_access_role: row.access_role,is_primary: row.is_primary,token_identity,actor,@@ -2437,6 +2383,7 @@ async fn upsert_calendar_tx(email_link_id: Uuid,account_id: Uuid,calendar: ProviderCalendar,+ provider_sync: bool,) -> Result<StoredCalendarRow, Report> {// Snapshot the reminder-relevant state before the upsert: a change to the// default reminders or the zone that anchors all-day starts invalidates@@ -2444,7 +2391,12 @@ async fn upsert_calendar_tx(let previous = sqlx::query!(r#"SELECT- time_zone, default_reminders, name, color, access_role, is_primary, is_deleted+ time_zone, default_reminders, name, color, access_role, is_primary, is_deleted,+ (snapshot_normalization_version < 1 OR EXISTS (+ SELECT 1 FROM calendar_event_sources source+ WHERE source.calendar_id = calendars.id+ AND source.provider_access_role IS DISTINCT FROM calendars.access_role+ )) AS "needs_verification!"FROM calendarsWHERE account_id = $1 AND provider_calendar_id = $2"#,@@ -2466,7 +2418,18 @@ async fn upsert_calendar_tx(|| previous.is_primary != calendar.is_primary|| previous.default_reminders != default_reminders});+ if provider_sync && (visibly_changed || reminders_invalidated) {+ source_access::invalidate_account_freshness(tx, account_id).await?;+ }let anchor_zone = calendar.time_zone.clone();+ // Provider ACL changes and pre-migration snapshots need a full refresh+ // even when no event's sequence changed or the calendar has no sources.+ // The migration preserves old workers' incremental state; this strict+ // worker invalidates it before requesting the verified snapshot.+ // Old sources remain ineligible for team reads until verified.+ let access_changed = previous.as_ref().is_some_and(|previous| {+ previous.access_role != calendar.access_role || previous.needs_verification+ });let row = sqlx::query_as!(StoredCalendarRow,r#"@@ -2482,6 +2445,12 @@ async fn upsert_calendar_tx(time_zone = EXCLUDED.time_zone,color = EXCLUDED.color,access_role = EXCLUDED.access_role,+ sync_token = CASE WHEN $12 THEN NULL ELSE calendars.sync_token END,+ materialized_starts_at = CASE WHEN $12 THEN NULL ELSE calendars.materialized_starts_at END,+ materialized_ends_at = CASE WHEN $12 THEN NULL ELSE calendars.materialized_ends_at END,+ materialized_start_date = CASE WHEN $12 THEN NULL ELSE calendars.materialized_start_date END,+ materialized_end_date = CASE WHEN $12 THEN NULL ELSE calendars.materialized_end_date END,+ synced_at = CASE WHEN $12 THEN NULL ELSE calendars.synced_at END,is_primary = EXCLUDED.is_primary,is_selected = EXCLUDED.is_selected,is_deleted = false,@@ -2521,6 +2490,7 @@ async fn upsert_calendar_tx(calendar.is_primary,calendar.is_selected,&default_reminders,+ access_changed,).fetch_one(&mut **tx).await@@ -2713,7 +2683,6 @@ impl CalendarBackfillRepository for PgCalendarRepository {r#"UPDATE calendar_accountsSET sync_status = 'syncing',- last_sync_error = NULL,updated_at = now()WHERE email_link_id = $1"#,@@ -3109,7 +3078,7 @@ async fn persist_source(id, event_id, source_link_id, source_kind, account_id, calendar_id,provider_event_id, provider_recurring_event_id,provider_etag, raw_payload, source_sequence,- source_updated_at, normalized_payload,+ source_updated_at, normalized_payload, provider_access_role,title, description, location, event_type, visibility, transparency,is_read_only, reminders_use_default, reminder_overrides,creator_email, creator_name@@ -3117,6 +3086,7 @@ async fn persist_source(VALUES ($1, $2, $3, 'google', $4, $5, $6, $7, $8, $9,$10, $11, $12,+ $24,$13, $14, $15, $16, $17, $18,$19, $20, $21,$22, $23@@ -3131,6 +3101,7 @@ async fn persist_source(source_sequence = EXCLUDED.source_sequence,source_updated_at = EXCLUDED.source_updated_at,normalized_payload = EXCLUDED.normalized_payload,+ provider_access_role = EXCLUDED.provider_access_role,title = EXCLUDED.title,description = EXCLUDED.description,location = EXCLUDED.location,@@ -3174,6 +3145,7 @@ async fn persist_source(serde_json::to_value(&event.reminders.overrides).map_err(report)?,event.creator_email.as_deref(),event.creator_name.as_deref(),+ source.observed_access_role.as_deref(),).fetch_optional(&mut **tx).awaitdiff --git a/crates/calendar_events/src/outbound/pg/source_access.rs b/crates/calendar_events/src/outbound/pg/source_access.rsnew file mode 100644index 0000000000..69843e9112--- /dev/null+++ b/crates/calendar_events/src/outbound/pg/source_access.rs@@ -0,0 +1,91 @@+//! Provider entitlement checks attached to a successfully observed source.++use rootcause::Report;+use sqlx::{Postgres, Transaction};++use crate::domain::models::GoogleEventSource;++use super::report;++/// A changed provider poll writes several source snapshots in separate+/// transactions. Withdraw the account's prior completeness claim with its+/// first visible change; successful account completion restores freshness.+pub(super) async fn invalidate_account_freshness(+ tx: &mut Transaction<'_, Postgres>,+ account_id: uuid::Uuid,+) -> Result<(), Report> {+ sqlx::query!(+ "UPDATE calendar_accounts SET last_synced_at=NULL WHERE id=$1 AND last_synced_at IS NOT NULL",+ account_id,+ )+ .execute(&mut **tx)+ .await+ .map_err(report)?;+ Ok(())+}++/// An unchanged response verifies its content only when the role observed+/// before its provider request still matches this account's calendar role.+/// A delayed response must never upgrade itself to a newer stored role.+pub(super) async fn verify_source_access(+ tx: &mut Transaction<'_, Postgres>,+ source: &GoogleEventSource,+) -> Result<(), Report> {+ sqlx::query!(+ r#"+ UPDATE calendar_event_sources source+ SET provider_access_role = $4+ FROM calendars calendar+ WHERE source.calendar_id = calendar.id+ AND calendar.account_id = $1+ AND source.account_id = $1+ AND source.calendar_id = $2+ AND source.provider_event_id = $3+ AND $4::text IS NOT NULL+ AND calendar.access_role = $4+ AND source.provider_access_role IS DISTINCT FROM $4+ "#,+ source.account_id,+ source.calendar_id,+ &source.provider_event_id,+ source.observed_access_role.as_deref(),+ )+ .execute(&mut **tx)+ .await+ .map_err(report)?;+ Ok(())+}++/// Lock the calendar's certification before committing new snapshot state.+pub(super) async fn snapshot_is_verified(+ tx: &mut Transaction<'_, Postgres>,+ account_id: uuid::Uuid,+ calendar_id: uuid::Uuid,+) -> Result<bool, Report> {+ sqlx::query_scalar!(+ r#"SELECT snapshot_normalization_version >= 1 AS "verified!" FROM calendars WHERE id=$1 AND account_id=$2 AND NOT is_deleted FOR UPDATE"#,+ calendar_id,+ account_id,+ )+ .fetch_optional(&mut **tx)+ .await+ .map(|verified| verified.unwrap_or(false))+ .map_err(report)+}++/// Certify a strict worker's snapshot after the state-change trigger ran.+pub(super) async fn verify_calendar_snapshot(+ tx: &mut Transaction<'_, Postgres>,+ account_id: uuid::Uuid,+ calendar_id: uuid::Uuid,+) -> Result<(), Report> {+ sqlx::query!(+ "UPDATE calendars SET snapshot_normalization_version=1 WHERE id=$1 AND account_id=$2 AND NOT is_deleted",+ calendar_id,+ account_id,+ )+ .execute(&mut **tx)+ .await+ .map_err(report)?;+ Ok(())+}diff --git a/crates/calendar_events/src/outbound/pg/test.rs b/crates/calendar_events/src/outbound/pg/test.rsindex c7db88bb24..e200937b0c 100644--- a/crates/calendar_events/src/outbound/pg/test.rs+++ b/crates/calendar_events/src/outbound/pg/test.rs@@ -1,4 +1,7 @@use super::*;+mod snapshot_coverage;+mod team_sharing;+mod team_sync_coverage;use crate::domain::models::{GOOGLE_CALENDAR_SCOPES, GoogleCalendarSyncSnapshot, GoogleEventSource, GoogleWatchChannel,OccurrenceException, OccurrenceListing, REMINDER_METHOD_EMAIL, REMINDER_METHOD_POPUP,@@ -161,6 +164,7 @@ fn timed_upsert(updated_at: starts_at + Duration::minutes(i64::from(sequence)),},source: CalendarEventSource::Google(GoogleEventSource {+ observed_access_role: Some("owner".to_owned()),email_link_id: link_id,account_id,calendar_id,@@ -590,6 +594,7 @@ async fn removing_calendar_scope_disables_sources_and_fences_the_running_job(poo1,);google.source = CalendarEventSource::Google(GoogleEventSource {+ observed_access_role: Some("owner".to_owned()),email_link_id: link_id,account_id,calendar_id,@@ -928,6 +933,7 @@ async fn fenced_google_snapshot_removes_deleted_events_and_calendars(pool: PgPoo1,);google.source = CalendarEventSource::Google(GoogleEventSource {+ observed_access_role: Some("owner".to_owned()),email_link_id: link_id,account_id,calendar_id,@@ -1074,6 +1080,7 @@ async fn expired_google_worker_cannot_resurrect_reconciled_provider_data(pool: P1,);google.source = CalendarEventSource::Google(GoogleEventSource {+ observed_access_role: Some("owner".to_owned()),email_link_id: link_id,account_id,calendar_id,@@ -1194,6 +1201,7 @@ async fn google_snapshot_deletion_removes_an_event_without_a_surviving_source(po2,);google.source = CalendarEventSource::Google(GoogleEventSource {+ observed_access_role: Some("owner".to_owned()),email_link_id: link_id,account_id,calendar_id,@@ -1274,6 +1282,7 @@ async fn incremental_cancellation_tombstones_retire_sources_without_a_snapshot(p2,);google.source = CalendarEventSource::Google(GoogleEventSource {+ observed_access_role: Some("owner".to_owned()),email_link_id: link_id,account_id,calendar_id,@@ -1292,6 +1301,7 @@ async fn incremental_cancellation_tombstones_retire_sources_without_a_snapshot(p1,);instance.source = CalendarEventSource::Google(GoogleEventSource {+ observed_access_role: Some("owner".to_owned()),email_link_id: link_id,account_id,calendar_id,@@ -1448,6 +1458,8 @@ async fn listing_keeps_the_series_event_beside_the_exception_and_its_link(pool:let recurrence_id = edited_start.to_rfc3339();upsert.occurrences[1].recurrence_id = Some(recurrence_id.clone());upsert.overrides = vec![CalendarEventOverride {+ visibility: None,+ transparency: None,sequence: None,source_updated_at: None,recurrence_id: recurrence_id.clone(),@@ -1548,6 +1560,8 @@ async fn occurrence_attendee_override_shadows_the_series_response(pool: PgPool)let recurrence_id = declined_start.to_rfc3339();upsert.occurrences[1].recurrence_id = Some(recurrence_id.clone());upsert.overrides = vec![CalendarEventOverride {+ visibility: None,+ transparency: None,sequence: None,source_updated_at: None,recurrence_id: recurrence_id.clone(),@@ -1633,6 +1647,8 @@ async fn occurrence_content_override_shadows_the_series_content(pool: PgPool) {let recurrence_id = edited_start.to_rfc3339();upsert.occurrences[1].recurrence_id = Some(recurrence_id.clone());upsert.overrides = vec![CalendarEventOverride {+ visibility: None,+ transparency: None,sequence: None,source_updated_at: None,recurrence_id: recurrence_id.clone(),@@ -1741,6 +1757,8 @@ async fn mention_preview_shows_the_previewed_occurrences_content(pool: PgPool) {let recurrence_id = edited_start.to_rfc3339();upsert.occurrences[1].recurrence_id = Some(recurrence_id.clone());upsert.overrides = vec![CalendarEventOverride {+ visibility: None,+ transparency: None,sequence: None,source_updated_at: None,recurrence_id: recurrence_id.clone(),@@ -1826,6 +1844,8 @@ async fn explicitly_empty_override_attendees_do_not_inherit_the_series_list(poollet recurrence_id = emptied_start.to_rfc3339();upsert.occurrences[1].recurrence_id = Some(recurrence_id.clone());upsert.overrides = vec![CalendarEventOverride {+ visibility: None,+ transparency: None,sequence: None,source_updated_at: None,recurrence_id: recurrence_id.clone(),@@ -2159,6 +2179,7 @@ async fn unchanged_google_projection_skips_the_write_path(pool: PgPool) {1,);upsert.source = CalendarEventSource::Google(GoogleEventSource {+ observed_access_role: Some("owner".to_owned()),email_link_id: link_id,account_id,calendar_id,@@ -2443,6 +2464,7 @@ async fn stale_google_source_projection_cannot_resurface_during_reconciliation(p);latest.event.updated_at += Duration::days(2);latest.source = CalendarEventSource::Google(GoogleEventSource {+ observed_access_role: Some("owner".to_owned()),email_link_id: link_id,account_id,calendar_id: primary_calendar_id,@@ -2462,6 +2484,7 @@ async fn stale_google_source_projection_cannot_resurface_during_reconciliation(p1,);sibling.source = CalendarEventSource::Google(GoogleEventSource {+ observed_access_role: Some("owner".to_owned()),email_link_id: link_id,account_id,calendar_id: sibling_calendar_id,@@ -2482,6 +2505,7 @@ async fn stale_google_source_projection_cannot_resurface_during_reconciliation(p);stale.event.updated_at -= Duration::days(2);stale.source = CalendarEventSource::Google(GoogleEventSource {+ observed_access_role: Some("owner".to_owned()),email_link_id: link_id,account_id,calendar_id: primary_calendar_id,@@ -3241,6 +3265,7 @@ async fn removing_a_google_source_restores_the_surviving_calendar_copy(pool: PgP1,);team_copy.source = CalendarEventSource::Google(GoogleEventSource {+ observed_access_role: Some("writer".to_owned()),email_link_id: link_id,account_id,calendar_id: secondary_id,@@ -3334,6 +3359,7 @@ fn reminder_upsert(updated_at: starts_at - Duration::days(1),},source: CalendarEventSource::Google(GoogleEventSource {+ observed_access_role: Some("owner".to_owned()),email_link_id: link_id,account_id,calendar_id,@@ -4684,6 +4710,26 @@ fn july_2026_range() -> OccurrenceRange {}}+/// An explicit detail grant and successful provider snapshot for OOO fixtures.+async fn enable_team_details(repo: &PgCalendarRepository, users: &[&str]) {+ sqlx::query!(+ "UPDATE calendar_accounts SET sync_status='ready',last_synced_at=now(),last_sync_error=NULL WHERE owner_id=ANY($1::text[]) AND sync_status<>'disabled'",+ users as &[&str]+ ).execute(&repo.pool).await.unwrap();+ sqlx::query!(+ "INSERT INTO calendar_team_sharing(user_id,sharing) SELECT unnest($1::text[]),'all' ON CONFLICT(user_id) DO UPDATE SET sharing='all'",+ users as &[&str]+ ).execute(&repo.pool).await.unwrap();+ sqlx::query!(+ "UPDATE calendars SET synced_at=now() WHERE account_id IN (SELECT id FROM calendar_accounts WHERE owner_id=ANY($1::text[]))",+ users as &[&str]+ ).execute(&repo.pool).await.unwrap();+ sqlx::query!(+ "UPDATE calendars SET snapshot_normalization_version=1 WHERE account_id IN (SELECT id FROM calendar_accounts WHERE owner_id=ANY($1::text[]))",+ users as &[&str]+ ).execute(&repo.pool).await.unwrap();+}+#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]async fn team_out_of_office_returns_teammates_status_only(pool: PgPool) {let requester = "macro|[email protected]";@@ -4736,6 +4782,8 @@ async fn team_out_of_office_returns_teammates_status_only(pool: PgPool) {.await.unwrap();+ enable_team_details(&repo, &[teammate]).await;+let rows = repo.list_team_out_of_office(requester, july_2026_range(), 100).await@@ -4821,6 +4869,8 @@ async fn team_out_of_office_requires_an_active_primary_calendar_source(pool: PgP.await.unwrap();+ enable_team_details(&repo, &[subscribed, disabled]).await;+let rows = repo.list_team_out_of_office(requester, july_2026_range(), 100).await@@ -4830,7 +4880,7 @@ async fn team_out_of_office_requires_an_active_primary_calendar_source(pool: PgP}#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]-async fn team_out_of_office_masks_private_titles_and_collapses_duplicate_inboxes(pool: PgPool) {+async fn team_out_of_office_hides_private_status_even_with_detail_sharing(pool: PgPool) {let requester = "macro|[email protected]";let teammate = "macro|[email protected]";insert_team(&pool, requester, &[requester, teammate]).await;@@ -4858,18 +4908,17 @@ async fn team_out_of_office_masks_private_titles_and_collapses_duplicate_inboxesduplicate.event.visibility = EventVisibility::Private;repo.upsert_event_fixture(duplicate).await.unwrap();- let service = CalendarService::new(repo);+ enable_team_details(&repo, &[teammate]).await;+ let service = CalendarService::new(repo).with_team_sharing_enabled(true);let rows = service.list_team_out_of_office(requester, july_2026_range(), 100).await.unwrap();- assert_eq!(rows.len(), 2);- assert!(rows.iter().all(|row| row.title.is_none()));- let mut keys: Vec<_> = rows.iter().map(|row| row.occurrence_key.as_str()).collect();- keys.sort_unstable();- keys.dedup();- assert_eq!(keys.len(), 2);+ assert!(+ rows.is_empty(),+ "the OOO endpoint must not reveal the category of private busy time"+ );}fn shift_upsert_days(upsert: &mut CalendarEventUpsert, days: i64) {@@ -4934,6 +4983,8 @@ async fn team_out_of_office_deduplicates_before_the_limit(pool: PgPool) {shift_upsert_days(&mut later, 1);repo.upsert_event_fixture(later).await.unwrap();+ enable_team_details(&repo, &[teammate]).await;+let rows = repo.list_team_out_of_office(requester, july_2026_range(), 3).await@@ -5049,6 +5100,7 @@ fn shared_copy_upsert(upsert.event.creator_name = Some("Vacation script".to_string());upsert.event.updated_at += Duration::hours(1);upsert.source = CalendarEventSource::Google(GoogleEventSource {+ observed_access_role: Some("reader".to_owned()),email_link_id: link_id,account_id,calendar_id,@@ -5218,17 +5270,14 @@ async fn shared_calendar_copy_records_its_content_without_touching_the_primary_e]);- // The team overlay reads the member's own type and title.+ // The semantic team overlay cannot reveal the primary copy's private OOO+ // category, even when the member explicitly shares ordinary event details.+ enable_team_details(&repo, &[member]).await;let team = repo.list_team_out_of_office(viewer, range_around(starts_at), 100).await.unwrap();- assert_eq!(- team.iter()- .map(|row| (row.owner_id.as_str(), row.title.as_deref()))- .collect::<Vec<_>>(),- vec![(member, Some("OOO"))]- );+ assert!(team.is_empty(), "private OOO remains generic availability");// Reminders fire once, per the member's own 30-minute setting.assert_eq!(@@ -5270,10 +5319,13 @@ async fn a_late_primary_sync_reclaims_the_entity_from_a_shared_copy(pool: PgPool("[teo] OOO", "default"));assert!(- repo.list_team_out_of_office(viewer, range_around(starts_at), 100)- .await- .unwrap()- .is_empty(),+ {+ enable_team_details(&repo, &[member]).await;+ repo.list_team_out_of_office(viewer, range_around(starts_at), 100)+ .await+ .unwrap()+ .is_empty()+ },"a copy on a subscribed calendar is not the member's own status");@@ -5316,12 +5368,12 @@ async fn a_late_primary_sync_reclaims_the_entity_from_a_shared_copy(pool: PgPool.collect::<Vec<_>>(),vec![primary_calendar_id, shared_calendar_id]);- assert_eq!(+ assert!(repo.list_team_out_of_office(viewer, range_around(starts_at), 100).await.unwrap()- .len(),- 1+ .is_empty(),+ "a private primary copy must not reveal the member's OOO category");assert_eq!(scheduled_firings(&pool, event_id).await,@@ -5480,6 +5532,10 @@ async fn mutation_target_addresses_the_primary_by_default_and_the_named_calendar.expect("owner sees the mutation target");assert_eq!(default_target.calendar_id, primary_calendar_id);assert_eq!(default_target.provider_calendar_id, "primary");+ assert_eq!(+ default_target.observed_access_role.as_deref(),+ Some("owner")+ );assert!(!default_target.is_read_only);let copy_target = repo@@ -5488,6 +5544,7 @@ async fn mutation_target_addresses_the_primary_by_default_and_the_named_calendar.unwrap().expect("the shared copy is addressable by its calendar");assert_eq!(copy_target.calendar_id, shared_calendar_id);+ assert_eq!(copy_target.observed_access_role.as_deref(), Some("reader"));assert_eq!(copy_target.provider_calendar_id,@@ -6679,6 +6736,7 @@ async fn retiring_an_unrelated_copy_keeps_a_fresher_schedule_written_through_anostarts_at,);third.source = CalendarEventSource::Google(GoogleEventSource {+ observed_access_role: Some("reader".to_owned()),email_link_id: link_id,account_id,calendar_id: third_calendar_id,@@ -6717,3 +6775,4 @@ async fn retiring_an_unrelated_copy_keeps_a_fresher_schedule_written_through_anomod changes;mod invitations;+mod source_access;diff --git a/crates/calendar_events/src/outbound/pg/test/changes.rs b/crates/calendar_events/src/outbound/pg/test/changes.rsindex 4e2d26d3d6..f4d6e8197c 100644--- a/crates/calendar_events/src/outbound/pg/test/changes.rs+++ b/crates/calendar_events/src/outbound/pg/test/changes.rs@@ -722,6 +722,8 @@ async fn replaying_the_log_reproduces_what_the_viewer_reads(pool: PgPool) {let declined_start = Utc.with_ymd_and_hms(2026, 7, 25, 14, 0, 0).unwrap();series.occurrences[1].recurrence_id = Some(declined_start.to_rfc3339());series.overrides = vec![CalendarEventOverride {+ visibility: None,+ transparency: None,sequence: None,source_updated_at: None,recurrence_id: declined_start.to_rfc3339(),diff --git a/crates/calendar_events/src/outbound/pg/test/invitations.rs b/crates/calendar_events/src/outbound/pg/test/invitations.rsindex 051907b9fa..55d95d464b 100644--- a/crates/calendar_events/src/outbound/pg/test/invitations.rs+++ b/crates/calendar_events/src/outbound/pg/test/invitations.rs@@ -113,6 +113,8 @@ async fn invitation_moved_instance_uses_original_key_and_instance_revision(pool:time_zone: None,};upsert.overrides.push(CalendarEventOverride {+ visibility: None,+ transparency: None,sequence: Some(8),source_updated_at: Some(Utc::now()),recurrence_id: original.clone(),@@ -171,6 +173,8 @@ async fn master_invitation_does_not_compare_revisions_with_first_exception(pool:let first = &mut upsert.occurrences[0];first.recurrence_id = Some(first.occurrence_key.clone());upsert.overrides.push(CalendarEventOverride {+ visibility: None,+ transparency: None,sequence: Some(8),source_updated_at: Some(Utc::now()),recurrence_id: first.occurrence_key.clone(),diff --git a/crates/calendar_events/src/outbound/pg/test/snapshot_coverage.rs b/crates/calendar_events/src/outbound/pg/test/snapshot_coverage.rsnew file mode 100644index 0000000000..f41757d092--- /dev/null+++ b/crates/calendar_events/src/outbound/pg/test/snapshot_coverage.rs@@ -0,0 +1,135 @@+use super::*;++#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]+async fn empty_calendars_require_strict_full_verification_and_old_writes_revoke_it(pool: PgPool) {+ let owner = "macro|[email protected]";+ let link = insert_link(&pool, owner).await;+ let repo = PgCalendarRepository::new(pool.clone());+ let grant = repo+ .apply_google_grant(+ link,+ complete_grant(),+ CalendarGrantIntent::CalendarRequested,+ )+ .await+ .unwrap();+ let job = grant+ .jobs+ .iter()+ .find(|job| job.kind == CalendarBackfillKind::GoogleCalendar)+ .unwrap();+ let account = job.account_id.unwrap();+ let key = CalendarBackfillJobKey {+ job_id: job.id,+ email_link_id: link,+ };+ let CalendarBackfillClaim::Claimed { lease_token, .. } =+ repo.claim_google_backfill(key).await.unwrap()+ else {+ panic!("the calendar job should be claimable");+ };+ let calendar = ProviderCalendar {+ provider_calendar_id: "primary".to_owned(),+ name: "Primary".to_owned(),+ description: None,+ time_zone: Some("UTC".to_owned()),+ color: None,+ access_role: Some("owner".to_owned()),+ is_primary: true,+ is_selected: true,+ default_reminders: Vec::new(),+ };+ let calendar_id = repo+ .upsert_google_calendar(key, lease_token, account, calendar.clone())+ .await+ .unwrap()+ .id;+ let version = || async {+ sqlx::query_scalar!(+ "SELECT snapshot_normalization_version FROM calendars WHERE id=$1",+ calendar_id+ )+ .fetch_one(&pool)+ .await+ .unwrap()+ };+ // The migration preserves a legacy worker's token and coverage while its+ // certificate remains zero. This empty snapshot has no source row whose+ // role could demand a rebuild: strict calendar upsert must independently+ // invalidate that preserved incremental state before provider sync.+ sqlx::query!("UPDATE calendars SET sync_token='legacy',synced_at=now(),materialized_starts_at='2026-07-01',materialized_ends_at='2026-08-01',materialized_start_date='2026-07-01',materialized_end_date='2026-08-01' WHERE id=$1", calendar_id).execute(&pool).await.unwrap();+ assert_eq!(version().await, 0);+ let stored = repo+ .upsert_google_calendar(key, lease_token, account, calendar.clone())+ .await+ .unwrap();+ assert!(stored.sync_token.is_none());+ assert!(stored.materialized_range.is_none());+ assert!(stored.synced_at.is_none());+ assert_eq!(+ version().await,+ 0,+ "invalidating preserved state cannot itself certify an empty calendar"+ );+ let full = GoogleCalendarSyncSnapshot {+ calendar_id,+ next_sync_token: "strict-full".to_owned(),+ observed_provider_event_ids: Some(Vec::new()),+ materialized_range: Some(july_2026_range()),+ cancelled_provider_event_ids: Vec::new(),+ };+ repo.commit_google_calendar_sync(key, lease_token, account, full.clone(), 0)+ .await+ .unwrap();+ assert_eq!(version().await, 1);++ let incremental = GoogleCalendarSyncSnapshot {+ next_sync_token: "strict-incremental".to_owned(),+ observed_provider_event_ids: None,+ materialized_range: None,+ ..full.clone()+ };+ repo.commit_google_calendar_sync(key, lease_token, account, incremental.clone(), 0)+ .await+ .unwrap();+ assert_eq!(+ version().await,+ 1,+ "ordinary strict polling preserves certification"+ );+ let stored = repo+ .upsert_google_calendar(key, lease_token, account, calendar.clone())+ .await+ .unwrap();+ assert_eq!(stored.sync_token.as_deref(), Some("strict-incremental"));+ assert!(stored.materialized_range.is_some());++ // An old worker omits the new certification column. The database must+ // revoke the certificate even if this follows a newer worker's success.+ sqlx::query!(+ "UPDATE calendars SET sync_token='legacy-after-strict',synced_at=now() WHERE id=$1",+ calendar_id+ )+ .execute(&pool)+ .await+ .unwrap();+ assert_eq!(version().await, 0);+ repo.commit_google_calendar_sync(key, lease_token, account, incremental, 0)+ .await+ .unwrap();+ assert_eq!(+ version().await,+ 0,+ "a token-only response cannot repair lost coverage"+ );+ let stored = repo+ .upsert_google_calendar(key, lease_token, account, calendar)+ .await+ .unwrap();+ assert!(stored.sync_token.is_none());+ assert!(stored.materialized_range.is_none());+ repo.commit_google_calendar_sync(key, lease_token, account, full, 0)+ .await+ .unwrap();+ assert_eq!(version().await, 1);+}diff --git a/crates/calendar_events/src/outbound/pg/test/source_access.rs b/crates/calendar_events/src/outbound/pg/test/source_access.rsnew file mode 100644index 0000000000..58ab024e00--- /dev/null+++ b/crates/calendar_events/src/outbound/pg/test/source_access.rs@@ -0,0 +1,335 @@+use super::*;++#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]+async fn pre_migration_sources_force_a_full_refresh_before_team_readiness(pool: PgPool) {+ let owner = "macro|[email protected]";+ let link = insert_link(&pool, owner).await;+ let repo = PgCalendarRepository::new(pool.clone());+ let provider = provider_ids(&repo, link).await;+ let original = timed_upsert(owner, link, provider, "[email protected]", "Unchanged", 1);+ let event_id = repo.upsert_event_fixture(original.clone()).await.unwrap();+ sqlx::query!(+ "UPDATE calendar_event_sources SET provider_access_role = NULL WHERE event_id = $1",+ event_id+ )+ .execute(&pool)+ .await+ .unwrap();+ sqlx::query!(+ "UPDATE calendars SET sync_token = 'old-token', synced_at = now() WHERE id = $1",+ provider.1+ )+ .execute(&pool)+ .await+ .unwrap();+ repo.upsert_calendar_fixture(+ provider.0,+ ProviderCalendar {+ provider_calendar_id: "primary".to_owned(),+ name: "Primary".to_owned(),+ description: None,+ time_zone: Some("UTC".to_owned()),+ color: None,+ access_role: Some("owner".to_owned()),+ is_primary: true,+ is_selected: true,+ default_reminders: Vec::new(),+ },+ )+ .await+ .unwrap();+ let refreshed = sqlx::query!(+ "SELECT sync_token, synced_at FROM calendars WHERE id = $1",+ provider.1+ )+ .fetch_one(&pool)+ .await+ .unwrap();+ assert!(refreshed.sync_token.is_none());+ assert!(refreshed.synced_at.is_none());+ assert_eq!(repo.upsert_event_fixture(original).await.unwrap(), event_id);+ let role = sqlx::query_scalar!(+ "SELECT provider_access_role FROM calendar_event_sources WHERE event_id = $1",+ event_id+ )+ .fetch_one(&pool)+ .await+ .unwrap();+ assert_eq!(role.as_deref(), Some("owner"));+}++#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]+async fn role_change_requires_a_new_snapshot_without_changing_event_identity(pool: PgPool) {+ let owner = "macro|[email protected]";+ let link = insert_link(&pool, owner).await;+ let repo = PgCalendarRepository::new(pool.clone());+ let provider = provider_ids(&repo, link).await;+ let mut original = timed_upsert(+ owner,+ link,+ provider,+ "[email protected]",+ "Original",+ 1,+ );+ let event_id = repo.upsert_event_fixture(original.clone()).await.unwrap();+ sqlx::query!(+ "UPDATE calendars SET sync_token = 'old-token', synced_at = now(), materialized_starts_at = now(), materialized_ends_at = now() + interval '1 day', materialized_start_date = current_date, materialized_end_date = current_date + 1 WHERE id = $1",+ provider.1,+ ).execute(&pool).await.unwrap();++ repo.upsert_calendar_fixture(+ provider.0,+ ProviderCalendar {+ provider_calendar_id: "primary".to_owned(),+ name: "Primary".to_owned(),+ description: None,+ time_zone: Some("UTC".to_owned()),+ color: None,+ access_role: Some("reader".to_owned()),+ is_primary: true,+ is_selected: true,+ default_reminders: Vec::new(),+ },+ )+ .await+ .unwrap();+ let invalidated = sqlx::query!(+ "SELECT calendar.sync_token, calendar.synced_at, calendar.materialized_starts_at, source.provider_access_role FROM calendars calendar JOIN calendar_event_sources source ON source.calendar_id = calendar.id WHERE source.event_id = $1",+ event_id,+ ).fetch_one(&pool).await.unwrap();+ assert!(invalidated.sync_token.is_none());+ assert!(invalidated.synced_at.is_none());+ assert!(invalidated.materialized_starts_at.is_none());+ assert_eq!(invalidated.provider_access_role.as_deref(), Some("owner"));++ // The provider can return the same content and sequence under the new+ // role. Verification must work through the no-op fast path too.+ let CalendarEventSource::Google(source) = &mut original.source;+ source.observed_access_role = Some("reader".to_owned());+ assert_eq!(repo.upsert_event_fixture(original).await.unwrap(), event_id);+ let verified = sqlx::query_scalar!(+ "SELECT provider_access_role FROM calendar_event_sources WHERE event_id = $1",+ event_id,+ )+ .fetch_one(&pool)+ .await+ .unwrap();+ assert_eq!(verified.as_deref(), Some("reader"));+}++#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]+async fn provider_redaction_replaces_details_even_without_a_sequence_change(pool: PgPool) {+ let owner = "macro|[email protected]";+ let link = insert_link(&pool, owner).await;+ let repo = PgCalendarRepository::new(pool.clone());+ let provider = provider_ids(&repo, link).await;+ let mut snapshot = timed_upsert(+ owner,+ link,+ provider,+ "[email protected]",+ "Private title",+ 1,+ );+ snapshot.event.description = Some("Private body".to_owned());+ snapshot.event.visibility = EventVisibility::Private;+ let event_id = repo.upsert_event_fixture(snapshot.clone()).await.unwrap();+ sqlx::query!(+ "UPDATE calendars SET access_role = 'reader' WHERE id = $1",+ provider.1+ )+ .execute(&pool)+ .await+ .unwrap();+ snapshot.event.title.clear();+ snapshot.event.description = None;+ snapshot.event.attendees.clear();+ let CalendarEventSource::Google(source) = &mut snapshot.source;+ source.observed_access_role = Some("reader".to_owned());+ assert_eq!(repo.upsert_event_fixture(snapshot).await.unwrap(), event_id);+ let redacted = sqlx::query!(+ "SELECT title, description, provider_access_role FROM calendar_event_sources WHERE event_id = $1",+ event_id,+ ).fetch_one(&pool).await.unwrap();+ assert!(redacted.title.is_empty());+ assert!(redacted.description.is_none());+ assert_eq!(redacted.provider_access_role.as_deref(), Some("reader"));+}++#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]+async fn delayed_mutation_echo_cannot_verify_content_under_a_new_role(pool: PgPool) {+ let owner = "macro|[email protected]";+ let link = insert_link(&pool, owner).await;+ let repo = PgCalendarRepository::new(pool.clone());+ let provider = provider_ids(&repo, link).await;+ let original = timed_upsert(owner, link, provider, "[email protected]", "Old details", 1);+ let event_id = repo.upsert_event_fixture(original.clone()).await.unwrap();++ // The worker has already detected a lower role and reconciled the source+ // before an in-flight mutation's richer provider response arrives.+ sqlx::query!(+ "UPDATE calendars SET access_role = 'reader', synced_at = now() WHERE id = $1",+ provider.1,+ )+ .execute(&pool)+ .await+ .unwrap();+ let mut redacted = original.clone();+ redacted.event.title.clear();+ let CalendarEventSource::Google(source) = &mut redacted.source;+ source.observed_access_role = Some("reader".to_owned());+ repo.upsert_event_fixture(redacted.clone()).await.unwrap();+ repo.upsert_event(CalendarEventWrite::UserMutation(original.clone()))+ .await+ .unwrap();++ let role = sqlx::query_scalar!(+ "SELECT provider_access_role FROM calendar_event_sources WHERE event_id = $1",+ event_id,+ )+ .fetch_one(&pool)+ .await+ .unwrap();+ assert_eq!(role.as_deref(), Some("owner"));+ let eligible = sqlx::query_scalar!(+ "SELECT source.provider_access_role = calendar.access_role AS \"eligible!\" FROM calendar_event_sources source JOIN calendars calendar ON calendar.id=source.calendar_id WHERE source.event_id=$1",+ event_id,+ ).fetch_one(&pool).await.unwrap();+ assert!(+ !eligible,+ "the delayed response retains its old, ineligible role"+ );++ // Retrying the identical mutation takes the no-op path. It must not turn+ // the mismatched snapshot into evidence of the current reader grant.+ repo.upsert_event(CalendarEventWrite::UserMutation(original))+ .await+ .unwrap();+ let role = sqlx::query_scalar!(+ "SELECT provider_access_role FROM calendar_event_sources WHERE event_id = $1",+ event_id,+ )+ .fetch_one(&pool)+ .await+ .unwrap();+ assert_eq!(role.as_deref(), Some("owner"));++ repo.upsert_event_fixture(redacted).await.unwrap();+ let verified = sqlx::query!(+ "SELECT title, provider_access_role FROM calendar_event_sources WHERE event_id = $1",+ event_id,+ )+ .fetch_one(&pool)+ .await+ .unwrap();+ assert!(verified.title.is_empty());+ assert_eq!(verified.provider_access_role.as_deref(), Some("reader"));+}++#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]+async fn unchanged_mutation_preserves_but_never_elevates_source_verification(pool: PgPool) {+ let owner = "macro|[email protected]";+ let link = insert_link(&pool, owner).await;+ let repo = PgCalendarRepository::new(pool.clone());+ let provider = provider_ids(&repo, link).await;+ let original = timed_upsert(owner, link, provider, "[email protected]", "Same details", 1);+ let event_id = repo.upsert_event_fixture(original.clone()).await.unwrap();+ repo.upsert_event(CalendarEventWrite::UserMutation(original.clone()))+ .await+ .unwrap();+ let role = sqlx::query_scalar!(+ "SELECT provider_access_role FROM calendar_event_sources WHERE event_id = $1",+ event_id,+ )+ .fetch_one(&pool)+ .await+ .unwrap();+ assert_eq!(role.as_deref(), Some("owner"));++ sqlx::query!(+ "UPDATE calendars SET access_role = 'reader' WHERE id = $1",+ provider.1,+ )+ .execute(&pool)+ .await+ .unwrap();+ repo.upsert_event(CalendarEventWrite::UserMutation(original))+ .await+ .unwrap();+ let role = sqlx::query_scalar!(+ "SELECT provider_access_role FROM calendar_event_sources WHERE event_id = $1",+ event_id,+ )+ .fetch_one(&pool)+ .await+ .unwrap();+ assert_eq!(role.as_deref(), Some("owner"));+}++#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]+async fn ordinary_mutation_preserves_incremental_sync_and_verified_access(pool: PgPool) {+ let owner = "macro|[email protected]";+ let link = insert_link(&pool, owner).await;+ let repo = PgCalendarRepository::new(pool.clone());+ let provider = provider_ids(&repo, link).await;+ let mut original = timed_upsert(owner, link, provider, "[email protected]", "Before", 1);+ original.event.is_read_only = false;+ let event_id = repo.upsert_event_fixture(original.clone()).await.unwrap();+ let target = repo+ .get_event_mutation_target(owner, event_id, Some(provider.1))+ .await+ .unwrap()+ .unwrap();+ assert_eq!(target.observed_access_role.as_deref(), Some("owner"));+ assert_eq!(target.account_id, provider.0);+ assert_eq!(target.calendar_id, provider.1);++ sqlx::query!(+ "UPDATE calendars SET sync_token='keep-token', synced_at=now(), materialized_starts_at='2026-07-01', materialized_ends_at='2026-08-01', materialized_start_date='2026-07-01', materialized_end_date='2026-08-01' WHERE id=$1",+ provider.1,+ ).execute(&pool).await.unwrap();+ sqlx::query!(+ "UPDATE calendars SET snapshot_normalization_version=1 WHERE id=$1",+ provider.1,+ )+ .execute(&pool)+ .await+ .unwrap();+ original.event.title = "After".to_owned();+ original.event.sequence += 1;+ original.event.updated_at += Duration::minutes(1);+ let CalendarEventSource::Google(source) = &mut original.source;+ source.observed_access_role = target.observed_access_role;+ repo.upsert_event(CalendarEventWrite::UserMutation(original))+ .await+ .unwrap();++ // A routine CalendarList refresh must keep the event-change token and+ // materialized range; an edit alone is not an entitlement transition.+ repo.upsert_calendar_fixture(+ provider.0,+ ProviderCalendar {+ provider_calendar_id: "primary".to_owned(),+ name: "Primary".to_owned(),+ description: None,+ time_zone: Some("UTC".to_owned()),+ color: None,+ access_role: Some("owner".to_owned()),+ is_primary: true,+ is_selected: true,+ default_reminders: Vec::new(),+ },+ )+ .await+ .unwrap();+ let state = sqlx::query!(+ "SELECT calendar.sync_token, calendar.synced_at, calendar.materialized_starts_at, source.provider_access_role, source.title FROM calendars calendar JOIN calendar_event_sources source ON source.calendar_id=calendar.id WHERE source.event_id=$1",+ event_id,+ ).fetch_one(&pool).await.unwrap();+ assert_eq!(state.sync_token.as_deref(), Some("keep-token"));+ assert!(state.synced_at.is_some());+ assert!(state.materialized_starts_at.is_some());+ assert_eq!(state.provider_access_role.as_deref(), Some("owner"));+ assert_eq!(state.title, "After");+}diff --git a/crates/calendar_events/src/outbound/pg/test/team_sharing.rs b/crates/calendar_events/src/outbound/pg/test/team_sharing.rsnew file mode 100644index 0000000000..9e480a43ca--- /dev/null+++ b/crates/calendar_events/src/outbound/pg/test/team_sharing.rs@@ -0,0 +1,602 @@+use super::*;+use crate::domain::team::{CalendarTeamRepository, TeamCalendarCoverage, TeamCalendarSharing};+use crate::outbound::pg_team::PgCalendarTeamRepository;++#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]+async fn routine_sync_keeps_verified_coverage_without_admitting_failed_or_stale_snapshots(+ pool: PgPool,+) {+ let viewer = "macro|[email protected]";+ let owner = "macro|[email protected]";+ insert_team(&pool, viewer, &[viewer, owner]).await;+ let link = insert_link(&pool, owner).await;+ let repo = PgCalendarRepository::new(pool.clone());+ let (account, calendar) = provider_ids(&repo, link).await;+ repo.upsert_event_fixture(timed_upsert(+ owner,+ link,+ (account, calendar),+ "routine-sync",+ "Existing meeting",+ 1,+ ))+ .await+ .unwrap();+ sqlx::query!(+ "UPDATE calendars SET synced_at=now(),materialized_starts_at='2026-07-01',materialized_ends_at='2026-08-01',materialized_start_date='2026-07-01',materialized_end_date='2026-08-01' WHERE account_id=$1",+ account+ )+ .execute(&pool)+ .await+ .unwrap();+ sqlx::query!(+ "UPDATE calendars SET snapshot_normalization_version=1 WHERE account_id=$1",+ account+ )+ .execute(&pool)+ .await+ .unwrap();+ sqlx::query!(+ "UPDATE calendar_accounts SET sync_status='ready',last_synced_at=now() WHERE id=$1",+ account+ )+ .execute(&pool)+ .await+ .unwrap();+ let team = PgCalendarTeamRepository::new(pool.clone());+ let ready_revision = team.projection_revision(viewer).await.unwrap();++ for (case, status, stale, account_error, calendar_error, verified, expected) in [+ (+ "routine refresh",+ "syncing",+ false,+ None,+ None,+ 1,+ TeamCalendarCoverage::Ready,+ ),+ (+ "stale authorization",+ "syncing",+ true,+ None,+ None,+ 1,+ TeamCalendarCoverage::Unavailable,+ ),+ (+ "account failure",+ "syncing",+ false,+ Some("provider failure"),+ None,+ 1,+ TeamCalendarCoverage::Unavailable,+ ),+ (+ "calendar failure",+ "syncing",+ false,+ None,+ Some("calendar failure"),+ 1,+ TeamCalendarCoverage::Unavailable,+ ),+ (+ "unverified snapshot",+ "syncing",+ false,+ None,+ None,+ 0,+ TeamCalendarCoverage::Unavailable,+ ),+ (+ "failed account status",+ "error",+ false,+ None,+ None,+ 1,+ TeamCalendarCoverage::Unavailable,+ ),+ ] {+ sqlx::query!(+ "UPDATE calendar_accounts SET sync_status=$2,last_synced_at=CASE WHEN $3 THEN now()-interval '16 minutes' ELSE now() END,last_sync_error=$4 WHERE id=$1",+ account,+ status,+ stale,+ account_error,+ )+ .execute(&pool)+ .await+ .unwrap();+ sqlx::query!(+ "UPDATE calendars SET last_sync_error=$2,snapshot_normalization_version=$3 WHERE id=$1",+ calendar,+ calendar_error,+ verified,+ )+ .execute(&pool)+ .await+ .unwrap();+ assert_eq!(+ team.members(viewer, false, &july_2026_range())+ .await+ .unwrap()[0]+ .coverage,+ expected,+ "{case}"+ );+ let sources = team+ .sources(viewer, july_2026_range(), &[owner.to_owned()], None, 100)+ .await+ .unwrap();+ if expected == TeamCalendarCoverage::Ready {+ assert_eq!(sources.len(), 2, "{case}");+ assert_eq!(+ ready_revision,+ team.projection_revision(viewer).await.unwrap(),+ "entering a routine refresh must not invalidate an unchanged snapshot's cursor"+ );+ } else {+ assert!(sources.is_empty(), "{case}");+ }+ }++ // Exercise the real failure/retry lifecycle. A retained, recent certificate+ // must not reopen known-failed coverage merely because its retry starts.+ let grant = repo+ .apply_google_grant(+ link,+ complete_grant(),+ CalendarGrantIntent::CalendarRequested,+ )+ .await+ .unwrap();+ let job = grant+ .jobs+ .iter()+ .find(|job| job.kind == CalendarBackfillKind::GoogleCalendar)+ .unwrap();+ let key = CalendarBackfillJobKey {+ job_id: job.id,+ email_link_id: link,+ };+ let CalendarBackfillClaim::Claimed { lease_token, .. } =+ repo.claim_google_backfill(key).await.unwrap()+ else {+ panic!("the calendar job should be claimable");+ };+ repo.fail_google_backfill(+ key,+ lease_token,+ CalendarBackfillFailureDisposition::Retry,+ "provider normalization failed",+ )+ .await+ .unwrap();+ let CalendarBackfillClaim::Claimed { lease_token, .. } =+ repo.claim_google_backfill(key).await.unwrap()+ else {+ panic!("the failed calendar job should be retryable");+ };+ repo.mark_google_account_syncing(key, lease_token)+ .await+ .unwrap();+ let retry = sqlx::query!(+ "SELECT sync_status,last_sync_error,last_synced_at FROM calendar_accounts WHERE id=$1",+ account,+ )+ .fetch_one(&pool)+ .await+ .unwrap();+ assert_eq!(retry.sync_status, "syncing");+ assert_eq!(+ retry.last_sync_error.as_deref(),+ Some("provider normalization failed")+ );+ assert!(retry.last_synced_at.is_some());+ assert_eq!(+ team.members(viewer, false, &july_2026_range())+ .await+ .unwrap()[0]+ .coverage,+ TeamCalendarCoverage::Unavailable,+ "starting a retry does not clear the previously observed failure"+ );+ assert!(+ team.sources(viewer, july_2026_range(), &[owner.to_owned()], None, 100)+ .await+ .unwrap()+ .is_empty()+ );+ repo.commit_google_calendar_sync(+ key,+ lease_token,+ account,+ GoogleCalendarSyncSnapshot {+ calendar_id: calendar,+ next_sync_token: "recovered-token".to_owned(),+ observed_provider_event_ids: None,+ materialized_range: None,+ cancelled_provider_event_ids: vec![],+ },+ 0,+ )+ .await+ .unwrap();+ assert_eq!(+ team.members(viewer, false, &july_2026_range())+ .await+ .unwrap()[0]+ .coverage,+ TeamCalendarCoverage::Unavailable,+ "a recovered calendar alone does not establish whole-account success"+ );+ repo.complete_google_backfill(key, lease_token)+ .await+ .unwrap();+ assert_eq!(+ team.members(viewer, false, &july_2026_range())+ .await+ .unwrap()[0]+ .coverage,+ TeamCalendarCoverage::Ready+ );+ assert_eq!(+ team.sources(viewer, july_2026_range(), &[owner.to_owned()], None, 100)+ .await+ .unwrap()+ .len(),+ 2,+ "only successful account completion restores source eligibility"+ );+}++#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]+async fn team_sources_require_current_membership_and_verified_source_entitlement(pool: PgPool) {+ let viewer = "macro|[email protected]";+ let owner = "macro|[email protected]";+ let outsider = "macro|[email protected]";+ let team_id = insert_team(&pool, viewer, &[viewer, owner]).await;+ insert_user(&pool, outsider).await;+ let link = insert_link(&pool, owner).await;+ let repo = PgCalendarRepository::new(pool.clone());+ let (account, primary) = provider_ids(&repo, link).await;+ let secondary = repo+ .upsert_calendar_fixture(+ account,+ ProviderCalendar {+ provider_calendar_id: "subscribed".into(),+ name: "Coworker".into(),+ description: None,+ time_zone: Some("America/New_York".into()),+ color: None,+ access_role: Some("reader".into()),+ is_primary: false,+ is_selected: true,+ default_reminders: vec![],+ },+ )+ .await+ .unwrap();+ // The entity's primary content is deliberately richer than the secondary+ // copy. A source read must never attach that content to the reader source.+ let first = timed_upsert(+ owner,+ link,+ (account, primary),+ "same-meeting",+ "Primary secret",+ 1,+ );+ repo.upsert_event_fixture(first).await.unwrap();+ let mut other = timed_upsert(+ owner,+ link,+ (account, secondary),+ "same-meeting",+ "Reader-visible title",+ 2,+ );+ other.event.conference_url = Some("https://reader.example.com".into());+ let CalendarEventSource::Google(source) = &mut other.source;+ source.observed_access_role = Some("reader".to_owned());+ repo.upsert_event_fixture(other).await.unwrap();+ sqlx::query!(+ "UPDATE calendars SET synced_at=now(),materialized_starts_at='2026-07-01',materialized_ends_at='2026-08-01',materialized_start_date='2026-07-01',materialized_end_date='2026-08-01' WHERE account_id=$1",+ account+ )+ .execute(&pool)+ .await+ .unwrap();+ sqlx::query!(+ "UPDATE calendar_accounts SET sync_status='ready',last_synced_at=now() WHERE id=$1",+ account+ )+ .execute(&pool)+ .await+ .unwrap();+ sqlx::query!(+ "UPDATE calendars SET snapshot_normalization_version=1 WHERE account_id=$1",+ account+ )+ .execute(&pool)+ .await+ .unwrap();+ let team = PgCalendarTeamRepository::new(pool.clone());+ assert_eq!(+ team.sharing(owner).await.unwrap(),+ TeamCalendarSharing::BusyOnly+ );+ let owners = [owner.to_owned()];+ assert_eq!(+ team.members(viewer, false, &july_2026_range())+ .await+ .unwrap()[0]+ .coverage,+ TeamCalendarCoverage::Ready+ );+ let pending_link = insert_link(&pool, owner).await;+ let pending_account = repo.upsert_google_account(pending_link).await.unwrap();+ assert_eq!(+ team.members(viewer, false, &july_2026_range())+ .await+ .unwrap()[0]+ .coverage,+ TeamCalendarCoverage::Unavailable,+ "a newly connected account without discovered calendars prevents a complete availability claim"+ );+ sqlx::query!(+ "UPDATE calendar_accounts SET sync_status='disabled' WHERE id=$1",+ pending_account+ )+ .execute(&pool)+ .await+ .unwrap();+ let rows = team+ .sources(viewer, july_2026_range(), &owners, None, 100)+ .await+ .unwrap();+ assert_eq!(rows.len(), 4, "all synced source calendars are included");+ sqlx::query!(+ "UPDATE calendars SET snapshot_normalization_version=0 WHERE account_id=$1",+ account+ )+ .execute(&pool)+ .await+ .unwrap();+ assert!(+ team.sources(viewer, july_2026_range(), &owners, None, 100)+ .await+ .unwrap()+ .is_empty()+ );+ assert_eq!(+ team.members(viewer, false, &july_2026_range())+ .await+ .unwrap()[0]+ .coverage,+ TeamCalendarCoverage::Unavailable+ );+ sqlx::query!(+ "UPDATE calendars SET snapshot_normalization_version=1 WHERE account_id=$1",+ account+ )+ .execute(&pool)+ .await+ .unwrap();+ let subscribed = rows+ .iter()+ .find(|row| row.calendar_id == secondary)+ .unwrap();+ assert_eq!(subscribed.event.title, "Reader-visible title");+ assert_eq!(+ subscribed.event.conference_url.as_deref(),+ Some("https://reader.example.com")+ );+ assert!(!subscribed.contributes_to_availability);+ assert!(+ team.sources(outsider, july_2026_range(), &owners, None, 100)+ .await+ .unwrap()+ .is_empty()+ );+ // A detected entitlement change hides the old source snapshot immediately.+ let initial_revision = team.projection_revision(viewer).await.unwrap();+ sqlx::query!(+ "UPDATE calendars SET access_role='freeBusyReader' WHERE id=$1",+ secondary+ )+ .execute(&pool)+ .await+ .unwrap();+ assert_eq!(+ team.sources(viewer, july_2026_range(), &owners, None, 100)+ .await+ .unwrap()+ .len(),+ 2+ );+ assert_ne!(+ initial_revision,+ team.projection_revision(viewer).await.unwrap()+ );+ assert_eq!(+ team.members(viewer, false, &july_2026_range())+ .await+ .unwrap()[0]+ .coverage,+ TeamCalendarCoverage::Unavailable+ );+ team.set_sharing(owner, TeamCalendarSharing::None)+ .await+ .unwrap();+ assert!(+ team.sources(viewer, july_2026_range(), &owners, None, 100)+ .await+ .unwrap()+ .is_empty()+ );+ team.set_sharing(owner, TeamCalendarSharing::All)+ .await+ .unwrap();+ sqlx::query!("DELETE FROM team_user WHERE user_id=$1", owner)+ .execute(&pool)+ .await+ .unwrap();+ assert!(+ team.sources(viewer, july_2026_range(), &owners, None, 100)+ .await+ .unwrap()+ .is_empty(),+ "membership revocation removes every source immediately"+ );+ sqlx::query!(+ "INSERT INTO team_user(user_id,team_id,team_role) VALUES($1,$2,'member')",+ owner,+ team_id+ )+ .execute(&pool)+ .await+ .unwrap();+ sqlx::query!(+ "UPDATE calendar_accounts SET last_sync_error='provider failure' WHERE id=$1",+ account+ )+ .execute(&pool)+ .await+ .unwrap();+ assert!(+ team.sources(viewer, july_2026_range(), &owners, None, 100)+ .await+ .unwrap()+ .is_empty(),+ "known provider failures cannot keep resharing old snapshots"+ );+ sqlx::query!("UPDATE calendar_accounts SET last_sync_error=NULL,last_synced_at=now()-interval '16 minutes' WHERE id=$1", account).execute(&pool).await.unwrap();+ assert!(+ team.sources(viewer, july_2026_range(), &owners, None, 100)+ .await+ .unwrap()+ .is_empty(),+ "stale source authorization fails closed"+ );+ assert!(+ !team+ .set_availability_calendar(outsider, primary, true)+ .await+ .unwrap()+ );+ assert!(+ team.set_availability_calendar(owner, secondary, true)+ .await+ .unwrap()+ );+ assert!(+ team.availability_calendars(owner)+ .await+ .unwrap()+ .iter()+ .find(|calendar| calendar.calendar_id == secondary)+ .unwrap()+ .contributes_to_availability+ );+}++#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]+async fn team_sources_follow_direct_delegation_without_recursive_resharing(pool: PgPool) {+ let viewer = "macro|[email protected]";+ let sharer = "macro|[email protected]";+ let account_owner = "macro|[email protected]";+ insert_team(&pool, viewer, &[viewer, sharer]).await;+ insert_user(&pool, account_owner).await;+ let link = insert_link(&pool, account_owner).await;+ let repo = PgCalendarRepository::new(pool.clone());+ let (account, calendar) = provider_ids(&repo, link).await;+ repo.upsert_event_fixture(timed_upsert(+ account_owner,+ link,+ (account, calendar),+ "directly-delegated-meeting",+ "Visible through a direct account link",+ 1,+ ))+ .await+ .unwrap();+ sqlx::query!(+ "UPDATE calendar_accounts SET sync_status='ready',last_synced_at=now() WHERE id=$1",+ account+ )+ .execute(&pool)+ .await+ .unwrap();+ sqlx::query!("UPDATE calendars SET synced_at=now() WHERE id=$1", calendar)+ .execute(&pool)+ .await+ .unwrap();+ sqlx::query!(+ "UPDATE calendars SET snapshot_normalization_version=1 WHERE account_id=$1",+ account+ )+ .execute(&pool)+ .await+ .unwrap();+ let team = PgCalendarTeamRepository::new(pool.clone());+ let owners = [sharer.to_owned()];+ assert!(+ team.sources(viewer, july_2026_range(), &owners, None, 100)+ .await+ .unwrap()+ .is_empty(),+ "team membership alone does not create access to another user's sources"+ );+ sqlx::query!(+ "INSERT INTO macro_user_links(primary_macro_id,child_macro_id,link_id) VALUES($1,$2,$3)",+ sharer,+ account_owner,+ link+ )+ .execute(&pool)+ .await+ .unwrap();+ let revision = team.projection_revision(viewer).await.unwrap();+ let rows = team+ .sources(viewer, july_2026_range(), &owners, None, 100)+ .await+ .unwrap();+ assert_eq!(rows.len(), 2);+ assert!(rows.iter().all(|row| row.shared_by == sharer));+ assert!(rows.iter().all(|row| !row.contributes_to_availability));+ assert!(+ team.sources(+ viewer,+ july_2026_range(),+ &[account_owner.to_owned()],+ None,+ 100,+ )+ .await+ .unwrap()+ .is_empty(),+ "a directly linked source does not add its owner to the viewer's team"+ );+ sqlx::query!(+ "DELETE FROM macro_user_links WHERE primary_macro_id=$1 AND link_id=$2",+ sharer,+ link+ )+ .execute(&pool)+ .await+ .unwrap();+ assert_ne!(revision, team.projection_revision(viewer).await.unwrap());+ assert!(+ team.sources(viewer, july_2026_range(), &owners, None, 100)+ .await+ .unwrap()+ .is_empty(),+ "revoking the direct link removes every team projection from that link"+ );+}diff --git a/crates/calendar_events/src/outbound/pg/test/team_sync_coverage.rs b/crates/calendar_events/src/outbound/pg/test/team_sync_coverage.rsnew file mode 100644index 0000000000..b194305e60--- /dev/null+++ b/crates/calendar_events/src/outbound/pg/test/team_sync_coverage.rs@@ -0,0 +1,387 @@+use super::*;+use crate::domain::team::{CalendarTeamRepository, TeamCalendarCoverage};+use crate::outbound::pg_team::PgCalendarTeamRepository;++struct SyncFixture {+ repo: PgCalendarRepository,+ team: PgCalendarTeamRepository,+ owner: String,+ viewer: String,+ account: Uuid,+ calendar: Uuid,+ secondary: Uuid,+ key: CalendarBackfillJobKey,+ events: Vec<CalendarEventUpsert>,+}++fn provider_calendar(id: &str, zone: &str) -> ProviderCalendar {+ ProviderCalendar {+ provider_calendar_id: id.to_owned(),+ name: id.to_owned(),+ description: None,+ time_zone: Some(zone.to_owned()),+ color: None,+ access_role: Some("owner".to_owned()),+ is_primary: id == "primary",+ is_selected: true,+ default_reminders: Vec::new(),+ }+}++fn shift_event(event: &mut CalendarEventUpsert, hours: i64) {+ let shift = |time: &mut EventTime| {+ let EventTime::Timed {+ starts_at, ends_at, ..+ } = time+ else {+ panic!("timed fixture");+ };+ *starts_at += Duration::hours(hours);+ *ends_at += Duration::hours(hours);+ };+ shift(&mut event.event.time);+ for occurrence in &mut event.occurrences {+ shift(&mut occurrence.time);+ }+}++impl SyncFixture {+ async fn new(pool: PgPool, label: &str) -> Self {+ let owner = format!("macro|{label}[email protected]");+ let viewer = format!("macro|{label}[email protected]");+ insert_team(&pool, &viewer, &[&viewer, &owner]).await;+ let link = insert_link(&pool, &owner).await;+ let repo = PgCalendarRepository::new(pool.clone());+ let grant = repo+ .apply_google_grant(+ link,+ complete_grant(),+ CalendarGrantIntent::CalendarRequested,+ )+ .await+ .unwrap();+ let job = grant+ .jobs+ .into_iter()+ .find(|job| job.kind == CalendarBackfillKind::GoogleCalendar)+ .unwrap();+ let account = job.account_id.unwrap();+ let key = CalendarBackfillJobKey {+ job_id: job.id,+ email_link_id: link,+ };+ let CalendarBackfillClaim::Claimed { lease_token, .. } =+ repo.claim_google_backfill(key).await.unwrap()+ else {+ panic!("initial sync is claimable");+ };+ let calendar = repo+ .upsert_google_calendar(+ key,+ lease_token,+ account,+ provider_calendar("primary", "UTC"),+ )+ .await+ .unwrap()+ .id;+ let secondary = repo+ .upsert_google_calendar(+ key,+ lease_token,+ account,+ provider_calendar("secondary", "UTC"),+ )+ .await+ .unwrap()+ .id;+ let mut events = vec![];+ for (uid, hours) in [("a", -5), ("b", -4)] {+ let mut event = timed_upsert(&owner, link, (account, calendar), uid, uid, 1);+ event.occurrences.truncate(1);+ shift_event(&mut event, hours);+ repo.upsert_event(CalendarEventWrite::GoogleBackfill {+ key,+ lease_token,+ upsert: event.clone(),+ })+ .await+ .unwrap();+ events.push(event);+ }+ for id in [calendar, secondary] {+ repo.commit_google_calendar_sync(+ key,+ lease_token,+ account,+ GoogleCalendarSyncSnapshot {+ calendar_id: id,+ next_sync_token: "initial".to_owned(),+ materialized_range: Some(july_2026_range()),+ observed_provider_event_ids: Some(if id == calendar {+ vec!["provider-a".to_owned(), "provider-b".to_owned()]+ } else {+ vec![]+ }),+ cancelled_provider_event_ids: vec![],+ },+ 0,+ )+ .await+ .unwrap();+ }+ repo.complete_google_backfill(key, lease_token)+ .await+ .unwrap();+ Self {+ repo,+ team: PgCalendarTeamRepository::new(pool),+ owner,+ viewer,+ account,+ calendar,+ secondary,+ key,+ events,+ }+ }++ async fn begin_poll(&self) -> Uuid {+ assert!(+ self.repo+ .schedule_google_sync_for_link(self.key.email_link_id)+ .await+ .unwrap()+ );+ let CalendarBackfillClaim::Claimed { lease_token, .. } =+ self.repo.claim_google_backfill(self.key).await.unwrap()+ else {+ panic!("incremental sync is claimable");+ };+ self.repo+ .mark_google_account_syncing(self.key, lease_token)+ .await+ .unwrap();+ lease_token+ }++ async fn assert_coverage(&self, ready: bool, sources: usize) {+ assert_eq!(+ self.team+ .members(&self.viewer, false, &july_2026_range())+ .await+ .unwrap()[0]+ .coverage,+ if ready {+ TeamCalendarCoverage::Ready+ } else {+ TeamCalendarCoverage::Unavailable+ }+ );+ assert_eq!(+ self.team+ .sources(+ &self.viewer,+ july_2026_range(),+ std::slice::from_ref(&self.owner),+ None,+ 100+ )+ .await+ .unwrap()+ .len(),+ sources+ );+ }++ fn token_only(&self) -> GoogleCalendarSyncSnapshot {+ GoogleCalendarSyncSnapshot {+ calendar_id: self.calendar,+ next_sync_token: "next".to_owned(),+ materialized_range: None,+ observed_provider_event_ids: None,+ cancelled_provider_event_ids: vec![],+ }+ }+}++#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]+async fn team_coverage_quiet_poll_stays_ready_but_partial_event_swap_withdraws_it(pool: PgPool) {+ let fixture = SyncFixture::new(pool, "swap").await;+ fixture.assert_coverage(true, 2).await;+ let revision = fixture+ .team+ .projection_revision(&fixture.viewer)+ .await+ .unwrap();+ let lease = fixture.begin_poll().await;+ fixture+ .repo+ .upsert_google_calendar(+ fixture.key,+ lease,+ fixture.account,+ provider_calendar("primary", "UTC"),+ )+ .await+ .unwrap();+ for event in &fixture.events {+ fixture+ .repo+ .upsert_event(CalendarEventWrite::GoogleBackfill {+ key: fixture.key,+ lease_token: lease,+ upsert: event.clone(),+ })+ .await+ .unwrap();+ }+ // A stale response rejected by the source freshness predicate is also a no-op.+ let mut stale = fixture.events[0].clone();+ stale.event.sequence = 0;+ stale.event.updated_at -= Duration::minutes(1);+ stale.event.title = "stale".to_owned();+ fixture+ .repo+ .upsert_event(CalendarEventWrite::GoogleBackfill {+ key: fixture.key,+ lease_token: lease,+ upsert: stale,+ })+ .await+ .unwrap();+ fixture+ .repo+ .commit_google_calendar_sync(fixture.key, lease, fixture.account, fixture.token_only(), 0)+ .await+ .unwrap();+ fixture.assert_coverage(true, 2).await;+ assert_eq!(+ revision,+ fixture+ .team+ .projection_revision(&fixture.viewer)+ .await+ .unwrap()+ );+ fixture+ .repo+ .complete_google_backfill(fixture.key, lease)+ .await+ .unwrap();+ assert_eq!(+ revision,+ fixture+ .team+ .projection_revision(&fixture.viewer)+ .await+ .unwrap()+ );++ let lease = fixture.begin_poll().await;+ // Swapping A09/B10 to A10/B09 must never expose the intermediate free 09 slot.+ for (event, hours) in fixture.events.iter().zip([1, -1]) {+ let mut moved = event.clone();+ moved.event.sequence += 1;+ moved.event.updated_at += Duration::minutes(1);+ shift_event(&mut moved, hours);+ fixture+ .repo+ .upsert_event(CalendarEventWrite::GoogleBackfill {+ key: fixture.key,+ lease_token: lease,+ upsert: moved,+ })+ .await+ .unwrap();+ fixture.assert_coverage(false, 0).await;+ assert_ne!(+ revision,+ fixture+ .team+ .projection_revision(&fixture.viewer)+ .await+ .unwrap()+ );+ }+ fixture+ .repo+ .commit_google_calendar_sync(fixture.key, lease, fixture.account, fixture.token_only(), 2)+ .await+ .unwrap();+ fixture.assert_coverage(false, 0).await;+ fixture+ .repo+ .complete_google_backfill(fixture.key, lease)+ .await+ .unwrap();+ fixture.assert_coverage(true, 2).await;+}++#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]+async fn team_coverage_withdraws_on_source_removal_calendar_removal_and_timezone_change(+ pool: PgPool,+) {+ for case in ["cancel", "snapshot", "timezone", "calendar-list"] {+ let fixture = SyncFixture::new(pool.clone(), case).await;+ let lease = fixture.begin_poll().await;+ match case {+ "cancel" | "snapshot" => {+ let mut snapshot = fixture.token_only();+ if case == "cancel" {+ snapshot.cancelled_provider_event_ids = vec!["provider-a".to_owned()];+ } else {+ snapshot.observed_provider_event_ids = Some(vec!["provider-b".to_owned()]);+ snapshot.materialized_range = Some(july_2026_range());+ }+ fixture+ .repo+ .commit_google_calendar_sync(fixture.key, lease, fixture.account, snapshot, 0)+ .await+ .unwrap();+ }+ "timezone" => {+ fixture+ .repo+ .upsert_google_calendar(+ fixture.key,+ lease,+ fixture.account,+ provider_calendar("primary", "America/New_York"),+ )+ .await+ .unwrap();+ }+ "calendar-list" => {+ assert_ne!(fixture.calendar, fixture.secondary);+ fixture+ .repo+ .reconcile_google_calendar_list(+ fixture.key,+ lease,+ fixture.account,+ vec![fixture.calendar],+ )+ .await+ .unwrap();+ }+ _ => unreachable!(),+ }+ fixture.assert_coverage(false, 0).await;+ fixture+ .repo+ .complete_google_backfill(fixture.key, lease)+ .await+ .unwrap();+ fixture+ .assert_coverage(+ true,+ if matches!(case, "cancel" | "snapshot") {+ 1+ } else {+ 2+ },+ )+ .await;+ }+}diff --git a/crates/calendar_events/src/outbound/pg_team.rs b/crates/calendar_events/src/outbound/pg_team.rsnew file mode 100644index 0000000000..7abf256155--- /dev/null+++ b/crates/calendar_events/src/outbound/pg_team.rs@@ -0,0 +1,307 @@+//! PostgreSQL facts for source-scoped team reads.+//!+//! Only directly owned/delegated Google sources enter these queries. Neither+//! channel grants nor team-derived grants can recursively expand access.++use crate::domain::{+ models::{CalendarEvent, CalendarEventOverride, OccurrenceRange},+ team::*,+};+use rootcause::Report;+use serde::Deserialize;+use sqlx::PgPool;+use uuid::Uuid;++mod ooo;+pub(super) use ooo::list_team_out_of_office;++/// PostgreSQL implementation of the team-calendar repository.+pub struct PgCalendarTeamRepository {+ pool: PgPool,+}+impl PgCalendarTeamRepository {+ /// Construct the source repository from the primary database pool.+ pub fn new(pool: PgPool) -> Self {+ Self { pool }+ }+}++#[derive(Deserialize)]+#[serde(rename_all = "camelCase")]+struct SourceSnapshot {+ event: CalendarEvent,+ overrides: Vec<CalendarEventOverride>,+}++fn sharing(value: &str) -> Result<TeamCalendarSharing, Report> {+ match value {+ "all" => Ok(TeamCalendarSharing::All),+ "busy_only" => Ok(TeamCalendarSharing::BusyOnly),+ "none" => Ok(TeamCalendarSharing::None),+ _ => Err(rootcause::report!("invalid stored calendar sharing policy")),+ }+}++impl CalendarTeamRepository for PgCalendarTeamRepository {+ async fn projection_revision(&self, requester: &str) -> Result<String, Report> {+ sqlx::query_scalar!(r#"+ WITH members AS (+ SELECT teammate.user_id FROM team_user viewer JOIN team_user teammate ON teammate.team_id = viewer.team_id WHERE viewer.user_id = $1+ UNION SELECT $1::text+ )+ SELECT md5(COALESCE(string_agg(jsonb_build_array(members.user_id, policy.sharing, policy.updated_at,+ account.id, account.sync_status IN ('ready','syncing'), account.last_sync_error IS NULL,+ COALESCE(account.last_synced_at > now() - interval '15 minutes', false), calendar.id, calendar.access_role,+ calendar.synced_at IS NULL, calendar.snapshot_normalization_version, calendar.is_deleted, calendar.is_primary, calendar.name, calendar.time_zone,+ calendar.last_sync_error IS NULL, calendar.materialized_starts_at, calendar.materialized_ends_at,+ calendar.materialized_start_date, calendar.materialized_end_date,+ preference.contributes_to_availability, counter.seq)::text, '|' ORDER BY members.user_id, account.id, calendar.id), '')) AS "revision!"+ FROM members LEFT JOIN calendar_team_sharing policy ON policy.user_id = members.user_id+ LEFT JOIN calendar_accounts account ON (account.owner_id = members.user_id OR EXISTS (+ SELECT 1 FROM macro_user_links link WHERE link.link_id = account.email_link_id AND link.primary_macro_id = members.user_id+ ))+ LEFT JOIN calendars calendar ON calendar.account_id = account.id+ LEFT JOIN calendar_availability_preferences preference ON preference.calendar_id = calendar.id AND preference.user_id = members.user_id+ LEFT JOIN calendar_change_counters counter ON counter.link_id = account.email_link_id+ "#, requester).fetch_one(&self.pool).await.map_err(|error| rootcause::report!(error).into())+ }+ async fn members(+ &self,+ requester: &str,+ include_self: bool,+ range: &OccurrenceRange,+ ) -> Result<Vec<TeamCalendarMember>, Report> {+ let rows = sqlx::query!(r#"+ WITH members AS (+ SELECT teammate.user_id+ FROM team_user viewer JOIN team_user teammate ON teammate.team_id = viewer.team_id+ WHERE viewer.user_id = $1 AND teammate.user_id <> $1+ UNION SELECT $1::text WHERE $2+ ), visible_accounts AS MATERIALIZED (+ SELECT members.user_id, account.id AS account_id+ FROM members JOIN calendar_accounts account ON account.owner_id = members.user_id+ WHERE account.sync_status <> 'disabled'+ UNION+ SELECT members.user_id, account.id AS account_id+ FROM members+ JOIN macro_user_links link ON link.primary_macro_id = members.user_id+ JOIN calendar_accounts account ON account.email_link_id = link.link_id+ WHERE account.sync_status <> 'disabled'+ )+ SELECT members.user_id AS "user_id!",+ COALESCE(policy.sharing, 'busy_only') AS "sharing!",+ COALESCE(bool_and(+ account.sync_status IN ('ready', 'syncing') AND account.last_sync_error IS NULL+ AND COALESCE(account.last_synced_at > now() - interval '15 minutes', false)+ AND calendar.last_sync_error IS NULL+ AND COALESCE(calendar.materialized_starts_at <= $3 AND calendar.materialized_ends_at >= $4+ AND calendar.materialized_start_date <= $5 AND calendar.materialized_end_date >= $6, false)+ AND calendar.synced_at IS NOT NULL AND calendar.snapshot_normalization_version >= 1+ AND NOT EXISTS (+ SELECT 1 FROM calendar_event_sources pending_source+ WHERE pending_source.calendar_id = calendar.id+ AND (pending_source.provider_access_role IS NULL+ OR pending_source.provider_access_role IS DISTINCT FROM calendar.access_role)+ )+ ), false) AS "ready!"+ FROM members LEFT JOIN calendar_team_sharing policy ON policy.user_id = members.user_id+ LEFT JOIN visible_accounts visible ON visible.user_id = members.user_id+ LEFT JOIN calendar_accounts account ON account.id = visible.account_id+ LEFT JOIN calendars calendar ON calendar.account_id = account.id AND NOT calendar.is_deleted+ GROUP BY members.user_id, policy.sharing+ ORDER BY members.user_id+ "#, requester, include_self, range.starts_at, range.ends_at, range.start_date, range.end_date).fetch_all(&self.pool).await.map_err(|error| rootcause::report!(error))?;+ rows.into_iter()+ .map(|row| {+ let policy = if row.user_id == requester {+ TeamCalendarSharing::All+ } else {+ sharing(&row.sharing)?+ };+ Ok(TeamCalendarMember {+ user_id: row.user_id,+ sharing: policy,+ coverage: if policy == TeamCalendarSharing::None {+ TeamCalendarCoverage::Hidden+ } else if row.ready {+ TeamCalendarCoverage::Ready+ } else {+ TeamCalendarCoverage::Unavailable+ },+ })+ })+ .collect()+ }++ async fn sources(+ &self,+ requester: &str,+ range: OccurrenceRange,+ owners: &[String],+ cursor: Option<&TeamCalendarCursor>,+ limit: u32,+ ) -> Result<Vec<TeamSourceOccurrence>, Report> {+ // The normalized source payload holds this source's schedule, guests,+ // conference, and exceptions. Joining canonical entity fields here would+ // borrow richer content from a different calendar's entitlement.+ let rows = sqlx::query!(r#"+ WITH eligible AS (+ SELECT teammate.user_id FROM team_user viewer+ JOIN team_user teammate ON teammate.team_id = viewer.team_id+ LEFT JOIN calendar_team_sharing policy ON policy.user_id = teammate.user_id+ WHERE viewer.user_id = $1 AND COALESCE(policy.sharing, 'busy_only') <> 'none'+ UNION SELECT $1::text+ ), visible_accounts AS MATERIALIZED (+ SELECT eligible.user_id, account.id AS account_id+ FROM eligible JOIN calendar_accounts account ON account.owner_id = eligible.user_id+ WHERE eligible.user_id = ANY($2::text[])+ UNION+ SELECT eligible.user_id, account.id AS account_id+ FROM eligible+ JOIN macro_user_links link ON link.primary_macro_id = eligible.user_id+ JOIN calendar_accounts account ON account.email_link_id = link.link_id+ WHERE eligible.user_id = ANY($2::text[])+ ), authorized_sources AS MATERIALIZED (+ SELECT eligible.user_id AS shared_by, source.id AS source_id,+ calendar.id AS calendar_id, calendar.name AS calendar_name, calendar.time_zone,+ COALESCE(preference.contributes_to_availability,+ account.owner_id = eligible.user_id AND calendar.is_primary) AS contributes,+ source.normalized_payload+ FROM visible_accounts eligible+ JOIN calendar_accounts account ON account.id = eligible.account_id+ AND account.sync_status IN ('ready', 'syncing')+ AND account.last_sync_error IS NULL+ AND account.last_synced_at > now() - interval '15 minutes'+ JOIN calendars calendar ON calendar.account_id = account.id AND NOT calendar.is_deleted+ AND calendar.synced_at IS NOT NULL AND calendar.last_sync_error IS NULL+ AND calendar.snapshot_normalization_version >= 1+ JOIN calendar_event_sources source ON source.calendar_id = calendar.id AND source.account_id = account.id+ AND source.provider_access_role IS NOT NULL+ AND source.provider_access_role IS NOT DISTINCT FROM calendar.access_role+ LEFT JOIN calendar_availability_preferences preference ON preference.user_id = eligible.user_id AND preference.calendar_id = calendar.id+ WHERE ($7::text IS NULL OR (eligible.user_id, source.id) >= ($7,$8))+ )+ SELECT shared_by AS "shared_by!", source_id AS "source_id!",+ calendar_id AS "calendar_id!", calendar_name AS "calendar_name!", time_zone,+ contributes AS "contributes!",+ ARRAY(SELECT owned.email_address::text FROM email_links owned WHERE owned.macro_id = shared_by) AS "owner_emails!",+ (normalized_payload - 'occurrences') AS "snapshot!", occurrence.value AS "occurrence!"+ FROM authorized_sources+ CROSS JOIN LATERAL jsonb_array_elements(normalized_payload->'occurrences') occurrence(value)+ WHERE (normalized_payload->'event'->>'status') <> 'cancelled'+ AND NOT COALESCE((occurrence.value->>'isCancelled')::boolean, false)+ AND (+ ((occurrence.value->'time'->>'kind') = 'timed'+ AND (occurrence.value->'time'->>'startsAt')::timestamptz < $4+ AND (occurrence.value->'time'->>'endsAt')::timestamptz > $3)+ OR ((occurrence.value->'time'->>'kind') = 'allDay'+ AND (occurrence.value->'time'->>'startDate')::date < $6+ AND (occurrence.value->'time'->>'endDate')::date > $5)+ )+ AND ($7::text IS NULL OR (shared_by, source_id, occurrence.value->>'occurrenceKey') > ($7,$8,$9))+ ORDER BY shared_by, source_id, occurrence.value->>'occurrenceKey'+ LIMIT $10+ "#, requester, owners, range.starts_at, range.ends_at, range.start_date, range.end_date,+ cursor.map(|cursor| cursor.user_id.as_str()), cursor.map(|cursor| cursor.source_id), cursor.map(|cursor| cursor.occurrence_key.as_str()), i64::from(limit))+ .fetch_all(&self.pool).await.map_err(|error| rootcause::report!(error))?;+ rows.into_iter()+ .map(|row| {+ let snapshot: SourceSnapshot = serde_json::from_value(row.snapshot)+ .map_err(|error| rootcause::report!(error))?;+ Ok(TeamSourceOccurrence {+ shared_by: row.shared_by,+ source_id: row.source_id,+ calendar_id: row.calendar_id,+ calendar_name: row.calendar_name,+ calendar_time_zone: row.time_zone,+ contributes_to_availability: row.contributes,+ owner_emails: row.owner_emails,+ event: snapshot.event,+ overrides: snapshot.overrides,+ occurrence: serde_json::from_value(row.occurrence)+ .map_err(|error| rootcause::report!(error))?,+ })+ })+ .collect()+ }++ async fn owned_emails(&self, requester: &str) -> Result<Vec<String>, Report> {+ sqlx::query_scalar!(+ r#"SELECT email_address::text AS "email!" FROM email_links WHERE macro_id = $1"#,+ requester+ )+ .fetch_all(&self.pool)+ .await+ .map_err(|error| rootcause::report!(error).into())+ }++ async fn sharing(&self, requester: &str) -> Result<TeamCalendarSharing, Report> {+ let value = sqlx::query_scalar!(+ "SELECT sharing FROM calendar_team_sharing WHERE user_id = $1",+ requester+ )+ .fetch_optional(&self.pool)+ .await+ .map_err(|error| rootcause::report!(error))?;+ sharing(value.as_deref().unwrap_or("busy_only"))+ }++ async fn set_sharing(+ &self,+ requester: &str,+ policy: TeamCalendarSharing,+ ) -> Result<(), Report> {+ sqlx::query!(+ r#"INSERT INTO calendar_team_sharing(user_id,sharing) VALUES($1,$2)+ ON CONFLICT(user_id) DO UPDATE SET sharing=EXCLUDED.sharing, updated_at=now()"#,+ requester,+ policy.as_str()+ )+ .execute(&self.pool)+ .await+ .map_err(|error| rootcause::report!(error))?;+ Ok(())+ }++ async fn availability_calendars(+ &self,+ requester: &str,+ ) -> Result<Vec<AvailabilityCalendar>, Report> {+ let rows = sqlx::query!(r#"+ SELECT calendar.id, calendar.name, calendar.is_primary,+ COALESCE(preference.contributes_to_availability,+ account.owner_id = $1 AND calendar.is_primary) AS "contributes!"+ FROM calendars calendar JOIN calendar_accounts account ON account.id = calendar.account_id+ LEFT JOIN calendar_availability_preferences preference ON preference.calendar_id = calendar.id AND preference.user_id = $1+ WHERE NOT calendar.is_deleted AND account.sync_status <> 'disabled'+ AND (account.owner_id = $1 OR EXISTS (SELECT 1 FROM macro_user_links link WHERE link.link_id = account.email_link_id AND link.primary_macro_id = $1))+ ORDER BY calendar.name, calendar.id+ "#, requester).fetch_all(&self.pool).await.map_err(|error| rootcause::report!(error))?;+ Ok(rows+ .into_iter()+ .map(|row| AvailabilityCalendar {+ calendar_id: row.id,+ name: row.name,+ is_primary: row.is_primary,+ contributes_to_availability: row.contributes,+ })+ .collect())+ }++ async fn set_availability_calendar(+ &self,+ requester: &str,+ calendar: Uuid,+ contributes: bool,+ ) -> Result<bool, Report> {+ let result = sqlx::query!(r#"+ INSERT INTO calendar_availability_preferences(user_id,calendar_id,contributes_to_availability)+ SELECT $1, calendar.id, $3 FROM calendars calendar+ JOIN calendar_accounts account ON account.id = calendar.account_id+ WHERE calendar.id = $2 AND NOT calendar.is_deleted AND account.sync_status <> 'disabled'+ AND (account.owner_id = $1 OR EXISTS (SELECT 1 FROM macro_user_links link WHERE link.link_id = account.email_link_id AND link.primary_macro_id = $1))+ ON CONFLICT(user_id,calendar_id) DO UPDATE SET contributes_to_availability=EXCLUDED.contributes_to_availability+ "#, requester, calendar, contributes).execute(&self.pool).await.map_err(|error| rootcause::report!(error))?;+ Ok(result.rows_affected() == 1)+ }+}diff --git a/crates/calendar_events/src/outbound/pg_team/ooo.rs b/crates/calendar_events/src/outbound/pg_team/ooo.rsnew file mode 100644index 0000000000..fa74014b27--- /dev/null+++ b/crates/calendar_events/src/outbound/pg_team/ooo.rs@@ -0,0 +1,77 @@+//! Compatibility projection for explicit detail-sharers' public OOO sources.++use crate::domain::models::{EventVisibility, OccurrenceRange, TeamOutOfOffice};+use rootcause::Report;+use sqlx::PgPool;++pub(in crate::outbound) async fn list_team_out_of_office(+ pool: &PgPool,+ requester: &str,+ range: OccurrenceRange,+ limit: u16,+) -> Result<Vec<TeamOutOfOffice>, Report> {+ let rows = sqlx::query!(r#"+ SELECT owner_id AS "owner_id!", event_id AS "event_id!", ical_uid AS "ical_uid!",+ occurrence_key AS "occurrence_key!", title AS "title!", time AS "time!"+ FROM (+ SELECT DISTINCT ON (event.owner_id,event.ical_uid,occurrence.value->>'occurrenceKey')+ event.owner_id, event.id AS event_id, event.ical_uid,+ occurrence.value->>'occurrenceKey' AS occurrence_key,+ COALESCE(exception.value->>'title',source.normalized_payload->'event'->>'title') AS title,+ occurrence.value->'time' AS time+ FROM calendar_event_sources source+ JOIN calendar_events event ON event.id=source.event_id+ JOIN calendars calendar ON calendar.id=source.calendar_id AND calendar.is_primary+ AND NOT calendar.is_deleted AND calendar.synced_at IS NOT NULL AND calendar.last_sync_error IS NULL+ AND calendar.snapshot_normalization_version >= 1+ JOIN calendar_accounts account ON account.id=source.account_id+ AND account.owner_id=event.owner_id+ AND account.sync_status IN ('ready','syncing') AND account.last_sync_error IS NULL+ AND account.last_synced_at > now() - interval '15 minutes'+ JOIN calendar_team_sharing sharing ON sharing.user_id=event.owner_id AND sharing.sharing='all'+ CROSS JOIN LATERAL jsonb_array_elements(source.normalized_payload->'occurrences') occurrence(value)+ LEFT JOIN LATERAL (+ SELECT candidate.value FROM jsonb_array_elements(source.normalized_payload->'overrides') candidate(value)+ WHERE candidate.value->>'recurrenceId'=occurrence.value->>'recurrenceId'+ LIMIT 1+ ) exception ON true+ WHERE event.owner_id IN (+ SELECT teammate.user_id FROM team_user viewer JOIN team_user teammate ON teammate.team_id=viewer.team_id+ WHERE viewer.user_id=$1 AND teammate.user_id<>$1+ )+ AND source.provider_access_role = calendar.access_role+ AND source.normalized_payload->'event'->>'eventType'='out_of_office'+ AND source.normalized_payload->'event'->>'visibility' IN ('default','public')+ AND COALESCE(exception.value->>'visibility','default') IN ('default','public')+ AND source.normalized_payload->'event'->>'status'<>'cancelled'+ AND COALESCE(exception.value->>'status','confirmed')<>'cancelled'+ AND NOT COALESCE((occurrence.value->>'isCancelled')::boolean,false)+ AND (+ (occurrence.value->'time'->>'kind'='timed'+ AND (occurrence.value->'time'->>'startsAt')::timestamptz<$3+ AND (occurrence.value->'time'->>'endsAt')::timestamptz>$2)+ OR (occurrence.value->'time'->>'kind'='allDay'+ AND (occurrence.value->'time'->>'startDate')::date<$5+ AND (occurrence.value->'time'->>'endDate')::date>$4)+ )+ ORDER BY event.owner_id,event.ical_uid,occurrence.value->>'occurrenceKey',source.source_updated_at DESC,source.id DESC+ ) sources+ ORDER BY COALESCE((time->>'startsAt')::timestamptz,(time->>'startDate')::date::timestamp AT TIME ZONE 'UTC'),event_id,occurrence_key+ LIMIT $6+ "#, requester, range.starts_at, range.ends_at, range.start_date, range.end_date, i64::from(limit))+ .fetch_all(pool).await.map_err(|error| rootcause::report!(error))?;+ rows.into_iter()+ .map(|row| {+ Ok(TeamOutOfOffice {+ owner_id: row.owner_id,+ event_id: row.event_id,+ ical_uid: row.ical_uid,+ occurrence_key: row.occurrence_key,+ title: Some(row.title),+ visibility: EventVisibility::Default,+ time: serde_json::from_value(row.time)+ .map_err(|error| rootcause::report!(error))?,+ })+ })+ .collect()+}diff --git a/crates/macro_db_client/migrations/20261007182215_calendar_team_sharing.sql b/crates/macro_db_client/migrations/20261007182215_calendar_team_sharing.sqlnew file mode 100644index 0000000000..c438909c2e--- /dev/null+++ b/crates/macro_db_client/migrations/20261007182215_calendar_team_sharing.sql@@ -0,0 +1,17 @@+-- Sharing is a Macro read entitlement, independent of provider write access.+-- Missing rows deliberately mean busy_only, including existing users.+CREATE TABLE calendar_team_sharing (+ user_id text PRIMARY KEY REFERENCES "User"(id) ON DELETE CASCADE,+ sharing text NOT NULL DEFAULT 'busy_only'+ CHECK (sharing IN ('all', 'busy_only', 'none')),+ updated_at timestamptz NOT NULL DEFAULT now()+);++-- This controls personal availability, never which synced calendars are shared.+-- It is viewer-specific because a delegated calendar is not automatically personal.+CREATE TABLE calendar_availability_preferences (+ user_id text NOT NULL REFERENCES "User"(id) ON DELETE CASCADE,+ calendar_id uuid NOT NULL REFERENCES calendars(id) ON DELETE CASCADE,+ contributes_to_availability boolean NOT NULL,+ PRIMARY KEY (user_id, calendar_id)+);diff --git a/crates/macro_db_client/migrations/20261007182532_calendar_source_permission_snapshot.sql b/crates/macro_db_client/migrations/20261007182532_calendar_source_permission_snapshot.sqlnew file mode 100644index 0000000000..18528d5856--- /dev/null+++ b/crates/macro_db_client/migrations/20261007182532_calendar_source_permission_snapshot.sql@@ -0,0 +1,5 @@+-- A source's content is eligible for team sharing only after it has been+-- fetched under the calendar's current provider role. Existing snapshots stay+-- unverified until the new sync worker observes them; old binaries can keep+-- writing sources without granting team access to an unverified snapshot.+ALTER TABLE calendar_event_sources ADD COLUMN provider_access_role text;diff --git a/crates/macro_db_client/migrations/20261007202524_calendar_verify_complete_snapshots.sql b/crates/macro_db_client/migrations/20261007202524_calendar_verify_complete_snapshots.sqlnew file mode 100644index 0000000000..2298304260--- /dev/null+++ b/crates/macro_db_client/migrations/20261007202524_calendar_verify_complete_snapshots.sql@@ -0,0 +1,37 @@+-- Earlier normalizers could omit malformed masters or instances while marking+-- coverage complete, including calendars with no retained source rows. Require+-- a strict snapshot once for every existing calendar before team activation.+-- Preserve existing sync state here so old workers can continue incremental+-- polling. A strict worker clears that state when it observes version 0 during+-- calendar upsert, then certifies only a successful full snapshot.+ALTER TABLE calendars+ ADD COLUMN snapshot_normalization_version integer NOT NULL DEFAULT 0;++-- A worker that predates strict normalization cannot retain a newer worker's+-- certification while advancing its own snapshot. The strict worker restores+-- version 1 in a separate statement inside the same fenced transaction.+CREATE FUNCTION calendar_invalidate_snapshot_normalization()+RETURNS trigger+LANGUAGE plpgsql+AS $$+BEGIN+ NEW.snapshot_normalization_version := 0;+ RETURN NEW;+END;+$$;++CREATE TRIGGER calendar_invalidate_snapshot_normalization+BEFORE UPDATE OF sync_token, synced_at,+ materialized_starts_at, materialized_ends_at,+ materialized_start_date, materialized_end_date+ON calendars+FOR EACH ROW+WHEN (+ OLD.sync_token IS DISTINCT FROM NEW.sync_token+ OR OLD.synced_at IS DISTINCT FROM NEW.synced_at+ OR OLD.materialized_starts_at IS DISTINCT FROM NEW.materialized_starts_at+ OR OLD.materialized_ends_at IS DISTINCT FROM NEW.materialized_ends_at+ OR OLD.materialized_start_date IS DISTINCT FROM NEW.materialized_start_date+ OR OLD.materialized_end_date IS DISTINCT FROM NEW.materialized_end_date+)+EXECUTE FUNCTION calendar_invalidate_snapshot_normalization();diff --git a/docs/AGENT_GUIDE/surfaces.md b/docs/AGENT_GUIDE/surfaces.mdindex e22375e622..f1faa87d6a 100644--- a/docs/AGENT_GUIDE/surfaces.md+++ b/docs/AGENT_GUIDE/surfaces.md@@ -1381,6 +1381,52 @@ Reminder. Inline Calendar previews retain their host's chrome without addinganother sidebar; their left header island has a compact New menu because thebottom New action follows the foreground host view.+With `enable-calendar-team-sharing` enabled, **Settings → Calendar** also has+**Team sharing**: `Busy blocks` (the default), `Event details`, and `Nothing`.+These are Macro read permissions. They do not change Google Calendar ACLs,+invite teammates to meetings, or let teammates edit, RSVP, or manage reminders.+The sharing choice covers every currently authorized calendar synced to Macro.+Private/confidential events only expose generic time blocks; event details+come from one authorized source copy. Disconnecting an account or losing+source access removes its team projection.++**Calendars that count as busy** controls which calendars represent the user's+personal schedule. Primary calendars count by default; other calendars require+explicit inclusion. Meetings the user attends also contribute, except declined+meetings. Following a coworker's calendar does not automatically make that+coworker's events occupy the user's time. In team overlays, `Busy` means the+block contributes to that teammate's availability; `Shared calendar block`+means it belongs to a calendar the teammate can access and does not count+toward their busy time. Event details show the same distinction explicitly.++The sidebar's **Team calendars** section has a master `Show team calendars`+switch and per-teammate checkboxes; Settings exposes the same display controls.+Display toggles affect this viewer's grid only. Team chips are prefixed with+the sharer's name and open read-only details. Copy-event links, guest-email+actions, RSVP, editing, and deletion are unavailable on team projections.+A directly accessible copy retains its own actions; another person's projection+of the same meeting may appear separately, with its sharing provenance.+Distinct authorized source copies may also appear separately for the same+teammate and meeting: their detail masking and availability contribution can differ.+Team projections and availability use server-confirmed copies. An offline queued+edit appears in the editor's own calendar, but reaches teammates only after the+server commits the provider-backed change and their shared projection refreshes.+An unavailable team fetch displays a warning and removes stale shared details.+Sharing-change notifications clear open shared details before refetching;+focus/reconnect and a 30-second refresh provide a fallback. Shared details also+disappear when an offline refresh is paused; they are not persisted for offline+use. While the app is running, team responses and in-flight requests expire+after 60 seconds, so a hung refresh cannot retain old details. Replacing a login+session clears team data and open shared details before the new identity loads.+Legacy out-of-office rows are read-only status displays and do not claim+that every absence blocks availability.++The `GetTeamAvailability` AI tool checks the requester together with the selected+teammates. It reports confirmed free windows only when every participant has+complete availability coverage. Hidden, disconnected, stale, or incomplete+calendars are reported as unknown, never free. Busy blocks contain no event+titles or private event metadata.+The in-view desktop Calendar header uses one responsive top bar. The viewedmonth and year stay on the left in a heading that scales from 16px in narrowsplits to a maximum of 24px, with a compact `New` menu when the sidebar is closed.diff --git a/docs/calendar-team-sharing.md b/docs/calendar-team-sharing.mdnew file mode 100644index 0000000000..0ae3f302dc--- /dev/null+++ b/docs/calendar-team-sharing.md@@ -0,0 +1,307 @@+# Team calendar sharing++Team calendar sharing lets a current Macro teammate read a projection of events+another member can access through their connected calendars. Google remains the+authority for the connected account's upstream access. Macro owns the separate+decision to show that account's synced content to a Macro teammate.++This document describes the implementation contract and the rollout work needed+before enabling it in an environment. A checklist item below is a release+requirement, not a claim that the check has already passed.++## Permission boundaries++| Boundary | What it authorizes |+| --- | --- |+| Google OAuth scopes | Operations Macro may request as the connected Google account. |+| Google calendar ACL, event visibility, and Workspace policy | The representation Google returns to that connected account. |+| Current Macro team membership and the sharer's setting | A read-only Macro projection from an eligible synced source. |+| A viewer's independent Google access | Actions and content available through that viewer's own Google credentials. |++A Macro team share does not invite anyone, change a Google ACL, confer editing or+RSVP rights, or make an attachment or meeting accessible in its original service.+The teammate does not need a Google grant to view the Macro projection. If they+also have their own authorized copy, that independent access remains separate.++Google itself maintains organizer and attendee calendar copies. Those copies can+have different local properties and sharing contexts. A default-visibility event+can become visible through an attendee's shared calendar. Consequently, neither+organizer ownership nor the organizer calendar's ACL alone describes every+attendee copy's disclosure. See Google's [sharing model][google-sharing] and+[event propagation model][google-copies].++An event's `iCalUID` is useful for correlation, not authorization. Each team read+starts from one current eligible provider source and uses that source's normalized+event, occurrence, and exception snapshots. It must never fill missing details+from a richer canonical event or another user's copy. Team-derived access does+not become a new source for another team's access.++Projection identities distinguish each eligible source copy. Two copies of the+same meeting shared by the same member can appear separately because their+visible details and contribution to that member's availability can differ.++Google ACL `owner` means calendar manager access; it does not establish that the+connected account is the calendar's data owner. OAuth read permission also does+not itself describe consent to team redistribution. The release must accurately+disclose Macro's sharing behavior and review existing consent against the+[Google API Services User Data Policy][google-data-policy].++## Sharing and browsing++The user's sharing choice applies to their current Macro teammates:++| Setting | Teammates see |+| --- | --- |+| `busy_only` — default | Generic occupied intervals from synced calendars, without event titles, descriptions, guests, meeting links, or source calendar names. |+| `all` | Details from each eligible source for ordinary events. Private and confidential events remain generic busy intervals. |+| `none` | No access through this person's team calendar share. |++Browsing covers all eligible synced calendars, including subscriptions and+calendars directly visible through delegated accounts. It is not limited to+meetings the sharing member organizes or attends. A subscribed coworker's busy+event may therefore appear as shared source content without claiming that the+sharing member is personally busy; projections explicitly identify whether the+event contributes to personal availability.++This includes synced system calendars and calendars unchecked in Google's+calendar view. Unchecked (`selected = false`) is different from hidden from+CalendarList; ingestion does not request Google's hidden-list entries.+Directly delegated sources are shared under the delegate's own Macro setting,+not the source owner's setting. A source owner's `none` does not revoke a+delegate's independent access or sharing choice. Disclosures and consent review+must cover this behavior before activation.++Busy-only and private-event projections use a separate response shape, rather+than blanking fields on a full event object. Details are allowed only for+default/public visibility. An explicit private/confidential instance restricts+details, and an instance cannot unhide a private/confidential series. Google now+documents propagation of stricter recurring-instance visibility across a series;+preserving the instance field is defensive and does not assert that independent+private-instance behavior has been reproduced against Google.++Team projections are read-only. They are not ordinary owned event entities for+editing, deletion, RSVP, drag/reschedule, invitation, or copy-as-event-mention+actions. A team view does not expand calendar search or generic event-detail+authorization. Attendee `self` flags in detailed projections describe the viewer,+not the source calendar account.++The existing team out-of-office overlay also follows the server gate and requires+explicit `all` sharing. Gate-off deployment suppresses that overlay; busy-only+sharing does not disclose an out-of-office label. This is an intentional privacy+change to the older overlay, not a claim that the person has no time off.++Team projections and availability use server-confirmed source copies. An offline+edit can appear immediately in the editor's own calendar through the mutation+queue, but does not change what teammates see or their availability results until+the server commits the provider-backed change and the shared projection refreshes.+Queued local edits never enter the team projection cache.++## Personal availability++Browsing and availability answer different questions. The availability tool+computes a person's busy time from:++- Their directly connected primary calendars by default.+- Additional calendars they explicitly include in availability settings.+- Events on any eligible source where one of their owned email addresses is an+ attendee, even if that source calendar is otherwise excluded.++Secondary calendars require explicit inclusion because the current source model+does not prove Google data ownership. Merely subscribing to or managing a+coworker's calendar must not mark the subscriber busy. Delegated addresses do not+establish the user's personal attendance. Provider `self` flags alone are also+insufficient on subscribed calendars.++Cancelled, transparent, declined, birthday, and working-location entries do not+block time. Instance cancellation, attendee responses, and transparency override+the master where supplied. Accepted, tentative, and unanswered invitations can+block time. All-day intervals use each source calendar's IANA timezone, including+23/25-hour days and transitions that skip midnight; there is no UTC or requester+timezone fallback for a missing source timezone.++Copies are correlated by the sharing person, event UID, and original recurrence+identity. Equal intervals collapse. Disagreeing copies contribute their known+busy intervals conservatively and make free time unknown. Moving one occurrence+does not make it a different original recurrence instance.++`GetTeamAvailability` always includes the requester. With `userIds` omitted it+includes the current team; a supplied list narrows to those teammates plus the+requester, and an empty list checks only the requester. Unknown IDs never broaden+the selection. At most 100 selected teammates plus the requester are supported.+Larger selections return guidance to supply a smaller `userIds` list.+The requester's own setting of `none` does not prevent reading their direct+calendar sources for their own availability.++The domain computes merged busy intervals and coverage; the AI adapter forwards+one service call. Its result contains no event titles or meeting metadata.+`freeWindows` is omitted unless every requested person and the entire requested+range have complete coverage. Hidden sharing, absent calendars, incomplete or+stale sync, access changes awaiting resync, unknown IDs, invalid all-day zones,+conflicting copies, or truncation prevent a confident common-free result.+Known busy intervals can still be useful when coverage is unknown.+Those intervals come only from currently eligible sources: stale or revoked+copies are withheld entirely, including from browsing.++A malformed live event, recurring exception, or instance fails that calendar's+sync batch; it is never silently dropped while declaring the range complete.+The failed batch cannot advance its sync token or materialized coverage. A durable+calendar/account sync error withholds teammate access and free-time claims until+a successful retry represents the data. Genuine cancellation tombstones and+occurrences outside the requested range remain valid omissions.++Coverage requires recent successful account sync (currently within 15 minutes),+successful calendar state, materialization covering the requested range, and+source snapshots verified under the calendar's current access role. A calendar+must also carry the current strict-normalization version; a legacy worker's sync+completion is insufficient evidence of complete coverage. The all-day+source query pads local dates around the UTC range; final intervals are converted+using their own source zones and clipped to the exact requested instants.++A quiet poll may continue serving its recent verified snapshot while the account+is syncing. The first actual source or calendar change withdraws account+freshness in the same transaction; teammate reads remain unavailable until the+account finishes successfully. This prevents partially applied event moves from+creating false free time. Starting a retry does not clear a known sync failure.++Queries are bounded to the existing materialized horizon: one year past to two+years future, at most 370 days per request. Availability loads at most 20,000+source occurrences and reports at most 100 merged busy intervals per person.+Exceeding a bound never silently turns missing events into free time. Common+free windows cover the specified range only; working hours, travel, desired+meeting duration, and booking guarantees are outside this tool's contract.++## Provider changes and revocation++Current membership and sharing policy are checked on each server read. A+projection revision invalidates continuation cursors when relevant source or+entitlement facts change, and the service checks the revision again after reading+the page. Client caches must be discarded on the team-sharing refresh event,+account changes, and logout. A server denial must not leave previously cached+team details visible.++Provider access is asynchronous. Each calendar refresh reads the full CalendarList;+the implementation does not depend on incremental CalendarList to detect role+changes. Google documents that incremental CalendarList omits changes confined+to read-only fields such as ACLs. A detected access-role change clears the+calendar's sync/materialization state. Each source also records the access role+under which its snapshot was verified; mismatched or unverified snapshots are+ineligible until refreshed. Availability remains unknown while reconciliation+is incomplete.++Provider requests carry the calendar role observed for their exact account and+calendar before the request starts, including user edits. Persisting a delayed+response never labels it with a newer role merely because that role is now in the+database. If the role changed while an edit was in flight, its old-role snapshot+is withheld from teammates until reconciliation. Ordinary edits under the same+role remain eligible and preserve incremental sync. An identical response can+verify a snapshot only when its captured role still matches the current role.++Google may invalidate sync tokens after ACL changes; a `410` requires source+reconciliation. A full resync must remove absent copies and replace redacted+content rather than retaining old detail fields. Confirmed disconnection or loss+of a source removes that source's entitlement. A separately authorized remaining+copy may still be visible. See [Google sync semantics][google-sync].++Push notifications are hints: Google says they can be dropped, contain no event+payload, and require channel renewal. Keep the existing scheduler/polling recovery+active, and measure provider-revocation detection latency during rollout. A+provider ACL change is not an instantaneous Macro notification; the service must+not promise immediate revocation before it has observed the provider change.+See [Google push notifications][google-push].++The synced set is bounded too. CalendarList is a user's subscribed list, not an+enumeration of every theoretically accessible calendar. The current ingestion+selects calendars with event-reading access; free/busy-only Google calendars are+not a promise of complete event coverage in this release. Google may restrict or+omit guests and event fields; another source must never be used to reconstruct+those hidden fields.++## Rollout++The server gate is `CALENDAR_TEAM_SHARING_ENABLED`, default `false`. It must be+configured consistently for document storage, calendar service, and every AI/MCP+host exposing the availability tool. The web gate is+`enable-calendar-team-sharing` (local override+`VITE_ENABLE_CALENDAR_TEAM_SHARING`). A client gate is not an authorization+boundary. Keep the existing calendar sync gate enabled for accounts participating+in the rollout.++1. Apply the migrations, regenerate SQLx metadata, and deploy the server+ code with the team-sharing gate disabled. The migration marks existing+ calendars unverified while preserving their sync tokens and materialized+ coverage, so old workers can continue incremental polling. A new strict worker+ clears that state when it first observes an unverified calendar, including+ empty calendars that may contain previously skipped provider data, and requires+ a full resync. The normalization version and database+ invalidation trigger prevent legacy worker writes from certifying strict+ coverage. Drain all old calendar workers before activation and confirm the+ new workers have reconciled the calendars participating in release checks.+ Keep sharing disabled throughout the mixed-version deployment.+ Refresh existing source snapshots+ before expecting complete availability; do not backfill verification roles+ merely from a calendar's current role. The next normal calendar-list sync+ forces a full refresh for retained sources whose verification role is missing+ or mismatched, including pre-migration snapshots. Let scheduler/watch recovery+ drive this verification while the gate is off; monitor Google quotas and+ catch-up progress before activation.+2. Verify disclosures and the busy-only default in the sharing settings. Confirm+ that switching to details clearly covers subscribed/shared calendars too, and+ that availability inclusion is a separate setting.+3. Validate real Google accounts and separate browser sessions in an isolated+ internal/dev environment. The server gate enables sharing across its entire+ environment; a small web cohort does not restrict backend exposure or the AI+ tool. Activate the production server gate deliberately for the whole environment+ only after the release checks pass. A production rollout limited to selected+ teams requires an additional server-side team allowlist before that mode is+ used; it is not part of this change.+ The same restriction applies to a team pilot in a shared dev environment.+ Gate-off deployment, migration checks, and sync reconciliation may proceed+ first; opening the global gate is not a substitute for isolated fixtures.+4. Verify source freshness, resync failures, unavailable coverage, invalidated+ cursors, and unauthorized/disabled responses before expanding the cohort.+5. Expand only after the checks below pass with the deployed provider integration.++Release checks:++- [ ] Busy-only serializes no event metadata; private/confidential stays masked+ under details sharing, including recurrence snapshots.+- [ ] A teammate without a Google connection can browse the permitted Macro view.+ They cannot edit, RSVP, invite, or use ordinary event-detail routes through it.+- [ ] A subscribed coworker's events are browsable but do not block the subscriber+ unless the subscriber attends or explicitly includes that calendar.+- [ ] Requester inclusion, unknown IDs, `none`, unavailable accounts, truncation,+ per-source all-day timezones, DST, declined instances, and moved instances are+ covered by domain tests and the tool renderer shows uncertainty.+- [ ] Sharing downgrade, team departure/removal, source disconnect, calendar+ removal, Google role downgrade, and a missed webhook remove stale access and+ cached details; a remaining independent entitlement is preserved.+- [ ] Real Google fixtures confirm role-downgrade/redaction and recurrence payload+ behavior. Synthetic normalization tests alone do not establish provider behavior.+- [ ] Real Google fixtures establish point-event and `endTimeUnspecified` payload+ behavior. Existing storage rejects equal start/end times; unsupported payloads+ must leave coverage unknown, never imply free time. Supporting point events+ requires coordinated storage, query, and normalization changes.+- [ ] Relevant Rust tests, SQLx preparation, generated API/tool/SDK artifacts,+ TypeScript checking, `just check`, and browser verification pass.++Rollback: disable the server gate in all read/AI hosts first, then disable the web+flag and discard client team-query caches. Leave sharing preferences and additive+schema in place. Calendar sync and users' own Google access continue independently;+rollback must not revoke OAuth, mutate Google ACLs, or delete connected calendars.+After fixing the issue, reconcile source snapshots and repeat the internal-team+checks before enabling reads again.++## Implementation references++- [Team policy and source models](../crates/calendar_events/src/domain/team.rs)+- [Source repository](../crates/calendar_events/src/outbound/pg_team.rs)+- [Availability calculation](../crates/calendar_events/src/domain/team_availability.rs)+- [AI adapter](../crates/calendar_events/src/inbound/team_toolset.rs)+- [HTTP adapter](../crates/calendar_events/src/inbound/team_router.rs)+- [Database workflow](DATABASE_DEVELOPMENT.md)++[google-sharing]: https://developers.google.com/workspace/calendar/api/concepts/sharing+[google-copies]: https://developers.google.com/workspace/calendar/api/concepts/inviting-attendees-to-events+[google-data-policy]: https://developers.google.com/terms/api-services-user-data-policy+[google-sync]: https://developers.google.com/workspace/calendar/api/guides/sync+[google-push]: https://developers.google.com/workspace/calendar/api/guides/pushdiff --git a/packages/sdk/generated/calendar/index.ts b/packages/sdk/generated/calendar/index.tsindex 99fc9c7e6c..c6260944dd 100644--- a/packages/sdk/generated/calendar/index.ts+++ b/packages/sdk/generated/calendar/index.ts@@ -1,4 +1,4 @@// This file is auto-generated by @hey-api/openapi-tsexport { type Options, Sdk } from './sdk.gen';-export type { AttendeeResponseStatus, CalendarAttendee, CalendarAttendeeInputBody, CalendarDeletionScopeParam, CalendarEvent, CalendarEventSourceContent, CalendarMutationApiError, CalendarMutationErrorCode, CalendarRsvpScopeParam, CalendarUpdateScopeParam, ClientOptions, ConferenceChange, ConferenceProvider, CreateCalendarEventData, CreateCalendarEventError, CreateCalendarEventErrors, CreateCalendarEventRequest, CreateCalendarEventResponse, CreateCalendarEventResponses, DeleteCalendarEventData, DeleteCalendarEventError, DeleteCalendarEventErrors, DeleteCalendarEventResponse, DeleteCalendarEventResponses, EventReminderOverride, EventReminders, EventStatus, EventTime, EventTransparency, EventType, EventVisibility, HealthHandlerData, HealthHandlerResponse, HealthHandlerResponses, ListCalendarsData, ListCalendarsError, ListCalendarsErrors, ListCalendarsResponse, ListCalendarsResponse2, ListCalendarsResponses, OutOfOfficeAutoDeclineMode, OutOfOfficeProperties, RefreshCalendarEvent, RsvpCalendarEventData, RsvpCalendarEventError, RsvpCalendarEventErrors, RsvpCalendarEventRequest, RsvpCalendarEventResponse, RsvpCalendarEventResponses, UpdateCalendarEventData, UpdateCalendarEventError, UpdateCalendarEventErrors, UpdateCalendarEventRequest, UpdateCalendarEventResponse, UpdateCalendarEventResponses, VisibleCalendar } from './types.gen';+export type { AttendeeResponseStatus, AvailabilityCalendar, AvailabilityCalendarBody, AvailabilityCalendarsResponse, CalendarAttendee, CalendarAttendeeInputBody, CalendarDeletionScopeParam, CalendarEvent, CalendarEventSourceContent, CalendarMutationApiError, CalendarMutationErrorCode, CalendarRsvpScopeParam, CalendarUpdateScopeParam, ClientOptions, ConferenceChange, ConferenceProvider, CreateCalendarEventData, CreateCalendarEventError, CreateCalendarEventErrors, CreateCalendarEventRequest, CreateCalendarEventResponse, CreateCalendarEventResponses, DeleteCalendarEventData, DeleteCalendarEventError, DeleteCalendarEventErrors, DeleteCalendarEventResponse, DeleteCalendarEventResponses, EventReminderOverride, EventReminders, EventStatus, EventTime, EventTransparency, EventType, EventVisibility, GetAvailabilityCalendarsData, GetAvailabilityCalendarsResponse, GetAvailabilityCalendarsResponses, GetTeamSharingData, GetTeamSharingResponse, GetTeamSharingResponses, HealthHandlerData, HealthHandlerResponse, HealthHandlerResponses, ListCalendarsData, ListCalendarsError, ListCalendarsErrors, ListCalendarsResponse, ListCalendarsResponse2, ListCalendarsResponses, OutOfOfficeAutoDeclineMode, OutOfOfficeProperties, RefreshCalendarEvent, RsvpCalendarEventData, RsvpCalendarEventError, RsvpCalendarEventErrors, RsvpCalendarEventRequest, RsvpCalendarEventResponse, RsvpCalendarEventResponses, SetAvailabilityCalendarData, SetAvailabilityCalendarResponse, SetAvailabilityCalendarResponses, SetTeamSharingData, SetTeamSharingResponse, SetTeamSharingResponses, TeamCalendarSharing, TeamCalendarSharingBody, UpdateCalendarEventData, UpdateCalendarEventError, UpdateCalendarEventErrors, UpdateCalendarEventRequest, UpdateCalendarEventResponse, UpdateCalendarEventResponses, VisibleCalendar } from './types.gen';diff --git a/packages/sdk/generated/calendar/sdk.gen.ts b/packages/sdk/generated/calendar/sdk.gen.tsindex 2f2ea091dd..232de1d32e 100644--- a/packages/sdk/generated/calendar/sdk.gen.ts+++ b/packages/sdk/generated/calendar/sdk.gen.ts@@ -2,7 +2,7 @@import type { Client, ClientMeta, Options as Options2, RequestResult, TDataShape } from './client';import { client } from './client.gen';-import type { CreateCalendarEventData, CreateCalendarEventErrors, CreateCalendarEventResponses, DeleteCalendarEventData, DeleteCalendarEventErrors, DeleteCalendarEventResponses, HealthHandlerData, HealthHandlerResponses, ListCalendarsData, ListCalendarsErrors, ListCalendarsResponses, RsvpCalendarEventData, RsvpCalendarEventErrors, RsvpCalendarEventResponses, UpdateCalendarEventData, UpdateCalendarEventErrors, UpdateCalendarEventResponses } from './types.gen';+import type { CreateCalendarEventData, CreateCalendarEventErrors, CreateCalendarEventResponses, DeleteCalendarEventData, DeleteCalendarEventErrors, DeleteCalendarEventResponses, GetAvailabilityCalendarsData, GetAvailabilityCalendarsResponses, GetTeamSharingData, GetTeamSharingResponses, HealthHandlerData, HealthHandlerResponses, ListCalendarsData, ListCalendarsErrors, ListCalendarsResponses, RsvpCalendarEventData, RsvpCalendarEventErrors, RsvpCalendarEventResponses, SetAvailabilityCalendarData, SetAvailabilityCalendarResponses, SetTeamSharingData, SetTeamSharingResponses, UpdateCalendarEventData, UpdateCalendarEventErrors, UpdateCalendarEventResponses } from './types.gen';export type Options<TData extends TDataShape = TDataShape, ThrowOnError extends boolean = boolean, TResponse = unknown> = Options2<TData, ThrowOnError, TResponse> & {/**@@ -57,6 +57,27 @@ export class Sdk extends HeyApiClient {Sdk.__registry.set(this, args?.key);}+ /**+ * List calendars and their personal-availability inclusion.+ */+ public getAvailabilityCalendars<ThrowOnError extends boolean = false>(options?: Options<GetAvailabilityCalendarsData, ThrowOnError>): RequestResult<GetAvailabilityCalendarsResponses, unknown, ThrowOnError> {+ return (options?.client ?? this.client).get<GetAvailabilityCalendarsResponses, unknown, ThrowOnError>({ url: '/availability-calendars', ...options });+ }++ /**+ * Change which source calendars normally occupy this user's time.+ */+ public setAvailabilityCalendar<ThrowOnError extends boolean = false>(options: Options<SetAvailabilityCalendarData, ThrowOnError>): RequestResult<SetAvailabilityCalendarResponses, unknown, ThrowOnError> {+ return (options.client ?? this.client).put<SetAvailabilityCalendarResponses, unknown, ThrowOnError>({+ url: '/availability-calendars/{calendar_id}',+ ...options,+ headers: {+ 'Content-Type': 'application/json',+ ...options.headers+ }+ });+ }+/*** List the requester's visible calendars for pickers and filters.*/@@ -119,4 +140,25 @@ export class Sdk extends HeyApiClient {public healthHandler<ThrowOnError extends boolean = false>(options?: Options<HealthHandlerData, ThrowOnError>): RequestResult<HealthHandlerResponses, unknown, ThrowOnError> {return (options?.client ?? this.client).get<HealthHandlerResponses, unknown, ThrowOnError>({ url: '/health', ...options });}++ /**+ * Read the authenticated user's sharing choice.+ */+ public getTeamSharing<ThrowOnError extends boolean = false>(options?: Options<GetTeamSharingData, ThrowOnError>): RequestResult<GetTeamSharingResponses, unknown, ThrowOnError> {+ return (options?.client ?? this.client).get<GetTeamSharingResponses, unknown, ThrowOnError>({ url: '/team-sharing', ...options });+ }++ /**+ * Set the authenticated user's sharing choice.+ */+ public setTeamSharing<ThrowOnError extends boolean = false>(options: Options<SetTeamSharingData, ThrowOnError>): RequestResult<SetTeamSharingResponses, unknown, ThrowOnError> {+ return (options.client ?? this.client).put<SetTeamSharingResponses, unknown, ThrowOnError>({+ url: '/team-sharing',+ ...options,+ headers: {+ 'Content-Type': 'application/json',+ ...options.headers+ }+ });+ }}diff --git a/packages/sdk/generated/calendar/types.gen.ts b/packages/sdk/generated/calendar/types.gen.tsindex c54118573f..388c08b221 100644--- a/packages/sdk/generated/calendar/types.gen.ts+++ b/packages/sdk/generated/calendar/types.gen.ts@@ -9,6 +9,48 @@ export type ClientOptions = {*/export type AttendeeResponseStatus = 'needs_action' | 'accepted' | 'declined' | 'tentative';+/**+ * Per-user inclusion of a source calendar in personal availability.+ */+export type AvailabilityCalendar = {+ /**+ * Visible source calendar.+ */+ calendarId: string;+ /**+ * Whether its events normally block the user's time.+ */+ contributesToAvailability: boolean;+ /**+ * Whether this is the connected account's primary calendar.+ */+ isPrimary: boolean;+ /**+ * Source name.+ */+ name: string;+};++/**+ * Own-user source inclusion preference.+ */+export type AvailabilityCalendarBody = {+ /**+ * Whether this calendar contributes to personal availability.+ */+ contributesToAvailability: boolean;+};++/**+ * Source calendar settings returned to their viewer.+ */+export type AvailabilityCalendarsResponse = {+ /**+ * Directly visible source calendars.+ */+ calendars: Array<AvailabilityCalendar>;+};+/*** An attendee on a calendar event.*/@@ -469,7 +511,7 @@ export type OutOfOfficeProperties = {};/**- * A sync run committed changes for `link_id`; viewers should refetch.+ * Realtime signal that a connected inbox's calendar projection changed.*/export type RefreshCalendarEvent = {event: 'synced';@@ -477,6 +519,8 @@ export type RefreshCalendarEvent = {* Connected inbox whose calendars changed.*/link_id: string;+} | {+ event: 'team_sharing_changed';};/**@@ -503,6 +547,21 @@ export type RsvpCalendarEventRequest = {scope?: null | CalendarRsvpScopeParam;};+/**+ * What a user exposes through their team membership.+ */+export type TeamCalendarSharing = 'all' | 'busy_only' | 'none';++/**+ * Own-user sharing preference.+ */+export type TeamCalendarSharingBody = {+ /**+ * Busy-only is the default, including when no setting has been saved.+ */+ sharing: TeamCalendarSharing;+};+/*** Request body patching an event; omitted fields are left untouched.*/@@ -594,6 +653,34 @@ export type VisibleCalendar = {syncError?: string | null;};+export type GetAvailabilityCalendarsData = {+ body?: never;+ path?: never;+ query?: never;+ url: '/availability-calendars';+};++export type GetAvailabilityCalendarsResponses = {+ 200: AvailabilityCalendarsResponse;+};++export type GetAvailabilityCalendarsResponse = GetAvailabilityCalendarsResponses[keyof GetAvailabilityCalendarsResponses];++export type SetAvailabilityCalendarData = {+ body: AvailabilityCalendarBody;+ path: {+ calendar_id: string;+ };+ query?: never;+ url: '/availability-calendars/{calendar_id}';+};++export type SetAvailabilityCalendarResponses = {+ 204: void;+};++export type SetAvailabilityCalendarResponse = SetAvailabilityCalendarResponses[keyof SetAvailabilityCalendarResponses];+export type ListCalendarsData = {body?: never;path?: never;@@ -835,3 +922,29 @@ export type HealthHandlerResponses = {};export type HealthHandlerResponse = HealthHandlerResponses[keyof HealthHandlerResponses];++export type GetTeamSharingData = {+ body?: never;+ path?: never;+ query?: never;+ url: '/team-sharing';+};++export type GetTeamSharingResponses = {+ 200: TeamCalendarSharingBody;+};++export type GetTeamSharingResponse = GetTeamSharingResponses[keyof GetTeamSharingResponses];++export type SetTeamSharingData = {+ body: TeamCalendarSharingBody;+ path?: never;+ query?: never;+ url: '/team-sharing';+};++export type SetTeamSharingResponses = {+ 200: TeamCalendarSharingBody;+};++export type SetTeamSharingResponse = SetTeamSharingResponses[keyof SetTeamSharingResponses];diff --git a/packages/sdk/generated/storage/index.ts b/packages/sdk/generated/storage/index.tsindex 507db64e28..a5417c5fb5 100644--- a/packages/sdk/generated/storage/index.ts+++ b/packages/sdk/generated/storage/index.ts@@ -1,4 +1,4 @@// This file is auto-generated by @hey-api/openapi-tsexport { type Options, Sdk } from './sdk.gen';-export type { AccessiblePipeline, AccessLevel, ActiveCallsResponse, ActiveCallSummary, ActiveMeeting, ActiveMeetingsResponse, ActivityType, AddFavoriteData, AddFavoriteError, AddFavoriteErrors, AddFavoriteRequest, AddFavoriteResponse, AddFavoriteResponses, AddParticipantsData, AddParticipantsError, AddParticipantsErrors, AddParticipantsRequest, AddParticipantsResponses, AddPinHandlerData, AddPinHandlerError, AddPinHandlerErrors, AddPinHandlerResponse, AddPinHandlerResponses, AddPinRequest, Agent, AgentActionId, AgentChannelScope, AgentMcpServer, AgentMcpServers, AgentPullRequestState, AgentSessionFilters, AgentSessionLifecycleEvent, Anchor, AnchorId, AnchorResponse, AnnotationIncrementalUpdate, Answer, ApiActivity, ApiAttachmentChannelReference, ApiAttachmentEntityReference, ApiAttachmentGenericReference, ApiChannelAttachment, ApiChannelAttachmentsPage, ApiChannelDetail, ApiChannelListMessage, ApiChannelListPage, ApiChannelListParticipant, ApiChannelListType, ApiChannelParticipant, ApiChannelWithLatest, ApiEntityFilterAst, ApiGroupByField, ApiGroupMeta, ApiParticipantListRole, ApiParticipantRole, ApiPropertyEntityType, AppliedOps, ApplyCrmPipelineOpsData, ApplyCrmPipelineOpsResponse, ApplyCrmPipelineOpsResponses, ApplyDatabaseOpsData, ApplyDatabaseOpsError, ApplyDatabaseOpsErrors, ApplyDatabaseOpsResponse, ApplyDatabaseOpsResponses, ApplyOpsRequest, ApplyOpsResponse, ApproveHarnessPairingData, ApproveHarnessPairingError, ApproveHarnessPairingErrors, ApproveHarnessPairingResponse, ApproveHarnessPairingResponses, ApprovePairingRequest, AttachmentChange, AttendeeResponseStatus, Audience, Awareness, AwarenessRelay, BasicDocument, BasicDocumentSubType, BomPart, BookingTarget, Bot, BotChannel, BotChannelType, BotId, BotKind, BotOwner, BotOwnerProfile, BotSenderProfile, BotToken, BranchNameResponse, BTreeMap, BulkWakeupRequest, BulkWakeupResponse, BulkWakeupSyncServiceDocumentsData, BulkWakeupSyncServiceDocumentsErrors, BulkWakeupSyncServiceDocumentsResponse, BulkWakeupSyncServiceDocumentsResponses, CalendarAttendee, CalendarEvent, CalendarEventFilters, CalendarEventSourceContent, CalendarMentionEvent, CalendarMentionPreviewItem, CalendarMentionPreviewKind, CalendarMentionPreviewRequest, CalendarMentionPreviewRequestItem, CalendarMentionPreviewResponse, CalendarOccurrence, CalendarOccurrenceItem, CalendarOccurrenceResponse, CalendarSyncStatus, CallActiveResponse, CallFilters, CallRecord, CallRecordGuest, CallRecordParticipant, CallRecordPreview, CallRecordPreviewData, CallRecordTranscriptSegment, CallStatus, CallTokenResponse, CallWebhookData, CallWebhookError, CallWebhookErrors, CallWebhookResponses, CancelSlackImportData, CancelSlackImportErrors, CancelSlackImportResponse, CancelSlackImportResponses, CardPosition, CastVerdict, CellValue, CellWrite, ChangedFileDto, ChangesetDto, ChangesetSourceDto, Channel, ChannelCreatedMetadata, ChannelDeletedMetadata, ChannelFilters, ChannelJoinCodeResponse, ChannelLabel, ChannelLabelRule, ChannelLabelsList, ChannelMessage, ChannelParticipant, ChannelParticipantAddedMetadata, ChannelParticipantRemovedMetadata, ChannelPreview, ChannelPreviewData, ChannelSender, ChannelSharePermission, ChannelThreadFilters, ChannelTopicEvent, ChannelType, ChannelUpdatedMetadata, ChannelWebhookRequest, ChannelWebhookResponse, ChannelWithParticipants, Chat, ChatFilters, CheckActiveCallData, CheckActiveCallError, CheckActiveCallErrors, CheckActiveCallResponse, CheckActiveCallResponses, ClaimedPairing, ClaimHarnessPairingData, ClaimHarnessPairingError, ClaimHarnessPairingErrors, ClaimHarnessPairingResponse, ClaimHarnessPairingResponses, ClaimPairingRequest, ClientOptions, CloudStorageItemType, CollaborateFormData, CollaborateFormError, CollaborateFormErrors, CollaborateFormResponse, CollaborateFormResponses, CollabSurfaceResponse, CollabSurfaceTokenResponse, Column, ColumnCast, ColumnChange, ColumnChangeKind, ColumnConfig, ColumnConversion, ColumnConversionRequest, ColumnDetail, ColumnKind, ColumnProtection, ColumnResult, CommandFailure, CommandRejectedMetadata, CommittedChange, CompleteSlackImportUploadsData, CompleteSlackImportUploadsErrors, CompleteSlackImportUploadsResponse, CompleteSlackImportUploadsResponses, CompleteUploads, ConferenceProvider, Conjunction, ConversationId, ConversationKind, ConversationMetadata, ConversationProgress, ConversationSeal, ConversationStatus, ConvertDatabaseColumnData, ConvertDatabaseColumnError, ConvertDatabaseColumnErrors, ConvertDatabaseColumnResponse, ConvertDatabaseColumnResponses, ConvertedCell, CopyDocumentData, CopyDocumentError, CopyDocumentErrors, CopyDocumentQueryParams, CopyDocumentRequest, CopyDocumentResponse, CopyDocumentResponse2, CopyDocumentResponses, CountedReaction, CreateAgentData, CreateAgentError, CreateAgentErrors, CreateAgentRequest, CreateAgentResponse, CreateAgentResponses, CreateAnchorData, CreateAnchorError, CreateAnchorErrors, CreateAnchorResponse, CreateAnchorResponses, CreateBotRequest, CreateBulkDocumentResponse, CreateBulkDocumentResponseData, CreateChannelData, CreateChannelError, CreateChannelErrors, CreateChannelLabelData, CreateChannelLabelError, CreateChannelLabelErrors, CreateChannelLabelRequest, CreateChannelLabelResponse, CreateChannelLabelResponses, CreateChannelRequest, CreateChannelResponse, CreateChannelResponse2, CreateChannelResponses, CreateChannelScopedBotData, CreateChannelScopedBotError, CreateChannelScopedBotErrors, CreateChannelScopedBotRequest, CreateChannelScopedBotResponse, CreateChannelScopedBotResponse2, CreateChannelScopedBotResponses, CreateCollabSurfaceTokenData, CreateCollabSurfaceTokenError, CreateCollabSurfaceTokenErrors, CreateCollabSurfaceTokenResponse, CreateCollabSurfaceTokenResponses, CreateCrmCompanyData, CreateCrmCompanyError, CreateCrmCompanyErrors, CreateCrmCompanyRequest, CreateCrmCompanyResponse, CreateCrmCompanyResponses, CreateCrmContactData, CreateCrmContactError, CreateCrmContactErrors, CreateCrmContactRequest, CreateCrmContactResponse, CreateCrmContactResponses, CreateCrmPipelineData, CreateCrmPipelineResponse, CreateCrmPipelineResponses, CreateDatabaseData, CreateDatabaseError, CreateDatabaseErrors, CreateDatabaseRequest, CreateDatabaseResponse, CreateDatabaseResponses, CreateDocumentData, CreateDocumentError, CreateDocumentErrors, CreateDocumentRequest, CreateDocumentResponse, CreateDocumentResponseData, CreateDocumentResponses, CreatedPairing, CreatedUserApiKey, CreateEntityMentionData, CreateEntityMentionError, CreateEntityMentionErrors, CreateEntityMentionRequest, CreateEntityMentionResponse, CreateEntityMentionResponse2, CreateEntityMentionResponses, CreateForm, CreateFormData, CreateFormError, CreateFormErrors, CreateFormResponse, CreateFormResponses, CreateHarnessPairingData, CreateHarnessPairingError, CreateHarnessPairingErrors, CreateHarnessPairingResponse, CreateHarnessPairingResponses, CreateImport, CreateInitiativeData, CreateInitiativeError, CreateInitiativeErrors, CreateInitiativeRequest, CreateInitiativeResponse, CreateInitiativeResponses, CreateInstructionsDocumentResponse, CreateInstructionsHandlerData, CreateInstructionsHandlerError, CreateInstructionsHandlerErrors, CreateInstructionsHandlerResponse, CreateInstructionsHandlerResponses, CreateMarkdownDocumentRequest, CreateMarkdownDocumentResponse, CreateMarkdownHandlerData, CreateMarkdownHandlerError, CreateMarkdownHandlerErrors, CreateMarkdownHandlerResponse, CreateMarkdownHandlerResponses, CreateMeetingRequest, CreatePairingRequest, CreatePipeline, CreateProjectHandlerData, CreateProjectHandlerError, CreateProjectHandlerErrors, CreateProjectHandlerResponse, CreateProjectHandlerResponses, CreateProjectRequest, CreateProjectResponse, CreateSkillHandlerData, CreateSkillHandlerError, CreateSkillHandlerErrors, CreateSkillHandlerResponse, CreateSkillHandlerResponses, CreateSkillRequest, CreateSkillResponse, CreateSlackImportData, CreateSlackImportErrors, CreateSlackImportResponse, CreateSlackImportResponses, CreateSnippetHandlerData, CreateSnippetHandlerError, CreateSnippetHandlerErrors, CreateSnippetHandlerResponse, CreateSnippetHandlerResponses, CreateSnippetRequest, CreateSnippetResponse, CreateTaskHandlerData, CreateTaskHandlerError, CreateTaskHandlerErrors, CreateTaskHandlerResponse, CreateTaskHandlerResponses, CreateTaskRequest, CreateTaskResponse, CreateToken, CreateUnthreadedAnchorRequest, CreateUnthreadedAnchorResponse, CreateUnthreadedPdfAnchorRequest, CreateUserApiKeyData, CreateUserApiKeyError, CreateUserApiKeyErrors, CreateUserApiKeyRequest, CreateUserApiKeyResponse, CreateUserApiKeyResponses, CreateViewHandlerData, CreateViewHandlerError, CreateViewHandlerErrors, CreateViewHandlerResponse, CreateViewHandlerResponses, CreateViewRequest, CreateWebhookData, CreateWebhookError, CreateWebhookErrors, CreateWebhookRequest, CreateWebhookResponse, CreateWebhookResponse2, CreateWebhookResponses, CrmCompanyFilters, CrmCompanyResponse, CrmContactResponse, CrmDomainResponse, CrmPermissionRole, CrmStageInput, CrmStageResponse, CrmStagesResponse, CrmTeamSettingsResponse, CustomSpeakerAssignment, Database, DatabaseDetail, DatabaseOp, DatabaseView, DataType, DateOperator, DeleteAnchorData, DeleteAnchorError, DeleteAnchorErrors, DeleteAnchorResponse, DeleteAnchorResponses, DeleteCallRecordData, DeleteCallRecordError, DeleteCallRecordErrors, DeleteCallRecordResponse, DeleteCallRecordResponses, DeleteChannelData, DeleteChannelError, DeleteChannelErrors, DeleteChannelLabelData, DeleteChannelLabelError, DeleteChannelLabelErrors, DeleteChannelLabelResponse, DeleteChannelLabelResponses, DeleteChannelResponse, DeleteChannelResponses, DeleteCollabSurfaceData, DeleteCollabSurfaceError, DeleteCollabSurfaceErrors, DeleteCollabSurfaceResponse, DeleteCollabSurfaceResponses, DeleteDocumentData, DeleteDocumentError, DeleteDocumentErrors, DeleteDocumentResponse, DeleteDocumentResponses, DeleteEntityMentionData, DeleteEntityMentionError, DeleteEntityMentionErrors, DeleteEntityMentionResponse, DeleteEntityMentionResponse2, DeleteEntityMentionResponses, DeleteHarnessData, DeleteHarnessError, DeleteHarnessErrors, DeleteHarnessResponse, DeleteHarnessResponses, DeleteHistoryHandlerData, DeleteHistoryHandlerError, DeleteHistoryHandlerErrors, DeleteHistoryHandlerResponse, DeleteHistoryHandlerResponses, DeleteInitiativeData, DeleteInitiativeError, DeleteInitiativeErrors, DeleteInitiativeResponse, DeleteInitiativeResponses, DeleteProjectHandlerData, DeleteProjectHandlerError, DeleteProjectHandlerErrors, DeleteProjectHandlerResponse, DeleteProjectHandlerResponses, DeleteSelfHarnessData, DeleteSelfHarnessError, DeleteSelfHarnessErrors, DeleteSelfHarnessResponse, DeleteSelfHarnessResponses, DeleteUnthreadedAnchorRequest, DeleteUnthreadedAnchorResponse, DeleteUnthreadedPdfAnchorRequest, DeleteUserApiKeyData, DeleteUserApiKeyError, DeleteUserApiKeyErrors, DeleteUserApiKeyResponse, DeleteUserApiKeyResponses, DeleteUserDocumentViewLocationData, DeleteUserDocumentViewLocationError, DeleteUserDocumentViewLocationErrors, DeleteUserDocumentViewLocationResponse, DeleteUserDocumentViewLocationResponses, DeleteViewHandlerData, DeleteViewHandlerError, DeleteViewHandlerErrors, DeleteViewHandlerResponses, DeleteWebhookData, DeleteWebhookError, DeleteWebhookErrors, DeleteWebhookResponse, DeleteWebhookResponses, DocumentBasic, DocumentContent, DocumentContentLocation, DocumentContentState, DocumentContentUploadedMetadata, DocumentCopiedMetadata, DocumentCreatedMetadata, DocumentDeletedMetadata, DocumentFilters, DocumentId, DocumentInteractionMetadata, DocumentMetadata, DocumentMetadataWithContent, DocumentPermissionsToken, DocumentPermissionsTokenRequest, DocumentPermissionsTokenResponse, DocumentPreview, DocumentPreviewData, DocumentPreviewDataSubType, DocumentPurgedMetadata, DocumentResponse, DocumentResponseMetadata, DocumentResponseMetadataWithContent, DocumentStorageServiceApiVersion, DocumentSubType, DocumentSyncContentUpdatedMetadata, DocumentSyncEditor, DocumentTeamShareResponse, DocumentTopicEvent, DocumentUpdatedMetadata, EditAnchorData, EditAnchorError, EditAnchorErrors, EditAnchorRequest, EditAnchorResponse, EditAnchorResponse2, EditAnchorResponses, EditCallRecordData, EditCallRecordError, EditCallRecordErrors, EditCallRecordRequest, EditCallRecordResponse, EditCallRecordResponses, EditCallTranscriptData, EditCallTranscriptError, EditCallTranscriptErrors, EditCallTranscriptRequest, EditCallTranscriptResponse, EditCallTranscriptResponses, EditDocumentData, EditDocumentError, EditDocumentErrors, EditDocumentResponse, EditDocumentResponse2, EditDocumentResponses, EditDocumentServiceArgs, EditMyFormResponseData, EditMyFormResponseError, EditMyFormResponseErrors, EditMyFormResponseResponse, EditMyFormResponseResponses, EditPdfAnchorRequest, EditPdfPlaceableCommentAnchorRequest, EditProjectV2Data, EditProjectV2Error, EditProjectV2Errors, EditProjectV2Response, EditProjectV2Responses, EditThreadV2Data, EditThreadV2Error, EditThreadV2Errors, EditThreadV2Response, EditThreadV2Responses, EmailFilters, EmailFollowup, EmailFollowupCommand, EmailFollowupResponse, EmailReminderCondition, EmailReminderPage, EmailReminderSummary, EmptyResponse, EnsureCollabSurfaceData, EnsureCollabSurfaceError, EnsureCollabSurfaceErrors, EnsureCollabSurfaceRequest, EnsureCollabSurfaceResponse, EnsureCollabSurfaceResponses, EnsureStarterHandlerData, EnsureStarterHandlerErrors, EnsureStarterHandlerResponse, EnsureStarterHandlerResponses, EntityFilters, EntityKind, EntityMessageCreateData, EntityMessageCreateResponse, EntityMessageCreateResponses, EntityMessageDeleteMessageData, EntityMessageDeleteMessageResponse, EntityMessageDeleteMessageResponses, EntityMessageDeleteThreadData, EntityMessageDeleteThreadResponse, EntityMessageDeleteThreadResponses, EntityMessageEditData, EntityMessageEditResponse, EntityMessageEditResponses, EntityMessageGetMessageData, EntityMessageGetMessageResponse, EntityMessageGetMessageResponses, EntityMessageGetThreadData, EntityMessageGetThreadResponse, EntityMessageGetThreadResponses, EntityMessageLegacyData, EntityMessageLegacyResponse, EntityMessageLegacyResponses, EntityMessagePatchThreadData, EntityMessagePatchThreadResponse, EntityMessagePatchThreadResponses, EntityMessageReactData, EntityMessageReactResponse, EntityMessageReactResponses, EntityMessageTypingData, EntityMessageTypingResponse, EntityMessageTypingResponses, EntityPermission, EntityPermissionResponse, EntityRef, EntityReference, EntityType, ErrorResponse, EventReminderOverride, EventReminders, EventStatus, EventTime, EventTransparency, EventType, EventVisibility, ExcludedDefaultView, ExcludeDefaultViewHandlerData, ExcludeDefaultViewHandlerError, ExcludeDefaultViewHandlerErrors, ExcludeDefaultViewHandlerResponses, ExcludeDefaultViewRequest, ExportDocumentData, ExportDocumentError, ExportDocumentErrors, ExportDocumentResponse, ExportDocumentResponse2, ExportDocumentResponses, Favorite, FavoriteEntityRef, FavoritesList, FileChangeKindDto, FileSystemNodeWithIds, FileType, FileTypeUpdate, FilterCondition, FilterGroup, FilterNode, FilterTest, FinalizeSlackImportData, FinalizeSlackImportErrors, FinalizeSlackImportResponse, FinalizeSlackImportResponses, FolderItem, FollowupState, ForeignEntity, ForeignEntityFilters, Form, FormAccess, FormCollaboration, FormDetail, FormErrorCode, FormErrorResponse, FormLayout, FormPublicationProblem, FormQuestionDetail, FormResponse, FormSection, FormSectionDetail, FormSource, FormStatus, FormTally, GenericErrorResponse, GenericResponse, GenericSuccessResponse, GetActiveCallsData, GetActiveCallsError, GetActiveCallsErrors, GetActiveCallsResponse, GetActiveCallsResponses, GetActivityData, GetActivityError, GetActivityErrors, GetActivityResponse, GetActivityResponses, GetAttachmentReferencesData, GetAttachmentReferencesError, GetAttachmentReferencesErrors, GetAttachmentReferencesResponse, GetAttachmentReferencesResponse2, GetAttachmentReferencesResponses, GetBatchCallRecordPreviewData, GetBatchCallRecordPreviewError, GetBatchCallRecordPreviewErrors, GetBatchCallRecordPreviewRequest, GetBatchCallRecordPreviewResponse, GetBatchCallRecordPreviewResponse2, GetBatchCallRecordPreviewResponses, GetBatchChannelPreviewData, GetBatchChannelPreviewError, GetBatchChannelPreviewErrors, GetBatchChannelPreviewRequest, GetBatchChannelPreviewResponse, GetBatchChannelPreviewResponse2, GetBatchChannelPreviewResponses, GetBatchPreviewHandlerData, GetBatchPreviewHandlerError, GetBatchPreviewHandlerErrors, GetBatchPreviewHandlerResponse, GetBatchPreviewHandlerResponses, GetBatchPreviewRequest, GetBatchPreviewResponse, GetBatchProjectPreviewData, GetBatchProjectPreviewError, GetBatchProjectPreviewErrors, GetBatchProjectPreviewRequest, GetBatchProjectPreviewResponse, GetBatchProjectPreviewResponse2, GetBatchProjectPreviewResponses, GetBotOwnerProfilesData, GetBotOwnerProfilesError, GetBotOwnerProfilesErrors, GetBotOwnerProfilesResponse, GetBotOwnerProfilesResponses, GetCallRecordData, GetCallRecordError, GetCallRecordErrors, GetCallRecordResponse, GetCallRecordResponses, GetChannelAttachmentsData, GetChannelAttachmentsError, GetChannelAttachmentsErrors, GetChannelAttachmentsResponse, GetChannelAttachmentsResponses, GetChannelData, GetChannelError, GetChannelErrors, GetChannelJoinLinkData, GetChannelJoinLinkError, GetChannelJoinLinkErrors, GetChannelJoinLinkResponse, GetChannelJoinLinkResponses, GetChannelParticipantsData, GetChannelParticipantsError, GetChannelParticipantsErrors, GetChannelParticipantsResponse, GetChannelParticipantsResponses, GetChannelResponse, GetChannelResponses, GetChannelsData, GetChannelsError, GetChannelsErrors, GetChannelsResponse, GetChannelsResponses, GetCollabSurfaceData, GetCollabSurfaceError, GetCollabSurfaceErrors, GetCollabSurfaceResponse, GetCollabSurfaceResponses, GetCompanyData, GetCompanyError, GetCompanyErrors, GetCompanyResponse, GetCompanyResponses, GetContactByEmailData, GetContactByEmailError, GetContactByEmailErrors, GetContactByEmailResponse, GetContactByEmailResponse2, GetContactByEmailResponses, GetContactData, GetContactError, GetContactErrors, GetContactResponse, GetContactResponses, GetCrmPipelineData, GetCrmPipelineResponse, GetCrmPipelineResponses, GetCrmPipelineRowsData, GetCrmPipelineRowsResponse, GetCrmPipelineRowsResponses, GetCrmPipelineTableData, GetCrmPipelineTableResponse, GetCrmPipelineTableResponses, GetCrmTeamSettingsData, GetCrmTeamSettingsError, GetCrmTeamSettingsErrors, GetCrmTeamSettingsResponse, GetCrmTeamSettingsResponses, GetDatabaseData, GetDatabaseError, GetDatabaseErrors, GetDatabasePermissionsData, GetDatabasePermissionsError, GetDatabasePermissionsErrors, GetDatabasePermissionsResponse, GetDatabasePermissionsResponses, GetDatabaseQueryData, GetDatabaseQueryError, GetDatabaseQueryErrors, GetDatabaseQueryResponse, GetDatabaseQueryResponses, GetDatabaseResponse, GetDatabaseResponses, GetDatabaseRowHistoryData, GetDatabaseRowHistoryError, GetDatabaseRowHistoryErrors, GetDatabaseRowHistoryResponse, GetDatabaseRowHistoryResponses, GetDatabaseTableChangesData, GetDatabaseTableChangesError, GetDatabaseTableChangesErrors, GetDatabaseTableChangesResponse, GetDatabaseTableChangesResponses, GetDatabaseViewPositionsData, GetDatabaseViewPositionsError, GetDatabaseViewPositionsErrors, GetDatabaseViewPositionsResponse, GetDatabaseViewPositionsResponses, GetDocumentAnchorsData, GetDocumentAnchorsError, GetDocumentAnchorsErrors, GetDocumentAnchorsResponse, GetDocumentAnchorsResponses, GetDocumentBranchNameData, GetDocumentBranchNameError, GetDocumentBranchNameErrors, GetDocumentBranchNameResponse, GetDocumentBranchNameResponses, GetDocumentByTeamSlugData, GetDocumentByTeamSlugError, GetDocumentByTeamSlugErrors, GetDocumentByTeamSlugResponse, GetDocumentByTeamSlugResponses, GetDocumentData, GetDocumentError, GetDocumentErrors, GetDocumentGithubPullRequestsData, GetDocumentGithubPullRequestsError, GetDocumentGithubPullRequestsErrors, GetDocumentGithubPullRequestsResponse, GetDocumentGithubPullRequestsResponses, GetDocumentKeyResponse, GetDocumentKeyResponseData, GetDocumentListHandlerData, GetDocumentListHandlerError, GetDocumentListHandlerErrors, GetDocumentListHandlerResponse, GetDocumentListHandlerResponses, GetDocumentListResult, GetDocumentLocationV3Data, GetDocumentLocationV3Error, GetDocumentLocationV3Errors, GetDocumentLocationV3Response, GetDocumentLocationV3Responses, GetDocumentPermissionsResponseDataV2, GetDocumentPermissionsTokenData, GetDocumentPermissionsTokenError, GetDocumentPermissionsTokenErrors, GetDocumentPermissionsTokenResponse, GetDocumentPermissionsTokenResponses, GetDocumentPermissionsV2Data, GetDocumentPermissionsV2Error, GetDocumentPermissionsV2Errors, GetDocumentPermissionsV2Response, GetDocumentPermissionsV2Responses, GetDocumentProcessingResult, GetDocumentProcessingResultData, GetDocumentProcessingResultError, GetDocumentProcessingResultErrors, GetDocumentProcessingResultResponse, GetDocumentProcessingResultResponse2, GetDocumentProcessingResultResponses, GetDocumentResponse, GetDocumentResponse2, GetDocumentResponseData, GetDocumentResponses, GetDocumentSearchResponse, GetDocumentShortIdData, GetDocumentShortIdError, GetDocumentShortIdErrors, GetDocumentShortIdResponse, GetDocumentShortIdResponses, GetDocumentsResponse, GetDocumentTeamShareData, GetDocumentTeamShareError, GetDocumentTeamShareErrors, GetDocumentTeamShareResponse, GetDocumentTeamShareResponses, GetDocumentUserAccessLevelResponse, GetDocumentVersionData, GetDocumentVersionError, GetDocumentVersionErrors, GetDocumentVersionResponse, GetDocumentVersionResponses, GetDocumentViewsHandlerData, GetDocumentViewsHandlerError, GetDocumentViewsHandlerErrors, GetDocumentViewsHandlerResponse, GetDocumentViewsHandlerResponses, GetEmailFollowupData, GetEmailFollowupError, GetEmailFollowupErrors, GetEmailFollowupResponse, GetEmailFollowupResponses, GetEntityPermissionData, GetEntityPermissionErrors, GetEntityPermissionResponse, GetEntityPermissionResponses, GetForeignEntityBySourceData, GetForeignEntityBySourceError, GetForeignEntityBySourceErrors, GetForeignEntityBySourceResponse, GetForeignEntityBySourceResponses, GetForeignEntityData, GetForeignEntityError, GetForeignEntityErrors, GetForeignEntityResponse, GetForeignEntityResponses, GetFormData, GetFormError, GetFormErrors, GetFormPermissionsData, GetFormPermissionsError, GetFormPermissionsErrors, GetFormPermissionsResponse, GetFormPermissionsResponses, GetFormResponse, GetFormResponses, GetFormResponseSummaryData, GetFormResponseSummaryError, GetFormResponseSummaryErrors, GetFormResponseSummaryResponse, GetFormResponseSummaryResponses, GetFormTallyData, GetFormTallyError, GetFormTallyErrors, GetFormTallyResponse, GetFormTallyResponses, GetGithubPullRequestChangesData, GetGithubPullRequestChangesError, GetGithubPullRequestChangesErrors, GetGithubPullRequestChangesPatchData, GetGithubPullRequestChangesPatchError, GetGithubPullRequestChangesPatchErrors, GetGithubPullRequestChangesPatchResponse, GetGithubPullRequestChangesPatchResponses, GetGithubPullRequestChangesResponse, GetGithubPullRequestChangesResponses, GetGithubPullRequestData, GetGithubPullRequestError, GetGithubPullRequestErrors, GetGithubPullRequestFacetsData, GetGithubPullRequestFacetsError, GetGithubPullRequestFacetsErrors, GetGithubPullRequestFacetsResponse, GetGithubPullRequestFacetsResponses, GetGithubPullRequestResponse, GetGithubPullRequestResponses, GetGithubPullRequestTasksData, GetGithubPullRequestTasksError, GetGithubPullRequestTasksErrors, GetGithubPullRequestTasksResponse, GetGithubPullRequestTasksResponses, GetHarnessPairingData, GetHarnessPairingError, GetHarnessPairingErrors, GetHarnessPairingResponse, GetHarnessPairingResponses, GetHistoryHandlerData, GetHistoryHandlerError, GetHistoryHandlerErrors, GetHistoryHandlerResponse, GetHistoryHandlerResponses, GetInitiativeData, GetInitiativeError, GetInitiativeErrors, GetInitiativeResponse, GetInitiativeResponses, GetInstructionsDocumentResponse, GetInstructionsHandlerData, GetInstructionsHandlerError, GetInstructionsHandlerErrors, GetInstructionsHandlerResponse, GetInstructionsHandlerResponses, GetItemsSoupData, GetItemsSoupError, GetItemsSoupErrors, GetItemsSoupResponse, GetItemsSoupResponses, GetLocationHandlerData, GetLocationHandlerError, GetLocationHandlerErrors, GetLocationHandlerResponse, GetLocationHandlerResponses, GetMyFormResponseData, GetMyFormResponseError, GetMyFormResponseErrors, GetMyFormResponseResponse, GetMyFormResponseResponses, GetOrCreateAction, GetOrCreateCallData, GetOrCreateCallError, GetOrCreateCallErrors, GetOrCreateCallResponse, GetOrCreateCallResponses, GetOrCreateChannelResponse, GetOrCreateDmData, GetOrCreateDmError, GetOrCreateDmErrors, GetOrCreateDmRequest, GetOrCreateDmResponse, GetOrCreateDmResponses, GetOrCreatePrivateData, GetOrCreatePrivateError, GetOrCreatePrivateErrors, GetOrCreatePrivateRequest, GetOrCreatePrivateResponse, GetOrCreatePrivateResponses, GetPendingProjectsHandlerData, GetPendingProjectsHandlerError, GetPendingProjectsHandlerErrors, GetPendingProjectsHandlerResponse, GetPendingProjectsHandlerResponses, GetPinsHandlerData, GetPinsHandlerError, GetPinsHandlerErrors, GetPinsHandlerResponse, GetPinsHandlerResponses, GetPinsResponse, GetProjectContentHandlerData, GetProjectContentHandlerError, GetProjectContentHandlerErrors, GetProjectContentHandlerResponse, GetProjectContentHandlerResponses, GetProjectContentResponse, GetProjectHandlerData, GetProjectHandlerError, GetProjectHandlerErrors, GetProjectHandlerResponse, GetProjectHandlerResponses, GetProjectPermissionsV2Data, GetProjectPermissionsV2Error, GetProjectPermissionsV2Errors, GetProjectPermissionsV2Response, GetProjectPermissionsV2Responses, GetProjectResponse, GetProjectResponseData, GetProjectsHandlerData, GetProjectsHandlerError, GetProjectsHandlerErrors, GetProjectsHandlerResponse, GetProjectsHandlerResponses, GetProjectsResponse, GetProjectUserAccessLevelData, GetProjectUserAccessLevelError, GetProjectUserAccessLevelErrors, GetProjectUserAccessLevelResponse, GetProjectUserAccessLevelResponses, GetRingStatusData, GetRingStatusError, GetRingStatusErrors, GetRingStatusResponse, GetRingStatusResponses, GetSelfBotData, GetSelfBotError, GetSelfBotErrors, GetSelfBotResponse, GetSelfBotResponses, GetSelfHarnessData, GetSelfHarnessError, GetSelfHarnessErrors, GetSelfHarnessResponse, GetSelfHarnessResponses, GetSlackImportData, GetSlackImportErrors, GetSlackImportResponse, GetSlackImportResponses, GetSystemSkillsHandlerData, GetSystemSkillsHandlerError, GetSystemSkillsHandlerErrors, GetSystemSkillsHandlerResponse, GetSystemSkillsHandlerResponses, GetUserDocumentsHandlerData, GetUserDocumentsHandlerError, GetUserDocumentsHandlerErrors, GetUserDocumentsHandlerResponse, GetUserDocumentsHandlerResponses, GetUserDocumentViewLocationData, GetUserDocumentViewLocationError, GetUserDocumentViewLocationErrors, GetUserDocumentViewLocationResponse, GetUserDocumentViewLocationResponses, GetUserHistoryResponse, GetViewsHandlerData, GetViewsHandlerError, GetViewsHandlerErrors, GetViewsHandlerResponse, GetViewsHandlerResponses, GetWebhookData, GetWebhookError, GetWebhookErrors, GetWebhookResponse, GetWebhookResponses, GithubLabelFacet, GithubPullRequest, GithubPullRequestChangesPatchResponse, GithubPullRequestChangesResponse, GithubPullRequestCheckRun, GithubPullRequestComment, GithubPullRequestFacets, GithubPullRequestLabel, GithubPullRequestReview, GithubPullRequestReviewDecision, GithubPullRequestReviewState, GithubPullRequestsResponse, GithubPullRequestTasks, GithubPullRequestTasksRequest, GithubPullRequestTasksResponse, GithubPullRequestUser, GithubRepositoryFacet, GithubUserFacet, GitRefDto, GroupedInitialParams, GroupedPageParams, GroupedSoupGroupPage, GroupedSoupInitialPage, GroupedSoupPage, GroupedSoupSort, GuestId, GuestJoinRequest, HandlerData, HandlerError, HandlerErrors, HandlerResponse, HandlerResponses, Harness, HarnessAgent, HarnessId, HarnessOwner, HarnessSession, HashMap, HealthHandlerData, HealthHandlerResponse, HealthHandlerResponses, HighlightType, ImportCounters, ImportDatabaseTableData, ImportDatabaseTableError, ImportDatabaseTableErrors, ImportDatabaseTableResponse, ImportDatabaseTableResponses, ImportedAuthor, ImportError, ImportLimits, ImportPage, ImportProgress, ImportTable, ImportWarning, InferColumnTypeOutcome, InferColumnTypeRequest, InferDatabaseColumnTypeData, InferDatabaseColumnTypeError, InferDatabaseColumnTypeErrors, InferDatabaseColumnTypeResponse, InferDatabaseColumnTypeResponses, InFlightTurnSummary, IngestTranscriptData, IngestTranscriptError, IngestTranscriptErrors, IngestTranscriptResponses, InitializeUserDocumentsData, InitializeUserDocumentsError, InitializeUserDocumentsErrors, InitializeUserDocumentsResponse, InitializeUserDocumentsResponses, InitialPropertyValue, InitiativeDetail, InitiativeFilters, InitiativeId, InitiativeList, InitiativeSummary, InputReceivedMetadata, InstallSyncData, InstallSyncErrors, InteractionReason, InviteMeetingRequest, InviteMeetingUsersRequest, Item, ItemWithUserAccessLevel, JobId, JobProcessingResultHandlerData, JobProcessingResultHandlerError, JobProcessingResultHandlerErrors, JobProcessingResultHandlerResponse, JobProcessingResultHandlerResponses, JobStatus, JoinChannelByCodeData, JoinChannelByCodeError, JoinChannelByCodeErrors, JoinChannelByCodeResponses, JoinChannelData, JoinChannelError, JoinChannelErrors, JoinChannelResponses, KeySegment, Lane, LaneKey, LatestMessage, LayoutProblem, LeaveCallResponse, LeaveChannelData, LeaveChannelError, LeaveChannelErrors, LeaveChannelResponses, LeaveOrEndCallData, LeaveOrEndCallError, LeaveOrEndCallErrors, LeaveOrEndCallResponse, LeaveOrEndCallResponses, LinkShare, ListAccessibleFormsData, ListAccessibleFormsError, ListAccessibleFormsErrors, ListAccessibleFormsResponse, ListAccessibleFormsResponses, ListAgentsData, ListAgentsError, ListAgentsErrors, ListAgentsResponse, ListAgentsResponses, ListBotChannelsData, ListBotChannelsError, ListBotChannelsErrors, ListBotChannelsResponse, ListBotChannelsResponses, ListChannelLabelsData, ListChannelLabelsError, ListChannelLabelsErrors, ListChannelLabelsResponse, ListChannelLabelsResponses, ListCompanyContactsData, ListCompanyContactsError, ListCompanyContactsErrors, ListCompanyContactsResponse, ListCompanyContactsResponses, ListCrmPipelinesData, ListCrmPipelinesResponse, ListCrmPipelinesResponses, ListDatabaseColumnCastsData, ListDatabaseColumnCastsError, ListDatabaseColumnCastsErrors, ListDatabaseColumnCastsResponse, ListDatabaseColumnCastsResponses, ListDatabasesData, ListDatabasesError, ListDatabasesErrors, ListDatabasesResponse, ListDatabasesResponses, ListedDatabase, ListedForm, ListEmailRemindersData, ListEmailRemindersError, ListEmailRemindersErrors, ListEmailRemindersResponse, ListEmailRemindersResponses, ListFavoritesData, ListFavoritesError, ListFavoritesErrors, ListFavoritesResponse, ListFavoritesResponses, ListFormsData, ListFormsError, ListFormsErrors, ListFormsResponse, ListFormsResponses, ListHarnessAgentsData, ListHarnessAgentsError, ListHarnessAgentsErrors, ListHarnessAgentsResponse, ListHarnessAgentsResponses, ListHarnessesData, ListHarnessesError, ListHarnessesErrors, ListHarnessesResponse, ListHarnessesResponses, ListHarnessSessionsData, ListHarnessSessionsError, ListHarnessSessionsErrors, ListHarnessSessionsResponse, ListHarnessSessionsResponses, ListInitiativesData, ListInitiativesError, ListInitiativesErrors, ListInitiativesResponse, ListInitiativesResponses, ListOccurrencesData, ListOccurrencesErrors, ListOccurrencesResponse, ListOccurrencesResponses, ListSlackImportsData, ListSlackImportsResponse, ListSlackImportsResponses, ListTeamOutOfOfficeData, ListTeamOutOfOfficeErrors, ListTeamOutOfOfficeResponse, ListTeamOutOfOfficeResponses, ListUserApiKeysData, ListUserApiKeysError, ListUserApiKeysErrors, ListUserApiKeysResponse, ListUserApiKeysResponses, ListWebhooksData, ListWebhooksError, ListWebhooksErrors, ListWebhooksResponse, ListWebhooksResponse2, ListWebhooksResponses, LocationResponseData, LocationResponseV3, MacroUserIdStr, Meeting, MeetingCancelData, MeetingCancelError, MeetingCancelErrors, MeetingCancelPreparationData, MeetingCancelPreparationError, MeetingCancelPreparationErrors, MeetingCancelPreparationResponse, MeetingCancelPreparationResponses, MeetingCancelResponse, MeetingCancelResponses, MeetingCreateData, MeetingCreateError, MeetingCreateErrors, MeetingCreateResponse, MeetingCreateResponses, MeetingGuestJoinData, MeetingGuestJoinError, MeetingGuestJoinErrors, MeetingGuestJoinResponse, MeetingGuestJoinResponses, MeetingGuestParticipantsData, MeetingGuestParticipantsError, MeetingGuestParticipantsErrors, MeetingGuestParticipantsResponse, MeetingGuestParticipantsResponses, MeetingInviteData, MeetingInviteError, MeetingInviteErrors, MeetingInvitePermissions, MeetingInvitePermissionsData, MeetingInvitePermissionsError, MeetingInvitePermissionsErrors, MeetingInvitePermissionsResponse, MeetingInvitePermissionsResponses, MeetingInviteResponse, MeetingInviteResponses, MeetingInviteUsersData, MeetingInviteUsersError, MeetingInviteUsersErrors, MeetingInviteUsersResponse, MeetingInviteUsersResponses, MeetingJoinData, MeetingJoinError, MeetingJoinErrors, MeetingJoinResponse, MeetingJoinResponses, MeetingLeaveData, MeetingLeaveError, MeetingLeaveErrors, MeetingLeaveResponse, MeetingLeaveResponses, MeetingListActiveData, MeetingListActiveError, MeetingListActiveErrors, MeetingListActiveResponse, MeetingListActiveResponses, MeetingListData, MeetingListError, MeetingListErrors, MeetingListResponse, MeetingListResponses, MeetingLookupData, MeetingLookupError, MeetingLookupErrors, MeetingLookupResponse, MeetingLookupResponses, MeetingParticipant, MeetingParticipants, MeetingParticipantsData, MeetingParticipantsError, MeetingParticipantsErrors, MeetingParticipantsResponse, MeetingParticipantsResponses, MeetingPreparation, MeetingPrepareData, MeetingPrepareError, MeetingPrepareErrors, MeetingPrepareResponse, MeetingPrepareResponses, MeetingShareData, MeetingShareError, MeetingShareErrors, MeetingShareResponse, MeetingShareResponses, MeetingsResponse, MeetingToken, MeetingUpdateData, MeetingUpdateError, MeetingUpdateErrors, MeetingUpdateResponse, MeetingUpdateResponses, MentionPreviewsData, MentionPreviewsErrors, MentionPreviewsResponse, MentionPreviewsResponses, Message, MessageAttachment, MessageAttachmentCreatedMetadata, MessageAttachmentRemovedMetadata, MessageChange, MessageCursor, MessageDeletedMetadata, MessageDirection, MessageEvent, MessageEventAttachment, MessageListItem, MessageMentionedMetadata, MessagePage, MessageParent, MessagePatch, MessagePatchedMetadata, MessagePostedMetadata, MessageThread, MessageThreadPreview, MessageTimelineData, MessageTimelineQuery, MessageTimelineResponse, MessageTimelineResponses, MessageTopicEvent, MyResponse, NewAttachment, NewColumn, NewOption, NewThreadAnchor, NewView, NotificationFilters, NotificationState, NumberOperator, OpBatch, OpRefusalResponse, OpResult, OptionRef, PairingDetails, Params, ParticipantRole, PatchBotRequest, PatchChannelData, PatchChannelError, PatchChannelErrors, PatchChannelRequest, PatchChannelResponse, PatchChannelResponses, PatchMessageNotificationPolicy, PatchProjectRequestV2, PatchThreadRequestV2, PatchViewHandlerData, PatchViewHandlerError, PatchViewHandlerErrors, PatchViewHandlerResponses, PatchWebhookData, PatchWebhookError, PatchWebhookErrors, PatchWebhookRequest, PatchWebhookResponse, PatchWebhookResponses, PdfAnchor, PdfAnchorId, PdfHighlightAnchor, PdfHighlightAnchorRequest, PdfHighlightRect, PdfHighlightRectAnchorRequest, PdfPlaceableCommentAnchor, PendingClaimResponse, PermanentlyDeleteDocumentData, PermanentlyDeleteDocumentError, PermanentlyDeleteDocumentErrors, PermanentlyDeleteDocumentResponse, PermanentlyDeleteDocumentResponses, PermanentlyDeleteProjectData, PermanentlyDeleteProjectError, PermanentlyDeleteProjectErrors, PermanentlyDeleteProjectResponse, PermanentlyDeleteProjectResponses, PinnedItem, PinRequest, Pipeline, PipelineRecordType, PipelineSharing, PostActivityData, PostActivityError, PostActivityErrors, PostActivityRequest, PostActivityResponse, PostActivityResponses, PostChannelBotWebhookData, PostChannelBotWebhookError, PostChannelBotWebhookErrors, PostChannelBotWebhookResponse, PostChannelBotWebhookResponses, PostGroupedSoupAstGroupPageRequest, PostGroupedSoupAstInitialRequest, PostGroupedSoupAstRequest, PostItemsSoupAstData, PostItemsSoupAstError, PostItemsSoupAstErrors, PostItemsSoupAstGroupedData, PostItemsSoupAstGroupedError, PostItemsSoupAstGroupedErrors, PostItemsSoupAstGroupedResponse, PostItemsSoupAstGroupedResponses, PostItemsSoupAstResponse, PostItemsSoupAstResponses, PostItemsSoupData, PostItemsSoupError, PostItemsSoupErrors, PostItemsSoupResponse, PostItemsSoupResponses, PostMessage, PostMessageNotificationPolicy, PostSoupAstRequest, PostSoupRequest, PresaveDocumentHandlerData, PresaveDocumentHandlerError, PresaveDocumentHandlerErrors, PresaveDocumentHandlerResponse, PresaveDocumentHandlerResponses, PreSaveDocumentRequest, PreSaveDocumentResponse, PreSaveDocumentResponseData, PresenceOperator, PresignedUrl, PreviewSmartTagData, PreviewSmartTagError, PreviewSmartTagErrors, PreviewSmartTagResponse, PreviewSmartTagResponses, Project, ProjectDeleteResponseData, ProjectDocumentStatus, ProjectFilters, ProjectPreview, ProjectPreviewData, PropertyDefinition, PropertyDefinitionWithOptions, PropertyFilter, PropertyInput, PropertyOption, PropertyOptionValue, PropertyOwner, PropertyValue, PutCrmTeamSettingsData, PutCrmTeamSettingsError, PutCrmTeamSettingsErrors, PutCrmTeamSettingsResponse, PutCrmTeamSettingsResponses, PutCrmTeamStagesData, PutCrmTeamStagesError, PutCrmTeamStagesErrors, PutCrmTeamStagesResponse, PutCrmTeamStagesResponses, PutFormLayoutData, PutFormLayoutError, PutFormLayoutErrors, PutFormLayoutResponse, PutFormLayoutResponses, QueryCrmPipelineRowsData, QueryCrmPipelineRowsResponse, QueryCrmPipelineRowsResponses, QueryDefinition, QuestionLayout, QuestionOption, QuestionTally, ReactionInput, RecentlyDeletedData, RecentlyDeletedError, RecentlyDeletedErrors, RecentlyDeletedResponse, RecentlyDeletedResponseData, RecentlyDeletedResponses, RegisterSlackImportUploadsData, RegisterSlackImportUploadsErrors, RegisterSlackImportUploadsResponse, RegisterSlackImportUploadsResponses, RegisterUploads, RemoveBotFromChannelByBotData, RemoveBotFromChannelByBotError, RemoveBotFromChannelByBotErrors, RemoveBotFromChannelByBotResponse, RemoveBotFromChannelByBotResponses, RemoveFavoriteByEntityData, RemoveFavoriteByEntityError, RemoveFavoriteByEntityErrors, RemoveFavoriteByEntityResponses, RemoveParticipantsData, RemoveParticipantsError, RemoveParticipantsErrors, RemoveParticipantsRequest, RemoveParticipantsResponses, RemovePinHandlerData, RemovePinHandlerError, RemovePinHandlerErrors, RemovePinHandlerResponse, RemovePinHandlerResponses, RenameChannelLabelData, RenameChannelLabelError, RenameChannelLabelErrors, RenameChannelLabelRequest, RenameChannelLabelResponse, RenameChannelLabelResponses, RenameCrmPipelineData, RenameCrmPipelineResponse, RenameCrmPipelineResponses, RenamePipeline, ReorderFavoritesData, ReorderFavoritesError, ReorderFavoritesErrors, ReorderFavoritesRequest, ReorderFavoritesResponses, ReorderPinRequest, ReorderPinsHandlerData, ReorderPinsHandlerError, ReorderPinsHandlerErrors, ReorderPinsHandlerResponse, ReorderPinsHandlerResponses, ReplaceCrmStagesRequest, RequestedHarnessScope, RequestedLayout, ResetCrmTeamStagesData, ResetCrmTeamStagesError, ResetCrmTeamStagesErrors, ResetCrmTeamStagesResponse, ResetCrmTeamStagesResponses, ResponseStatus, ResponseSummary, RevertDeleteDocumentData, RevertDeleteDocumentError, RevertDeleteDocumentErrors, RevertDeleteDocumentResponse, RevertDeleteDocumentResponses, RevertDeleteProjectData, RevertDeleteProjectError, RevertDeleteProjectErrors, RevertDeleteProjectResponse, RevertDeleteProjectResponses, RingStatus, RingStatusResponse, RowChange, RowChangeKind, RowChanges, RowHistoryEntry, RowHistoryResponse, RowId, RowsChange, RowsResult, S3ObjectInfo, SaveBomPart, SaveDatabaseQueryData, SaveDatabaseQueryError, SaveDatabaseQueryErrors, SaveDatabaseQueryResponse, SaveDatabaseQueryResponses, SaveDocumentHandlerData, SaveDocumentHandlerError, SaveDocumentHandlerErrors, SaveDocumentHandlerResponse, SaveDocumentHandlerResponses, SaveDocumentRequest, SaveDocumentResponse, SaveDocumentResponseData, SavedQuery, SaveQueryRequest, SearchContactsData, SearchContactsError, SearchContactsErrors, SearchContactsResponse, SearchContactsResponse2, SearchContactsResponses, SearchState, SectionCount, SessionDeletedMetadata, SessionIdentity, SessionMentionedMetadata, SessionOpenedMetadata, SessionRenamedMetadata, SessionSettledMetadata, SessionStoppedMetadata, SetChannelLabelData, SetChannelLabelError, SetChannelLabelErrors, SetChannelLabelRequest, SetChannelLabelResponse, SetChannelLabelResponses, SetChannelPictureData, SetChannelPictureError, SetChannelPictureErrors, SetChannelPictureRequest, SetChannelPictureResponse, SetChannelPictureResponses, SetCompanyHiddenData, SetCompanyHiddenError, SetCompanyHiddenErrors, SetCompanyHiddenRequest, SetCompanyHiddenResponse, SetCompanyHiddenResponses, SetCompanyNameRequest, SetContactHiddenData, SetContactHiddenError, SetContactHiddenErrors, SetContactHiddenRequest, SetContactHiddenResponse, SetContactHiddenResponses, SetContactNameRequest, SetCrmCompanyNameData, SetCrmCompanyNameError, SetCrmCompanyNameErrors, SetCrmCompanyNameResponse, SetCrmCompanyNameResponses, SetCrmContactNameData, SetCrmContactNameError, SetCrmContactNameErrors, SetCrmContactNameResponse, SetCrmContactNameResponses, SetDocumentTeamShareData, SetDocumentTeamShareError, SetDocumentTeamShareErrors, SetDocumentTeamShareRequest, SetDocumentTeamShareResponse, SetDocumentTeamShareResponses, SetEmailFollowupData, SetEmailFollowupError, SetEmailFollowupErrors, SetEmailFollowupResponse, SetEmailFollowupResponses, SetEmailSyncData, SetEmailSyncError, SetEmailSyncErrors, SetEmailSyncRequest, SetEmailSyncResponse, SetEmailSyncResponses, SetOperator, SetPropertyValue, Sha256Digest, ShareCrmPipelineData, ShareCrmPipelineResponse, ShareCrmPipelineResponses, ShareDatabaseAwarenessData, ShareDatabaseAwarenessError, ShareDatabaseAwarenessErrors, ShareDatabaseAwarenessResponse, ShareDatabaseAwarenessResponses, SharedEmailFilter, SharePermissionV2, SharePipeline, ShortIdResponse, SimpleMention, SimpleSaveData, SimpleSaveError, SimpleSaveErrors, SimpleSaveResponse, SimpleSaveResponses, SkippedCell, SlackCompleteRequest, SlackCreateRequest, SlackRegisterRequest, SlackTimestamp, SlackUserId, SmartTagChannelMatch, SmartTagPreview, SortDirection, SortKey, SoupAgentSessionSoupPropertiesField, SoupApiItem, SoupApiSort, SoupApiSortDirection, SoupAttachment, SoupCalendarEventSoupPropertiesField, SoupCalendarEventTime, SoupCallRecordGuest, SoupCallRecordParticipant, SoupCallRecordSoupPropertiesField, SoupChannel, SoupChannelThread, SoupChatSoupPropertiesField, SoupContact, SoupCountedReaction, SoupCrmCompanySoupPropertiesField, SoupCrmContactSoupPropertiesField, SoupCrmDomain, SoupDatabaseRowSoupPropertiesField, SoupDocumentSoupPropertiesField, SoupDocumentSubType, SoupEmailThreadPreview, SoupEnrichedEmailThreadPreviewSoupPropertiesField, SoupForeignEntity, SoupInitiativeSoupPropertiesField, SoupItem, SoupLabel, SoupLabelListVisibility, SoupLabelType, SoupMessageAttachment, SoupMessageListVisibility, SoupMessageSender, SoupMessageSenderType, SoupPage, SoupProjectSoupPropertiesField, SoupPropertiesField, SoupProperty, SoupThreadInfo, SoupThreadReply, SourceBinding, SourceId, SourceIdentity, StarterDatabase, StarterDocumentsResponse, StorageRow, StorageRows, StorageRowsQuery, StoredGithubPullRequest, StreamEventsData, StreamEventsError, StreamEventsErrors, StreamEventsResponse, StreamEventsResponses, String, Submission, SubmissionOutcome, SubmitFormResponseData, SubmitFormResponseError, SubmitFormResponseErrors, SubmitFormResponseResponse, SubmitFormResponseResponses, SuccessResponse, SurfaceState, SyncServiceVersionId, SystemSkillSummary, Table, TableChange, TableChanged, TableChanges, TableDetail, TableResult, TableVersion, TagFilterMode, TakenId, TallyBucket, TallyValue, TaskFilters, TeamOutOfOfficeItem, TeamOutOfOfficeResponse, TeamRole, TextOperator, ThreadAnchor, ThreadOrigin, ThreadPatch, ThreadState, ToggleShareWithTeamData, ToggleShareWithTeamError, ToggleShareWithTeamErrors, ToggleShareWithTeamResponse, ToggleShareWithTeamResponses, TouchedColumn, TouchedRow, TranscribeDictationData, TranscribeDictationError, TranscribeDictationErrors, TranscribeDictationResponse, TranscribeDictationResponses, TranscribeResponse, TranscriptSegmentRequest, TrashCrmPipelineData, TrashCrmPipelineResponse, TrashCrmPipelineResponses, TrashPipeline, TurnEndedMetadata, TurnStartedMetadata, TurnSummary, TypedSuccessResponse, TypedSuccessResponseGetDocumentResponseData, TypingInput, UndoChangeResponse, UndoDatabaseChangeData, UndoDatabaseChangeError, UndoDatabaseChangeErrors, UndoDatabaseChangeResponse, UndoDatabaseChangeResponses, UndoOutcome, UndoRefusal, UnlockedBooking, UpdateAgentData, UpdateAgentError, UpdateAgentErrors, UpdateAgentRequest, UpdateAgentResponse, UpdateAgentResponses, UpdateChannelSharePermission, UpdateCrmTeamSettingsRequest, UpdateDatabasePermissionsData, UpdateDatabasePermissionsError, UpdateDatabasePermissionsErrors, UpdateDatabasePermissionsResponse, UpdateDatabasePermissionsResponses, UpdateForm, UpdateFormData, UpdateFormError, UpdateFormErrors, UpdateFormPermissionsData, UpdateFormPermissionsError, UpdateFormPermissionsErrors, UpdateFormPermissionsResponse, UpdateFormPermissionsResponses, UpdateFormResponse, UpdateFormResponses, UpdateInitiativeData, UpdateInitiativeError, UpdateInitiativeErrors, UpdateInitiativeRequest, UpdateInitiativeResponse, UpdateInitiativeResponses, UpdateMeetingRequest, UpdateOperation, UpdateSharePermissionRequestV2, UploadDescriptor, UploadDocumentStatus, UploadExtractFolderHandlerData, UploadExtractFolderHandlerError, UploadExtractFolderHandlerErrors, UploadExtractFolderHandlerResponse, UploadExtractFolderHandlerResponses, UploadExtractFolderRequest, UploadFolderHandlerData, UploadFolderHandlerError, UploadFolderHandlerErrors, UploadFolderHandlerResponse, UploadFolderHandlerResponses, UploadFolderRequest, UploadGrant, UploadId, UpsertHistoryHandlerData, UpsertHistoryHandlerError, UpsertHistoryHandlerErrors, UpsertHistoryHandlerResponse, UpsertHistoryHandlerResponses, UpsertUserDocumentViewLocationData, UpsertUserDocumentViewLocationError, UpsertUserDocumentViewLocationErrors, UpsertUserDocumentViewLocationRequest, UpsertUserDocumentViewLocationResponse, UpsertUserDocumentViewLocationResponses, UserApiKeyId, UserApiKeyInfo, UserApiKeysList, UserDocumentsResponse, UserDocumentViewLocation, UserDocumentViewLocationResponse, UserPinsResponse, UserViewsResponse, ValidateDocumentPermissionsTokenData, ValidateDocumentPermissionsTokenError, ValidateDocumentPermissionsTokenErrors, ValidateDocumentPermissionsTokenResponse, ValidateDocumentPermissionsTokenResponses, ValidateWebhookData, ValidateWebhookError, ValidateWebhookErrors, ValidateWebhookResponse, ValidateWebhookResponse2, ValidateWebhookResponses, Vec, VersionedTable, View, ViewChange, ViewColumn, ViewLayout, ViewPatch, ViewPosition, ViewPositionsResponse, ViewQuery, ViewResult, ViewsResponse, WaitingForInputMetadata, Webhook, WebhookEvent, WebhookFilter, WebhookScope, WebhookStatus, WebhookValidationTestEvent, Widget, WithCallId, WithChannelId, WithDocumentId, WithProjectId } from './types.gen';+export type { AccessiblePipeline, AccessLevel, ActiveCallsResponse, ActiveCallSummary, ActiveMeeting, ActiveMeetingsResponse, ActivityType, AddFavoriteData, AddFavoriteError, AddFavoriteErrors, AddFavoriteRequest, AddFavoriteResponse, AddFavoriteResponses, AddParticipantsData, AddParticipantsError, AddParticipantsErrors, AddParticipantsRequest, AddParticipantsResponses, AddPinHandlerData, AddPinHandlerError, AddPinHandlerErrors, AddPinHandlerResponse, AddPinHandlerResponses, AddPinRequest, Agent, AgentActionId, AgentChannelScope, AgentMcpServer, AgentMcpServers, AgentPullRequestState, AgentSessionFilters, AgentSessionLifecycleEvent, Anchor, AnchorId, AnchorResponse, AnnotationIncrementalUpdate, Answer, ApiActivity, ApiAttachmentChannelReference, ApiAttachmentEntityReference, ApiAttachmentGenericReference, ApiChannelAttachment, ApiChannelAttachmentsPage, ApiChannelDetail, ApiChannelListMessage, ApiChannelListPage, ApiChannelListParticipant, ApiChannelListType, ApiChannelParticipant, ApiChannelWithLatest, ApiEntityFilterAst, ApiGroupByField, ApiGroupMeta, ApiParticipantListRole, ApiParticipantRole, ApiPropertyEntityType, AppliedOps, ApplyCrmPipelineOpsData, ApplyCrmPipelineOpsResponse, ApplyCrmPipelineOpsResponses, ApplyDatabaseOpsData, ApplyDatabaseOpsError, ApplyDatabaseOpsErrors, ApplyDatabaseOpsResponse, ApplyDatabaseOpsResponses, ApplyOpsRequest, ApplyOpsResponse, ApproveHarnessPairingData, ApproveHarnessPairingError, ApproveHarnessPairingErrors, ApproveHarnessPairingResponse, ApproveHarnessPairingResponses, ApprovePairingRequest, AttachmentChange, AttendeeResponseStatus, Audience, Awareness, AwarenessRelay, BasicDocument, BasicDocumentSubType, BomPart, BookingTarget, Bot, BotChannel, BotChannelType, BotId, BotKind, BotOwner, BotOwnerProfile, BotSenderProfile, BotToken, BranchNameResponse, BTreeMap, BulkWakeupRequest, BulkWakeupResponse, BulkWakeupSyncServiceDocumentsData, BulkWakeupSyncServiceDocumentsErrors, BulkWakeupSyncServiceDocumentsResponse, BulkWakeupSyncServiceDocumentsResponses, CalendarAttendee, CalendarEvent, CalendarEventFilters, CalendarEventSourceContent, CalendarMentionEvent, CalendarMentionPreviewItem, CalendarMentionPreviewKind, CalendarMentionPreviewRequest, CalendarMentionPreviewRequestItem, CalendarMentionPreviewResponse, CalendarOccurrence, CalendarOccurrenceItem, CalendarOccurrenceResponse, CalendarSyncStatus, CallActiveResponse, CallFilters, CallRecord, CallRecordGuest, CallRecordParticipant, CallRecordPreview, CallRecordPreviewData, CallRecordTranscriptSegment, CallStatus, CallTokenResponse, CallWebhookData, CallWebhookError, CallWebhookErrors, CallWebhookResponses, CancelSlackImportData, CancelSlackImportErrors, CancelSlackImportResponse, CancelSlackImportResponses, CardPosition, CastVerdict, CellValue, CellWrite, ChangedFileDto, ChangesetDto, ChangesetSourceDto, Channel, ChannelCreatedMetadata, ChannelDeletedMetadata, ChannelFilters, ChannelJoinCodeResponse, ChannelLabel, ChannelLabelRule, ChannelLabelsList, ChannelMessage, ChannelParticipant, ChannelParticipantAddedMetadata, ChannelParticipantRemovedMetadata, ChannelPreview, ChannelPreviewData, ChannelSender, ChannelSharePermission, ChannelThreadFilters, ChannelTopicEvent, ChannelType, ChannelUpdatedMetadata, ChannelWebhookRequest, ChannelWebhookResponse, ChannelWithParticipants, Chat, ChatFilters, CheckActiveCallData, CheckActiveCallError, CheckActiveCallErrors, CheckActiveCallResponse, CheckActiveCallResponses, ClaimedPairing, ClaimHarnessPairingData, ClaimHarnessPairingError, ClaimHarnessPairingErrors, ClaimHarnessPairingResponse, ClaimHarnessPairingResponses, ClaimPairingRequest, ClientOptions, CloudStorageItemType, CollaborateFormData, CollaborateFormError, CollaborateFormErrors, CollaborateFormResponse, CollaborateFormResponses, CollabSurfaceResponse, CollabSurfaceTokenResponse, Column, ColumnCast, ColumnChange, ColumnChangeKind, ColumnConfig, ColumnConversion, ColumnConversionRequest, ColumnDetail, ColumnKind, ColumnProtection, ColumnResult, CommandFailure, CommandRejectedMetadata, CommittedChange, CompleteSlackImportUploadsData, CompleteSlackImportUploadsErrors, CompleteSlackImportUploadsResponse, CompleteSlackImportUploadsResponses, CompleteUploads, ConferenceProvider, Conjunction, ConversationId, ConversationKind, ConversationMetadata, ConversationProgress, ConversationSeal, ConversationStatus, ConvertDatabaseColumnData, ConvertDatabaseColumnError, ConvertDatabaseColumnErrors, ConvertDatabaseColumnResponse, ConvertDatabaseColumnResponses, ConvertedCell, CopyDocumentData, CopyDocumentError, CopyDocumentErrors, CopyDocumentQueryParams, CopyDocumentRequest, CopyDocumentResponse, CopyDocumentResponse2, CopyDocumentResponses, CountedReaction, CreateAgentData, CreateAgentError, CreateAgentErrors, CreateAgentRequest, CreateAgentResponse, CreateAgentResponses, CreateAnchorData, CreateAnchorError, CreateAnchorErrors, CreateAnchorResponse, CreateAnchorResponses, CreateBotRequest, CreateBulkDocumentResponse, CreateBulkDocumentResponseData, CreateChannelData, CreateChannelError, CreateChannelErrors, CreateChannelLabelData, CreateChannelLabelError, CreateChannelLabelErrors, CreateChannelLabelRequest, CreateChannelLabelResponse, CreateChannelLabelResponses, CreateChannelRequest, CreateChannelResponse, CreateChannelResponse2, CreateChannelResponses, CreateChannelScopedBotData, CreateChannelScopedBotError, CreateChannelScopedBotErrors, CreateChannelScopedBotRequest, CreateChannelScopedBotResponse, CreateChannelScopedBotResponse2, CreateChannelScopedBotResponses, CreateCollabSurfaceTokenData, CreateCollabSurfaceTokenError, CreateCollabSurfaceTokenErrors, CreateCollabSurfaceTokenResponse, CreateCollabSurfaceTokenResponses, CreateCrmCompanyData, CreateCrmCompanyError, CreateCrmCompanyErrors, CreateCrmCompanyRequest, CreateCrmCompanyResponse, CreateCrmCompanyResponses, CreateCrmContactData, CreateCrmContactError, CreateCrmContactErrors, CreateCrmContactRequest, CreateCrmContactResponse, CreateCrmContactResponses, CreateCrmPipelineData, CreateCrmPipelineResponse, CreateCrmPipelineResponses, CreateDatabaseData, CreateDatabaseError, CreateDatabaseErrors, CreateDatabaseRequest, CreateDatabaseResponse, CreateDatabaseResponses, CreateDocumentData, CreateDocumentError, CreateDocumentErrors, CreateDocumentRequest, CreateDocumentResponse, CreateDocumentResponseData, CreateDocumentResponses, CreatedPairing, CreatedUserApiKey, CreateEntityMentionData, CreateEntityMentionError, CreateEntityMentionErrors, CreateEntityMentionRequest, CreateEntityMentionResponse, CreateEntityMentionResponse2, CreateEntityMentionResponses, CreateForm, CreateFormData, CreateFormError, CreateFormErrors, CreateFormResponse, CreateFormResponses, CreateHarnessPairingData, CreateHarnessPairingError, CreateHarnessPairingErrors, CreateHarnessPairingResponse, CreateHarnessPairingResponses, CreateImport, CreateInitiativeData, CreateInitiativeError, CreateInitiativeErrors, CreateInitiativeRequest, CreateInitiativeResponse, CreateInitiativeResponses, CreateInstructionsDocumentResponse, CreateInstructionsHandlerData, CreateInstructionsHandlerError, CreateInstructionsHandlerErrors, CreateInstructionsHandlerResponse, CreateInstructionsHandlerResponses, CreateMarkdownDocumentRequest, CreateMarkdownDocumentResponse, CreateMarkdownHandlerData, CreateMarkdownHandlerError, CreateMarkdownHandlerErrors, CreateMarkdownHandlerResponse, CreateMarkdownHandlerResponses, CreateMeetingRequest, CreatePairingRequest, CreatePipeline, CreateProjectHandlerData, CreateProjectHandlerError, CreateProjectHandlerErrors, CreateProjectHandlerResponse, CreateProjectHandlerResponses, CreateProjectRequest, CreateProjectResponse, CreateSkillHandlerData, CreateSkillHandlerError, CreateSkillHandlerErrors, CreateSkillHandlerResponse, CreateSkillHandlerResponses, CreateSkillRequest, CreateSkillResponse, CreateSlackImportData, CreateSlackImportErrors, CreateSlackImportResponse, CreateSlackImportResponses, CreateSnippetHandlerData, CreateSnippetHandlerError, CreateSnippetHandlerErrors, CreateSnippetHandlerResponse, CreateSnippetHandlerResponses, CreateSnippetRequest, CreateSnippetResponse, CreateTaskHandlerData, CreateTaskHandlerError, CreateTaskHandlerErrors, CreateTaskHandlerResponse, CreateTaskHandlerResponses, CreateTaskRequest, CreateTaskResponse, CreateToken, CreateUnthreadedAnchorRequest, CreateUnthreadedAnchorResponse, CreateUnthreadedPdfAnchorRequest, CreateUserApiKeyData, CreateUserApiKeyError, CreateUserApiKeyErrors, CreateUserApiKeyRequest, CreateUserApiKeyResponse, CreateUserApiKeyResponses, CreateViewHandlerData, CreateViewHandlerError, CreateViewHandlerErrors, CreateViewHandlerResponse, CreateViewHandlerResponses, CreateViewRequest, CreateWebhookData, CreateWebhookError, CreateWebhookErrors, CreateWebhookRequest, CreateWebhookResponse, CreateWebhookResponse2, CreateWebhookResponses, CrmCompanyFilters, CrmCompanyResponse, CrmContactResponse, CrmDomainResponse, CrmPermissionRole, CrmStageInput, CrmStageResponse, CrmStagesResponse, CrmTeamSettingsResponse, CustomSpeakerAssignment, Database, DatabaseDetail, DatabaseOp, DatabaseView, DataType, DateOperator, DeleteAnchorData, DeleteAnchorError, DeleteAnchorErrors, DeleteAnchorResponse, DeleteAnchorResponses, DeleteCallRecordData, DeleteCallRecordError, DeleteCallRecordErrors, DeleteCallRecordResponse, DeleteCallRecordResponses, DeleteChannelData, DeleteChannelError, DeleteChannelErrors, DeleteChannelLabelData, DeleteChannelLabelError, DeleteChannelLabelErrors, DeleteChannelLabelResponse, DeleteChannelLabelResponses, DeleteChannelResponse, DeleteChannelResponses, DeleteCollabSurfaceData, DeleteCollabSurfaceError, DeleteCollabSurfaceErrors, DeleteCollabSurfaceResponse, DeleteCollabSurfaceResponses, DeleteDocumentData, DeleteDocumentError, DeleteDocumentErrors, DeleteDocumentResponse, DeleteDocumentResponses, DeleteEntityMentionData, DeleteEntityMentionError, DeleteEntityMentionErrors, DeleteEntityMentionResponse, DeleteEntityMentionResponse2, DeleteEntityMentionResponses, DeleteHarnessData, DeleteHarnessError, DeleteHarnessErrors, DeleteHarnessResponse, DeleteHarnessResponses, DeleteHistoryHandlerData, DeleteHistoryHandlerError, DeleteHistoryHandlerErrors, DeleteHistoryHandlerResponse, DeleteHistoryHandlerResponses, DeleteInitiativeData, DeleteInitiativeError, DeleteInitiativeErrors, DeleteInitiativeResponse, DeleteInitiativeResponses, DeleteProjectHandlerData, DeleteProjectHandlerError, DeleteProjectHandlerErrors, DeleteProjectHandlerResponse, DeleteProjectHandlerResponses, DeleteSelfHarnessData, DeleteSelfHarnessError, DeleteSelfHarnessErrors, DeleteSelfHarnessResponse, DeleteSelfHarnessResponses, DeleteUnthreadedAnchorRequest, DeleteUnthreadedAnchorResponse, DeleteUnthreadedPdfAnchorRequest, DeleteUserApiKeyData, DeleteUserApiKeyError, DeleteUserApiKeyErrors, DeleteUserApiKeyResponse, DeleteUserApiKeyResponses, DeleteUserDocumentViewLocationData, DeleteUserDocumentViewLocationError, DeleteUserDocumentViewLocationErrors, DeleteUserDocumentViewLocationResponse, DeleteUserDocumentViewLocationResponses, DeleteViewHandlerData, DeleteViewHandlerError, DeleteViewHandlerErrors, DeleteViewHandlerResponses, DeleteWebhookData, DeleteWebhookError, DeleteWebhookErrors, DeleteWebhookResponse, DeleteWebhookResponses, DocumentBasic, DocumentContent, DocumentContentLocation, DocumentContentState, DocumentContentUploadedMetadata, DocumentCopiedMetadata, DocumentCreatedMetadata, DocumentDeletedMetadata, DocumentFilters, DocumentId, DocumentInteractionMetadata, DocumentMetadata, DocumentMetadataWithContent, DocumentPermissionsToken, DocumentPermissionsTokenRequest, DocumentPermissionsTokenResponse, DocumentPreview, DocumentPreviewData, DocumentPreviewDataSubType, DocumentPurgedMetadata, DocumentResponse, DocumentResponseMetadata, DocumentResponseMetadataWithContent, DocumentStorageServiceApiVersion, DocumentSubType, DocumentSyncContentUpdatedMetadata, DocumentSyncEditor, DocumentTeamShareResponse, DocumentTopicEvent, DocumentUpdatedMetadata, EditAnchorData, EditAnchorError, EditAnchorErrors, EditAnchorRequest, EditAnchorResponse, EditAnchorResponse2, EditAnchorResponses, EditCallRecordData, EditCallRecordError, EditCallRecordErrors, EditCallRecordRequest, EditCallRecordResponse, EditCallRecordResponses, EditCallTranscriptData, EditCallTranscriptError, EditCallTranscriptErrors, EditCallTranscriptRequest, EditCallTranscriptResponse, EditCallTranscriptResponses, EditDocumentData, EditDocumentError, EditDocumentErrors, EditDocumentResponse, EditDocumentResponse2, EditDocumentResponses, EditDocumentServiceArgs, EditMyFormResponseData, EditMyFormResponseError, EditMyFormResponseErrors, EditMyFormResponseResponse, EditMyFormResponseResponses, EditPdfAnchorRequest, EditPdfPlaceableCommentAnchorRequest, EditProjectV2Data, EditProjectV2Error, EditProjectV2Errors, EditProjectV2Response, EditProjectV2Responses, EditThreadV2Data, EditThreadV2Error, EditThreadV2Errors, EditThreadV2Response, EditThreadV2Responses, EmailFilters, EmailFollowup, EmailFollowupCommand, EmailFollowupResponse, EmailReminderCondition, EmailReminderPage, EmailReminderSummary, EmptyResponse, EnsureCollabSurfaceData, EnsureCollabSurfaceError, EnsureCollabSurfaceErrors, EnsureCollabSurfaceRequest, EnsureCollabSurfaceResponse, EnsureCollabSurfaceResponses, EnsureStarterHandlerData, EnsureStarterHandlerErrors, EnsureStarterHandlerResponse, EnsureStarterHandlerResponses, EntityFilters, EntityKind, EntityMessageCreateData, EntityMessageCreateResponse, EntityMessageCreateResponses, EntityMessageDeleteMessageData, EntityMessageDeleteMessageResponse, EntityMessageDeleteMessageResponses, EntityMessageDeleteThreadData, EntityMessageDeleteThreadResponse, EntityMessageDeleteThreadResponses, EntityMessageEditData, EntityMessageEditResponse, EntityMessageEditResponses, EntityMessageGetMessageData, EntityMessageGetMessageResponse, EntityMessageGetMessageResponses, EntityMessageGetThreadData, EntityMessageGetThreadResponse, EntityMessageGetThreadResponses, EntityMessageLegacyData, EntityMessageLegacyResponse, EntityMessageLegacyResponses, EntityMessagePatchThreadData, EntityMessagePatchThreadResponse, EntityMessagePatchThreadResponses, EntityMessageReactData, EntityMessageReactResponse, EntityMessageReactResponses, EntityMessageTypingData, EntityMessageTypingResponse, EntityMessageTypingResponses, EntityPermission, EntityPermissionResponse, EntityRef, EntityReference, EntityType, ErrorResponse, EventReminderOverride, EventReminders, EventStatus, EventTime, EventTransparency, EventType, EventVisibility, ExcludedDefaultView, ExcludeDefaultViewHandlerData, ExcludeDefaultViewHandlerError, ExcludeDefaultViewHandlerErrors, ExcludeDefaultViewHandlerResponses, ExcludeDefaultViewRequest, ExportDocumentData, ExportDocumentError, ExportDocumentErrors, ExportDocumentResponse, ExportDocumentResponse2, ExportDocumentResponses, Favorite, FavoriteEntityRef, FavoritesList, FileChangeKindDto, FileSystemNodeWithIds, FileType, FileTypeUpdate, FilterCondition, FilterGroup, FilterNode, FilterTest, FinalizeSlackImportData, FinalizeSlackImportErrors, FinalizeSlackImportResponse, FinalizeSlackImportResponses, FolderItem, FollowupState, ForeignEntity, ForeignEntityFilters, Form, FormAccess, FormCollaboration, FormDetail, FormErrorCode, FormErrorResponse, FormLayout, FormPublicationProblem, FormQuestionDetail, FormResponse, FormSection, FormSectionDetail, FormSource, FormStatus, FormTally, GenericErrorResponse, GenericResponse, GenericSuccessResponse, GetActiveCallsData, GetActiveCallsError, GetActiveCallsErrors, GetActiveCallsResponse, GetActiveCallsResponses, GetActivityData, GetActivityError, GetActivityErrors, GetActivityResponse, GetActivityResponses, GetAttachmentReferencesData, GetAttachmentReferencesError, GetAttachmentReferencesErrors, GetAttachmentReferencesResponse, GetAttachmentReferencesResponse2, GetAttachmentReferencesResponses, GetBatchCallRecordPreviewData, GetBatchCallRecordPreviewError, GetBatchCallRecordPreviewErrors, GetBatchCallRecordPreviewRequest, GetBatchCallRecordPreviewResponse, GetBatchCallRecordPreviewResponse2, GetBatchCallRecordPreviewResponses, GetBatchChannelPreviewData, GetBatchChannelPreviewError, GetBatchChannelPreviewErrors, GetBatchChannelPreviewRequest, GetBatchChannelPreviewResponse, GetBatchChannelPreviewResponse2, GetBatchChannelPreviewResponses, GetBatchPreviewHandlerData, GetBatchPreviewHandlerError, GetBatchPreviewHandlerErrors, GetBatchPreviewHandlerResponse, GetBatchPreviewHandlerResponses, GetBatchPreviewRequest, GetBatchPreviewResponse, GetBatchProjectPreviewData, GetBatchProjectPreviewError, GetBatchProjectPreviewErrors, GetBatchProjectPreviewRequest, GetBatchProjectPreviewResponse, GetBatchProjectPreviewResponse2, GetBatchProjectPreviewResponses, GetBotOwnerProfilesData, GetBotOwnerProfilesError, GetBotOwnerProfilesErrors, GetBotOwnerProfilesResponse, GetBotOwnerProfilesResponses, GetCallRecordData, GetCallRecordError, GetCallRecordErrors, GetCallRecordResponse, GetCallRecordResponses, GetChannelAttachmentsData, GetChannelAttachmentsError, GetChannelAttachmentsErrors, GetChannelAttachmentsResponse, GetChannelAttachmentsResponses, GetChannelData, GetChannelError, GetChannelErrors, GetChannelJoinLinkData, GetChannelJoinLinkError, GetChannelJoinLinkErrors, GetChannelJoinLinkResponse, GetChannelJoinLinkResponses, GetChannelParticipantsData, GetChannelParticipantsError, GetChannelParticipantsErrors, GetChannelParticipantsResponse, GetChannelParticipantsResponses, GetChannelResponse, GetChannelResponses, GetChannelsData, GetChannelsError, GetChannelsErrors, GetChannelsResponse, GetChannelsResponses, GetCollabSurfaceData, GetCollabSurfaceError, GetCollabSurfaceErrors, GetCollabSurfaceResponse, GetCollabSurfaceResponses, GetCompanyData, GetCompanyError, GetCompanyErrors, GetCompanyResponse, GetCompanyResponses, GetContactByEmailData, GetContactByEmailError, GetContactByEmailErrors, GetContactByEmailResponse, GetContactByEmailResponse2, GetContactByEmailResponses, GetContactData, GetContactError, GetContactErrors, GetContactResponse, GetContactResponses, GetCrmPipelineData, GetCrmPipelineResponse, GetCrmPipelineResponses, GetCrmPipelineRowsData, GetCrmPipelineRowsResponse, GetCrmPipelineRowsResponses, GetCrmPipelineTableData, GetCrmPipelineTableResponse, GetCrmPipelineTableResponses, GetCrmTeamSettingsData, GetCrmTeamSettingsError, GetCrmTeamSettingsErrors, GetCrmTeamSettingsResponse, GetCrmTeamSettingsResponses, GetDatabaseData, GetDatabaseError, GetDatabaseErrors, GetDatabasePermissionsData, GetDatabasePermissionsError, GetDatabasePermissionsErrors, GetDatabasePermissionsResponse, GetDatabasePermissionsResponses, GetDatabaseQueryData, GetDatabaseQueryError, GetDatabaseQueryErrors, GetDatabaseQueryResponse, GetDatabaseQueryResponses, GetDatabaseResponse, GetDatabaseResponses, GetDatabaseRowHistoryData, GetDatabaseRowHistoryError, GetDatabaseRowHistoryErrors, GetDatabaseRowHistoryResponse, GetDatabaseRowHistoryResponses, GetDatabaseTableChangesData, GetDatabaseTableChangesError, GetDatabaseTableChangesErrors, GetDatabaseTableChangesResponse, GetDatabaseTableChangesResponses, GetDatabaseViewPositionsData, GetDatabaseViewPositionsError, GetDatabaseViewPositionsErrors, GetDatabaseViewPositionsResponse, GetDatabaseViewPositionsResponses, GetDocumentAnchorsData, GetDocumentAnchorsError, GetDocumentAnchorsErrors, GetDocumentAnchorsResponse, GetDocumentAnchorsResponses, GetDocumentBranchNameData, GetDocumentBranchNameError, GetDocumentBranchNameErrors, GetDocumentBranchNameResponse, GetDocumentBranchNameResponses, GetDocumentByTeamSlugData, GetDocumentByTeamSlugError, GetDocumentByTeamSlugErrors, GetDocumentByTeamSlugResponse, GetDocumentByTeamSlugResponses, GetDocumentData, GetDocumentError, GetDocumentErrors, GetDocumentGithubPullRequestsData, GetDocumentGithubPullRequestsError, GetDocumentGithubPullRequestsErrors, GetDocumentGithubPullRequestsResponse, GetDocumentGithubPullRequestsResponses, GetDocumentKeyResponse, GetDocumentKeyResponseData, GetDocumentListHandlerData, GetDocumentListHandlerError, GetDocumentListHandlerErrors, GetDocumentListHandlerResponse, GetDocumentListHandlerResponses, GetDocumentListResult, GetDocumentLocationV3Data, GetDocumentLocationV3Error, GetDocumentLocationV3Errors, GetDocumentLocationV3Response, GetDocumentLocationV3Responses, GetDocumentPermissionsResponseDataV2, GetDocumentPermissionsTokenData, GetDocumentPermissionsTokenError, GetDocumentPermissionsTokenErrors, GetDocumentPermissionsTokenResponse, GetDocumentPermissionsTokenResponses, GetDocumentPermissionsV2Data, GetDocumentPermissionsV2Error, GetDocumentPermissionsV2Errors, GetDocumentPermissionsV2Response, GetDocumentPermissionsV2Responses, GetDocumentProcessingResult, GetDocumentProcessingResultData, GetDocumentProcessingResultError, GetDocumentProcessingResultErrors, GetDocumentProcessingResultResponse, GetDocumentProcessingResultResponse2, GetDocumentProcessingResultResponses, GetDocumentResponse, GetDocumentResponse2, GetDocumentResponseData, GetDocumentResponses, GetDocumentSearchResponse, GetDocumentShortIdData, GetDocumentShortIdError, GetDocumentShortIdErrors, GetDocumentShortIdResponse, GetDocumentShortIdResponses, GetDocumentsResponse, GetDocumentTeamShareData, GetDocumentTeamShareError, GetDocumentTeamShareErrors, GetDocumentTeamShareResponse, GetDocumentTeamShareResponses, GetDocumentUserAccessLevelResponse, GetDocumentVersionData, GetDocumentVersionError, GetDocumentVersionErrors, GetDocumentVersionResponse, GetDocumentVersionResponses, GetDocumentViewsHandlerData, GetDocumentViewsHandlerError, GetDocumentViewsHandlerErrors, GetDocumentViewsHandlerResponse, GetDocumentViewsHandlerResponses, GetEmailFollowupData, GetEmailFollowupError, GetEmailFollowupErrors, GetEmailFollowupResponse, GetEmailFollowupResponses, GetEntityPermissionData, GetEntityPermissionErrors, GetEntityPermissionResponse, GetEntityPermissionResponses, GetForeignEntityBySourceData, GetForeignEntityBySourceError, GetForeignEntityBySourceErrors, GetForeignEntityBySourceResponse, GetForeignEntityBySourceResponses, GetForeignEntityData, GetForeignEntityError, GetForeignEntityErrors, GetForeignEntityResponse, GetForeignEntityResponses, GetFormData, GetFormError, GetFormErrors, GetFormPermissionsData, GetFormPermissionsError, GetFormPermissionsErrors, GetFormPermissionsResponse, GetFormPermissionsResponses, GetFormResponse, GetFormResponses, GetFormResponseSummaryData, GetFormResponseSummaryError, GetFormResponseSummaryErrors, GetFormResponseSummaryResponse, GetFormResponseSummaryResponses, GetFormTallyData, GetFormTallyError, GetFormTallyErrors, GetFormTallyResponse, GetFormTallyResponses, GetGithubPullRequestChangesData, GetGithubPullRequestChangesError, GetGithubPullRequestChangesErrors, GetGithubPullRequestChangesPatchData, GetGithubPullRequestChangesPatchError, GetGithubPullRequestChangesPatchErrors, GetGithubPullRequestChangesPatchResponse, GetGithubPullRequestChangesPatchResponses, GetGithubPullRequestChangesResponse, GetGithubPullRequestChangesResponses, GetGithubPullRequestData, GetGithubPullRequestError, GetGithubPullRequestErrors, GetGithubPullRequestFacetsData, GetGithubPullRequestFacetsError, GetGithubPullRequestFacetsErrors, GetGithubPullRequestFacetsResponse, GetGithubPullRequestFacetsResponses, GetGithubPullRequestResponse, GetGithubPullRequestResponses, GetGithubPullRequestTasksData, GetGithubPullRequestTasksError, GetGithubPullRequestTasksErrors, GetGithubPullRequestTasksResponse, GetGithubPullRequestTasksResponses, GetHarnessPairingData, GetHarnessPairingError, GetHarnessPairingErrors, GetHarnessPairingResponse, GetHarnessPairingResponses, GetHistoryHandlerData, GetHistoryHandlerError, GetHistoryHandlerErrors, GetHistoryHandlerResponse, GetHistoryHandlerResponses, GetInitiativeData, GetInitiativeError, GetInitiativeErrors, GetInitiativeResponse, GetInitiativeResponses, GetInstructionsDocumentResponse, GetInstructionsHandlerData, GetInstructionsHandlerError, GetInstructionsHandlerErrors, GetInstructionsHandlerResponse, GetInstructionsHandlerResponses, GetItemsSoupData, GetItemsSoupError, GetItemsSoupErrors, GetItemsSoupResponse, GetItemsSoupResponses, GetLocationHandlerData, GetLocationHandlerError, GetLocationHandlerErrors, GetLocationHandlerResponse, GetLocationHandlerResponses, GetMyFormResponseData, GetMyFormResponseError, GetMyFormResponseErrors, GetMyFormResponseResponse, GetMyFormResponseResponses, GetOrCreateAction, GetOrCreateCallData, GetOrCreateCallError, GetOrCreateCallErrors, GetOrCreateCallResponse, GetOrCreateCallResponses, GetOrCreateChannelResponse, GetOrCreateDmData, GetOrCreateDmError, GetOrCreateDmErrors, GetOrCreateDmRequest, GetOrCreateDmResponse, GetOrCreateDmResponses, GetOrCreatePrivateData, GetOrCreatePrivateError, GetOrCreatePrivateErrors, GetOrCreatePrivateRequest, GetOrCreatePrivateResponse, GetOrCreatePrivateResponses, GetPendingProjectsHandlerData, GetPendingProjectsHandlerError, GetPendingProjectsHandlerErrors, GetPendingProjectsHandlerResponse, GetPendingProjectsHandlerResponses, GetPinsHandlerData, GetPinsHandlerError, GetPinsHandlerErrors, GetPinsHandlerResponse, GetPinsHandlerResponses, GetPinsResponse, GetProjectContentHandlerData, GetProjectContentHandlerError, GetProjectContentHandlerErrors, GetProjectContentHandlerResponse, GetProjectContentHandlerResponses, GetProjectContentResponse, GetProjectHandlerData, GetProjectHandlerError, GetProjectHandlerErrors, GetProjectHandlerResponse, GetProjectHandlerResponses, GetProjectPermissionsV2Data, GetProjectPermissionsV2Error, GetProjectPermissionsV2Errors, GetProjectPermissionsV2Response, GetProjectPermissionsV2Responses, GetProjectResponse, GetProjectResponseData, GetProjectsHandlerData, GetProjectsHandlerError, GetProjectsHandlerErrors, GetProjectsHandlerResponse, GetProjectsHandlerResponses, GetProjectsResponse, GetProjectUserAccessLevelData, GetProjectUserAccessLevelError, GetProjectUserAccessLevelErrors, GetProjectUserAccessLevelResponse, GetProjectUserAccessLevelResponses, GetRingStatusData, GetRingStatusError, GetRingStatusErrors, GetRingStatusResponse, GetRingStatusResponses, GetSelfBotData, GetSelfBotError, GetSelfBotErrors, GetSelfBotResponse, GetSelfBotResponses, GetSelfHarnessData, GetSelfHarnessError, GetSelfHarnessErrors, GetSelfHarnessResponse, GetSelfHarnessResponses, GetSlackImportData, GetSlackImportErrors, GetSlackImportResponse, GetSlackImportResponses, GetSystemSkillsHandlerData, GetSystemSkillsHandlerError, GetSystemSkillsHandlerErrors, GetSystemSkillsHandlerResponse, GetSystemSkillsHandlerResponses, GetUserDocumentsHandlerData, GetUserDocumentsHandlerError, GetUserDocumentsHandlerErrors, GetUserDocumentsHandlerResponse, GetUserDocumentsHandlerResponses, GetUserDocumentViewLocationData, GetUserDocumentViewLocationError, GetUserDocumentViewLocationErrors, GetUserDocumentViewLocationResponse, GetUserDocumentViewLocationResponses, GetUserHistoryResponse, GetViewsHandlerData, GetViewsHandlerError, GetViewsHandlerErrors, GetViewsHandlerResponse, GetViewsHandlerResponses, GetWebhookData, GetWebhookError, GetWebhookErrors, GetWebhookResponse, GetWebhookResponses, GithubLabelFacet, GithubPullRequest, GithubPullRequestChangesPatchResponse, GithubPullRequestChangesResponse, GithubPullRequestCheckRun, GithubPullRequestComment, GithubPullRequestFacets, GithubPullRequestLabel, GithubPullRequestReview, GithubPullRequestReviewDecision, GithubPullRequestReviewState, GithubPullRequestsResponse, GithubPullRequestTasks, GithubPullRequestTasksRequest, GithubPullRequestTasksResponse, GithubPullRequestUser, GithubRepositoryFacet, GithubUserFacet, GitRefDto, GroupedInitialParams, GroupedPageParams, GroupedSoupGroupPage, GroupedSoupInitialPage, GroupedSoupPage, GroupedSoupSort, GuestId, GuestJoinRequest, HandlerData, HandlerError, HandlerErrors, HandlerResponse, HandlerResponses, Harness, HarnessAgent, HarnessId, HarnessOwner, HarnessSession, HashMap, HealthHandlerData, HealthHandlerResponse, HealthHandlerResponses, HighlightType, ImportCounters, ImportDatabaseTableData, ImportDatabaseTableError, ImportDatabaseTableErrors, ImportDatabaseTableResponse, ImportDatabaseTableResponses, ImportedAuthor, ImportError, ImportLimits, ImportPage, ImportProgress, ImportTable, ImportWarning, InferColumnTypeOutcome, InferColumnTypeRequest, InferDatabaseColumnTypeData, InferDatabaseColumnTypeError, InferDatabaseColumnTypeErrors, InferDatabaseColumnTypeResponse, InferDatabaseColumnTypeResponses, InFlightTurnSummary, IngestTranscriptData, IngestTranscriptError, IngestTranscriptErrors, IngestTranscriptResponses, InitializeUserDocumentsData, InitializeUserDocumentsError, InitializeUserDocumentsErrors, InitializeUserDocumentsResponse, InitializeUserDocumentsResponses, InitialPropertyValue, InitiativeDetail, InitiativeFilters, InitiativeId, InitiativeList, InitiativeSummary, InputReceivedMetadata, InstallSyncData, InstallSyncErrors, InteractionReason, InviteMeetingRequest, InviteMeetingUsersRequest, Item, ItemWithUserAccessLevel, JobId, JobProcessingResultHandlerData, JobProcessingResultHandlerError, JobProcessingResultHandlerErrors, JobProcessingResultHandlerResponse, JobProcessingResultHandlerResponses, JobStatus, JoinChannelByCodeData, JoinChannelByCodeError, JoinChannelByCodeErrors, JoinChannelByCodeResponses, JoinChannelData, JoinChannelError, JoinChannelErrors, JoinChannelResponses, KeySegment, Lane, LaneKey, LatestMessage, LayoutProblem, LeaveCallResponse, LeaveChannelData, LeaveChannelError, LeaveChannelErrors, LeaveChannelResponses, LeaveOrEndCallData, LeaveOrEndCallError, LeaveOrEndCallErrors, LeaveOrEndCallResponse, LeaveOrEndCallResponses, LinkShare, ListAccessibleFormsData, ListAccessibleFormsError, ListAccessibleFormsErrors, ListAccessibleFormsResponse, ListAccessibleFormsResponses, ListAgentsData, ListAgentsError, ListAgentsErrors, ListAgentsResponse, ListAgentsResponses, ListBotChannelsData, ListBotChannelsError, ListBotChannelsErrors, ListBotChannelsResponse, ListBotChannelsResponses, ListChannelLabelsData, ListChannelLabelsError, ListChannelLabelsErrors, ListChannelLabelsResponse, ListChannelLabelsResponses, ListCompanyContactsData, ListCompanyContactsError, ListCompanyContactsErrors, ListCompanyContactsResponse, ListCompanyContactsResponses, ListCrmPipelinesData, ListCrmPipelinesResponse, ListCrmPipelinesResponses, ListDatabaseColumnCastsData, ListDatabaseColumnCastsError, ListDatabaseColumnCastsErrors, ListDatabaseColumnCastsResponse, ListDatabaseColumnCastsResponses, ListDatabasesData, ListDatabasesError, ListDatabasesErrors, ListDatabasesResponse, ListDatabasesResponses, ListedDatabase, ListedForm, ListEmailRemindersData, ListEmailRemindersError, ListEmailRemindersErrors, ListEmailRemindersResponse, ListEmailRemindersResponses, ListFavoritesData, ListFavoritesError, ListFavoritesErrors, ListFavoritesResponse, ListFavoritesResponses, ListFormsData, ListFormsError, ListFormsErrors, ListFormsResponse, ListFormsResponses, ListHarnessAgentsData, ListHarnessAgentsError, ListHarnessAgentsErrors, ListHarnessAgentsResponse, ListHarnessAgentsResponses, ListHarnessesData, ListHarnessesError, ListHarnessesErrors, ListHarnessesResponse, ListHarnessesResponses, ListHarnessSessionsData, ListHarnessSessionsError, ListHarnessSessionsErrors, ListHarnessSessionsResponse, ListHarnessSessionsResponses, ListInitiativesData, ListInitiativesError, ListInitiativesErrors, ListInitiativesResponse, ListInitiativesResponses, ListOccurrencesData, ListOccurrencesErrors, ListOccurrencesResponse, ListOccurrencesResponses, ListSlackImportsData, ListSlackImportsResponse, ListSlackImportsResponses, ListTeamCalendarData, ListTeamCalendarResponse, ListTeamCalendarResponses, ListTeamOutOfOfficeData, ListTeamOutOfOfficeErrors, ListTeamOutOfOfficeResponse, ListTeamOutOfOfficeResponses, ListUserApiKeysData, ListUserApiKeysError, ListUserApiKeysErrors, ListUserApiKeysResponse, ListUserApiKeysResponses, ListWebhooksData, ListWebhooksError, ListWebhooksErrors, ListWebhooksResponse, ListWebhooksResponse2, ListWebhooksResponses, LocationResponseData, LocationResponseV3, MacroUserIdStr, Meeting, MeetingCancelData, MeetingCancelError, MeetingCancelErrors, MeetingCancelPreparationData, MeetingCancelPreparationError, MeetingCancelPreparationErrors, MeetingCancelPreparationResponse, MeetingCancelPreparationResponses, MeetingCancelResponse, MeetingCancelResponses, MeetingCreateData, MeetingCreateError, MeetingCreateErrors, MeetingCreateResponse, MeetingCreateResponses, MeetingGuestJoinData, MeetingGuestJoinError, MeetingGuestJoinErrors, MeetingGuestJoinResponse, MeetingGuestJoinResponses, MeetingGuestParticipantsData, MeetingGuestParticipantsError, MeetingGuestParticipantsErrors, MeetingGuestParticipantsResponse, MeetingGuestParticipantsResponses, MeetingInviteData, MeetingInviteError, MeetingInviteErrors, MeetingInvitePermissions, MeetingInvitePermissionsData, MeetingInvitePermissionsError, MeetingInvitePermissionsErrors, MeetingInvitePermissionsResponse, MeetingInvitePermissionsResponses, MeetingInviteResponse, MeetingInviteResponses, MeetingInviteUsersData, MeetingInviteUsersError, MeetingInviteUsersErrors, MeetingInviteUsersResponse, MeetingInviteUsersResponses, MeetingJoinData, MeetingJoinError, MeetingJoinErrors, MeetingJoinResponse, MeetingJoinResponses, MeetingLeaveData, MeetingLeaveError, MeetingLeaveErrors, MeetingLeaveResponse, MeetingLeaveResponses, MeetingListActiveData, MeetingListActiveError, MeetingListActiveErrors, MeetingListActiveResponse, MeetingListActiveResponses, MeetingListData, MeetingListError, MeetingListErrors, MeetingListResponse, MeetingListResponses, MeetingLookupData, MeetingLookupError, MeetingLookupErrors, MeetingLookupResponse, MeetingLookupResponses, MeetingParticipant, MeetingParticipants, MeetingParticipantsData, MeetingParticipantsError, MeetingParticipantsErrors, MeetingParticipantsResponse, MeetingParticipantsResponses, MeetingPreparation, MeetingPrepareData, MeetingPrepareError, MeetingPrepareErrors, MeetingPrepareResponse, MeetingPrepareResponses, MeetingShareData, MeetingShareError, MeetingShareErrors, MeetingShareResponse, MeetingShareResponses, MeetingsResponse, MeetingToken, MeetingUpdateData, MeetingUpdateError, MeetingUpdateErrors, MeetingUpdateResponse, MeetingUpdateResponses, MentionPreviewsData, MentionPreviewsErrors, MentionPreviewsResponse, MentionPreviewsResponses, Message, MessageAttachment, MessageAttachmentCreatedMetadata, MessageAttachmentRemovedMetadata, MessageChange, MessageCursor, MessageDeletedMetadata, MessageDirection, MessageEvent, MessageEventAttachment, MessageListItem, MessageMentionedMetadata, MessagePage, MessageParent, MessagePatch, MessagePatchedMetadata, MessagePostedMetadata, MessageThread, MessageThreadPreview, MessageTimelineData, MessageTimelineQuery, MessageTimelineResponse, MessageTimelineResponses, MessageTopicEvent, MyResponse, NewAttachment, NewColumn, NewOption, NewThreadAnchor, NewView, NotificationFilters, NotificationState, NumberOperator, OpBatch, OpRefusalResponse, OpResult, OptionRef, PairingDetails, Params, ParticipantRole, PatchBotRequest, PatchChannelData, PatchChannelError, PatchChannelErrors, PatchChannelRequest, PatchChannelResponse, PatchChannelResponses, PatchMessageNotificationPolicy, PatchProjectRequestV2, PatchThreadRequestV2, PatchViewHandlerData, PatchViewHandlerError, PatchViewHandlerErrors, PatchViewHandlerResponses, PatchWebhookData, PatchWebhookError, PatchWebhookErrors, PatchWebhookRequest, PatchWebhookResponse, PatchWebhookResponses, PdfAnchor, PdfAnchorId, PdfHighlightAnchor, PdfHighlightAnchorRequest, PdfHighlightRect, PdfHighlightRectAnchorRequest, PdfPlaceableCommentAnchor, PendingClaimResponse, PermanentlyDeleteDocumentData, PermanentlyDeleteDocumentError, PermanentlyDeleteDocumentErrors, PermanentlyDeleteDocumentResponse, PermanentlyDeleteDocumentResponses, PermanentlyDeleteProjectData, PermanentlyDeleteProjectError, PermanentlyDeleteProjectErrors, PermanentlyDeleteProjectResponse, PermanentlyDeleteProjectResponses, PinnedItem, PinRequest, Pipeline, PipelineRecordType, PipelineSharing, PostActivityData, PostActivityError, PostActivityErrors, PostActivityRequest, PostActivityResponse, PostActivityResponses, PostChannelBotWebhookData, PostChannelBotWebhookError, PostChannelBotWebhookErrors, PostChannelBotWebhookResponse, PostChannelBotWebhookResponses, PostGroupedSoupAstGroupPageRequest, PostGroupedSoupAstInitialRequest, PostGroupedSoupAstRequest, PostItemsSoupAstData, PostItemsSoupAstError, PostItemsSoupAstErrors, PostItemsSoupAstGroupedData, PostItemsSoupAstGroupedError, PostItemsSoupAstGroupedErrors, PostItemsSoupAstGroupedResponse, PostItemsSoupAstGroupedResponses, PostItemsSoupAstResponse, PostItemsSoupAstResponses, PostItemsSoupData, PostItemsSoupError, PostItemsSoupErrors, PostItemsSoupResponse, PostItemsSoupResponses, PostMessage, PostMessageNotificationPolicy, PostSoupAstRequest, PostSoupRequest, PresaveDocumentHandlerData, PresaveDocumentHandlerError, PresaveDocumentHandlerErrors, PresaveDocumentHandlerResponse, PresaveDocumentHandlerResponses, PreSaveDocumentRequest, PreSaveDocumentResponse, PreSaveDocumentResponseData, PresenceOperator, PresignedUrl, PreviewSmartTagData, PreviewSmartTagError, PreviewSmartTagErrors, PreviewSmartTagResponse, PreviewSmartTagResponses, Project, ProjectDeleteResponseData, ProjectDocumentStatus, ProjectFilters, ProjectPreview, ProjectPreviewData, PropertyDefinition, PropertyDefinitionWithOptions, PropertyFilter, PropertyInput, PropertyOption, PropertyOptionValue, PropertyOwner, PropertyValue, PutCrmTeamSettingsData, PutCrmTeamSettingsError, PutCrmTeamSettingsErrors, PutCrmTeamSettingsResponse, PutCrmTeamSettingsResponses, PutCrmTeamStagesData, PutCrmTeamStagesError, PutCrmTeamStagesErrors, PutCrmTeamStagesResponse, PutCrmTeamStagesResponses, PutFormLayoutData, PutFormLayoutError, PutFormLayoutErrors, PutFormLayoutResponse, PutFormLayoutResponses, QueryCrmPipelineRowsData, QueryCrmPipelineRowsResponse, QueryCrmPipelineRowsResponses, QueryDefinition, QuestionLayout, QuestionOption, QuestionTally, ReactionInput, RecentlyDeletedData, RecentlyDeletedError, RecentlyDeletedErrors, RecentlyDeletedResponse, RecentlyDeletedResponseData, RecentlyDeletedResponses, RegisterSlackImportUploadsData, RegisterSlackImportUploadsErrors, RegisterSlackImportUploadsResponse, RegisterSlackImportUploadsResponses, RegisterUploads, RemoveBotFromChannelByBotData, RemoveBotFromChannelByBotError, RemoveBotFromChannelByBotErrors, RemoveBotFromChannelByBotResponse, RemoveBotFromChannelByBotResponses, RemoveFavoriteByEntityData, RemoveFavoriteByEntityError, RemoveFavoriteByEntityErrors, RemoveFavoriteByEntityResponses, RemoveParticipantsData, RemoveParticipantsError, RemoveParticipantsErrors, RemoveParticipantsRequest, RemoveParticipantsResponses, RemovePinHandlerData, RemovePinHandlerError, RemovePinHandlerErrors, RemovePinHandlerResponse, RemovePinHandlerResponses, RenameChannelLabelData, RenameChannelLabelError, RenameChannelLabelErrors, RenameChannelLabelRequest, RenameChannelLabelResponse, RenameChannelLabelResponses, RenameCrmPipelineData, RenameCrmPipelineResponse, RenameCrmPipelineResponses, RenamePipeline, ReorderFavoritesData, ReorderFavoritesError, ReorderFavoritesErrors, ReorderFavoritesRequest, ReorderFavoritesResponses, ReorderPinRequest, ReorderPinsHandlerData, ReorderPinsHandlerError, ReorderPinsHandlerErrors, ReorderPinsHandlerResponse, ReorderPinsHandlerResponses, ReplaceCrmStagesRequest, RequestedHarnessScope, RequestedLayout, ResetCrmTeamStagesData, ResetCrmTeamStagesError, ResetCrmTeamStagesErrors, ResetCrmTeamStagesResponse, ResetCrmTeamStagesResponses, ResponseStatus, ResponseSummary, RevertDeleteDocumentData, RevertDeleteDocumentError, RevertDeleteDocumentErrors, RevertDeleteDocumentResponse, RevertDeleteDocumentResponses, RevertDeleteProjectData, RevertDeleteProjectError, RevertDeleteProjectErrors, RevertDeleteProjectResponse, RevertDeleteProjectResponses, RingStatus, RingStatusResponse, RowChange, RowChangeKind, RowChanges, RowHistoryEntry, RowHistoryResponse, RowId, RowsChange, RowsResult, S3ObjectInfo, SaveBomPart, SaveDatabaseQueryData, SaveDatabaseQueryError, SaveDatabaseQueryErrors, SaveDatabaseQueryResponse, SaveDatabaseQueryResponses, SaveDocumentHandlerData, SaveDocumentHandlerError, SaveDocumentHandlerErrors, SaveDocumentHandlerResponse, SaveDocumentHandlerResponses, SaveDocumentRequest, SaveDocumentResponse, SaveDocumentResponseData, SavedQuery, SaveQueryRequest, SearchContactsData, SearchContactsError, SearchContactsErrors, SearchContactsResponse, SearchContactsResponse2, SearchContactsResponses, SearchState, SectionCount, SessionDeletedMetadata, SessionIdentity, SessionMentionedMetadata, SessionOpenedMetadata, SessionRenamedMetadata, SessionSettledMetadata, SessionStoppedMetadata, SetChannelLabelData, SetChannelLabelError, SetChannelLabelErrors, SetChannelLabelRequest, SetChannelLabelResponse, SetChannelLabelResponses, SetChannelPictureData, SetChannelPictureError, SetChannelPictureErrors, SetChannelPictureRequest, SetChannelPictureResponse, SetChannelPictureResponses, SetCompanyHiddenData, SetCompanyHiddenError, SetCompanyHiddenErrors, SetCompanyHiddenRequest, SetCompanyHiddenResponse, SetCompanyHiddenResponses, SetCompanyNameRequest, SetContactHiddenData, SetContactHiddenError, SetContactHiddenErrors, SetContactHiddenRequest, SetContactHiddenResponse, SetContactHiddenResponses, SetContactNameRequest, SetCrmCompanyNameData, SetCrmCompanyNameError, SetCrmCompanyNameErrors, SetCrmCompanyNameResponse, SetCrmCompanyNameResponses, SetCrmContactNameData, SetCrmContactNameError, SetCrmContactNameErrors, SetCrmContactNameResponse, SetCrmContactNameResponses, SetDocumentTeamShareData, SetDocumentTeamShareError, SetDocumentTeamShareErrors, SetDocumentTeamShareRequest, SetDocumentTeamShareResponse, SetDocumentTeamShareResponses, SetEmailFollowupData, SetEmailFollowupError, SetEmailFollowupErrors, SetEmailFollowupResponse, SetEmailFollowupResponses, SetEmailSyncData, SetEmailSyncError, SetEmailSyncErrors, SetEmailSyncRequest, SetEmailSyncResponse, SetEmailSyncResponses, SetOperator, SetPropertyValue, Sha256Digest, ShareCrmPipelineData, ShareCrmPipelineResponse, ShareCrmPipelineResponses, ShareDatabaseAwarenessData, ShareDatabaseAwarenessError, ShareDatabaseAwarenessErrors, ShareDatabaseAwarenessResponse, ShareDatabaseAwarenessResponses, SharedEmailFilter, SharePermissionV2, SharePipeline, ShortIdResponse, SimpleMention, SimpleSaveData, SimpleSaveError, SimpleSaveErrors, SimpleSaveResponse, SimpleSaveResponses, SkippedCell, SlackCompleteRequest, SlackCreateRequest, SlackRegisterRequest, SlackTimestamp, SlackUserId, SmartTagChannelMatch, SmartTagPreview, SortDirection, SortKey, SoupAgentSessionSoupPropertiesField, SoupApiItem, SoupApiSort, SoupApiSortDirection, SoupAttachment, SoupCalendarEventSoupPropertiesField, SoupCalendarEventTime, SoupCallRecordGuest, SoupCallRecordParticipant, SoupCallRecordSoupPropertiesField, SoupChannel, SoupChannelThread, SoupChatSoupPropertiesField, SoupContact, SoupCountedReaction, SoupCrmCompanySoupPropertiesField, SoupCrmContactSoupPropertiesField, SoupCrmDomain, SoupDatabaseRowSoupPropertiesField, SoupDocumentSoupPropertiesField, SoupDocumentSubType, SoupEmailThreadPreview, SoupEnrichedEmailThreadPreviewSoupPropertiesField, SoupForeignEntity, SoupInitiativeSoupPropertiesField, SoupItem, SoupLabel, SoupLabelListVisibility, SoupLabelType, SoupMessageAttachment, SoupMessageListVisibility, SoupMessageSender, SoupMessageSenderType, SoupPage, SoupProjectSoupPropertiesField, SoupPropertiesField, SoupProperty, SoupThreadInfo, SoupThreadReply, SourceBinding, SourceId, SourceIdentity, StarterDatabase, StarterDocumentsResponse, StorageRow, StorageRows, StorageRowsQuery, StoredGithubPullRequest, StreamEventsData, StreamEventsError, StreamEventsErrors, StreamEventsResponse, StreamEventsResponses, String, Submission, SubmissionOutcome, SubmitFormResponseData, SubmitFormResponseError, SubmitFormResponseErrors, SubmitFormResponseResponse, SubmitFormResponseResponses, SuccessResponse, SurfaceState, SyncServiceVersionId, SystemSkillSummary, Table, TableChange, TableChanged, TableChanges, TableDetail, TableResult, TableVersion, TagFilterMode, TakenId, TallyBucket, TallyValue, TaskFilters, TeamCalendarContent, TeamCalendarCoverage, TeamCalendarDetails, TeamCalendarItem, TeamCalendarMember, TeamCalendarPage, TeamCalendarSharing, TeamOutOfOfficeItem, TeamOutOfOfficeResponse, TeamRole, TextOperator, ThreadAnchor, ThreadOrigin, ThreadPatch, ThreadState, ToggleShareWithTeamData, ToggleShareWithTeamError, ToggleShareWithTeamErrors, ToggleShareWithTeamResponse, ToggleShareWithTeamResponses, TouchedColumn, TouchedRow, TranscribeDictationData, TranscribeDictationError, TranscribeDictationErrors, TranscribeDictationResponse, TranscribeDictationResponses, TranscribeResponse, TranscriptSegmentRequest, TrashCrmPipelineData, TrashCrmPipelineResponse, TrashCrmPipelineResponses, TrashPipeline, TurnEndedMetadata, TurnStartedMetadata, TurnSummary, TypedSuccessResponse, TypedSuccessResponseGetDocumentResponseData, TypingInput, UndoChangeResponse, UndoDatabaseChangeData, UndoDatabaseChangeError, UndoDatabaseChangeErrors, UndoDatabaseChangeResponse, UndoDatabaseChangeResponses, UndoOutcome, UndoRefusal, UnlockedBooking, UpdateAgentData, UpdateAgentError, UpdateAgentErrors, UpdateAgentRequest, UpdateAgentResponse, UpdateAgentResponses, UpdateChannelSharePermission, UpdateCrmTeamSettingsRequest, UpdateDatabasePermissionsData, UpdateDatabasePermissionsError, UpdateDatabasePermissionsErrors, UpdateDatabasePermissionsResponse, UpdateDatabasePermissionsResponses, UpdateForm, UpdateFormData, UpdateFormError, UpdateFormErrors, UpdateFormPermissionsData, UpdateFormPermissionsError, UpdateFormPermissionsErrors, UpdateFormPermissionsResponse, UpdateFormPermissionsResponses, UpdateFormResponse, UpdateFormResponses, UpdateInitiativeData, UpdateInitiativeError, UpdateInitiativeErrors, UpdateInitiativeRequest, UpdateInitiativeResponse, UpdateInitiativeResponses, UpdateMeetingRequest, UpdateOperation, UpdateSharePermissionRequestV2, UploadDescriptor, UploadDocumentStatus, UploadExtractFolderHandlerData, UploadExtractFolderHandlerError, UploadExtractFolderHandlerErrors, UploadExtractFolderHandlerResponse, UploadExtractFolderHandlerResponses, UploadExtractFolderRequest, UploadFolderHandlerData, UploadFolderHandlerError, UploadFolderHandlerErrors, UploadFolderHandlerResponse, UploadFolderHandlerResponses, UploadFolderRequest, UploadGrant, UploadId, UpsertHistoryHandlerData, UpsertHistoryHandlerError, UpsertHistoryHandlerErrors, UpsertHistoryHandlerResponse, UpsertHistoryHandlerResponses, UpsertUserDocumentViewLocationData, UpsertUserDocumentViewLocationError, UpsertUserDocumentViewLocationErrors, UpsertUserDocumentViewLocationRequest, UpsertUserDocumentViewLocationResponse, UpsertUserDocumentViewLocationResponses, UserApiKeyId, UserApiKeyInfo, UserApiKeysList, UserDocumentsResponse, UserDocumentViewLocation, UserDocumentViewLocationResponse, UserPinsResponse, UserViewsResponse, ValidateDocumentPermissionsTokenData, ValidateDocumentPermissionsTokenError, ValidateDocumentPermissionsTokenErrors, ValidateDocumentPermissionsTokenResponse, ValidateDocumentPermissionsTokenResponses, ValidateWebhookData, ValidateWebhookError, ValidateWebhookErrors, ValidateWebhookResponse, ValidateWebhookResponse2, ValidateWebhookResponses, Vec, VersionedTable, View, ViewChange, ViewColumn, ViewLayout, ViewPatch, ViewPosition, ViewPositionsResponse, ViewQuery, ViewResult, ViewsResponse, WaitingForInputMetadata, Webhook, WebhookEvent, WebhookFilter, WebhookScope, WebhookStatus, WebhookValidationTestEvent, Widget, WithCallId, WithChannelId, WithDocumentId, WithProjectId } from './types.gen';diff --git a/packages/sdk/generated/storage/sdk.gen.ts b/packages/sdk/generated/storage/sdk.gen.tsindex 1d87015035..c2e6a863c7 100644--- a/packages/sdk/generated/storage/sdk.gen.ts+++ b/packages/sdk/generated/storage/sdk.gen.ts@@ -2,7 +2,7 @@import type { Client, ClientMeta, Options as Options2, RequestResult, ServerSentEventsResult, TDataShape } from './client';import { client } from './client.gen';-import type { AddFavoriteData, AddFavoriteErrors, AddFavoriteResponses, AddParticipantsData, AddParticipantsErrors, AddParticipantsResponses, AddPinHandlerData, AddPinHandlerErrors, AddPinHandlerResponses, ApplyCrmPipelineOpsData, ApplyCrmPipelineOpsResponses, ApplyDatabaseOpsData, ApplyDatabaseOpsErrors, ApplyDatabaseOpsResponses, ApproveHarnessPairingData, ApproveHarnessPairingErrors, ApproveHarnessPairingResponses, BulkWakeupSyncServiceDocumentsData, BulkWakeupSyncServiceDocumentsErrors, BulkWakeupSyncServiceDocumentsResponses, CallWebhookData, CallWebhookErrors, CallWebhookResponses, CancelSlackImportData, CancelSlackImportErrors, CancelSlackImportResponses, CheckActiveCallData, CheckActiveCallErrors, CheckActiveCallResponses, ClaimHarnessPairingData, ClaimHarnessPairingErrors, ClaimHarnessPairingResponses, CollaborateFormData, CollaborateFormErrors, CollaborateFormResponses, CompleteSlackImportUploadsData, CompleteSlackImportUploadsErrors, CompleteSlackImportUploadsResponses, ConvertDatabaseColumnData, ConvertDatabaseColumnErrors, ConvertDatabaseColumnResponses, CopyDocumentData, CopyDocumentErrors, CopyDocumentResponses, CreateAgentData, CreateAgentErrors, CreateAgentResponses, CreateAnchorData, CreateAnchorErrors, CreateAnchorResponses, CreateChannelData, CreateChannelErrors, CreateChannelLabelData, CreateChannelLabelErrors, CreateChannelLabelResponses, CreateChannelResponses, CreateChannelScopedBotData, CreateChannelScopedBotErrors, CreateChannelScopedBotResponses, CreateCollabSurfaceTokenData, CreateCollabSurfaceTokenErrors, CreateCollabSurfaceTokenResponses, CreateCrmCompanyData, CreateCrmCompanyErrors, CreateCrmCompanyResponses, CreateCrmContactData, CreateCrmContactErrors, CreateCrmContactResponses, CreateCrmPipelineData, CreateCrmPipelineResponses, CreateDatabaseData, CreateDatabaseErrors, CreateDatabaseResponses, CreateDocumentData, CreateDocumentErrors, CreateDocumentResponses, CreateEntityMentionData, CreateEntityMentionErrors, CreateEntityMentionResponses, CreateFormData, CreateFormErrors, CreateFormResponses, CreateHarnessPairingData, CreateHarnessPairingErrors, CreateHarnessPairingResponses, CreateInitiativeData, CreateInitiativeErrors, CreateInitiativeResponses, CreateInstructionsHandlerData, CreateInstructionsHandlerErrors, CreateInstructionsHandlerResponses, CreateMarkdownHandlerData, CreateMarkdownHandlerErrors, CreateMarkdownHandlerResponses, CreateProjectHandlerData, CreateProjectHandlerErrors, CreateProjectHandlerResponses, CreateSkillHandlerData, CreateSkillHandlerErrors, CreateSkillHandlerResponses, CreateSlackImportData, CreateSlackImportErrors, CreateSlackImportResponses, CreateSnippetHandlerData, CreateSnippetHandlerErrors, CreateSnippetHandlerResponses, CreateTaskHandlerData, CreateTaskHandlerErrors, CreateTaskHandlerResponses, CreateUserApiKeyData, CreateUserApiKeyErrors, CreateUserApiKeyResponses, CreateViewHandlerData, CreateViewHandlerErrors, CreateViewHandlerResponses, CreateWebhookData, CreateWebhookErrors, CreateWebhookResponses, DeleteAnchorData, DeleteAnchorErrors, DeleteAnchorResponses, DeleteCallRecordData, DeleteCallRecordErrors, DeleteCallRecordResponses, DeleteChannelData, DeleteChannelErrors, DeleteChannelLabelData, DeleteChannelLabelErrors, DeleteChannelLabelResponses, DeleteChannelResponses, DeleteCollabSurfaceData, DeleteCollabSurfaceErrors, DeleteCollabSurfaceResponses, DeleteDocumentData, DeleteDocumentErrors, DeleteDocumentResponses, DeleteEntityMentionData, DeleteEntityMentionErrors, DeleteEntityMentionResponses, DeleteHarnessData, DeleteHarnessErrors, DeleteHarnessResponses, DeleteHistoryHandlerData, DeleteHistoryHandlerErrors, DeleteHistoryHandlerResponses, DeleteInitiativeData, DeleteInitiativeErrors, DeleteInitiativeResponses, DeleteProjectHandlerData, DeleteProjectHandlerErrors, DeleteProjectHandlerResponses, DeleteSelfHarnessData, DeleteSelfHarnessErrors, DeleteSelfHarnessResponses, DeleteUserApiKeyData, DeleteUserApiKeyErrors, DeleteUserApiKeyResponses, DeleteUserDocumentViewLocationData, DeleteUserDocumentViewLocationErrors, DeleteUserDocumentViewLocationResponses, DeleteViewHandlerData, DeleteViewHandlerErrors, DeleteViewHandlerResponses, DeleteWebhookData, DeleteWebhookErrors, DeleteWebhookResponses, EditAnchorData, EditAnchorErrors, EditAnchorResponses, EditCallRecordData, EditCallRecordErrors, EditCallRecordResponses, EditCallTranscriptData, EditCallTranscriptErrors, EditCallTranscriptResponses, EditDocumentData, EditDocumentErrors, EditDocumentResponses, EditMyFormResponseData, EditMyFormResponseErrors, EditMyFormResponseResponses, EditProjectV2Data, EditProjectV2Errors, EditProjectV2Responses, EditThreadV2Data, EditThreadV2Errors, EditThreadV2Responses, EnsureCollabSurfaceData, EnsureCollabSurfaceErrors, EnsureCollabSurfaceResponses, EnsureStarterHandlerData, EnsureStarterHandlerErrors, EnsureStarterHandlerResponses, EntityMessageCreateData, EntityMessageCreateResponses, EntityMessageDeleteMessageData, EntityMessageDeleteMessageResponses, EntityMessageDeleteThreadData, EntityMessageDeleteThreadResponses, EntityMessageEditData, EntityMessageEditResponses, EntityMessageGetMessageData, EntityMessageGetMessageResponses, EntityMessageGetThreadData, EntityMessageGetThreadResponses, EntityMessageLegacyData, EntityMessageLegacyResponses, EntityMessagePatchThreadData, EntityMessagePatchThreadResponses, EntityMessageReactData, EntityMessageReactResponses, EntityMessageTypingData, EntityMessageTypingResponses, ExcludeDefaultViewHandlerData, ExcludeDefaultViewHandlerErrors, ExcludeDefaultViewHandlerResponses, ExportDocumentData, ExportDocumentErrors, ExportDocumentResponses, FinalizeSlackImportData, FinalizeSlackImportErrors, FinalizeSlackImportResponses, GetActiveCallsData, GetActiveCallsErrors, GetActiveCallsResponses, GetActivityData, GetActivityErrors, GetActivityResponses, GetAttachmentReferencesData, GetAttachmentReferencesErrors, GetAttachmentReferencesResponses, GetBatchCallRecordPreviewData, GetBatchCallRecordPreviewErrors, GetBatchCallRecordPreviewResponses, GetBatchChannelPreviewData, GetBatchChannelPreviewErrors, GetBatchChannelPreviewResponses, GetBatchPreviewHandlerData, GetBatchPreviewHandlerErrors, GetBatchPreviewHandlerResponses, GetBatchProjectPreviewData, GetBatchProjectPreviewErrors, GetBatchProjectPreviewResponses, GetBotOwnerProfilesData, GetBotOwnerProfilesErrors, GetBotOwnerProfilesResponses, GetCallRecordData, GetCallRecordErrors, GetCallRecordResponses, GetChannelAttachmentsData, GetChannelAttachmentsErrors, GetChannelAttachmentsResponses, GetChannelData, GetChannelErrors, GetChannelJoinLinkData, GetChannelJoinLinkErrors, GetChannelJoinLinkResponses, GetChannelParticipantsData, GetChannelParticipantsErrors, GetChannelParticipantsResponses, GetChannelResponses, GetChannelsData, GetChannelsErrors, GetChannelsResponses, GetCollabSurfaceData, GetCollabSurfaceErrors, GetCollabSurfaceResponses, GetCompanyData, GetCompanyErrors, GetCompanyResponses, GetContactByEmailData, GetContactByEmailErrors, GetContactByEmailResponses, GetContactData, GetContactErrors, GetContactResponses, GetCrmPipelineData, GetCrmPipelineResponses, GetCrmPipelineRowsData, GetCrmPipelineRowsResponses, GetCrmPipelineTableData, GetCrmPipelineTableResponses, GetCrmTeamSettingsData, GetCrmTeamSettingsErrors, GetCrmTeamSettingsResponses, GetDatabaseData, GetDatabaseErrors, GetDatabasePermissionsData, GetDatabasePermissionsErrors, GetDatabasePermissionsResponses, GetDatabaseQueryData, GetDatabaseQueryErrors, GetDatabaseQueryResponses, GetDatabaseResponses, GetDatabaseRowHistoryData, GetDatabaseRowHistoryErrors, GetDatabaseRowHistoryResponses, GetDatabaseTableChangesData, GetDatabaseTableChangesErrors, GetDatabaseTableChangesResponses, GetDatabaseViewPositionsData, GetDatabaseViewPositionsErrors, GetDatabaseViewPositionsResponses, GetDocumentAnchorsData, GetDocumentAnchorsErrors, GetDocumentAnchorsResponses, GetDocumentBranchNameData, GetDocumentBranchNameErrors, GetDocumentBranchNameResponses, GetDocumentByTeamSlugData, GetDocumentByTeamSlugErrors, GetDocumentByTeamSlugResponses, GetDocumentData, GetDocumentErrors, GetDocumentGithubPullRequestsData, GetDocumentGithubPullRequestsErrors, GetDocumentGithubPullRequestsResponses, GetDocumentListHandlerData, GetDocumentListHandlerErrors, GetDocumentListHandlerResponses, GetDocumentLocationV3Data, GetDocumentLocationV3Errors, GetDocumentLocationV3Responses, GetDocumentPermissionsTokenData, GetDocumentPermissionsTokenErrors, GetDocumentPermissionsTokenResponses, GetDocumentPermissionsV2Data, GetDocumentPermissionsV2Errors, GetDocumentPermissionsV2Responses, GetDocumentProcessingResultData, GetDocumentProcessingResultErrors, GetDocumentProcessingResultResponses, GetDocumentResponses, GetDocumentShortIdData, GetDocumentShortIdErrors, GetDocumentShortIdResponses, GetDocumentTeamShareData, GetDocumentTeamShareErrors, GetDocumentTeamShareResponses, GetDocumentVersionData, GetDocumentVersionErrors, GetDocumentVersionResponses, GetDocumentViewsHandlerData, GetDocumentViewsHandlerErrors, GetDocumentViewsHandlerResponses, GetEmailFollowupData, GetEmailFollowupErrors, GetEmailFollowupResponses, GetEntityPermissionData, GetEntityPermissionErrors, GetEntityPermissionResponses, GetForeignEntityBySourceData, GetForeignEntityBySourceErrors, GetForeignEntityBySourceResponses, GetForeignEntityData, GetForeignEntityErrors, GetForeignEntityResponses, GetFormData, GetFormErrors, GetFormPermissionsData, GetFormPermissionsErrors, GetFormPermissionsResponses, GetFormResponses, GetFormResponseSummaryData, GetFormResponseSummaryErrors, GetFormResponseSummaryResponses, GetFormTallyData, GetFormTallyErrors, GetFormTallyResponses, GetGithubPullRequestChangesData, GetGithubPullRequestChangesErrors, GetGithubPullRequestChangesPatchData, GetGithubPullRequestChangesPatchErrors, GetGithubPullRequestChangesPatchResponses, GetGithubPullRequestChangesResponses, GetGithubPullRequestData, GetGithubPullRequestErrors, GetGithubPullRequestFacetsData, GetGithubPullRequestFacetsErrors, GetGithubPullRequestFacetsResponses, GetGithubPullRequestResponses, GetGithubPullRequestTasksData, GetGithubPullRequestTasksErrors, GetGithubPullRequestTasksResponses, GetHarnessPairingData, GetHarnessPairingErrors, GetHarnessPairingResponses, GetHistoryHandlerData, GetHistoryHandlerErrors, GetHistoryHandlerResponses, GetInitiativeData, GetInitiativeErrors, GetInitiativeResponses, GetInstructionsHandlerData, GetInstructionsHandlerErrors, GetInstructionsHandlerResponses, GetItemsSoupData, GetItemsSoupErrors, GetItemsSoupResponses, GetLocationHandlerData, GetLocationHandlerErrors, GetLocationHandlerResponses, GetMyFormResponseData, GetMyFormResponseErrors, GetMyFormResponseResponses, GetOrCreateCallData, GetOrCreateCallErrors, GetOrCreateCallResponses, GetOrCreateDmData, GetOrCreateDmErrors, GetOrCreateDmResponses, GetOrCreatePrivateData, GetOrCreatePrivateErrors, GetOrCreatePrivateResponses, GetPendingProjectsHandlerData, GetPendingProjectsHandlerErrors, GetPendingProjectsHandlerResponses, GetPinsHandlerData, GetPinsHandlerErrors, GetPinsHandlerResponses, GetProjectContentHandlerData, GetProjectContentHandlerErrors, GetProjectContentHandlerResponses, GetProjectHandlerData, GetProjectHandlerErrors, GetProjectHandlerResponses, GetProjectPermissionsV2Data, GetProjectPermissionsV2Errors, GetProjectPermissionsV2Responses, GetProjectsHandlerData, GetProjectsHandlerErrors, GetProjectsHandlerResponses, GetProjectUserAccessLevelData, GetProjectUserAccessLevelErrors, GetProjectUserAccessLevelResponses, GetRingStatusData, GetRingStatusErrors, GetRingStatusResponses, GetSelfBotData, GetSelfBotErrors, GetSelfBotResponses, GetSelfHarnessData, GetSelfHarnessErrors, GetSelfHarnessResponses, GetSlackImportData, GetSlackImportErrors, GetSlackImportResponses, GetSystemSkillsHandlerData, GetSystemSkillsHandlerErrors, GetSystemSkillsHandlerResponses, GetUserDocumentsHandlerData, GetUserDocumentsHandlerErrors, GetUserDocumentsHandlerResponses, GetUserDocumentViewLocationData, GetUserDocumentViewLocationErrors, GetUserDocumentViewLocationResponses, GetViewsHandlerData, GetViewsHandlerErrors, GetViewsHandlerResponses, GetWebhookData, GetWebhookErrors, GetWebhookResponses, HandlerData, HandlerErrors, HandlerResponses, HealthHandlerData, HealthHandlerResponses, ImportDatabaseTableData, ImportDatabaseTableErrors, ImportDatabaseTableResponses, InferDatabaseColumnTypeData, InferDatabaseColumnTypeErrors, InferDatabaseColumnTypeResponses, IngestTranscriptData, IngestTranscriptErrors, IngestTranscriptResponses, InitializeUserDocumentsData, InitializeUserDocumentsErrors, InitializeUserDocumentsResponses, InstallSyncData, InstallSyncErrors, JobProcessingResultHandlerData, JobProcessingResultHandlerErrors, JobProcessingResultHandlerResponses, JoinChannelByCodeData, JoinChannelByCodeErrors, JoinChannelByCodeResponses, JoinChannelData, JoinChannelErrors, JoinChannelResponses, LeaveChannelData, LeaveChannelErrors, LeaveChannelResponses, LeaveOrEndCallData, LeaveOrEndCallErrors, LeaveOrEndCallResponses, ListAccessibleFormsData, ListAccessibleFormsErrors, ListAccessibleFormsResponses, ListAgentsData, ListAgentsErrors, ListAgentsResponses, ListBotChannelsData, ListBotChannelsErrors, ListBotChannelsResponses, ListChannelLabelsData, ListChannelLabelsErrors, ListChannelLabelsResponses, ListCompanyContactsData, ListCompanyContactsErrors, ListCompanyContactsResponses, ListCrmPipelinesData, ListCrmPipelinesResponses, ListDatabaseColumnCastsData, ListDatabaseColumnCastsErrors, ListDatabaseColumnCastsResponses, ListDatabasesData, ListDatabasesErrors, ListDatabasesResponses, ListEmailRemindersData, ListEmailRemindersErrors, ListEmailRemindersResponses, ListFavoritesData, ListFavoritesErrors, ListFavoritesResponses, ListFormsData, ListFormsErrors, ListFormsResponses, ListHarnessAgentsData, ListHarnessAgentsErrors, ListHarnessAgentsResponses, ListHarnessesData, ListHarnessesErrors, ListHarnessesResponses, ListHarnessSessionsData, ListHarnessSessionsErrors, ListHarnessSessionsResponses, ListInitiativesData, ListInitiativesErrors, ListInitiativesResponses, ListOccurrencesData, ListOccurrencesErrors, ListOccurrencesResponses, ListSlackImportsData, ListSlackImportsResponses, ListTeamOutOfOfficeData, ListTeamOutOfOfficeErrors, ListTeamOutOfOfficeResponses, ListUserApiKeysData, ListUserApiKeysErrors, ListUserApiKeysResponses, ListWebhooksData, ListWebhooksErrors, ListWebhooksResponses, MeetingCancelData, MeetingCancelErrors, MeetingCancelPreparationData, MeetingCancelPreparationErrors, MeetingCancelPreparationResponses, MeetingCancelResponses, MeetingCreateData, MeetingCreateErrors, MeetingCreateResponses, MeetingGuestJoinData, MeetingGuestJoinErrors, MeetingGuestJoinResponses, MeetingGuestParticipantsData, MeetingGuestParticipantsErrors, MeetingGuestParticipantsResponses, MeetingInviteData, MeetingInviteErrors, MeetingInvitePermissionsData, MeetingInvitePermissionsErrors, MeetingInvitePermissionsResponses, MeetingInviteResponses, MeetingInviteUsersData, MeetingInviteUsersErrors, MeetingInviteUsersResponses, MeetingJoinData, MeetingJoinErrors, MeetingJoinResponses, MeetingLeaveData, MeetingLeaveErrors, MeetingLeaveResponses, MeetingListActiveData, MeetingListActiveErrors, MeetingListActiveResponses, MeetingListData, MeetingListErrors, MeetingListResponses, MeetingLookupData, MeetingLookupErrors, MeetingLookupResponses, MeetingParticipantsData, MeetingParticipantsErrors, MeetingParticipantsResponses, MeetingPrepareData, MeetingPrepareErrors, MeetingPrepareResponses, MeetingShareData, MeetingShareErrors, MeetingShareResponses, MeetingUpdateData, MeetingUpdateErrors, MeetingUpdateResponses, MentionPreviewsData, MentionPreviewsErrors, MentionPreviewsResponses, MessageTimelineData, MessageTimelineResponses, PatchChannelData, PatchChannelErrors, PatchChannelResponses, PatchViewHandlerData, PatchViewHandlerErrors, PatchViewHandlerResponses, PatchWebhookData, PatchWebhookErrors, PatchWebhookResponses, PermanentlyDeleteDocumentData, PermanentlyDeleteDocumentErrors, PermanentlyDeleteDocumentResponses, PermanentlyDeleteProjectData, PermanentlyDeleteProjectErrors, PermanentlyDeleteProjectResponses, PostActivityData, PostActivityErrors, PostActivityResponses, PostChannelBotWebhookData, PostChannelBotWebhookErrors, PostChannelBotWebhookResponses, PostItemsSoupAstData, PostItemsSoupAstErrors, PostItemsSoupAstGroupedData, PostItemsSoupAstGroupedErrors, PostItemsSoupAstGroupedResponses, PostItemsSoupAstResponses, PostItemsSoupData, PostItemsSoupErrors, PostItemsSoupResponses, PresaveDocumentHandlerData, PresaveDocumentHandlerErrors, PresaveDocumentHandlerResponses, PreviewSmartTagData, PreviewSmartTagErrors, PreviewSmartTagResponses, PutCrmTeamSettingsData, PutCrmTeamSettingsErrors, PutCrmTeamSettingsResponses, PutCrmTeamStagesData, PutCrmTeamStagesErrors, PutCrmTeamStagesResponses, PutFormLayoutData, PutFormLayoutErrors, PutFormLayoutResponses, QueryCrmPipelineRowsData, QueryCrmPipelineRowsResponses, RecentlyDeletedData, RecentlyDeletedErrors, RecentlyDeletedResponses, RegisterSlackImportUploadsData, RegisterSlackImportUploadsErrors, RegisterSlackImportUploadsResponses, RemoveBotFromChannelByBotData, RemoveBotFromChannelByBotErrors, RemoveBotFromChannelByBotResponses, RemoveFavoriteByEntityData, RemoveFavoriteByEntityErrors, RemoveFavoriteByEntityResponses, RemoveParticipantsData, RemoveParticipantsErrors, RemoveParticipantsResponses, RemovePinHandlerData, RemovePinHandlerErrors, RemovePinHandlerResponses, RenameChannelLabelData, RenameChannelLabelErrors, RenameChannelLabelResponses, RenameCrmPipelineData, RenameCrmPipelineResponses, ReorderFavoritesData, ReorderFavoritesErrors, ReorderFavoritesResponses, ReorderPinsHandlerData, ReorderPinsHandlerErrors, ReorderPinsHandlerResponses, ResetCrmTeamStagesData, ResetCrmTeamStagesErrors, ResetCrmTeamStagesResponses, RevertDeleteDocumentData, RevertDeleteDocumentErrors, RevertDeleteDocumentResponses, RevertDeleteProjectData, RevertDeleteProjectErrors, RevertDeleteProjectResponses, SaveDatabaseQueryData, SaveDatabaseQueryErrors, SaveDatabaseQueryResponses, SaveDocumentHandlerData, SaveDocumentHandlerErrors, SaveDocumentHandlerResponses, SearchContactsData, SearchContactsErrors, SearchContactsResponses, SetChannelLabelData, SetChannelLabelErrors, SetChannelLabelResponses, SetChannelPictureData, SetChannelPictureErrors, SetChannelPictureResponses, SetCompanyHiddenData, SetCompanyHiddenErrors, SetCompanyHiddenResponses, SetContactHiddenData, SetContactHiddenErrors, SetContactHiddenResponses, SetCrmCompanyNameData, SetCrmCompanyNameErrors, SetCrmCompanyNameResponses, SetCrmContactNameData, SetCrmContactNameErrors, SetCrmContactNameResponses, SetDocumentTeamShareData, SetDocumentTeamShareErrors, SetDocumentTeamShareResponses, SetEmailFollowupData, SetEmailFollowupErrors, SetEmailFollowupResponses, SetEmailSyncData, SetEmailSyncErrors, SetEmailSyncResponses, ShareCrmPipelineData, ShareCrmPipelineResponses, ShareDatabaseAwarenessData, ShareDatabaseAwarenessErrors, ShareDatabaseAwarenessResponses, SimpleSaveData, SimpleSaveErrors, SimpleSaveResponses, StreamEventsData, StreamEventsErrors, StreamEventsResponse, StreamEventsResponses, SubmitFormResponseData, SubmitFormResponseErrors, SubmitFormResponseResponses, ToggleShareWithTeamData, ToggleShareWithTeamErrors, ToggleShareWithTeamResponses, TranscribeDictationData, TranscribeDictationErrors, TranscribeDictationResponses, TrashCrmPipelineData, TrashCrmPipelineResponses, UndoDatabaseChangeData, UndoDatabaseChangeErrors, UndoDatabaseChangeResponses, UpdateAgentData, UpdateAgentErrors, UpdateAgentResponses, UpdateDatabasePermissionsData, UpdateDatabasePermissionsErrors, UpdateDatabasePermissionsResponses, UpdateFormData, UpdateFormErrors, UpdateFormPermissionsData, UpdateFormPermissionsErrors, UpdateFormPermissionsResponses, UpdateFormResponses, UpdateInitiativeData, UpdateInitiativeErrors, UpdateInitiativeResponses, UploadExtractFolderHandlerData, UploadExtractFolderHandlerErrors, UploadExtractFolderHandlerResponses, UploadFolderHandlerData, UploadFolderHandlerErrors, UploadFolderHandlerResponses, UpsertHistoryHandlerData, UpsertHistoryHandlerErrors, UpsertHistoryHandlerResponses, UpsertUserDocumentViewLocationData, UpsertUserDocumentViewLocationErrors, UpsertUserDocumentViewLocationResponses, ValidateDocumentPermissionsTokenData, ValidateDocumentPermissionsTokenErrors, ValidateDocumentPermissionsTokenResponses, ValidateWebhookData, ValidateWebhookErrors, ValidateWebhookResponses } from './types.gen';+import type { AddFavoriteData, AddFavoriteErrors, AddFavoriteResponses, AddParticipantsData, AddParticipantsErrors, AddParticipantsResponses, AddPinHandlerData, AddPinHandlerErrors, AddPinHandlerResponses, ApplyCrmPipelineOpsData, ApplyCrmPipelineOpsResponses, ApplyDatabaseOpsData, ApplyDatabaseOpsErrors, ApplyDatabaseOpsResponses, ApproveHarnessPairingData, ApproveHarnessPairingErrors, ApproveHarnessPairingResponses, BulkWakeupSyncServiceDocumentsData, BulkWakeupSyncServiceDocumentsErrors, BulkWakeupSyncServiceDocumentsResponses, CallWebhookData, CallWebhookErrors, CallWebhookResponses, CancelSlackImportData, CancelSlackImportErrors, CancelSlackImportResponses, CheckActiveCallData, CheckActiveCallErrors, CheckActiveCallResponses, ClaimHarnessPairingData, ClaimHarnessPairingErrors, ClaimHarnessPairingResponses, CollaborateFormData, CollaborateFormErrors, CollaborateFormResponses, CompleteSlackImportUploadsData, CompleteSlackImportUploadsErrors, CompleteSlackImportUploadsResponses, ConvertDatabaseColumnData, ConvertDatabaseColumnErrors, ConvertDatabaseColumnResponses, CopyDocumentData, CopyDocumentErrors, CopyDocumentResponses, CreateAgentData, CreateAgentErrors, CreateAgentResponses, CreateAnchorData, CreateAnchorErrors, CreateAnchorResponses, CreateChannelData, CreateChannelErrors, CreateChannelLabelData, CreateChannelLabelErrors, CreateChannelLabelResponses, CreateChannelResponses, CreateChannelScopedBotData, CreateChannelScopedBotErrors, CreateChannelScopedBotResponses, CreateCollabSurfaceTokenData, CreateCollabSurfaceTokenErrors, CreateCollabSurfaceTokenResponses, CreateCrmCompanyData, CreateCrmCompanyErrors, CreateCrmCompanyResponses, CreateCrmContactData, CreateCrmContactErrors, CreateCrmContactResponses, CreateCrmPipelineData, CreateCrmPipelineResponses, CreateDatabaseData, CreateDatabaseErrors, CreateDatabaseResponses, CreateDocumentData, CreateDocumentErrors, CreateDocumentResponses, CreateEntityMentionData, CreateEntityMentionErrors, CreateEntityMentionResponses, CreateFormData, CreateFormErrors, CreateFormResponses, CreateHarnessPairingData, CreateHarnessPairingErrors, CreateHarnessPairingResponses, CreateInitiativeData, CreateInitiativeErrors, CreateInitiativeResponses, CreateInstructionsHandlerData, CreateInstructionsHandlerErrors, CreateInstructionsHandlerResponses, CreateMarkdownHandlerData, CreateMarkdownHandlerErrors, CreateMarkdownHandlerResponses, CreateProjectHandlerData, CreateProjectHandlerErrors, CreateProjectHandlerResponses, CreateSkillHandlerData, CreateSkillHandlerErrors, CreateSkillHandlerResponses, CreateSlackImportData, CreateSlackImportErrors, CreateSlackImportResponses, CreateSnippetHandlerData, CreateSnippetHandlerErrors, CreateSnippetHandlerResponses, CreateTaskHandlerData, CreateTaskHandlerErrors, CreateTaskHandlerResponses, CreateUserApiKeyData, CreateUserApiKeyErrors, CreateUserApiKeyResponses, CreateViewHandlerData, CreateViewHandlerErrors, CreateViewHandlerResponses, CreateWebhookData, CreateWebhookErrors, CreateWebhookResponses, DeleteAnchorData, DeleteAnchorErrors, DeleteAnchorResponses, DeleteCallRecordData, DeleteCallRecordErrors, DeleteCallRecordResponses, DeleteChannelData, DeleteChannelErrors, DeleteChannelLabelData, DeleteChannelLabelErrors, DeleteChannelLabelResponses, DeleteChannelResponses, DeleteCollabSurfaceData, DeleteCollabSurfaceErrors, DeleteCollabSurfaceResponses, DeleteDocumentData, DeleteDocumentErrors, DeleteDocumentResponses, DeleteEntityMentionData, DeleteEntityMentionErrors, DeleteEntityMentionResponses, DeleteHarnessData, DeleteHarnessErrors, DeleteHarnessResponses, DeleteHistoryHandlerData, DeleteHistoryHandlerErrors, DeleteHistoryHandlerResponses, DeleteInitiativeData, DeleteInitiativeErrors, DeleteInitiativeResponses, DeleteProjectHandlerData, DeleteProjectHandlerErrors, DeleteProjectHandlerResponses, DeleteSelfHarnessData, DeleteSelfHarnessErrors, DeleteSelfHarnessResponses, DeleteUserApiKeyData, DeleteUserApiKeyErrors, DeleteUserApiKeyResponses, DeleteUserDocumentViewLocationData, DeleteUserDocumentViewLocationErrors, DeleteUserDocumentViewLocationResponses, DeleteViewHandlerData, DeleteViewHandlerErrors, DeleteViewHandlerResponses, DeleteWebhookData, DeleteWebhookErrors, DeleteWebhookResponses, EditAnchorData, EditAnchorErrors, EditAnchorResponses, EditCallRecordData, EditCallRecordErrors, EditCallRecordResponses, EditCallTranscriptData, EditCallTranscriptErrors, EditCallTranscriptResponses, EditDocumentData, EditDocumentErrors, EditDocumentResponses, EditMyFormResponseData, EditMyFormResponseErrors, EditMyFormResponseResponses, EditProjectV2Data, EditProjectV2Errors, EditProjectV2Responses, EditThreadV2Data, EditThreadV2Errors, EditThreadV2Responses, EnsureCollabSurfaceData, EnsureCollabSurfaceErrors, EnsureCollabSurfaceResponses, EnsureStarterHandlerData, EnsureStarterHandlerErrors, EnsureStarterHandlerResponses, EntityMessageCreateData, EntityMessageCreateResponses, EntityMessageDeleteMessageData, EntityMessageDeleteMessageResponses, EntityMessageDeleteThreadData, EntityMessageDeleteThreadResponses, EntityMessageEditData, EntityMessageEditResponses, EntityMessageGetMessageData, EntityMessageGetMessageResponses, EntityMessageGetThreadData, EntityMessageGetThreadResponses, EntityMessageLegacyData, EntityMessageLegacyResponses, EntityMessagePatchThreadData, EntityMessagePatchThreadResponses, EntityMessageReactData, EntityMessageReactResponses, EntityMessageTypingData, EntityMessageTypingResponses, ExcludeDefaultViewHandlerData, ExcludeDefaultViewHandlerErrors, ExcludeDefaultViewHandlerResponses, ExportDocumentData, ExportDocumentErrors, ExportDocumentResponses, FinalizeSlackImportData, FinalizeSlackImportErrors, FinalizeSlackImportResponses, GetActiveCallsData, GetActiveCallsErrors, GetActiveCallsResponses, GetActivityData, GetActivityErrors, GetActivityResponses, GetAttachmentReferencesData, GetAttachmentReferencesErrors, GetAttachmentReferencesResponses, GetBatchCallRecordPreviewData, GetBatchCallRecordPreviewErrors, GetBatchCallRecordPreviewResponses, GetBatchChannelPreviewData, GetBatchChannelPreviewErrors, GetBatchChannelPreviewResponses, GetBatchPreviewHandlerData, GetBatchPreviewHandlerErrors, GetBatchPreviewHandlerResponses, GetBatchProjectPreviewData, GetBatchProjectPreviewErrors, GetBatchProjectPreviewResponses, GetBotOwnerProfilesData, GetBotOwnerProfilesErrors, GetBotOwnerProfilesResponses, GetCallRecordData, GetCallRecordErrors, GetCallRecordResponses, GetChannelAttachmentsData, GetChannelAttachmentsErrors, GetChannelAttachmentsResponses, GetChannelData, GetChannelErrors, GetChannelJoinLinkData, GetChannelJoinLinkErrors, GetChannelJoinLinkResponses, GetChannelParticipantsData, GetChannelParticipantsErrors, GetChannelParticipantsResponses, GetChannelResponses, GetChannelsData, GetChannelsErrors, GetChannelsResponses, GetCollabSurfaceData, GetCollabSurfaceErrors, GetCollabSurfaceResponses, GetCompanyData, GetCompanyErrors, GetCompanyResponses, GetContactByEmailData, GetContactByEmailErrors, GetContactByEmailResponses, GetContactData, GetContactErrors, GetContactResponses, GetCrmPipelineData, GetCrmPipelineResponses, GetCrmPipelineRowsData, GetCrmPipelineRowsResponses, GetCrmPipelineTableData, GetCrmPipelineTableResponses, GetCrmTeamSettingsData, GetCrmTeamSettingsErrors, GetCrmTeamSettingsResponses, GetDatabaseData, GetDatabaseErrors, GetDatabasePermissionsData, GetDatabasePermissionsErrors, GetDatabasePermissionsResponses, GetDatabaseQueryData, GetDatabaseQueryErrors, GetDatabaseQueryResponses, GetDatabaseResponses, GetDatabaseRowHistoryData, GetDatabaseRowHistoryErrors, GetDatabaseRowHistoryResponses, GetDatabaseTableChangesData, GetDatabaseTableChangesErrors, GetDatabaseTableChangesResponses, GetDatabaseViewPositionsData, GetDatabaseViewPositionsErrors, GetDatabaseViewPositionsResponses, GetDocumentAnchorsData, GetDocumentAnchorsErrors, GetDocumentAnchorsResponses, GetDocumentBranchNameData, GetDocumentBranchNameErrors, GetDocumentBranchNameResponses, GetDocumentByTeamSlugData, GetDocumentByTeamSlugErrors, GetDocumentByTeamSlugResponses, GetDocumentData, GetDocumentErrors, GetDocumentGithubPullRequestsData, GetDocumentGithubPullRequestsErrors, GetDocumentGithubPullRequestsResponses, GetDocumentListHandlerData, GetDocumentListHandlerErrors, GetDocumentListHandlerResponses, GetDocumentLocationV3Data, GetDocumentLocationV3Errors, GetDocumentLocationV3Responses, GetDocumentPermissionsTokenData, GetDocumentPermissionsTokenErrors, GetDocumentPermissionsTokenResponses, GetDocumentPermissionsV2Data, GetDocumentPermissionsV2Errors, GetDocumentPermissionsV2Responses, GetDocumentProcessingResultData, GetDocumentProcessingResultErrors, GetDocumentProcessingResultResponses, GetDocumentResponses, GetDocumentShortIdData, GetDocumentShortIdErrors, GetDocumentShortIdResponses, GetDocumentTeamShareData, GetDocumentTeamShareErrors, GetDocumentTeamShareResponses, GetDocumentVersionData, GetDocumentVersionErrors, GetDocumentVersionResponses, GetDocumentViewsHandlerData, GetDocumentViewsHandlerErrors, GetDocumentViewsHandlerResponses, GetEmailFollowupData, GetEmailFollowupErrors, GetEmailFollowupResponses, GetEntityPermissionData, GetEntityPermissionErrors, GetEntityPermissionResponses, GetForeignEntityBySourceData, GetForeignEntityBySourceErrors, GetForeignEntityBySourceResponses, GetForeignEntityData, GetForeignEntityErrors, GetForeignEntityResponses, GetFormData, GetFormErrors, GetFormPermissionsData, GetFormPermissionsErrors, GetFormPermissionsResponses, GetFormResponses, GetFormResponseSummaryData, GetFormResponseSummaryErrors, GetFormResponseSummaryResponses, GetFormTallyData, GetFormTallyErrors, GetFormTallyResponses, GetGithubPullRequestChangesData, GetGithubPullRequestChangesErrors, GetGithubPullRequestChangesPatchData, GetGithubPullRequestChangesPatchErrors, GetGithubPullRequestChangesPatchResponses, GetGithubPullRequestChangesResponses, GetGithubPullRequestData, GetGithubPullRequestErrors, GetGithubPullRequestFacetsData, GetGithubPullRequestFacetsErrors, GetGithubPullRequestFacetsResponses, GetGithubPullRequestResponses, GetGithubPullRequestTasksData, GetGithubPullRequestTasksErrors, GetGithubPullRequestTasksResponses, GetHarnessPairingData, GetHarnessPairingErrors, GetHarnessPairingResponses, GetHistoryHandlerData, GetHistoryHandlerErrors, GetHistoryHandlerResponses, GetInitiativeData, GetInitiativeErrors, GetInitiativeResponses, GetInstructionsHandlerData, GetInstructionsHandlerErrors, GetInstructionsHandlerResponses, GetItemsSoupData, GetItemsSoupErrors, GetItemsSoupResponses, GetLocationHandlerData, GetLocationHandlerErrors, GetLocationHandlerResponses, GetMyFormResponseData, GetMyFormResponseErrors, GetMyFormResponseResponses, GetOrCreateCallData, GetOrCreateCallErrors, GetOrCreateCallResponses, GetOrCreateDmData, GetOrCreateDmErrors, GetOrCreateDmResponses, GetOrCreatePrivateData, GetOrCreatePrivateErrors, GetOrCreatePrivateResponses, GetPendingProjectsHandlerData, GetPendingProjectsHandlerErrors, GetPendingProjectsHandlerResponses, GetPinsHandlerData, GetPinsHandlerErrors, GetPinsHandlerResponses, GetProjectContentHandlerData, GetProjectContentHandlerErrors, GetProjectContentHandlerResponses, GetProjectHandlerData, GetProjectHandlerErrors, GetProjectHandlerResponses, GetProjectPermissionsV2Data, GetProjectPermissionsV2Errors, GetProjectPermissionsV2Responses, GetProjectsHandlerData, GetProjectsHandlerErrors, GetProjectsHandlerResponses, GetProjectUserAccessLevelData, GetProjectUserAccessLevelErrors, GetProjectUserAccessLevelResponses, GetRingStatusData, GetRingStatusErrors, GetRingStatusResponses, GetSelfBotData, GetSelfBotErrors, GetSelfBotResponses, GetSelfHarnessData, GetSelfHarnessErrors, GetSelfHarnessResponses, GetSlackImportData, GetSlackImportErrors, GetSlackImportResponses, GetSystemSkillsHandlerData, GetSystemSkillsHandlerErrors, GetSystemSkillsHandlerResponses, GetUserDocumentsHandlerData, GetUserDocumentsHandlerErrors, GetUserDocumentsHandlerResponses, GetUserDocumentViewLocationData, GetUserDocumentViewLocationErrors, GetUserDocumentViewLocationResponses, GetViewsHandlerData, GetViewsHandlerErrors, GetViewsHandlerResponses, GetWebhookData, GetWebhookErrors, GetWebhookResponses, HandlerData, HandlerErrors, HandlerResponses, HealthHandlerData, HealthHandlerResponses, ImportDatabaseTableData, ImportDatabaseTableErrors, ImportDatabaseTableResponses, InferDatabaseColumnTypeData, InferDatabaseColumnTypeErrors, InferDatabaseColumnTypeResponses, IngestTranscriptData, IngestTranscriptErrors, IngestTranscriptResponses, InitializeUserDocumentsData, InitializeUserDocumentsErrors, InitializeUserDocumentsResponses, InstallSyncData, InstallSyncErrors, JobProcessingResultHandlerData, JobProcessingResultHandlerErrors, JobProcessingResultHandlerResponses, JoinChannelByCodeData, JoinChannelByCodeErrors, JoinChannelByCodeResponses, JoinChannelData, JoinChannelErrors, JoinChannelResponses, LeaveChannelData, LeaveChannelErrors, LeaveChannelResponses, LeaveOrEndCallData, LeaveOrEndCallErrors, LeaveOrEndCallResponses, ListAccessibleFormsData, ListAccessibleFormsErrors, ListAccessibleFormsResponses, ListAgentsData, ListAgentsErrors, ListAgentsResponses, ListBotChannelsData, ListBotChannelsErrors, ListBotChannelsResponses, ListChannelLabelsData, ListChannelLabelsErrors, ListChannelLabelsResponses, ListCompanyContactsData, ListCompanyContactsErrors, ListCompanyContactsResponses, ListCrmPipelinesData, ListCrmPipelinesResponses, ListDatabaseColumnCastsData, ListDatabaseColumnCastsErrors, ListDatabaseColumnCastsResponses, ListDatabasesData, ListDatabasesErrors, ListDatabasesResponses, ListEmailRemindersData, ListEmailRemindersErrors, ListEmailRemindersResponses, ListFavoritesData, ListFavoritesErrors, ListFavoritesResponses, ListFormsData, ListFormsErrors, ListFormsResponses, ListHarnessAgentsData, ListHarnessAgentsErrors, ListHarnessAgentsResponses, ListHarnessesData, ListHarnessesErrors, ListHarnessesResponses, ListHarnessSessionsData, ListHarnessSessionsErrors, ListHarnessSessionsResponses, ListInitiativesData, ListInitiativesErrors, ListInitiativesResponses, ListOccurrencesData, ListOccurrencesErrors, ListOccurrencesResponses, ListSlackImportsData, ListSlackImportsResponses, ListTeamCalendarData, ListTeamCalendarResponses, ListTeamOutOfOfficeData, ListTeamOutOfOfficeErrors, ListTeamOutOfOfficeResponses, ListUserApiKeysData, ListUserApiKeysErrors, ListUserApiKeysResponses, ListWebhooksData, ListWebhooksErrors, ListWebhooksResponses, MeetingCancelData, MeetingCancelErrors, MeetingCancelPreparationData, MeetingCancelPreparationErrors, MeetingCancelPreparationResponses, MeetingCancelResponses, MeetingCreateData, MeetingCreateErrors, MeetingCreateResponses, MeetingGuestJoinData, MeetingGuestJoinErrors, MeetingGuestJoinResponses, MeetingGuestParticipantsData, MeetingGuestParticipantsErrors, MeetingGuestParticipantsResponses, MeetingInviteData, MeetingInviteErrors, MeetingInvitePermissionsData, MeetingInvitePermissionsErrors, MeetingInvitePermissionsResponses, MeetingInviteResponses, MeetingInviteUsersData, MeetingInviteUsersErrors, MeetingInviteUsersResponses, MeetingJoinData, MeetingJoinErrors, MeetingJoinResponses, MeetingLeaveData, MeetingLeaveErrors, MeetingLeaveResponses, MeetingListActiveData, MeetingListActiveErrors, MeetingListActiveResponses, MeetingListData, MeetingListErrors, MeetingListResponses, MeetingLookupData, MeetingLookupErrors, MeetingLookupResponses, MeetingParticipantsData, MeetingParticipantsErrors, MeetingParticipantsResponses, MeetingPrepareData, MeetingPrepareErrors, MeetingPrepareResponses, MeetingShareData, MeetingShareErrors, MeetingShareResponses, MeetingUpdateData, MeetingUpdateErrors, MeetingUpdateResponses, MentionPreviewsData, MentionPreviewsErrors, MentionPreviewsResponses, MessageTimelineData, MessageTimelineResponses, PatchChannelData, PatchChannelErrors, PatchChannelResponses, PatchViewHandlerData, PatchViewHandlerErrors, PatchViewHandlerResponses, PatchWebhookData, PatchWebhookErrors, PatchWebhookResponses, PermanentlyDeleteDocumentData, PermanentlyDeleteDocumentErrors, PermanentlyDeleteDocumentResponses, PermanentlyDeleteProjectData, PermanentlyDeleteProjectErrors, PermanentlyDeleteProjectResponses, PostActivityData, PostActivityErrors, PostActivityResponses, PostChannelBotWebhookData, PostChannelBotWebhookErrors, PostChannelBotWebhookResponses, PostItemsSoupAstData, PostItemsSoupAstErrors, PostItemsSoupAstGroupedData, PostItemsSoupAstGroupedErrors, PostItemsSoupAstGroupedResponses, PostItemsSoupAstResponses, PostItemsSoupData, PostItemsSoupErrors, PostItemsSoupResponses, PresaveDocumentHandlerData, PresaveDocumentHandlerErrors, PresaveDocumentHandlerResponses, PreviewSmartTagData, PreviewSmartTagErrors, PreviewSmartTagResponses, PutCrmTeamSettingsData, PutCrmTeamSettingsErrors, PutCrmTeamSettingsResponses, PutCrmTeamStagesData, PutCrmTeamStagesErrors, PutCrmTeamStagesResponses, PutFormLayoutData, PutFormLayoutErrors, PutFormLayoutResponses, QueryCrmPipelineRowsData, QueryCrmPipelineRowsResponses, RecentlyDeletedData, RecentlyDeletedErrors, RecentlyDeletedResponses, RegisterSlackImportUploadsData, RegisterSlackImportUploadsErrors, RegisterSlackImportUploadsResponses, RemoveBotFromChannelByBotData, RemoveBotFromChannelByBotErrors, RemoveBotFromChannelByBotResponses, RemoveFavoriteByEntityData, RemoveFavoriteByEntityErrors, RemoveFavoriteByEntityResponses, RemoveParticipantsData, RemoveParticipantsErrors, RemoveParticipantsResponses, RemovePinHandlerData, RemovePinHandlerErrors, RemovePinHandlerResponses, RenameChannelLabelData, RenameChannelLabelErrors, RenameChannelLabelResponses, RenameCrmPipelineData, RenameCrmPipelineResponses, ReorderFavoritesData, ReorderFavoritesErrors, ReorderFavoritesResponses, ReorderPinsHandlerData, ReorderPinsHandlerErrors, ReorderPinsHandlerResponses, ResetCrmTeamStagesData, ResetCrmTeamStagesErrors, ResetCrmTeamStagesResponses, RevertDeleteDocumentData, RevertDeleteDocumentErrors, RevertDeleteDocumentResponses, RevertDeleteProjectData, RevertDeleteProjectErrors, RevertDeleteProjectResponses, SaveDatabaseQueryData, SaveDatabaseQueryErrors, SaveDatabaseQueryResponses, SaveDocumentHandlerData, SaveDocumentHandlerErrors, SaveDocumentHandlerResponses, SearchContactsData, SearchContactsErrors, SearchContactsResponses, SetChannelLabelData, SetChannelLabelErrors, SetChannelLabelResponses, SetChannelPictureData, SetChannelPictureErrors, SetChannelPictureResponses, SetCompanyHiddenData, SetCompanyHiddenErrors, SetCompanyHiddenResponses, SetContactHiddenData, SetContactHiddenErrors, SetContactHiddenResponses, SetCrmCompanyNameData, SetCrmCompanyNameErrors, SetCrmCompanyNameResponses, SetCrmContactNameData, SetCrmContactNameErrors, SetCrmContactNameResponses, SetDocumentTeamShareData, SetDocumentTeamShareErrors, SetDocumentTeamShareResponses, SetEmailFollowupData, SetEmailFollowupErrors, SetEmailFollowupResponses, SetEmailSyncData, SetEmailSyncErrors, SetEmailSyncResponses, ShareCrmPipelineData, ShareCrmPipelineResponses, ShareDatabaseAwarenessData, ShareDatabaseAwarenessErrors, ShareDatabaseAwarenessResponses, SimpleSaveData, SimpleSaveErrors, SimpleSaveResponses, StreamEventsData, StreamEventsErrors, StreamEventsResponse, StreamEventsResponses, SubmitFormResponseData, SubmitFormResponseErrors, SubmitFormResponseResponses, ToggleShareWithTeamData, ToggleShareWithTeamErrors, ToggleShareWithTeamResponses, TranscribeDictationData, TranscribeDictationErrors, TranscribeDictationResponses, TrashCrmPipelineData, TrashCrmPipelineResponses, UndoDatabaseChangeData, UndoDatabaseChangeErrors, UndoDatabaseChangeResponses, UpdateAgentData, UpdateAgentErrors, UpdateAgentResponses, UpdateDatabasePermissionsData, UpdateDatabasePermissionsErrors, UpdateDatabasePermissionsResponses, UpdateFormData, UpdateFormErrors, UpdateFormPermissionsData, UpdateFormPermissionsErrors, UpdateFormPermissionsResponses, UpdateFormResponses, UpdateInitiativeData, UpdateInitiativeErrors, UpdateInitiativeResponses, UploadExtractFolderHandlerData, UploadExtractFolderHandlerErrors, UploadExtractFolderHandlerResponses, UploadFolderHandlerData, UploadFolderHandlerErrors, UploadFolderHandlerResponses, UpsertHistoryHandlerData, UpsertHistoryHandlerErrors, UpsertHistoryHandlerResponses, UpsertUserDocumentViewLocationData, UpsertUserDocumentViewLocationErrors, UpsertUserDocumentViewLocationResponses, ValidateDocumentPermissionsTokenData, ValidateDocumentPermissionsTokenErrors, ValidateDocumentPermissionsTokenResponses, ValidateWebhookData, ValidateWebhookErrors, ValidateWebhookResponses } from './types.gen';export type Options<TData extends TDataShape = TDataShape, ThrowOnError extends boolean = boolean, TResponse = unknown> = Options2<TData, ThrowOnError, TResponse> & {/**@@ -195,6 +195,13 @@ export class Sdk extends HeyApiClient {});}+ /**+ * Query authorized projections in a bounded viewport.+ */+ public listTeamCalendar<ThrowOnError extends boolean = false>(options: Options<ListTeamCalendarData, ThrowOnError>): RequestResult<ListTeamCalendarResponses, unknown, ThrowOnError> {+ return (options.client ?? this.client).get<ListTeamCalendarResponses, unknown, ThrowOnError>({ url: '/calendar-events/team', ...options });+ }+/*** Return teammates' out-of-office occurrences in the requested viewport.*/diff --git a/packages/sdk/generated/storage/types.gen.ts b/packages/sdk/generated/storage/types.gen.tsindex 78a2d8f9ec..7aef8a5dbb 100644--- a/packages/sdk/generated/storage/types.gen.ts+++ b/packages/sdk/generated/storage/types.gen.ts@@ -13047,6 +13047,126 @@ export type TaskFilters = {include_cbm_atm_nc?: boolean | null;};+/**+ * Disjoint busy/detail shapes prevent new event fields leaking by default.+ */+export type TeamCalendarContent = {+ kind: 'busy';+} | {+ /**+ * Detail projection.+ */+ details: TeamCalendarDetails;+ kind: 'details';+};++/**+ * Whether a member's calendar projection can establish availability.+ */+export type TeamCalendarCoverage = 'ready' | 'unavailable' | 'hidden';++/**+ * Safe details from a single authorized source.+ */+export type TeamCalendarDetails = {+ /**+ * Attendees; self flags are relative to the requesting viewer.+ */+ attendees: Array<CalendarAttendee>;+ /**+ * Source calendar name, shown only with details.+ */+ calendarName: string;+ /**+ * Join URL, if supplied by this source.+ */+ conferenceUrl?: string | null;+ /**+ * Body, if supplied by this source.+ */+ description?: string | null;+ /**+ * Location, if supplied by this source.+ */+ location?: string | null;+ /**+ * Organizer address from this source.+ */+ organizerEmail?: string | null;+ /**+ * Organizer name from this source.+ */+ organizerName?: string | null;+ /**+ * Display title.+ */+ title: string;+};++/**+ * A read-only team calendar occurrence.+ */+export type TeamCalendarItem = TeamCalendarContent & {+ /**+ * Whether this occurrence blocks the sharer's personal availability.+ * A subscribed calendar's block can be shared without occupying the sharer.+ */+ contributesToAvailability: boolean;+ /**+ * Stable opaque projection identity, never an event entity id.+ */+ id: string;+ /**+ * The person sharing access to the source.+ */+ ownerId: string;+ /**+ * Occurrence interval.+ */+ time: EventTime;+};++/**+ * A current member of the requester's team.+ */+export type TeamCalendarMember = {+ /**+ * Coverage available for a trustworthy calculation.+ */+ coverage: TeamCalendarCoverage;+ /**+ * Current team-sharing policy.+ */+ sharing: TeamCalendarSharing;+ /**+ * Macro user identifier.+ */+ userId: string;+};++/**+ * A bounded page of team calendar projections.+ */+export type TeamCalendarPage = {+ /**+ * Authorized read-only projections.+ */+ items: Array<TeamCalendarItem>;+ /**+ * Current membership and sharing policies.+ */+ members: Array<TeamCalendarMember>;+ /**+ * Opaque continuation token; null after the last source occurrence.+ */+ nextCursor?: string | null;+};++/**+ * What a user exposes through their team membership.+ */+export type TeamCalendarSharing = 'all' | 'busy_only' | 'none';+/*** One teammate's out-of-office occurrence.*/@@ -14678,6 +14798,36 @@ export type MentionPreviewsResponses = {export type MentionPreviewsResponse = MentionPreviewsResponses[keyof MentionPreviewsResponses];+export type ListTeamCalendarData = {+ body?: never;+ path?: never;+ query: {+ /**+ * Inclusive instant.+ */+ start: string;+ /**+ * Exclusive instant.+ */+ end: string;+ /**+ * Continuation returned by the preceding page.+ */+ cursor?: string | null;+ /**+ * Maximum source occurrences, at most 2,000. Zero returns the roster only.+ */+ limit?: number | null;+ };+ url: '/calendar-events/team';+};++export type ListTeamCalendarResponses = {+ 200: TeamCalendarPage;+};++export type ListTeamCalendarResponse = ListTeamCalendarResponses[keyof ListTeamCalendarResponses];+export type ListTeamOutOfOfficeData = {body?: never;path?: never;diff --git a/packages/sdk/specs/calendar.json b/packages/sdk/specs/calendar.jsonindex 6a807ef493..6acb6ba900 100644--- a/packages/sdk/specs/calendar.json+++ b/packages/sdk/specs/calendar.json@@ -9,6 +9,58 @@"version": "0.1.0"},"paths": {+ "/availability-calendars": {+ "get": {+ "tags": ["calendar_events"],+ "summary": "List calendars and their personal-availability inclusion.",+ "operationId": "get_availability_calendars",+ "responses": {+ "200": {+ "description": "",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/AvailabilityCalendarsResponse"+ }+ }+ }+ }+ }+ }+ },+ "/availability-calendars/{calendar_id}": {+ "put": {+ "tags": ["calendar_events"],+ "summary": "Change which source calendars normally occupy this user's time.",+ "operationId": "set_availability_calendar",+ "parameters": [+ {+ "name": "calendar_id",+ "in": "path",+ "required": true,+ "schema": {+ "type": "string",+ "format": "uuid"+ }+ }+ ],+ "requestBody": {+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/AvailabilityCalendarBody"+ }+ }+ },+ "required": true+ },+ "responses": {+ "204": {+ "description": ""+ }+ }+ }+ },"/calendars": {"get": {"tags": ["calendar_events"],@@ -402,6 +454,52 @@}}}+ },+ "/team-sharing": {+ "get": {+ "tags": ["calendar_events"],+ "summary": "Read the authenticated user's sharing choice.",+ "operationId": "get_team_sharing",+ "responses": {+ "200": {+ "description": "",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/TeamCalendarSharingBody"+ }+ }+ }+ }+ }+ },+ "put": {+ "tags": ["calendar_events"],+ "summary": "Set the authenticated user's sharing choice.",+ "operationId": "set_team_sharing",+ "requestBody": {+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/TeamCalendarSharingBody"+ }+ }+ },+ "required": true+ },+ "responses": {+ "200": {+ "description": "",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/TeamCalendarSharingBody"+ }+ }+ }+ }+ }+ }}},"components": {@@ -411,6 +509,60 @@"description": "RSVP state for an attendee.","enum": ["needs_action", "accepted", "declined", "tentative"]},+ "AvailabilityCalendar": {+ "type": "object",+ "description": "Per-user inclusion of a source calendar in personal availability.",+ "required": [+ "calendarId",+ "name",+ "contributesToAvailability",+ "isPrimary"+ ],+ "properties": {+ "calendarId": {+ "type": "string",+ "format": "uuid",+ "description": "Visible source calendar."+ },+ "contributesToAvailability": {+ "type": "boolean",+ "description": "Whether its events normally block the user's time."+ },+ "isPrimary": {+ "type": "boolean",+ "description": "Whether this is the connected account's primary calendar."+ },+ "name": {+ "type": "string",+ "description": "Source name."+ }+ }+ },+ "AvailabilityCalendarBody": {+ "type": "object",+ "description": "Own-user source inclusion preference.",+ "required": ["contributesToAvailability"],+ "properties": {+ "contributesToAvailability": {+ "type": "boolean",+ "description": "Whether this calendar contributes to personal availability."+ }+ }+ },+ "AvailabilityCalendarsResponse": {+ "type": "object",+ "description": "Source calendar settings returned to their viewer.",+ "required": ["calendars"],+ "properties": {+ "calendars": {+ "type": "array",+ "items": {+ "$ref": "#/components/schemas/AvailabilityCalendar"+ },+ "description": "Directly visible source calendars."+ }+ }+ },"CalendarAttendee": {"type": "object","description": "An attendee on a calendar event.",@@ -1005,6 +1157,17 @@"description": "Connected inbox whose calendars changed."}}+ },+ {+ "type": "object",+ "description": "A team entitlement changed; discard cached team projections before refetching.",+ "required": ["event"],+ "properties": {+ "event": {+ "type": "string",+ "enum": ["team_sharing_changed"]+ }+ }}],"description": "Realtime signal that a connected inbox's calendar projection changed."@@ -1044,6 +1207,22 @@}}},+ "TeamCalendarSharing": {+ "type": "string",+ "description": "What a user exposes through their team membership.",+ "enum": ["all", "busy_only", "none"]+ },+ "TeamCalendarSharingBody": {+ "type": "object",+ "description": "Own-user sharing preference.",+ "required": ["sharing"],+ "properties": {+ "sharing": {+ "$ref": "#/components/schemas/TeamCalendarSharing",+ "description": "Busy-only is the default, including when no setting has been saved."+ }+ }+ },"UpdateCalendarEventRequest": {"type": "object","description": "Request body patching an event; omitted fields are left untouched.",diff --git a/packages/sdk/specs/storage.json b/packages/sdk/specs/storage.jsonindex 904516377a..a3a16aa98c 100644--- a/packages/sdk/specs/storage.json+++ b/packages/sdk/specs/storage.json@@ -816,6 +816,67 @@}}},+ "/calendar-events/team": {+ "get": {+ "tags": ["calendar_events"],+ "summary": "Query authorized projections in a bounded viewport.",+ "operationId": "list_team_calendar",+ "parameters": [+ {+ "name": "start",+ "in": "query",+ "description": "Inclusive instant.",+ "required": true,+ "schema": {+ "type": "string",+ "format": "date-time"+ }+ },+ {+ "name": "end",+ "in": "query",+ "description": "Exclusive instant.",+ "required": true,+ "schema": {+ "type": "string",+ "format": "date-time"+ }+ },+ {+ "name": "cursor",+ "in": "query",+ "description": "Continuation returned by the preceding page.",+ "required": false,+ "schema": {+ "type": ["string", "null"]+ }+ },+ {+ "name": "limit",+ "in": "query",+ "description": "Maximum source occurrences, at most 2,000. Zero returns the roster only.",+ "required": false,+ "schema": {+ "type": ["integer", "null"],+ "format": "int32",+ "minimum": 0+ }+ }+ ],+ "responses": {+ "200": {+ "description": "",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/TeamCalendarPage"+ }+ }+ }+ }+ }+ }+ },"/calendar-events/team-out-of-office": {"get": {"tags": ["calendar_events"],@@ -37802,6 +37863,164 @@}}},+ "TeamCalendarContent": {+ "oneOf": [+ {+ "type": "object",+ "description": "No provider or event metadata.",+ "required": ["kind"],+ "properties": {+ "kind": {+ "type": "string",+ "enum": ["busy"]+ }+ }+ },+ {+ "type": "object",+ "description": "Explicitly authorized source content.",+ "required": ["details", "kind"],+ "properties": {+ "details": {+ "$ref": "#/components/schemas/TeamCalendarDetails",+ "description": "Detail projection."+ },+ "kind": {+ "type": "string",+ "enum": ["details"]+ }+ }+ }+ ],+ "description": "Disjoint busy/detail shapes prevent new event fields leaking by default."+ },+ "TeamCalendarCoverage": {+ "type": "string",+ "description": "Whether a member's calendar projection can establish availability.",+ "enum": ["ready", "unavailable", "hidden"]+ },+ "TeamCalendarDetails": {+ "type": "object",+ "description": "Safe details from a single authorized source.",+ "required": ["title", "attendees", "calendarName"],+ "properties": {+ "attendees": {+ "type": "array",+ "items": {+ "$ref": "#/components/schemas/CalendarAttendee"+ },+ "description": "Attendees; self flags are relative to the requesting viewer."+ },+ "calendarName": {+ "type": "string",+ "description": "Source calendar name, shown only with details."+ },+ "conferenceUrl": {+ "type": ["string", "null"],+ "description": "Join URL, if supplied by this source."+ },+ "description": {+ "type": ["string", "null"],+ "description": "Body, if supplied by this source."+ },+ "location": {+ "type": ["string", "null"],+ "description": "Location, if supplied by this source."+ },+ "organizerEmail": {+ "type": ["string", "null"],+ "description": "Organizer address from this source."+ },+ "organizerName": {+ "type": ["string", "null"],+ "description": "Organizer name from this source."+ },+ "title": {+ "type": "string",+ "description": "Display title."+ }+ }+ },+ "TeamCalendarItem": {+ "allOf": [+ {+ "$ref": "#/components/schemas/TeamCalendarContent",+ "description": "Authorized content variant."+ },+ {+ "type": "object",+ "required": ["id", "ownerId", "time", "contributesToAvailability"],+ "properties": {+ "contributesToAvailability": {+ "type": "boolean",+ "description": "Whether this occurrence blocks the sharer's personal availability.\nA subscribed calendar's block can be shared without occupying the sharer."+ },+ "id": {+ "type": "string",+ "description": "Stable opaque projection identity, never an event entity id."+ },+ "ownerId": {+ "type": "string",+ "description": "The person sharing access to the source."+ },+ "time": {+ "$ref": "#/components/schemas/EventTime",+ "description": "Occurrence interval."+ }+ }+ }+ ],+ "description": "A read-only team calendar occurrence."+ },+ "TeamCalendarMember": {+ "type": "object",+ "description": "A current member of the requester's team.",+ "required": ["userId", "sharing", "coverage"],+ "properties": {+ "coverage": {+ "$ref": "#/components/schemas/TeamCalendarCoverage",+ "description": "Coverage available for a trustworthy calculation."+ },+ "sharing": {+ "$ref": "#/components/schemas/TeamCalendarSharing",+ "description": "Current team-sharing policy."+ },+ "userId": {+ "type": "string",+ "description": "Macro user identifier."+ }+ }+ },+ "TeamCalendarPage": {+ "type": "object",+ "description": "A bounded page of team calendar projections.",+ "required": ["members", "items"],+ "properties": {+ "items": {+ "type": "array",+ "items": {+ "$ref": "#/components/schemas/TeamCalendarItem"+ },+ "description": "Authorized read-only projections."+ },+ "members": {+ "type": "array",+ "items": {+ "$ref": "#/components/schemas/TeamCalendarMember"+ },+ "description": "Current membership and sharing policies."+ },+ "nextCursor": {+ "type": ["string", "null"],+ "description": "Opaque continuation token; null after the last source occurrence."+ }+ }+ },+ "TeamCalendarSharing": {+ "type": "string",+ "description": "What a user exposes through their team membership.",+ "enum": ["all", "busy_only", "none"]+ },"TeamOutOfOfficeItem": {"type": "object","description": "One teammate's out-of-office occurrence.",diff --git a/packages/sdk/src/coverage/skipped.ts b/packages/sdk/src/coverage/skipped.tsindex e1b3716d11..a8e5e424de 100644--- a/packages/sdk/src/coverage/skipped.ts+++ b/packages/sdk/src/coverage/skipped.ts@@ -143,8 +143,13 @@ export const calendarExcluded = ['healthHandler',] as const satisfies readonly (keyof CalendarSdk)[];-export const calendarBacklog =- [] as const satisfies readonly (keyof CalendarSdk)[];+export const calendarBacklog = [+ // Team sharing and availability preferences use the generated client for now.+ 'getAvailabilityCalendars',+ 'getTeamSharing',+ 'setAvailabilityCalendar',+ 'setTeamSharing',+] as const satisfies readonly (keyof CalendarSdk)[];export const cognitionExcluded = ['addMcpServer',@@ -445,6 +450,8 @@ export const storageBacklog = ['listHarnesses','listInitiatives','listOccurrences',+ // Read-only team projections use the generated client for now.+ 'listTeamCalendar','listTeamOutOfOffice','listUserApiKeys',// Meeting management uses the generated client.diff --git a/rules/ast-grep/ts-feature-components-presentational.yml b/rules/ast-grep/ts-feature-components-presentational.ymlindex 5f0d6a8e48..b7edd1060b 100644--- a/rules/ast-grep/ts-feature-components-presentational.yml+++ b/rules/ast-grep/ts-feature-components-presentational.yml@@ -13,6 +13,7 @@ note: |-untyped wire JSON for property-changed rows. In block-agent, `ui/` isthe presentation layer and `component/` is the composition layer.files:+ - apps/web/src/features/calendar-team/components/**- apps/web/src/features/tasks-view/components/task-board*- apps/web/src/features/routines/components/**- apps/web/src/features/scheduling/components/**diff --git a/rules/ast-grep/ts-feature-core-pure.yml b/rules/ast-grep/ts-feature-core-pure.ymlindex 9b5ab5f10c..bce50334bd 100644--- a/rules/ast-grep/ts-feature-core-pure.yml+++ b/rules/ast-grep/ts-feature-core-pure.yml@@ -15,6 +15,7 @@ note: |-The shared @core/util/base64 codec, cron helpers, and dateSearch/parseTime parser are pure utilities and may be reused.Block-agent names its rendering layers `ui/` and `component/`.files:+ - apps/web/src/features/calendar-team/core/**- apps/web/src/features/tasks-view/core/task-board*- apps/web/src/features/routines/core/**- apps/web/src/features/scheduling/core/**diff --git a/rules/ast-grep/ts-feature-data-no-ui.yml b/rules/ast-grep/ts-feature-data-no-ui.ymlindex 53a6f86395..3c6abf064f 100644--- a/rules/ast-grep/ts-feature-data-no-ui.yml+++ b/rules/ast-grep/ts-feature-data-no-ui.yml@@ -11,6 +11,8 @@ note: |-with fake clients and controllers with fake capabilities; neither importsrendering code, including block-agent’s `ui/` and `component/` layers.files:+ - apps/web/src/features/calendar-team/queries/**+ - apps/web/src/features/calendar-team/primitives/**- apps/web/src/features/tasks-view/queries/task-board*- apps/web/src/features/tasks-view/primitives/create-task-board*- apps/web/src/features/routines/queries/**diff --git a/rules/ast-grep/ts-feature-layers-use-context.yml b/rules/ast-grep/ts-feature-layers-use-context.ymlindex babec682fd..c1369a691b 100644--- a/rules/ast-grep/ts-feature-layers-use-context.yml+++ b/rules/ast-grep/ts-feature-layers-use-context.yml@@ -15,6 +15,10 @@ note: |-`files` in each ts-/tsx-feature-* rule. Block-agent uses `ui/` forpresentation and `component/` for composition.files:+ - apps/web/src/features/calendar-team/queries/**+ - apps/web/src/features/calendar-team/primitives/**+ - apps/web/src/features/calendar-team/components/**+ - apps/web/src/features/calendar-team/views/**- apps/web/src/features/tasks-view/queries/task-board*- apps/web/src/features/tasks-view/primitives/create-task-board*- apps/web/src/features/tasks-view/components/task-board*diff --git a/rules/ast-grep/tsx-feature-components-presentational.yml b/rules/ast-grep/tsx-feature-components-presentational.ymlindex e30b8f3694..34692c9613 100644--- a/rules/ast-grep/tsx-feature-components-presentational.yml+++ b/rules/ast-grep/tsx-feature-components-presentational.yml@@ -13,6 +13,7 @@ note: |-untyped wire JSON for property-changed rows. In block-agent, `ui/` isthe presentation layer and `component/` is the composition layer.files:+ - apps/web/src/features/calendar-team/components/**- apps/web/src/features/tasks-view/components/task-board*- apps/web/src/features/routines/components/**- apps/web/src/features/scheduling/components/**diff --git a/rules/ast-grep/tsx-feature-core-pure.yml b/rules/ast-grep/tsx-feature-core-pure.ymlindex 4f5726a538..095c9a521a 100644--- a/rules/ast-grep/tsx-feature-core-pure.yml+++ b/rules/ast-grep/tsx-feature-core-pure.yml@@ -15,6 +15,7 @@ note: |-The shared @core/util/base64 codec, cron helpers, and dateSearch/parseTime parser are pure utilities and may be reused.Block-agent names its rendering layers `ui/` and `component/`.files:+ - apps/web/src/features/calendar-team/core/**- apps/web/src/features/tasks-view/core/task-board*- apps/web/src/features/routines/core/**- apps/web/src/features/scheduling/core/**diff --git a/rules/ast-grep/tsx-feature-data-no-ui.yml b/rules/ast-grep/tsx-feature-data-no-ui.ymlindex fddd564dc2..4c1af3e60c 100644--- a/rules/ast-grep/tsx-feature-data-no-ui.yml+++ b/rules/ast-grep/tsx-feature-data-no-ui.yml@@ -11,6 +11,8 @@ note: |-with fake clients and controllers with fake capabilities; neither importsrendering code, including block-agent’s `ui/` and `component/` layers.files:+ - apps/web/src/features/calendar-team/queries/**+ - apps/web/src/features/calendar-team/primitives/**- apps/web/src/features/tasks-view/queries/task-board*- apps/web/src/features/tasks-view/primitives/create-task-board*- apps/web/src/features/routines/queries/**diff --git a/rules/ast-grep/tsx-feature-layers-use-context.yml b/rules/ast-grep/tsx-feature-layers-use-context.ymlindex 10e0b03acc..d584e29829 100644--- a/rules/ast-grep/tsx-feature-layers-use-context.yml+++ b/rules/ast-grep/tsx-feature-layers-use-context.yml@@ -15,6 +15,10 @@ note: |-`files` in each ts-/tsx-feature-* rule. Block-agent uses `ui/` forpresentation and `component/` for composition.files:+ - apps/web/src/features/calendar-team/queries/**+ - apps/web/src/features/calendar-team/primitives/**+ - apps/web/src/features/calendar-team/components/**+ - apps/web/src/features/calendar-team/views/**- apps/web/src/features/tasks-view/queries/task-board*- apps/web/src/features/tasks-view/primitives/create-task-board*- apps/web/src/features/tasks-view/components/task-board*diff --git a/services/calendar_service/src/api.rs b/services/calendar_service/src/api.rsindex f96da33981..ab886b2229 100644--- a/services/calendar_service/src/api.rs+++ b/services/calendar_service/src/api.rs@@ -61,10 +61,17 @@ fn swagger_ui() -> Router {}fn api_router(state: ApiContext) -> Router<ApiContext> {+ let team_settings = calendar_events::inbound::team_router::team_calendar_settings_router(+ calendar_events::inbound::team_router::CalendarTeamRouterState::new(+ state.calendar_team_service.clone(),+ state.authorization_state.clone(),+ ),+ );// Calendar mutations follow the calendar sync kill switch: without sync a// provider write would never be reflected locally.if state.config.calendar_sync_enabled {calendar_watch::router()+ .merge(team_settings).nest("/scheduling",calendar_scheduling::inbound::router::router(@@ -79,6 +86,6 @@ fn api_router(state: ApiContext) -> Router<ApiContext> {state.authorization_state.clone(),)))} else {- calendar_watch::router()+ calendar_watch::router().merge(team_settings)}}diff --git a/services/calendar_service/src/api/context.rs b/services/calendar_service/src/api/context.rsindex 3e6a097448..08d1a4fe97 100644--- a/services/calendar_service/src/api/context.rs+++ b/services/calendar_service/src/api/context.rs@@ -18,6 +18,11 @@ use crate::config::Config;pub type AuthorizationService = MacroAuthorizationServiceImpl<MacroAuthJwtValidator>;/// Calendar grant/watch service backing the push webhook.pub type CalendarGrantService = CalendarService<PgCalendarRepository>;+/// Team-sharing policy service with viewer refresh notifications.+pub type CalendarTeamSvc = calendar_events::domain::team::CalendarTeamServiceImpl<+ calendar_events::outbound::pg_team::PgCalendarTeamRepository,+ ConnectionGatewayCalendarRefresh,+>;/// Booking policy backed by calendar services and the team directory.pub type SchedulingService = calendar_scheduling::domain::service::Service<calendar_scheduling::outbound::postgres::PostgresRepository,@@ -49,6 +54,8 @@ pub struct ApiContext {pub calendar_service: Arc<CalendarGrantService>,/// User-initiated calendar mutation service.pub calendar_mutation_service: Arc<CalendarMutationSvc>,+ /// Read-only team-sharing preferences and personal availability inclusion.+ pub calendar_team_service: Arc<CalendarTeamSvc>,/// Personal and team scheduling service.pub scheduling_service: Arc<SchedulingService>,}diff --git a/services/calendar_service/src/api/swagger.rs b/services/calendar_service/src/api/swagger.rsindex c9bc578b1b..233d901cc8 100644--- a/services/calendar_service/src/api/swagger.rs+++ b/services/calendar_service/src/api/swagger.rs@@ -9,6 +9,10 @@ use utoipa::OpenApi;#[openapi(paths(crate::health::health_handler,+ calendar_events::inbound::team_router::get_team_sharing,+ calendar_events::inbound::team_router::set_team_sharing,+ calendar_events::inbound::team_router::get_availability_calendars,+ calendar_events::inbound::team_router::set_availability_calendar,calendar_events::inbound::mutation_router::list_calendars,calendar_events::inbound::mutation_router::create_calendar_event,calendar_events::inbound::mutation_router::update_calendar_event,@@ -16,6 +20,11 @@ use utoipa::OpenApi;calendar_events::inbound::mutation_router::rsvp_calendar_event,),components(schemas(+ calendar_events::inbound::team_router::TeamCalendarSharingBody,+ calendar_events::inbound::team_router::AvailabilityCalendarBody,+ calendar_events::inbound::team_router::AvailabilityCalendarsResponse,+ calendar_events::domain::team::TeamCalendarSharing,+ calendar_events::domain::team::AvailabilityCalendar,calendar_events::inbound::mutation_router::CreateCalendarEventRequest,calendar_events::inbound::mutation_router::ListCalendarsResponse,calendar_events::domain::models::VisibleCalendar,diff --git a/services/calendar_service/src/calendar_backfill.rs b/services/calendar_service/src/calendar_backfill.rsindex 7ce59e6325..bb9782b9e2 100644--- a/services/calendar_service/src/calendar_backfill.rs+++ b/services/calendar_service/src/calendar_backfill.rs@@ -66,6 +66,7 @@ pub struct CalendarBackfillContext {failure: Arc<GoogleCalendarBackfillFailureHandler>,reauth: Arc<CalendarReauth>,calendar_sync_enabled: bool,+ team_sharing_enabled: bool,}impl CalendarBackfillContext {@@ -82,6 +83,7 @@ impl CalendarBackfillContext {reauth_notifier: LinkManagerReauthNotifier,watch: Option<GoogleWatchConfig>,calendar_sync_enabled: bool,+ team_sharing_enabled: bool,) -> Self {let repository = PgCalendarRepository::new(db.clone());let coordinator = Arc::new(GoogleCalendarBackfillCoordinator::new(@@ -109,6 +111,7 @@ impl CalendarBackfillContext {failure,reauth,calendar_sync_enabled,+ team_sharing_enabled,}}}@@ -319,6 +322,7 @@ async fn run_coordinator(&ctx.db,link.macro_id.as_ref(),link.id,+ ctx.team_sharing_enabled,).await;}diff --git a/services/calendar_service/src/calendar_refresh.rs b/services/calendar_service/src/calendar_refresh.rsindex 9033434f82..fe25983b11 100644--- a/services/calendar_service/src/calendar_refresh.rs+++ b/services/calendar_service/src/calendar_refresh.rs@@ -14,12 +14,21 @@ use crate::pubsub_util::cg_refresh_calendar;pub struct ConnectionGatewayCalendarRefresh {client: ConnectionGatewayClient,db: sqlx::PgPool,+ team_sharing_enabled: bool,}impl ConnectionGatewayCalendarRefresh {/// Construct the adapter.- pub fn new(client: ConnectionGatewayClient, db: sqlx::PgPool) -> Self {- Self { client, db }+ pub fn new(+ client: ConnectionGatewayClient,+ db: sqlx::PgPool,+ team_sharing_enabled: bool,+ ) -> Self {+ Self {+ client,+ db,+ team_sharing_enabled,+ }}}@@ -31,8 +40,20 @@ impl CalendarRefreshNotifier for ConnectionGatewayCalendarRefresh {let client = self.client.clone();let db = self.db.clone();let owner_id = owner_id.to_string();+ let team_sharing_enabled = self.team_sharing_enabled;tokio::spawn(async move {- cg_refresh_calendar(&client, &db, &owner_id, email_link_id).await;+ cg_refresh_calendar(&client, &db, &owner_id, email_link_id, team_sharing_enabled).await;+ });+ }+}++impl calendar_events::domain::team::CalendarTeamNotifier for ConnectionGatewayCalendarRefresh {+ async fn sharing_changed(&self, user_id: &str) {+ let client = self.client.clone();+ let db = self.db.clone();+ let user_id = user_id.to_owned();+ tokio::spawn(async move {+ crate::pubsub_util::cg_refresh_team_calendar(&client, &db, &[user_id]).await;});}}diff --git a/services/calendar_service/src/config.rs b/services/calendar_service/src/config.rsindex 55a473ddd0..9e88d192a0 100644--- a/services/calendar_service/src/config.rs+++ b/services/calendar_service/src/config.rs@@ -56,6 +56,10 @@ pub struct Config {#[macro_config_default(false)]pub calendar_sync_enabled: bool,+ /// Enable read-only calendar projections shared with current teammates.+ #[macro_config_default(false)]+ pub calendar_team_sharing_enabled: bool,+/// Auth service secret key, used for internal accesspub authentication_service_secret_key: LocalOrRemoteSecret<AuthenticationServiceSecretKey>,diff --git a/services/calendar_service/src/main.rs b/services/calendar_service/src/main.rsindex b1a9a3d9b1..b29b440f12 100644--- a/services/calendar_service/src/main.rs+++ b/services/calendar_service/src/main.rs@@ -154,6 +154,7 @@ async fn main() -> anyhow::Result<()> {reauth_notifier.clone(),calendar_watch_config(),config.calendar_sync_enabled,+ config.calendar_team_sharing_enabled,);let cancellation_token = worker_cancellation_token.clone();worker_tracker.spawn(async move {@@ -178,7 +179,21 @@ async fn main() -> anyhow::Result<()> {PgUserApiKeyAuthorizer::new(PgUserApiKeyAuthorizationRepo::new(db.clone())),)));- let calendar_service = Arc::new(CalendarService::new(PgCalendarRepository::new(db.clone())));+ let calendar_service = Arc::new(+ CalendarService::new(PgCalendarRepository::new(db.clone()))+ .with_team_sharing_enabled(config.calendar_team_sharing_enabled),+ );+ let calendar_team_service = Arc::new(+ calendar_events::domain::team::CalendarTeamServiceImpl::with_notifier(+ calendar_events::outbound::pg_team::PgCalendarTeamRepository::new(db.clone()),+ ConnectionGatewayCalendarRefresh::new(+ connection_gateway_client.clone(),+ db.clone(),+ config.calendar_team_sharing_enabled,+ ),+ config.calendar_team_sharing_enabled,+ ),+ );let calendar_mutation_service = Arc::new(CalendarMutationServiceImpl::new(PgCalendarRepository::new(db.clone()),GoogleCalendarClient::with_gate(@@ -190,7 +205,11 @@ async fn main() -> anyhow::Result<()> {),CalendarTokenProviderAdapter::new(redis_conn, Arc::new(auth_service_client)),macro_event_broker.clone(),- ConnectionGatewayCalendarRefresh::new(connection_gateway_client, db.clone()),+ ConnectionGatewayCalendarRefresh::new(+ connection_gateway_client,+ db.clone(),+ config.calendar_team_sharing_enabled,+ ),));let scheduling_service = Arc::new(calendar_scheduling::domain::service::Service::new(@@ -219,6 +238,7 @@ async fn main() -> anyhow::Result<()> {authorization_state,calendar_service,calendar_mutation_service,+ calendar_team_service,scheduling_service,}).await;diff --git a/services/calendar_service/src/pubsub_util.rs b/services/calendar_service/src/pubsub_util.rsindex 05a975debb..50a3e4922a 100644--- a/services/calendar_service/src/pubsub_util.rs+++ b/services/calendar_service/src/pubsub_util.rs@@ -1,6 +1,7 @@//! Shared calendar pubsub helpers.use connection_gateway_client::client::ConnectionGatewayClient;+use futures::{StreamExt, stream};/// Signal every viewer of a connected inbox's calendars — the link owner/// plus its delegated users — that the calendar projection changed. Best@@ -11,6 +12,7 @@ pub async fn cg_refresh_calendar(db: &sqlx::PgPool,owner_macro_id: &str,link_id: uuid::Uuid,+ team_sharing_enabled: bool,) {if !cfg!(feature = "connection_gateway") {return;@@ -34,6 +36,9 @@ pub async fn cg_refresh_calendar(}recipients.sort();recipients.dedup();+ if team_sharing_enabled {+ cg_refresh_team_calendar(client, db, &recipients).await;+ }for macro_id in recipients {let _ = client.refresh_calendar(¯o_id, payload.clone())@@ -43,3 +48,51 @@ pub async fn cg_refresh_calendar();}}++/// Invalidate teammate projections without exposing the underlying inbox IDs.+#[tracing::instrument(skip(client, db, shared_by))]+pub async fn cg_refresh_team_calendar(+ client: &ConnectionGatewayClient,+ db: &sqlx::PgPool,+ shared_by: &[String],+) {+ if !cfg!(feature = "connection_gateway") || shared_by.is_empty() {+ return;+ }+ let recipients = sqlx::query_scalar!(+ r#"+ SELECT DISTINCT teammate.user_id+ FROM team_user membership+ JOIN team_user teammate ON teammate.team_id = membership.team_id+ WHERE membership.user_id = ANY($1::text[])+ UNION+ SELECT unnest($1::text[])+ "#,+ shared_by,+ )+ .fetch_all(db)+ .await;+ let recipients = match recipients {+ Ok(recipients) => recipients,+ Err(error) => {+ tracing::warn!(error=?error, "failed to resolve team calendar refresh recipients");+ return;+ }+ };+ let payload = serde_json::json!({"event": "team_sharing_changed"});+ stream::iter(recipients.into_iter().flatten())+ .for_each_concurrent(16, |user_id| {+ let payload = payload.clone();+ async move {+ match tokio::time::timeout(+ std::time::Duration::from_secs(3),+ client.refresh_calendar(&user_id, payload),+ ).await {+ Ok(Ok(_)) => {},+ Ok(Err(error)) => tracing::warn!(error=?error, "failed to invalidate a team calendar projection"),+ Err(_) => tracing::warn!("team calendar invalidation timed out"),+ }+ }+ })+ .await;+}diff --git a/services/document_cognition_service/src/api/context/test.rs b/services/document_cognition_service/src/api/context/test.rsindex 15f8fd90ef..e63b25778c 100644--- a/services/document_cognition_service/src/api/context/test.rs+++ b/services/document_cognition_service/src/api/context/test.rs@@ -507,6 +507,7 @@ pub async fn test_api_context(pool: sqlx::Pool<sqlx::Postgres>) -> std::sync::Armacro_service_urls::ServiceUrl::owned("http://localhost:0").into(),"test-internal-api-key".to_string(),),+ team_calendar_tool_context: ai_tools::build_team_calendar_tool_context(pool.clone(), true),notification_tool_context: notification_tool_context.clone(),databases_tool_context,forms_tool_context,diff --git a/services/document_cognition_service/src/server.rs b/services/document_cognition_service/src/server.rsindex 6fd5900a61..7d5659e476 100644--- a/services/document_cognition_service/src/server.rs+++ b/services/document_cognition_service/src/server.rs@@ -736,6 +736,12 @@ pub async fn run() -> anyhow::Result<()> {config.environment,),calendar_tool_context,+ team_calendar_tool_context: ai_tools::build_team_calendar_tool_context(+ db.clone(),+ macro_env_var::maybe_read_env("CALENDAR_TEAM_SHARING_ENABLED")+ .and_then(|value| value.parse::<bool>().ok())+ .unwrap_or(false),+ ),notification_tool_context: notification_tool_context.clone(),databases_tool_context,forms_tool_context,diff --git a/services/document_storage_service/src/api.rs b/services/document_storage_service/src/api.rsindex efd10996ce..266d5a6536 100644--- a/services/document_storage_service/src/api.rs+++ b/services/document_storage_service/src/api.rs@@ -216,6 +216,17 @@ fn api_router(state: ApiContext) -> Router {.merge(calendar_events::inbound::axum_router::calendar_router(state.calendar_state.clone(),))+ .merge(calendar_events::inbound::team_router::team_calendar_router(+ calendar_events::inbound::team_router::CalendarTeamRouterState::new(+ std::sync::Arc::new(calendar_events::domain::team::CalendarTeamServiceImpl::new(+ calendar_events::outbound::pg_team::PgCalendarTeamRepository::new(+ state.db.clone(),+ ),+ state.config.calendar_team_sharing_enabled,+ )),+ state.authorization_state.clone(),+ ),+ )).nest("/channels",channels::inbound::axum_router::channels_router(state.channels_state.clone()),diff --git a/services/document_storage_service/src/api/swagger.rs b/services/document_storage_service/src/api/swagger.rsindex b0a8a3a170..cdccdd7642 100644--- a/services/document_storage_service/src/api/swagger.rs+++ b/services/document_storage_service/src/api/swagger.rs@@ -218,6 +218,7 @@ use utoipa::OpenApi;calendar_events::inbound::axum_router::list_occurrences,calendar_events::inbound::axum_router::mention_previews,calendar_events::inbound::axum_router::list_team_out_of_office,+ calendar_events::inbound::team_router::list_team_calendar,// annotationsannotations::get::get_document_anchors_handler,@@ -613,6 +614,13 @@ use utoipa::OpenApi;calendar_events::inbound::axum_router::CalendarMentionPreviewKind,calendar_events::inbound::axum_router::TeamOutOfOfficeItem,calendar_events::inbound::axum_router::TeamOutOfOfficeResponse,+ calendar_events::domain::team::TeamCalendarPage,+ calendar_events::domain::team::TeamCalendarItem,+ calendar_events::domain::team::TeamCalendarContent,+ calendar_events::domain::team::TeamCalendarDetails,+ calendar_events::domain::team::TeamCalendarMember,+ calendar_events::domain::team::TeamCalendarSharing,+ calendar_events::domain::team::TeamCalendarCoverage,calendar_events::domain::models::CalendarMentionEvent,calendar_events::domain::models::CalendarSyncStatus,SoupItemWithProperties,diff --git a/services/document_storage_service/src/config.rs b/services/document_storage_service/src/config.rsindex d571af0e59..10f161241d 100644--- a/services/document_storage_service/src/config.rs+++ b/services/document_storage_service/src/config.rs@@ -154,6 +154,10 @@ pub struct Config {#[macro_config_default(false)]pub calendar_search_enabled: bool,+ /// Enable read-only calendar projections shared with current teammates.+ #[macro_config_default(false)]+ pub calendar_team_sharing_enabled: bool,+/// Enable Slack import creation and uploads. Existing receipts remain/// readable, finalizable and cancellable when this switch is off.#[macro_config_default(false)]diff --git a/services/document_storage_service/src/server.rs b/services/document_storage_service/src/server.rsindex 39ab28cea4..7754a16229 100644--- a/services/document_storage_service/src/server.rs+++ b/services/document_storage_service/src/server.rs@@ -1757,8 +1757,18 @@ pub async fn run() -> anyhow::Result<()> {),),);- let calendar_state =- CalendarRouterState::new(calendar_read_service, authorization_state.clone());+ // Team policy reads use the primary so a sharing downgrade cannot be+ // served from a lagging replica. The GraphQL own-calendar feed retains+ // its existing readonly-pool routing.+ let calendar_state = CalendarRouterState::new(+ Arc::new(+ calendar_events::domain::service::CalendarService::new(+ calendar_events::outbound::pg::PgCalendarRepository::new(db.clone()),+ )+ .with_team_sharing_enabled(config.calendar_team_sharing_enabled),+ ),+ authorization_state.clone(),+ );// Calendar writes belong to calendar_service; each GraphQL mutation then// answers from the primary so it reads the state its write committed.let graphql_calendar_mutation_context = graphql_calendar::CalendarGraphqlMutationContext::new(diff --git a/services/mcp_service/src/context.rs b/services/mcp_service/src/context.rsindex 9cf6fe09e5..af2cfa0723 100644--- a/services/mcp_service/src/context.rs+++ b/services/mcp_service/src/context.rs@@ -471,6 +471,12 @@ async fn build_tool_context(args: ToolContextBuildArgs<'_>) -> anyhow::Result<Toconfig.environment,),calendar_tool_context,+ team_calendar_tool_context: ai_tools::build_team_calendar_tool_context(+ db.clone(),+ macro_env_var::maybe_read_env("CALENDAR_TEAM_SHARING_ENABLED")+ .and_then(|value| value.parse::<bool>().ok())+ .unwrap_or(false),+ ),notification_tool_context,databases_tool_context,forms_tool_context,