Skip to main content

task_graph_mcp/tools/
tasks.rs

1//! Task CRUD tools.
2
3use super::{get_bool, get_i32, get_i64, get_string, get_string_array, make_tool_with_prompts};
4use crate::config::{
5    AttachmentsConfig, AutoAdvanceConfig, DependenciesConfig, GateEnforcement, IdsConfig,
6    PhasesConfig, Prompts, StatesConfig, TagsConfig, UnknownKeyBehavior,
7};
8use crate::db::Database;
9use crate::error::ToolError;
10use crate::format::{
11    OutputFormat, format_scan_result_markdown, format_task_markdown, format_tasks_markdown,
12    markdown_to_json,
13};
14use crate::gates::evaluate_gates;
15use crate::prompts::PromptContext;
16use crate::types::{ScanResult, TaskTreeInput, parse_priority};
17use anyhow::Result;
18use rmcp::model::Tool;
19use serde_json::{Value, json};
20use tracing::warn;
21
22pub fn get_tools(prompts: &Prompts, states_config: &StatesConfig) -> Vec<Tool> {
23    // Generate state enum from config
24    let state_names: Vec<&str> = states_config.state_names();
25    let state_enum: Vec<Value> = state_names.iter().map(|s| json!(s)).collect();
26
27    vec![
28        make_tool_with_prompts(
29            "create",
30            "Create a new task. Use parent for subtasks. Use the link system (block tool) for dependencies.",
31            json!({
32                "id": {
33                    "type": "string",
34                    "description": "Custom task ID (optional, petname ID generated if not provided)"
35                },
36                "description": {
37                    "type": "string",
38                    "description": "Task description (required)"
39                },
40                "parent": {
41                    "type": "string",
42                    "description": "Parent task ID for nesting"
43                },
44                "priority": {
45                    "type": "integer",
46                    "description": "Task priority 0-10 (higher = more important, default 5)"
47                },
48                "points": {
49                    "type": "integer",
50                    "description": "Story points / complexity estimate"
51                },
52                "time_estimate_ms": {
53                    "type": "integer",
54                    "description": "Estimated duration in milliseconds"
55                },
56                "tags": {
57                    "type": "array",
58                    "items": { "type": "string" },
59                    "description": "Categorization/discovery tags (what the task IS, for querying)"
60                }
61            }),
62            vec!["description"],
63            prompts,
64        ),
65        make_tool_with_prompts(
66            "create_tree",
67            "Create a task tree from nested structure. child_type (default 'contains') links parent→children, sibling_type ('follows' or null) links siblings. Use 'ref' in nodes to include existing tasks.",
68            json!({
69                "tree": {
70                    "type": "object",
71                    "description": "Nested tree structure with title, children[], etc. Use 'ref' to reference existing tasks.",
72                    "properties": {
73                        "ref": { "type": "string", "description": "Reference to an existing task ID (other fields ignored when set)" },
74                        "id": { "type": "string", "description": "Custom task ID (optional, petname ID generated if not provided)" },
75                        "title": { "type": "string", "description": "Task title (required for new tasks)" },
76                        "description": { "type": "string", "description": "Task description" },
77                        "priority": { "type": "integer", "description": "Task priority 0-10 (default 5)" },
78                        "points": { "type": "integer", "description": "Story points / complexity estimate" },
79                        "time_estimate_ms": { "type": "integer", "description": "Estimated duration in milliseconds" },
80                        "tags": { "type": "array", "items": { "type": "string" }, "description": "Categorization/discovery tags" },
81                        "needed_tags": { "type": "array", "items": { "type": "string" }, "description": "Tags agent must have ALL of to claim (AND)" },
82                        "wanted_tags": { "type": "array", "items": { "type": "string" }, "description": "Tags agent must have AT LEAST ONE of to claim (OR)" },
83                        "children": { "type": "array", "description": "Child nodes (same structure, recursive)" }
84                    }
85                },
86                "parent": {
87                    "type": "string",
88                    "description": "Optional parent task ID for the tree root"
89                },
90                "child_type": {
91                    "type": "string",
92                    "description": "Dependency type from parent to children (default: 'contains'). Set to null for no parent-child deps."
93                },
94                "sibling_type": {
95                    "type": "string",
96                    "description": "Dependency type between consecutive siblings (default: null/parallel). Use 'follows' for sequential."
97                }
98            }),
99            vec!["tree"],
100            prompts,
101        ),
102        make_tool_with_prompts(
103            "get",
104            "Get a single task by ID. Returns detailed task with attachment metadata list and counts by type.",
105            json!({
106                "task": {
107                    "type": "string",
108                    "description": "Task ID"
109                }
110            }),
111            vec!["task"],
112            prompts,
113        ),
114        make_tool_with_prompts(
115            "list_tasks",
116            "Query tasks with flexible filters.",
117            json!({
118                "status": {
119                    "oneOf": [
120                        { "type": "string", "enum": state_enum },
121                        { "type": "array", "items": { "type": "string" } }
122                    ],
123                    "description": "Filter by status (single or array)"
124                },
125                "ready": {
126                    "type": "boolean",
127                    "description": "Filter for claimable tasks: in initial status, unclaimed, all start-blocking deps satisfied. When combined with 'agent', also filters by agent's tag qualifications."
128                },
129                "blocked": {
130                    "type": "boolean",
131                    "description": "Filter for blocked tasks: have unsatisfied start-blocking dependencies"
132                },
133                "claimed": {
134                    "type": "boolean",
135                    "description": "Filter for claimed tasks: currently owned by any agent (owner_agent IS NOT NULL)"
136                },
137                "owner": {
138                    "type": "string",
139                    "description": "Filter by owner agent ID (tasks currently claimed by this specific agent)"
140                },
141                "parent": {
142                    "type": "string",
143                    "description": "Filter by parent task ID (use 'null' for root tasks)"
144                },
145                "agent": {
146                    "type": "string",
147                    "description": "Agent ID for filtering. With ready=true, filters tasks the agent is qualified to claim based on agent_tags_all/agent_tags_any requirements."
148                },
149                "tags_any": {
150                    "type": "array",
151                    "items": { "type": "string" },
152                    "description": "Filter tasks that have ANY of these tags (OR)"
153                },
154                "tags_all": {
155                    "type": "array",
156                    "items": { "type": "string" },
157                    "description": "Filter tasks that have ALL of these tags (AND)"
158                },
159                "sort_by": {
160                    "type": "string",
161                    "enum": ["priority", "created_at", "updated_at"],
162                    "description": "Field to sort by (default: created_at for general queries, priority then created_at for ready queries)"
163                },
164                "sort_order": {
165                    "type": "string",
166                    "enum": ["asc", "desc"],
167                    "description": "Sort order: 'asc' for ascending, 'desc' for descending (default: desc for created_at/updated_at, priority always high-to-low)"
168                },
169                "limit": {
170                    "type": "integer",
171                    "description": "Maximum number of tasks to return"
172                }
173            }),
174            vec![],
175            prompts,
176        ),
177        make_tool_with_prompts(
178            "update",
179            "Update a task's properties. Status changes handle ownership automatically: transitioning to a timed status (e.g., working) claims the task, transitioning to non-timed releases it, transitioning to terminal (e.g., completed) completes it. For push coordination: use assignee to assign a task to another agent (sets owner and transitions to 'assigned' status). Only the owner can update a claimed task unless force=true.",
180            json!({
181                "worker_id": {
182                    "type": "string",
183                    "description": "Worker ID making the update"
184                },
185                "task": {
186                    "type": "string",
187                    "description": "Task ID"
188                },
189                "assignee": {
190                    "type": "string",
191                    "description": "Agent ID to assign the task to (push coordination). Sets owner_agent to assignee and transitions to 'assigned' status. The assignee can then claim (transition to working) when ready."
192                },
193                "status": {
194                    "type": "string",
195                    "enum": state_enum,
196                    "description": "New status"
197                },
198                "title": {
199                    "type": "string",
200                    "description": "New title"
201                },
202                "description": {
203                    "type": "string",
204                    "description": "New description"
205                },
206                "priority": {
207                    "type": "integer",
208                    "description": "New priority 0-10 (higher = more important)"
209                },
210                "points": {
211                    "type": "integer",
212                    "description": "New points estimate"
213                },
214                "tags": {
215                    "type": "array",
216                    "items": { "type": "string" },
217                    "description": "New categorization/discovery tags"
218                },
219                "needed_tags": {
220                    "type": "array",
221                    "items": { "type": "string" },
222                    "description": "Tags agent must have ALL of to claim (AND)"
223                },
224                "wanted_tags": {
225                    "type": "array",
226                    "items": { "type": "string" },
227                    "description": "Tags agent must have AT LEAST ONE of to claim (OR)"
228                },
229                "time_estimate_ms": {
230                    "type": "integer",
231                    "description": "Estimated duration in milliseconds"
232                },
233                "reason": {
234                    "type": "string",
235                    "description": "Reason for the update (stored in audit trail for state transitions)"
236                },
237                "force": {
238                    "type": "boolean",
239                    "description": "Force ownership changes even if owned by another worker (default: false)"
240                },
241                "attachments": {
242                    "type": "array",
243                    "description": "List of attachments to add to the task (e.g., commit hashes, changelists, notes)",
244                    "items": {
245                        "type": "object",
246                        "properties": {
247                            "type": {
248                                "type": "string",
249                                "description": "Attachment type/category (e.g., 'commit', 'changelist', 'note'). Used for indexing and replace operations."
250                            },
251                            "name": {
252                                "type": "string",
253                                "description": "Optional label/name for the attachment (arbitrary string)"
254                            },
255                            "content": {
256                                "type": "string",
257                                "description": "Attachment content (text)"
258                            },
259                            "mime": {
260                                "type": "string",
261                                "description": "MIME type (uses configured default if omitted)"
262                            },
263                            "mode": {
264                                "type": "string",
265                                "enum": ["append", "replace"],
266                                "description": "How to handle existing attachments of this type: 'append' adds new, 'replace' deletes all of this type first"
267                            }
268                        },
269                        "required": ["type", "content"]
270                    }
271                }
272            }),
273            vec!["worker_id", "task"],
274            prompts,
275        ),
276        make_tool_with_prompts(
277            "delete",
278            "Delete a task. Soft deletes by default (sets deleted_at), use obliterate=true to permanently remove. Rejects if task is claimed by another worker unless force=true.",
279            json!({
280                "worker_id": {
281                    "type": "string",
282                    "description": "Worker ID attempting to delete"
283                },
284                "task": {
285                    "type": "string",
286                    "description": "Task ID"
287                },
288                "cascade": {
289                    "type": "boolean",
290                    "description": "Whether to delete children (default: false)"
291                },
292                "reason": {
293                    "type": "string",
294                    "description": "Optional reason for deletion"
295                },
296                "obliterate": {
297                    "type": "boolean",
298                    "description": "If true, permanently deletes the task from the database. If false (default), soft deletes by setting deleted_at timestamp."
299                },
300                "force": {
301                    "type": "boolean",
302                    "description": "Force deletion even if claimed by another worker (default: false)"
303                }
304            }),
305            vec!["worker_id", "task"],
306            prompts,
307        ),
308        make_tool_with_prompts(
309            "scan",
310            "Scan the task graph from a starting task in multiple directions. Returns related tasks organized by direction: before (predecessors via blocks/follows), after (successors), above (ancestors via contains), below (descendants). Each direction has depth control: 0=none, N=levels, -1=all.",
311            json!({
312                "task": {
313                    "type": "string",
314                    "description": "Task ID to scan from"
315                },
316                "before": {
317                    "type": "integer",
318                    "description": "Depth for predecessors (tasks that block this one): 0=none, N=levels, -1=all (default: 0)"
319                },
320                "after": {
321                    "type": "integer",
322                    "description": "Depth for successors (tasks this one blocks): 0=none, N=levels, -1=all (default: 0)"
323                },
324                "above": {
325                    "type": "integer",
326                    "description": "Depth for ancestors (parent chain): 0=none, N=levels, -1=all (default: 0)"
327                },
328                "below": {
329                    "type": "integer",
330                    "description": "Depth for descendants (children tree): 0=none, N=levels, -1=all (default: 0)"
331                },
332                "format": {
333                    "type": "string",
334                    "enum": ["json", "markdown"],
335                    "description": "Output format (default: json)"
336                }
337            }),
338            vec!["task"],
339            prompts,
340        ),
341    ]
342}
343
344pub fn create(
345    db: &Database,
346    states_config: &StatesConfig,
347    phases_config: &PhasesConfig,
348    tags_config: &TagsConfig,
349    ids_config: &IdsConfig,
350    args: Value,
351) -> Result<Value> {
352    let id = get_string(&args, "id");
353    let description =
354        get_string(&args, "description").ok_or_else(|| ToolError::missing_field("description"))?;
355    let parent_id = get_string(&args, "parent");
356    let phase = get_string(&args, "phase");
357    // Support both integer and string priority
358    let priority = get_i32(&args, "priority")
359        .or_else(|| get_string(&args, "priority").map(|s| parse_priority(&s)));
360    let points = get_i32(&args, "points");
361    let time_estimate_ms = get_i64(&args, "time_estimate_ms");
362    let tags = get_string_array(&args, "tags");
363    let needed_tags = get_string_array(&args, "needed_tags");
364    let wanted_tags = get_string_array(&args, "wanted_tags");
365
366    // Check phase validity (may return warning)
367    let phase_warning = if let Some(ref p) = phase {
368        phases_config.check_phase(p)?
369    } else {
370        None
371    };
372
373    // Check tag validity for all tag types
374    let mut tag_warnings = Vec::new();
375    if let Some(ref t) = tags {
376        tag_warnings.extend(tags_config.validate_tags(t)?);
377    }
378    if let Some(ref t) = needed_tags {
379        tag_warnings.extend(tags_config.validate_tags(t)?);
380    }
381    if let Some(ref t) = wanted_tags {
382        tag_warnings.extend(tags_config.validate_tags(t)?);
383    }
384
385    let task = db.create_task(
386        id,
387        description,
388        parent_id,
389        phase,
390        priority,
391        points,
392        time_estimate_ms,
393        needed_tags,
394        wanted_tags,
395        tags,
396        states_config,
397        ids_config,
398    )?;
399
400    let mut response = json!({
401        "id": &task.id,
402        "description": task.description,
403        "status": task.status,
404        "phase": task.phase,
405        "priority": task.priority,
406        "created_at": task.created_at
407    });
408
409    if let Some(warning) = phase_warning {
410        response["phase_warning"] = json!(warning);
411    }
412
413    if !tag_warnings.is_empty() {
414        response["tag_warnings"] = json!(tag_warnings);
415    }
416
417    Ok(response)
418}
419
420pub fn create_tree(
421    db: &Database,
422    states_config: &StatesConfig,
423    phases_config: &PhasesConfig,
424    tags_config: &TagsConfig,
425    ids_config: &IdsConfig,
426    args: Value,
427) -> Result<Value> {
428    let tree: TaskTreeInput = serde_json::from_value(
429        args.get("tree")
430            .cloned()
431            .ok_or_else(|| ToolError::missing_field("tree"))?,
432    )?;
433    let parent_id = get_string(&args, "parent");
434    let child_type = get_string(&args, "child_type");
435    let sibling_type = get_string(&args, "sibling_type");
436
437    let (root_id, all_ids, phase_warnings, tag_warnings) = db.create_task_tree(
438        tree,
439        parent_id,
440        child_type,
441        sibling_type,
442        states_config,
443        phases_config,
444        tags_config,
445        ids_config,
446    )?;
447
448    // Fetch the root task to return full details
449    let root_task = db.get_task(&root_id)?.ok_or_else(|| {
450        ToolError::new(
451            crate::error::ErrorCode::TaskNotFound,
452            "Root task not found after creation",
453        )
454    })?;
455
456    let mut response = json!({
457        "root": {
458            "id": root_task.id,
459            "title": root_task.title,
460            "description": root_task.description,
461            "status": root_task.status,
462            "phase": root_task.phase,
463            "priority": root_task.priority,
464            "created_at": root_task.created_at
465        },
466        "all_ids": all_ids,
467        "count": all_ids.len()
468    });
469
470    if !phase_warnings.is_empty() {
471        response["phase_warnings"] = json!(phase_warnings);
472    }
473
474    if !tag_warnings.is_empty() {
475        response["tag_warnings"] = json!(tag_warnings);
476    }
477
478    Ok(response)
479}
480
481pub fn get(db: &Database, default_format: OutputFormat, args: Value) -> Result<Value> {
482    let task_id = get_string(&args, "task").ok_or_else(|| ToolError::missing_field("task"))?;
483    let format = get_string(&args, "format")
484        .and_then(|s| OutputFormat::parse(&s))
485        .unwrap_or(default_format);
486
487    let task = db
488        .get_task(&task_id)?
489        .ok_or_else(|| ToolError::new(crate::error::ErrorCode::TaskNotFound, "Task not found"))?;
490
491    let blocked_by = db.get_blockers(&task_id)?;
492
493    // Get attachment metadata
494    let attachments = db.get_attachments(&task_id)?;
495
496    // Calculate attachment counts by MIME type
497    let mut attachment_counts: std::collections::HashMap<String, i32> =
498        std::collections::HashMap::new();
499    for att in &attachments {
500        *attachment_counts.entry(att.mime_type.clone()).or_insert(0) += 1;
501    }
502
503    match format {
504        OutputFormat::Markdown => {
505            let mut md = format_task_markdown(&task, &blocked_by);
506
507            // Add attachment section if there are attachments
508            if !attachments.is_empty() {
509                md.push_str("\n### Attachments\n");
510                for att in &attachments {
511                    let file_indicator = if att.file_path.is_some() {
512                        " (file)"
513                    } else {
514                        ""
515                    };
516                    md.push_str(&format!(
517                        "- **{}** [{}]{}\n",
518                        att.name, att.mime_type, file_indicator
519                    ));
520                }
521
522                // Add counts by type
523                md.push_str("\n**Counts by type:**\n");
524                for (mime_type, count) in &attachment_counts {
525                    md.push_str(&format!("- {}: {}\n", mime_type, count));
526                }
527            }
528
529            Ok(markdown_to_json(md))
530        }
531        OutputFormat::Json => {
532            let mut task_json = serde_json::to_value(&task)?;
533            if let Some(obj) = task_json.as_object_mut() {
534                obj.insert("blocked_by".to_string(), json!(blocked_by));
535                obj.insert(
536                    "attachments".to_string(),
537                    serde_json::to_value(&attachments)?,
538                );
539                obj.insert(
540                    "attachment_counts".to_string(),
541                    serde_json::to_value(&attachment_counts)?,
542                );
543            }
544            Ok(task_json)
545        }
546    }
547}
548
549pub fn list_tasks(
550    db: &Database,
551    states_config: &StatesConfig,
552    deps_config: &DependenciesConfig,
553    default_format: OutputFormat,
554    args: Value,
555) -> Result<Value> {
556    let format = get_string(&args, "format")
557        .and_then(|s| OutputFormat::parse(&s))
558        .unwrap_or(default_format);
559
560    let ready = get_bool(&args, "ready").unwrap_or(false);
561    let blocked = get_bool(&args, "blocked").unwrap_or(false);
562    let claimed = get_bool(&args, "claimed").unwrap_or(false);
563    let limit = get_i32(&args, "limit");
564    let phase = get_string(&args, "phase");
565
566    // Extract tag filtering parameters
567    let tags_any = get_string_array(&args, "tags_any");
568    let tags_all = get_string_array(&args, "tags_all");
569
570    // 'agent' replaces both 'worker_id' and 'qualified_for' - single param for agent-related filtering
571    let agent_id = get_string(&args, "agent");
572
573    // Sorting parameters
574    let sort_by = get_string(&args, "sort_by");
575    let sort_order = get_string(&args, "sort_order");
576
577    // Get tasks based on filters
578    let mut tasks = if ready {
579        // Ready tasks: in initial state, unclaimed, all deps satisfied
580        // If agent is provided, also filter by agent's tag qualifications
581        db.get_ready_tasks(
582            agent_id.as_deref(),
583            states_config,
584            deps_config,
585            sort_by.as_deref(),
586            sort_order.as_deref(),
587        )?
588    } else if blocked {
589        // Blocked tasks: have unsatisfied deps
590        db.get_blocked_tasks(
591            states_config,
592            deps_config,
593            sort_by.as_deref(),
594            sort_order.as_deref(),
595        )?
596    } else if claimed {
597        // Claimed tasks: currently owned by any agent
598        db.get_claimed_tasks(None)?
599    } else {
600        // General query with filters
601        // Handle status which can be string or array
602        let status_vec: Option<Vec<String>> = if let Some(status_val) = args.get("status") {
603            if let Some(s) = status_val.as_str() {
604                Some(vec![s.to_string()])
605            } else {
606                status_val.as_array().map(|arr| {
607                    arr.iter()
608                        .filter_map(|v| v.as_str().map(String::from))
609                        .collect()
610                })
611            }
612        } else {
613            None
614        };
615        let owner = get_string(&args, "owner");
616        let parent_id_str = get_string(&args, "parent");
617        let parent_id: Option<Option<&str>> = match &parent_id_str {
618            Some(pid_str) if pid_str == "null" => Some(None), // Root tasks
619            Some(pid_str) => Some(Some(pid_str.as_str())),
620            None => None,
621        };
622
623        // Check if tag filtering or agent qualification filtering is needed
624        let has_tag_filters = tags_any.is_some() || tags_all.is_some() || agent_id.is_some();
625
626        if has_tag_filters {
627            // Use the tag-filtered query
628            // When agent is provided without ready=true, filter by agent's qualification
629            let qualified_agent_tags = if let Some(aid) = &agent_id {
630                Some(db.get_agent_tags(aid)?)
631            } else {
632                None
633            };
634
635            db.list_tasks_with_tag_filters(
636                status_vec,
637                owner.as_deref(),
638                parent_id,
639                tags_any,
640                tags_all,
641                qualified_agent_tags,
642                limit,
643                sort_by.as_deref(),
644                sort_order.as_deref(),
645            )?
646        } else {
647            // Use list_tasks which returns full Task objects (only supports single status)
648            let status = status_vec
649                .as_ref()
650                .and_then(|v| v.first().map(|s| s.as_str()));
651            db.list_tasks(
652                status,
653                phase.as_deref(),
654                owner.as_deref(),
655                parent_id,
656                limit,
657                sort_by.as_deref(),
658                sort_order.as_deref(),
659            )?
660        }
661    };
662
663    // Apply phase filter for ready/blocked/claimed paths (list_tasks handles it internally)
664    if let Some(ref p) = phase {
665        tasks.retain(|t| t.phase.as_deref() == Some(p.as_str()));
666    }
667
668    // Apply limit (some paths may already have limit applied, but this ensures consistency)
669    if let Some(l) = limit {
670        tasks.truncate(l as usize);
671    }
672
673    // Get blockers for each task
674    let tasks_with_blockers: Vec<_> = tasks
675        .into_iter()
676        .map(|task| {
677            let blockers = db.get_blockers(&task.id).unwrap_or_default();
678            (task, blockers)
679        })
680        .collect();
681
682    match format {
683        OutputFormat::Markdown => Ok(markdown_to_json(format_tasks_markdown(
684            &tasks_with_blockers,
685            states_config,
686        ))),
687        OutputFormat::Json => Ok(json!({
688            "tasks": tasks_with_blockers.iter().map(|(task, blockers)| {
689                let mut task_json = serde_json::to_value(task).unwrap();
690                if let Some(obj) = task_json.as_object_mut() {
691                    obj.insert("blocked_by".to_string(), json!(blockers));
692                }
693                task_json
694            }).collect::<Vec<_>>()
695        })),
696    }
697}
698
699pub fn update(
700    db: &Database,
701    attachments_config: &AttachmentsConfig,
702    states_config: &StatesConfig,
703    phases_config: &PhasesConfig,
704    deps_config: &DependenciesConfig,
705    auto_advance: &AutoAdvanceConfig,
706    tags_config: &TagsConfig,
707    workflows: &crate::config::workflows::WorkflowsConfig,
708    args: Value,
709) -> Result<Value> {
710    let worker_id =
711        get_string(&args, "worker_id").ok_or_else(|| ToolError::missing_field("worker_id"))?;
712    let task_id = get_string(&args, "task").ok_or_else(|| ToolError::missing_field("task"))?;
713    let assignee = get_string(&args, "assignee");
714    let title = get_string(&args, "title");
715    let description = if args.get("description").is_some() {
716        Some(get_string(&args, "description"))
717    } else {
718        None
719    };
720    let status = get_string(&args, "status");
721    let phase = get_string(&args, "phase");
722    // Support both integer and string priority
723    let priority = get_i32(&args, "priority")
724        .or_else(|| get_string(&args, "priority").map(|s| parse_priority(&s)));
725    let points = if args.get("points").is_some() {
726        Some(get_i32(&args, "points"))
727    } else {
728        None
729    };
730    let tags = if args.get("tags").is_some() {
731        Some(get_string_array(&args, "tags").unwrap_or_default())
732    } else {
733        None
734    };
735    let needed_tags = if args.get("needed_tags").is_some() {
736        Some(get_string_array(&args, "needed_tags").unwrap_or_default())
737    } else {
738        None
739    };
740    let wanted_tags = if args.get("wanted_tags").is_some() {
741        Some(get_string_array(&args, "wanted_tags").unwrap_or_default())
742    } else {
743        None
744    };
745    let time_estimate_ms = get_i64(&args, "time_estimate_ms");
746    let reason = get_string(&args, "reason");
747    let force = get_bool(&args, "force").unwrap_or(false);
748
749    // Process attachments first (before the update)
750    let mut attachment_results: Vec<Value> = Vec::new();
751    let mut attachment_warnings: Vec<String> = Vec::new();
752
753    if let Some(attachments_arr) = args.get("attachments").and_then(|v| v.as_array()) {
754        for att_value in attachments_arr {
755            let attachment_type = att_value.get("type").and_then(|v| v.as_str());
756            let name = att_value.get("name").and_then(|v| v.as_str()).unwrap_or("");
757            let content = att_value.get("content").and_then(|v| v.as_str());
758            let mime_override = att_value.get("mime").and_then(|v| v.as_str());
759            let mode_override = att_value.get("mode").and_then(|v| v.as_str());
760
761            let attachment_type = match attachment_type {
762                Some(t) => t,
763                None => {
764                    attachment_warnings
765                        .push("Skipped attachment: missing 'type' field".to_string());
766                    continue;
767                }
768            };
769
770            let content = match content {
771                Some(c) => c,
772                None => {
773                    attachment_warnings.push(format!(
774                        "Skipped attachment type '{}': missing 'content' field",
775                        attachment_type
776                    ));
777                    continue;
778                }
779            };
780
781            // Check unknown key behavior
782            if !attachments_config.is_known_key(attachment_type) {
783                match attachments_config.unknown_key {
784                    UnknownKeyBehavior::Reject => {
785                        attachment_warnings.push(format!(
786                            "Rejected attachment type '{}': unknown type (configure in attachments.definitions or set unknown_key to 'allow')",
787                            attachment_type
788                        ));
789                        continue;
790                    }
791                    UnknownKeyBehavior::Warn => {
792                        attachment_warnings
793                            .push(format!("Unknown attachment type '{}'", attachment_type));
794                    }
795                    UnknownKeyBehavior::Allow => {}
796                }
797            }
798
799            // Use config defaults for mime/mode, but allow explicit overrides
800            let mime_type = mime_override.map(String::from).unwrap_or_else(|| {
801                attachments_config
802                    .get_mime_default(attachment_type)
803                    .to_string()
804            });
805            let mode = mode_override
806                .unwrap_or_else(|| attachments_config.get_mode_default(attachment_type));
807
808            // Validate mode
809            if mode != "append" && mode != "replace" {
810                attachment_warnings.push(format!(
811                    "Skipped attachment type '{}': mode must be 'append' or 'replace'",
812                    attachment_type
813                ));
814                continue;
815            }
816
817            // Handle replace mode - delete all existing attachments of this type
818            if mode == "replace" {
819                let _ = db.delete_attachments_by_type(&task_id, attachment_type);
820            }
821
822            // Add the attachment
823            match db.add_attachment(
824                &task_id,
825                attachment_type.to_string(),
826                name.to_string(),
827                content.to_string(),
828                Some(mime_type.clone()),
829                None,
830            ) {
831                Ok(sequence) => {
832                    attachment_results.push(json!({
833                        "type": attachment_type,
834                        "sequence": sequence,
835                        "name": name,
836                        "mime_type": mime_type
837                    }));
838                }
839                Err(e) => {
840                    attachment_warnings.push(format!(
841                        "Failed to add attachment type '{}': {}",
842                        attachment_type, e
843                    ));
844                }
845            }
846        }
847    }
848
849    // Check phase validity (may return warning)
850    let phase_warning = if let Some(ref p) = phase {
851        phases_config.check_phase(p)?
852    } else {
853        None
854    };
855
856    // Check tag validity for all tag types
857    let mut tag_warnings = Vec::new();
858    if let Some(ref t) = tags {
859        tag_warnings.extend(tags_config.validate_tags(t)?);
860    }
861    if let Some(ref t) = needed_tags {
862        tag_warnings.extend(tags_config.validate_tags(t)?);
863    }
864    if let Some(ref t) = wanted_tags {
865        tag_warnings.extend(tags_config.validate_tags(t)?);
866    }
867
868    // Check exit gates for status transitions
869    let mut gate_warnings: Vec<String> = Vec::new();
870    // Track skipped gates for audit logging (separate from warnings for response)
871    let mut skipped_status_gates: Vec<String> = Vec::new();
872    let mut skipped_phase_gates: Vec<String> = Vec::new();
873    if let Some(ref new_status) = status {
874        // Get current task to check if status is actually changing
875        let current_task = db.get_task(&task_id)?.ok_or_else(|| {
876            ToolError::new(crate::error::ErrorCode::TaskNotFound, "Task not found")
877        })?;
878
879        if &current_task.status != new_status {
880            // Status is changing - check exit gates for the CURRENT status
881            let exit_gates = workflows.get_status_exit_gates(&current_task.status);
882
883            if !exit_gates.is_empty() {
884                // Convert references to owned GateDefinitions for evaluate_gates
885                let gates_owned: Vec<crate::config::GateDefinition> =
886                    exit_gates.iter().map(|g| (*g).clone()).collect();
887                let gate_result = evaluate_gates(db, &task_id, &gates_owned)?;
888
889                match gate_result.status.as_str() {
890                    "fail" => {
891                        // Reject-level gates unsatisfied - cannot proceed
892                        let gate_names: Vec<String> = gate_result
893                            .unsatisfied_gates
894                            .iter()
895                            .filter(|g| g.enforcement == GateEnforcement::Reject)
896                            .map(|g| format!("{} ({})", g.gate_type, g.description))
897                            .collect();
898                        return Err(ToolError::gates_not_satisfied(
899                            &current_task.status,
900                            &gate_names,
901                        )
902                        .into());
903                    }
904                    "warn" => {
905                        // Warn-level gates unsatisfied
906                        let warn_gates: Vec<String> = gate_result
907                            .unsatisfied_gates
908                            .iter()
909                            .filter(|g| g.enforcement == GateEnforcement::Warn)
910                            .map(|g| format!("{} ({})", g.gate_type, g.description))
911                            .collect();
912
913                        if !force {
914                            // Cannot proceed without force flag
915                            return Err(ToolError::new(
916                                crate::error::ErrorCode::GatesNotSatisfied,
917                                format!(
918                                    "Cannot exit '{}' without force=true: unsatisfied gates: {}",
919                                    current_task.status,
920                                    warn_gates.join(", ")
921                                ),
922                            )
923                            .into());
924                        }
925                        // force=true: proceed but include warning and log for audit
926                        warn!(
927                            task_id = %task_id,
928                            agent = %worker_id,
929                            from_status = %current_task.status,
930                            to_status = %new_status,
931                            skipped_gates = ?warn_gates,
932                            "Status transition with skipped warn gates (force=true)"
933                        );
934                        skipped_status_gates = warn_gates.clone();
935                        gate_warnings.push(format!(
936                            "Proceeding despite unsatisfied gates (force=true): {}",
937                            warn_gates.join(", ")
938                        ));
939                    }
940                    "pass" => {
941                        // All gates satisfied - check for allow-level warnings
942                        let allow_gates: Vec<String> = gate_result
943                            .unsatisfied_gates
944                            .iter()
945                            .filter(|g| g.enforcement == GateEnforcement::Allow)
946                            .map(|g| format!("{} ({})", g.gate_type, g.description))
947                            .collect();
948                        if !allow_gates.is_empty() {
949                            gate_warnings.push(format!(
950                                "Optional gates not satisfied: {}",
951                                allow_gates.join(", ")
952                            ));
953                        }
954                    }
955                    _ => {}
956                }
957            }
958        }
959    }
960
961    // Check exit gates for phase transitions
962    if let Some(ref new_phase) = phase {
963        // Get current task to check if phase is actually changing
964        // Note: We may have already fetched the task for status gate checking,
965        // but we fetch again to ensure we have fresh data and to handle cases
966        // where only phase is changing (not status)
967        let current_task = db.get_task(&task_id)?.ok_or_else(|| {
968            ToolError::new(crate::error::ErrorCode::TaskNotFound, "Task not found")
969        })?;
970
971        // Only check gates if there's a current phase AND it's different from new phase
972        if let Some(ref current_phase) = current_task.phase {
973            if current_phase != new_phase {
974                // Phase is changing - check exit gates for the CURRENT phase
975                let exit_gates = workflows.get_phase_exit_gates(current_phase);
976
977                if !exit_gates.is_empty() {
978                    // Convert references to owned GateDefinitions for evaluate_gates
979                    let gates_owned: Vec<crate::config::GateDefinition> =
980                        exit_gates.iter().map(|g| (*g).clone()).collect();
981                    let gate_result = evaluate_gates(db, &task_id, &gates_owned)?;
982
983                    match gate_result.status.as_str() {
984                        "fail" => {
985                            // Reject-level gates unsatisfied - cannot proceed
986                            let gate_names: Vec<String> = gate_result
987                                .unsatisfied_gates
988                                .iter()
989                                .filter(|g| g.enforcement == GateEnforcement::Reject)
990                                .map(|g| format!("{} ({})", g.gate_type, g.description))
991                                .collect();
992                            return Err(ToolError::new(
993                                crate::error::ErrorCode::GatesNotSatisfied,
994                                format!(
995                                    "Cannot exit phase '{}': unsatisfied gates: {}",
996                                    current_phase,
997                                    gate_names.join(", ")
998                                ),
999                            )
1000                            .into());
1001                        }
1002                        "warn" => {
1003                            // Warn-level gates unsatisfied
1004                            let warn_gates: Vec<String> = gate_result
1005                                .unsatisfied_gates
1006                                .iter()
1007                                .filter(|g| g.enforcement == GateEnforcement::Warn)
1008                                .map(|g| format!("{} ({})", g.gate_type, g.description))
1009                                .collect();
1010
1011                            if !force {
1012                                // Cannot proceed without force flag
1013                                return Err(ToolError::new(
1014                                    crate::error::ErrorCode::GatesNotSatisfied,
1015                                    format!(
1016                                        "Cannot exit phase '{}' without force=true: unsatisfied gates: {}",
1017                                        current_phase,
1018                                        warn_gates.join(", ")
1019                                    ),
1020                                )
1021                                .into());
1022                            }
1023                            // force=true: proceed but include warning and log for audit
1024                            warn!(
1025                                task_id = %task_id,
1026                                agent = %worker_id,
1027                                from_phase = %current_phase,
1028                                to_phase = %new_phase,
1029                                skipped_gates = ?warn_gates,
1030                                "Phase transition with skipped warn gates (force=true)"
1031                            );
1032                            skipped_phase_gates = warn_gates.clone();
1033                            gate_warnings.push(format!(
1034                                "Proceeding despite unsatisfied phase gates (force=true): {}",
1035                                warn_gates.join(", ")
1036                            ));
1037                        }
1038                        "pass" => {
1039                            // All gates satisfied - check for allow-level warnings
1040                            let allow_gates: Vec<String> = gate_result
1041                                .unsatisfied_gates
1042                                .iter()
1043                                .filter(|g| g.enforcement == GateEnforcement::Allow)
1044                                .map(|g| format!("{} ({})", g.gate_type, g.description))
1045                                .collect();
1046                            if !allow_gates.is_empty() {
1047                                gate_warnings.push(format!(
1048                                    "Optional phase gates not satisfied: {}",
1049                                    allow_gates.join(", ")
1050                                ));
1051                            }
1052                        }
1053                        _ => {}
1054                    }
1055                }
1056            }
1057        }
1058    }
1059
1060    // Build audit reason including any skipped gates
1061    let audit_reason = {
1062        let mut parts: Vec<String> = Vec::new();
1063
1064        // Include original reason if provided
1065        if let Some(ref r) = reason {
1066            parts.push(r.clone());
1067        }
1068
1069        // Include skipped status gates for audit
1070        if !skipped_status_gates.is_empty() {
1071            parts.push(format!(
1072                "Skipped status exit gates (force=true): {}",
1073                skipped_status_gates.join(", ")
1074            ));
1075        }
1076
1077        // Include skipped phase gates for audit
1078        if !skipped_phase_gates.is_empty() {
1079            parts.push(format!(
1080                "Skipped phase exit gates (force=true): {}",
1081                skipped_phase_gates.join(", ")
1082            ));
1083        }
1084
1085        if parts.is_empty() {
1086            None
1087        } else {
1088            Some(parts.join("; "))
1089        }
1090    };
1091
1092    // Perform the task update
1093    let (task, unblocked, auto_advanced) = db.update_task_unified(
1094        &task_id,
1095        &worker_id,
1096        assignee.as_deref(),
1097        title,
1098        description,
1099        status,
1100        phase,
1101        priority,
1102        points,
1103        tags,
1104        needed_tags,
1105        wanted_tags,
1106        time_estimate_ms,
1107        audit_reason,
1108        force,
1109        states_config,
1110        deps_config,
1111        auto_advance,
1112    )?;
1113
1114    // Get transition prompts if status or phase may have changed
1115    // We update the worker's last seen state and get any matching prompts
1116    let transition_prompt_list: Vec<String> = {
1117        // Update worker state and get old state for prompt calculation
1118        match db.update_worker_state(&worker_id, Some(&task.status), task.phase.as_deref()) {
1119            Ok((old_status, old_phase)) => {
1120                // Create context for template expansion
1121                let ctx = PromptContext::new(
1122                    &task.status,
1123                    task.phase.as_deref(),
1124                    states_config,
1125                    phases_config,
1126                );
1127                // Get prompts for this transition with template expansion
1128                crate::prompts::get_transition_prompts_with_context(
1129                    old_status.as_deref().unwrap_or(""),
1130                    old_phase.as_deref(),
1131                    &task.status,
1132                    task.phase.as_deref(),
1133                    workflows,
1134                    &ctx,
1135                )
1136            }
1137            Err(_) => vec![], // Worker not found or other error - skip prompts
1138        }
1139    };
1140
1141    // Build response with task and unblocked/auto_advanced lists
1142    let mut response = serde_json::to_value(&task)?;
1143    if let Value::Object(ref mut map) = response {
1144        // Always include unblocked if non-empty (tasks now ready to claim)
1145        if !unblocked.is_empty() {
1146            map.insert("unblocked".to_string(), json!(unblocked));
1147        }
1148        // Include auto_advanced if non-empty (tasks that were actually transitioned)
1149        if !auto_advanced.is_empty() {
1150            map.insert("auto_advanced".to_string(), json!(auto_advanced));
1151        }
1152        // Include attachment results if any were added
1153        if !attachment_results.is_empty() {
1154            map.insert("attachments_added".to_string(), json!(attachment_results));
1155        }
1156        // Include warnings if any
1157        if !attachment_warnings.is_empty() {
1158            map.insert(
1159                "attachment_warnings".to_string(),
1160                json!(attachment_warnings),
1161            );
1162        }
1163        // Include phase warning if any
1164        if let Some(ref warning) = phase_warning {
1165            map.insert("phase_warning".to_string(), json!(warning));
1166        }
1167        // Include tag warnings if any
1168        if !tag_warnings.is_empty() {
1169            map.insert("tag_warnings".to_string(), json!(tag_warnings));
1170        }
1171        // Include gate warnings if any
1172        if !gate_warnings.is_empty() {
1173            map.insert("gate_warnings".to_string(), json!(gate_warnings));
1174        }
1175        // Include transition prompts if any
1176        if !transition_prompt_list.is_empty() {
1177            map.insert("prompts".to_string(), json!(transition_prompt_list));
1178        }
1179    }
1180
1181    Ok(response)
1182}
1183
1184pub fn delete(db: &Database, args: Value) -> Result<Value> {
1185    let worker_id =
1186        get_string(&args, "worker_id").ok_or_else(|| ToolError::missing_field("worker_id"))?;
1187    let task_id = get_string(&args, "task").ok_or_else(|| ToolError::missing_field("task"))?;
1188    let cascade = get_bool(&args, "cascade").unwrap_or(false);
1189    let reason = get_string(&args, "reason");
1190    let obliterate = get_bool(&args, "obliterate").unwrap_or(false);
1191    let force = get_bool(&args, "force").unwrap_or(false);
1192
1193    db.delete_task(&task_id, &worker_id, cascade, reason, obliterate, force)?;
1194
1195    Ok(json!({
1196        "success": true,
1197        "soft_deleted": !obliterate
1198    }))
1199}
1200
1201pub fn scan(db: &Database, default_format: OutputFormat, args: Value) -> Result<Value> {
1202    let task_id = get_string(&args, "task").ok_or_else(|| ToolError::missing_field("task"))?;
1203    let format = get_string(&args, "format")
1204        .and_then(|s| OutputFormat::parse(&s))
1205        .unwrap_or(default_format);
1206
1207    // Depth parameters: 0=none, N=levels, -1=all
1208    let before_depth = get_i32(&args, "before").unwrap_or(0);
1209    let after_depth = get_i32(&args, "after").unwrap_or(0);
1210    let above_depth = get_i32(&args, "above").unwrap_or(0);
1211    let below_depth = get_i32(&args, "below").unwrap_or(0);
1212
1213    // Verify the task exists
1214    let root_task = db
1215        .get_task(&task_id)?
1216        .ok_or_else(|| ToolError::new(crate::error::ErrorCode::TaskNotFound, "Task not found"))?;
1217
1218    // Traverse in each direction
1219    let before = db.get_predecessors(&task_id, before_depth)?;
1220    let after = db.get_successors(&task_id, after_depth)?;
1221    let above = db.get_ancestors(&task_id, above_depth)?;
1222    let below = db.get_descendants(&task_id, below_depth)?;
1223
1224    let result = ScanResult {
1225        root: root_task,
1226        before,
1227        after,
1228        above,
1229        below,
1230    };
1231
1232    match format {
1233        OutputFormat::Markdown => Ok(markdown_to_json(format_scan_result_markdown(&result))),
1234        OutputFormat::Json => Ok(serde_json::to_value(&result)?),
1235    }
1236}