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
support commenting on github prs (#1777)
Will Hutchinsonbed4c36c3ba2
diff --git a/rust/cloud-storage/Cargo.lock b/rust/cloud-storage/Cargo.lockindex a0ea86d2dc..0c7df3dbb0 100644--- a/rust/cloud-storage/Cargo.lock+++ b/rust/cloud-storage/Cargo.lock@@ -4167,6 +4167,7 @@ dependencies = ["axum","axum-extra","chrono",+ "document_sub_type","documents","entity_access","fusionauth",@@ -4175,11 +4176,13 @@ dependencies = ["http-body-util","jsonwebtoken","macro_db_migrator",+ "macro_env","macro_user_id","macro_uuid","mockall","model","model-error-response",+ "models_permissions","redis","regex","reqwest",diff --git a/rust/cloud-storage/entity_access/src/domain/models.rs b/rust/cloud-storage/entity_access/src/domain/models.rsindex e28cb9a56e..f0152c57d9 100644--- a/rust/cloud-storage/entity_access/src/domain/models.rs+++ b/rust/cloud-storage/entity_access/src/domain/models.rs@@ -149,7 +149,6 @@ impl<T: RequiredAccessLevel> EntityAccessReceipt<T> {/// to circumvent AI tool permissioning/// This **DOES NOT** assert the existence of the itempub fn dangerously_assert_internal_user(- &self,entity_id: &str,entity_type: EntityType,) -> EntityAccessReceipt<T> {diff --git a/rust/cloud-storage/github/Cargo.toml b/rust/cloud-storage/github/Cargo.tomlindex 73b580d99c..62f398519d 100644--- a/rust/cloud-storage/github/Cargo.toml+++ b/rust/cloud-storage/github/Cargo.toml@@ -5,50 +5,50 @@ publish = falseversion = "0.1.0"[features]-default = ["ports", "sync", "link", "inbound", "outbound", "axum"]-ports = []-sync = ["dep:reqwest", "dep:documents", "ports"]-link = ["ports"]+axum = ["dep:axum", "dep:axum-extra", "dep:model-error-response", "dep:utoipa"]+default = ["axum", "inbound", "link", "outbound", "ports", "sync"]inbound = ["axum", "ports"]+link = ["ports"]outbound = [- "dep:sqlx",- "dep:reqwest",- "dep:urlencoding",+ "dep:fusionauth","dep:redis",+ "dep:reqwest",+ "dep:sqlx","dep:tokio",- "dep:fusionauth",- "ports"-]-axum = [- "dep:axum",- "dep:axum-extra",- "dep:model-error-response",- "dep:utoipa",+ "dep:urlencoding",+ "ports",]+ports = []+sync = ["dep:documents", "dep:entity_access", "dep:reqwest", "ports"][dependencies]anyhow = { workspace = true }-tracing = { workspace = true }-thiserror = { workspace = true }chrono = { workspace = true }-sqlx = { workspace = true, optional = true }-uuid = { workspace = true }-serde = { workspace = true}-reqwest = {workspace = true, optional = true }-serde_json = { workspace = true }-regex = { workspace = true }-urlencoding = { workspace = true, optional = true }-documents = { path = "../documents", default-features = false, features = ["ports"], optional = true }-entity_access = { path = "../entity_access" }-jsonwebtoken = { workspace = true }+documents = { path = "../documents", default-features = false, features = [+ "ports",+], optional = true }+entity_access = { path = "../entity_access", default-features = false, features = [+ "ports",+], optional = true }+hex = { workspace = true }hmac = "0.12.1"+jsonwebtoken = { workspace = true }+regex = { workspace = true }+reqwest = { workspace = true, optional = true }+serde = { workspace = true }+serde_json = { workspace = true }sha2 = { workspace = true }+sqlx = { workspace = true, optional = true }subtle = "2.6.1"-hex = { workspace = true }+thiserror = { workspace = true }+tracing = { workspace = true }+urlencoding = { workspace = true, optional = true }+uuid = { workspace = true }+macro_env = { path = "../macro_env" }fusionauth = { path = "../fusionauth", optional = true }-macro_uuid = { path = "../macro_uuid" }macro_user_id = { path = "../macro_user_id" }+macro_uuid = { path = "../macro_uuid" }redis = { workspace = true, features = ["aio", "tokio-comp"], optional = true }tokio = { workspace = true, features = ["sync"], optional = true }@@ -58,9 +58,11 @@ model-error-response = { path = "../model-error-response", optional = true }utoipa = { workspace = true, optional = true }[dev-dependencies]+document_sub_type = { path = "../document_sub_type" }+http-body-util = { workspace = true }macro_db_migrator = { path = "../macro_db_migrator" }mockall = { workspace = true }-http-body-util = { workspace = true }model = { path = "../model" }+models_permissions = { path = "../models_permissions" }tokio = { workspace = true }tower = { workspace = true }diff --git a/rust/cloud-storage/github/src/domain/models/sync.rs b/rust/cloud-storage/github/src/domain/models/sync.rsindex eb32f11436..3860ba5c60 100644--- a/rust/cloud-storage/github/src/domain/models/sync.rs+++ b/rust/cloud-storage/github/src/domain/models/sync.rs@@ -85,6 +85,83 @@ impl ValidatedGithubWebhookEvent {}texts}++ /// Extract the pull request / issue number from the webhook payload.+ pub fn pull_number(&self) -> Option<u64> {+ self.payload+ .get("pull_request")+ .and_then(|pr| pr.get("number"))+ .or_else(|| {+ self.payload+ .get("issue")+ .and_then(|issue| issue.get("number"))+ })+ .and_then(|v| v.as_u64())+ }++ /// Extract the repository owner login from the webhook payload.+ pub fn repo_owner(&self) -> Option<&str> {+ self.payload+ .get("repository")+ .and_then(|r| r.get("owner"))+ .and_then(|o| o.get("login"))+ .and_then(|v| v.as_str())+ }++ /// Extract the repository name from the webhook payload.+ pub fn repo_name(&self) -> Option<&str> {+ self.payload+ .get("repository")+ .and_then(|r| r.get("name"))+ .and_then(|v| v.as_str())+ }++ /// Extract the GitHub App installation ID from the webhook payload.+ pub fn installation_id(&self) -> Option<u64> {+ self.payload+ .get("installation")+ .and_then(|i| i.get("id"))+ .and_then(|v| v.as_u64())+ }++ /// Extract text from the PR context (title, body, branch) regardless of+ /// event type. For comment/review events this returns the surrounding PR+ /// info so callers can determine which task IDs are already associated+ /// with the PR itself. Returns empty for `PullRequest` events (since the+ /// event *is* the PR context) and unknown events.+ pub fn extract_pr_context_text(&self) -> Vec<String> {+ let mut texts = Vec::new();++ let pr = match self.parsed_event_type() {+ // For PR events, the event itself is the context — nothing to compare against.+ GithubWebhookEventType::PullRequest | GithubWebhookEventType::Unknown(_) => {+ return texts;+ }+ // issue_comment payloads embed the issue (which contains PR title/body).+ GithubWebhookEventType::IssueComment => self.payload.get("issue"),+ // review / review_comment payloads embed the full pull_request object.+ GithubWebhookEventType::PullRequestReview+ | GithubWebhookEventType::PullRequestReviewComment => self.payload.get("pull_request"),+ };++ if let Some(pr) = pr {+ if let Some(s) = pr.get("title").and_then(|v| v.as_str()) {+ texts.push(s.to_string());+ }+ if let Some(s) = pr.get("body").and_then(|v| v.as_str()) {+ texts.push(s.to_string());+ }+ if let Some(s) = pr+ .get("head")+ .and_then(|h| h.get("ref"))+ .and_then(|v| v.as_str())+ {+ texts.push(s.to_string());+ }+ }++ texts+ }}/// Known GitHub webhook event types we handle.diff --git a/rust/cloud-storage/github/src/domain/models/test.rs b/rust/cloud-storage/github/src/domain/models/test.rsindex e73196c286..dfbcda6163 100644--- a/rust/cloud-storage/github/src/domain/models/test.rs+++ b/rust/cloud-storage/github/src/domain/models/test.rs@@ -112,6 +112,102 @@ fn extract_multiple_in_sentence() {assert_eq!(ids[1].short_uuid, "bbb222");}+// ---------------------------------------------------------------------------+// ValidatedGithubWebhookEvent::pull_number / repo_owner / repo_name / installation_id+// ---------------------------------------------------------------------------++#[test]+fn pull_number_from_pull_request() {+ let event = ValidatedGithubWebhookEvent::new(+ "pull_request".to_string(),+ serde_json::json!({+ "pull_request": { "number": 42 }+ }),+ );+ assert_eq!(event.pull_number(), Some(42));+}++#[test]+fn pull_number_from_issue() {+ let event = ValidatedGithubWebhookEvent::new(+ "issue_comment".to_string(),+ serde_json::json!({+ "issue": { "number": 99 }+ }),+ );+ assert_eq!(event.pull_number(), Some(99));+}++#[test]+fn pull_number_prefers_pull_request_over_issue() {+ let event = ValidatedGithubWebhookEvent::new(+ "pull_request".to_string(),+ serde_json::json!({+ "pull_request": { "number": 1 },+ "issue": { "number": 2 }+ }),+ );+ assert_eq!(event.pull_number(), Some(1));+}++#[test]+fn pull_number_missing() {+ let event =+ ValidatedGithubWebhookEvent::new("ping".to_string(), serde_json::json!({"zen": "hello"}));+ assert_eq!(event.pull_number(), None);+}++#[test]+fn repo_owner_present() {+ let event = ValidatedGithubWebhookEvent::new(+ "pull_request".to_string(),+ serde_json::json!({+ "repository": { "owner": { "login": "my-org" }, "name": "my-repo" }+ }),+ );+ assert_eq!(event.repo_owner(), Some("my-org"));+}++#[test]+fn repo_owner_missing() {+ let event = ValidatedGithubWebhookEvent::new("pull_request".to_string(), serde_json::json!({}));+ assert_eq!(event.repo_owner(), None);+}++#[test]+fn repo_name_present() {+ let event = ValidatedGithubWebhookEvent::new(+ "pull_request".to_string(),+ serde_json::json!({+ "repository": { "name": "cool-repo", "owner": { "login": "x" } }+ }),+ );+ assert_eq!(event.repo_name(), Some("cool-repo"));+}++#[test]+fn repo_name_missing() {+ let event = ValidatedGithubWebhookEvent::new("pull_request".to_string(), serde_json::json!({}));+ assert_eq!(event.repo_name(), None);+}++#[test]+fn installation_id_present() {+ let event = ValidatedGithubWebhookEvent::new(+ "pull_request".to_string(),+ serde_json::json!({+ "installation": { "id": 12345 }+ }),+ );+ assert_eq!(event.installation_id(), Some(12345));+}++#[test]+fn installation_id_missing() {+ let event = ValidatedGithubWebhookEvent::new("pull_request".to_string(), serde_json::json!({}));+ assert_eq!(event.installation_id(), None);+}+// ---------------------------------------------------------------------------// GithubWebhookEventType::from_event_header// ---------------------------------------------------------------------------@@ -241,3 +337,92 @@ fn extract_text_unknown_event() {let texts = event.extract_searchable_text();assert!(texts.is_empty());}++// ---------------------------------------------------------------------------+// ValidatedGithubWebhookEvent::extract_pr_context_text+// ---------------------------------------------------------------------------++#[test]+fn pr_context_empty_for_pull_request_event() {+ let payload = serde_json::json!({+ "action": "opened",+ "pull_request": {+ "title": "fixes MACRO-abc123",+ "body": "body text",+ "head": { "ref": "feature/macro-abc123" }+ }+ });+ let event = ValidatedGithubWebhookEvent::new("pull_request".to_string(), payload);+ assert!(event.extract_pr_context_text().is_empty());+}++#[test]+fn pr_context_from_issue_comment() {+ let payload = serde_json::json!({+ "action": "created",+ "issue": {+ "title": "PR title with MACRO-abc123",+ "body": "PR body with MACRO-def456",+ "pull_request": {},+ "head": { "ref": "feature/macro-ghi789" }+ },+ "comment": {+ "body": "Fixes MACRO-abc123"+ }+ });+ let event = ValidatedGithubWebhookEvent::new("issue_comment".to_string(), payload);+ let texts = event.extract_pr_context_text();+ assert_eq!(texts.len(), 3);+ assert_eq!(texts[0], "PR title with MACRO-abc123");+ assert_eq!(texts[1], "PR body with MACRO-def456");+ assert_eq!(texts[2], "feature/macro-ghi789");+}++#[test]+fn pr_context_from_review() {+ let payload = serde_json::json!({+ "action": "submitted",+ "pull_request": {+ "title": "MACRO-abc123 fix",+ "body": null,+ "head": { "ref": "main" }+ },+ "review": {+ "body": "Relates to MACRO-abc123"+ }+ });+ let event = ValidatedGithubWebhookEvent::new("pull_request_review".to_string(), payload);+ let texts = event.extract_pr_context_text();+ assert_eq!(texts.len(), 2);+ assert_eq!(texts[0], "MACRO-abc123 fix");+ assert_eq!(texts[1], "main");+}++#[test]+fn pr_context_from_review_comment() {+ let payload = serde_json::json!({+ "action": "created",+ "pull_request": {+ "title": "MACRO-abc123 fix",+ "body": "details",+ "head": { "ref": "feature/macro-abc123" }+ },+ "comment": {+ "body": "This line relates to MACRO-abc123"+ }+ });+ let event =+ ValidatedGithubWebhookEvent::new("pull_request_review_comment".to_string(), payload);+ let texts = event.extract_pr_context_text();+ assert_eq!(texts.len(), 3);+ assert_eq!(texts[0], "MACRO-abc123 fix");+ assert_eq!(texts[1], "details");+ assert_eq!(texts[2], "feature/macro-abc123");+}++#[test]+fn pr_context_empty_for_unknown_event() {+ let payload = serde_json::json!({"zen": "Keep it logically awesome."});+ let event = ValidatedGithubWebhookEvent::new("ping".to_string(), payload);+ assert!(event.extract_pr_context_text().is_empty());+}diff --git a/rust/cloud-storage/github/src/domain/ports/sync_client.rs b/rust/cloud-storage/github/src/domain/ports/sync_client.rsindex a3658ccb6a..2011c837bc 100644--- a/rust/cloud-storage/github/src/domain/ports/sync_client.rs+++ b/rust/cloud-storage/github/src/domain/ports/sync_client.rs@@ -15,4 +15,23 @@ pub trait GithubSyncClient: Send + Sync + 'static {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/mod.rs b/rust/cloud-storage/github/src/domain/service/mod.rsindex b9fb5dc6d7..fab784e299 100644--- a/rust/cloud-storage/github/src/domain/service/mod.rs+++ b/rust/cloud-storage/github/src/domain/service/mod.rs@@ -43,7 +43,8 @@ mod sync_impl {},ports::{GithubSyncClient, GithubSyncService},};- use documents::domain::ports::DocumentService;+ use documents::domain::{models::DocumentError, ports::DocumentService};+ use entity_access::domain::models::ViewAccessLevel;use hmac::{Hmac, Mac};use sha2::Sha256;use std::sync::Arc;@@ -55,7 +56,7 @@ mod sync_impl {config: super::GithubSyncConfig,#[allow(dead_code)]document_service: Arc<D>,- client: C,+ pub(crate) client: C,}impl<D: DocumentService, C: GithubSyncClient> GithubSyncServiceImpl<D, C> {@@ -119,15 +120,151 @@ mod sync_impl {return Ok(());}- for task_id in &task_ids {+ // Filter out task IDs already present in the PR context (title, body, branch)+ // so that e.g. a comment saying "Fixes MACRO-X" on a PR already titled MACRO-X+ // does not trigger a duplicate association.+ let pr_context = webhook_event.extract_pr_context_text().join(" ");+ let existing_task_ids: std::collections::HashSet<_> =+ MacroTaskId::extract_from_text(&pr_context)+ .into_iter()+ .collect();++ let new_task_ids: Vec<_> = task_ids+ .into_iter()+ .filter(|id| !existing_task_ids.contains(id))+ .collect();++ if new_task_ids.is_empty() {+ tracing::debug!(+ event_type=?event_type,+ "all task IDs already present in PR context, skipping"+ );+ return Ok(());+ }++ // Acquire an installation token and fetch existing PR comments once,+ // so we can check for duplicates without an API call per task.+ let pr_meta = match (+ webhook_event.installation_id(),+ webhook_event.repo_owner(),+ webhook_event.repo_name(),+ webhook_event.pull_number(),+ ) {+ (Some(installation_id), Some(owner), Some(repo), Some(pull_number)) => {+ match self+ .generate_installation_access_token(installation_id)+ .await+ {+ Ok(token) => {+ let existing_comments = self+ .client+ .list_pr_comments(&token.token, owner, repo, pull_number)+ .await+ .inspect_err(|e| {+ tracing::error!(error=?e, "failed to list PR comments");+ })+ .unwrap_or_default();+ Some((+ token,+ owner.to_string(),+ repo.to_string(),+ pull_number,+ existing_comments,+ ))+ }+ Err(e) => {+ tracing::error!(+ error=?e,+ "failed to generate installation access token for PR comment"+ );+ None+ }+ }+ }+ _ => {+ tracing::warn!("missing PR metadata, cannot post comments");+ None+ }+ };++ for task_id in &new_task_ids {match task_id.to_uuid() {Ok(uuid) => {tracing::info!(- task_id=%task_id,- uuid=%uuid,- event_type=?event_type,- "detected macro task ID in github event"+ task_id=%task_id,+ uuid=%uuid,+ event_type=?event_type,+ "detected potential macro task ID in github event",+ );++ // SAFETY: This is ok as we are only using the preview information of the+ // document+ let entity_access = entity_access::domain::models::EntityAccessReceipt::<+ ViewAccessLevel,+ >::dangerously_assert_internal_user(+ &uuid.to_string(),+ entity_access::domain::models::EntityType::Document,);++ match self.document_service.get_document(entity_access).await {+ Ok(document) => {+ // converting to string here to avoid needing to bring models crate+ // into github crate+ if let Some(sub_type) = document.document_metadata.sub_type+ && sub_type.to_string() == "task"+ {+ tracing::info!(task_id=%uuid, "task found");++ if let Some((+ ref token,+ ref owner,+ ref repo,+ pull_number,+ ref existing_comments,+ )) = pr_meta+ {+ let doc_name = &document.document_metadata.document_name;+ let doc_id = &document.document_metadata.document_id;+ let comment_body =+ create_macro_task_comment_link(doc_name, doc_id);++ // Skip if we already posted a comment linking to this task+ let task_link = format!("/app/task/{doc_id})");+ if existing_comments.iter().any(|c| c.contains(&task_link))+ {+ tracing::debug!(+ task_id=%uuid,+ "PR already has a comment linking to this task, skipping"+ );+ continue;+ }++ self.client+ .create_pr_comment(+ &token.token,+ owner,+ repo,+ pull_number,+ &comment_body,+ )+ .await+ .inspect_err(|e| {+ tracing::error!(+ error=?e,+ "failed to create PR comment"+ );+ })+ .ok();+ }++ // TODO: update task status based on event+ }+ }+ Err(e) => match e {+ DocumentError::NotFound(_) => (),+ _ => tracing::error!(error=?e, "unable to get document"),+ },+ }}Err(e) => {tracing::warn!(@@ -324,5 +461,16 @@ mod link_impl {}}+/// Creates a macro task comment given the document name and id+fn create_macro_task_comment_link(name: &str, id: &str) -> String {+ let url = match macro_env::Environment::new_or_prod() {+ macro_env::Environment::Production => "https://macro.com/app/task",+ macro_env::Environment::Develop => "https://dev.macro.com/app/task",+ macro_env::Environment::Local => "http://localhost:3000/app/task",+ };++ format!("[{name}]({url}/{id})")+}+#[cfg(feature = "link")]pub use link_impl::*;diff --git a/rust/cloud-storage/github/src/domain/service/test.rs b/rust/cloud-storage/github/src/domain/service/test.rsindex 5e5dd51040..5a0c858d7a 100644--- a/rust/cloud-storage/github/src/domain/service/test.rs+++ b/rust/cloud-storage/github/src/domain/service/test.rs@@ -1,9 +1,10 @@-use std::sync::Arc;+use std::sync::{Arc, Mutex};use crate::domain::{models::{GithubError, GithubInstallationAccessToken, ValidatedGithubWebhookEvent},ports::{GithubSyncClient, GithubSyncService},};+use document_sub_type::DocumentSubType;use documents::domain::{models::{CreateDocumentRepoArgs, DocumentError, LocationQueryParams},ports::DocumentService,@@ -11,14 +12,72 @@ use documents::domain::{use entity_access::domain::models::{EntityAccessReceipt, OwnerAccessLevel, ViewAccessLevel};use macro_user_id::user_id::MacroUserIdStr;use model::document::{- DocumentBasic,+ DocumentBasic, DocumentMetadata,response::{CreateDocumentResponseData, GetDocumentResponseData, LocationResponseV3},};+use models_permissions::share_permission::access_level::AccessLevel;use super::*;+/// UUID that corresponds to the short ID `2BuyvtY3aeEvHx4uG8iD51`.+const KNOWN_TASK_UUID: &str = "0d0dc589-f301-43f1-8b11-4ab448ca4bb4";++/// SAFETY: This is used for testing only+/// Minimal RSA private key used only for test JWT signing.+const TEST_PEM: &str = "-----BEGIN RSA PRIVATE KEY-----+MIIEogIBAAKCAQEAky4t+NMylQ8TEjJIKciwvjKWM+5EzSXDkvc+dlNN2g0/wRsr+CTkFE9tQdEpJASbUz8+TRnExM8rbAB3p0tAyhAino2UDYvMRCBH5tGIBxKAPejZ2+pEv63Gzk7xAlbIKyoOqdf/VUs5rNOsiB+l6/0Dbi2nBXFEjbQTNt33LOY6Smqu5f+tcvN9gxHMr+m+vhnuUraL39sP0AWEhml/aw+LLIPlO1Cfp/on0sxRGmd0bhqTVWa+o3fVqp8xqopQ3nCkZaYu6EUIzdg/ioktPEgY3kul/IS2QvJAfLAmi20/ahMLXJ+v+izWM11Qs4jwfjKDxtXBgU70bv3WMC4aaU6o7JQIDAQABAoIBAHXS5UiqQncj3z+U+80JIAH3y313pZDja/4s61U1CeTOTobNEvZofhJoV232NLo52eK14Xk1pNlthDRs1+10dGFvquNw3OQvzG256bTUyDnSi8fkd3LFlw3f3ySv+67ErHApth1v5l9w3lYmCp+vawih+n21nrKrlt1y9iRhGb6cJFBOsF8lmcFo9ijEzbRyaW+ou8J0ty9GNuwioET+RaimVOo0nct0lrN4A269C+LqHLRUpj2MdxYEH4+1ziSCRDhCIQhPxd0ylpcXVEYP+XubG5Kad8bueXn9HPtvkhxJJ0P9rD0M6+enPh5CdFPRg1qQchsoqSvRDxN4kwf5k+XzbLw8ECgYEAxDQrvwDaGDMpcMrNaxtyatUfLi4uuinDNYuK+45XqMSWKXehINMc+5bva0WBT3brKAdAoDRmZtfDiVvwc6Z59/WBSh+Zq29iLftazUhgCLejWFdIVO/SE+vAx6v3Ctyl0XgrkkV2wtKtpj9T8EU+8O9HnduP075VXrMmOwrh8/qbECgYEAwAkz+UG1fTs29BIbtAXauqhp14QM+J91viSQ7kzRIyElxp7S9IkAWWzei5K4piJGxBGBg+QwgviN0cpK8URtfFIXQijzcYMwKhf0RqPrX9Kwh+9FGHcK0SHCx3JMdzkhtNrkR3+1w+cjhP3VqsoZo/+reT7Wy6E4FlcrY6Rbo2qkbUCgYBZJiNibC6spEKGH3/q1NPO+Ovwp7Y4JxIQQRlFmL60g4AIi4VpzIbmVoR+x1wUEUKUM4dnw6drv0n3lbDRu6jbw+891MJqQTNHddsIxWFtaWqZ7s10ISte3BzCHR7o7ozheqrBkZJ+v19rlIa9O5l3vC+FcVrEpUuhTWS9b0HwOcaYQKBgCuOqq32cOS9876gIAfx9IIuyEgGZUXDizXvGvgz+psKPLhFdBH1NTgTYpMD74/3PFfipJ4xsweNoS8Pq1k2PSW5iGiij1YBUe28ThIm++27K0FZ+zEmZzSyVKzKdx+fvM55y8ePY120u6qaJl5h8FUD3/LygqcAc3HbdcHA6Y+YXT1AoGAUyOZ7RPz8dLHWMA0+bRM4XGNxbyIjULKC/Fjf9bM3GIUWG8klxmBkCQJ+MEt9yPb3VfwFUyBSNJt4C6zDrnd+62oT+A9aJHJcUDUjqdBsmZamDu7xBAeLGxsn+sNRx7TF4iOEBkdJgBUoY4X/rZ+51FQOrdZGqeWo+8TjBhMQN7b4=+-----END RSA PRIVATE KEY-----";+struct StubDocumentService;+impl StubDocumentService {+ fn task_metadata(document_id: &str) -> DocumentMetadata {+ DocumentMetadata {+ document_id: document_id.to_string(),+ document_version_id: 1,+ owner: MacroUserIdStr::try_from_email("[email protected]").unwrap(),+ document_name: "My Task".to_string(),+ file_type: Some("md".to_string()),+ sha: None,+ project_id: None,+ project_name: None,+ branched_from_id: None,+ branched_from_version_id: None,+ document_family_id: None,+ document_bom: None,+ modification_data: None,+ created_at: None,+ updated_at: None,+ deleted_at: None,+ sub_type: Some(DocumentSubType::Task),+ }+ }+}+impl DocumentService for StubDocumentService {async fn internal_get_basic_document(&self,@@ -28,9 +87,18 @@ impl DocumentService for StubDocumentService {}async fn get_document(&self,- _receipt: EntityAccessReceipt<ViewAccessLevel>,+ receipt: EntityAccessReceipt<ViewAccessLevel>,) -> Result<GetDocumentResponseData, DocumentError> {- unimplemented!()+ let document_id = receipt.entity().entity_id.clone();+ if document_id == KNOWN_TASK_UUID {+ Ok(GetDocumentResponseData {+ document_metadata: Self::task_metadata(&document_id),+ user_access_level: AccessLevel::Owner,+ view_location: None,+ })+ } else {+ Err(DocumentError::NotFound(document_id))+ }}async fn get_document_location(&self,@@ -63,7 +131,30 @@ impl DocumentService for StubDocumentService {}}-struct StubSyncClient;+/// Recorded PR comment call.+#[derive(Debug, Clone)]+struct PrCommentCall {+ owner: String,+ repo: String,+ pull_number: u64,+ body: String,+}++struct StubSyncClient {+ pr_comments: Mutex<Vec<PrCommentCall>>,+}++impl StubSyncClient {+ fn new() -> Self {+ Self {+ pr_comments: Mutex::new(Vec::new()),+ }+ }++ fn pr_comments(&self) -> Vec<PrCommentCall> {+ self.pr_comments.lock().unwrap().clone()+ }+}impl GithubSyncClient for StubSyncClient {async fn generate_installation_access_token(@@ -71,7 +162,43 @@ impl GithubSyncClient for StubSyncClient {_jwt: &str,_installation_id: u64,) -> Result<GithubInstallationAccessToken, GithubError> {- unimplemented!()+ Ok(GithubInstallationAccessToken {+ token: "test-token".to_string(),+ expires_at: "2099-01-01T00:00:00Z".to_string(),+ })+ }++ async fn create_pr_comment(+ &self,+ _access_token: &str,+ owner: &str,+ repo: &str,+ pull_number: u64,+ body: &str,+ ) -> Result<(), GithubError> {+ self.pr_comments.lock().unwrap().push(PrCommentCall {+ owner: owner.to_string(),+ repo: repo.to_string(),+ pull_number,+ body: body.to_string(),+ });+ Ok(())+ }++ async fn list_pr_comments(+ &self,+ _access_token: &str,+ _owner: &str,+ _repo: &str,+ _pull_number: u64,+ ) -> Result<Vec<String>, GithubError> {+ Ok(self+ .pr_comments+ .lock()+ .unwrap()+ .iter()+ .map(|c| c.body.clone())+ .collect())}}@@ -80,11 +207,11 @@ fn make_sync_service() -> GithubSyncServiceImpl<StubDocumentService, StubSyncCliGithubSyncConfig {webhook_secret: "test-webhook-secret".to_string(),github_sync_app_url: "test".to_string(),- sync_app_pem: "test-sync-app-pem".to_string(),+ sync_app_pem: TEST_PEM.to_string(),sync_app_client_id: "test-sync-app-client-id".to_string(),},Arc::new(StubDocumentService),- StubSyncClient,+ StubSyncClient::new(),)}@@ -96,15 +223,31 @@ async fn pr_with_task_id_in_title() {serde_json::json!({"action": "opened","pull_request": {+ "number": 42,"title": "fixes MACRO-2BuyvtY3aeEvHx4uG8iD51","body": null,"head": { "ref": "feature/some-branch" }- }+ },+ "repository": {+ "name": "my-repo",+ "owner": { "login": "my-org" }+ },+ "installation": { "id": 12345 }}),);let result = service.process_webhook_event(&event).await;assert!(result.is_ok());++ let comments = service.client.pr_comments();+ assert_eq!(comments.len(), 1);+ assert_eq!(comments[0].owner, "my-org");+ assert_eq!(comments[0].repo, "my-repo");+ assert_eq!(comments[0].pull_number, 42);+ assert_eq!(+ comments[0].body,+ format!("[My Task](https://macro.com/app/task/{KNOWN_TASK_UUID})")+ );}#[tokio::test]@@ -115,15 +258,25 @@ async fn pr_with_task_id_in_branch_name() {serde_json::json!({"action": "opened","pull_request": {+ "number": 7,"title": "some feature","body": "no task ids here","head": { "ref": "macro-2BuyvtY3aeEvHx4uG8iD51" }- }+ },+ "repository": {+ "name": "my-repo",+ "owner": { "login": "my-org" }+ },+ "installation": { "id": 12345 }}),);let result = service.process_webhook_event(&event).await;assert!(result.is_ok());++ let comments = service.client.pr_comments();+ assert_eq!(comments.len(), 1);+ assert_eq!(comments[0].pull_number, 7);}#[tokio::test]@@ -133,14 +286,29 @@ async fn issue_comment_with_task_id() {"issue_comment".to_string(),serde_json::json!({"action": "created",+ "issue": {+ "number": 99,+ "title": "some issue",+ "body": null,+ "head": { "ref": "main" }+ },"comment": {"body": "fixes MACRO-2BuyvtY3aeEvHx4uG8iD51"- }+ },+ "repository": {+ "name": "my-repo",+ "owner": { "login": "my-org" }+ },+ "installation": { "id": 12345 }}),);let result = service.process_webhook_event(&event).await;assert!(result.is_ok());++ let comments = service.client.pr_comments();+ assert_eq!(comments.len(), 1);+ assert_eq!(comments[0].pull_number, 99);}#[tokio::test]@@ -200,14 +368,29 @@ async fn pull_request_review_with_task_id() {"pull_request_review".to_string(),serde_json::json!({"action": "submitted",+ "pull_request": {+ "number": 10,+ "title": "some PR",+ "body": null,+ "head": { "ref": "main" }+ },"review": {"body": "Approved, relates to MACRO-2BuyvtY3aeEvHx4uG8iD51"- }+ },+ "repository": {+ "name": "my-repo",+ "owner": { "login": "my-org" }+ },+ "installation": { "id": 12345 }}),);let result = service.process_webhook_event(&event).await;assert!(result.is_ok());++ let comments = service.client.pr_comments();+ assert_eq!(comments.len(), 1);+ assert_eq!(comments[0].pull_number, 10);}#[tokio::test]@@ -226,3 +409,138 @@ async fn pull_request_review_comment_with_task_id() {let result = service.process_webhook_event(&event).await;assert!(result.is_ok());}++// ---------------------------------------------------------------------------+// Deduplication: bot already posted a comment linking to the same task+// ---------------------------------------------------------------------------++#[tokio::test]+async fn duplicate_comment_not_posted_when_bot_already_commented() {+ let service = make_sync_service();++ let make_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" }+ },+ "repository": {+ "name": "my-repo",+ "owner": { "login": "my-org" }+ },+ "installation": { "id": 12345 }+ }),+ )+ };++ // First event — comment should be posted+ let event = make_event();+ service.process_webhook_event(&event).await.unwrap();+ assert_eq!(service.client.pr_comments().len(), 1);++ // Second event with same task ID — should NOT post a duplicate+ let event = make_event();+ service.process_webhook_event(&event).await.unwrap();+ assert_eq!(service.client.pr_comments().len(), 1);+}++// ---------------------------------------------------------------------------+// Deduplication: comment mentions task ID already in PR context+// ---------------------------------------------------------------------------++#[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(+ "issue_comment".to_string(),+ serde_json::json!({+ "action": "created",+ "issue": {+ "title": "fixes MACRO-abc123",+ "body": null,+ "head": { "ref": "main" }+ },+ "comment": {+ "body": "Fixes MACRO-abc123"+ }+ }),+ );++ let result = service.process_webhook_event(&event).await;+ assert!(result.is_ok());+}++#[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+ let event = ValidatedGithubWebhookEvent::new(+ "issue_comment".to_string(),+ serde_json::json!({+ "action": "created",+ "issue": {+ "title": "fixes MACRO-abc123",+ "body": null,+ "head": { "ref": "main" }+ },+ "comment": {+ "body": "Also fixes MACRO-def456"+ }+ }),+ );++ let result = service.process_webhook_event(&event).await;+ assert!(result.is_ok());+}++#[tokio::test]+async fn review_duplicate_task_id_skipped() {+ let service = make_sync_service();+ // PR title already has the task ID, review body repeats it+ let event = ValidatedGithubWebhookEvent::new(+ "pull_request_review".to_string(),+ serde_json::json!({+ "action": "submitted",+ "pull_request": {+ "title": "MACRO-abc123 fix",+ "body": null,+ "head": { "ref": "main" }+ },+ "review": {+ "body": "Approved, relates to MACRO-abc123"+ }+ }),+ );++ let result = service.process_webhook_event(&event).await;+ assert!(result.is_ok());+}++#[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)+ let event = ValidatedGithubWebhookEvent::new(+ "pull_request_review_comment".to_string(),+ serde_json::json!({+ "action": "created",+ "pull_request": {+ "title": "some fix",+ "body": null,+ "head": { "ref": "feature/macro-abc123" }+ },+ "comment": {+ "body": "Relates to MACRO-abc123 and MACRO-def456"+ }+ }),+ );++ let result = service.process_webhook_event(&event).await;+ assert!(result.is_ok());+}diff --git a/rust/cloud-storage/github/src/outbound/github_sync_client.rs b/rust/cloud-storage/github/src/outbound/github_sync_client.rsindex 90fde1b5cb..0758fd1f89 100644--- a/rust/cloud-storage/github/src/outbound/github_sync_client.rs+++ b/rust/cloud-storage/github/src/outbound/github_sync_client.rs@@ -50,4 +50,84 @@ impl GithubSyncClient for GithubSyncClientImpl {Ok(token)}++ #[tracing::instrument(skip(self, access_token, body), err)]+ async fn create_pr_comment(+ &self,+ access_token: &str,+ owner: &str,+ repo: &str,+ pull_number: u64,+ body: &str,+ ) -> Result<(), GithubError> {+ let response = self+ .client+ .post(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")+ .json(&serde_json::json!({ "body": body }))+ .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 create PR comment (status {status}): {error_body}"+ )));+ }++ 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())+ }}