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): associate pr with task (#1799)
Will Hutchinsonb0fbae19f7f0
diff --git a/rust/cloud-storage/document_storage_service/src/api/context.rs b/rust/cloud-storage/document_storage_service/src/api/context.rsindex 4f80177727..c152011c8d 100644--- a/rust/cloud-storage/document_storage_service/src/api/context.rs+++ b/rust/cloud-storage/document_storage_service/src/api/context.rs@@ -23,6 +23,7 @@ use entity_access::{domain::service::EntityAccessServiceImpl, outbound::PgAccessuse frecency::{domain::services::FrecencyQueryServiceImpl, outbound::postgres::FrecencyPgStorage};use github::domain::service::GithubSyncServiceImpl;use github::outbound::github_sync_client::GithubSyncClientImpl;+use github::outbound::pg_github_sync_repo::PgGithubSyncRepo;use macro_auth::middleware::decode_jwt::JwtValidationArgs;use macro_env_var::env_var;use macro_sha_count_client::Redis;@@ -144,7 +145,7 @@ pub(crate) type GithubDocumentService =/// Type alias for the github sync service.pub(crate) type GithubSyncServiceType =- GithubSyncServiceImpl<GithubDocumentService, GithubSyncClientImpl>;+ GithubSyncServiceImpl<GithubDocumentService, PgGithubSyncRepo, GithubSyncClientImpl>;#[derive(Clone, FromRef)]pub(crate) struct ApiContext {diff --git a/rust/cloud-storage/document_storage_service/src/main.rs b/rust/cloud-storage/document_storage_service/src/main.rsindex 0d8e956793..d99f528133 100644--- a/rust/cloud-storage/document_storage_service/src/main.rs+++ b/rust/cloud-storage/document_storage_service/src/main.rs@@ -29,6 +29,7 @@ use email::{domain::service::EmailServiceImpl, outbound::EmailPgRepo};use frecency::{domain::services::FrecencyQueryServiceImpl, outbound::postgres::FrecencyPgStorage};use github::domain::service::{GithubSyncConfig, GithubSyncServiceImpl};use github::outbound::github_sync_client::GithubSyncClientImpl;+use github::outbound::pg_github_sync_repo::PgGithubSyncRepo;use macro_auth::middleware::decode_jwt::JwtValidationArgs;use macro_entrypoint::MacroEntrypoint;use macro_middleware::auth::internal_access::InternalApiSecretKey;@@ -336,6 +337,7 @@ async fn main() -> anyhow::Result<()> {sync_app_client_id: config.vars.github_sync_app_client_id.to_string(),},document_service.clone(),+ PgGithubSyncRepo::new(db.clone()),GithubSyncClientImpl::default(),);diff --git a/rust/cloud-storage/github/.sqlx/query-04d60026064c2948d7a528352bb3bb086ba5a39c1dc656aec25f2dd2a4eb249e.json b/rust/cloud-storage/github/.sqlx/query-04d60026064c2948d7a528352bb3bb086ba5a39c1dc656aec25f2dd2a4eb249e.jsonnew file mode 100644index 0000000000..97f5b33bb1--- /dev/null+++ b/rust/cloud-storage/github/.sqlx/query-04d60026064c2948d7a528352bb3bb086ba5a39c1dc656aec25f2dd2a4eb249e.json@@ -0,0 +1,23 @@+{+ "db_name": "PostgreSQL",+ "query": "\n SELECT task_id\n FROM github_pr_tasks\n WHERE github_key = $1\n AND task_id = ANY($2::text[])\n ",+ "describe": {+ "columns": [+ {+ "ordinal": 0,+ "name": "task_id",+ "type_info": "Text"+ }+ ],+ "parameters": {+ "Left": [+ "Text",+ "TextArray"+ ]+ },+ "nullable": [+ false+ ]+ },+ "hash": "04d60026064c2948d7a528352bb3bb086ba5a39c1dc656aec25f2dd2a4eb249e"+}diff --git a/rust/cloud-storage/github/.sqlx/query-76f6793eaead8c4f3a2aa4b02ad573beda79b93bfd874acc1b2059cbe041d8a3.json b/rust/cloud-storage/github/.sqlx/query-76f6793eaead8c4f3a2aa4b02ad573beda79b93bfd874acc1b2059cbe041d8a3.jsonnew file mode 100644index 0000000000..23986dc09f--- /dev/null+++ b/rust/cloud-storage/github/.sqlx/query-76f6793eaead8c4f3a2aa4b02ad573beda79b93bfd874acc1b2059cbe041d8a3.json@@ -0,0 +1,16 @@+{+ "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/rust/cloud-storage/github/.sqlx/query-a386157d6a94f85f1e1c2c0c0cfe39345a04dee3de88fd4cbc8fc6ab8f34da60.json b/rust/cloud-storage/github/.sqlx/query-a386157d6a94f85f1e1c2c0c0cfe39345a04dee3de88fd4cbc8fc6ab8f34da60.jsonnew file mode 100644index 0000000000..2182432ca0--- /dev/null+++ b/rust/cloud-storage/github/.sqlx/query-a386157d6a94f85f1e1c2c0c0cfe39345a04dee3de88fd4cbc8fc6ab8f34da60.json@@ -0,0 +1,22 @@+{+ "db_name": "PostgreSQL",+ "query": "\n SELECT task_id FROM github_pr_tasks\n WHERE github_key = $1\n ",+ "describe": {+ "columns": [+ {+ "ordinal": 0,+ "name": "task_id",+ "type_info": "Text"+ }+ ],+ "parameters": {+ "Left": [+ "Text"+ ]+ },+ "nullable": [+ false+ ]+ },+ "hash": "a386157d6a94f85f1e1c2c0c0cfe39345a04dee3de88fd4cbc8fc6ab8f34da60"+}diff --git a/rust/cloud-storage/github/fixtures/github_sync_test_data.sql b/rust/cloud-storage/github/fixtures/github_sync_test_data.sqlnew file mode 100644index 0000000000..220e8e2e80--- /dev/null+++ b/rust/cloud-storage/github/fixtures/github_sync_test_data.sql@@ -0,0 +1,6 @@+INSERT INTO+ public.github_pr_tasks (id, github_key, task_id)+VALUES+ ('11111111-1111-1111-1111-111111111111'::uuid, 'my-org/my-repo/pull/1', 's61deeZUHehUjkNT8rxB3S'),+ ('22222222-2222-2222-2222-222222222222'::uuid, 'my-org/my-repo/pull/1', 'bMv3eymKvu18qsQyrpt1VH'),+ ('33333333-3333-3333-3333-333333333333'::uuid, 'my-org/other-repo/pull/42', 'xdyzHm2ZVGr6UAkaeBCUxZ');diff --git a/rust/cloud-storage/github/src/domain/models/sync.rs b/rust/cloud-storage/github/src/domain/models/sync.rsindex 6dd2cefc95..bc1cc48b3b 100644--- a/rust/cloud-storage/github/src/domain/models/sync.rs+++ b/rust/cloud-storage/github/src/domain/models/sync.rs@@ -7,6 +7,29 @@ use std::sync::LazyLock;use regex::Regex;use serde::Deserialize;+/// Github key used for tracking tasks+#[derive(Debug, Clone)]+pub struct GithubKey(String);++impl GithubKey {+ /// Create a new github key+ pub fn new(org: &str, repo: &str, pr: u64) -> Self {+ Self(format!("{org}/{repo}/pull/{pr}"))+ }+}++impl fmt::Display for GithubKey {+ fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {+ write!(f, "{}", self.0)+ }+}++impl AsRef<str> for GithubKey {+ fn as_ref(&self) -> &str {+ &self.0+ }+}+/// GitHub App installation access token response#[derive(Debug, Clone, Deserialize)]pub struct GithubInstallationAccessToken {diff --git a/rust/cloud-storage/github/src/domain/models/test.rs b/rust/cloud-storage/github/src/domain/models/test.rsindex dfbcda6163..3dadd814ba 100644--- a/rust/cloud-storage/github/src/domain/models/test.rs+++ b/rust/cloud-storage/github/src/domain/models/test.rs@@ -1,5 +1,12 @@use super::*;+#[test]+fn test_github_key() {+ let key = GithubKey::new("rust-lang", "rust", 12345);+ assert_eq!(key.as_ref(), "rust-lang/rust/pull/12345");+ assert_eq!(key.to_string(), "rust-lang/rust/pull/12345");+}+// ---------------------------------------------------------------------------// MacroTaskId::from_short_uuid// ---------------------------------------------------------------------------diff --git a/rust/cloud-storage/github/src/domain/ports/mod.rs b/rust/cloud-storage/github/src/domain/ports/mod.rsindex cabd48b15f..bf902b40d1 100644--- a/rust/cloud-storage/github/src/domain/ports/mod.rs+++ b/rust/cloud-storage/github/src/domain/ports/mod.rs@@ -6,12 +6,8 @@mod link;#[cfg(feature = "sync")]mod sync;-#[cfg(feature = "sync")]-mod sync_client;#[cfg(feature = "link")]pub use link::*;#[cfg(feature = "sync")]pub use sync::*;-#[cfg(feature = "sync")]-pub use sync_client::*;diff --git a/rust/cloud-storage/github/src/domain/ports/sync.rs b/rust/cloud-storage/github/src/domain/ports/sync.rsindex 06fbb87014..9b1a27ec6e 100644--- a/rust/cloud-storage/github/src/domain/ports/sync.rs+++ b/rust/cloud-storage/github/src/domain/ports/sync.rs@@ -3,9 +3,63 @@use std::future::Future;use crate::domain::models::{- GithubError, GithubInstallationAccessToken, ValidatedGithubWebhookEvent,+ GithubError, GithubInstallationAccessToken, GithubKey, MacroTaskId, ValidatedGithubWebhookEvent,};+/// Repository for accessing github sync data from the database.+///+/// All methods perform database operations — SQL queries are written+/// directly in the outbound adapter implementation.+#[cfg_attr(test, mockall::automock(type Err = anyhow::Error;))]+pub trait GithubSyncRepo: Send + Sync + 'static {+ /// The error type returned by repository operations.+ type Err: Into<anyhow::Error> + Send + std::fmt::Debug;++ /// Provides a list of all task ids for a given github key+ fn get_task_ids(+ &self,+ github_key: GithubKey,+ ) -> impl Future<Output = Result<Vec<MacroTaskId>, Self::Err>> + Send;++ /// Upserts task ids for a given github key+ fn upsert_task_ids(+ &self,+ github_key: GithubKey,+ task_ids: &[MacroTaskId],+ ) -> impl Future<Output = Result<(), Self::Err>> + Send;++ /// Filters out all pre-existing tasks for the github key+ /// Returns only new task ids+ fn filter_duplicate_tasks(+ &self,+ github_key: GithubKey,+ task_ids: &[MacroTaskId],+ ) -> impl Future<Output = Result<Vec<MacroTaskId>, Self::Err>> + Send;+}++/// Client interface for making GitHub sync API calls.+///+/// Abstracts HTTP communication with GitHub's API so the service+/// layer does not need to manage its own HTTP client.+pub trait GithubSyncClient: Send + Sync + 'static {+ /// Generates an installation access token for a given GitHub App installation.+ fn generate_installation_access_token(+ &self,+ jwt: &str,+ installation_id: u64,+ ) -> impl Future<Output = Result<GithubInstallationAccessToken, GithubError>> + Send;++ /// Posts a comment on a GitHub pull request (via the issues API).+ fn create_pr_comment(+ &self,+ access_token: &str,+ owner: &str,+ repo: &str,+ pull_number: u64,+ body: &str,+ ) -> impl Future<Output = Result<(), GithubError>> + Send;+}+/// Service interface for github sync operations (webhooks and sync app).////// Handles webhook validation/processing and sync app installation token generation.diff --git a/rust/cloud-storage/github/src/domain/ports/sync_client.rs b/rust/cloud-storage/github/src/domain/ports/sync_client.rsdeleted file mode 100644index 2011c837bc..0000000000--- a/rust/cloud-storage/github/src/domain/ports/sync_client.rs+++ /dev/null@@ -1,37 +0,0 @@-//! Port definition for the github sync API client.--use std::future::Future;--use crate::domain::models::{GithubError, GithubInstallationAccessToken};--/// Client interface for making GitHub sync API calls.-///-/// Abstracts HTTP communication with GitHub's API so the service-/// layer does not need to manage its own HTTP client.-pub trait GithubSyncClient: Send + Sync + 'static {- /// Generates an installation access token for a given GitHub App installation.- fn generate_installation_access_token(- &self,- jwt: &str,- installation_id: u64,- ) -> impl Future<Output = Result<GithubInstallationAccessToken, GithubError>> + Send;-- /// Posts a comment on a GitHub pull request (via the issues API).- fn create_pr_comment(- &self,- access_token: &str,- owner: &str,- repo: &str,- pull_number: u64,- body: &str,- ) -> impl Future<Output = Result<(), GithubError>> + Send;-- /// Lists comment bodies on a GitHub pull request (via the issues API).- fn list_pr_comments(- &self,- access_token: &str,- owner: &str,- repo: &str,- pull_number: u64,- ) -> impl Future<Output = Result<Vec<String>, GithubError>> + Send;-}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 a99ce77f59..4b1e6575f4 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@@ -2,19 +2,18 @@use crate::domain::{models::{GithubError, MacroTaskId, ValidatedGithubWebhookEvent},- ports::GithubSyncClient,+ ports::{GithubSyncClient, GithubSyncRepo},};use documents::domain::ports::DocumentService;-use std::collections::HashSet;use super::GithubSyncServiceImpl;-impl<D: DocumentService, C: GithubSyncClient> GithubSyncServiceImpl<D, C> {+impl<D: DocumentService, R: GithubSyncRepo, C: GithubSyncClient> GithubSyncServiceImpl<D, R, C> {/// Handle `issue_comment`, `pull_request_review`, and/// `pull_request_review_comment` events.////// Extracts task IDs from the new comment/review text and deduplicates- /// against PR context text and all existing PR comments.+ /// against tasks already tracked in the repo for this PR.#[tracing::instrument(skip(self, event), err)]pub(crate) async fn handle_comment_event(&self,@@ -23,58 +22,54 @@ impl<D: DocumentService, C: GithubSyncClient> GithubSyncServiceImpl<D, C> {// Extract task IDs from the new comment/review text onlylet searchable_texts = event.extract_searchable_text();let combined = searchable_texts.join(" ");- let new_task_ids: HashSet<MacroTaskId> = MacroTaskId::extract_from_text(&combined)- .into_iter()- .collect();+ let comment_task_ids: Vec<MacroTaskId> = MacroTaskId::extract_from_text(&combined);tracing::trace!(- new_task_id_count = new_task_ids.len(),- task_ids = ?new_task_ids.iter().map(|t| t.to_task_id_string()).collect::<Vec<_>>(),+ new_task_id_count = comment_task_ids.len(),+ task_ids = ?comment_task_ids.iter().map(|t| t.to_task_id_string()).collect::<Vec<_>>(),"extracted task IDs from comment/review text");- if new_task_ids.is_empty() {+ if comment_task_ids.is_empty() {tracing::debug!("no task IDs found in comment/review text");return Ok(());}- let pr_meta = self.acquire_pr_meta(event).await;-- // Build the set of pre-existing task IDs from PR context text + all- // existing comment bodies- let pr_context = event.extract_pr_context_text().join(" ");- let mut existing_task_ids: HashSet<MacroTaskId> =- MacroTaskId::extract_from_text(&pr_context)- .into_iter()- .collect();-- tracing::trace!(- pr_context_task_ids = existing_task_ids.len(),- existing_task_ids = ?existing_task_ids.iter().map(|t| t.to_task_id_string()).collect::<Vec<_>>(),- "extracted pre-existing task IDs from PR context"- );+ let github_key = Self::github_key(event);++ // Ensure PR context task IDs are tracked in the repo (handles PRs+ // that existed before the tracking table was introduced).+ if let Some(ref key) = github_key {+ let pr_context_tasks = {+ let pr_context = event.extract_pr_context_text().join(" ");+ MacroTaskId::extract_from_text(&pr_context)+ };+ if !pr_context_tasks.is_empty() {+ tracing::trace!(+ pr_context_task_count = pr_context_tasks.len(),+ "upserting PR context task IDs"+ );+ self.repo+ .upsert_task_ids(key.clone(), &pr_context_tasks)+ .await+ .inspect_err(+ |e| tracing::error!(error=?e, "failed to upsert PR context task IDs"),+ )+ .ok();+ }+ }- let existing_comments = if let Some(ref meta) = pr_meta {- let comments = self.fetch_pr_comments(meta).await;- let comment_combined = comments.join(" ");- let comment_task_ids = MacroTaskId::extract_from_text(&comment_combined);- tracing::trace!(- comment_task_id_count = comment_task_ids.len(),- comment_task_ids = ?comment_task_ids.iter().map(|t| t.to_task_id_string()).collect::<Vec<_>>(),- "extracted task IDs from existing PR comments"- );- existing_task_ids.extend(comment_task_ids);- comments+ // Filter to only truly new task IDs using the repo+ let truly_new = if let Some(ref key) = github_key {+ self.repo+ .filter_duplicate_tasks(key.clone(), &comment_task_ids)+ .await+ .inspect_err(|e| tracing::error!(error=?e, "failed to filter duplicate tasks"))+ .unwrap_or_else(|_| comment_task_ids.clone())} else {- Vec::new()+ comment_task_ids.clone()};- // Filter to only task IDs that are truly new- let truly_new: Vec<_> = new_task_ids- .into_iter()- .filter(|id| !existing_task_ids.contains(id))- .collect();-tracing::trace!(truly_new_count = truly_new.len(),truly_new_task_ids = ?truly_new.iter().map(|t| t.to_task_id_string()).collect::<Vec<_>>(),@@ -82,16 +77,24 @@ impl<D: DocumentService, C: GithubSyncClient> GithubSyncServiceImpl<D, C> {);if truly_new.is_empty() {- tracing::debug!(- "all task IDs already present in PR context or prior comments, skipping"- );+ tracing::debug!("all task IDs already tracked for this PR, skipping");return Ok(());}- let resolved = self.resolve_tasks(&truly_new, &existing_comments).await;+ let resolved = self.resolve_tasks(&truly_new).await;+ let pr_meta = self.acquire_pr_meta(event).await;if let Some(ref meta) = pr_meta {- self.post_task_comment(meta, &resolved.new_task_links).await;+ self.post_task_comment(meta, &resolved.task_links).await;+ }++ // Track the new task IDs in the repo+ if let Some(ref key) = github_key {+ self.repo+ .upsert_task_ids(key.clone(), &comment_task_ids)+ .await+ .inspect_err(|e| tracing::error!(error=?e, "failed to upsert comment task IDs"))+ .ok();}// Only update status if the PR is opendiff --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 f02f5dc2b2..53d66500e6 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@@ -2,18 +2,15 @@use crate::domain::{models::{GithubError, MacroTaskId, ValidatedGithubWebhookEvent},- ports::GithubSyncClient,+ ports::{GithubSyncClient, GithubSyncRepo},};use documents::domain::ports::DocumentService;use std::collections::HashSet;use super::GithubSyncServiceImpl;-impl<D: DocumentService, C: GithubSyncClient> GithubSyncServiceImpl<D, C> {+impl<D: DocumentService, R: GithubSyncRepo, C: GithubSyncClient> GithubSyncServiceImpl<D, R, C> {/// Handle `pull_request` events with action `opened` or `reopened`.- ///- /// Only looks at PR title/body/branch for task IDs — does not fetch- /// existing comments.#[tracing::instrument(skip(self, event), err)]pub(crate) async fn handle_pr_open(&self,@@ -34,22 +31,39 @@ impl<D: DocumentService, C: GithubSyncClient> GithubSyncServiceImpl<D, C> {return Ok(());}- let pr_meta = self.acquire_pr_meta(event).await;+ let github_key = Self::github_key(event);- // Fetch existing comments only for dedup (don't extract task IDs from them)- let existing_comments = if let Some(ref meta) = pr_meta {- self.fetch_pr_comments(meta).await+ // Determine which tasks are new for this PR+ let new_task_ids = if let Some(ref key) = github_key {+ self.repo+ .filter_duplicate_tasks(key.clone(), &task_ids)+ .await+ .inspect_err(|e| tracing::error!(error=?e, "failed to filter duplicate tasks"))+ .unwrap_or_else(|_| task_ids.clone())} else {- Vec::new()+ task_ids.clone()};- let resolved = self.resolve_tasks(&task_ids, &existing_comments).await;+ // Resolve new tasks and post comment+ let new_resolved = self.resolve_tasks(&new_task_ids).await;+ let pr_meta = self.acquire_pr_meta(event).await;if let Some(ref meta) = pr_meta {- self.post_task_comment(meta, &resolved.new_task_links).await;+ self.post_task_comment(meta, &new_resolved.task_links).await;}- self.update_task_statuses(&resolved.doc_ids, "In Review")+ // Track all task IDs in the repo+ if let Some(ref key) = github_key {+ self.repo+ .upsert_task_ids(key.clone(), &task_ids)+ .await+ .inspect_err(|e| tracing::error!(error=?e, "failed to upsert task IDs"))+ .ok();+ }++ // Update status for all tasks from PR text+ let resolved_all = self.resolve_tasks(&task_ids).await;+ self.update_task_statuses(&resolved_all.doc_ids, "In Review").await;tracing::trace!("PR open handler complete");@@ -58,9 +72,9 @@ impl<D: DocumentService, C: GithubSyncClient> GithubSyncServiceImpl<D, C> {/// Handle `pull_request` events with action `edited`.///- /// Searches PR title/body/branch and existing PR comments for task IDs,- /// posts a bot comment for any newly discovered tasks, and sets status to- /// "In Review".+ /// Searches PR title/body/branch for task IDs, uses the repo to+ /// deduplicate, posts a bot comment for newly discovered tasks, and+ /// sets status to "In Review".#[tracing::instrument(skip(self, event), err)]pub(crate) async fn handle_pr_edit(&self,@@ -68,53 +82,52 @@ impl<D: DocumentService, C: GithubSyncClient> GithubSyncServiceImpl<D, C> {) -> Result<(), GithubError> {let searchable_texts = event.extract_searchable_text();let combined = searchable_texts.join(" ");- let mut task_id_set: HashSet<MacroTaskId> = MacroTaskId::extract_from_text(&combined)- .into_iter()- .collect();+ let task_ids: Vec<MacroTaskId> = MacroTaskId::extract_from_text(&combined);tracing::trace!(- task_id_count = task_id_set.len(),- task_ids = ?task_id_set.iter().map(|t| t.to_task_id_string()).collect::<Vec<_>>(),+ task_id_count = task_ids.len(),+ task_ids = ?task_ids.iter().map(|t| t.to_task_id_string()).collect::<Vec<_>>(),"extracted task IDs from PR text");- if task_id_set.is_empty() {+ if task_ids.is_empty() {tracing::debug!("no task IDs found in PR text");return Ok(());}- let pr_meta = self.acquire_pr_meta(event).await;+ let github_key = Self::github_key(event);- // For edits, also search existing comments for additional task IDs- let existing_comments = if let Some(ref meta) = pr_meta {- let comments = self.fetch_pr_comments(meta).await;- let comment_combined = comments.join(" ");- let comment_task_ids = MacroTaskId::extract_from_text(&comment_combined);- tracing::trace!(- comment_task_id_count = comment_task_ids.len(),- comment_task_ids = ?comment_task_ids.iter().map(|t| t.to_task_id_string()).collect::<Vec<_>>(),- "extracted additional task IDs from existing comments"- );- task_id_set.extend(comment_task_ids);- comments+ // Determine which tasks are new for this PR+ let new_task_ids = if let Some(ref key) = github_key {+ self.repo+ .filter_duplicate_tasks(key.clone(), &task_ids)+ .await+ .inspect_err(|e| tracing::error!(error=?e, "failed to filter duplicate tasks"))+ .unwrap_or_else(|_| task_ids.clone())} else {- Vec::new()+ task_ids.clone()};- let all_task_ids: Vec<_> = task_id_set.into_iter().collect();- tracing::trace!(- total_task_ids = all_task_ids.len(),- task_ids = ?all_task_ids.iter().map(|t| t.to_task_id_string()).collect::<Vec<_>>(),- "merged task IDs from PR text and comments"- );-- let resolved = self.resolve_tasks(&all_task_ids, &existing_comments).await;+ // Resolve new tasks and post comment+ let new_resolved = self.resolve_tasks(&new_task_ids).await;+ let pr_meta = self.acquire_pr_meta(event).await;if let Some(ref meta) = pr_meta {- self.post_task_comment(meta, &resolved.new_task_links).await;+ self.post_task_comment(meta, &new_resolved.task_links).await;+ }++ // Track all task IDs in the repo+ if let Some(ref key) = github_key {+ self.repo+ .upsert_task_ids(key.clone(), &task_ids)+ .await+ .inspect_err(|e| tracing::error!(error=?e, "failed to upsert task IDs"))+ .ok();}- self.update_task_statuses(&resolved.doc_ids, "In Review")+ // Update status for all tasks from PR text+ let resolved_all = self.resolve_tasks(&task_ids).await;+ self.update_task_statuses(&resolved_all.doc_ids, "In Review").await;tracing::trace!("PR edit handler complete");@@ -123,9 +136,9 @@ impl<D: DocumentService, C: GithubSyncClient> GithubSyncServiceImpl<D, C> {/// Handle `pull_request` events with action `closed`.///- /// Always fetches comments since tasks may only exist there. Does NOT post- /// a new bot comment (PR is closing). Updates task status to "Completed"- /// (if merged) or "Canceled" (if closed without merge).+ /// Gathers all tracked task IDs from the repo plus any from PR text,+ /// then updates status to "Completed" (if merged) or "Canceled".+ /// Does NOT post a new bot comment.#[tracing::instrument(skip(self, event), err)]pub(crate) async fn handle_pr_close(&self,@@ -134,8 +147,6 @@ impl<D: DocumentService, C: GithubSyncClient> GithubSyncServiceImpl<D, C> {let is_merged = event.is_merged();tracing::trace!(is_merged, "handling PR close");- let pr_meta = self.acquire_pr_meta(event).await;-// Gather task IDs from PR title/body/branchlet searchable_texts = event.extract_searchable_text();let combined = searchable_texts.join(" ");@@ -149,17 +160,20 @@ impl<D: DocumentService, C: GithubSyncClient> GithubSyncServiceImpl<D, C> {"extracted task IDs from PR text");- // Always fetch comments — tasks may only exist there- if let Some(ref meta) = pr_meta {- let comments = self.fetch_pr_comments(meta).await;- let comment_combined = comments.join(" ");- let comment_task_ids = MacroTaskId::extract_from_text(&comment_combined);- tracing::trace!(- comment_task_id_count = comment_task_ids.len(),- comment_task_ids = ?comment_task_ids.iter().map(|t| t.to_task_id_string()).collect::<Vec<_>>(),- "extracted task IDs from PR comments"- );- task_id_set.extend(comment_task_ids);+ // Also include all previously tracked tasks from the repo+ if let Some(key) = Self::github_key(event) {+ match self.repo.get_task_ids(key).await {+ Ok(repo_tasks) => {+ tracing::trace!(+ repo_task_count = repo_tasks.len(),+ "fetched tracked task IDs from repo"+ );+ task_id_set.extend(repo_tasks);+ }+ Err(e) => {+ tracing::error!(error=?e, "failed to get task IDs from repo");+ }+ }}if task_id_set.is_empty() {@@ -174,8 +188,7 @@ impl<D: DocumentService, C: GithubSyncClient> GithubSyncServiceImpl<D, C> {"total task IDs for close event");- // Empty existing_comments — no comment dedup needed since we won't post- let resolved = self.resolve_tasks(&all_task_ids, &[]).await;+ let resolved = self.resolve_tasks(&all_task_ids).await;// No bot comment on closelet status = if is_merged { "Completed" } else { "Canceled" };diff --git a/rust/cloud-storage/github/src/domain/service/sync/mod.rs b/rust/cloud-storage/github/src/domain/service/sync/mod.rsindex 07cdd005bc..90e4f7b4e7 100644--- a/rust/cloud-storage/github/src/domain/service/sync/mod.rs+++ b/rust/cloud-storage/github/src/domain/service/sync/mod.rs@@ -8,10 +8,10 @@ mod handle_pr;use crate::domain::{models::{- GithubError, GithubInstallationAccessToken, GithubWebhookEventType, MacroTaskId,+ GithubError, GithubInstallationAccessToken, GithubKey, GithubWebhookEventType, MacroTaskId,ValidatedGithubWebhookEvent,},- ports::{GithubSyncClient, GithubSyncService},+ ports::{GithubSyncClient, GithubSyncRepo, GithubSyncService},};use documents::domain::{models::DocumentError, ports::DocumentService};use entity_access::domain::models::{EditAccessLevel, ViewAccessLevel};@@ -36,19 +36,20 @@ pub struct GithubSyncConfig {}/// The concrete github sync service implementation.-pub struct GithubSyncServiceImpl<D: DocumentService, C: GithubSyncClient> {- config: super::GithubSyncConfig,- #[allow(dead_code)]+pub struct GithubSyncServiceImpl<D: DocumentService, R: GithubSyncRepo, C: GithubSyncClient> {+ config: GithubSyncConfig,document_service: Arc<D>,+ repo: R,pub(crate) client: C,}-impl<D: DocumentService, C: GithubSyncClient> GithubSyncServiceImpl<D, C> {+impl<D: DocumentService, R: GithubSyncRepo, C: GithubSyncClient> GithubSyncServiceImpl<D, R, C> {/// Create a new github sync service.- pub fn new(config: super::GithubSyncConfig, document_service: Arc<D>, client: C) -> Self {+ pub fn new(config: GithubSyncConfig, document_service: Arc<D>, repo: R, client: C) -> Self {Self {config,document_service,+ repo,client,}}@@ -66,11 +67,11 @@ struct PrMeta {struct ResolvedTasks {/// Document IDs for all resolved tasks (used for status updates).doc_ids: Vec<String>,- /// Markdown links for tasks not yet commented on the PR.- new_task_links: Vec<String>,+ /// Markdown links for resolved tasks (used for PR comments).+ task_links: Vec<String>,}-impl<D: DocumentService, C: GithubSyncClient> GithubSyncServiceImpl<D, C> {+impl<D: DocumentService, R: GithubSyncRepo, C: GithubSyncClient> GithubSyncServiceImpl<D, R, C> {/// 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))]@@ -119,22 +120,26 @@ impl<D: DocumentService, C: GithubSyncClient> GithubSyncServiceImpl<D, C> {}}- /// Resolve task IDs to documents, filtering for actual tasks and checking- /// comment dedup against `existing_comments`.- #[tracing::instrument(skip(self, task_ids, existing_comments))]- async fn resolve_tasks(- &self,- task_ids: &[MacroTaskId],- existing_comments: &[String],- ) -> ResolvedTasks {+ /// Build a [`GithubKey`] from the webhook event, if owner/repo/pull_number+ /// are all present.+ fn github_key(event: &ValidatedGithubWebhookEvent) -> Option<GithubKey> {+ match (event.repo_owner(), event.repo_name(), event.pull_number()) {+ (Some(o), Some(r), Some(p)) => Some(GithubKey::new(o, r, p)),+ _ => None,+ }+ }++ /// 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))]+ async fn resolve_tasks(&self, task_ids: &[MacroTaskId]) -> ResolvedTasks {tracing::trace!(task_id_count = task_ids.len(),- existing_comment_count = existing_comments.len(),"resolving task IDs to documents");let mut doc_ids = Vec::new();- let mut new_task_links = Vec::new();+ let mut task_links = Vec::new();for task_id in task_ids {let uuid = match task_id.to_uuid() {@@ -170,22 +175,7 @@ impl<D: DocumentService, C: GithubSyncClient> GithubSyncServiceImpl<D, C> {tracing::trace!(task_id=%uuid, doc_id, doc_name, "resolved task document");doc_ids.push(doc_id.clone());-- let already_commented = {- let task_link = format!("/app/task/{doc_id})");- existing_comments.iter().any(|c| c.contains(&task_link))- };-- if already_commented {- tracing::trace!(- task_id=%uuid,- doc_id,- "PR already has a comment linking to this task, skipping comment"- );- } else {- tracing::trace!(task_id=%uuid, doc_id, "adding new task link for comment");- new_task_links.push(create_macro_task_comment_link(doc_name, doc_id));- }+ task_links.push(create_macro_task_comment_link(doc_name, doc_id));} else {tracing::trace!(task_id=%uuid, "document found but is not a task, skipping");}@@ -201,13 +191,13 @@ impl<D: DocumentService, C: GithubSyncClient> GithubSyncServiceImpl<D, C> {tracing::trace!(resolved_count = doc_ids.len(),- new_link_count = new_task_links.len(),+ link_count = task_links.len(),"task resolution complete");ResolvedTasks {doc_ids,- new_task_links,+ task_links,}}@@ -272,37 +262,11 @@ impl<D: DocumentService, C: GithubSyncClient> GithubSyncServiceImpl<D, C> {.ok();}}-- /// Fetch existing PR comment bodies, returning empty vec on failure.- #[tracing::instrument(skip(self, pr_meta))]- async fn fetch_pr_comments(&self, pr_meta: &PrMeta) -> Vec<String> {- tracing::trace!(- owner = %pr_meta.owner,- repo = %pr_meta.repo,- pull_number = pr_meta.pull_number,- "fetching existing PR comments"- );-- let comments = self- .client- .list_pr_comments(- &pr_meta.token.token,- &pr_meta.owner,- &pr_meta.repo,- pr_meta.pull_number,- )- .await- .inspect_err(|e| {- tracing::error!(error=?e, "failed to list PR comments");- })- .unwrap_or_default();-- tracing::trace!(comment_count = comments.len(), "fetched PR comments");- comments- }}-impl<D: DocumentService, C: GithubSyncClient> GithubSyncService for GithubSyncServiceImpl<D, C> {+impl<D: DocumentService, R: GithubSyncRepo, C: GithubSyncClient> GithubSyncService+ for GithubSyncServiceImpl<D, R, C>+{#[tracing::instrument(skip(self, body), err)]async fn validate_webhook_event(&self,diff --git a/rust/cloud-storage/github/src/domain/service/sync/test.rs b/rust/cloud-storage/github/src/domain/service/sync/test.rsindex 685fde6586..c01fb651f2 100644--- a/rust/cloud-storage/github/src/domain/service/sync/test.rs+++ b/rust/cloud-storage/github/src/domain/service/sync/test.rs@@ -1,8 +1,12 @@+use std::collections::{HashMap, HashSet};use std::sync::{Arc, Mutex};use crate::domain::{- models::{GithubError, GithubInstallationAccessToken, ValidatedGithubWebhookEvent},- ports::{GithubSyncClient, GithubSyncService},+ models::{+ GithubError, GithubInstallationAccessToken, GithubKey, MacroTaskId,+ ValidatedGithubWebhookEvent,+ },+ ports::{GithubSyncClient, GithubSyncRepo, GithubSyncService},};use document_sub_type::DocumentSubType;use documents::domain::{@@ -169,6 +173,67 @@ impl DocumentService for StubDocumentService {}}+/// Stateful stub repo that tracks task IDs per github key.+struct StubSyncRepo {+ tasks: Mutex<HashMap<String, HashSet<String>>>,+}++impl StubSyncRepo {+ fn new() -> Self {+ Self {+ tasks: Mutex::new(HashMap::new()),+ }+ }+}++impl GithubSyncRepo for StubSyncRepo {+ type Err = anyhow::Error;++ async fn get_task_ids(&self, github_key: GithubKey) -> Result<Vec<MacroTaskId>, Self::Err> {+ let tasks = self.tasks.lock().unwrap();+ let ids = tasks+ .get(github_key.as_ref())+ .map(|set| {+ set.iter()+ .filter_map(|s| MacroTaskId::from_short_uuid(s))+ .collect()+ })+ .unwrap_or_default();+ Ok(ids)+ }++ async fn upsert_task_ids(+ &self,+ github_key: GithubKey,+ task_ids: &[MacroTaskId],+ ) -> Result<(), Self::Err> {+ let mut tasks = self.tasks.lock().unwrap();+ let set = tasks.entry(github_key.as_ref().to_string()).or_default();+ for id in task_ids {+ set.insert(id.short_uuid.clone());+ }+ Ok(())+ }++ async fn filter_duplicate_tasks(+ &self,+ github_key: GithubKey,+ task_ids: &[MacroTaskId],+ ) -> Result<Vec<MacroTaskId>, Self::Err> {+ let tasks = self.tasks.lock().unwrap();+ let existing = tasks.get(github_key.as_ref());+ Ok(task_ids+ .iter()+ .filter(|t| {+ existing+ .map(|set| !set.contains(&t.short_uuid))+ .unwrap_or(true)+ })+ .cloned()+ .collect())+ }+}+/// Recorded PR comment call.#[derive(Debug, Clone)]struct PrCommentCall {@@ -178,26 +243,14 @@ struct PrCommentCall {body: String,}-/// Stub sync client that optionally returns pre-seeded comments from-/// `seed_comments`, then also includes any comments created via-/// `create_pr_comment`.struct StubSyncClient {pr_comments: Mutex<Vec<PrCommentCall>>,- seed_comments: Mutex<Vec<String>>,}impl StubSyncClient {fn new() -> Self {Self {pr_comments: Mutex::new(Vec::new()),- seed_comments: Mutex::new(Vec::new()),- }- }-- fn with_seed_comments(comments: Vec<String>) -> Self {- Self {- pr_comments: Mutex::new(Vec::new()),- seed_comments: Mutex::new(comments),}}@@ -234,32 +287,14 @@ impl GithubSyncClient for StubSyncClient {});Ok(())}-- async fn list_pr_comments(- &self,- _access_token: &str,- _owner: &str,- _repo: &str,- _pull_number: u64,- ) -> Result<Vec<String>, GithubError> {- let mut result: Vec<String> = self.seed_comments.lock().unwrap().clone();- result.extend(- self.pr_comments- .lock()- .unwrap()- .iter()- .map(|c| c.body.clone()),- );- Ok(result)- }}-fn make_sync_service() -> GithubSyncServiceImpl<StubDocumentService, StubSyncClient> {+fn make_sync_service() -> GithubSyncServiceImpl<StubDocumentService, StubSyncRepo, StubSyncClient> {make_sync_service_with_doc_service().0}fn make_sync_service_with_doc_service() -> (- GithubSyncServiceImpl<StubDocumentService, StubSyncClient>,+ GithubSyncServiceImpl<StubDocumentService, StubSyncRepo, StubSyncClient>,Arc<StubDocumentService>,) {let doc_service = Arc::new(StubDocumentService::new());@@ -271,31 +306,12 @@ fn make_sync_service_with_doc_service() -> (sync_app_client_id: "test-sync-app-client-id".to_string(),},doc_service.clone(),+ StubSyncRepo::new(),StubSyncClient::new(),);(service, doc_service)}-fn make_sync_service_with_seed_comments(- seed_comments: Vec<String>,-) -> (- GithubSyncServiceImpl<StubDocumentService, StubSyncClient>,- Arc<StubDocumentService>,-) {- let doc_service = Arc::new(StubDocumentService::new());- let service = GithubSyncServiceImpl::new(- GithubSyncConfig {- webhook_secret: "test-webhook-secret".to_string(),- github_sync_app_url: "test".to_string(),- sync_app_pem: TEST_PEM.to_string(),- sync_app_client_id: "test-sync-app-client-id".to_string(),- },- doc_service.clone(),- StubSyncClient::with_seed_comments(seed_comments),- );- (service, doc_service)-}-#[tokio::test]async fn pr_with_task_id_in_title() {let service = make_sync_service();@@ -492,11 +508,11 @@ async fn pull_request_review_comment_with_task_id() {}// ----------------------------------------------------------------------------// Deduplication: bot already posted a comment linking to the same task+// Deduplication: repo tracks tasks already associated with a PR// ---------------------------------------------------------------------------#[tokio::test]-async fn duplicate_comment_not_posted_when_bot_already_commented() {+async fn duplicate_comment_not_posted_when_task_already_tracked() {let service = make_sync_service();let make_event = || {@@ -537,30 +553,59 @@ async fn duplicate_comment_not_posted_when_bot_already_commented() {#[tokio::test]async fn issue_comment_duplicate_task_id_skipped() {let service = make_sync_service();- // PR title already contains MACRO-abc123, comment also mentions it- let event = ValidatedGithubWebhookEvent::new(++ // First, open the PR with the task ID to populate the repo+ let pr_event = ValidatedGithubWebhookEvent::new(+ "pull_request".to_string(),+ serde_json::json!({+ "action": "opened",+ "pull_request": {+ "number": 99,+ "title": "fixes MACRO-abc123",+ "body": null,+ "head": { "ref": "main" }+ },+ "repository": {+ "name": "my-repo",+ "owner": { "login": "my-org" }+ },+ "installation": { "id": 12345 }+ }),+ );+ service.process_webhook_event(&pr_event).await.unwrap();++ // Comment mentions the same task ID — should be skipped+ let comment_event = ValidatedGithubWebhookEvent::new("issue_comment".to_string(),serde_json::json!({"action": "created","issue": {+ "number": 99,"title": "fixes MACRO-abc123","body": null,"head": { "ref": "main" }},"comment": {"body": "Fixes MACRO-abc123"- }+ },+ "repository": {+ "name": "my-repo",+ "owner": { "login": "my-org" }+ },+ "installation": { "id": 12345 }}),);- let result = service.process_webhook_event(&event).await;+ let result = service.process_webhook_event(&comment_event).await;assert!(result.is_ok());+ // No additional comment posted (PR open posted one, comment should not)+ assert_eq!(service.client.pr_comments().len(), 0);}#[tokio::test]async fn issue_comment_new_task_id_not_skipped() {let service = make_sync_service();- // PR title has MACRO-abc123, but comment introduces MACRO-def456+ // Comment introduces a new task ID not previously trackedlet event = ValidatedGithubWebhookEvent::new("issue_comment".to_string(),serde_json::json!({@@ -581,9 +626,10 @@ async fn issue_comment_new_task_id_not_skipped() {}#[tokio::test]-async fn review_duplicate_task_id_skipped() {+async fn review_duplicate_task_id_skipped_via_pr_context() {let service = make_sync_service();- // PR title already has the task ID, review body repeats it+ // PR title already has the task ID. The comment handler upserts PR context+ // tasks, so the review body's mention is considered a duplicate.let event = ValidatedGithubWebhookEvent::new("pull_request_review".to_string(),serde_json::json!({@@ -606,7 +652,8 @@ async fn review_duplicate_task_id_skipped() {#[tokio::test]async fn review_comment_mixed_new_and_duplicate() {let service = make_sync_service();- // PR has MACRO-abc123 in branch, comment mentions both abc123 (dup) and def456 (new)+ // PR has MACRO-abc123 in branch (will be upserted as PR context),+ // comment mentions both abc123 (dup via context) and def456 (new)let event = ValidatedGithubWebhookEvent::new("pull_request_review_comment".to_string(),serde_json::json!({@@ -788,7 +835,7 @@ async fn issue_comment_on_closed_pr_does_not_update_task_status() {}#[tokio::test]-async fn pr_merged_updates_status_even_when_already_commented() {+async fn pr_merged_updates_status_even_when_already_tracked() {let (service, doc_service) = make_sync_service_with_doc_service();// First event: PR opened — posts comment and sets "In Review"@@ -890,10 +937,8 @@ async fn pr_close_does_not_post_comment() {#[tokio::test]async fn pr_open_does_not_search_existing_comments() {// On open, only PR title/body/branch are searched — not existing comments.- // The seed comment has the known task ID, but the PR text does not, so- // nothing should happen.- let (service, doc_service) =- make_sync_service_with_seed_comments(vec![format!("See MACRO-2BuyvtY3aeEvHx4uG8iD51")]);+ // No tasks in the PR text, so nothing should happen.+ let (service, doc_service) = make_sync_service_with_doc_service();let event = ValidatedGithubWebhookEvent::new("pull_request".to_string(),@@ -915,28 +960,25 @@ async fn pr_open_does_not_search_existing_comments() {service.process_webhook_event(&event).await.unwrap();- // No comment posted — open doesn't search existing comments for task IDsassert!(service.client.pr_comments().is_empty());assert!(doc_service.task_status_calls().is_empty());}#[tokio::test]-async fn pr_edit_picks_up_task_from_existing_comment() {- // On edit, existing PR comments ARE searched for additional task IDs.- let task_link = format!("[My Task](https://macro.com/app/task/{KNOWN_TASK_UUID})");- let (service, doc_service) =- make_sync_service_with_seed_comments(vec![format!("See MACRO-2BuyvtY3aeEvHx4uG8iD51")]);+async fn pr_close_picks_up_task_from_repo() {+ let (service, doc_service) = make_sync_service_with_doc_service();- // PR title has a different (non-existent) task, but the comment has the real one- let event = ValidatedGithubWebhookEvent::new(+ // First, open PR with the task to populate the repo+ let open_event = ValidatedGithubWebhookEvent::new("pull_request".to_string(),serde_json::json!({- "action": "edited",+ "action": "opened","pull_request": {"number": 42,- "title": "fixes MACRO-abc123",+ "title": "fixes MACRO-2BuyvtY3aeEvHx4uG8iD51","body": null,- "head": { "ref": "feature/some-branch" }+ "head": { "ref": "feature/some-branch" },+ "merged": false},"repository": {"name": "my-repo",@@ -945,28 +987,10 @@ async fn pr_edit_picks_up_task_from_existing_comment() {"installation": { "id": 12345 }}),);+ service.process_webhook_event(&open_event).await.unwrap();- service.process_webhook_event(&event).await.unwrap();-- // Should pick up the task from the existing comment and post a link- let comments = service.client.pr_comments();- assert_eq!(comments.len(), 1);- assert_eq!(comments[0].body, task_link);-- // Status should be updated- let status_calls = doc_service.task_status_calls();- assert_eq!(status_calls.len(), 1);- assert_eq!(status_calls[0].entity_id, KNOWN_TASK_UUID);- assert_eq!(status_calls[0].status, "In Review");-}--#[tokio::test]-async fn pr_close_picks_up_task_from_comments() {- // Task ID only in a comment, not title/body/branch- let (service, doc_service) =- make_sync_service_with_seed_comments(vec!["See MACRO-2BuyvtY3aeEvHx4uG8iD51".to_string()]);-- let event = ValidatedGithubWebhookEvent::new(+ // Close with a different title (no task ID in text), but repo remembers it+ let close_event = ValidatedGithubWebhookEvent::new("pull_request".to_string(),serde_json::json!({"action": "closed",@@ -985,32 +1009,51 @@ async fn pr_close_picks_up_task_from_comments() {}),);- service.process_webhook_event(&event).await.unwrap();+ service.process_webhook_event(&close_event).await.unwrap();// No comment posted on close- assert!(service.client.pr_comments().is_empty());+ assert_eq!(service.client.pr_comments().len(), 1); // only from open- // Status should be updated from comment-discovered task+ // Status should be updated from repo-tracked tasklet status_calls = doc_service.task_status_calls();- assert_eq!(status_calls.len(), 1);- assert_eq!(status_calls[0].entity_id, KNOWN_TASK_UUID);- assert_eq!(status_calls[0].status, "Completed");+ assert_eq!(status_calls.len(), 2); // "In Review" from open, "Completed" from close+ assert_eq!(status_calls[1].entity_id, KNOWN_TASK_UUID);+ assert_eq!(status_calls[1].status, "Completed");}#[tokio::test]-async fn comment_deduplicates_against_prior_comments() {- // A prior comment already mentions the task ID. A new comment mentioning- // the same task ID should not trigger a new bot comment.- let (service, _doc_service) =- make_sync_service_with_seed_comments(vec!["See MACRO-2BuyvtY3aeEvHx4uG8iD51".to_string()]);+async fn comment_deduplicates_against_repo() {+ let (service, _doc_service) = make_sync_service_with_doc_service();- let event = ValidatedGithubWebhookEvent::new(+ // Open PR with a task — tracked in repo+ let pr_event = ValidatedGithubWebhookEvent::new(+ "pull_request".to_string(),+ serde_json::json!({+ "action": "opened",+ "pull_request": {+ "number": 99,+ "title": "fixes MACRO-2BuyvtY3aeEvHx4uG8iD51",+ "body": null,+ "head": { "ref": "main" }+ },+ "repository": {+ "name": "my-repo",+ "owner": { "login": "my-org" }+ },+ "installation": { "id": 12345 }+ }),+ );+ service.process_webhook_event(&pr_event).await.unwrap();+ assert_eq!(service.client.pr_comments().len(), 1);++ // A comment mentions the same task ID — should be deduped by the repo+ let comment_event = ValidatedGithubWebhookEvent::new("issue_comment".to_string(),serde_json::json!({"action": "created","issue": {"number": 99,- "title": "some issue",+ "title": "fixes MACRO-2BuyvtY3aeEvHx4uG8iD51","body": null,"state": "open","head": { "ref": "main" }@@ -1026,12 +1069,12 @@ async fn comment_deduplicates_against_prior_comments() {}),);- service.process_webhook_event(&event).await.unwrap();+ service.process_webhook_event(&comment_event).await.unwrap();- // Task ID was already in a prior comment, so it should be filtered out- // as a duplicate — no new bot comment- assert!(- service.client.pr_comments().is_empty(),- "comment should not re-trigger for task already mentioned in prior comment"+ // No additional comment — task was already tracked in repo+ assert_eq!(+ service.client.pr_comments().len(),+ 1,+ "comment should not re-trigger for task already tracked in repo");}diff --git a/rust/cloud-storage/github/src/outbound.rs b/rust/cloud-storage/github/src/outbound.rsindex 3450f552f6..9fba36a96e 100644--- a/rust/cloud-storage/github/src/outbound.rs+++ b/rust/cloud-storage/github/src/outbound.rs@@ -8,3 +8,5 @@ pub mod github_oauth_client;pub mod github_sync_client;#[cfg(feature = "link")]pub mod pg_github_repo;+#[cfg(feature = "sync")]+pub mod pg_github_sync_repo;diff --git a/rust/cloud-storage/github/src/outbound/github_sync_client.rs b/rust/cloud-storage/github/src/outbound/github_sync_client.rsindex 0758fd1f89..c93579d2f8 100644--- a/rust/cloud-storage/github/src/outbound/github_sync_client.rs+++ b/rust/cloud-storage/github/src/outbound/github_sync_client.rs@@ -87,47 +87,4 @@ impl GithubSyncClient for GithubSyncClientImpl {Ok(())}-- #[tracing::instrument(skip(self, access_token), err)]- async fn list_pr_comments(- &self,- access_token: &str,- owner: &str,- repo: &str,- pull_number: u64,- ) -> Result<Vec<String>, GithubError> {- let response = self- .client- .get(format!(- "https://api.github.com/repos/{owner}/{repo}/issues/{pull_number}/comments"- ))- .header("Authorization", format!("Bearer {access_token}"))- .header("Accept", "application/vnd.github+json")- .header("User-Agent", "Macro-Auth-Service")- .header("X-GitHub-Api-Version", "2022-11-28")- .send()- .await- .map_err(|e| GithubError::Internal(e.into()))?;-- let status = response.status();- if !status.is_success() {- let error_body = response- .text()- .await- .unwrap_or_else(|_| "unknown error".to_string());- return Err(GithubError::Internal(anyhow::anyhow!(- "failed to list PR comments (status {status}): {error_body}"- )));- }-- let comments: Vec<serde_json::Value> = response- .json()- .await- .map_err(|e| GithubError::Internal(e.into()))?;-- Ok(comments- .into_iter()- .filter_map(|c| c.get("body")?.as_str().map(String::from))- .collect())- }}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.rsnew file mode 100644index 0000000000..00c2eb89dc--- /dev/null+++ b/rust/cloud-storage/github/src/outbound/pg_github_sync_repo.rs@@ -0,0 +1,109 @@+//! PostgreSQL implementation of the [`GithubSyncRepo`] port.++#[cfg(test)]+mod test;++use std::collections::HashSet;++use sqlx::PgPool;++use crate::domain::{+ models::{GithubKey, MacroTaskId},+ ports::GithubSyncRepo,+};++/// PostgreSQL-backed github repository.+#[derive(Clone)]+pub struct PgGithubSyncRepo {+ pool: PgPool,+}++impl PgGithubSyncRepo {+ /// Create a new repository backed by the given connection pool.+ pub fn new(pool: PgPool) -> Self {+ Self { pool }+ }+}++impl GithubSyncRepo for PgGithubSyncRepo {+ type Err = sqlx::Error;++ #[tracing::instrument(skip(self), err)]+ async fn get_task_ids(&self, github_key: GithubKey) -> Result<Vec<MacroTaskId>, Self::Err> {+ let task_ids: Vec<String> = sqlx::query!(+ r#"+ SELECT task_id FROM github_pr_tasks+ WHERE github_key = $1+ "#,+ github_key.as_ref(),+ )+ .map(|r| r.task_id)+ .fetch_all(&self.pool)+ .await?;++ Ok(task_ids+ .into_iter()+ .filter_map(|t| MacroTaskId::from_short_uuid(&t))+ .collect())+ }++ #[tracing::instrument(skip(self), err)]+ async fn upsert_task_ids(+ &self,+ github_key: GithubKey,+ task_ids: &[MacroTaskId],+ ) -> Result<(), Self::Err> {+ let short_ids: Vec<String> = task_ids.iter().map(|t| t.short_uuid.clone()).collect();+ let ids: Vec<uuid::Uuid> = short_ids+ .iter()+ .map(|_| macro_uuid::generate_uuid_v7())+ .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+ "#,+ &ids,+ &github_keys as &[&str],+ &short_ids+ )+ .execute(&self.pool)+ .await?;++ Ok(())+ }++ #[tracing::instrument(skip(self), err)]+ async fn filter_duplicate_tasks(+ &self,+ github_key: GithubKey,+ task_ids: &[MacroTaskId],+ ) -> Result<Vec<MacroTaskId>, Self::Err> {+ let short_ids: Vec<String> = task_ids.iter().map(|t| t.short_uuid.clone()).collect();++ let existing: Vec<String> = sqlx::query_scalar!(+ r#"+ SELECT task_id+ FROM github_pr_tasks+ WHERE github_key = $1+ AND task_id = ANY($2::text[])+ "#,+ github_key.as_ref(),+ &short_ids+ )+ .fetch_all(&self.pool)+ .await?;++ let existing_set: HashSet<String> = existing.into_iter().collect();++ Ok(task_ids+ .iter()+ .filter(|t| !existing_set.contains(&t.short_uuid))+ .cloned()+ .collect())+ }+}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.rsnew file mode 100644index 0000000000..dc15f93256--- /dev/null+++ b/rust/cloud-storage/github/src/outbound/pg_github_sync_repo/test.rs@@ -0,0 +1,187 @@+use macro_db_migrator::MACRO_DB_MIGRATIONS;+use sqlx::{Pool, Postgres};++use crate::domain::models::{GithubKey, MacroTaskId};+use crate::domain::ports::GithubSyncRepo;+use crate::outbound::pg_github_sync_repo::PgGithubSyncRepo;++// ---------------------------------------------------------------------------+// get_task_ids+// ---------------------------------------------------------------------------++#[sqlx::test(+ migrator = "MACRO_DB_MIGRATIONS",+ fixtures(path = "../../../fixtures", scripts("github_sync_test_data"))+)]+async fn test_get_task_ids(pool: Pool<Postgres>) {+ let repo = PgGithubSyncRepo::new(pool);++ let key = GithubKey::new("my-org", "my-repo", 1);+ let task_ids = repo.get_task_ids(key).await.unwrap();++ assert_eq!(task_ids.len(), 2);+ let shorts: Vec<&str> = task_ids.iter().map(|t| t.short_uuid.as_str()).collect();+ assert!(shorts.contains(&"s61deeZUHehUjkNT8rxB3S"));+ assert!(shorts.contains(&"bMv3eymKvu18qsQyrpt1VH"));+}++#[sqlx::test(+ migrator = "MACRO_DB_MIGRATIONS",+ fixtures(path = "../../../fixtures", scripts("github_sync_test_data"))+)]+async fn test_get_task_ids_different_pr(pool: Pool<Postgres>) {+ let repo = PgGithubSyncRepo::new(pool);++ let key = GithubKey::new("my-org", "other-repo", 42);+ let task_ids = repo.get_task_ids(key).await.unwrap();++ assert_eq!(task_ids.len(), 1);+ assert_eq!(task_ids[0].short_uuid, "xdyzHm2ZVGr6UAkaeBCUxZ");+}++#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]+async fn test_get_task_ids_empty(pool: Pool<Postgres>) {+ let repo = PgGithubSyncRepo::new(pool);++ let key = GithubKey::new("no-org", "no-repo", 999);+ let task_ids = repo.get_task_ids(key).await.unwrap();++ assert!(task_ids.is_empty());+}++// ---------------------------------------------------------------------------+// upsert_task_ids+// ---------------------------------------------------------------------------++#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]+async fn test_upsert_task_ids_inserts_new(pool: Pool<Postgres>) {+ let repo = PgGithubSyncRepo::new(pool);++ let key = GithubKey::new("org", "repo", 10);+ let tasks = vec![+ MacroTaskId::from_short_uuid("xoyQ8nrV6PNZFmpsWYMdyC").unwrap(),+ MacroTaskId::from_short_uuid("2ZbZ7wJQfEMWyBSycKYTYr").unwrap(),+ ];++ repo.upsert_task_ids(key.clone(), &tasks).await.unwrap();++ let fetched = repo.get_task_ids(key).await.unwrap();+ assert_eq!(fetched.len(), 2);+}++#[sqlx::test(+ migrator = "MACRO_DB_MIGRATIONS",+ fixtures(path = "../../../fixtures", scripts("github_sync_test_data"))+)]+async fn test_upsert_task_ids_ignores_duplicates(pool: Pool<Postgres>) {+ let repo = PgGithubSyncRepo::new(pool);++ let key = GithubKey::new("my-org", "my-repo", 1);+ let tasks = vec![+ MacroTaskId::from_short_uuid("s61deeZUHehUjkNT8rxB3S").unwrap(), // already exists+ MacroTaskId::from_short_uuid("xoyQ8nrV6PNZFmpsWYMdyC").unwrap(),+ ];++ repo.upsert_task_ids(key.clone(), &tasks).await.unwrap();++ let fetched = repo.get_task_ids(key).await.unwrap();+ assert_eq!(fetched.len(), 3); // s61dee.., bMv3e.. (existing) + xoyQ8..+}++#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]+async fn test_upsert_task_ids_empty_list(pool: Pool<Postgres>) {+ let repo = PgGithubSyncRepo::new(pool);++ let key = GithubKey::new("org", "repo", 1);+ repo.upsert_task_ids(key.clone(), &[]).await.unwrap();++ let fetched = repo.get_task_ids(key).await.unwrap();+ assert!(fetched.is_empty());+}++// ---------------------------------------------------------------------------+// filter_duplicate_tasks+// ---------------------------------------------------------------------------++#[sqlx::test(+ migrator = "MACRO_DB_MIGRATIONS",+ fixtures(path = "../../../fixtures", scripts("github_sync_test_data"))+)]+async fn test_filter_duplicate_tasks_removes_existing(pool: Pool<Postgres>) {+ let repo = PgGithubSyncRepo::new(pool);++ let key = GithubKey::new("my-org", "my-repo", 1);+ let candidates = vec![+ MacroTaskId::from_short_uuid("s61deeZUHehUjkNT8rxB3S").unwrap(), // exists+ MacroTaskId::from_short_uuid("bMv3eymKvu18qsQyrpt1VH").unwrap(), // exists+ MacroTaskId::from_short_uuid("xoyQ8nrV6PNZFmpsWYMdyC").unwrap(),+ ];++ let new_only = repo.filter_duplicate_tasks(key, &candidates).await.unwrap();++ assert_eq!(new_only.len(), 1);+ assert_eq!(new_only[0].short_uuid, "xoyQ8nrV6PNZFmpsWYMdyC");+}++#[sqlx::test(+ migrator = "MACRO_DB_MIGRATIONS",+ fixtures(path = "../../../fixtures", scripts("github_sync_test_data"))+)]+async fn test_filter_duplicate_tasks_all_new(pool: Pool<Postgres>) {+ let repo = PgGithubSyncRepo::new(pool);++ let key = GithubKey::new("my-org", "my-repo", 1);+ let candidates = vec![+ MacroTaskId::from_short_uuid("xoyQ8nrV6PNZFmpsWYMdyC").unwrap(),+ MacroTaskId::from_short_uuid("2ZbZ7wJQfEMWyBSycKYTYr").unwrap(),+ ];++ let new_only = repo.filter_duplicate_tasks(key, &candidates).await.unwrap();++ assert_eq!(new_only.len(), 2);+}++#[sqlx::test(+ migrator = "MACRO_DB_MIGRATIONS",+ fixtures(path = "../../../fixtures", scripts("github_sync_test_data"))+)]+async fn test_filter_duplicate_tasks_all_existing(pool: Pool<Postgres>) {+ let repo = PgGithubSyncRepo::new(pool);++ let key = GithubKey::new("my-org", "my-repo", 1);+ let candidates = vec![+ MacroTaskId::from_short_uuid("s61deeZUHehUjkNT8rxB3S").unwrap(),+ MacroTaskId::from_short_uuid("bMv3eymKvu18qsQyrpt1VH").unwrap(),+ ];++ let new_only = repo.filter_duplicate_tasks(key, &candidates).await.unwrap();++ assert!(new_only.is_empty());+}++#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]+async fn test_filter_duplicate_tasks_empty_input(pool: Pool<Postgres>) {+ let repo = PgGithubSyncRepo::new(pool);++ let key = GithubKey::new("org", "repo", 1);+ let new_only = repo.filter_duplicate_tasks(key, &[]).await.unwrap();++ assert!(new_only.is_empty());+}++#[sqlx::test(+ migrator = "MACRO_DB_MIGRATIONS",+ fixtures(path = "../../../fixtures", scripts("github_sync_test_data"))+)]+async fn test_filter_duplicate_tasks_different_key_not_filtered(pool: Pool<Postgres>) {+ let repo = PgGithubSyncRepo::new(pool);++ // s61dee.. exists for my-org/my-repo/pull/1, but not for this key+ let key = GithubKey::new("my-org", "other-repo", 42);+ let candidates = vec![MacroTaskId::from_short_uuid("s61deeZUHehUjkNT8rxB3S").unwrap()];++ let new_only = repo.filter_duplicate_tasks(key, &candidates).await.unwrap();++ assert_eq!(new_only.len(), 1);+ assert_eq!(new_only[0].short_uuid, "s61deeZUHehUjkNT8rxB3S");+}diff --git a/rust/cloud-storage/macro_db_client/migrations/20260305182148_track_task_with_pr.sql b/rust/cloud-storage/macro_db_client/migrations/20260305182148_track_task_with_pr.sqlnew file mode 100644index 0000000000..2dec050ef7--- /dev/null+++ b/rust/cloud-storage/macro_db_client/migrations/20260305182148_track_task_with_pr.sql@@ -0,0 +1,19 @@+-- Add migration script here+CREATE TABLE public.github_pr_tasks+(+ id UUID NOT NULL,+ github_key TEXT NOT NULL, -- organization:repo_name:pr_number+ task_id TEXT NOT NULL, -- the short id of the macro task+ created_at TIMESTAMP WITH TIME ZONE DEFAULT NOW() NOT NULL,+ updated_at TIMESTAMP WITH TIME ZONE DEFAULT NOW() NOT NULL,++ CONSTRAINT github_pr_tasks_pkey PRIMARY KEY (id),+ CONSTRAINT github_pr_tasks_github_key_task_id_unique UNIQUE (github_key, task_id)+);++-- Lookup indices+CREATE INDEX idx_github_pr_tasks_github_key+ ON public.github_pr_tasks (github_key);++CREATE INDEX idx_github_pr_tasks_task_id+ ON public.github_pr_tasks (task_id);