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: add initiative MCP tools (#6845)
teoc466201c7838
diff --git a/.github/workspace-dep-closures.json b/.github/workspace-dep-closures.jsonindex 52b98023fb..ac607aea45 100644--- a/.github/workspace-dep-closures.json+++ b/.github/workspace-dep-closures.json@@ -455,6 +455,7 @@"crates/harnesses","crates/import","crates/initiative",+ "crates/initiative_documents","crates/invite_email","crates/ip_extractor","crates/item_filters",@@ -603,6 +604,7 @@"crates/harness_token","crates/import","crates/initiative",+ "crates/initiative_documents","crates/invite_email","crates/ip_extractor","crates/item_filters",@@ -1078,6 +1080,7 @@"crates/harness_token","crates/import","crates/initiative",+ "crates/initiative_documents","crates/invite_email","crates/ip_extractor","crates/item_filters",@@ -1301,6 +1304,7 @@"crates/harness_token","crates/import","crates/initiative",+ "crates/initiative_documents","crates/invite_email","crates/ip_extractor","crates/item_filters",@@ -2071,6 +2075,7 @@"crates/harness_token","crates/import","crates/initiative",+ "crates/initiative_documents","crates/invite_email","crates/ip_extractor","crates/item_filters",@@ -3526,6 +3531,7 @@"crates/harness_token","crates/import","crates/initiative",+ "crates/initiative_documents","crates/invite_email","crates/ip_extractor","crates/item_filters",@@ -7020,6 +7026,7 @@"crates/harness_token","crates/import","crates/initiative",+ "crates/initiative_documents","crates/invite_email","crates/ip_extractor","crates/item_filters",@@ -7173,6 +7180,7 @@"crates/harness_token","crates/import","crates/initiative",+ "crates/initiative_documents","crates/invite_email","crates/ip_extractor","crates/item_filters",@@ -8587,6 +8595,7 @@"crates/harness_token","crates/import","crates/initiative",+ "crates/initiative_documents","crates/invite_email","crates/ip_extractor","crates/item_filters",diff --git a/.sqlx/query-7be53dc216b01e1dddfb3b446c5f696248a25fee57f48cea19eca7323af956c0.json b/.sqlx/query-7be53dc216b01e1dddfb3b446c5f696248a25fee57f48cea19eca7323af956c0.jsonnew file mode 100644index 0000000000..3dffe266f6--- /dev/null+++ b/.sqlx/query-7be53dc216b01e1dddfb3b446c5f696248a25fee57f48cea19eca7323af956c0.json@@ -0,0 +1,28 @@+{+ "db_name": "PostgreSQL",+ "query": "\n WITH task AS (\n SELECT d.id, COALESCE(dst.sub_type = 'task', false) AS is_task\n FROM \"Document\" d\n LEFT JOIN document_sub_type dst ON dst.document_id = d.id\n WHERE d.id = $1 AND d.\"deletedAt\" IS NULL\n ), removed AS (\n DELETE FROM task_initiative ti\n USING task\n WHERE ti.task_id = task.id AND task.is_task\n RETURNING initiative_id\n ), updated AS (\n UPDATE initiative\n SET updated_at = now()\n WHERE id IN (SELECT initiative_id FROM removed)\n RETURNING id\n )\n SELECT task.is_task AS \"is_task!\", (SELECT id FROM updated) AS initiative_id\n FROM task\n ",+ "describe": {+ "columns": [+ {+ "ordinal": 0,+ "name": "is_task!",+ "type_info": "Bool"+ },+ {+ "ordinal": 1,+ "name": "initiative_id",+ "type_info": "Uuid"+ }+ ],+ "parameters": {+ "Left": [+ "Text"+ ]+ },+ "nullable": [+ null,+ null+ ]+ },+ "hash": "7be53dc216b01e1dddfb3b446c5f696248a25fee57f48cea19eca7323af956c0"+}diff --git a/.sqlx/query-bd9bd32d3afaa137889ae90b81a8aa73266047c37c341ed60f965a4c58119b7a.json b/.sqlx/query-bd9bd32d3afaa137889ae90b81a8aa73266047c37c341ed60f965a4c58119b7a.jsondeleted file mode 100644index 56188e98cd..0000000000--- a/.sqlx/query-bd9bd32d3afaa137889ae90b81a8aa73266047c37c341ed60f965a4c58119b7a.json+++ /dev/null@@ -1,22 +0,0 @@-{- "db_name": "PostgreSQL",- "query": "\n WITH removed AS (\n DELETE FROM task_initiative\n WHERE task_id = $1\n RETURNING initiative_id\n )\n UPDATE initiative\n SET updated_at = now()\n WHERE id IN (SELECT initiative_id FROM removed)\n RETURNING id\n ",- "describe": {- "columns": [- {- "ordinal": 0,- "name": "id",- "type_info": "Uuid"- }- ],- "parameters": {- "Left": [- "Text"- ]- },- "nullable": [- false- ]- },- "hash": "bd9bd32d3afaa137889ae90b81a8aa73266047c37c341ed60f965a4c58119b7a"-}diff --git a/Cargo.lock b/Cargo.lockindex 2bef4d5056..666c01e0fa 100644--- a/Cargo.lock+++ b/Cargo.lock@@ -778,6 +778,7 @@ dependencies = ["futures","import","initiative",+ "initiative_documents","item_filters","lazy_static","lexical_client",@@ -9154,8 +9155,11 @@ name = "initiative"version = "0.1.0"dependencies = ["activity",+ "ai_toolset","anyhow",+ "async-trait","axum",+ "bot_id","chrono","entity_access","entity_access_db_utils",@@ -9174,6 +9178,7 @@ dependencies = ["models_properties","properties","rootcause",+ "schemars 1.2.1","serde","serde_json","share_permission_db_utils",diff --git a/apps/docs/AI/mcp/tools/create-initiative.mdx b/apps/docs/AI/mcp/tools/create-initiative.mdxnew file mode 100644index 0000000000..8344d73a9c--- /dev/null+++ b/apps/docs/AI/mcp/tools/create-initiative.mdx@@ -0,0 +1,17 @@+---+title: CreateInitiative+description: "Create a project for coordinating tasks (called an initiative in the API). Projects have status, priority, assignees, due dates, discussions and activity. Shares with the owner's team by default. This is different from CreateProject, which creates a folder. Use property tools with entity_type='initiative' to set project properties."+---++# CreateInitiative++Create a project for coordinating tasks (called an initiative in the API). Projects have status, priority, assignees, due dates, discussions and activity. Shares with the owner's team by default. This is different from CreateProject, which creates a folder. Use property tools with entity_type='initiative' to set project properties.++## Parameters++| Parameter | Type | Required | Description |+| --- | --- | --- | --- |+| `name` | string | Yes | Project name, up to 100 graphemes. |+| `description` | string | No | Initial Markdown description, up to 2000 graphemes; optional. |+| `memberIds` | string[] | No | Users to grant collaboration access; distinct from property assignees. |+| `shareWithTeam` | boolean | No | Defaults to true. False creates without an explicit team grant. |diff --git a/apps/docs/AI/mcp/tools/delete-initiative.mdx b/apps/docs/AI/mcp/tools/delete-initiative.mdxnew file mode 100644index 0000000000..29a07ee69e--- /dev/null+++ b/apps/docs/AI/mcp/tools/delete-initiative.mdx@@ -0,0 +1,14 @@+---+title: DeleteInitiative+description: "Permanently delete a project, its description and properties. Associated tasks remain and lose their project association. Requires ownership. This operation cannot be undone."+---++# DeleteInitiative++Permanently delete a project, its description and properties. Associated tasks remain and lose their project association. Requires ownership. This operation cannot be undone.++## Parameters++| Parameter | Type | Required | Description |+| --- | --- | --- | --- |+| `initiativeId` | string | Yes | Project to permanently delete. |diff --git a/apps/docs/AI/mcp/tools/get-entity-properties.mdx b/apps/docs/AI/mcp/tools/get-entity-properties.mdxindex 058314511f..21730b5b60 100644--- a/apps/docs/AI/mcp/tools/get-entity-properties.mdx+++ b/apps/docs/AI/mcp/tools/get-entity-properties.mdx@@ -12,4 +12,4 @@ Get all properties attached to an entity (document, project, CRM company, etc.).| Parameter | Type | Required | Description || --- | --- | --- | --- || `entity_id` | string | Yes | The ID of the entity to get properties for. |-| `entity_type` | `"document"` \| `"project"` \| `"chat"` \| `"thread"` \| `"channel"` \| `"call"` \| `"user"` \| `"company"` | Yes | Canonical entity type accepted when an AI tool targets an entity's properties. Tasks are targeted as `document`; email threads (type `email` in ListEntities and search results) are targeted as `thread`. |+| `entity_type` | `"document"` \| `"initiative"` \| `"project"` \| `"chat"` \| `"thread"` \| `"channel"` \| `"call"` \| `"user"` \| `"company"` | Yes | Canonical entity type accepted when an AI tool targets an entity's properties. Tasks are targeted as `document`; email threads (type `email` in ListEntities and search results) are targeted as `thread`. |diff --git a/apps/docs/AI/mcp/tools/index.mdx b/apps/docs/AI/mcp/tools/index.mdxindex 6321947826..494552b5bb 100644--- a/apps/docs/AI/mcp/tools/index.mdx+++ b/apps/docs/AI/mcp/tools/index.mdx@@ -20,12 +20,14 @@ These pages are generated from Macro's Rust MCP tool registry.- [CreateChannel](/AI/mcp/tools/create-channel)- [CreateDocument](/AI/mcp/tools/create-document)- [CreateImportEntity](/AI/mcp/tools/create-import-entity)+- [CreateInitiative](/AI/mcp/tools/create-initiative)- [CreateProject](/AI/mcp/tools/create-project)- [CreateReminder](/AI/mcp/tools/create-reminder)- [CreateTag](/AI/mcp/tools/create-tag)- [DeleteBot](/AI/mcp/tools/delete-bot)- [DeleteCalendarEvent](/AI/mcp/tools/delete-calendar-event)- [DeleteImportEntity](/AI/mcp/tools/delete-import-entity)+- [DeleteInitiative](/AI/mcp/tools/delete-initiative)- [DeleteReminder](/AI/mcp/tools/delete-reminder)- [DeleteTag](/AI/mcp/tools/delete-tag)- [DisplayResults](/AI/mcp/tools/display-results)@@ -45,6 +47,7 @@ These pages are generated from Macro's Rust MCP tool registry.- [ListEntities](/AI/mcp/tools/list-entities)- [ListImportEntities](/AI/mcp/tools/list-import-entities)- [ListInboxes](/AI/mcp/tools/list-inboxes)+- [ListInitiatives](/AI/mcp/tools/list-initiatives)- [ListLabels](/AI/mcp/tools/list-labels)- [ListNotifications](/AI/mcp/tools/list-notifications)- [ListReminders](/AI/mcp/tools/list-reminders)@@ -65,9 +68,12 @@ These pages are generated from Macro's Rust MCP tool registry.- [ReadChannelThread](/AI/mcp/tools/read-channel-thread)- [ReadChat](/AI/mcp/tools/read-chat)- [ReadContent](/AI/mcp/tools/read-content)+- [ReadInitiative](/AI/mcp/tools/read-initiative)+- [ReadInitiativeActivity](/AI/mcp/tools/read-initiative-activity)- [ReadMetadata](/AI/mcp/tools/read-metadata)- [ReadProject](/AI/mcp/tools/read-project)- [ReadSpreadsheet](/AI/mcp/tools/read-spreadsheet)+- [ReadTaskInitiatives](/AI/mcp/tools/read-task-initiatives)- [ReadThread](/AI/mcp/tools/read-thread)- [RenameChannel](/AI/mcp/tools/rename-channel)- [RenameDocument](/AI/mcp/tools/rename-document)@@ -81,9 +87,12 @@ These pages are generated from Macro's Rust MCP tool registry.- [SendEmail](/AI/mcp/tools/send-email)- [SetEntityProperty](/AI/mcp/tools/set-entity-property)- [SetSenderPolicy](/AI/mcp/tools/set-sender-policy)+- [SetTaskInitiative](/AI/mcp/tools/set-task-initiative)- [Subagent](/AI/mcp/tools/subagent)- [TextEditorCodeExecution](/AI/mcp/tools/text-editor-code-execution)- [UpdateCalendarEvent](/AI/mcp/tools/update-calendar-event)+- [UpdateInitiative](/AI/mcp/tools/update-initiative)+- [UpdateInitiativeSharing](/AI/mcp/tools/update-initiative-sharing)- [UpdateReminder](/AI/mcp/tools/update-reminder)- [UpdateThreadLabels](/AI/mcp/tools/update-thread-labels)- [UploadFile](/AI/mcp/tools/upload-file)diff --git a/apps/docs/AI/mcp/tools/list-initiatives.mdx b/apps/docs/AI/mcp/tools/list-initiatives.mdxnew file mode 100644index 0000000000..05ca52ac61--- /dev/null+++ b/apps/docs/AI/mcp/tools/list-initiatives.mdx@@ -0,0 +1,21 @@+---+title: ListInitiatives+description: "Find projects (initiatives), with canonical properties and progress over tasks you can view. Returns at most 100 recently updated matches per page. Pass nextCursor back as cursor with the same filters to read more. Filter by name, status, priority, assignee, or due date. Project folders use ReadProject instead."+---++# ListInitiatives++Find projects (initiatives), with canonical properties and progress over tasks you can view. Returns at most 100 recently updated matches per page. Pass nextCursor back as cursor with the same filters to read more. Filter by name, status, priority, assignee, or due date. Project folders use ReadProject instead.++## Parameters++| Parameter | Type | Required | Description |+| --- | --- | --- | --- |+| `query` | string | No | Case-insensitive project name substring. |+| `status` | string | No | Status option id, obtained from property definitions. |+| `priority` | string | No | Priority option id, obtained from property definitions. |+| `assignee` | string | No | Assigned user id. |+| `dueAfter` | string | No | Earliest inclusive due timestamp. |+| `dueBefore` | string | No | Latest inclusive due timestamp. |+| `cursor` | string | No | Opaque nextCursor from the preceding page, with the same filters. |+| `limit` | integer | No | Maximum projects to return, from 1 through 100; defaults to 100. |diff --git a/apps/docs/AI/mcp/tools/read-initiative-activity.mdx b/apps/docs/AI/mcp/tools/read-initiative-activity.mdxnew file mode 100644index 0000000000..130c0215ec--- /dev/null+++ b/apps/docs/AI/mcp/tools/read-initiative-activity.mdx@@ -0,0 +1,18 @@+---+title: ReadInitiativeActivity+description: "Read project creation, edits, property changes, and task membership changes, newest first. Task references require current task view access. Each page scans at most 100 events and may contain fewer visible records. Pass nextCursor back as cursor with the same time filters to continue, including after an empty page."+---++# ReadInitiativeActivity++Read project creation, edits, property changes, and task membership changes, newest first. Task references require current task view access. Each page scans at most 100 events and may contain fewer visible records. Pass nextCursor back as cursor with the same time filters to continue, including after an empty page.++## Parameters++| Parameter | Type | Required | Description |+| --- | --- | --- | --- |+| `initiativeId` | string | Yes | Project identifier. |+| `after` | string | No | Only changes at or after this timestamp. |+| `before` | string | No | Only changes before this timestamp. |+| `cursor` | InitiativeActivityCursor | No | Opaque nextCursor from the preceding activity page. |+| `limit` | integer | No | Maximum events to scan, from 1 through 100; defaults to 100. |diff --git a/apps/docs/AI/mcp/tools/read-initiative.mdx b/apps/docs/AI/mcp/tools/read-initiative.mdxnew file mode 100644index 0000000000..79a1d50a8b--- /dev/null+++ b/apps/docs/AI/mcp/tools/read-initiative.mdx@@ -0,0 +1,16 @@+---+title: ReadInitiative+description: "Read a project, its sharing, canonical status/priority/assignees/due date, and a bounded page of associated task ids that you can view, with their total count. Pass nextTaskCursor back as taskCursor to read more task ids. Requires view access. The descriptionDocumentId can be read or edited with document tools. Use entity_type='initiative' with property tools. ReadInitiativeActivity returns the project's activity history."+---++# ReadInitiative++Read a project, its sharing, canonical status/priority/assignees/due date, and a bounded page of associated task ids that you can view, with their total count. Pass nextTaskCursor back as taskCursor to read more task ids. Requires view access. The descriptionDocumentId can be read or edited with document tools. Use entity_type='initiative' with property tools. ReadInitiativeActivity returns the project's activity history.++## Parameters++| Parameter | Type | Required | Description |+| --- | --- | --- | --- |+| `initiativeId` | string | Yes | Project identifier. |+| `taskCursor` | string | No | Opaque nextTaskCursor from the preceding page for this project. |+| `taskLimit` | integer | No | Maximum task ids to return, from 1 through 100; defaults to 100. |diff --git a/apps/docs/AI/mcp/tools/read-task-initiatives.mdx b/apps/docs/AI/mcp/tools/read-task-initiatives.mdxnew file mode 100644index 0000000000..6a68352d71--- /dev/null+++ b/apps/docs/AI/mcp/tools/read-task-initiatives.mdx@@ -0,0 +1,14 @@+---+title: ReadTaskInitiatives+description: "Find the project associated with each requested task. Returns project id/name only when both task and project are visible. Distinguishes no project from unavailable. Accepts up to 100 unique task ids."+---++# ReadTaskInitiatives++Find the project associated with each requested task. Returns project id/name only when both task and project are visible. Distinguishes no project from unavailable. Accepts up to 100 unique task ids.++## Parameters++| Parameter | Type | Required | Description |+| --- | --- | --- | --- |+| `taskIds` | string[] | Yes | Task ids to look up, deduplicated in input order. |diff --git a/apps/docs/AI/mcp/tools/set-entity-property.mdx b/apps/docs/AI/mcp/tools/set-entity-property.mdxindex 43110c9496..96d70ed8bb 100644--- a/apps/docs/AI/mcp/tools/set-entity-property.mdx+++ b/apps/docs/AI/mcp/tools/set-entity-property.mdx@@ -1,11 +1,11 @@---title: SetEntityProperty-description: "Set or update a property value on an entity (document, project, etc.). Tasks are targeted as entity_type='document'. Provide the property_definition_id and exactly one value field matching the property's data type. For multi-select properties — including tags — prefer add_option_ids / remove_option_ids over option_ids: they add or remove just those options atomically, composing with concurrent edits. option_ids replaces the entire value, so a stale read can silently drop options someone else just added; only use it when the user asks to set the value to exactly a given list. To apply a tag, pass the tag set's property_definition_id and the tag's option id (both from ListTags) in add_option_ids; to remove a tag, use remove_option_ids. Tasks always have these system properties (use these property_definition_id values directly): - Assignees (00000001-0000-0000-0000-000000000001): entity type, multi-select. Use entity_refs with entity_type='user' and entity_id='macro|[email protected]'. - Status (00000001-0000-0000-0000-000000000002): select_string, single. Options: Not Started (00000001-0000-0000-0002-000000000001), In Progress (...0002), In Review (...0003), Completed (...0004), Canceled (...0005). - Priority (00000001-0000-0000-0000-000000000003): select_string, single. Options: Low (...0001), Medium (...0002), High (...0003), Urgent (...0004). Option IDs: 00000001-0000-0000-0003-0000000000XX. - Due Date (00000001-0000-0000-0000-000000000004): date, single. Use date_value with ISO 8601. - Parent Task (00000001-0000-0000-0000-000000000005): entity, single. Use entity_ref with entity_type='task'. - Subtasks (00000001-0000-0000-0000-000000000006): entity, multi. Use entity_refs with entity_type='task'. - Story Points (00000001-0000-0000-0000-000000000009): number, single. Use number_value. CRM companies (entity_type='company', entity_id=the company UUID) always have these system properties: - Stage (00000001-0000-0000-0000-000000000010): select_string, single. Use option_id. Default options: Lead (00000001-0000-0000-0010-000000000001), Qualified (...0002), Demo (...0003), Trial (...0004), Negotiation (...0005), Customer (...0006), Churned (...0007). Teams can customize their stages, so prefer calling GetCompany or GetEntityProperties first to get the valid stage option ids. - Owner (00000001-0000-0000-0000-000000000011): entity, single. Use entity_ref with entity_type='user' and entity_id='macro|[email protected]'. - Revenue (00000001-0000-0000-0000-000000000012): number, single. Use number_value (dollars). Any member of the owning team can edit visible company properties; hidden records remain admin/owner-only. For non-system or custom properties, call GetEntityProperties first to discover property_definition_id values and options."+description: "Set or update a property value on an entity. Tasks are targeted as entity_type='document'. Projects in the Tasks UI are entity_type='initiative'; entity_type='project' still means a folder. Initiatives share the Assignees, Status, Priority and Due Date definitions below and their clearing behavior. Project Status accepts only Not Started (00000001-0000-0000-0002-000000000001), In Progress (...0002), and Completed (...0004); In Review and Canceled are task-only options. Provide the property_definition_id and exactly one value field matching the property's data type. For multi-select properties — including tags — prefer add_option_ids / remove_option_ids over option_ids: they add or remove just those options atomically, composing with concurrent edits. option_ids replaces the entire value, so a stale read can silently drop options someone else just added; only use it when the user asks to set the value to exactly a given list. To apply a tag, pass the tag set's property_definition_id and the tag's option id (both from ListTags) in add_option_ids; to remove a tag, use remove_option_ids. Tasks always have these system properties (use these property_definition_id values directly): - Assignees (00000001-0000-0000-0000-000000000001): entity type, multi-select. Use entity_refs with entity_type='user' and entity_id='macro|[email protected]'. - Status (00000001-0000-0000-0000-000000000002): select_string, single. Options: Not Started (00000001-0000-0000-0002-000000000001), In Progress (...0002), In Review (...0003), Completed (...0004), Canceled (...0005). - Priority (00000001-0000-0000-0000-000000000003): select_string, single. Options: Low (...0001), Medium (...0002), High (...0003), Urgent (...0004). Option IDs: 00000001-0000-0000-0003-0000000000XX. - Due Date (00000001-0000-0000-0000-000000000004): date, single. Use date_value with ISO 8601. - Parent Task (00000001-0000-0000-0000-000000000005): entity, single. Use entity_ref with entity_type='task'. - Subtasks (00000001-0000-0000-0000-000000000006): entity, multi. Use entity_refs with entity_type='task'. - Story Points (00000001-0000-0000-0000-000000000009): number, single. Use number_value. CRM companies (entity_type='company', entity_id=the company UUID) always have these system properties: - Stage (00000001-0000-0000-0000-000000000010): select_string, single. Use option_id. Default options: Lead (00000001-0000-0000-0010-000000000001), Qualified (...0002), Demo (...0003), Trial (...0004), Negotiation (...0005), Customer (...0006), Churned (...0007). Teams can customize their stages, so prefer calling GetCompany or GetEntityProperties first to get the valid stage option ids. - Owner (00000001-0000-0000-0000-000000000011): entity, single. Use entity_ref with entity_type='user' and entity_id='macro|[email protected]'. - Revenue (00000001-0000-0000-0000-000000000012): number, single. Use number_value (dollars). Any member of the owning team can edit visible company properties; hidden records remain admin/owner-only. For non-system or custom properties, call GetEntityProperties first to discover property_definition_id values and options."---# SetEntityProperty-Set or update a property value on an entity (document, project, etc.). Tasks are targeted as entity_type='document'. Provide the property_definition_id and exactly one value field matching the property's data type.+Set or update a property value on an entity. Tasks are targeted as entity_type='document'. Projects in the Tasks UI are entity_type='initiative'; entity_type='project' still means a folder. Initiatives share the Assignees, Status, Priority and Due Date definitions below and their clearing behavior. Project Status accepts only Not Started (00000001-0000-0000-0002-000000000001), In Progress (...0002), and Completed (...0004); In Review and Canceled are task-only options. Provide the property_definition_id and exactly one value field matching the property's data type.For multi-select properties — including tags — prefer add_option_ids / remove_option_ids over option_ids: they add or remove just those options atomically, composing with concurrent edits. option_ids replaces the entire value, so a stale read can silently drop options someone else just added; only use it when the user asks to set the value to exactly a given list. To apply a tag, pass the tag set's property_definition_id and the tag's option id (both from ListTags) in add_option_ids; to remove a tag, use remove_option_ids.@@ -31,7 +31,7 @@ For non-system or custom properties, call GetEntityProperties first to discover| Parameter | Type | Required | Description || --- | --- | --- | --- || `entity_id` | string | Yes | The ID of the entity to update. |-| `entity_type` | `"document"` \| `"project"` \| `"chat"` \| `"thread"` \| `"channel"` \| `"call"` \| `"user"` \| `"company"` | Yes | Canonical entity type accepted when an AI tool targets an entity's properties. Tasks are targeted as `document`; email threads (type `email` in ListEntities and search results) are targeted as `thread`. |+| `entity_type` | `"document"` \| `"initiative"` \| `"project"` \| `"chat"` \| `"thread"` \| `"channel"` \| `"call"` \| `"user"` \| `"company"` | Yes | Canonical entity type accepted when an AI tool targets an entity's properties. Tasks are targeted as `document`; email threads (type `email` in ListEntities and search results) are targeted as `thread`. || `property_definition_id` | string | Yes | The property definition ID. Get this from GetEntityProperties results. || `boolean_value` | boolean | No | For boolean properties. || `date_value` | string | No | For date properties (ISO 8601 date-time). |diff --git a/apps/docs/AI/mcp/tools/set-task-initiative.mdx b/apps/docs/AI/mcp/tools/set-task-initiative.mdxnew file mode 100644index 0000000000..ba90a16f57--- /dev/null+++ b/apps/docs/AI/mcp/tools/set-task-initiative.mdx@@ -0,0 +1,15 @@+---+title: SetTaskInitiative+description: "Set the project associated with tasks, moving them from their previous project if needed. Requires edit access to each task and the destination project; access to the previous project is unnecessary. Omit initiativeId to clear the association using task edit access alone. Reports each task's outcome independently; at most 100 unique tasks."+---++# SetTaskInitiative++Set the project associated with tasks, moving them from their previous project if needed. Requires edit access to each task and the destination project; access to the previous project is unnecessary. Omit initiativeId to clear the association using task edit access alone. Reports each task's outcome independently; at most 100 unique tasks.++## Parameters++| Parameter | Type | Required | Description |+| --- | --- | --- | --- |+| `taskIds` | string[] | Yes | Task ids to assign or clear, deduplicated in request order. |+| `initiativeId` | string | No | Destination project; omit to clear each task's current project. |diff --git a/apps/docs/AI/mcp/tools/update-initiative-sharing.mdx b/apps/docs/AI/mcp/tools/update-initiative-sharing.mdxnew file mode 100644index 0000000000..706f10970a--- /dev/null+++ b/apps/docs/AI/mcp/tools/update-initiative-sharing.mdx@@ -0,0 +1,18 @@+---+title: UpdateInitiativeSharing+description: "Change a project's team, link or channel sharing. Only the actual project owner may change sharing. Each omitted field remains unchanged; off disables that share. Project and description document permissions change together. Collaboration member changes use UpdateInitiative."+---++# UpdateInitiativeSharing++Change a project's team, link or channel sharing. Only the actual project owner may change sharing. Each omitted field remains unchanged; off disables that share. Project and description document permissions change together. Collaboration member changes use UpdateInitiative.++## Parameters++| Parameter | Type | Required | Description |+| --- | --- | --- | --- |+| `initiativeId` | string | Yes | Project identifier. |+| `teamAccess` | `"off"` \| `"view"` \| `"comment"` \| `"edit"` | No | Explicit owner-team grant; off removes it. |+| `linkScope` | `"off"` \| `"public"` \| `"team"` | No | Who the project link admits; off disables it. |+| `linkAccess` | `"off"` \| `"view"` \| `"comment"` \| `"edit"` | No | Permission granted by an enabled link. Off resets it to the default view level. |+| `channels` | ProjectChannelSharing[] | No | Individual channel shares to set or remove; other shares remain unchanged. |diff --git a/apps/docs/AI/mcp/tools/update-initiative.mdx b/apps/docs/AI/mcp/tools/update-initiative.mdxnew file mode 100644index 0000000000..c6c784fbbd--- /dev/null+++ b/apps/docs/AI/mcp/tools/update-initiative.mdx@@ -0,0 +1,16 @@+---+title: UpdateInitiative+description: "Rename a project with edit access, or replace its collaboration member list as the owner. Members control sharing independently of the assignee property. Assigning a user grants collaboration access; removing an assignment retains that access. For status, priority, assignees and due date use SetEntityProperty with entity_type='initiative'. ReadInitiative returns the description document id for document editing tools."+---++# UpdateInitiative++Rename a project with edit access, or replace its collaboration member list as the owner. Members control sharing independently of the assignee property. Assigning a user grants collaboration access; removing an assignment retains that access. For status, priority, assignees and due date use SetEntityProperty with entity_type='initiative'. ReadInitiative returns the description document id for document editing tools.++## Parameters++| Parameter | Type | Required | Description |+| --- | --- | --- | --- |+| `initiativeId` | string | Yes | Project identifier. |+| `name` | string | No | Replacement name; omitted leaves it unchanged. |+| `memberIds` | string[] | No | Owner-only complete replacement member list; omitted preserves existing members, [] clears it. |diff --git a/apps/docs/config/tool-pages.json b/apps/docs/config/tool-pages.jsonindex c43e8031c9..825f659c5e 100644--- a/apps/docs/config/tool-pages.json+++ b/apps/docs/config/tool-pages.json@@ -11,12 +11,14 @@"AI/mcp/tools/create-channel","AI/mcp/tools/create-document","AI/mcp/tools/create-import-entity",+ "AI/mcp/tools/create-initiative","AI/mcp/tools/create-project","AI/mcp/tools/create-reminder","AI/mcp/tools/create-tag","AI/mcp/tools/delete-bot","AI/mcp/tools/delete-calendar-event","AI/mcp/tools/delete-import-entity",+ "AI/mcp/tools/delete-initiative","AI/mcp/tools/delete-reminder","AI/mcp/tools/delete-tag","AI/mcp/tools/display-results",@@ -36,6 +38,7 @@"AI/mcp/tools/list-entities","AI/mcp/tools/list-import-entities","AI/mcp/tools/list-inboxes",+ "AI/mcp/tools/list-initiatives","AI/mcp/tools/list-labels","AI/mcp/tools/list-notifications","AI/mcp/tools/list-reminders",@@ -56,9 +59,12 @@"AI/mcp/tools/read-channel-thread","AI/mcp/tools/read-chat","AI/mcp/tools/read-content",+ "AI/mcp/tools/read-initiative",+ "AI/mcp/tools/read-initiative-activity","AI/mcp/tools/read-metadata","AI/mcp/tools/read-project","AI/mcp/tools/read-spreadsheet",+ "AI/mcp/tools/read-task-initiatives","AI/mcp/tools/read-thread","AI/mcp/tools/rename-channel","AI/mcp/tools/rename-document",@@ -72,9 +78,12 @@"AI/mcp/tools/send-email","AI/mcp/tools/set-entity-property","AI/mcp/tools/set-sender-policy",+ "AI/mcp/tools/set-task-initiative","AI/mcp/tools/subagent","AI/mcp/tools/text-editor-code-execution","AI/mcp/tools/update-calendar-event",+ "AI/mcp/tools/update-initiative",+ "AI/mcp/tools/update-initiative-sharing","AI/mcp/tools/update-reminder","AI/mcp/tools/update-thread-labels","AI/mcp/tools/upload-file",diff --git a/apps/docs/docs.json b/apps/docs/docs.jsonindex 7972ffce69..73f9371a20 100644--- a/apps/docs/docs.json+++ b/apps/docs/docs.json@@ -82,12 +82,14 @@"AI/mcp/tools/create-channel","AI/mcp/tools/create-document","AI/mcp/tools/create-import-entity",+ "AI/mcp/tools/create-initiative","AI/mcp/tools/create-project","AI/mcp/tools/create-reminder","AI/mcp/tools/create-tag","AI/mcp/tools/delete-bot","AI/mcp/tools/delete-calendar-event","AI/mcp/tools/delete-import-entity",+ "AI/mcp/tools/delete-initiative","AI/mcp/tools/delete-reminder","AI/mcp/tools/delete-tag","AI/mcp/tools/display-results",@@ -107,6 +109,7 @@"AI/mcp/tools/list-entities","AI/mcp/tools/list-import-entities","AI/mcp/tools/list-inboxes",+ "AI/mcp/tools/list-initiatives","AI/mcp/tools/list-labels","AI/mcp/tools/list-notifications","AI/mcp/tools/list-reminders",@@ -127,9 +130,12 @@"AI/mcp/tools/read-channel-thread","AI/mcp/tools/read-chat","AI/mcp/tools/read-content",+ "AI/mcp/tools/read-initiative",+ "AI/mcp/tools/read-initiative-activity","AI/mcp/tools/read-metadata","AI/mcp/tools/read-project","AI/mcp/tools/read-spreadsheet",+ "AI/mcp/tools/read-task-initiatives","AI/mcp/tools/read-thread","AI/mcp/tools/rename-channel","AI/mcp/tools/rename-document",@@ -143,9 +149,12 @@"AI/mcp/tools/send-email","AI/mcp/tools/set-entity-property","AI/mcp/tools/set-sender-policy",+ "AI/mcp/tools/set-task-initiative","AI/mcp/tools/subagent","AI/mcp/tools/text-editor-code-execution","AI/mcp/tools/update-calendar-event",+ "AI/mcp/tools/update-initiative",+ "AI/mcp/tools/update-initiative-sharing","AI/mcp/tools/update-reminder","AI/mcp/tools/update-thread-labels","AI/mcp/tools/upload-file",diff --git a/apps/web/src/lib/core/component/AI/component/tool/Initiatives.tsx b/apps/web/src/lib/core/component/AI/component/tool/Initiatives.tsxnew file mode 100644index 0000000000..af081c9955--- /dev/null+++ b/apps/web/src/lib/core/component/AI/component/tool/Initiatives.tsx@@ -0,0 +1,60 @@+import Stack from '@phosphor-icons/core/regular/stack.svg';+import type { ToolName } from '@service-cognition/generated/tools/tool';+import { createSignal } from 'solid-js';+import { BaseTool } from './BaseTool';+import { Tool } from './Tool';+import { createToolRenderer } from './ToolRenderer';++/** Keep project tool results inspectable before native project views are available. */+function initiativeHandler<TName extends ToolName>(name: TName, label: string) {+ return createToolRenderer({+ name,+ render: (ctx) => {+ const [expanded, setExpanded] = createSignal(false);+ return (+ <BaseTool+ type="call"+ icon={Stack}+ renderContext={ctx.renderContext}+ response={+ ctx.response && expanded() ? (+ <pre class="max-h-96 overflow-auto whitespace-pre-wrap break-all text-ink-muted">+ {JSON.stringify(ctx.response.data, null, 2)}+ </pre>+ ) : undefined+ }+ >+ <div class="flex min-w-0 items-center justify-between gap-3">+ <span class="truncate">{label}</span>+ <Tool.ResultToggle+ expanded={expanded()}+ showToggle={!!ctx.response}+ onToggle={() => setExpanded((value) => !value)}+ />+ </div>+ </BaseTool>+ );+ },+ });+}++export const initiativeToolHandlers = {+ ListInitiatives: initiativeHandler('ListInitiatives', 'Find projects'),+ ReadInitiative: initiativeHandler('ReadInitiative', 'Read project'),+ CreateInitiative: initiativeHandler('CreateInitiative', 'Create project'),+ UpdateInitiative: initiativeHandler('UpdateInitiative', 'Update project'),+ DeleteInitiative: initiativeHandler('DeleteInitiative', 'Delete project'),+ UpdateInitiativeSharing: initiativeHandler(+ 'UpdateInitiativeSharing',+ 'Update project sharing'+ ),+ SetTaskInitiative: initiativeHandler('SetTaskInitiative', 'Set task project'),+ ReadTaskInitiatives: initiativeHandler(+ 'ReadTaskInitiatives',+ 'Read task projects'+ ),+ ReadInitiativeActivity: initiativeHandler(+ 'ReadInitiativeActivity',+ 'Read project activity'+ ),+};diff --git a/apps/web/src/lib/core/component/AI/component/tool/handler.tsx b/apps/web/src/lib/core/component/AI/component/tool/handler.tsxindex c35ad04aba..d3d7b3280e 100644--- a/apps/web/src/lib/core/component/AI/component/tool/handler.tsx+++ b/apps/web/src/lib/core/component/AI/component/tool/handler.tsx@@ -47,6 +47,7 @@ import {importNotionPageHandler,listImportEntitiesHandler,} from './ImportTools';+import { initiativeToolHandlers } from './Initiatives';import { listEntitiesHandler } from './ListEntities';import { listInboxesHandler } from './ListInboxes';import { listLabelsHandler } from './ListLabels';@@ -111,6 +112,7 @@ import { webFetchHandler } from './WebFetch';import { webSearchHandler } from './WebSearch';const toolHandlers: ToolHandlerMap<RenderContext> = {+ ...initiativeToolHandlers,ReadSpreadsheet: readSpreadsheetHandler,CalculateSpreadsheet: calculateSpreadsheetHandler,EditSpreadsheet: editSpreadsheetHandler,diff --git a/apps/web/src/lib/service-clients/service-cognition/generated/tools/schemas.ts b/apps/web/src/lib/service-clients/service-cognition/generated/tools/schemas.tsindex 804eb9851f..6e6d167d40 100644--- a/apps/web/src/lib/service-clients/service-cognition/generated/tools/schemas.ts+++ b/apps/web/src/lib/service-clients/service-cognition/generated/tools/schemas.ts@@ -76,6 +76,7 @@ export const BulkSetEntityPropertyOptions = z.object({z.object({entity_type: z.enum(['document',+ 'initiative','project','chat','thread',@@ -1779,6 +1780,31 @@ export const CreateImportEntityResponse = z.object({message: z.string(),});+export const CreateInitiative = z.object({+ name: z.string(),+ description: z.union([z.string(), z.null()]).optional(),+ memberIds: z.union([z.array(z.string()), z.null()]).optional(),+ shareWithTeam: z.union([z.boolean(), z.null()]).optional(),+});++export const ProjectDetails = z.object({+ initiativeId: z.string().uuid(),+ name: z.string(),+ descriptionDocumentId: z.string().uuid(),+ ownerId: z.string(),+ memberIds: z.array(z.string()),+ taskIds: z.array(z.string()),+ taskCount: z.number().int().gte(0),+ tasksTruncated: z.boolean(),+ access: z.string(),+ teamAccess: z.union([z.string(), z.null()]).optional(),+ linkScope: z.union([z.string(), z.null()]).optional(),+ linkAccess: z.union([z.string(), z.null()]).optional(),+ channelShares: z.array(+ z.object({ channelId: z.string(), access: z.string() })+ ),+});+export const CreateProject = z.object({projectName: z.string(),parentProjectId: z.union([z.string().uuid(), z.null()]).optional(),@@ -2003,6 +2029,10 @@ export const DeleteImportEntityResponse = z.object({message: z.string(),});+export const DeleteInitiative = z.object({ initiativeId: z.string().uuid() });++export const ProjectOperationComplete = z.object({ success: z.boolean() });+export const DeleteReminder = z.object({ reminderId: z.string().uuid() });export const DeleteReminderResponse = z.object({@@ -2547,6 +2577,7 @@ export const GetEntityProperties = z.object({entity_id: z.string(),entity_type: z.enum(['document',+ 'initiative','project','chat','thread',@@ -3356,6 +3387,45 @@ export const ListInboxesResponse = z.object({summary: z.string(),});+export const ListInitiatives = z.object({+ query: z.union([z.string(), z.null()]).optional(),+ status: z.union([z.string().uuid(), z.null()]).optional(),+ priority: z.union([z.string().uuid(), z.null()]).optional(),+ assignee: z.union([z.string(), z.null()]).optional(),+ dueAfter: z+ .union([z.string().datetime({ offset: true }), z.null()])+ .optional(),+ dueBefore: z+ .union([z.string().datetime({ offset: true }), z.null()])+ .optional(),+ cursor: z.union([z.string(), z.null()]).optional(),+ limit: z.union([z.number().int().gte(0).lte(65535), z.null()]).optional(),+});++export const ProjectListResult = z.object({+ projects: z.array(+ z.object({+ initiativeId: z.string().uuid(),+ name: z.string(),+ descriptionDocumentId: z.string().uuid(),+ access: z.string(),+ properties: z.object({+ status: z.union([z.string().uuid(), z.null()]).optional(),+ priority: z.union([z.string().uuid(), z.null()]).optional(),+ assignees: z.array(z.string()),+ dueDate: z+ .union([z.string().datetime({ offset: true }), z.null()])+ .optional(),+ completed: z.boolean(),+ }),+ taskCount: z.number().int().gte(0),+ completedTaskCount: z.number().int().gte(0),+ })+ ),+ truncated: z.boolean(),+ nextCursor: z.union([z.string(), z.null()]).optional(),+});+export const ListLabels = z.object({thread_id: z.union([z.string().uuid(), z.null()]).optional(),inbox: z.union([z.string(), z.null()]).optional(),@@ -4919,6 +4989,81 @@ export const ReadContentResponse = z.object({),});+export const ReadInitiative = z.object({+ initiativeId: z.string().uuid(),+ taskCursor: z.union([z.string(), z.null()]).optional(),+ taskLimit: z.union([z.number().int().gte(0).lte(65535), z.null()]).optional(),+});++export const ProjectReadResult = z.object({+ project: z.object({+ initiativeId: z.string().uuid(),+ name: z.string(),+ descriptionDocumentId: z.string().uuid(),+ ownerId: z.string(),+ memberIds: z.array(z.string()),+ taskIds: z.array(z.string()),+ taskCount: z.number().int().gte(0),+ tasksTruncated: z.boolean(),+ access: z.string(),+ teamAccess: z.union([z.string(), z.null()]).optional(),+ linkScope: z.union([z.string(), z.null()]).optional(),+ linkAccess: z.union([z.string(), z.null()]).optional(),+ channelShares: z.array(+ z.object({ channelId: z.string(), access: z.string() })+ ),+ }),+ properties: z.object({+ status: z.union([z.string().uuid(), z.null()]).optional(),+ priority: z.union([z.string().uuid(), z.null()]).optional(),+ assignees: z.array(z.string()),+ dueDate: z+ .union([z.string().datetime({ offset: true }), z.null()])+ .optional(),+ completed: z.boolean(),+ }),+ nextTaskCursor: z.union([z.string(), z.null()]).optional(),+});++export const ReadInitiativeActivity = z.object({+ initiativeId: z.string().uuid(),+ after: z.union([z.string().datetime({ offset: true }), z.null()]).optional(),+ before: z.union([z.string().datetime({ offset: true }), z.null()]).optional(),+ cursor: z+ .union([+ z.object({+ occurredAt: z.string().datetime({ offset: true }),+ id: z.string().uuid(),+ }),+ z.null(),+ ])+ .optional(),+ limit: z.union([z.number().int().gte(0).lte(65535), z.null()]).optional(),+});++export const ProjectActivityResult = z.object({+ records: z.array(+ z.object({+ id: z.string().uuid(),+ actorId: z.string(),+ subjectId: z.string(),+ action: z.string(),+ actionPayload: z.any().optional(),+ occurredAt: z.string().datetime({ offset: true }),+ })+ ),+ truncated: z.boolean(),+ nextCursor: z+ .union([+ z.object({+ occurredAt: z.string().datetime({ offset: true }),+ id: z.string().uuid(),+ }),+ z.null(),+ ])+ .optional(),+});+export const ReadMetadata = z.object({ documentId: z.string().uuid() });export const ReadMetadataResponse = z.object({@@ -5081,6 +5226,40 @@ export const ReadSpreadsheet = z.object({includeStyles: z.union([z.boolean(), z.null()]).optional(),});+export const ReadTaskInitiatives = z.object({ taskIds: z.array(z.string()) });++export const TaskProjectReferences = z.object({+ references: z.array(+ z.any().superRefine((x, ctx) => {+ const schemas = [+ z.object({ taskId: z.string(), state: z.literal('none') }),+ z.object({ taskId: z.string(), state: z.literal('unavailable') }),+ z.object({+ taskId: z.string(),+ initiativeId: z.string().uuid(),+ name: z.string(),+ state: z.literal('visible'),+ }),+ ];+ const errors = schemas.reduce<z.ZodError[]>(+ (errors, schema) =>+ ((result) => (result.error ? [...errors, result.error] : errors))(+ schema.safeParse(x)+ ),+ []+ );+ if (schemas.length - errors.length !== 1) {+ ctx.addIssue({+ path: ctx.path,+ code: 'invalid_union',+ unionErrors: errors,+ message: 'Invalid input: Should pass single schema',+ });+ }+ })+ ),+});+export const RenameChannel = z.object({channelId: z.string().uuid(),name: z.string(),@@ -5346,6 +5525,7 @@ export const SetEntityProperty = z.object({entity_id: z.string(),entity_type: z.enum(['document',+ 'initiative','project','chat','thread',@@ -5371,6 +5551,7 @@ export const SetEntityProperty = z.object({entityType: z.enum(['document','task',+ 'initiative','project','chat','thread',@@ -5391,6 +5572,7 @@ export const SetEntityProperty = z.object({entityType: z.enum(['document','task',+ 'initiative','project','chat','thread',@@ -5470,6 +5652,15 @@ export const SetSenderPolicyResponse = z.object({summary: z.string(),});+export const SetTaskInitiative = z.object({+ taskIds: z.array(z.string()),+ initiativeId: z.union([z.string().uuid(), z.null()]).optional(),+});++export const TaskProjectOutcomes = z.object({+ results: z.array(z.object({ taskId: z.string(), status: z.string() })),+});+export const Subagent = z.object({ task: z.string() });export const SubagentResponse = z.object({ result: z.string() });@@ -5782,6 +5973,133 @@ export const ToolCalendarEvent = z.object({calendarId: z.union([z.string().uuid(), z.null()]).optional(),});+export const UpdateInitiative = z.object({+ initiativeId: z.string().uuid(),+ name: z.union([z.string(), z.null()]).optional(),+ memberIds: z.union([z.array(z.string()), z.null()]).optional(),+});++export const UpdateInitiativeSharing = z.object({+ initiativeId: z.string().uuid(),+ teamAccess: z+ .union([+ z.any().superRefine((x, ctx) => {+ const schemas = [+ z.literal('off'),+ z.literal('view'),+ z.literal('comment'),+ z.literal('edit'),+ ];+ const errors = schemas.reduce<z.ZodError[]>(+ (errors, schema) =>+ ((result) => (result.error ? [...errors, result.error] : errors))(+ schema.safeParse(x)+ ),+ []+ );+ if (schemas.length - errors.length !== 1) {+ ctx.addIssue({+ path: ctx.path,+ code: 'invalid_union',+ unionErrors: errors,+ message: 'Invalid input: Should pass single schema',+ });+ }+ }),+ z.null(),+ ])+ .optional(),+ linkScope: z+ .union([+ z.any().superRefine((x, ctx) => {+ const schemas = [+ z.literal('off'),+ z.literal('public'),+ z.literal('team'),+ ];+ const errors = schemas.reduce<z.ZodError[]>(+ (errors, schema) =>+ ((result) => (result.error ? [...errors, result.error] : errors))(+ schema.safeParse(x)+ ),+ []+ );+ if (schemas.length - errors.length !== 1) {+ ctx.addIssue({+ path: ctx.path,+ code: 'invalid_union',+ unionErrors: errors,+ message: 'Invalid input: Should pass single schema',+ });+ }+ }),+ z.null(),+ ])+ .optional(),+ linkAccess: z+ .union([+ z.any().superRefine((x, ctx) => {+ const schemas = [+ z.literal('off'),+ z.literal('view'),+ z.literal('comment'),+ z.literal('edit'),+ ];+ const errors = schemas.reduce<z.ZodError[]>(+ (errors, schema) =>+ ((result) => (result.error ? [...errors, result.error] : errors))(+ schema.safeParse(x)+ ),+ []+ );+ if (schemas.length - errors.length !== 1) {+ ctx.addIssue({+ path: ctx.path,+ code: 'invalid_union',+ unionErrors: errors,+ message: 'Invalid input: Should pass single schema',+ });+ }+ }),+ z.null(),+ ])+ .optional(),+ channels: z+ .union([+ z.array(+ z.object({+ channelId: z.string().uuid(),+ access: z.any().superRefine((x, ctx) => {+ const schemas = [+ z.literal('off'),+ z.literal('view'),+ z.literal('comment'),+ z.literal('edit'),+ ];+ const errors = schemas.reduce<z.ZodError[]>(+ (errors, schema) =>+ ((result) =>+ result.error ? [...errors, result.error] : errors)(+ schema.safeParse(x)+ ),+ []+ );+ if (schemas.length - errors.length !== 1) {+ ctx.addIssue({+ path: ctx.path,+ code: 'invalid_union',+ unionErrors: errors,+ message: 'Invalid input: Should pass single schema',+ });+ }+ }),+ })+ ),+ z.null(),+ ])+ .optional(),+});+export const UpdateReminder = z.object({reminderId: z.string().uuid(),description: z.union([z.string(), z.null()]).optional(),diff --git a/apps/web/src/lib/service-clients/service-cognition/generated/tools/tool.ts b/apps/web/src/lib/service-clients/service-cognition/generated/tools/tool.tsindex caa406e66a..6e104d3809 100644--- a/apps/web/src/lib/service-clients/service-cognition/generated/tools/tool.ts+++ b/apps/web/src/lib/service-clients/service-cognition/generated/tools/tool.ts@@ -49,6 +49,10 @@ type ToolParserMap = {call: types.CreateImportEntity;response: types.CreateImportEntityResponse;};+ CreateInitiative: {+ call: types.CreateInitiative;+ response: types.ProjectDetails;+ };CreateProject: {call: types.CreateProject;response: types.CreateProjectResponse;@@ -64,6 +68,10 @@ type ToolParserMap = {call: types.DeleteImportEntity;response: types.DeleteImportEntityResponse;};+ DeleteInitiative: {+ call: types.DeleteInitiative;+ response: types.ProjectOperationComplete;+ };DeleteReminder: {call: types.DeleteReminder;response: types.DeleteReminderResponse;@@ -122,6 +130,10 @@ type ToolParserMap = {response: types.ListImportEntitiesResponse;};ListInboxes: { call: types.ListInboxes; response: types.ListInboxesResponse };+ ListInitiatives: {+ call: types.ListInitiatives;+ response: types.ProjectListResult;+ };ListLabels: { call: types.ListLabels; response: types.ListLabelsResponse };ListNotifications: {call: types.ListNotifications;@@ -181,6 +193,14 @@ type ToolParserMap = {};ReadChat: { call: types.ReadChat; response: types.ReadChatResponse };ReadContent: { call: types.ReadContent; response: types.ReadContentResponse };+ ReadInitiative: {+ call: types.ReadInitiative;+ response: types.ProjectReadResult;+ };+ ReadInitiativeActivity: {+ call: types.ReadInitiativeActivity;+ response: types.ProjectActivityResult;+ };ReadMetadata: {call: types.ReadMetadata;response: types.ReadMetadataResponse;@@ -190,6 +210,10 @@ type ToolParserMap = {call: types.ReadSpreadsheet;response: types.SpreadsheetResponse;};+ ReadTaskInitiatives: {+ call: types.ReadTaskInitiatives;+ response: types.TaskProjectReferences;+ };ReadThread: { call: types.ReadThread; response: types.ReadResponse };RenameChannel: {call: types.RenameChannel;@@ -236,6 +260,10 @@ type ToolParserMap = {call: types.SetSenderPolicy;response: types.SetSenderPolicyResponse;};+ SetTaskInitiative: {+ call: types.SetTaskInitiative;+ response: types.TaskProjectOutcomes;+ };Subagent: { call: types.Subagent; response: types.SubagentResponse };TextEditorCodeExecution: {call: types.TextEditorCodeExecution;@@ -245,6 +273,14 @@ type ToolParserMap = {call: types.UpdateCalendarEvent;response: types.ToolCalendarEvent;};+ UpdateInitiative: {+ call: types.UpdateInitiative;+ response: types.ProjectDetails;+ };+ UpdateInitiativeSharing: {+ call: types.UpdateInitiativeSharing;+ response: types.ProjectDetails;+ };UpdateReminder: { call: types.UpdateReminder; response: types.ToolReminder };UpdateThreadLabels: {call: types.UpdateThreadLabels;@@ -297,6 +333,10 @@ const toolParserMap = {call: schemas.CreateImportEntity,response: schemas.CreateImportEntityResponse,},+ CreateInitiative: {+ call: schemas.CreateInitiative,+ response: schemas.ProjectDetails,+ },CreateProject: {call: schemas.CreateProject,response: schemas.CreateProjectResponse,@@ -315,6 +355,10 @@ const toolParserMap = {call: schemas.DeleteImportEntity,response: schemas.DeleteImportEntityResponse,},+ DeleteInitiative: {+ call: schemas.DeleteInitiative,+ response: schemas.ProjectOperationComplete,+ },DeleteReminder: {call: schemas.DeleteReminder,response: schemas.DeleteReminderResponse,@@ -379,6 +423,10 @@ const toolParserMap = {call: schemas.ListInboxes,response: schemas.ListInboxesResponse,},+ ListInitiatives: {+ call: schemas.ListInitiatives,+ response: schemas.ProjectListResult,+ },ListLabels: {call: schemas.ListLabels,response: schemas.ListLabelsResponse,@@ -450,6 +498,14 @@ const toolParserMap = {call: schemas.ReadContent,response: schemas.ReadContentResponse,},+ ReadInitiative: {+ call: schemas.ReadInitiative,+ response: schemas.ProjectReadResult,+ },+ ReadInitiativeActivity: {+ call: schemas.ReadInitiativeActivity,+ response: schemas.ProjectActivityResult,+ },ReadMetadata: {call: schemas.ReadMetadata,response: schemas.ReadMetadataResponse,@@ -462,6 +518,10 @@ const toolParserMap = {call: schemas.ReadSpreadsheet,response: schemas.SpreadsheetResponse,},+ ReadTaskInitiatives: {+ call: schemas.ReadTaskInitiatives,+ response: schemas.TaskProjectReferences,+ },ReadThread: { call: schemas.ReadThread, response: schemas.ReadResponse },RenameChannel: {call: schemas.RenameChannel,@@ -511,6 +571,10 @@ const toolParserMap = {call: schemas.SetSenderPolicy,response: schemas.SetSenderPolicyResponse,},+ SetTaskInitiative: {+ call: schemas.SetTaskInitiative,+ response: schemas.TaskProjectOutcomes,+ },Subagent: { call: schemas.Subagent, response: schemas.SubagentResponse },TextEditorCodeExecution: {call: schemas.TextEditorCodeExecution,@@ -520,6 +584,14 @@ const toolParserMap = {call: schemas.UpdateCalendarEvent,response: schemas.ToolCalendarEvent,},+ UpdateInitiative: {+ call: schemas.UpdateInitiative,+ response: schemas.ProjectDetails,+ },+ UpdateInitiativeSharing: {+ call: schemas.UpdateInitiativeSharing,+ response: schemas.ProjectDetails,+ },UpdateReminder: {call: schemas.UpdateReminder,response: schemas.ToolReminder,@@ -586,6 +658,10 @@ type ToolDataMap = {call: types.CreateImportEntity;response: types.CreateImportEntityResponse;};+ CreateInitiative: {+ call: types.CreateInitiative;+ response: types.ProjectDetails;+ };CreateProject: {call: types.CreateProject;response: types.CreateProjectResponse;@@ -601,6 +677,10 @@ type ToolDataMap = {call: types.DeleteImportEntity;response: types.DeleteImportEntityResponse;};+ DeleteInitiative: {+ call: types.DeleteInitiative;+ response: types.ProjectOperationComplete;+ };DeleteReminder: {call: types.DeleteReminder;response: types.DeleteReminderResponse;@@ -659,6 +739,10 @@ type ToolDataMap = {response: types.ListImportEntitiesResponse;};ListInboxes: { call: types.ListInboxes; response: types.ListInboxesResponse };+ ListInitiatives: {+ call: types.ListInitiatives;+ response: types.ProjectListResult;+ };ListLabels: { call: types.ListLabels; response: types.ListLabelsResponse };ListNotifications: {call: types.ListNotifications;@@ -718,6 +802,14 @@ type ToolDataMap = {};ReadChat: { call: types.ReadChat; response: types.ReadChatResponse };ReadContent: { call: types.ReadContent; response: types.ReadContentResponse };+ ReadInitiative: {+ call: types.ReadInitiative;+ response: types.ProjectReadResult;+ };+ ReadInitiativeActivity: {+ call: types.ReadInitiativeActivity;+ response: types.ProjectActivityResult;+ };ReadMetadata: {call: types.ReadMetadata;response: types.ReadMetadataResponse;@@ -727,6 +819,10 @@ type ToolDataMap = {call: types.ReadSpreadsheet;response: types.SpreadsheetResponse;};+ ReadTaskInitiatives: {+ call: types.ReadTaskInitiatives;+ response: types.TaskProjectReferences;+ };ReadThread: { call: types.ReadThread; response: types.ReadResponse };RenameChannel: {call: types.RenameChannel;@@ -773,6 +869,10 @@ type ToolDataMap = {call: types.SetSenderPolicy;response: types.SetSenderPolicyResponse;};+ SetTaskInitiative: {+ call: types.SetTaskInitiative;+ response: types.TaskProjectOutcomes;+ };Subagent: { call: types.Subagent; response: types.SubagentResponse };TextEditorCodeExecution: {call: types.TextEditorCodeExecution;@@ -782,6 +882,14 @@ type ToolDataMap = {call: types.UpdateCalendarEvent;response: types.ToolCalendarEvent;};+ UpdateInitiative: {+ call: types.UpdateInitiative;+ response: types.ProjectDetails;+ };+ UpdateInitiativeSharing: {+ call: types.UpdateInitiativeSharing;+ response: types.ProjectDetails;+ };UpdateReminder: { call: types.UpdateReminder; response: types.ToolReminder };UpdateThreadLabels: {call: types.UpdateThreadLabels;diff --git a/apps/web/src/lib/service-clients/service-cognition/generated/tools/types.ts b/apps/web/src/lib/service-clients/service-cognition/generated/tools/types.tsindex c52e8c2a53..fa34117dac 100644--- a/apps/web/src/lib/service-clients/service-cognition/generated/tools/types.ts+++ b/apps/web/src/lib/service-clients/service-cognition/generated/tools/types.ts@@ -36,6 +36,7 @@ export type CodeExecutionErrorCode =*/export type ToolPropertyTargetEntityType =| 'document'+ | 'initiative'| 'project'| 'chat'| 'thread'@@ -1031,6 +1032,39 @@ export type AccessLevel = 'view' | 'comment' | 'edit' | 'owner';* The kind of an item inside a project.*/export type ProjectItemType = 'document' | 'chat' | 'project';+/**+ * Privacy-preserving task project reference.+ */+export type TaskProjectReference =+ | {+ /**+ * Requested task id.+ */+ taskId: string;+ state: 'none';+ }+ | {+ /**+ * Requested task id.+ */+ taskId: string;+ state: 'unavailable';+ }+ | {+ /**+ * Requested task id.+ */+ taskId: string;+ /**+ * Associated project id.+ */+ initiativeId: string;+ /**+ * Associated project name.+ */+ name: string;+ state: 'visible';+ };/*** How search terms are matched against skill names.*/@@ -1069,6 +1103,7 @@ export type UserToolResponseForSendEmailResponse =export type ToolEntityType =| 'document'| 'task'+ | 'initiative'| 'project'| 'chat'| 'thread'@@ -1108,6 +1143,14 @@ export type ConferenceChangeInput = 'google_meet' | 'remove';* The requester's own RSVP on an event they were invited to.*/export type RsvpResponseInput = 'accepted' | 'declined' | 'tentative';+/**+ * A share can be disabled or grant a non-owner permission.+ */+export type ProjectShareAccess = 'off' | 'view' | 'comment' | 'edit';+/**+ * Scope admitted by a project's share link.+ */+export type ProjectLinkScope = 'off' | 'public' | 'team';/*** Content of a web fetch response - either a successful result or an error*/@@ -2875,6 +2918,97 @@ export interface ImportEntityView {*/importedByTeammate: boolean;}+/**+ * Create a project for coordinating tasks (called an initiative in the API). Projects have status, priority, assignees, due dates, discussions and activity. Shares with the owner's team by default. This is different from CreateProject, which creates a folder. Use property tools with entity_type='initiative' to set project properties.+ */+export interface CreateInitiative {+ /**+ * Project name, up to 100 graphemes.+ */+ name: string;+ /**+ * Initial Markdown description, up to 2000 graphemes; optional.+ */+ description?: string | null;+ /**+ * Users to grant collaboration access; distinct from property assignees.+ */+ memberIds?: string[] | null;+ /**+ * Defaults to true. False creates without an explicit team grant.+ */+ shareWithTeam?: boolean | null;+}+/**+ * Current project state, including visibility-filtered task membership.+ */+export interface ProjectDetails {+ /**+ * Project id; use entity type `initiative` in property tools.+ */+ initiativeId: string;+ /**+ * Project name.+ */+ name: string;+ /**+ * Description document; read or edit its Markdown using document tools.+ */+ descriptionDocumentId: string;+ /**+ * Project owner.+ */+ ownerId: string;+ /**+ * Collaboration members, distinct from property assignees.+ */+ memberIds: string[];+ /**+ * Up to 200 associated tasks the caller can view.+ */+ taskIds: string[];+ /**+ * Total associated tasks the caller can view.+ */+ taskCount: number;+ /**+ * Whether the project contains additional visible tasks beyond taskIds.+ */+ tasksTruncated: boolean;+ /**+ * Caller's effective permission.+ */+ access: string;+ /**+ * Explicit owner-team access, or absent when off.+ */+ teamAccess?: string | null;+ /**+ * Link scope: PUBLIC or TEAM, or absent when off.+ */+ linkScope?: string | null;+ /**+ * Access granted by the link.+ */+ linkAccess?: string | null;+ /**+ * Explicit channel shares.+ */+ channelShares: ProjectChannelShare[];+}+/**+ * One channel's explicit project grant.+ */+export interface ProjectChannelShare {+ /**+ * Shared channel identifier.+ */+ channelId: string;+ /**+ * Granted access level.+ */+ access: string;+}/*** Create a project — shown as a folder in the app UI. Documents, AI chats, email threads, and other projects can be placed inside it.*/@@ -3119,6 +3253,24 @@ export interface DeleteImportEntityResponse {*/message: string;}+/**+ * Permanently delete a project, its description and properties. Associated tasks remain and lose their project association. Requires ownership. This operation cannot be undone.+ */+export interface DeleteInitiative {+ /**+ * Project to permanently delete.+ */+ initiativeId: string;+}+/**+ * Successful project mutation with no further result body.+ */+export interface ProjectOperationComplete {+ /**+ * True when the operation completed.+ */+ success: boolean;+}/*** Permanently delete one of the current user's reminders, along with any notification it already produced. Get the `reminderId` from ListReminders or CreateReminder.*@@ -4164,6 +4316,115 @@ export interface ToolInbox {*/isDelegated: boolean;}+/**+ * Find projects (initiatives), with canonical properties and progress over tasks you can view. Returns at most 100 recently updated matches per page. Pass nextCursor back as cursor with the same filters to read more. Filter by name, status, priority, assignee, or due date. Project folders use ReadProject instead.+ */+export interface ListInitiatives {+ /**+ * Case-insensitive project name substring.+ */+ query?: string | null;+ /**+ * Status option id, obtained from property definitions.+ */+ status?: string | null;+ /**+ * Priority option id, obtained from property definitions.+ */+ priority?: string | null;+ /**+ * Assigned user id.+ */+ assignee?: string | null;+ /**+ * Earliest inclusive due timestamp.+ */+ dueAfter?: string | null;+ /**+ * Latest inclusive due timestamp.+ */+ dueBefore?: string | null;+ /**+ * Opaque nextCursor from the preceding page, with the same filters.+ */+ cursor?: string | null;+ /**+ * Maximum projects to return, from 1 through 100; defaults to 100.+ */+ limit?: number | null;+}+/**+ * Bounded project search results.+ */+export interface ProjectListResult {+ /**+ * Matching visible projects.+ */+ projects: ProjectListRow[];+ /**+ * True when additional matches exist.+ */+ truncated: boolean;+ /**+ * Opaque cursor for the next page, absent after the final page.+ */+ nextCursor?: string | null;+}+/**+ * One visible project with canonical fields and permission-aware progress.+ */+export interface ProjectListRow {+ /**+ * Project id.+ */+ initiativeId: string;+ /**+ * Project name.+ */+ name: string;+ /**+ * Description document id.+ */+ descriptionDocumentId: string;+ /**+ * Effective caller access.+ */+ access: string;+ properties: ProjectPropertyValues;+ /**+ * Count of associated tasks visible to the caller.+ */+ taskCount: number;+ /**+ * Visible completed tasks.+ */+ completedTaskCount: number;+}+/**+ * Canonical system-property values, editable through SetEntityProperty.+ */+export interface ProjectPropertyValues {+ /**+ * Status option id, or unset.+ */+ status?: string | null;+ /**+ * Priority option id, or unset.+ */+ priority?: string | null;+ /**+ * Assigned users, independent from sharing membership.+ */+ assignees: string[];+ /**+ * Due timestamp, or unset.+ */+ dueDate?: string | null;+ /**+ * Whether the status is completed.+ */+ completed: boolean;+}/*** List the user's Gmail labels. Returns both system labels (INBOX, SENT, DRAFTS, UNREAD, STARRED, TRASH, SPAM, IMPORTANT, CATEGORY_PERSONAL, CATEGORY_SOCIAL, CATEGORY_PROMOTIONS, CATEGORY_UPDATES, CATEGORY_FORUMS, etc.) and any custom user-created labels. Each label has a UUID `id` and a `name`.*@@ -5377,6 +5638,120 @@ export interface DocumentComment {*/editedAt?: string | null;}+/**+ * Read a project, its sharing, canonical status/priority/assignees/due date, and a bounded page of associated task ids that you can view, with their total count. Pass nextTaskCursor back as taskCursor to read more task ids. Requires view access. The descriptionDocumentId can be read or edited with document tools. Use entity_type='initiative' with property tools. ReadInitiativeActivity returns the project's activity history.+ */+export interface ReadInitiative {+ /**+ * Project identifier.+ */+ initiativeId: string;+ /**+ * Opaque nextTaskCursor from the preceding page for this project.+ */+ taskCursor?: string | null;+ /**+ * Maximum task ids to return, from 1 through 100; defaults to 100.+ */+ taskLimit?: number | null;+}+/**+ * Project detail and canonical property values.+ */+export interface ProjectReadResult {+ project: ProjectDetails;+ properties: ProjectPropertyValues;+ /**+ * Opaque cursor for the next task page, absent after the final page.+ */+ nextTaskCursor?: string | null;+}+/**+ * Read project creation, edits, property changes, and task membership changes, newest first. Task references require current task view access. Each page scans at most 100 events and may contain fewer visible records. Pass nextCursor back as cursor with the same time filters to continue, including after an empty page.+ */+export interface ReadInitiativeActivity {+ /**+ * Project identifier.+ */+ initiativeId: string;+ /**+ * Only changes at or after this timestamp.+ */+ after?: string | null;+ /**+ * Only changes before this timestamp.+ */+ before?: string | null;+ /**+ * Opaque nextCursor from the preceding activity page.+ */+ cursor?: InitiativeActivityCursor | null;+ /**+ * Maximum events to scan, from 1 through 100; defaults to 100.+ */+ limit?: number | null;+}+/**+ * Stable cursor for project history.+ */+export interface InitiativeActivityCursor {+ /**+ * Time of the last scanned activity.+ */+ occurredAt: string;+ /**+ * Tie-breaker within the same timestamp.+ */+ id: string;+}+/**+ * Bounded visible project activity.+ */+export interface ProjectActivityResult {+ /**+ * Visible events ordered newest first.+ */+ records: InitiativeActivityRecord[];+ /**+ * More events may match; follow nextCursor.+ */+ truncated: boolean;+ /**+ * Stable continuation, absent after the final matching page.+ */+ nextCursor?: InitiativeActivityCursor | null;+}+/**+ * One authorized activity row; task names are hydrated through existing authorized task reads.+ */+export interface InitiativeActivityRecord {+ /**+ * Stable record identifier, also used for realtime deduplication.+ */+ id: string;+ /**+ * Principal who acted.+ */+ actorId: string;+ /**+ * Acting user's feed identity when a bot acted on their behalf.+ */+ subjectId: string;+ /**+ * Durable activity action tag.+ */+ action: string;+ /**+ * Typed payload for known actions. Absent for unknown actions.+ */+ actionPayload?: {+ [k: string]: unknown;+ };+ /**+ * Time of the change.+ */+ occurredAt: string;+}/*** Retrieve a documents metadata*/@@ -5569,6 +5944,24 @@ export interface ReadSpreadsheet {*/includeStyles?: boolean | null;}+/**+ * Find the project associated with each requested task. Returns project id/name only when both task and project are visible. Distinguishes no project from unavailable. Accepts up to 100 unique task ids.+ */+export interface ReadTaskInitiatives {+ /**+ * Task ids to look up, deduplicated in input order.+ */+ taskIds: string[];+}+/**+ * Visibility-aware project references for the requested tasks.+ */+export interface TaskProjectReferences {+ /**+ * References in deduplicated request order.+ */+ references: TaskProjectReference[];+}/*** Rename an existing channel. Requires the current user to be an active channel participant. Direct-message channels cannot be renamed. Use only when the user asks to rename a channel.*/@@ -5878,7 +6271,7 @@ export interface SendEmail {includeSignature?: boolean | null;}/**- * Set or update a property value on an entity (document, project, etc.). Tasks are targeted as entity_type='document'. Provide the property_definition_id and exactly one value field matching the property's data type.+ * Set or update a property value on an entity. Tasks are targeted as entity_type='document'. Projects in the Tasks UI are entity_type='initiative'; entity_type='project' still means a folder. Initiatives share the Assignees, Status, Priority and Due Date definitions below and their clearing behavior. Project Status accepts only Not Started (00000001-0000-0000-0002-000000000001), In Progress (...0002), and Completed (...0004); In Review and Canceled are task-only options. Provide the property_definition_id and exactly one value field matching the property's data type.** For multi-select properties — including tags — prefer add_option_ids / remove_option_ids over option_ids: they add or remove just those options atomically, composing with concurrent edits. option_ids replaces the entire value, so a stale read can silently drop options someone else just added; only use it when the user asks to set the value to exactly a given list. To apply a tag, pass the tag set's property_definition_id and the tag's option id (both from ListTags) in add_option_ids; to remove a tag, use remove_option_ids.*@@ -6015,6 +6408,41 @@ export interface SetSenderPolicyResponse {*/summary: string;}+/**+ * Set the project associated with tasks, moving them from their previous project if needed. Requires edit access to each task and the destination project; access to the previous project is unnecessary. Omit initiativeId to clear the association using task edit access alone. Reports each task's outcome independently; at most 100 unique tasks.+ */+export interface SetTaskInitiative {+ /**+ * Task ids to assign or clear, deduplicated in request order.+ */+ taskIds: string[];+ /**+ * Destination project; omit to clear each task's current project.+ */+ initiativeId?: string | null;+}+/**+ * Results in deduplicated input order.+ */+export interface TaskProjectOutcomes {+ /**+ * Outcome for every submitted task.+ */+ results: TaskProjectOutcome[];+}+/**+ * One task mutation outcome.+ */+export interface TaskProjectOutcome {+ /**+ * Requested task identifier.+ */+ taskId: string;+ /**+ * assigned, moved, cleared, notATask, notFound, skippedNoPermission, or failed.+ */+ status: string;+}/*** Delegate a task to a subagent that can independently use tools to research and complete it. The subagent has access to search, documents, properties, calls, and channel tools. Use this for tasks that require multiple tool calls or independent research.*/@@ -6163,6 +6591,58 @@ export interface UpdateCalendarEvent {*/outOfOffice?: OutOfOfficeInput | null;}+/**+ * Rename a project with edit access, or replace its collaboration member list as the owner. Members control sharing independently of the assignee property. Assigning a user grants collaboration access; removing an assignment retains that access. For status, priority, assignees and due date use SetEntityProperty with entity_type='initiative'. ReadInitiative returns the description document id for document editing tools.+ */+export interface UpdateInitiative {+ /**+ * Project identifier.+ */+ initiativeId: string;+ /**+ * Replacement name; omitted leaves it unchanged.+ */+ name?: string | null;+ /**+ * Owner-only complete replacement member list; omitted preserves existing members, [] clears it.+ */+ memberIds?: string[] | null;+}+/**+ * Change a project's team, link or channel sharing. Only the actual project owner may change sharing. Each omitted field remains unchanged; off disables that share. Project and description document permissions change together. Collaboration member changes use UpdateInitiative.+ */+export interface UpdateInitiativeSharing {+ /**+ * Project identifier.+ */+ initiativeId: string;+ /**+ * Explicit owner-team grant; off removes it.+ */+ teamAccess?: ProjectShareAccess | null;+ /**+ * Who the project link admits; off disables it.+ */+ linkScope?: ProjectLinkScope | null;+ /**+ * Permission granted by an enabled link. Off resets it to the default view level.+ */+ linkAccess?: ProjectShareAccess | null;+ /**+ * Individual channel shares to set or remove; other shares remain unchanged.+ */+ channels?: ProjectChannelSharing[] | null;+}+/**+ * Update one channel's grant without replacing other channel grants.+ */+export interface ProjectChannelSharing {+ /**+ * Channel id to share with or revoke.+ */+ channelId: string;+ access: ProjectShareAccess;+}/*** Change one of the current user's reminders: reword it, move when it fires, or mark it done. Get the `reminderId` from ListReminders or CreateReminder.*diff --git a/crates/ai_tools/Cargo.toml b/crates/ai_tools/Cargo.tomlindex f2e62c6db8..c2f2b66cad 100644--- a/crates/ai_tools/Cargo.toml+++ b/crates/ai_tools/Cargo.toml@@ -8,7 +8,8 @@ version = "0.1.0"test-support = [][dependencies]-initiative = { path = "../initiative", default-features = false, features = ["postgres", "resources"] }+initiative = { path = "../initiative", default-features = false, features = ["postgres", "resources", "toolset"] }+initiative_documents = { path = "../initiative_documents" }activity = { path = "../activity", default-features = false, features = ["ai_tools", "outbound"] }agent = { path = "../agent" }ai_usage = { path = "../ai_usage" }@@ -36,7 +37,7 @@ contacts = { path = "../contacts", default-features = false, features = ["outbound",] }crm = { path = "../crm" }-documents = { path = "../documents", features = ["ai_tools"] }+documents = { path = "../documents", features = ["ai_tools", "purge"] }email = { path = "../email", features = ["ai_schema", "ai_tools", "axum", "outbound"] }email_service_client = { path = "../email_service_client" }entity_access = { path = "../entity_access" }diff --git a/crates/ai_tools/src/build_context.rs b/crates/ai_tools/src/build_context.rsindex 9030095681..43ceb051b5 100644--- a/crates/ai_tools/src/build_context.rs+++ b/crates/ai_tools/src/build_context.rs@@ -405,6 +405,15 @@ pub async fn build_tool_service_context_from_env(let skill_tool_context =crate::tool_context::build_skill_tool_context(search_client.clone(), soup_service.clone());+ let initiative_tool_context = crate::tool_context::build_initiative_tool_context(+ pool.clone(),+ &document_tool_context,+ properties_service.clone(),+ entity_access_service.clone(),+ side_effect_clients.sqs,+ side_effect_clients.macro_event_broker,+ );+Ok(ToolServiceContext {search_service_client: search_client.clone(),email_service_client: email_ext_client,@@ -435,6 +444,7 @@ pub async fn build_tool_service_context_from_env(document_storage_service_url,),project_tool_context,+ initiative_tool_context,team_tool_context: crate::tool_context::build_team_tool_context(pool.clone()),crm_tool_context: crate::tool_context::build_crm_tool_context(pool.clone()),skill_tool_context,diff --git a/crates/ai_tools/src/lib.rs b/crates/ai_tools/src/lib.rsindex 47f3ee1dce..ee2e181ac1 100644--- a/crates/ai_tools/src/lib.rs+++ b/crates/ai_tools/src/lib.rs@@ -30,6 +30,7 @@ use display_results::DisplayResults;use documents::inbound::toolset::document_toolset;use email::inbound::toolset::{email_toolset, mcp_toolset as email_mcp_toolset};use import::inbound::toolset::import_toolset;+use initiative::inbound::toolset::initiative_toolset;use notification::inbound::ai_tool::notification_toolset;use projects::inbound::toolset::project_toolset;use properties::inbound::toolset::properties_toolset;@@ -60,18 +61,19 @@ pub use tool_context::{ToolDocumentService, ToolDocumentToolContext, ToolEmailService, ToolEmailToolContext,ToolEntityAccessManagementService, ToolEntityAccessService, ToolEntityCreator,ToolForeignEntityService, ToolFrecencyService, ToolImportService, ToolImportToolContext,- ToolMcpSelector, ToolNotificationQueue, ToolNotificationService, ToolNotificationToolContext,- ToolPipedreamConnection, ToolProjectService, ToolProjectToolContext, ToolPropertiesService,- ToolPropertiesToolContext, ToolRemindersService, ToolRemindersToolContext, ToolServiceContext,- ToolSkillService, ToolSkillToolContext, ToolSoupService, ToolSystemPropertiesService,- ToolTeamService, ToolTeamToolContext, ToolUserEmailService, build_activity_tool_context,- build_bot_tool_context, build_calendar_tool_context,- build_channel_tool_context_with_dispatcher, build_channel_tool_context_with_side_effects,- build_channel_tool_context_without_side_effects, build_crm_tool_context,- build_message_service_with_side_effects, build_message_service_without_side_effects,- build_project_tool_context, build_properties_service, build_properties_service_with_broker,- build_properties_tool_context, build_reminders_tool_context, build_skill_tool_context,- build_task_properties_adapter, build_team_repository, build_team_tool_context,+ ToolInitiativeToolContext, ToolMcpSelector, ToolNotificationQueue, ToolNotificationService,+ ToolNotificationToolContext, ToolPipedreamConnection, ToolProjectService,+ ToolProjectToolContext, ToolPropertiesService, ToolPropertiesToolContext, ToolRemindersService,+ ToolRemindersToolContext, ToolServiceContext, ToolSkillService, ToolSkillToolContext,+ ToolSoupService, ToolSystemPropertiesService, ToolTeamService, ToolTeamToolContext,+ ToolUserEmailService, build_activity_tool_context, build_bot_tool_context,+ build_calendar_tool_context, build_channel_tool_context_with_dispatcher,+ build_channel_tool_context_with_side_effects, build_channel_tool_context_without_side_effects,+ build_crm_tool_context, build_initiative_tool_context, build_message_service_with_side_effects,+ build_message_service_without_side_effects, build_project_tool_context,+ build_properties_service, build_properties_service_with_broker, build_properties_tool_context,+ build_reminders_tool_context, build_skill_tool_context, build_task_properties_adapter,+ build_team_repository, build_team_tool_context,};pub type AiToolSet = AsyncToolCollection<ToolServiceContext>;@@ -99,6 +101,7 @@ pub(crate) fn subagent_toolset() -> AiToolSet {.add_subtoolset::<ToolActivityToolContext>(activity_toolset()).add_subtoolset::<ToolDocumentToolContext>(document_toolset()).add_subtoolset::<ToolProjectToolContext>(project_toolset())+ .add_subtoolset::<ToolInitiativeToolContext>(initiative_toolset()).add_subtoolset::<ToolPropertiesToolContext>(properties_toolset()).add_subtoolset::<ToolCallToolContext>(call_toolset()).add_subtoolset::<ToolChatToolContext>(chat_toolset())diff --git a/crates/ai_tools/src/test.rs b/crates/ai_tools/src/test.rsindex 5b7e062c0a..7d3b7817c6 100644--- a/crates/ai_tools/src/test.rs+++ b/crates/ai_tools/src/test.rs@@ -32,6 +32,47 @@ fn every_host_toolset_passes_schema_validation() {}}+#[test]+fn project_workflows_are_available_in_every_host_alongside_folder_and_property_tools() {+ let names = [+ "ListInitiatives",+ "ReadInitiative",+ "CreateInitiative",+ "UpdateInitiative",+ "DeleteInitiative",+ "UpdateInitiativeSharing",+ "SetTaskInitiative",+ "ReadTaskInitiatives",+ "ReadInitiativeActivity",+ "SetEntityProperty",+ "ReplyToDocumentComment",+ "CommentOnDocumentText",+ "ResolveDocumentComment",+ "CreateProject",+ "ReadProject",+ ];+ for host in [+ AiHost::Chat,+ AiHost::AgentSession,+ AiHost::ChannelBot,+ AiHost::Mcp,+ ] {+ let json = frontend_schemas_builder()+ .merge(&tools_for(host))+ .build()+ .to_json_pretty()+ .expect("schemas serialize");+ let schema: serde_json::Value = serde_json::from_str(&json).unwrap();+ let tools = schema["tools"].as_array().unwrap();+ for name in names {+ assert!(+ tools.iter().any(|tool| tool["name"] == name),+ "{host:?} must expose {name}"+ );+ }+ }+}+/// An agent session finishes user tools in the turn, so it keeps chat's/// deferring registrations - and gets the prompt that says a review card,/// not a pending composer, is what follows the call.diff --git a/crates/ai_tools/src/tool_context.rs b/crates/ai_tools/src/tool_context.rsindex fb11303f76..3d9d2349ea 100644--- a/crates/ai_tools/src/tool_context.rs+++ b/crates/ai_tools/src/tool_context.rs@@ -63,6 +63,8 @@ use teams::{inbound::toolset::TeamToolContext, outbound::team_repo::TeamRepositouse tokio_util::task::TaskTracker;mod activity_metadata;+mod initiatives;+pub use initiatives::{ToolInitiativeToolContext, build_initiative_tool_context};use activity_metadata::ToolActivityMetadataResolver;pub use ai_toolset::RequestContext;@@ -1489,6 +1491,8 @@ pub struct ToolServiceContext {pub channel_tool_context: ToolChannelToolContext,pub bot_tool_context: ToolBotToolContext,pub project_tool_context: ToolProjectToolContext,+ /// Native task project lifecycle, properties, sharing and history.+ pub initiative_tool_context: ToolInitiativeToolContext,pub team_tool_context: ToolTeamToolContext,pub crm_tool_context: ToolCrmToolContext,pub skill_tool_context: ToolSkillToolContext,@@ -1510,6 +1514,7 @@ impl ToolServiceContext {self.document_tool_context = self.document_tool_context.with_actor(actor);self.properties_tool_context = self.properties_tool_context.with_actor(actor);self.project_tool_context = self.project_tool_context.with_actor(actor);+ self.initiative_tool_context = self.initiative_tool_context.with_actor(actor);self.channel_tool_context = self.channel_tool_context.with_actor(actor);self}diff --git a/crates/ai_tools/src/tool_context/initiatives.rs b/crates/ai_tools/src/tool_context/initiatives.rsnew file mode 100644index 0000000000..b346a0f214--- /dev/null+++ b/crates/ai_tools/src/tool_context/initiatives.rs@@ -0,0 +1,85 @@+//! Composition of project workflows from owning domain ports and adapters.++use super::*;+use documents::domain::{ports::mentions::NoOpDocumentMentionTracker, purge::DocumentPurger};+use documents::outbound::{+ document_bytes_upload::ReqwestDocumentBytesUploader,+ document_purge::{LegacyDocumentPurgeRepository, SqsDocumentPurgeQueue},+ markdown_init::LexicalSyncMarkdownInitializer,+};+use initiative::{+ domain::{+ history::InitiativeHistory, resources::InitiativeResources, service::InitiativeServiceImpl,+ },+ inbound::toolset::InitiativeToolContext,+ outbound::{PgInitiativeRepo, resources::ProjectResources},+};++type ToolDescriptionDocuments = initiative_documents::InitiativeDescriptionDocumentsAdapter<+ Arc<ToolDocumentService>,+ LexicalSyncMarkdownInitializer,+ ReqwestDocumentBytesUploader,+ NoOpDocumentMentionTracker,+ DocumentPurger<LegacyDocumentPurgeRepository, SqsDocumentPurgeQueue, ToolEventBroker>,+>;++/// Production initiative service with the same document lifecycle as DSS.+pub type ToolInitiativeService = InitiativeServiceImpl<PgInitiativeRepo, ToolDescriptionDocuments>;++/// Native project workflow context for every AI/MCP host.+pub type ToolInitiativeToolContext = InitiativeToolContext<+ ToolInitiativeService,+ ToolEntityAccessService,+ activity::outbound::pg_activity_repo::PgActivityRepo,+>;++/// Compose project lifecycle tools with document cleanup and activity publication.+pub fn build_initiative_tool_context(+ pool: sqlx::PgPool,+ documents: &ToolDocumentToolContext,+ properties: Arc<ToolPropertiesService>,+ access: Arc<ToolEntityAccessService>,+ sqs: aws_sdk_sqs::Client,+ event_broker: ToolEventBroker,+) -> ToolInitiativeToolContext {+ let document_queue = Arc::new(+ sqs_client::SQS::new(sqs)+ .document_delete_queue(macro_queues::DocumentDeleteQueue::new().as_ref()),+ );+ let purger = DocumentPurger::new(+ LegacyDocumentPurgeRepository::new(pool.clone()),+ SqsDocumentPurgeQueue::new(document_queue),+ event_broker.clone(),+ );+ let description = initiative_documents::InitiativeDescriptionDocumentsAdapter::new(+ documents.creator.clone(),+ purger,+ );+ let resources: Arc<dyn InitiativeResources> = Arc::new(ProjectResources::new(+ properties,+ Arc::new(SystemPropertiesServiceImpl::new(+ PgSystemPropertiesRepository::new(pool.clone()),+ )),+ access.clone(),+ ));+ let service = InitiativeServiceImpl::new(+ PgInitiativeRepo::new(pool.clone()),+ description,+ resources.clone(),+ )+ .with_event_publisher(Arc::new(+ initiative::outbound::event_publisher::BrokerInitiativeEventPublisher::new(+ event_broker.clone(),+ ),+ ));+ InitiativeToolContext {+ service: Arc::new(service),+ access: access.clone(),+ history: Arc::new(InitiativeHistory::new(+ activity::outbound::pg_activity_repo::PgActivityRepo::new(pool.clone()),+ access.clone(),+ )),+ resources,+ actor: bot_id::MACRO_AI_BOT_ID,+ }+}diff --git a/crates/graphql_initiative/src/lib.rs b/crates/graphql_initiative/src/lib.rsindex 9d050cd557..c3bba3427e 100644--- a/crates/graphql_initiative/src/lib.rs+++ b/crates/graphql_initiative/src/lib.rs@@ -30,6 +30,7 @@ use initiative::domain::models::InitiativeError;fn graphql_error(error: InitiativeError) -> async_graphql::Error {let (message, code) = match error {InitiativeError::NotFound => ("initiative not found".to_string(), "NOT_FOUND"),+ InitiativeError::NotATask => ("document is not a task".to_string(), "BAD_USER_INPUT"),InitiativeError::Unauthorized => ("unauthorized".to_string(), "FORBIDDEN"),InitiativeError::BadRequest(message) => (message, "BAD_USER_INPUT"),InitiativeError::Conflict(message) => (message, "CONFLICT"),diff --git a/crates/initiative/Cargo.toml b/crates/initiative/Cargo.tomlindex 57f7960a66..6212426a76 100644--- a/crates/initiative/Cargo.toml+++ b/crates/initiative/Cargo.toml@@ -5,6 +5,7 @@ publish = falseversion = "0.1.0"[features]+toolset = ["inbound", "dep:ai_toolset", "dep:anyhow", "dep:async-trait", "dep:bot_id", "dep:schemars"]default = ["ports", "postgres"]inbound = ["dep:axum",@@ -27,6 +28,11 @@ postgres = [][dependencies]+ai_toolset = { path = "../ai_toolset", optional = true }+anyhow = { workspace = true, optional = true }+async-trait = { workspace = true, optional = true }+bot_id = { path = "../bot_id", optional = true }+schemars = { workspace = true, optional = true }properties = { path = "../properties", optional = true, default-features = false }system_properties = { path = "../system_properties", optional = true }models_properties = { path = "../models_properties", optional = true }diff --git a/crates/initiative/src/domain/history.rs b/crates/initiative/src/domain/history.rsindex 3deeecf6e3..6ed23963fc 100644--- a/crates/initiative/src/domain/history.rs+++ b/crates/initiative/src/domain/history.rs@@ -19,6 +19,7 @@ use super::models::InitiativeError;/// Stable cursor for project history.#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]+#[cfg_attr(feature = "toolset", derive(schemars::JsonSchema))]#[cfg_attr(feature = "inbound", derive(utoipa::ToSchema))]#[serde(rename_all = "camelCase")]pub struct InitiativeActivityCursor {@@ -30,6 +31,7 @@ pub struct InitiativeActivityCursor {/// One authorized activity row; task names are hydrated through existing authorized task reads.#[derive(Debug, Clone, PartialEq, Serialize)]+#[cfg_attr(feature = "toolset", derive(schemars::JsonSchema))]#[cfg_attr(feature = "inbound", derive(utoipa::ToSchema))]#[serde(rename_all = "camelCase")]pub struct InitiativeActivityRecord {diff --git a/crates/initiative/src/domain/models.rs b/crates/initiative/src/domain/models.rsindex 4eb1e5d85d..f1a95e2a65 100644--- a/crates/initiative/src/domain/models.rs+++ b/crates/initiative/src/domain/models.rs@@ -403,6 +403,9 @@ pub enum InitiativeError {/// The initiative does not exist.#[error("initiative not found")]NotFound,+ /// The document exists but does not have the task subtype.+ #[error("document is not a task")]+ NotATask,/// The caller cannot perform this action.#[error("unauthorized")]Unauthorized,diff --git a/crates/initiative/src/domain/service.rs b/crates/initiative/src/domain/service.rsindex 34c0287c6e..7560ef0198 100644--- a/crates/initiative/src/domain/service.rs+++ b/crates/initiative/src/domain/service.rs@@ -13,6 +13,9 @@ use std::str::FromStr;use std::sync::Arc;mod reads;+mod tasks;++pub use tasks::{ClearTaskOutcome, ClearTaskStatus, clear_task_batch};use entity_access::domain::models::{AccessLevel, EditAccessLevel, EntityAccessAuth, EntityAccessReceipt, EntityPermission,diff --git a/crates/initiative/src/domain/service/tasks.rs b/crates/initiative/src/domain/service/tasks.rsnew file mode 100644index 0000000000..e24a01ca67--- /dev/null+++ b/crates/initiative/src/domain/service/tasks.rs@@ -0,0 +1,62 @@+//! Independent outcomes for a bounded batch of task-side project clears.++use crate::domain::{+ models::{InitiativeError, MAX_TASKS_PER_ASSIGN, TaskAssignment},+ ports::InitiativeService,+};++/// Result of clearing one task's project association.+#[derive(Debug, Clone, Copy, PartialEq, Eq)]+pub enum ClearTaskStatus {+ /// The task is now unassigned, including an already-unassigned task.+ Cleared,+ /// The authorized document is not a task.+ NotATask,+ /// The task no longer exists.+ NotFound,+ /// The actor may not edit this task.+ SkippedNoPermission,+ /// This task failed; other tasks retain their independent outcomes.+ Failed,+}++/// A requested task and its independent clear outcome.+#[derive(Debug, PartialEq, Eq)]+pub struct ClearTaskOutcome {+ /// Requested task ID.+ pub task_id: String,+ /// Committed result or safe failure classification.+ pub status: ClearTaskStatus,+}++/// Clear authorized task associations without discarding earlier results on a later failure.+pub async fn clear_task_batch<S: InitiativeService>(+ service: &S,+ assignments: Vec<TaskAssignment>,+) -> Result<Vec<ClearTaskOutcome>, InitiativeError> {+ if assignments.len() > MAX_TASKS_PER_ASSIGN {+ return Err(InitiativeError::BadRequest(format!(+ "cannot clear more than {MAX_TASKS_PER_ASSIGN} tasks at once"+ )));+ }+ let mut results = Vec::with_capacity(assignments.len());+ for assignment in assignments {+ let task_id = assignment.task_id().to_owned();+ let status = match assignment {+ TaskAssignment::Authorized { receipt } => match service.clear_task(receipt).await {+ Ok(()) => ClearTaskStatus::Cleared,+ Err(InitiativeError::NotATask) => ClearTaskStatus::NotATask,+ Err(InitiativeError::NotFound) => ClearTaskStatus::NotFound,+ Err(InitiativeError::Unauthorized) => ClearTaskStatus::SkippedNoPermission,+ Err(error) => {+ tracing::error!(error=?error, %task_id, "failed to clear task project association");+ ClearTaskStatus::Failed+ }+ },+ TaskAssignment::NotFound { .. } => ClearTaskStatus::NotFound,+ TaskAssignment::SkippedNoPermission { .. } => ClearTaskStatus::SkippedNoPermission,+ };+ results.push(ClearTaskOutcome { task_id, status });+ }+ Ok(results)+}diff --git a/crates/initiative/src/domain/service/test/access.rs b/crates/initiative/src/domain/service/test/access.rsindex 8fb2b3e505..be012b7964 100644--- a/crates/initiative/src/domain/service/test/access.rs+++ b/crates/initiative/src/domain/service/test/access.rs@@ -202,3 +202,48 @@ async fn assignee_sharing_deduplicates_and_keeps_owner_assignable() {.await.expect("granted");}++#[tokio::test]+async fn batch_clear_preserves_successes_and_continues_after_independent_failures() {+ use crate::domain::service::{ClearTaskStatus, clear_task_batch};+ let mut repo = MockInitiativeRepo::new();+ repo.expect_clear_task().times(4).returning(|id| {+ let result = match id {+ "first" | "last" => Ok(None),+ "not-task" => Err(InitiativeError::NotATask),+ "broken" => Err(InitiativeError::Internal(rootcause::report!(+ "storage unavailable"+ ))),+ _ => panic!("unauthorized or missing IDs must not reach persistence"),+ };+ Box::pin(async move { result })+ });+ let assignments = vec![+ assignment("first"),+ assignment("broken"),+ assignment("not-task"),+ TaskAssignment::NotFound {+ task_id: "missing".into(),+ },+ TaskAssignment::SkippedNoPermission {+ task_id: "denied".into(),+ },+ assignment("last"),+ ];+ let result = clear_task_batch(&service(repo), assignments).await.unwrap();+ let actual: Vec<_> = result+ .into_iter()+ .map(|row| (row.task_id, row.status))+ .collect();+ assert_eq!(+ actual,+ vec![+ ("first".into(), ClearTaskStatus::Cleared),+ ("broken".into(), ClearTaskStatus::Failed),+ ("not-task".into(), ClearTaskStatus::NotATask),+ ("missing".into(), ClearTaskStatus::NotFound),+ ("denied".into(), ClearTaskStatus::SkippedNoPermission),+ ("last".into(), ClearTaskStatus::Cleared),+ ]+ );+}diff --git a/crates/initiative/src/domain/service/test/events.rs b/crates/initiative/src/domain/service/test/events.rsindex ede989c8f8..dd7227df3f 100644--- a/crates/initiative/src/domain/service/test/events.rs+++ b/crates/initiative/src/domain/service/test/events.rs@@ -13,6 +13,67 @@ use std::{#[derive(Default)]pub(super) struct Events(pub(super) Mutex<Vec<InitiativeTopicEvent>>);+#[cfg(feature = "toolset")]+#[tokio::test]+async fn attributed_creation_preserves_the_bot_and_delegating_owner() {+ let mut repo = MockInitiativeRepo::new();+ repo.expect_get_team_default_link_share()+ .return_once(|_| Box::pin(async { Ok(None) }));+ repo.expect_create()+ .return_once(|_, _, _| Box::pin(async { Ok(detail(Vec::new())) }));+ let mut documents = MockInitiativeDescriptionDocuments::new();+ documents+ .expect_create()+ .return_once(|_| Box::pin(async { Ok(description_document_id()) }));+ let events = Arc::new(Events::default());+ let attribution = activity::Attribution::delegated(+ activity::Actor::new_from_bot(bot_id::MACRO_AI_BOT_ID),+ user(OWNER),+ );+ service_with_documents(repo, documents)+ .with_event_publisher(events.clone())+ .create_attributed(+ &user(OWNER),+ CreateInitiativeRequest {+ name: "Launch".into(),+ ..Default::default()+ },+ attribution.clone(),+ )+ .await+ .unwrap();+ let recorded = events.0.lock().unwrap();+ let [InitiativeTopicEvent::Created(change)] = recorded.as_slice() else {+ panic!("one attributed creation")+ };+ assert_eq!(change.attribution, Some(attribution.into()));+}++#[cfg(feature = "toolset")]+#[tokio::test]+async fn attributed_creation_rejects_mismatched_owner_before_creating_anything() {+ for attribution in [+ activity::Attribution::direct(activity::Actor::new_from_user(user(OTHER))),+ activity::Attribution::delegated(+ activity::Actor::new_from_bot(bot_id::MACRO_AI_BOT_ID),+ user(OTHER),+ ),+ activity::Attribution::delegated(activity::Actor::new_from_user(user(OWNER)), user(OWNER)),+ ] {+ let result = service(MockInitiativeRepo::new())+ .create_attributed(+ &user(OWNER),+ CreateInitiativeRequest {+ name: "Launch".into(),+ ..Default::default()+ },+ attribution,+ )+ .await;+ assert!(matches!(result, Err(InitiativeError::Unauthorized)));+ }+}+impl InitiativeEventPublisher for Events {fn publish(&self,diff --git a/crates/initiative/src/inbound.rs b/crates/initiative/src/inbound.rsindex 8f92e78fa1..eba956f3b9 100644--- a/crates/initiative/src/inbound.rs+++ b/crates/initiative/src/inbound.rs@@ -1,3 +1,6 @@//! Inbound (driving) adapters for initiatives.pub mod axum_router;++#[cfg(feature = "toolset")]+pub mod toolset;diff --git a/crates/initiative/src/inbound/axum_router.rs b/crates/initiative/src/inbound/axum_router.rsindex 80a3863b6e..7ff527cadf 100644--- a/crates/initiative/src/inbound/axum_router.rs+++ b/crates/initiative/src/inbound/axum_router.rs@@ -212,7 +212,7 @@ impl IntoResponse for InitiativeError {let status_code = match &self {InitiativeError::NotFound => StatusCode::NOT_FOUND,InitiativeError::Unauthorized => StatusCode::UNAUTHORIZED,- InitiativeError::BadRequest(_) => StatusCode::BAD_REQUEST,+ InitiativeError::BadRequest(_) | InitiativeError::NotATask => StatusCode::BAD_REQUEST,InitiativeError::Conflict(_) => StatusCode::CONFLICT,InitiativeError::NameTooLong { .. } => StatusCode::UNPROCESSABLE_ENTITY,InitiativeError::Internal(_) => StatusCode::INTERNAL_SERVER_ERROR,diff --git a/crates/initiative/src/inbound/toolset.rs b/crates/initiative/src/inbound/toolset.rsnew file mode 100644index 0000000000..7696a72fb7--- /dev/null+++ b/crates/initiative/src/inbound/toolset.rs@@ -0,0 +1,122 @@+//! Workflow tools for projects (the initiative domain), separate from folder tools.++mod lifecycle;+mod reads;+mod sharing;+mod tasks;+mod types;++#[cfg(test)]+mod test;++pub use lifecycle::{CreateInitiative, DeleteInitiative, UpdateInitiative};+pub use reads::{ListInitiatives, ReadInitiative, ReadInitiativeActivity, ReadTaskInitiatives};+pub use sharing::UpdateInitiativeSharing;+pub use tasks::SetTaskInitiative;+pub use types::*;++use std::sync::Arc;++use crate::domain::{+ history::InitiativeHistory, models::InitiativeError, ports::InitiativeService,+ resources::InitiativeResources,+};+use activity::domain::ports::EntityActivityReads;+use ai_toolset::{AsyncToolCollection, RequestContext, ToolCallError, ToolResult};+use bot_id::BotId;+use entity_access::domain::{+ models::{BotAccessScope, EntityAccessReceipt, EntityType, RequiredPermission},+ ports::EntityAccessService,+};++/// Domain services shared by every project tool.+pub struct InitiativeToolContext<S, A, R> {+ /// Project lifecycle and read application service.+ pub service: Arc<S>,+ /// Capability issuer; task capabilities retain the same bot and user scope.+ pub access: Arc<A>,+ /// Authorized project activity history.+ pub history: Arc<InitiativeHistory<R, A>>,+ /// Canonical properties, under the same verified project capability.+ pub resources: Arc<dyn InitiativeResources>,+ /// Bot responsible for tool mutations.+ pub actor: BotId,+}++impl<S, A, R> Clone for InitiativeToolContext<S, A, R> {+ fn clone(&self) -> Self {+ Self {+ service: self.service.clone(),+ access: self.access.clone(),+ history: self.history.clone(),+ resources: self.resources.clone(),+ actor: self.actor,+ }+ }+}++impl<S, A, R> InitiativeToolContext<S, A, R> {+ /// Select the agent performing delegated changes.+ pub fn with_actor(mut self, actor: BotId) -> Self {+ self.actor = actor;+ self+ }+}++impl<S, A: EntityAccessService, R> InitiativeToolContext<S, A, R> {+ async fn receipt<T: RequiredPermission>(+ &self,+ request: &RequestContext,+ id: &str,+ entity_type: EntityType,+ ) -> ToolResult<EntityAccessReceipt<T>> {+ self.access+ .generate_bot_entity_access_receipt::<T>(+ self.actor,+ BotAccessScope::user(request.user_id.clone()),+ id,+ entity_type,+ )+ .await+ .map_err(|error| ToolCallError {+ description: "The item is unavailable or you do not have the required permission"+ .into(),+ internal_error: error.into(),+ })+ }+}++fn failure(error: InitiativeError) -> ToolCallError {+ ToolCallError {+ description: match &error {+ InitiativeError::BadRequest(message) | InitiativeError::Conflict(message) => {+ message.clone()+ }+ InitiativeError::Unauthorized => {+ "You do not have permission to perform this project operation".into()+ }+ InitiativeError::NotFound => "The project is unavailable".into(),+ InitiativeError::NameTooLong { max } => {+ format!("Project names must be at most {max} graphemes long")+ }+ InitiativeError::NotATask => "The document is not a task".into(),+ _ => "The project operation failed".into(),+ },+ internal_error: error.into(),+ }+}++/// Complete project lifecycle, sharing, membership and history toolset.+pub fn initiative_toolset<S: InitiativeService, A: EntityAccessService, R: EntityActivityReads>()+-> AsyncToolCollection<InitiativeToolContext<S, A, R>> {+ AsyncToolCollection::new()+ .add_tool::<ListInitiatives, InitiativeToolContext<S, A, R>>()+ .add_tool::<ReadInitiative, InitiativeToolContext<S, A, R>>()+ .add_tool::<CreateInitiative, InitiativeToolContext<S, A, R>>()+ .add_tool::<UpdateInitiative, InitiativeToolContext<S, A, R>>()+ .add_tool::<DeleteInitiative, InitiativeToolContext<S, A, R>>()+ .add_tool::<UpdateInitiativeSharing, InitiativeToolContext<S, A, R>>()+ .add_tool::<SetTaskInitiative, InitiativeToolContext<S, A, R>>()+ .add_tool::<ReadTaskInitiatives, InitiativeToolContext<S, A, R>>()+ .add_tool::<ReadInitiativeActivity, InitiativeToolContext<S, A, R>>()+}diff --git a/crates/initiative/src/inbound/toolset/lifecycle.rs b/crates/initiative/src/inbound/toolset/lifecycle.rsnew file mode 100644index 0000000000..3f475f4ed7--- /dev/null+++ b/crates/initiative/src/inbound/toolset/lifecycle.rs@@ -0,0 +1,167 @@+//! Project lifecycle tools.++use super::*;+use crate::domain::models::{CreateInitiativeRequest, UpdateInitiativeRequest};+use ai_toolset::{AsyncTool, ServiceContext, ToolAnnotated, ToolAnnotations};+use async_trait::async_trait;+use entity_access::domain::models::{EditAccessLevel, OwnerAccessLevel};+use schemars::JsonSchema;+use serde::Deserialize;+use uuid::Uuid;++/// Create a project with the same defaults as the application.+#[derive(Debug, Clone, Deserialize, JsonSchema)]+#[serde(rename_all = "camelCase")]+#[schemars(+ title = "CreateInitiative",+ description = "Create a project for coordinating tasks (called an initiative in the API). Projects have status, priority, assignees, due dates, discussions and activity. Shares with the owner's team by default. This is different from CreateProject, which creates a folder. Use property tools with entity_type='initiative' to set project properties."+)]+pub struct CreateInitiative {+ /// Project name, up to 100 graphemes.+ #[schemars(description = "Project name, up to 100 graphemes.")]+ pub name: String,+ /// Initial Markdown description, up to 2000 graphemes; optional.+ #[schemars(description = "Initial Markdown description, up to 2000 graphemes; optional.")]+ pub description: Option<String>,+ /// Users to grant collaboration access; distinct from property assignees.+ #[schemars(+ description = "Users to grant collaboration access; distinct from property assignees."+ )]+ pub member_ids: Option<Vec<String>>,+ /// Defaults to true. False creates without an explicit team grant.+ #[schemars(description = "Defaults to true. False creates without an explicit team grant.")]+ pub share_with_team: Option<bool>,+}++impl ToolAnnotated for CreateInitiative {+ const ANNOTATIONS: ToolAnnotations = ToolAnnotations::additive("Create project");+}++#[async_trait]+impl<S: InitiativeService, A: EntityAccessService, R: EntityActivityReads>+ AsyncTool<InitiativeToolContext<S, A, R>> for CreateInitiative+{+ type Output = ProjectDetails;+ async fn call(+ &self,+ context: ServiceContext<InitiativeToolContext<S, A, R>>,+ request: RequestContext,+ ) -> ToolResult<Self::Output> {+ context+ .service+ .create_attributed(+ &request.user_id,+ CreateInitiativeRequest {+ name: self.name.clone(),+ description: self.description.clone(),+ member_ids: self.member_ids.clone(),+ share_with_team: self.share_with_team,+ },+ activity::Attribution::delegated(+ activity::Actor::new_from_bot(context.actor),+ request.user_id.clone(),+ ),+ )+ .await+ .map(Into::into)+ .map_err(failure)+ }+}++/// Rename a project or change its collaboration members.+#[derive(Debug, Clone, Deserialize, JsonSchema)]+#[serde(rename_all = "camelCase")]+#[schemars(+ title = "UpdateInitiative",+ description = "Rename a project with edit access, or replace its collaboration member list as the owner. Members control sharing independently of the assignee property. Assigning a user grants collaboration access; removing an assignment retains that access. For status, priority, assignees and due date use SetEntityProperty with entity_type='initiative'. ReadInitiative returns the description document id for document editing tools."+)]+pub struct UpdateInitiative {+ /// Project identifier.+ #[schemars(description = "Project identifier.")]+ pub initiative_id: Uuid,+ /// Replacement name; omitted leaves it unchanged.+ #[schemars(description = "Replacement name; omitted leaves it unchanged.")]+ pub name: Option<String>,+ /// Owner-only complete replacement member list; omitted preserves existing members, [] clears it.+ #[schemars(+ description = "Owner-only complete replacement member list; omitted preserves existing members, [] clears it."+ )]+ pub member_ids: Option<Vec<String>>,+}++impl ToolAnnotated for UpdateInitiative {+ const ANNOTATIONS: ToolAnnotations =+ ToolAnnotations::destructive("Update project").with_idempotent();+}++#[async_trait]+impl<S: InitiativeService, A: EntityAccessService, R: EntityActivityReads>+ AsyncTool<InitiativeToolContext<S, A, R>> for UpdateInitiative+{+ type Output = ProjectDetails;+ async fn call(+ &self,+ context: ServiceContext<InitiativeToolContext<S, A, R>>,+ request: RequestContext,+ ) -> ToolResult<Self::Output> {+ let receipt = context+ .receipt::<EditAccessLevel>(+ &request,+ &self.initiative_id.to_string(),+ EntityType::Initiative,+ )+ .await?;+ context+ .service+ .update(+ receipt,+ UpdateInitiativeRequest {+ name: self.name.clone(),+ member_ids: self.member_ids.clone(),+ share_permission: None,+ },+ )+ .await+ .map(Into::into)+ .map_err(failure)+ }+}++/// Delete a project and its description while retaining its tasks.+#[derive(Debug, Clone, Deserialize, JsonSchema)]+#[serde(rename_all = "camelCase")]+#[schemars(+ title = "DeleteInitiative",+ description = "Permanently delete a project, its description and properties. Associated tasks remain and lose their project association. Requires ownership. This operation cannot be undone."+)]+pub struct DeleteInitiative {+ /// Project to permanently delete.+ #[schemars(description = "Project to permanently delete.")]+ pub initiative_id: Uuid,+}++impl ToolAnnotated for DeleteInitiative {+ const ANNOTATIONS: ToolAnnotations = ToolAnnotations::destructive("Delete project");+}++#[async_trait]+impl<S: InitiativeService, A: EntityAccessService, R: EntityActivityReads>+ AsyncTool<InitiativeToolContext<S, A, R>> for DeleteInitiative+{+ type Output = ProjectOperationComplete;+ async fn call(+ &self,+ context: ServiceContext<InitiativeToolContext<S, A, R>>,+ request: RequestContext,+ ) -> ToolResult<Self::Output> {+ let receipt = context+ .receipt::<OwnerAccessLevel>(+ &request,+ &self.initiative_id.to_string(),+ EntityType::Initiative,+ )+ .await?;+ context.service.delete(receipt).await.map_err(failure)?;+ Ok(ProjectOperationComplete { success: true })+ }+}diff --git a/crates/initiative/src/inbound/toolset/reads.rs b/crates/initiative/src/inbound/toolset/reads.rsnew file mode 100644index 0000000000..e43ee4ed9d--- /dev/null+++ b/crates/initiative/src/inbound/toolset/reads.rs@@ -0,0 +1,407 @@+//! Semantic project reads with bounded results and explicit truncation.++use super::*;+use crate::domain::{+ history::{InitiativeActivityCursor, InitiativeActivityRecord},+ reads::{+ InitiativePageRequest, InitiativeTasksRequest, TaskInitiativeReference,+ TaskInitiativeReferencesRequest,+ },+};+use ai_toolset::{AsyncTool, ServiceContext, ToolAnnotated, ToolAnnotations};+use async_trait::async_trait;+use chrono::{DateTime, Utc};+use entity_access::domain::models::ViewAccessLevel;+use schemars::JsonSchema;+use serde::{Deserialize, Serialize};+use uuid::Uuid;++/// Search projects using canonical property filters.+#[derive(Debug, Clone, Deserialize, JsonSchema)]+#[serde(rename_all = "camelCase")]+#[schemars(+ title = "ListInitiatives",+ description = "Find projects (initiatives), with canonical properties and progress over tasks you can view. Returns at most 100 recently updated matches per page. Pass nextCursor back as cursor with the same filters to read more. Filter by name, status, priority, assignee, or due date. Project folders use ReadProject instead."+)]+pub struct ListInitiatives {+ /// Case-insensitive project name substring.+ #[schemars(description = "Case-insensitive project name substring.")]+ pub query: Option<String>,+ /// Status option id, obtained from property definitions.+ #[schemars(description = "Status option id, obtained from property definitions.")]+ pub status: Option<Uuid>,+ /// Priority option id, obtained from property definitions.+ #[schemars(description = "Priority option id, obtained from property definitions.")]+ pub priority: Option<Uuid>,+ /// Assigned user id.+ #[schemars(description = "Assigned user id.")]+ pub assignee: Option<String>,+ /// Earliest inclusive due timestamp.+ #[schemars(description = "Earliest inclusive due timestamp.")]+ pub due_after: Option<DateTime<Utc>>,+ /// Latest inclusive due timestamp.+ #[schemars(description = "Latest inclusive due timestamp.")]+ pub due_before: Option<DateTime<Utc>>,+ /// Opaque nextCursor from the preceding page, with the same filters.+ #[schemars(description = "Opaque nextCursor from the preceding page, with the same filters.")]+ pub cursor: Option<String>,+ /// Maximum projects to return, from 1 through 100; defaults to 100.+ #[schemars(description = "Maximum projects to return, from 1 through 100; defaults to 100.")]+ pub limit: Option<u16>,+}++/// One visible project with canonical fields and permission-aware progress.+#[derive(Debug, Serialize, JsonSchema)]+#[serde(rename_all = "camelCase")]+pub struct ProjectListRow {+ /// Project id.+ pub initiative_id: Uuid,+ /// Project name.+ pub name: String,+ /// Description document id.+ pub description_document_id: Uuid,+ /// Effective caller access.+ pub access: String,+ /// Canonical system properties.+ pub properties: ProjectPropertyValues,+ /// Count of associated tasks visible to the caller.+ pub task_count: u32,+ /// Visible completed tasks.+ pub completed_task_count: u32,+}++/// Bounded project search results.+#[derive(Debug, Serialize, JsonSchema)]+#[serde(rename_all = "camelCase")]+pub struct ProjectListResult {+ /// Matching visible projects.+ pub projects: Vec<ProjectListRow>,+ /// True when additional matches exist.+ pub truncated: bool,+ /// Opaque cursor for the next page, absent after the final page.+ pub next_cursor: Option<String>,+}++impl ToolAnnotated for ListInitiatives {+ const ANNOTATIONS: ToolAnnotations = ToolAnnotations::read_only("Find projects");+}++#[async_trait]+impl<S: InitiativeService, A: EntityAccessService, R: EntityActivityReads>+ AsyncTool<InitiativeToolContext<S, A, R>> for ListInitiatives+{+ type Output = ProjectListResult;+ async fn call(+ &self,+ context: ServiceContext<InitiativeToolContext<S, A, R>>,+ request: RequestContext,+ ) -> ToolResult<Self::Output> {+ let page = context+ .service+ .page(+ &request.user_id,+ InitiativePageRequest {+ limit: self.limit.or(Some(100)),+ cursor: self.cursor.clone(),+ query: self.query.clone(),+ status: self.status,+ priority: self.priority,+ assignee: self.assignee.clone(),+ due_after: self.due_after,+ due_before: self.due_before,+ ..Default::default()+ },+ )+ .await+ .map_err(failure)?;+ Ok(ProjectListResult {+ truncated: page.next_cursor.is_some(),+ next_cursor: page.next_cursor,+ projects: page+ .initiatives+ .into_iter()+ .map(|row| ProjectListRow {+ initiative_id: row.initiative.id.as_uuid(),+ name: row.initiative.name,+ description_document_id: row.initiative.description_document_id.as_uuid(),+ access: row.user_access_level.to_string(),+ properties: row.properties.into(),+ task_count: row.task_count,+ completed_task_count: row.completed_task_count,+ })+ .collect(),+ })+ }+}++/// Read a project's metadata and visible task membership.+#[derive(Debug, Clone, Deserialize, JsonSchema)]+#[serde(rename_all = "camelCase")]+#[schemars(+ title = "ReadInitiative",+ description = "Read a project, its sharing, canonical status/priority/assignees/due date, and a bounded page of associated task ids that you can view, with their total count. Pass nextTaskCursor back as taskCursor to read more task ids. Requires view access. The descriptionDocumentId can be read or edited with document tools. Use entity_type='initiative' with property tools. ReadInitiativeActivity returns the project's activity history."+)]+pub struct ReadInitiative {+ /// Project identifier.+ #[schemars(description = "Project identifier.")]+ pub initiative_id: Uuid,+ /// Opaque nextTaskCursor from the preceding page for this project.+ #[schemars(description = "Opaque nextTaskCursor from the preceding page for this project.")]+ pub task_cursor: Option<String>,+ /// Maximum task ids to return, from 1 through 100; defaults to 100.+ #[schemars(description = "Maximum task ids to return, from 1 through 100; defaults to 100.")]+ pub task_limit: Option<u16>,+}++/// Project detail and canonical property values.+#[derive(Debug, Serialize, JsonSchema)]+#[serde(rename_all = "camelCase")]+pub struct ProjectReadResult {+ /// Project metadata and authorized task identifiers.+ #[schemars(description = "Project metadata and authorized task identifiers.")]+ pub project: ProjectDetails,+ /// Canonical system properties.+ #[schemars(description = "Canonical system properties.")]+ pub properties: ProjectPropertyValues,+ /// Opaque cursor for the next task page, absent after the final page.+ pub next_task_cursor: Option<String>,+}++impl ToolAnnotated for ReadInitiative {+ const ANNOTATIONS: ToolAnnotations = ToolAnnotations::read_only("Read project");+}++#[async_trait]+impl<S: InitiativeService, A: EntityAccessService, R: EntityActivityReads>+ AsyncTool<InitiativeToolContext<S, A, R>> for ReadInitiative+{+ type Output = ProjectReadResult;+ async fn call(+ &self,+ context: ServiceContext<InitiativeToolContext<S, A, R>>,+ request: RequestContext,+ ) -> ToolResult<Self::Output> {+ let id = self.initiative_id.to_string();+ let receipt = context+ .receipt::<ViewAccessLevel>(&request, &id, EntityType::Initiative)+ .await?;+ let properties = context+ .resources+ .properties(vec![receipt.clone()])+ .await+ .map_err(failure)?+ .remove(&id)+ .unwrap_or_default();+ let detail = context.service.get(receipt).await.map_err(failure)?;+ let tasks = detail+ .task_page(InitiativeTasksRequest {+ limit: self.task_limit.or(Some(100)),+ cursor: self.task_cursor.clone(),+ })+ .map_err(failure)?;+ let mut project: ProjectDetails = detail.into();+ project.task_ids = tasks.task_ids;+ project.task_count = tasks.total as usize;+ project.tasks_truncated = tasks.next_cursor.is_some();+ Ok(ProjectReadResult {+ project,+ properties: properties.into(),+ next_task_cursor: tasks.next_cursor,+ })+ }+}++/// Resolve projects for a batch of tasks without exposing inaccessible projects.+#[derive(Debug, Clone, Deserialize, JsonSchema)]+#[serde(rename_all = "camelCase")]+#[schemars(+ title = "ReadTaskInitiatives",+ description = "Find the project associated with each requested task. Returns project id/name only when both task and project are visible. Distinguishes no project from unavailable. Accepts up to 100 unique task ids."+)]+pub struct ReadTaskInitiatives {+ /// Task ids to look up, deduplicated in input order.+ #[schemars(description = "Task ids to look up, deduplicated in input order.")]+ pub task_ids: Vec<String>,+}++/// Privacy-preserving task project reference.+#[derive(Debug, Serialize, JsonSchema)]+#[serde(+ tag = "state",+ rename_all = "camelCase",+ rename_all_fields = "camelCase"+)]+pub enum TaskProjectReference {+ /// Visible task with no project association.+ None {+ /// Requested task id.+ task_id: String,+ },+ /// Task or project is inaccessible.+ Unavailable {+ /// Requested task id.+ task_id: String,+ },+ /// Task and project are visible.+ Visible {+ /// Requested task id.+ task_id: String,+ /// Associated project id.+ initiative_id: Uuid,+ /// Associated project name.+ name: String,+ },+}++/// Visibility-aware project references for the requested tasks.+#[derive(Debug, Serialize, JsonSchema)]+pub struct TaskProjectReferences {+ /// References in deduplicated request order.+ pub references: Vec<TaskProjectReference>,+}++impl ToolAnnotated for ReadTaskInitiatives {+ const ANNOTATIONS: ToolAnnotations = ToolAnnotations::read_only("Read task projects");+}++#[async_trait]+impl<S: InitiativeService, A: EntityAccessService, R: EntityActivityReads>+ AsyncTool<InitiativeToolContext<S, A, R>> for ReadTaskInitiatives+{+ type Output = TaskProjectReferences;+ async fn call(+ &self,+ context: ServiceContext<InitiativeToolContext<S, A, R>>,+ request: RequestContext,+ ) -> ToolResult<Self::Output> {+ let result = context+ .service+ .task_references(+ &request.user_id,+ TaskInitiativeReferencesRequest {+ task_ids: self.task_ids.clone(),+ },+ )+ .await+ .map_err(failure)?;+ Ok(TaskProjectReferences {+ references: result+ .references+ .into_iter()+ .map(|reference| match reference {+ TaskInitiativeReference::None { task_id } => {+ TaskProjectReference::None { task_id }+ }+ TaskInitiativeReference::Unavailable { task_id } => {+ TaskProjectReference::Unavailable { task_id }+ }+ TaskInitiativeReference::Visible {+ task_id,+ initiative,+ } => TaskProjectReference::Visible {+ task_id,+ initiative_id: initiative.id.as_uuid(),+ name: initiative.name,+ },+ })+ .collect(),+ })+ }+}++/// Read project history with current task permissions applied.+#[derive(Debug, Clone, Deserialize, JsonSchema)]+#[serde(rename_all = "camelCase")]+#[schemars(+ title = "ReadInitiativeActivity",+ description = "Read project creation, edits, property changes, and task membership changes, newest first. Task references require current task view access. Each page scans at most 100 events and may contain fewer visible records. Pass nextCursor back as cursor with the same time filters to continue, including after an empty page."+)]+pub struct ReadInitiativeActivity {+ /// Project identifier.+ #[schemars(description = "Project identifier.")]+ pub initiative_id: Uuid,+ /// Only changes at or after this timestamp.+ #[schemars(description = "Only changes at or after this timestamp.")]+ pub after: Option<DateTime<Utc>>,+ /// Only changes before this timestamp.+ #[schemars(description = "Only changes before this timestamp.")]+ pub before: Option<DateTime<Utc>>,+ /// Opaque nextCursor from the preceding activity page.+ #[schemars(description = "Opaque nextCursor from the preceding activity page.")]+ pub cursor: Option<InitiativeActivityCursor>,+ /// Maximum events to scan, from 1 through 100; defaults to 100.+ #[schemars(description = "Maximum events to scan, from 1 through 100; defaults to 100.")]+ pub limit: Option<u16>,+}++/// Bounded visible project activity.+#[derive(Debug, Serialize, JsonSchema)]+#[serde(rename_all = "camelCase")]+pub struct ProjectActivityResult {+ /// Visible events ordered newest first.+ pub records: Vec<InitiativeActivityRecord>,+ /// More events may match; follow nextCursor.+ pub truncated: bool,+ /// Stable continuation, absent after the final matching page.+ pub next_cursor: Option<InitiativeActivityCursor>,+}++impl ToolAnnotated for ReadInitiativeActivity {+ const ANNOTATIONS: ToolAnnotations = ToolAnnotations::read_only("Read project activity");+}++#[async_trait]+impl<S: InitiativeService, A: EntityAccessService, R: EntityActivityReads>+ AsyncTool<InitiativeToolContext<S, A, R>> for ReadInitiativeActivity+{+ type Output = ProjectActivityResult;+ async fn call(+ &self,+ context: ServiceContext<InitiativeToolContext<S, A, R>>,+ request: RequestContext,+ ) -> ToolResult<Self::Output> {+ let receipt = context+ .receipt::<ViewAccessLevel>(+ &request,+ &self.initiative_id.to_string(),+ EntityType::Initiative,+ )+ .await?;+ if self+ .after+ .zip(self.before)+ .is_some_and(|(after, before)| after >= before)+ {+ return Err(failure(InitiativeError::BadRequest(+ "after must precede before".into(),+ )));+ }+ let cursor = self.cursor.clone().or_else(|| {+ self.before.map(|occurred_at| InitiativeActivityCursor {+ occurred_at,+ id: Uuid::nil(),+ })+ });+ let page = context+ .history+ .read(receipt, cursor, u32::from(self.limit.unwrap_or(100)))+ .await+ .map_err(failure)?;+ let next_cursor = page+ .next_cursor+ .filter(|cursor| self.after.is_none_or(|after| cursor.occurred_at >= after));+ let records = page+ .records+ .into_iter()+ .filter(|record| {+ self.after.is_none_or(|after| record.occurred_at >= after)+ && self.before.is_none_or(|before| record.occurred_at < before)+ })+ .collect();+ Ok(ProjectActivityResult {+ records,+ truncated: next_cursor.is_some(),+ next_cursor,+ })+ }+}diff --git a/crates/initiative/src/inbound/toolset/sharing.rs b/crates/initiative/src/inbound/toolset/sharing.rsnew file mode 100644index 0000000000..88ad8aa4f3--- /dev/null+++ b/crates/initiative/src/inbound/toolset/sharing.rs@@ -0,0 +1,153 @@+//! Owner-only sharing updates, mirrored by the domain onto the description document.++use super::*;+use crate::domain::models::UpdateInitiativeRequest;+use ai_toolset::{AsyncTool, ServiceContext, ToolAnnotated, ToolAnnotations};+use async_trait::async_trait;+use entity_access::domain::models::EditAccessLevel;+use models_permissions::share_permission::{+ LinkShare, UpdateSharePermissionRequestV2,+ access_level::AccessLevel,+ channel_share_permission::{UpdateChannelSharePermission, UpdateOperation},+};+use schemars::JsonSchema;+use serde::Deserialize;+use uuid::Uuid;++/// A share can be disabled or grant a non-owner permission.+#[derive(Debug, Clone, Copy, Deserialize, JsonSchema)]+#[serde(rename_all = "snake_case")]+pub enum ProjectShareAccess {+ /// Disable this explicit share.+ Off,+ /// View only.+ View,+ /// View and comment.+ Comment,+ /// Edit.+ Edit,+}++impl ProjectShareAccess {+ fn level(self) -> Option<AccessLevel> {+ match self {+ Self::Off => None,+ Self::View => Some(AccessLevel::View),+ Self::Comment => Some(AccessLevel::Comment),+ Self::Edit => Some(AccessLevel::Edit),+ }+ }+}++/// Scope admitted by a project's share link.+#[derive(Debug, Clone, Copy, Deserialize, JsonSchema)]+#[serde(rename_all = "snake_case")]+pub enum ProjectLinkScope {+ /// Disable link sharing.+ Off,+ /// Anyone with the link.+ Public,+ /// Owner-team members with the link.+ Team,+}++/// Update one channel's grant without replacing other channel grants.+#[derive(Debug, Clone, Deserialize, JsonSchema)]+#[serde(rename_all = "camelCase")]+pub struct ProjectChannelSharing {+ /// Channel id to share with or revoke.+ #[schemars(description = "Channel id to share with or revoke.")]+ pub channel_id: Uuid,+ /// Desired grant; off removes only this channel grant.+ #[schemars(description = "Desired grant; off removes only this channel grant.")]+ pub access: ProjectShareAccess,+}++/// Update project sharing, retaining domain-owned authorization.+#[derive(Debug, Clone, Deserialize, JsonSchema)]+#[serde(rename_all = "camelCase")]+#[schemars(+ title = "UpdateInitiativeSharing",+ description = "Change a project's team, link or channel sharing. Only the actual project owner may change sharing. Each omitted field remains unchanged; off disables that share. Project and description document permissions change together. Collaboration member changes use UpdateInitiative."+)]+pub struct UpdateInitiativeSharing {+ /// Project identifier.+ #[schemars(description = "Project identifier.")]+ pub initiative_id: Uuid,+ /// Explicit owner-team grant; off removes it.+ #[schemars(description = "Explicit owner-team grant; off removes it.")]+ pub team_access: Option<ProjectShareAccess>,+ /// Who the project link admits; off disables it.+ #[schemars(description = "Who the project link admits; off disables it.")]+ pub link_scope: Option<ProjectLinkScope>,+ /// Permission granted by an enabled link. Off resets it to the default view level.+ #[schemars(+ description = "Permission granted by an enabled link. Off resets it to the default view level."+ )]+ pub link_access: Option<ProjectShareAccess>,+ /// Individual channel shares to set or remove; other shares remain unchanged.+ #[schemars(+ description = "Individual channel shares to set or remove; other shares remain unchanged."+ )]+ pub channels: Option<Vec<ProjectChannelSharing>>,+}++impl ToolAnnotated for UpdateInitiativeSharing {+ const ANNOTATIONS: ToolAnnotations =+ ToolAnnotations::destructive("Change project sharing").with_idempotent();+}++#[async_trait]+impl<S: InitiativeService, A: EntityAccessService, R: EntityActivityReads>+ AsyncTool<InitiativeToolContext<S, A, R>> for UpdateInitiativeSharing+{+ type Output = ProjectDetails;+ async fn call(+ &self,+ context: ServiceContext<InitiativeToolContext<S, A, R>>,+ request: RequestContext,+ ) -> ToolResult<Self::Output> {+ let receipt = context+ .receipt::<EditAccessLevel>(+ &request,+ &self.initiative_id.to_string(),+ EntityType::Initiative,+ )+ .await?;+ context+ .service+ .update(+ receipt,+ UpdateInitiativeRequest {+ share_permission: Some(UpdateSharePermissionRequestV2 {+ team_share_access_level: self.team_access.map(ProjectShareAccess::level),+ link_share: self.link_scope.map(|scope| match scope {+ ProjectLinkScope::Off => None,+ ProjectLinkScope::Public => Some(LinkShare::Public),+ ProjectLinkScope::Team => Some(LinkShare::Team),+ }),+ link_share_access_level: self.link_access.map(ProjectShareAccess::level),+ channel_share_permissions: self.channels.as_ref().map(|channels| {+ channels+ .iter()+ .map(|channel| UpdateChannelSharePermission {+ operation: if matches!(channel.access, ProjectShareAccess::Off)+ {+ UpdateOperation::Remove+ } else {+ UpdateOperation::Replace+ },+ channel_id: channel.channel_id.to_string(),+ access_level: channel.access.level(),+ })+ .collect()+ }),+ }),+ ..Default::default()+ },+ )+ .await+ .map(Into::into)+ .map_err(failure)+ }+}diff --git a/crates/initiative/src/inbound/toolset/tasks.rs b/crates/initiative/src/inbound/toolset/tasks.rsnew file mode 100644index 0000000000..d7397b85c6--- /dev/null+++ b/crates/initiative/src/inbound/toolset/tasks.rs@@ -0,0 +1,128 @@+//! Task assignment with shared actor capabilities and bounded partial outcomes.++use super::*;+use crate::domain::{+ models::{AssignTaskStatus, TaskAssignment, TaskAssignmentBatch},+ service::{ClearTaskStatus, clear_task_batch},+};+use ai_toolset::{AsyncTool, ServiceContext, ToolAnnotated, ToolAnnotations};+use async_trait::async_trait;+use entity_access::domain::models::{BotAccessScope, EditAccessLevel};+use schemars::JsonSchema;+use serde::{Deserialize, Serialize};+use uuid::Uuid;++/// Set or clear the project associated with a bounded set of tasks.+#[derive(Debug, Clone, Deserialize, JsonSchema)]+#[serde(rename_all = "camelCase")]+#[schemars(+ title = "SetTaskInitiative",+ description = "Set the project associated with tasks, moving them from their previous project if needed. Requires edit access to each task and the destination project; access to the previous project is unnecessary. Omit initiativeId to clear the association using task edit access alone. Reports each task's outcome independently; at most 100 unique tasks."+)]+pub struct SetTaskInitiative {+ /// Task ids to assign or clear, deduplicated in request order.+ #[schemars(description = "Task ids to assign or clear, deduplicated in request order.")]+ pub task_ids: Vec<String>,+ /// Destination project; omit to clear each task's current project.+ #[schemars(description = "Destination project; omit to clear each task's current project.")]+ pub initiative_id: Option<Uuid>,+}++/// One task mutation outcome.+#[derive(Debug, Serialize, JsonSchema)]+#[serde(rename_all = "camelCase")]+pub struct TaskProjectOutcome {+ /// Requested task identifier.+ pub task_id: String,+ /// assigned, moved, cleared, notATask, notFound, skippedNoPermission, or failed.+ pub status: String,+}++/// Results in deduplicated input order.+#[derive(Debug, Serialize, JsonSchema)]+pub struct TaskProjectOutcomes {+ /// Outcome for every submitted task.+ pub results: Vec<TaskProjectOutcome>,+}++impl ToolAnnotated for SetTaskInitiative {+ const ANNOTATIONS: ToolAnnotations =+ ToolAnnotations::destructive("Set task project").with_idempotent();+}++#[async_trait]+impl<S: InitiativeService, A: EntityAccessService, R: EntityActivityReads>+ AsyncTool<InitiativeToolContext<S, A, R>> for SetTaskInitiative+{+ type Output = TaskProjectOutcomes;+ async fn call(+ &self,+ context: ServiceContext<InitiativeToolContext<S, A, R>>,+ request: RequestContext,+ ) -> ToolResult<Self::Output> {+ let ids = TaskAssignmentBatch::try_new(self.task_ids.clone())+ .map_err(failure)?+ .into_task_ids();+ let destination = if let Some(id) = self.initiative_id {+ Some(+ context+ .receipt::<EditAccessLevel>(&request, &id.to_string(), EntityType::Initiative)+ .await?,+ )+ } else {+ None+ };+ let mut assignments = Vec::with_capacity(ids.len());+ for id in ids {+ let access = context+ .access+ .generate_bot_entity_access_receipt::<EditAccessLevel>(+ context.actor,+ BotAccessScope::user(request.user_id.clone()),+ &id,+ EntityType::Document,+ )+ .await;+ assignments.push(TaskAssignment::from_access(id, access).map_err(failure)?);+ }+ let results = if let Some(destination) = destination {+ context+ .service+ .assign_tasks(destination, assignments)+ .await+ .map_err(failure)?+ .results+ .into_iter()+ .map(|outcome| TaskProjectOutcome {+ task_id: outcome.task_id,+ status: match outcome.status {+ AssignTaskStatus::Assigned => "assigned",+ AssignTaskStatus::Moved => "moved",+ AssignTaskStatus::NotATask => "notATask",+ AssignTaskStatus::NotFound => "notFound",+ AssignTaskStatus::SkippedNoPermission => "skippedNoPermission",+ }+ .into(),+ })+ .collect()+ } else {+ clear_task_batch(context.service.as_ref(), assignments)+ .await+ .map_err(failure)?+ .into_iter()+ .map(|outcome| TaskProjectOutcome {+ task_id: outcome.task_id,+ status: match outcome.status {+ ClearTaskStatus::Cleared => "cleared",+ ClearTaskStatus::NotATask => "notATask",+ ClearTaskStatus::NotFound => "notFound",+ ClearTaskStatus::SkippedNoPermission => "skippedNoPermission",+ ClearTaskStatus::Failed => "failed",+ }+ .into(),+ })+ .collect()+ };+ Ok(TaskProjectOutcomes { results })+ }+}diff --git a/crates/initiative/src/inbound/toolset/test.rs b/crates/initiative/src/inbound/toolset/test.rsnew file mode 100644index 0000000000..da99c768d6--- /dev/null+++ b/crates/initiative/src/inbound/toolset/test.rs@@ -0,0 +1,14 @@+use super::*;++#[test]+fn invalid_name_length_is_actionable_without_exposing_internal_errors() {+ let error = failure(InitiativeError::NameTooLong { max: 100 });+ assert_eq!(+ error.description,+ "Project names must be at most 100 graphemes long"+ );+ let internal = failure(InitiativeError::Internal(rootcause::report!(+ "private database failure"+ )));+ assert_eq!(internal.description, "The project operation failed");+}diff --git a/crates/initiative/src/inbound/toolset/types.rs b/crates/initiative/src/inbound/toolset/types.rsnew file mode 100644index 0000000000..2aa64e1f01--- /dev/null+++ b/crates/initiative/src/inbound/toolset/types.rs@@ -0,0 +1,118 @@+//! Typed results optimized for project workflows.++use crate::domain::{models::InitiativeDetail, reads::InitiativePropertySnapshot};+use chrono::{DateTime, Utc};+use schemars::JsonSchema;+use serde::Serialize;+use uuid::Uuid;++/// Current project state, including visibility-filtered task membership.+#[derive(Debug, Serialize, JsonSchema)]+#[serde(rename_all = "camelCase")]+pub struct ProjectDetails {+ /// Project id; use entity type `initiative` in property tools.+ pub initiative_id: Uuid,+ /// Project name.+ pub name: String,+ /// Description document; read or edit its Markdown using document tools.+ pub description_document_id: Uuid,+ /// Project owner.+ pub owner_id: String,+ /// Collaboration members, distinct from property assignees.+ pub member_ids: Vec<String>,+ /// Up to 200 associated tasks the caller can view.+ pub task_ids: Vec<String>,+ /// Total associated tasks the caller can view.+ pub task_count: usize,+ /// Whether the project contains additional visible tasks beyond taskIds.+ pub tasks_truncated: bool,+ /// Caller's effective permission.+ pub access: String,+ /// Explicit owner-team access, or absent when off.+ pub team_access: Option<String>,+ /// Link scope: PUBLIC or TEAM, or absent when off.+ pub link_scope: Option<String>,+ /// Access granted by the link.+ pub link_access: Option<String>,+ /// Explicit channel shares.+ pub channel_shares: Vec<ProjectChannelShare>,+}++/// One channel's explicit project grant.+#[derive(Debug, Serialize, JsonSchema)]+#[serde(rename_all = "camelCase")]+pub struct ProjectChannelShare {+ /// Shared channel identifier.+ pub channel_id: String,+ /// Granted access level.+ pub access: String,+}++impl From<InitiativeDetail> for ProjectDetails {+ fn from(value: InitiativeDetail) -> Self {+ let share = value.share_permission;+ let task_count = value.task_ids.len();+ Self {+ initiative_id: value.id.as_uuid(),+ name: value.name,+ description_document_id: value.description_document_id.as_uuid(),+ owner_id: value.owner_id.to_string(),+ member_ids: value+ .member_ids+ .into_iter()+ .map(|id| id.to_string())+ .collect(),+ task_ids: value.task_ids.into_iter().take(200).collect(),+ task_count,+ tasks_truncated: task_count > 200,+ access: value.user_access_level.to_string(),+ team_access: share.team_share_access_level.map(|level| level.to_string()),+ link_scope: share.link_share.map(|scope| scope.to_string()),+ link_access: share.link_share_access_level.map(|level| level.to_string()),+ channel_shares: share+ .channel_share_permissions+ .unwrap_or_default()+ .into_iter()+ .map(|share| ProjectChannelShare {+ channel_id: share.channel_id,+ access: share.access_level.to_string(),+ })+ .collect(),+ }+ }+}++/// Canonical system-property values, editable through SetEntityProperty.+#[derive(Debug, Serialize, JsonSchema)]+#[serde(rename_all = "camelCase")]+pub struct ProjectPropertyValues {+ /// Status option id, or unset.+ pub status: Option<Uuid>,+ /// Priority option id, or unset.+ pub priority: Option<Uuid>,+ /// Assigned users, independent from sharing membership.+ pub assignees: Vec<String>,+ /// Due timestamp, or unset.+ pub due_date: Option<DateTime<Utc>>,+ /// Whether the status is completed.+ pub completed: bool,+}++impl From<InitiativePropertySnapshot> for ProjectPropertyValues {+ fn from(value: InitiativePropertySnapshot) -> Self {+ Self {+ status: value.status,+ priority: value.priority,+ assignees: value.assignees,+ due_date: value.due_date,+ completed: value.completed,+ }+ }+}++/// Successful project mutation with no further result body.+#[derive(Debug, Serialize, JsonSchema)]+pub struct ProjectOperationComplete {+ /// True when the operation completed.+ pub success: bool,+}diff --git a/crates/initiative/src/outbound/pg_initiative_repo/tasks.rs b/crates/initiative/src/outbound/pg_initiative_repo/tasks.rsindex 4813578b26..21a3bedb1f 100644--- a/crates/initiative/src/outbound/pg_initiative_repo/tasks.rs+++ b/crates/initiative/src/outbound/pg_initiative_repo/tasks.rs@@ -175,25 +175,38 @@ pub(super) async fn clear_task(pool: &PgPool,task_id: &str,) -> Result<Option<TaskMembershipChange>, InitiativeError> {- let removed = sqlx::query_scalar!(+ let outcome = sqlx::query!(r#"- WITH removed AS (- DELETE FROM task_initiative- WHERE task_id = $1+ WITH task AS (+ SELECT d.id, COALESCE(dst.sub_type = 'task', false) AS is_task+ FROM "Document" d+ LEFT JOIN document_sub_type dst ON dst.document_id = d.id+ WHERE d.id = $1 AND d."deletedAt" IS NULL+ ), removed AS (+ DELETE FROM task_initiative ti+ USING task+ WHERE ti.task_id = task.id AND task.is_taskRETURNING initiative_id+ ), updated AS (+ UPDATE initiative+ SET updated_at = now()+ WHERE id IN (SELECT initiative_id FROM removed)+ RETURNING id)- UPDATE initiative- SET updated_at = now()- WHERE id IN (SELECT initiative_id FROM removed)- RETURNING id+ SELECT task.is_task AS "is_task!", (SELECT id FROM updated) AS initiative_id+ FROM task"#,task_id,).fetch_optional(pool).await.map_err(AdapterError::Sqlx)- .map_err(map_sqlx)?;- Ok(removed.map(|id| TaskMembershipChange {+ .map_err(map_sqlx)?+ .ok_or(InitiativeError::NotFound)?;+ if !outcome.is_task {+ return Err(InitiativeError::NotATask);+ }+ Ok(outcome.initiative_id.map(|id| TaskMembershipChange {task_id: task_id.to_string(),from: Some(InitiativeId::from_uuid(id)),to: None,diff --git a/crates/initiative/src/outbound/pg_initiative_repo/test.rs b/crates/initiative/src/outbound/pg_initiative_repo/test.rsindex 80cf701907..e4032530c9 100644--- a/crates/initiative/src/outbound/pg_initiative_repo/test.rs+++ b/crates/initiative/src/outbound/pg_initiative_repo/test.rs@@ -2,6 +2,8 @@ use entity_access_db_utils::AccessLevel;mod access;mod history;+#[cfg(feature = "toolset")]+mod toolset;use macro_db_migrator::MACRO_DB_MIGRATIONS;use macro_user_id::cowlike::CowLike;use macro_user_id::user_id::MacroUserIdStr;diff --git a/crates/initiative/src/outbound/pg_initiative_repo/test/toolset.rs b/crates/initiative/src/outbound/pg_initiative_repo/test/toolset.rsnew file mode 100644index 0000000000..109e5414d4--- /dev/null+++ b/crates/initiative/src/outbound/pg_initiative_repo/test/toolset.rs@@ -0,0 +1,363 @@+use super::*;+mod reads;+use crate::domain::{+ events::{InitiativeEventPublisher, InitiativeMacroEvent, InitiativeTopicEvent},+ history::InitiativeHistory,+ ports::MockInitiativeDescriptionDocuments,+ reads::InitiativePropertySnapshot,+ resources::{InitiativeResources, ResourceFuture},+ service::InitiativeServiceImpl,+};+use crate::inbound::toolset::{InitiativeToolContext, SetTaskInitiative, UpdateInitiativeSharing};+use activity::outbound::pg_activity_repo::PgActivityRepo;+use ai_toolset::{AsyncTool, RequestContext, ServiceContext};+use entity_access::{+ domain::{+ models::{EditAccessLevel, Entity, EntityAccessAuth, EntityAccessReceipt, ViewAccessLevel},+ ports::EntityAccessService,+ service::EntityAccessServiceImpl,+ },+ outbound::PgAccessRepository,+};+use macro_event_broker::MacroEvent;+use std::{+ collections::HashMap,+ sync::{Arc, Mutex},+};++#[derive(Debug)]+struct UnusedProperties;++impl InitiativeResources for UnusedProperties {+ fn initialize(&self, _: InitiativeId) -> ResourceFuture<'_, ()> {+ panic!("unexpected property initialization")+ }+ fn purge(&self, _: EntityAccessReceipt<EditAccessLevel>) -> ResourceFuture<'_, ()> {+ panic!("unexpected property deletion")+ }+ fn view(+ &self,+ _: EntityAccessAuth,+ _: Entity,+ ) -> ResourceFuture<'_, Option<EntityAccessReceipt<ViewAccessLevel>>> {+ panic!("unexpected child lookup")+ }+ fn properties(+ &self,+ _: Vec<EntityAccessReceipt<ViewAccessLevel>>,+ ) -> ResourceFuture<'_, HashMap<String, InitiativePropertySnapshot>> {+ panic!("unexpected property read")+ }+}++#[derive(Default)]+struct Events(Mutex<Vec<InitiativeTopicEvent>>);++impl InitiativeEventPublisher for Events {+ fn publish(&self, event: InitiativeMacroEvent) -> ResourceFuture<'_, ()> {+ Box::pin(async move {+ self.0.lock().unwrap().push(event.event().event.clone());+ Ok(())+ })+ }+}++type Context = InitiativeToolContext<+ InitiativeServiceImpl<PgInitiativeRepo, MockInitiativeDescriptionDocuments>,+ EntityAccessServiceImpl<PgAccessRepository>,+ PgActivityRepo,+>;++fn context(pool: PgPool, events: Arc<Events>) -> Context {+ context_with_resources(pool, events, Arc::new(UnusedProperties))+}++fn context_with_resources(+ pool: PgPool,+ events: Arc<Events>,+ resources: Arc<dyn InitiativeResources>,+) -> Context {+ let access = Arc::new(EntityAccessServiceImpl::new(PgAccessRepository::new(+ pool.clone(),+ )));+ Context {+ service: Arc::new(+ InitiativeServiceImpl::new(+ repo(pool.clone()),+ MockInitiativeDescriptionDocuments::new(),+ resources.clone(),+ )+ .with_event_publisher(events),+ ),+ history: Arc::new(InitiativeHistory::new(+ PgActivityRepo::new(pool),+ access.clone(),+ )),+ access,+ resources,+ actor: bot_id::MACRO_AI_BOT_ID,+ }+}++#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]+async fn tool_moves_from_inaccessible_source_and_clears_after_project_access_is_revoked(+ pool: PgPool,+) -> anyhow::Result<()> {+ for id in [OWNER, MEMBER, OTHER_OWNER] {+ insert_user(&pool, id).await?;+ }+ let task_id = Uuid::now_v7().to_string();+ insert_document(&pool, &task_id, MEMBER, true).await?;+ entity_access_db_utils::upsert_user_entity_access_bulk(+ &pool,+ &[user(MEMBER)],+ &Uuid::parse_str(&task_id)?,+ model_entity::EntityType::Document,+ AccessLevel::Owner,+ )+ .await?;+ let repo = repo(pool.clone());+ let source = repo+ .create(+ create_args(&pool, OTHER_OWNER, "Hidden source", &[]).await?,+ share_off(),+ TeamShareCreation::Unshared,+ )+ .await?;+ let destination = repo+ .create(+ create_args(&pool, OWNER, "Destination", &[MEMBER]).await?,+ share_off(),+ TeamShareCreation::Unshared,+ )+ .await?;+ repo.assign_tasks(source.id, vec![task_id.clone()]).await?;+ let events = Arc::new(Events::default());+ let context = context(pool, events.clone());+ assert!(+ context+ .access+ .generate_entity_access_receipt::<ViewAccessLevel>(+ &user(MEMBER),+ None,+ &source.id.to_string(),+ model_entity::EntityType::Initiative+ )+ .await+ .is_err()+ );++ let moved = SetTaskInitiative {+ task_ids: vec![task_id.clone(), task_id.clone()],+ initiative_id: Some(destination.id.as_uuid()),+ }+ .call(+ ServiceContext(context.clone()),+ RequestContext::new(user(MEMBER)),+ )+ .await+ .map_err(|error| error.internal_error)?;+ assert_eq!(moved.results.len(), 1);+ assert_eq!(moved.results[0].status, "moved");+ let recorded = events.0.lock().unwrap().clone();+ let [InitiativeTopicEvent::TasksChanged(change)] = recorded.as_slice() else {+ panic!("one committed membership change")+ };+ let attribution = change.attribution.as_ref().unwrap();+ assert_eq!(+ attribution.actor.as_ref(),+ bot_id::MACRO_AI_BOT_ID.into_storage_id().as_ref()+ );+ assert_eq!(attribution.on_behalf_of.as_ref(), Some(&user(MEMBER)));+ assert_eq!(change.changes[0].from, Some(source.id));+ assert_eq!(change.changes[0].to, Some(destination.id));++ // The same decorated ActivityReads backs personal GraphQL pages/overview and+ // the ReadActivity MCP tool. Persist both sides of the move to exercise it.+ use activity::domain::ports::{ActivityReads, ActivityRepo};+ use activity::{ActivitySource, Ingest};+ let Ingest::Insert(rows) = recorded[0].ingest(Uuid::now_v7()) else {+ panic!("move activities")+ };+ let activity_repo = PgActivityRepo::new(repo.pool.clone());+ activity_repo.insert_activities(&rows).await?;+ let reads = crate::domain::personal_activity::ProjectVisibleActivityReads::new(+ activity_repo,+ context.access.clone(),+ );+ let feed = reads+ .subject_feed(MEMBER, None, std::num::NonZeroU32::new(10).unwrap())+ .await?;+ assert_eq!(feed.records.len(), 1);+ assert_eq!(feed.records[0].entity_id, destination.id.to_string());+ let range = reads+ .subject_activity_range(+ MEMBER,+ chrono::Utc::now() - chrono::Duration::days(1),+ chrono::Utc::now() + chrono::Duration::days(1),+ std::num::NonZeroU32::new(10).unwrap(),+ )+ .await?;+ assert_eq!(range.records.len(), 1);+ assert_eq!(range.records[0].entity_id, destination.id.to_string());+ let window = activity::trailing_year(chrono::Utc::now(), "UTC".parse().unwrap());+ let overview = reads.subject_overview(MEMBER, window.clone()).await?;+ assert_eq!(overview.top_entities.len(), 1);+ assert_eq!(+ overview.top_entities[0].entity_id,+ destination.id.to_string()+ );++ let mut remove_access = update_args(destination.id);+ remove_access.member_ids_removed = vec![user(MEMBER)];+ repo.update(remove_access).await?;+ assert!(+ reads+ .subject_feed(MEMBER, None, std::num::NonZeroU32::new(10).unwrap())+ .await?+ .records+ .is_empty()+ );+ assert!(+ reads+ .subject_overview(MEMBER, window)+ .await?+ .top_entities+ .is_empty()+ );+ assert!(+ context+ .access+ .generate_entity_access_receipt::<ViewAccessLevel>(+ &user(MEMBER),+ None,+ &destination.id.to_string(),+ model_entity::EntityType::Initiative+ )+ .await+ .is_err()+ );+ let cleared = SetTaskInitiative {+ task_ids: vec![task_id.clone()],+ initiative_id: None,+ }+ .call(ServiceContext(context), RequestContext::new(user(MEMBER)))+ .await+ .map_err(|error| error.internal_error)?;+ assert_eq!(cleared.results[0].status, "cleared");+ assert!(repo.task_memberships(vec![task_id]).await?.is_empty());+ Ok(())+}++#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]+async fn sharing_tool_checks_actual_ownership_under_delegated_bot_receipt(+ pool: PgPool,+) -> anyhow::Result<()> {+ for id in [OWNER, MEMBER] {+ insert_user(&pool, id).await?;+ }+ let repo = repo(pool.clone());+ let project = repo+ .create(+ create_args(&pool, OWNER, "Launch", &[MEMBER]).await?,+ share_off(),+ TeamShareCreation::Unshared,+ )+ .await?;+ let context = context(pool, Arc::new(Events::default()));+ let tool: UpdateInitiativeSharing = serde_json::from_value(+ serde_json::json!({"initiativeId": project.id.as_uuid(), "linkScope": "public", "linkAccess": "view"}),+ )?;+ let denied = tool+ .call(+ ServiceContext(context.clone()),+ RequestContext::new(user(MEMBER)),+ )+ .await;+ assert!(denied.is_err());+ assert!(+ repo.get_detail(project.id)+ .await?+ .unwrap()+ .share_permission+ .link_share+ .is_none()+ );+ let shared = tool+ .call(ServiceContext(context), RequestContext::new(user(OWNER)))+ .await+ .map_err(|error| error.internal_error)?;+ assert_eq!(shared.link_scope.as_deref(), Some("PUBLIC"));+ assert_eq!(shared.access, "owner");+ Ok(())+}++#[tokio::test]+async fn oversized_tool_batch_fails_before_any_database_access() -> anyhow::Result<()> {+ let pool = sqlx::postgres::PgPoolOptions::new()+ .connect_lazy("postgres://unused:[email protected]:1/unused")?;+ let context = context(pool, Arc::new(Events::default()));+ let result = SetTaskInitiative {+ task_ids: (0..101).map(|id| id.to_string()).collect(),+ initiative_id: Some(Uuid::now_v7()),+ }+ .call(ServiceContext(context), RequestContext::new(user(OWNER)))+ .await;+ assert!(result.unwrap_err().description.contains("100"));+ Ok(())+}++#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]+async fn clear_tool_reports_non_tasks_and_keeps_clearing_the_remaining_tasks(+ pool: PgPool,+) -> anyhow::Result<()> {+ insert_user(&pool, OWNER).await?;+ let ids: Vec<String> = (0..3).map(|_| Uuid::now_v7().to_string()).collect();+ for (index, id) in ids.iter().enumerate() {+ insert_document(&pool, id, OWNER, index != 1).await?;+ entity_access_db_utils::upsert_user_entity_access_bulk(+ &pool,+ &[user(OWNER)],+ &Uuid::parse_str(id)?,+ model_entity::EntityType::Document,+ AccessLevel::Owner,+ )+ .await?;+ }+ let repo = repo(pool.clone());+ let initiative = repo+ .create(+ create_args(&pool, OWNER, "Launch", &[]).await?,+ share_off(),+ TeamShareCreation::Unshared,+ )+ .await?;+ repo.assign_tasks(initiative.id, vec![ids[0].clone(), ids[2].clone()])+ .await?;+ let context = context(pool, Arc::new(Events::default()));+ let result = SetTaskInitiative {+ task_ids: ids.clone(),+ initiative_id: None,+ }+ .call(ServiceContext(context), RequestContext::new(user(OWNER)))+ .await+ .map_err(|error| error.internal_error)?;+ assert_eq!(+ result+ .results+ .iter()+ .map(|row| row.status.as_str())+ .collect::<Vec<_>>(),+ ["cleared", "notATask", "cleared"]+ );+ assert!(+ repo.task_memberships(vec![ids[0].clone(), ids[2].clone()])+ .await?+ .is_empty()+ );+ assert!(matches!(+ repo.clear_task(&Uuid::now_v7().to_string()).await,+ Err(InitiativeError::NotFound)+ ));+ Ok(())+}diff --git a/crates/initiative/src/outbound/pg_initiative_repo/test/toolset/reads.rs b/crates/initiative/src/outbound/pg_initiative_repo/test/toolset/reads.rsnew file mode 100644index 0000000000..7e04b1cd1d--- /dev/null+++ b/crates/initiative/src/outbound/pg_initiative_repo/test/toolset/reads.rs@@ -0,0 +1,154 @@+use super::*;+use crate::inbound::toolset::{ListInitiatives, ReadInitiative};+use entity_access::domain::models::{EntityPermission, EntityType};++#[derive(Debug)]+struct VisibleResources {+ hidden_task: String,+ task_reads: Arc<std::sync::atomic::AtomicUsize>,+}++impl InitiativeResources for VisibleResources {+ fn initialize(&self, _: InitiativeId) -> ResourceFuture<'_, ()> {+ panic!("read-only fixture")+ }+ fn purge(&self, _: EntityAccessReceipt<EditAccessLevel>) -> ResourceFuture<'_, ()> {+ panic!("read-only fixture")+ }+ fn view(+ &self,+ auth: EntityAccessAuth,+ entity: Entity,+ ) -> ResourceFuture<'_, Option<EntityAccessReceipt<ViewAccessLevel>>> {+ Box::pin(async move {+ if entity.entity_type == EntityType::Document {+ self.task_reads+ .fetch_add(1, std::sync::atomic::Ordering::SeqCst);+ }+ if entity.entity_id == self.hidden_task {+ return Ok(None);+ }+ Ok(Some(EntityAccessReceipt::try_new(+ auth,+ entity,+ EntityPermission::AccessLevel {+ access_level: AccessLevel::View,+ },+ )?))+ })+ }+ fn properties(+ &self,+ _: Vec<EntityAccessReceipt<ViewAccessLevel>>,+ ) -> ResourceFuture<'_, HashMap<String, InitiativePropertySnapshot>> {+ Box::pin(async { Ok(HashMap::new()) })+ }+}++#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]+async fn tool_cursors_enumerate_projects_and_more_than_two_hundred_visible_tasks(+ pool: PgPool,+) -> anyhow::Result<()> {+ insert_user(&pool, OWNER).await?;+ let repo = repo(pool.clone());+ let mut projects = Vec::new();+ for name in ["Launch one", "Launch two"] {+ projects.push(+ repo.create(+ create_args(&pool, OWNER, name, &[]).await?,+ share_off(),+ TeamShareCreation::Unshared,+ )+ .await?,+ );+ }+ let mut task_ids = Vec::new();+ for _ in 0..202 {+ let id = Uuid::now_v7().to_string();+ insert_document(&pool, &id, OWNER, true).await?;+ task_ids.push(id);+ }+ repo.assign_tasks(projects[0].id, task_ids.clone()).await?;+ let hidden_task = task_ids.remove(100);+ let task_reads = Arc::new(std::sync::atomic::AtomicUsize::new(0));+ let context = context_with_resources(+ pool,+ Arc::new(Events::default()),+ Arc::new(VisibleResources {+ hidden_task: hidden_task.clone(),+ task_reads: task_reads.clone(),+ }),+ );+ let mut list: ListInitiatives =+ serde_json::from_value(serde_json::json!({"query": "Launch", "limit": 1}))?;+ let mut listed = Vec::new();+ loop {+ let page = list+ .call(+ ServiceContext(context.clone()),+ RequestContext::new(user(OWNER)),+ )+ .await+ .map_err(|error| error.internal_error)?;+ assert_eq!(page.projects.len(), 1);+ assert_eq!(page.truncated, page.next_cursor.is_some());+ listed.extend(+ page.projects+ .into_iter()+ .map(|project| project.initiative_id),+ );+ list.cursor = page.next_cursor;+ if list.cursor.is_none() {+ break;+ }+ assert!(listed.len() < 3, "collection cursor must advance");+ }+ listed.sort();+ let mut expected: Vec<_> = projects+ .iter()+ .map(|project| project.id.as_uuid())+ .collect();+ expected.sort();+ assert_eq!(listed, expected);++ task_reads.store(0, std::sync::atomic::Ordering::SeqCst);+ let mut read = ReadInitiative {+ initiative_id: projects[0].id.as_uuid(),+ task_cursor: None,+ task_limit: Some(100),+ };+ let mut found = Vec::new();+ let mut page_count = 0;+ loop {+ let page = read+ .call(+ ServiceContext(context.clone()),+ RequestContext::new(user(OWNER)),+ )+ .await+ .map_err(|error| error.internal_error)?;+ assert_eq!(page.project.task_count, 201);+ assert!(page.project.task_ids.len() <= 100);+ assert!(!page.project.task_ids.contains(&hidden_task));+ assert_eq!(+ page.project.tasks_truncated,+ page.next_task_cursor.is_some()+ );+ found.extend(page.project.task_ids);+ page_count += 1;+ read.task_cursor = page.next_task_cursor;+ if read.task_cursor.is_none() {+ break;+ }+ assert!(page_count < 4, "task cursor must advance");+ }+ assert_eq!(page_count, 3);+ assert_eq!(+ task_reads.load(std::sync::atomic::Ordering::SeqCst),+ 202 * page_count,+ "each tool read should perform one task visibility scan"+ );+ task_ids.sort();+ assert_eq!(found, task_ids);+ Ok(())+}diff --git a/crates/properties/src/inbound/toolset/bulk_set_entity_property_options.rs b/crates/properties/src/inbound/toolset/bulk_set_entity_property_options.rsindex 161d4642f9..239fabefcd 100644--- a/crates/properties/src/inbound/toolset/bulk_set_entity_property_options.rs+++ b/crates/properties/src/inbound/toolset/bulk_set_entity_property_options.rs@@ -84,6 +84,7 @@ pub struct BulkSetEntityPropertyOptionsResponse {fn entity_type_label(entity_type: ToolPropertyTargetEntityType) -> &'static str {match entity_type {ToolPropertyTargetEntityType::Document => "document",+ ToolPropertyTargetEntityType::Initiative => "initiative",ToolPropertyTargetEntityType::Project => "project",ToolPropertyTargetEntityType::Chat => "chat",ToolPropertyTargetEntityType::Thread => "thread",diff --git a/crates/properties/src/inbound/toolset/get_entity_properties.rs b/crates/properties/src/inbound/toolset/get_entity_properties.rsindex daeb5a0f59..66700ed1b8 100644--- a/crates/properties/src/inbound/toolset/get_entity_properties.rs+++ b/crates/properties/src/inbound/toolset/get_entity_properties.rs@@ -23,6 +23,7 @@ use super::PropertiesToolContext;pub enum ToolEntityType {Document,Task,+ Initiative,Project,Chat,// Listing and search tools report email threads as `email`. A doc comment@@ -41,6 +42,7 @@ impl From<ToolEntityType> for EntityType {match t {ToolEntityType::Document => EntityType::Document,ToolEntityType::Task => EntityType::Task,+ ToolEntityType::Initiative => EntityType::Initiative,ToolEntityType::Project => EntityType::Project,ToolEntityType::Chat => EntityType::Chat,ToolEntityType::Thread => EntityType::Thread,@@ -59,6 +61,7 @@ impl From<ToolEntityType> for EntityType {#[serde(rename_all = "snake_case")]pub enum ToolPropertyTargetEntityType {Document,+ Initiative,Project,Chat,// Listing and search tools report email threads as `email`. A doc comment@@ -76,6 +79,7 @@ impl From<ToolPropertyTargetEntityType> for model_entity::EntityType {fn from(value: ToolPropertyTargetEntityType) -> Self {match value {ToolPropertyTargetEntityType::Document => Self::Document,+ ToolPropertyTargetEntityType::Initiative => Self::Initiative,ToolPropertyTargetEntityType::Project => Self::Project,ToolPropertyTargetEntityType::Chat => Self::Chat,ToolPropertyTargetEntityType::Thread => Self::EmailThread,@@ -96,7 +100,9 @@ pub struct GetEntityProperties {#[schemars(description = "The ID of the entity to get properties for.")]pub entity_id: String,- #[schemars(description = "The type of entity.")]+ #[schemars(+ description = "The type of entity. Use initiative for Projects in Tasks, and project for folders."+ )]pub entity_type: ToolPropertyTargetEntityType,}diff --git a/crates/properties/src/inbound/toolset/set_entity_property.rs b/crates/properties/src/inbound/toolset/set_entity_property.rsindex c3cc6ef1c0..9504919a4d 100644--- a/crates/properties/src/inbound/toolset/set_entity_property.rs+++ b/crates/properties/src/inbound/toolset/set_entity_property.rs@@ -39,7 +39,7 @@ pub struct ToolEntityRef {#[derive(Debug, Deserialize, JsonSchema)]#[schemars(title = "SetEntityProperty",- description = "Set or update a property value on an entity (document, project, etc.). Tasks are targeted as entity_type='document'. Provide the property_definition_id and exactly one value field matching the property's data type.+ description = "Set or update a property value on an entity. Tasks are targeted as entity_type='document'. Projects in the Tasks UI are entity_type='initiative'; entity_type='project' still means a folder. Initiatives share the Assignees, Status, Priority and Due Date definitions below and their clearing behavior. Project Status accepts only Not Started (00000001-0000-0000-0002-000000000001), In Progress (...0002), and Completed (...0004); In Review and Canceled are task-only options. Provide the property_definition_id and exactly one value field matching the property's data type.For multi-select properties — including tags — prefer add_option_ids / remove_option_ids over option_ids: they add or remove just those options atomically, composing with concurrent edits. option_ids replaces the entire value, so a stale read can silently drop options someone else just added; only use it when the user asks to set the value to exactly a given list. To apply a tag, pass the tag set's property_definition_id and the tag's option id (both from ListTags) in add_option_ids; to remove a tag, use remove_option_ids.diff --git a/infra/packages/shared/src/ai_tools.ts b/infra/packages/shared/src/ai_tools.tsindex bf7968c0fe..fc549c91ce 100644--- a/infra/packages/shared/src/ai_tools.ts+++ b/infra/packages/shared/src/ai_tools.ts@@ -54,6 +54,10 @@ export function getAiToolsInfra(): AiToolsInfra {.getOutput('docxUploadBucketArn').apply((v) => v as string);+ const documentDeleteQueueArn: pulumi.Output<string> = cloudStorageServiceStack+ .getOutput('deleteDocumentQueueArn')+ .apply((v) => v as string);+// Queue names come from the `macro_queues` crate at runtime; we only need the// ARNs here for the IAM send/receive grants below.const emailScheduledQueueArn: pulumi.Output<string> = emailServiceStack@@ -100,6 +104,7 @@ export function getAiToolsInfra(): AiToolsInfra {mcpCredentialsKeyArn,],queueArns: [+ documentDeleteQueueArn,emailScheduledQueueArn,gmailOpsQueueArn,notificationIngressQueueArn,diff --git a/services/document_cognition_service/src/api/context/test.rs b/services/document_cognition_service/src/api/context/test.rsindex 7a2bbd124f..a86b9da883 100644--- a/services/document_cognition_service/src/api/context/test.rs+++ b/services/document_cognition_service/src/api/context/test.rs@@ -206,7 +206,7 @@ pub async fn test_api_context(pool: sqlx::Pool<sqlx::Postgres>) -> std::sync::Ar});let notification_reader_queue = SqsQueue::new(- aws_sdk_sqs::Client::from_conf(sqs_config),+ aws_sdk_sqs::Client::from_conf(sqs_config.clone()),"test-notification-queue".to_string(),);let notification_reader_service = NotificationReaderService {@@ -358,6 +358,15 @@ pub async fn test_api_context(pool: sqlx::Pool<sqlx::Postgres>) -> std::sync::Aruser_email_service,);+ let initiative_tool_context = ai_tools::build_initiative_tool_context(+ pool.clone(),+ &document_tool_context,+ properties_service.clone(),+ entity_access_service.clone(),+ aws_sdk_sqs::Client::from_conf(sqs_config.clone()),+ macro_event_broker.clone(),+ );+let tool_service_context = ai_tools::ToolServiceContext {search_service_client: search_service_client.clone(),email_service_client: email_service_client_external.clone(),@@ -395,6 +404,7 @@ pub async fn test_api_context(pool: sqlx::Pool<sqlx::Postgres>) -> std::sync::Ar"http://localhost:8086".to_string(),),project_tool_context,+ initiative_tool_context,team_tool_context: ai_tools::build_team_tool_context(pool.clone()),crm_tool_context: ai_tools::build_crm_tool_context(pool.clone()),skill_tool_context: ai_tools::build_skill_tool_context(diff --git a/services/document_cognition_service/src/main.rs b/services/document_cognition_service/src/main.rsindex 9f0610e930..eaba53f00a 100644--- a/services/document_cognition_service/src/main.rs+++ b/services/document_cognition_service/src/main.rs@@ -625,6 +625,15 @@ async fn main() -> anyhow::Result<()> {user_email_service,);+ let initiative_tool_context = ai_tools::build_initiative_tool_context(+ db.clone(),+ &document_tool_context,+ properties_service.clone(),+ entity_access_service.clone(),+ aws_sdk_sqs::Client::new(&aws_config),+ macro_event_broker.clone(),+ );+let tool_service_context = ai_tools::ToolServiceContext {search_service_client: search_service_client.clone(),email_service_client: email_service_client_external.clone(),@@ -661,6 +670,7 @@ async fn main() -> anyhow::Result<()> {DocumentStorageServiceUrl::new()?.to_string(),),project_tool_context,+ initiative_tool_context,team_tool_context: ai_tools::build_team_tool_context(db.clone()),crm_tool_context: ai_tools::build_crm_tool_context(db.clone()),skill_tool_context: ai_tools::build_skill_tool_context(diff --git a/services/mcp_service/src/context.rs b/services/mcp_service/src/context.rsindex cfd3191e99..652fc7c1c4 100644--- a/services/mcp_service/src/context.rs+++ b/services/mcp_service/src/context.rs@@ -377,6 +377,15 @@ async fn build_tool_context(args: ToolContextBuildArgs<'_>) -> anyhow::Result<Tolet search_service_client = Arc::new(search_service_client);let skill_tool_context =ai_tools::build_skill_tool_context(search_service_client.clone(), soup_service.clone());+ let initiative_tool_context = ai_tools::build_initiative_tool_context(+ db.clone(),+ &document_tool_context,+ properties_service.clone(),+ entity_access_service.clone(),+ side_effect_clients.sqs,+ side_effect_clients.macro_event_broker,+ );+let tool_context = ToolServiceContext {email_service_client: Arc::new(EmailServiceClientExternal::new(email_service_client.url().to_owned(),@@ -413,6 +422,7 @@ async fn build_tool_context(args: ToolContextBuildArgs<'_>) -> anyhow::Result<Todss_url,),project_tool_context,+ initiative_tool_context,team_tool_context: ai_tools::build_team_tool_context(db.clone()),crm_tool_context: ai_tools::build_crm_tool_context(db.clone()),skill_tool_context,