Skip to content

armgit / macro

Public Imported from GitHub
0

Macro is a unified workspace for teams: email, chat, docs, tasks, agents, calls, and CRM — @-linked together with shared AI memory.

feat(call): add provider-independent call entity model (#7660)

Eric Hayes7d0ae26de296
diff --git a/.sqlx/query-03c1f300effe353d4fbd0edadb14d47d823a7b30fb531e515758ef72919cd9df.json b/.sqlx/query-03c1f300effe353d4fbd0edadb14d47d823a7b30fb531e515758ef72919cd9df.json
deleted file mode 100644
index 30b8a29f8c..0000000000
--- a/.sqlx/query-03c1f300effe353d4fbd0edadb14d47d823a7b30fb531e515758ef72919cd9df.json
+++ /dev/null
@@ -1,14 +0,0 @@
-{
- "db_name": "PostgreSQL",
- "query": "DELETE FROM agent_session WHERE id = $1",
- "describe": {
- "columns": [],
- "parameters": {
- "Left": [
- "Uuid"
- ]
- },
- "nullable": []
- },
- "hash": "03c1f300effe353d4fbd0edadb14d47d823a7b30fb531e515758ef72919cd9df"
-}
diff --git a/.sqlx/query-521e016780b024ace9d5c2863cbdf7bdd9f9488751a8121835d13bb8cb74e22b.json b/.sqlx/query-0a3753647863cd45dc6080913118a7398b5cef91303e9f034cb981ba8834603d.json
similarity index 69%
rename from .sqlx/query-521e016780b024ace9d5c2863cbdf7bdd9f9488751a8121835d13bb8cb74e22b.json
rename to .sqlx/query-0a3753647863cd45dc6080913118a7398b5cef91303e9f034cb981ba8834603d.json
index 9a0125fc0f..7ab3bc0873 100644
--- a/.sqlx/query-521e016780b024ace9d5c2863cbdf7bdd9f9488751a8121835d13bb8cb74e22b.json
+++ b/.sqlx/query-0a3753647863cd45dc6080913118a7398b5cef91303e9f034cb981ba8834603d.json
@@ -1,6 +1,6 @@
{
"db_name": "PostgreSQL",
- "query": "\n SELECT\n share_permission.\"linkShareAccessLevel\" AS \"access_level!: AccessLevel\"\n FROM \"SharePermission\" share_permission\n JOIN (\n SELECT share_permission_id\n FROM calls\n WHERE id = $1\n\n UNION ALL\n\n SELECT share_permission_id\n FROM call_records\n WHERE id = $1\n LIMIT 1\n ) call_item ON call_item.share_permission_id = share_permission.id\n WHERE share_permission.\"linkShare\" = 'PUBLIC'\n AND share_permission.\"linkShareAccessLevel\" IS NOT NULL\n ",
+ "query": "\n SELECT\n share_permission.\"linkShareAccessLevel\" AS \"access_level!: AccessLevel\"\n FROM \"SharePermission\" share_permission\n JOIN (\n SELECT share_permission_id FROM call_entities WHERE id = $1\n ) call_item ON call_item.share_permission_id = share_permission.id\n WHERE share_permission.\"linkShare\" = 'PUBLIC'\n AND share_permission.\"linkShareAccessLevel\" IS NOT NULL\n ",
"describe": {
"columns": [
{
@@ -30,5 +30,5 @@
true
]
},
- "hash": "521e016780b024ace9d5c2863cbdf7bdd9f9488751a8121835d13bb8cb74e22b"
+ "hash": "0a3753647863cd45dc6080913118a7398b5cef91303e9f034cb981ba8834603d"
}
diff --git a/.sqlx/query-4742c6a50a7c9c9eaea6253c574207e1fb569e858d233061a8b2104f4c010fb6.json b/.sqlx/query-4742c6a50a7c9c9eaea6253c574207e1fb569e858d233061a8b2104f4c010fb6.json
deleted file mode 100644
index 5498308486..0000000000
--- a/.sqlx/query-4742c6a50a7c9c9eaea6253c574207e1fb569e858d233061a8b2104f4c010fb6.json
+++ /dev/null
@@ -1,16 +0,0 @@
-{
- "db_name": "PostgreSQL",
- "query": "UPDATE agent_session SET turn_action_id = $2, turn_state = $3 WHERE id = $1",
- "describe": {
- "columns": [],
- "parameters": {
- "Left": [
- "Uuid",
- "Uuid",
- "Text"
- ]
- },
- "nullable": []
- },
- "hash": "4742c6a50a7c9c9eaea6253c574207e1fb569e858d233061a8b2104f4c010fb6"
-}
diff --git a/.sqlx/query-169aff669342e0bcf9bee8306009716589d4671ade11f841d0cbcf2c5986ce5c.json b/.sqlx/query-5bfb1fe94e84c5b3cc01741fc11a59c329b50919a786ba127255d7f096c8a1ad.json
similarity index 56%
rename from .sqlx/query-169aff669342e0bcf9bee8306009716589d4671ade11f841d0cbcf2c5986ce5c.json
rename to .sqlx/query-5bfb1fe94e84c5b3cc01741fc11a59c329b50919a786ba127255d7f096c8a1ad.json
index 3aaadcab92..6a213de819 100644
--- a/.sqlx/query-169aff669342e0bcf9bee8306009716589d4671ade11f841d0cbcf2c5986ce5c.json
+++ b/.sqlx/query-5bfb1fe94e84c5b3cc01741fc11a59c329b50919a786ba127255d7f096c8a1ad.json
@@ -1,6 +1,6 @@
{
"db_name": "PostgreSQL",
- "query": "SELECT EXISTS(SELECT 1 FROM calls WHERE id = $1 UNION ALL SELECT 1 FROM call_records WHERE id = $1) AS \"exists!\"",
+ "query": "SELECT EXISTS(SELECT 1 FROM call_entities WHERE id = $1) AS \"exists!\"",
"describe": {
"columns": [
{
@@ -18,5 +18,5 @@
null
]
},
- "hash": "169aff669342e0bcf9bee8306009716589d4671ade11f841d0cbcf2c5986ce5c"
+ "hash": "5bfb1fe94e84c5b3cc01741fc11a59c329b50919a786ba127255d7f096c8a1ad"
}
diff --git a/.sqlx/query-768a058ebc239672e75f959eb9aa6976f4b1846bf82d03580249579cf8ccc55a.json b/.sqlx/query-6db3da8924f9708b03ecacc59e33112ba3120ffe0cb018831f61ba250f3a5e67.json
similarity index 56%
rename from .sqlx/query-768a058ebc239672e75f959eb9aa6976f4b1846bf82d03580249579cf8ccc55a.json
rename to .sqlx/query-6db3da8924f9708b03ecacc59e33112ba3120ffe0cb018831f61ba250f3a5e67.json
index 307e76bc75..2315e77c21 100644
--- a/.sqlx/query-768a058ebc239672e75f959eb9aa6976f4b1846bf82d03580249579cf8ccc55a.json
+++ b/.sqlx/query-6db3da8924f9708b03ecacc59e33112ba3120ffe0cb018831f61ba250f3a5e67.json
@@ -1,6 +1,6 @@
{
"db_name": "PostgreSQL",
- "query": "\n SELECT channel_id AS \"channel_id?\", share_permission_id AS \"share_permission_id!\"\n FROM calls\n WHERE id = $1\n UNION ALL\n SELECT channel_id, share_permission_id\n FROM call_records\n WHERE id = $1\n LIMIT 1\n ",
+ "query": "\n SELECT channel_id AS \"channel_id?\", share_permission_id AS \"share_permission_id!\"\n FROM call_entities\n WHERE id = $1\n ",
"describe": {
"columns": [
{
@@ -20,9 +20,9 @@
]
},
"nullable": [
- null,
- null
+ true,
+ false
]
},
- "hash": "768a058ebc239672e75f959eb9aa6976f4b1846bf82d03580249579cf8ccc55a"
+ "hash": "6db3da8924f9708b03ecacc59e33112ba3120ffe0cb018831f61ba250f3a5e67"
}
diff --git a/.sqlx/query-816c121dc4e7251b4b7beaf9a31fa9c2f755230fa890bc45099a0a6fbdf422cb.json b/.sqlx/query-816c121dc4e7251b4b7beaf9a31fa9c2f755230fa890bc45099a0a6fbdf422cb.json
deleted file mode 100644
index 3e65c653d8..0000000000
--- a/.sqlx/query-816c121dc4e7251b4b7beaf9a31fa9c2f755230fa890bc45099a0a6fbdf422cb.json
+++ /dev/null
@@ -1,14 +0,0 @@
-{
- "db_name": "PostgreSQL",
- "query": "UPDATE agent_session SET turn_state = 'running', is_archived = true WHERE id = $1",
- "describe": {
- "columns": [],
- "parameters": {
- "Left": [
- "Uuid"
- ]
- },
- "nullable": []
- },
- "hash": "816c121dc4e7251b4b7beaf9a31fa9c2f755230fa890bc45099a0a6fbdf422cb"
-}
diff --git a/.sqlx/query-fcd4b2c0a70c138c4efcc3698f6fe4522197997819944c08284ce264554b1012.json b/.sqlx/query-9a0ce2e68e7761f11a2070192b7baa85785adc28568d5a315e4315af116990c5.json
similarity index 58%
rename from .sqlx/query-fcd4b2c0a70c138c4efcc3698f6fe4522197997819944c08284ce264554b1012.json
rename to .sqlx/query-9a0ce2e68e7761f11a2070192b7baa85785adc28568d5a315e4315af116990c5.json
index e1e246c8c9..9f5215deb3 100644
--- a/.sqlx/query-fcd4b2c0a70c138c4efcc3698f6fe4522197997819944c08284ce264554b1012.json
+++ b/.sqlx/query-9a0ce2e68e7761f11a2070192b7baa85785adc28568d5a315e4315af116990c5.json
@@ -1,6 +1,6 @@
{
"db_name": "PostgreSQL",
- "query": "\n SELECT\n share_permission.\"linkShareAccessLevel\" AS \"access_level!: AccessLevel\"\n FROM \"SharePermission\" share_permission\n JOIN (\n SELECT share_permission_id\n FROM calls\n WHERE id = $1\n\n UNION ALL\n\n SELECT share_permission_id\n FROM call_records\n WHERE id = $1\n LIMIT 1\n ) call_item ON call_item.share_permission_id = share_permission.id\n WHERE share_permission.\"linkShare\" = 'PUBLIC'\n AND share_permission.\"linkShareAccessLevel\" IS NOT NULL\n ",
+ "query": "\n SELECT\n share_permission.\"linkShareAccessLevel\" AS \"access_level!: AccessLevel\"\n FROM \"SharePermission\" share_permission\n JOIN (\n SELECT share_permission_id FROM call_entities WHERE id = $1\n ) call_item ON call_item.share_permission_id = share_permission.id\n WHERE share_permission.\"linkShare\" = 'PUBLIC'\n AND share_permission.\"linkShareAccessLevel\" IS NOT NULL\n ",
"describe": {
"columns": [
{
@@ -30,5 +30,5 @@
true
]
},
- "hash": "fcd4b2c0a70c138c4efcc3698f6fe4522197997819944c08284ce264554b1012"
+ "hash": "9a0ce2e68e7761f11a2070192b7baa85785adc28568d5a315e4315af116990c5"
}
diff --git a/.sqlx/query-e68554daf5eb02338102760b6632243ecd9a4139517a7c70ac38e29b7758f01c.json b/.sqlx/query-b879fc8a19242d356478c8261f9fa4560a30f877251a1b49b2813f61e15c3d93.json
similarity index 58%
rename from .sqlx/query-e68554daf5eb02338102760b6632243ecd9a4139517a7c70ac38e29b7758f01c.json
rename to .sqlx/query-b879fc8a19242d356478c8261f9fa4560a30f877251a1b49b2813f61e15c3d93.json
index dd09baead3..941948db08 100644
--- a/.sqlx/query-e68554daf5eb02338102760b6632243ecd9a4139517a7c70ac38e29b7758f01c.json
+++ b/.sqlx/query-b879fc8a19242d356478c8261f9fa4560a30f877251a1b49b2813f61e15c3d93.json
@@ -1,6 +1,6 @@
{
"db_name": "PostgreSQL",
- "query": "\n SELECT\n share_permission.\"linkShareAccessLevel\" AS \"access_level!: AccessLevel\",\n owner_team.team_id AS \"owner_team_id!\"\n FROM \"SharePermission\" share_permission\n JOIN (\n SELECT share_permission_id, created_by\n FROM calls\n WHERE id = $1\n\n UNION ALL\n\n SELECT share_permission_id, created_by\n FROM call_records\n WHERE id = $1\n LIMIT 1\n ) call_item ON call_item.share_permission_id = share_permission.id\n JOIN team_user owner_team\n ON owner_team.user_id = call_item.created_by\n AND owner_team.team_id::text = ANY($2)\n WHERE share_permission.\"linkShare\" = 'TEAM'\n AND share_permission.\"linkShareAccessLevel\" IS NOT NULL\n ",
+ "query": "\n SELECT\n share_permission.\"linkShareAccessLevel\" AS \"access_level!: AccessLevel\",\n owner_team.team_id AS \"owner_team_id!\"\n FROM \"SharePermission\" share_permission\n JOIN (\n SELECT share_permission_id, user_id AS created_by FROM call_entities WHERE id = $1\n ) call_item ON call_item.share_permission_id = share_permission.id\n JOIN team_user owner_team\n ON owner_team.user_id = call_item.created_by\n AND owner_team.team_id::text = ANY($2)\n WHERE share_permission.\"linkShare\" = 'TEAM'\n AND share_permission.\"linkShareAccessLevel\" IS NOT NULL\n ",
"describe": {
"columns": [
{
@@ -37,5 +37,5 @@
false
]
},
- "hash": "e68554daf5eb02338102760b6632243ecd9a4139517a7c70ac38e29b7758f01c"
+ "hash": "b879fc8a19242d356478c8261f9fa4560a30f877251a1b49b2813f61e15c3d93"
}
diff --git a/.sqlx/query-bda67ef0d33a9aff0acc58e5e87e8b55b9df468042dc22246eb7bd7d8c5cab8b.json b/.sqlx/query-bda67ef0d33a9aff0acc58e5e87e8b55b9df468042dc22246eb7bd7d8c5cab8b.json
new file mode 100644
index 0000000000..3e9dcd6990
--- /dev/null
+++ b/.sqlx/query-bda67ef0d33a9aff0acc58e5e87e8b55b9df468042dc22246eb7bd7d8c5cab8b.json
@@ -0,0 +1,23 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n SELECT access_level FROM (\n -- Source 1: entity_access source_id match\n SELECT\n access_level::text FROM entity_access\n WHERE entity_id = $1\n AND entity_type = 'call'\n AND source_id = ANY($2)\n\n UNION ALL\n -- Source 2: call link share permission\n SELECT\n share_permission.\"linkShareAccessLevel\"::text AS access_level\n FROM \"SharePermission\" share_permission\n JOIN (\n SELECT share_permission_id, user_id AS created_by FROM call_entities WHERE id = $1\n ) call_item ON call_item.share_permission_id = share_permission.id\n WHERE share_permission.\"linkShareAccessLevel\" IS NOT NULL\n AND (\n share_permission.\"linkShare\" = 'PUBLIC'\n OR (\n share_permission.\"linkShare\" = 'TEAM'\n AND EXISTS (\n SELECT 1\n FROM team_user owner_team\n WHERE owner_team.user_id = call_item.created_by\n AND owner_team.team_id::text = ANY($2)\n )\n )\n )\n ) AS combined_access\n ",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "access_level",
+ "type_info": "Text"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Uuid",
+ "TextArray"
+ ]
+ },
+ "nullable": [
+ null
+ ]
+ },
+ "hash": "bda67ef0d33a9aff0acc58e5e87e8b55b9df468042dc22246eb7bd7d8c5cab8b"
+}
diff --git a/.sqlx/query-c709131deddbceb7a7ce6643b03bf9144b089fab54e5f4bdba5d434288d48e6d.json b/.sqlx/query-c709131deddbceb7a7ce6643b03bf9144b089fab54e5f4bdba5d434288d48e6d.json
deleted file mode 100644
index 194760779f..0000000000
--- a/.sqlx/query-c709131deddbceb7a7ce6643b03bf9144b089fab54e5f4bdba5d434288d48e6d.json
+++ /dev/null
@@ -1,80 +0,0 @@
-{
- "db_name": "PostgreSQL",
- "query": "\n SELECT id, macro_id, fusionauth_user_id, email_address, provider as \"provider: _\",\n is_sync_active, is_primary, created_at, updated_at\n FROM email_links\n WHERE macro_id = $1\n LIMIT 1\n ",
- "describe": {
- "columns": [
- {
- "ordinal": 0,
- "name": "id",
- "type_info": "Uuid"
- },
- {
- "ordinal": 1,
- "name": "macro_id",
- "type_info": "Text"
- },
- {
- "ordinal": 2,
- "name": "fusionauth_user_id",
- "type_info": "Text"
- },
- {
- "ordinal": 3,
- "name": "email_address",
- "type_info": "Varchar"
- },
- {
- "ordinal": 4,
- "name": "provider: _",
- "type_info": {
- "Custom": {
- "name": "email_user_provider_enum",
- "kind": {
- "Enum": [
- "GMAIL",
- "OUTLOOK"
- ]
- }
- }
- }
- },
- {
- "ordinal": 5,
- "name": "is_sync_active",
- "type_info": "Bool"
- },
- {
- "ordinal": 6,
- "name": "is_primary",
- "type_info": "Bool"
- },
- {
- "ordinal": 7,
- "name": "created_at",
- "type_info": "Timestamptz"
- },
- {
- "ordinal": 8,
- "name": "updated_at",
- "type_info": "Timestamptz"
- }
- ],
- "parameters": {
- "Left": [
- "Text"
- ]
- },
- "nullable": [
- false,
- false,
- false,
- false,
- false,
- false,
- false,
- false,
- false
- ]
- },
- "hash": "c709131deddbceb7a7ce6643b03bf9144b089fab54e5f4bdba5d434288d48e6d"
-}
diff --git a/.sqlx/query-c73cd6db3f1c9967e7d3d5c4cbc4b60cf24719b480d66713dd707ce7153864d1.json b/.sqlx/query-c73cd6db3f1c9967e7d3d5c4cbc4b60cf24719b480d66713dd707ce7153864d1.json
new file mode 100644
index 0000000000..0750db6e23
--- /dev/null
+++ b/.sqlx/query-c73cd6db3f1c9967e7d3d5c4cbc4b60cf24719b480d66713dd707ce7153864d1.json
@@ -0,0 +1,22 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n SELECT share_permission_id as \"share_permission_id!\"\n FROM call_entities WHERE id = $1\n ",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "share_permission_id!",
+ "type_info": "Text"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Uuid"
+ ]
+ },
+ "nullable": [
+ false
+ ]
+ },
+ "hash": "c73cd6db3f1c9967e7d3d5c4cbc4b60cf24719b480d66713dd707ce7153864d1"
+}
diff --git a/.sqlx/query-cf72111cb8f0154305b4e2ad2cb1f1f26964a3068b3d2909c5450fbb5de66882.json b/.sqlx/query-cf72111cb8f0154305b4e2ad2cb1f1f26964a3068b3d2909c5450fbb5de66882.json
deleted file mode 100644
index 11dd4ad825..0000000000
--- a/.sqlx/query-cf72111cb8f0154305b4e2ad2cb1f1f26964a3068b3d2909c5450fbb5de66882.json
+++ /dev/null
@@ -1,23 +0,0 @@
-{
- "db_name": "PostgreSQL",
- "query": "\n SELECT access_level FROM (\n -- Source 1: entity_access source_id match\n SELECT\n access_level::text FROM entity_access\n WHERE entity_id = $1\n AND entity_type = 'call'\n AND source_id = ANY($2)\n\n UNION ALL\n -- Source 2: call link share permission\n SELECT\n share_permission.\"linkShareAccessLevel\"::text AS access_level\n FROM \"SharePermission\" share_permission\n JOIN (\n SELECT share_permission_id, created_by\n FROM calls\n WHERE id = $1\n\n UNION ALL\n\n SELECT share_permission_id, created_by\n FROM call_records\n WHERE id = $1\n LIMIT 1\n ) call_item ON call_item.share_permission_id = share_permission.id\n WHERE share_permission.\"linkShareAccessLevel\" IS NOT NULL\n AND (\n share_permission.\"linkShare\" = 'PUBLIC'\n OR (\n share_permission.\"linkShare\" = 'TEAM'\n AND EXISTS (\n SELECT 1\n FROM team_user owner_team\n WHERE owner_team.user_id = call_item.created_by\n AND owner_team.team_id::text = ANY($2)\n )\n )\n )\n ) AS combined_access\n ",
- "describe": {
- "columns": [
- {
- "ordinal": 0,
- "name": "access_level",
- "type_info": "Text"
- }
- ],
- "parameters": {
- "Left": [
- "Uuid",
- "TextArray"
- ]
- },
- "nullable": [
- null
- ]
- },
- "hash": "cf72111cb8f0154305b4e2ad2cb1f1f26964a3068b3d2909c5450fbb5de66882"
-}
diff --git a/.sqlx/query-d9ad977df73e6a2e5cf561edfb41d5ab7728a12ca7245876c3ede0c3adc69647.json b/.sqlx/query-d9ad977df73e6a2e5cf561edfb41d5ab7728a12ca7245876c3ede0c3adc69647.json
deleted file mode 100644
index 921f441cd6..0000000000
--- a/.sqlx/query-d9ad977df73e6a2e5cf561edfb41d5ab7728a12ca7245876c3ede0c3adc69647.json
+++ /dev/null
@@ -1,22 +0,0 @@
-{
- "db_name": "PostgreSQL",
- "query": "\n SELECT share_permission_id as \"share_permission_id!\"\n FROM (\n SELECT share_permission_id FROM calls WHERE id = $1\n UNION ALL\n SELECT share_permission_id FROM call_records WHERE id = $1\n ) t\n LIMIT 1\n ",
- "describe": {
- "columns": [
- {
- "ordinal": 0,
- "name": "share_permission_id!",
- "type_info": "Text"
- }
- ],
- "parameters": {
- "Left": [
- "Uuid"
- ]
- },
- "nullable": [
- null
- ]
- },
- "hash": "d9ad977df73e6a2e5cf561edfb41d5ab7728a12ca7245876c3ede0c3adc69647"
-}
diff --git a/.sqlx/query-5a43284afd685db881048bdef2b122f44f1ffef896d82631461a081a380f29d4.json b/.sqlx/query-f1ee541b0fd4854bf373d75d224f61f5ba26e0b11150f19d047788668b30f3ed.json
similarity index 61%
rename from .sqlx/query-5a43284afd685db881048bdef2b122f44f1ffef896d82631461a081a380f29d4.json
rename to .sqlx/query-f1ee541b0fd4854bf373d75d224f61f5ba26e0b11150f19d047788668b30f3ed.json
index bd9c26f516..91b858604b 100644
--- a/.sqlx/query-5a43284afd685db881048bdef2b122f44f1ffef896d82631461a081a380f29d4.json
+++ b/.sqlx/query-f1ee541b0fd4854bf373d75d224f61f5ba26e0b11150f19d047788668b30f3ed.json
@@ -1,6 +1,6 @@
{
"db_name": "PostgreSQL",
- "query": "WITH entity AS (\n SELECT d.owner, dp.\"sharePermissionId\" AS permission_id\n FROM \"Document\" d LEFT JOIN \"DocumentPermission\" dp ON dp.\"documentId\" = d.id\n WHERE $2 = 'document' AND d.id = $1\n UNION ALL\n SELECT p.\"userId\", pp.\"sharePermissionId\"\n FROM \"Project\" p LEFT JOIN \"ProjectPermission\" pp ON pp.\"projectId\" = p.id\n WHERE $2 = 'project' AND p.id = $1\n UNION ALL\n SELECT c.\"userId\", cp.\"sharePermissionId\"\n FROM \"Chat\" c LEFT JOIN \"ChatPermission\" cp ON cp.\"chatId\" = c.id\n WHERE $2 = 'chat' AND c.id = $1\n UNION ALL\n SELECT l.macro_id, tp.\"sharePermissionId\"\n FROM email_threads t JOIN email_links l ON l.id = t.link_id\n LEFT JOIN \"EmailThreadPermission\" tp ON tp.\"threadId\" = t.id::text\n WHERE $2 = 'email_thread' AND t.id = $3\n UNION ALL\n SELECT c.created_by, c.share_permission_id FROM calls c\n WHERE $2 = 'call' AND c.id = $3\n UNION ALL\n SELECT c.created_by, c.share_permission_id FROM call_records c\n WHERE $2 = 'call' AND c.id = $3 AND NOT EXISTS (SELECT 1 FROM calls WHERE id = $3)\n UNION ALL\n SELECT i.owner_user_id, i.share_permission_id FROM initiative i\n WHERE $2 = 'initiative' AND i.id = $3\n UNION ALL\n SELECT s.owner_id, s.share_permission_id FROM agent_session s\n WHERE $2 = 'agent_session' AND s.id = $3\n )\n SELECT e.owner AS \"owner!\", e.permission_id,\n sp.id AS \"stored_permission_id?\",\n sp.team_share_access_level AS \"level: AccessLevel\",\n sp.team_share_team_id AS team_id, sp.team_share_revision AS \"revision?\",\n tu.team_id AS \"user_team?\", b.team_id AS \"bot_team?\", btu.team_id AS \"bot_user_team?\"\n FROM entity e LEFT JOIN \"SharePermission\" sp ON sp.id = e.permission_id\n LEFT JOIN team_user tu ON tu.user_id = e.owner\n LEFT JOIN bots b ON b.id = CASE\n WHEN e.owner ~ '^bot\\|[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$'\n THEN substring(e.owner FROM 5)::uuid END\n LEFT JOIN team_user btu ON btu.user_id = b.owner_user_id",
+ "query": "WITH entity AS (\n SELECT d.owner, dp.\"sharePermissionId\" AS permission_id\n FROM \"Document\" d LEFT JOIN \"DocumentPermission\" dp ON dp.\"documentId\" = d.id\n WHERE $2 = 'document' AND d.id = $1\n UNION ALL\n SELECT p.\"userId\", pp.\"sharePermissionId\"\n FROM \"Project\" p LEFT JOIN \"ProjectPermission\" pp ON pp.\"projectId\" = p.id\n WHERE $2 = 'project' AND p.id = $1\n UNION ALL\n SELECT c.\"userId\", cp.\"sharePermissionId\"\n FROM \"Chat\" c LEFT JOIN \"ChatPermission\" cp ON cp.\"chatId\" = c.id\n WHERE $2 = 'chat' AND c.id = $1\n UNION ALL\n SELECT l.macro_id, tp.\"sharePermissionId\"\n FROM email_threads t JOIN email_links l ON l.id = t.link_id\n LEFT JOIN \"EmailThreadPermission\" tp ON tp.\"threadId\" = t.id::text\n WHERE $2 = 'email_thread' AND t.id = $3\n UNION ALL\n SELECT c.user_id, c.share_permission_id FROM call_entities c\n WHERE $2 = 'call' AND c.id = $3\n UNION ALL\n SELECT i.owner_user_id, i.share_permission_id FROM initiative i\n WHERE $2 = 'initiative' AND i.id = $3\n UNION ALL\n SELECT s.owner_id, s.share_permission_id FROM agent_session s\n WHERE $2 = 'agent_session' AND s.id = $3\n )\n SELECT e.owner AS \"owner!\", e.permission_id,\n sp.id AS \"stored_permission_id?\",\n sp.team_share_access_level AS \"level: AccessLevel\",\n sp.team_share_team_id AS team_id, sp.team_share_revision AS \"revision?\",\n tu.team_id AS \"user_team?\", b.team_id AS \"bot_team?\", btu.team_id AS \"bot_user_team?\"\n FROM entity e LEFT JOIN \"SharePermission\" sp ON sp.id = e.permission_id\n LEFT JOIN team_user tu ON tu.user_id = e.owner\n LEFT JOIN bots b ON b.id = CASE\n WHEN e.owner ~ '^bot\\|[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$'\n THEN substring(e.owner FROM 5)::uuid END\n LEFT JOIN team_user btu ON btu.user_id = b.owner_user_id",
"describe": {
"columns": [
{
@@ -80,5 +80,5 @@
false
]
},
- "hash": "5a43284afd685db881048bdef2b122f44f1ffef896d82631461a081a380f29d4"
+ "hash": "f1ee541b0fd4854bf373d75d224f61f5ba26e0b11150f19d047788668b30f3ed"
}
diff --git a/crates/call/src/domain/mod.rs b/crates/call/src/domain/mod.rs
index 410d76713f..605547250c 100644
--- a/crates/call/src/domain/mod.rs
+++ b/crates/call/src/domain/mod.rs
@@ -20,3 +20,6 @@ pub mod service;
/// Persistent meeting invitations and guest models.
pub mod meetings;
+
+/// Provider-independent durable call entities and optional resources.
+pub mod records;
diff --git a/crates/call/src/domain/records.rs b/crates/call/src/domain/records.rs
new file mode 100644
index 0000000000..55243f210a
--- /dev/null
+++ b/crates/call/src/domain/records.rs
@@ -0,0 +1,252 @@
+//! Provider-independent, durable call records. Native RTC sessions are optional.
+//!
+//! All resources share the existing `call` entity ID and its permissions. A
+//! participant, recording, transcript, collab surface, or discussion is optional.
+//! Native runtime/archive resources continue to use the existing storage tables.
+
+use chrono::{DateTime, Utc};
+use macro_user_id::user_id::MacroUserIdStr;
+use serde::{Deserialize, Serialize};
+use uuid::Uuid;
+
+#[cfg(test)]
+mod test;
+
+/// A nonempty, opaque provider identifier, preserved verbatim.
+#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
+#[serde(try_from = "String", into = "String")]
+pub struct ExternalCallId(String);
+
+impl TryFrom<String> for ExternalCallId {
+ type Error = &'static str;
+
+ fn try_from(value: String) -> Result<Self, Self::Error> {
+ if value.is_empty() {
+ return Err("external call identifiers cannot be empty");
+ }
+ Ok(Self(value))
+ }
+}
+
+impl From<ExternalCallId> for String {
+ fn from(value: ExternalCallId) -> Self {
+ value.0
+ }
+}
+
+impl AsRef<str> for ExternalCallId {
+ fn as_ref(&self) -> &str {
+ &self.0
+ }
+}
+
+/// How the entity was originally created; independent of its media and sources.
+#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
+#[serde(rename_all = "snake_case")]
+pub enum CallCreatedVia {
+ /// A Macro RTC session.
+ Native,
+ /// An integration supplied the record.
+ Import,
+ /// A user supplied a recording.
+ Upload,
+ /// A user entered the record manually.
+ Manual,
+}
+
+/// Supported call and transcript providers. Add variants as integrations grow.
+#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
+#[serde(rename_all = "snake_case")]
+pub enum CallProvider {
+ /// A Macro-native call or transcript.
+ Macro,
+ /// A call or transcript imported from Granola.
+ Granola,
+}
+
+/// Durable product identity, independent of any room or provider.
+#[derive(Debug, Clone, Serialize, Deserialize)]
+#[serde(rename_all = "camelCase")]
+pub struct CallEntity {
+ /// Stable Macro entity ID, preserved when a native call is archived.
+ pub id: Uuid,
+ /// Macro owner, independent of any external organizer.
+ pub user_id: MacroUserIdStr<'static>,
+ /// User-visible title, when known.
+ pub title: Option<String>,
+ /// Original creation mechanism.
+ pub created_via: CallCreatedVia,
+ /// Actual start; an import must not substitute its creation time.
+ pub started_at: Option<DateTime<Utc>>,
+ /// Actual end, independently optional.
+ pub ended_at: Option<DateTime<Utc>>,
+ /// Conversation duration, independent of a recording's length.
+ pub duration_ms: Option<i64>,
+ /// Optional Macro channel association.
+ pub channel_id: Option<Uuid>,
+ /// Optional reusable Macro meeting invitation.
+ pub meeting_id: Option<Uuid>,
+ /// Creation time in Macro, usable for ordering when timing is unknown.
+ pub created_at: DateTime<Utc>,
+ /// Last metadata modification in Macro.
+ pub updated_at: DateTime<Utc>,
+}
+
+/// External object identity. The full tuple is the database uniqueness key.
+///
+/// The importer supplies an authenticated user and an authorized stable account
+/// namespace; provider IDs, titles, or meeting URLs alone are not deduplication keys.
+#[derive(Debug, Clone, Serialize, Deserialize)]
+#[serde(rename_all = "camelCase")]
+pub struct CallSource {
+ /// User whose integration supplied the object; this is not an access grant.
+ pub user_id: MacroUserIdStr<'static>,
+ /// Stable provider-account namespace, retained across credential rotation.
+ pub namespace: String,
+ /// Provider that supplied the source object.
+ pub provider: CallProvider,
+ /// Provider object category, such as `note` or `meeting`.
+ pub object_type: String,
+ /// Opaque provider identifier, not necessarily a UUID.
+ pub external_id: ExternalCallId,
+ /// Stable source permalink, if supplied.
+ pub external_url: Option<String>,
+ /// Provider revision time, distinct from call timing.
+ pub external_updated_at: Option<DateTime<Utc>>,
+ /// Most recent successful synchronization.
+ pub synced_at: Option<DateTime<Utc>>,
+ /// Provider-specific facts, never credentials.
+ #[serde(default)]
+ pub metadata: serde_json::Map<String, serde_json::Value>,
+}
+
+/// A call-local participant or speaker; identification and attendance are optional.
+#[derive(Debug, Clone, Serialize, Deserialize)]
+#[serde(rename_all = "camelCase")]
+pub struct CallParticipant {
+ /// Call-local identity; never use an email address as a primary key.
+ pub id: Uuid,
+ /// Resolved Macro account, if any. Does not confer access.
+ pub user_id: Option<MacroUserIdStr<'static>>,
+ /// Display name when supplied.
+ pub display_name: Option<String>,
+ /// Provider-supplied email address, not proof of identity.
+ pub email: Option<String>,
+ /// Telephone number when supplied.
+ pub phone: Option<String>,
+ /// Opaque participant identifier from the source.
+ pub external_id: Option<ExternalCallId>,
+ /// Known attendance intervals; empty does not mean absent.
+ #[serde(default)]
+ pub attendance: Vec<CallAttendance>,
+}
+
+/// One known attendance interval. Rejoining creates another interval.
+#[derive(Debug, Clone, Serialize, Deserialize)]
+#[serde(rename_all = "camelCase")]
+pub struct CallAttendance {
+ /// Stable interval ID.
+ pub id: Uuid,
+ /// Join instant, if known.
+ pub joined_at: Option<DateTime<Utc>>,
+ /// Leave instant, if known.
+ pub left_at: Option<DateTime<Utc>>,
+}
+
+/// Media actually stored, independent of the medium used for the conversation.
+#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
+#[serde(rename_all = "snake_case")]
+pub enum CallMediaType {
+ /// Audio-only media.
+ Audio,
+ /// Video media, potentially with audio.
+ Video,
+}
+
+/// A stable media locator. Playback URLs must be resolved separately.
+#[derive(Debug, Clone, Serialize, Deserialize)]
+#[serde(tag = "kind", content = "value", rename_all = "snake_case")]
+pub enum CallRecordingLocation {
+ /// Macro-managed object storage key, not a signed URL.
+ StorageKey(String),
+ /// External provider URL; never implies public access to the media.
+ ExternalUrl(String),
+}
+
+/// One of potentially many recordings of a call.
+#[derive(Debug, Clone, Serialize, Deserialize)]
+#[serde(rename_all = "camelCase")]
+pub struct CallRecording {
+ /// Stable recording ID.
+ pub id: Uuid,
+ /// Recorded media type.
+ pub media_type: CallMediaType,
+ /// Stable media reference.
+ pub location: CallRecordingLocation,
+ /// Optional MIME type.
+ pub mime_type: Option<String>,
+ /// Media duration, distinct from call duration.
+ pub duration_ms: Option<i64>,
+ /// Actual media start, if known.
+ pub started_at: Option<DateTime<Utc>>,
+}
+
+/// A transcript version or language, with or without a recording.
+#[derive(Debug, Clone, Serialize, Deserialize)]
+#[serde(rename_all = "camelCase")]
+pub struct CallTranscript {
+ /// Stable transcript ID.
+ pub id: Uuid,
+ /// Optional recording in the same call.
+ pub recording_id: Option<Uuid>,
+ /// Language tag, if known.
+ pub language: Option<String>,
+ /// Provider that supplied the transcript, independently of the call's source.
+ pub provider: Option<CallProvider>,
+ /// Optional absolute origin for transcript offsets.
+ pub started_at: Option<DateTime<Utc>>,
+ /// Ordered content; missing timing and speaker information remain absent.
+ #[serde(default)]
+ pub segments: Vec<CallTranscriptSegment>,
+}
+
+/// One ordered text segment. Text-only imports need no fabricated timestamps.
+#[derive(Debug, Clone, Serialize, Deserialize)]
+#[serde(rename_all = "camelCase")]
+pub struct CallTranscriptSegment {
+ /// Stable ordering within a transcript, independent of timing.
+ pub sequence_num: i32,
+ /// Resolved speaker in the same call, when known.
+ pub participant_id: Option<Uuid>,
+ /// Original provider speaker label, even if no person can be resolved.
+ pub speaker_label: Option<String>,
+ /// Transcript text.
+ pub content: String,
+ /// Milliseconds relative to the transcript origin, when known.
+ pub start_ms: Option<i64>,
+ /// End offset relative to the same origin, when known.
+ pub end_ms: Option<i64>,
+}
+
+/// Saved view of a call and its optional imported resources.
+///
+/// Discussions and collaborative notes use the existing call parent ID through
+/// comms and collab surfaces; neither requires a placeholder child here.
+#[derive(Debug, Clone, Serialize, Deserialize)]
+#[serde(rename_all = "camelCase")]
+pub struct CallEntityRecord {
+ /// Durable identity and optional occurrence metadata.
+ pub entity: CallEntity,
+ /// External object bindings; several providers may describe the same call.
+ #[serde(default)]
+ pub sources: Vec<CallSource>,
+ /// Known participants and speakers.
+ #[serde(default)]
+ pub participants: Vec<CallParticipant>,
+ /// Available audio and/or video recordings.
+ #[serde(default)]
+ pub recordings: Vec<CallRecording>,
+ /// Available transcripts, independently optional.
+ #[serde(default)]
+ pub transcripts: Vec<CallTranscript>,
+}
diff --git a/crates/call/src/domain/records/test.rs b/crates/call/src/domain/records/test.rs
new file mode 100644
index 0000000000..03d0612a2f
--- /dev/null
+++ b/crates/call/src/domain/records/test.rs
@@ -0,0 +1,55 @@
+use super::{CallProvider, CallSource, CallTranscript};
+use serde_json::json;
+
+#[test]
+fn source_requires_a_supported_provider() {
+ let mut source = json!({
+ "userId": "macro|[email protected]",
+ "namespace": "account-1",
+ "provider": "granola",
+ "objectType": "note",
+ "externalId": "not_opaque"
+ });
+
+ for (value, expected) in [
+ ("macro", CallProvider::Macro),
+ ("granola", CallProvider::Granola),
+ ] {
+ source["provider"] = json!(value);
+ let parsed: CallSource = serde_json::from_value(source.clone()).unwrap();
+ assert_eq!(parsed.provider, expected);
+ assert_eq!(serde_json::to_value(parsed).unwrap()["provider"], value);
+ }
+
+ for invalid in [json!("unknown"), json!(""), json!(null)] {
+ source["provider"] = invalid;
+ assert!(serde_json::from_value::<CallSource>(source.clone()).is_err());
+ }
+ source.as_object_mut().unwrap().remove("provider");
+ assert!(serde_json::from_value::<CallSource>(source).is_err());
+}
+
+#[test]
+fn transcript_provider_is_optional_but_validated_when_present() {
+ let mut transcript = json!({"id": "019a0000-0000-7000-8000-000000000050"});
+ assert!(
+ serde_json::from_value::<CallTranscript>(transcript.clone())
+ .unwrap()
+ .provider
+ .is_none()
+ );
+
+ for (value, expected) in [
+ (json!(null), None),
+ (json!("macro"), Some(CallProvider::Macro)),
+ (json!("granola"), Some(CallProvider::Granola)),
+ ] {
+ transcript["provider"] = value.clone();
+ let parsed: CallTranscript = serde_json::from_value(transcript.clone()).unwrap();
+ assert_eq!(parsed.provider, expected);
+ assert_eq!(serde_json::to_value(parsed).unwrap()["provider"], value);
+ }
+
+ transcript["provider"] = json!("unknown");
+ assert!(serde_json::from_value::<CallTranscript>(transcript).is_err());
+}
diff --git a/crates/entity_access/src/domain/ports.rs b/crates/entity_access/src/domain/ports.rs
index 186852040a..a343784214 100644
--- a/crates/entity_access/src/domain/ports.rs
+++ b/crates/entity_access/src/domain/ports.rs
@@ -321,8 +321,8 @@ pub trait AccessRepository: Clone + Send + Sync + 'static {
/// Resolve a call ID to its channel ID and share permission ID.
///
- /// Checks both the `calls` table (active calls) and the `call_records` table
- /// (archived calls). Returns `None` if the call does not exist in either table.
+ /// Resolves the durable identity for native and imported calls.
+ /// Returns `None` if the call entity does not exist.
fn get_call_channel(
&self,
call_id: &Uuid,
@@ -571,7 +571,7 @@ pub trait EntityAccessService: Clone + Send + Sync + 'static {
/// Resolve a call ID to its channel ID and share permission ID.
///
- /// Checks both `calls` (active) and `call_records` (archived) tables.
+ /// Resolves the durable identity for native and imported calls.
fn get_call_channel(
&self,
call_id: &Uuid,
diff --git a/crates/entity_access/src/inbound/axum_extractors/call.rs b/crates/entity_access/src/inbound/axum_extractors/call.rs
index 59d0cc026c..47ae89ec69 100644
--- a/crates/entity_access/src/inbound/axum_extractors/call.rs
+++ b/crates/entity_access/src/inbound/axum_extractors/call.rs
@@ -1,6 +1,6 @@
//! Call access extractors.
//!
-//! Resolves a call (from both `calls` and `call_records` tables), checks channel
+//! Resolves a durable call entity, checks channel
//! membership, and exposes the call's `share_permission_id` for downstream handlers.
#[cfg(test)]
@@ -43,8 +43,8 @@ struct CallWithChannelIdAccessParams {
/// Validates that the user satisfies the required permission for the channel
/// that a call belongs to, using a `call_id` path parameter.
///
-/// Resolves the call from both `calls` (active) and `call_records` (archived)
-/// tables, then checks the user's channel membership.
+/// Resolves the durable call entity, then checks the user's channel membership
+/// or the call's entity access when it has no channel.
///
/// Type parameter `T` specifies the required permission marker.
/// Type parameter `Svc` is the entity access service implementation.
diff --git a/crates/entity_access/src/outbound/pg_access_repo/queries/call_access.rs b/crates/entity_access/src/outbound/pg_access_repo/queries/call_access.rs
index 0e2f2a087e..f1e95f0e11 100644
--- a/crates/entity_access/src/outbound/pg_access_repo/queries/call_access.rs
+++ b/crates/entity_access/src/outbound/pg_access_repo/queries/call_access.rs
@@ -28,16 +28,7 @@ pub async fn get_call_access(
share_permission."linkShareAccessLevel" AS "access_level!: AccessLevel"
FROM "SharePermission" share_permission
JOIN (
- SELECT share_permission_id
- FROM calls
- WHERE id = $1
-
- UNION ALL
-
- SELECT share_permission_id
- FROM call_records
- WHERE id = $1
- LIMIT 1
+ SELECT share_permission_id FROM call_entities WHERE id = $1
) call_item ON call_item.share_permission_id = share_permission.id
WHERE share_permission."linkShare" = 'PUBLIC'
AND share_permission."linkShareAccessLevel" IS NOT NULL
@@ -66,16 +57,7 @@ pub async fn get_call_access(
share_permission."linkShareAccessLevel"::text AS access_level
FROM "SharePermission" share_permission
JOIN (
- SELECT share_permission_id, created_by
- FROM calls
- WHERE id = $1
-
- UNION ALL
-
- SELECT share_permission_id, created_by
- FROM call_records
- WHERE id = $1
- LIMIT 1
+ SELECT share_permission_id, user_id AS created_by FROM call_entities WHERE id = $1
) call_item ON call_item.share_permission_id = share_permission.id
WHERE share_permission."linkShareAccessLevel" IS NOT NULL
AND (
@@ -121,16 +103,7 @@ pub async fn explain_call_access(
share_permission."linkShareAccessLevel" AS "access_level!: AccessLevel"
FROM "SharePermission" share_permission
JOIN (
- SELECT share_permission_id
- FROM calls
- WHERE id = $1
-
- UNION ALL
-
- SELECT share_permission_id
- FROM call_records
- WHERE id = $1
- LIMIT 1
+ SELECT share_permission_id FROM call_entities WHERE id = $1
) call_item ON call_item.share_permission_id = share_permission.id
WHERE share_permission."linkShare" = 'PUBLIC'
AND share_permission."linkShareAccessLevel" IS NOT NULL
@@ -156,16 +129,7 @@ pub async fn explain_call_access(
owner_team.team_id AS "owner_team_id!"
FROM "SharePermission" share_permission
JOIN (
- SELECT share_permission_id, created_by
- FROM calls
- WHERE id = $1
-
- UNION ALL
-
- SELECT share_permission_id, created_by
- FROM call_records
- WHERE id = $1
- LIMIT 1
+ SELECT share_permission_id, user_id AS created_by FROM call_entities WHERE id = $1
) call_item ON call_item.share_permission_id = share_permission.id
JOIN team_user owner_team
ON owner_team.user_id = call_item.created_by
diff --git a/crates/entity_access/src/outbound/pg_access_repo/queries/call_access/test.rs b/crates/entity_access/src/outbound/pg_access_repo/queries/call_access/test.rs
index 9064a93689..dad544677d 100644
--- a/crates/entity_access/src/outbound/pg_access_repo/queries/call_access/test.rs
+++ b/crates/entity_access/src/outbound/pg_access_repo/queries/call_access/test.rs
@@ -16,10 +16,11 @@ const OTHER_TEAM: Uuid = Uuid::from_u128(0x000000000000000000000000000ca102);
enum CallTable {
Calls,
CallRecords,
+ CallEntities,
}
impl CallTable {
- const ALL: [Self; 2] = [Self::Calls, Self::CallRecords];
+ const ALL: [Self; 3] = [Self::Calls, Self::CallRecords, Self::CallEntities];
}
#[derive(Clone, Copy)]
@@ -167,6 +168,16 @@ async fn insert_link_shared_call(
insert_channel(pool, channel_id, owner_id).await?;
match call_table {
+ CallTable::CallEntities => {
+ sqlx::query!(
+ "INSERT INTO call_entities (id, user_id, created_via, share_permission_id) VALUES ($1, $2, 'import', $3)",
+ call_id,
+ owner_id,
+ share_permission_id,
+ )
+ .execute(pool)
+ .await?;
+ }
CallTable::Calls => {
sqlx::query!(
r#"
diff --git a/crates/entity_access/src/outbound/pg_access_repo/queries/call_channel.rs b/crates/entity_access/src/outbound/pg_access_repo/queries/call_channel.rs
index fde64621ad..c1aee0edcb 100644
--- a/crates/entity_access/src/outbound/pg_access_repo/queries/call_channel.rs
+++ b/crates/entity_access/src/outbound/pg_access_repo/queries/call_channel.rs
@@ -17,7 +17,7 @@ pub struct CallChannelRow {
/// Look up a call's channel and share permission by call ID.
///
-/// Checks both active calls and archived call records.
+/// Resolves the durable identity for native and imported calls.
#[tracing::instrument(err, skip(pool))]
pub async fn get_call_channel(
pool: &PgPool,
@@ -27,13 +27,8 @@ pub async fn get_call_channel(
CallChannelRow,
r#"
SELECT channel_id AS "channel_id?", share_permission_id AS "share_permission_id!"
- FROM calls
+ FROM call_entities
WHERE id = $1
- UNION ALL
- SELECT channel_id, share_permission_id
- FROM call_records
- WHERE id = $1
- LIMIT 1
"#,
call_id,
)
diff --git a/crates/macro_db_client/migrations/20261006214256_generic_call_entities.sql b/crates/macro_db_client/migrations/20261006214256_generic_call_entities.sql
new file mode 100644
index 0000000000..77d1d58c38
--- /dev/null
+++ b/crates/macro_db_client/migrations/20261006214256_generic_call_entities.sql
@@ -0,0 +1,252 @@
+-- Durable identity for native sessions and records imported without an RTC room.
+-- Existing native tables remain the runtime/archive storage during the rollout.
+-- Prevent native writes between the backfill snapshot and trigger installation.
+SET LOCAL lock_timeout = '5s';
+LOCK TABLE calls, call_records IN SHARE ROW EXCLUSIVE MODE;
+
+CREATE TABLE call_entities (
+ id UUID PRIMARY KEY,
+ -- Preserve legacy call owners even when their account row no longer exists.
+ -- Account deletion below explicitly cleans entities whose owner still exists.
+ user_id TEXT NOT NULL,
+ title TEXT,
+ created_via TEXT NOT NULL CHECK (created_via IN ('native', 'import', 'upload', 'manual')),
+ started_at TIMESTAMPTZ,
+ ended_at TIMESTAMPTZ,
+ duration_ms BIGINT CHECK (duration_ms >= 0),
+ channel_id UUID REFERENCES comms_channels(id) ON DELETE SET NULL,
+ meeting_id UUID REFERENCES call_meetings(id) ON DELETE SET NULL,
+ share_permission_id TEXT NOT NULL REFERENCES "SharePermission"(id) DEFERRABLE INITIALLY DEFERRED,
+ created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
+ updated_at TIMESTAMPTZ NOT NULL DEFAULT now(),
+ CHECK (ended_at >= started_at)
+);
+CREATE INDEX call_entities_user_created_idx ON call_entities(user_id, created_at DESC, id);
+CREATE INDEX call_entities_channel_idx ON call_entities(channel_id) WHERE channel_id IS NOT NULL;
+CREATE INDEX call_entities_meeting_idx ON call_entities(meeting_id) WHERE meeting_id IS NOT NULL;
+CREATE INDEX call_entities_share_permission_idx ON call_entities(share_permission_id);
+
+-- A namespace is a stable provider-account identity, not a rotating credential.
+-- The user is part of the key: imports from different users never silently merge.
+CREATE TABLE call_entity_sources (
+ call_id UUID NOT NULL REFERENCES call_entities(id) ON DELETE CASCADE,
+ user_id TEXT NOT NULL REFERENCES "User"(id) ON UPDATE CASCADE ON DELETE CASCADE,
+ namespace TEXT NOT NULL CHECK (length(btrim(namespace)) > 0),
+ provider TEXT NOT NULL CHECK (length(btrim(provider)) > 0),
+ object_type TEXT NOT NULL CHECK (length(btrim(object_type)) > 0),
+ external_id TEXT NOT NULL CHECK (length(external_id) > 0),
+ external_url TEXT,
+ external_updated_at TIMESTAMPTZ,
+ synced_at TIMESTAMPTZ,
+ metadata JSONB NOT NULL DEFAULT '{}' CHECK (jsonb_typeof(metadata) = 'object'),
+ PRIMARY KEY (user_id, namespace, provider, object_type, external_id)
+);
+CREATE INDEX call_entity_sources_call_idx ON call_entity_sources(call_id);
+
+-- A call-local speaker need not be a Macro account or even have a known name.
+CREATE TABLE call_entity_participants (
+ call_id UUID NOT NULL REFERENCES call_entities(id) ON DELETE CASCADE,
+ id UUID NOT NULL,
+ user_id TEXT REFERENCES "User"(id) ON UPDATE CASCADE ON DELETE SET NULL,
+ display_name TEXT,
+ email TEXT,
+ phone TEXT,
+ external_id TEXT,
+ PRIMARY KEY (call_id, id)
+);
+CREATE INDEX call_entity_participants_user_idx ON call_entity_participants(user_id) WHERE user_id IS NOT NULL;
+
+-- Multiple intervals preserve reconnects; an identified speaker need not have any.
+CREATE TABLE call_entity_attendance (
+ call_id UUID NOT NULL,
+ participant_id UUID NOT NULL,
+ id UUID NOT NULL,
+ joined_at TIMESTAMPTZ,
+ left_at TIMESTAMPTZ,
+ PRIMARY KEY (call_id, participant_id, id),
+ FOREIGN KEY (call_id, participant_id) REFERENCES call_entity_participants(call_id, id) ON DELETE CASCADE,
+ CHECK (left_at >= joined_at),
+ CHECK (joined_at IS NOT NULL OR left_at IS NOT NULL)
+);
+
+-- Multiple independent audio/video assets, including externally hosted assets.
+-- Persist stable object keys or provider URLs, never signed playback URLs.
+CREATE TABLE call_entity_recordings (
+ call_id UUID NOT NULL REFERENCES call_entities(id) ON DELETE CASCADE,
+ id UUID NOT NULL,
+ media_type TEXT NOT NULL CHECK (media_type IN ('audio', 'video')),
+ storage_key TEXT,
+ external_url TEXT,
+ mime_type TEXT,
+ duration_ms BIGINT CHECK (duration_ms >= 0),
+ started_at TIMESTAMPTZ,
+ PRIMARY KEY (call_id, id),
+ CHECK ((storage_key IS NOT NULL)::int + (external_url IS NOT NULL)::int = 1),
+ CHECK (storage_key IS NULL OR length(storage_key) > 0),
+ CHECK (external_url IS NULL OR length(external_url) > 0)
+);
+
+-- A transcript can exist without a recording, and multiple versions/languages
+-- can coexist. Offsets below are relative to this transcript, not the call clock.
+CREATE TABLE call_entity_transcripts (
+ call_id UUID NOT NULL REFERENCES call_entities(id) ON DELETE CASCADE,
+ id UUID NOT NULL,
+ recording_id UUID,
+ language TEXT,
+ provider TEXT,
+ started_at TIMESTAMPTZ,
+ PRIMARY KEY (call_id, id),
+ FOREIGN KEY (call_id, recording_id) REFERENCES call_entity_recordings(call_id, id)
+ ON DELETE NO ACTION DEFERRABLE INITIALLY DEFERRED
+);
+CREATE INDEX call_entity_transcripts_recording_idx ON call_entity_transcripts(call_id, recording_id) WHERE recording_id IS NOT NULL;
+
+CREATE TABLE call_entity_transcript_segments (
+ call_id UUID NOT NULL,
+ transcript_id UUID NOT NULL,
+ sequence_num INTEGER NOT NULL CHECK (sequence_num >= 0),
+ participant_id UUID,
+ speaker_label TEXT,
+ content TEXT NOT NULL,
+ start_ms BIGINT CHECK (start_ms >= 0),
+ end_ms BIGINT CHECK (end_ms >= 0),
+ PRIMARY KEY (call_id, transcript_id, sequence_num),
+ FOREIGN KEY (call_id, transcript_id) REFERENCES call_entity_transcripts(call_id, id) ON DELETE CASCADE,
+ FOREIGN KEY (call_id, participant_id) REFERENCES call_entity_participants(call_id, id)
+ ON DELETE NO ACTION DEFERRABLE INITIALLY DEFERRED,
+ CHECK (end_ms >= start_ms)
+);
+CREATE INDEX call_entity_segments_participant_idx ON call_entity_transcript_segments(call_id, participant_id) WHERE participant_id IS NOT NULL;
+
+-- PostgreSQL 14 cannot SET NULL on just one column of a composite foreign key.
+-- Detach optional references explicitly, retaining the non-null call scope.
+CREATE FUNCTION detach_call_entity_recording() RETURNS trigger LANGUAGE plpgsql AS $$
+BEGIN
+ -- During whole-call deletion the children are already being cascaded away.
+ IF EXISTS (SELECT 1 FROM call_entities WHERE id = OLD.call_id) THEN
+ UPDATE call_entity_transcripts SET recording_id = NULL
+ WHERE call_id = OLD.call_id AND recording_id = OLD.id;
+ END IF;
+ RETURN OLD;
+END;
+$$;
+CREATE TRIGGER detach_call_entity_recording AFTER DELETE ON call_entity_recordings
+FOR EACH ROW EXECUTE FUNCTION detach_call_entity_recording();
+
+CREATE FUNCTION detach_call_entity_participant() RETURNS trigger LANGUAGE plpgsql AS $$
+BEGIN
+ IF EXISTS (SELECT 1 FROM call_entities WHERE id = OLD.call_id) THEN
+ UPDATE call_entity_transcript_segments SET participant_id = NULL
+ WHERE call_id = OLD.call_id AND participant_id = OLD.id;
+ END IF;
+ RETURN OLD;
+END;
+$$;
+CREATE TRIGGER detach_call_entity_participant AFTER DELETE ON call_entity_participants
+FOR EACH ROW EXECUTE FUNCTION detach_call_entity_participant();
+
+-- Preserve existing IDs, owner grants, share permissions, and call permalinks.
+-- Archival stamps ended_at with the service clock and started_at with the
+-- database clock, so skew can reverse them; clamp rather than reject.
+INSERT INTO call_entities (id, user_id, title, created_via, started_at, ended_at, duration_ms,
+ channel_id, meeting_id, share_permission_id, created_at)
+SELECT id, created_by, custom_name, 'native', started_at,
+ CASE WHEN ended_at < started_at THEN started_at ELSE ended_at END,
+ CASE WHEN duration_ms < 0 THEN 0 ELSE duration_ms END,
+ channel_id, meeting_id, share_permission_id, started_at
+FROM call_records
+ON CONFLICT (id) DO NOTHING;
+INSERT INTO call_entities (id, user_id, created_via, started_at, channel_id, meeting_id, share_permission_id, created_at)
+SELECT id, created_by, 'native', created_at, channel_id, meeting_id, share_permission_id, created_at
+FROM calls
+ON CONFLICT (id) DO NOTHING;
+
+-- Keep old service versions writing native identity throughout the rollout.
+-- Native participants/media/transcripts remain in their existing tables; they
+-- are not duplicated into the imported-artifact tables above.
+CREATE FUNCTION sync_native_call_entity() RETURNS trigger LANGUAGE plpgsql AS $$
+BEGIN
+ IF TG_TABLE_NAME = 'calls' THEN
+ INSERT INTO call_entities (id, user_id, created_via, started_at, channel_id, meeting_id, share_permission_id, created_at)
+ VALUES (NEW.id, NEW.created_by, 'native', NEW.created_at, NEW.channel_id, NEW.meeting_id, NEW.share_permission_id, NEW.created_at)
+ ON CONFLICT (id) DO UPDATE SET
+ channel_id = EXCLUDED.channel_id, meeting_id = EXCLUDED.meeting_id,
+ share_permission_id = EXCLUDED.share_permission_id, updated_at = now();
+ ELSE
+ INSERT INTO call_entities (id, user_id, title, created_via, started_at, ended_at, duration_ms,
+ channel_id, meeting_id, share_permission_id, created_at)
+ -- Clamp clock-skewed timing (see the backfill) so mirroring never
+ -- fails a native archive.
+ VALUES (NEW.id, NEW.created_by, NEW.custom_name, 'native', NEW.started_at,
+ CASE WHEN NEW.ended_at < NEW.started_at THEN NEW.started_at ELSE NEW.ended_at END,
+ CASE WHEN NEW.duration_ms < 0 THEN 0 ELSE NEW.duration_ms END,
+ NEW.channel_id, NEW.meeting_id, NEW.share_permission_id, NEW.started_at)
+ ON CONFLICT (id) DO UPDATE SET
+ title = EXCLUDED.title, started_at = EXCLUDED.started_at, ended_at = EXCLUDED.ended_at,
+ duration_ms = EXCLUDED.duration_ms, channel_id = EXCLUDED.channel_id, meeting_id = EXCLUDED.meeting_id,
+ share_permission_id = EXCLUDED.share_permission_id, updated_at = now();
+ END IF;
+ RETURN NEW;
+END;
+$$;
+CREATE TRIGGER sync_active_call_entity AFTER INSERT OR UPDATE ON calls
+FOR EACH ROW EXECUTE FUNCTION sync_native_call_entity();
+CREATE TRIGGER sync_archived_call_entity AFTER INSERT OR UPDATE ON call_records
+FOR EACH ROW EXECUTE FUNCTION sync_native_call_entity();
+
+-- Archiving inserts the record before removing the room; preserve the entity.
+CREATE FUNCTION cleanup_native_call_entity() RETURNS trigger LANGUAGE plpgsql AS $$
+BEGIN
+ IF NOT EXISTS (SELECT 1 FROM calls WHERE id = OLD.id)
+ AND NOT EXISTS (SELECT 1 FROM call_records WHERE id = OLD.id) THEN
+ DELETE FROM call_entities WHERE id = OLD.id;
+ END IF;
+ RETURN OLD;
+END;
+$$;
+CREATE TRIGGER cleanup_active_call_entity AFTER DELETE ON calls
+FOR EACH ROW EXECUTE FUNCTION cleanup_native_call_entity();
+CREATE TRIGGER cleanup_archived_call_entity AFTER DELETE ON call_records
+FOR EACH ROW EXECUTE FUNCTION cleanup_native_call_entity();
+
+-- Entity deletion owns both runtime cleanup and private sharing state.
+CREATE FUNCTION cleanup_call_entity() RETURNS trigger LANGUAGE plpgsql AS $$
+BEGIN
+ DELETE FROM calls WHERE id = OLD.id;
+ DELETE FROM call_records WHERE id = OLD.id;
+ DELETE FROM entity_access WHERE entity_type = 'call' AND entity_id = OLD.id;
+ DELETE FROM "SharePermission" WHERE id = OLD.share_permission_id;
+ RETURN OLD;
+END;
+$$;
+CREATE TRIGGER cleanup_call_entity AFTER DELETE ON call_entities
+FOR EACH ROW EXECUTE FUNCTION cleanup_call_entity();
+
+CREATE FUNCTION cleanup_user_call_entities() RETURNS trigger LANGUAGE plpgsql AS $$
+BEGIN
+ DELETE FROM call_entities WHERE user_id = OLD.id;
+ RETURN OLD;
+END;
+$$;
+CREATE TRIGGER cleanup_user_call_entities AFTER DELETE ON "User"
+FOR EACH ROW EXECUTE FUNCTION cleanup_user_call_entities();
+
+-- Discussions still use the existing call message parent and canonical root.
+CREATE OR REPLACE FUNCTION cleanup_call_messages() RETURNS trigger LANGUAGE plpgsql AS $$
+BEGIN
+ PERFORM pg_advisory_xact_lock(hashtextextended(OLD.id::text, 0));
+ IF NOT EXISTS (SELECT 1 FROM call_entities WHERE id = OLD.id)
+ AND NOT EXISTS (SELECT 1 FROM calls WHERE id = OLD.id)
+ AND NOT EXISTS (SELECT 1 FROM call_records WHERE id = OLD.id) THEN
+ DELETE FROM comms_entity_mentions
+ WHERE source_entity_type = 'message' AND source_entity_id IN (
+ SELECT id::text FROM comms_messages
+ WHERE parent_entity_type = 'call' AND parent_entity_id = OLD.id::text
+ );
+ DELETE FROM comms_messages WHERE parent_entity_type = 'call' AND parent_entity_id = OLD.id::text;
+ END IF;
+ RETURN OLD;
+END;
+$$;
+CREATE TRIGGER cleanup_call_entity_messages AFTER DELETE ON call_entities
+FOR EACH ROW EXECUTE FUNCTION cleanup_call_messages();
diff --git a/crates/macro_db_migrator/src/test.rs b/crates/macro_db_migrator/src/test.rs
index e772a5b48c..74cf340355 100644
--- a/crates/macro_db_migrator/src/test.rs
+++ b/crates/macro_db_migrator/src/test.rs
@@ -158,3 +158,34 @@ async fn outlook_online_migrations_preserve_existing_mail_and_reminders(pool: Pg
.await
.unwrap();
}
+
+#[sqlx::test(migrations = false)]
+async fn generic_call_entities_preserve_native_identity_and_optional_resources(pool: PgPool) {
+ sqlx::raw_sql(EMPTY_PUBLIC_SCHEMA)
+ .execute(&pool)
+ .await
+ .unwrap();
+ let before_calls = Migrator {
+ migrations: Cow::Owned(
+ MACRO_DB_MIGRATIONS
+ .iter()
+ .filter(|migration| migration.version < 20261006214256)
+ .cloned()
+ .collect(),
+ ),
+ ..Migrator::DEFAULT
+ };
+ before_calls.run(&pool).await.unwrap();
+ // Multi-statement migration fixtures intentionally exercise both historical
+ // and current schemas, including constraint failures inside savepoints.
+ sqlx::raw_sql(include_str!("test/call_entities_before.sql"))
+ .execute(&pool)
+ .await
+ .unwrap();
+ MACRO_DB_MIGRATIONS.run(&pool).await.unwrap();
+ sqlx::raw_sql(include_str!("test/call_entities_after.sql"))
+ .execute(&pool)
+ .await
+ .unwrap();
+ MACRO_DB_MIGRATIONS.run(&pool).await.unwrap();
+}
diff --git a/crates/macro_db_migrator/src/test/call_entities_after.sql b/crates/macro_db_migrator/src/test/call_entities_after.sql
new file mode 100644
index 0000000000..a3f0745e44
--- /dev/null
+++ b/crates/macro_db_migrator/src/test/call_entities_after.sql
@@ -0,0 +1,146 @@
+DO $$ BEGIN
+ ASSERT (SELECT count(*) FROM call_entities WHERE created_via = 'native') = 3;
+ ASSERT (SELECT started_at FROM call_entities WHERE id = '019a0000-0000-7000-8000-000000000010') = '2026-01-01T10:00:00Z'::timestamptz;
+ ASSERT (SELECT title FROM call_entities WHERE id = '019a0000-0000-7000-8000-000000000011') = 'Existing call';
+END $$;
+DELETE FROM calls WHERE id = '019a0000-0000-7000-8000-000000000012';
+
+-- Calls created after deployment also receive a durable identity immediately.
+INSERT INTO "SharePermission" (id) VALUES ('call-model-new');
+INSERT INTO calls (id, room_name, created_by, share_permission_id, created_at) VALUES
+('019a0000-0000-7000-8000-000000000013', 'new-native-room', 'macro|[email protected]', 'call-model-new', '2026-01-02T10:00:00Z');
+DO $$ BEGIN
+ ASSERT EXISTS (
+ SELECT 1 FROM call_entities
+ WHERE id = '019a0000-0000-7000-8000-000000000013'
+ AND user_id = 'macro|[email protected]'
+ AND created_via = 'native'
+ AND started_at = '2026-01-02T10:00:00Z'::timestamptz
+ AND share_permission_id = 'call-model-new'
+ );
+END $$;
+INSERT INTO call_records (id, room_name, created_by, share_permission_id, started_at, ended_at, duration_ms)
+SELECT id, room_name, created_by, share_permission_id, created_at, '2026-01-02T10:05:00Z', 300000 FROM calls
+WHERE id = '019a0000-0000-7000-8000-000000000013';
+DELETE FROM calls WHERE id = '019a0000-0000-7000-8000-000000000013';
+DO $$ BEGIN
+ ASSERT EXISTS (
+ SELECT 1 FROM call_entities
+ WHERE id = '019a0000-0000-7000-8000-000000000013'
+ AND ended_at = '2026-01-02T10:05:00Z'::timestamptz
+ AND duration_ms = 300000
+ AND share_permission_id = 'call-model-new'
+ );
+END $$;
+DELETE FROM call_records WHERE id = '019a0000-0000-7000-8000-000000000013';
+DO $$ BEGIN
+ ASSERT NOT EXISTS (SELECT 1 FROM call_entities WHERE id = '019a0000-0000-7000-8000-000000000013');
+ ASSERT NOT EXISTS (SELECT 1 FROM "SharePermission" WHERE id = 'call-model-new');
+END $$;
+
+-- Old service writers update the new identity without changing native IDs.
+UPDATE call_records SET custom_name = 'Renamed call' WHERE id = '019a0000-0000-7000-8000-000000000011';
+INSERT INTO call_records (id, room_name, created_by, share_permission_id, started_at, ended_at, duration_ms)
+SELECT id, room_name, created_by, share_permission_id, created_at, '2026-01-01T10:05:00Z', 300000 FROM calls
+WHERE id = '019a0000-0000-7000-8000-000000000010';
+DELETE FROM calls WHERE id = '019a0000-0000-7000-8000-000000000010';
+DO $$ BEGIN
+ ASSERT (SELECT count(*) FROM call_entities WHERE created_via = 'native') = 2;
+ ASSERT (SELECT duration_ms FROM call_entities WHERE id = '019a0000-0000-7000-8000-000000000010') = 300000;
+ ASSERT (SELECT title FROM call_entities WHERE id = '019a0000-0000-7000-8000-000000000011') = 'Renamed call';
+END $$;
+
+-- Bare manual/imported records require no room, people, media, or timing.
+INSERT INTO "SharePermission" (id) VALUES ('call-model-import-a'), ('call-model-import-b');
+INSERT INTO call_entities (id, user_id, created_via, share_permission_id) VALUES
+('019a0000-0000-7000-8000-000000000020', 'macro|[email protected]', 'import', 'call-model-import-a'),
+('019a0000-0000-7000-8000-000000000021', 'macro|[email protected]', 'manual', 'call-model-import-b');
+INSERT INTO call_entity_sources (call_id, user_id, namespace, provider, object_type, external_id) VALUES
+('019a0000-0000-7000-8000-000000000020', 'macro|[email protected]', 'account-1', 'granola', 'note', 'opaque:/note#one'),
+('019a0000-0000-7000-8000-000000000021', 'macro|[email protected]', 'account-1', 'granola', 'note', 'opaque:/note#one');
+DO $$ BEGIN
+ ASSERT (SELECT started_at IS NULL AND ended_at IS NULL AND duration_ms IS NULL FROM call_entities WHERE id = '019a0000-0000-7000-8000-000000000020');
+ BEGIN
+ INSERT INTO call_entity_sources (call_id, user_id, namespace, provider, object_type, external_id) VALUES
+ ('019a0000-0000-7000-8000-000000000021', 'macro|[email protected]', 'account-1', 'granola', 'note', 'opaque:/note#one');
+ RAISE EXCEPTION 'duplicate source identity was accepted';
+ EXCEPTION WHEN unique_violation THEN NULL; END;
+ BEGIN
+ UPDATE call_entities SET duration_ms = -1 WHERE id = '019a0000-0000-7000-8000-000000000020';
+ RAISE EXCEPTION 'negative duration was accepted';
+ EXCEPTION WHEN check_violation THEN NULL; END;
+ BEGIN
+ UPDATE call_entities SET started_at = '2026-01-02', ended_at = '2026-01-01' WHERE id = '019a0000-0000-7000-8000-000000000020';
+ RAISE EXCEPTION 'reversed call bounds were accepted';
+ EXCEPTION WHEN check_violation THEN NULL; END;
+END $$;
+
+INSERT INTO call_entity_participants (call_id, id) VALUES
+('019a0000-0000-7000-8000-000000000020', '019a0000-0000-7000-8000-000000000030');
+INSERT INTO call_entity_attendance (call_id, participant_id, id, joined_at, left_at) VALUES
+('019a0000-0000-7000-8000-000000000020', '019a0000-0000-7000-8000-000000000030', '019a0000-0000-7000-8000-000000000031', '2026-01-01T12:00:00Z', '2026-01-01T12:01:00Z'),
+('019a0000-0000-7000-8000-000000000020', '019a0000-0000-7000-8000-000000000030', '019a0000-0000-7000-8000-000000000032', '2026-01-01T12:02:00Z', NULL);
+INSERT INTO call_entity_recordings (call_id, id, media_type, storage_key) VALUES
+('019a0000-0000-7000-8000-000000000020', '019a0000-0000-7000-8000-000000000040', 'audio', 'calls/recording.wav');
+INSERT INTO call_entity_recordings (call_id, id, media_type, external_url) VALUES
+('019a0000-0000-7000-8000-000000000020', '019a0000-0000-7000-8000-000000000041', 'video', 'https://provider.test/recording');
+INSERT INTO call_entity_transcripts (call_id, id, recording_id) VALUES
+('019a0000-0000-7000-8000-000000000020', '019a0000-0000-7000-8000-000000000050', NULL),
+('019a0000-0000-7000-8000-000000000020', '019a0000-0000-7000-8000-000000000051', '019a0000-0000-7000-8000-000000000040');
+INSERT INTO call_entity_transcript_segments (call_id, transcript_id, sequence_num, content, participant_id) VALUES
+('019a0000-0000-7000-8000-000000000020', '019a0000-0000-7000-8000-000000000050', 0, 'Unknown speaker and timing', NULL),
+('019a0000-0000-7000-8000-000000000020', '019a0000-0000-7000-8000-000000000050', 1, 'Known speaker, unknown timing', '019a0000-0000-7000-8000-000000000030');
+DO $$ BEGIN
+ BEGIN
+ INSERT INTO call_entity_transcripts (call_id, id, recording_id) VALUES
+ ('019a0000-0000-7000-8000-000000000021', '019a0000-0000-7000-8000-000000000052', '019a0000-0000-7000-8000-000000000040');
+ SET CONSTRAINTS ALL IMMEDIATE;
+ RAISE EXCEPTION 'cross-call recording reference was accepted';
+ EXCEPTION WHEN foreign_key_violation THEN NULL; END;
+ BEGIN
+ INSERT INTO call_entity_transcript_segments (call_id, transcript_id, sequence_num, content, start_ms, end_ms) VALUES
+ ('019a0000-0000-7000-8000-000000000020', '019a0000-0000-7000-8000-000000000050', 2, 'Invalid', 2000, 1000);
+ RAISE EXCEPTION 'reversed offsets were accepted';
+ EXCEPTION WHEN check_violation THEN NULL; END;
+ BEGIN
+ UPDATE call_entity_recordings SET external_url = 'https://provider.test/also' WHERE id = '019a0000-0000-7000-8000-000000000040';
+ RAISE EXCEPTION 'ambiguous recording locator was accepted';
+ EXCEPTION WHEN check_violation THEN NULL; END;
+END $$;
+
+-- Deleting people/media must preserve independently useful transcript text.
+DELETE FROM call_entity_participants WHERE id = '019a0000-0000-7000-8000-000000000030';
+DELETE FROM call_entity_recordings WHERE id = '019a0000-0000-7000-8000-000000000040';
+DO $$ BEGIN
+ ASSERT (SELECT count(*) FROM call_entity_transcript_segments) = 2;
+ ASSERT (SELECT count(*) FROM call_entity_transcript_segments WHERE participant_id IS NOT NULL) = 0;
+ ASSERT (SELECT count(*) FROM call_entity_attendance) = 0;
+ ASSERT (SELECT recording_id IS NULL FROM call_entity_transcripts WHERE id = '019a0000-0000-7000-8000-000000000051');
+END $$;
+
+-- Both legacy deletion and entity deletion clean permissions and child rows.
+-- Include references still attached when the owning call is deleted.
+INSERT INTO call_entity_transcripts (call_id, id, recording_id) VALUES
+('019a0000-0000-7000-8000-000000000020', '019a0000-0000-7000-8000-000000000052', '019a0000-0000-7000-8000-000000000041');
+INSERT INTO call_entity_participants (call_id, id) VALUES
+('019a0000-0000-7000-8000-000000000020', '019a0000-0000-7000-8000-000000000033');
+INSERT INTO call_entity_transcript_segments (call_id, transcript_id, sequence_num, content, participant_id) VALUES
+('019a0000-0000-7000-8000-000000000020', '019a0000-0000-7000-8000-000000000050', 2, 'Still attached', '019a0000-0000-7000-8000-000000000033');
+DELETE FROM call_records WHERE id = '019a0000-0000-7000-8000-000000000010';
+DELETE FROM call_entities WHERE id IN ('019a0000-0000-7000-8000-000000000011', '019a0000-0000-7000-8000-000000000020');
+DO $$ BEGIN
+ ASSERT (SELECT count(*) FROM call_entities) = 1;
+ ASSERT (SELECT count(*) FROM call_records) = 0;
+ ASSERT (SELECT count(*) FROM call_entity_recordings) = 0;
+ ASSERT (SELECT count(*) FROM call_entity_transcripts) = 0;
+ ASSERT (SELECT count(*) FROM call_entity_transcript_segments) = 0;
+ ASSERT (SELECT count(*) FROM call_entity_sources) = 1;
+ ASSERT NOT EXISTS (SELECT 1 FROM "SharePermission" WHERE id IN ('call-model-live', 'call-model-archive', 'call-model-import-a'));
+END $$;
+
+DELETE FROM "User" WHERE id = 'macro|[email protected]';
+DO $$ BEGIN
+ ASSERT NOT EXISTS (SELECT 1 FROM call_entities);
+ ASSERT NOT EXISTS (SELECT 1 FROM call_entity_sources);
+ ASSERT NOT EXISTS (SELECT 1 FROM "SharePermission" WHERE id = 'call-model-import-b');
+END $$;
diff --git a/crates/macro_db_migrator/src/test/call_entities_before.sql b/crates/macro_db_migrator/src/test/call_entities_before.sql
new file mode 100644
index 0000000000..51300fa8ad
--- /dev/null
+++ b/crates/macro_db_migrator/src/test/call_entities_before.sql
@@ -0,0 +1,15 @@
+INSERT INTO macro_user (id, username, email, stripe_customer_id) VALUES
+('019a0000-0000-7000-8000-000000000001', 'call-model-a', '[email protected]', 'call-model-a'),
+('019a0000-0000-7000-8000-000000000002', 'call-model-b', '[email protected]', 'call-model-b');
+INSERT INTO "User" (id, email, macro_user_id) VALUES
+('macro|[email protected]', '[email protected]', '019a0000-0000-7000-8000-000000000001'),
+('macro|[email protected]', '[email protected]', '019a0000-0000-7000-8000-000000000002');
+INSERT INTO "SharePermission" (id) VALUES ('call-model-live'), ('call-model-archive'), ('call-model-former-owner');
+INSERT INTO calls (id, room_name, created_by, share_permission_id, created_at) VALUES
+('019a0000-0000-7000-8000-000000000010', 'native-room', 'macro|[email protected]', 'call-model-live', '2026-01-01T10:00:00Z');
+-- Legacy native storage permits owners whose account has since disappeared.
+INSERT INTO calls (id, room_name, created_by, share_permission_id) VALUES
+('019a0000-0000-7000-8000-000000000012', 'former-owner-room', 'macro|[email protected]', 'call-model-former-owner');
+INSERT INTO call_records (id, room_name, created_by, share_permission_id, started_at, ended_at, duration_ms, custom_name) VALUES
+('019a0000-0000-7000-8000-000000000011', 'archived-room', 'macro|[email protected]', 'call-model-archive',
+ '2026-01-01T09:00:00Z', '2026-01-01T09:05:00Z', 300000, 'Existing call');
diff --git a/crates/messages/src/outbound/pg_message_repo.rs b/crates/messages/src/outbound/pg_message_repo.rs
index 35b4a4807b..2d0582c283 100644
--- a/crates/messages/src/outbound/pg_message_repo.rs
+++ b/crates/messages/src/outbound/pg_message_repo.rs
@@ -579,7 +579,7 @@ impl MessageRepository for PgMessageRepository {
.fetch_one(&self.pool).await,
MessageParent::Channel(id) => sqlx::query_scalar!(r#"SELECT EXISTS(SELECT 1 FROM comms_channels WHERE id = $1) AS "exists!""#, id)
.fetch_one(&self.pool).await,
- MessageParent::Call(id) => sqlx::query_scalar!(r#"SELECT EXISTS(SELECT 1 FROM calls WHERE id = $1 UNION ALL SELECT 1 FROM call_records WHERE id = $1) AS "exists!""#, id)
+ MessageParent::Call(id) => sqlx::query_scalar!(r#"SELECT EXISTS(SELECT 1 FROM call_entities WHERE id = $1) AS "exists!""#, id)
.fetch_one(&self.pool).await,
};
exists.map_err(database_error)
@@ -692,7 +692,7 @@ impl MessageRepository for PgMessageRepository {
.await
.map_err(database_error)?;
let parent_exists = sqlx::query_scalar!(
- r#"SELECT EXISTS(SELECT 1 FROM calls WHERE id = $1 UNION ALL SELECT 1 FROM call_records WHERE id = $1) AS "exists!""#,
+ r#"SELECT EXISTS(SELECT 1 FROM call_entities WHERE id = $1) AS "exists!""#,
root_id,
)
.fetch_one(&mut *tx)
diff --git a/crates/messages/src/outbound/pg_message_repo/test.rs b/crates/messages/src/outbound/pg_message_repo/test.rs
index fea1520f85..3214ce99ee 100644
--- a/crates/messages/src/outbound/pg_message_repo/test.rs
+++ b/crates/messages/src/outbound/pg_message_repo/test.rs
@@ -1707,3 +1707,43 @@ async fn retrying_first_call_message_cannot_append_it_twice(pool: PgPool) {
assert!(deleted.deleted_at.is_some());
assert!(deleted.content.is_empty());
}
+
+#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
+async fn imported_call_discussion_needs_no_native_session(pool: PgPool) {
+ setup(&pool).await;
+ let call_id = Uuid::now_v7();
+ let permission_id = Uuid::now_v7().to_string();
+ sqlx::query!(
+ r#"INSERT INTO "SharePermission" (id) VALUES ($1)"#,
+ permission_id
+ )
+ .execute(&pool)
+ .await
+ .unwrap();
+ sqlx::query!(
+ "INSERT INTO call_entities (id, user_id, created_via, share_permission_id) VALUES ($1, $2, 'import', $3)",
+ call_id,
+ USER,
+ permission_id,
+ )
+ .execute(&pool)
+ .await
+ .unwrap();
+ let repo = PgMessageRepository::new(pool.clone());
+ let parent = MessageParent::Call(call_id);
+ assert!(repo.parent_exists(&parent).await.unwrap());
+ repo.create(call_message(call_id, "Notes from an external call"))
+ .await
+ .unwrap();
+ repo.create(call_message(call_id, "Follow-up discussion"))
+ .await
+ .unwrap();
+ assert_eq!(repo.replies(&parent, call_id).await.unwrap().len(), 1);
+ sqlx::query!("DELETE FROM call_entities WHERE id = $1", call_id)
+ .execute(&pool)
+ .await
+ .unwrap();
+ assert!(!repo.parent_exists(&parent).await.unwrap());
+ assert!(repo.get(&parent, call_id).await.unwrap().is_none());
+ assert!(repo.replies(&parent, call_id).await.unwrap().is_empty());
+}
diff --git a/crates/share_permission_db_utils/src/lib.rs b/crates/share_permission_db_utils/src/lib.rs
index 93a3ca01e7..6db95f8a45 100644
--- a/crates/share_permission_db_utils/src/lib.rs
+++ b/crates/share_permission_db_utils/src/lib.rs
@@ -113,12 +113,7 @@ where
sqlx::query_scalar!(
r#"
SELECT share_permission_id as "share_permission_id!"
- FROM (
- SELECT share_permission_id FROM calls WHERE id = $1
- UNION ALL
- SELECT share_permission_id FROM call_records WHERE id = $1
- ) t
- LIMIT 1
+ FROM call_entities WHERE id = $1
"#,
item_id,
)
diff --git a/crates/share_permission_db_utils/src/team_share.rs b/crates/share_permission_db_utils/src/team_share.rs
index 3939d455e8..20f75f6dc1 100644
--- a/crates/share_permission_db_utils/src/team_share.rs
+++ b/crates/share_permission_db_utils/src/team_share.rs
@@ -111,7 +111,7 @@ fn entity_uuid(entity: &Entity<'_>) -> TeamShareResult<Uuid> {
/// Load actual owner, current membership and canonical state under the shared guard.
/// Threads and sessions without permissions read as NULL/revision zero without creating rows.
-/// Tasks and snippets use Document, and active calls take precedence during archive.
+/// Tasks and snippets use Document; calls resolve their durable entity.
pub async fn load_facts(
transaction: &mut Transaction<'_, Postgres>,
entity: &Entity<'_>,
@@ -143,12 +143,9 @@ async fn load_state(connection: &mut PgConnection, entity: &Entity<'_>) -> TeamS
LEFT JOIN "EmailThreadPermission" tp ON tp."threadId" = t.id::text
WHERE $2 = 'email_thread' AND t.id = $3
UNION ALL
- SELECT c.created_by, c.share_permission_id FROM calls c
+ SELECT c.user_id, c.share_permission_id FROM call_entities c
WHERE $2 = 'call' AND c.id = $3
UNION ALL
- SELECT c.created_by, c.share_permission_id FROM call_records c
- WHERE $2 = 'call' AND c.id = $3 AND NOT EXISTS (SELECT 1 FROM calls WHERE id = $3)
- UNION ALL
SELECT i.owner_user_id, i.share_permission_id FROM initiative i
WHERE $2 = 'initiative' AND i.id = $3
UNION ALL