Macro is a unified workspace for teams: email, chat, docs, tasks, agents, calls, and CRM — @-linked together with shared AI memory.
TypeScript agentaiai-agentsall-in-onecrmcrm-systememaillinearmcpmessagingnotesnotionofficerustslackslack-alternativestartupstartup-toolstypescriptworkspace
feat(github): sync task status from GitHub (#1782)
Will Hutchinsona136ca8969f2
diff --git a/rust/cloud-storage/document_storage_service/src/api/context.rs b/rust/cloud-storage/document_storage_service/src/api/context.rsindex 7a4c06529e..4f80177727 100644--- a/rust/cloud-storage/document_storage_service/src/api/context.rs+++ b/rust/cloud-storage/document_storage_service/src/api/context.rs@@ -48,7 +48,8 @@ use sqlx::PgPool;use std::sync::Arc;use sync_service_client::SyncServiceClient;use system_properties::{- PgSystemPropertiesRepository, SystemPropertiesService as _, SystemPropertiesServiceImpl,+ PgSystemPropertiesRepository, StatusOption, SystemPropertiesService as _,+ SystemPropertiesServiceImpl,};#[derive(Debug, Clone)]@@ -110,6 +111,14 @@ impl TaskPropertiesPort for TaskPropertiesAdapter {.await.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))?;++ self.0.update_task_status(task_id, status_option).await?;++ Ok(())+ }}/// Type alias for the documents router state.diff --git a/rust/cloud-storage/documents/examples/documents_toolset.rs b/rust/cloud-storage/documents/examples/documents_toolset.rsindex 2b24165f5c..41ac16624a 100644--- a/rust/cloud-storage/documents/examples/documents_toolset.rs+++ b/rust/cloud-storage/documents/examples/documents_toolset.rs@@ -43,6 +43,10 @@ impl TaskPropertiesPort for NoOpTaskProperties {async fn attach_task_properties(&self, _entity_ids: Vec<String>) -> anyhow::Result<()> {Ok(())}++ async fn update_task_status(&self, _task_id: &str, _status: &str) -> anyhow::Result<()> {+ Ok(())+ }}/// The prompt to use in the example.diff --git a/rust/cloud-storage/documents/src/domain/ports.rs b/rust/cloud-storage/documents/src/domain/ports.rsindex 5439178129..3cf4ba56e6 100644--- a/rust/cloud-storage/documents/src/domain/ports.rs+++ b/rust/cloud-storage/documents/src/domain/ports.rs@@ -4,7 +4,9 @@use std::future::Future;-use entity_access::domain::models::{EntityAccessReceipt, OwnerAccessLevel, ViewAccessLevel};+use entity_access::domain::models::{+ EditAccessLevel, EntityAccessReceipt, OwnerAccessLevel, ViewAccessLevel,+};use macro_user_id::user_id::MacroUserIdStr;use model::document::response::{CreateDocumentResponseData, GetDocumentResponseData, LocationResponseV3,@@ -129,6 +131,13 @@ pub trait TaskPropertiesPort: Send + Sync + 'static {&self,entity_ids: Vec<String>,) -> impl Future<Output = anyhow::Result<()>> + Send;++ /// Updates the tasks status+ fn update_task_status(+ &self,+ entity_id: &str,+ status: &str,+ ) -> impl Future<Output = anyhow::Result<()>> + Send;}/// Service interface for document operations.@@ -176,4 +185,11 @@ pub trait DocumentService: Send + Sync + 'static {args: CreateDocumentRepoArgs,job_id: Option<String>,) -> impl Future<Output = Result<CreateDocumentResponseData, DocumentError>> + Send;++ /// Updates the tasks status to what is provided+ fn update_task_status(+ &self,+ entity_access_receipt: EntityAccessReceipt<EditAccessLevel>,+ status: &str,+ ) -> impl Future<Output = Result<(), DocumentError>> + Send;}diff --git a/rust/cloud-storage/documents/src/domain/service.rs b/rust/cloud-storage/documents/src/domain/service.rsindex dd6f18dad7..6b3524fdb3 100644--- a/rust/cloud-storage/documents/src/domain/service.rs+++ b/rust/cloud-storage/documents/src/domain/service.rs@@ -544,4 +544,16 @@ impl<R: DocumentRepo, U: PresignedUploadUrlPort, T: TaskPropertiesPort> Documentfile_type: file_type.map(|f| f.to_string()),})}++ #[tracing::instrument(skip(self))]+ async fn update_task_status(+ &self,+ entity_access_receipt: EntityAccessReceipt<entity_access::domain::models::EditAccessLevel>,+ status: &str,+ ) -> Result<(), DocumentError> {+ self.task_properties_service+ .update_task_status(&entity_access_receipt.entity().entity_id, status)+ .await+ .map_err(DocumentError::Internal)+ }}diff --git a/rust/cloud-storage/github/src/domain/models/sync.rs b/rust/cloud-storage/github/src/domain/models/sync.rsindex 3860ba5c60..6dd2cefc95 100644--- a/rust/cloud-storage/github/src/domain/models/sync.rs+++ b/rust/cloud-storage/github/src/domain/models/sync.rs@@ -86,6 +86,56 @@ impl ValidatedGithubWebhookEvent {texts}+ /// Extract the `action` field from the webhook payload (e.g. "opened", "closed", "created").+ pub fn action(&self) -> Option<&str> {+ self.payload.get("action").and_then(|v| v.as_str())+ }++ /// Whether the pull request was merged (only meaningful for `closed` actions).+ pub fn is_merged(&self) -> bool {+ self.payload+ .get("pull_request")+ .and_then(|pr| pr.get("merged"))+ .and_then(|v| v.as_bool())+ .unwrap_or(false)+ }++ /// Derive the task status string based on the event, if applicable.+ ///+ /// For `pull_request` events: `opened`/`reopened` → `"In Review"`,+ /// `closed` + merged → `"Completed"`, `closed` → `"Canceled"`.+ ///+ /// For comment/review events that newly associate a task with an open PR,+ /// returns `"In Review"`.+ ///+ /// Returns `None` when no status change is warranted.+ pub fn task_status_for_event(&self) -> Option<&'static str> {+ match self.parsed_event_type() {+ GithubWebhookEventType::PullRequest => match self.action() {+ Some("opened" | "reopened" | "edited") => Some("In Review"),+ Some("closed") if self.is_merged() => Some("Completed"),+ Some("closed") => Some("Canceled"),+ _ => None,+ },+ GithubWebhookEventType::IssueComment+ | GithubWebhookEventType::PullRequestReview+ | GithubWebhookEventType::PullRequestReviewComment => {+ // A comment/review that introduces a new task association on an+ // open PR should mark the task as "In Review".+ let is_open = self+ .payload+ .get("pull_request")+ .or_else(|| self.payload.get("issue"))+ .and_then(|pr| pr.get("state"))+ .and_then(|v| v.as_str())+ == Some("open");++ if is_open { Some("In Review") } else { None }+ }+ GithubWebhookEventType::Unknown(_) => None,+ }+ }+/// Extract the pull request / issue number from the webhook payload.pub fn pull_number(&self) -> Option<u64> {self.payloaddiff --git a/rust/cloud-storage/github/src/domain/service/mod.rs b/rust/cloud-storage/github/src/domain/service/mod.rsindex fab784e299..0c5d013d22 100644--- a/rust/cloud-storage/github/src/domain/service/mod.rs+++ b/rust/cloud-storage/github/src/domain/service/mod.rs@@ -44,7 +44,7 @@ mod sync_impl {ports::{GithubSyncClient, GithubSyncService},};use documents::domain::{models::DocumentError, ports::DocumentService};- use entity_access::domain::models::ViewAccessLevel;+ use entity_access::domain::models::{EditAccessLevel, ViewAccessLevel};use hmac::{Hmac, Mac};use sha2::Sha256;use std::sync::Arc;@@ -113,28 +113,36 @@ mod sync_impl {let searchable_texts = webhook_event.extract_searchable_text();let combined = searchable_texts.join(" ");- let task_ids = MacroTaskId::extract_from_text(&combined);+ let all_task_ids = MacroTaskId::extract_from_text(&combined);- if task_ids.is_empty() {+ if all_task_ids.is_empty() {tracing::debug!(event_type=?event_type, "no task IDs found in event");return Ok(());}- // Filter out task IDs already present in the PR context (title, body, branch)- // so that e.g. a comment saying "Fixes MACRO-X" on a PR already titled MACRO-X- // does not trigger a duplicate association.- let pr_context = webhook_event.extract_pr_context_text().join(" ");- let existing_task_ids: std::collections::HashSet<_> =- MacroTaskId::extract_from_text(&pr_context)- .into_iter()- .collect();-- let new_task_ids: Vec<_> = task_ids- .into_iter()- .filter(|id| !existing_task_ids.contains(id))- .collect();-- if new_task_ids.is_empty() {+ // 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"@@ -187,92 +195,117 @@ mod sync_impl {}};- for task_id in &new_task_ids {- match task_id.to_uuid() {- Ok(uuid) => {- tracing::info!(- task_id=%task_id,- uuid=%uuid,- event_type=?event_type,- "detected 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,- );+ // 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();- match self.document_service.get_document(entity_access).await {- Ok(document) => {- // converting to string here to avoid needing to bring models crate- // into github crate- if let Some(sub_type) = document.document_metadata.sub_type- && sub_type.to_string() == "task"- {- tracing::info!(task_id=%uuid, "task found");-- if let Some((- ref token,- ref owner,- ref repo,- pull_number,- ref existing_comments,- )) = pr_meta- {- let doc_name = &document.document_metadata.document_name;- let doc_id = &document.document_metadata.document_id;- let comment_body =- create_macro_task_comment_link(doc_name, doc_id);-- // Skip if we already posted a comment linking to this task- let task_link = format!("/app/task/{doc_id})");- if existing_comments.iter().any(|c| c.contains(&task_link))- {- tracing::debug!(- task_id=%uuid,- "PR already has a comment linking to this task, skipping"- );- continue;- }-- self.client- .create_pr_comment(- &token.token,- owner,- repo,- pull_number,- &comment_body,- )- .await- .inspect_err(|e| {- tracing::error!(- error=?e,- "failed to create PR comment"- );- })- .ok();- }-- // TODO: update task status based on event- }- }- Err(e) => match e {- DocumentError::NotFound(_) => (),- _ => tracing::error!(error=?e, "unable to get document"),- },- }- }+ 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();}}diff --git a/rust/cloud-storage/github/src/domain/service/test.rs b/rust/cloud-storage/github/src/domain/service/test.rsindex 5a0c858d7a..5ec5716d65 100644--- a/rust/cloud-storage/github/src/domain/service/test.rs+++ b/rust/cloud-storage/github/src/domain/service/test.rs@@ -9,7 +9,9 @@ use documents::domain::{models::{CreateDocumentRepoArgs, DocumentError, LocationQueryParams},ports::DocumentService,};-use entity_access::domain::models::{EntityAccessReceipt, OwnerAccessLevel, ViewAccessLevel};+use entity_access::domain::models::{+ EditAccessLevel, EntityAccessReceipt, OwnerAccessLevel, ViewAccessLevel,+};use macro_user_id::user_id::MacroUserIdStr;use model::document::{DocumentBasic, DocumentMetadata,@@ -52,9 +54,28 @@ MEt9yPb3VfwFUyBSNJt4C6zDrnd+62oT+A9aJHJcUDUjqdBsmZamDu7xBAeLGxsnsNRx7TF4iOEBkdJgBUoY4X/rZ+51FQOrdZGqeWo+8TjBhMQN7b4=-----END RSA PRIVATE KEY-----";-struct StubDocumentService;+/// Recorded update_task_status call.+#[derive(Debug, Clone)]+struct TaskStatusCall {+ entity_id: String,+ status: String,+}++struct StubDocumentService {+ task_status_calls: Mutex<Vec<TaskStatusCall>>,+}impl StubDocumentService {+ fn new() -> Self {+ Self {+ task_status_calls: Mutex::new(Vec::new()),+ }+ }++ fn task_status_calls(&self) -> Vec<TaskStatusCall> {+ self.task_status_calls.lock().unwrap().clone()+ }+fn task_metadata(document_id: &str) -> DocumentMetadata {DocumentMetadata {document_id: document_id.to_string(),@@ -129,6 +150,17 @@ impl DocumentService for StubDocumentService {) -> Result<CreateDocumentResponseData, DocumentError> {unimplemented!()}+ async fn update_task_status(+ &self,+ receipt: EntityAccessReceipt<EditAccessLevel>,+ status: &str,+ ) -> Result<(), DocumentError> {+ self.task_status_calls.lock().unwrap().push(TaskStatusCall {+ entity_id: receipt.entity().entity_id.clone(),+ status: status.to_string(),+ });+ Ok(())+ }}/// Recorded PR comment call.@@ -203,16 +235,25 @@ impl GithubSyncClient for StubSyncClient {}fn make_sync_service() -> GithubSyncServiceImpl<StubDocumentService, StubSyncClient> {- GithubSyncServiceImpl::new(+ make_sync_service_with_doc_service().0+}++fn make_sync_service_with_doc_service() -> (+ 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(),},- Arc::new(StubDocumentService),+ doc_service.clone(),StubSyncClient::new(),- )+ );+ (service, doc_service)}#[tokio::test]@@ -544,3 +585,224 @@ async fn review_comment_mixed_new_and_duplicate() {let result = service.process_webhook_event(&event).await;assert!(result.is_ok());}++// ---------------------------------------------------------------------------+// Task status updates based on PR action+// ---------------------------------------------------------------------------++#[tokio::test]+async fn pr_opened_sets_task_status_in_review() {+ let (service, doc_service) = make_sync_service_with_doc_service();+ let event = ValidatedGithubWebhookEvent::new(+ "pull_request".to_string(),+ serde_json::json!({+ "action": "opened",+ "pull_request": {+ "number": 42,+ "title": "fixes MACRO-2BuyvtY3aeEvHx4uG8iD51",+ "body": null,+ "head": { "ref": "feature/some-branch" },+ "merged": false+ },+ "repository": {+ "name": "my-repo",+ "owner": { "login": "my-org" }+ },+ "installation": { "id": 12345 }+ }),+ );++ 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].entity_id, KNOWN_TASK_UUID);+ assert_eq!(status_calls[0].status, "In Review");+}++#[tokio::test]+async fn pr_merged_sets_task_status_completed() {+ 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();++ 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 pr_closed_without_merge_sets_task_status_canceled() {+ 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": false+ },+ "repository": {+ "name": "my-repo",+ "owner": { "login": "my-org" }+ },+ "installation": { "id": 12345 }+ }),+ );++ 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].entity_id, KNOWN_TASK_UUID);+ assert_eq!(status_calls[0].status, "Canceled");+}++#[tokio::test]+async fn issue_comment_on_open_pr_sets_task_status_in_review() {+ let (service, doc_service) = make_sync_service_with_doc_service();+ 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": "fixes MACRO-2BuyvtY3aeEvHx4uG8iD51"+ },+ "repository": {+ "name": "my-repo",+ "owner": { "login": "my-org" }+ },+ "installation": { "id": 12345 }+ }),+ );++ 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].entity_id, KNOWN_TASK_UUID);+ assert_eq!(status_calls[0].status, "In Review");+}++#[tokio::test]+async fn issue_comment_on_closed_pr_does_not_update_task_status() {+ let (service, doc_service) = make_sync_service_with_doc_service();+ let event = ValidatedGithubWebhookEvent::new(+ "issue_comment".to_string(),+ serde_json::json!({+ "action": "created",+ "issue": {+ "number": 99,+ "title": "some issue",+ "body": null,+ "state": "closed",+ "head": { "ref": "main" }+ },+ "comment": {+ "body": "fixes MACRO-2BuyvtY3aeEvHx4uG8iD51"+ },+ "repository": {+ "name": "my-repo",+ "owner": { "login": "my-org" }+ },+ "installation": { "id": 12345 }+ }),+ );++ service.process_webhook_event(&event).await.unwrap();++ let status_calls = doc_service.task_status_calls();+ assert!(+ status_calls.is_empty(),+ "issue_comment on closed PR should not update task status"+ );+}++#[tokio::test]+async fn pr_merged_updates_status_even_when_already_commented() {+ let (service, doc_service) = make_sync_service_with_doc_service();++ // First event: PR opened — posts comment and sets "In Review"+ let opened_event = ValidatedGithubWebhookEvent::new(+ "pull_request".to_string(),+ serde_json::json!({+ "action": "opened",+ "pull_request": {+ "number": 42,+ "title": "fixes MACRO-2BuyvtY3aeEvHx4uG8iD51",+ "body": null,+ "head": { "ref": "feature/some-branch" },+ "merged": false+ },+ "repository": {+ "name": "my-repo",+ "owner": { "login": "my-org" }+ },+ "installation": { "id": 12345 }+ }),+ );+ service.process_webhook_event(&opened_event).await.unwrap();+ assert_eq!(service.client.pr_comments().len(), 1);+ assert_eq!(doc_service.task_status_calls().len(), 1);+ assert_eq!(doc_service.task_status_calls()[0].status, "In Review");++ // Second event: PR merged — should NOT post a duplicate comment,+ // but SHOULD update status to "Completed"+ let merged_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(&merged_event).await.unwrap();++ // Still only 1 comment (no duplicate)+ assert_eq!(service.client.pr_comments().len(), 1);++ // But status was updated twice: "In Review" then "Completed"+ let status_calls = doc_service.task_status_calls();+ assert_eq!(status_calls.len(), 2);+ assert_eq!(status_calls[1].entity_id, KNOWN_TASK_UUID);+ assert_eq!(status_calls[1].status, "Completed");+}diff --git a/rust/cloud-storage/system_properties/.sqlx/query-cf71680da3444f573f4cddf66b6269bfe31aeee4bbec34b7e6067a855e28f2b7.json b/rust/cloud-storage/system_properties/.sqlx/query-cf71680da3444f573f4cddf66b6269bfe31aeee4bbec34b7e6067a855e28f2b7.jsonnew file mode 100644index 0000000000..9dc9838dc0--- /dev/null+++ b/rust/cloud-storage/system_properties/.sqlx/query-cf71680da3444f573f4cddf66b6269bfe31aeee4bbec34b7e6067a855e28f2b7.json@@ -0,0 +1,15 @@+{+ "db_name": "PostgreSQL",+ "query": "\n UPDATE entity_properties\n SET values = $2\n WHERE entity_id = $1;\n ",+ "describe": {+ "columns": [],+ "parameters": {+ "Left": [+ "Text",+ "Jsonb"+ ]+ },+ "nullable": []+ },+ "hash": "cf71680da3444f573f4cddf66b6269bfe31aeee4bbec34b7e6067a855e28f2b7"+}diff --git a/rust/cloud-storage/system_properties/src/domain/model/constants/options/status.rs b/rust/cloud-storage/system_properties/src/domain/model/constants/options/status.rsindex 92f0b56f3c..1a1dc95230 100644--- a/rust/cloud-storage/system_properties/src/domain/model/constants/options/status.rs+++ b/rust/cloud-storage/system_properties/src/domain/model/constants/options/status.rs@@ -14,6 +14,21 @@ pub enum StatusOption {Canceled,}+impl TryFrom<&str> for StatusOption {+ type Error = String;++ fn try_from(s: &str) -> Result<Self, Self::Error> {+ match s {+ "Not Started" | "not_started" => Ok(Self::NotStarted),+ "In Progress" | "in_progress" => Ok(Self::InProgress),+ "In Review" | "in_review" => Ok(Self::InReview),+ "Completed" | "completed" => Ok(Self::Completed),+ "Canceled" | "canceled" => Ok(Self::Canceled),+ _ => Err(format!("unknown status option: {s}")),+ }+ }+}+impl StatusOption {pub const NOT_STARTED_UUID: Uuid = Uuid::from_u128(0x00000001_0000_0000_0002_000000000001);pub const IN_PROGRESS_UUID: Uuid = Uuid::from_u128(0x00000001_0000_0000_0002_000000000002);diff --git a/rust/cloud-storage/system_properties/src/domain/port.rs b/rust/cloud-storage/system_properties/src/domain/port.rsindex 2d5b7d0e73..20d6b5581a 100644--- a/rust/cloud-storage/system_properties/src/domain/port.rs+++ b/rust/cloud-storage/system_properties/src/domain/port.rs@@ -3,7 +3,7 @@//! These traits define the interfaces that the domain layer uses.//! Implementations live in the outbound module.-use crate::domain::model::SystemPropertyError;+use crate::{StatusOption, domain::model::SystemPropertyError};/// Repository trait for system property database operations.///@@ -22,4 +22,11 @@ pub trait SystemPropertiesRepository: Clone + Send + Sync + 'static {from_task_id: &str,to_task_id: &str,) -> impl Future<Output = Result<(), SystemPropertyError>> + Send;++ /// Updates the task to have the provided status+ fn update_task_status(+ &self,+ task_id: &str,+ status: StatusOption,+ ) -> impl Future<Output = Result<(), SystemPropertyError>> + Send;}diff --git a/rust/cloud-storage/system_properties/src/domain/service.rs b/rust/cloud-storage/system_properties/src/domain/service.rsindex 80caeaebca..b31727c6eb 100644--- a/rust/cloud-storage/system_properties/src/domain/service.rs+++ b/rust/cloud-storage/system_properties/src/domain/service.rs@@ -2,12 +2,15 @@use models_properties::EntityType;-use crate::domain::{- model::{- EmailAttachmentInput, EmailAttachmentProperty, PropertyRow, SystemPropertyError,- SystemPropertyKey,+use crate::{+ StatusOption,+ domain::{+ model::{+ EmailAttachmentInput, EmailAttachmentProperty, PropertyRow, SystemPropertyError,+ SystemPropertyKey,+ },+ port::SystemPropertiesRepository,},- port::SystemPropertiesRepository,};/// Service trait for system property operations.@@ -39,6 +42,13 @@ pub trait SystemPropertiesService: Clone + Send + Sync + 'static {from_task_id: &str,to_task_id: &str,) -> impl Future<Output = Result<(), SystemPropertyError>> + Send;++ /// Updates the task to have the provided status+ fn update_task_status(+ &self,+ task_id: &str,+ status: StatusOption,+ ) -> impl Future<Output = Result<(), SystemPropertyError>> + Send;}/// Implementation of SystemPropertiesService using a repository.@@ -100,6 +110,15 @@ where.copy_task_properties(from_task_id, to_task_id).await}++ #[tracing::instrument(skip(self))]+ async fn update_task_status(+ &self,+ task_id: &str,+ status: StatusOption,+ ) -> Result<(), SystemPropertyError> {+ self.repository.update_task_status(task_id, status).await+ }}/// Collect property rows for a single entity's email attachment properties.diff --git a/rust/cloud-storage/system_properties/src/outbound/pgpool/mod.rs b/rust/cloud-storage/system_properties/src/outbound/pgpool/mod.rsindex 4ab2454b89..c5beb8f3b4 100644--- a/rust/cloud-storage/system_properties/src/outbound/pgpool/mod.rs+++ b/rust/cloud-storage/system_properties/src/outbound/pgpool/mod.rs@@ -3,12 +3,16 @@#[cfg(test)]mod test;+use models_properties::api::PropertyValue;use sqlx::{Pool, Postgres};use uuid::Uuid;-use crate::domain::{- model::{PropertyRow, SystemPropertyError, SystemPropertyKey},- port::SystemPropertiesRepository,+use crate::{+ StatusOption,+ domain::{+ model::{PropertyRow, SystemPropertyError, SystemPropertyKey},+ port::SystemPropertiesRepository,+ },};use macro_uuid::generate_uuid_v7;@@ -194,4 +198,29 @@ impl SystemPropertiesRepository for PgSystemPropertiesRepository {Ok(())}++ #[tracing::instrument(skip(self), err)]+ async fn update_task_status(+ &self,+ task_id: &str,+ status: StatusOption,+ ) -> Result<(), SystemPropertyError> {+ let value = PropertyValue::SelectOption(vec![status.uuid()]);++ let value = serde_json::to_value(&value).map_err(SystemPropertyError::Serialization)?;++ sqlx::query!(+ r#"+ UPDATE entity_properties+ SET values = $2+ WHERE entity_id = $1;+ "#,+ task_id,+ value+ )+ .execute(&self.pool)+ .await?;++ Ok(())+ }}