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        use vtcode_exec_events::tracker::TrackerItemStatus as Canonical;
187        let canonical = Canonical::from_str(value)
188            .map_err(|()| anyhow::anyhow!("Invalid status '{value}'. Use: pending, in_progress, completed, blocked"))?;
189        match canonical {
190            Canonical::Pending => Ok(Self::Pending),
191            Canonical::InProgress => Ok(Self::InProgress),
192            Canonical::Completed => Ok(Self::Completed),
193            Canonical::Blocked => Ok(Self::Blocked),
194            Canonical::Unknown => {
195                bail!("Invalid status '{value}'. Use: pending, in_progress, completed, blocked")
196            }
197        }
198    }
199}
200
201impl TaskTrackingStatus {
202    /// The canonical durable status this tool-facing subset projects.
203    const fn as_tracker(self) -> vtcode_exec_events::tracker::TrackerItemStatus {
204        use vtcode_exec_events::tracker::TrackerItemStatus as Canonical;
205        match self {
206            Self::Pending => Canonical::Pending,
207            Self::InProgress => Canonical::InProgress,
208            Self::Completed => Canonical::Completed,
209            Self::Blocked => Canonical::Blocked,
210        }
211    }
212
213    pub fn as_str(&self) -> &'static str {
214        self.as_tracker().as_str()
215    }
216
217    pub fn flat_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 plan_checkbox(&self) -> &'static str {
227        match self {
228            Self::Pending => "[ ]",
229            Self::InProgress => "[~]",
230            Self::Completed => "[x]",
231            Self::Blocked => "[!]",
232        }
233    }
234
235    pub fn view_symbol(&self) -> &'static str {
236        match self {
237            Self::Pending => "•",
238            Self::InProgress => ">",
239            Self::Completed => "✔",
240            Self::Blocked => "!",
241        }
242    }
243
244    pub fn compact_view_symbol(&self) -> &'static str {
245        match self {
246            Self::Pending => "□",
247            Self::InProgress => "[-]",
248            Self::Completed => "[x]",
249            Self::Blocked => "[!]",
250        }
251    }
252}
253
254pub fn parse_marked_status_prefix(value: &str) -> Option<(TaskTrackingStatus, String)> {
255    let trimmed = value.trim_start();
256    let mapping = [
257        ("[x] ", TaskTrackingStatus::Completed),
258        ("[X] ", TaskTrackingStatus::Completed),
259        ("[~] ", TaskTrackingStatus::InProgress),
260        ("[/] ", TaskTrackingStatus::InProgress),
261        ("[!] ", TaskTrackingStatus::Blocked),
262        ("[ ] ", TaskTrackingStatus::Pending),
263    ];
264    for (prefix, status) in mapping {
265        if let Some(rest) = trimmed.strip_prefix(prefix) {
266            return Some((status, rest.to_string()));
267        }
268    }
269    None
270}
271
272pub fn parse_status_prefix(value: &str) -> (TaskTrackingStatus, String) {
273    parse_marked_status_prefix(value).unwrap_or((TaskTrackingStatus::Pending, value.trim_start().to_string()))
274}
275
276pub fn append_notes(existing: Option<String>, append: Option<&str>) -> Option<String> {
277    match (existing, append) {
278        (None, None) => None,
279        (Some(text), None) => {
280            if text.trim().is_empty() {
281                None
282            } else {
283                Some(text)
284            }
285        }
286        (None, Some(extra)) => {
287            let trimmed = extra.trim();
288            if trimmed.is_empty() {
289                None
290            } else {
291                Some(trimmed.to_string())
292            }
293        }
294        (Some(text), Some(extra)) => {
295            let left = text.trim();
296            let right = extra.trim();
297            if left.is_empty() && right.is_empty() {
298                None
299            } else if left.is_empty() {
300                Some(right.to_string())
301            } else if right.is_empty() {
302                Some(left.to_string())
303            } else {
304                Some(format!("{left}\n{right}"))
305            }
306        }
307    }
308}
309
310pub fn append_notes_section(markdown: &mut String, notes: Option<&str>) {
311    if let Some(text) = notes {
312        let trimmed = text.trim();
313        if !trimmed.is_empty() {
314            markdown.push_str("\n## Notes\n\n");
315            markdown.push_str(trimmed);
316            markdown.push('\n');
317        }
318    }
319}
320
321pub(crate) fn validate_update_shape<T>(
322    items: Option<&[T]>,
323    index: Option<usize>,
324    index_path: Option<&str>,
325    status: Option<&str>,
326) -> Result<()> {
327    if index.is_some() && index_path.is_some() {
328        bail!("task-tracker updates cannot combine 'index' and 'index_path'");
329    }
330
331    if items.is_some() && (index.is_some() || index_path.is_some() || status.is_some()) {
332        bail!("bulk task-tracker updates cannot combine 'items' with 'index', 'index_path', or 'status'");
333    }
334
335    Ok(())
336}
337
338pub(crate) fn validate_action_index_fields(action: &str, index: Option<usize>, index_path: Option<&str>) -> Result<()> {
339    if action != "update" && (index.is_some() || index_path.is_some()) {
340        bail!(
341            "task-tracker action '{action}' cannot use 'index' or 'index_path'; indices are only valid with action='update'"
342        );
343    }
344
345    Ok(())
346}
347
348/// Checklist replacement must not interpret encoded update commands as descriptions.
349pub(crate) fn validate_task_item_inputs(items: &[TaskItemInput]) -> Result<()> {
350    for item in items {
351        let TaskItemInput::Text(text) = item else {
352            continue;
353        };
354        let (_, description) = parse_status_prefix(text.trim());
355        if let Ok(Value::Object(object)) = serde_json::from_str::<Value>(&description)
356            && ["index", "index_path", "description", "status"]
357                .iter()
358                .any(|key| object.contains_key(*key))
359        {
360            bail!(
361                "'items' replaces the complete checklist; JSON-encoded task updates are not task descriptions. \
362                 Update an existing step directly: {{\"action\":\"update\",\"index_path\":\"1\",\"status\":\"completed\"}}. \
363                 For full synchronization, send descriptions with statuses, for example \
364                 {{\"action\":\"update\",\"items\":[{{\"description\":\"Original step\",\"status\":\"completed\"}}]}}. \
365                 The checklist was not changed. Retry once with the intended shape."
366            );
367        }
368    }
369    Ok(())
370}
371
372pub fn is_bulk_sync_update<T>(
373    items: Option<&[T]>,
374    index: Option<usize>,
375    index_path: Option<&str>,
376    status: Option<&str>,
377) -> bool {
378    items.is_some() && index.is_none() && index_path.is_none() && status.is_none()
379}
380
381pub fn deserialize_optional_string_list<'de, D>(deserializer: D) -> std::result::Result<Option<Vec<String>>, D::Error>
382where
383    D: serde::Deserializer<'de>,
384{
385    #[derive(Deserialize)]
386    #[serde(untagged)]
387    enum OneOrMany {
388        One(String),
389        Many(Vec<String>),
390    }
391
392    let parsed = Option::<OneOrMany>::deserialize(deserializer)?;
393    Ok(parsed.map(|value| match value {
394        OneOrMany::One(item) => vec![item],
395        OneOrMany::Many(items) => items,
396    }))
397}
398
399/// Strip one balanced markdown code-span pair from a `verify` entry.
400///
401/// `verify` values are shell commands, and models faithfully emit them in the
402/// code-spans the prompt examples use (`verify: [`cargo check`]`). A stored
403/// code span is never valid shell, so the decoration must not reach
404/// strings that are later compared literally or re-executed — otherwise the
405/// completion gate demands an "exact command" the executor is forbidden to
406/// type (preflight rejects code spans as command substitution).
407/// Callers choose where to apply this: producer ingestion
408/// (`apply_metadata_input`/`apply_metadata_line`) for canonical storage, or
409/// a consumer defense boundary. Markdown mirrors keep code spans.
410pub(crate) fn unwrap_verify_code_span(command: &str) -> &str {
411    let trimmed = command.trim();
412    if trimmed.starts_with('`') && trimmed.ends_with('`') && trimmed.len() >= 2 {
413        let inner = &trimmed[1..trimmed.len() - 1];
414        if !inner.contains('`') {
415            return inner;
416        }
417    }
418    trimmed
419}
420
421/// Normalize the executable `verify` item: trim, drop the code-span
422/// decoration, and drop empties.
423pub(crate) fn normalize_verify_items<'a>(items: impl IntoIterator<Item = &'a str>) -> Vec<String> {
424    items
425        .into_iter()
426        .filter_map(|item| {
427            let unwrapped = unwrap_verify_code_span(item);
428            (!unwrapped.is_empty()).then(|| unwrapped.to_owned())
429        })
430        .collect()
431}
432
433pub fn normalize_string_items(items: Option<&[String]>) -> Vec<String> {
434    items
435        .unwrap_or(&[])
436        .iter()
437        .map(|item| item.trim())
438        .filter(|item| !item.is_empty())
439        .map(ToOwned::to_owned)
440        .collect()
441}
442
443pub fn normalize_optional_text(value: Option<&str>) -> Option<String> {
444    value.map(str::trim).filter(|value| !value.is_empty()).map(ToOwned::to_owned)
445}
446
447/// Parse a `files: [...]` metadata value into trimmed non-empty paths.
448/// Commas inside single/double quotes stay part of one item, and both the
449/// whole-group (`[a, b]`) and per-item (`[a], [b]`) forms are unwrapped.
450pub fn parse_files_metadata(value: &str) -> Vec<String> {
451    super::planning_workflow::parse_bracket_list(value)
452}
453
454/// Consume one indented markdown metadata line (`files:`, `outcome:`,
455/// `verify:`, `scope-review:`) into `metadata`, tracking multi-line `verify:` blocks through
456/// `in_verify_block`. Returns `true` when the line was metadata.
457pub fn apply_metadata_line(metadata: &mut TaskStepMetadata, raw: &str, in_verify_block: &mut bool) -> bool {
458    let trimmed = raw.trim_start();
459
460    if *in_verify_block {
461        if let Some(command) = trimmed
462            .strip_prefix("- ")
463            .or_else(|| trimmed.strip_prefix("* "))
464            .or_else(|| trimmed.strip_prefix("+ "))
465        {
466            if let Some(command) = normalize_verify_items([command]).pop() {
467                metadata.verify.push(command);
468            }
469            return true;
470        }
471        *in_verify_block = false;
472    }
473
474    if let Some(rest) = trimmed.strip_prefix("files:") {
475        metadata.files = parse_files_metadata(rest);
476        return true;
477    }
478    if let Some(rest) = trimmed.strip_prefix("outcome:") {
479        metadata.outcome = normalize_optional_text(Some(rest));
480        return true;
481    }
482    if let Some(rest) = trimmed.strip_prefix("scope-review:") {
483        if rest.trim().is_empty() {
484            metadata.scope_review.clear();
485        } else {
486            metadata.scope_review.extend(normalize_verify_items([rest]));
487        }
488        return true;
489    }
490    if trimmed == "verify:" {
491        metadata.verify.clear();
492        *in_verify_block = true;
493        return true;
494    }
495    if let Some(rest) = trimmed.strip_prefix("verify:") {
496        metadata.verify = normalize_verify_items([rest]);
497        return true;
498    }
499
500    false
501}
502
503pub fn append_task_step_metadata(markdown: &mut String, indent: &str, metadata: &TaskStepMetadata) {
504    if !metadata.files.is_empty() {
505        markdown.push_str(indent);
506        markdown.push_str("  files: ");
507        markdown.push_str(&metadata.files.join(", "));
508        markdown.push('\n');
509    }
510
511    if let Some(outcome) = metadata.outcome.as_deref() {
512        markdown.push_str(indent);
513        markdown.push_str("  outcome: ");
514        markdown.push_str(outcome);
515        markdown.push('\n');
516    }
517
518    for command in &metadata.scope_review {
519        markdown.push_str(indent);
520        markdown.push_str("  scope-review: ");
521        markdown.push_str(command);
522        markdown.push('\n');
523    }
524
525    if metadata.verify.len() == 1 {
526        markdown.push_str(indent);
527        markdown.push_str("  verify: ");
528        markdown.push_str(&metadata.verify[0]);
529        markdown.push('\n');
530    } else if !metadata.verify.is_empty() {
531        markdown.push_str(indent);
532        markdown.push_str("  verify:\n");
533        for command in &metadata.verify {
534            markdown.push_str(indent);
535            markdown.push_str("    - ");
536            markdown.push_str(command);
537            markdown.push('\n');
538        }
539    }
540}
541
542pub fn metadata_from_input(
543    files: Option<&[String]>,
544    outcome: Option<&str>,
545    verify: Option<&[String]>,
546) -> TaskStepMetadata {
547    let mut metadata = TaskStepMetadata::default();
548    apply_metadata_input(&mut metadata, files, outcome, verify);
549    metadata
550}
551
552/// Strip an inline `-> files:` / `-> verify:` / `-> outcome:` suffix for
553/// display. Structured metadata stays in the payload; the visible compact row
554/// must not reintroduce it as detail text.
555pub fn strip_task_description_metadata(description: &str) -> String {
556    split_task_description_metadata(description).0
557}
558
559/// One short description for a task row: the leading clause before detail
560/// separators (` — `/` – `/` - `/`: `, `; `, `. `, ` (`).
561///
562/// Plan steps often carry a long detail tail
563/// (`"Add X – document Y in Z, sourced from W"`); the TODO transcript and
564/// panel must show only `"Add X"` so each item stays on one scannable row.
565/// Inline `-> files:`/`-> verify:` suffixes are stripped first; the full text
566/// stays in structured tracker metadata.
567pub fn short_task_description(description: &str) -> String {
568    let (clean, _, _) = split_task_description_metadata(description);
569    let base = if clean.trim().is_empty() {
570        description.trim()
571    } else {
572        clean.trim()
573    };
574    let first_line = base.lines().map(str::trim).find(|line| !line.is_empty()).unwrap_or("");
575    let collapsed = vtcode_commons::formatting::collapse_whitespace(first_line);
576    if collapsed.is_empty() {
577        return String::new();
578    }
579    let mut cut = collapsed.len();
580    for separator in [" — ", " – ", " - ", ": ", "; ", ". ", " ("] {
581        if let Some(index) = collapsed.find(separator) {
582            cut = cut.min(index);
583        }
584    }
585    let short = collapsed[..cut].trim().trim_end_matches([',', ';', ':', '.']).trim();
586    if short.is_empty() { collapsed } else { short.to_string() }
587}
588
589/// A renderer-independent task tree used by both task-tracker implementations.
590///
591/// The persisted checklist formats remain implementation-specific; this type is
592/// only the shared shape required to produce the compact visible view.
593#[derive(Debug, Clone, PartialEq, Eq)]
594pub(crate) struct TaskTreeNode {
595    pub(crate) index_path: String,
596    pub(crate) description: String,
597    pub(crate) status: TaskTrackingStatus,
598    pub(crate) metadata: TaskStepMetadata,
599    pub(crate) children: Vec<TaskTreeNode>,
600}
601
602/// Format task nodes as the compact tree shared by inline output and the task
603/// panel. Root leaves retain `├`/`└` connectors; nested leaves use their status
604/// glyph as the connector so the hierarchy stays readable without redundant
605/// branch characters.
606pub(crate) fn compact_task_tree_view(nodes: &[TaskTreeNode]) -> Vec<Value> {
607    let mut lines = Vec::new();
608    append_compact_task_tree_view(nodes, "  ", &mut lines);
609    lines
610}
611
612fn append_compact_task_tree_view(nodes: &[TaskTreeNode], tree_prefix: &str, out: &mut Vec<Value>) {
613    for (index, node) in nodes.iter().enumerate() {
614        let is_last = index + 1 == nodes.len();
615        let branch = if is_last { "└" } else { "├" };
616        let display = if node.children.is_empty() {
617            if tree_prefix == "  " {
618                format!("{tree_prefix}{branch} {} {}", node.status.compact_view_symbol(), node.description)
619            } else {
620                format!("{tree_prefix}{} {}", node.status.compact_view_symbol(), node.description)
621            }
622        } else {
623            format!("{tree_prefix}{branch} {}", node.description)
624        };
625
626        out.push(json!({
627            "display": display,
628            "index_path": node.index_path.clone(),
629            "status": node.status.as_str(),
630            "text": node.description.clone(),
631            "files": node.metadata.files.clone(),
632            "outcome": node.metadata.outcome.clone(),
633            "verify": node.metadata.verify.clone(),
634            "scope_review": node.metadata.scope_review.clone(),
635        }));
636
637        let next_prefix = if is_last {
638            format!("{tree_prefix}  ")
639        } else {
640            format!("{tree_prefix}│ ")
641        };
642        append_compact_task_tree_view(&node.children, &next_prefix, out);
643    }
644}
645
646/// Build the compact tree from a flattened checklist summary.
647///
648/// Standard task trackers expose numeric `index` values while planning
649/// trackers expose dotted `index_path` values. Accept both forms so callers at
650/// the UI boundary do not need to know which tracker produced the payload.
651pub fn compact_task_tree_view_from_items(items: &[Value]) -> Vec<Value> {
652    let mut ordered_paths = Vec::with_capacity(items.len());
653    let mut nodes_by_path = std::collections::HashMap::with_capacity(items.len());
654
655    for (position, item) in items.iter().enumerate() {
656        let index_path = item
657            .get("index_path")
658            .and_then(Value::as_str)
659            .filter(|path| !path.trim().is_empty())
660            .map(ToOwned::to_owned)
661            .or_else(|| item.get("index").and_then(Value::as_u64).map(|index| index.to_string()))
662            .unwrap_or_else(|| (position + 1).to_string());
663        if nodes_by_path.contains_key(&index_path) {
664            continue;
665        }
666
667        let status = match item.get("status").and_then(Value::as_str) {
668            Some(value) => match TaskTrackingStatus::from_str(value) {
669                Ok(status) => status,
670                Err(_) => continue,
671            },
672            None => TaskTrackingStatus::Pending,
673        };
674        let Some(description) = item
675            .get("description")
676            .and_then(Value::as_str)
677            .or_else(|| item.get("text").and_then(Value::as_str))
678            .filter(|description| !description.trim().is_empty())
679        else {
680            continue;
681        };
682        // Descriptions copied from plan steps may still carry an inline
683        // `Action -> files: [...] -> verify: [...]` suffix plus a long detail
684        // tail (`"Add X – document Y, sourced from Z"`). Keep only the short
685        // leading clause for the visible row and fold the rest into structured
686        // metadata so the compact view never reintroduces files/verify/detail
687        // text.
688        let (clean_description, parsed_files, parsed_verify) = split_task_description_metadata(description);
689        let raw = if clean_description.trim().is_empty() {
690            description.trim()
691        } else {
692            clean_description.trim()
693        };
694        let description = short_task_description(raw);
695        let mut metadata = TaskStepMetadata {
696            files: string_array(item.get("files")),
697            outcome: item.get("outcome").and_then(Value::as_str).map(ToOwned::to_owned),
698            verify: string_or_string_array(item.get("verify")),
699            scope_review: string_or_string_array(item.get("scope_review")),
700        };
701        if metadata.files.is_empty() {
702            metadata.files = parsed_files;
703        }
704        if metadata.verify.is_empty() {
705            metadata.verify = parsed_verify;
706        }
707
708        ordered_paths.push(index_path.clone());
709        nodes_by_path.insert(
710            index_path.clone(),
711            TaskTreeNode {
712                index_path,
713                description,
714                status,
715                metadata,
716                children: Vec::new(),
717            },
718        );
719    }
720
721    let mut attachment_order = ordered_paths.clone();
722    attachment_order.sort_by_key(|path| std::cmp::Reverse(path.split('.').count()));
723    for path in attachment_order {
724        let Some(parent_path) = path.rsplit_once('.').map(|(parent, _)| parent.to_string()) else {
725            continue;
726        };
727        let Some(child) = nodes_by_path.remove(&path) else {
728            continue;
729        };
730        if let Some(parent) = nodes_by_path.get_mut(&parent_path) {
731            parent.children.push(child);
732        } else {
733            nodes_by_path.insert(path, child);
734        }
735    }
736
737    let roots = ordered_paths
738        .into_iter()
739        .filter_map(|path| nodes_by_path.remove(&path))
740        .collect::<Vec<_>>();
741    compact_task_tree_view(&roots)
742}
743
744fn string_array(value: Option<&Value>) -> Vec<String> {
745    value
746        .and_then(Value::as_array)
747        .into_iter()
748        .flatten()
749        .filter_map(Value::as_str)
750        .map(ToOwned::to_owned)
751        .collect()
752}
753
754fn string_or_string_array(value: Option<&Value>) -> Vec<String> {
755    match value {
756        Some(Value::String(value)) => vec![value.clone()],
757        Some(Value::Array(_)) => string_array(value),
758        _ => Vec::new(),
759    }
760}
761
762#[derive(Default)]
763pub struct TaskCounts {
764    pub total: usize,
765    pub completed: usize,
766    pub in_progress: usize,
767    pub pending: usize,
768    pub blocked: usize,
769}
770
771impl TaskCounts {
772    pub fn add(&mut self, status: &TaskTrackingStatus) {
773        self.total += 1;
774        match status {
775            TaskTrackingStatus::Pending => self.pending += 1,
776            TaskTrackingStatus::InProgress => self.in_progress += 1,
777            TaskTrackingStatus::Completed => self.completed += 1,
778            TaskTrackingStatus::Blocked => self.blocked += 1,
779        }
780    }
781
782    pub fn progress_percent(&self) -> usize {
783        if self.total > 0 {
784            #[allow(
785                clippy::cast_sign_loss,
786                clippy::let_and_return,
787                reason = "Intentional compatibility, platform, or test-only suppression."
788            )]
789            let progress = ((self.completed as f64 / self.total as f64 * 100.0).round()).max(0.0) as usize;
790            progress
791        } else {
792            0
793        }
794    }
795}
796
797#[cfg(test)]
798mod tests;