Skip to content

armgit / macro

Public Imported from GitHub
0

Macro is a unified workspace for teams: email, chat, docs, tasks, agents, calls, and CRM — @-linked together with shared AI memory.

feat: add initiative AI toolset (#7211)

Will Hutchinsona8416f8ab772
diff --git a/apps/docs/AI/mcp/tools/assign-tasks-to-initiative.mdx b/apps/docs/AI/mcp/tools/assign-tasks-to-initiative.mdx
new file mode 100644
index 0000000000..c5b0c78cc7
--- /dev/null
+++ b/apps/docs/AI/mcp/tools/assign-tasks-to-initiative.mdx
@@ -0,0 +1,15 @@
+---
+title: AssignTasksToInitiative
+description: "Move tasks into an initiative. A task already in another initiative is moved; duplicates are ignored; at most 100 unique task ids per call. Requires edit access to the initiative and to each task. Returns one status per task id: assigned, moved, not_a_task, not_found, or skipped_no_permission."
+---
+
+# AssignTasksToInitiative
+
+Move tasks into an initiative. A task already in another initiative is moved; duplicates are ignored; at most 100 unique task ids per call. Requires edit access to the initiative and to each task. Returns one status per task id: assigned, moved, not_a_task, not_found, or skipped_no_permission.
+
+## Parameters
+
+| Parameter | Type | Required | Description |
+| --- | --- | --- | --- |
+| `initiativeId` | string | Yes | The id of the initiative to assign tasks to. Requires edit access. |
+| `taskIds` | string[] | Yes | Task document ids to assign, at least one and at most 100 unique ids per call. Duplicates are ignored. Requires edit access to each task. |
diff --git a/apps/docs/AI/mcp/tools/index.mdx b/apps/docs/AI/mcp/tools/index.mdx
index b5dd32e716..aa9b9f2979 100644
--- a/apps/docs/AI/mcp/tools/index.mdx
+++ b/apps/docs/AI/mcp/tools/index.mdx
@@ -9,6 +9,7 @@ These pages are generated from Macro's Rust MCP tool registry.
## Tools
+- [AssignTasksToInitiative](/AI/mcp/tools/assign-tasks-to-initiative)
- [BashCodeExecution](/AI/mcp/tools/bash-code-execution)
- [BulkSetEntityPropertyOptions](/AI/mcp/tools/bulk-set-entity-property-options)
- [CalculateSpreadsheet](/AI/mcp/tools/calculate-spreadsheet)
@@ -90,6 +91,7 @@ These pages are generated from Macro's Rust MCP tool registry.
- [SetTaskInitiative](/AI/mcp/tools/set-task-initiative)
- [Subagent](/AI/mcp/tools/subagent)
- [TextEditorCodeExecution](/AI/mcp/tools/text-editor-code-execution)
+- [UnassignTasksFromInitiative](/AI/mcp/tools/unassign-tasks-from-initiative)
- [UpdateCalendarEvent](/AI/mcp/tools/update-calendar-event)
- [UpdateInitiative](/AI/mcp/tools/update-initiative)
- [UpdateInitiativeSharing](/AI/mcp/tools/update-initiative-sharing)
diff --git a/apps/docs/AI/mcp/tools/unassign-tasks-from-initiative.mdx b/apps/docs/AI/mcp/tools/unassign-tasks-from-initiative.mdx
new file mode 100644
index 0000000000..18f3f6ebc8
--- /dev/null
+++ b/apps/docs/AI/mcp/tools/unassign-tasks-from-initiative.mdx
@@ -0,0 +1,15 @@
+---
+title: UnassignTasksFromInitiative
+description: "Move tasks out of a specific initiative (project). Requires edit access to the initiative and each task; at most 100 unique tasks. Returns one status per task id: unassigned, or not_assigned when the task was not in this initiative. Tasks in other initiatives are left unchanged. An access or service failure stops the batch; earlier removals may have succeeded."
+---
+
+# UnassignTasksFromInitiative
+
+Move tasks out of a specific initiative (project). Requires edit access to the initiative and each task; at most 100 unique tasks. Returns one status per task id: unassigned, or not_assigned when the task was not in this initiative. Tasks in other initiatives are left unchanged. An access or service failure stops the batch; earlier removals may have succeeded.
+
+## Parameters
+
+| Parameter | Type | Required | Description |
+| --- | --- | --- | --- |
+| `initiativeId` | string | Yes | The id of the initiative to remove tasks from. Requires edit access. |
+| `taskIds` | string[] | Yes | Task document ids to remove. Provide at least one and at most 100 unique ids; duplicates are ignored. Requires edit access to each task. |
diff --git a/apps/docs/config/tool-pages.json b/apps/docs/config/tool-pages.json
index ede47e86a6..e56fa07f55 100644
--- a/apps/docs/config/tool-pages.json
+++ b/apps/docs/config/tool-pages.json
@@ -1,5 +1,6 @@
[
"AI/mcp/tools/index",
+ "AI/mcp/tools/assign-tasks-to-initiative",
"AI/mcp/tools/bash-code-execution",
"AI/mcp/tools/bulk-set-entity-property-options",
"AI/mcp/tools/calculate-spreadsheet",
@@ -81,6 +82,7 @@
"AI/mcp/tools/set-task-initiative",
"AI/mcp/tools/subagent",
"AI/mcp/tools/text-editor-code-execution",
+ "AI/mcp/tools/unassign-tasks-from-initiative",
"AI/mcp/tools/update-calendar-event",
"AI/mcp/tools/update-initiative",
"AI/mcp/tools/update-initiative-sharing",
diff --git a/apps/docs/docs.json b/apps/docs/docs.json
index 7e8539bd1c..ae5d64c2b9 100644
--- a/apps/docs/docs.json
+++ b/apps/docs/docs.json
@@ -71,6 +71,7 @@
"icon": "wrench",
"pages": [
"AI/mcp/tools/index",
+ "AI/mcp/tools/assign-tasks-to-initiative",
"AI/mcp/tools/bash-code-execution",
"AI/mcp/tools/bulk-set-entity-property-options",
"AI/mcp/tools/calculate-spreadsheet",
@@ -152,6 +153,7 @@
"AI/mcp/tools/set-task-initiative",
"AI/mcp/tools/subagent",
"AI/mcp/tools/text-editor-code-execution",
+ "AI/mcp/tools/unassign-tasks-from-initiative",
"AI/mcp/tools/update-calendar-event",
"AI/mcp/tools/update-initiative",
"AI/mcp/tools/update-initiative-sharing",
diff --git a/apps/web/src/lib/core/component/AI/component/tool/Initiatives.test.tsx b/apps/web/src/lib/core/component/AI/component/tool/Initiatives.test.tsx
index ee18e5e47a..36a8f9aa9e 100644
--- a/apps/web/src/lib/core/component/AI/component/tool/Initiatives.test.tsx
+++ b/apps/web/src/lib/core/component/AI/component/tool/Initiatives.test.tsx
@@ -137,6 +137,56 @@ it('preserves per-task failures and unavailable references in expandable results
expect(screen.queryByRole('button', { name: 'Project' })).toBeNull();
});
+it('shows separate assignment outcomes and retains the full response', () => {
+ tool(
+ 'AssignTasksToInitiative',
+ { initiativeId: projectId, taskIds: ['a', 'b', 'c'] },
+ {
+ initiativeId: projectId,
+ results: [
+ { taskId: 'a', status: 'assigned' },
+ { taskId: 'b', status: 'moved' },
+ { taskId: 'c', status: 'skipped_no_permission' },
+ ],
+ }
+ );
+ expect(screen.getByText('Add 3 tasks to project')).toBeTruthy();
+ fireEvent.click(screen.getByRole('button', { name: '3 tasks' }));
+ expect(screen.getByText('a — assigned')).toBeTruthy();
+ expect(screen.getByText('b — moved')).toBeTruthy();
+ expect(screen.getByText('c — skipped no permission')).toBeTruthy();
+ expect(screen.getByText('Result data')).toBeTruthy();
+});
+
+it('distinguishes removed tasks from tasks not assigned to the project', () => {
+ tool(
+ 'UnassignTasksFromInitiative',
+ { initiativeId: projectId, taskIds: ['a', 'b'] },
+ {
+ initiativeId: projectId,
+ results: [
+ { taskId: 'a', status: 'unassigned' },
+ { taskId: 'b', status: 'not_assigned' },
+ ],
+ }
+ );
+ expect(screen.getByText('Remove 2 tasks from project')).toBeTruthy();
+ fireEvent.click(screen.getByRole('button', { name: '2 tasks' }));
+ expect(screen.getByText('a — unassigned')).toBeTruthy();
+ expect(screen.getByText('b — not assigned')).toBeTruthy();
+});
+
+it('refreshes project caches after both batch membership tools', async () => {
+ await initiativeToolHandlers.AssignTasksToInitiative.handleResponse?.(
+ {} as never
+ );
+ await initiativeToolHandlers.UnassignTasksFromInitiative.handleResponse?.(
+ {} as never
+ );
+ expect(invalidate).toHaveBeenCalledTimes(2);
+ expect(invalidate).toHaveBeenCalledWith({ queryKey: ['initiatives'] });
+});
+
it('keeps successful deletion results inspectable without a stale project link', () => {
tool('DeleteInitiative', { initiativeId: projectId }, { success: true });
fireEvent.click(screen.getByRole('button', { name: 'Deleted' }));
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.tsx
index f33906b6d0..4705237755 100644
--- a/apps/web/src/lib/core/component/AI/component/tool/Initiatives.tsx
+++ b/apps/web/src/lib/core/component/AI/component/tool/Initiatives.tsx
@@ -125,7 +125,55 @@ function ProjectDetailsResult(props: { project: ProjectDetails }) {
);
}
+function TaskMembershipResults(props: {
+ results?: { taskId: string; status: string }[];
+}) {
+ return (
+ <Tool.List>
+ <For each={props.results}>
+ {(outcome) => (
+ <Tool.ListItem>
+ {outcome.taskId} — {outcome.status.replaceAll('_', ' ')}
+ </Tool.ListItem>
+ )}
+ </For>
+ </Tool.List>
+ );
+}
+
export const initiativeToolHandlers = {
+ AssignTasksToInitiative: createToolRenderer({
+ name: 'AssignTasksToInitiative',
+ handleResponse: refreshProjectsAfterMutation,
+ render: (ctx) => (
+ <ProjectToolCard
+ label={`Add ${ctx.tool.data.taskIds.length} tasks to project`}
+ renderContext={ctx.renderContext}
+ hasResult={!!ctx.response}
+ result={ctx.response?.data}
+ projectId={ctx.tool.data.initiativeId}
+ status={resultCount(ctx.response?.data.results.length ?? 0, 'task')}
+ >
+ <TaskMembershipResults results={ctx.response?.data.results} />
+ </ProjectToolCard>
+ ),
+ }),
+ UnassignTasksFromInitiative: createToolRenderer({
+ name: 'UnassignTasksFromInitiative',
+ handleResponse: refreshProjectsAfterMutation,
+ render: (ctx) => (
+ <ProjectToolCard
+ label={`Remove ${ctx.tool.data.taskIds.length} tasks from project`}
+ renderContext={ctx.renderContext}
+ hasResult={!!ctx.response}
+ result={ctx.response?.data}
+ projectId={ctx.tool.data.initiativeId}
+ status={resultCount(ctx.response?.data.results.length ?? 0, 'task')}
+ >
+ <TaskMembershipResults results={ctx.response?.data.results} />
+ </ProjectToolCard>
+ ),
+ }),
ListInitiatives: createToolRenderer({
name: 'ListInitiatives',
render: (ctx) => (
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.ts
index dad88e192c..c51b10204b 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
@@ -3,6 +3,44 @@
*/
import { z } from 'zod/v3';
+export const AssignTasksToInitiative = z.object({
+ initiativeId: z.string().uuid(),
+ taskIds: z.array(z.string()),
+});
+
+export const AssignTasksToInitiativeResponse = z.object({
+ initiativeId: z.string().uuid(),
+ results: z.array(
+ z.object({
+ taskId: z.string(),
+ status: z.any().superRefine((x, ctx) => {
+ const schemas = [
+ z.literal('assigned'),
+ z.literal('moved'),
+ z.literal('not_a_task'),
+ z.literal('not_found'),
+ z.literal('skipped_no_permission'),
+ ];
+ 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 BashCodeExecution = z.object({ input: z.string() });
export const BashCodeExecutionResponse = z.object({
@@ -5779,6 +5817,38 @@ export const TextEditorCodeExecutionResponse = z.object({
}),
});
+export const UnassignTasksFromInitiative = z.object({
+ initiativeId: z.string().uuid(),
+ taskIds: z.array(z.string()),
+});
+
+export const UnassignTasksFromInitiativeResponse = z.object({
+ initiativeId: z.string().uuid(),
+ results: z.array(
+ z.object({
+ taskId: z.string(),
+ status: z.any().superRefine((x, ctx) => {
+ const schemas = [z.literal('unassigned'), z.literal('not_assigned')];
+ 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 UpdateCalendarEvent = z.object({
eventId: z.string().uuid(),
calendarId: z.union([z.string().uuid(), 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.ts
index c14249b893..82e44c5e87 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
@@ -8,6 +8,10 @@ import * as schemas from './schemas';
import type * as types from './types';
type ToolParserMap = {
+ AssignTasksToInitiative: {
+ call: types.AssignTasksToInitiative;
+ response: types.AssignTasksToInitiativeResponse;
+ };
BashCodeExecution: {
call: types.BashCodeExecution;
response: types.BashCodeExecutionResponse;
@@ -266,6 +270,10 @@ type ToolParserMap = {
call: types.TextEditorCodeExecution;
response: types.TextEditorCodeExecutionResponse;
};
+ UnassignTasksFromInitiative: {
+ call: types.UnassignTasksFromInitiative;
+ response: types.UnassignTasksFromInitiativeResponse;
+ };
UpdateCalendarEvent: {
call: types.UpdateCalendarEvent;
response: types.ToolCalendarEvent;
@@ -289,6 +297,10 @@ type ToolParserMap = {
};
const toolParserMap = {
+ AssignTasksToInitiative: {
+ call: schemas.AssignTasksToInitiative,
+ response: schemas.AssignTasksToInitiativeResponse,
+ },
BashCodeExecution: {
call: schemas.BashCodeExecution,
response: schemas.BashCodeExecutionResponse,
@@ -574,6 +586,10 @@ const toolParserMap = {
call: schemas.TextEditorCodeExecution,
response: schemas.TextEditorCodeExecutionResponse,
},
+ UnassignTasksFromInitiative: {
+ call: schemas.UnassignTasksFromInitiative,
+ response: schemas.UnassignTasksFromInitiativeResponse,
+ },
UpdateCalendarEvent: {
call: schemas.UpdateCalendarEvent,
response: schemas.ToolCalendarEvent,
@@ -611,6 +627,10 @@ type NamedRawTool = {
};
type ToolDataMap = {
+ AssignTasksToInitiative: {
+ call: types.AssignTasksToInitiative;
+ response: types.AssignTasksToInitiativeResponse;
+ };
BashCodeExecution: {
call: types.BashCodeExecution;
response: types.BashCodeExecutionResponse;
@@ -869,6 +889,10 @@ type ToolDataMap = {
call: types.TextEditorCodeExecution;
response: types.TextEditorCodeExecutionResponse;
};
+ UnassignTasksFromInitiative: {
+ call: types.UnassignTasksFromInitiative;
+ response: types.UnassignTasksFromInitiativeResponse;
+ };
UpdateCalendarEvent: {
call: types.UpdateCalendarEvent;
response: types.ToolCalendarEvent;
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.ts
index f74c09ae3c..9e629871ae 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
@@ -8,6 +8,15 @@
* and run json-schema-to-typescript to regenerate this file.
*/
+/**
+ * Tool-facing status of a task assignment.
+ */
+export type TaskAssignmentStatus =
+ | 'assigned'
+ | 'moved'
+ | 'not_a_task'
+ | 'not_found'
+ | 'skipped_no_permission';
/**
* Content of a bash code execution response - either a result or an error
*/
@@ -1146,6 +1155,10 @@ export type TextEditorCodeExecutionContent =
| (TextEditorCodeExecutionToolError & {
type: 'text_editor_code_execution_tool_result_error';
});
+/**
+ * Tool-facing status of a task unassignment.
+ */
+export type TaskUnassignmentStatus = 'unassigned' | 'not_assigned';
/**
* How much of a recurring series an update applies to.
*/
@@ -1238,6 +1251,42 @@ export type ReadThreadReadContent =
type: 'itemPreviews';
};
+/**
+ * Move tasks into an initiative. A task already in another initiative is moved; duplicates are ignored; at most 100 unique task ids per call. Requires edit access to the initiative and to each task. Returns one status per task id: assigned, moved, not_a_task, not_found, or skipped_no_permission.
+ */
+export interface AssignTasksToInitiative {
+ /**
+ * The id of the initiative to assign tasks to. Requires edit access.
+ */
+ initiativeId: string;
+ /**
+ * Task document ids to assign, at least one and at most 100 unique ids per call. Duplicates are ignored. Requires edit access to each task.
+ */
+ taskIds: string[];
+}
+/**
+ * Response from [`AssignTasksToInitiative`].
+ */
+export interface AssignTasksToInitiativeResponse {
+ /**
+ * The id of the initiative receiving the tasks.
+ */
+ initiativeId: string;
+ /**
+ * Outcomes in request order after removing duplicates.
+ */
+ results: TaskAssignmentOutcome[];
+}
+/**
+ * The result of assigning one task to an initiative.
+ */
+export interface TaskAssignmentOutcome {
+ /**
+ * The task id this outcome describes.
+ */
+ taskId: string;
+ status: TaskAssignmentStatus;
+}
/**
* Execute a bash command in a sandboxed environment using Claude's built-in code execution tool.
*/
@@ -6540,6 +6589,42 @@ export interface TextEditorCodeExecutionResult {
export interface TextEditorCodeExecutionToolError {
error_code: CodeExecutionErrorCode;
}
+/**
+ * Move tasks out of a specific initiative (project). Requires edit access to the initiative and each task; at most 100 unique tasks. Returns one status per task id: unassigned, or not_assigned when the task was not in this initiative. Tasks in other initiatives are left unchanged. An access or service failure stops the batch; earlier removals may have succeeded.
+ */
+export interface UnassignTasksFromInitiative {
+ /**
+ * The id of the initiative to remove tasks from. Requires edit access.
+ */
+ initiativeId: string;
+ /**
+ * Task document ids to remove. Provide at least one and at most 100 unique ids; duplicates are ignored. Requires edit access to each task.
+ */
+ taskIds: string[];
+}
+/**
+ * Response from [`UnassignTasksFromInitiative`].
+ */
+export interface UnassignTasksFromInitiativeResponse {
+ /**
+ * The id of the initiative the tasks were removed from.
+ */
+ initiativeId: string;
+ /**
+ * Outcomes in request order after removing duplicates.
+ */
+ results: TaskUnassignmentOutcome[];
+}
+/**
+ * The result of removing one task from an initiative.
+ */
+export interface TaskUnassignmentOutcome {
+ /**
+ * The task id this outcome describes.
+ */
+ taskId: string;
+ status: TaskUnassignmentStatus;
+}
/**
* Update an existing calendar event. Only the supplied fields change; omitted fields keep their current values. The change is written to Google immediately and attendees are notified of it, so confirm details with the user first. Get the `eventId` from ListCalendarEvents.
*
diff --git a/crates/initiative/src/inbound/toolset.rs b/crates/initiative/src/inbound/toolset.rs
index 7696a72fb7..e898277c1d 100644
--- a/crates/initiative/src/inbound/toolset.rs
+++ b/crates/initiative/src/inbound/toolset.rs
@@ -1,19 +1,29 @@
//! Workflow tools for projects (the initiative domain), separate from folder tools.
+mod assign_tasks_to_initiative;
mod lifecycle;
mod reads;
mod sharing;
mod tasks;
mod types;
+mod unassign_tasks_from_initiative;
#[cfg(test)]
mod test;
+pub use assign_tasks_to_initiative::{
+ AssignTasksToInitiative, AssignTasksToInitiativeResponse, TaskAssignmentOutcome,
+ TaskAssignmentStatus,
+};
pub use lifecycle::{CreateInitiative, DeleteInitiative, UpdateInitiative};
pub use reads::{ListInitiatives, ReadInitiative, ReadInitiativeActivity, ReadTaskInitiatives};
pub use sharing::UpdateInitiativeSharing;
pub use tasks::SetTaskInitiative;
pub use types::*;
+pub use unassign_tasks_from_initiative::{
+ TaskUnassignmentOutcome, TaskUnassignmentStatus, UnassignTasksFromInitiative,
+ UnassignTasksFromInitiativeResponse,
+};
use std::sync::Arc;
@@ -106,6 +116,17 @@ fn failure(error: InitiativeError) -> ToolCallError {
}
}
+fn required_task_batch(task_ids: Vec<String>) -> ToolResult<Vec<String>> {
+ if task_ids.is_empty() {
+ return Err(failure(InitiativeError::BadRequest(
+ "provide at least one task id".into(),
+ )));
+ }
+ crate::domain::models::TaskAssignmentBatch::try_new(task_ids)
+ .map(|batch| batch.into_task_ids())
+ .map_err(failure)
+}
+
/// Complete project lifecycle, sharing, membership and history toolset.
pub fn initiative_toolset<S: InitiativeService, A: EntityAccessService, R: EntityActivityReads>()
-> AsyncToolCollection<InitiativeToolContext<S, A, R>> {
@@ -117,6 +138,8 @@ pub fn initiative_toolset<S: InitiativeService, A: EntityAccessService, R: Entit
.add_tool::<DeleteInitiative, InitiativeToolContext<S, A, R>>()
.add_tool::<UpdateInitiativeSharing, InitiativeToolContext<S, A, R>>()
.add_tool::<SetTaskInitiative, InitiativeToolContext<S, A, R>>()
+ .add_tool::<AssignTasksToInitiative, InitiativeToolContext<S, A, R>>()
+ .add_tool::<UnassignTasksFromInitiative, 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/assign_tasks_to_initiative.rs b/crates/initiative/src/inbound/toolset/assign_tasks_to_initiative.rs
new file mode 100644
index 0000000000..706eeee5bf
--- /dev/null
+++ b/crates/initiative/src/inbound/toolset/assign_tasks_to_initiative.rs
@@ -0,0 +1,144 @@
+//! AssignTasksToInitiative tool for moving tasks into an initiative.
+
+use activity::domain::ports::EntityActivityReads;
+use ai_toolset::{
+ AsyncTool, RequestContext, ServiceContext, ToolAnnotated, ToolAnnotations, ToolResult,
+};
+use async_trait::async_trait;
+use entity_access::domain::models::{BotAccessScope, EditAccessLevel, EntityType};
+use entity_access::domain::ports::EntityAccessService;
+use schemars::JsonSchema;
+use serde::{Deserialize, Serialize};
+
+use super::{InitiativeToolContext, failure, required_task_batch};
+use crate::domain::models::{AssignTaskStatus, TaskAssignment};
+use crate::domain::ports::InitiativeService;
+
+/// Response from [`AssignTasksToInitiative`].
+#[derive(Debug, Serialize, JsonSchema)]
+#[serde(rename_all = "camelCase")]
+pub struct AssignTasksToInitiativeResponse {
+ /// The id of the initiative receiving the tasks.
+ pub initiative_id: uuid::Uuid,
+ /// Outcomes in request order after removing duplicates.
+ pub results: Vec<TaskAssignmentOutcome>,
+}
+
+/// The result of assigning one task to an initiative.
+#[derive(Debug, Serialize, JsonSchema)]
+#[serde(rename_all = "camelCase")]
+pub struct TaskAssignmentOutcome {
+ /// The task id this outcome describes.
+ pub task_id: String,
+ /// What happened to the task.
+ pub status: TaskAssignmentStatus,
+}
+
+/// Tool-facing status of a task assignment.
+#[derive(Debug, Serialize, JsonSchema, Clone, Copy, PartialEq, Eq)]
+#[serde(rename_all = "snake_case")]
+pub enum TaskAssignmentStatus {
+ /// Assigned to this initiative.
+ Assigned,
+ /// Moved from another initiative.
+ Moved,
+ /// The document exists but is not a task.
+ NotATask,
+ /// The task does not exist.
+ NotFound,
+ /// The caller cannot edit the task.
+ SkippedNoPermission,
+}
+
+impl From<AssignTaskStatus> for TaskAssignmentStatus {
+ fn from(status: AssignTaskStatus) -> Self {
+ match status {
+ AssignTaskStatus::Assigned => Self::Assigned,
+ AssignTaskStatus::Moved => Self::Moved,
+ AssignTaskStatus::NotATask => Self::NotATask,
+ AssignTaskStatus::NotFound => Self::NotFound,
+ AssignTaskStatus::SkippedNoPermission => Self::SkippedNoPermission,
+ }
+ }
+}
+
+/// AssignTasksToInitiative tool input.
+#[derive(Debug, Deserialize, JsonSchema, Clone, Default)]
+#[serde(rename_all = "camelCase")]
+#[schemars(
+ title = "AssignTasksToInitiative",
+ description = "Move tasks into an initiative. A task already in another initiative is moved; duplicates are ignored; at most 100 unique task ids per call. Requires edit access to the initiative and to each task. Returns one status per task id: assigned, moved, not_a_task, not_found, or skipped_no_permission."
+)]
+pub struct AssignTasksToInitiative {
+ /// The id of the initiative receiving the tasks.
+ #[schemars(description = "The id of the initiative to assign tasks to. Requires edit access.")]
+ pub initiative_id: uuid::Uuid,
+ /// Task document ids to assign, in request order.
+ #[schemars(
+ description = "Task document ids to assign, at least one and at most 100 unique ids per call. Duplicates are ignored. Requires edit access to each task."
+ )]
+ pub task_ids: Vec<String>,
+}
+
+impl ToolAnnotated for AssignTasksToInitiative {
+ const ANNOTATIONS: ToolAnnotations =
+ ToolAnnotations::destructive("Assign tasks to initiative").with_idempotent();
+}
+
+#[async_trait]
+impl<ISvc, ESvc, R> AsyncTool<InitiativeToolContext<ISvc, ESvc, R>> for AssignTasksToInitiative
+where
+ ISvc: InitiativeService,
+ ESvc: EntityAccessService,
+ R: EntityActivityReads,
+{
+ type Output = AssignTasksToInitiativeResponse;
+
+ async fn call(
+ &self,
+ service_context: ServiceContext<InitiativeToolContext<ISvc, ESvc, R>>,
+ request_context: RequestContext,
+ ) -> ToolResult<Self::Output> {
+ let task_ids = required_task_batch(self.task_ids.clone())?;
+
+ let receipt = service_context
+ .receipt::<EditAccessLevel>(
+ &request_context,
+ &self.initiative_id.to_string(),
+ EntityType::Initiative,
+ )
+ .await?;
+
+ let mut assignments = Vec::with_capacity(task_ids.len());
+ for task_id in task_ids {
+ let result = service_context
+ .access
+ .generate_bot_entity_access_receipt::<EditAccessLevel>(
+ service_context.actor,
+ BotAccessScope::user(request_context.user_id.clone()),
+ &task_id,
+ EntityType::Document,
+ )
+ .await;
+ assignments.push(TaskAssignment::from_access(task_id, result).map_err(failure)?);
+ }
+
+ let response = service_context
+ .service
+ .assign_tasks(receipt, assignments)
+ .await
+ .map_err(failure)?;
+
+ Ok(AssignTasksToInitiativeResponse {
+ initiative_id: self.initiative_id,
+ results: response
+ .results
+ .into_iter()
+ .map(|result| TaskAssignmentOutcome {
+ task_id: result.task_id,
+ status: result.status.into(),
+ })
+ .collect(),
+ })
+ }
+}
diff --git a/crates/initiative/src/inbound/toolset/test.rs b/crates/initiative/src/inbound/toolset/test.rs
index da99c768d6..988e397666 100644
--- a/crates/initiative/src/inbound/toolset/test.rs
+++ b/crates/initiative/src/inbound/toolset/test.rs
@@ -1,5 +1,67 @@
use super::*;
+#[test]
+fn batch_tools_have_valid_strict_schemas() {
+ use ai_toolset::schema::generate_validated_input_schema;
+ assert_eq!(
+ generate_validated_input_schema::<AssignTasksToInitiative>()
+ .unwrap()
+ .name,
+ "AssignTasksToInitiative"
+ );
+ assert_eq!(
+ generate_validated_input_schema::<UnassignTasksFromInitiative>()
+ .unwrap()
+ .name,
+ "UnassignTasksFromInitiative"
+ );
+}
+
+#[test]
+fn required_batch_rejects_empty_and_oversized_requests_and_deduplicates_in_order() {
+ assert_eq!(
+ required_task_batch(vec![]).unwrap_err().description,
+ "provide at least one task id"
+ );
+ assert!(required_task_batch((0..101).map(|id| id.to_string()).collect()).is_err());
+ assert_eq!(
+ required_task_batch(vec!["b".into(), "a".into(), "b".into()]).unwrap(),
+ vec!["b", "a"]
+ );
+ assert_eq!(
+ required_task_batch(vec!["a".into(); 101]).unwrap(),
+ vec!["a"]
+ );
+}
+
+#[test]
+fn task_outcome_statuses_preserve_the_wire_contract() {
+ use crate::domain::models::AssignTaskStatus;
+ for (domain, expected) in [
+ (AssignTaskStatus::Assigned, "assigned"),
+ (AssignTaskStatus::Moved, "moved"),
+ (AssignTaskStatus::NotATask, "not_a_task"),
+ (AssignTaskStatus::NotFound, "not_found"),
+ (
+ AssignTaskStatus::SkippedNoPermission,
+ "skipped_no_permission",
+ ),
+ ] {
+ assert_eq!(
+ serde_json::to_value(TaskAssignmentStatus::from(domain)).unwrap(),
+ expected
+ );
+ }
+ assert_eq!(
+ serde_json::to_value(TaskUnassignmentStatus::Unassigned).unwrap(),
+ "unassigned"
+ );
+ assert_eq!(
+ serde_json::to_value(TaskUnassignmentStatus::NotAssigned).unwrap(),
+ "not_assigned"
+ );
+}
+
#[test]
fn invalid_name_length_is_actionable_without_exposing_internal_errors() {
let error = failure(InitiativeError::NameTooLong { max: 100 });
diff --git a/crates/initiative/src/inbound/toolset/unassign_tasks_from_initiative.rs b/crates/initiative/src/inbound/toolset/unassign_tasks_from_initiative.rs
new file mode 100644
index 0000000000..a5ae9f97d8
--- /dev/null
+++ b/crates/initiative/src/inbound/toolset/unassign_tasks_from_initiative.rs
@@ -0,0 +1,118 @@
+//! UnassignTasksFromInitiative tool for moving tasks out of an initiative.
+
+use activity::domain::ports::EntityActivityReads;
+use ai_toolset::{
+ AsyncTool, RequestContext, ServiceContext, ToolAnnotated, ToolAnnotations, ToolResult,
+};
+use async_trait::async_trait;
+use entity_access::domain::models::{EditAccessLevel, EntityType};
+use entity_access::domain::ports::EntityAccessService;
+use schemars::JsonSchema;
+use serde::{Deserialize, Serialize};
+
+use super::{InitiativeToolContext, failure, required_task_batch};
+use crate::domain::models::InitiativeError;
+use crate::domain::ports::InitiativeService;
+
+/// Response from [`UnassignTasksFromInitiative`].
+#[derive(Debug, Serialize, JsonSchema)]
+#[serde(rename_all = "camelCase")]
+pub struct UnassignTasksFromInitiativeResponse {
+ /// The id of the initiative the tasks were removed from.
+ pub initiative_id: uuid::Uuid,
+ /// Outcomes in request order after removing duplicates.
+ pub results: Vec<TaskUnassignmentOutcome>,
+}
+
+/// The result of removing one task from an initiative.
+#[derive(Debug, Serialize, JsonSchema)]
+#[serde(rename_all = "camelCase")]
+pub struct TaskUnassignmentOutcome {
+ /// The task id this outcome describes.
+ pub task_id: String,
+ /// What happened to the task.
+ pub status: TaskUnassignmentStatus,
+}
+
+/// Tool-facing status of a task unassignment.
+#[derive(Debug, Serialize, JsonSchema, Clone, Copy, PartialEq, Eq)]
+#[serde(rename_all = "snake_case")]
+pub enum TaskUnassignmentStatus {
+ /// Removed from this initiative.
+ Unassigned,
+ /// The task was not assigned to this initiative.
+ NotAssigned,
+}
+
+/// UnassignTasksFromInitiative tool input.
+#[derive(Debug, Deserialize, JsonSchema, Clone, Default)]
+#[serde(rename_all = "camelCase")]
+#[schemars(
+ title = "UnassignTasksFromInitiative",
+ description = "Move tasks out of a specific initiative (project). Requires edit access to the initiative and each task; at most 100 unique tasks. Returns one status per task id: unassigned, or not_assigned when the task was not in this initiative. Tasks in other initiatives are left unchanged. An access or service failure stops the batch; earlier removals may have succeeded."
+)]
+pub struct UnassignTasksFromInitiative {
+ /// The id of the initiative to remove tasks from.
+ #[schemars(
+ description = "The id of the initiative to remove tasks from. Requires edit access."
+ )]
+ pub initiative_id: uuid::Uuid,
+ /// Task document ids to remove, in request order.
+ #[schemars(
+ description = "Task document ids to remove. Provide at least one and at most 100 unique ids; duplicates are ignored. Requires edit access to each task."
+ )]
+ pub task_ids: Vec<String>,
+}
+
+impl ToolAnnotated for UnassignTasksFromInitiative {
+ const ANNOTATIONS: ToolAnnotations =
+ ToolAnnotations::destructive("Unassign tasks from initiative").with_idempotent();
+}
+
+#[async_trait]
+impl<ISvc, ESvc, R> AsyncTool<InitiativeToolContext<ISvc, ESvc, R>> for UnassignTasksFromInitiative
+where
+ ISvc: InitiativeService,
+ ESvc: EntityAccessService,
+ R: EntityActivityReads,
+{
+ type Output = UnassignTasksFromInitiativeResponse;
+
+ async fn call(
+ &self,
+ service_context: ServiceContext<InitiativeToolContext<ISvc, ESvc, R>>,
+ request_context: RequestContext,
+ ) -> ToolResult<Self::Output> {
+ let task_ids = required_task_batch(self.task_ids.clone())?;
+
+ let receipt = service_context
+ .receipt::<EditAccessLevel>(
+ &request_context,
+ &self.initiative_id.to_string(),
+ EntityType::Initiative,
+ )
+ .await?;
+
+ let mut results = Vec::with_capacity(task_ids.len());
+ for task_id in task_ids {
+ let task_receipt = service_context
+ .receipt::<EditAccessLevel>(&request_context, &task_id, EntityType::Document)
+ .await?;
+ let status = match service_context
+ .service
+ .unassign_task(receipt.clone(), task_receipt)
+ .await
+ {
+ Ok(()) => TaskUnassignmentStatus::Unassigned,
+ Err(InitiativeError::NotFound) => TaskUnassignmentStatus::NotAssigned,
+ Err(error) => return Err(failure(error)),
+ };
+ results.push(TaskUnassignmentOutcome { task_id, status });
+ }
+
+ Ok(UnassignTasksFromInitiativeResponse {
+ initiative_id: self.initiative_id,
+ results,
+ })
+ }
+}
diff --git a/docs/AGENT_GUIDE/ai-chat.md b/docs/AGENT_GUIDE/ai-chat.md
index 2d888660bf..adfe687b2c 100644
--- a/docs/AGENT_GUIDE/ai-chat.md
+++ b/docs/AGENT_GUIDE/ai-chat.md
@@ -449,6 +449,7 @@ After completion, each assistant message gets `Edit assistant response in Notes`
The chat auto-titles itself after the first exchange (route stays stable, title changes).
The agent has workspace tools (it can list your documents, read channels, create tasks,
+list, create, and update projects (initiatives in the API) and move tasks in or out of them,
render `displayResults` views). Requests go to `POST /cognition/stream/chat/message`; results
stream over the app's websocket, not the HTTP response.
@@ -466,6 +467,16 @@ A passage that is missing, spans blocks, or repeats with no occurrence chosen is
refused with no highlight left behind. The comment is posted as the agent with a
**from <user>** pill, and needs the user's comment access to the document.
+Project rows include **Find projects**, **Read project**, **Create project <name>**,
+**Update project**, **Add N tasks to project**, and **Remove N tasks from project**.
+The assignment and removal rows show a task count; the caret expands each task id
+and its outcome, with the full response available under **Result data**. Assignment
+outcomes are **assigned**, **moved**, **not a task**, **not found**, or
+**skipped no permission**. Removal outcomes are **unassigned** or **not assigned**;
+a task in a different project is left unchanged. Both actions require edit access
+to the project and each task. Removal stops on access or service failures, so
+previous tasks in the same batch may already have been removed.
+
## Agent sessions asking a question
For manual testing on local or deployed development environments, send