1use std::str::FromStr;
2
3use anyhow::{Result, bail};
4use hashbrown::HashMap;
5use serde::{Deserialize, Serialize};
6use serde_json::{Value, json};
7
8mod persistence;
9pub(crate) use persistence::{
10 TrackerArtifact, persist_tracker_artifacts, read_tracker_artifact, write_tracker_artifact,
11};
12
13#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, Default)]
14pub struct TaskStepMetadata {
15 #[serde(default, skip_serializing_if = "Vec::is_empty")]
16 pub files: Vec<String>,
17 #[serde(default, skip_serializing_if = "Option::is_none")]
18 pub outcome: Option<String>,
19 #[serde(default, skip_serializing_if = "Vec::is_empty")]
20 pub verify: Vec<String>,
21}
22
23#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
24#[serde(untagged)]
25pub enum TaskItemInput {
26 Text(String),
27 Structured(TaskItemInputObject),
28}
29
30#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, Default)]
31pub struct TaskItemInputObject {
32 pub description: String,
33 #[serde(default)]
34 pub status: Option<String>,
35 #[serde(default, deserialize_with = "deserialize_optional_string_list")]
36 pub files: Option<Vec<String>>,
37 #[serde(default)]
38 pub outcome: Option<String>,
39 #[serde(default, deserialize_with = "deserialize_optional_string_list")]
40 pub verify: Option<Vec<String>>,
41}
42
43pub(crate) struct TaskMetadataRef<'a> {
44 pub description: &'a str,
45 pub metadata: &'a TaskStepMetadata,
46}
47
48pub(crate) struct ParsedTaskItem {
49 pub level: usize,
50 pub description: String,
51 pub status: TaskTrackingStatus,
52 pub metadata: TaskStepMetadata,
53}
54
55pub(crate) fn parse_task_items(
59 items: &[TaskItemInput],
60 previous: &[TaskMetadataRef<'_>],
61) -> Result<Vec<ParsedTaskItem>> {
62 validate_task_item_inputs(items)?;
63 let mut previous_by_description = HashMap::new();
64 for item in previous {
65 previous_by_description
66 .entry(item.description.trim())
67 .and_modify(|metadata| *metadata = None)
68 .or_insert(Some(item.metadata));
69 }
70 let mut description_counts = HashMap::new();
71 for item in items {
72 let raw = match item {
73 TaskItemInput::Text(raw) => raw,
74 TaskItemInput::Structured(input) => &input.description,
75 };
76 let (_, description) = parse_status_prefix(raw.trim());
77 *description_counts.entry(description.trim().to_owned()).or_insert(0usize) += 1;
78 }
79
80 let mut parsed_items = Vec::with_capacity(items.len());
81 for item in items {
82 let raw = match item {
83 TaskItemInput::Text(raw) => raw,
84 TaskItemInput::Structured(input) => &input.description,
85 };
86 let (mut status, description) = parse_status_prefix(raw.trim());
87 let description = description.trim().to_owned();
88 if description.is_empty() {
89 continue;
90 }
91 let previous_metadata = if description_counts.get(&description) == Some(&1) {
92 previous_by_description.get(description.as_str()).copied().flatten()
93 } else {
94 None
95 };
96 if previous_metadata.is_none()
97 && previous
98 .iter()
99 .any(|item| item.description.trim() == description && item.metadata != &TaskStepMetadata::default())
100 && !matches!(item, TaskItemInput::Structured(input) if input.files.is_some() && input.outcome.is_some() && input.verify.is_some())
101 {
102 bail!(
103 "Ambiguous task description '{description}': provide explicit files, outcome, and verify metadata for duplicate steps. Use empty arrays and an empty outcome to clear them. The checklist was not changed."
104 );
105 }
106 let mut metadata = previous_metadata.cloned().unwrap_or_default();
107 if let TaskItemInput::Structured(input) = item {
108 if let Some(raw_status) = input.status.as_deref() {
109 status = TaskTrackingStatus::from_str(raw_status)?;
110 }
111 apply_metadata_input(
112 &mut metadata,
113 input.files.as_deref(),
114 input.outcome.as_deref(),
115 input.verify.as_deref(),
116 );
117 }
118 parsed_items.push(ParsedTaskItem {
119 level: raw.chars().take_while(|character| *character == ' ').count() / 2,
120 description,
121 status,
122 metadata,
123 });
124 }
125 Ok(parsed_items)
126}
127
128pub(crate) fn apply_metadata_input(
129 metadata: &mut TaskStepMetadata,
130 files: Option<&[String]>,
131 outcome: Option<&str>,
132 verify: Option<&[String]>,
133) {
134 if let Some(files) = files {
135 metadata.files = normalize_string_items(Some(files));
136 }
137 if let Some(outcome) = outcome {
138 metadata.outcome = normalize_optional_text(Some(outcome));
139 }
140 if let Some(verify) = verify {
141 metadata.verify = normalize_verify_items(verify.iter().map(String::as_str));
142 }
143}
144
145#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
146#[serde(rename_all = "snake_case")]
147pub enum TaskTrackingStatus {
148 Pending,
149 InProgress,
150 Completed,
151 Blocked,
152}
153
154impl std::fmt::Display for TaskTrackingStatus {
155 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
156 write!(f, "{}", self.as_str())
157 }
158}
159
160impl FromStr for TaskTrackingStatus {
161 type Err = anyhow::Error;
162
163 fn from_str(value: &str) -> Result<Self> {
164 match value {
165 "pending" => Ok(Self::Pending),
166 "in_progress" => Ok(Self::InProgress),
167 "completed" => Ok(Self::Completed),
168 "blocked" => Ok(Self::Blocked),
169 other => {
170 bail!("Invalid status '{other}'. Use: pending, in_progress, completed, blocked")
171 }
172 }
173 }
174}
175
176impl TaskTrackingStatus {
177 pub fn as_str(&self) -> &'static str {
178 match self {
179 Self::Pending => "pending",
180 Self::InProgress => "in_progress",
181 Self::Completed => "completed",
182 Self::Blocked => "blocked",
183 }
184 }
185
186 pub fn flat_checkbox(&self) -> &'static str {
187 match self {
188 Self::Pending => "[ ]",
189 Self::InProgress => "[/]",
190 Self::Completed => "[x]",
191 Self::Blocked => "[!]",
192 }
193 }
194
195 pub fn plan_checkbox(&self) -> &'static str {
196 match self {
197 Self::Pending => "[ ]",
198 Self::InProgress => "[~]",
199 Self::Completed => "[x]",
200 Self::Blocked => "[!]",
201 }
202 }
203
204 pub fn view_symbol(&self) -> &'static str {
205 match self {
206 Self::Pending => "•",
207 Self::InProgress => ">",
208 Self::Completed => "✔",
209 Self::Blocked => "!",
210 }
211 }
212
213 pub fn compact_view_symbol(&self) -> &'static str {
214 match self {
215 Self::Pending => "□",
216 Self::InProgress => "[-]",
217 Self::Completed => "[x]",
218 Self::Blocked => "[!]",
219 }
220 }
221}
222
223pub fn parse_marked_status_prefix(value: &str) -> Option<(TaskTrackingStatus, String)> {
224 let trimmed = value.trim_start();
225 let mapping = [
226 ("[x] ", TaskTrackingStatus::Completed),
227 ("[X] ", TaskTrackingStatus::Completed),
228 ("[~] ", TaskTrackingStatus::InProgress),
229 ("[/] ", TaskTrackingStatus::InProgress),
230 ("[!] ", TaskTrackingStatus::Blocked),
231 ("[ ] ", TaskTrackingStatus::Pending),
232 ];
233 for (prefix, status) in mapping {
234 if let Some(rest) = trimmed.strip_prefix(prefix) {
235 return Some((status, rest.to_string()));
236 }
237 }
238 None
239}
240
241pub fn parse_status_prefix(value: &str) -> (TaskTrackingStatus, String) {
242 parse_marked_status_prefix(value).unwrap_or((TaskTrackingStatus::Pending, value.trim_start().to_string()))
243}
244
245pub fn append_notes(existing: Option<String>, append: Option<&str>) -> Option<String> {
246 match (existing, append) {
247 (None, None) => None,
248 (Some(text), None) => {
249 if text.trim().is_empty() {
250 None
251 } else {
252 Some(text)
253 }
254 }
255 (None, Some(extra)) => {
256 let trimmed = extra.trim();
257 if trimmed.is_empty() {
258 None
259 } else {
260 Some(trimmed.to_string())
261 }
262 }
263 (Some(text), Some(extra)) => {
264 let left = text.trim();
265 let right = extra.trim();
266 if left.is_empty() && right.is_empty() {
267 None
268 } else if left.is_empty() {
269 Some(right.to_string())
270 } else if right.is_empty() {
271 Some(left.to_string())
272 } else {
273 Some(format!("{left}\n{right}"))
274 }
275 }
276 }
277}
278
279pub fn append_notes_section(markdown: &mut String, notes: Option<&str>) {
280 if let Some(text) = notes {
281 let trimmed = text.trim();
282 if !trimmed.is_empty() {
283 markdown.push_str("\n## Notes\n\n");
284 markdown.push_str(trimmed);
285 markdown.push('\n');
286 }
287 }
288}
289
290pub(crate) fn validate_update_shape<T>(
291 items: Option<&[T]>,
292 index: Option<usize>,
293 index_path: Option<&str>,
294 status: Option<&str>,
295) -> Result<()> {
296 if index.is_some() && index_path.is_some() {
297 bail!("task-tracker updates cannot combine 'index' and 'index_path'");
298 }
299
300 if items.is_some() && (index.is_some() || index_path.is_some() || status.is_some()) {
301 bail!("bulk task-tracker updates cannot combine 'items' with 'index', 'index_path', or 'status'");
302 }
303
304 Ok(())
305}
306
307pub(crate) fn validate_action_index_fields(action: &str, index: Option<usize>, index_path: Option<&str>) -> Result<()> {
308 if action != "update" && (index.is_some() || index_path.is_some()) {
309 bail!(
310 "task-tracker action '{action}' cannot use 'index' or 'index_path'; indices are only valid with action='update'"
311 );
312 }
313
314 Ok(())
315}
316
317pub(crate) const TASK_ITEMS_DESCRIPTION: &str = "Full checklist replacement for create or bulk update, not indexed updates. Send plain descriptions with [x]/[~]/[!]/[ ] status prefixes or actual objects with description and status; never JSON-encoded strings. Bulk updates preserve omitted metadata for unique unchanged descriptions. Explicit metadata replaces it; use empty arrays or an empty outcome to clear fields. Duplicate descriptions with existing metadata require explicit files, outcome, and verify.";
318
319pub(crate) const TASK_STATUS_VALUES: [&str; 4] = ["pending", "in_progress", "completed", "blocked"];
323
324pub(crate) fn task_status_schema() -> Value {
326 json!({
327 "type": "string",
328 "enum": TASK_STATUS_VALUES
329 })
330}
331
332pub(crate) fn task_files_schema() -> Value {
334 json!({
335 "type": "array",
336 "items": { "type": "string" }
337 })
338}
339
340pub(crate) fn task_verify_schema() -> Value {
342 json!({
343 "anyOf": [
344 { "type": "string" },
345 {
346 "type": "array",
347 "items": { "type": "string" }
348 }
349 ]
350 })
351}
352
353fn with_description(mut schema: Value, description: &str) -> Value {
354 if let Value::Object(map) = &mut schema {
355 map.insert("description".to_string(), Value::String(description.to_string()));
356 }
357 schema
358}
359
360pub(crate) fn tracker_schema_allof(include_index_zero_rule: bool) -> Vec<Value> {
369 let mut allof = vec![
370 json!({
371 "if": {
372 "properties": { "action": { "const": "create" } },
373 "required": ["action"]
374 },
375 "then": {
376 "required": ["items"]
377 }
378 }),
379 json!({
380 "if": {
381 "properties": { "action": { "const": "update" } },
382 "required": ["action"]
383 },
384 "then": {
385 "anyOf": [
386 {
387 "required": ["index", "status"],
388 "not": {
389 "anyOf": [
390 { "required": ["items"] },
391 { "required": ["index_path"] }
392 ]
393 }
394 },
395 {
396 "required": ["index_path", "status"],
397 "not": {
398 "anyOf": [
399 { "required": ["items"] },
400 { "required": ["index"] }
401 ]
402 }
403 },
404 {
405 "required": ["items"],
406 "not": {
407 "anyOf": [
408 { "required": ["index"] },
409 { "required": ["index_path"] },
410 { "required": ["status"] }
411 ]
412 }
413 }
414 ]
415 }
416 }),
417 json!({
418 "if": {
419 "properties": { "action": { "enum": ["create", "list", "add"] } },
420 "required": ["action"]
421 },
422 "then": {
423 "not": {
424 "anyOf": [
425 { "required": ["index"] },
426 { "required": ["index_path"] }
427 ]
428 }
429 }
430 }),
431 json!({
432 "if": {
433 "properties": { "action": { "const": "add" } },
434 "required": ["action"]
435 },
436 "then": {
437 "required": ["description"]
438 }
439 }),
440 ];
441 if include_index_zero_rule {
442 allof.insert(
443 2,
444 json!({
445 "if": {
446 "properties": { "index": { "const": 0 } },
447 "required": ["index"]
448 },
449 "then": {
450 "properties": {
451 "action": { "const": "update" },
452 "status": { "const": "completed" }
453 },
454 "required": ["action", "status"]
455 }
456 }),
457 );
458 }
459 allof
460}
461
462pub(crate) fn task_item_object_schema() -> Value {
465 json!({
466 "type": "object",
467 "properties": {
468 "description": { "type": "string" },
469 "status": task_status_schema(),
470 "files": task_files_schema(),
471 "outcome": { "type": "string" },
472 "verify": task_verify_schema()
473 },
474 "required": ["description"]
475 })
476}
477
478pub(crate) fn task_items_array_schema(items_description: &str) -> Value {
480 with_description(
481 json!({
482 "type": "array",
483 "items": {
484 "anyOf": [
485 { "type": "string" },
486 task_item_object_schema()
487 ]
488 }
489 }),
490 items_description,
491 )
492}
493
494pub(crate) fn task_status_property_schema(description: &str) -> Value {
496 with_description(task_status_schema(), description)
497}
498
499pub(crate) fn task_files_property_schema(description: &str) -> Value {
501 with_description(task_files_schema(), description)
502}
503
504pub(crate) fn task_verify_property_schema(description: &str) -> Value {
506 with_description(task_verify_schema(), description)
507}
508
509pub(crate) fn validate_task_item_inputs(items: &[TaskItemInput]) -> Result<()> {
511 for item in items {
512 let TaskItemInput::Text(text) = item else {
513 continue;
514 };
515 let (_, description) = parse_status_prefix(text.trim());
516 if let Ok(Value::Object(object)) = serde_json::from_str::<Value>(&description)
517 && ["index", "index_path", "description", "status"]
518 .iter()
519 .any(|key| object.contains_key(*key))
520 {
521 bail!(
522 "'items' replaces the complete checklist; JSON-encoded task updates are not task descriptions. \
523 Update an existing step directly: {{\"action\":\"update\",\"index_path\":\"1\",\"status\":\"completed\"}}. \
524 For full synchronization, send descriptions with statuses, for example \
525 {{\"action\":\"update\",\"items\":[{{\"description\":\"Original step\",\"status\":\"completed\"}}]}}. \
526 The checklist was not changed. Retry once with the intended shape."
527 );
528 }
529 }
530 Ok(())
531}
532
533pub fn is_bulk_sync_update<T>(
534 items: Option<&[T]>,
535 index: Option<usize>,
536 index_path: Option<&str>,
537 status: Option<&str>,
538) -> bool {
539 items.is_some() && index.is_none() && index_path.is_none() && status.is_none()
540}
541
542pub fn deserialize_optional_string_list<'de, D>(deserializer: D) -> std::result::Result<Option<Vec<String>>, D::Error>
543where
544 D: serde::Deserializer<'de>,
545{
546 #[derive(Deserialize)]
547 #[serde(untagged)]
548 enum OneOrMany {
549 One(String),
550 Many(Vec<String>),
551 }
552
553 let parsed = Option::<OneOrMany>::deserialize(deserializer)?;
554 Ok(parsed.map(|value| match value {
555 OneOrMany::One(item) => vec![item],
556 OneOrMany::Many(items) => items,
557 }))
558}
559
560pub(crate) fn unwrap_verify_code_span(command: &str) -> &str {
572 let trimmed = command.trim();
573 if trimmed.starts_with('`') && trimmed.ends_with('`') && trimmed.len() >= 2 {
574 let inner = &trimmed[1..trimmed.len() - 1];
575 if !inner.contains('`') {
576 return inner;
577 }
578 }
579 trimmed
580}
581
582pub(crate) fn normalize_verify_items<'a>(items: impl IntoIterator<Item = &'a str>) -> Vec<String> {
585 items
586 .into_iter()
587 .filter_map(|item| {
588 let unwrapped = unwrap_verify_code_span(item);
589 (!unwrapped.is_empty()).then(|| unwrapped.to_owned())
590 })
591 .collect()
592}
593
594pub fn normalize_string_items(items: Option<&[String]>) -> Vec<String> {
595 items
596 .unwrap_or(&[])
597 .iter()
598 .map(|item| item.trim())
599 .filter(|item| !item.is_empty())
600 .map(ToOwned::to_owned)
601 .collect()
602}
603
604pub fn normalize_optional_text(value: Option<&str>) -> Option<String> {
605 value.map(str::trim).filter(|value| !value.is_empty()).map(ToOwned::to_owned)
606}
607
608pub fn parse_files_metadata(value: &str) -> Vec<String> {
611 super::planning_workflow::split_bracket_items(value)
612 .into_iter()
613 .map(|item| item.trim().to_owned())
614 .filter(|item| !item.is_empty())
615 .collect()
616}
617
618pub fn apply_metadata_line(metadata: &mut TaskStepMetadata, raw: &str, in_verify_block: &mut bool) -> bool {
622 let trimmed = raw.trim_start();
623
624 if *in_verify_block {
625 if let Some(command) = trimmed
626 .strip_prefix("- ")
627 .or_else(|| trimmed.strip_prefix("* "))
628 .or_else(|| trimmed.strip_prefix("+ "))
629 {
630 if let Some(command) = normalize_verify_items([command]).pop() {
631 metadata.verify.push(command);
632 }
633 return true;
634 }
635 *in_verify_block = false;
636 }
637
638 if let Some(rest) = trimmed.strip_prefix("files:") {
639 metadata.files = parse_files_metadata(rest);
640 return true;
641 }
642 if let Some(rest) = trimmed.strip_prefix("outcome:") {
643 metadata.outcome = normalize_optional_text(Some(rest));
644 return true;
645 }
646 if trimmed == "verify:" {
647 metadata.verify.clear();
648 *in_verify_block = true;
649 return true;
650 }
651 if let Some(rest) = trimmed.strip_prefix("verify:") {
652 metadata.verify = normalize_verify_items([rest]);
653 return true;
654 }
655
656 false
657}
658
659pub fn append_task_step_metadata(markdown: &mut String, indent: &str, metadata: &TaskStepMetadata) {
660 if !metadata.files.is_empty() {
661 markdown.push_str(indent);
662 markdown.push_str(" files: ");
663 markdown.push_str(&metadata.files.join(", "));
664 markdown.push('\n');
665 }
666
667 if let Some(outcome) = metadata.outcome.as_deref() {
668 markdown.push_str(indent);
669 markdown.push_str(" outcome: ");
670 markdown.push_str(outcome);
671 markdown.push('\n');
672 }
673
674 if metadata.verify.len() == 1 {
675 markdown.push_str(indent);
676 markdown.push_str(" verify: ");
677 markdown.push_str(&metadata.verify[0]);
678 markdown.push('\n');
679 } else if !metadata.verify.is_empty() {
680 markdown.push_str(indent);
681 markdown.push_str(" verify:\n");
682 for command in &metadata.verify {
683 markdown.push_str(indent);
684 markdown.push_str(" - ");
685 markdown.push_str(command);
686 markdown.push('\n');
687 }
688 }
689}
690
691pub fn metadata_from_input(
692 files: Option<&[String]>,
693 outcome: Option<&str>,
694 verify: Option<&[String]>,
695) -> TaskStepMetadata {
696 let mut metadata = TaskStepMetadata::default();
697 apply_metadata_input(&mut metadata, files, outcome, verify);
698 metadata
699}
700
701const INLINE_TASK_METADATA_MARKERS: &[&str] = &[" -> files:", " -> verify:", " -> outcome:"];
706
707fn parse_inline_bracket_list(raw: &str) -> Vec<String> {
708 let trimmed = raw.trim();
709 let inner = trimmed
710 .strip_prefix('[')
711 .and_then(|value| value.strip_suffix(']'))
712 .unwrap_or(trimmed);
713 super::planning_workflow::split_bracket_items(inner)
714 .into_iter()
715 .map(|item| item.trim().to_owned())
716 .filter(|value| !value.is_empty())
717 .collect()
718}
719
720pub fn split_task_description_metadata(description: &str) -> (String, Vec<String>, Vec<String>) {
729 let normalized;
730 let source = if description.contains('→') {
731 normalized = description.replace('→', "->");
732 normalized.as_str()
733 } else {
734 description
735 };
736 let Some(first) = find_inline_metadata_marker(source, 0) else {
737 return (source.trim().to_string(), Vec::new(), Vec::new());
738 };
739 let head = source[..first.0].trim();
740 if head.is_empty() {
741 return (source.trim().to_string(), Vec::new(), Vec::new());
742 }
743
744 let mut files = Vec::new();
745 let mut verify = Vec::new();
746 let mut cursor = first.0;
747 while let Some((marker_start, marker)) = find_inline_metadata_marker(source, cursor) {
748 let value_start = marker_start + marker.len();
749 let next = find_inline_metadata_marker(source, value_start)
750 .map(|(start, _)| start)
751 .unwrap_or(source.len());
752 let value = source[value_start..next].trim();
753 if marker.contains("files:") {
754 files.extend(parse_inline_bracket_list(value));
755 } else if marker.contains("verify:") {
756 verify.extend(parse_inline_bracket_list(value));
757 }
758 cursor = next;
759 if cursor >= source.len() {
760 break;
761 }
762 }
763 (head.to_string(), files, verify)
764}
765
766pub fn strip_task_description_metadata(description: &str) -> String {
770 split_task_description_metadata(description).0
771}
772
773pub fn short_task_description(description: &str) -> String {
782 let (clean, _, _) = split_task_description_metadata(description);
783 let base = if clean.trim().is_empty() {
784 description.trim()
785 } else {
786 clean.trim()
787 };
788 let first_line = base.lines().map(str::trim).find(|line| !line.is_empty()).unwrap_or("");
789 let collapsed = vtcode_commons::formatting::collapse_whitespace(first_line);
790 if collapsed.is_empty() {
791 return String::new();
792 }
793 let mut cut = collapsed.len();
794 for separator in [" — ", " – ", " - ", ": ", "; ", ". ", " ("] {
795 if let Some(index) = collapsed.find(separator) {
796 cut = cut.min(index);
797 }
798 }
799 let short = collapsed[..cut].trim().trim_end_matches([',', ';', ':', '.']).trim();
800 if short.is_empty() { collapsed } else { short.to_string() }
801}
802
803fn find_inline_metadata_marker(source: &str, from: usize) -> Option<(usize, &'static str)> {
804 let mut inline_ticks: Option<usize> = None;
805 let mut cursor = from.min(source.len());
806 while cursor < source.len() {
807 let remainder = &source[cursor..];
808 if remainder.starts_with('`') {
809 let run = remainder.bytes().take_while(|byte| *byte == b'`').count();
810 if inline_ticks.is_some_and(|ticks| ticks == run) {
811 inline_ticks = None;
812 } else if inline_ticks.is_none() {
813 inline_ticks = Some(run);
814 }
815 cursor += run;
816 continue;
817 }
818 if inline_ticks.is_none() {
819 for marker in INLINE_TASK_METADATA_MARKERS {
820 if remainder.starts_with(marker) {
821 return Some((cursor, marker));
822 }
823 }
824 }
825 let character = remainder.chars().next()?;
826 cursor += character.len_utf8();
827 }
828 None
829}
830
831#[derive(Debug, Clone, PartialEq, Eq)]
836pub(crate) struct TaskTreeNode {
837 pub(crate) index_path: String,
838 pub(crate) description: String,
839 pub(crate) status: TaskTrackingStatus,
840 pub(crate) metadata: TaskStepMetadata,
841 pub(crate) children: Vec<TaskTreeNode>,
842}
843
844pub(crate) fn compact_task_tree_view(nodes: &[TaskTreeNode]) -> Vec<Value> {
849 let mut lines = Vec::new();
850 append_compact_task_tree_view(nodes, " ", &mut lines);
851 lines
852}
853
854fn append_compact_task_tree_view(nodes: &[TaskTreeNode], tree_prefix: &str, out: &mut Vec<Value>) {
855 for (index, node) in nodes.iter().enumerate() {
856 let is_last = index + 1 == nodes.len();
857 let branch = if is_last { "└" } else { "├" };
858 let display = if node.children.is_empty() {
859 if tree_prefix == " " {
860 format!("{tree_prefix}{branch} {} {}", node.status.compact_view_symbol(), node.description)
861 } else {
862 format!("{tree_prefix}{} {}", node.status.compact_view_symbol(), node.description)
863 }
864 } else {
865 format!("{tree_prefix}{branch} {}", node.description)
866 };
867
868 out.push(json!({
869 "display": display,
870 "index_path": node.index_path.clone(),
871 "status": node.status.as_str(),
872 "text": node.description.clone(),
873 "files": node.metadata.files.clone(),
874 "outcome": node.metadata.outcome.clone(),
875 "verify": node.metadata.verify.clone(),
876 }));
877
878 let next_prefix = if is_last {
879 format!("{tree_prefix} ")
880 } else {
881 format!("{tree_prefix}│ ")
882 };
883 append_compact_task_tree_view(&node.children, &next_prefix, out);
884 }
885}
886
887pub fn compact_task_tree_view_from_items(items: &[Value]) -> Vec<Value> {
893 let mut ordered_paths = Vec::with_capacity(items.len());
894 let mut nodes_by_path = std::collections::HashMap::with_capacity(items.len());
895
896 for (position, item) in items.iter().enumerate() {
897 let index_path = item
898 .get("index_path")
899 .and_then(Value::as_str)
900 .filter(|path| !path.trim().is_empty())
901 .map(ToOwned::to_owned)
902 .or_else(|| item.get("index").and_then(Value::as_u64).map(|index| index.to_string()))
903 .unwrap_or_else(|| (position + 1).to_string());
904 if nodes_by_path.contains_key(&index_path) {
905 continue;
906 }
907
908 let status = match item.get("status").and_then(Value::as_str) {
909 Some(value) => match TaskTrackingStatus::from_str(value) {
910 Ok(status) => status,
911 Err(_) => continue,
912 },
913 None => TaskTrackingStatus::Pending,
914 };
915 let Some(description) = item
916 .get("description")
917 .and_then(Value::as_str)
918 .or_else(|| item.get("text").and_then(Value::as_str))
919 .filter(|description| !description.trim().is_empty())
920 else {
921 continue;
922 };
923 let (clean_description, parsed_files, parsed_verify) = split_task_description_metadata(description);
930 let raw = if clean_description.trim().is_empty() {
931 description.trim()
932 } else {
933 clean_description.trim()
934 };
935 let description = short_task_description(raw);
936 let mut metadata = TaskStepMetadata {
937 files: string_array(item.get("files")),
938 outcome: item.get("outcome").and_then(Value::as_str).map(ToOwned::to_owned),
939 verify: string_or_string_array(item.get("verify")),
940 };
941 if metadata.files.is_empty() {
942 metadata.files = parsed_files;
943 }
944 if metadata.verify.is_empty() {
945 metadata.verify = parsed_verify;
946 }
947
948 ordered_paths.push(index_path.clone());
949 nodes_by_path.insert(
950 index_path.clone(),
951 TaskTreeNode {
952 index_path,
953 description,
954 status,
955 metadata,
956 children: Vec::new(),
957 },
958 );
959 }
960
961 let mut attachment_order = ordered_paths.clone();
962 attachment_order.sort_by_key(|path| std::cmp::Reverse(path.split('.').count()));
963 for path in attachment_order {
964 let Some(parent_path) = path.rsplit_once('.').map(|(parent, _)| parent.to_string()) else {
965 continue;
966 };
967 let Some(child) = nodes_by_path.remove(&path) else {
968 continue;
969 };
970 if let Some(parent) = nodes_by_path.get_mut(&parent_path) {
971 parent.children.push(child);
972 } else {
973 nodes_by_path.insert(path, child);
974 }
975 }
976
977 let roots = ordered_paths
978 .into_iter()
979 .filter_map(|path| nodes_by_path.remove(&path))
980 .collect::<Vec<_>>();
981 compact_task_tree_view(&roots)
982}
983
984fn string_array(value: Option<&Value>) -> Vec<String> {
985 value
986 .and_then(Value::as_array)
987 .into_iter()
988 .flatten()
989 .filter_map(Value::as_str)
990 .map(ToOwned::to_owned)
991 .collect()
992}
993
994fn string_or_string_array(value: Option<&Value>) -> Vec<String> {
995 match value {
996 Some(Value::String(value)) => vec![value.clone()],
997 Some(Value::Array(_)) => string_array(value),
998 _ => Vec::new(),
999 }
1000}
1001
1002#[derive(Default)]
1003pub struct TaskCounts {
1004 pub total: usize,
1005 pub completed: usize,
1006 pub in_progress: usize,
1007 pub pending: usize,
1008 pub blocked: usize,
1009}
1010
1011impl TaskCounts {
1012 pub fn add(&mut self, status: &TaskTrackingStatus) {
1013 self.total += 1;
1014 match status {
1015 TaskTrackingStatus::Pending => self.pending += 1,
1016 TaskTrackingStatus::InProgress => self.in_progress += 1,
1017 TaskTrackingStatus::Completed => self.completed += 1,
1018 TaskTrackingStatus::Blocked => self.blocked += 1,
1019 }
1020 }
1021
1022 pub fn progress_percent(&self) -> usize {
1023 if self.total > 0 {
1024 #[allow(
1025 clippy::cast_sign_loss,
1026 clippy::let_and_return,
1027 reason = "Intentional compatibility, platform, or test-only suppression."
1028 )]
1029 let progress = ((self.completed as f64 / self.total as f64 * 100.0).round()).max(0.0) as usize;
1030 progress
1031 } else {
1032 0
1033 }
1034 }
1035}
1036
1037#[cfg(test)]
1038mod tests {
1039 use super::*;
1040
1041 #[test]
1042 fn parse_files_metadata_keeps_quoted_commas_as_single_item() {
1043 let items = parse_files_metadata("'src/a.rs, b.rs', src/c.rs");
1044 assert_eq!(items, vec!["'src/a.rs, b.rs'".to_string(), "src/c.rs".to_string()]);
1045 }
1046
1047 #[test]
1048 fn apply_metadata_line_drives_verify_block_state_machine() {
1049 let mut metadata = TaskStepMetadata::default();
1050 let mut in_verify_block = false;
1051
1052 assert!(!apply_metadata_line(&mut metadata, "just a description", &mut in_verify_block));
1054 assert!(!in_verify_block);
1055 assert!(metadata.verify.is_empty());
1056
1057 assert!(apply_metadata_line(&mut metadata, " files: a.rs, b.rs", &mut in_verify_block));
1059 assert!(apply_metadata_line(&mut metadata, " outcome: did the thing", &mut in_verify_block));
1060 assert_eq!(metadata.files, vec!["a.rs".to_string(), "b.rs".to_string()]);
1061 assert_eq!(metadata.outcome.as_deref(), Some("did the thing"));
1062
1063 assert!(apply_metadata_line(&mut metadata, " verify:", &mut in_verify_block));
1065 assert!(in_verify_block);
1066 assert!(apply_metadata_line(&mut metadata, " - cargo test", &mut in_verify_block));
1067 assert!(apply_metadata_line(&mut metadata, " * cargo clippy", &mut in_verify_block));
1068 assert_eq!(metadata.verify, vec!["cargo test".to_string(), "cargo clippy".to_string()]);
1069
1070 assert!(!apply_metadata_line(&mut metadata, " other: x", &mut in_verify_block));
1072 assert!(!in_verify_block);
1073
1074 assert!(apply_metadata_line(&mut metadata, " verify: make check", &mut in_verify_block));
1076 assert_eq!(metadata.verify, vec!["make check".to_string()]);
1077 }
1078
1079 #[test]
1080 fn verify_ingestion_strips_code_span_decoration() {
1081 let mut metadata = TaskStepMetadata::default();
1087 let mut in_verify_block = false;
1088 assert!(apply_metadata_line(
1089 &mut metadata,
1090 " verify: `./scripts/update-contributors-readme.sh --dry-run`",
1091 &mut in_verify_block
1092 ));
1093 assert_eq!(metadata.verify, vec!["./scripts/update-contributors-readme.sh --dry-run".to_string()]);
1094 assert!(apply_metadata_line(&mut metadata, " verify:", &mut in_verify_block));
1096 assert!(apply_metadata_line(&mut metadata, " - `git show --stat HEAD`", &mut in_verify_block));
1097 assert_eq!(metadata.verify, vec!["git show --stat HEAD".to_string()]);
1098 let mut structured = TaskStepMetadata::default();
1100 apply_metadata_input(
1101 &mut structured,
1102 Some(&["README.md".to_string()]),
1103 None,
1104 Some(&["`cargo check --locked`".to_string()]),
1105 );
1106 assert_eq!(structured.verify, vec!["cargo check --locked".to_string()]);
1107 let mut nested = TaskStepMetadata::default();
1109 apply_metadata_input(&mut nested, None, None, Some(&["`grep -n '`x`' f`".to_string()]));
1110 assert_eq!(nested.verify, vec!["`grep -n '`x`' f`".to_string()]);
1111 }
1112
1113 #[test]
1114 fn parse_marked_status_prefix_rejects_unmarked_text() {
1115 let parsed = parse_marked_status_prefix("plain text without marker");
1116 assert!(parsed.is_none());
1117 }
1118
1119 #[test]
1120 fn parse_status_prefix_defaults_to_pending_for_unmarked_text() {
1121 let (status, description) = parse_status_prefix("plain text without marker");
1122 assert_eq!(status, TaskTrackingStatus::Pending);
1123 assert_eq!(description, "plain text without marker");
1124 }
1125
1126 #[test]
1127 fn parse_status_prefix_supports_both_in_progress_markers() {
1128 let (status_tilde, text_tilde) = parse_status_prefix("[~] do thing");
1129 let (status_slash, text_slash) = parse_status_prefix("[/] do thing");
1130 assert_eq!(status_tilde, TaskTrackingStatus::InProgress);
1131 assert_eq!(status_slash, TaskTrackingStatus::InProgress);
1132 assert_eq!(text_tilde, "do thing");
1133 assert_eq!(text_slash, "do thing");
1134 }
1135
1136 #[test]
1137 fn append_notes_joins_with_single_newline() {
1138 let merged = append_notes(Some("left".to_string()), Some("right"));
1139 assert_eq!(merged, Some("left\nright".to_string()));
1140 }
1141
1142 #[test]
1143 fn append_notes_section_ignores_blank_notes() {
1144 let mut markdown = "# Title\n".to_string();
1145 append_notes_section(&mut markdown, Some(" "));
1146 assert_eq!(markdown, "# Title\n");
1147 }
1148
1149 #[test]
1150 fn bulk_sync_validation_preserves_text_and_actual_structured_items() {
1151 let valid = vec![
1152 TaskItemInput::Text(r#"[x] Document {"status":"completed"}"#.to_string()),
1153 TaskItemInput::Text(r#"{"example":"literal JSON"}"#.to_string()),
1154 TaskItemInput::Structured(TaskItemInputObject {
1155 description: "Original step".to_string(),
1156 status: Some("completed".to_string()),
1157 ..Default::default()
1158 }),
1159 ];
1160 validate_task_item_inputs(&valid).unwrap();
1161 for text in [
1162 r#"{"index":1,"status":"completed"}"#,
1163 r#"{"description":"Encoded step","status":"completed"}"#,
1164 ] {
1165 for prefix in ["", "[x] ", "[X] ", "[~] ", "[/] ", "[!] ", "[ ] "] {
1166 let item = TaskItemInput::Text(format!(" {prefix}{text} "));
1167 assert!(validate_task_item_inputs(&[item]).is_err(), "prefix {prefix:?}");
1168 }
1169 }
1170 }
1171
1172 #[test]
1173 fn is_bulk_sync_update_requires_items_and_missing_single_item_fields() {
1174 let items = vec!["Step".to_string()];
1175 let no_items: Option<&[String]> = None;
1176 assert!(is_bulk_sync_update(Some(&items), None, None, None));
1177 assert!(!is_bulk_sync_update(no_items, Some(1), None, Some("completed")));
1178 }
1179
1180 #[test]
1181 fn is_bulk_sync_update_rejects_mixed_single_item_fields() {
1182 let items = vec!["Step".to_string()];
1183 let error = validate_update_shape(Some(&items), Some(1), None, Some("completed"))
1184 .expect_err("mixed bulk and single update fields must fail closed");
1185
1186 assert!(error.to_string().contains("cannot combine 'items'"));
1187 }
1188
1189 #[test]
1190 fn task_tracker_update_rejects_both_index_forms() {
1191 let error = validate_update_shape::<String>(None, Some(1), Some("1"), Some("completed"))
1192 .expect_err("an update must select exactly one index form");
1193
1194 assert!(error.to_string().contains("cannot combine 'index' and 'index_path'"));
1195 }
1196
1197 #[test]
1198 fn task_counts_tracks_progress() {
1199 let mut counts = TaskCounts::default();
1200 counts.add(&TaskTrackingStatus::Completed);
1201 counts.add(&TaskTrackingStatus::Pending);
1202 counts.add(&TaskTrackingStatus::Blocked);
1203 counts.add(&TaskTrackingStatus::InProgress);
1204 assert_eq!(counts.total, 4);
1205 assert_eq!(counts.completed, 1);
1206 assert_eq!(counts.pending, 1);
1207 assert_eq!(counts.blocked, 1);
1208 assert_eq!(counts.in_progress, 1);
1209 assert_eq!(counts.progress_percent(), 25);
1210 }
1211
1212 #[test]
1213 fn compact_task_tree_view_formats_flat_leaf_statuses_exactly() {
1214 let nodes = [
1215 TaskTreeNode {
1216 index_path: "1".to_string(),
1217 description: "Pending".to_string(),
1218 status: TaskTrackingStatus::Pending,
1219 metadata: TaskStepMetadata::default(),
1220 children: Vec::new(),
1221 },
1222 TaskTreeNode {
1223 index_path: "2".to_string(),
1224 description: "In progress".to_string(),
1225 status: TaskTrackingStatus::InProgress,
1226 metadata: TaskStepMetadata::default(),
1227 children: Vec::new(),
1228 },
1229 TaskTreeNode {
1230 index_path: "3".to_string(),
1231 description: "Completed".to_string(),
1232 status: TaskTrackingStatus::Completed,
1233 metadata: TaskStepMetadata::default(),
1234 children: Vec::new(),
1235 },
1236 TaskTreeNode {
1237 index_path: "4".to_string(),
1238 description: "Blocked".to_string(),
1239 status: TaskTrackingStatus::Blocked,
1240 metadata: TaskStepMetadata::default(),
1241 children: Vec::new(),
1242 },
1243 ];
1244
1245 let displays = compact_task_tree_view(&nodes)
1246 .into_iter()
1247 .filter_map(|line| line.get("display").and_then(Value::as_str).map(ToOwned::to_owned))
1248 .collect::<Vec<_>>();
1249 assert_eq!(
1250 displays,
1251 vec![
1252 " ├ □ Pending".to_string(),
1253 " ├ [-] In progress".to_string(),
1254 " ├ [x] Completed".to_string(),
1255 " └ [!] Blocked".to_string(),
1256 ]
1257 );
1258 }
1259
1260 #[test]
1261 fn compact_task_tree_view_omits_parent_status_but_keeps_metadata_fields() {
1262 let nodes = [TaskTreeNode {
1263 index_path: "1".to_string(),
1264 description: "Parent".to_string(),
1265 status: TaskTrackingStatus::InProgress,
1266 metadata: TaskStepMetadata {
1267 files: vec!["Cargo.toml".to_string()],
1268 outcome: Some("Ready".to_string()),
1269 verify: vec!["cargo check".to_string()],
1270 },
1271 children: vec![TaskTreeNode {
1272 index_path: "1.1".to_string(),
1273 description: "Child".to_string(),
1274 status: TaskTrackingStatus::Completed,
1275 metadata: TaskStepMetadata::default(),
1276 children: Vec::new(),
1277 }],
1278 }];
1279
1280 let lines = compact_task_tree_view(&nodes);
1281 assert_eq!(lines[0]["display"], " └ Parent");
1282 assert_eq!(lines[1]["display"], " [x] Child");
1283 assert_eq!(lines[0]["files"], json!(["Cargo.toml"]));
1284 assert_eq!(lines[0]["outcome"], "Ready");
1285 assert_eq!(lines[0]["verify"], json!(["cargo check"]));
1286 }
1287
1288 #[test]
1289 fn split_task_description_metadata_strips_files_and_verify_suffix() {
1290 let (clean, files, verify) =
1291 split_task_description_metadata("Emit summary -> files: [src/a.rs, src/b.rs] -> verify: [cargo check]");
1292 assert_eq!(clean, "Emit summary");
1293 assert_eq!(files, vec!["src/a.rs".to_string(), "src/b.rs".to_string()]);
1294 assert_eq!(verify, vec!["cargo check".to_string()]);
1295 }
1296
1297 #[test]
1298 fn split_task_description_metadata_keeps_inline_code_arrows_intact() {
1299 let (clean, files, verify) =
1300 split_task_description_metadata("Use `a -> files: b` in code -> files: [src/a.rs]");
1301 assert_eq!(clean, "Use `a -> files: b` in code");
1302 assert_eq!(files, vec!["src/a.rs".to_string()]);
1303 assert!(verify.is_empty());
1304 }
1305
1306 #[test]
1307 fn split_task_description_metadata_without_markers_returns_trimmed_description() {
1308 let (clean, files, verify) = split_task_description_metadata(" Just an action ");
1309 assert_eq!(clean, "Just an action");
1310 assert!(files.is_empty());
1311 assert!(verify.is_empty());
1312 }
1313
1314 #[test]
1315 fn split_task_description_metadata_preserves_quoted_commas_in_files_and_verify() {
1316 let (clean, files, verify) = split_task_description_metadata(
1317 "Inspect range -> files: ['src/a.rs, b.rs', src/c.rs] -> verify: [sed -n '/^## A/,/^## B/p']",
1318 );
1319 assert_eq!(clean, "Inspect range");
1320 assert_eq!(files, vec!["'src/a.rs, b.rs'".to_string(), "src/c.rs".to_string()]);
1321 assert_eq!(verify, vec!["sed -n '/^## A/,/^## B/p'".to_string()]);
1322 }
1323
1324 #[test]
1325 fn compact_task_tree_view_from_items_strips_inline_metadata_into_fields() {
1326 let items = vec![json!({
1327 "index_path": "1",
1328 "description": "Update parser -> files: [src/a.rs] -> verify: [cargo check]",
1329 "status": "pending",
1330 })];
1331 let rows = compact_task_tree_view_from_items(&items);
1332 assert_eq!(rows.len(), 1);
1333 assert_eq!(rows[0]["display"], " └ □ Update parser");
1334 assert_eq!(rows[0]["text"], "Update parser");
1335 assert_eq!(rows[0]["files"], json!(["src/a.rs"]));
1336 assert_eq!(rows[0]["verify"], json!(["cargo check"]));
1337 }
1338
1339 #[test]
1340 fn short_task_description_keeps_leading_clause_only() {
1341 assert_eq!(
1342 short_task_description(
1343 "Add vtcode exec resume to the Commands section – document the cross-turn contract, sourced from ExecSubcommand::Resume"
1344 ),
1345 "Add vtcode exec resume to the Commands section"
1346 );
1347 assert_eq!(
1348 short_task_description("Update the Everyday recipes block — add a headless example"),
1349 "Update the Everyday recipes block"
1350 );
1351 assert_eq!(
1352 short_task_description("Emit summary -> files: [src/a.rs] -> verify: [cargo check]"),
1353 "Emit summary"
1354 );
1355 assert_eq!(short_task_description("Verify with cargo check"), "Verify with cargo check");
1356 assert_eq!(short_task_description(""), "");
1357 }
1358
1359 #[test]
1360 fn compact_task_tree_view_from_items_shortens_detail_tail() {
1361 let items = vec![json!({
1362 "index_path": "1",
1363 "description": "Add vtcode exec resume to the Commands section – document the cross-turn contract in the command table",
1364 "status": "pending",
1365 })];
1366 let rows = compact_task_tree_view_from_items(&items);
1367 assert_eq!(rows.len(), 1);
1368 assert_eq!(rows[0]["display"], " └ □ Add vtcode exec resume to the Commands section");
1369 assert_eq!(rows[0]["text"], "Add vtcode exec resume to the Commands section");
1370 }
1371
1372 #[test]
1373 fn shared_schema_helpers_stay_actionable_and_drift_free() {
1374 assert_eq!(TASK_STATUS_VALUES, ["pending", "in_progress", "completed", "blocked"]);
1375
1376 let status = task_status_schema();
1377 assert_eq!(status["type"], "string");
1378 assert_eq!(status["enum"], json!(TASK_STATUS_VALUES));
1379 assert!(status.get("description").is_none());
1380
1381 let with_desc = task_status_property_schema("New status.");
1382 assert_eq!(with_desc["description"], "New status.");
1383 assert_eq!(with_desc["enum"], json!(TASK_STATUS_VALUES));
1384
1385 let items_schema = task_items_array_schema("Items desc.");
1387 let validator = jsonschema::validator_for(&items_schema).expect("items schema is valid");
1388 assert!(validator.validate(&json!(["plain step"])).is_ok());
1389 assert!(
1390 validator
1391 .validate(&json!([{
1392 "description": "Structured step",
1393 "status": "in_progress",
1394 "files": ["src/a.rs"],
1395 "outcome": "Done",
1396 "verify": ["cargo check"],
1397 }]))
1398 .is_ok()
1399 );
1400 assert!(validator.validate(&json!([{"status": "completed"}])).is_err());
1402 assert!(validator.validate(&json!([{"description": "Bad", "status": "done"}])).is_err());
1403
1404 assert_eq!(task_files_property_schema("F.")["description"], "F.");
1405 assert_eq!(task_verify_property_schema("V.")["description"], "V.");
1406 }
1407
1408 #[test]
1409 fn shared_status_values_match_runtime_parser() {
1410 use std::str::FromStr;
1411 for status in TASK_STATUS_VALUES {
1412 assert!(TaskTrackingStatus::from_str(status).is_ok(), "schema status {status:?} must parse");
1413 }
1414 assert!(TaskTrackingStatus::from_str("done").is_err());
1415 }
1416
1417 #[test]
1425 fn task_status_as_str_serde_and_from_str_stay_in_lockstep() {
1426 use std::str::FromStr;
1427 let variants = [
1428 TaskTrackingStatus::Pending,
1429 TaskTrackingStatus::InProgress,
1430 TaskTrackingStatus::Completed,
1431 TaskTrackingStatus::Blocked,
1432 ];
1433 let strings: Vec<&str> = variants.iter().map(TaskTrackingStatus::as_str).collect();
1434 assert_eq!(strings, TASK_STATUS_VALUES);
1435
1436 for variant in variants {
1437 let expected = variant.as_str();
1438 assert_eq!(
1439 serde_json::to_value(variant).expect("serializes"),
1440 json!(expected),
1441 "serde form drifted for {variant:?}"
1442 );
1443 assert_eq!(
1444 TaskTrackingStatus::from_str(expected).expect("as_str output must parse back"),
1445 variant,
1446 "FromStr drift for {variant:?}"
1447 );
1448 }
1449 }
1450
1451 #[test]
1458 fn task_item_status_matches_tracking_status_strings() {
1459 use std::str::FromStr;
1460 use vtcode_commons::ui_protocol::TaskItemStatus;
1461
1462 for variant in [
1463 TaskTrackingStatus::Pending,
1464 TaskTrackingStatus::InProgress,
1465 TaskTrackingStatus::Completed,
1466 TaskTrackingStatus::Blocked,
1467 ] {
1468 let canonical = variant.as_str();
1469 let display = TaskItemStatus::from_str(canonical)
1470 .unwrap_or_else(|_| panic!("TaskItemStatus must parse runtime status {canonical:?}"));
1471 assert_eq!(display.as_str(), canonical, "TaskItemStatus/TaskTrackingStatus string drift for {variant:?}");
1472 }
1473 }
1474}