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(github): associate GitHub installation id with a team (#2113)

Will Hutchinson462487f1943c
diff --git a/rust/cloud-storage/CLAUDE.md b/rust/cloud-storage/CLAUDE.md
index 2399b9ba80..2e0ea7d30c 100644
--- a/rust/cloud-storage/CLAUDE.md
+++ b/rust/cloud-storage/CLAUDE.md
@@ -52,9 +52,9 @@ connection tracking.
DB migration files are located in `rust/cloud-storage/macro_db_client`. Use the `/dump-schema` skill to dump the current Postgres schema for reference.
If you are still getting migration errors after running `just setup_macrodb`, you may need to run `just force_drop_db`
in `macro-api/cloud-storage/macro_db_client` to drop the database and re-create it
-with `just setup_macrodb` in `macro-api/cloud-storage`. Remember that when you are reading the database columns, the
-names are camelCased and not snake_cased (use `/dump-schema` or check the migration files for actual column names).
-So you need to cast as the snake_cased version of the column name when reading from the database. E.g.
+with `just setup_macrodb` in `macro-api/cloud-storage`. Remember that some database table and column names may be
+camelCased rather than snake_cased (use `/dump-schema` or check the migration files for actual column names).
+When a column is camelCased, you need to cast it as the snake_cased version when reading from the database. E.g.
`SELECT "userId" as "user_id" FROM "UserInsights"`.
Any time you make changes to the SQL code in rust, you need to run `just prepare_db` in
`macro-api/cloud-storage/macro_db_client` to update the .sqlx.
diff --git a/rust/cloud-storage/github/.sqlx/query-28c518d844cd4d843c097af1551f6f384a4763514d278b5444341390f58a8281.json b/rust/cloud-storage/github/.sqlx/query-28c518d844cd4d843c097af1551f6f384a4763514d278b5444341390f58a8281.json
deleted file mode 100644
index 98ceb2aeec..0000000000
--- a/rust/cloud-storage/github/.sqlx/query-28c518d844cd4d843c097af1551f6f384a4763514d278b5444341390f58a8281.json
+++ /dev/null
@@ -1,14 +0,0 @@
-{
- "db_name": "PostgreSQL",
- "query": "UPDATE \"Project\" SET \"updatedAt\" = NOW() WHERE id = $1",
- "describe": {
- "columns": [],
- "parameters": {
- "Left": [
- "Text"
- ]
- },
- "nullable": []
- },
- "hash": "28c518d844cd4d843c097af1551f6f384a4763514d278b5444341390f58a8281"
-}
diff --git a/rust/cloud-storage/github/.sqlx/query-37b5168f739c490a3373c65eab35f247a34af0a8e659cbad61cb99e3094e5a60.json b/rust/cloud-storage/github/.sqlx/query-37b5168f739c490a3373c65eab35f247a34af0a8e659cbad61cb99e3094e5a60.json
deleted file mode 100644
index 44d3a67e72..0000000000
--- a/rust/cloud-storage/github/.sqlx/query-37b5168f739c490a3373c65eab35f247a34af0a8e659cbad61cb99e3094e5a60.json
+++ /dev/null
@@ -1,23 +0,0 @@
-{
- "db_name": "PostgreSQL",
- "query": "\n SELECT EXISTS (\n SELECT 1\n FROM public.email_threads t\n JOIN public.email_links l ON l.id = t.link_id\n WHERE t.id = $1::uuid\n AND l.macro_id = $2\n ) AS \"exists!\"\n ",
- "describe": {
- "columns": [
- {
- "ordinal": 0,
- "name": "exists!",
- "type_info": "Bool"
- }
- ],
- "parameters": {
- "Left": [
- "Uuid",
- "Text"
- ]
- },
- "nullable": [
- null
- ]
- },
- "hash": "37b5168f739c490a3373c65eab35f247a34af0a8e659cbad61cb99e3094e5a60"
-}
diff --git a/rust/cloud-storage/github/.sqlx/query-3a7be99469ed150e0506efa786b672198a6d3419c6bd5548418520cd3e6a8e95.json b/rust/cloud-storage/github/.sqlx/query-3a7be99469ed150e0506efa786b672198a6d3419c6bd5548418520cd3e6a8e95.json
deleted file mode 100644
index 60bfee0647..0000000000
--- a/rust/cloud-storage/github/.sqlx/query-3a7be99469ed150e0506efa786b672198a6d3419c6bd5548418520cd3e6a8e95.json
+++ /dev/null
@@ -1,23 +0,0 @@
-{
- "db_name": "PostgreSQL",
- "query": "\n WITH RECURSIVE project_hierarchy AS (\n SELECT p.id as project_id\n FROM \"Document\" d\n JOIN \"Project\" p ON d.\"projectId\" = p.id AND p.\"deletedAt\" IS NULL\n WHERE d.id = $1 AND d.\"deletedAt\" IS NULL\n UNION ALL\n SELECT parent.id as project_id\n FROM project_hierarchy ph\n JOIN \"Project\" parent ON parent.id = (\n SELECT \"parentId\" FROM \"Project\" WHERE id = ph.project_id AND \"parentId\" IS NOT NULL AND \"deletedAt\" IS NULL\n )\n )\n SELECT access_level FROM (\n -- Source 1: Cast the AccessLevel enum to text.\n SELECT access_level::text FROM \"UserItemAccess\"\n WHERE user_id = $2 AND item_id IN (\n SELECT $1\n UNION\n SELECT project_id FROM project_hierarchy\n )\n UNION ALL\n -- Source 2: Select the publicAccessLevel (which is already text).\n SELECT \"publicAccessLevel\" as access_level\n FROM \"SharePermission\"\n WHERE \"isPublic\" = true AND \"publicAccessLevel\" IS NOT NULL AND id IN (\n SELECT \"sharePermissionId\" FROM \"DocumentPermission\" WHERE \"documentId\" = $1\n UNION\n SELECT \"sharePermissionId\" FROM \"ProjectPermission\" WHERE \"projectId\" IN (SELECT project_id FROM project_hierarchy)\n )\n ) as all_levels\n ",
- "describe": {
- "columns": [
- {
- "ordinal": 0,
- "name": "access_level",
- "type_info": "Text"
- }
- ],
- "parameters": {
- "Left": [
- "Text",
- "Text"
- ]
- },
- "nullable": [
- null
- ]
- },
- "hash": "3a7be99469ed150e0506efa786b672198a6d3419c6bd5548418520cd3e6a8e95"
-}
diff --git a/rust/cloud-storage/github/.sqlx/query-4afa79ca95bdbcebe9d3de7ebb204636419e6cf89e650a8716c40ab2e588aa5b.json b/rust/cloud-storage/github/.sqlx/query-4afa79ca95bdbcebe9d3de7ebb204636419e6cf89e650a8716c40ab2e588aa5b.json
deleted file mode 100644
index 58618b2697..0000000000
--- a/rust/cloud-storage/github/.sqlx/query-4afa79ca95bdbcebe9d3de7ebb204636419e6cf89e650a8716c40ab2e588aa5b.json
+++ /dev/null
@@ -1,23 +0,0 @@
-{
- "db_name": "PostgreSQL",
- "query": "\n -- CTE to recursively find all parent projects, starting from the given project.\n WITH RECURSIVE project_hierarchy AS (\n -- Base case: Start with the project ID provided.\n SELECT id as project_id\n FROM \"Project\"\n WHERE id = $1 AND \"deletedAt\" IS NULL\n UNION ALL\n -- Recursive case: Find the parent of the project from the previous step.\n SELECT parent.id as project_id\n FROM project_hierarchy ph\n JOIN \"Project\" parent ON parent.id = (\n SELECT \"parentId\" FROM \"Project\" WHERE id = ph.project_id AND \"parentId\" IS NOT NULL AND \"deletedAt\" IS NULL\n )\n )\n -- The subquery now gathers all levels as plain text.\n SELECT access_level FROM (\n -- Source 1: Cast the AccessLevel enum to text.\n SELECT access_level::text FROM \"UserItemAccess\"\n WHERE user_id = $2 AND item_id IN (\n -- The hierarchy CTE includes the starting project, so this is all we need.\n SELECT project_id FROM project_hierarchy\n )\n UNION ALL\n -- Source 2: Select the publicAccessLevel (which is already text).\n SELECT \"publicAccessLevel\" as access_level\n FROM \"SharePermission\"\n WHERE \"isPublic\" = true AND \"publicAccessLevel\" IS NOT NULL AND id IN (\n -- We only need to check ProjectPermission for the items in the hierarchy.\n SELECT \"sharePermissionId\" FROM \"ProjectPermission\"\n WHERE \"projectId\" IN (SELECT project_id FROM project_hierarchy)\n )\n ) as all_levels\n ",
- "describe": {
- "columns": [
- {
- "ordinal": 0,
- "name": "access_level",
- "type_info": "Text"
- }
- ],
- "parameters": {
- "Left": [
- "Text",
- "Text"
- ]
- },
- "nullable": [
- null
- ]
- },
- "hash": "4afa79ca95bdbcebe9d3de7ebb204636419e6cf89e650a8716c40ab2e588aa5b"
-}
diff --git a/rust/cloud-storage/github/.sqlx/query-4c695b011d49ba7d5fce4b309875ed952dc386ac760444d7883c5a76718f15be.json b/rust/cloud-storage/github/.sqlx/query-4c695b011d49ba7d5fce4b309875ed952dc386ac760444d7883c5a76718f15be.json
deleted file mode 100644
index 524cc25ec7..0000000000
--- a/rust/cloud-storage/github/.sqlx/query-4c695b011d49ba7d5fce4b309875ed952dc386ac760444d7883c5a76718f15be.json
+++ /dev/null
@@ -1,23 +0,0 @@
-{
- "db_name": "PostgreSQL",
- "query": "\n WITH RECURSIVE project_hierarchy AS (\n SELECT p.id as project_id\n FROM \"Chat\" c\n JOIN \"Project\" p ON c.\"projectId\" = p.id AND p.\"deletedAt\" IS NULL\n WHERE c.id = $1 AND c.\"deletedAt\" IS NULL\n UNION ALL\n SELECT parent.id as project_id\n FROM project_hierarchy ph\n JOIN \"Project\" parent ON parent.id = (\n SELECT \"parentId\" FROM \"Project\" WHERE id = ph.project_id AND \"parentId\" IS NOT NULL AND \"deletedAt\" IS NULL\n )\n )\n SELECT access_level FROM (\n -- Source 1: Cast the AccessLevel enum to text.\n SELECT access_level::text FROM \"UserItemAccess\"\n WHERE user_id = $2 AND item_id IN (\n SELECT $1 -- The chat itself\n UNION\n SELECT project_id FROM project_hierarchy -- All parent projects\n )\n UNION ALL\n -- Source 2: Select the publicAccessLevel (which is already text).\n SELECT \"publicAccessLevel\" as access_level\n FROM \"SharePermission\"\n WHERE \"isPublic\" = true AND \"publicAccessLevel\" IS NOT NULL AND id IN (\n SELECT \"sharePermissionId\" FROM \"ChatPermission\" WHERE \"chatId\" = $1\n UNION\n SELECT \"sharePermissionId\" FROM \"ProjectPermission\" WHERE \"projectId\" IN (SELECT project_id FROM project_hierarchy)\n )\n ) as all_levels\n ",
- "describe": {
- "columns": [
- {
- "ordinal": 0,
- "name": "access_level",
- "type_info": "Text"
- }
- ],
- "parameters": {
- "Left": [
- "Text",
- "Text"
- ]
- },
- "nullable": [
- null
- ]
- },
- "hash": "4c695b011d49ba7d5fce4b309875ed952dc386ac760444d7883c5a76718f15be"
-}
diff --git a/rust/cloud-storage/github/.sqlx/query-4c8f1c99fe7ca583e05b4ef8aba08d4fdf58135dc3e99ed73381a29f94b8a270.json b/rust/cloud-storage/github/.sqlx/query-4c8f1c99fe7ca583e05b4ef8aba08d4fdf58135dc3e99ed73381a29f94b8a270.json
new file mode 100644
index 0000000000..ca98651009
--- /dev/null
+++ b/rust/cloud-storage/github/.sqlx/query-4c8f1c99fe7ca583e05b4ef8aba08d4fdf58135dc3e99ed73381a29f94b8a270.json
@@ -0,0 +1,22 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n SELECT team_id\n FROM team_user\n WHERE user_id = $1\n ",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "team_id",
+ "type_info": "Uuid"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Text"
+ ]
+ },
+ "nullable": [
+ false
+ ]
+ },
+ "hash": "4c8f1c99fe7ca583e05b4ef8aba08d4fdf58135dc3e99ed73381a29f94b8a270"
+}
diff --git a/rust/cloud-storage/github/.sqlx/query-54e3755d63a676a7fa70da77321e618032f0130c73eb6b0ae985f07c5c6c448b.json b/rust/cloud-storage/github/.sqlx/query-54e3755d63a676a7fa70da77321e618032f0130c73eb6b0ae985f07c5c6c448b.json
deleted file mode 100644
index 03a8dbf6bb..0000000000
--- a/rust/cloud-storage/github/.sqlx/query-54e3755d63a676a7fa70da77321e618032f0130c73eb6b0ae985f07c5c6c448b.json
+++ /dev/null
@@ -1,22 +0,0 @@
-{
- "db_name": "PostgreSQL",
- "query": "\n WITH RECURSIVE project_hierarchy AS (\n SELECT p.id as project_id\n FROM \"Chat\" c\n JOIN \"Project\" p ON c.\"projectId\" = p.id AND p.\"deletedAt\" IS NULL\n WHERE c.id = $1 AND c.\"deletedAt\" IS NULL\n UNION ALL\n SELECT parent.id as project_id\n FROM project_hierarchy ph\n JOIN \"Project\" parent ON parent.id = (\n SELECT \"parentId\" FROM \"Project\" WHERE id = ph.project_id AND \"parentId\" IS NOT NULL AND \"deletedAt\" IS NULL\n )\n )\n SELECT DISTINCT user_id FROM \"UserItemAccess\"\n WHERE item_id IN (\n SELECT $1\n UNION\n SELECT project_id FROM project_hierarchy\n )\n ",
- "describe": {
- "columns": [
- {
- "ordinal": 0,
- "name": "user_id",
- "type_info": "Text"
- }
- ],
- "parameters": {
- "Left": [
- "Text"
- ]
- },
- "nullable": [
- false
- ]
- },
- "hash": "54e3755d63a676a7fa70da77321e618032f0130c73eb6b0ae985f07c5c6c448b"
-}
diff --git a/rust/cloud-storage/github/.sqlx/query-6a83d04482526e2ceb9e9eb812d3ceaf1c8c7fafb25ba1cbecb4dadc543fad67.json b/rust/cloud-storage/github/.sqlx/query-6a83d04482526e2ceb9e9eb812d3ceaf1c8c7fafb25ba1cbecb4dadc543fad67.json
new file mode 100644
index 0000000000..88be9c45d5
--- /dev/null
+++ b/rust/cloud-storage/github/.sqlx/query-6a83d04482526e2ceb9e9eb812d3ceaf1c8c7fafb25ba1cbecb4dadc543fad67.json
@@ -0,0 +1,16 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n INSERT INTO github_app_installation_team (id, team_id, installed_by)\n SELECT * FROM UNNEST($1::text[], $2::uuid[], $3::text[])\n ON CONFLICT (id, team_id) DO NOTHING\n ",
+ "describe": {
+ "columns": [],
+ "parameters": {
+ "Left": [
+ "TextArray",
+ "UuidArray",
+ "TextArray"
+ ]
+ },
+ "nullable": []
+ },
+ "hash": "6a83d04482526e2ceb9e9eb812d3ceaf1c8c7fafb25ba1cbecb4dadc543fad67"
+}
diff --git a/rust/cloud-storage/github/.sqlx/query-7617f808df94ffe77c8195a911ee6b230a21fe9935e099d1310d244248ca253a.json b/rust/cloud-storage/github/.sqlx/query-7617f808df94ffe77c8195a911ee6b230a21fe9935e099d1310d244248ca253a.json
deleted file mode 100644
index 655495fb29..0000000000
--- a/rust/cloud-storage/github/.sqlx/query-7617f808df94ffe77c8195a911ee6b230a21fe9935e099d1310d244248ca253a.json
+++ /dev/null
@@ -1,23 +0,0 @@
-{
- "db_name": "PostgreSQL",
- "query": "\n SELECT c.id\n FROM comms_channels c\n INNER JOIN comms_channel_participants cp ON cp.channel_id = c.id\n WHERE cp.user_id = $1 AND cp.left_at IS NULL\n AND c.id = ANY($2::uuid[])\n ",
- "describe": {
- "columns": [
- {
- "ordinal": 0,
- "name": "id",
- "type_info": "Uuid"
- }
- ],
- "parameters": {
- "Left": [
- "Text",
- "UuidArray"
- ]
- },
- "nullable": [
- false
- ]
- },
- "hash": "7617f808df94ffe77c8195a911ee6b230a21fe9935e099d1310d244248ca253a"
-}
diff --git a/rust/cloud-storage/github/.sqlx/query-79d3bc72e6f424765706f7deea426379ae49cbd70dd122daedd95343618b9ac6.json b/rust/cloud-storage/github/.sqlx/query-79d3bc72e6f424765706f7deea426379ae49cbd70dd122daedd95343618b9ac6.json
deleted file mode 100644
index 2bde15938f..0000000000
--- a/rust/cloud-storage/github/.sqlx/query-79d3bc72e6f424765706f7deea426379ae49cbd70dd122daedd95343618b9ac6.json
+++ /dev/null
@@ -1,22 +0,0 @@
-{
- "db_name": "PostgreSQL",
- "query": "\n WITH RECURSIVE project_hierarchy AS (\n SELECT id as project_id\n FROM \"Project\"\n WHERE id = $1 AND \"deletedAt\" IS NULL\n UNION ALL\n SELECT parent.id as project_id\n FROM project_hierarchy ph\n JOIN \"Project\" parent ON parent.id = (\n SELECT \"parentId\" FROM \"Project\" WHERE id = ph.project_id AND \"parentId\" IS NOT NULL AND \"deletedAt\" IS NULL\n )\n )\n SELECT DISTINCT user_id FROM \"UserItemAccess\"\n WHERE item_id IN (\n SELECT project_id FROM project_hierarchy\n )\n ",
- "describe": {
- "columns": [
- {
- "ordinal": 0,
- "name": "user_id",
- "type_info": "Text"
- }
- ],
- "parameters": {
- "Left": [
- "Text"
- ]
- },
- "nullable": [
- false
- ]
- },
- "hash": "79d3bc72e6f424765706f7deea426379ae49cbd70dd122daedd95343618b9ac6"
-}
diff --git a/rust/cloud-storage/github/.sqlx/query-96d853b887f2e6d7aac6b15ddd2b71a8d8900d2ef30047da7ca1a5940503b6d0.json b/rust/cloud-storage/github/.sqlx/query-96d853b887f2e6d7aac6b15ddd2b71a8d8900d2ef30047da7ca1a5940503b6d0.json
deleted file mode 100644
index e42c9f2009..0000000000
--- a/rust/cloud-storage/github/.sqlx/query-96d853b887f2e6d7aac6b15ddd2b71a8d8900d2ef30047da7ca1a5940503b6d0.json
+++ /dev/null
@@ -1,22 +0,0 @@
-{
- "db_name": "PostgreSQL",
- "query": "\n WITH RECURSIVE project_hierarchy AS (\n SELECT p.id as project_id\n FROM \"Document\" d\n JOIN \"Project\" p ON d.\"projectId\" = p.id AND p.\"deletedAt\" IS NULL\n WHERE d.id = $1 AND d.\"deletedAt\" IS NULL\n UNION ALL\n SELECT parent.id as project_id\n FROM project_hierarchy ph\n JOIN \"Project\" parent ON parent.id = (\n SELECT \"parentId\" FROM \"Project\" WHERE id = ph.project_id AND \"parentId\" IS NOT NULL AND \"deletedAt\" IS NULL\n )\n )\n SELECT DISTINCT user_id FROM \"UserItemAccess\"\n WHERE item_id IN (\n SELECT $1\n UNION\n SELECT project_id FROM project_hierarchy\n )\n ",
- "describe": {
- "columns": [
- {
- "ordinal": 0,
- "name": "user_id",
- "type_info": "Text"
- }
- ],
- "parameters": {
- "Left": [
- "Text"
- ]
- },
- "nullable": [
- false
- ]
- },
- "hash": "96d853b887f2e6d7aac6b15ddd2b71a8d8900d2ef30047da7ca1a5940503b6d0"
-}
diff --git a/rust/cloud-storage/github/.sqlx/query-b3aeddd507e0efee0e0cecef6eae7503820f0f3302e95a459790c5cb78e5dfb0.json b/rust/cloud-storage/github/.sqlx/query-b3aeddd507e0efee0e0cecef6eae7503820f0f3302e95a459790c5cb78e5dfb0.json
deleted file mode 100644
index 2b67c5606d..0000000000
--- a/rust/cloud-storage/github/.sqlx/query-b3aeddd507e0efee0e0cecef6eae7503820f0f3302e95a459790c5cb78e5dfb0.json
+++ /dev/null
@@ -1,23 +0,0 @@
-{
- "db_name": "PostgreSQL",
- "query": "\n -- CTE to recursively find all parent projects for the given email thread.\n WITH RECURSIVE project_hierarchy AS (\n -- Base case: Start with the project directly associated with the thread.\n SELECT\n p.id as project_id\n FROM\n \"EmailThreadPermission\" etp\n JOIN \"Project\" p ON etp.\"projectId\" = p.id AND p.\"deletedAt\" IS NULL\n WHERE\n etp.\"threadId\" = $1\n UNION ALL\n -- Recursive case: Find the parent of the project from the previous step.\n SELECT\n parent.id as project_id\n FROM\n project_hierarchy ph\n JOIN \"Project\" parent ON parent.id = (\n SELECT \"parentId\" FROM \"Project\" WHERE id = ph.project_id AND \"parentId\" IS NOT NULL AND \"deletedAt\" IS NULL\n )\n )\n -- The subquery now gathers all levels as plain text.\n SELECT access_level FROM (\n -- Source 1: Cast the AccessLevel enum to text.\n SELECT access_level::text FROM \"UserItemAccess\"\n WHERE user_id = $2 AND item_id IN (\n SELECT $1 -- The thread ID itself\n UNION\n SELECT project_id FROM project_hierarchy -- All parent projects\n )\n UNION ALL\n -- Source 2: Select the publicAccessLevel (which is already text).\n SELECT \"publicAccessLevel\" as access_level\n FROM \"SharePermission\"\n WHERE \"isPublic\" = true AND \"publicAccessLevel\" IS NOT NULL AND id IN (\n SELECT \"sharePermissionId\" FROM \"EmailThreadPermission\" WHERE \"threadId\" = $1\n UNION\n SELECT \"sharePermissionId\" FROM \"ProjectPermission\" WHERE \"projectId\" IN (SELECT project_id FROM project_hierarchy)\n )\n ) as all_levels\n ",
- "describe": {
- "columns": [
- {
- "ordinal": 0,
- "name": "access_level",
- "type_info": "Text"
- }
- ],
- "parameters": {
- "Left": [
- "Text",
- "Text"
- ]
- },
- "nullable": [
- null
- ]
- },
- "hash": "b3aeddd507e0efee0e0cecef6eae7503820f0f3302e95a459790c5cb78e5dfb0"
-}
diff --git a/rust/cloud-storage/github/.sqlx/query-e7235d6ad2033a2ff7be0bf57ab042cd71e3b3d0e1f8a9750e55cdda92e70c6f.json b/rust/cloud-storage/github/.sqlx/query-e7235d6ad2033a2ff7be0bf57ab042cd71e3b3d0e1f8a9750e55cdda92e70c6f.json
deleted file mode 100644
index 4c96ff0fd5..0000000000
--- a/rust/cloud-storage/github/.sqlx/query-e7235d6ad2033a2ff7be0bf57ab042cd71e3b3d0e1f8a9750e55cdda92e70c6f.json
+++ /dev/null
@@ -1,22 +0,0 @@
-{
- "db_name": "PostgreSQL",
- "query": "\n WITH RECURSIVE project_hierarchy AS (\n SELECT p.id as project_id\n FROM \"EmailThreadPermission\" etp\n JOIN \"Project\" p ON etp.\"projectId\" = p.id AND p.\"deletedAt\" IS NULL\n WHERE etp.\"threadId\" = $1\n UNION ALL\n SELECT parent.id as project_id\n FROM project_hierarchy ph\n JOIN \"Project\" parent ON parent.id = (\n SELECT \"parentId\" FROM \"Project\" WHERE id = ph.project_id AND \"parentId\" IS NOT NULL AND \"deletedAt\" IS NULL\n )\n )\n SELECT DISTINCT user_id FROM \"UserItemAccess\"\n WHERE item_id IN (\n SELECT $1\n UNION\n SELECT project_id FROM project_hierarchy\n )\n ",
- "describe": {
- "columns": [
- {
- "ordinal": 0,
- "name": "user_id",
- "type_info": "Text"
- }
- ],
- "parameters": {
- "Left": [
- "Text"
- ]
- },
- "nullable": [
- false
- ]
- },
- "hash": "e7235d6ad2033a2ff7be0bf57ab042cd71e3b3d0e1f8a9750e55cdda92e70c6f"
-}
diff --git a/rust/cloud-storage/github/.sqlx/query-ed43958d3b45528df34f3216299e47e00e2aa671b9d235abffa4ad8bfe126c12.json b/rust/cloud-storage/github/.sqlx/query-ed43958d3b45528df34f3216299e47e00e2aa671b9d235abffa4ad8bfe126c12.json
new file mode 100644
index 0000000000..104b3123e1
--- /dev/null
+++ b/rust/cloud-storage/github/.sqlx/query-ed43958d3b45528df34f3216299e47e00e2aa671b9d235abffa4ad8bfe126c12.json
@@ -0,0 +1,22 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n SELECT macro_id\n FROM github_links\n WHERE github_user_id = $1\n ",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "macro_id",
+ "type_info": "Text"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Text"
+ ]
+ },
+ "nullable": [
+ false
+ ]
+ },
+ "hash": "ed43958d3b45528df34f3216299e47e00e2aa671b9d235abffa4ad8bfe126c12"
+}
diff --git a/rust/cloud-storage/github/fixtures/github_installation_test_data.sql b/rust/cloud-storage/github/fixtures/github_installation_test_data.sql
new file mode 100644
index 0000000000..464117c008
--- /dev/null
+++ b/rust/cloud-storage/github/fixtures/github_installation_test_data.sql
@@ -0,0 +1,26 @@
+INSERT INTO
+ public.macro_user (id, username, email, stripe_customer_id)
+VALUES
+ ('bbbbbbbb-bbbb-bbbb-bbbb-bbbbbbbbbbbb'::uuid, 'testuser', '[email protected]', 'cus_test');
+
+INSERT INTO
+ public."User" (id, email, macro_user_id)
+VALUES
+ ('macro|[email protected]', '[email protected]', 'bbbbbbbb-bbbb-bbbb-bbbb-bbbbbbbbbbbb'::uuid);
+
+INSERT INTO
+ public.github_links (id, macro_id, fusionauth_user_id, github_username, github_user_id)
+VALUES
+ ('aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa'::uuid, 'macro|[email protected]', 'bbbbbbbb-bbbb-bbbb-bbbb-bbbbbbbbbbbb'::uuid, 'testuser', '12345');
+
+INSERT INTO
+ public.team (id, name, owner_id)
+VALUES
+ ('dddddddd-dddd-dddd-dddd-dddddddddddd'::uuid, 'Team Alpha', 'macro|[email protected]'),
+ ('eeeeeeee-eeee-eeee-eeee-eeeeeeeeeeee'::uuid, 'Team Beta', 'macro|[email protected]');
+
+INSERT INTO
+ public.team_user (user_id, team_id, team_role)
+VALUES
+ ('macro|[email protected]', 'dddddddd-dddd-dddd-dddd-dddddddddddd'::uuid, 'owner'),
+ ('macro|[email protected]', 'eeeeeeee-eeee-eeee-eeee-eeeeeeeeeeee'::uuid, 'member');
diff --git a/rust/cloud-storage/github/src/domain/models/sync.rs b/rust/cloud-storage/github/src/domain/models/sync.rs
index bc1cc48b3b..9f61d9c6ec 100644
--- a/rust/cloud-storage/github/src/domain/models/sync.rs
+++ b/rust/cloud-storage/github/src/domain/models/sync.rs
@@ -104,7 +104,7 @@ impl ValidatedGithubWebhookEvent {
texts.push(s.to_string());
}
}
- GithubWebhookEventType::Unknown(_) => {}
+ GithubWebhookEventType::Installation | GithubWebhookEventType::Unknown(_) => {}
}
texts
}
@@ -155,7 +155,7 @@ impl ValidatedGithubWebhookEvent {
if is_open { Some("In Review") } else { None }
}
- GithubWebhookEventType::Unknown(_) => None,
+ GithubWebhookEventType::Installation | GithubWebhookEventType::Unknown(_) => None,
}
}
@@ -197,6 +197,18 @@ impl ValidatedGithubWebhookEvent {
.and_then(|v| v.as_u64())
}
+ /// Extract the sender's GitHub user ID from the webhook payload.
+ ///
+ /// Uses the numeric `sender.id` rather than `sender.login` because
+ /// GitHub usernames can change but user IDs are stable.
+ pub fn sender_github_user_id(&self) -> Option<String> {
+ self.payload
+ .get("sender")
+ .and_then(|s| s.get("id"))
+ .and_then(|v| v.as_u64())
+ .map(|id| id.to_string())
+ }
+
/// Extract text from the PR context (title, body, branch) regardless of
/// event type. For comment/review events this returns the surrounding PR
/// info so callers can determine which task IDs are already associated
@@ -207,7 +219,9 @@ impl ValidatedGithubWebhookEvent {
let pr = match self.parsed_event_type() {
// For PR events, the event itself is the context — nothing to compare against.
- GithubWebhookEventType::PullRequest | GithubWebhookEventType::Unknown(_) => {
+ GithubWebhookEventType::PullRequest
+ | GithubWebhookEventType::Installation
+ | GithubWebhookEventType::Unknown(_) => {
return texts;
}
// issue_comment payloads embed the issue (which contains PR title/body).
@@ -248,6 +262,8 @@ pub enum GithubWebhookEventType {
PullRequestReview,
/// `pull_request_review_comment` events
PullRequestReviewComment,
+ /// `installation` events (app installed/uninstalled)
+ Installation,
/// Any event type we don't handle
Unknown(String),
}
@@ -260,6 +276,7 @@ impl GithubWebhookEventType {
"issue_comment" => Self::IssueComment,
"pull_request_review" => Self::PullRequestReview,
"pull_request_review_comment" => Self::PullRequestReviewComment,
+ "installation" => Self::Installation,
other => Self::Unknown(other.to_string()),
}
}
diff --git a/rust/cloud-storage/github/src/domain/ports/sync.rs b/rust/cloud-storage/github/src/domain/ports/sync.rs
index 9b1a27ec6e..d61b5b1c70 100644
--- a/rust/cloud-storage/github/src/domain/ports/sync.rs
+++ b/rust/cloud-storage/github/src/domain/ports/sync.rs
@@ -35,6 +35,28 @@ pub trait GithubSyncRepo: Send + Sync + 'static {
github_key: GithubKey,
task_ids: &[MacroTaskId],
) -> impl Future<Output = Result<Vec<MacroTaskId>, Self::Err>> + Send;
+
+ /// Looks up the macro user ID associated with a GitHub user ID via the `github_links` table.
+ /// Returns `None` if no link exists.
+ fn get_macro_id_by_github_user_id(
+ &self,
+ github_user_id: &str,
+ ) -> impl Future<Output = Result<Option<String>, Self::Err>> + Send;
+
+ /// Returns all team IDs the given macro user belongs to.
+ fn get_user_team_ids(
+ &self,
+ macro_id: &str,
+ ) -> impl Future<Output = Result<Vec<uuid::Uuid>, Self::Err>> + Send;
+
+ /// Inserts associations between a GitHub App installation and the given teams.
+ /// Ignores conflicts (idempotent).
+ fn insert_installation_team_associations(
+ &self,
+ installation_id: &str,
+ team_ids: &[uuid::Uuid],
+ installed_by: &str,
+ ) -> impl Future<Output = Result<(), Self::Err>> + Send;
}
/// Client interface for making GitHub sync API calls.
diff --git a/rust/cloud-storage/github/src/domain/service/sync/handle_installation.rs b/rust/cloud-storage/github/src/domain/service/sync/handle_installation.rs
new file mode 100644
index 0000000000..89b5e4b92e
--- /dev/null
+++ b/rust/cloud-storage/github/src/domain/service/sync/handle_installation.rs
@@ -0,0 +1,75 @@
+//! Installation event handlers.
+
+use crate::domain::{
+ models::{GithubError, ValidatedGithubWebhookEvent},
+ ports::{GithubSyncClient, GithubSyncRepo},
+};
+use documents::domain::ports::DocumentService;
+
+use super::GithubSyncServiceImpl;
+
+impl<D: DocumentService, R: GithubSyncRepo, C: GithubSyncClient> GithubSyncServiceImpl<D, R, C> {
+ /// Handle `installation` events with action `created`.
+ ///
+ /// Associates the GitHub App installation with all teams the installer belongs to.
+ #[tracing::instrument(skip(self, event), err)]
+ pub(crate) async fn handle_installation_created(
+ &self,
+ event: &ValidatedGithubWebhookEvent,
+ ) -> Result<(), GithubError> {
+ let installation_id = event
+ .installation_id()
+ .ok_or_else(|| GithubError::Internal(anyhow::anyhow!("missing installation.id")))?;
+ let installation_id_str = installation_id.to_string();
+
+ let sender_github_user_id = event.sender_github_user_id().ok_or_else(|| {
+ GithubError::Internal(anyhow::anyhow!("missing sender.id in installation event"))
+ })?;
+
+ tracing::info!(installation_id, "processing installation created event");
+
+ let macro_id = self
+ .repo
+ .get_macro_id_by_github_user_id(&sender_github_user_id)
+ .await
+ .map_err(|e| GithubError::Internal(e.into()))?;
+
+ let macro_id = match macro_id {
+ Some(id) => id,
+ None => {
+ tracing::warn!(
+ installation_id,
+ "no github link found for sender, cannot associate installation with teams"
+ );
+ return Ok(());
+ }
+ };
+
+ let team_ids = self
+ .repo
+ .get_user_team_ids(&macro_id)
+ .await
+ .map_err(|e| GithubError::Internal(e.into()))?;
+
+ if team_ids.is_empty() {
+ tracing::info!(
+ installation_id,
+ "user has no teams, skipping installation association"
+ );
+ return Ok(());
+ }
+
+ tracing::info!(
+ installation_id,
+ team_count = team_ids.len(),
+ "associating installation with user teams"
+ );
+
+ self.repo
+ .insert_installation_team_associations(&installation_id_str, &team_ids, &macro_id)
+ .await
+ .map_err(|e| GithubError::Internal(e.into()))?;
+
+ Ok(())
+ }
+}
diff --git a/rust/cloud-storage/github/src/domain/service/sync/mod.rs b/rust/cloud-storage/github/src/domain/service/sync/mod.rs
index 72387c96ed..ef1bc77eb8 100644
--- a/rust/cloud-storage/github/src/domain/service/sync/mod.rs
+++ b/rust/cloud-storage/github/src/domain/service/sync/mod.rs
@@ -4,6 +4,7 @@
mod test;
mod handle_comment;
+mod handle_installation;
mod handle_pr;
use crate::domain::{
@@ -327,6 +328,13 @@ impl<D: DocumentService, R: GithubSyncRepo, C: GithubSyncClient> GithubSyncServi
| GithubWebhookEventType::PullRequestReviewComment => {
self.handle_comment_event(webhook_event).await
}
+ GithubWebhookEventType::Installation => match action {
+ Some("created") => self.handle_installation_created(webhook_event).await,
+ _ => {
+ tracing::debug!(action, "skipping unhandled installation action");
+ Ok(())
+ }
+ },
}
}
diff --git a/rust/cloud-storage/github/src/domain/service/sync/test.rs b/rust/cloud-storage/github/src/domain/service/sync/test.rs
index 6f896201a0..ff4bfac920 100644
--- a/rust/cloud-storage/github/src/domain/service/sync/test.rs
+++ b/rust/cloud-storage/github/src/domain/service/sync/test.rs
@@ -195,14 +195,43 @@ impl DocumentService for StubDocumentService {
/// Stateful stub repo that tracks task IDs per github key.
struct StubSyncRepo {
tasks: Mutex<HashMap<String, HashSet<String>>>,
+ /// Maps github_user_id -> macro_id for installation event lookups.
+ github_links: Mutex<HashMap<String, String>>,
+ /// Maps macro_id -> team_ids for installation event lookups.
+ user_teams: Mutex<HashMap<String, Vec<uuid::Uuid>>>,
+ /// Recorded installation-team association inserts: (installation_id, team_ids, installed_by).
+ installation_associations: Mutex<Vec<(String, Vec<uuid::Uuid>, String)>>,
}
impl StubSyncRepo {
fn new() -> Self {
Self {
tasks: Mutex::new(HashMap::new()),
+ github_links: Mutex::new(HashMap::new()),
+ user_teams: Mutex::new(HashMap::new()),
+ installation_associations: Mutex::new(Vec::new()),
}
}
+
+ fn with_github_link(self, github_user_id: &str, macro_id: &str) -> Self {
+ self.github_links
+ .lock()
+ .unwrap()
+ .insert(github_user_id.to_string(), macro_id.to_string());
+ self
+ }
+
+ fn with_user_teams(self, macro_id: &str, team_ids: Vec<uuid::Uuid>) -> Self {
+ self.user_teams
+ .lock()
+ .unwrap()
+ .insert(macro_id.to_string(), team_ids);
+ self
+ }
+
+ fn installation_associations(&self) -> Vec<(String, Vec<uuid::Uuid>, String)> {
+ self.installation_associations.lock().unwrap().clone()
+ }
}
impl GithubSyncRepo for StubSyncRepo {
@@ -251,6 +280,42 @@ impl GithubSyncRepo for StubSyncRepo {
.cloned()
.collect())
}
+
+ async fn get_macro_id_by_github_user_id(
+ &self,
+ github_user_id: &str,
+ ) -> Result<Option<String>, Self::Err> {
+ Ok(self
+ .github_links
+ .lock()
+ .unwrap()
+ .get(github_user_id)
+ .cloned())
+ }
+
+ async fn get_user_team_ids(&self, macro_id: &str) -> Result<Vec<uuid::Uuid>, Self::Err> {
+ Ok(self
+ .user_teams
+ .lock()
+ .unwrap()
+ .get(macro_id)
+ .cloned()
+ .unwrap_or_default())
+ }
+
+ async fn insert_installation_team_associations(
+ &self,
+ installation_id: &str,
+ team_ids: &[uuid::Uuid],
+ installed_by: &str,
+ ) -> Result<(), Self::Err> {
+ self.installation_associations.lock().unwrap().push((
+ installation_id.to_string(),
+ team_ids.to_vec(),
+ installed_by.to_string(),
+ ));
+ Ok(())
+ }
}
/// Recorded PR comment call.
@@ -312,6 +377,23 @@ fn make_sync_service() -> GithubSyncServiceImpl<StubDocumentService, StubSyncRep
make_sync_service_with_doc_service().0
}
+fn make_sync_service_with_repo(
+ repo: StubSyncRepo,
+) -> GithubSyncServiceImpl<StubDocumentService, StubSyncRepo, StubSyncClient> {
+ let doc_service = Arc::new(StubDocumentService::new());
+ GithubSyncServiceImpl::new(
+ GithubSyncConfig {
+ webhook_secret: "test-webhook-secret".to_string(),
+ github_sync_app_url: "test".to_string(),
+ sync_app_pem: TEST_PEM.to_string(),
+ sync_app_client_id: "test-sync-app-client-id".to_string(),
+ },
+ doc_service,
+ repo,
+ StubSyncClient::new(),
+ )
+}
+
fn make_sync_service_with_doc_service() -> (
GithubSyncServiceImpl<StubDocumentService, StubSyncRepo, StubSyncClient>,
Arc<StubDocumentService>,
@@ -1131,3 +1213,84 @@ async fn false_positive_macro_prefix_ignored() {
"false positive macro- prefix should not trigger a status update"
);
}
+
+// ---------------------------------------------------------------------------
+// installation created
+// ---------------------------------------------------------------------------
+
+fn installation_created_event(sender_id: u64, installation_id: u64) -> ValidatedGithubWebhookEvent {
+ ValidatedGithubWebhookEvent::new(
+ "installation".to_string(),
+ serde_json::json!({
+ "action": "created",
+ "installation": { "id": installation_id },
+ "sender": { "login": "testuser", "id": sender_id }
+ }),
+ )
+}
+
+#[tokio::test]
+async fn installation_created_associates_teams() {
+ let team_a: uuid::Uuid = "dddddddd-dddd-dddd-dddd-dddddddddddd".parse().unwrap();
+ let team_b: uuid::Uuid = "eeeeeeee-eeee-eeee-eeee-eeeeeeeeeeee".parse().unwrap();
+
+ let repo = StubSyncRepo::new()
+ .with_github_link("12345", "macro|[email protected]")
+ .with_user_teams("macro|[email protected]", vec![team_a, team_b]);
+
+ let service = make_sync_service_with_repo(repo);
+ let event = installation_created_event(12345, 99999);
+
+ service.process_webhook_event(&event).await.unwrap();
+
+ let associations = service.repo.installation_associations();
+ assert_eq!(associations.len(), 1);
+ assert_eq!(associations[0].0, "99999");
+ assert_eq!(associations[0].1.len(), 2);
+ assert!(associations[0].1.contains(&team_a));
+ assert!(associations[0].1.contains(&team_b));
+ assert_eq!(associations[0].2, "macro|[email protected]");
+}
+
+#[tokio::test]
+async fn installation_created_no_github_link() {
+ let service = make_sync_service();
+ let event = installation_created_event(99999, 11111);
+
+ // No github link for sender — should succeed without inserting anything
+ service.process_webhook_event(&event).await.unwrap();
+
+ assert!(service.repo.installation_associations().is_empty());
+}
+
+#[tokio::test]
+async fn installation_created_no_teams() {
+ let repo = StubSyncRepo::new().with_github_link("12345", "macro|[email protected]");
+ // user_teams is empty by default
+
+ let service = make_sync_service_with_repo(repo);
+ let event = installation_created_event(12345, 11111);
+
+ service.process_webhook_event(&event).await.unwrap();
+
+ let associations = service.repo.installation_associations();
+ assert!(associations.is_empty());
+}
+
+#[tokio::test]
+async fn installation_deleted_is_skipped() {
+ let service = make_sync_service();
+ let event = ValidatedGithubWebhookEvent::new(
+ "installation".to_string(),
+ serde_json::json!({
+ "action": "deleted",
+ "installation": { "id": 12345 },
+ "sender": { "login": "testuser", "id": 12345 }
+ }),
+ );
+
+ // Should not error — just skips
+ service.process_webhook_event(&event).await.unwrap();
+
+ assert!(service.repo.installation_associations().is_empty());
+}
diff --git a/rust/cloud-storage/github/src/outbound/pg_github_sync_repo.rs b/rust/cloud-storage/github/src/outbound/pg_github_sync_repo.rs
index 00c2eb89dc..88d462288c 100644
--- a/rust/cloud-storage/github/src/outbound/pg_github_sync_repo.rs
+++ b/rust/cloud-storage/github/src/outbound/pg_github_sync_repo.rs
@@ -106,4 +106,66 @@ impl GithubSyncRepo for PgGithubSyncRepo {
.cloned()
.collect())
}
+
+ #[tracing::instrument(skip(self), err)]
+ async fn get_macro_id_by_github_user_id(
+ &self,
+ github_user_id: &str,
+ ) -> Result<Option<String>, Self::Err> {
+ let macro_id = sqlx::query_scalar!(
+ r#"
+ SELECT macro_id
+ FROM github_links
+ WHERE github_user_id = $1
+ "#,
+ github_user_id,
+ )
+ .fetch_optional(&self.pool)
+ .await?;
+
+ Ok(macro_id)
+ }
+
+ #[tracing::instrument(skip(self), err)]
+ async fn get_user_team_ids(&self, macro_id: &str) -> Result<Vec<uuid::Uuid>, Self::Err> {
+ let team_ids = sqlx::query_scalar!(
+ r#"
+ SELECT team_id
+ FROM team_user
+ WHERE user_id = $1
+ "#,
+ macro_id,
+ )
+ .fetch_all(&self.pool)
+ .await?;
+
+ Ok(team_ids)
+ }
+
+ #[tracing::instrument(skip(self), err)]
+ async fn insert_installation_team_associations(
+ &self,
+ installation_id: &str,
+ team_ids: &[uuid::Uuid],
+ installed_by: &str,
+ ) -> Result<(), Self::Err> {
+ let installation_ids: Vec<&str> =
+ std::iter::repeat_n(installation_id, team_ids.len()).collect();
+ let installed_bys: Vec<&str> = std::iter::repeat_n(installed_by, team_ids.len()).collect();
+
+ sqlx::query!(
+ r#"
+ INSERT INTO github_app_installation_team (id, team_id, installed_by)
+ SELECT * FROM UNNEST($1::text[], $2::uuid[], $3::text[])
+ ON CONFLICT (id, team_id) DO NOTHING
+ "#,
+ &installation_ids as &[&str],
+ team_ids,
+ &installed_bys as &[&str],
+ )
+ .execute(&self.pool)
+ .await?;
+
+ Ok(())
+ }
}
diff --git a/rust/cloud-storage/github/src/outbound/pg_github_sync_repo/test.rs b/rust/cloud-storage/github/src/outbound/pg_github_sync_repo/test.rs
index dc15f93256..cefe6d035a 100644
--- a/rust/cloud-storage/github/src/outbound/pg_github_sync_repo/test.rs
+++ b/rust/cloud-storage/github/src/outbound/pg_github_sync_repo/test.rs
@@ -1,5 +1,6 @@
use macro_db_migrator::MACRO_DB_MIGRATIONS;
use sqlx::{Pool, Postgres};
+use uuid::Uuid;
use crate::domain::models::{GithubKey, MacroTaskId};
use crate::domain::ports::GithubSyncRepo;
@@ -185,3 +186,119 @@ async fn test_filter_duplicate_tasks_different_key_not_filtered(pool: Pool<Postg
assert_eq!(new_only.len(), 1);
assert_eq!(new_only[0].short_uuid, "s61deeZUHehUjkNT8rxB3S");
}
+
+// ---------------------------------------------------------------------------
+// get_macro_id_by_github_user_id
+// ---------------------------------------------------------------------------
+
+#[sqlx::test(
+ migrator = "MACRO_DB_MIGRATIONS",
+ fixtures(path = "../../../fixtures", scripts("github_installation_test_data"))
+)]
+async fn test_get_macro_id_by_github_user_id_found(pool: Pool<Postgres>) {
+ let repo = PgGithubSyncRepo::new(pool);
+
+ let macro_id = repo.get_macro_id_by_github_user_id("12345").await.unwrap();
+
+ assert_eq!(macro_id.as_deref(), Some("macro|[email protected]"));
+}
+
+#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
+async fn test_get_macro_id_by_github_user_id_not_found(pool: Pool<Postgres>) {
+ let repo = PgGithubSyncRepo::new(pool);
+
+ let macro_id = repo.get_macro_id_by_github_user_id("99999").await.unwrap();
+
+ assert!(macro_id.is_none());
+}
+
+// ---------------------------------------------------------------------------
+// get_user_team_ids
+// ---------------------------------------------------------------------------
+
+#[sqlx::test(
+ migrator = "MACRO_DB_MIGRATIONS",
+ fixtures(path = "../../../fixtures", scripts("github_installation_test_data"))
+)]
+async fn test_get_user_team_ids(pool: Pool<Postgres>) {
+ let repo = PgGithubSyncRepo::new(pool);
+
+ let team_ids = repo.get_user_team_ids("macro|[email protected]").await.unwrap();
+
+ assert_eq!(team_ids.len(), 2);
+ let expected: Vec<Uuid> = vec![
+ "dddddddd-dddd-dddd-dddd-dddddddddddd".parse().unwrap(),
+ "eeeeeeee-eeee-eeee-eeee-eeeeeeeeeeee".parse().unwrap(),
+ ];
+ for id in &expected {
+ assert!(team_ids.contains(id));
+ }
+}
+
+#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
+async fn test_get_user_team_ids_no_teams(pool: Pool<Postgres>) {
+ let repo = PgGithubSyncRepo::new(pool);
+
+ let team_ids = repo
+ .get_user_team_ids("macro|[email protected]")
+ .await
+ .unwrap();
+
+ assert!(team_ids.is_empty());
+}
+
+// ---------------------------------------------------------------------------
+// insert_installation_team_associations
+// ---------------------------------------------------------------------------
+
+#[sqlx::test(
+ migrator = "MACRO_DB_MIGRATIONS",
+ fixtures(path = "../../../fixtures", scripts("github_installation_test_data"))
+)]
+async fn test_insert_installation_team_associations(pool: Pool<Postgres>) {
+ let repo = PgGithubSyncRepo::new(pool.clone());
+
+ let team_ids: Vec<Uuid> = vec![
+ "dddddddd-dddd-dddd-dddd-dddddddddddd".parse().unwrap(),
+ "eeeeeeee-eeee-eeee-eeee-eeeeeeeeeeee".parse().unwrap(),
+ ];
+
+ repo.insert_installation_team_associations("123456", &team_ids, "macro|[email protected]")
+ .await
+ .unwrap();
+
+ let rows: Vec<(String, Uuid)> =
+ sqlx::query_as("SELECT id, team_id FROM github_app_installation_team ORDER BY team_id")
+ .fetch_all(&pool)
+ .await
+ .unwrap();
+
+ assert_eq!(rows.len(), 2);
+ assert!(rows.iter().all(|r| r.0 == "123456"));
+}
+
+#[sqlx::test(
+ migrator = "MACRO_DB_MIGRATIONS",
+ fixtures(path = "../../../fixtures", scripts("github_installation_test_data"))
+)]
+async fn test_insert_installation_team_associations_idempotent(pool: Pool<Postgres>) {
+ let repo = PgGithubSyncRepo::new(pool.clone());
+
+ let team_ids: Vec<Uuid> = vec!["dddddddd-dddd-dddd-dddd-dddddddddddd".parse().unwrap()];
+
+ repo.insert_installation_team_associations("123456", &team_ids, "macro|[email protected]")
+ .await
+ .unwrap();
+ // Insert again — should not error
+ repo.insert_installation_team_associations("123456", &team_ids, "macro|[email protected]")
+ .await
+ .unwrap();
+
+ let count: (i64,) =
+ sqlx::query_as("SELECT COUNT(*) FROM github_app_installation_team WHERE id = '123456'")
+ .fetch_one(&pool)
+ .await
+ .unwrap();
+
+ assert_eq!(count.0, 1);
+}
diff --git a/rust/cloud-storage/macro_db_client/migrations/20260323152227_github_app_installation_id_team_association.sql b/rust/cloud-storage/macro_db_client/migrations/20260323152227_github_app_installation_id_team_association.sql
new file mode 100644
index 0000000000..6a806685e5
--- /dev/null
+++ b/rust/cloud-storage/macro_db_client/migrations/20260323152227_github_app_installation_id_team_association.sql
@@ -0,0 +1,11 @@
+-- Adds new table that associates a github app installation with a given team id
+CREATE TABLE github_app_installation_team
+(
+ id TEXT NOT NULL, -- The github installation id converted to a string
+ team_id UUID NOT NULL REFERENCES "team" ("id") ON DELETE CASCADE,
+ installed_by TEXT NOT NULL REFERENCES "User" ("id") ON DELETE CASCADE,
+ PRIMARY KEY (id, team_id)
+);
+
+-- Allow for github app installation id lookup by team id
+CREATE INDEX "github_app_installation_team_team_id_idx" ON github_app_installation_team ("team_id");