1use super::planning_task_tracker::{PlanningTaskTrackerArgs, PlanningTaskTrackerTool};
16use super::planning_workflow::{PlanningWorkflowState, plan_file_for_tracker_file, tracker_file_for_plan_file};
17use std::str::FromStr;
18
19use crate::config::constants::tools;
20use crate::tools::error_helpers::deserialize_tool_args;
21use crate::tools::handlers::task_tracking::{
22 TASK_ITEMS_DESCRIPTION, TaskCounts, TaskItemInput, TaskMetadataRef, TaskStepMetadata, TaskTrackingStatus,
23 TaskTreeNode, TrackerArtifact, append_notes, append_notes_section, append_task_step_metadata, apply_metadata_input,
24 apply_metadata_line, compact_task_tree_view, is_bulk_sync_update, metadata_from_input, normalize_optional_text,
25 parse_marked_status_prefix, parse_status_prefix, parse_task_items, persist_tracker_artifacts,
26 task_files_property_schema, task_items_array_schema, task_status_property_schema, task_verify_property_schema,
27 tracker_schema_allof, validate_action_index_fields, validate_update_shape, write_tracker_artifact,
28};
29use crate::utils::file_utils::{ensure_dir_exists, read_file_with_context};
30use anyhow::{Context, Result, bail};
31use async_trait::async_trait;
32use serde::{Deserialize, Serialize};
33use serde_json::{Value, json};
34use std::fmt::Write as _;
35use std::path::{Path, PathBuf};
36use vtcode_commons::workspace_relative_display;
37
38use crate::tools::traits::Tool;
39
40pub type TaskStatus = TaskTrackingStatus;
41
42#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
44pub struct TaskItem {
45 pub index: usize,
46 pub description: String,
47 pub status: TaskStatus,
48 #[serde(default, flatten)]
49 pub metadata: TaskStepMetadata,
50}
51
52#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
54pub struct TaskChecklist {
55 pub title: String,
56 pub items: Vec<TaskItem>,
57 #[serde(skip_serializing_if = "Option::is_none")]
58 pub notes: Option<String>,
59}
60
61impl TaskChecklist {
62 fn to_markdown(&self) -> String {
63 let mut md = format!("# {}\n\n", self.title);
64 for item in &self.items {
65 let _ = writeln!(md, "- {} {}", item.status.flat_checkbox(), item.description);
66 append_task_step_metadata(&mut md, "", &item.metadata);
67 }
68 append_notes_section(&mut md, self.notes.as_deref());
69 md
70 }
71
72 fn to_plan_markdown(&self) -> String {
73 let mut md = format!("# {}\n\n## Plan of Work\n\n", self.title);
74 for item in &self.items {
75 let trimmed = item.description.trim_start();
76 let indent = &item.description[..item.description.len() - trimmed.len()];
77 let _ = writeln!(md, "{}- {} {}", indent, item.status.plan_checkbox(), trimmed);
78 append_task_step_metadata(&mut md, indent, &item.metadata);
79 }
80 append_notes_section(&mut md, self.notes.as_deref());
81 md
82 }
83
84 fn summary(&self) -> Value {
85 let mut counts = TaskCounts::default();
86 for item in &self.items {
87 counts.add(&item.status);
88 }
89
90 json!({
91 "title": self.title,
92 "total": counts.total,
93 "completed": counts.completed,
94 "in_progress": counts.in_progress,
95 "pending": counts.pending,
96 "blocked": counts.blocked,
97 "progress_percent": counts.progress_percent(),
98 "items": self.items.iter().map(|item| {
99 json!({
100 "index": item.index,
101 "description": item.description,
102 "status": item.status.to_string(),
103 "files": item.metadata.files.clone(),
104 "outcome": item.metadata.outcome.clone(),
105 "verify": item.metadata.verify.clone(),
106 "scope_review": item.metadata.scope_review.clone(),
107 })
108 }).collect::<Vec<_>>()
109 ,
110 "notes": self.notes.clone(),
111 })
112 }
113
114 fn view(&self) -> Value {
115 let nodes = self
116 .items
117 .iter()
118 .map(|item| TaskTreeNode {
119 index_path: item.index.to_string(),
120 description: item.description.clone(),
121 status: item.status,
122 metadata: item.metadata.clone(),
123 children: Vec::new(),
124 })
125 .collect::<Vec<_>>();
126
127 json!({
128 "title": self.title,
129 "lines": compact_task_tree_view(&nodes),
130 })
131 }
132}
133
134fn parse_input_items(items: &[TaskItemInput], previous: &[TaskItem]) -> Result<Vec<TaskItem>> {
135 let previous_metadata: Vec<_> = previous
136 .iter()
137 .map(|item| TaskMetadataRef {
138 description: &item.description,
139 metadata: &item.metadata,
140 })
141 .collect();
142 Ok(parse_task_items(items, &previous_metadata)?
143 .into_iter()
144 .enumerate()
145 .map(|(idx, item)| TaskItem {
146 index: idx + 1,
147 description: item.description,
148 status: item.status,
149 metadata: item.metadata,
150 })
151 .collect())
152}
153
154fn parse_single_index_from_path(index_path: &str) -> Result<usize> {
155 let mut parts = index_path.trim().split('.');
156 let first = parts.next().context("index_path cannot be empty")?;
157 if parts.next().is_some() {
158 bail!(
159 "Hierarchical index_path '{index_path}' requires Planning workflow support. Use 'index' for standard task-tracker updates or switch to Planning workflow."
160 );
161 }
162 let parsed = first
163 .parse::<usize>()
164 .with_context(|| format!("Invalid index_path '{index_path}': expected integer"))?;
165 if parsed == 0 {
166 bail!("index_path must be >= 1");
167 }
168 Ok(parsed)
169}
170
171fn parse_plan_mirror_markdown(content: &str) -> Option<TaskChecklist> {
172 let mut title = String::new();
173 let mut items: Vec<TaskItem> = Vec::new();
174 let mut notes_lines = Vec::new();
175 let mut in_notes = false;
176 let mut in_verify_block = false;
177 let mut idx = 1usize;
178
179 for raw in content.lines() {
180 let trimmed = raw.trim();
181
182 if title.is_empty()
183 && let Some(rest) = trimmed.strip_prefix("# ")
184 {
185 title = rest.trim().to_string();
186 continue;
187 }
188
189 if trimmed == "## Notes" {
190 in_notes = true;
191 continue;
192 }
193
194 if let Some(header) = trimmed.strip_prefix("## ") {
195 let lowered = header.trim().to_ascii_lowercase();
196 in_notes = lowered == "notes";
197 continue;
198 }
199
200 if in_notes {
201 notes_lines.push(raw.to_string());
202 continue;
203 }
204
205 if let Some(last) = items.last_mut() {
206 let indent = raw.chars().take_while(|c| *c == ' ').count();
207 if indent >= 2 && apply_metadata_line(&mut last.metadata, raw, &mut in_verify_block) {
208 continue;
209 }
210 in_verify_block = false;
211 }
212
213 let Some(rest) = trimmed
214 .strip_prefix("- ")
215 .or_else(|| trimmed.strip_prefix("* "))
216 .or_else(|| trimmed.strip_prefix("+ "))
217 else {
218 continue;
219 };
220
221 if let Some((status, description)) = parse_marked_status_prefix(rest) {
222 let leading_spaces = raw.chars().take_while(|c| *c == ' ').count();
223 let description = format!("{}{}", " ".repeat(leading_spaces), description.trim());
224 items.push(TaskItem {
225 index: idx,
226 description,
227 status,
228 metadata: TaskStepMetadata::default(),
229 });
230 idx += 1;
231 in_verify_block = false;
232 }
233 }
234
235 if title.is_empty() && items.is_empty() {
236 return None;
237 }
238
239 let notes = if notes_lines.is_empty() {
240 None
241 } else {
242 Some(notes_lines.join("\n").trim().to_string())
243 };
244
245 Some(TaskChecklist { title, items, notes })
246}
247
248fn newer_source(
249 global_modified: Option<std::time::SystemTime>,
250 plan_modified: Option<std::time::SystemTime>,
251 planning_active: bool,
252) -> TrackerSource {
253 if planning_active {
254 return if plan_modified.is_some() {
255 TrackerSource::Plan
256 } else {
257 TrackerSource::Global
258 };
259 }
260
261 match (global_modified, plan_modified) {
262 (Some(global), Some(plan)) => {
263 if global > plan {
264 TrackerSource::Global
265 } else if plan > global {
266 TrackerSource::Plan
267 } else {
268 TrackerSource::Global
269 }
270 }
271 (Some(_), None) => TrackerSource::Global,
272 (None, Some(_)) => TrackerSource::Plan,
273 (None, None) => {
274 if planning_active {
275 TrackerSource::Plan
276 } else {
277 TrackerSource::Global
278 }
279 }
280 }
281}
282
283#[derive(Debug, Clone, Copy, PartialEq, Eq)]
284enum TrackerSource {
285 Global,
286 Plan,
287}
288
289#[derive(Debug, Clone, Serialize, Deserialize)]
291pub struct TaskTrackerArgs {
292 pub action: String,
294
295 #[serde(default)]
297 pub title: Option<String>,
298
299 #[serde(default)]
301 pub items: Option<Vec<TaskItemInput>>,
302
303 #[serde(default)]
305 pub index: Option<usize>,
306
307 #[serde(default)]
309 pub index_path: Option<String>,
310
311 #[serde(default)]
313 pub status: Option<String>,
314
315 #[serde(default)]
317 pub description: Option<String>,
318
319 #[serde(default)]
321 pub files: Option<Vec<String>>,
322
323 #[serde(default)]
325 pub outcome: Option<String>,
326
327 #[serde(
329 default,
330 deserialize_with = "crate::tools::handlers::task_tracking::deserialize_optional_string_list"
331 )]
332 pub verify: Option<Vec<String>>,
333
334 #[serde(default)]
336 pub parent_index_path: Option<String>,
337
338 #[serde(default)]
340 pub notes: Option<String>,
341}
342
343pub struct TaskTrackerTool {
345 workspace_root: PathBuf,
346 planning_workflow_state: PlanningWorkflowState,
347}
348
349fn standard_task_tracker_parameter_schema() -> Value {
350 json!({
351 "type": "object",
352 "properties": {
353 "action": {
354 "type": "string",
355 "enum": ["create", "update", "list", "add"],
356 "description": "Action to perform on the task checklist."
357 },
358 "title": {
359 "type": "string",
360 "description": "Title for the checklist (used with 'create')."
361 },
362 "items": task_items_array_schema(TASK_ITEMS_DESCRIPTION),
363 "index": {
364 "type": "integer",
365 "minimum": 0,
366 "description": "Action=update only: use a 1-based item index. index: 0 is reserved for standard checklist-level completion and is valid only with action: update and status: completed."
367 },
368 "index_path": {
369 "type": "string",
370 "pattern": "^[1-9][0-9]*$",
371 "description": "Action=update only: positive flat index path for compatibility (example: '2'). Hierarchical paths are accepted only by Planning workflow."
372 },
373 "status": task_status_property_schema("New status for the item (used with single-item 'update')."),
374 "description": {
375 "type": "string",
376 "description": "Description for a new item (used with 'add')."
377 },
378 "files": task_files_property_schema("Optional file paths associated with a single add/update item."),
379 "outcome": {
380 "type": "string",
381 "description": "Optional expected outcome associated with a single add/update item."
382 },
383 "verify": task_verify_property_schema("Optional verification command or commands associated with a single add/update item."),
384 "parent_index_path": {
385 "type": "string",
386 "description": "Optional parent path for add in Planning workflow (example: '2')."
387 },
388 "notes": {
389 "type": "string",
390 "description": "Optional notes to append to the checklist."
391 }
392 },
393 "required": ["action"],
394 "allOf": tracker_schema_allof(true)
395 })
396}
397
398pub(crate) fn task_tracker_description_for_workflow(planning_active: bool) -> &'static str {
399 if planning_active {
400 "Adaptive task tracking for planning. Persists hierarchical plan progress under .vtcode/plans/<plan>.tasks.md and mirrors updates to .vtcode/tasks/current_task.md. Actions: create, update, list, add. Calling action=create again replaces the plan task list and its progress; use action=update or action=add to change it. For action=update, planning item indices are positive 1-based flat or hierarchical index_path values; index: 0 is invalid. Use items only to replace the full checklist with descriptions and explicit statuses, not indexed updates or JSON-encoded strings. Minimal calls: {\"action\":\"list\"}; {\"action\":\"update\",\"index\":1,\"status\":\"in_progress\"}; {\"action\":\"update\",\"items\":[\"[x] Done\",\"[ ] Remaining\"]}. List uses only action; choose one of index, index_path, or items for update; omit unused fields."
401 } else {
402 "Track task progress through a single checklist API (action: create | update | list | add). Use action=create to start a multi-step plan; action=update as work progresses; action=list to review state. For action=update, item indices are 1-based; checklist-level completion alone may use index: 0 with status: completed. Planning workflow accepts only positive flat or hierarchical index paths. Use items only to replace the full checklist with descriptions and explicit statuses, not indexed updates or JSON-encoded strings. Minimal calls: {\"action\":\"list\"}; {\"action\":\"update\",\"index\":1,\"status\":\"in_progress\"}; {\"action\":\"update\",\"items\":[\"[x] Done\",\"[ ] Remaining\"]}. List uses only action; choose one of index, index_path, or items for update; omit unused fields. Calling action=create again replaces the checklist unless title and items match the active one (a no-op); use action=update or action=add to change it. Tracker state mirrors .vtcode/tasks/current_task.md and active plan sidecars when available."
403 }
404}
405
406pub(crate) fn task_tracker_parameter_schema_for_workflow(planning_active: bool) -> Value {
407 if planning_active {
408 super::planning_task_tracker::planning_task_tracker_parameter_schema()
409 } else {
410 standard_task_tracker_parameter_schema()
411 }
412}
413
414pub const TASK_TRACKER_ARGUMENT_CORRECTION: &str = r#"Invalid task_tracker shape. List: {"action":"list"}. Individual update: {"action":"update","index":1,"status":"in_progress"} OR {"action":"update","index_path":"2.1","status":"completed"} (planning). Bulk replacement: {"action":"update","items":["[x] Done","[ ] Remaining"]}. For create, index/index_path are forbidden (use title/items); add uses description; list/add also forbid index/index_path. Never combine index with index_path or items; omit unused fields and retry once."#;
428
429pub(crate) fn is_task_tracker_shape_error(error_msg: &str) -> bool {
435 const MARKERS: [&str; 6] = [
436 "must not include",
437 "does not match any allowed shape",
438 "matches more than one allowed shape",
439 "is forbidden by schema",
440 "missing required property",
441 "failed validation (schema",
442 ];
443 MARKERS.iter().any(|marker| error_msg.contains(marker))
444}
445
446impl TaskTrackerTool {
447 pub fn new(workspace_root: PathBuf, planning_workflow_state: PlanningWorkflowState) -> Self {
448 Self { workspace_root, planning_workflow_state }
449 }
450
451 fn tasks_dir(&self) -> PathBuf {
452 self.workspace_root.join(".vtcode").join("tasks")
453 }
454
455 fn task_file(&self) -> PathBuf {
456 self.tasks_dir().join("current_task.md")
457 }
458
459 fn display_path(&self, path: &Path) -> String {
460 workspace_relative_display(&self.workspace_root, path)
461 }
462
463 async fn plan_task_file(&self) -> Option<PathBuf> {
464 let plan_file = self.planning_workflow_state.get_plan_file()?;
465 tracker_file_for_plan_file(&plan_file)
466 }
467
468 async fn save_checklist(&self, checklist: &TaskChecklist) -> Result<()> {
469 let dir = self.tasks_dir();
470 ensure_dir_exists(&dir)
471 .await
472 .with_context(|| format!("Failed to create tasks directory: {}", dir.display()))?;
473 let md = checklist.to_markdown();
474 write_tracker_artifact(&self.task_file(), &md, "task checklist")
475 .await
476 .with_context(|| "Failed to write task checklist")?;
477 Ok(())
478 }
479
480 async fn save_plan_mirror_to_file(&self, tracker_file: &Path, checklist: &TaskChecklist) -> Result<()> {
481 persist_tracker_artifacts(Self::plan_mirror_artifacts(tracker_file, checklist).await?).await
482 }
483
484 async fn plan_mirror_artifacts(tracker_file: &Path, checklist: &TaskChecklist) -> Result<Vec<TrackerArtifact>> {
485 let markdown = checklist.to_plan_markdown();
486 let mut artifacts =
487 vec![TrackerArtifact::new(tracker_file.to_path_buf(), markdown.clone(), "plan task tracker file").await?];
488 if let Some(plan_file) = plan_file_for_tracker_file(tracker_file)
489 && let Some(artifact) = TrackerArtifact::embedded_plan(plan_file, &markdown).await?
490 {
491 artifacts.push(artifact);
492 }
493 Ok(artifacts)
494 }
495
496 async fn load_global_checklist(&self) -> Result<Option<TaskChecklist>> {
497 let file = self.task_file();
498 if !tokio::fs::try_exists(&file).await.unwrap_or(false) {
499 return Ok(None);
500 }
501 let content = read_file_with_context(&file, "task checklist").await?;
502
503 let mut title = String::new();
504 let mut items: Vec<TaskItem> = Vec::new();
505 let mut notes_lines = Vec::new();
506 let mut in_notes = false;
507 let mut in_verify_block = false;
508 let mut idx = 1;
509
510 for line in content.lines() {
511 let trimmed = line.trim();
512 if trimmed.starts_with("# ") && title.is_empty() {
513 title = trimmed.trim_prefix("# ").to_string();
514 continue;
515 }
516 if trimmed == "## Notes" {
517 in_notes = true;
518 continue;
519 }
520 if in_notes {
521 notes_lines.push(line.to_string());
522 continue;
523 }
524 if let Some(last) = items.last_mut() {
525 let indent = line.chars().take_while(|c| *c == ' ').count();
526 if indent >= 2 && apply_metadata_line(&mut last.metadata, line, &mut in_verify_block) {
527 continue;
528 }
529 in_verify_block = false;
530 }
531 if let Some(rest) = trimmed.strip_prefix("- ")
532 && let Some((status, description)) = parse_marked_status_prefix(rest)
533 {
534 items.push(TaskItem {
535 index: idx,
536 description,
537 status,
538 metadata: TaskStepMetadata::default(),
539 });
540 idx += 1;
541 in_verify_block = false;
542 }
543 }
544
545 if title.is_empty() && items.is_empty() {
546 return Ok(None);
547 }
548
549 let notes = if notes_lines.is_empty() {
550 None
551 } else {
552 Some(notes_lines.join("\n").trim().to_string())
553 };
554
555 Ok(Some(TaskChecklist { title, items, notes }))
556 }
557
558 async fn load_plan_checklist_from(&self, tracker_file: &Path) -> Result<Option<TaskChecklist>> {
559 if !tokio::fs::try_exists(tracker_file).await.unwrap_or(false) {
560 return Ok(None);
561 }
562 let content = read_file_with_context(tracker_file, "plan task tracker file").await?;
563 Ok(parse_plan_mirror_markdown(&content))
564 }
565
566 async fn load_preferred_checklist(&self) -> Result<Option<TaskChecklist>> {
567 let task_file = self.task_file();
568 let plan_file = self.plan_task_file().await;
569
570 let global_exists = tokio::fs::try_exists(&task_file).await.unwrap_or(false);
571 let plan_exists = match plan_file.as_ref() {
572 Some(path) => tokio::fs::try_exists(path).await.unwrap_or(false),
573 None => false,
574 };
575
576 if !global_exists && !plan_exists {
577 return Ok(None);
578 }
579
580 let selected = if global_exists && plan_exists {
581 let global_modified = tokio::fs::metadata(&task_file).await.ok().and_then(|meta| meta.modified().ok());
582 let plan_modified = match &plan_file {
583 Some(path) => tokio::fs::metadata(path).await.ok().and_then(|meta| meta.modified().ok()),
584 None => None,
585 };
586 newer_source(global_modified, plan_modified, self.planning_workflow_state.is_active())
587 } else if plan_exists {
588 TrackerSource::Plan
589 } else {
590 TrackerSource::Global
591 };
592
593 let loaded = match selected {
594 TrackerSource::Global => self.load_global_checklist().await?,
595 TrackerSource::Plan => {
596 if let Some(path) = plan_file.as_ref() {
597 self.load_plan_checklist_from(path).await?
598 } else {
599 None
600 }
601 }
602 };
603
604 if let Some(checklist) = loaded.as_ref() {
605 match selected {
606 TrackerSource::Global => {
607 if let Some(path) = plan_file.as_ref() {
608 self.save_plan_mirror_to_file(path, checklist).await?;
609 }
610 }
611 TrackerSource::Plan => {
612 self.save_checklist(checklist).await?;
613 }
614 }
615 }
616
617 Ok(loaded)
618 }
619
620 async fn persist_edit_mode_snapshot(&self, checklist: &TaskChecklist) -> Result<()> {
621 let mut artifacts =
622 vec![TrackerArtifact::new(self.task_file(), checklist.to_markdown(), "task checklist").await?];
623 if let Some(tracker_file) = self.plan_task_file().await {
624 artifacts.extend(Self::plan_mirror_artifacts(&tracker_file, checklist).await?);
625 }
626 persist_tracker_artifacts(artifacts).await
627 }
628
629 async fn persist_and_build_view(&self, checklist: &TaskChecklist) -> Result<(Value, Value)> {
630 self.persist_edit_mode_snapshot(checklist).await?;
631 Ok((checklist.summary(), checklist.view()))
632 }
633
634 async fn persist_update(
635 &self,
636 previous: Option<&TaskChecklist>,
637 checklist: &TaskChecklist,
638 message: String,
639 ) -> Result<Value> {
640 let unchanged = previous == Some(checklist);
641 if !unchanged {
642 self.persist_edit_mode_snapshot(checklist).await?;
643 }
644 Ok(json!({
645 "status": if unchanged { "unchanged" } else { "updated" },
646 "message": if unchanged { "Checklist already matches requested state.".to_string() } else { message },
647 "checklist": checklist.summary(),
648 "view": checklist.view(),
649 }))
650 }
651
652 fn to_plan_args(args: &TaskTrackerArgs) -> PlanningTaskTrackerArgs {
653 PlanningTaskTrackerArgs {
654 action: args.action.clone(),
655 title: args.title.clone(),
656 items: args.items.clone(),
657 index: args.index,
658 index_path: args.index_path.clone(),
659 status: args.status.clone(),
660 description: args.description.clone(),
661 files: args.files.clone(),
662 outcome: args.outcome.clone(),
663 verify: args.verify.clone(),
664 parent_index_path: args.parent_index_path.clone(),
665 notes: args.notes.clone(),
666 }
667 }
668
669 async fn execute_in_planning_workflow(&self, args: &TaskTrackerArgs) -> Result<Value> {
670 let plan_tool = PlanningTaskTrackerTool::new(self.planning_workflow_state.clone());
671 let mapped = Self::to_plan_args(args);
672 plan_tool.execute(serde_json::to_value(mapped)?).await
673 }
674
675 fn check_create_idempotency(
680 existing: &TaskChecklist,
681 title: &str,
682 items: &[TaskItem],
683 task_file_display: &str,
684 ) -> Option<Value> {
685 let same_structure = existing.title == title
686 && existing.items.len() == items.len()
687 && existing
688 .items
689 .iter()
690 .zip(items.iter())
691 .all(|(left, right)| left.description == right.description);
692 let requested_has_explicit_status = items.iter().any(|item| item.status != TaskStatus::Pending);
693 let requested_has_step_metadata = items.iter().any(|item| {
694 !item.metadata.files.is_empty()
695 || item.metadata.outcome.is_some()
696 || !item.metadata.verify.is_empty()
697 || !item.metadata.scope_review.is_empty()
698 });
699
700 let unchanged = if same_structure && !requested_has_explicit_status && !requested_has_step_metadata {
701 Some("Checklist already active; preserved current progress.")
702 } else if existing.title == title
703 && existing.items.len() == items.len()
704 && existing.items.iter().zip(items.iter()).all(|(l, r)| l == r)
705 {
706 Some("Requested checklist already matches current tracker state.")
707 } else {
708 None
709 };
710
711 unchanged.map(|message| {
712 json!({
713 "status": "unchanged",
714 "message": message,
715 "task_file": task_file_display,
716 "checklist": existing.summary(),
717 "view": existing.view()
718 })
719 })
720 }
721
722 async fn handle_create(&self, args: &TaskTrackerArgs) -> Result<Value> {
723 let title = args.title.as_deref().unwrap_or("Task Checklist").to_string();
724 let item_descs = args.items.as_deref().unwrap_or(&[]);
725 if item_descs.is_empty() {
726 anyhow::bail!("At least one item is required for 'create'. Provide items: [\"step 1\", \"step 2\", ...]");
727 }
728
729 let items = parse_input_items(item_descs, &[])?;
730 if items.is_empty() {
731 anyhow::bail!("No valid task items were provided for create.");
732 }
733 let notes = append_notes(None, args.notes.as_deref());
734
735 let existing_checklist = self.load_preferred_checklist().await?;
736 let mut existing_item_count = 0usize;
737 if let Some(existing) = existing_checklist.as_ref() {
738 existing_item_count = existing.items.len();
739 if let Some(unchanged) =
740 Self::check_create_idempotency(existing, &title, &items, &self.display_path(&self.task_file()))
741 {
742 return Ok(unchanged);
743 }
744 }
745
746 let checklist = TaskChecklist { title, items, notes };
747
748 let (summary, view) = self.persist_and_build_view(&checklist).await?;
749
750 let (status, message) = if existing_item_count > 0 {
751 (
752 "replaced",
753 format!("Previous checklist replaced with new structure (was {existing_item_count} items).",),
754 )
755 } else {
756 ("created", "Task checklist created successfully.".to_string())
757 };
758
759 Ok(json!({
760 "status": status,
761 "message": message,
762 "task_file": self.display_path(&self.task_file()),
763 "checklist": summary,
764 "view": view
765 }))
766 }
767
768 async fn handle_update(&self, args: &TaskTrackerArgs) -> Result<Value> {
769 validate_update_shape(args.items.as_deref(), args.index, args.index_path.as_deref(), args.status.as_deref())?;
770 let is_bulk_update =
771 is_bulk_sync_update(args.items.as_deref(), args.index, args.index_path.as_deref(), args.status.as_deref());
772 let mut current = self.load_preferred_checklist().await?;
773 let previous = current.clone();
774 if is_bulk_update {
775 let input_items = args.items.as_deref().unwrap_or(&[]);
776 let items = parse_input_items(
777 input_items,
778 current.as_ref().map(|checklist| checklist.items.as_slice()).unwrap_or(&[]),
779 )?;
780 if items.is_empty() {
781 anyhow::bail!("No valid items provided for checklist sync.");
782 }
783
784 let title = args
785 .title
786 .clone()
787 .or_else(|| current.as_ref().map(|checklist| checklist.title.clone()))
788 .unwrap_or_else(|| "Task Checklist".to_string());
789
790 let checklist = current.get_or_insert(TaskChecklist {
791 title: title.clone(),
792 items: Vec::new(),
793 notes: None,
794 });
795
796 checklist.title = title;
797 checklist.items = items;
798 checklist.notes = append_notes(checklist.notes.take(), args.notes.as_deref());
799 let snapshot = checklist.clone();
800 return self
801 .persist_update(previous.as_ref(), &snapshot, "Checklist synchronized from provided items.".to_string())
802 .await;
803 }
804
805 let checklist = current.as_mut().context("No active checklist. Use action='create' first.")?;
806
807 let index = match (args.index, args.index_path.as_deref()) {
808 (Some(idx), _) => idx,
809 (None, Some(path)) => parse_single_index_from_path(path)?,
810 (None, None) => {
811 bail!(
812 "'index' is required for 'update' (1-indexed), or provide 'index_path' for Planning workflow updates, or 'items' for bulk sync"
813 )
814 }
815 };
816
817 let status_str = args
818 .status
819 .as_deref()
820 .context("'status' is required for 'update' (pending|in_progress|completed|blocked), or provide 'items' for bulk sync")?;
821
822 let new_status = TaskStatus::from_str(status_str)?;
823
824 if index == 0 {
825 if new_status != TaskStatus::Completed {
826 bail!("index 0 is reserved for checklist-level completion; individual item indices are 1-indexed");
827 }
828
829 if let Some(outcome) = normalize_optional_text(args.outcome.as_deref()) {
830 let checklist_outcome = format!("Checklist outcome: {outcome}");
831 checklist.notes = append_notes(checklist.notes.take(), Some(checklist_outcome.as_str()));
832 }
833 checklist.notes = append_notes(checklist.notes.take(), args.notes.as_deref());
834
835 let snapshot = checklist.clone();
836 return self
837 .persist_update(
838 previous.as_ref(),
839 &snapshot,
840 "Checklist-level completion acknowledged; checklist progress remains derived from item statuses."
841 .to_string(),
842 )
843 .await;
844 }
845
846 let item_count = checklist.items.len();
847 let pos = checklist
848 .items
849 .iter()
850 .position(|i| i.index == index)
851 .with_context(|| format!("No item at index {index}. Valid range: 1-{item_count}"))?;
852
853 let old_status = checklist.items[pos].status.to_string();
854 checklist.items[pos].status = new_status;
855 let new_status_str = checklist.items[pos].status.to_string();
856 apply_metadata_input(
857 &mut checklist.items[pos].metadata,
858 args.files.as_deref(),
859 args.outcome.as_deref(),
860 args.verify.as_deref(),
861 );
862 checklist.notes = append_notes(checklist.notes.take(), args.notes.as_deref());
863
864 let snapshot = checklist.clone();
865 self.persist_update(
866 previous.as_ref(),
867 &snapshot,
868 format!("Item {} status changed: {} → {}", index, old_status, new_status_str),
869 )
870 .await
871 }
872
873 async fn handle_list(&self) -> Result<Value> {
874 match self.load_preferred_checklist().await? {
875 Some(checklist) => Ok(json!({
876 "status": "ok",
877 "checklist": checklist.summary(),
878 "view": checklist.view()
879 })),
880 None => Ok(json!({
881 "status": "empty",
882 "message": "No active checklist. Use action='create' to start one."
883 })),
884 }
885 }
886
887 async fn handle_add(&self, args: &TaskTrackerArgs) -> Result<Value> {
888 if let Some(parent_path) = args.parent_index_path.as_deref()
889 && !parent_path.trim().is_empty()
890 {
891 bail!(
892 "'parent_index_path' is only supported for hierarchical Planning workflow updates. Use Planning workflow or omit parent_index_path for standard task-tracker updates."
893 );
894 }
895
896 let mut checklist = self
897 .load_preferred_checklist()
898 .await?
899 .context("No active checklist. Use action='create' first.")?;
900
901 let desc = args.description.as_deref().context("'description' is required for 'add'")?;
902 let (status, parsed_description) = parse_status_prefix(desc);
903 let description = parsed_description.trim().to_string();
904 if description.is_empty() {
905 bail!("description cannot be empty");
906 }
907
908 let new_index = checklist.items.len() + 1;
909 checklist.items.push(TaskItem {
910 index: new_index,
911 description: description.clone(),
912 status,
913 metadata: metadata_from_input(args.files.as_deref(), args.outcome.as_deref(), args.verify.as_deref()),
914 });
915
916 checklist.notes = append_notes(checklist.notes.take(), args.notes.as_deref());
917 let (summary, view) = self.persist_and_build_view(&checklist).await?;
918
919 Ok(json!({
920 "status": "added",
921 "message": format!("Added item {}: {}", new_index, description),
922 "checklist": summary,
923 "view": view
924 }))
925 }
926}
927
928#[async_trait]
929impl Tool for TaskTrackerTool {
930 async fn execute(&self, args: Value) -> Result<Value> {
931 let args: TaskTrackerArgs = deserialize_tool_args(&args, "task_tracker")?;
932 validate_action_index_fields(&args.action, args.index, args.index_path.as_deref())?;
933
934 if self.planning_workflow_state.is_active() {
935 return self.execute_in_planning_workflow(&args).await;
936 }
937
938 match args.action.as_str() {
939 "create" => self.handle_create(&args).await,
940 "update" => self.handle_update(&args).await,
941 "list" => self.handle_list().await,
942 "add" => self.handle_add(&args).await,
943 other => Ok(json!({
944 "status": "error",
945 "message": format!("Unknown action '{}'. Use: create, update, list, add", other)
946 })),
947 }
948 }
949
950 fn name(&self) -> &str {
951 tools::TASK_TRACKER
952 }
953
954 fn description(&self) -> &str {
955 task_tracker_description_for_workflow(self.planning_workflow_state.is_active())
956 }
957
958 fn parameter_schema(&self) -> Option<Value> {
959 Some(task_tracker_parameter_schema_for_workflow(self.planning_workflow_state.is_active()))
960 }
961
962 fn is_mutating(&self) -> bool {
963 false }
965
966 fn is_parallel_safe(&self) -> bool {
967 false }
969}
970
971#[cfg(test)]
972mod update_regressions;
973
974#[cfg(test)]
975mod tests;