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(routines): fire on PR status changes from any GitHub account (#9205)

gbirman8fc7719171d0
diff --git a/Cargo.lock b/Cargo.lock
index 9c00c96223..e73d46e177 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -8889,6 +8889,7 @@ dependencies = [
"model_owner",
"model_user",
"models_permissions",
+ "models_properties",
"notification",
"redis",
"regex",
diff --git a/apps/docs/product/routines.mdx b/apps/docs/product/routines.mdx
index 095ec309ac..85db1eeefd 100644
--- a/apps/docs/product/routines.mdx
+++ b/apps/docs/product/routines.mdx
@@ -33,7 +33,7 @@ Recurring schedules use the time zone they were created in. One-time runs use yo
- **Tasks**: task created, status changed, priority changed, or any property changed
- **Email**: new email received. Spam, trash, and drafts are excluded.
-Message, mention, deletion, and task triggers can be scoped to specific channels, documents, or tasks, or to everything you have access to. Changes made by agents and bots do not fire triggers.
+Message, mention, deletion, and task triggers can be scoped to specific channels, documents, or tasks, or to everything you have access to. Changes made by agents and bots do not fire triggers. A task status change from a linked GitHub pull request does, whether or not the GitHub account is connected to Macro.
Click a trigger chip to edit it. Choose **Remove trigger** to delete it.
diff --git a/crates/agent_trigger/src/domain/project_assignment/test.rs b/crates/agent_trigger/src/domain/project_assignment/test.rs
index 41def8040e..11778f94d4 100644
--- a/crates/agent_trigger/src/domain/project_assignment/test.rs
+++ b/crates/agent_trigger/src/domain/project_assignment/test.rs
@@ -35,6 +35,7 @@ fn update(
actor_user_id: Some(user()),
actor: None,
on_behalf_of: None,
+ source: None,
value: project_value(project),
previous_value: project_value(previous),
updated_at: Utc::now(),
diff --git a/crates/agent_trigger/src/domain/sources/test.rs b/crates/agent_trigger/src/domain/sources/test.rs
index 6351094de1..eff6a0b84c 100644
--- a/crates/agent_trigger/src/domain/sources/test.rs
+++ b/crates/agent_trigger/src/domain/sources/test.rs
@@ -111,6 +111,7 @@ fn a_task_joining_a_project_decodes_as_a_project_addition() {
actor_user_id: Some(user.clone()),
actor: None,
on_behalf_of: None,
+ source: None,
value: Some(PropertyValue::EntityRef(vec![EntityReference {
entity_id: project.to_string(),
entity_type: EntityType::Initiative,
diff --git a/crates/agent_trigger/src/domain/task_assignment/test.rs b/crates/agent_trigger/src/domain/task_assignment/test.rs
index 493c71f01b..99872f31f5 100644
--- a/crates/agent_trigger/src/domain/task_assignment/test.rs
+++ b/crates/agent_trigger/src/domain/task_assignment/test.rs
@@ -62,6 +62,7 @@ fn update() -> EntityPropertyUpdatedMetadata {
actor_user_id: Some(MacroUserIdStr::try_from_email("[email protected]").unwrap()),
actor: None,
on_behalf_of: None,
+ source: None,
value: value(&["bot|00000000-0000-0000-0000-00000000b07a"]),
previous_value: None,
updated_at: Utc::now(),
diff --git a/crates/ai_tools/src/tool_context.rs b/crates/ai_tools/src/tool_context.rs
index 26794dc9da..1b43fc2e1c 100644
--- a/crates/ai_tools/src/tool_context.rs
+++ b/crates/ai_tools/src/tool_context.rs
@@ -64,6 +64,7 @@ use macro_event_broker::{
NoopMacroEventBroker,
};
use macro_user_id::user_id::MacroUserIdStr;
+use models_properties::service::property_change_source::PropertyChangeSource;
use models_properties::service::property_value::PropertyValue;
use notification::domain::service::SqsNotificationIngress;
use notification::inbound::ai_tool::NotificationToolContext;
@@ -775,6 +776,7 @@ impl TaskPropertiesPort for NoOpTaskProperties {
&self,
_access: &EntityAccessReceipt<EditAccessLevel>,
_credited_user: Option<&MacroUserIdStr<'static>>,
+ _source: Option<&PropertyChangeSource>,
_status: &str,
) -> anyhow::Result<()> {
Ok(())
@@ -833,6 +835,7 @@ impl TaskPropertiesPort for TaskPropertiesAdapter {
&self,
access: &EntityAccessReceipt<EditAccessLevel>,
credited_user: Option<&MacroUserIdStr<'static>>,
+ source: Option<&PropertyChangeSource>,
status: &str,
) -> anyhow::Result<()> {
use properties::PropertiesService as _;
@@ -858,7 +861,7 @@ impl TaskPropertiesPort for TaskPropertiesAdapter {
matches!(access.auth(), EntityAccessAuth::Authenticated(_)),
);
self.properties
- .set_entity_property(
+ .set_entity_property_with_source(
&access,
system_properties::SystemPropertyKey::STATUS_UUID,
Some(
@@ -866,6 +869,7 @@ impl TaskPropertiesPort for TaskPropertiesAdapter {
option_id: status_option.uuid(),
},
),
+ source.cloned(),
)
.await
.map(|_| ())
diff --git a/crates/documents/src/domain/ports.rs b/crates/documents/src/domain/ports.rs
index 14ca3ce3b8..a46d0d4d1f 100644
--- a/crates/documents/src/domain/ports.rs
+++ b/crates/documents/src/domain/ports.rs
@@ -25,6 +25,7 @@ use models_permissions::share_permission::SharePermissionV2;
use models_permissions::share_permission::team_share::{
AuthorizedTeamShareCommand, TeamShareFacts,
};
+use models_properties::service::property_change_source::PropertyChangeSource;
use super::content::DocumentContent;
use super::events::InteractionReason;
@@ -381,11 +382,13 @@ pub trait TaskPropertiesPort: Send + Sync + 'static {
) -> impl Future<Output = anyhow::Result<()>> + Send;
/// Updates the tasks status, credited to `credited_user` when they can edit
- /// the task (see [`credited_task_edit_receipt`]).
+ /// the task (see [`credited_task_edit_receipt`]). `source` records the
+ /// outside event behind the change on its published event.
fn update_task_status(
&self,
access: &EntityAccessReceipt<EditAccessLevel>,
credited_user: Option<&MacroUserIdStr<'static>>,
+ source: Option<&PropertyChangeSource>,
status: &str,
) -> impl Future<Output = anyhow::Result<()>> + Send;
@@ -612,11 +615,13 @@ pub trait DocumentService: Send + Sync + 'static {
) -> impl Future<Output = Result<(), DocumentError>> + Send;
/// Updates the tasks status to what is provided, credited to
- /// `credited_user` when they can edit the task
+ /// `credited_user` when they can edit the task, and recording `source` as
+ /// the outside event behind the change
fn update_task_status(
&self,
entity_access_receipt: EntityAccessReceipt<EditAccessLevel>,
credited_user: Option<MacroUserIdStr<'static>>,
+ source: Option<PropertyChangeSource>,
status: &str,
) -> impl Future<Output = Result<(), DocumentError>> + Send;
diff --git a/crates/documents/src/domain/service.rs b/crates/documents/src/domain/service.rs
index de0cb8b7de..d5139b14c4 100644
--- a/crates/documents/src/domain/service.rs
+++ b/crates/documents/src/domain/service.rs
@@ -17,6 +17,7 @@ use models_permissions::share_permission::{
};
use models_properties::EntityReference;
use models_properties::api::SetPropertyValue;
+use models_properties::service::property_change_source::PropertyChangeSource;
use std::borrow::Cow;
use std::str::FromStr;
use std::time::{SystemTime, UNIX_EPOCH};
@@ -2191,10 +2192,11 @@ impl<
}
#[tracing::instrument(
- skip(self, entity_access_receipt, credited_user),
+ skip(self, entity_access_receipt, credited_user, source),
fields(
task_id = %entity_access_receipt.entity().entity_id,
- credit_requested = credited_user.is_some()
+ credit_requested = credited_user.is_some(),
+ has_source = source.is_some()
),
err
)]
@@ -2202,10 +2204,16 @@ impl<
&self,
entity_access_receipt: EntityAccessReceipt<entity_access::domain::models::EditAccessLevel>,
credited_user: Option<MacroUserIdStr<'static>>,
+ source: Option<PropertyChangeSource>,
status: &str,
) -> Result<(), DocumentError> {
self.task_properties_service
- .update_task_status(&entity_access_receipt, credited_user.as_ref(), status)
+ .update_task_status(
+ &entity_access_receipt,
+ credited_user.as_ref(),
+ source.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 70dd63d908..7b6727758b 100644
--- a/crates/documents/src/domain/service/tests.rs
+++ b/crates/documents/src/domain/service/tests.rs
@@ -162,6 +162,7 @@ impl TaskPropertiesPort for TestTaskPropertiesPort {
&self,
_access: &EntityAccessReceipt<EditAccessLevel>,
_credited_user: Option<&macro_user_id::user_id::MacroUserIdStr<'static>>,
+ _source: Option<&models_properties::service::property_change_source::PropertyChangeSource>,
_status: &str,
) -> anyhow::Result<()> {
Ok(())
@@ -2786,6 +2787,7 @@ impl TaskPropertiesPort for RecordingTaskPropertiesPort {
&self,
_access: &EntityAccessReceipt<EditAccessLevel>,
_credited_user: Option<&macro_user_id::user_id::MacroUserIdStr<'static>>,
+ _source: Option<&models_properties::service::property_change_source::PropertyChangeSource>,
_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 5d2398a3a9..741d3a3fa9 100644
--- a/crates/documents/src/inbound/axum_router/tests.rs
+++ b/crates/documents/src/inbound/axum_router/tests.rs
@@ -415,6 +415,7 @@ impl DocumentService for FakeDocumentService {
&self,
_entity_access_receipt: EntityAccessReceipt<entity_access::domain::models::EditAccessLevel>,
_credited_user: Option<MacroUserIdStr<'static>>,
+ _source: Option<models_properties::service::property_change_source::PropertyChangeSource>,
_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 d6e8cad4b7..b48ef020bd 100644
--- a/crates/documents/src/inbound/toolset/edit_document/test.rs
+++ b/crates/documents/src/inbound/toolset/edit_document/test.rs
@@ -262,6 +262,7 @@ impl DocumentService for FakeDocumentService {
&self,
_entity_access_receipt: EntityAccessReceipt<EditAccessLevel>,
_credited_user: Option<MacroUserIdStr<'static>>,
+ _source: Option<models_properties::service::property_change_source::PropertyChangeSource>,
_status: &str,
) -> Result<(), DocumentError> {
panic!("unexpected update_task_status call")
diff --git a/crates/github/Cargo.toml b/crates/github/Cargo.toml
index 750ddd29fa..74ee7c3b98 100644
--- a/crates/github/Cargo.toml
+++ b/crates/github/Cargo.toml
@@ -90,6 +90,7 @@ uuid = { workspace = true }
fusionauth = { path = "../fusionauth", optional = true }
macro_user_id = { path = "../macro_user_id" }
+models_properties = { path = "../models_properties" }
macro_uuid = { path = "../macro_uuid" }
redis = { workspace = true, features = ["aio", "tokio-comp"], optional = true }
tokio = { workspace = true, features = ["sync"], optional = true }
diff --git a/crates/github/src/domain/models/sync.rs b/crates/github/src/domain/models/sync.rs
index 07e88d3ee2..3614adc9e9 100644
--- a/crates/github/src/domain/models/sync.rs
+++ b/crates/github/src/domain/models/sync.rs
@@ -4,6 +4,7 @@ use std::collections::HashSet;
use std::fmt;
use std::sync::LazyLock;
+use models_properties::service::property_change_source::{GithubAccount, PropertyChangeSource};
use regex::Regex;
use serde::Deserialize;
@@ -342,6 +343,30 @@ impl ValidatedGithubWebhookEvent {
.and_then(|v| v.as_u64())
}
+ /// The pull request and GitHub account behind this event's task status
+ /// change: whoever merged it on a merge, the webhook sender otherwise. A
+ /// comment on a plain issue also changes status, but has no pull request.
+ pub fn task_status_source(&self) -> Option<PropertyChangeSource> {
+ if !self.is_associated_with_pull_request() {
+ return None;
+ }
+ let pull_request = self
+ .payload
+ .get("pull_request")
+ .or_else(|| self.payload.get("issue"))?;
+ let merged_by = pull_request
+ .get("merged_by")
+ .filter(|merged_by| !merged_by.is_null() && self.action() == Some("closed"));
+ let account = merged_by.or_else(|| self.payload.get("sender"))?;
+ Some(PropertyChangeSource::GithubPullRequest {
+ url: pull_request.get("html_url")?.as_str()?.to_string(),
+ account: GithubAccount {
+ id: account.get("id")?.as_u64()?.to_string(),
+ login: account.get("login")?.as_str()?.to_string(),
+ },
+ })
+ }
+
/// Extract the sender's GitHub user ID from the webhook payload.
///
/// Uses the numeric `sender.id` rather than `sender.login` because
diff --git a/crates/github/src/domain/models/test.rs b/crates/github/src/domain/models/test.rs
index 2cf325657c..5c90a928fd 100644
--- a/crates/github/src/domain/models/test.rs
+++ b/crates/github/src/domain/models/test.rs
@@ -1,4 +1,5 @@
use super::*;
+use models_properties::service::property_change_source::{GithubAccount, PropertyChangeSource};
// ---------------------------------------------------------------------------
// MacroTaskId::from_short_uuid
@@ -631,6 +632,130 @@ fn pull_request_task_reference_falls_back_to_the_macro_id() {
assert_eq!(MacroTaskId::extract_from_text(&reference), [task]);
}
+#[test]
+fn task_status_source_names_who_merged_over_the_webhook_sender() {
+ let event = ValidatedGithubWebhookEvent::new(
+ "pull_request".to_string(),
+ serde_json::json!({
+ "action": "closed",
+ "pull_request": {
+ "merged": true,
+ "html_url": "https://github.com/my-org/my-repo/pull/42",
+ "merged_by": { "login": "merger", "id": 333 }
+ },
+ "sender": { "login": "automation", "id": 444 }
+ }),
+ );
+
+ assert_eq!(
+ event.task_status_source(),
+ Some(PropertyChangeSource::GithubPullRequest {
+ url: "https://github.com/my-org/my-repo/pull/42".to_string(),
+ account: GithubAccount {
+ id: "333".to_string(),
+ login: "merger".to_string(),
+ },
+ })
+ );
+}
+
+#[test]
+fn task_status_source_falls_back_to_the_sender_on_an_open_pull_request() {
+ let event = ValidatedGithubWebhookEvent::new(
+ "pull_request".to_string(),
+ serde_json::json!({
+ "action": "opened",
+ "pull_request": {
+ "html_url": "https://github.com/my-org/my-repo/pull/42",
+ "merged_by": null
+ },
+ "sender": { "login": "opener", "id": 444 }
+ }),
+ );
+
+ assert_eq!(
+ event.task_status_source(),
+ Some(PropertyChangeSource::GithubPullRequest {
+ url: "https://github.com/my-org/my-repo/pull/42".to_string(),
+ account: GithubAccount {
+ id: "444".to_string(),
+ login: "opener".to_string(),
+ },
+ })
+ );
+}
+
+#[test]
+fn task_status_source_reads_the_pull_request_from_a_comment_event() {
+ let event = ValidatedGithubWebhookEvent::new(
+ "issue_comment".to_string(),
+ serde_json::json!({
+ "action": "created",
+ "issue": {
+ "html_url": "https://github.com/my-org/my-repo/pull/42",
+ "pull_request": { "url": "https://api.github.com/repos/my-org/my-repo/pulls/42" }
+ },
+ "sender": { "login": "commenter", "id": 555 }
+ }),
+ );
+
+ assert_eq!(
+ event.task_status_source(),
+ Some(PropertyChangeSource::GithubPullRequest {
+ url: "https://github.com/my-org/my-repo/pull/42".to_string(),
+ account: GithubAccount {
+ id: "555".to_string(),
+ login: "commenter".to_string(),
+ },
+ })
+ );
+}
+
+#[test]
+fn task_status_source_is_none_for_a_comment_on_a_plain_issue() {
+ let event = ValidatedGithubWebhookEvent::new(
+ "issue_comment".to_string(),
+ serde_json::json!({
+ "action": "created",
+ "issue": {
+ "html_url": "https://github.com/my-org/my-repo/issues/42",
+ "state": "open"
+ },
+ "sender": { "login": "commenter", "id": 555 }
+ }),
+ );
+
+ assert_eq!(event.task_status_for_event(), Some("In Review"));
+ assert_eq!(event.task_status_source(), None);
+}
+
+#[test]
+fn task_status_source_names_the_editor_of_an_already_merged_pull_request() {
+ let event = ValidatedGithubWebhookEvent::new(
+ "pull_request".to_string(),
+ serde_json::json!({
+ "action": "edited",
+ "pull_request": {
+ "merged": true,
+ "html_url": "https://github.com/my-org/my-repo/pull/42",
+ "merged_by": { "login": "merger", "id": 333 }
+ },
+ "sender": { "login": "editor", "id": 444 }
+ }),
+ );
+
+ assert_eq!(
+ event.task_status_source(),
+ Some(PropertyChangeSource::GithubPullRequest {
+ url: "https://github.com/my-org/my-repo/pull/42".to_string(),
+ account: GithubAccount {
+ id: "444".to_string(),
+ login: "editor".to_string(),
+ },
+ })
+ );
+}
+
#[test]
fn a_delivery_keeps_its_meaning_and_drops_api_links() {
let body = serde_json::json!({
diff --git a/crates/github/src/domain/service/sync.rs b/crates/github/src/domain/service/sync.rs
index fb7de310ec..c7d84ef846 100644
--- a/crates/github/src/domain/service/sync.rs
+++ b/crates/github/src/domain/service/sync.rs
@@ -870,10 +870,12 @@ impl<
return;
}
let credited_user = self.notification_sender(event).await.sender_id;
+ let source = event.task_status_source();
tracing::trace!(
doc_count = doc_ids.len(),
status,
linked_user = credited_user.is_some(),
+ has_source = source.is_some(),
"updating task statuses"
);
@@ -888,7 +890,7 @@ impl<
);
self.document_service
- .update_task_status(entity_access, credited_user.clone(), status)
+ .update_task_status(entity_access, credited_user.clone(), source.clone(), status)
.await
.inspect_err(|e| {
tracing::error!(
diff --git a/crates/github/src/domain/service/sync/test.rs b/crates/github/src/domain/service/sync/test.rs
index b5e4b255bb..d4a079abe4 100644
--- a/crates/github/src/domain/service/sync/test.rs
+++ b/crates/github/src/domain/service/sync/test.rs
@@ -43,6 +43,7 @@ use model::document::{DocumentBasic, DocumentMetadata};
use model_entity::Entity;
use model_owner::CreationPrincipal;
use models_permissions::share_permission::access_level::AccessLevel;
+use models_properties::service::property_change_source::{GithubAccount, PropertyChangeSource};
use notification::domain::{
models::{Notification, NotificationResult, SendNotificationRequest},
service::{NotificationIngress, SendNotificationError},
@@ -92,6 +93,7 @@ sNRx7TF4iOEBkdJgBUoY4X/rZ+51FQOrdZGqeWo+8TjBhMQN7b4=
struct TaskStatusCall {
entity_id: String,
credited_user: Option<MacroUserIdStr<'static>>,
+ source: Option<PropertyChangeSource>,
status: String,
}
@@ -261,11 +263,13 @@ impl DocumentService for StubDocumentService {
&self,
receipt: EntityAccessReceipt<EditAccessLevel>,
credited_user: Option<MacroUserIdStr<'static>>,
+ source: Option<PropertyChangeSource>,
status: &str,
) -> Result<(), DocumentError> {
self.task_status_calls.lock().unwrap().push(TaskStatusCall {
entity_id: receipt.entity().entity_id.clone(),
credited_user,
+ source,
status: status.to_string(),
});
Ok(())
@@ -2394,6 +2398,48 @@ async fn pr_merged_by_an_unlinked_github_account_is_not_credited() {
assert!(status_calls[0].credited_user.is_none());
}
+#[tokio::test]
+async fn pr_merged_by_an_unlinked_account_records_who_merged() {
+ 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,
+ "html_url": "https://github.com/my-org/my-repo/pull/42",
+ "merged_by": { "login": "someone-else", "id": 444 }
+ },
+ "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!(status_calls[0].credited_user.is_none());
+ assert_eq!(
+ status_calls[0].source,
+ Some(PropertyChangeSource::GithubPullRequest {
+ url: "https://github.com/my-org/my-repo/pull/42".to_string(),
+ account: GithubAccount {
+ id: "444".to_string(),
+ login: "someone-else".to_string(),
+ },
+ })
+ );
+}
+
#[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/models_properties/AGENTS.md b/crates/models_properties/AGENTS.md
index 7965bfbcc5..7ab28e2d8a 100644
--- a/crates/models_properties/AGENTS.md
+++ b/crates/models_properties/AGENTS.md
@@ -31,7 +31,7 @@ split into three layers plus a `shared` layer used by all of them.
- Depends on: `document_sub_type`.
- Used by: `agent_trigger`, `ai_tools`, `complete_graph`, `crm`, `databases`,
`databases_sql`, `documents`, `document_storage_service`, `email_service`,
- `forms`, `graphql_common`, `graphql_crm`, `graphql_initiative`,
+ `forms`, `github`, `graphql_common`, `graphql_crm`, `graphql_initiative`,
`graphql_properties`, `graphql_soup`, `import`, `initiative`, `messages`,
`models_soup`, `properties`, `properties_service`, `scheduled_action`,
`search_service`, `soup`, `soup_realtime`, `system_properties`.
diff --git a/crates/models_properties/src/service/mod.rs b/crates/models_properties/src/service/mod.rs
index 71d01c4679..c44701e43c 100644
--- a/crates/models_properties/src/service/mod.rs
+++ b/crates/models_properties/src/service/mod.rs
@@ -7,6 +7,7 @@ pub mod document_metadata;
pub mod entity_property;
pub mod entity_property_with_definition;
pub mod project_metadata;
+pub mod property_change_source;
pub mod property_definition;
pub mod property_definition_with_options;
pub mod property_option;
diff --git a/crates/models_properties/src/service/property_change_source.rs b/crates/models_properties/src/service/property_change_source.rs
new file mode 100644
index 0000000000..2af8418de6
--- /dev/null
+++ b/crates/models_properties/src/service/property_change_source.rs
@@ -0,0 +1,25 @@
+//! The outside event behind a property change.
+
+use serde::{Deserialize, Serialize};
+
+/// What outside Macro caused a property change.
+#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
+#[serde(tag = "type", rename_all = "snake_case")]
+pub enum PropertyChangeSource {
+ /// A GitHub pull request event.
+ GithubPullRequest {
+ /// The pull request's URL.
+ url: String,
+ /// The GitHub account behind the change, linked to Macro or not.
+ account: GithubAccount,
+ },
+}
+
+/// A GitHub account, which may have no Macro user.
+#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
+pub struct GithubAccount {
+ /// GitHub's numeric user id.
+ pub id: String,
+ /// The account's login.
+ pub login: String,
+}
diff --git a/crates/properties/README.md b/crates/properties/README.md
index 8c33132d70..ae64e0a2ed 100644
--- a/crates/properties/README.md
+++ b/crates/properties/README.md
@@ -27,7 +27,8 @@ cleanup is an internal call and produces `entity_properties.cleared` with a null
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
+otherwise; either way its `source` names the pull request and GitHub account.
+Optional metadata fields are serialized as `null` unless their reused
nested model specifies otherwise.
| Event name | Emitted after | Metadata |
@@ -37,7 +38,7 @@ nested model specifies otherwise.
| `property_option.created` | An option is added to a SELECT or TAG definition. | `option_id`, `property_definition_id`, `actor_user_id`, `value`, `color`, `display_order` |
| `property_option.updated` | An option is renamed, recolored, reordered, or moved to another definition by a tag promotion. The metadata is the full post-update state, not a delta, so `property_definition_id` is the definition that owns the option *after* the change. | `option_id`, `property_definition_id`, `actor_user_id`, `value`, `color`, `display_order` |
| `property_option.deleted` | An option is deleted. `value` is the pre-delete snapshot. | `option_id`, `property_definition_id`, `actor_user_id`, `value` |
-| `entity_property.updated` | An entity value is set, replaced, attached with a null value, changed by an option add/remove, or has a deleted option stripped from it. Bulk operations emit one event for each actual `(entity, property_definition)` mutation. | `entity_property_id`, `entity_id`, `entity_type`, `property_definition_id`, `actor_user_id`, `value`, `updated_at` |
+| `entity_property.updated` | An entity value is set, replaced, attached with a null value, changed by an option add/remove, or has a deleted option stripped from it. Bulk operations emit one event for each actual `(entity, property_definition)` mutation. | `entity_property_id`, `entity_id`, `entity_type`, `property_definition_id`, `actor_user_id`, `source` (the outside event behind the change; the key is omitted when there is none), `value`, `updated_at` |
| `entity_property.deleted` | One entity-property row is deleted. | `entity_property_id`, `entity_id`, `entity_type`, `property_definition_id`, `actor_user_id` |
| `entity_properties.cleared` | `delete_entity_properties` successfully wipes all property values for an entity, including the document-deletion path. One clear event replaces per-value deletion events. | `entity_id`, `entity_type`, `actor_user_id` |
diff --git a/crates/properties/src/domain/activity/test.rs b/crates/properties/src/domain/activity/test.rs
index b4e36d48d5..158bc9cd82 100644
--- a/crates/properties/src/domain/activity/test.rs
+++ b/crates/properties/src/domain/activity/test.rs
@@ -27,6 +27,7 @@ fn update(actor: Option<MacroUserIdStr<'static>>) -> EntityPropertyUpdatedMetada
actor_user_id: actor,
actor: None,
on_behalf_of: None,
+ source: None,
value: None,
previous_value: None,
updated_at: Utc::now(),
diff --git a/crates/properties/src/domain/events.rs b/crates/properties/src/domain/events.rs
index 2aa3a5289e..45894a6466 100644
--- a/crates/properties/src/domain/events.rs
+++ b/crates/properties/src/domain/events.rs
@@ -11,6 +11,7 @@ use chrono::{DateTime, Utc};
use macro_event_broker::{Event, MacroEvent, TopicEvent};
use macro_event_topics::MacroPropertiesTopic;
use macro_user_id::user_id::MacroUserIdStr;
+use models_properties::service::property_change_source::PropertyChangeSource;
use models_properties::service::property_option::PropertyOptionValue;
use models_properties::service::property_value::PropertyValue;
use models_properties::{DataType, EntityType, PropertyOwner};
@@ -122,6 +123,9 @@ pub struct EntityPropertyUpdatedMetadata {
/// [`Self::actor`]. Absent means the actor is also the subject.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub on_behalf_of: Option<MacroUserIdStr<'static>>,
+ /// The outside event behind the change, when an integration made it.
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub source: Option<PropertyChangeSource>,
/// Full value after the update, or `None` when cleared without deleting the row.
pub value: Option<PropertyValue>,
/// Full value before the update: `None` when the property was newly
diff --git a/crates/properties/src/domain/events/test.rs b/crates/properties/src/domain/events/test.rs
index 037d79070b..aaccca0d60 100644
--- a/crates/properties/src/domain/events/test.rs
+++ b/crates/properties/src/domain/events/test.rs
@@ -162,6 +162,7 @@ fn topic_events(
actor_user_id: actor_user_id.clone(),
actor: None,
on_behalf_of: None,
+ source: None,
value: Some(PropertyValue::SelectOption(vec![uuid(OPTION_ID)])),
previous_value: None,
updated_at: timestamp(UPDATED_AT),
diff --git a/crates/properties/src/domain/service.rs b/crates/properties/src/domain/service.rs
index 1f8a5b4d68..3490bb516d 100644
--- a/crates/properties/src/domain/service.rs
+++ b/crates/properties/src/domain/service.rs
@@ -18,6 +18,7 @@ use models_properties::api::{
AddPropertyOptionRequest, CreatePropertyDefinitionRequest, UpdatePropertyOptionRequest,
};
use models_properties::service::entity_property_with_definition::EntityPropertyWithDefinition;
+use models_properties::service::property_change_source::PropertyChangeSource;
use models_properties::service::property_definition::PropertyDefinition;
use models_properties::service::property_definition_with_options::PropertyDefinitionWithOptions;
use models_properties::service::property_option::PropertyOption;
@@ -86,6 +87,16 @@ pub trait PropertiesService: Send + Sync + 'static {
value: Option<SetPropertyValue>,
) -> impl Future<Output = Result<EntityPropertyWithDefinition, PropertiesErr>> + Send;
+ /// [`Self::set_entity_property`] that records the outside event behind the
+ /// change on the published `entity_property.updated`.
+ fn set_entity_property_with_source(
+ &self,
+ access: &EditReceipt,
+ property_definition_id: Uuid,
+ value: Option<SetPropertyValue>,
+ source: Option<PropertyChangeSource>,
+ ) -> impl Future<Output = Result<EntityPropertyWithDefinition, PropertiesErr>> + Send;
+
/// Append the project's agent assignees to a newly added task, preserving
/// existing assignees and concurrent edits. Both capabilities must belong
/// to the same actor. Publishes assignment changes with the task's attribution.
diff --git a/crates/properties/src/domain/service_impl.rs b/crates/properties/src/domain/service_impl.rs
index c853f967a4..062a50d6db 100644
--- a/crates/properties/src/domain/service_impl.rs
+++ b/crates/properties/src/domain/service_impl.rs
@@ -26,6 +26,7 @@ use models_properties::api::{
use models_properties::convert_set_property_value_to_property_value;
use models_properties::service::entity_property::EntityProperty;
use models_properties::service::entity_property_with_definition::EntityPropertyWithDefinition;
+use models_properties::service::property_change_source::PropertyChangeSource;
use models_properties::service::property_definition::PropertyDefinition;
use models_properties::service::property_definition_with_options::PropertyDefinitionWithOptions;
use models_properties::service::property_option::{PropertyOption, PropertyOptionValue};
@@ -247,6 +248,7 @@ where
value: &Option<PropertyValue>,
previous_value: &Option<PropertyValue>,
access: &EditReceipt,
+ source: Option<&PropertyChangeSource>,
) -> PropertyMacroEvent {
let PublishedEventActors {
actor,
@@ -261,6 +263,7 @@ where
actor_user_id,
actor,
on_behalf_of,
+ source: source.cloned(),
value: value.clone(),
previous_value: previous_value.clone(),
updated_at: property.updated_at,
@@ -282,6 +285,7 @@ where
&mutation.value,
&mutation.previous_value,
access,
+ None,
));
}
}
@@ -465,6 +469,7 @@ where
actor_user_id: Some(actor.clone().into_owned()),
actor: None,
on_behalf_of: None,
+ source: None,
value: mutation.value.clone(),
previous_value: mutation.previous_value.clone(),
updated_at: mutation.property.updated_at,
@@ -613,20 +618,32 @@ where
self.get_property_value(access, property_key.uuid()).await
}
+ async fn set_entity_property(
+ &self,
+ access: &EditReceipt,
+ property_definition_id: Uuid,
+ value: Option<SetPropertyValue>,
+ ) -> Result<EntityPropertyWithDefinition, PropertiesErr> {
+ self.set_entity_property_with_source(access, property_definition_id, value, None)
+ .await
+ }
+
#[tracing::instrument(
- skip(self, access),
+ skip(self, access, source),
fields(
entity_id = %access.entity_id(),
entity_type = ?access.entity_type(),
property_definition_id = %property_definition_id,
- has_value = value.is_some()
+ has_value = value.is_some(),
+ has_source = source.is_some()
)
)]
- async fn set_entity_property(
+ async fn set_entity_property_with_source(
&self,
access: &EditReceipt,
property_definition_id: Uuid,
value: Option<SetPropertyValue>,
+ source: Option<PropertyChangeSource>,
) -> Result<EntityPropertyWithDefinition, PropertiesErr> {
let subject = self.resolve_subject(access).await?;
let entity_id = access.entity_id();
@@ -718,6 +735,7 @@ where
// value; the activity transition simply omits its "from" side.
&None,
access,
+ source.as_ref(),
));
return Ok(EntityPropertyWithDefinition {
property,
@@ -765,6 +783,7 @@ where
&property_value,
&snapshot.previous_value,
access,
+ source.as_ref(),
));
Ok(EntityPropertyWithDefinition {
@@ -838,6 +857,7 @@ where
&mutation.value,
&mutation.previous_value,
task,
+ None,
));
}
Ok(())
@@ -902,6 +922,7 @@ where
&mutation.value,
&mutation.previous_value,
access,
+ None,
));
Ok(())
@@ -940,6 +961,7 @@ where
&mutation.value,
&mutation.previous_value,
access,
+ None,
));
}
diff --git a/crates/properties/src/domain/test.rs b/crates/properties/src/domain/test.rs
index 68bffb4c0c..3208a53239 100644
--- a/crates/properties/src/domain/test.rs
+++ b/crates/properties/src/domain/test.rs
@@ -23,6 +23,7 @@ use entity_access::domain::models::{
};
use macro_event_broker::{EventBrokerError, MacroEvent, MacroEventBroker};
use macro_user_id::{cowlike::CowLike, user_id::MacroUserIdStr};
+use models_properties::service::property_change_source::{GithubAccount, PropertyChangeSource};
use models_properties::{
DataType, EntityType, PropertyOwner,
api::{
@@ -1344,6 +1345,62 @@ async fn entity_property_event_attributes_team_bot_but_not_system_access() {
}
}
+#[tokio::test]
+async fn entity_property_event_records_the_outside_source_of_an_internal_write() {
+ let access = EditReceipt::dangerously_assert_internal_user("doc1", AccessEntityType::Document);
+ let property_definition_id = Uuid::from_u128(0xE70A);
+ let assignment = entity_property_for_event(
+ Uuid::from_u128(0xE70B),
+ "doc1",
+ EntityType::Document,
+ property_definition_id,
+ event_timestamp(),
+ );
+ let mut repo = MockPropertiesRepo::new();
+ repo.expect_get_property_definition().return_once(move |_| {
+ Box::pin(async move { Ok(Some(multi_select_definition(property_definition_id, false))) })
+ });
+ repo.expect_upsert_entity_property()
+ .return_once(move |_, _, _, _| {
+ Box::pin(async move {
+ Ok(EntityPropertyMutationSnapshot {
+ property: assignment,
+ value: None,
+ previous_value: None,
+ })
+ })
+ });
+ let event_broker = RecordingEventBroker::default();
+ let service = service_with_event_broker(repo, event_broker.clone());
+
+ service
+ .set_entity_property_with_source(
+ &access,
+ property_definition_id,
+ None,
+ Some(PropertyChangeSource::GithubPullRequest {
+ url: "https://github.com/my-org/my-repo/pull/42".to_string(),
+ account: GithubAccount {
+ id: "444".to_string(),
+ login: "someone-else".to_string(),
+ },
+ }),
+ )
+ .await
+ .unwrap();
+
+ let published = only_published_property_event(&event_broker);
+ assert_eq!(
+ published.envelope["metadata"]["source"],
+ serde_json::json!({
+ "type": "github_pull_request",
+ "url": "https://github.com/my-org/my-repo/pull/42",
+ "account": { "id": "444", "login": "someone-else" },
+ })
+ );
+ assert!(published.envelope["metadata"]["actor_user_id"].is_null());
+}
+
#[tokio::test]
async fn entity_property_event_delegates_user_scoped_bot_writes() {
let bot_id = BotId::new_from_uuid(uuid::uuid!("00000000-0000-0000-0000-000000005759"));
diff --git a/crates/scheduled_action/AGENTS.md b/crates/scheduled_action/AGENTS.md
index 563d282ba6..33dd0c392c 100644
--- a/crates/scheduled_action/AGENTS.md
+++ b/crates/scheduled_action/AGENTS.md
@@ -77,7 +77,9 @@ that listener is ready. Cancellation can stop the gate before startup finishes.
`RoutineSessions::prepare` checks again on every run, then adds them to an
agent limited to selected apps. An update that omits the key is rejected
when the stored task has apps (`require_explicit_selection`).
-- Macro events store only ids and are read again, as the owner, at dispatch.
+- Macro events store only ids, plus the GitHub pull request and account behind
+ a task status change (`change_source`), and are read again, as the owner, at
+ dispatch.
GitHub deliveries can't be read again, so their event runs keep the bounded
payload in `event_context`; access for them is the owner's installation
claim, which needs a linked GitHub account and, for a personal installation,
@@ -95,6 +97,8 @@ that listener is ready. Cancellation can stop the gate before startup finishes.
it after the template is unshared or its source routine is deleted.
- `run_visibility` is copied onto each run's agent session when the run is
prepared, so changing it affects later runs only.
+- `EventReference` rejects unknown keys, so a replica still on older code can't
+ read a run row with a new key: write a new optional key only when it is set.
## Related
diff --git a/crates/scheduled_action/src/domain/event_trigger.rs b/crates/scheduled_action/src/domain/event_trigger.rs
index 421514f05c..e1c28a72e1 100644
--- a/crates/scheduled_action/src/domain/event_trigger.rs
+++ b/crates/scheduled_action/src/domain/event_trigger.rs
@@ -1,9 +1,10 @@
//! Routine-owned event eligibility and exact selector matching.
//!
//! Adapters strip the broker envelope into [`IncomingEvent`]. Only explicitly
-//! allowlisted human actions, inbound emails, call lifecycle events and GitHub
-//! App deliveries become [`EventReference`]s. GitHub deliveries can also be
-//! filtered on exact payload values.
+//! allowlisted human actions, inbound emails, call lifecycle events, task status
+//! changes from GitHub pull requests and GitHub App deliveries become
+//! [`EventReference`]s. GitHub deliveries can also be filtered on exact payload
+//! values.
use activity::Actor;
use call::domain::events::CallTopicEvent;
@@ -26,6 +27,7 @@ use messages::domain::{
models::MessageParent,
};
use models_properties::EntityType as PropertyEntityType;
+use models_properties::service::property_change_source::PropertyChangeSource;
use properties::domain::events::PropertyTopicEvent;
use serde::{Deserialize, Serialize};
use serde_json::Value;
@@ -571,8 +573,9 @@ impl EventId {
}
}
-/// Durable context. A Macro event keeps no content, actor, owner or full
-/// envelope: dispatch reads its content again, as the routine's owner. An
+/// Durable context. A Macro event keeps no content, owner or full envelope:
+/// dispatch reads its content again, as the routine's owner. Its only actor is
+/// the GitHub account in a change source, which nothing else records. An
/// external delivery has nothing to read again, so it keeps its payload.
/// The entity kind and publication timestamp derive from the name and event ID.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
@@ -586,10 +589,12 @@ pub struct EventReference {
/// What an event is about.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum EventSource {
- /// A Macro entity, and the message the event concerns.
+ /// A Macro entity, the message the event concerns, and what outside Macro
+ /// changed it.
Entity {
entity_id: Uuid,
message_id: Option<Uuid>,
+ change_source: Option<PropertyChangeSource>,
},
/// A delivery from Macro's GitHub App. Boxed: it carries its payload.
Github(Box<GithubWebhookReceived>),
@@ -607,6 +612,8 @@ struct EventReferenceInput {
message_id: Option<Option<Uuid>>,
#[serde(default, skip_serializing_if = "Option::is_none")]
github: Option<Box<GithubWebhookReceived>>,
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ change_source: Option<PropertyChangeSource>,
}
fn skip_message_id(message_id: &Option<Option<Uuid>>) -> bool {
@@ -627,9 +634,14 @@ impl TryFrom<EventReferenceInput> for EventReference {
EventSource::Entity {
entity_id,
message_id,
+ change_source: input.change_source,
}
}
- (None, Some(delivery)) if name == EventName::Github => EventSource::Github(delivery),
+ (None, Some(delivery))
+ if name == EventName::Github && input.change_source.is_none() =>
+ {
+ EventSource::Github(delivery)
+ }
_ => return Err(EventRejection::InvalidContext),
};
Ok(Self {
@@ -648,14 +660,17 @@ impl From<EventReference> for EventReferenceInput {
entity_id: None,
message_id: None,
github: None,
+ change_source: None,
};
match event.source {
EventSource::Entity {
entity_id,
message_id,
+ change_source,
} => {
input.entity_id = Some(entity_id);
input.message_id = Some(message_id);
+ input.change_source = change_source;
}
EventSource::Github(delivery) => input.github = Some(delivery),
}
@@ -689,6 +704,12 @@ impl EventReference {
EventSource::Github(_) => None,
}
}
+ pub fn change_source(&self) -> Option<&PropertyChangeSource> {
+ match &self.source {
+ EventSource::Entity { change_source, .. } => change_source.as_ref(),
+ EventSource::Github(_) => None,
+ }
+ }
pub fn published_at(&self) -> DateTime<Utc> {
self.event_id.published_at()
}
@@ -799,6 +820,7 @@ impl IncomingEvent {
return Err(EventRejection::UnsupportedSchema);
}
let event_id = EventId::try_from(self.event_id)?;
+ let mut change_source = None;
let (event_name, entity_id, message_id) = match &self.payload {
EventPayload::Document(event) => {
let (name, id) = match event {
@@ -885,8 +907,9 @@ impl IncomingEvent {
MessageFact::Other => return Err(EventRejection::UnsupportedEvent),
},
EventPayload::Property(event) => {
- let (name, id) = task_property_event(event)?;
+ let (name, id, property_source) = task_property_event(event)?;
let id = Uuid::parse_str(id).map_err(|_| EventRejection::InvalidEntityId)?;
+ change_source = property_source;
(name, id, None)
}
EventPayload::Email(EmailTopicEvent::MessageReceived(data)) => {
@@ -934,13 +957,16 @@ impl IncomingEvent {
source: EventSource::Entity {
entity_id,
message_id,
+ change_source,
},
})
}
}
-fn task_property_event(event: &PropertyTopicEvent) -> Result<(EventName, &str), EventRejection> {
- let (entity_type, entity_id, property_id, actor, fallback, delegated) = match event {
+fn task_property_event(
+ event: &PropertyTopicEvent,
+) -> Result<(EventName, &str, Option<PropertyChangeSource>), EventRejection> {
+ let (entity_type, entity_id, property_id, actor, fallback, delegated, source) = match event {
PropertyTopicEvent::EntityPropertyUpdated(data) => {
if data.value == data.previous_value {
return Err(EventRejection::UnsupportedEvent);
@@ -952,6 +978,7 @@ fn task_property_event(event: &PropertyTopicEvent) -> Result<(EventName, &str),
data.actor.as_ref(),
data.actor_user_id.as_ref(),
data.on_behalf_of.is_some(),
+ data.source.clone(),
)
}
PropertyTopicEvent::EntityPropertyDeleted(data) => (
@@ -961,6 +988,7 @@ fn task_property_event(event: &PropertyTopicEvent) -> Result<(EventName, &str),
data.actor.as_ref(),
data.actor_user_id.as_ref(),
data.on_behalf_of.is_some(),
+ None,
),
PropertyTopicEvent::EntityPropertiesCleared(data) => (
&data.entity_type,
@@ -969,6 +997,7 @@ fn task_property_event(event: &PropertyTopicEvent) -> Result<(EventName, &str),
data.actor.as_ref(),
data.actor_user_id.as_ref(),
data.on_behalf_of.is_some(),
+ None,
),
_ => return Err(EventRejection::UnsupportedEvent),
};
@@ -976,11 +1005,18 @@ fn task_property_event(event: &PropertyTopicEvent) -> Result<(EventName, &str),
if *entity_type != PropertyEntityType::Task {
return Err(EventRejection::UnsupportedEvent);
}
- document_actor(actor, fallback, delegated)?;
let name = match property_id {
Some(SystemPropertyKey::STATUS_UUID) => EventName::TaskStatusChanged,
Some(SystemPropertyKey::PRIORITY_UUID) => EventName::TaskPriorityChanged,
_ => EventName::TaskPropertyChanged,
};
- Ok((name, entity_id))
+ // GitHub reports what happened to a pull request whether or not its account
+ // has a Macro user, so its status changes need no Macro actor. An actor that
+ // is present still has to be a person.
+ let from_github =
+ name == EventName::TaskStatusChanged && source.is_some() && actor.is_none() && !delegated;
+ if !from_github {
+ document_actor(actor, fallback, delegated)?;
+ }
+ Ok((name, entity_id, source))
}
diff --git a/crates/scheduled_action/src/domain/event_trigger/test.rs b/crates/scheduled_action/src/domain/event_trigger/test.rs
index fd2f019155..67248ff847 100644
--- a/crates/scheduled_action/src/domain/event_trigger/test.rs
+++ b/crates/scheduled_action/src/domain/event_trigger/test.rs
@@ -543,6 +543,76 @@ fn property_changes_ignore_other_entities_noops_and_bot_writes() {
}
}
+fn unattributed_status_change() -> Value {
+ let mut data = property_metadata();
+ data["actor"] = json!(null);
+ data["actor_user_id"] = json!(null);
+ data
+}
+
+fn github_source() -> Value {
+ json!({
+ "type": "github_pull_request",
+ "url": "https://github.com/my-org/my-repo/pull/42",
+ "account": {"id": "444", "login": "someone-else"}
+ })
+}
+
+#[test]
+fn a_status_change_from_github_needs_no_macro_actor() {
+ let mut data = unattributed_status_change();
+ data["source"] = github_source();
+
+ let event = property_event("entity_property.updated", data)
+ .normalize()
+ .unwrap();
+
+ assert_eq!(event.event_name(), EventName::TaskStatusChanged);
+ assert_eq!(
+ event.change_source(),
+ Some(&serde_json::from_value(github_source()).unwrap())
+ );
+ let stored = serde_json::to_value(&event).unwrap();
+ assert_eq!(
+ serde_json::from_value::<EventReference>(stored).unwrap(),
+ event
+ );
+}
+
+#[test]
+fn an_unattributed_status_change_with_no_source_stays_ignored() {
+ assert_eq!(
+ property_event("entity_property.updated", unattributed_status_change()).normalize(),
+ Err(EventRejection::UnsafeAttribution)
+ );
+}
+
+#[test]
+fn a_github_source_only_opens_status_changes() {
+ let mut data = unattributed_status_change();
+ data["source"] = github_source();
+ data["property_definition_id"] = json!(SystemPropertyKey::PRIORITY_UUID);
+
+ assert_eq!(
+ property_event("entity_property.updated", data).normalize(),
+ Err(EventRejection::UnsafeAttribution)
+ );
+}
+
+#[test]
+fn a_source_does_not_admit_a_change_made_by_a_bot_or_for_someone_else() {
+ for (field, value) in [("actor", BOT), ("on_behalf_of", HUMAN)] {
+ let mut data = unattributed_status_change();
+ data["source"] = github_source();
+ data[field] = json!(value);
+
+ assert_eq!(
+ property_event("entity_property.updated", data).normalize(),
+ Err(EventRejection::UnsafeAttribution)
+ );
+ }
+}
+
#[test]
fn mention_trigger_is_only_for_the_mentioned_user() {
let owner = MacroUserIdStr::parse_from_str(HUMAN).unwrap();
diff --git a/crates/scheduled_action/src/domain/target_runner/test.rs b/crates/scheduled_action/src/domain/target_runner/test.rs
index 2da1a9bbea..da227350f4 100644
--- a/crates/scheduled_action/src/domain/target_runner/test.rs
+++ b/crates/scheduled_action/src/domain/target_runner/test.rs
@@ -950,6 +950,7 @@ async fn a_task_status_change_hands_the_agent_the_task_instead_of_its_ids() {
}],
project: None,
},
+ pull_request: None,
};
let runner = TargetRunner::new(
Arc::new(Sessions {
diff --git a/crates/scheduled_action/src/outbound/event_content/routine_event.rs b/crates/scheduled_action/src/outbound/event_content/routine_event.rs
index 7cb923d911..e6ba830b78 100644
--- a/crates/scheduled_action/src/outbound/event_content/routine_event.rs
+++ b/crates/scheduled_action/src/outbound/event_content/routine_event.rs
@@ -12,7 +12,8 @@ use macro_uuid::Uuid;
use messages::domain::models::{Message, MessageThread};
use model::document::DocumentBasic;
use models_properties::service::{
- property_option::PropertyOptionValue, property_value::PropertyValue,
+ property_change_source::PropertyChangeSource, property_option::PropertyOptionValue,
+ property_value::PropertyValue,
};
use properties::EntityPropertyInfo;
use rootcause::Report;
@@ -20,7 +21,8 @@ use system_properties::SystemPropertyKey;
use trigger_context::{
CallSnapshot, CallStartedSnapshot, ChannelType, ContextAttachment, ContextMessage,
ContextPerson, ContextThread, DiscussionContext, DiscussionSurface, DocumentSnapshot,
- EmailSnapshot, GithubDelivery, ReplyTarget, RoutineEvent, TaskSnapshot, TranscriptLine,
+ EmailSnapshot, GithubDelivery, PullRequestChange, ReplyTarget, RoutineEvent, TaskSnapshot,
+ TranscriptLine,
};
use super::{
@@ -47,7 +49,13 @@ pub(super) fn routine_event(
document,
properties,
markdown,
- } => document_event(name, document, &properties, markdown.as_deref()),
+ } => document_event(
+ name,
+ document,
+ &properties,
+ markdown.as_deref(),
+ event.change_source(),
+ ),
EventContent::Email(message) => match (name, message) {
(EventName::EmailMessageReceived, Some(message)) => Ok(RoutineEvent::EmailReceived {
email: email_snapshot(entity_id()?, &message),
@@ -96,6 +104,7 @@ fn document_event(
document: DocumentBasic,
properties: &[EntityPropertyInfo],
markdown: Option<&str>,
+ source: Option<&PropertyChangeSource>,
) -> Result<RoutineEvent, Report> {
Ok(match name {
EventName::DocumentCreated => RoutineEvent::DocumentCreated {
@@ -113,6 +122,7 @@ fn document_event(
},
EventName::TaskStatusChanged => RoutineEvent::TaskStatusChanged {
task: task_snapshot(document, properties, markdown),
+ pull_request: source.map(pull_request_change),
},
EventName::TaskPriorityChanged => RoutineEvent::TaskPriorityChanged {
task: task_snapshot(document, properties, markdown),
@@ -124,6 +134,15 @@ fn document_event(
})
}
+fn pull_request_change(source: &PropertyChangeSource) -> PullRequestChange {
+ match source {
+ PropertyChangeSource::GithubPullRequest { url, account } => PullRequestChange {
+ url: url.clone(),
+ github_login: account.login.clone(),
+ },
+ }
+}
+
fn channel_event(
name: EventName,
channel_id: Uuid,
diff --git a/crates/scheduled_action/src/outbound/event_content/routine_event/test.rs b/crates/scheduled_action/src/outbound/event_content/routine_event/test.rs
index a72be07a36..21e2dc2f0f 100644
--- a/crates/scheduled_action/src/outbound/event_content/routine_event/test.rs
+++ b/crates/scheduled_action/src/outbound/event_content/routine_event/test.rs
@@ -21,8 +21,8 @@ use serde_json::json;
use system_properties::SystemPropertyKey;
use trigger_context::{
CallSnapshot, CallStartedSnapshot, ChannelType, ContextMessage, ContextPerson, ContextThread,
- DiscussionContext, DiscussionSurface, EmailSnapshot, ReplyTarget, RoutineEvent, TaskSnapshot,
- TranscriptLine,
+ DiscussionContext, DiscussionSurface, EmailSnapshot, PullRequestChange, ReplyTarget,
+ RoutineEvent, TaskSnapshot, TranscriptLine,
};
use super::super::{ChannelMessage, EventContent, MAX_TRANSCRIPT_CHARS};
@@ -331,10 +331,56 @@ fn a_task_status_change_carries_the_task_as_it_reads_now() {
}],
project: None,
},
+ pull_request: None,
}
);
}
+#[test]
+fn a_status_change_from_a_pull_request_names_it_and_who_acted() {
+ let event: EventReference = serde_json::from_value(json!({
+ "event_id": "01928f3e-6a2b-7c3d-8e4f-0123456789cd",
+ "event_name": "task.status_changed",
+ "entity_id": "01928f3e-6a2b-7c3d-8e4f-000000007a5c",
+ "message_id": null,
+ "change_source": {
+ "type": "github_pull_request",
+ "url": "https://github.com/my-org/my-repo/pull/42",
+ "account": { "id": "444", "login": "someone-else" },
+ },
+ }))
+ .unwrap();
+ let content = EventContent::Document {
+ document: DocumentBasic {
+ document_id: "01928f3e-6a2b-7c3d-8e4f-000000007a5c".into(),
+ document_name: "Login page crashes on Safari".into(),
+ owner: Owner::User(MacroUserIdStr::parse_from_str("macro|[email protected]").unwrap()),
+ file_type: Some("md".into()),
+ sub_type: Some(DocumentSubType::Task),
+ branched_from_id: None,
+ branched_from_version_id: None,
+ document_family_id: None,
+ project_id: None,
+ deleted_at: None,
+ },
+ properties: Vec::new(),
+ markdown: None,
+ };
+
+ let RoutineEvent::TaskStatusChanged { pull_request, .. } =
+ routine_event(&event, content).unwrap()
+ else {
+ panic!("expected a task status change");
+ };
+ assert_eq!(
+ pull_request,
+ Some(PullRequestChange {
+ url: "https://github.com/my-org/my-repo/pull/42".into(),
+ github_login: "someone-else".into(),
+ })
+ );
+}
+
#[test]
fn a_received_email_carries_its_headers_and_reply_free_body() {
let event: EventReference = serde_json::from_value(json!({
diff --git a/crates/scheduled_action/src/outbound/pg_event_run_repo/test.rs b/crates/scheduled_action/src/outbound/pg_event_run_repo/test.rs
index 0984d97ff1..c5b0d6d4e8 100644
--- a/crates/scheduled_action/src/outbound/pg_event_run_repo/test.rs
+++ b/crates/scheduled_action/src/outbound/pg_event_run_repo/test.rs
@@ -1079,6 +1079,50 @@ async fn conditions_do_not_change_candidate_matching(pool: PgPool) {
admit(&repo, id, &event).await;
}
+#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
+async fn a_run_keeps_its_change_source_and_writes_the_key_only_when_set(pool: PgPool) {
+ let sourced_action = action(&pool, json!([{"events":["task.status_changed"]}])).await;
+ let plain_action = action(&pool, json!([{"events":["task.status_changed"]}])).await;
+ let repo = PgEventRunRepo::new(pool.clone());
+ let sourced: EventReference = serde_json::from_value(json!({
+ "event_id": generate_uuid_v7(),
+ "event_name": "task.status_changed",
+ "entity_id": generate_uuid_v7(),
+ "message_id": null,
+ "change_source": {
+ "type": "github_pull_request",
+ "url": "https://github.com/my-org/my-repo/pull/42",
+ "account": { "id": "444", "login": "someone-else" },
+ },
+ }))
+ .unwrap();
+ let plain: EventReference = serde_json::from_value(json!({
+ "event_id": generate_uuid_v7(),
+ "event_name": "task.status_changed",
+ "entity_id": generate_uuid_v7(),
+ "message_id": null,
+ }))
+ .unwrap();
+
+ admit(&repo, sourced_action, &sourced).await;
+ admit(&repo, plain_action, &plain).await;
+
+ let pending = repo.pending_runs(page(100)).await.unwrap();
+ let run = pending
+ .iter()
+ .find(|run| run.action_id == sourced_action)
+ .unwrap();
+ assert_eq!(run.event, sourced);
+ let plain_context = sqlx::query_scalar!(
+ "SELECT event_context FROM scheduled_action_event_run WHERE action_id = $1",
+ plain_action,
+ )
+ .fetch_one(&pool)
+ .await
+ .unwrap();
+ assert!(plain_context.get("change_source").is_none());
+}
+
fn github_event(event: &str) -> EventReference {
serde_json::from_value(json!({
"event_id": generate_uuid_v7(),
diff --git a/crates/soup_realtime/src/inbound/kafka_consumer/test.rs b/crates/soup_realtime/src/inbound/kafka_consumer/test.rs
index 00b31512e6..75f95b1008 100644
--- a/crates/soup_realtime/src/inbound/kafka_consumer/test.rs
+++ b/crates/soup_realtime/src/inbound/kafka_consumer/test.rs
@@ -338,6 +338,7 @@ fn task_property_updates_map_to_document_updates() {
actor_user_id: Some(user()),
actor: None,
on_behalf_of: None,
+ source: None,
value: None,
previous_value: None,
updated_at: Utc::now(),
@@ -467,6 +468,7 @@ fn a_cell_edit_updates_the_database_row() {
actor_user_id: Some(user()),
actor: None,
on_behalf_of: None,
+ source: None,
value: None,
previous_value: None,
updated_at: Utc::now(),
@@ -1045,6 +1047,7 @@ fn moving_a_task_between_projects_refreshes_the_task_and_both_projects() {
actor_user_id: Some(user()),
actor: None,
on_behalf_of: None,
+ source: None,
value: project("project-to"),
previous_value: project("project-from"),
updated_at: Utc::now(),
diff --git a/crates/trigger_context/src/lib.rs b/crates/trigger_context/src/lib.rs
index 0db1b4939f..04451a5456 100644
--- a/crates/trigger_context/src/lib.rs
+++ b/crates/trigger_context/src/lib.rs
@@ -533,6 +533,15 @@ pub enum RoutineFiring {
},
}
+/// The GitHub pull request event behind a change.
+#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
+pub struct PullRequestChange {
+ /// The pull request's URL.
+ pub url: String,
+ /// The GitHub login behind the change: whoever merged it, on a merge.
+ pub github_login: String,
+}
+
/// The event a routine fired on, one variant per event it can watch.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(tag = "event", rename_all = "snake_case")]
@@ -563,6 +572,9 @@ pub enum RoutineEvent {
TaskStatusChanged {
/// The task as it reads now.
task: TaskSnapshot,
+ /// The pull request event that changed it, when one did.
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pull_request: Option<PullRequestChange>,
},
/// A task's priority changed.
TaskPriorityChanged {
diff --git a/packages/lexical-core/tests/agent-trigger-context.test.ts b/packages/lexical-core/tests/agent-trigger-context.test.ts
index 1a6de4b711..1e578dd830 100644
--- a/packages/lexical-core/tests/agent-trigger-context.test.ts
+++ b/packages/lexical-core/tests/agent-trigger-context.test.ts
@@ -614,6 +614,45 @@ describe('composeAgentContextPrompt with a trigger', () => {
);
});
+ it('names the pull request and who acted when one changed the task status', () => {
+ const markdown = composeAgentContextPrompt({
+ promptMarkdown: 'Tell me what landed.',
+ trigger: {
+ kind: 'routine',
+ routine_id: 'r-3',
+ name: 'Watch the fix',
+ owner: {
+ id: 'macro|[email protected]',
+ name: 'Julia',
+ email: '[email protected]',
+ },
+ instructions: 'Tell me when this ships.',
+ triggers: [{ type: 'events', events: ['task.status_changed'] }],
+ firing: {
+ type: 'event',
+ event: {
+ event: 'task_status_changed',
+ task: {
+ id: 'task-3',
+ title: 'Renew SSL cert',
+ markdown: 'Expires Friday.',
+ status: 'Completed',
+ },
+ pull_request: {
+ url: 'https://github.com/my-org/my-repo/pull/42',
+ github_login: 'someone-else',
+ },
+ },
+ conditions: [],
+ },
+ },
+ });
+
+ expect(hiddenContext(markdown)).toContain(
+ '<change property="status" to="Completed" pull_request="https://github.com/my-org/my-repo/pull/42" by="someone-else"/>'
+ );
+ });
+
it('renders a routine fired by an email', () => {
const markdown = composeAgentContextPrompt({
promptMarkdown: 'File the invoice.',
diff --git a/packages/lexical-core/utils/agent-context.ts b/packages/lexical-core/utils/agent-context.ts
index 9887bcde6b..703179edb9 100644
--- a/packages/lexical-core/utils/agent-context.ts
+++ b/packages/lexical-core/utils/agent-context.ts
@@ -235,13 +235,24 @@ export type RoutineFiring =
conditions?: string[];
};
+/** The GitHub pull request event behind a change. */
+export type PullRequestChange = {
+ url: string;
+ /** Whoever merged it, on a merge; otherwise whoever acted on it. */
+ github_login: string;
+};
+
/** The event a routine fired on. */
export type RoutineEvent =
| { event: 'document_created'; document: DocumentSnapshot }
| { event: 'document_updated'; document: DocumentSnapshot }
| { event: 'document_deleted'; id: string; name: string }
| { event: 'task_created'; task: TaskSnapshot }
- | { event: 'task_status_changed'; task: TaskSnapshot }
+ | {
+ event: 'task_status_changed';
+ task: TaskSnapshot;
+ pull_request?: PullRequestChange;
+ }
| { event: 'task_priority_changed'; task: TaskSnapshot }
/** The event does not record which property changed. */
| { event: 'task_property_changed'; task: TaskSnapshot }
@@ -1330,8 +1341,17 @@ function routineEventChildren(event: RoutineEvent): FxpNode[] {
el('document', [], { id, name }),
])
.with({ event: 'task_created' }, ({ task }) => [taskNode(task)])
- .with({ event: 'task_status_changed' }, ({ task }) => [
- el('change', [], present({ property: 'status', to: task.status })),
+ .with({ event: 'task_status_changed' }, ({ task, pull_request }) => [
+ el(
+ 'change',
+ [],
+ present({
+ property: 'status',
+ to: task.status,
+ pull_request: pull_request?.url,
+ by: pull_request?.github_login,
+ })
+ ),
taskNode(task),
])
.with({ event: 'task_priority_changed' }, ({ task }) => [
diff --git a/services/document_storage_service/src/api/context.rs b/services/document_storage_service/src/api/context.rs
index 9a57c7f028..4c688847fa 100644
--- a/services/document_storage_service/src/api/context.rs
+++ b/services/document_storage_service/src/api/context.rs
@@ -125,6 +125,7 @@ use macro_authorization::{
};
use macro_env_var::env_var;
use macro_sha_count_client::Redis;
+use models_properties::service::property_change_source::PropertyChangeSource;
use models_properties::service::property_value::PropertyValue;
use notification::domain::service::SqsNotificationIngress;
use notification::outbound::queue::SqsQueue;
@@ -346,6 +347,7 @@ impl TaskPropertiesPort for TaskPropertiesAdapter {
&self,
access: &EntityAccessReceipt<EditAccessLevel>,
credited_user: Option<&macro_user_id::user_id::MacroUserIdStr<'static>>,
+ source: Option<&PropertyChangeSource>,
status: &str,
) -> anyhow::Result<()> {
use properties::PropertiesService as _;
@@ -371,7 +373,7 @@ impl TaskPropertiesPort for TaskPropertiesAdapter {
matches!(access.auth(), EntityAccessAuth::Authenticated(_)),
);
self.properties
- .set_entity_property(
+ .set_entity_property_with_source(
&access,
SystemPropertyKey::STATUS_UUID,
Some(
@@ -379,6 +381,7 @@ impl TaskPropertiesPort for TaskPropertiesAdapter {
option_id: status_option.uuid(),
},
),
+ source.cloned(),
)
.await
.map(|_| ())
diff --git a/services/lexical-service/src/endpoints/agent-context.ts b/services/lexical-service/src/endpoints/agent-context.ts
index 3933d7aa10..2d3ef33c68 100644
--- a/services/lexical-service/src/endpoints/agent-context.ts
+++ b/services/lexical-service/src/endpoints/agent-context.ts
@@ -200,6 +200,11 @@ const projectRef = z.object({
name: z.string(),
});
+const pullRequestChange = z.object({
+ url: z.string(),
+ github_login: z.string(),
+});
+
const taskSnapshot = z.object({
id: z.string().min(1),
title: z.string(),
@@ -273,7 +278,11 @@ const routineEvent = z.discriminatedUnion('event', [
name: z.string(),
}),
z.object({ event: z.literal('task_created'), task: taskSnapshot }),
- z.object({ event: z.literal('task_status_changed'), task: taskSnapshot }),
+ z.object({
+ event: z.literal('task_status_changed'),
+ task: taskSnapshot,
+ pull_request: pullRequestChange.optional(),
+ }),
z.object({ event: z.literal('task_priority_changed'), task: taskSnapshot }),
z.object({ event: z.literal('task_property_changed'), task: taskSnapshot }),
z.object({ event: z.literal('email_received'), email: emailSnapshot }),
diff --git a/services/search_processing_service/src/inbound/kafka_consumer/test.rs b/services/search_processing_service/src/inbound/kafka_consumer/test.rs
index 878e5caa70..6cef2a4015 100644
--- a/services/search_processing_service/src/inbound/kafka_consumer/test.rs
+++ b/services/search_processing_service/src/inbound/kafka_consumer/test.rs
@@ -1263,6 +1263,7 @@ fn property_event_cases() -> Vec<(PropertyTopicEvent, PropertyEventDescription<'
actor_user_id: actor_user_id.clone(),
actor: None,
on_behalf_of: None,
+ source: None,
value: None,
previous_value: None,
updated_at: Utc::now(),