Skip to main content

vtcode_core/tools/handlers/task_tracking/
mod.rs

1use std::str::FromStr;
2
3use anyhow::{Result, bail};
4use hashbrown::HashMap;
5use serde::{Deserialize, Serialize};
6use serde_json::{Value, json};
7
8mod inline_metadata;
9pub use inline_metadata::split_task_description_metadata;
10
11mod persistence;
12pub(crate) use persistence::{
13    TrackerArtifact, persist_tracker_artifacts, read_tracker_artifact, write_tracker_artifact,
14};
15
16mod schema;
17pub(crate) use schema::{
18    TASK_ITEMS_DESCRIPTION, task_files_property_schema, task_items_array_schema, task_status_property_schema,
19    task_verify_property_schema, tracker_schema_allof,
20};
21#[cfg(test)]
22pub(crate) use schema::{TASK_STATUS_VALUES, task_status_schema};
23
24#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, Default)]
25pub struct TaskStepMetadata {
26    #[serde(default, skip_serializing_if = "Vec::is_empty")]
27    pub files: Vec<String>,
28    #[serde(default, skip_serializing_if = "Option::is_none")]
29    pub outcome: Option<String>,
30    #[serde(default, skip_serializing_if = "Vec::is_empty")]
31    pub verify: Vec<String>,
32    /// Workspace-scope evidence, kept separate from functional verification.
33    #[serde(default, skip_serializing_if = "Vec::is_empty")]
34    pub scope_review: Vec<String>,
35}
36
37#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
38#[serde(untagged)]
39pub enum TaskItemInput {
40    Text(String),
41    Structured(TaskItemInputObject),
42}
43
44#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, Default)]
45pub struct TaskItemInputObject {
46    pub description: String,
47    #[serde(default)]
48    pub status: Option<String>,
49    #[serde(default, deserialize_with = "deserialize_optional_string_list")]
50    pub files: Option<Vec<String>>,
51    #[serde(default)]
52    pub outcome: Option<String>,
53    #[serde(default, deserialize_with = "deserialize_optional_string_list")]
54    pub verify: Option<Vec<String>>,
55    #[serde(default, deserialize_with = "deserialize_optional_string_list")]
56    pub scope_review: Option<Vec<String>>,
57}
58
59pub(crate) struct TaskMetadataRef<'a> {
60    pub description: &'a str,
61    pub metadata: &'a TaskStepMetadata,
62}
63
64pub(crate) struct ParsedTaskItem {
65    pub level: usize,
66    pub description: String,
67    pub status: TaskTrackingStatus,
68    pub metadata: TaskStepMetadata,
69}
70
71/// Normalize both tracker variants and preserve omitted metadata only when
72/// a description identifies exactly one old step and exactly one new step.
73/// Creates pass no previous items; explicit empty metadata still clears it.
74pub(crate) fn parse_task_items(
75    items: &[TaskItemInput],
76    previous: &[TaskMetadataRef<'_>],
77) -> Result<Vec<ParsedTaskItem>> {
78    validate_task_item_inputs(items)?;
79    let mut previous_by_description = HashMap::new();
80    for item in previous {
81        previous_by_description
82            .entry(item.description.trim())
83            .and_modify(|metadata| *metadata = None)
84            .or_insert(Some(item.metadata));
85    }
86    let mut description_counts = HashMap::new();
87    for item in items {
88        let raw = match item {
89            TaskItemInput::Text(raw) => raw,
90            TaskItemInput::Structured(input) => &input.description,
91        };
92        let (_, description) = parse_status_prefix(raw.trim());
93        *description_counts.entry(description.trim().to_owned()).or_insert(0usize) += 1;
94    }
95
96    let mut parsed_items = Vec::with_capacity(items.len());
97    for item in items {
98        let raw = match item {
99            TaskItemInput::Text(raw) => raw,
100            TaskItemInput::Structured(input) => &input.description,
101        };
102        let (mut status, description) = parse_status_prefix(raw.trim());
103        let description = description.trim().to_owned();
104        if description.is_empty() {
105            continue;
106        }
107        let previous_metadata = if description_counts.get(&description) == Some(&1) {
108            previous_by_description.get(description.as_str()).copied().flatten()
109        } else {
110            None
111        };
112        let has_previous_scope_review = previous
113            .iter()
114            .any(|previous| previous.description.trim() == description && !previous.metadata.scope_review.is_empty());
115        if previous_metadata.is_none()
116            && previous
117                .iter()
118                .any(|item| item.description.trim() == description && item.metadata != &TaskStepMetadata::default())
119            && !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()))
120        {
121            bail!(
122                "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."
123            );
124        }
125        let mut metadata = previous_metadata.cloned().unwrap_or_default();
126        if let TaskItemInput::Structured(input) = item {
127            if let Some(raw_status) = input.status.as_deref() {
128                status = TaskTrackingStatus::from_str(raw_status)?;
129            }
130            apply_metadata_input(
131                &mut metadata,
132                input.files.as_deref(),
133                input.outcome.as_deref(),
134                input.verify.as_deref(),
135            );
136            if let Some(scope_review) = input.scope_review.as_deref() {
137                metadata.scope_review = normalize_verify_items(scope_review.iter().map(String::as_str));
138            }
139        }
140        parsed_items.push(ParsedTaskItem {
141            level: raw.chars().take_while(|character| *character == ' ').count() / 2,
142            description,
143            status,
144            metadata,
145        });
146    }
147    Ok(parsed_items)
148}
149
150pub(crate) fn apply_metadata_input(
151    metadata: &mut TaskStepMetadata,
152    files: Option<&[String]>,
153    outcome: Option<&str>,
154    verify: Option<&[String]>,
155) {
156    if let Some(files) = files {
157        metadata.files = normalize_string_items(Some(files));
158    }
159    if let Some(outcome) = outcome {
160        metadata.outcome = normalize_optional_text(Some(outcome));
161    }
162    if let Some(verify) = verify {
163        metadata.verify = normalize_verify_items(verify.iter().map(String::as_str));
164    }
165}
166
167#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
168#[serde(rename_all = "snake_case")]
169pub enum TaskTrackingStatus {
170    Pending,
171    InProgress,
172    Completed,
173    Blocked,
174}
175
176impl std::fmt::Display for TaskTrackingStatus {
177    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
178        write!(f, "{}", self.as_str())
179    }
180}
181
182impl FromStr for TaskTrackingStatus {
183    type Err = anyhow::Error;
184
185    fn from_str(value: &str) -> Result<Self> {
186        match value {
187            "pending" => Ok(Self::Pending),
188            "in_progress" => Ok(Self::InProgress),
189            "completed" => Ok(Self::Completed),
190            "blocked" => Ok(Self::Blocked),
191            other => {
192                bail!("Invalid status '{other}'. Use: pending, in_progress, completed, blocked")
193            }
194        }
195    }
196}
197
198impl TaskTrackingStatus {
199    pub fn as_str(&self) -> &'static str {
200        match self {
201            Self::Pending => "pending",
202            Self::InProgress => "in_progress",
203            Self::Completed => "completed",
204            Self::Blocked => "blocked",
205        }
206    }
207
208    pub fn flat_checkbox(&self) -> &'static str {
209        match self {
210            Self::Pending => "[ ]",
211            Self::InProgress => "[/]",
212            Self::Completed => "[x]",
213            Self::Blocked => "[!]",
214        }
215    }
216
217    pub fn plan_checkbox(&self) -> &'static str {
218        match self {
219            Self::Pending => "[ ]",
220            Self::InProgress => "[~]",
221            Self::Completed => "[x]",
222            Self::Blocked => "[!]",
223        }
224    }
225
226    pub fn view_symbol(&self) -> &'static str {
227        match self {
228            Self::Pending => "•",
229            Self::InProgress => ">",
230            Self::Completed => "✔",
231            Self::Blocked => "!",
232        }
233    }
234
235    pub fn compact_view_symbol(&self) -> &'static str {
236        match self {
237            Self::Pending => "□",
238            Self::InProgress => "[-]",
239            Self::Completed => "[x]",
240            Self::Blocked => "[!]",
241        }
242    }
243}
244
245pub fn parse_marked_status_prefix(value: &str) -> Option<(TaskTrackingStatus, String)> {
246    let trimmed = value.trim_start();
247    let mapping = [
248        ("[x] ", TaskTrackingStatus::Completed),
249        ("[X] ", TaskTrackingStatus::Completed),
250        ("[~] ", TaskTrackingStatus::InProgress),
251        ("[/] ", TaskTrackingStatus::InProgress),
252        ("[!] ", TaskTrackingStatus::Blocked),
253        ("[ ] ", TaskTrackingStatus::Pending),
254    ];
255    for (prefix, status) in mapping {
256        if let Some(rest) = trimmed.strip_prefix(prefix) {
257            return Some((status, rest.to_string()));
258        }
259    }
260    None
261}
262
263pub fn parse_status_prefix(value: &str) -> (TaskTrackingStatus, String) {
264    parse_marked_status_prefix(value).unwrap_or((TaskTrackingStatus::Pending, value.trim_start().to_string()))
265}
266
267pub fn append_notes(existing: Option<String>, append: Option<&str>) -> Option<String> {
268    match (existing, append) {
269        (None, None) => None,
270        (Some(text), None) => {
271            if text.trim().is_empty() {
272                None
273            } else {
274                Some(text)
275            }
276        }
277        (None, Some(extra)) => {
278            let trimmed = extra.trim();
279            if trimmed.is_empty() {
280                None
281            } else {
282                Some(trimmed.to_string())
283            }
284        }
285        (Some(text), Some(extra)) => {
286            let left = text.trim();
287            let right = extra.trim();
288            if left.is_empty() && right.is_empty() {
289                None
290            } else if left.is_empty() {
291                Some(right.to_string())
292            } else if right.is_empty() {
293                Some(left.to_string())
294            } else {
295                Some(format!("{left}\n{right}"))
296            }
297        }
298    }
299}
300
301pub fn append_notes_section(markdown: &mut String, notes: Option<&str>) {
302    if let Some(text) = notes {
303        let trimmed = text.trim();
304        if !trimmed.is_empty() {
305            markdown.push_str("\n## Notes\n\n");
306            markdown.push_str(trimmed);
307            markdown.push('\n');
308        }
309    }
310}
311
312pub(crate) fn validate_update_shape<T>(
313    items: Option<&[T]>,
314    index: Option<usize>,
315    index_path: Option<&str>,
316    status: Option<&str>,
317) -> Result<()> {
318    if index.is_some() && index_path.is_some() {
319        bail!("task-tracker updates cannot combine 'index' and 'index_path'");
320    }
321
322    if items.is_some() && (index.is_some() || index_path.is_some() || status.is_some()) {
323        bail!("bulk task-tracker updates cannot combine 'items' with 'index', 'index_path', or 'status'");
324    }
325
326    Ok(())
327}
328
329pub(crate) fn validate_action_index_fields(action: &str, index: Option<usize>, index_path: Option<&str>) -> Result<()> {
330    if action != "update" && (index.is_some() || index_path.is_some()) {
331        bail!(
332            "task-tracker action '{action}' cannot use 'index' or 'index_path'; indices are only valid with action='update'"
333        );
334    }
335
336    Ok(())
337}
338
339/// Checklist replacement must not interpret encoded update commands as descriptions.
340pub(crate) fn validate_task_item_inputs(items: &[TaskItemInput]) -> Result<()> {
341    for item in items {
342        let TaskItemInput::Text(text) = item else {
343            continue;
344        };
345        let (_, description) = parse_status_prefix(text.trim());
346        if let Ok(Value::Object(object)) = serde_json::from_str::<Value>(&description)
347            && ["index", "index_path", "description", "status"]
348                .iter()
349                .any(|key| object.contains_key(*key))
350        {
351            bail!(
352                "'items' replaces the complete checklist; JSON-encoded task updates are not task descriptions. \
353                 Update an existing step directly: {{\"action\":\"update\",\"index_path\":\"1\",\"status\":\"completed\"}}. \
354                 For full synchronization, send descriptions with statuses, for example \
355                 {{\"action\":\"update\",\"items\":[{{\"description\":\"Original step\",\"status\":\"completed\"}}]}}. \
356                 The checklist was not changed. Retry once with the intended shape."
357            );
358        }
359    }
360    Ok(())
361}
362
363pub fn is_bulk_sync_update<T>(
364    items: Option<&[T]>,
365    index: Option<usize>,
366    index_path: Option<&str>,
367    status: Option<&str>,
368) -> bool {
369    items.is_some() && index.is_none() && index_path.is_none() && status.is_none()
370}
371
372pub fn deserialize_optional_string_list<'de, D>(deserializer: D) -> std::result::Result<Option<Vec<String>>, D::Error>
373where
374    D: serde::Deserializer<'de>,
375{
376    #[derive(Deserialize)]
377    #[serde(untagged)]
378    enum OneOrMany {
379        One(String),
380        Many(Vec<String>),
381    }
382
383    let parsed = Option::<OneOrMany>::deserialize(deserializer)?;
384    Ok(parsed.map(|value| match value {
385        OneOrMany::One(item) => vec![item],
386        OneOrMany::Many(items) => items,
387    }))
388}
389
390/// Strip one balanced markdown code-span pair from a `verify` entry.
391///
392/// `verify` values are shell commands, and models faithfully emit them in the
393/// code-spans the prompt examples use (`verify: [`cargo check`]`). A stored
394/// code span is never valid shell, so the decoration must not reach
395/// strings that are later compared literally or re-executed — otherwise the
396/// completion gate demands an "exact command" the executor is forbidden to
397/// type (preflight rejects code spans as command substitution).
398/// Callers choose where to apply this: producer ingestion
399/// (`apply_metadata_input`/`apply_metadata_line`) for canonical storage, or
400/// a consumer defense boundary. Markdown mirrors keep code spans.
401pub(crate) fn unwrap_verify_code_span(command: &str) -> &str {
402    let trimmed = command.trim();
403    if trimmed.starts_with('`') && trimmed.ends_with('`') && trimmed.len() >= 2 {
404        let inner = &trimmed[1..trimmed.len() - 1];
405        if !inner.contains('`') {
406            return inner;
407        }
408    }
409    trimmed
410}
411
412/// Normalize the executable `verify` item: trim, drop the code-span
413/// decoration, and drop empties.
414pub(crate) fn normalize_verify_items<'a>(items: impl IntoIterator<Item = &'a str>) -> Vec<String> {
415    items
416        .into_iter()
417        .filter_map(|item| {
418            let unwrapped = unwrap_verify_code_span(item);
419            (!unwrapped.is_empty()).then(|| unwrapped.to_owned())
420        })
421        .collect()
422}
423
424pub fn normalize_string_items(items: Option<&[String]>) -> Vec<String> {
425    items
426        .unwrap_or(&[])
427        .iter()
428        .map(|item| item.trim())
429        .filter(|item| !item.is_empty())
430        .map(ToOwned::to_owned)
431        .collect()
432}
433
434pub fn normalize_optional_text(value: Option<&str>) -> Option<String> {
435    value.map(str::trim).filter(|value| !value.is_empty()).map(ToOwned::to_owned)
436}
437
438/// Parse a `files: [...]` metadata value into trimmed non-empty paths.
439/// Commas inside single/double quotes stay part of one item, and both the
440/// whole-group (`[a, b]`) and per-item (`[a], [b]`) forms are unwrapped.
441pub fn parse_files_metadata(value: &str) -> Vec<String> {
442    super::planning_workflow::parse_bracket_list(value)
443}
444
445/// Consume one indented markdown metadata line (`files:`, `outcome:`,
446/// `verify:`, `scope-review:`) into `metadata`, tracking multi-line `verify:` blocks through
447/// `in_verify_block`. Returns `true` when the line was metadata.
448pub 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
543/// Strip an inline `-> files:` / `-> verify:` / `-> outcome:` suffix for
544/// display. Structured metadata stays in the payload; the visible compact row
545/// must not reintroduce it as detail text.
546pub fn strip_task_description_metadata(description: &str) -> String {
547    split_task_description_metadata(description).0
548}
549
550/// One short description for a task row: the leading clause before detail
551/// separators (` — `/` – `/` - `/`: `, `; `, `. `, ` (`).
552///
553/// Plan steps often carry a long detail tail
554/// (`"Add X – document Y in Z, sourced from W"`); the TODO transcript and
555/// panel must show only `"Add X"` so each item stays on one scannable row.
556/// Inline `-> files:`/`-> verify:` suffixes are stripped first; the full text
557/// stays in structured tracker metadata.
558pub fn short_task_description(description: &str) -> String {
559    let (clean, _, _) = split_task_description_metadata(description);
560    let base = if clean.trim().is_empty() {
561        description.trim()
562    } else {
563        clean.trim()
564    };
565    let first_line = base.lines().map(str::trim).find(|line| !line.is_empty()).unwrap_or("");
566    let collapsed = vtcode_commons::formatting::collapse_whitespace(first_line);
567    if collapsed.is_empty() {
568        return String::new();
569    }
570    let mut cut = collapsed.len();
571    for separator in [" — ", " – ", " - ", ": ", "; ", ". ", " ("] {
572        if let Some(index) = collapsed.find(separator) {
573            cut = cut.min(index);
574        }
575    }
576    let short = collapsed[..cut].trim().trim_end_matches([',', ';', ':', '.']).trim();
577    if short.is_empty() { collapsed } else { short.to_string() }
578}
579
580/// A renderer-independent task tree used by both task-tracker implementations.
581///
582/// The persisted checklist formats remain implementation-specific; this type is
583/// only the shared shape required to produce the compact visible view.
584#[derive(Debug, Clone, PartialEq, Eq)]
585pub(crate) struct TaskTreeNode {
586    pub(crate) index_path: String,
587    pub(crate) description: String,
588    pub(crate) status: TaskTrackingStatus,
589    pub(crate) metadata: TaskStepMetadata,
590    pub(crate) children: Vec<TaskTreeNode>,
591}
592
593/// Format task nodes as the compact tree shared by inline output and the task
594/// panel. Root leaves retain `├`/`└` connectors; nested leaves use their status
595/// glyph as the connector so the hierarchy stays readable without redundant
596/// branch characters.
597pub(crate) fn compact_task_tree_view(nodes: &[TaskTreeNode]) -> Vec<Value> {
598    let mut lines = Vec::new();
599    append_compact_task_tree_view(nodes, "  ", &mut lines);
600    lines
601}
602
603fn append_compact_task_tree_view(nodes: &[TaskTreeNode], tree_prefix: &str, out: &mut Vec<Value>) {
604    for (index, node) in nodes.iter().enumerate() {
605        let is_last = index + 1 == nodes.len();
606        let branch = if is_last { "└" } else { "├" };
607        let display = if node.children.is_empty() {
608            if tree_prefix == "  " {
609                format!("{tree_prefix}{branch} {} {}", node.status.compact_view_symbol(), node.description)
610            } else {
611                format!("{tree_prefix}{} {}", node.status.compact_view_symbol(), node.description)
612            }
613        } else {
614            format!("{tree_prefix}{branch} {}", node.description)
615        };
616
617        out.push(json!({
618            "display": display,
619            "index_path": node.index_path.clone(),
620            "status": node.status.as_str(),
621            "text": node.description.clone(),
622            "files": node.metadata.files.clone(),
623            "outcome": node.metadata.outcome.clone(),
624            "verify": node.metadata.verify.clone(),
625            "scope_review": node.metadata.scope_review.clone(),
626        }));
627
628        let next_prefix = if is_last {
629            format!("{tree_prefix}  ")
630        } else {
631            format!("{tree_prefix}│ ")
632        };
633        append_compact_task_tree_view(&node.children, &next_prefix, out);
634    }
635}
636
637/// Build the compact tree from a flattened checklist summary.
638///
639/// Standard task trackers expose numeric `index` values while planning
640/// trackers expose dotted `index_path` values. Accept both forms so callers at
641/// the UI boundary do not need to know which tracker produced the payload.
642pub fn compact_task_tree_view_from_items(items: &[Value]) -> Vec<Value> {
643    let mut ordered_paths = Vec::with_capacity(items.len());
644    let mut nodes_by_path = std::collections::HashMap::with_capacity(items.len());
645
646    for (position, item) in items.iter().enumerate() {
647        let index_path = item
648            .get("index_path")
649            .and_then(Value::as_str)
650            .filter(|path| !path.trim().is_empty())
651            .map(ToOwned::to_owned)
652            .or_else(|| item.get("index").and_then(Value::as_u64).map(|index| index.to_string()))
653            .unwrap_or_else(|| (position + 1).to_string());
654        if nodes_by_path.contains_key(&index_path) {
655            continue;
656        }
657
658        let status = match item.get("status").and_then(Value::as_str) {
659            Some(value) => match TaskTrackingStatus::from_str(value) {
660                Ok(status) => status,
661                Err(_) => continue,
662            },
663            None => TaskTrackingStatus::Pending,
664        };
665        let Some(description) = item
666            .get("description")
667            .and_then(Value::as_str)
668            .or_else(|| item.get("text").and_then(Value::as_str))
669            .filter(|description| !description.trim().is_empty())
670        else {
671            continue;
672        };
673        // Descriptions copied from plan steps may still carry an inline
674        // `Action -> files: [...] -> verify: [...]` suffix plus a long detail
675        // tail (`"Add X – document Y, sourced from Z"`). Keep only the short
676        // leading clause for the visible row and fold the rest into structured
677        // metadata so the compact view never reintroduces files/verify/detail
678        // text.
679        let (clean_description, parsed_files, parsed_verify) = split_task_description_metadata(description);
680        let raw = if clean_description.trim().is_empty() {
681            description.trim()
682        } else {
683            clean_description.trim()
684        };
685        let description = short_task_description(raw);
686        let mut metadata = TaskStepMetadata {
687            files: string_array(item.get("files")),
688            outcome: item.get("outcome").and_then(Value::as_str).map(ToOwned::to_owned),
689            verify: string_or_string_array(item.get("verify")),
690            scope_review: string_or_string_array(item.get("scope_review")),
691        };
692        if metadata.files.is_empty() {
693            metadata.files = parsed_files;
694        }
695        if metadata.verify.is_empty() {
696            metadata.verify = parsed_verify;
697        }
698
699        ordered_paths.push(index_path.clone());
700        nodes_by_path.insert(
701            index_path.clone(),
702            TaskTreeNode {
703                index_path,
704                description,
705                status,
706                metadata,
707                children: Vec::new(),
708            },
709        );
710    }
711
712    let mut attachment_order = ordered_paths.clone();
713    attachment_order.sort_by_key(|path| std::cmp::Reverse(path.split('.').count()));
714    for path in attachment_order {
715        let Some(parent_path) = path.rsplit_once('.').map(|(parent, _)| parent.to_string()) else {
716            continue;
717        };
718        let Some(child) = nodes_by_path.remove(&path) else {
719            continue;
720        };
721        if let Some(parent) = nodes_by_path.get_mut(&parent_path) {
722            parent.children.push(child);
723        } else {
724            nodes_by_path.insert(path, child);
725        }
726    }
727
728    let roots = ordered_paths
729        .into_iter()
730        .filter_map(|path| nodes_by_path.remove(&path))
731        .collect::<Vec<_>>();
732    compact_task_tree_view(&roots)
733}
734
735fn string_array(value: Option<&Value>) -> Vec<String> {
736    value
737        .and_then(Value::as_array)
738        .into_iter()
739        .flatten()
740        .filter_map(Value::as_str)
741        .map(ToOwned::to_owned)
742        .collect()
743}
744
745fn string_or_string_array(value: Option<&Value>) -> Vec<String> {
746    match value {
747        Some(Value::String(value)) => vec![value.clone()],
748        Some(Value::Array(_)) => string_array(value),
749        _ => Vec::new(),
750    }
751}
752
753#[derive(Default)]
754pub struct TaskCounts {
755    pub total: usize,
756    pub completed: usize,
757    pub in_progress: usize,
758    pub pending: usize,
759    pub blocked: usize,
760}
761
762impl TaskCounts {
763    pub fn add(&mut self, status: &TaskTrackingStatus) {
764        self.total += 1;
765        match status {
766            TaskTrackingStatus::Pending => self.pending += 1,
767            TaskTrackingStatus::InProgress => self.in_progress += 1,
768            TaskTrackingStatus::Completed => self.completed += 1,
769            TaskTrackingStatus::Blocked => self.blocked += 1,
770        }
771    }
772
773    pub fn progress_percent(&self) -> usize {
774        if self.total > 0 {
775            #[allow(
776                clippy::cast_sign_loss,
777                clippy::let_and_return,
778                reason = "Intentional compatibility, platform, or test-only suppression."
779            )]
780            let progress = ((self.completed as f64 / self.total as f64 * 100.0).round()).max(0.0) as usize;
781            progress
782        } else {
783            0
784        }
785    }
786}
787
788#[cfg(test)]
789mod tests;