Macro is a unified workspace for teams: email, chat, docs, tasks, agents, calls, and CRM — @-linked together with shared AI memory.
TypeScript agentaiai-agentsall-in-onecrmcrm-systememaillinearmcpmessagingnotesnotionofficerustslackslack-alternativestartupstartup-toolstypescriptworkspace
feat(github): add foreign entity for prs (#3590)
Will Hutchinsonccab601be4fe
diff --git a/rust/cloud-storage/.sqlx/query-51c9b178186c513e2359c6ae0d9eb291f29d3fe5dca1bfa5ae426aad4a086ccd.json b/rust/cloud-storage/.sqlx/query-51c9b178186c513e2359c6ae0d9eb291f29d3fe5dca1bfa5ae426aad4a086ccd.jsonnew file mode 100644index 0000000000..d1507c076c--- /dev/null+++ b/rust/cloud-storage/.sqlx/query-51c9b178186c513e2359c6ae0d9eb291f29d3fe5dca1bfa5ae426aad4a086ccd.json@@ -0,0 +1,28 @@+{+ "db_name": "PostgreSQL",+ "query": "\n SELECT source_id AS \"source_id!\", source_type::text AS \"source_type!\"\n FROM github_app_installation\n WHERE id = $1\n ORDER BY source_type, source_id\n ",+ "describe": {+ "columns": [+ {+ "ordinal": 0,+ "name": "source_id!",+ "type_info": "Text"+ },+ {+ "ordinal": 1,+ "name": "source_type!",+ "type_info": "Text"+ }+ ],+ "parameters": {+ "Left": [+ "Text"+ ]+ },+ "nullable": [+ false,+ null+ ]+ },+ "hash": "51c9b178186c513e2359c6ae0d9eb291f29d3fe5dca1bfa5ae426aad4a086ccd"+}diff --git a/rust/cloud-storage/Cargo.lock b/rust/cloud-storage/Cargo.lockindex 213c465ba5..97c00210c9 100644--- a/rust/cloud-storage/Cargo.lock+++ b/rust/cloud-storage/Cargo.lock@@ -3432,6 +3432,7 @@ dependencies = ["email","entity_access","entity_access_management",+ "foreign_entity","frecency","futures","github",@@ -4798,6 +4799,7 @@ dependencies = ["document_sub_type","documents","entity_access",+ "foreign_entity","fusionauth","hex","hmac 0.12.1",diff --git a/rust/cloud-storage/document_storage_service/Cargo.toml b/rust/cloud-storage/document_storage_service/Cargo.tomlindex 72cb9a0841..10d98dd8fb 100644--- a/rust/cloud-storage/document_storage_service/Cargo.toml+++ b/rust/cloud-storage/document_storage_service/Cargo.toml@@ -56,6 +56,7 @@ dynamodb_client = { path = "../dynamodb_client" }email = { path = "../email", features = ["outbound", "ports"] }entity_access = { path = "../entity_access", features = ["inbound", "schema"] }entity_access_management = { path = "../entity_access_management" }+foreign_entity = { path = "../foreign_entity" }frecency = { path = "../frecency", features = ["postgres"] }futures = { workspace = true }github = { path = "../github", default-features = false, features = [diff --git a/rust/cloud-storage/document_storage_service/src/api/context.rs b/rust/cloud-storage/document_storage_service/src/api/context.rsindex 67e46bf72e..171c260a54 100644--- a/rust/cloud-storage/document_storage_service/src/api/context.rs+++ b/rust/cloud-storage/document_storage_service/src/api/context.rs@@ -49,6 +49,10 @@ use email::{outbound::EmailPgRepo,};use entity_access::{domain::service::EntityAccessServiceImpl, outbound::PgAccessRepository};+use foreign_entity::{+ domain::service::ForeignEntityServiceImpl,+ outbound::pg_foreign_entity_repo::PgForeignEntityRepo,+};use frecency::{domain::services::FrecencyQueryServiceImpl, outbound::postgres::FrecencyPgStorage};use github::domain::service::GithubSyncServiceImpl;use github::outbound::github_sync_client::GithubSyncClientImpl;@@ -258,9 +262,16 @@ pub(crate) type DssCallWebhookState = WebhookRouterState<DssCallService>;/// Type alias for the internal call router state.pub(crate) type DssCallInternalState = InternalCallRouterState<DssCallService>;+/// Type alias for the foreign entity service.+pub(crate) type ForeignEntityServiceType = ForeignEntityServiceImpl<PgForeignEntityRepo>;+/// Type alias for the github sync service.-pub(crate) type GithubSyncServiceType =- GithubSyncServiceImpl<DocumentService, PgGithubSyncRepo, GithubSyncClientImpl>;+pub(crate) type GithubSyncServiceType = GithubSyncServiceImpl<+ DocumentService,+ PgGithubSyncRepo,+ GithubSyncClientImpl,+ ForeignEntityServiceType,+>;/// Type alias for the cal.com webhook service.pub(crate) type CalWebhookServiceType = CalWebhookServiceImpl<AnalyticsClientSink>;diff --git a/rust/cloud-storage/document_storage_service/src/main.rs b/rust/cloud-storage/document_storage_service/src/main.rsindex a90621bdcd..41f4c64c08 100644--- a/rust/cloud-storage/document_storage_service/src/main.rs+++ b/rust/cloud-storage/document_storage_service/src/main.rs@@ -59,6 +59,10 @@ use email::{domain::{ports::ReadonlyEmailPreviewAdapter, service::EmailServiceImpl},outbound::EmailPgRepo,};+use foreign_entity::{+ domain::service::ForeignEntityServiceImpl,+ outbound::pg_foreign_entity_repo::PgForeignEntityRepo,+};use frecency::{domain::services::FrecencyQueryServiceImpl, outbound::postgres::FrecencyPgStorage};use github::domain::service::{GithubSyncConfig, GithubSyncServiceImpl};use github::outbound::github_sync_client::GithubSyncClientImpl;@@ -390,6 +394,10 @@ async fn main() -> anyhow::Result<()> {.get_maybe_secret_value(env, GithubSyncAppPemSecretKey::new()?).await?;+ let foreign_entity_service = Arc::new(ForeignEntityServiceImpl::new(PgForeignEntityRepo::new(+ db.clone(),+ )));+let github_sync_service_impl = GithubSyncServiceImpl::new(GithubSyncConfig {webhook_secret: github_webhook_secret.as_ref().to_string(),@@ -398,6 +406,7 @@ async fn main() -> anyhow::Result<()> {sync_app_client_id: config.vars.github_sync_app_client_id.to_string(),},document_service.clone(),+ foreign_entity_service,PgGithubSyncRepo::new(db.clone()),GithubSyncClientImpl::default(),);diff --git a/rust/cloud-storage/github/Cargo.toml b/rust/cloud-storage/github/Cargo.tomlindex 2da6daa483..c70276bbcc 100644--- a/rust/cloud-storage/github/Cargo.toml+++ b/rust/cloud-storage/github/Cargo.toml@@ -19,7 +19,13 @@ outbound = ["ports",]ports = []-sync = ["dep:documents", "dep:entity_access", "dep:reqwest", "ports"]+sync = [+ "dep:documents",+ "dep:entity_access",+ "dep:foreign_entity",+ "dep:reqwest",+ "ports",+][dependencies]anyhow = { workspace = true }@@ -30,6 +36,9 @@ documents = { path = "../documents", default-features = false, features = [entity_access = { path = "../entity_access", default-features = false, features = ["ports",], optional = true }+foreign_entity = { path = "../foreign_entity", default-features = false, features = [+ "ports",+], optional = true }hex = { workspace = true }hmac = { workspace = true }jsonwebtoken = { workspace = true }diff --git a/rust/cloud-storage/github/src/domain/ports/sync.rs b/rust/cloud-storage/github/src/domain/ports/sync.rsindex 90a586461c..d777a65d4e 100644--- a/rust/cloud-storage/github/src/domain/ports/sync.rs+++ b/rust/cloud-storage/github/src/domain/ports/sync.rs@@ -61,6 +61,12 @@ pub trait GithubSyncRepo: Send + Sync + 'static {macro_id: &str,) -> impl Future<Output = Result<Vec<uuid::Uuid>, Self::Err>> + Send;+ /// Returns the Macro sources associated with a GitHub App installation.+ fn get_installation_sources(+ &self,+ installation_id: &str,+ ) -> impl Future<Output = Result<Vec<GithubAppInstallationSource>, Self::Err>> + Send;+/// Upserts associations between a GitHub App installation and its sources./// Ignores conflicts (idempotent).fn upsert_installation_sources(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.rsindex a632096923..ca06c0d425 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@@ -5,10 +5,13 @@ use crate::domain::{ports::{GithubSyncClient, GithubSyncRepo},};use documents::domain::ports::DocumentService;+use foreign_entity::domain::ports::ForeignEntityService;use super::GithubSyncServiceImpl;-impl<D: DocumentService, R: GithubSyncRepo, C: GithubSyncClient> GithubSyncServiceImpl<D, R, C> {+impl<D: DocumentService, R: GithubSyncRepo, C: GithubSyncClient, F: ForeignEntityService>+ GithubSyncServiceImpl<D, R, C, F>+{/// Handle `issue_comment`, `pull_request_review`, and/// `pull_request_review_comment` events.///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.rsindex 02a9be95ce..c42c4c7353 100644--- a/rust/cloud-storage/github/src/domain/service/sync/handle_installation.rs+++ b/rust/cloud-storage/github/src/domain/service/sync/handle_installation.rs@@ -5,10 +5,13 @@ use crate::domain::{ports::{GithubSyncClient, GithubSyncRepo},};use documents::domain::ports::DocumentService;+use foreign_entity::domain::ports::ForeignEntityService;use super::GithubSyncServiceImpl;-impl<D: DocumentService, R: GithubSyncRepo, C: GithubSyncClient> GithubSyncServiceImpl<D, R, C> {+impl<D: DocumentService, R: GithubSyncRepo, C: GithubSyncClient, F: ForeignEntityService>+ GithubSyncServiceImpl<D, R, C, F>+{/// Handle `installation` events with action `created`.////// Associates the GitHub App installation with the installer's team or user source.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.rsindex 6062ea7bde..e45542e0dc 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@@ -5,11 +5,14 @@ use crate::domain::{ports::{GithubSyncClient, GithubSyncRepo},};use documents::domain::ports::DocumentService;+use foreign_entity::domain::ports::ForeignEntityService;use std::collections::HashSet;use super::GithubSyncServiceImpl;-impl<D: DocumentService, R: GithubSyncRepo, C: GithubSyncClient> GithubSyncServiceImpl<D, R, C> {+impl<D: DocumentService, R: GithubSyncRepo, C: GithubSyncClient, F: ForeignEntityService>+ GithubSyncServiceImpl<D, R, C, F>+{/// Handle `pull_request` events with action `opened` or `reopened`.#[tracing::instrument(skip(self, event), err)]pub(crate) async fn handle_pr_open(diff --git a/rust/cloud-storage/github/src/domain/service/sync/mod.rs b/rust/cloud-storage/github/src/domain/service/sync/mod.rsindex 15da5f6b25..a8dd2ac27d 100644--- a/rust/cloud-storage/github/src/domain/service/sync/mod.rs+++ b/rust/cloud-storage/github/src/domain/service/sync/mod.rs@@ -9,13 +9,18 @@ mod handle_pr;use crate::domain::{models::{- GithubError, GithubInstallationAccessToken, GithubKey, GithubWebhookEventType, MacroTaskId,- TeamTaskReference, ValidatedGithubWebhookEvent,+ EnrichedGithubPullRequest, GithubError, GithubInstallationAccessToken, GithubKey,+ GithubPullRequestStatus, GithubWebhookEventType, MacroTaskId, TeamTaskReference,+ ValidatedGithubWebhookEvent,},ports::{GithubSyncClient, GithubSyncRepo, GithubSyncService},};use documents::domain::{models::DocumentError, ports::DocumentService};use entity_access::domain::models::{EditAccessLevel, ViewAccessLevel};+use foreign_entity::domain::{+ models::{CreateForeignEntity, PatchForeignEntity},+ ports::ForeignEntityService,+};use hmac::{Hmac, Mac};use sha2::Sha256;use std::{collections::HashSet, sync::Arc};@@ -23,6 +28,8 @@ use subtle::ConstantTimeEq;type HmacSha256 = Hmac<Sha256>;+const GITHUB_PULL_REQUEST_FOREIGN_ENTITY_SOURCE: &str = "github_pull_request";+/// Github sync config#[derive(Debug)]pub struct GithubSyncConfig {@@ -37,19 +44,34 @@ pub struct GithubSyncConfig {}/// The concrete github sync service implementation.-pub struct GithubSyncServiceImpl<D: DocumentService, R: GithubSyncRepo, C: GithubSyncClient> {+pub struct GithubSyncServiceImpl<+ D: DocumentService,+ R: GithubSyncRepo,+ C: GithubSyncClient,+ F: ForeignEntityService,+> {config: GithubSyncConfig,document_service: Arc<D>,+ foreign_entity_service: Arc<F>,repo: R,pub(crate) client: C,}-impl<D: DocumentService, R: GithubSyncRepo, C: GithubSyncClient> GithubSyncServiceImpl<D, R, C> {+impl<D: DocumentService, R: GithubSyncRepo, C: GithubSyncClient, F: ForeignEntityService>+ GithubSyncServiceImpl<D, R, C, F>+{/// Create a new github sync service.- pub fn new(config: GithubSyncConfig, document_service: Arc<D>, repo: R, client: C) -> Self {+ pub fn new(+ config: GithubSyncConfig,+ document_service: Arc<D>,+ foreign_entity_service: Arc<F>,+ repo: R,+ client: C,+ ) -> Self {Self {config,document_service,+ foreign_entity_service,repo,client,}@@ -74,7 +96,9 @@ struct ResolvedTasks {validated_task_ids: Vec<MacroTaskId>,}-impl<D: DocumentService, R: GithubSyncRepo, C: GithubSyncClient> GithubSyncServiceImpl<D, R, C> {+impl<D: DocumentService, R: GithubSyncRepo, C: GithubSyncClient, F: ForeignEntityService>+ GithubSyncServiceImpl<D, R, C, F>+{/// Extract PR metadata and generate an installation access token./// Returns `None` if any required field is missing or token generation fails.#[tracing::instrument(skip(self, event))]@@ -132,6 +156,186 @@ impl<D: DocumentService, R: GithubSyncRepo, C: GithubSyncClient> GithubSyncServi}}+ /// Build pull request metadata for storage as a foreign entity.+ fn enriched_pull_request_from_event(+ event: &ValidatedGithubWebhookEvent,+ ) -> Option<EnrichedGithubPullRequest> {+ let (owner, repo, number) =+ match (event.repo_owner(), event.repo_name(), event.pull_number()) {+ (Some(owner), Some(repo), Some(number)) => (owner, repo, number),+ _ => return None,+ };++ let github_key = GithubKey::new(owner, repo, number);+ let pull_request = event.payload.get("pull_request");+ let url = pull_request+ .and_then(|pr| pr.get("html_url"))+ .and_then(|value| value.as_str())+ .map(str::to_string)+ .unwrap_or_else(|| format!("https://github.com/{owner}/{repo}/pull/{number}"));++ Some(EnrichedGithubPullRequest {+ github_key: github_key.as_ref().to_string(),+ owner: owner.to_string(),+ repo: repo.to_string(),+ number,+ url,+ display_name: format!("{owner}/{repo}#{number}"),+ name: pull_request+ .and_then(|pr| pr.get("title"))+ .and_then(|value| value.as_str())+ .map(str::to_string),+ status: Some(Self::pull_request_status_from_event(event)),+ additions: pull_request+ .and_then(|pr| pr.get("additions"))+ .and_then(|value| value.as_u64()),+ deletions: pull_request+ .and_then(|pr| pr.get("deletions"))+ .and_then(|value| value.as_u64()),+ })+ }++ /// Derive a normalized pull request status from the webhook payload.+ fn pull_request_status_from_event(+ event: &ValidatedGithubWebhookEvent,+ ) -> GithubPullRequestStatus {+ let pull_request = event.payload.get("pull_request");+ let has_merged_at = pull_request+ .and_then(|pr| pr.get("merged_at"))+ .and_then(|value| value.as_str())+ .is_some_and(|merged_at| !merged_at.is_empty());++ if event.is_merged() || has_merged_at {+ return GithubPullRequestStatus::Merged;+ }++ let state = pull_request+ .and_then(|pr| pr.get("state"))+ .and_then(|value| value.as_str());++ if state == Some("closed") || event.action() == Some("closed") {+ return GithubPullRequestStatus::Closed;+ }++ GithubPullRequestStatus::Open+ }++ /// Create or refresh foreign entity rows for a pull request, scoped to the+ /// Macro source (team or user) associated with the GitHub App installation.+ #[tracing::instrument(skip(self, event))]+ async fn upsert_pull_request_foreign_entities(&self, event: &ValidatedGithubWebhookEvent) {+ let Some(installation_id) = event.installation_id() else {+ tracing::warn!("missing installation id, cannot upsert PR foreign entity");+ return;+ };+ let installation_id = installation_id.to_string();++ let stored_for_sources = match self.repo.get_installation_sources(&installation_id).await {+ Ok(sources) => sources,+ Err(error) => {+ tracing::error!(+ error=?error,+ installation_id,+ "failed to fetch GitHub App installation sources for PR foreign entity"+ );+ return;+ }+ };++ if stored_for_sources.is_empty() {+ tracing::trace!(+ installation_id,+ "no GitHub App installation sources found for PR foreign entity upsert"+ );+ return;+ }++ let Some(pull_request) = Self::enriched_pull_request_from_event(event) else {+ tracing::warn!("missing PR metadata, cannot upsert foreign entity");+ return;+ };++ let metadata = match serde_json::to_value(&pull_request) {+ Ok(metadata) => metadata,+ Err(error) => {+ tracing::error!(error=?error, "failed to serialize PR foreign entity metadata");+ return;+ }+ };++ let existing = match self+ .foreign_entity_service+ .get_foreign_entities_by_foreign_entity_id(+ &pull_request.github_key,+ Some(GITHUB_PULL_REQUEST_FOREIGN_ENTITY_SOURCE),+ )+ .await+ {+ Ok(existing) => existing,+ Err(error) => {+ tracing::error!(error=?error, "failed to fetch existing PR foreign entities");+ return;+ }+ };++ let mut seen_sources = HashSet::new();+ for source in stored_for_sources {+ let stored_for_id = source.source_id();+ let stored_for_auth_entity = source.source_type().to_string();+ if !seen_sources.insert((stored_for_id.clone(), stored_for_auth_entity.clone())) {+ continue;+ }++ let existing_entity = existing.iter().find(|entity| {+ entity.stored_for_id.as_str() == stored_for_id.as_str()+ && entity.stored_for_auth_entity.as_str() == stored_for_auth_entity.as_str()+ });++ if let Some(entity) = existing_entity {+ self.foreign_entity_service+ .patch_foreign_entity(+ entity.id,+ PatchForeignEntity {+ metadata: Some(metadata.clone()),+ ..PatchForeignEntity::default()+ },+ )+ .await+ .inspect_err(|error| {+ tracing::error!(+ error=?error,+ foreign_entity_id=%pull_request.github_key,+ stored_for_id=%stored_for_id,+ stored_for_auth_entity=%stored_for_auth_entity,+ "failed to patch PR foreign entity"+ );+ })+ .ok();+ continue;+ }++ self.foreign_entity_service+ .create_foreign_entity(CreateForeignEntity {+ foreign_entity_id: pull_request.github_key.clone(),+ foreign_entity_source: GITHUB_PULL_REQUEST_FOREIGN_ENTITY_SOURCE.to_string(),+ metadata: metadata.clone(),+ stored_for_id: stored_for_id.clone(),+ stored_for_auth_entity: stored_for_auth_entity.clone(),+ })+ .await+ .inspect_err(|error| {+ tracing::error!(+ error=?error,+ foreign_entity_id=%pull_request.github_key,+ stored_for_id=%stored_for_id,+ stored_for_auth_entity=%stored_for_auth_entity,+ "failed to create PR foreign entity"+ );+ })+ .ok();+ }+ }+/// Extract both legacy `MACRO-{short_uuid}` IDs and team-scoped/// `{team_slug}-{team_task_id}` references from text.#[tracing::instrument(skip(self, event, text))]@@ -325,8 +529,8 @@ impl<D: DocumentService, R: GithubSyncRepo, C: GithubSyncClient> GithubSyncServi}}-impl<D: DocumentService, R: GithubSyncRepo, C: GithubSyncClient> GithubSyncService- for GithubSyncServiceImpl<D, R, C>+impl<D: DocumentService, R: GithubSyncRepo, C: GithubSyncClient, F: ForeignEntityService>+ GithubSyncService for GithubSyncServiceImpl<D, R, C, F>{#[tracing::instrument(skip(self, body), err)]async fn validate_webhook_event(@@ -369,15 +573,20 @@ impl<D: DocumentService, R: GithubSyncRepo, C: GithubSyncClient> GithubSyncServitracing::debug!(event_type=%name, "skipping unknown event type");Ok(())}- GithubWebhookEventType::PullRequest => match action {- Some("opened" | "reopened") => self.handle_pr_open(webhook_event).await,- Some("edited") => self.handle_pr_edit(webhook_event).await,- Some("closed") => self.handle_pr_close(webhook_event).await,- _ => {- tracing::debug!(action, "skipping unhandled pull_request action");- Ok(())+ GithubWebhookEventType::PullRequest => {+ self.upsert_pull_request_foreign_entities(webhook_event)+ .await;++ match action {+ Some("opened" | "reopened") => self.handle_pr_open(webhook_event).await,+ Some("edited") => self.handle_pr_edit(webhook_event).await,+ Some("closed") => self.handle_pr_close(webhook_event).await,+ _ => {+ tracing::debug!(action, "skipping unhandled pull_request action");+ Ok(())+ }}- },+ }GithubWebhookEventType::IssueComment| GithubWebhookEventType::PullRequestReview| GithubWebhookEventType::PullRequestReviewComment => {diff --git a/rust/cloud-storage/github/src/domain/service/sync/test.rs b/rust/cloud-storage/github/src/domain/service/sync/test.rsindex 786b19f61e..f01c3bb572 100644--- a/rust/cloud-storage/github/src/domain/service/sync/test.rs+++ b/rust/cloud-storage/github/src/domain/service/sync/test.rs@@ -3,8 +3,9 @@ use std::sync::{Arc, Mutex};use crate::domain::{models::{- GithubAppInstallationSource, GithubError, GithubInstallationAccessToken, GithubKey,- MacroTaskId, TeamTaskReference, ValidatedGithubWebhookEvent,+ EnrichedGithubPullRequest, GithubAppInstallationSource, GithubError,+ GithubInstallationAccessToken, GithubKey, GithubPullRequestStatus, MacroTaskId,+ TeamTaskReference, ValidatedGithubWebhookEvent,},ports::{GithubSyncClient, GithubSyncRepo, GithubSyncService},};@@ -22,6 +23,10 @@ use documents::domain::{use entity_access::domain::models::{EditAccessLevel, EntityAccessReceipt, OwnerAccessLevel, ViewAccessLevel,};+use foreign_entity::domain::{+ models::{CreateForeignEntity, ForeignEntity, ForeignEntityError, PatchForeignEntity},+ ports::ForeignEntityService,+};use macro_user_id::user_id::MacroUserIdStr;use model::document::{DocumentBasic, DocumentMetadata};use model_entity::Entity;@@ -256,6 +261,8 @@ struct StubSyncRepo {github_links: Mutex<HashMap<String, String>>,/// Maps macro_id -> team_ids for installation event lookups.user_teams: Mutex<HashMap<String, Vec<uuid::Uuid>>>,+ /// Current github_app_installation source rows keyed by installation id.+ installation_source_rows: Mutex<HashMap<String, HashSet<GithubAppInstallationSource>>>,/// Recorded installation source upserts: (installation_id, sources).installation_sources: Mutex<Vec<(String, Vec<GithubAppInstallationSource>)>>,}@@ -267,6 +274,7 @@ impl StubSyncRepo {team_task_references: Mutex::new(HashMap::new()),github_links: Mutex::new(HashMap::new()),user_teams: Mutex::new(HashMap::new()),+ installation_source_rows: Mutex::new(HashMap::new()),installation_sources: Mutex::new(Vec::new()),}}@@ -305,6 +313,19 @@ impl StubSyncRepo {self}+ fn with_installation_sources(+ self,+ installation_id: &str,+ sources: Vec<GithubAppInstallationSource>,+ ) -> Self {+ {+ let mut rows = self.installation_source_rows.lock().unwrap();+ let row_sources = rows.entry(installation_id.to_string()).or_default();+ row_sources.extend(sources);+ }+ self+ }+fn installation_sources(&self) -> Vec<(String, Vec<GithubAppInstallationSource>)> {self.installation_sources.lock().unwrap().clone()}@@ -404,11 +425,29 @@ impl GithubSyncRepo for StubSyncRepo {.unwrap_or_default())}+ async fn get_installation_sources(+ &self,+ installation_id: &str,+ ) -> Result<Vec<GithubAppInstallationSource>, Self::Err> {+ Ok(self+ .installation_source_rows+ .lock()+ .unwrap()+ .get(installation_id)+ .map(|sources| sources.iter().cloned().collect())+ .unwrap_or_default())+ }+async fn upsert_installation_sources(&self,installation_id: &str,sources: &[GithubAppInstallationSource],) -> Result<(), Self::Err> {+ {+ let mut rows = self.installation_source_rows.lock().unwrap();+ let row_sources = rows.entry(installation_id.to_string()).or_default();+ row_sources.extend(sources.iter().cloned());+ }self.installation_sources.lock().unwrap()@@ -472,14 +511,150 @@ impl GithubSyncClient for StubSyncClient {}}-fn make_sync_service() -> GithubSyncServiceImpl<StubDocumentService, StubSyncRepo, StubSyncClient> {+struct StubForeignEntityService {+ foreign_entities: Mutex<Vec<ForeignEntity>>,+ create_calls: Mutex<Vec<CreateForeignEntity>>,+ patch_calls: Mutex<Vec<(uuid::Uuid, PatchForeignEntity)>>,+}++impl StubForeignEntityService {+ fn new() -> Self {+ Self {+ foreign_entities: Mutex::new(Vec::new()),+ create_calls: Mutex::new(Vec::new()),+ patch_calls: Mutex::new(Vec::new()),+ }+ }++ fn foreign_entities(&self) -> Vec<ForeignEntity> {+ self.foreign_entities.lock().unwrap().clone()+ }++ fn create_calls(&self) -> Vec<CreateForeignEntity> {+ self.create_calls.lock().unwrap().clone()+ }++ fn patch_calls(&self) -> Vec<(uuid::Uuid, PatchForeignEntity)> {+ self.patch_calls.lock().unwrap().clone()+ }+}++impl ForeignEntityService for StubForeignEntityService {+ async fn get_foreign_entity_by_id(+ &self,+ id: uuid::Uuid,+ ) -> Result<ForeignEntity, ForeignEntityError> {+ self.foreign_entities+ .lock()+ .unwrap()+ .iter()+ .find(|entity| entity.id == id)+ .cloned()+ .ok_or(ForeignEntityError::NotFound(id))+ }++ async fn get_foreign_entities_by_foreign_entity_id(+ &self,+ foreign_entity_id: &str,+ foreign_entity_source: Option<&str>,+ ) -> Result<Vec<ForeignEntity>, ForeignEntityError> {+ Ok(self+ .foreign_entities+ .lock()+ .unwrap()+ .iter()+ .filter(|entity| entity.foreign_entity_id == foreign_entity_id)+ .filter(|entity| {+ foreign_entity_source+ .map(|source| entity.foreign_entity_source == source)+ .unwrap_or(true)+ })+ .cloned()+ .collect())+ }++ async fn create_foreign_entity(+ &self,+ create: CreateForeignEntity,+ ) -> Result<ForeignEntity, ForeignEntityError> {+ let now = chrono::Utc::now();+ let entity = ForeignEntity {+ id: uuid::Uuid::new_v4(),+ foreign_entity_id: create.foreign_entity_id.clone(),+ foreign_entity_source: create.foreign_entity_source.clone(),+ metadata: create.metadata.clone(),+ stored_for_id: create.stored_for_id.clone(),+ stored_for_auth_entity: create.stored_for_auth_entity.clone(),+ created_at: now,+ updated_at: now,+ };++ self.create_calls.lock().unwrap().push(create);+ self.foreign_entities.lock().unwrap().push(entity.clone());+ Ok(entity)+ }++ async fn delete_foreign_entity(&self, id: uuid::Uuid) -> Result<(), ForeignEntityError> {+ let mut foreign_entities = self.foreign_entities.lock().unwrap();+ let original_len = foreign_entities.len();+ foreign_entities.retain(|entity| entity.id != id);++ if foreign_entities.len() == original_len {+ return Err(ForeignEntityError::NotFound(id));+ }++ Ok(())+ }++ async fn patch_foreign_entity(+ &self,+ id: uuid::Uuid,+ patch: PatchForeignEntity,+ ) -> Result<ForeignEntity, ForeignEntityError> {+ self.patch_calls.lock().unwrap().push((id, patch.clone()));++ let mut foreign_entities = self.foreign_entities.lock().unwrap();+ let Some(entity) = foreign_entities.iter_mut().find(|entity| entity.id == id) else {+ return Err(ForeignEntityError::NotFound(id));+ };++ if let Some(foreign_entity_id) = patch.foreign_entity_id {+ entity.foreign_entity_id = foreign_entity_id;+ }+ if let Some(foreign_entity_source) = patch.foreign_entity_source {+ entity.foreign_entity_source = foreign_entity_source;+ }+ if let Some(metadata) = patch.metadata {+ entity.metadata = metadata;+ }+ if let Some(stored_for_id) = patch.stored_for_id {+ entity.stored_for_id = stored_for_id;+ }+ if let Some(stored_for_auth_entity) = patch.stored_for_auth_entity {+ entity.stored_for_auth_entity = stored_for_auth_entity;+ }+ entity.updated_at = chrono::Utc::now();++ Ok(entity.clone())+ }+}++type TestGithubSyncService = GithubSyncServiceImpl<+ StubDocumentService,+ StubSyncRepo,+ StubSyncClient,+ StubForeignEntityService,+>;+type TestServiceWithForeignEntityService = (TestGithubSyncService, Arc<StubForeignEntityService>);++fn make_sync_service() -> TestGithubSyncService {make_sync_service_with_doc_service().0}-fn make_sync_service_with_repo(- repo: StubSyncRepo,-) -> GithubSyncServiceImpl<StubDocumentService, StubSyncRepo, StubSyncClient> {+fn make_sync_service_with_repo(repo: StubSyncRepo) -> TestGithubSyncService {let doc_service = Arc::new(StubDocumentService::new());+ let foreign_entity_service = Arc::new(StubForeignEntityService::new());+GithubSyncServiceImpl::new(GithubSyncConfig {webhook_secret: "test-webhook-secret".to_string(),@@ -488,16 +663,16 @@ fn make_sync_service_with_repo(sync_app_client_id: "test-sync-app-client-id".to_string(),},doc_service,+ foreign_entity_service,repo,StubSyncClient::new(),)}-fn make_sync_service_with_doc_service() -> (- GithubSyncServiceImpl<StubDocumentService, StubSyncRepo, StubSyncClient>,- Arc<StubDocumentService>,-) {+fn make_sync_service_with_doc_service() -> (TestGithubSyncService, Arc<StubDocumentService>) {let doc_service = Arc::new(StubDocumentService::new());+ let foreign_entity_service = Arc::new(StubForeignEntityService::new());+let service = GithubSyncServiceImpl::new(GithubSyncConfig {webhook_secret: "test-webhook-secret".to_string(),@@ -506,12 +681,47 @@ fn make_sync_service_with_doc_service() -> (sync_app_client_id: "test-sync-app-client-id".to_string(),},doc_service.clone(),+ foreign_entity_service,StubSyncRepo::new(),StubSyncClient::new(),);(service, doc_service)}+fn make_sync_service_with_foreign_entity_service() -> TestServiceWithForeignEntityService {+ let repo = StubSyncRepo::new().with_installation_sources(+ "12345",+ vec![GithubAppInstallationSource::Team(+ "dddddddd-dddd-dddd-dddd-dddddddddddd".parse().unwrap(),+ )],+ );+ let service = make_sync_service_with_repo(repo);+ let foreign_entity_service = service.foreign_entity_service.clone();++ (service, foreign_entity_service)+}++fn expected_pull_request_metadata(+ title: &str,+ status: GithubPullRequestStatus,+ additions: Option<u64>,+ deletions: Option<u64>,+) -> serde_json::Value {+ serde_json::to_value(EnrichedGithubPullRequest {+ github_key: "my-org/my-repo/pull/42".to_string(),+ owner: "my-org".to_string(),+ repo: "my-repo".to_string(),+ number: 42,+ url: "https://github.com/my-org/my-repo/pull/42".to_string(),+ display_name: "my-org/my-repo#42".to_string(),+ name: Some(title.to_string()),+ status: Some(status),+ additions,+ deletions,+ })+ .unwrap()+}+#[tokio::test]async fn pr_with_task_id_in_title() {let service = make_sync_service();@@ -1211,6 +1421,336 @@ async fn pr_merged_updates_status_even_when_already_tracked() {assert_eq!(status_calls[1].status, "Completed");}+// ---------------------------------------------------------------------------+// PR foreign entity upserts+// ---------------------------------------------------------------------------++#[tokio::test]+async fn pr_opened_upserts_foreign_entity_for_installation_source() {+ let (service, foreign_entity_service) = make_sync_service_with_foreign_entity_service();+ let event = ValidatedGithubWebhookEvent::new(+ "pull_request".to_string(),+ serde_json::json!({+ "action": "opened",+ "pull_request": {+ "number": 42,+ "title": "fixes MACRO-2BuyvtY3aeEvHx4uG8iD51",+ "body": null,+ "head": { "ref": "feature/some-branch" },+ "state": "open",+ "merged": false,+ "additions": 10,+ "deletions": 2+ },+ "repository": {+ "name": "my-repo",+ "owner": { "login": "my-org" }+ },+ "installation": { "id": 12345 }+ }),+ );++ service.process_webhook_event(&event).await.unwrap();++ let foreign_entities = foreign_entity_service.foreign_entities();+ assert_eq!(foreign_entities.len(), 1);++ let foreign_entity = &foreign_entities[0];+ assert_eq!(foreign_entity.foreign_entity_id, "my-org/my-repo/pull/42");+ assert_eq!(+ foreign_entity.foreign_entity_source,+ GITHUB_PULL_REQUEST_FOREIGN_ENTITY_SOURCE+ );+ assert_eq!(+ foreign_entity.stored_for_id,+ "dddddddd-dddd-dddd-dddd-dddddddddddd"+ );+ assert_eq!(foreign_entity.stored_for_auth_entity, "team");+ assert_eq!(+ foreign_entity.metadata,+ expected_pull_request_metadata(+ "fixes MACRO-2BuyvtY3aeEvHx4uG8iD51",+ GithubPullRequestStatus::Open,+ Some(10),+ Some(2),+ )+ );+ assert_eq!(foreign_entity_service.create_calls().len(), 1);+ assert!(foreign_entity_service.patch_calls().is_empty());+}++#[tokio::test]+async fn pr_opened_upserts_foreign_entity_for_user_installation_source() {+ let repo = StubSyncRepo::new().with_installation_sources(+ "77777",+ vec![GithubAppInstallationSource::User(+ "macro|[email protected]".to_string(),+ )],+ );+ let service = make_sync_service_with_repo(repo);+ let foreign_entity_service = service.foreign_entity_service.clone();+ let event = ValidatedGithubWebhookEvent::new(+ "pull_request".to_string(),+ serde_json::json!({+ "action": "opened",+ "pull_request": {+ "number": 42,+ "title": "fixes MACRO-2BuyvtY3aeEvHx4uG8iD51",+ "body": null,+ "head": { "ref": "feature/some-branch" },+ "state": "open",+ "merged": false,+ "additions": 10,+ "deletions": 2+ },+ "repository": {+ "name": "my-repo",+ "owner": { "login": "my-org" }+ },+ "installation": { "id": 77777 }+ }),+ );++ service.process_webhook_event(&event).await.unwrap();++ let foreign_entities = foreign_entity_service.foreign_entities();+ assert_eq!(foreign_entities.len(), 1);+ assert_eq!(foreign_entities[0].stored_for_id, "macro|[email protected]");+ assert_eq!(foreign_entities[0].stored_for_auth_entity, "user");+}++#[tokio::test]+async fn pr_edit_patches_existing_foreign_entity_metadata() {+ let (service, foreign_entity_service) = make_sync_service_with_foreign_entity_service();+ let opened_event = ValidatedGithubWebhookEvent::new(+ "pull_request".to_string(),+ serde_json::json!({+ "action": "opened",+ "pull_request": {+ "number": 42,+ "title": "fixes MACRO-2BuyvtY3aeEvHx4uG8iD51",+ "body": null,+ "head": { "ref": "feature/some-branch" },+ "state": "open",+ "merged": false,+ "additions": 10,+ "deletions": 2+ },+ "repository": {+ "name": "my-repo",+ "owner": { "login": "my-org" }+ },+ "installation": { "id": 12345 }+ }),+ );+ service.process_webhook_event(&opened_event).await.unwrap();++ let edited_event = ValidatedGithubWebhookEvent::new(+ "pull_request".to_string(),+ serde_json::json!({+ "action": "edited",+ "pull_request": {+ "number": 42,+ "title": "fixes MACRO-2BuyvtY3aeEvHx4uG8iD51 with new title",+ "body": null,+ "head": { "ref": "feature/some-branch" },+ "state": "open",+ "merged": false,+ "additions": 25,+ "deletions": 7+ },+ "repository": {+ "name": "my-repo",+ "owner": { "login": "my-org" }+ },+ "installation": { "id": 12345 }+ }),+ );+ service.process_webhook_event(&edited_event).await.unwrap();++ let expected_metadata = expected_pull_request_metadata(+ "fixes MACRO-2BuyvtY3aeEvHx4uG8iD51 with new title",+ GithubPullRequestStatus::Open,+ Some(25),+ Some(7),+ );+ let foreign_entities = foreign_entity_service.foreign_entities();+ assert_eq!(foreign_entities.len(), 1);+ assert_eq!(foreign_entities[0].metadata, expected_metadata);+ assert_eq!(foreign_entity_service.create_calls().len(), 1);++ let patch_calls = foreign_entity_service.patch_calls();+ assert_eq!(patch_calls.len(), 1);+ assert_eq!(patch_calls[0].1.metadata, Some(expected_metadata));+}++#[tokio::test]+async fn pr_closed_upserts_merged_pull_request_metadata() {+ let (service, foreign_entity_service) = make_sync_service_with_foreign_entity_service();+ let event = ValidatedGithubWebhookEvent::new(+ "pull_request".to_string(),+ serde_json::json!({+ "action": "closed",+ "pull_request": {+ "number": 42,+ "title": "fixes MACRO-2BuyvtY3aeEvHx4uG8iD51",+ "body": null,+ "head": { "ref": "feature/some-branch" },+ "state": "closed",+ "merged": true,+ "merged_at": "2026-05-27T19:00:00Z",+ "additions": 10,+ "deletions": 2+ },+ "repository": {+ "name": "my-repo",+ "owner": { "login": "my-org" }+ },+ "installation": { "id": 12345 }+ }),+ );++ service.process_webhook_event(&event).await.unwrap();++ let foreign_entities = foreign_entity_service.foreign_entities();+ assert_eq!(foreign_entities.len(), 1);+ assert_eq!(+ foreign_entities[0].metadata,+ expected_pull_request_metadata(+ "fixes MACRO-2BuyvtY3aeEvHx4uG8iD51",+ GithubPullRequestStatus::Merged,+ Some(10),+ Some(2),+ )+ );+}++#[tokio::test]+async fn pr_event_without_valid_tasks_still_upserts_foreign_entity() {+ let (service, foreign_entity_service) = make_sync_service_with_foreign_entity_service();+ let unknown_task_id = MacroTaskId::from_uuid(+ &uuid::Uuid::parse_str("11111111-1111-1111-1111-111111111111").unwrap(),+ )+ .to_task_id_string();+ let title = format!("fixes {unknown_task_id}");+ let event = ValidatedGithubWebhookEvent::new(+ "pull_request".to_string(),+ serde_json::json!({+ "action": "opened",+ "pull_request": {+ "number": 42,+ "title": title.clone(),+ "body": null,+ "head": { "ref": "feature/some-branch" },+ "state": "open",+ "merged": false,+ "additions": 10,+ "deletions": 2+ },+ "repository": {+ "name": "my-repo",+ "owner": { "login": "my-org" }+ },+ "installation": { "id": 12345 }+ }),+ );++ service.process_webhook_event(&event).await.unwrap();++ let foreign_entities = foreign_entity_service.foreign_entities();+ assert_eq!(foreign_entities.len(), 1);+ assert_eq!(+ foreign_entities[0].metadata,+ expected_pull_request_metadata(&title, GithubPullRequestStatus::Open, Some(10), Some(2))+ );+ assert_eq!(foreign_entity_service.create_calls().len(), 1);+ assert!(foreign_entity_service.patch_calls().is_empty());+}++#[tokio::test]+async fn pr_event_without_task_ids_still_upserts_foreign_entity() {+ let (service, foreign_entity_service) = make_sync_service_with_foreign_entity_service();+ let event = ValidatedGithubWebhookEvent::new(+ "pull_request".to_string(),+ serde_json::json!({+ "action": "opened",+ "pull_request": {+ "number": 42,+ "title": "just a normal PR",+ "body": null,+ "head": { "ref": "feature/some-branch" },+ "state": "open",+ "merged": false,+ "additions": 10,+ "deletions": 2+ },+ "repository": {+ "name": "my-repo",+ "owner": { "login": "my-org" }+ },+ "installation": { "id": 12345 }+ }),+ );++ service.process_webhook_event(&event).await.unwrap();++ let foreign_entities = foreign_entity_service.foreign_entities();+ assert_eq!(foreign_entities.len(), 1);+ assert_eq!(+ foreign_entities[0].metadata,+ expected_pull_request_metadata(+ "just a normal PR",+ GithubPullRequestStatus::Open,+ Some(10),+ Some(2),+ )+ );+ assert_eq!(foreign_entity_service.create_calls().len(), 1);+ assert!(foreign_entity_service.patch_calls().is_empty());+}++#[tokio::test]+async fn unhandled_pr_action_still_upserts_foreign_entity() {+ let (service, foreign_entity_service) = make_sync_service_with_foreign_entity_service();+ let event = ValidatedGithubWebhookEvent::new(+ "pull_request".to_string(),+ serde_json::json!({+ "action": "synchronize",+ "pull_request": {+ "number": 42,+ "title": "sync branch changes",+ "body": null,+ "head": { "ref": "feature/some-branch" },+ "state": "open",+ "merged": false,+ "additions": 12,+ "deletions": 3+ },+ "repository": {+ "name": "my-repo",+ "owner": { "login": "my-org" }+ },+ "installation": { "id": 12345 }+ }),+ );++ service.process_webhook_event(&event).await.unwrap();++ let foreign_entities = foreign_entity_service.foreign_entities();+ assert_eq!(foreign_entities.len(), 1);+ assert_eq!(+ foreign_entities[0].metadata,+ expected_pull_request_metadata(+ "sync branch changes",+ GithubPullRequestStatus::Open,+ Some(12),+ Some(3),+ )+ );+ assert_eq!(foreign_entity_service.create_calls().len(), 1);+ assert!(foreign_entity_service.patch_calls().is_empty());+}+// ---------------------------------------------------------------------------// New behavioral tests// ---------------------------------------------------------------------------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.rsindex 4056429729..caf7fd5c0b 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@@ -193,6 +193,50 @@ impl GithubSyncRepo for PgGithubSyncRepo {Ok(team_ids)}+ #[tracing::instrument(skip(self), err)]+ async fn get_installation_sources(+ &self,+ installation_id: &str,+ ) -> Result<Vec<GithubAppInstallationSource>, Self::Err> {+ let rows = sqlx::query!(+ r#"+ SELECT source_id AS "source_id!", source_type::text AS "source_type!"+ FROM github_app_installation+ WHERE id = $1+ ORDER BY source_type, source_id+ "#,+ installation_id,+ )+ .fetch_all(&self.pool)+ .await?;++ let mut sources = Vec::new();+ for row in rows {+ let source_id = row.source_id;+ let source_type = row.source_type;+ match source_type.as_str() {+ "team" => match uuid::Uuid::parse_str(&source_id) {+ Ok(team_id) => sources.push(GithubAppInstallationSource::Team(team_id)),+ Err(error) => tracing::warn!(+ installation_id,+ source_id,+ error=?error,+ "github_app_installation team source_id is not a UUID"+ ),+ },+ "user" => sources.push(GithubAppInstallationSource::User(source_id)),+ _ => tracing::warn!(+ installation_id,+ source_id,+ source_type,+ "github_app_installation has unknown source_type"+ ),+ }+ }++ Ok(sources)+ }+#[tracing::instrument(skip(self), err)]async fn upsert_installation_sources(&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.rsindex d39996670e..0c6290750a 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@@ -264,6 +264,41 @@ async fn test_filter_duplicate_tasks_different_key_not_filtered(pool: Pool<Postgassert_eq!(new_only[0].short_uuid, "s61deeZUHehUjkNT8rxB3S");}+// ---------------------------------------------------------------------------+// get_installation_sources+// ---------------------------------------------------------------------------++#[sqlx::test(+ migrator = "MACRO_DB_MIGRATIONS",+ fixtures(path = "../../../fixtures", scripts("github_team_task_test_data"))+)]+async fn test_get_installation_sources_returns_sources(pool: Pool<Postgres>) {+ let repo = PgGithubSyncRepo::new(pool);++ let sources = repo.get_installation_sources("12345").await.unwrap();++ assert_eq!(+ sources,+ vec![+ GithubAppInstallationSource::Team(+ "dddddddd-dddd-dddd-dddd-dddddddddddd".parse().unwrap()+ ),+ GithubAppInstallationSource::Team(+ "eeeeeeee-eeee-eeee-eeee-eeeeeeeeeeee".parse().unwrap()+ ),+ ]+ );+}++#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]+async fn test_get_installation_sources_empty(pool: Pool<Postgres>) {+ let repo = PgGithubSyncRepo::new(pool);++ let sources = repo.get_installation_sources("missing").await.unwrap();++ assert!(sources.is_empty());+}+// ---------------------------------------------------------------------------// get_macro_id_by_github_user_id// ---------------------------------------------------------------------------