Macro is a unified workspace for teams: email, chat, docs, tasks, agents, calls, and CRM — @-linked together with shared AI memory.
TypeScript agentaiai-agentsall-in-onecrmcrm-systememaillinearmcpmessagingnotesnotionofficerustslackslack-alternativestartupstartup-toolstypescriptworkspace
fix(github): team task association (#5326)
Will Hutchinson8b08cea12bdc
diff --git a/.sqlx/query-2d689689caf98fbfbb437fe34129b37a1ece02e7c4189d0619ea741f74f05bdf.json b/.sqlx/query-2d689689caf98fbfbb437fe34129b37a1ece02e7c4189d0619ea741f74f05bdf.jsondeleted file mode 100644index 05a17cf734..0000000000--- a/.sqlx/query-2d689689caf98fbfbb437fe34129b37a1ece02e7c4189d0619ea741f74f05bdf.json+++ /dev/null@@ -1,24 +0,0 @@-{- "db_name": "PostgreSQL",- "query": "\n SELECT DISTINCT tt.document_id\n FROM UNNEST($2::text[], $3::int4[]) AS refs(team_slug, task_num)\n JOIN github_app_installation gai\n ON gai.id = $1\n AND gai.source_type = 'team'::github_app_installation_source_type\n JOIN team t\n ON t.id = gai.source_id::uuid\n AND LOWER(t.slug) = LOWER(refs.team_slug)\n JOIN team_task tt ON tt.team_id = t.id AND tt.task_num = refs.task_num\n ",- "describe": {- "columns": [- {- "ordinal": 0,- "name": "document_id",- "type_info": "Text"- }- ],- "parameters": {- "Left": [- "Text",- "TextArray",- "Int4Array"- ]- },- "nullable": [- false- ]- },- "hash": "2d689689caf98fbfbb437fe34129b37a1ece02e7c4189d0619ea741f74f05bdf"-}diff --git a/.sqlx/query-2d860324def387468b6b089c4be85a965281da729a7cba15f0f0c9d97f296e94.json b/.sqlx/query-2d860324def387468b6b089c4be85a965281da729a7cba15f0f0c9d97f296e94.jsonnew file mode 100644index 0000000000..9bdf9de25d--- /dev/null+++ b/.sqlx/query-2d860324def387468b6b089c4be85a965281da729a7cba15f0f0c9d97f296e94.json@@ -0,0 +1,17 @@+{+ "db_name": "PostgreSQL",+ "query": "\n INSERT INTO github_pr_tasks (id, github_key, task_id, team_id)\n SELECT u.id, u.github_key, u.task_id, tt.team_id\n FROM UNNEST($1::uuid[], $2::text[], $3::text[], $4::text[])\n AS u(id, github_key, task_id, document_id)\n LEFT JOIN team_task tt ON tt.document_id = u.document_id\n ON CONFLICT (github_key, task_id)\n DO UPDATE SET team_id = COALESCE(github_pr_tasks.team_id, EXCLUDED.team_id)\n ",+ "describe": {+ "columns": [],+ "parameters": {+ "Left": [+ "UuidArray",+ "TextArray",+ "TextArray",+ "TextArray"+ ]+ },+ "nullable": []+ },+ "hash": "2d860324def387468b6b089c4be85a965281da729a7cba15f0f0c9d97f296e94"+}diff --git a/.sqlx/query-76f6793eaead8c4f3a2aa4b02ad573beda79b93bfd874acc1b2059cbe041d8a3.json b/.sqlx/query-76f6793eaead8c4f3a2aa4b02ad573beda79b93bfd874acc1b2059cbe041d8a3.jsondeleted file mode 100644index 23986dc09f..0000000000--- a/.sqlx/query-76f6793eaead8c4f3a2aa4b02ad573beda79b93bfd874acc1b2059cbe041d8a3.json+++ /dev/null@@ -1,16 +0,0 @@-{- "db_name": "PostgreSQL",- "query": "\n INSERT INTO github_pr_tasks (id, github_key, task_id)\n SELECT * FROM UNNEST($1::uuid[], $2::text[], $3::text[])\n ON CONFLICT (github_key, task_id) DO NOTHING\n ",- "describe": {- "columns": [],- "parameters": {- "Left": [- "UuidArray",- "TextArray",- "TextArray"- ]- },- "nullable": []- },- "hash": "76f6793eaead8c4f3a2aa4b02ad573beda79b93bfd874acc1b2059cbe041d8a3"-}diff --git a/.sqlx/query-f8d5930bc985a02933afc33e8a908915e3a70baebc90ba622768f69cf87f68cf.json b/.sqlx/query-f8d5930bc985a02933afc33e8a908915e3a70baebc90ba622768f69cf87f68cf.jsonnew file mode 100644index 0000000000..e3532f8c88--- /dev/null+++ b/.sqlx/query-f8d5930bc985a02933afc33e8a908915e3a70baebc90ba622768f69cf87f68cf.json@@ -0,0 +1,42 @@+{+ "db_name": "PostgreSQL",+ "query": "\n SELECT DISTINCT\n refs.team_slug AS \"team_slug!\",\n refs.task_num AS \"task_num!\",\n t.id AS \"team_id!\",\n tt.document_id AS \"document_id!\"\n FROM UNNEST($2::text[], $3::int4[]) AS refs(team_slug, task_num)\n JOIN github_app_installation gai\n ON gai.id = $1\n AND gai.source_type = 'team'::github_app_installation_source_type\n JOIN team t\n ON t.id = gai.source_id::uuid\n AND LOWER(t.slug) = LOWER(refs.team_slug)\n JOIN team_task tt ON tt.team_id = t.id AND tt.task_num = refs.task_num\n ",+ "describe": {+ "columns": [+ {+ "ordinal": 0,+ "name": "team_slug!",+ "type_info": "Text"+ },+ {+ "ordinal": 1,+ "name": "task_num!",+ "type_info": "Int4"+ },+ {+ "ordinal": 2,+ "name": "team_id!",+ "type_info": "Uuid"+ },+ {+ "ordinal": 3,+ "name": "document_id!",+ "type_info": "Text"+ }+ ],+ "parameters": {+ "Left": [+ "Text",+ "TextArray",+ "Int4Array"+ ]+ },+ "nullable": [+ null,+ null,+ false,+ false+ ]+ },+ "hash": "f8d5930bc985a02933afc33e8a908915e3a70baebc90ba622768f69cf87f68cf"+}diff --git a/crates/github/src/domain/models/mod.rs b/crates/github/src/domain/models/mod.rsindex 2cb416bd7a..0fe78fb81a 100644--- a/crates/github/src/domain/models/mod.rs+++ b/crates/github/src/domain/models/mod.rs@@ -16,7 +16,8 @@ pub use pull_request::{};pub use sync::{GithubAppInstallationSource, GithubInstallationAccessToken, GithubKey, GithubWebhookEventType,- MacroTaskId, TeamTaskReference, ValidatedGithubWebhookEvent, extract_github_mentions,+ MacroTaskId, ResolvedTeamTaskReference, TeamTaskReference, ValidatedGithubWebhookEvent,+ extract_github_mentions,};/// Errors that can occur during github operations.#[derive(Debug, thiserror::Error)]diff --git a/crates/github/src/domain/models/sync.rs b/crates/github/src/domain/models/sync.rsindex bc7f7b2e2c..b5011242f6 100644--- a/crates/github/src/domain/models/sync.rs+++ b/crates/github/src/domain/models/sync.rs@@ -429,6 +429,21 @@ impl TeamTaskReference {}}+/// A [`TeamTaskReference`] resolved against a concrete team.+///+/// Because team slugs are not unique, one reference can resolve in more than+/// one of an installation's teams; callers must treat such references as+/// ambiguous rather than linking every match.+#[derive(Debug, Clone, PartialEq, Eq, Hash)]+pub struct ResolvedTeamTaskReference {+ /// The reference that was resolved.+ pub reference: TeamTaskReference,+ /// The team whose slug and task number matched the reference.+ pub team_id: uuid::Uuid,+ /// The task document backing the team task.+ pub task_id: MacroTaskId,+}+/// A Macro task ID in the form `MACRO-{short_uuid}`.#[derive(Debug, Clone, PartialEq, Eq, Hash)]pub struct MacroTaskId {diff --git a/crates/github/src/domain/ports/sync.rs b/crates/github/src/domain/ports/sync.rsindex dc35781b17..7cf8eeef4e 100644--- a/crates/github/src/domain/ports/sync.rs+++ b/crates/github/src/domain/ports/sync.rs@@ -7,7 +7,7 @@ use macro_user_id::user_id::MacroUserIdStr;use crate::domain::models::{EnrichedGithubPullRequest, GithubAppInstallationSource, GithubError,GithubInstallationAccessToken, GithubKey, GithubPullRequestDetails, MacroTaskId,- TeamTaskReference, ValidatedGithubWebhookEvent,+ ResolvedTeamTaskReference, TeamTaskReference, ValidatedGithubWebhookEvent,};/// Repository for accessing github sync data from the database.@@ -44,12 +44,16 @@ pub trait GithubSyncRepo: Send + Sync + 'static {////// Implementations should use the installation's team sources from/// `github_app_installation` (`source_type = 'team'`) and the referenced- /// team slug/task number to find the backing Macro task document.+ /// team slug/task number to find the backing Macro task document. Each+ /// match is returned with the team it resolved in; because team slugs are+ /// not unique, one reference may resolve in several of the installation's+ /// teams and callers must treat such references as ambiguous instead of+ /// linking every match.fn resolve_team_task_references(&self,installation_id: &str,references: &[TeamTaskReference],- ) -> impl Future<Output = Result<Vec<MacroTaskId>, Self::Err>> + Send;+ ) -> impl Future<Output = Result<Vec<ResolvedTeamTaskReference>, Self::Err>> + Send;/// Maps GitHub user IDs to the Macro user IDs linked to them via the `github_links` table.///diff --git a/crates/github/src/domain/service/sync/mod.rs b/crates/github/src/domain/service/sync/mod.rsindex 202083dc22..5a31db951c 100644--- a/crates/github/src/domain/service/sync/mod.rs+++ b/crates/github/src/domain/service/sync/mod.rs@@ -15,7 +15,7 @@ use crate::domain::{EnrichedGithubPullRequest, GITHUB_PULL_REQUEST_FOREIGN_ENTITY_SOURCE,GithubAppInstallationSource, GithubError, GithubInstallationAccessToken, GithubKey,GithubPullRequestDetails, GithubPullRequestStatus, GithubWebhookEventType, MacroTaskId,- TeamTaskReference, ValidatedGithubWebhookEvent,+ ResolvedTeamTaskReference, TeamTaskReference, ValidatedGithubWebhookEvent,},ports::{GithubSyncClient, GithubSyncRepo, GithubSyncService},};@@ -29,7 +29,10 @@ use hmac::{Hmac, Mac};use macro_env_var::maybe_env_vars;use notification::domain::service::NotificationIngress;use sha2::Sha256;-use std::{collections::HashSet, sync::Arc};+use std::{+ collections::{HashMap, HashSet},+ sync::Arc,+};use subtle::ConstantTimeEq;type HmacSha256 = Hmac<Sha256>;@@ -645,13 +648,46 @@ impl<.resolve_team_task_references(&installation_id, &team_task_refs).await{- Ok(mut resolved_team_task_ids) => {+ Ok(resolutions) => {+ // Team slugs are not unique, so a reference can match+ // tasks in several of the installation's teams. Only+ // link references that resolve in exactly one team;+ // an ambiguous reference must not fan out links to+ // other teams' tasks.+ let mut by_reference: HashMap<+ TeamTaskReference,+ Vec<ResolvedTeamTaskReference>,+ > = HashMap::new();+ for resolution in resolutions {+ by_reference+ .entry(resolution.reference.clone())+ .or_default()+ .push(resolution);+ }++ let mut resolved_team_task_id_count = 0;+ for (reference, resolutions) in by_reference {+ if resolutions.len() > 1 {+ tracing::warn!(+ team_slug = %reference.team_slug,+ team_task_id = reference.team_task_id,+ team_ids = ?resolutions+ .iter()+ .map(|r| r.team_id)+ .collect::<Vec<_>>(),+ "team task reference matched tasks in multiple teams, skipping ambiguous reference"+ );+ continue;+ }+ resolved_team_task_id_count += resolutions.len();+ task_ids.extend(resolutions.into_iter().map(|r| r.task_id));+ }+tracing::trace!(team_task_ref_count = team_task_refs.len(),- resolved_team_task_id_count = resolved_team_task_ids.len(),+ resolved_team_task_id_count,"resolved team task references from webhook text");- task_ids.append(&mut resolved_team_task_ids);}Err(e) => {tracing::error!(diff --git a/crates/github/src/domain/service/sync/test.rs b/crates/github/src/domain/service/sync/test.rsindex 853f46f8f1..15fdf3abc6 100644--- a/crates/github/src/domain/service/sync/test.rs+++ b/crates/github/src/domain/service/sync/test.rs@@ -6,7 +6,7 @@ use crate::domain::{EnrichedGithubPullRequest, GithubAppInstallationSource, GithubError,GithubInstallationAccessToken, GithubKey, GithubPullRequestCheckRun,GithubPullRequestComment, GithubPullRequestDetails, GithubPullRequestStatus, MacroTaskId,- TeamTaskReference, ValidatedGithubWebhookEvent,+ ResolvedTeamTaskReference, TeamTaskReference, ValidatedGithubWebhookEvent,},ports::{GithubSyncClient, GithubSyncRepo, GithubSyncService},};@@ -301,8 +301,11 @@ impl DocumentService for StubDocumentService {/// Stateful stub repo that tracks task IDs per github key.struct StubSyncRepo {tasks: Mutex<HashMap<String, HashSet<String>>>,- /// Maps (installation_id, normalized team_slug, team_task_id) -> task ID.- team_task_references: Mutex<HashMap<(String, String, i32), MacroTaskId>>,+ /// Maps (installation_id, normalized team_slug, team_task_id) -> matching+ /// (team_id, task ID) pairs. Multiple entries model a slug shared by+ /// several of the installation's teams.+ #[allow(clippy::type_complexity)]+ team_task_references: Mutex<HashMap<(String, String, i32), Vec<(uuid::Uuid, MacroTaskId)>>>,/// Maps github_user_id -> macro_ids for installation event lookups.////// A github_user_id may map to multiple Macro users because multiple Macro@@ -382,16 +385,19 @@ impl StubSyncRepo {installation_id: &str,team_slug: &str,team_task_id: i32,+ team_id: uuid::Uuid,task_id: MacroTaskId,) -> Self {- self.team_task_references.lock().unwrap().insert(- (+ self.team_task_references+ .lock()+ .unwrap()+ .entry((installation_id.to_string(),team_slug.to_ascii_lowercase(),team_task_id,- ),- task_id,- );+ ))+ .or_default()+ .push((team_id, task_id));self}@@ -476,7 +482,7 @@ impl GithubSyncRepo for StubSyncRepo {&self,installation_id: &str,references: &[TeamTaskReference],- ) -> Result<Vec<MacroTaskId>, Self::Err> {+ ) -> Result<Vec<ResolvedTeamTaskReference>, Self::Err> {let team_task_references = self.team_task_references.lock().unwrap();let mut seen = HashSet::new();let mut resolved = Vec::new();@@ -487,10 +493,14 @@ impl GithubSyncRepo for StubSyncRepo {reference.team_slug.to_ascii_lowercase(),reference.team_task_id,);- if let Some(task_id) = team_task_references.get(&key)- && seen.insert(task_id.clone())- {- resolved.push(task_id.clone());+ for (team_id, task_id) in team_task_references.get(&key).into_iter().flatten() {+ if seen.insert((*team_id, task_id.clone())) {+ resolved.push(ResolvedTeamTaskReference {+ reference: reference.clone(),+ team_id: *team_id,+ task_id: task_id.clone(),+ });+ }}}@@ -1470,7 +1480,8 @@ async fn pr_with_task_id_in_branch_name() {#[tokio::test]async fn pr_with_team_task_id_in_branch_name() {let task_id = MacroTaskId::from_uuid(&uuid::Uuid::parse_str(KNOWN_TASK_UUID).unwrap());- let repo = StubSyncRepo::new().with_team_task_reference("12345", "eng", 123, task_id);+ let team_id = uuid::Uuid::parse_str("dddddddd-dddd-dddd-dddd-dddddddddddd").unwrap();+ let repo = StubSyncRepo::new().with_team_task_reference("12345", "eng", 123, team_id, task_id);let service = make_sync_service_with_repo(repo);let event = ValidatedGithubWebhookEvent::new(@@ -1506,7 +1517,8 @@ async fn pr_with_team_task_id_in_branch_name() {#[tokio::test]async fn team_task_id_requires_installation_team_match() {let task_id = MacroTaskId::from_uuid(&uuid::Uuid::parse_str(KNOWN_TASK_UUID).unwrap());- let repo = StubSyncRepo::new().with_team_task_reference("99999", "eng", 123, task_id);+ let team_id = uuid::Uuid::parse_str("dddddddd-dddd-dddd-dddd-dddddddddddd").unwrap();+ let repo = StubSyncRepo::new().with_team_task_reference("99999", "eng", 123, team_id, task_id);let service = make_sync_service_with_repo(repo);let event = ValidatedGithubWebhookEvent::new(@@ -1532,6 +1544,53 @@ async fn team_task_id_requires_installation_team_match() {assert!(service.client.pr_comments().is_empty());}+#[tokio::test]+async fn ambiguous_team_task_reference_links_nothing() {+ // Two of the installation's teams share the slug "eng" (slugs are not+ // unique), so "eng-123" matches a different task in each team. Linking+ // either would risk attributing the PR to the wrong team's task, so the+ // reference must be skipped entirely.+ let task_a = MacroTaskId::from_uuid(&uuid::Uuid::parse_str(KNOWN_TASK_UUID).unwrap());+ let task_b = MacroTaskId::from_uuid(+ &uuid::Uuid::parse_str("11111111-1111-1111-1111-111111111111").unwrap(),+ );+ let team_a = uuid::Uuid::parse_str("dddddddd-dddd-dddd-dddd-dddddddddddd").unwrap();+ let team_b = uuid::Uuid::parse_str("eeeeeeee-eeee-eeee-eeee-eeeeeeeeeeee").unwrap();+ let repo = StubSyncRepo::new()+ .with_team_task_reference("12345", "eng", 123, team_a, task_a)+ .with_team_task_reference("12345", "eng", 123, team_b, task_b);+ let service = make_sync_service_with_repo(repo);++ let event = ValidatedGithubWebhookEvent::new(+ "pull_request".to_string(),+ serde_json::json!({+ "action": "opened",+ "pull_request": {+ "number": 7,+ "title": "some feature",+ "body": null,+ "head": { "ref": "whutch/eng-123-fix-some-bug" }+ },+ "repository": {+ "name": "my-repo",+ "owner": { "login": "my-org" }+ },+ "installation": { "id": 12345 }+ }),+ );++ let result = service.process_webhook_event(&event).await;+ assert!(result.is_ok());++ assert!(service.client.pr_comments().is_empty());+ let tracked = service+ .repo+ .get_task_ids(GithubKey::new("my-org", "my-repo", 7))+ .await+ .unwrap();+ assert!(tracked.is_empty());+}+#[tokio::test]async fn issue_comment_with_task_id() {let service = make_sync_service();diff --git a/crates/github/src/outbound/pg_github_sync_repo.rs b/crates/github/src/outbound/pg_github_sync_repo.rsindex 5ccda32310..9f95feb2fe 100644--- a/crates/github/src/outbound/pg_github_sync_repo.rs+++ b/crates/github/src/outbound/pg_github_sync_repo.rs@@ -9,7 +9,10 @@ use macro_user_id::user_id::MacroUserIdStr;use sqlx::PgPool;use crate::domain::{- models::{GithubAppInstallationSource, GithubKey, MacroTaskId, TeamTaskReference},+ models::{+ GithubAppInstallationSource, GithubKey, MacroTaskId, ResolvedTeamTaskReference,+ TeamTaskReference,+ },ports::GithubSyncRepo,};@@ -59,18 +62,29 @@ impl GithubSyncRepo for PgGithubSyncRepo {.iter().map(|_| macro_uuid::generate_uuid_v7()).collect();+ // Full-UUID document ids used to look up each task's owning team;+ // an unconvertible short UUID simply matches no team_task row.+ let document_ids: Vec<String> = task_ids+ .iter()+ .map(|t| t.to_uuid().map(|uuid| uuid.to_string()).unwrap_or_default())+ .collect();let github_key = github_key.as_ref();let github_keys: Vec<&str> = std::iter::repeat_n(github_key, short_ids.len()).collect();sqlx::query!(r#"- INSERT INTO github_pr_tasks (id, github_key, task_id)- SELECT * FROM UNNEST($1::uuid[], $2::text[], $3::text[])- ON CONFLICT (github_key, task_id) DO NOTHING+ INSERT INTO github_pr_tasks (id, github_key, task_id, team_id)+ SELECT u.id, u.github_key, u.task_id, tt.team_id+ FROM UNNEST($1::uuid[], $2::text[], $3::text[], $4::text[])+ AS u(id, github_key, task_id, document_id)+ LEFT JOIN team_task tt ON tt.document_id = u.document_id+ ON CONFLICT (github_key, task_id)+ DO UPDATE SET team_id = COALESCE(github_pr_tasks.team_id, EXCLUDED.team_id)"#,&ids,&github_keys as &[&str],- &short_ids+ &short_ids,+ &document_ids).execute(&self.pool).await?;@@ -113,7 +127,7 @@ impl GithubSyncRepo for PgGithubSyncRepo {&self,installation_id: &str,references: &[TeamTaskReference],- ) -> Result<Vec<MacroTaskId>, Self::Err> {+ ) -> Result<Vec<ResolvedTeamTaskReference>, Self::Err> {if references.is_empty() {return Ok(Vec::new());}@@ -123,7 +137,11 @@ impl GithubSyncRepo for PgGithubSyncRepo {let rows = sqlx::query!(r#"- SELECT DISTINCT tt.document_id+ SELECT DISTINCT+ refs.team_slug AS "team_slug!",+ refs.task_num AS "task_num!",+ t.id AS "team_id!",+ tt.document_id AS "document_id!"FROM UNNEST($2::text[], $3::int4[]) AS refs(team_slug, task_num)JOIN github_app_installation gaiON gai.id = $1@@ -143,12 +161,16 @@ impl GithubSyncRepo for PgGithubSyncRepo {Ok(rows.into_iter().filter_map(|row| {- let document_id = row.document_id;- match uuid::Uuid::parse_str(&document_id) {- Ok(uuid) => Some(MacroTaskId::from_uuid(&uuid)),+ let reference = TeamTaskReference::new(&row.team_slug, row.task_num)?;+ match uuid::Uuid::parse_str(&row.document_id) {+ Ok(uuid) => Some(ResolvedTeamTaskReference {+ reference,+ team_id: row.team_id,+ task_id: MacroTaskId::from_uuid(&uuid),+ }),Err(e) => {tracing::warn!(- document_id,+ document_id = row.document_id,error=?e,"team task document id is not a UUID");diff --git a/crates/github/src/outbound/pg_github_sync_repo/test.rs b/crates/github/src/outbound/pg_github_sync_repo/test.rsindex 188648515e..1097e8d646 100644--- a/crates/github/src/outbound/pg_github_sync_repo/test.rs+++ b/crates/github/src/outbound/pg_github_sync_repo/test.rs@@ -3,7 +3,8 @@ use sqlx::{Pool, Postgres};use uuid::Uuid;use crate::domain::models::{- GithubAppInstallationSource, GithubKey, MacroTaskId, TeamTaskReference,+ GithubAppInstallationSource, GithubKey, MacroTaskId, ResolvedTeamTaskReference,+ TeamTaskReference,};use crate::domain::ports::GithubSyncRepo;use crate::outbound::pg_github_sync_repo::PgGithubSyncRepo;@@ -91,6 +92,86 @@ async fn test_upsert_task_ids_ignores_duplicates(pool: Pool<Postgres>) {assert_eq!(fetched.len(), 3); // s61dee.., bMv3e.. (existing) + xoyQ8..}+#[sqlx::test(+ migrator = "MACRO_DB_MIGRATIONS",+ fixtures(path = "../../../fixtures", scripts("github_team_task_test_data"))+)]+async fn test_upsert_task_ids_records_owning_team(pool: Pool<Postgres>) {+ let repo = PgGithubSyncRepo::new(pool.clone());++ // 0d0dc589-f301-43f1-8b11-4ab448ca4bb4 is team task ENG-123 of team+ // dddddddd-...; the second task id has no team_task row.+ let team_task =+ MacroTaskId::from_uuid(&Uuid::parse_str("0d0dc589-f301-43f1-8b11-4ab448ca4bb4").unwrap());+ let teamless_task = MacroTaskId::from_short_uuid("xoyQ8nrV6PNZFmpsWYMdyC").unwrap();++ let key = GithubKey::new("org", "repo", 10);+ repo.upsert_task_ids(key.clone(), &[team_task.clone(), teamless_task.clone()])+ .await+ .unwrap();++ let rows = sqlx::query!(+ r#"SELECT task_id, team_id FROM github_pr_tasks WHERE github_key = $1"#,+ key.as_ref()+ )+ .fetch_all(&pool)+ .await+ .unwrap();++ assert_eq!(rows.len(), 2);+ let expected_team = Uuid::parse_str("dddddddd-dddd-dddd-dddd-dddddddddddd").unwrap();+ for row in rows {+ if row.task_id == team_task.short_uuid {+ assert_eq!(row.team_id, Some(expected_team));+ } else {+ assert_eq!(row.task_id, teamless_task.short_uuid);+ assert_eq!(row.team_id, None);+ }+ }+}++#[sqlx::test(+ migrator = "MACRO_DB_MIGRATIONS",+ fixtures(path = "../../../fixtures", scripts("github_team_task_test_data"))+)]+async fn test_upsert_task_ids_backfills_team_on_existing_rows(pool: Pool<Postgres>) {+ let repo = PgGithubSyncRepo::new(pool.clone());++ let team_task =+ MacroTaskId::from_uuid(&Uuid::parse_str("0d0dc589-f301-43f1-8b11-4ab448ca4bb4").unwrap());+ let key = GithubKey::new("org", "repo", 10);++ // Simulate a legacy row written before team_id existed.+ sqlx::query!(+ r#"INSERT INTO github_pr_tasks (id, github_key, task_id) VALUES ($1, $2, $3)"#,+ macro_uuid::generate_uuid_v7(),+ key.as_ref(),+ &team_task.short_uuid+ )+ .execute(&pool)+ .await+ .unwrap();++ repo.upsert_task_ids(key.clone(), std::slice::from_ref(&team_task))+ .await+ .unwrap();++ let rows = sqlx::query!(+ r#"SELECT team_id FROM github_pr_tasks WHERE github_key = $1 AND task_id = $2"#,+ key.as_ref(),+ &team_task.short_uuid+ )+ .fetch_all(&pool)+ .await+ .unwrap();++ assert_eq!(rows.len(), 1);+ assert_eq!(+ rows[0].team_id,+ Some(Uuid::parse_str("dddddddd-dddd-dddd-dddd-dddddddddddd").unwrap())+ );+}+#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]async fn test_upsert_task_ids_empty_list(pool: Pool<Postgres>) {let repo = PgGithubSyncRepo::new(pool);@@ -188,19 +269,86 @@ async fn test_resolve_team_task_references(pool: Pool<Postgres>) {TeamTaskReference::new("platform_api", 7).unwrap(),];- let task_ids = repo+ let resolutions = repo.resolve_team_task_references("12345", &refs).await.unwrap();- let expected_known =- MacroTaskId::from_uuid(&Uuid::parse_str("0d0dc589-f301-43f1-8b11-4ab448ca4bb4").unwrap());- let expected_platform =- MacroTaskId::from_uuid(&Uuid::parse_str("11111111-1111-1111-1111-111111111111").unwrap());+ let expected_known = ResolvedTeamTaskReference {+ reference: TeamTaskReference::new("eng", 123).unwrap(),+ team_id: Uuid::parse_str("dddddddd-dddd-dddd-dddd-dddddddddddd").unwrap(),+ task_id: MacroTaskId::from_uuid(+ &Uuid::parse_str("0d0dc589-f301-43f1-8b11-4ab448ca4bb4").unwrap(),+ ),+ };+ let expected_platform = ResolvedTeamTaskReference {+ reference: TeamTaskReference::new("platform_api", 7).unwrap(),+ team_id: Uuid::parse_str("eeeeeeee-eeee-eeee-eeee-eeeeeeeeeeee").unwrap(),+ task_id: MacroTaskId::from_uuid(+ &Uuid::parse_str("11111111-1111-1111-1111-111111111111").unwrap(),+ ),+ };++ assert_eq!(resolutions.len(), 2);+ assert!(resolutions.contains(&expected_known));+ assert!(resolutions.contains(&expected_platform));+}- assert_eq!(task_ids.len(), 2);- assert!(task_ids.contains(&expected_known));- assert!(task_ids.contains(&expected_platform));+#[sqlx::test(+ migrator = "MACRO_DB_MIGRATIONS",+ fixtures(path = "../../../fixtures", scripts("github_team_task_test_data"))+)]+async fn test_resolve_team_task_references_returns_all_teams_sharing_a_slug(pool: Pool<Postgres>) {+ // Give the installation a second team whose slug is also ENG, with its+ // own task 123. The resolver reports both matches (with their teams) so+ // the service can detect the ambiguity.+ sqlx::query!(+ r#"+ WITH new_macro_user AS (+ INSERT INTO macro_user (id, username, email, stripe_customer_id)+ VALUES ('99999999-9999-9999-9999-999999999999'::uuid, 'owner3', '[email protected]', 'cus_test3')+ ), new_user AS (+ INSERT INTO "User" (id, email, macro_user_id)+ VALUES ('macro|[email protected]', '[email protected]', '99999999-9999-9999-9999-999999999999'::uuid)+ RETURNING id+ ), new_team AS (+ INSERT INTO team (id, name, owner_id, slug)+ SELECT 'ffffffff-ffff-ffff-ffff-ffffffffffff'::uuid, 'Other Eng', new_user.id, 'ENG' FROM new_user+ RETURNING id+ ), new_doc AS (+ INSERT INTO "Document" (id, name, "fileType", owner)+ VALUES ('22222222-2222-2222-2222-222222222222', 'Other Task', 'md', 'macro|[email protected]')+ RETURNING id+ ), new_task AS (+ INSERT INTO team_task (team_id, document_id, task_num)+ SELECT new_team.id, new_doc.id, 123 FROM new_team, new_doc+ )+ INSERT INTO github_app_installation (id, source_id, source_type)+ SELECT '12345', new_team.id::text, 'team'::github_app_installation_source_type FROM new_team+ "#,+ )+ .execute(&pool)+ .await+ .unwrap();++ let repo = PgGithubSyncRepo::new(pool);+ let refs = vec![TeamTaskReference::new("eng", 123).unwrap()];++ let resolutions = repo+ .resolve_team_task_references("12345", &refs)+ .await+ .unwrap();++ assert_eq!(resolutions.len(), 2);+ let team_ids: Vec<Uuid> = resolutions.iter().map(|r| r.team_id).collect();+ assert!(team_ids.contains(&Uuid::parse_str("dddddddd-dddd-dddd-dddd-dddddddddddd").unwrap()));+ assert!(team_ids.contains(&Uuid::parse_str("ffffffff-ffff-ffff-ffff-ffffffffffff").unwrap()));+ for resolution in &resolutions {+ assert_eq!(+ resolution.reference,+ TeamTaskReference::new("eng", 123).unwrap()+ );+ }}#[sqlx::test(diff --git a/crates/macro_db_client/migrations/20260731123644_add_team_id_to_github_pr_tasks.sql b/crates/macro_db_client/migrations/20260731123644_add_team_id_to_github_pr_tasks.sqlnew file mode 100644index 0000000000..20a1786140--- /dev/null+++ b/crates/macro_db_client/migrations/20260731123644_add_team_id_to_github_pr_tasks.sql@@ -0,0 +1,9 @@+-- Record which team's task a PR link belongs to, making github_pr_tasks rows+-- explicitly team-scoped. NULL for rows written before this column existed+-- (task_id is a base58 short UUID, so they cannot be joined to team_task in+-- SQL; upsert_task_ids backfills them as PR events recur) and for tasks that+-- have no team_task row.+ALTER TABLE github_pr_tasks+ ADD COLUMN team_id UUID REFERENCES team (id) ON DELETE SET NULL;++CREATE INDEX idx_github_pr_tasks_team_id ON github_pr_tasks (team_id);