Skip to main content

vtcode_core/tools/handlers/
task_tracker.rs

1//! Task Tracker tool for structured task management during complex sessions.
2//!
3//! Based on NL2Repo-Bench findings: agents that leverage explicit planning
4//! tools achieve significantly better scores. This tool provides a first-class
5//! mechanism for the agent to create, update, and query a task checklist
6//! persisted to `.vtcode/tasks/`.
7//!
8//! ## Actions
9//!
10//! - `create`: Create a new task checklist with a title and list of items
11//! - `update`: Mark a specific task item as completed, in_progress, or pending
12//! - `list`: Show the current task checklist and its status
13//! - `add`: Add a new item to an existing checklist
14
15use 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/// A single task item
43#[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/// The full task checklist
53#[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/// Arguments for the task_tracker tool
290#[derive(Debug, Clone, Serialize, Deserialize)]
291pub struct TaskTrackerArgs {
292    /// Action to perform: create, update, list, add
293    pub action: String,
294
295    /// Title for the checklist (required for `create`)
296    #[serde(default)]
297    pub title: Option<String>,
298
299    /// List of task descriptions (required for `create`)
300    #[serde(default)]
301    pub items: Option<Vec<TaskItemInput>>,
302
303    /// Index of item to update (required for `update`, 1-indexed)
304    #[serde(default)]
305    pub index: Option<usize>,
306
307    /// Hierarchical index path for update (Planning workflow, optional)
308    #[serde(default)]
309    pub index_path: Option<String>,
310
311    /// New status for the item (required for `update`)
312    #[serde(default)]
313    pub status: Option<String>,
314
315    /// Description for a new item (required for `add`)
316    #[serde(default)]
317    pub description: Option<String>,
318
319    /// Optional file paths associated with a step
320    #[serde(default)]
321    pub files: Option<Vec<String>>,
322
323    /// Optional expected outcome associated with a step
324    #[serde(default)]
325    pub outcome: Option<String>,
326
327    /// Optional verification command or commands associated with a step
328    #[serde(
329        default,
330        deserialize_with = "crate::tools::handlers::task_tracking::deserialize_optional_string_list"
331    )]
332    pub verify: Option<Vec<String>>,
333
334    /// Optional parent path for add in Planning workflow (example: "2")
335    #[serde(default)]
336    pub parent_index_path: Option<String>,
337
338    /// Optional notes to append
339    #[serde(default)]
340    pub notes: Option<String>,
341}
342
343/// Task Tracker tool state
344pub 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
414/// Model-facing correction for `task_tracker` shape failures.
415///
416/// The schema uses conditional (`if`/`then`/`not`) rules, so a bare
417/// "required fields" hint is not enough: `create` forbids `index`/`index_path`,
418/// `update` needs exactly one shape, and `add`/`list` have their own shapes.
419/// Without this, a `create` bundled with update fields fails with a generic
420/// root error and the model retries blindly.
421///
422/// Note: the schema only *forbids* `index`/`index_path` on
423/// `create`/`list`/`add`; other single-item fields (`status`, `description`,
424/// `files`, `outcome`, `verify`) are ignored by those actions, not rejected.
425/// The wording below matches that enforced contract: it forbids only what the
426/// schema forbids and recommends (not requires) the minimal shapes.
427pub 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
429/// Whether a `task_tracker` schema error is a shape error (conditional
430/// `if`/`then`/`not`, `anyOf`/`oneOf`, missing required, fallback) rather
431/// than a single-field value error (`enum`, `type`, `const`, ...). The shape
432/// correction above only helps the former; appending it to a bad-enum error
433/// would point the model at the wrong axis.
434pub(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().await?;
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.strip_prefix("# ").unwrap_or(trimmed).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    /// Check if a `create` call is idempotent (same checklist already active).
676    ///
677    /// Returns `Some(unchanged_response)` when the existing checklist should be
678    /// preserved, or `None` when a new checklist must be created.
679    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 // Writes tracker artifacts only (.vtcode/tasks and .vtcode/plans)
964    }
965
966    fn is_parallel_safe(&self) -> bool {
967        false // State management should be sequential
968    }
969}
970
971#[cfg(test)]
972mod update_regressions;
973
974#[cfg(test)]
975mod tests {
976    use super::*;
977    use tempfile::TempDir;
978
979    fn setup_tool(temp: &TempDir) -> (PlanningWorkflowState, TaskTrackerTool) {
980        let state = PlanningWorkflowState::new(temp.path().to_path_buf());
981        let tool = TaskTrackerTool::new(temp.path().to_path_buf(), state.clone());
982        (state, tool)
983    }
984
985    #[tokio::test]
986    async fn test_create_checklist() {
987        let temp = TempDir::new().unwrap();
988        let (_state, tool) = setup_tool(&temp);
989
990        let result = tool
991            .execute(json!({
992                "action": "create",
993                "title": "Refactor Auth",
994                "items": ["Extract middleware", "Add tests", "Update docs"]
995            }))
996            .await
997            .unwrap();
998
999        assert_eq!(result["status"], "created");
1000        assert_eq!(result["checklist"]["total"], 3);
1001        assert_eq!(result["checklist"]["completed"], 0);
1002        assert_eq!(result["view"]["title"], "Refactor Auth");
1003        assert_eq!(result["task_file"], ".vtcode/tasks/current_task.md");
1004    }
1005
1006    #[tokio::test]
1007    async fn test_create_accepts_metadata_and_verify_string_forms() {
1008        let temp = TempDir::new().unwrap();
1009        let (_state, tool) = setup_tool(&temp);
1010
1011        let result = tool
1012            .execute(json!({
1013                "action": "create",
1014                "title": "Harness tracker",
1015                "items": [
1016                    {
1017                        "description": "Analyze current harness",
1018                        "files": ["docs/ARCHITECTURE.md"],
1019                        "outcome": "Document the harness map",
1020                        "verify": "cargo check"
1021                    },
1022                    {
1023                        "description": "Wire continuation",
1024                        "verify": ["cargo test -p vtcode-core continuation", "cargo check -p vtcode"]
1025                    }
1026                ]
1027            }))
1028            .await
1029            .unwrap();
1030
1031        assert_eq!(result["checklist"]["items"][0]["files"], json!(["docs/ARCHITECTURE.md"]));
1032        assert_eq!(result["checklist"]["items"][0]["outcome"], "Document the harness map");
1033        assert_eq!(result["checklist"]["items"][0]["verify"], json!(["cargo check"]));
1034        assert_eq!(
1035            result["checklist"]["items"][1]["verify"],
1036            json!(["cargo test -p vtcode-core continuation", "cargo check -p vtcode"])
1037        );
1038
1039        let persisted = std::fs::read_to_string(temp.path().join(".vtcode/tasks/current_task.md")).unwrap();
1040        assert!(persisted.contains("files: docs/ARCHITECTURE.md"));
1041        assert!(persisted.contains("outcome: Document the harness map"));
1042        assert!(persisted.contains("verify: cargo check"));
1043    }
1044
1045    #[tokio::test]
1046    async fn test_scope_review_metadata_survives_public_create_and_status_update() {
1047        let temp = TempDir::new().unwrap();
1048        let (_state, tool) = setup_tool(&temp);
1049        let created = tool
1050            .execute(json!({
1051                "action": "create", "title": "Scope review", "items": [{
1052                    "description": "Review final scope", "files": ["README.md"],
1053                    "scope_review": ["git status --porcelain", "git diff --stat HEAD -- README.md"]
1054                }]
1055            }))
1056            .await
1057            .unwrap();
1058        assert_eq!(
1059            created["checklist"]["items"][0]["scope_review"],
1060            json!(["git status --porcelain", "git diff --stat HEAD -- README.md"])
1061        );
1062        assert_eq!(created["checklist"]["items"][0]["verify"], json!([]));
1063        tool.execute(json!({"action": "update", "index": 1, "status": "completed"}))
1064            .await
1065            .unwrap();
1066        let persisted = std::fs::read_to_string(temp.path().join(".vtcode/tasks/current_task.md")).unwrap();
1067        assert!(persisted.contains("[x] Review final scope"));
1068        assert!(persisted.contains("  scope-review: git status --porcelain"));
1069        assert!(persisted.contains("  scope-review: git diff --stat HEAD -- README.md"));
1070        assert!(!persisted.contains("  verify:"));
1071    }
1072
1073    #[tokio::test]
1074    async fn test_update_item() {
1075        let temp = TempDir::new().unwrap();
1076        let (_state, tool) = setup_tool(&temp);
1077
1078        tool.execute(json!({
1079            "action": "create",
1080            "title": "Test",
1081            "items": ["Step 1", "Step 2"]
1082        }))
1083        .await
1084        .unwrap();
1085
1086        let result = tool
1087            .execute(json!({
1088                "action": "update",
1089                "index": 1,
1090                "status": "completed"
1091            }))
1092            .await
1093            .unwrap();
1094
1095        assert_eq!(result["status"], "updated");
1096        assert_eq!(result["checklist"]["completed"], 1);
1097        assert_eq!(result["checklist"]["progress_percent"], 50);
1098    }
1099
1100    #[tokio::test]
1101    async fn test_update_index_zero_allows_checklist_completion_note() {
1102        let temp = TempDir::new().unwrap();
1103        let (_state, tool) = setup_tool(&temp);
1104
1105        tool.execute(json!({
1106            "action": "create",
1107            "title": "Test",
1108            "items": ["Step 1", "Step 2"]
1109        }))
1110        .await
1111        .unwrap();
1112
1113        let result = tool
1114            .execute(json!({
1115                "action": "update",
1116                "index": 0,
1117                "status": "completed",
1118                "outcome": "Reported summary to user"
1119            }))
1120            .await
1121            .unwrap();
1122
1123        assert_eq!(result["status"], "updated");
1124        assert_eq!(result["checklist"]["completed"], 0);
1125        assert_eq!(result["checklist"]["notes"], "Checklist outcome: Reported summary to user");
1126    }
1127
1128    #[test]
1129    fn task_tracker_schema_describes_action_aware_indices() {
1130        let (_state, tool) = setup_tool(&TempDir::new().unwrap());
1131        let schema = tool.parameter_schema().expect("task tracker schema");
1132
1133        assert_eq!(schema["properties"]["index"]["minimum"], 0);
1134        let items_description = schema["properties"]["items"]["description"].as_str().unwrap();
1135        assert!(items_description.contains("Full checklist replacement"));
1136        assert!(items_description.contains("never JSON-encoded strings"));
1137        assert_eq!(schema["properties"]["index_path"]["pattern"], "^[1-9][0-9]*$");
1138        let description = schema["properties"]["index"]["description"]
1139            .as_str()
1140            .expect("index description");
1141        assert!(description.contains("index: 0"));
1142        assert!(description.contains("action: update"));
1143        assert!(description.contains("completed"));
1144        assert_eq!(schema["allOf"][2]["then"]["properties"]["status"]["const"], "completed");
1145    }
1146
1147    #[test]
1148    fn standard_task_tracker_schema_rejects_zero_except_legacy_completion() {
1149        let schema = standard_task_tracker_parameter_schema();
1150        let valid_cases = [
1151            json!({"action": "update", "index": 0, "status": "completed"}),
1152            json!({"action": "update", "index": 1, "status": "completed"}),
1153            json!({"action": "update", "items": ["[x] Done"]}),
1154        ];
1155        let invalid_cases = [
1156            json!({"action": "list", "index": 0}),
1157            json!({"action": "list", "index": 1}),
1158            json!({"action": "list", "index_path": "1"}),
1159            json!({"action": "add", "index": 0, "description": "New item"}),
1160            json!({"action": "add", "index": 1, "description": "New item"}),
1161            json!({"action": "create", "index": 1, "items": ["New item"]}),
1162            json!({"action": "update", "index": 0, "status": "pending"}),
1163        ];
1164
1165        for args in valid_cases {
1166            assert!(jsonschema::validate(&schema, &args).is_ok(), "expected valid args: {args}");
1167        }
1168        for args in invalid_cases {
1169            assert!(jsonschema::validate(&schema, &args).is_err(), "expected invalid args: {args}");
1170        }
1171    }
1172
1173    #[test]
1174    fn standard_task_tracker_schema_rejects_mixed_bulk_and_single_updates() {
1175        let schema = standard_task_tracker_parameter_schema();
1176        let invalid_cases = [
1177            json!({"action": "update", "items": ["Done"], "index": 1, "status": "completed"}),
1178            json!({"action": "update", "items": ["Done"], "index_path": "1", "status": "completed"}),
1179            json!({"action": "update", "index": 1, "index_path": "1", "status": "completed"}),
1180            json!({"action": "update", "items": ["Done"], "status": "completed"}),
1181            json!({"action": "update", "items": ["Done"], "index": 0, "status": "completed"}),
1182        ];
1183
1184        for args in invalid_cases {
1185            assert!(jsonschema::validate(&schema, &args).is_err(), "expected invalid args: {args}");
1186        }
1187    }
1188
1189    #[test]
1190    fn tracker_schemas_share_update_shapes_but_diverge_on_index_zero() {
1191        let standard = standard_task_tracker_parameter_schema();
1192        let planning = crate::tools::handlers::planning_task_tracker::planning_task_tracker_parameter_schema();
1193
1194        // Shared shapes: both address modes validate on both schemas,
1195        // proving the normalized anyOf arm order is behavior-preserving.
1196        for args in [
1197            json!({"action": "update", "index": 1, "status": "completed"}),
1198            json!({"action": "update", "index_path": "1", "status": "completed"}),
1199            json!({"action": "update", "items": ["[x] Done"]}),
1200            json!({"action": "create", "title": "T", "items": ["New item"]}),
1201            json!({"action": "add", "description": "New item"}),
1202            json!({"action": "list"}),
1203        ] {
1204            assert!(jsonschema::validate(&standard, &args).is_ok(), "standard rejects shared shape: {args}");
1205            assert!(jsonschema::validate(&planning, &args).is_ok(), "planning rejects shared shape: {args}");
1206        }
1207
1208        // Shared rejections on both schemas.
1209        for args in [
1210            json!({"action": "list", "index": 1}),
1211            json!({"action": "create", "index": 1, "items": ["New item"]}),
1212            json!({"action": "update", "index": 1, "index_path": "1", "status": "completed"}),
1213        ] {
1214            assert!(jsonschema::validate(&standard, &args).is_err(), "standard accepts rejected shape: {args}");
1215            assert!(jsonschema::validate(&planning, &args).is_err(), "planning accepts rejected shape: {args}");
1216        }
1217
1218        // Divergent boundary: index 0 completes a standard checklist but is
1219        // invalid in planning (indices start at 1).
1220        let zero_completion = json!({"action": "update", "index": 0, "status": "completed"});
1221        assert!(jsonschema::validate(&standard, &zero_completion).is_ok());
1222        assert!(jsonschema::validate(&planning, &zero_completion).is_err());
1223    }
1224
1225    #[tokio::test]
1226    async fn bulk_update_rejects_encoded_commands_without_resetting_completed_steps() {
1227        let temp = TempDir::new().unwrap();
1228        let (_state, tool) = setup_tool(&temp);
1229        tool.execute(json!({
1230            "action": "create",
1231            "title": "Preserve progress",
1232            "items": [
1233                {"description": "Update introduction", "status": "completed", "files": ["README.md"], "outcome": "Clear overview", "verify": ["review headings"]},
1234                {"description": "Review links", "status": "blocked", "outcome": "Await network"}
1235            ]
1236        })).await.unwrap();
1237        let tracker_path = temp.path().join(".vtcode/tasks/current_task.md");
1238        let persisted_before = std::fs::read_to_string(&tracker_path).unwrap();
1239        let before = tool.execute(json!({"action": "list"})).await.unwrap();
1240
1241        for (action, encoded) in [
1242            ("update", r#"{"index_path":"1","status":"completed","outcome":"Done","verify":"review headings"}"#),
1243            ("update", r#"  [x] {"index_path":"1","status":"completed"}"#),
1244            ("create", r#"{"index":1,"status":"completed"}"#),
1245        ] {
1246            let error = tool
1247                .execute(json!({
1248                    "action": action,
1249                    "title": "Incorrect replacement",
1250                    "items": ["Replacement must not leak", encoded]
1251                }))
1252                .await
1253                .expect_err("encoded updates must not replace the tracker");
1254            assert!(error.to_string().contains("JSON-encoded task updates"));
1255            assert!(
1256                error
1257                    .to_string()
1258                    .contains(r#"{"action":"update","index_path":"1","status":"completed"}"#)
1259            );
1260            assert_eq!(tool.execute(json!({"action": "list"})).await.unwrap(), before);
1261            assert_eq!(std::fs::read_to_string(&tracker_path).unwrap(), persisted_before);
1262        }
1263
1264        tool.execute(json!({"action": "update", "index_path": "2", "status": "completed"}))
1265            .await
1266            .unwrap();
1267        let after = tool.execute(json!({"action": "list"})).await.unwrap();
1268        assert_eq!(after["checklist"]["completed"], 2);
1269        assert_eq!(after["checklist"]["items"][0]["description"], "Update introduction");
1270        assert_eq!(after["checklist"]["items"][0]["files"], json!(["README.md"]));
1271    }
1272
1273    #[tokio::test]
1274    async fn update_rejects_mixed_bulk_and_single_fields_before_mutation() {
1275        let temp = TempDir::new().unwrap();
1276        let (_state, tool) = setup_tool(&temp);
1277
1278        tool.execute(json!({
1279            "action": "create",
1280            "title": "Test",
1281            "items": ["Original"]
1282        }))
1283        .await
1284        .unwrap();
1285
1286        let error = tool
1287            .execute(json!({
1288                "action": "update",
1289                "items": ["Replacement"],
1290                "index": 1,
1291                "status": "completed"
1292            }))
1293            .await
1294            .expect_err("mixed update must fail closed");
1295        assert!(error.to_string().contains("cannot combine 'items'"));
1296
1297        let result = tool.execute(json!({"action": "list"})).await.unwrap();
1298        assert_eq!(result["checklist"]["items"][0]["description"], "Original");
1299        assert_eq!(result["checklist"]["items"][0]["status"], "pending");
1300    }
1301
1302    #[tokio::test]
1303    async fn update_rejects_both_index_forms_before_mutation() {
1304        let temp = TempDir::new().unwrap();
1305        let (_state, tool) = setup_tool(&temp);
1306
1307        tool.execute(json!({
1308            "action": "create",
1309            "title": "Test",
1310            "items": ["Original"]
1311        }))
1312        .await
1313        .unwrap();
1314
1315        let error = tool
1316            .execute(json!({
1317                "action": "update",
1318                "index": 1,
1319                "index_path": "1",
1320                "status": "completed"
1321            }))
1322            .await
1323            .expect_err("ambiguous index forms must fail closed");
1324        assert!(error.to_string().contains("cannot combine 'index' and 'index_path'"));
1325
1326        let result = tool.execute(json!({"action": "list"})).await.unwrap();
1327        assert_eq!(result["checklist"]["items"][0]["description"], "Original");
1328        assert_eq!(result["checklist"]["items"][0]["status"], "pending");
1329    }
1330
1331    #[tokio::test]
1332    async fn execute_rejects_indices_for_non_update_actions() {
1333        let temp = TempDir::new().unwrap();
1334        let (_state, tool) = setup_tool(&temp);
1335
1336        let invalid_inputs = [
1337            json!({"action": "list", "index": 1}),
1338            json!({"action": "create", "index_path": "1", "items": ["New item"]}),
1339            json!({"action": "add", "index": 1, "description": "New item"}),
1340            json!({"action": "unexpected", "index_path": "1"}),
1341        ];
1342
1343        for input in invalid_inputs {
1344            let error = tool.execute(input).await.expect_err("non-update index must fail closed");
1345            assert!(error.to_string().contains("cannot use 'index' or 'index_path'"), "unexpected error: {error}");
1346        }
1347    }
1348
1349    #[test]
1350    fn task_tracker_metadata_switches_with_planning_state() {
1351        let temp = TempDir::new().unwrap();
1352        let (state, tool) = setup_tool(&temp);
1353
1354        assert_eq!(tool.description(), task_tracker_description_for_workflow(false));
1355        assert_eq!(tool.parameter_schema().expect("standard schema")["properties"]["index"]["minimum"], 0);
1356
1357        state.enable();
1358
1359        assert_eq!(tool.description(), task_tracker_description_for_workflow(true));
1360        assert_eq!(tool.parameter_schema().expect("planning schema")["properties"]["index"]["minimum"], 1);
1361    }
1362
1363    #[tokio::test]
1364    async fn test_add_item() {
1365        let temp = TempDir::new().unwrap();
1366        let (_state, tool) = setup_tool(&temp);
1367
1368        tool.execute(json!({
1369            "action": "create",
1370            "title": "Test",
1371            "items": ["Step 1"]
1372        }))
1373        .await
1374        .unwrap();
1375
1376        let result = tool
1377            .execute(json!({
1378                "action": "add",
1379                "description": "Step 2"
1380            }))
1381            .await
1382            .unwrap();
1383
1384        assert_eq!(result["status"], "added");
1385        assert_eq!(result["checklist"]["total"], 2);
1386    }
1387
1388    #[tokio::test]
1389    async fn test_create_is_idempotent_for_same_structure() {
1390        let temp = TempDir::new().unwrap();
1391        let (_state, tool) = setup_tool(&temp);
1392
1393        tool.execute(json!({
1394            "action": "create",
1395            "title": "Clippy Warnings",
1396            "items": ["Fix A", "Fix B"]
1397        }))
1398        .await
1399        .unwrap();
1400
1401        tool.execute(json!({
1402            "action": "update",
1403            "index": 1,
1404            "status": "completed"
1405        }))
1406        .await
1407        .unwrap();
1408
1409        let duplicate = tool
1410            .execute(json!({
1411                "action": "create",
1412                "title": "Clippy Warnings",
1413                "items": ["Fix A", "Fix B"]
1414            }))
1415            .await
1416            .unwrap();
1417
1418        assert_eq!(duplicate["status"], "unchanged");
1419        assert_eq!(duplicate["checklist"]["completed"], 1);
1420    }
1421
1422    #[tokio::test]
1423    async fn test_create_with_new_structure_replaces_checklist() {
1424        let temp = TempDir::new().unwrap();
1425        let (_state, tool) = setup_tool(&temp);
1426
1427        tool.execute(json!({
1428            "action": "create",
1429            "title": "First",
1430            "items": ["Fix A", "Fix B"]
1431        }))
1432        .await
1433        .unwrap();
1434
1435        tool.execute(json!({
1436            "action": "update",
1437            "index": 1,
1438            "status": "completed"
1439        }))
1440        .await
1441        .unwrap();
1442
1443        let replaced = tool
1444            .execute(json!({
1445                "action": "create",
1446                "title": "Second",
1447                "items": ["Fix C"]
1448            }))
1449            .await
1450            .unwrap();
1451
1452        assert_eq!(replaced["status"], "replaced");
1453        assert_eq!(replaced["checklist"]["total"], 1);
1454        assert_eq!(replaced["checklist"]["completed"], 0);
1455    }
1456
1457    #[test]
1458    fn task_tracker_descriptions_state_that_repeat_create_replaces() {
1459        for planning_active in [false, true] {
1460            let description = task_tracker_description_for_workflow(planning_active);
1461            assert!(
1462                description.contains("Calling action=create again replaces"),
1463                "planning_active={planning_active}: {description}"
1464            );
1465            assert!(!description.contains("subsequent calls update"), "planning_active={planning_active}");
1466        }
1467        assert!(task_tracker_description_for_workflow(false).contains("no-op"));
1468    }
1469
1470    #[tokio::test]
1471    async fn test_update_supports_bulk_item_sync() {
1472        let temp = TempDir::new().unwrap();
1473        let (_state, tool) = setup_tool(&temp);
1474
1475        tool.execute(json!({
1476            "action": "create",
1477            "title": "Sync Test",
1478            "items": ["Step 1", "Step 2", "Step 3"]
1479        }))
1480        .await
1481        .unwrap();
1482
1483        let updated = tool
1484            .execute(json!({
1485                "action": "update",
1486                "items": ["[x] Step 1", "[~] Step 2", "[ ] Step 3"]
1487            }))
1488            .await
1489            .unwrap();
1490
1491        assert_eq!(updated["status"], "updated");
1492        assert_eq!(updated["checklist"]["completed"], 1);
1493        assert_eq!(updated["checklist"]["in_progress"], 1);
1494        assert_eq!(updated["checklist"]["pending"], 1);
1495    }
1496
1497    #[tokio::test]
1498    async fn test_list_empty() {
1499        let temp = TempDir::new().unwrap();
1500        let (_state, tool) = setup_tool(&temp);
1501
1502        let result = tool.execute(json!({"action": "list"})).await.unwrap();
1503        assert_eq!(result["status"], "empty");
1504    }
1505
1506    #[tokio::test]
1507    async fn test_persistence_across_loads() {
1508        let temp = TempDir::new().unwrap();
1509
1510        {
1511            let (_state, tool) = setup_tool(&temp);
1512            tool.execute(json!({
1513                "action": "create",
1514                "title": "Persist Test",
1515                "items": ["Alpha", "Beta"]
1516            }))
1517            .await
1518            .unwrap();
1519
1520            tool.execute(json!({
1521                "action": "update",
1522                "index": 1,
1523                "status": "completed"
1524            }))
1525            .await
1526            .unwrap();
1527        }
1528
1529        let (_state, tool2) = setup_tool(&temp);
1530        let result = tool2.execute(json!({"action": "list"})).await.unwrap();
1531
1532        assert_eq!(result["status"], "ok");
1533        assert_eq!(result["checklist"]["total"], 2);
1534        assert_eq!(result["checklist"]["completed"], 1);
1535    }
1536
1537    #[tokio::test]
1538    async fn test_planning_workflow_task_tracker_delegates_and_mirrors_global() {
1539        let temp = TempDir::new().unwrap();
1540        let (state, tool) = setup_tool(&temp);
1541
1542        let plans_dir = state.plans_dir();
1543        std::fs::create_dir_all(&plans_dir).unwrap();
1544        let plan_file = plans_dir.join("adaptive.md");
1545        std::fs::write(&plan_file, "# Adaptive\n").unwrap();
1546        state.set_plan_file(Some(plan_file)).await;
1547        state.enable();
1548
1549        let created = tool
1550            .execute(json!({
1551                "action": "create",
1552                "title": "Adaptive Plan",
1553                "items": ["Root task", "  Child task"]
1554            }))
1555            .await
1556            .unwrap();
1557
1558        assert_eq!(created["status"], "created");
1559        assert_eq!(created["checklist"]["total"], 2);
1560
1561        let task_file = temp.path().join(".vtcode/tasks/current_task.md");
1562        let persisted = std::fs::read_to_string(task_file).unwrap();
1563        assert!(persisted.contains("Root task"));
1564        assert!(persisted.contains("Child task"));
1565    }
1566
1567    #[tokio::test]
1568    async fn test_planning_workflow_adaptive_tool_accepts_hierarchical_index_path() {
1569        let temp = TempDir::new().unwrap();
1570        let (state, tool) = setup_tool(&temp);
1571
1572        let plans_dir = state.plans_dir();
1573        std::fs::create_dir_all(&plans_dir).unwrap();
1574        let plan_file = plans_dir.join("hierarchical.md");
1575        std::fs::write(&plan_file, "# Hierarchical\n").unwrap();
1576        state.set_plan_file(Some(plan_file)).await;
1577        state.enable();
1578
1579        tool.execute(json!({
1580            "action": "create",
1581            "items": ["Parent task", "  Child task"]
1582        }))
1583        .await
1584        .unwrap();
1585
1586        let updated = tool
1587            .execute(json!({
1588                "action": "update",
1589                "index_path": "1.1",
1590                "status": "completed"
1591            }))
1592            .await
1593            .unwrap();
1594
1595        assert_eq!(updated["status"], "updated");
1596        assert_eq!(updated["checklist"]["completed"], 1);
1597    }
1598
1599    #[tokio::test]
1600    async fn test_planning_workflow_adaptive_tool_rejects_index_zero() {
1601        let temp = TempDir::new().unwrap();
1602        let (state, tool) = setup_tool(&temp);
1603
1604        let plans_dir = state.plans_dir();
1605        std::fs::create_dir_all(&plans_dir).unwrap();
1606        let plan_file = plans_dir.join("reject-zero.md");
1607        std::fs::write(&plan_file, "# Reject zero\n").unwrap();
1608        state.set_plan_file(Some(plan_file)).await;
1609        state.enable();
1610
1611        tool.execute(json!({
1612            "action": "create",
1613            "items": ["Parent task"]
1614        }))
1615        .await
1616        .unwrap();
1617
1618        let error = tool
1619            .execute(json!({
1620                "action": "update",
1621                "index": 0,
1622                "status": "completed"
1623            }))
1624            .await
1625            .expect_err("planning index zero must be rejected");
1626
1627        assert!(error.to_string().contains("index_path components must be >= 1"));
1628    }
1629
1630    #[tokio::test]
1631    async fn test_planning_workflow_mirror_preserves_notes() {
1632        let temp = TempDir::new().unwrap();
1633        let (state, tool) = setup_tool(&temp);
1634
1635        let plans_dir = state.plans_dir();
1636        std::fs::create_dir_all(&plans_dir).unwrap();
1637        let plan_file = plans_dir.join("notes.md");
1638        std::fs::write(&plan_file, "# Notes\n").unwrap();
1639        state.set_plan_file(Some(plan_file)).await;
1640        state.enable();
1641
1642        tool.execute(json!({
1643            "action": "create",
1644            "items": ["Root task"],
1645            "notes": "Keep this note"
1646        }))
1647        .await
1648        .unwrap();
1649
1650        let task_file = temp.path().join(".vtcode/tasks/current_task.md");
1651        let persisted = std::fs::read_to_string(task_file).unwrap();
1652        assert!(persisted.contains("## Notes"));
1653        assert!(persisted.contains("Keep this note"));
1654    }
1655
1656    #[tokio::test]
1657    async fn test_edit_mode_prefers_newer_plan_mirror_when_present() {
1658        let temp = TempDir::new().unwrap();
1659        let (state, tool) = setup_tool(&temp);
1660
1661        let plans_dir = state.plans_dir();
1662        std::fs::create_dir_all(&plans_dir).unwrap();
1663        let plan_file = plans_dir.join("freshness.md");
1664        std::fs::write(&plan_file, "# Freshness\n").unwrap();
1665        state.set_plan_file(Some(plan_file.clone())).await;
1666
1667        let global_file = temp.path().join(".vtcode/tasks/current_task.md");
1668        std::fs::create_dir_all(global_file.parent().unwrap()).unwrap();
1669        std::fs::write(&global_file, "# Freshness\n\n- [ ] stale global\n").unwrap();
1670
1671        std::thread::sleep(std::time::Duration::from_millis(15));
1672
1673        let sidecar = plans_dir.join("freshness.tasks.md");
1674        std::fs::write(&sidecar, "# Freshness\n\n## Plan of Work\n\n- [x] newer plan\n").unwrap();
1675
1676        let listed = tool.execute(json!({"action": "list"})).await.unwrap();
1677        assert_eq!(listed["status"], "ok");
1678        assert_eq!(listed["checklist"]["completed"], 1);
1679        assert_eq!(listed["checklist"]["pending"], 0);
1680
1681        let global_synced = std::fs::read_to_string(global_file).unwrap();
1682        assert!(global_synced.contains("newer plan"));
1683    }
1684
1685    #[tokio::test]
1686    async fn test_planning_workflow_prefers_plan_sidecar_even_if_global_is_newer() {
1687        let temp = TempDir::new().unwrap();
1688        let (state, tool) = setup_tool(&temp);
1689
1690        let plans_dir = state.plans_dir();
1691        std::fs::create_dir_all(&plans_dir).unwrap();
1692        let plan_file = plans_dir.join("plan-primary.md");
1693        std::fs::write(&plan_file, "# Plan Primary\n").unwrap();
1694        state.set_plan_file(Some(plan_file.clone())).await;
1695        state.enable();
1696
1697        let global_file = temp.path().join(".vtcode/tasks/current_task.md");
1698        std::fs::create_dir_all(global_file.parent().unwrap()).unwrap();
1699        std::fs::write(&global_file, "# Plan Primary\n\n- [x] global newer\n").unwrap();
1700        std::thread::sleep(std::time::Duration::from_millis(15));
1701
1702        let sidecar = plans_dir.join("plan-primary.tasks.md");
1703        std::fs::write(&sidecar, "# Plan Primary\n\n## Plan of Work\n\n- [ ] plan source\n").unwrap();
1704        std::thread::sleep(std::time::Duration::from_millis(15));
1705        std::fs::write(&global_file, "# Plan Primary\n\n- [x] global newest\n").unwrap();
1706
1707        let listed = tool.execute(json!({"action": "list"})).await.unwrap();
1708        assert_eq!(listed["status"], "ok");
1709        assert_eq!(listed["checklist"]["pending"], 1);
1710        assert_eq!(listed["checklist"]["completed"], 0);
1711    }
1712}