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): support team-slug pr task integration (#3506)

Will Hutchinson5326d9a58e4f
diff --git a/rust/cloud-storage/.sqlx/query-69eb6f834b928cea392026149a61b09f53c38f7ef7f43720f16d7ecf98bfe0f4.json b/rust/cloud-storage/.sqlx/query-69eb6f834b928cea392026149a61b09f53c38f7ef7f43720f16d7ecf98bfe0f4.json
new file mode 100644
index 0000000000..d816a21685
--- /dev/null
+++ b/rust/cloud-storage/.sqlx/query-69eb6f834b928cea392026149a61b09f53c38f7ef7f43720f16d7ecf98bfe0f4.json
@@ -0,0 +1,24 @@
+{
+ "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_team gait ON gait.id = $1\n JOIN team t ON t.id = gait.team_id 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": "69eb6f834b928cea392026149a61b09f53c38f7ef7f43720f16d7ecf98bfe0f4"
+}
diff --git a/rust/cloud-storage/github/fixtures/github_team_task_test_data.sql b/rust/cloud-storage/github/fixtures/github_team_task_test_data.sql
new file mode 100644
index 0000000000..d7eb6b7fc5
--- /dev/null
+++ b/rust/cloud-storage/github/fixtures/github_team_task_test_data.sql
@@ -0,0 +1,47 @@
+INSERT INTO
+ public.macro_user (id, username, email, stripe_customer_id)
+VALUES
+ ('bbbbbbbb-bbbb-bbbb-bbbb-bbbbbbbbbbbb'::uuid, 'testuser', '[email protected]', 'cus_test'),
+ ('cccccccc-cccc-cccc-cccc-cccccccccccc'::uuid, 'owner2', '[email protected]', 'cus_test2');
+
+INSERT INTO
+ public."User" (id, email, macro_user_id)
+VALUES
+ ('macro|[email protected]', '[email protected]', 'bbbbbbbb-bbbb-bbbb-bbbb-bbbbbbbbbbbb'::uuid),
+ ('macro|[email protected]', '[email protected]', 'cccccccc-cccc-cccc-cccc-cccccccccccc'::uuid);
+
+INSERT INTO
+ public.team (id, name, owner_id, slug)
+VALUES
+ ('dddddddd-dddd-dddd-dddd-dddddddddddd'::uuid, 'Engineering', 'macro|[email protected]', 'ENG'),
+ ('eeeeeeee-eeee-eeee-eeee-eeeeeeeeeeee'::uuid, 'Platform API', 'macro|[email protected]', 'PLATFORM_API');
+
+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, 'owner');
+
+INSERT INTO
+ public."Document" (id, name, "fileType", owner)
+VALUES
+ ('0d0dc589-f301-43f1-8b11-4ab448ca4bb4', 'Known Task', 'md', 'macro|[email protected]'),
+ ('11111111-1111-1111-1111-111111111111', 'Platform Task', 'md', 'macro|[email protected]');
+
+INSERT INTO
+ public.document_sub_type (document_id, sub_type)
+VALUES
+ ('0d0dc589-f301-43f1-8b11-4ab448ca4bb4', 'task'),
+ ('11111111-1111-1111-1111-111111111111', 'task');
+
+INSERT INTO
+ public.team_task (team_id, document_id, task_num)
+VALUES
+ ('dddddddd-dddd-dddd-dddd-dddddddddddd'::uuid, '0d0dc589-f301-43f1-8b11-4ab448ca4bb4', 123),
+ ('eeeeeeee-eeee-eeee-eeee-eeeeeeeeeeee'::uuid, '11111111-1111-1111-1111-111111111111', 7);
+
+INSERT INTO
+ public.github_app_installation_team (id, team_id, installed_by)
+VALUES
+ ('12345', 'dddddddd-dddd-dddd-dddd-dddddddddddd'::uuid, 'macro|[email protected]'),
+ ('12345', 'eeeeeeee-eeee-eeee-eeee-eeeeeeeeeeee'::uuid, 'macro|[email protected]');
diff --git a/rust/cloud-storage/github/src/domain/models/mod.rs b/rust/cloud-storage/github/src/domain/models/mod.rs
index 8852f8c2f2..74e11145ce 100644
--- a/rust/cloud-storage/github/src/domain/models/mod.rs
+++ b/rust/cloud-storage/github/src/domain/models/mod.rs
@@ -9,7 +9,7 @@ mod sync;
pub use link::{GithubAccessToken, GithubExchangeTokenResponse, GithubLink, GithubUserInfo};
pub use sync::{
GithubInstallationAccessToken, GithubKey, GithubWebhookEventType, MacroTaskId,
- ValidatedGithubWebhookEvent,
+ TeamTaskReference, ValidatedGithubWebhookEvent,
};
/// Errors that can occur during github operations.
#[derive(Debug, thiserror::Error)]
diff --git a/rust/cloud-storage/github/src/domain/models/sync.rs b/rust/cloud-storage/github/src/domain/models/sync.rs
index 6618108891..22ec938665 100644
--- a/rust/cloud-storage/github/src/domain/models/sync.rs
+++ b/rust/cloud-storage/github/src/domain/models/sync.rs
@@ -290,6 +290,62 @@ static MACRO_TASK_ID_RE: LazyLock<Regex> = LazyLock::new(|| {
.expect("valid regex")
});
+/// Regex matching `{team_slug}-{team_task_id}` references.
+///
+/// The slug follows the team slug format used in generated branch names
+/// (letters/numbers/underscores, matched case-insensitively). The numeric
+/// portion is the per-team task number.
+static TEAM_TASK_REFERENCE_RE: LazyLock<Regex> = LazyLock::new(|| {
+ Regex::new(r"(?i)(?:^|[^a-z0-9_])([a-z][a-z0-9_]{0,19})-([1-9][0-9]*)(?:$|[^a-z0-9_])")
+ .expect("valid regex")
+});
+
+/// A team-scoped task reference in the form `{team_slug}-{team_task_id}`.
+#[derive(Debug, Clone, PartialEq, Eq, Hash)]
+pub struct TeamTaskReference {
+ /// Team slug as it appears in the reference, normalized to lowercase.
+ pub team_slug: String,
+ /// Positive per-team task number.
+ pub team_task_id: i32,
+}
+
+impl TeamTaskReference {
+ /// Create a normalized team task reference.
+ pub fn new(team_slug: &str, team_task_id: i32) -> Option<Self> {
+ let team_slug = team_slug.trim().to_ascii_lowercase();
+ if team_slug.is_empty() || team_task_id <= 0 {
+ return None;
+ }
+
+ Some(Self {
+ team_slug,
+ team_task_id,
+ })
+ }
+
+ /// Extract all unique `{team_slug}-{team_task_id}` references from text.
+ pub fn extract_from_text(text: &str) -> Vec<Self> {
+ let mut seen = HashSet::new();
+ let mut results = Vec::new();
+
+ for caps in TEAM_TASK_REFERENCE_RE.captures_iter(text) {
+ let Some(task_num) = caps[2].parse::<i32>().ok() else {
+ continue;
+ };
+
+ let Some(reference) = Self::new(&caps[1], task_num) else {
+ continue;
+ };
+
+ if seen.insert((reference.team_slug.clone(), reference.team_task_id)) {
+ results.push(reference);
+ }
+ }
+
+ results
+ }
+}
+
/// A Macro task ID in the form `MACRO-{short_uuid}`.
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct MacroTaskId {
diff --git a/rust/cloud-storage/github/src/domain/models/test.rs b/rust/cloud-storage/github/src/domain/models/test.rs
index 3dadd814ba..a15f471955 100644
--- a/rust/cloud-storage/github/src/domain/models/test.rs
+++ b/rust/cloud-storage/github/src/domain/models/test.rs
@@ -119,6 +119,30 @@ fn extract_multiple_in_sentence() {
assert_eq!(ids[1].short_uuid, "bbb222");
}
+// ---------------------------------------------------------------------------
+// TeamTaskReference::extract_from_text
+// ---------------------------------------------------------------------------
+
+#[test]
+fn extract_team_task_reference_from_branch_name() {
+ let refs = TeamTaskReference::extract_from_text("whutch/eng-123-fix-the-thing");
+ assert_eq!(refs, vec![TeamTaskReference::new("eng", 123).unwrap()]);
+}
+
+#[test]
+fn extract_team_task_reference_case_insensitive_and_dedupes() {
+ let refs = TeamTaskReference::extract_from_text("ENG-123 eng-123 platform_api-7");
+ assert_eq!(refs.len(), 2);
+ assert_eq!(refs[0], TeamTaskReference::new("eng", 123).unwrap());
+ assert_eq!(refs[1], TeamTaskReference::new("platform_api", 7).unwrap());
+}
+
+#[test]
+fn extract_team_task_reference_rejects_invalid_numbers() {
+ let refs = TeamTaskReference::extract_from_text("eng-0 eng-abc eng-999999999999999999999");
+ assert!(refs.is_empty());
+}
+
// ---------------------------------------------------------------------------
// ValidatedGithubWebhookEvent::pull_number / repo_owner / repo_name / installation_id
// ---------------------------------------------------------------------------
diff --git a/rust/cloud-storage/github/src/domain/ports/sync.rs b/rust/cloud-storage/github/src/domain/ports/sync.rs
index d61b5b1c70..66aa214895 100644
--- a/rust/cloud-storage/github/src/domain/ports/sync.rs
+++ b/rust/cloud-storage/github/src/domain/ports/sync.rs
@@ -3,7 +3,8 @@
use std::future::Future;
use crate::domain::models::{
- GithubError, GithubInstallationAccessToken, GithubKey, MacroTaskId, ValidatedGithubWebhookEvent,
+ GithubError, GithubInstallationAccessToken, GithubKey, MacroTaskId, TeamTaskReference,
+ ValidatedGithubWebhookEvent,
};
/// Repository for accessing github sync data from the database.
@@ -36,6 +37,17 @@ pub trait GithubSyncRepo: Send + Sync + 'static {
task_ids: &[MacroTaskId],
) -> impl Future<Output = Result<Vec<MacroTaskId>, Self::Err>> + Send;
+ /// Resolves team-scoped task references for a GitHub App installation.
+ ///
+ /// Implementations should use the installation's teams (via
+ /// `github_app_installation_team`) and the referenced team slug/task number
+ /// to find the backing Macro task document.
+ fn resolve_team_task_references(
+ &self,
+ installation_id: &str,
+ references: &[TeamTaskReference],
+ ) -> 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(
diff --git a/rust/cloud-storage/github/src/domain/service/sync/handle_comment.rs b/rust/cloud-storage/github/src/domain/service/sync/handle_comment.rs
index 6af84802de..a632096923 100644
--- a/rust/cloud-storage/github/src/domain/service/sync/handle_comment.rs
+++ b/rust/cloud-storage/github/src/domain/service/sync/handle_comment.rs
@@ -22,7 +22,7 @@ impl<D: DocumentService, R: GithubSyncRepo, C: GithubSyncClient> GithubSyncServi
// Extract task IDs from the new comment/review text only
let searchable_texts = event.extract_searchable_text();
let combined = searchable_texts.join(" ");
- let comment_task_ids: Vec<MacroTaskId> = MacroTaskId::extract_from_text(&combined);
+ let comment_task_ids = self.extract_task_ids_from_text(event, &combined).await;
tracing::trace!(
new_task_id_count = comment_task_ids.len(),
@@ -50,7 +50,7 @@ impl<D: DocumentService, R: GithubSyncRepo, C: GithubSyncClient> GithubSyncServi
if let Some(ref key) = github_key {
let pr_context_tasks = {
let pr_context = event.extract_pr_context_text().join(" ");
- let extracted = MacroTaskId::extract_from_text(&pr_context);
+ let extracted = self.extract_task_ids_from_text(event, &pr_context).await;
// Validate PR context task IDs too
self.resolve_tasks(&extracted).await.validated_task_ids
};
diff --git a/rust/cloud-storage/github/src/domain/service/sync/handle_pr.rs b/rust/cloud-storage/github/src/domain/service/sync/handle_pr.rs
index 65c6ca292c..6062ea7bde 100644
--- a/rust/cloud-storage/github/src/domain/service/sync/handle_pr.rs
+++ b/rust/cloud-storage/github/src/domain/service/sync/handle_pr.rs
@@ -18,7 +18,7 @@ impl<D: DocumentService, R: GithubSyncRepo, C: GithubSyncClient> GithubSyncServi
) -> Result<(), GithubError> {
let searchable_texts = event.extract_searchable_text();
let combined = searchable_texts.join(" ");
- let task_ids = MacroTaskId::extract_from_text(&combined);
+ let task_ids = self.extract_task_ids_from_text(event, &combined).await;
tracing::trace!(
task_id_count = task_ids.len(),
@@ -99,7 +99,7 @@ impl<D: DocumentService, R: GithubSyncRepo, C: GithubSyncClient> GithubSyncServi
) -> Result<(), GithubError> {
let searchable_texts = event.extract_searchable_text();
let combined = searchable_texts.join(" ");
- let task_ids: Vec<MacroTaskId> = MacroTaskId::extract_from_text(&combined);
+ let task_ids = self.extract_task_ids_from_text(event, &combined).await;
tracing::trace!(
task_id_count = task_ids.len(),
@@ -187,7 +187,9 @@ impl<D: DocumentService, R: GithubSyncRepo, C: GithubSyncClient> GithubSyncServi
// Gather task IDs from PR title/body/branch
let searchable_texts = event.extract_searchable_text();
let combined = searchable_texts.join(" ");
- let mut task_id_set: HashSet<MacroTaskId> = MacroTaskId::extract_from_text(&combined)
+ let mut task_id_set: HashSet<MacroTaskId> = self
+ .extract_task_ids_from_text(event, &combined)
+ .await
.into_iter()
.collect();
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 d3d7c57a06..15da5f6b25 100644
--- a/rust/cloud-storage/github/src/domain/service/sync/mod.rs
+++ b/rust/cloud-storage/github/src/domain/service/sync/mod.rs
@@ -10,7 +10,7 @@ mod handle_pr;
use crate::domain::{
models::{
GithubError, GithubInstallationAccessToken, GithubKey, GithubWebhookEventType, MacroTaskId,
- ValidatedGithubWebhookEvent,
+ TeamTaskReference, ValidatedGithubWebhookEvent,
},
ports::{GithubSyncClient, GithubSyncRepo, GithubSyncService},
};
@@ -18,7 +18,7 @@ use documents::domain::{models::DocumentError, ports::DocumentService};
use entity_access::domain::models::{EditAccessLevel, ViewAccessLevel};
use hmac::{Hmac, Mac};
use sha2::Sha256;
-use std::sync::Arc;
+use std::{collections::HashSet, sync::Arc};
use subtle::ConstantTimeEq;
type HmacSha256 = Hmac<Sha256>;
@@ -132,6 +132,61 @@ impl<D: DocumentService, R: GithubSyncRepo, C: GithubSyncClient> GithubSyncServi
}
}
+ /// Extract both legacy `MACRO-{short_uuid}` IDs and team-scoped
+ /// `{team_slug}-{team_task_id}` references from text.
+ #[tracing::instrument(skip(self, event, text))]
+ async fn extract_task_ids_from_text(
+ &self,
+ event: &ValidatedGithubWebhookEvent,
+ text: &str,
+ ) -> Vec<MacroTaskId> {
+ let mut task_ids = MacroTaskId::extract_from_text(text);
+ let legacy_task_id_count = task_ids.len();
+ let team_task_refs = TeamTaskReference::extract_from_text(text);
+
+ if !team_task_refs.is_empty() {
+ if let Some(installation_id) = event.installation_id() {
+ let installation_id = installation_id.to_string();
+ match self
+ .repo
+ .resolve_team_task_references(&installation_id, &team_task_refs)
+ .await
+ {
+ Ok(mut resolved_team_task_ids) => {
+ tracing::trace!(
+ team_task_ref_count = team_task_refs.len(),
+ resolved_team_task_id_count = resolved_team_task_ids.len(),
+ "resolved team task references from webhook text"
+ );
+ task_ids.append(&mut resolved_team_task_ids);
+ }
+ Err(e) => {
+ tracing::error!(
+ error=?e,
+ team_task_ref_count = team_task_refs.len(),
+ "failed to resolve team task references"
+ );
+ }
+ }
+ } else {
+ tracing::debug!(
+ team_task_ref_count = team_task_refs.len(),
+ "found team task references but webhook payload has no installation id"
+ );
+ }
+ }
+
+ let task_ids = dedupe_task_ids(task_ids);
+ tracing::trace!(
+ legacy_task_id_count,
+ team_task_ref_count = team_task_refs.len(),
+ total_task_id_count = task_ids.len(),
+ task_ids = ?task_ids.iter().map(|t| t.to_task_id_string()).collect::<Vec<_>>(),
+ "extracted task IDs from webhook text"
+ );
+ task_ids
+ }
+
/// Resolve task IDs to documents, returning doc IDs and markdown links
/// for all tasks that are actually task-type documents.
#[tracing::instrument(skip(self, task_ids))]
@@ -369,6 +424,19 @@ impl<D: DocumentService, R: GithubSyncRepo, C: GithubSyncClient> GithubSyncServi
}
}
+fn dedupe_task_ids(task_ids: Vec<MacroTaskId>) -> Vec<MacroTaskId> {
+ let mut seen = HashSet::new();
+ let mut deduped = Vec::new();
+
+ for task_id in task_ids {
+ if seen.insert(task_id.short_uuid.clone()) {
+ deduped.push(task_id);
+ }
+ }
+
+ deduped
+}
+
/// Creates a macro task comment given the document name and id
fn create_macro_task_comment_link(name: &str, id: &str) -> String {
let url = match macro_env::Environment::new_or_prod() {
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 0a322923c7..894b97316f 100644
--- a/rust/cloud-storage/github/src/domain/service/sync/test.rs
+++ b/rust/cloud-storage/github/src/domain/service/sync/test.rs
@@ -3,7 +3,7 @@ use std::sync::{Arc, Mutex};
use crate::domain::{
models::{
- GithubError, GithubInstallationAccessToken, GithubKey, MacroTaskId,
+ GithubError, GithubInstallationAccessToken, GithubKey, MacroTaskId, TeamTaskReference,
ValidatedGithubWebhookEvent,
},
ports::{GithubSyncClient, GithubSyncRepo, GithubSyncService},
@@ -243,6 +243,8 @@ 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 github_user_id -> macro_id for installation event lookups.
github_links: Mutex<HashMap<String, String>>,
/// Maps macro_id -> team_ids for installation event lookups.
@@ -255,6 +257,7 @@ impl StubSyncRepo {
fn new() -> Self {
Self {
tasks: Mutex::new(HashMap::new()),
+ team_task_references: Mutex::new(HashMap::new()),
github_links: Mutex::new(HashMap::new()),
user_teams: Mutex::new(HashMap::new()),
installation_associations: Mutex::new(Vec::new()),
@@ -277,6 +280,24 @@ impl StubSyncRepo {
self
}
+ fn with_team_task_reference(
+ self,
+ installation_id: &str,
+ team_slug: &str,
+ team_task_id: i32,
+ task_id: MacroTaskId,
+ ) -> Self {
+ self.team_task_references.lock().unwrap().insert(
+ (
+ installation_id.to_string(),
+ team_slug.to_ascii_lowercase(),
+ team_task_id,
+ ),
+ task_id,
+ );
+ self
+ }
+
fn installation_associations(&self) -> Vec<(String, Vec<uuid::Uuid>, String)> {
self.installation_associations.lock().unwrap().clone()
}
@@ -329,6 +350,31 @@ impl GithubSyncRepo for StubSyncRepo {
.collect())
}
+ async fn resolve_team_task_references(
+ &self,
+ installation_id: &str,
+ references: &[TeamTaskReference],
+ ) -> Result<Vec<MacroTaskId>, Self::Err> {
+ let team_task_references = self.team_task_references.lock().unwrap();
+ let mut seen = HashSet::new();
+ let mut resolved = Vec::new();
+
+ for reference in references {
+ let key = (
+ installation_id.to_string(),
+ 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());
+ }
+ }
+
+ Ok(resolved)
+ }
+
async fn get_macro_id_by_github_user_id(
&self,
github_user_id: &str,
@@ -525,6 +571,71 @@ async fn pr_with_task_id_in_branch_name() {
assert_eq!(comments[0].pull_number, 7);
}
+#[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 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": "no legacy task ids here",
+ "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());
+
+ let comments = service.client.pr_comments();
+ assert_eq!(comments.len(), 1);
+ assert_eq!(comments[0].pull_number, 7);
+ assert_eq!(
+ comments[0].body,
+ format!("[My Task](https://macro.com/app/task/{KNOWN_TASK_UUID})")
+ );
+}
+
+#[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 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());
+}
+
#[tokio::test]
async fn issue_comment_with_task_id() {
let service = make_sync_service();
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 88d462288c..6f207c8617 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
@@ -8,7 +8,7 @@ use std::collections::HashSet;
use sqlx::PgPool;
use crate::domain::{
- models::{GithubKey, MacroTaskId},
+ models::{GithubKey, MacroTaskId, TeamTaskReference},
ports::GithubSyncRepo,
};
@@ -107,6 +107,53 @@ impl GithubSyncRepo for PgGithubSyncRepo {
.collect())
}
+ #[tracing::instrument(skip(self, references), err)]
+ async fn resolve_team_task_references(
+ &self,
+ installation_id: &str,
+ references: &[TeamTaskReference],
+ ) -> Result<Vec<MacroTaskId>, Self::Err> {
+ if references.is_empty() {
+ return Ok(Vec::new());
+ }
+
+ let team_slugs: Vec<String> = references.iter().map(|r| r.team_slug.clone()).collect();
+ let team_task_ids: Vec<i32> = references.iter().map(|r| r.team_task_id).collect();
+
+ let rows = sqlx::query!(
+ r#"
+ SELECT DISTINCT tt.document_id
+ FROM UNNEST($2::text[], $3::int4[]) AS refs(team_slug, task_num)
+ JOIN github_app_installation_team gait ON gait.id = $1
+ JOIN team t ON t.id = gait.team_id AND LOWER(t.slug) = LOWER(refs.team_slug)
+ JOIN team_task tt ON tt.team_id = t.id AND tt.task_num = refs.task_num
+ "#,
+ installation_id,
+ &team_slugs,
+ &team_task_ids
+ )
+ .fetch_all(&self.pool)
+ .await?;
+
+ 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)),
+ Err(e) => {
+ tracing::warn!(
+ document_id,
+ error=?e,
+ "team task document id is not a UUID"
+ );
+ None
+ }
+ }
+ })
+ .collect())
+ }
+
#[tracing::instrument(skip(self), err)]
async fn get_macro_id_by_github_user_id(
&self,
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 1ec0ec1f87..29381c60b6 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
@@ -170,6 +170,53 @@ async fn test_filter_duplicate_tasks_empty_input(pool: Pool<Postgres>) {
assert!(new_only.is_empty());
}
+// ---------------------------------------------------------------------------
+// resolve_team_task_references
+// ---------------------------------------------------------------------------
+
+#[sqlx::test(
+ migrator = "MACRO_DB_MIGRATIONS",
+ fixtures(path = "../../../fixtures", scripts("github_team_task_test_data"))
+)]
+async fn test_resolve_team_task_references(pool: Pool<Postgres>) {
+ let repo = PgGithubSyncRepo::new(pool);
+
+ let refs = vec![
+ crate::domain::models::TeamTaskReference::new("eng", 123).unwrap(),
+ crate::domain::models::TeamTaskReference::new("platform_api", 7).unwrap(),
+ ];
+
+ let task_ids = 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());
+
+ 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_requires_installation_team(pool: Pool<Postgres>) {
+ let repo = PgGithubSyncRepo::new(pool);
+ let refs = vec![crate::domain::models::TeamTaskReference::new("eng", 123).unwrap()];
+
+ let task_ids = repo
+ .resolve_team_task_references("99999", &refs)
+ .await
+ .unwrap();
+
+ assert!(task_ids.is_empty());
+}
+
#[sqlx::test(
migrator = "MACRO_DB_MIGRATIONS",
fixtures(path = "../../../fixtures", scripts("github_sync_test_data"))