1use super::planning_workflow::{PlanningWorkflowState, tracker_file_for_plan_file};
7use crate::config::constants::tools;
8use crate::tools::error_helpers::deserialize_tool_args;
9use crate::tools::handlers::task_tracking::{
10 TASK_ITEMS_DESCRIPTION, TaskCounts, TaskItemInput, TaskMetadataRef, TaskStepMetadata, TaskTrackingStatus,
11 TaskTreeNode, TrackerArtifact, append_notes, append_notes_section, append_task_step_metadata, apply_metadata_input,
12 apply_metadata_line, compact_task_tree_view, is_bulk_sync_update, metadata_from_input, parse_marked_status_prefix,
13 parse_status_prefix, parse_task_items, persist_tracker_artifacts, task_files_property_schema,
14 task_items_array_schema, task_status_property_schema, task_verify_property_schema, tracker_schema_allof,
15 validate_action_index_fields, validate_update_shape,
16};
17use crate::tools::traits::Tool;
18use crate::utils::file_utils::read_file_with_context;
19use anyhow::{Context, Result, bail};
20use async_trait::async_trait;
21use serde::{Deserialize, Serialize};
22use serde_json::{Value, json};
23use std::fmt::Write as _;
24use std::path::{Path, PathBuf};
25use std::str::FromStr;
26use vtcode_commons::workspace_relative_display;
27
28type PlanTaskStatus = TaskTrackingStatus;
29
30#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
31struct PlanTaskNode {
32 description: String,
33 status: PlanTaskStatus,
34 #[serde(default, flatten)]
35 metadata: TaskStepMetadata,
36 children: Vec<PlanTaskNode>,
37}
38
39#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
40struct PlanTaskDocument {
41 title: String,
42 items: Vec<PlanTaskNode>,
43 #[serde(skip_serializing_if = "Option::is_none")]
44 notes: Option<String>,
45}
46
47#[derive(Debug, Clone, Serialize, Deserialize)]
48pub struct PlanningTaskTrackerArgs {
49 pub action: String,
51
52 #[serde(default)]
54 pub title: Option<String>,
55
56 #[serde(default)]
58 pub items: Option<Vec<TaskItemInput>>,
59
60 #[serde(default)]
62 pub index_path: Option<String>,
63
64 #[serde(default)]
66 pub index: Option<usize>,
67
68 #[serde(default)]
70 pub status: Option<String>,
71
72 #[serde(default)]
74 pub description: Option<String>,
75
76 #[serde(default)]
78 pub files: Option<Vec<String>>,
79
80 #[serde(default)]
82 pub outcome: Option<String>,
83
84 #[serde(
86 default,
87 deserialize_with = "crate::tools::handlers::task_tracking::deserialize_optional_string_list"
88 )]
89 pub verify: Option<Vec<String>>,
90
91 #[serde(default)]
93 pub parent_index_path: Option<String>,
94
95 #[serde(default)]
97 pub notes: Option<String>,
98}
99
100#[derive(Debug, Clone)]
101struct FlatTaskLine {
102 level: usize,
103 status: PlanTaskStatus,
104 description: String,
105 metadata: TaskStepMetadata,
106}
107
108impl PlanTaskDocument {
109 fn to_markdown(&self) -> String {
110 let mut out = format!("# {}\n\n## Plan of Work\n\n", self.title);
111 write_markdown_nodes(&self.items, 0, &mut out);
112 append_notes_section(&mut out, self.notes.as_deref());
113 out
114 }
115
116 fn summary_json(&self) -> Value {
117 let mut counts = TaskCounts::default();
118 count_nodes(&self.items, &mut counts);
119
120 json!({
121 "title": self.title,
122 "total": counts.total,
123 "completed": counts.completed,
124 "in_progress": counts.in_progress,
125 "pending": counts.pending,
126 "blocked": counts.blocked,
127 "progress_percent": counts.progress_percent(),
128 "items": flatten_items_json(&self.items),
129 "notes": self.notes.clone(),
130 })
131 }
132
133 fn view_json(&self) -> Value {
134 json!({
135 "title": self.title,
136 "lines": compact_task_tree_view(&compact_view_nodes(&self.items, "")),
137 })
138 }
139}
140
141fn count_nodes(nodes: &[PlanTaskNode], counts: &mut TaskCounts) {
142 for node in nodes {
143 counts.add(&node.status);
144 count_nodes(&node.children, counts);
145 }
146}
147
148fn write_markdown_nodes(nodes: &[PlanTaskNode], level: usize, out: &mut String) {
149 let indent = " ".repeat(level);
150 for node in nodes {
151 out.push_str(&indent);
152 out.push_str("- ");
153 out.push_str(node.status.plan_checkbox());
154 out.push(' ');
155 out.push_str(&node.description);
156 out.push('\n');
157 append_task_step_metadata(out, &indent, &node.metadata);
158 write_markdown_nodes(&node.children, level + 1, out);
159 }
160}
161
162fn flatten_items_json(nodes: &[PlanTaskNode]) -> Vec<Value> {
163 let mut items = Vec::new();
164 flatten_items_json_inner(nodes, "", 0, &mut items);
165 items
166}
167
168fn flatten_for_global_items(nodes: &[PlanTaskNode], level: usize, out: &mut Vec<FlatTaskLine>) {
169 for node in nodes {
170 out.push(FlatTaskLine {
171 level,
172 status: node.status,
173 description: node.description.clone(),
174 metadata: node.metadata.clone(),
175 });
176 flatten_for_global_items(&node.children, level + 1, out);
177 }
178}
179
180fn flatten_items_json_inner(nodes: &[PlanTaskNode], index_prefix: &str, level: usize, out: &mut Vec<Value>) {
181 for (idx, node) in nodes.iter().enumerate() {
182 let index_path = if index_prefix.is_empty() {
183 format!("{}", idx + 1)
184 } else {
185 format!("{index_prefix}.{}", idx + 1)
186 };
187 out.push(json!({
188 "index_path": index_path,
189 "description": node.description,
190 "status": node.status.as_str(),
191 "level": level,
192 "files": node.metadata.files.clone(),
193 "outcome": node.metadata.outcome.clone(),
194 "verify": node.metadata.verify.clone(),
195 "scope_review": node.metadata.scope_review.clone(),
196 }));
197 flatten_items_json_inner(&node.children, &index_path, level + 1, out);
198 }
199}
200
201fn compact_view_nodes(nodes: &[PlanTaskNode], index_prefix: &str) -> Vec<TaskTreeNode> {
202 nodes
203 .iter()
204 .enumerate()
205 .map(|(index, node)| {
206 let index_path = if index_prefix.is_empty() {
207 format!("{}", index + 1)
208 } else {
209 format!("{index_prefix}.{}", index + 1)
210 };
211 TaskTreeNode {
212 index_path: index_path.clone(),
213 description: node.description.clone(),
214 status: node.status,
215 metadata: node.metadata.clone(),
216 children: compact_view_nodes(&node.children, &index_path),
217 }
218 })
219 .collect()
220}
221
222fn parse_task_line(line: &str) -> Option<FlatTaskLine> {
223 let indent_spaces = line.chars().take_while(|c| *c == ' ').count();
224 let level = indent_spaces / 2;
225 let trimmed = line.trim_start();
226 let rest = trimmed
227 .strip_prefix("- ")
228 .or_else(|| trimmed.strip_prefix("* "))
229 .or_else(|| trimmed.strip_prefix("+ "))?;
230
231 let (status, description) = parse_marked_status_prefix(rest)?;
232 if description.trim().is_empty() {
233 return None;
234 }
235 Some(FlatTaskLine {
236 level,
237 status,
238 description: description.trim().to_string(),
239 metadata: TaskStepMetadata::default(),
240 })
241}
242
243fn build_tree_from_flat(lines: &[FlatTaskLine]) -> Vec<PlanTaskNode> {
244 let mut roots = Vec::<PlanTaskNode>::new();
245 let mut current_path = Vec::<usize>::new();
246 let mut previous_level = 0usize;
247
248 for line in lines {
249 let mut level = line.level;
250 if level > previous_level + 1 {
251 level = previous_level + 1;
252 }
253 while current_path.len() > level {
254 current_path.pop();
255 }
256 if level > current_path.len() {
257 level = current_path.len();
258 }
259
260 let node = PlanTaskNode {
261 description: line.description.clone(),
262 status: line.status,
263 metadata: line.metadata.clone(),
264 children: Vec::new(),
265 };
266
267 if level == 0 || current_path.is_empty() {
268 roots.push(node);
269 current_path.clear();
270 current_path.push(roots.len() - 1);
271 previous_level = 0;
272 continue;
273 }
274
275 if let Some(parent) = get_node_mut_by_indices(&mut roots, ¤t_path) {
276 parent.children.push(node);
277 let child_idx = parent.children.len() - 1;
278 current_path.push(child_idx);
279 } else {
280 roots.push(node);
281 current_path.clear();
282 current_path.push(roots.len() - 1);
283 }
284
285 previous_level = level;
286 }
287
288 roots
289}
290
291fn get_node_mut_by_indices<'a>(nodes: &'a mut [PlanTaskNode], path: &[usize]) -> Option<&'a mut PlanTaskNode> {
292 let (&head, tail) = path.split_first()?;
293 let node = nodes.get_mut(head)?;
294 if tail.is_empty() {
295 Some(node)
296 } else {
297 get_node_mut_by_indices(node.children.as_mut_slice(), tail)
298 }
299}
300
301fn get_node_mut_by_index_path<'a>(nodes: &'a mut [PlanTaskNode], path: &[usize]) -> Option<&'a mut PlanTaskNode> {
302 let (&head, tail) = path.split_first()?;
303 let idx = head.checked_sub(1)?;
304 let node = nodes.get_mut(idx)?;
305 if tail.is_empty() {
306 Some(node)
307 } else {
308 get_node_mut_by_index_path(node.children.as_mut_slice(), tail)
309 }
310}
311
312fn parse_index_path(value: &str) -> Result<Vec<usize>> {
313 let trimmed = value.trim();
314 if trimmed.is_empty() {
315 bail!("index_path cannot be empty");
316 }
317
318 trimmed
319 .split('.')
320 .map(|token| {
321 let parsed = token
322 .parse::<usize>()
323 .with_context(|| format!("Invalid index component '{token}'"))?;
324 if parsed == 0 {
325 bail!("index_path components must be >= 1");
326 }
327 Ok(parsed)
328 })
329 .collect()
330}
331
332fn parse_document_from_markdown(content: &str) -> Option<PlanTaskDocument> {
333 let mut title = String::new();
334 let mut in_plan_section = false;
335 let mut in_notes = false;
336 let mut notes_lines = Vec::new();
337 let mut task_lines = Vec::<FlatTaskLine>::new();
338 let mut in_verify_block = false;
339
340 for raw in content.lines() {
341 let trimmed = raw.trim();
342
343 if title.is_empty()
344 && let Some(rest) = trimmed.strip_prefix("# ")
345 {
346 title = rest.trim().to_string();
347 continue;
348 }
349
350 if let Some(header) = trimmed.strip_prefix("## ") {
351 let lowered = header.trim().to_ascii_lowercase();
352 in_plan_section = matches!(lowered.as_str(), "plan of work" | "concrete steps" | "updated plan")
353 || lowered.starts_with("phase ");
354 in_notes = lowered == "notes";
355 continue;
356 }
357
358 if in_notes {
359 notes_lines.push(raw.to_string());
360 continue;
361 }
362
363 if in_plan_section {
364 if let Some(line) = parse_task_line(raw) {
365 task_lines.push(line);
366 in_verify_block = false;
367 continue;
368 }
369
370 if let Some(last) = task_lines.last_mut() {
371 let leading_spaces = raw.chars().take_while(|c| *c == ' ').count();
372 let min_indent = (last.level + 1) * 2;
373 if leading_spaces >= min_indent && apply_metadata_line(&mut last.metadata, raw, &mut in_verify_block) {
374 continue;
375 }
376 }
377 in_verify_block = false;
378 }
379 }
380
381 if title.is_empty() && task_lines.is_empty() {
382 return None;
383 }
384
385 let notes = if notes_lines.is_empty() {
386 None
387 } else {
388 Some(notes_lines.join("\n").trim().to_string())
389 };
390 let items = build_tree_from_flat(&task_lines);
391
392 Some(PlanTaskDocument { title, items, notes })
393}
394
395fn collect_task_metadata<'a>(nodes: &'a [PlanTaskNode], metadata: &mut Vec<TaskMetadataRef<'a>>) {
396 for node in nodes {
397 metadata.push(TaskMetadataRef {
398 description: &node.description,
399 metadata: &node.metadata,
400 });
401 collect_task_metadata(&node.children, metadata);
402 }
403}
404
405fn build_flat_task_lines(items: &[TaskItemInput], previous: &[PlanTaskNode]) -> Result<Vec<FlatTaskLine>> {
406 let mut previous_metadata = Vec::new();
407 collect_task_metadata(previous, &mut previous_metadata);
408 Ok(parse_task_items(items, &previous_metadata)?
409 .into_iter()
410 .map(|item| FlatTaskLine {
411 level: item.level,
412 status: item.status,
413 description: item.description,
414 metadata: item.metadata,
415 })
416 .collect())
417}
418
419pub struct PlanningTaskTrackerTool {
420 state: PlanningWorkflowState,
421}
422
423pub(crate) fn planning_task_tracker_parameter_schema() -> Value {
424 json!({
425 "type": "object",
426 "properties": {
427 "action": {
428 "type": "string",
429 "enum": ["create", "update", "list", "add"],
430 "description": "Action to perform on the plan-scoped tracker."
431 },
432 "title": {
433 "type": "string",
434 "description": "Title for tracker document (used with create)."
435 },
436 "items": task_items_array_schema(&format!("{TASK_ITEMS_DESCRIPTION} Leading 2-space indentation in description indicates nesting.")),
437 "index_path": {
438 "type": "string",
439 "pattern": "^[1-9][0-9]*(\\.[1-9][0-9]*)*$",
440 "description": "Action=update only: positive flat or hierarchical item path (examples: '2' or '2.1'). Zero is not a valid planning index."
441 },
442 "index": {
443 "type": "integer",
444 "minimum": 1,
445 "description": "Action=update only: positive top-level item index compatibility fallback. Planning index 0 is invalid; use items for bulk updates."
446 },
447 "status": task_status_property_schema("New status for update."),
448 "description": {
449 "type": "string",
450 "description": "Task description for add. Optional prefix like '[x] ' or '[~] ' is supported."
451 },
452 "files": task_files_property_schema("Optional file paths associated with a single add/update item."),
453 "outcome": {
454 "type": "string",
455 "description": "Optional expected outcome associated with a single add/update item."
456 },
457 "verify": task_verify_property_schema("Optional verification command or commands associated with a single add/update item."),
458 "parent_index_path": {
459 "type": "string",
460 "description": "Optional parent path for add (example: '2'). If omitted, adds top-level task."
461 },
462 "notes": {
463 "type": "string",
464 "description": "Optional notes to append."
465 }
466 },
467 "required": ["action"],
468 "allOf": tracker_schema_allof(false)
469 })
470}
471
472impl PlanningTaskTrackerTool {
473 pub fn new(state: PlanningWorkflowState) -> Self {
474 Self { state }
475 }
476
477 fn display_path(&self, path: &Path) -> String {
478 self.state
479 .workspace_root()
480 .map(|workspace| workspace_relative_display(&workspace, path))
481 .unwrap_or_else(|| path.to_string_lossy().into_owned())
482 }
483
484 fn tracker_file_for_plan(plan_file: &Path) -> Result<PathBuf> {
485 tracker_file_for_plan_file(plan_file).context("Active plan file is missing a valid file stem")
486 }
487
488 async fn active_plan_file(&self) -> Result<PathBuf> {
489 if !self.state.is_active() {
490 bail!("task_tracker planning storage is only available while planning");
491 }
492 self.state
493 .get_plan_file()
494 .await
495 .context("No active plan file. Call start_planning first.")
496 }
497
498 async fn tracker_file(&self) -> Result<PathBuf> {
499 let plan_file = self.active_plan_file().await?;
500 Self::tracker_file_for_plan(&plan_file)
501 }
502
503 async fn load_document(&self) -> Result<Option<PlanTaskDocument>> {
504 let tracker_file = self.tracker_file().await?;
505 if !tokio::fs::try_exists(&tracker_file).await.unwrap_or(false) {
506 return Ok(None);
507 }
508 let content = read_file_with_context(&tracker_file, "plan task tracker file").await?;
509 Ok(parse_document_from_markdown(&content))
510 }
511
512 fn global_task_file(&self) -> Option<PathBuf> {
513 self.state
514 .workspace_root()
515 .map(|workspace| workspace.join(".vtcode").join("tasks").join("current_task.md"))
516 }
517
518 fn global_task_markdown(document: &PlanTaskDocument) -> String {
519 let mut lines = Vec::new();
520 flatten_for_global_items(&document.items, 0, &mut lines);
521
522 let mut markdown = format!("# {}\n\n", document.title);
523 for line in lines {
524 let _ =
525 writeln!(markdown, "- {} {}{}", line.status.flat_checkbox(), " ".repeat(line.level), line.description);
526 append_task_step_metadata(&mut markdown, "", &line.metadata);
527 }
528 append_notes_section(&mut markdown, document.notes.as_deref());
529
530 markdown
531 }
532
533 fn success_payload(
534 &self,
535 status: &str,
536 message: String,
537 tracker_file: &Path,
538 document: &PlanTaskDocument,
539 ) -> Value {
540 json!({
541 "status": status,
542 "message": message,
543 "tracker_file": self.display_path(tracker_file),
544 "checklist": document.summary_json(),
545 "view": document.view_json(),
546 })
547 }
548
549 async fn persist_document_and_payload(
550 &self,
551 status: &str,
552 message: String,
553 document: &PlanTaskDocument,
554 ) -> Result<Value> {
555 let tracker_file = self.tracker_file().await?;
556 let markdown = document.to_markdown();
557 let mut artifacts =
558 vec![TrackerArtifact::new(tracker_file.clone(), markdown.clone(), "plan task tracker file").await?];
559 if let Some(task_file) = self.global_task_file() {
560 artifacts
561 .push(TrackerArtifact::new(task_file, Self::global_task_markdown(document), "task checklist").await?);
562 }
563 if let Some(plan_file) = self.state.get_plan_file().await
564 && let Some(artifact) = TrackerArtifact::embedded_plan(plan_file, &markdown).await?
565 {
566 artifacts.push(artifact);
567 }
568 persist_tracker_artifacts(artifacts).await?;
569 Ok(self.success_payload(status, message, &tracker_file, document))
570 }
571
572 async fn handle_create(&self, args: &PlanningTaskTrackerArgs) -> Result<Value> {
573 let items = args.items.as_deref().unwrap_or(&[]);
574 if items.is_empty() {
575 bail!("At least one item is required for 'create'. Provide items: [\"step 1\", \"step 2\", ...]");
576 }
577
578 let flat_lines = build_flat_task_lines(items, &[])?;
579 if flat_lines.is_empty() {
580 bail!("No valid task items were provided for create");
581 }
582
583 let mut document = PlanTaskDocument {
584 title: args.title.clone().unwrap_or_else(|| "Updated Plan".to_string()),
585 items: build_tree_from_flat(&flat_lines),
586 notes: None,
587 };
588 document.notes = append_notes(document.notes.take(), args.notes.as_deref());
589
590 self.persist_document_and_payload("created", "Plan task tracker created successfully.".to_string(), &document)
591 .await
592 }
593
594 async fn handle_update(&self, args: &PlanningTaskTrackerArgs) -> Result<Value> {
595 validate_update_shape(args.items.as_deref(), args.index, args.index_path.as_deref(), args.status.as_deref())?;
596 let is_bulk_update =
597 is_bulk_sync_update(args.items.as_deref(), args.index, args.index_path.as_deref(), args.status.as_deref());
598 let mut document = self
599 .load_document()
600 .await?
601 .context("No active plan tracker. Use action='create' first.")?;
602 let previous = document.clone();
603
604 if is_bulk_update {
605 let input_items = args.items.as_deref().unwrap_or(&[]);
606 let flat_lines = build_flat_task_lines(input_items, &document.items)?;
607 if flat_lines.is_empty() {
608 bail!("No valid items provided for checklist sync");
609 }
610 if let Some(title) = args.title.as_deref() {
611 document.title = title.to_string();
612 }
613 document.items = build_tree_from_flat(&flat_lines);
614 document.notes = append_notes(document.notes.take(), args.notes.as_deref());
615
616 return self
617 .persist_update(&previous, &document, "Checklist synchronized from provided items.".to_string())
618 .await;
619 }
620
621 let index_path = args
622 .index_path
623 .clone()
624 .or_else(|| args.index.map(|value| value.to_string()))
625 .context(
626 "'index_path' is required for 'update' (example: \"2.1\"), or provide 'index' for top-level compatibility",
627 )?;
628 let path = parse_index_path(&index_path)?;
629 let status_str = args
630 .status
631 .as_deref()
632 .context("'status' is required for 'update' (pending|in_progress|completed|blocked)")?;
633 let new_status = PlanTaskStatus::from_str(status_str)?;
634
635 let (old_status, new_status_str) = {
636 let node = get_node_mut_by_index_path(document.items.as_mut_slice(), &path)
637 .with_context(|| format!("No item at index_path '{index_path}'"))?;
638 let old_status = node.status.as_str().to_string();
639 node.status = new_status;
640 apply_metadata_input(
641 &mut node.metadata,
642 args.files.as_deref(),
643 args.outcome.as_deref(),
644 args.verify.as_deref(),
645 );
646 (old_status, node.status.as_str().to_string())
647 };
648
649 document.notes = append_notes(document.notes.take(), args.notes.as_deref());
650
651 self.persist_update(
652 &previous,
653 &document,
654 format!("Item {index_path} status changed: {old_status} -> {new_status_str}"),
655 )
656 .await
657 }
658
659 async fn persist_update(
660 &self,
661 previous: &PlanTaskDocument,
662 document: &PlanTaskDocument,
663 message: String,
664 ) -> Result<Value> {
665 let (status, message) = if previous == document {
666 ("unchanged", "Checklist already matches requested state.".to_string())
667 } else {
668 ("updated", message)
669 };
670 self.persist_document_and_payload(status, message, document).await
671 }
672
673 async fn handle_list(&self) -> Result<Value> {
674 let tracker_file = self.tracker_file().await?;
675 match self.load_document().await? {
676 Some(document) => {
677 Ok(self.success_payload("ok", "Plan task tracker loaded.".to_string(), &tracker_file, &document))
678 }
679 None => Ok(json!({
680 "status": "empty",
681 "message": "No active plan tracker. Use action='create' to start one.",
682 "tracker_file": self.display_path(&tracker_file),
683 })),
684 }
685 }
686
687 async fn handle_add(&self, args: &PlanningTaskTrackerArgs) -> Result<Value> {
688 let mut document = self
689 .load_document()
690 .await?
691 .context("No active plan tracker. Use action='create' first.")?;
692
693 let description = args.description.as_deref().context("'description' is required for 'add'")?;
694 let (status, parsed_description) = parse_status_prefix(description);
695 let node = PlanTaskNode {
696 description: parsed_description.trim().to_string(),
697 status,
698 metadata: metadata_from_input(args.files.as_deref(), args.outcome.as_deref(), args.verify.as_deref()),
699 children: Vec::new(),
700 };
701 if node.description.is_empty() {
702 bail!("description cannot be empty");
703 }
704
705 if let Some(parent_path_str) = args.parent_index_path.as_deref() {
706 let parent_path = parse_index_path(parent_path_str)?;
707 let parent = get_node_mut_by_index_path(document.items.as_mut_slice(), &parent_path)
708 .with_context(|| format!("No parent item at parent_index_path '{parent_path_str}'"))?;
709 parent.children.push(node);
710 } else {
711 document.items.push(node);
712 }
713
714 document.notes = append_notes(document.notes.take(), args.notes.as_deref());
715
716 self.persist_document_and_payload("added", "Plan task added successfully.".to_string(), &document)
717 .await
718 }
719}
720
721#[async_trait]
722impl Tool for PlanningTaskTrackerTool {
723 async fn execute(&self, args: Value) -> Result<Value> {
724 let args: PlanningTaskTrackerArgs = deserialize_tool_args(&args, "task_tracker")?;
725 validate_action_index_fields(&args.action, args.index, args.index_path.as_deref())?;
726
727 match args.action.as_str() {
728 "create" => self.handle_create(&args).await,
729 "update" => self.handle_update(&args).await,
730 "list" => self.handle_list().await,
731 "add" => self.handle_add(&args).await,
732 other => Ok(json!({
733 "status": "error",
734 "message": format!("Unknown action '{}'. Use: create, update, list, add", other),
735 })),
736 }
737 }
738
739 fn name(&self) -> &str {
740 tools::TASK_TRACKER
741 }
742
743 fn description(&self) -> &str {
744 super::task_tracker::task_tracker_description_for_workflow(true)
745 }
746
747 fn parameter_schema(&self) -> Option<Value> {
748 Some(planning_task_tracker_parameter_schema())
749 }
750
751 fn is_mutating(&self) -> bool {
752 false
753 }
754
755 fn is_parallel_safe(&self) -> bool {
756 false
757 }
758}
759
760#[cfg(test)]
761mod tests {
762 use super::*;
763 use tempfile::TempDir;
764
765 async fn setup_planning_workflow() -> (TempDir, PlanningWorkflowState, PlanningTaskTrackerTool) {
766 let temp_dir = TempDir::new().expect("temp dir");
767 let state = PlanningWorkflowState::new(temp_dir.path().to_path_buf());
768 let plans_dir = state.plans_dir();
769 std::fs::create_dir_all(&plans_dir).expect("create plans dir");
770 let plan_file = plans_dir.join("test-plan.md");
771 std::fs::write(&plan_file, "# Test Plan\n").expect("write plan");
772 state.set_plan_file(Some(plan_file)).await;
773 state.enable();
774
775 let tool = PlanningTaskTrackerTool::new(state.clone());
776 (temp_dir, state, tool)
777 }
778
779 #[tokio::test]
780 async fn create_and_list_tracker_with_hierarchy() {
781 let (_temp_dir, _state, tool) = setup_planning_workflow().await;
782
783 let created = tool
784 .execute(json!({
785 "action": "create",
786 "title": "Updated Plan",
787 "items": [
788 "Add config cap",
789 " Use cap in guard logic",
790 "[~] Expose setting in template"
791 ]
792 }))
793 .await
794 .expect("create tracker");
795
796 assert_eq!(created["status"], "created");
797 assert_eq!(created["checklist"]["total"], 3);
798 assert_eq!(created["checklist"]["in_progress"], 1);
799 assert_eq!(created["view"]["title"], "Updated Plan");
800 assert_eq!(created["tracker_file"], ".vtcode/plans/test-plan.tasks.md");
801
802 let lines = created["view"]["lines"].as_array().expect("view lines array");
803 assert!(!lines.is_empty());
804 let first = lines[0]["display"].as_str().unwrap_or_default();
805 assert!(first.contains('└') || first.contains('├'));
806 }
807
808 #[tokio::test]
809 async fn create_accepts_metadata_and_verify_string_forms() {
810 let (_temp_dir, _state, tool) = setup_planning_workflow().await;
811
812 let created = tool
813 .execute(json!({
814 "action": "create",
815 "title": "Harness plan",
816 "items": [
817 {
818 "description": "Analyze",
819 "files": ["docs/ARCHITECTURE.md"],
820 "outcome": "Map the harness",
821 "verify": "cargo check"
822 },
823 {
824 "description": "Implement",
825 "verify": ["cargo test -p vtcode-core task_tracker", "cargo check -p vtcode"]
826 }
827 ]
828 }))
829 .await
830 .expect("create tracker");
831
832 assert_eq!(created["checklist"]["items"][0]["files"], json!(["docs/ARCHITECTURE.md"]));
833 assert_eq!(created["checklist"]["items"][0]["outcome"], "Map the harness");
834 assert_eq!(created["checklist"]["items"][0]["verify"], json!(["cargo check"]));
835 assert_eq!(
836 created["checklist"]["items"][1]["verify"],
837 json!(["cargo test -p vtcode-core task_tracker", "cargo check -p vtcode"])
838 );
839 }
840
841 #[tokio::test]
842 async fn scope_review_survives_resume_bulk_sync_and_global_mirror() {
843 let (temp, state, tool) = setup_planning_workflow().await;
844 tool.execute(json!({
845 "action": "create", "items": [{
846 "description": "Review final scope", "files": ["README.md"],
847 "scope_review": ["git status --porcelain", "git diff --stat HEAD -- README.md"]
848 }]
849 }))
850 .await
851 .expect("create scope tracker");
852 let resumed = PlanningTaskTrackerTool::new(state);
853 let updated = resumed
854 .execute(json!({
855 "action": "update", "items": ["[x] Review final scope"]
856 }))
857 .await
858 .expect("bulk status update");
859 assert_eq!(
860 updated["checklist"]["items"][0]["scope_review"],
861 json!(["git status --porcelain", "git diff --stat HEAD -- README.md"])
862 );
863 assert_eq!(updated["checklist"]["items"][0]["verify"], json!([]));
864 for path in [".vtcode/plans/test-plan.tasks.md", ".vtcode/tasks/current_task.md"] {
865 let persisted = std::fs::read_to_string(temp.path().join(path)).expect("persisted tracker");
866 assert!(persisted.contains("[x] Review final scope"));
867 assert_eq!(persisted.matches(" scope-review:").count(), 2);
868 assert!(!persisted.contains(" verify:"));
869 }
870 }
871
872 #[tokio::test]
873 async fn add_and_update_nested_item() {
874 let (_temp_dir, _state, tool) = setup_planning_workflow().await;
875
876 tool.execute(json!({
877 "action": "create",
878 "items": ["Parent task"]
879 }))
880 .await
881 .expect("create tracker");
882
883 tool.execute(json!({
884 "action": "add",
885 "parent_index_path": "1",
886 "description": "Child task"
887 }))
888 .await
889 .expect("add nested task");
890
891 let updated = tool
892 .execute(json!({
893 "action": "update",
894 "index_path": "1.1",
895 "status": "completed"
896 }))
897 .await
898 .expect("update nested task");
899
900 assert_eq!(updated["status"], "updated");
901 assert_eq!(updated["checklist"]["completed"], 1);
902 }
903
904 #[tokio::test]
905 async fn persistence_across_instances() {
906 let (_temp_dir, state, tool) = setup_planning_workflow().await;
907
908 tool.execute(json!({
909 "action": "create",
910 "items": ["Persisted step"]
911 }))
912 .await
913 .expect("create tracker");
914
915 tool.execute(json!({
916 "action": "update",
917 "index_path": "1",
918 "status": "completed"
919 }))
920 .await
921 .expect("update tracker");
922
923 let tool2 = PlanningTaskTrackerTool::new(state);
924 let listed = tool2.execute(json!({"action": "list"})).await.expect("list tracker");
925
926 assert_eq!(listed["status"], "ok");
927 assert_eq!(listed["checklist"]["completed"], 1);
928 }
929
930 #[tokio::test]
931 async fn update_supports_bulk_item_sync_and_global_mirror() {
932 let (temp_dir, _state, tool) = setup_planning_workflow().await;
933
934 tool.execute(json!({
935 "action": "create",
936 "items": ["Step 1", "Step 2"]
937 }))
938 .await
939 .expect("create tracker");
940
941 let updated = tool
942 .execute(json!({
943 "action": "update",
944 "items": ["[x] Step 1", "[~] Step 2", "[ ] Step 3"]
945 }))
946 .await
947 .expect("bulk update");
948
949 assert_eq!(updated["status"], "updated");
950 assert_eq!(updated["checklist"]["completed"], 1);
951 assert_eq!(updated["checklist"]["in_progress"], 1);
952 assert_eq!(updated["checklist"]["pending"], 1);
953
954 let mirrored = temp_dir.path().join(".vtcode").join("tasks").join("current_task.md");
955 let mirrored_content = std::fs::read_to_string(mirrored).expect("read mirrored checklist");
956 assert!(mirrored_content.contains("Step 3"));
957 }
958
959 #[tokio::test]
960 async fn update_accepts_flat_index_fallback() {
961 let (_temp_dir, _state, tool) = setup_planning_workflow().await;
962
963 tool.execute(json!({
964 "action": "create",
965 "items": ["Parent task"]
966 }))
967 .await
968 .expect("create tracker");
969
970 let updated = tool
971 .execute(json!({
972 "action": "update",
973 "index": 1,
974 "status": "completed"
975 }))
976 .await
977 .expect("flat-index update");
978
979 assert_eq!(updated["status"], "updated");
980 assert_eq!(updated["checklist"]["completed"], 1);
981 }
982
983 #[tokio::test]
984 async fn update_rejects_zero_flat_index_even_for_checklist_completion() {
985 let (_temp_dir, _state, tool) = setup_planning_workflow().await;
986
987 tool.execute(json!({
988 "action": "create",
989 "items": ["Parent task"]
990 }))
991 .await
992 .expect("create tracker");
993
994 let error = tool
995 .execute(json!({
996 "action": "update",
997 "index": 0,
998 "status": "completed"
999 }))
1000 .await
1001 .expect_err("planning index zero must be rejected");
1002
1003 assert!(error.to_string().contains("index_path components must be >= 1"));
1004 }
1005
1006 #[tokio::test]
1007 async fn planning_task_tracker_schema_requires_positive_indices() {
1008 let (_temp_dir, _state, tool) = setup_planning_workflow().await;
1009 let schema = tool.parameter_schema().expect("planning task tracker schema");
1010
1011 assert_eq!(schema["properties"]["index"]["minimum"], 1);
1012 let items_description = schema["properties"]["items"]["description"].as_str().unwrap();
1013 assert!(items_description.contains("Full checklist replacement"));
1014 assert!(items_description.contains("never JSON-encoded strings"));
1015 assert!(items_description.contains("2-space indentation"));
1016 assert_eq!(schema["properties"]["index_path"]["pattern"], "^[1-9][0-9]*(\\.[1-9][0-9]*)*$");
1017 assert!(
1018 schema["properties"]["index_path"]["description"]
1019 .as_str()
1020 .expect("index path description")
1021 .contains("positive")
1022 );
1023 }
1024
1025 #[tokio::test]
1026 async fn planning_task_tracker_schema_rejects_mixed_bulk_and_single_updates() {
1027 let (_temp_dir, _state, tool) = setup_planning_workflow().await;
1028 let schema = tool.parameter_schema().expect("planning task tracker schema");
1029 let invalid_cases = [
1030 json!({"action": "list", "index": 1}),
1031 json!({"action": "list", "index_path": "1"}),
1032 json!({"action": "create", "index": 1, "items": ["New item"]}),
1033 json!({"action": "add", "index_path": "1", "description": "New item"}),
1034 json!({"action": "update", "items": ["Done"], "index": 1, "status": "completed"}),
1035 json!({"action": "update", "items": ["Done"], "index_path": "1.1", "status": "completed"}),
1036 json!({"action": "update", "index": 1, "index_path": "1.1", "status": "completed"}),
1037 json!({"action": "update", "items": ["Done"], "status": "completed"}),
1038 ];
1039
1040 for args in invalid_cases {
1041 assert!(jsonschema::validate(&schema, &args).is_err(), "expected invalid args: {args}");
1042 }
1043 }
1044
1045 #[tokio::test]
1046 async fn bulk_update_rejects_encoded_commands_without_resetting_completed_steps() {
1047 let (_temp_dir, _state, tool) = setup_planning_workflow().await;
1048 tool.execute(json!({
1049 "action": "create",
1050 "title": "Preserve progress",
1051 "items": [
1052 {"description": "Update introduction", "status": "completed", "files": ["README.md"], "outcome": "Clear overview", "verify": ["review headings"]},
1053 {"description": "Review links", "status": "blocked", "outcome": "Await network"}
1054 ]
1055 })).await.unwrap();
1056 let tracker_path = _temp_dir.path().join(".vtcode/tasks/current_task.md");
1057 let persisted_before = std::fs::read_to_string(&tracker_path).unwrap();
1058 let before = tool.execute(json!({"action": "list"})).await.unwrap();
1059
1060 for (action, encoded) in [
1061 ("update", r#"{"index_path":"1","status":"completed","outcome":"Done","verify":"review headings"}"#),
1062 ("update", r#" [x] {"index_path":"1","status":"completed"}"#),
1063 ("create", r#"{"index":1,"status":"completed"}"#),
1064 ] {
1065 let error = tool
1066 .execute(json!({
1067 "action": action,
1068 "title": "Incorrect replacement",
1069 "items": ["Replacement must not leak", encoded]
1070 }))
1071 .await
1072 .expect_err("encoded updates must not replace the tracker");
1073 assert!(error.to_string().contains("JSON-encoded task updates"));
1074 assert!(
1075 error
1076 .to_string()
1077 .contains(r#"{"action":"update","index_path":"1","status":"completed"}"#)
1078 );
1079 assert_eq!(tool.execute(json!({"action": "list"})).await.unwrap(), before);
1080 assert_eq!(std::fs::read_to_string(&tracker_path).unwrap(), persisted_before);
1081 }
1082
1083 tool.execute(json!({"action": "update", "index_path": "2", "status": "completed"}))
1084 .await
1085 .unwrap();
1086 let after = tool.execute(json!({"action": "list"})).await.unwrap();
1087 assert_eq!(after["checklist"]["completed"], 2);
1088 assert_eq!(after["checklist"]["items"][0]["description"], "Update introduction");
1089 assert_eq!(after["checklist"]["items"][0]["files"], json!(["README.md"]));
1090 }
1091
1092 #[tokio::test]
1093 async fn planning_update_rejects_mixed_bulk_and_single_fields_before_mutation() {
1094 let (_temp_dir, _state, tool) = setup_planning_workflow().await;
1095
1096 tool.execute(json!({
1097 "action": "create",
1098 "items": ["Original"]
1099 }))
1100 .await
1101 .expect("create tracker");
1102
1103 let error = tool
1104 .execute(json!({
1105 "action": "update",
1106 "items": ["Replacement"],
1107 "index_path": "1",
1108 "status": "completed"
1109 }))
1110 .await
1111 .expect_err("mixed update must fail closed");
1112 assert!(error.to_string().contains("cannot combine 'items'"));
1113
1114 let result = tool.execute(json!({"action": "list"})).await.unwrap();
1115 assert_eq!(result["checklist"]["items"][0]["description"], "Original");
1116 assert_eq!(result["checklist"]["items"][0]["status"], "pending");
1117 }
1118
1119 #[tokio::test]
1120 async fn planning_update_rejects_both_index_forms_before_mutation() {
1121 let (_temp_dir, _state, tool) = setup_planning_workflow().await;
1122
1123 tool.execute(json!({
1124 "action": "create",
1125 "items": ["Original"]
1126 }))
1127 .await
1128 .expect("create tracker");
1129
1130 let error = tool
1131 .execute(json!({
1132 "action": "update",
1133 "index": 1,
1134 "index_path": "1",
1135 "status": "completed"
1136 }))
1137 .await
1138 .expect_err("ambiguous index forms must fail closed");
1139 assert!(error.to_string().contains("cannot combine 'index' and 'index_path'"));
1140
1141 let result = tool.execute(json!({"action": "list"})).await.unwrap();
1142 assert_eq!(result["checklist"]["items"][0]["description"], "Original");
1143 assert_eq!(result["checklist"]["items"][0]["status"], "pending");
1144 }
1145
1146 #[tokio::test]
1147 async fn execute_rejects_indices_for_non_update_actions() {
1148 let (_temp_dir, _state, tool) = setup_planning_workflow().await;
1149
1150 let invalid_inputs = [
1151 json!({"action": "list", "index": 1}),
1152 json!({"action": "create", "index_path": "1", "items": ["New item"]}),
1153 json!({"action": "add", "index": 1, "description": "New item"}),
1154 json!({"action": "unexpected", "index_path": "1"}),
1155 ];
1156
1157 for input in invalid_inputs {
1158 let error = tool.execute(input).await.expect_err("non-update index must fail closed");
1159 assert!(error.to_string().contains("cannot use 'index' or 'index_path'"), "unexpected error: {error}");
1160 }
1161 }
1162
1163 #[tokio::test]
1164 async fn rejects_when_planning_workflow_is_inactive() {
1165 let temp_dir = TempDir::new().expect("temp dir");
1166 let state = PlanningWorkflowState::new(temp_dir.path().to_path_buf());
1167 let tool = PlanningTaskTrackerTool::new(state);
1168
1169 let err = tool
1170 .execute(json!({"action": "list"}))
1171 .await
1172 .expect_err("should fail outside planning workflow");
1173
1174 assert!(err.to_string().contains("only available while planning"));
1175 }
1176}