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
13mod schema;
14pub(crate) use schema::{
15 TASK_ITEMS_DESCRIPTION, task_files_property_schema, task_items_array_schema, task_status_property_schema,
16 task_verify_property_schema, tracker_schema_allof,
17};
18#[cfg(test)]
19pub(crate) use schema::{TASK_STATUS_VALUES, task_status_schema};
20
21#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, Default)]
22pub struct TaskStepMetadata {
23 #[serde(default, skip_serializing_if = "Vec::is_empty")]
24 pub files: Vec<String>,
25 #[serde(default, skip_serializing_if = "Option::is_none")]
26 pub outcome: Option<String>,
27 #[serde(default, skip_serializing_if = "Vec::is_empty")]
28 pub verify: Vec<String>,
29 #[serde(default, skip_serializing_if = "Vec::is_empty")]
31 pub scope_review: Vec<String>,
32}
33
34#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
35#[serde(untagged)]
36pub enum TaskItemInput {
37 Text(String),
38 Structured(TaskItemInputObject),
39}
40
41#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, Default)]
42pub struct TaskItemInputObject {
43 pub description: String,
44 #[serde(default)]
45 pub status: Option<String>,
46 #[serde(default, deserialize_with = "deserialize_optional_string_list")]
47 pub files: Option<Vec<String>>,
48 #[serde(default)]
49 pub outcome: Option<String>,
50 #[serde(default, deserialize_with = "deserialize_optional_string_list")]
51 pub verify: Option<Vec<String>>,
52 #[serde(default, deserialize_with = "deserialize_optional_string_list")]
53 pub scope_review: Option<Vec<String>>,
54}
55
56pub(crate) struct TaskMetadataRef<'a> {
57 pub description: &'a str,
58 pub metadata: &'a TaskStepMetadata,
59}
60
61pub(crate) struct ParsedTaskItem {
62 pub level: usize,
63 pub description: String,
64 pub status: TaskTrackingStatus,
65 pub metadata: TaskStepMetadata,
66}
67
68pub(crate) fn parse_task_items(
72 items: &[TaskItemInput],
73 previous: &[TaskMetadataRef<'_>],
74) -> Result<Vec<ParsedTaskItem>> {
75 validate_task_item_inputs(items)?;
76 let mut previous_by_description = HashMap::new();
77 for item in previous {
78 previous_by_description
79 .entry(item.description.trim())
80 .and_modify(|metadata| *metadata = None)
81 .or_insert(Some(item.metadata));
82 }
83 let mut description_counts = HashMap::new();
84 for item in items {
85 let raw = match item {
86 TaskItemInput::Text(raw) => raw,
87 TaskItemInput::Structured(input) => &input.description,
88 };
89 let (_, description) = parse_status_prefix(raw.trim());
90 *description_counts.entry(description.trim().to_owned()).or_insert(0usize) += 1;
91 }
92
93 let mut parsed_items = Vec::with_capacity(items.len());
94 for item in items {
95 let raw = match item {
96 TaskItemInput::Text(raw) => raw,
97 TaskItemInput::Structured(input) => &input.description,
98 };
99 let (mut status, description) = parse_status_prefix(raw.trim());
100 let description = description.trim().to_owned();
101 if description.is_empty() {
102 continue;
103 }
104 let previous_metadata = if description_counts.get(&description) == Some(&1) {
105 previous_by_description.get(description.as_str()).copied().flatten()
106 } else {
107 None
108 };
109 let has_previous_scope_review = previous
110 .iter()
111 .any(|previous| previous.description.trim() == description && !previous.metadata.scope_review.is_empty());
112 if previous_metadata.is_none()
113 && previous
114 .iter()
115 .any(|item| item.description.trim() == description && item.metadata != &TaskStepMetadata::default())
116 && !matches!(item, TaskItemInput::Structured(input) if input.files.is_some() && input.outcome.is_some() && input.verify.is_some() && (!has_previous_scope_review || input.scope_review.is_some()))
117 {
118 bail!(
119 "Ambiguous task description '{description}': provide explicit files, outcome, verify, and scope_review metadata for duplicate steps. Use empty arrays and an empty outcome to clear them. The checklist was not changed."
120 );
121 }
122 let mut metadata = previous_metadata.cloned().unwrap_or_default();
123 if let TaskItemInput::Structured(input) = item {
124 if let Some(raw_status) = input.status.as_deref() {
125 status = TaskTrackingStatus::from_str(raw_status)?;
126 }
127 apply_metadata_input(
128 &mut metadata,
129 input.files.as_deref(),
130 input.outcome.as_deref(),
131 input.verify.as_deref(),
132 );
133 if let Some(scope_review) = input.scope_review.as_deref() {
134 metadata.scope_review = normalize_verify_items(scope_review.iter().map(String::as_str));
135 }
136 }
137 parsed_items.push(ParsedTaskItem {
138 level: raw.chars().take_while(|character| *character == ' ').count() / 2,
139 description,
140 status,
141 metadata,
142 });
143 }
144 Ok(parsed_items)
145}
146
147pub(crate) fn apply_metadata_input(
148 metadata: &mut TaskStepMetadata,
149 files: Option<&[String]>,
150 outcome: Option<&str>,
151 verify: Option<&[String]>,
152) {
153 if let Some(files) = files {
154 metadata.files = normalize_string_items(Some(files));
155 }
156 if let Some(outcome) = outcome {
157 metadata.outcome = normalize_optional_text(Some(outcome));
158 }
159 if let Some(verify) = verify {
160 metadata.verify = normalize_verify_items(verify.iter().map(String::as_str));
161 }
162}
163
164#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
165#[serde(rename_all = "snake_case")]
166pub enum TaskTrackingStatus {
167 Pending,
168 InProgress,
169 Completed,
170 Blocked,
171}
172
173impl std::fmt::Display for TaskTrackingStatus {
174 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
175 write!(f, "{}", self.as_str())
176 }
177}
178
179impl FromStr for TaskTrackingStatus {
180 type Err = anyhow::Error;
181
182 fn from_str(value: &str) -> Result<Self> {
183 match value {
184 "pending" => Ok(Self::Pending),
185 "in_progress" => Ok(Self::InProgress),
186 "completed" => Ok(Self::Completed),
187 "blocked" => Ok(Self::Blocked),
188 other => {
189 bail!("Invalid status '{other}'. Use: pending, in_progress, completed, blocked")
190 }
191 }
192 }
193}
194
195impl TaskTrackingStatus {
196 pub fn as_str(&self) -> &'static str {
197 match self {
198 Self::Pending => "pending",
199 Self::InProgress => "in_progress",
200 Self::Completed => "completed",
201 Self::Blocked => "blocked",
202 }
203 }
204
205 pub fn flat_checkbox(&self) -> &'static str {
206 match self {
207 Self::Pending => "[ ]",
208 Self::InProgress => "[/]",
209 Self::Completed => "[x]",
210 Self::Blocked => "[!]",
211 }
212 }
213
214 pub fn plan_checkbox(&self) -> &'static str {
215 match self {
216 Self::Pending => "[ ]",
217 Self::InProgress => "[~]",
218 Self::Completed => "[x]",
219 Self::Blocked => "[!]",
220 }
221 }
222
223 pub fn view_symbol(&self) -> &'static str {
224 match self {
225 Self::Pending => "•",
226 Self::InProgress => ">",
227 Self::Completed => "✔",
228 Self::Blocked => "!",
229 }
230 }
231
232 pub fn compact_view_symbol(&self) -> &'static str {
233 match self {
234 Self::Pending => "□",
235 Self::InProgress => "[-]",
236 Self::Completed => "[x]",
237 Self::Blocked => "[!]",
238 }
239 }
240}
241
242pub fn parse_marked_status_prefix(value: &str) -> Option<(TaskTrackingStatus, String)> {
243 let trimmed = value.trim_start();
244 let mapping = [
245 ("[x] ", TaskTrackingStatus::Completed),
246 ("[X] ", TaskTrackingStatus::Completed),
247 ("[~] ", TaskTrackingStatus::InProgress),
248 ("[/] ", TaskTrackingStatus::InProgress),
249 ("[!] ", TaskTrackingStatus::Blocked),
250 ("[ ] ", TaskTrackingStatus::Pending),
251 ];
252 for (prefix, status) in mapping {
253 if let Some(rest) = trimmed.strip_prefix(prefix) {
254 return Some((status, rest.to_string()));
255 }
256 }
257 None
258}
259
260pub fn parse_status_prefix(value: &str) -> (TaskTrackingStatus, String) {
261 parse_marked_status_prefix(value).unwrap_or((TaskTrackingStatus::Pending, value.trim_start().to_string()))
262}
263
264pub fn append_notes(existing: Option<String>, append: Option<&str>) -> Option<String> {
265 match (existing, append) {
266 (None, None) => None,
267 (Some(text), None) => {
268 if text.trim().is_empty() {
269 None
270 } else {
271 Some(text)
272 }
273 }
274 (None, Some(extra)) => {
275 let trimmed = extra.trim();
276 if trimmed.is_empty() {
277 None
278 } else {
279 Some(trimmed.to_string())
280 }
281 }
282 (Some(text), Some(extra)) => {
283 let left = text.trim();
284 let right = extra.trim();
285 if left.is_empty() && right.is_empty() {
286 None
287 } else if left.is_empty() {
288 Some(right.to_string())
289 } else if right.is_empty() {
290 Some(left.to_string())
291 } else {
292 Some(format!("{left}\n{right}"))
293 }
294 }
295 }
296}
297
298pub fn append_notes_section(markdown: &mut String, notes: Option<&str>) {
299 if let Some(text) = notes {
300 let trimmed = text.trim();
301 if !trimmed.is_empty() {
302 markdown.push_str("\n## Notes\n\n");
303 markdown.push_str(trimmed);
304 markdown.push('\n');
305 }
306 }
307}
308
309pub(crate) fn validate_update_shape<T>(
310 items: Option<&[T]>,
311 index: Option<usize>,
312 index_path: Option<&str>,
313 status: Option<&str>,
314) -> Result<()> {
315 if index.is_some() && index_path.is_some() {
316 bail!("task-tracker updates cannot combine 'index' and 'index_path'");
317 }
318
319 if items.is_some() && (index.is_some() || index_path.is_some() || status.is_some()) {
320 bail!("bulk task-tracker updates cannot combine 'items' with 'index', 'index_path', or 'status'");
321 }
322
323 Ok(())
324}
325
326pub(crate) fn validate_action_index_fields(action: &str, index: Option<usize>, index_path: Option<&str>) -> Result<()> {
327 if action != "update" && (index.is_some() || index_path.is_some()) {
328 bail!(
329 "task-tracker action '{action}' cannot use 'index' or 'index_path'; indices are only valid with action='update'"
330 );
331 }
332
333 Ok(())
334}
335
336pub(crate) fn validate_task_item_inputs(items: &[TaskItemInput]) -> Result<()> {
338 for item in items {
339 let TaskItemInput::Text(text) = item else {
340 continue;
341 };
342 let (_, description) = parse_status_prefix(text.trim());
343 if let Ok(Value::Object(object)) = serde_json::from_str::<Value>(&description)
344 && ["index", "index_path", "description", "status"]
345 .iter()
346 .any(|key| object.contains_key(*key))
347 {
348 bail!(
349 "'items' replaces the complete checklist; JSON-encoded task updates are not task descriptions. \
350 Update an existing step directly: {{\"action\":\"update\",\"index_path\":\"1\",\"status\":\"completed\"}}. \
351 For full synchronization, send descriptions with statuses, for example \
352 {{\"action\":\"update\",\"items\":[{{\"description\":\"Original step\",\"status\":\"completed\"}}]}}. \
353 The checklist was not changed. Retry once with the intended shape."
354 );
355 }
356 }
357 Ok(())
358}
359
360pub fn is_bulk_sync_update<T>(
361 items: Option<&[T]>,
362 index: Option<usize>,
363 index_path: Option<&str>,
364 status: Option<&str>,
365) -> bool {
366 items.is_some() && index.is_none() && index_path.is_none() && status.is_none()
367}
368
369pub fn deserialize_optional_string_list<'de, D>(deserializer: D) -> std::result::Result<Option<Vec<String>>, D::Error>
370where
371 D: serde::Deserializer<'de>,
372{
373 #[derive(Deserialize)]
374 #[serde(untagged)]
375 enum OneOrMany {
376 One(String),
377 Many(Vec<String>),
378 }
379
380 let parsed = Option::<OneOrMany>::deserialize(deserializer)?;
381 Ok(parsed.map(|value| match value {
382 OneOrMany::One(item) => vec![item],
383 OneOrMany::Many(items) => items,
384 }))
385}
386
387pub(crate) fn unwrap_verify_code_span(command: &str) -> &str {
399 let trimmed = command.trim();
400 if trimmed.starts_with('`') && trimmed.ends_with('`') && trimmed.len() >= 2 {
401 let inner = &trimmed[1..trimmed.len() - 1];
402 if !inner.contains('`') {
403 return inner;
404 }
405 }
406 trimmed
407}
408
409pub(crate) fn normalize_verify_items<'a>(items: impl IntoIterator<Item = &'a str>) -> Vec<String> {
412 items
413 .into_iter()
414 .filter_map(|item| {
415 let unwrapped = unwrap_verify_code_span(item);
416 (!unwrapped.is_empty()).then(|| unwrapped.to_owned())
417 })
418 .collect()
419}
420
421pub fn normalize_string_items(items: Option<&[String]>) -> Vec<String> {
422 items
423 .unwrap_or(&[])
424 .iter()
425 .map(|item| item.trim())
426 .filter(|item| !item.is_empty())
427 .map(ToOwned::to_owned)
428 .collect()
429}
430
431pub fn normalize_optional_text(value: Option<&str>) -> Option<String> {
432 value.map(str::trim).filter(|value| !value.is_empty()).map(ToOwned::to_owned)
433}
434
435pub fn parse_files_metadata(value: &str) -> Vec<String> {
438 super::planning_workflow::split_bracket_items(value)
439 .into_iter()
440 .map(|item| item.trim().to_owned())
441 .filter(|item| !item.is_empty())
442 .collect()
443}
444
445pub fn apply_metadata_line(metadata: &mut TaskStepMetadata, raw: &str, in_verify_block: &mut bool) -> bool {
449 let trimmed = raw.trim_start();
450
451 if *in_verify_block {
452 if let Some(command) = trimmed
453 .strip_prefix("- ")
454 .or_else(|| trimmed.strip_prefix("* "))
455 .or_else(|| trimmed.strip_prefix("+ "))
456 {
457 if let Some(command) = normalize_verify_items([command]).pop() {
458 metadata.verify.push(command);
459 }
460 return true;
461 }
462 *in_verify_block = false;
463 }
464
465 if let Some(rest) = trimmed.strip_prefix("files:") {
466 metadata.files = parse_files_metadata(rest);
467 return true;
468 }
469 if let Some(rest) = trimmed.strip_prefix("outcome:") {
470 metadata.outcome = normalize_optional_text(Some(rest));
471 return true;
472 }
473 if let Some(rest) = trimmed.strip_prefix("scope-review:") {
474 if rest.trim().is_empty() {
475 metadata.scope_review.clear();
476 } else {
477 metadata.scope_review.extend(normalize_verify_items([rest]));
478 }
479 return true;
480 }
481 if trimmed == "verify:" {
482 metadata.verify.clear();
483 *in_verify_block = true;
484 return true;
485 }
486 if let Some(rest) = trimmed.strip_prefix("verify:") {
487 metadata.verify = normalize_verify_items([rest]);
488 return true;
489 }
490
491 false
492}
493
494pub fn append_task_step_metadata(markdown: &mut String, indent: &str, metadata: &TaskStepMetadata) {
495 if !metadata.files.is_empty() {
496 markdown.push_str(indent);
497 markdown.push_str(" files: ");
498 markdown.push_str(&metadata.files.join(", "));
499 markdown.push('\n');
500 }
501
502 if let Some(outcome) = metadata.outcome.as_deref() {
503 markdown.push_str(indent);
504 markdown.push_str(" outcome: ");
505 markdown.push_str(outcome);
506 markdown.push('\n');
507 }
508
509 for command in &metadata.scope_review {
510 markdown.push_str(indent);
511 markdown.push_str(" scope-review: ");
512 markdown.push_str(command);
513 markdown.push('\n');
514 }
515
516 if metadata.verify.len() == 1 {
517 markdown.push_str(indent);
518 markdown.push_str(" verify: ");
519 markdown.push_str(&metadata.verify[0]);
520 markdown.push('\n');
521 } else if !metadata.verify.is_empty() {
522 markdown.push_str(indent);
523 markdown.push_str(" verify:\n");
524 for command in &metadata.verify {
525 markdown.push_str(indent);
526 markdown.push_str(" - ");
527 markdown.push_str(command);
528 markdown.push('\n');
529 }
530 }
531}
532
533pub fn metadata_from_input(
534 files: Option<&[String]>,
535 outcome: Option<&str>,
536 verify: Option<&[String]>,
537) -> TaskStepMetadata {
538 let mut metadata = TaskStepMetadata::default();
539 apply_metadata_input(&mut metadata, files, outcome, verify);
540 metadata
541}
542
543const INLINE_TASK_METADATA_MARKERS: &[&str] = &[" -> files:", " -> verify:", " -> outcome:"];
548
549fn parse_inline_bracket_list(raw: &str) -> Vec<String> {
550 let trimmed = raw.trim();
551 let inner = trimmed
552 .strip_prefix('[')
553 .and_then(|value| value.strip_suffix(']'))
554 .unwrap_or(trimmed);
555 super::planning_workflow::split_bracket_items(inner)
556 .into_iter()
557 .map(|item| item.trim().to_owned())
558 .filter(|value| !value.is_empty())
559 .collect()
560}
561
562pub fn split_task_description_metadata(description: &str) -> (String, Vec<String>, Vec<String>) {
571 let normalized;
572 let source = if description.contains('→') {
573 normalized = description.replace('→', "->");
574 normalized.as_str()
575 } else {
576 description
577 };
578 let Some(first) = find_inline_metadata_marker(source, 0) else {
579 return (source.trim().to_string(), Vec::new(), Vec::new());
580 };
581 let head = source[..first.0].trim();
582 if head.is_empty() {
583 return (source.trim().to_string(), Vec::new(), Vec::new());
584 }
585
586 let mut files = Vec::new();
587 let mut verify = Vec::new();
588 let mut cursor = first.0;
589 while let Some((marker_start, marker)) = find_inline_metadata_marker(source, cursor) {
590 let value_start = marker_start + marker.len();
591 let next = find_inline_metadata_marker(source, value_start)
592 .map(|(start, _)| start)
593 .unwrap_or(source.len());
594 let value = source[value_start..next].trim();
595 if marker.contains("files:") {
596 files.extend(parse_inline_bracket_list(value));
597 } else if marker.contains("verify:") {
598 verify.extend(parse_inline_bracket_list(value));
599 }
600 cursor = next;
601 if cursor >= source.len() {
602 break;
603 }
604 }
605 (head.to_string(), files, verify)
606}
607
608pub fn strip_task_description_metadata(description: &str) -> String {
612 split_task_description_metadata(description).0
613}
614
615pub fn short_task_description(description: &str) -> String {
624 let (clean, _, _) = split_task_description_metadata(description);
625 let base = if clean.trim().is_empty() {
626 description.trim()
627 } else {
628 clean.trim()
629 };
630 let first_line = base.lines().map(str::trim).find(|line| !line.is_empty()).unwrap_or("");
631 let collapsed = vtcode_commons::formatting::collapse_whitespace(first_line);
632 if collapsed.is_empty() {
633 return String::new();
634 }
635 let mut cut = collapsed.len();
636 for separator in [" — ", " – ", " - ", ": ", "; ", ". ", " ("] {
637 if let Some(index) = collapsed.find(separator) {
638 cut = cut.min(index);
639 }
640 }
641 let short = collapsed[..cut].trim().trim_end_matches([',', ';', ':', '.']).trim();
642 if short.is_empty() { collapsed } else { short.to_string() }
643}
644
645fn find_inline_metadata_marker(source: &str, from: usize) -> Option<(usize, &'static str)> {
646 let mut inline_ticks: Option<usize> = None;
647 let mut cursor = from.min(source.len());
648 while cursor < source.len() {
649 let remainder = &source[cursor..];
650 if remainder.starts_with('`') {
651 let run = remainder.bytes().take_while(|byte| *byte == b'`').count();
652 if inline_ticks.is_some_and(|ticks| ticks == run) {
653 inline_ticks = None;
654 } else if inline_ticks.is_none() {
655 inline_ticks = Some(run);
656 }
657 cursor += run;
658 continue;
659 }
660 if inline_ticks.is_none() {
661 for marker in INLINE_TASK_METADATA_MARKERS {
662 if remainder.starts_with(marker) {
663 return Some((cursor, marker));
664 }
665 }
666 }
667 let character = remainder.chars().next()?;
668 cursor += character.len_utf8();
669 }
670 None
671}
672
673#[derive(Debug, Clone, PartialEq, Eq)]
678pub(crate) struct TaskTreeNode {
679 pub(crate) index_path: String,
680 pub(crate) description: String,
681 pub(crate) status: TaskTrackingStatus,
682 pub(crate) metadata: TaskStepMetadata,
683 pub(crate) children: Vec<TaskTreeNode>,
684}
685
686pub(crate) fn compact_task_tree_view(nodes: &[TaskTreeNode]) -> Vec<Value> {
691 let mut lines = Vec::new();
692 append_compact_task_tree_view(nodes, " ", &mut lines);
693 lines
694}
695
696fn append_compact_task_tree_view(nodes: &[TaskTreeNode], tree_prefix: &str, out: &mut Vec<Value>) {
697 for (index, node) in nodes.iter().enumerate() {
698 let is_last = index + 1 == nodes.len();
699 let branch = if is_last { "└" } else { "├" };
700 let display = if node.children.is_empty() {
701 if tree_prefix == " " {
702 format!("{tree_prefix}{branch} {} {}", node.status.compact_view_symbol(), node.description)
703 } else {
704 format!("{tree_prefix}{} {}", node.status.compact_view_symbol(), node.description)
705 }
706 } else {
707 format!("{tree_prefix}{branch} {}", node.description)
708 };
709
710 out.push(json!({
711 "display": display,
712 "index_path": node.index_path.clone(),
713 "status": node.status.as_str(),
714 "text": node.description.clone(),
715 "files": node.metadata.files.clone(),
716 "outcome": node.metadata.outcome.clone(),
717 "verify": node.metadata.verify.clone(),
718 "scope_review": node.metadata.scope_review.clone(),
719 }));
720
721 let next_prefix = if is_last {
722 format!("{tree_prefix} ")
723 } else {
724 format!("{tree_prefix}│ ")
725 };
726 append_compact_task_tree_view(&node.children, &next_prefix, out);
727 }
728}
729
730pub fn compact_task_tree_view_from_items(items: &[Value]) -> Vec<Value> {
736 let mut ordered_paths = Vec::with_capacity(items.len());
737 let mut nodes_by_path = std::collections::HashMap::with_capacity(items.len());
738
739 for (position, item) in items.iter().enumerate() {
740 let index_path = item
741 .get("index_path")
742 .and_then(Value::as_str)
743 .filter(|path| !path.trim().is_empty())
744 .map(ToOwned::to_owned)
745 .or_else(|| item.get("index").and_then(Value::as_u64).map(|index| index.to_string()))
746 .unwrap_or_else(|| (position + 1).to_string());
747 if nodes_by_path.contains_key(&index_path) {
748 continue;
749 }
750
751 let status = match item.get("status").and_then(Value::as_str) {
752 Some(value) => match TaskTrackingStatus::from_str(value) {
753 Ok(status) => status,
754 Err(_) => continue,
755 },
756 None => TaskTrackingStatus::Pending,
757 };
758 let Some(description) = item
759 .get("description")
760 .and_then(Value::as_str)
761 .or_else(|| item.get("text").and_then(Value::as_str))
762 .filter(|description| !description.trim().is_empty())
763 else {
764 continue;
765 };
766 let (clean_description, parsed_files, parsed_verify) = split_task_description_metadata(description);
773 let raw = if clean_description.trim().is_empty() {
774 description.trim()
775 } else {
776 clean_description.trim()
777 };
778 let description = short_task_description(raw);
779 let mut metadata = TaskStepMetadata {
780 files: string_array(item.get("files")),
781 outcome: item.get("outcome").and_then(Value::as_str).map(ToOwned::to_owned),
782 verify: string_or_string_array(item.get("verify")),
783 scope_review: string_or_string_array(item.get("scope_review")),
784 };
785 if metadata.files.is_empty() {
786 metadata.files = parsed_files;
787 }
788 if metadata.verify.is_empty() {
789 metadata.verify = parsed_verify;
790 }
791
792 ordered_paths.push(index_path.clone());
793 nodes_by_path.insert(
794 index_path.clone(),
795 TaskTreeNode {
796 index_path,
797 description,
798 status,
799 metadata,
800 children: Vec::new(),
801 },
802 );
803 }
804
805 let mut attachment_order = ordered_paths.clone();
806 attachment_order.sort_by_key(|path| std::cmp::Reverse(path.split('.').count()));
807 for path in attachment_order {
808 let Some(parent_path) = path.rsplit_once('.').map(|(parent, _)| parent.to_string()) else {
809 continue;
810 };
811 let Some(child) = nodes_by_path.remove(&path) else {
812 continue;
813 };
814 if let Some(parent) = nodes_by_path.get_mut(&parent_path) {
815 parent.children.push(child);
816 } else {
817 nodes_by_path.insert(path, child);
818 }
819 }
820
821 let roots = ordered_paths
822 .into_iter()
823 .filter_map(|path| nodes_by_path.remove(&path))
824 .collect::<Vec<_>>();
825 compact_task_tree_view(&roots)
826}
827
828fn string_array(value: Option<&Value>) -> Vec<String> {
829 value
830 .and_then(Value::as_array)
831 .into_iter()
832 .flatten()
833 .filter_map(Value::as_str)
834 .map(ToOwned::to_owned)
835 .collect()
836}
837
838fn string_or_string_array(value: Option<&Value>) -> Vec<String> {
839 match value {
840 Some(Value::String(value)) => vec![value.clone()],
841 Some(Value::Array(_)) => string_array(value),
842 _ => Vec::new(),
843 }
844}
845
846#[derive(Default)]
847pub struct TaskCounts {
848 pub total: usize,
849 pub completed: usize,
850 pub in_progress: usize,
851 pub pending: usize,
852 pub blocked: usize,
853}
854
855impl TaskCounts {
856 pub fn add(&mut self, status: &TaskTrackingStatus) {
857 self.total += 1;
858 match status {
859 TaskTrackingStatus::Pending => self.pending += 1,
860 TaskTrackingStatus::InProgress => self.in_progress += 1,
861 TaskTrackingStatus::Completed => self.completed += 1,
862 TaskTrackingStatus::Blocked => self.blocked += 1,
863 }
864 }
865
866 pub fn progress_percent(&self) -> usize {
867 if self.total > 0 {
868 #[allow(
869 clippy::cast_sign_loss,
870 clippy::let_and_return,
871 reason = "Intentional compatibility, platform, or test-only suppression."
872 )]
873 let progress = ((self.completed as f64 / self.total as f64 * 100.0).round()).max(0.0) as usize;
874 progress
875 } else {
876 0
877 }
878 }
879}
880
881#[cfg(test)]
882mod tests;