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
refactor(documents): move create_task to documents crate (#1918)
Will Hutchinson5d2cff9d8b33
diff --git a/js/app/packages/service-clients/service-storage/generated/schemas/createTaskHandler200.ts b/js/app/packages/service-clients/service-storage/generated/schemas/createTaskHandler200.tsindex 9f749000e9..85f4f39670 100644--- a/js/app/packages/service-clients/service-storage/generated/schemas/createTaskHandler200.ts+++ b/js/app/packages/service-clients/service-storage/generated/schemas/createTaskHandler200.ts@@ -6,9 +6,9 @@*//**- * Response for create_task+ * Response for creating a task.*/export type CreateTaskHandler200 = {- /** The document id of the created task */+ /** The document ID of the created task. */documentId: string;};diff --git a/js/app/packages/service-clients/service-storage/generated/schemas/createTaskRequest.ts b/js/app/packages/service-clients/service-storage/generated/schemas/createTaskRequest.tsindex ebe75b9b62..a4d9a44a52 100644--- a/js/app/packages/service-clients/service-storage/generated/schemas/createTaskRequest.ts+++ b/js/app/packages/service-clients/service-storage/generated/schemas/createTaskRequest.ts@@ -8,13 +8,13 @@ import type { CreateTaskRequestProjectId } from './createTaskRequestProjectId';import type { CreateTaskRequestPropertyValues } from './createTaskRequestPropertyValues';/**- * Request body for create_task+ * Request body for creating a task.*/export interface CreateTaskRequest {- /** Optional project id to associate the task with */+ /** Optional project ID to associate the task with. */projectId?: CreateTaskRequestProjectId;- /** Optional property values to set on the task */+ /** Optional property values to set on the task. */propertyValues?: CreateTaskRequestPropertyValues;- /** The name of the task */+ /** The name of the task. */taskName: string;}diff --git a/js/app/packages/service-clients/service-storage/generated/schemas/createTaskRequestProjectId.ts b/js/app/packages/service-clients/service-storage/generated/schemas/createTaskRequestProjectId.tsindex 86c3971eda..af1dbf627e 100644--- a/js/app/packages/service-clients/service-storage/generated/schemas/createTaskRequestProjectId.ts+++ b/js/app/packages/service-clients/service-storage/generated/schemas/createTaskRequestProjectId.ts@@ -6,6 +6,6 @@*//**- * Optional project id to associate the task with+ * Optional project ID to associate the task with.*/export type CreateTaskRequestProjectId = string | null;diff --git a/js/app/packages/service-clients/service-storage/generated/schemas/createTaskRequestPropertyValues.ts b/js/app/packages/service-clients/service-storage/generated/schemas/createTaskRequestPropertyValues.tsindex 66e56249be..17fa1bc511 100644--- a/js/app/packages/service-clients/service-storage/generated/schemas/createTaskRequestPropertyValues.ts+++ b/js/app/packages/service-clients/service-storage/generated/schemas/createTaskRequestPropertyValues.ts@@ -7,6 +7,6 @@import type { PropertyInput } from './propertyInput';/**- * Optional property values to set on the task+ * Optional property values to set on the task.*/export type CreateTaskRequestPropertyValues = PropertyInput[] | null;diff --git a/js/app/packages/service-clients/service-storage/generated/schemas/createTaskResponse.ts b/js/app/packages/service-clients/service-storage/generated/schemas/createTaskResponse.tsindex 1787504a29..8d2fff2e02 100644--- a/js/app/packages/service-clients/service-storage/generated/schemas/createTaskResponse.ts+++ b/js/app/packages/service-clients/service-storage/generated/schemas/createTaskResponse.ts@@ -6,9 +6,9 @@*//**- * Response for create_task+ * Response for creating a task.*/export interface CreateTaskResponse {- /** The document id of the created task */+ /** The document ID of the created task. */documentId: string;}diff --git a/js/app/packages/service-clients/service-storage/generated/schemas/propertyInput.ts b/js/app/packages/service-clients/service-storage/generated/schemas/propertyInput.tsindex be99710e55..880b5ae3cf 100644--- a/js/app/packages/service-clients/service-storage/generated/schemas/propertyInput.ts+++ b/js/app/packages/service-clients/service-storage/generated/schemas/propertyInput.ts@@ -7,11 +7,11 @@import type { SetPropertyValue } from './setPropertyValue';/**- * Property input for setting a property value on the task+ * Property input for setting a property value on a task.*/export interface PropertyInput {- /** The property definition ID */+ /** The property definition ID. */propertyId: string;- /** The value to set for the property */+ /** The value to set for the property. */value: SetPropertyValue;}diff --git a/js/app/packages/service-clients/service-storage/generated/zod.ts b/js/app/packages/service-clients/service-storage/generated/zod.tsindex 2e3e3c34be..a42a7c04f7 100644--- a/js/app/packages/service-clients/service-storage/generated/zod.ts+++ b/js/app/packages/service-clients/service-storage/generated/zod.ts@@ -1416,10 +1416,6 @@ export const createDocumentResponse = zod.object({/*** This endpoint creates task metadata and sets properties atomically.Task content should be set separately via the sync service.--NOTE: Ideally content initialization would happen here on the backend, but that requires-adding Loro/Lexical support to initialize sync service documents server-side. Deferring-for now — client must call `syncServiceClient.initializeFromSnapshot()` after this returns.* @summary Creates a task document with properties in a single call.*/export const createTaskHandlerBody = zod@@ -1428,12 +1424,12 @@ export const createTaskHandlerBody = zod.string().uuid().nullish()- .describe('Optional project id to associate the task with'),+ .describe('Optional project ID to associate the task with.'),propertyValues: zod.array(zod.object({- propertyId: zod.string().describe('The property definition ID'),+ propertyId: zod.string().describe('The property definition ID.'),value: zod.union([zod@@ -1563,19 +1559,19 @@ export const createTaskHandlerBody = zod'Type-safe enum for setting entity property values - provides compile-time validation.'),})- .describe('Property input for setting a property value on the task')+ .describe('Property input for setting a property value on a task.')).nullish()- .describe('Optional property values to set on the task'),- taskName: zod.string().describe('The name of the task'),+ .describe('Optional property values to set on the task.'),+ taskName: zod.string().describe('The name of the task.'),})- .describe('Request body for create_task');+ .describe('Request body for creating a task.');export const createTaskHandlerResponse = zod.object({- documentId: zod.string().describe('The document id of the created task'),+ documentId: zod.string().describe('The document ID of the created task.'),})- .describe('Response for create_task');+ .describe('Response for creating a task.');export const initializeUserDocumentsResponse = zod.object({success: zod.boolean().describe('Indicates if the request was successful'),diff --git a/js/app/packages/service-clients/service-storage/openapi.json b/js/app/packages/service-clients/service-storage/openapi.jsonindex 320782c599..3d3612a0b0 100644--- a/js/app/packages/service-clients/service-storage/openapi.json+++ b/js/app/packages/service-clients/service-storage/openapi.json@@ -1108,7 +1108,7 @@"post": {"tags": ["document"],"summary": "Creates a task document with properties in a single call.",- "description": "This endpoint creates task metadata and sets properties atomically.\nTask content should be set separately via the sync service.\n\nNOTE: Ideally content initialization would happen here on the backend, but that requires\nadding Loro/Lexical support to initialize sync service documents server-side. Deferring\nfor now — client must call `syncServiceClient.initializeFromSnapshot()` after this returns.",+ "description": "This endpoint creates task metadata and sets properties atomically.\nTask content should be set separately via the sync service.","operationId": "create_task_handler","requestBody": {"content": {@@ -1127,12 +1127,12 @@"application/json": {"schema": {"type": "object",- "description": "Response for create_task",+ "description": "Response for creating a task.","required": ["documentId"],"properties": {"documentId": {"type": "string",- "description": "The document id of the created task"+ "description": "The document ID of the created task."}}}@@ -1159,16 +1159,6 @@}}},- "403": {- "description": "",- "content": {- "application/json": {- "schema": {- "$ref": "#/components/schemas/ErrorResponse"- }- }- }- },"500": {"description": "","content": {@@ -6056,35 +6046,35 @@},"CreateTaskRequest": {"type": "object",- "description": "Request body for create_task",+ "description": "Request body for creating a task.","required": ["taskName"],"properties": {"projectId": {"type": ["string", "null"],"format": "uuid",- "description": "Optional project id to associate the task with"+ "description": "Optional project ID to associate the task with."},"propertyValues": {"type": ["array", "null"],"items": {"$ref": "#/components/schemas/PropertyInput"},- "description": "Optional property values to set on the task"+ "description": "Optional property values to set on the task."},"taskName": {"type": "string",- "description": "The name of the task"+ "description": "The name of the task."}}},"CreateTaskResponse": {"type": "object",- "description": "Response for create_task",+ "description": "Response for creating a task.","required": ["documentId"],"properties": {"documentId": {"type": "string",- "description": "The document id of the created task"+ "description": "The document ID of the created task."}}},@@ -9098,16 +9088,16 @@},"PropertyInput": {"type": "object",- "description": "Property input for setting a property value on the task",+ "description": "Property input for setting a property value on a task.","required": ["propertyId", "value"],"properties": {"propertyId": {"type": "string",- "description": "The property definition ID"+ "description": "The property definition ID."},"value": {"$ref": "#/components/schemas/SetPropertyValue",- "description": "The value to set for the property"+ "description": "The value to set for the property."}}},diff --git a/rust/cloud-storage/Cargo.lock b/rust/cloud-storage/Cargo.lockindex 39847fd649..84f190d945 100644--- a/rust/cloud-storage/Cargo.lock+++ b/rust/cloud-storage/Cargo.lock@@ -111,6 +111,7 @@ dependencies = ["models_email","models_pagination","models_permissions",+ "models_properties","models_search","rand 0.9.0","schemars",@@ -3052,6 +3053,7 @@ dependencies = ["model_file_type","model_user","models_permissions",+ "models_properties","reqwest","schemars","serde",diff --git a/rust/cloud-storage/ai_tools/Cargo.toml b/rust/cloud-storage/ai_tools/Cargo.tomlindex ac4f3ae22a..c961244ff6 100644--- a/rust/cloud-storage/ai_tools/Cargo.toml+++ b/rust/cloud-storage/ai_tools/Cargo.toml@@ -30,6 +30,7 @@ models_dcs = { path = "../models_dcs" }models_email = { path = "../models_email" }models_pagination = { path = "../models_pagination" }models_permissions = { path = "../models_permissions" }+models_properties = { path = "../models_properties" }models_search = { path = "../models_search" }rand.workspace = trueschemars.workspace = truediff --git a/rust/cloud-storage/ai_tools/src/tool_context.rs b/rust/cloud-storage/ai_tools/src/tool_context.rsindex 2f84aff349..2bc53272e6 100644--- a/rust/cloud-storage/ai_tools/src/tool_context.rs+++ b/rust/cloud-storage/ai_tools/src/tool_context.rs@@ -52,6 +52,15 @@ impl TaskPropertiesPort for NoOpTaskProperties {async fn attach_task_properties(&self, _entity_ids: Vec<String>) -> anyhow::Result<()> {Ok(())}+ async fn set_entity_property(+ &self,+ _user_id: &str,+ _entity_id: &str,+ _property_definition_id: uuid::Uuid,+ _value: Option<models_properties::api::requests::SetPropertyValue>,+ ) -> anyhow::Result<()> {+ Ok(())+ }}/// No-op connection servicediff --git a/rust/cloud-storage/document_storage_service/src/api/context.rs b/rust/cloud-storage/document_storage_service/src/api/context.rsindex fcc0d19f18..f98d4d93b7 100644--- a/rust/cloud-storage/document_storage_service/src/api/context.rs+++ b/rust/cloud-storage/document_storage_service/src/api/context.rs@@ -106,11 +106,14 @@ type PropertiesService = PropertiesServiceImpl<pub(crate) type EntityAccessService = EntityAccessServiceImpl<PgAccessRepository>;/// Adapter implementing [`TaskPropertiesPort`] for the system properties service.-pub(crate) struct TaskPropertiesAdapter(pub Arc<SystemPropertiesService>);+pub(crate) struct TaskPropertiesAdapter {+ pub system_properties: Arc<SystemPropertiesService>,+ pub properties: Arc<PropertiesService>,+}impl TaskPropertiesPort for TaskPropertiesAdapter {async fn attach_task_properties(&self, entity_ids: Vec<String>) -> anyhow::Result<()> {- self.0+ self.system_properties.attach_task_properties(entity_ids).await.map_err(Into::into)@@ -119,10 +122,33 @@ impl TaskPropertiesPort for TaskPropertiesAdapter {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?;+ self.system_properties+ .update_task_status(task_id, status_option)+ .await?;Ok(())}++ async fn set_entity_property(+ &self,+ user_id: &str,+ entity_id: &str,+ property_definition_id: uuid::Uuid,+ value: Option<models_properties::api::requests::SetPropertyValue>,+ ) -> anyhow::Result<()> {+ use properties::PropertiesService as _;++ self.properties+ .set_entity_property(+ user_id,+ entity_id,+ models_properties::EntityType::Task,+ property_definition_id,+ value,+ )+ .await+ .map_err(Into::into)+ }}pub(crate) type DocumentService = DocumentServiceImpl<diff --git a/rust/cloud-storage/document_storage_service/src/api/documents/create_task.rs b/rust/cloud-storage/document_storage_service/src/api/documents/create_task.rsdeleted file mode 100644index ce00e4ab08..0000000000--- a/rust/cloud-storage/document_storage_service/src/api/documents/create_task.rs+++ /dev/null@@ -1,148 +0,0 @@-use axum::{Json, extract::State, http::StatusCode};-use documents_hex::domain::models::CreateDocumentRepoArgs;-use documents_hex::domain::ports::DocumentService;-use macro_middleware::cloud_storage::ensure_access::project::ProjectBodyAccessLevelExtractor;-use model::document::FileType;-use model::response::ErrorResponse;-use model_user::axum_extractor::MacroUserExtractor;-use models_permissions::share_permission::access_level::EditAccessLevel;-use models_properties::EntityType as PropertyEntityType;-use models_properties::api::requests::SetPropertyValue;-use properties::PropertiesService;-use uuid::Uuid;--use crate::api::context::ApiContext;--/// SHA256 hash of empty string - for an empty markdown document-const EMPTY_SHA256: &str = "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855";--/// Property input for setting a property value on the task-#[derive(serde::Serialize, serde::Deserialize, Debug, Clone, utoipa::ToSchema)]-#[serde(rename_all = "camelCase")]-pub struct PropertyInput {- /// The property definition ID- pub property_id: String,- /// The value to set for the property- pub value: SetPropertyValue,-}--/// Request body for create_task-#[derive(serde::Serialize, serde::Deserialize, Debug, utoipa::ToSchema)]-#[serde(rename_all = "camelCase")]-pub struct CreateTaskRequest {- /// The name of the task- pub task_name: String,- /// Optional project id to associate the task with- pub project_id: Option<uuid::Uuid>,- /// Optional property values to set on the task- pub property_values: Option<Vec<PropertyInput>>,-}--/// Response for create_task-#[derive(serde::Serialize, serde::Deserialize, Debug, utoipa::ToSchema)]-#[serde(rename_all = "camelCase")]-pub struct CreateTaskResponse {- /// The document id of the created task- pub document_id: String,-}--/// Creates a task document with properties in a single call.-///-/// This endpoint creates task metadata and sets properties atomically.-/// Task content should be set separately via the sync service.-///-/// NOTE: Ideally content initialization would happen here on the backend, but that requires-/// adding Loro/Lexical support to initialize sync service documents server-side. Deferring-/// for now — client must call `syncServiceClient.initializeFromSnapshot()` after this returns.-#[utoipa::path(- post,- tag = "document",- path = "/documents/create_task",- request_body = CreateTaskRequest,- responses(- (status = 200, body=inline(CreateTaskResponse)),- (status = 401, body=ErrorResponse),- (status = 403, body=ErrorResponse),- (status = 400, body=ErrorResponse),- (status = 500, body=ErrorResponse),- )- )]-#[tracing::instrument(skip(state, user_context, project), fields(user_id=?user_context.macro_user_id))]-#[axum::debug_handler(state = ApiContext)]-pub(in crate::api) async fn create_task_handler(- State(state): State<ApiContext>,- user_context: MacroUserExtractor,- project: ProjectBodyAccessLevelExtractor<EditAccessLevel, CreateTaskRequest>,-) -> Result<Json<CreateTaskResponse>, (StatusCode, Json<ErrorResponse<'static>>)> {- let req = project.into_inner();- let user_id = user_context.user_context.user_id.clone();-- let macro_user_id = user_context.macro_user_id;-- // Create task document metadata (empty content - client sets via sync service)- let response_data = state- .documents_state- .service- .create_document(- macro_user_id.clone(),- CreateDocumentRepoArgs {- id: None,- sha: EMPTY_SHA256.to_string(),- document_name: req.task_name,- user_id: macro_user_id,- file_type: Some(FileType::Md),- project_id: req.project_id,- email_attachment_id: None,- created_at: None,- is_task: true,- skip_history: false,- },- None,- )- .await- .map_err(|e| {- tracing::error!(error=?e, "unable to create task document");- (- StatusCode::INTERNAL_SERVER_ERROR,- Json(ErrorResponse {- message: "failed to create task document",- }),- )- })?;-- let document_id = response_data- .document_response- .document_metadata- .document_id- .clone();-- // Apply properties to the task (partial failure is OK)- if let Some(properties) = req.property_values {- for property_input in properties {- let Ok(property_uuid) = Uuid::parse_str(&property_input.property_id) else {- tracing::warn!(property_id=?property_input.property_id, "invalid property_id UUID, skipping");- continue;- };-- let _ = state- .properties_service- .set_entity_property(- &user_id,- &document_id,- PropertyEntityType::Task,- property_uuid,- Some(property_input.value.clone()),- )- .await- .inspect_err(|e| {- tracing::warn!(- property_id=?property_uuid,- error=?e,- "failed to set property on task, continuing"- );- });- }- }-- Ok(Json(CreateTaskResponse { document_id }))-}diff --git a/rust/cloud-storage/document_storage_service/src/api/documents/mod.rs b/rust/cloud-storage/document_storage_service/src/api/documents/mod.rsindex b5caa235e3..00a3f24f6a 100644--- a/rust/cloud-storage/document_storage_service/src/api/documents/mod.rs+++ b/rust/cloud-storage/document_storage_service/src/api/documents/mod.rs@@ -7,7 +7,6 @@ use tower::ServiceBuilder;// needs to be public in api crate for swaggerpub(in crate::api) mod copy_document;-pub(in crate::api) mod create_task;pub(in crate::api) mod delete_document;pub(in crate::api) mod export_document;pub(in crate::api) mod get_batch_preview;@@ -54,23 +53,7 @@ pub fn router(state: ApiContext) -> Router<ApiContext> {)),)// NOTE: POST / (create_document) is now served by the documents hex crate router- .route(- "/create_task",- post(create_task::create_task_handler).layer(- ServiceBuilder::new()- .layer(axum::middleware::from_fn(- macro_middleware::auth::ensure_user_exists::handler,- ))- .layer(axum::middleware::from_fn_with_state(- state.clone(),- macro_middleware::user_permissions::attach_user_permissions::handler,- ))- .layer(axum::middleware::from_fn_with_state(- state.clone(),- macro_middleware::user_permissions::validate_user_quota::document_handler,- )),- ),- )+ // NOTE: POST /create_task is now served by the documents hex crate router.route("/initialize_user_documents",post(initialize_user_documents::handler).layer(diff --git a/rust/cloud-storage/document_storage_service/src/api/swagger.rs b/rust/cloud-storage/document_storage_service/src/api/swagger.rsindex a59324fd87..bc26cb84e2 100644--- a/rust/cloud-storage/document_storage_service/src/api/swagger.rs+++ b/rust/cloud-storage/document_storage_service/src/api/swagger.rs@@ -11,7 +11,6 @@ use crate::{activity, annotations,documents::{self,- create_task::{CreateTaskRequest, CreateTaskResponse, PropertyInput},export_document::ExportDocumentResponse,permissions_token::{create_permission_token::DocumentPermissionsTokenResponse,@@ -161,7 +160,7 @@ use utoipa::OpenApi;documents::permissions_token::validate_permissions_token::handler,documents::revert_delete_document::handler,documents::export_document::handler,- documents::create_task::create_task_handler,+ documents_hex::inbound::axum_router::create_task_handler,// instructionsinstructions::create_instructions::create_instructions_handler,@@ -250,9 +249,9 @@ use utoipa::OpenApi;CreateDocumentRequest,CreateDocumentResponse,CreateDocumentResponseData, // Create document- CreateTaskRequest,- CreateTaskResponse,- PropertyInput,+ documents_hex::domain::models::CreateTaskRequest,+ documents_hex::domain::models::CreateTaskResponse,+ documents_hex::domain::models::PropertyInput,models_properties::api::requests::SetPropertyValue,models_properties::shared::EntityReference,models_properties::shared::EntityType, // Quick create taskdiff --git a/rust/cloud-storage/document_storage_service/src/main.rs b/rust/cloud-storage/document_storage_service/src/main.rsindex 07fabe612c..5b5de914b9 100644--- a/rust/cloud-storage/document_storage_service/src/main.rs+++ b/rust/cloud-storage/document_storage_service/src/main.rs@@ -256,11 +256,11 @@ async fn main() -> anyhow::Result<()> {let permission_checker = PermissionServiceImpl::new(db.clone());let notification_service = NotificationServiceImpl::new(make_notification_ingress());- let properties_service = PropertiesServiceImpl::new(+ let properties_service = Arc::new(PropertiesServiceImpl::new(PropertiesPgRepo::new(db.clone()),Some(permission_checker),Some(notification_service),- );+ ));// Create the ChannelServiceImpl - we need to create separate instances as it doesn't impl Clonelet channel_service_for_soup = ChannelServiceImpl::new(@@ -327,7 +327,10 @@ async fn main() -> anyhow::Result<()> {cloudfront_config,sync_service_client.clone(),s3_upload_adapter,- TaskPropertiesAdapter(system_properties_service.clone()),+ TaskPropertiesAdapter {+ system_properties: system_properties_service.clone(),+ properties: properties_service.clone(),+ },connection_service,));@@ -380,7 +383,7 @@ async fn main() -> anyhow::Result<()> {conn_gateway_client: Arc::new(conn_gateway_client),sync_service_client: Arc::new(sync_service_client),system_properties_service: system_properties_service.clone(),- properties_service: Arc::new(properties_service),+ properties_service: properties_service.clone(),opensearch_client: Arc::new(opensearch_client),config: Arc::new(config),jwt_validation_args,diff --git a/rust/cloud-storage/documents/Cargo.toml b/rust/cloud-storage/documents/Cargo.tomlindex e9d607d954..d66b2707cd 100644--- a/rust/cloud-storage/documents/Cargo.toml+++ b/rust/cloud-storage/documents/Cargo.toml@@ -50,6 +50,7 @@ macro_user_id = { path = "../macro_user_id" }macro_uuid = { path = "../macro_uuid" }model = { path = "../model" }models_permissions = { path = "../models_permissions" }+models_properties = { path = "../models_properties" }# Async runtime (for ports)tokio = { workspace = true, optional = true }diff --git a/rust/cloud-storage/documents/examples/documents_toolset.rs b/rust/cloud-storage/documents/examples/documents_toolset.rsindex 78802f449b..2c5a7e74db 100644--- a/rust/cloud-storage/documents/examples/documents_toolset.rs+++ b/rust/cloud-storage/documents/examples/documents_toolset.rs@@ -61,6 +61,16 @@ impl TaskPropertiesPort for NoOpTaskProperties {async fn update_task_status(&self, _task_id: &str, _status: &str) -> anyhow::Result<()> {Ok(())}++ async fn set_entity_property(+ &self,+ _user_id: &str,+ _entity_id: &str,+ _property_definition_id: uuid::Uuid,+ _value: Option<models_properties::api::requests::SetPropertyValue>,+ ) -> anyhow::Result<()> {+ Ok(())+ }}/// The prompt to use in the example.diff --git a/rust/cloud-storage/documents/src/domain/models.rs b/rust/cloud-storage/documents/src/domain/models.rsindex 9c7c9be7c7..3beeadc35d 100644--- a/rust/cloud-storage/documents/src/domain/models.rs+++ b/rust/cloud-storage/documents/src/domain/models.rs@@ -2,6 +2,10 @@use macro_user_id::user_id::MacroUserIdStr;use model::document::FileType;+use models_properties::api::requests::SetPropertyValue;++/// SHA256 hash of an empty string — used for empty markdown documents (tasks).+pub const EMPTY_SHA256: &str = "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855";/// Errors that can occur during document operations.#[derive(Debug, thiserror::Error)]@@ -99,3 +103,36 @@ pub struct LocationQueryParams {/// If true, this will return the converted docx url.pub get_converted_docx_url: Option<bool>,}++/// Property input for setting a property value on a task.+#[derive(serde::Serialize, serde::Deserialize, Debug, Clone)]+#[cfg_attr(feature = "axum", derive(utoipa::ToSchema))]+#[serde(rename_all = "camelCase")]+pub struct PropertyInput {+ /// The property definition ID.+ pub property_id: String,+ /// The value to set for the property.+ pub value: SetPropertyValue,+}++/// Request body for creating a task.+#[derive(serde::Serialize, serde::Deserialize, Debug)]+#[cfg_attr(feature = "axum", derive(utoipa::ToSchema))]+#[serde(rename_all = "camelCase")]+pub struct CreateTaskRequest {+ /// The name of the task.+ pub task_name: String,+ /// Optional project ID to associate the task with.+ pub project_id: Option<uuid::Uuid>,+ /// Optional property values to set on the task.+ pub property_values: Option<Vec<PropertyInput>>,+}++/// Response for creating a task.+#[derive(serde::Serialize, serde::Deserialize, Debug)]+#[cfg_attr(feature = "axum", derive(utoipa::ToSchema))]+#[serde(rename_all = "camelCase")]+pub struct CreateTaskResponse {+ /// The document ID of the created task.+ pub document_id: String,+}diff --git a/rust/cloud-storage/documents/src/domain/ports.rs b/rust/cloud-storage/documents/src/domain/ports.rsindex d4ab8aca67..bc4400e713 100644--- a/rust/cloud-storage/documents/src/domain/ports.rs+++ b/rust/cloud-storage/documents/src/domain/ports.rs@@ -14,8 +14,8 @@ use model::document::response::{use model::document::{ContentType, DocumentBasic, DocumentMetadata};use super::models::{- CreateDocumentRepoArgs, DocumentError, EditDocumentRepoArgs, EditDocumentServiceArgs,- LocationQueryParams,+ CreateDocumentRepoArgs, CreateTaskRequest, CreateTaskResponse, DocumentError,+ EditDocumentRepoArgs, EditDocumentServiceArgs, LocationQueryParams,};/// Repository for accessing document data from the database.@@ -155,6 +155,15 @@ pub trait TaskPropertiesPort: Send + Sync + 'static {entity_id: &str,status: &str,) -> impl Future<Output = anyhow::Result<()>> + Send;++ /// Set a property value on an entity.+ fn set_entity_property(+ &self,+ user_id: &str,+ entity_id: &str,+ property_definition_id: uuid::Uuid,+ value: Option<models_properties::api::requests::SetPropertyValue>,+ ) -> impl Future<Output = anyhow::Result<()>> + Send;}/// Service interface for document operations.@@ -226,4 +235,12 @@ pub trait DocumentService: Send + Sync + 'static {entity_access_receipt: EntityAccessReceipt<EditAccessLevel>,status: &str,) -> impl Future<Output = Result<(), DocumentError>> + Send;++ /// Create a task document and optionally set property values on it.+ fn create_task(+ &self,+ user_id: MacroUserIdStr<'static>,+ plain_user_id: String,+ request: CreateTaskRequest,+ ) -> impl Future<Output = Result<CreateTaskResponse, DocumentError>> + Send;}diff --git a/rust/cloud-storage/documents/src/domain/service.rs b/rust/cloud-storage/documents/src/domain/service.rsindex 41806b63b3..db813c3930 100644--- a/rust/cloud-storage/documents/src/domain/service.rs+++ b/rust/cloud-storage/documents/src/domain/service.rs@@ -28,8 +28,8 @@ use model::response::PresignedUrl;use tracing;use super::models::{- CloudFrontConfig, CreateDocumentRepoArgs, DocumentError, EditDocumentRepoArgs,- EditDocumentServiceArgs, LocationQueryParams,+ CloudFrontConfig, CreateDocumentRepoArgs, CreateTaskRequest, CreateTaskResponse, DocumentError,+ EMPTY_SHA256, EditDocumentRepoArgs, EditDocumentServiceArgs, LocationQueryParams,};use super::ports::{DocumentRepo, DocumentService, PresignedUploadUrlPort, TaskPropertiesPort};@@ -672,4 +672,65 @@ impl<R: DocumentRepo, U: PresignedUploadUrlPort, T: TaskPropertiesPort, C: ConneOk(())}++ #[tracing::instrument(err, skip(self, request))]+ async fn create_task(+ &self,+ user_id: MacroUserIdStr<'static>,+ plain_user_id: String,+ request: CreateTaskRequest,+ ) -> Result<CreateTaskResponse, DocumentError> {+ let response_data = self+ .create_document(+ user_id.clone(),+ CreateDocumentRepoArgs {+ id: None,+ sha: EMPTY_SHA256.to_string(),+ document_name: request.task_name,+ user_id,+ file_type: Some(FileType::Md),+ project_id: request.project_id,+ email_attachment_id: None,+ created_at: None,+ is_task: true,+ skip_history: false,+ },+ None,+ )+ .await?;++ let document_id = response_data+ .document_response+ .document_metadata+ .document_id+ .clone();++ if let Some(properties) = request.property_values {+ for property_input in properties {+ let Ok(property_uuid) = uuid::Uuid::parse_str(&property_input.property_id) else {+ tracing::warn!(property_id=?property_input.property_id, "invalid property_id UUID, skipping");+ continue;+ };++ let _ = self+ .task_properties_service+ .set_entity_property(+ &plain_user_id,+ &document_id,+ property_uuid,+ Some(property_input.value.clone()),+ )+ .await+ .inspect_err(|e| {+ tracing::warn!(+ property_id=?property_uuid,+ error=?e,+ "failed to set property on task, continuing"+ );+ });+ }+ }++ Ok(CreateTaskResponse { document_id })+ }}diff --git a/rust/cloud-storage/documents/src/inbound/axum_router.rs b/rust/cloud-storage/documents/src/inbound/axum_router.rsindex 5af3efaa13..3cbc9c8c78 100644--- a/rust/cloud-storage/documents/src/inbound/axum_router.rs+++ b/rust/cloud-storage/documents/src/inbound/axum_router.rs@@ -11,6 +11,7 @@mod tests;mod create_document;+mod create_task;mod delete_document;mod edit_document;mod get_document;@@ -37,6 +38,7 @@ use crate::domain::ports::DocumentService;// Re-export handlers and utoipa path types for external use (swagger, internal routes)pub use create_document::*;+pub use create_task::*;pub use delete_document::*;pub use edit_document::*;pub use get_document::*;@@ -127,6 +129,10 @@ whereRouter::new().merge(document_id_routes).route("/", axum::routing::post(create_document_handler::<T, Svc>))+ .route(+ "/create_task",+ axum::routing::post(create_task_handler::<T, Svc>),+ ).with_state(state)}diff --git a/rust/cloud-storage/documents/src/inbound/axum_router/create_task.rs b/rust/cloud-storage/documents/src/inbound/axum_router/create_task.rsnew file mode 100644index 0000000000..bc84279d9b--- /dev/null+++ b/rust/cloud-storage/documents/src/inbound/axum_router/create_task.rs@@ -0,0 +1,45 @@+//! Handler for `POST /documents/create_task`.++use axum::{Json, extract::State};+use entity_access::domain::ports::EntityAccessService;+use entity_access::inbound::axum_extractors::ProjectBodyAccessLevelExtractor;+use model_user::axum_extractor::MacroUserExtractor;+use models_permissions::share_permission::access_level::EditAccessLevel;++use super::DocumentRouterState;+use crate::domain::models::{CreateTaskRequest, CreateTaskResponse, DocumentError};+use crate::domain::ports::DocumentService;++/// Creates a task document with properties in a single call.+///+/// This endpoint creates task metadata and sets properties atomically.+/// Task content should be set separately via the sync service.+#[utoipa::path(+ tag = "document",+ post,+ path = "/documents/create_task",+ request_body = CreateTaskRequest,+ responses(+ (status = 200, body = inline(CreateTaskResponse)),+ (status = 400, body = model_error_response::ErrorResponse),+ (status = 401, body = model_error_response::ErrorResponse),+ (status = 500, body = model_error_response::ErrorResponse),+ )+)]+#[tracing::instrument(skip(state, user_context, project), fields(user_id=?user_context.macro_user_id))]+pub async fn create_task_handler<T: DocumentService, Svc: EntityAccessService>(+ State(state): State<DocumentRouterState<T, Svc>>,+ user_context: MacroUserExtractor,+ project: ProjectBodyAccessLevelExtractor<EditAccessLevel, CreateTaskRequest, Svc>,+) -> Result<Json<CreateTaskResponse>, DocumentError> {+ let req = project.into_inner();+ let user_id = user_context.user_context.user_id.clone();+ let macro_user_id = user_context.macro_user_id;++ let response = state+ .service+ .create_task(macro_user_id, user_id, req)+ .await?;++ Ok(Json(response))+}diff --git a/rust/cloud-storage/github/src/domain/service/sync/test.rs b/rust/cloud-storage/github/src/domain/service/sync/test.rsindex 0a2bad9d5c..6f896201a0 100644--- a/rust/cloud-storage/github/src/domain/service/sync/test.rs+++ b/rust/cloud-storage/github/src/domain/service/sync/test.rs@@ -181,6 +181,15 @@ impl DocumentService for StubDocumentService {) -> Result<(), DocumentError> {Ok(())}++ async fn create_task(+ &self,+ _user_id: MacroUserIdStr<'static>,+ _plain_user_id: String,+ _request: documents::domain::models::CreateTaskRequest,+ ) -> Result<documents::domain::models::CreateTaskResponse, DocumentError> {+ unimplemented!()+ }}/// Stateful stub repo that tracks task IDs per github key.