Skip to content

armgit / macro

Public Imported from GitHub
0

Macro is a unified workspace for teams: email, chat, docs, tasks, agents, calls, and CRM — @-linked together with shared AI memory.

feat(github): Better tracing and event handling (#1787)

Will Hutchinson8e463d80c459
diff --git a/infra/stacks/cloud-storage-service/index.ts b/infra/stacks/cloud-storage-service/index.ts
index 93590e0955..3d3560fb58 100644
--- a/infra/stacks/cloud-storage-service/index.ts
+++ b/infra/stacks/cloud-storage-service/index.ts
@@ -317,7 +317,7 @@ const cloudStorageService = new CloudStorageService(
},
{
name: 'RUST_LOG',
- value: 'info',
+ value: 'info,github=trace',
},
{
name: 'DOCUMENT_STORAGE_BUCKET',
diff --git a/rust/cloud-storage/CLAUDE.md b/rust/cloud-storage/CLAUDE.md
index c7d6aa6a38..d81c37ccb6 100644
--- a/rust/cloud-storage/CLAUDE.md
+++ b/rust/cloud-storage/CLAUDE.md
@@ -297,7 +297,7 @@ This keeps implementation files focused and makes tests easier to locate and mai
### Tracing
-- Include `err` when adding the `tracing::instrument` attribute to functions. Never include `level = "info"`.
+- Include `err` when adding the `tracing::instrument` attribute to functions that return `Result`. Do not include `err` on functions that return `Option`, `()`, or other non-`Result` types. Never include `level = "info"`.
- When including an error with a log, include it like so: `tracing::error!(error=?e, "error msg");`
don't inject it directly into the error message.
- Prefer using `.inspect_err` instead of `if let Err(e)` in order to do logging.
diff --git a/rust/cloud-storage/github/src/domain/service/link.rs b/rust/cloud-storage/github/src/domain/service/link.rs
new file mode 100644
index 0000000000..7259dfd5ac
--- /dev/null
+++ b/rust/cloud-storage/github/src/domain/service/link.rs
@@ -0,0 +1,153 @@
+//! Github Link Service implemenation
+
+use chrono::Utc;
+use macro_user_id::{
+ lowercased::Lowercase,
+ user_id::{MacroUserId, MacroUserIdStr},
+};
+
+use crate::domain::{
+ models::{GithubError, GithubLink},
+ ports::{Auth, GithubLinkService, GithubOauth, GithubRepo},
+};
+
+/// Github link config
+#[derive(Debug)]
+pub struct GithubLinkConfig {
+ /// The github application client id
+ pub client_id: String,
+ /// The github application client secret
+ pub client_secret: String,
+ /// The id of the github identity provider in fusionauth
+ pub idp_id: String,
+}
+
+/// The concrete github link service implementation.
+pub struct GithubLinkServiceImpl<R: GithubRepo, U: GithubOauth, F: Auth> {
+ repo: R,
+ oauth: U,
+ auth: F,
+ config: super::GithubLinkConfig,
+}
+
+impl<R: GithubRepo, U: GithubOauth, F: Auth> GithubLinkServiceImpl<R, U, F> {
+ /// Create a new github link service.
+ pub fn new(repo: R, oauth: U, auth: F, config: super::GithubLinkConfig) -> Self {
+ Self {
+ repo,
+ oauth,
+ auth,
+ config,
+ }
+ }
+}
+
+impl<R: GithubRepo, U: GithubOauth, F: Auth> GithubLinkService for GithubLinkServiceImpl<R, U, F> {
+ #[tracing::instrument(skip(self), err)]
+ fn construct_oauth_url<T: serde::Serialize + std::fmt::Debug + 'static>(
+ &self,
+ redirect_uri: &str,
+ state: T,
+ ) -> Result<String, GithubError> {
+ self.oauth
+ .construct_oauth_url(&self.config.client_id, redirect_uri, state)
+ .map_err(|e| GithubError::Internal(e.into()))
+ }
+
+ #[tracing::instrument(skip(self), err)]
+ async fn link_user(
+ &self,
+ user_id: &MacroUserId<Lowercase<'static>>,
+ fusionauth_user_id: &uuid::Uuid,
+ in_progess_link_id: &uuid::Uuid,
+ redirect_uri: &str,
+ code: &str,
+ ) -> Result<GithubLink, GithubError> {
+ let tokens = self
+ .oauth
+ .exchange_oauth_code_for_tokens(
+ &self.config.client_id,
+ &self.config.client_secret,
+ redirect_uri,
+ code,
+ )
+ .await
+ .map_err(|e| GithubError::Internal(e.into()))?;
+
+ let user_info = self
+ .oauth
+ .get_user_info(&tokens.access_token)
+ .await
+ .map_err(|e| GithubError::Internal(e.into()))?;
+
+ tracing::trace!(user_info=?user_info, "got user info");
+
+ // Check if Github account is already linked to a different user
+ match self
+ .repo
+ .get_github_link_by_github_user_id(&user_info.id.to_string())
+ .await
+ {
+ Ok(link) => {
+ if !link.macro_id.0.eq(user_id) {
+ return Err(GithubError::AccountAlreadyLinked);
+ }
+ }
+ Err(e) => {
+ let err: anyhow::Error = e.into();
+ // We should only error if the error is something other
+ // than the link not existing
+ if !err.to_string().contains("no rows returned") {
+ return Err(GithubError::Internal(err));
+ }
+ }
+ }
+
+ self.auth
+ .link_user(
+ fusionauth_user_id,
+ &self.config.idp_id,
+ &user_info.id.to_string(),
+ &user_info.login,
+ &tokens.access_token,
+ )
+ .await
+ .map_err(|e| GithubError::Internal(e.into()))?;
+
+ tracing::trace!("linked auth user");
+
+ // create github link
+ let link = GithubLink {
+ id: macro_uuid::generate_uuid_v7(),
+ macro_id: MacroUserIdStr(user_id.clone()),
+ fusionauth_user_id: *fusionauth_user_id,
+ github_username: user_info.login.clone(),
+ github_user_id: user_info.id.to_string(),
+ created_at: Utc::now(),
+ updated_at: Utc::now(),
+ };
+
+ tracing::debug!(
+ fusionauth_user_id=%fusionauth_user_id,
+ github_user_id=%user_info.id,
+ github_username=%user_info.login,
+ "creating github_links record"
+ );
+
+ self.repo
+ .insert_github_link(&link)
+ .await
+ .map_err(|e| GithubError::Internal(e.into()))?;
+
+ tracing::trace!("successfully linked github account");
+
+ // SAFETY: this is ok to fail as we have an auto cleanup job for this table
+ let _ = self
+ .repo
+ .delete_in_progress_user_link(in_progess_link_id)
+ .await
+ .inspect_err(|e| tracing::error!(error=?e, "unable to delete in progress link id"));
+
+ Ok(link)
+ }
+}
diff --git a/rust/cloud-storage/github/src/domain/service/mod.rs b/rust/cloud-storage/github/src/domain/service/mod.rs
index 0c5d013d22..c55d93beec 100644
--- a/rust/cloud-storage/github/src/domain/service/mod.rs
+++ b/rust/cloud-storage/github/src/domain/service/mod.rs
@@ -1,509 +1,13 @@
//! Github service implementation.
-#[cfg(test)]
-mod test;
-
-use crate::domain::models::GithubError;
-
-/// Github sync config
-#[cfg(feature = "sync")]
-#[derive(Debug)]
-pub struct GithubSyncConfig {
- /// The webhook secret used to validate github webhook events
- pub webhook_secret: String,
- /// The url to the github sync app installation page
- pub github_sync_app_url: String,
- /// The PEM key for the github sync app
- pub sync_app_pem: String,
- /// The client id for the github sync app
- pub sync_app_client_id: String,
-}
-
-/// Github link config
-#[cfg(feature = "link")]
-#[derive(Debug)]
-pub struct GithubLinkConfig {
- /// The github application client id
- pub client_id: String,
- /// The github application client secret
- pub client_secret: String,
- /// The id of the github identity provider in fusionauth
- pub idp_id: String,
-}
-
-// ── Sync service ──────────────────────────────────────────────────────
-
#[cfg(feature = "sync")]
-mod sync_impl {
- use super::*;
- use crate::domain::{
- models::{
- GithubInstallationAccessToken, GithubWebhookEventType, MacroTaskId,
- ValidatedGithubWebhookEvent,
- },
- ports::{GithubSyncClient, GithubSyncService},
- };
- use documents::domain::{models::DocumentError, ports::DocumentService};
- use entity_access::domain::models::{EditAccessLevel, ViewAccessLevel};
- use hmac::{Hmac, Mac};
- use sha2::Sha256;
- use std::sync::Arc;
- use subtle::ConstantTimeEq;
- type HmacSha256 = Hmac<Sha256>;
-
- /// The concrete github sync service implementation.
- pub struct GithubSyncServiceImpl<D: DocumentService, C: GithubSyncClient> {
- config: super::GithubSyncConfig,
- #[allow(dead_code)]
- document_service: Arc<D>,
- pub(crate) client: C,
- }
-
- impl<D: DocumentService, C: GithubSyncClient> GithubSyncServiceImpl<D, C> {
- /// Create a new github sync service.
- pub fn new(config: super::GithubSyncConfig, document_service: Arc<D>, client: C) -> Self {
- Self {
- config,
- document_service,
- client,
- }
- }
- }
-
- impl<D: DocumentService, C: GithubSyncClient> GithubSyncService for GithubSyncServiceImpl<D, C> {
- #[tracing::instrument(skip(self, body), err)]
- async fn validate_webhook_event(
- &self,
- event_type: &str,
- signature: &str,
- body: &[u8],
- ) -> Result<ValidatedGithubWebhookEvent, GithubError> {
- let sig_bytes =
- hex::decode(signature).map_err(|_| GithubError::InvalidWebhookSignature)?;
-
- let mut mac = HmacSha256::new_from_slice(self.config.webhook_secret.as_bytes())
- .map_err(|e| GithubError::Internal(e.into()))?;
-
- mac.update(body);
- let expected = mac.finalize().into_bytes();
-
- // constant-time comparison
- if expected.as_slice().ct_eq(&sig_bytes).into() {
- Ok(ValidatedGithubWebhookEvent::new(
- event_type.to_string(),
- serde_json::from_slice(body).map_err(|e| GithubError::Internal(e.into()))?,
- ))
- } else {
- Err(GithubError::InvalidWebhookSignature)
- }
- }
-
- #[tracing::instrument(skip(self, webhook_event), err)]
- async fn process_webhook_event(
- &self,
- webhook_event: &ValidatedGithubWebhookEvent,
- ) -> Result<(), GithubError> {
- let event_type = webhook_event.parsed_event_type();
- tracing::info!(event_type=?event_type, "processing github webhook event");
-
- if let GithubWebhookEventType::Unknown(ref name) = event_type {
- tracing::debug!(event_type=%name, "skipping unknown event type");
- return Ok(());
- }
-
- let searchable_texts = webhook_event.extract_searchable_text();
- let combined = searchable_texts.join(" ");
- let all_task_ids = MacroTaskId::extract_from_text(&combined);
-
- if all_task_ids.is_empty() {
- tracing::debug!(event_type=?event_type, "no task IDs found in event");
- return Ok(());
- }
-
- // For PR events we process ALL task IDs (the PR itself is the context).
- // For comment/review events we only process task IDs that are new
- // relative to the surrounding PR context, so that e.g. a comment
- // saying "Fixes MACRO-X" on a PR already titled MACRO-X does not
- // trigger a duplicate comment.
- let is_pr_event = event_type == GithubWebhookEventType::PullRequest;
-
- let task_ids_for_comment: Vec<_> = if is_pr_event {
- all_task_ids.clone()
- } else {
- let pr_context = webhook_event.extract_pr_context_text().join(" ");
- let existing: std::collections::HashSet<_> =
- MacroTaskId::extract_from_text(&pr_context)
- .into_iter()
- .collect();
- all_task_ids
- .iter()
- .filter(|id| !existing.contains(*id))
- .cloned()
- .collect()
- };
-
- if task_ids_for_comment.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
- }
- };
-
- // Resolve task IDs to documents. We always collect doc IDs for
- // status updates, but only add to task_links if not already
- // commented (to avoid duplicate PR comments).
- let mut task_links: Vec<String> = Vec::new();
- let mut task_doc_ids: Vec<String> = Vec::new();
-
- for task_id in &task_ids_for_comment {
- let uuid = match task_id.to_uuid() {
- Ok(uuid) => uuid,
- Err(e) => {
- tracing::warn!(
- task_id=%task_id,
- error=?e,
- "failed to convert task ID to UUID"
- );
- continue;
- }
- };
-
- tracing::info!(
- 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");
- let doc_name = &document.document_metadata.document_name;
- let doc_id = &document.document_metadata.document_id;
-
- // Always track for status updates
- task_doc_ids.push(doc_id.clone());
-
- // Only add comment link if not already posted
- let already_commented = pr_meta
- .as_ref()
- .map(|(_, _, _, _, existing_comments)| {
- let task_link = format!("/app/task/{doc_id})");
- existing_comments.iter().any(|c| c.contains(&task_link))
- })
- .unwrap_or(false);
-
- if already_commented {
- tracing::debug!(
- task_id=%uuid,
- "PR already has a comment linking to this task, skipping comment"
- );
- } else {
- task_links.push(create_macro_task_comment_link(doc_name, doc_id));
- }
- }
- }
- Err(e) => match e {
- DocumentError::NotFound(_) => (),
- _ => tracing::error!(error=?e, "unable to get document"),
- },
- }
- }
-
- // Post a single comment mentioning all newly discovered tasks
- if !task_links.is_empty()
- && let Some((ref token, ref owner, ref repo, pull_number, _)) = pr_meta
- {
- let comment_body = task_links.join("\n");
- 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();
- }
-
- // Update task statuses for all resolved tasks
- if let Some(status) = webhook_event.task_status_for_event() {
- for doc_id in &task_doc_ids {
- let entity_access = entity_access::domain::models::EntityAccessReceipt::<
- EditAccessLevel,
- >::dangerously_assert_internal_user(
- doc_id,
- entity_access::domain::models::EntityType::Document,
- );
-
- self.document_service
- .update_task_status(entity_access, status)
- .await
- .inspect_err(|e| {
- tracing::error!(
- error=?e,
- doc_id=%doc_id,
- status=%status,
- "failed to update task status"
- );
- })
- .ok();
- }
- }
-
- Ok(())
- }
-
- fn get_github_sync_app_url(&self) -> &str {
- &self.config.github_sync_app_url
- }
-
- #[tracing::instrument(skip(self), err)]
- async fn generate_installation_access_token(
- &self,
- installation_id: u64,
- ) -> Result<GithubInstallationAccessToken, GithubError> {
- let now = chrono::Utc::now().timestamp() as u64;
-
- let claims = serde_json::json!({
- "iat": now - 60,
- "exp": now + (10 * 60),
- "iss": self.config.sync_app_client_id,
- });
-
- let header = jsonwebtoken::Header::new(jsonwebtoken::Algorithm::RS256);
- let encoding_key =
- jsonwebtoken::EncodingKey::from_rsa_pem(self.config.sync_app_pem.as_bytes())
- .map_err(|e| GithubError::Internal(anyhow::anyhow!("invalid PEM key: {e}")))?;
-
- let jwt = jsonwebtoken::encode(&header, &claims, &encoding_key)
- .map_err(|e| GithubError::Internal(anyhow::anyhow!("failed to encode JWT: {e}")))?;
-
- self.client
- .generate_installation_access_token(&jwt, installation_id)
- .await
- }
- }
-}
+mod sync;
#[cfg(feature = "sync")]
-pub use sync_impl::*;
-
-// ── Link service ──────────────────────────────────────────────────────
+pub use sync::*;
#[cfg(feature = "link")]
-mod link_impl {
- use super::*;
- use chrono::Utc;
- use macro_user_id::{
- lowercased::Lowercase,
- user_id::{MacroUserId, MacroUserIdStr},
- };
-
- use crate::domain::{
- models::GithubLink,
- ports::{Auth, GithubLinkService, GithubOauth, GithubRepo},
- };
-
- /// The concrete github link service implementation.
- pub struct GithubLinkServiceImpl<R: GithubRepo, U: GithubOauth, F: Auth> {
- repo: R,
- oauth: U,
- auth: F,
- config: super::GithubLinkConfig,
- }
-
- impl<R: GithubRepo, U: GithubOauth, F: Auth> GithubLinkServiceImpl<R, U, F> {
- /// Create a new github link service.
- pub fn new(repo: R, oauth: U, auth: F, config: super::GithubLinkConfig) -> Self {
- Self {
- repo,
- oauth,
- auth,
- config,
- }
- }
- }
-
- impl<R: GithubRepo, U: GithubOauth, F: Auth> GithubLinkService for GithubLinkServiceImpl<R, U, F> {
- #[tracing::instrument(skip(self), err)]
- fn construct_oauth_url<T: serde::Serialize + std::fmt::Debug + 'static>(
- &self,
- redirect_uri: &str,
- state: T,
- ) -> Result<String, GithubError> {
- self.oauth
- .construct_oauth_url(&self.config.client_id, redirect_uri, state)
- .map_err(|e| GithubError::Internal(e.into()))
- }
-
- #[tracing::instrument(skip(self), err)]
- async fn link_user(
- &self,
- user_id: &MacroUserId<Lowercase<'static>>,
- fusionauth_user_id: &uuid::Uuid,
- in_progess_link_id: &uuid::Uuid,
- redirect_uri: &str,
- code: &str,
- ) -> Result<GithubLink, GithubError> {
- let tokens = self
- .oauth
- .exchange_oauth_code_for_tokens(
- &self.config.client_id,
- &self.config.client_secret,
- redirect_uri,
- code,
- )
- .await
- .map_err(|e| GithubError::Internal(e.into()))?;
-
- let user_info = self
- .oauth
- .get_user_info(&tokens.access_token)
- .await
- .map_err(|e| GithubError::Internal(e.into()))?;
-
- tracing::trace!(user_info=?user_info, "got user info");
-
- // Check if Github account is already linked to a different user
- match self
- .repo
- .get_github_link_by_github_user_id(&user_info.id.to_string())
- .await
- {
- Ok(link) => {
- if !link.macro_id.0.eq(user_id) {
- return Err(GithubError::AccountAlreadyLinked);
- }
- }
- Err(e) => {
- let err: anyhow::Error = e.into();
- // We should only error if the error is something other
- // than the link not existing
- if !err.to_string().contains("no rows returned") {
- return Err(GithubError::Internal(err));
- }
- }
- }
-
- self.auth
- .link_user(
- fusionauth_user_id,
- &self.config.idp_id,
- &user_info.id.to_string(),
- &user_info.login,
- &tokens.access_token,
- )
- .await
- .map_err(|e| GithubError::Internal(e.into()))?;
-
- tracing::trace!("linked auth user");
-
- // create github link
- let link = GithubLink {
- id: macro_uuid::generate_uuid_v7(),
- macro_id: MacroUserIdStr(user_id.clone()),
- fusionauth_user_id: *fusionauth_user_id,
- github_username: user_info.login.clone(),
- github_user_id: user_info.id.to_string(),
- created_at: Utc::now(),
- updated_at: Utc::now(),
- };
-
- tracing::debug!(
- fusionauth_user_id=%fusionauth_user_id,
- github_user_id=%user_info.id,
- github_username=%user_info.login,
- "creating github_links record"
- );
-
- self.repo
- .insert_github_link(&link)
- .await
- .map_err(|e| GithubError::Internal(e.into()))?;
-
- tracing::trace!("successfully linked github account");
-
- // SAFETY: this is ok to fail as we have an auto cleanup job for this table
- let _ = self
- .repo
- .delete_in_progress_user_link(in_progess_link_id)
- .await
- .inspect_err(|e| tracing::error!(error=?e, "unable to delete in progress link id"));
-
- Ok(link)
- }
- }
-}
-
-/// 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})")
-}
+mod link;
#[cfg(feature = "link")]
-pub use link_impl::*;
+pub use link::*;
diff --git a/rust/cloud-storage/github/src/domain/service/sync/handle_comment.rs b/rust/cloud-storage/github/src/domain/service/sync/handle_comment.rs
new file mode 100644
index 0000000000..a99ce77f59
--- /dev/null
+++ b/rust/cloud-storage/github/src/domain/service/sync/handle_comment.rs
@@ -0,0 +1,107 @@
+//! Issue comment, PR review, and PR review comment event handlers.
+
+use crate::domain::{
+ models::{GithubError, MacroTaskId, ValidatedGithubWebhookEvent},
+ ports::GithubSyncClient,
+};
+use documents::domain::ports::DocumentService;
+use std::collections::HashSet;
+
+use super::GithubSyncServiceImpl;
+
+impl<D: DocumentService, C: GithubSyncClient> GithubSyncServiceImpl<D, 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.
+ #[tracing::instrument(skip(self, event), err)]
+ pub(crate) async fn handle_comment_event(
+ &self,
+ event: &ValidatedGithubWebhookEvent,
+ ) -> Result<(), GithubError> {
+ // Extract task IDs from the new comment/review text only
+ let 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();
+
+ 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<_>>(),
+ "extracted task IDs from comment/review text"
+ );
+
+ if new_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 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
+ } else {
+ Vec::new()
+ };
+
+ // 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<_>>(),
+ "filtered to truly new task IDs"
+ );
+
+ if truly_new.is_empty() {
+ tracing::debug!(
+ "all task IDs already present in PR context or prior comments, skipping"
+ );
+ return Ok(());
+ }
+
+ let resolved = self.resolve_tasks(&truly_new, &existing_comments).await;
+
+ if let Some(ref meta) = pr_meta {
+ self.post_task_comment(meta, &resolved.new_task_links).await;
+ }
+
+ // Only update status if the PR is open
+ if let Some(status) = event.task_status_for_event() {
+ self.update_task_statuses(&resolved.doc_ids, status).await;
+ } else {
+ tracing::trace!("no status update warranted for this event");
+ }
+
+ tracing::trace!("comment event handler complete");
+ Ok(())
+ }
+}
diff --git a/rust/cloud-storage/github/src/domain/service/sync/handle_pr.rs b/rust/cloud-storage/github/src/domain/service/sync/handle_pr.rs
new file mode 100644
index 0000000000..f02f5dc2b2
--- /dev/null
+++ b/rust/cloud-storage/github/src/domain/service/sync/handle_pr.rs
@@ -0,0 +1,192 @@
+//! PR open/edit/close event handlers.
+
+use crate::domain::{
+ models::{GithubError, MacroTaskId, ValidatedGithubWebhookEvent},
+ ports::GithubSyncClient,
+};
+use documents::domain::ports::DocumentService;
+use std::collections::HashSet;
+
+use super::GithubSyncServiceImpl;
+
+impl<D: DocumentService, C: GithubSyncClient> GithubSyncServiceImpl<D, 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,
+ event: &ValidatedGithubWebhookEvent,
+ ) -> Result<(), GithubError> {
+ let searchable_texts = event.extract_searchable_text();
+ let combined = searchable_texts.join(" ");
+ let task_ids = MacroTaskId::extract_from_text(&combined);
+
+ tracing::trace!(
+ 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_ids.is_empty() {
+ tracing::debug!("no task IDs found in PR text");
+ return Ok(());
+ }
+
+ let pr_meta = self.acquire_pr_meta(event).await;
+
+ // 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
+ } else {
+ Vec::new()
+ };
+
+ let resolved = self.resolve_tasks(&task_ids, &existing_comments).await;
+
+ if let Some(ref meta) = pr_meta {
+ self.post_task_comment(meta, &resolved.new_task_links).await;
+ }
+
+ self.update_task_statuses(&resolved.doc_ids, "In Review")
+ .await;
+
+ tracing::trace!("PR open handler complete");
+ Ok(())
+ }
+
+ /// 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".
+ #[tracing::instrument(skip(self, event), err)]
+ pub(crate) async fn handle_pr_edit(
+ &self,
+ event: &ValidatedGithubWebhookEvent,
+ ) -> 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();
+
+ tracing::trace!(
+ task_id_count = task_id_set.len(),
+ task_ids = ?task_id_set.iter().map(|t| t.to_task_id_string()).collect::<Vec<_>>(),
+ "extracted task IDs from PR text"
+ );
+
+ if task_id_set.is_empty() {
+ tracing::debug!("no task IDs found in PR text");
+ return Ok(());
+ }
+
+ let pr_meta = self.acquire_pr_meta(event).await;
+
+ // 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
+ } else {
+ Vec::new()
+ };
+
+ 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;
+
+ if let Some(ref meta) = pr_meta {
+ self.post_task_comment(meta, &resolved.new_task_links).await;
+ }
+
+ self.update_task_statuses(&resolved.doc_ids, "In Review")
+ .await;
+
+ tracing::trace!("PR edit handler complete");
+ Ok(())
+ }
+
+ /// 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).
+ #[tracing::instrument(skip(self, event), err)]
+ pub(crate) async fn handle_pr_close(
+ &self,
+ event: &ValidatedGithubWebhookEvent,
+ ) -> Result<(), GithubError> {
+ 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/branch
+ let searchable_texts = event.extract_searchable_text();
+ let combined = searchable_texts.join(" ");
+ let mut task_id_set: HashSet<MacroTaskId> = MacroTaskId::extract_from_text(&combined)
+ .into_iter()
+ .collect();
+
+ tracing::trace!(
+ pr_text_task_ids = task_id_set.len(),
+ task_ids = ?task_id_set.iter().map(|t| t.to_task_id_string()).collect::<Vec<_>>(),
+ "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);
+ }
+
+ if task_id_set.is_empty() {
+ tracing::debug!("no task IDs found anywhere for PR close event");
+ return Ok(());
+ }
+
+ 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<_>>(),
+ "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;
+
+ // No bot comment on close
+ let status = if is_merged { "Completed" } else { "Canceled" };
+ tracing::trace!(
+ status,
+ doc_count = resolved.doc_ids.len(),
+ "updating task statuses for PR close"
+ );
+ self.update_task_statuses(&resolved.doc_ids, status).await;
+
+ tracing::trace!("PR close handler complete");
+ Ok(())
+ }
+}
diff --git a/rust/cloud-storage/github/src/domain/service/sync/mod.rs b/rust/cloud-storage/github/src/domain/service/sync/mod.rs
new file mode 100644
index 0000000000..07cdd005bc
--- /dev/null
+++ b/rust/cloud-storage/github/src/domain/service/sync/mod.rs
@@ -0,0 +1,403 @@
+//! Github Sync Service implementation
+
+#[cfg(test)]
+mod test;
+
+mod handle_comment;
+mod handle_pr;
+
+use crate::domain::{
+ models::{
+ GithubError, GithubInstallationAccessToken, GithubWebhookEventType, MacroTaskId,
+ ValidatedGithubWebhookEvent,
+ },
+ ports::{GithubSyncClient, GithubSyncService},
+};
+use documents::domain::{models::DocumentError, ports::DocumentService};
+use entity_access::domain::models::{EditAccessLevel, ViewAccessLevel};
+use hmac::{Hmac, Mac};
+use sha2::Sha256;
+use std::sync::Arc;
+use subtle::ConstantTimeEq;
+
+type HmacSha256 = Hmac<Sha256>;
+
+/// Github sync config
+#[derive(Debug)]
+pub struct GithubSyncConfig {
+ /// The webhook secret used to validate github webhook events
+ pub webhook_secret: String,
+ /// The url to the github sync app installation page
+ pub github_sync_app_url: String,
+ /// The PEM key for the github sync app
+ pub sync_app_pem: String,
+ /// The client id for the github sync app
+ pub sync_app_client_id: String,
+}
+
+/// The concrete github sync service implementation.
+pub struct GithubSyncServiceImpl<D: DocumentService, C: GithubSyncClient> {
+ config: super::GithubSyncConfig,
+ #[allow(dead_code)]
+ document_service: Arc<D>,
+ pub(crate) client: C,
+}
+
+impl<D: DocumentService, C: GithubSyncClient> GithubSyncServiceImpl<D, C> {
+ /// Create a new github sync service.
+ pub fn new(config: super::GithubSyncConfig, document_service: Arc<D>, client: C) -> Self {
+ Self {
+ config,
+ document_service,
+ client,
+ }
+ }
+}
+
+/// Metadata needed to interact with a pull request via the GitHub API.
+struct PrMeta {
+ token: GithubInstallationAccessToken,
+ owner: String,
+ repo: String,
+ pull_number: u64,
+}
+
+/// Result of resolving task IDs to documents.
+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>,
+}
+
+impl<D: DocumentService, C: GithubSyncClient> GithubSyncServiceImpl<D, 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))]
+ async fn acquire_pr_meta(&self, event: &ValidatedGithubWebhookEvent) -> Option<PrMeta> {
+ let (installation_id, owner, repo, pull_number) = match (
+ event.installation_id(),
+ event.repo_owner(),
+ event.repo_name(),
+ event.pull_number(),
+ ) {
+ (Some(i), Some(o), Some(r), Some(p)) => (i, o, r, p),
+ _ => {
+ tracing::warn!("missing PR metadata, cannot post comments");
+ return None;
+ }
+ };
+
+ tracing::trace!(
+ installation_id,
+ owner,
+ repo,
+ pull_number,
+ "extracted PR metadata, generating installation token"
+ );
+
+ match self
+ .generate_installation_access_token(installation_id)
+ .await
+ {
+ Ok(token) => {
+ tracing::trace!("installation access token acquired");
+ Some(PrMeta {
+ token,
+ owner: owner.to_string(),
+ repo: repo.to_string(),
+ pull_number,
+ })
+ }
+ Err(e) => {
+ tracing::error!(
+ error=?e,
+ "failed to generate installation access token for PR comment"
+ );
+ None
+ }
+ }
+ }
+
+ /// 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 {
+ 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();
+
+ for task_id in task_ids {
+ let uuid = match task_id.to_uuid() {
+ Ok(uuid) => uuid,
+ Err(e) => {
+ tracing::warn!(
+ task_id=%task_id,
+ error=?e,
+ "failed to convert task ID to UUID"
+ );
+ continue;
+ }
+ };
+
+ tracing::trace!(task_id=%task_id, uuid=%uuid, "looking up document for task ID");
+
+ // 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) => {
+ if let Some(sub_type) = document.document_metadata.sub_type
+ && sub_type.to_string() == "task"
+ {
+ let doc_name = &document.document_metadata.document_name;
+ let doc_id = &document.document_metadata.document_id;
+ 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));
+ }
+ } else {
+ tracing::trace!(task_id=%uuid, "document found but is not a task, skipping");
+ }
+ }
+ Err(e) => match e {
+ DocumentError::NotFound(_) => {
+ tracing::trace!(task_id=%uuid, "no document found for task ID");
+ }
+ _ => tracing::error!(error=?e, "unable to get document"),
+ },
+ }
+ }
+
+ tracing::trace!(
+ resolved_count = doc_ids.len(),
+ new_link_count = new_task_links.len(),
+ "task resolution complete"
+ );
+
+ ResolvedTasks {
+ doc_ids,
+ new_task_links,
+ }
+ }
+
+ /// Post a single bot comment on the PR with all new task links.
+ #[tracing::instrument(skip(self, pr_meta, task_links))]
+ async fn post_task_comment(&self, pr_meta: &PrMeta, task_links: &[String]) {
+ if task_links.is_empty() {
+ tracing::trace!("no new task links to post");
+ return;
+ }
+
+ tracing::trace!(
+ owner = %pr_meta.owner,
+ repo = %pr_meta.repo,
+ pull_number = pr_meta.pull_number,
+ link_count = task_links.len(),
+ "posting task comment on PR"
+ );
+
+ let comment_body = task_links.join("\n");
+ self.client
+ .create_pr_comment(
+ &pr_meta.token.token,
+ &pr_meta.owner,
+ &pr_meta.repo,
+ pr_meta.pull_number,
+ &comment_body,
+ )
+ .await
+ .inspect_err(|e| {
+ tracing::error!(error=?e, "failed to create PR comment");
+ })
+ .ok();
+ }
+
+ /// Update task statuses for all resolved task doc IDs.
+ #[tracing::instrument(skip(self, doc_ids))]
+ async fn update_task_statuses(&self, doc_ids: &[String], status: &str) {
+ tracing::trace!(doc_count = doc_ids.len(), status, "updating task statuses");
+
+ for doc_id in doc_ids {
+ tracing::trace!(doc_id, status, "updating task status");
+
+ let entity_access = entity_access::domain::models::EntityAccessReceipt::<
+ EditAccessLevel,
+ >::dangerously_assert_internal_user(
+ doc_id,
+ entity_access::domain::models::EntityType::Document,
+ );
+
+ self.document_service
+ .update_task_status(entity_access, status)
+ .await
+ .inspect_err(|e| {
+ tracing::error!(
+ error=?e,
+ doc_id=%doc_id,
+ status=%status,
+ "failed to update task status"
+ );
+ })
+ .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> {
+ #[tracing::instrument(skip(self, body), err)]
+ async fn validate_webhook_event(
+ &self,
+ event_type: &str,
+ signature: &str,
+ body: &[u8],
+ ) -> Result<ValidatedGithubWebhookEvent, GithubError> {
+ let sig_bytes = hex::decode(signature).map_err(|_| GithubError::InvalidWebhookSignature)?;
+
+ let mut mac = HmacSha256::new_from_slice(self.config.webhook_secret.as_bytes())
+ .map_err(|e| GithubError::Internal(e.into()))?;
+
+ mac.update(body);
+ let expected = mac.finalize().into_bytes();
+
+ // constant-time comparison
+ if expected.as_slice().ct_eq(&sig_bytes).into() {
+ Ok(ValidatedGithubWebhookEvent::new(
+ event_type.to_string(),
+ serde_json::from_slice(body).map_err(|e| GithubError::Internal(e.into()))?,
+ ))
+ } else {
+ Err(GithubError::InvalidWebhookSignature)
+ }
+ }
+
+ #[tracing::instrument(skip(self, webhook_event), err)]
+ async fn process_webhook_event(
+ &self,
+ webhook_event: &ValidatedGithubWebhookEvent,
+ ) -> Result<(), GithubError> {
+ let event_type = webhook_event.parsed_event_type();
+ let action = webhook_event.action();
+ tracing::info!(event_type=?event_type, action, "processing github webhook event");
+
+ match event_type {
+ GithubWebhookEventType::Unknown(ref name) => {
+ tracing::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::IssueComment
+ | GithubWebhookEventType::PullRequestReview
+ | GithubWebhookEventType::PullRequestReviewComment => {
+ self.handle_comment_event(webhook_event).await
+ }
+ }
+ }
+
+ fn get_github_sync_app_url(&self) -> &str {
+ &self.config.github_sync_app_url
+ }
+
+ #[tracing::instrument(skip(self), err)]
+ async fn generate_installation_access_token(
+ &self,
+ installation_id: u64,
+ ) -> Result<GithubInstallationAccessToken, GithubError> {
+ let now = chrono::Utc::now().timestamp() as u64;
+
+ let claims = serde_json::json!({
+ "iat": now - 60,
+ "exp": now + (10 * 60),
+ "iss": self.config.sync_app_client_id,
+ });
+
+ let header = jsonwebtoken::Header::new(jsonwebtoken::Algorithm::RS256);
+ let encoding_key =
+ jsonwebtoken::EncodingKey::from_rsa_pem(self.config.sync_app_pem.as_bytes())
+ .map_err(|e| GithubError::Internal(anyhow::anyhow!("invalid PEM key: {e}")))?;
+
+ let jwt = jsonwebtoken::encode(&header, &claims, &encoding_key)
+ .map_err(|e| GithubError::Internal(anyhow::anyhow!("failed to encode JWT: {e}")))?;
+
+ self.client
+ .generate_installation_access_token(&jwt, installation_id)
+ .await
+ }
+}
+
+/// 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})")
+}
diff --git a/rust/cloud-storage/github/src/domain/service/test.rs b/rust/cloud-storage/github/src/domain/service/sync/test.rs
similarity index 76%
rename from rust/cloud-storage/github/src/domain/service/test.rs
rename to rust/cloud-storage/github/src/domain/service/sync/test.rs
index 5ec5716d65..21eea4d131 100644
--- a/rust/cloud-storage/github/src/domain/service/test.rs
+++ b/rust/cloud-storage/github/src/domain/service/sync/test.rs
@@ -172,14 +172,26 @@ 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),
}
}
@@ -224,13 +236,15 @@ impl GithubSyncClient for StubSyncClient {
_repo: &str,
_pull_number: u64,
) -> Result<Vec<String>, GithubError> {
- Ok(self
- .pr_comments
- .lock()
- .unwrap()
- .iter()
- .map(|c| c.body.clone())
- .collect())
+ 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)
}
}
@@ -256,6 +270,26 @@ fn make_sync_service_with_doc_service() -> (
(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();
@@ -806,3 +840,192 @@ async fn pr_merged_updates_status_even_when_already_commented() {
assert_eq!(status_calls[1].entity_id, KNOWN_TASK_UUID);
assert_eq!(status_calls[1].status, "Completed");
}
+
+// ---------------------------------------------------------------------------
+// New behavioral tests
+// ---------------------------------------------------------------------------
+
+#[tokio::test]
+async fn pr_close_does_not_post_comment() {
+ let (service, doc_service) = make_sync_service_with_doc_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" },
+ "merged": true
+ },
+ "repository": {
+ "name": "my-repo",
+ "owner": { "login": "my-org" }
+ },
+ "installation": { "id": 12345 }
+ }),
+ );
+
+ service.process_webhook_event(&event).await.unwrap();
+
+ // No comment posted on close
+ assert!(
+ service.client.pr_comments().is_empty(),
+ "PR close should not post a new bot comment"
+ );
+
+ // But status should still be updated
+ let status_calls = doc_service.task_status_calls();
+ assert_eq!(status_calls.len(), 1);
+ assert_eq!(status_calls[0].status, "Completed");
+}
+
+#[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")]);
+
+ 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" }
+ },
+ "repository": {
+ "name": "my-repo",
+ "owner": { "login": "my-org" }
+ },
+ "installation": { "id": 12345 }
+ }),
+ );
+
+ service.process_webhook_event(&event).await.unwrap();
+
+ // No comment posted — open doesn't search existing comments for task IDs
+ assert!(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")]);
+
+ // PR title has a different (non-existent) task, but the comment has the real one
+ let event = ValidatedGithubWebhookEvent::new(
+ "pull_request".to_string(),
+ serde_json::json!({
+ "action": "edited",
+ "pull_request": {
+ "number": 42,
+ "title": "fixes MACRO-abc123",
+ "body": null,
+ "head": { "ref": "feature/some-branch" }
+ },
+ "repository": {
+ "name": "my-repo",
+ "owner": { "login": "my-org" }
+ },
+ "installation": { "id": 12345 }
+ }),
+ );
+
+ 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(
+ "pull_request".to_string(),
+ serde_json::json!({
+ "action": "closed",
+ "pull_request": {
+ "number": 42,
+ "title": "some feature",
+ "body": null,
+ "head": { "ref": "feature/some-branch" },
+ "merged": true
+ },
+ "repository": {
+ "name": "my-repo",
+ "owner": { "login": "my-org" }
+ },
+ "installation": { "id": 12345 }
+ }),
+ );
+
+ service.process_webhook_event(&event).await.unwrap();
+
+ // No comment posted on close
+ assert!(service.client.pr_comments().is_empty());
+
+ // Status should be updated from comment-discovered task
+ 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, "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()]);
+
+ let event = ValidatedGithubWebhookEvent::new(
+ "issue_comment".to_string(),
+ serde_json::json!({
+ "action": "created",
+ "issue": {
+ "number": 99,
+ "title": "some issue",
+ "body": null,
+ "state": "open",
+ "head": { "ref": "main" }
+ },
+ "comment": {
+ "body": "Also see MACRO-2BuyvtY3aeEvHx4uG8iD51"
+ },
+ "repository": {
+ "name": "my-repo",
+ "owner": { "login": "my-org" }
+ },
+ "installation": { "id": 12345 }
+ }),
+ );
+
+ service.process_webhook_event(&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"
+ );
+}