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.

fix(github): publish task status changes from PRs and credit the merger (#9192)

gbirman96e19ffc9a78
diff --git a/crates/ai_tools/src/tool_context.rs b/crates/ai_tools/src/tool_context.rs
index 85a2ddd98e..26794dc9da 100644
--- a/crates/ai_tools/src/tool_context.rs
+++ b/crates/ai_tools/src/tool_context.rs
@@ -38,13 +38,15 @@ use databases::inbound::toolset::DatabasesToolContext;
use databases_sql::toolset::DatabasesSqlToolContext;
use databases_sql::{DatabasesSql, ViewOnlyAccess};
use documents::{
- domain::ports::{TaskPropertiesPort, task_property_edit_receipt},
+ domain::ports::{TaskPropertiesPort, credited_task_edit_receipt, task_property_edit_receipt},
inbound::toolset::DocumentToolContext,
};
use email::{
domain::service::EmailServiceImpl, inbound::toolset::EmailToolContext, outbound::EmailPgRepo,
};
-use entity_access::domain::models::EditAccessLevel;
+use entity_access::domain::models::{
+ EditAccessLevel, EntityAccessAuth, EntityAccessReceipt, ViewAccessLevel,
+};
use entity_access::domain::ports::EntityAccessService as _;
use entity_registry::OwnerGrantPolicy;
use entity_registry_db_utils::OwnedEntityRegistrar;
@@ -62,6 +64,7 @@ use macro_event_broker::{
NoopMacroEventBroker,
};
use macro_user_id::user_id::MacroUserIdStr;
+use models_properties::service::property_value::PropertyValue;
use notification::domain::service::SqsNotificationIngress;
use notification::inbound::ai_tool::NotificationToolContext;
use projects::inbound::toolset::ProjectToolContext;
@@ -768,7 +771,12 @@ pub fn build_team_tool_context(pool: sqlx::PgPool) -> ToolTeamToolContext {
pub struct NoOpTaskProperties;
impl TaskPropertiesPort for NoOpTaskProperties {
- async fn update_task_status(&self, _entity_id: &str, _status: &str) -> anyhow::Result<()> {
+ async fn update_task_status(
+ &self,
+ _access: &EntityAccessReceipt<EditAccessLevel>,
+ _credited_user: Option<&MacroUserIdStr<'static>>,
+ _status: &str,
+ ) -> anyhow::Result<()> {
Ok(())
}
async fn attach_task_properties(&self, _entity_ids: Vec<String>) -> anyhow::Result<()> {
@@ -811,14 +819,57 @@ impl TaskPropertiesPort for TaskPropertiesAdapter {
.map_err(Into::into)
}
- async fn update_task_status(&self, task_id: &str, status: &str) -> anyhow::Result<()> {
- let status_option = StatusOption::try_from(status).map_err(|e| anyhow::anyhow!(e))?;
+ #[tracing::instrument(
+ skip_all,
+ fields(
+ task_id = %access.entity().entity_id,
+ status,
+ unchanged = tracing::field::Empty,
+ credited = tracing::field::Empty
+ ),
+ err
+ )]
+ async fn update_task_status(
+ &self,
+ access: &EntityAccessReceipt<EditAccessLevel>,
+ credited_user: Option<&MacroUserIdStr<'static>>,
+ status: &str,
+ ) -> anyhow::Result<()> {
+ use properties::PropertiesService as _;
- self.system_properties
- .update_task_status(task_id, status_option)
+ let status_option = StatusOption::try_from(status).map_err(|e| anyhow::anyhow!(e))?;
+ let current = self
+ .properties
+ .get_system_property_value(
+ &access.clone().try_into_requirement::<ViewAccessLevel>()?,
+ system_properties::SystemPropertyKey::Status,
+ )
.await?;
-
- Ok(())
+ // PR edits and comments re-send In Review; an unchanged status publishes nothing.
+ if current == Some(PropertyValue::SelectOption(vec![status_option.uuid()])) {
+ tracing::Span::current().record("unchanged", true);
+ return Ok(());
+ }
+ let access =
+ credited_task_edit_receipt(self.entity_access_service.as_ref(), access, credited_user)
+ .await;
+ tracing::Span::current().record(
+ "credited",
+ matches!(access.auth(), EntityAccessAuth::Authenticated(_)),
+ );
+ self.properties
+ .set_entity_property(
+ &access,
+ system_properties::SystemPropertyKey::STATUS_UUID,
+ Some(
+ models_properties::api::requests::SetPropertyValue::SelectOption {
+ option_id: status_option.uuid(),
+ },
+ ),
+ )
+ .await
+ .map(|_| ())
+ .map_err(Into::into)
}
async fn set_entity_property(
@@ -1753,10 +1804,15 @@ impl ToolEntityCreator {
let principal = Self::creation_principal(user);
if let Some(status) = properties.status.as_deref()
- && let Err(e) = self
- .task_properties
- .update_task_status(task_id, status)
- .await
+ && let Err(e) = match StatusOption::try_from(status) {
+ Ok(option) => self
+ .task_properties
+ .system_properties
+ .update_task_status(task_id, option)
+ .await
+ .map_err(anyhow::Error::from),
+ Err(e) => Err(anyhow::anyhow!(e)),
+ }
{
tracing::warn!(task_id, status, error = ?e, "failed to set imported task status");
}
diff --git a/crates/documents/src/domain/ports.rs b/crates/documents/src/domain/ports.rs
index 923996b09c..14ca3ce3b8 100644
--- a/crates/documents/src/domain/ports.rs
+++ b/crates/documents/src/domain/ports.rs
@@ -8,6 +8,8 @@ pub mod editing;
pub mod markdown;
pub mod mentions;
pub mod sync;
+#[cfg(test)]
+mod test;
use std::future::Future;
@@ -378,10 +380,12 @@ pub trait TaskPropertiesPort: Send + Sync + 'static {
entity_ids: Vec<String>,
) -> impl Future<Output = anyhow::Result<()>> + Send;
- /// Updates the tasks status
+ /// Updates the tasks status, credited to `credited_user` when they can edit
+ /// the task (see [`credited_task_edit_receipt`]).
fn update_task_status(
&self,
- entity_id: &str,
+ access: &EntityAccessReceipt<EditAccessLevel>,
+ credited_user: Option<&MacroUserIdStr<'static>>,
status: &str,
) -> impl Future<Output = anyhow::Result<()>> + Send;
@@ -441,6 +445,30 @@ pub async fn task_property_edit_receipt<A: EntityAccessService>(
}
}
+/// Pick the edit receipt a task status change is written with.
+///
+/// The change is attributed to `credited_user` when they can edit the task, so
+/// it reads as their action wherever property events go (activity, routines).
+/// Otherwise it is written with `access` and stays uncredited, so the status
+/// still changes.
+pub async fn credited_task_edit_receipt<A: EntityAccessService>(
+ entity_access: &A,
+ access: &EntityAccessReceipt<EditAccessLevel>,
+ credited_user: Option<&MacroUserIdStr<'static>>,
+) -> EntityAccessReceipt<EditAccessLevel> {
+ let Some(user) = credited_user else {
+ return access.clone();
+ };
+ let entity = access.entity();
+ entity_access
+ .generate_entity_access_receipt(user, None, &entity.entity_id, entity.entity_type)
+ .await
+ .inspect_err(|error| {
+ tracing::info!(error = ?error, "task status change left uncredited");
+ })
+ .unwrap_or_else(|_| access.clone())
+}
+
/// Use cases for relaying document content-change events.
pub trait DocumentContentEventService: Send + Sync + 'static {
/// Load the document owner and publish a content-uploaded event.
@@ -583,10 +611,12 @@ pub trait DocumentService: Send + Sync + 'static {
args: EditDocumentServiceArgs,
) -> impl Future<Output = Result<(), DocumentError>> + Send;
- /// Updates the tasks status to what is provided
+ /// Updates the tasks status to what is provided, credited to
+ /// `credited_user` when they can edit the task
fn update_task_status(
&self,
entity_access_receipt: EntityAccessReceipt<EditAccessLevel>,
+ credited_user: Option<MacroUserIdStr<'static>>,
status: &str,
) -> impl Future<Output = Result<(), DocumentError>> + Send;
diff --git a/crates/documents/src/domain/ports/test.rs b/crates/documents/src/domain/ports/test.rs
new file mode 100644
index 0000000000..29f53fa022
--- /dev/null
+++ b/crates/documents/src/domain/ports/test.rs
@@ -0,0 +1,165 @@
+use super::*;
+
+use entity_access::domain::models::{
+ AccessLevel, BotId, CallChannelInfo, EntityAccessAuth, EntityPermission, RequiredPermission,
+ TeamRole, UserTeamInfo,
+};
+use macro_user_id::{lowercased::Lowercase, user_id::MacroUserId};
+use uuid::Uuid;
+
+/// Grants edit access on every entity to the listed users and nobody else.
+#[derive(Clone)]
+struct EditorsOnly {
+ editors: Vec<&'static str>,
+}
+
+impl EntityAccessService for EditorsOnly {
+ async fn generate_entity_access_receipt<T: RequiredPermission>(
+ &self,
+ user_id: &MacroUserId<Lowercase<'_>>,
+ _user_org_id: Option<i64>,
+ entity_id: &str,
+ entity_type: EntityType,
+ ) -> Result<EntityAccessReceipt<T>, AccessError> {
+ if !self.editors.contains(&user_id.as_ref()) {
+ return Err(AccessError::Unauthorized);
+ }
+ EntityAccessReceipt::try_new_authenticated_user(
+ MacroUserIdStr::try_from(user_id.as_ref().to_string())
+ .expect("test user id should be valid"),
+ entity_access::domain::models::Entity {
+ entity_id: entity_id.to_string(),
+ entity_type,
+ },
+ EntityPermission::AccessLevel {
+ access_level: AccessLevel::Edit,
+ },
+ )
+ }
+
+ async fn generate_bot_entity_access_receipt<T: RequiredPermission>(
+ &self,
+ _bot_id: BotId,
+ _scope: BotAccessScope,
+ _entity_id: &str,
+ _entity_type: EntityType,
+ ) -> Result<EntityAccessReceipt<T>, AccessError> {
+ panic!("unexpected generate_bot_entity_access_receipt call")
+ }
+
+ async fn get_access_level(
+ &self,
+ _user_id: Option<&MacroUserId<Lowercase<'_>>>,
+ _entity_id: &str,
+ _entity_type: EntityType,
+ ) -> Result<Option<AccessLevel>, AccessError> {
+ panic!("unexpected get_access_level call")
+ }
+
+ async fn check_access(
+ &self,
+ _user_id: Option<&MacroUserId<Lowercase<'_>>>,
+ _entity_id: &str,
+ _entity_type: EntityType,
+ _required_level: AccessLevel,
+ ) -> Result<AccessLevel, AccessError> {
+ panic!("unexpected check_access call")
+ }
+
+ async fn check_public_access(
+ &self,
+ _entity_id: &str,
+ _entity_type: EntityType,
+ _required_level: AccessLevel,
+ ) -> Result<AccessLevel, AccessError> {
+ panic!("unexpected check_public_access call")
+ }
+
+ async fn get_entity_permission(
+ &self,
+ _user_id: Option<&MacroUserId<Lowercase<'_>>>,
+ _entity_id: &str,
+ _entity_type: EntityType,
+ _user_org_id: Option<i64>,
+ ) -> Result<EntityPermission, AccessError> {
+ panic!("unexpected get_entity_permission call")
+ }
+
+ async fn get_crm_entity_permission_with_team(
+ &self,
+ _user_id: Option<&MacroUserId<Lowercase<'_>>>,
+ _entity_id: &str,
+ _entity_type: EntityType,
+ ) -> Result<(EntityPermission, Uuid, TeamRole), AccessError> {
+ panic!("unexpected get_crm_entity_permission_with_team call")
+ }
+
+ async fn get_users_by_entity(
+ &self,
+ _entity_id: &str,
+ _entity_type: EntityType,
+ ) -> Result<Vec<MacroUserIdStr<'static>>, AccessError> {
+ panic!("unexpected get_users_by_entity call")
+ }
+
+ async fn get_call_channel(
+ &self,
+ _call_id: &Uuid,
+ ) -> Result<Option<CallChannelInfo>, AccessError> {
+ panic!("unexpected get_call_channel call")
+ }
+
+ async fn get_call_channel_by_channel_id(
+ &self,
+ _channel_id: &Uuid,
+ ) -> Result<Option<CallChannelInfo>, AccessError> {
+ panic!("unexpected get_call_channel_by_channel_id call")
+ }
+
+ async fn get_user_team(
+ &self,
+ _user_id: &MacroUserId<Lowercase<'_>>,
+ ) -> Result<Option<UserTeamInfo>, AccessError> {
+ panic!("unexpected get_user_team call")
+ }
+}
+
+#[tokio::test]
+async fn status_change_is_credited_to_a_user_who_can_edit_the_task() {
+ let access = EntityAccessReceipt::<EditAccessLevel>::dangerously_assert_internal_user(
+ "task-1",
+ EntityType::Document,
+ );
+ let merger = MacroUserIdStr::parse_from_str("macro|[email protected]").unwrap();
+ let entity_access = EditorsOnly {
+ editors: vec!["macro|[email protected]"],
+ };
+
+ let receipt = credited_task_edit_receipt(&entity_access, &access, Some(&merger)).await;
+
+ assert!(
+ matches!(receipt.auth(), EntityAccessAuth::Authenticated(user) if *user == merger),
+ "expected the merger's receipt, got {:?}",
+ receipt.auth()
+ );
+ assert_eq!(receipt.entity().entity_id, "task-1");
+}
+
+#[tokio::test]
+async fn status_change_stays_uncredited_when_the_user_cannot_edit_the_task() {
+ let access = EntityAccessReceipt::<EditAccessLevel>::dangerously_assert_internal_user(
+ "task-1",
+ EntityType::Document,
+ );
+ let merger = MacroUserIdStr::parse_from_str("macro|[email protected]").unwrap();
+ let entity_access = EditorsOnly { editors: vec![] };
+
+ let receipt = credited_task_edit_receipt(&entity_access, &access, Some(&merger)).await;
+
+ assert!(
+ matches!(receipt.auth(), EntityAccessAuth::Internal),
+ "expected the caller's internal receipt, got {:?}",
+ receipt.auth()
+ );
+ assert_eq!(receipt.entity().entity_id, "task-1");
+}
diff --git a/crates/documents/src/domain/service.rs b/crates/documents/src/domain/service.rs
index 6fbb1d9428..de0cb8b7de 100644
--- a/crates/documents/src/domain/service.rs
+++ b/crates/documents/src/domain/service.rs
@@ -2190,14 +2190,22 @@ impl<
})
}
- #[tracing::instrument(skip(self))]
+ #[tracing::instrument(
+ skip(self, entity_access_receipt, credited_user),
+ fields(
+ task_id = %entity_access_receipt.entity().entity_id,
+ credit_requested = credited_user.is_some()
+ ),
+ err
+ )]
async fn update_task_status(
&self,
entity_access_receipt: EntityAccessReceipt<entity_access::domain::models::EditAccessLevel>,
+ credited_user: Option<MacroUserIdStr<'static>>,
status: &str,
) -> Result<(), DocumentError> {
self.task_properties_service
- .update_task_status(&entity_access_receipt.entity().entity_id, status)
+ .update_task_status(&entity_access_receipt, credited_user.as_ref(), status)
.await
.map_err(DocumentError::Internal)?;
diff --git a/crates/documents/src/domain/service/tests.rs b/crates/documents/src/domain/service/tests.rs
index d014c68c6c..70dd63d908 100644
--- a/crates/documents/src/domain/service/tests.rs
+++ b/crates/documents/src/domain/service/tests.rs
@@ -158,7 +158,12 @@ impl TaskPropertiesPort for TestTaskPropertiesPort {
Ok(())
}
- async fn update_task_status(&self, _entity_id: &str, _status: &str) -> anyhow::Result<()> {
+ async fn update_task_status(
+ &self,
+ _access: &EntityAccessReceipt<EditAccessLevel>,
+ _credited_user: Option<&macro_user_id::user_id::MacroUserIdStr<'static>>,
+ _status: &str,
+ ) -> anyhow::Result<()> {
Ok(())
}
@@ -2777,7 +2782,12 @@ impl TaskPropertiesPort for RecordingTaskPropertiesPort {
Ok(())
}
- async fn update_task_status(&self, _entity_id: &str, _status: &str) -> anyhow::Result<()> {
+ async fn update_task_status(
+ &self,
+ _access: &EntityAccessReceipt<EditAccessLevel>,
+ _credited_user: Option<&macro_user_id::user_id::MacroUserIdStr<'static>>,
+ _status: &str,
+ ) -> anyhow::Result<()> {
Ok(())
}
diff --git a/crates/documents/src/inbound/axum_router/tests.rs b/crates/documents/src/inbound/axum_router/tests.rs
index d165421b8c..5d2398a3a9 100644
--- a/crates/documents/src/inbound/axum_router/tests.rs
+++ b/crates/documents/src/inbound/axum_router/tests.rs
@@ -414,6 +414,7 @@ impl DocumentService for FakeDocumentService {
async fn update_task_status(
&self,
_entity_access_receipt: EntityAccessReceipt<entity_access::domain::models::EditAccessLevel>,
+ _credited_user: Option<MacroUserIdStr<'static>>,
_status: &str,
) -> Result<(), DocumentError> {
panic!("unexpected update_task_status call")
diff --git a/crates/documents/src/inbound/toolset/edit_document/test.rs b/crates/documents/src/inbound/toolset/edit_document/test.rs
index 97ca695ee2..d6e8cad4b7 100644
--- a/crates/documents/src/inbound/toolset/edit_document/test.rs
+++ b/crates/documents/src/inbound/toolset/edit_document/test.rs
@@ -261,6 +261,7 @@ impl DocumentService for FakeDocumentService {
async fn update_task_status(
&self,
_entity_access_receipt: EntityAccessReceipt<EditAccessLevel>,
+ _credited_user: Option<MacroUserIdStr<'static>>,
_status: &str,
) -> Result<(), DocumentError> {
panic!("unexpected update_task_status call")
diff --git a/crates/github/src/domain/service/sync.rs b/crates/github/src/domain/service/sync.rs
index 3266ec823d..abff4bb618 100644
--- a/crates/github/src/domain/service/sync.rs
+++ b/crates/github/src/domain/service/sync.rs
@@ -828,10 +828,25 @@ impl<
.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");
+ /// Update task statuses for all resolved task doc IDs, crediting the Macro
+ /// user linked to the webhook sender (for a merge, the person who merged).
+ #[tracing::instrument(skip(self, event, doc_ids))]
+ async fn update_task_statuses(
+ &self,
+ event: &ValidatedGithubWebhookEvent,
+ doc_ids: &[String],
+ status: &str,
+ ) {
+ if doc_ids.is_empty() {
+ return;
+ }
+ let credited_user = self.notification_sender(event).await.sender_id;
+ tracing::trace!(
+ doc_count = doc_ids.len(),
+ status,
+ linked_user = credited_user.is_some(),
+ "updating task statuses"
+ );
for doc_id in doc_ids {
tracing::trace!(doc_id, status, "updating task status");
@@ -844,7 +859,7 @@ impl<
);
self.document_service
- .update_task_status(entity_access, status)
+ .update_task_status(entity_access, credited_user.clone(), status)
.await
.inspect_err(|e| {
tracing::error!(
diff --git a/crates/github/src/domain/service/sync/handle_comment.rs b/crates/github/src/domain/service/sync/handle_comment.rs
index 3992c11727..86ab3d3fdf 100644
--- a/crates/github/src/domain/service/sync/handle_comment.rs
+++ b/crates/github/src/domain/service/sync/handle_comment.rs
@@ -124,7 +124,8 @@ impl<
// 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;
+ self.update_task_statuses(event, &resolved.doc_ids, status)
+ .await;
} else {
tracing::trace!("no status update warranted for this event");
}
diff --git a/crates/github/src/domain/service/sync/handle_pr.rs b/crates/github/src/domain/service/sync/handle_pr.rs
index def70db8f6..1192833ec8 100644
--- a/crates/github/src/domain/service/sync/handle_pr.rs
+++ b/crates/github/src/domain/service/sync/handle_pr.rs
@@ -90,7 +90,7 @@ impl<
}
// Update status for all validated tasks
- self.update_task_statuses(&resolved_all.doc_ids, "In Review")
+ self.update_task_statuses(event, &resolved_all.doc_ids, "In Review")
.await;
tracing::trace!("PR open handler complete");
@@ -171,7 +171,7 @@ impl<
}
// Update status for all validated tasks
- self.update_task_statuses(&resolved_all.doc_ids, "In Review")
+ self.update_task_statuses(event, &resolved_all.doc_ids, "In Review")
.await;
tracing::trace!("PR edit handler complete");
@@ -252,7 +252,8 @@ impl<
doc_count = resolved.doc_ids.len(),
"updating task statuses for PR close"
);
- self.update_task_statuses(&resolved.doc_ids, status).await;
+ self.update_task_statuses(event, &resolved.doc_ids, status)
+ .await;
tracing::trace!("PR close handler complete");
Ok(())
diff --git a/crates/github/src/domain/service/sync/notify_pr.rs b/crates/github/src/domain/service/sync/notify_pr.rs
index 7eac31cafc..b168bbccd6 100644
--- a/crates/github/src/domain/service/sync/notify_pr.rs
+++ b/crates/github/src/domain/service/sync/notify_pr.rs
@@ -32,13 +32,14 @@ struct PullRequestStatusTransition {
/// The webhook actor resolved to Macro users via `github_links`.
///
-/// `sender_id` is the single Macro user a notification is attributed to. A
+/// `sender_id` is the single Macro user a notification is attributed to, and
+/// the user a task status change from the same event is credited to. A
/// GitHub account may be linked to several Macro users, so `actor_user_ids`
/// carries every linked user; `send_github_notification` excludes all of them
/// from recipients so nobody is notified about their own GitHub activity.
#[derive(Default)]
pub(super) struct NotificationSender {
- sender_id: Option<MacroUserIdStr<'static>>,
+ pub(super) sender_id: Option<MacroUserIdStr<'static>>,
actor_user_ids: HashSet<MacroUserIdStr<'static>>,
}
diff --git a/crates/github/src/domain/service/sync/test.rs b/crates/github/src/domain/service/sync/test.rs
index eaa2cdf5b3..a707b8b845 100644
--- a/crates/github/src/domain/service/sync/test.rs
+++ b/crates/github/src/domain/service/sync/test.rs
@@ -91,6 +91,7 @@ sNRx7TF4iOEBkdJgBUoY4X/rZ+51FQOrdZGqeWo+8TjBhMQN7b4=
#[derive(Debug, Clone)]
struct TaskStatusCall {
entity_id: String,
+ credited_user: Option<MacroUserIdStr<'static>>,
status: String,
}
@@ -259,10 +260,12 @@ impl DocumentService for StubDocumentService {
async fn update_task_status(
&self,
receipt: EntityAccessReceipt<EditAccessLevel>,
+ credited_user: Option<MacroUserIdStr<'static>>,
status: &str,
) -> Result<(), DocumentError> {
self.task_status_calls.lock().unwrap().push(TaskStatusCall {
entity_id: receipt.entity().entity_id.clone(),
+ credited_user,
status: status.to_string(),
});
Ok(())
@@ -1308,6 +1311,12 @@ fn make_sync_service_with_repo_and_notification_ingress(
}
fn make_sync_service_with_doc_service() -> (TestGithubSyncService, Arc<StubDocumentService>) {
+ make_sync_service_with_repo_and_doc_service(StubSyncRepo::new())
+}
+
+fn make_sync_service_with_repo_and_doc_service(
+ repo: StubSyncRepo,
+) -> (TestGithubSyncService, Arc<StubDocumentService>) {
let doc_service = Arc::new(StubDocumentService::new());
let foreign_entity_service = StubForeignEntityService::new();
@@ -1324,7 +1333,7 @@ fn make_sync_service_with_doc_service() -> (TestGithubSyncService, Arc<StubDocum
doc_service.clone(),
pull_request_service(&foreign_entity_service),
StubNotificationIngress::new(),
- StubSyncRepo::new(),
+ repo,
StubSyncClient::new(),
StubRealtime::default(),
);
@@ -2313,6 +2322,78 @@ async fn pr_merged_sets_task_status_completed() {
assert_eq!(status_calls[0].status, "Completed");
}
+#[tokio::test]
+async fn pr_merged_credits_the_linked_macro_user_who_merged() {
+ let (service, doc_service) = make_sync_service_with_repo_and_doc_service(
+ StubSyncRepo::new().with_github_link("333", "macro|[email protected]"),
+ );
+ 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 },
+ "sender": { "login": "monalisa", "id": 333 }
+ }),
+ );
+
+ service.process_webhook_event(&event).await.unwrap();
+
+ let status_calls = doc_service.task_status_calls();
+ assert_eq!(status_calls.len(), 1);
+ assert_eq!(status_calls[0].status, "Completed");
+ assert_eq!(
+ status_calls[0]
+ .credited_user
+ .as_ref()
+ .map(ToString::to_string),
+ Some("macro|[email protected]".to_string())
+ );
+}
+
+#[tokio::test]
+async fn pr_merged_by_an_unlinked_github_account_is_not_credited() {
+ let (service, doc_service) = make_sync_service_with_repo_and_doc_service(
+ StubSyncRepo::new().with_github_link("333", "macro|[email protected]"),
+ );
+ 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 },
+ "sender": { "login": "someone-else", "id": 444 }
+ }),
+ );
+
+ service.process_webhook_event(&event).await.unwrap();
+
+ let status_calls = doc_service.task_status_calls();
+ assert_eq!(status_calls.len(), 1);
+ assert_eq!(status_calls[0].status, "Completed");
+ assert!(status_calls[0].credited_user.is_none());
+}
+
#[tokio::test]
async fn pr_closed_without_merge_sets_task_status_todo() {
let (service, doc_service) = make_sync_service_with_doc_service();
diff --git a/crates/properties/README.md b/crates/properties/README.md
index c05c8b01cb..8c33132d70 100644
--- a/crates/properties/README.md
+++ b/crates/properties/README.md
@@ -24,7 +24,10 @@ includes `actor_user_id`, which is a nullable Macro user ID. It identifies the
authenticated user responsible for the mutation and is `null` for internal,
machine, bot, or unauthenticated callers. In particular, document-deletion
cleanup is an internal call and produces `entity_properties.cleared` with a null
-actor. Optional metadata fields are serialized as `null` unless their reused
+actor. A task status change from a linked GitHub pull request (opened, edited,
+commented on, merged, or closed) credits the Macro user linked to the GitHub
+account that caused it when that user can edit the task, and is internal
+otherwise. Optional metadata fields are serialized as `null` unless their reused
nested model specifies otherwise.
| Event name | Emitted after | Metadata |
diff --git a/services/document_storage_service/src/api/context.rs b/services/document_storage_service/src/api/context.rs
index dba9a6fa15..9a57c7f028 100644
--- a/services/document_storage_service/src/api/context.rs
+++ b/services/document_storage_service/src/api/context.rs
@@ -45,7 +45,9 @@ use connection::{
outbound::connection_gateway_client::ConnectionGatewayImpl,
};
use connection_gateway_client::client::ConnectionGatewayClient;
-use documents_hex::domain::ports::{TaskPropertiesPort, task_property_edit_receipt};
+use documents_hex::domain::ports::{
+ TaskPropertiesPort, credited_task_edit_receipt, task_property_edit_receipt,
+};
use documents_hex::domain::purge::DocumentPurger;
use documents_hex::domain::service::DocumentServiceImpl;
use documents_hex::inbound::axum_router::DocumentRouterState;
@@ -59,7 +61,13 @@ use email::{
domain::{ports::ReadonlyEmailPreviewAdapter, service::EmailServiceImpl},
outbound::EmailPgRepo,
};
-use entity_access::{domain::service::EntityAccessServiceImpl, outbound::PgAccessRepository};
+use entity_access::{
+ domain::{
+ models::{EditAccessLevel, EntityAccessAuth, EntityAccessReceipt, ViewAccessLevel},
+ service::EntityAccessServiceImpl,
+ },
+ outbound::PgAccessRepository,
+};
use favorites::{
domain::{mutation_service::FavoritesMutationServiceImpl, service::FavoritesServiceImpl},
inbound::axum_router::FavoritesRouterState,
@@ -117,6 +125,7 @@ use macro_authorization::{
};
use macro_env_var::env_var;
use macro_sha_count_client::Redis;
+use models_properties::service::property_value::PropertyValue;
use notification::domain::service::SqsNotificationIngress;
use notification::outbound::queue::SqsQueue;
use opensearch_client::OpensearchClient;
@@ -149,7 +158,7 @@ use std::sync::Arc;
use sync_service_client::SyncServiceClient;
use system_properties::{
PgSystemPropertiesRepository, StatusOption, SystemPropertiesService as _,
- SystemPropertiesServiceImpl,
+ SystemPropertiesServiceImpl, SystemPropertyKey,
};
use tokio_util::task::TaskTracker;
use webhook::{
@@ -323,14 +332,57 @@ impl TaskPropertiesPort for TaskPropertiesAdapter {
.map_err(Into::into)
}
- async fn update_task_status(&self, task_id: &str, status: &str) -> anyhow::Result<()> {
- let status_option = StatusOption::try_from(status).map_err(|e| anyhow::anyhow!(e))?;
+ #[tracing::instrument(
+ skip_all,
+ fields(
+ task_id = %access.entity().entity_id,
+ status,
+ unchanged = tracing::field::Empty,
+ credited = tracing::field::Empty
+ ),
+ err
+ )]
+ async fn update_task_status(
+ &self,
+ access: &EntityAccessReceipt<EditAccessLevel>,
+ credited_user: Option<&macro_user_id::user_id::MacroUserIdStr<'static>>,
+ status: &str,
+ ) -> anyhow::Result<()> {
+ use properties::PropertiesService as _;
- self.system_properties
- .update_task_status(task_id, status_option)
+ let status_option = StatusOption::try_from(status).map_err(|e| anyhow::anyhow!(e))?;
+ let current = self
+ .properties
+ .get_system_property_value(
+ &access.clone().try_into_requirement::<ViewAccessLevel>()?,
+ SystemPropertyKey::Status,
+ )
.await?;
-
- Ok(())
+ // PR edits and comments re-send In Review; an unchanged status publishes nothing.
+ if current == Some(PropertyValue::SelectOption(vec![status_option.uuid()])) {
+ tracing::Span::current().record("unchanged", true);
+ return Ok(());
+ }
+ let access =
+ credited_task_edit_receipt(self.entity_access_service.as_ref(), access, credited_user)
+ .await;
+ tracing::Span::current().record(
+ "credited",
+ matches!(access.auth(), EntityAccessAuth::Authenticated(_)),
+ );
+ self.properties
+ .set_entity_property(
+ &access,
+ SystemPropertyKey::STATUS_UUID,
+ Some(
+ models_properties::api::requests::SetPropertyValue::SelectOption {
+ option_id: status_option.uuid(),
+ },
+ ),
+ )
+ .await
+ .map(|_| ())
+ .map_err(Into::into)
}
async fn set_entity_property(