Skip to main content

vtcode_core/tools/handlers/
task_tracking.rs

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    /// Workspace-scope evidence, kept separate from functional verification.
22    #[serde(default, skip_serializing_if = "Vec::is_empty")]
23    pub scope_review: Vec<String>,
24}
25
26#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
27#[serde(untagged)]
28pub enum TaskItemInput {
29    Text(String),
30    Structured(TaskItemInputObject),
31}
32
33#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, Default)]
34pub struct TaskItemInputObject {
35    pub description: String,
36    #[serde(default)]
37    pub status: Option<String>,
38    #[serde(default, deserialize_with = "deserialize_optional_string_list")]
39    pub files: Option<Vec<String>>,
40    #[serde(default)]
41    pub outcome: Option<String>,
42    #[serde(default, deserialize_with = "deserialize_optional_string_list")]
43    pub verify: Option<Vec<String>>,
44    #[serde(default, deserialize_with = "deserialize_optional_string_list")]
45    pub scope_review: Option<Vec<String>>,
46}
47
48pub(crate) struct TaskMetadataRef<'a> {
49    pub description: &'a str,
50    pub metadata: &'a TaskStepMetadata,
51}
52
53pub(crate) struct ParsedTaskItem {
54    pub level: usize,
55    pub description: String,
56    pub status: TaskTrackingStatus,
57    pub metadata: TaskStepMetadata,
58}
59
60/// Normalize both tracker variants and preserve omitted metadata only when
61/// a description identifies exactly one old step and exactly one new step.
62/// Creates pass no previous items; explicit empty metadata still clears it.
63pub(crate) fn parse_task_items(
64    items: &[TaskItemInput],
65    previous: &[TaskMetadataRef<'_>],
66) -> Result<Vec<ParsedTaskItem>> {
67    validate_task_item_inputs(items)?;
68    let mut previous_by_description = HashMap::new();
69    for item in previous {
70        previous_by_description
71            .entry(item.description.trim())
72            .and_modify(|metadata| *metadata = None)
73            .or_insert(Some(item.metadata));
74    }
75    let mut description_counts = HashMap::new();
76    for item in items {
77        let raw = match item {
78            TaskItemInput::Text(raw) => raw,
79            TaskItemInput::Structured(input) => &input.description,
80        };
81        let (_, description) = parse_status_prefix(raw.trim());
82        *description_counts.entry(description.trim().to_owned()).or_insert(0usize) += 1;
83    }
84
85    let mut parsed_items = Vec::with_capacity(items.len());
86    for item in items {
87        let raw = match item {
88            TaskItemInput::Text(raw) => raw,
89            TaskItemInput::Structured(input) => &input.description,
90        };
91        let (mut status, description) = parse_status_prefix(raw.trim());
92        let description = description.trim().to_owned();
93        if description.is_empty() {
94            continue;
95        }
96        let previous_metadata = if description_counts.get(&description) == Some(&1) {
97            previous_by_description.get(description.as_str()).copied().flatten()
98        } else {
99            None
100        };
101        let has_previous_scope_review = previous
102            .iter()
103            .any(|previous| previous.description.trim() == description && !previous.metadata.scope_review.is_empty());
104        if previous_metadata.is_none()
105            && previous
106                .iter()
107                .any(|item| item.description.trim() == description && item.metadata != &TaskStepMetadata::default())
108            && !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()))
109        {
110            bail!(
111                "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."
112            );
113        }
114        let mut metadata = previous_metadata.cloned().unwrap_or_default();
115        if let TaskItemInput::Structured(input) = item {
116            if let Some(raw_status) = input.status.as_deref() {
117                status = TaskTrackingStatus::from_str(raw_status)?;
118            }
119            apply_metadata_input(
120                &mut metadata,
121                input.files.as_deref(),
122                input.outcome.as_deref(),
123                input.verify.as_deref(),
124            );
125            if let Some(scope_review) = input.scope_review.as_deref() {
126                metadata.scope_review = normalize_verify_items(scope_review.iter().map(String::as_str));
127            }
128        }
129        parsed_items.push(ParsedTaskItem {
130            level: raw.chars().take_while(|character| *character == ' ').count() / 2,
131            description,
132            status,
133            metadata,
134        });
135    }
136    Ok(parsed_items)
137}
138
139pub(crate) fn apply_metadata_input(
140    metadata: &mut TaskStepMetadata,
141    files: Option<&[String]>,
142    outcome: Option<&str>,
143    verify: Option<&[String]>,
144) {
145    if let Some(files) = files {
146        metadata.files = normalize_string_items(Some(files));
147    }
148    if let Some(outcome) = outcome {
149        metadata.outcome = normalize_optional_text(Some(outcome));
150    }
151    if let Some(verify) = verify {
152        metadata.verify = normalize_verify_items(verify.iter().map(String::as_str));
153    }
154}
155
156#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
157#[serde(rename_all = "snake_case")]
158pub enum TaskTrackingStatus {
159    Pending,
160    InProgress,
161    Completed,
162    Blocked,
163}
164
165impl std::fmt::Display for TaskTrackingStatus {
166    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
167        write!(f, "{}", self.as_str())
168    }
169}
170
171impl FromStr for TaskTrackingStatus {
172    type Err = anyhow::Error;
173
174    fn from_str(value: &str) -> Result<Self> {
175        match value {
176            "pending" => Ok(Self::Pending),
177            "in_progress" => Ok(Self::InProgress),
178            "completed" => Ok(Self::Completed),
179            "blocked" => Ok(Self::Blocked),
180            other => {
181                bail!("Invalid status '{other}'. Use: pending, in_progress, completed, blocked")
182            }
183        }
184    }
185}
186
187impl TaskTrackingStatus {
188    pub fn as_str(&self) -> &'static str {
189        match self {
190            Self::Pending => "pending",
191            Self::InProgress => "in_progress",
192            Self::Completed => "completed",
193            Self::Blocked => "blocked",
194        }
195    }
196
197    pub fn flat_checkbox(&self) -> &'static str {
198        match self {
199            Self::Pending => "[ ]",
200            Self::InProgress => "[/]",
201            Self::Completed => "[x]",
202            Self::Blocked => "[!]",
203        }
204    }
205
206    pub fn plan_checkbox(&self) -> &'static str {
207        match self {
208            Self::Pending => "[ ]",
209            Self::InProgress => "[~]",
210            Self::Completed => "[x]",
211            Self::Blocked => "[!]",
212        }
213    }
214
215    pub fn view_symbol(&self) -> &'static str {
216        match self {
217            Self::Pending => "•",
218            Self::InProgress => ">",
219            Self::Completed => "✔",
220            Self::Blocked => "!",
221        }
222    }
223
224    pub fn compact_view_symbol(&self) -> &'static str {
225        match self {
226            Self::Pending => "□",
227            Self::InProgress => "[-]",
228            Self::Completed => "[x]",
229            Self::Blocked => "[!]",
230        }
231    }
232}
233
234pub fn parse_marked_status_prefix(value: &str) -> Option<(TaskTrackingStatus, String)> {
235    let trimmed = value.trim_start();
236    let mapping = [
237        ("[x] ", TaskTrackingStatus::Completed),
238        ("[X] ", TaskTrackingStatus::Completed),
239        ("[~] ", TaskTrackingStatus::InProgress),
240        ("[/] ", TaskTrackingStatus::InProgress),
241        ("[!] ", TaskTrackingStatus::Blocked),
242        ("[ ] ", TaskTrackingStatus::Pending),
243    ];
244    for (prefix, status) in mapping {
245        if let Some(rest) = trimmed.strip_prefix(prefix) {
246            return Some((status, rest.to_string()));
247        }
248    }
249    None
250}
251
252pub fn parse_status_prefix(value: &str) -> (TaskTrackingStatus, String) {
253    parse_marked_status_prefix(value).unwrap_or((TaskTrackingStatus::Pending, value.trim_start().to_string()))
254}
255
256pub fn append_notes(existing: Option<String>, append: Option<&str>) -> Option<String> {
257    match (existing, append) {
258        (None, None) => None,
259        (Some(text), None) => {
260            if text.trim().is_empty() {
261                None
262            } else {
263                Some(text)
264            }
265        }
266        (None, Some(extra)) => {
267            let trimmed = extra.trim();
268            if trimmed.is_empty() {
269                None
270            } else {
271                Some(trimmed.to_string())
272            }
273        }
274        (Some(text), Some(extra)) => {
275            let left = text.trim();
276            let right = extra.trim();
277            if left.is_empty() && right.is_empty() {
278                None
279            } else if left.is_empty() {
280                Some(right.to_string())
281            } else if right.is_empty() {
282                Some(left.to_string())
283            } else {
284                Some(format!("{left}\n{right}"))
285            }
286        }
287    }
288}
289
290pub fn append_notes_section(markdown: &mut String, notes: Option<&str>) {
291    if let Some(text) = notes {
292        let trimmed = text.trim();
293        if !trimmed.is_empty() {
294            markdown.push_str("\n## Notes\n\n");
295            markdown.push_str(trimmed);
296            markdown.push('\n');
297        }
298    }
299}
300
301pub(crate) fn validate_update_shape<T>(
302    items: Option<&[T]>,
303    index: Option<usize>,
304    index_path: Option<&str>,
305    status: Option<&str>,
306) -> Result<()> {
307    if index.is_some() && index_path.is_some() {
308        bail!("task-tracker updates cannot combine 'index' and 'index_path'");
309    }
310
311    if items.is_some() && (index.is_some() || index_path.is_some() || status.is_some()) {
312        bail!("bulk task-tracker updates cannot combine 'items' with 'index', 'index_path', or 'status'");
313    }
314
315    Ok(())
316}
317
318pub(crate) fn validate_action_index_fields(action: &str, index: Option<usize>, index_path: Option<&str>) -> Result<()> {
319    if action != "update" && (index.is_some() || index_path.is_some()) {
320        bail!(
321            "task-tracker action '{action}' cannot use 'index' or 'index_path'; indices are only valid with action='update'"
322        );
323    }
324
325    Ok(())
326}
327
328pub(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; include scope_review when existing scope checks would otherwise be ambiguous.";
329
330/// Shared status values for every task-tracker schema (standard + planning,
331/// top-level and nested item objects). Single source so a future status
332/// addition cannot drift between the planning on/off variants.
333pub(crate) const TASK_STATUS_VALUES: [&str; 4] = ["pending", "in_progress", "completed", "blocked"];
334
335/// Base `status` type schema without a description (callers add their own).
336pub(crate) fn task_status_schema() -> Value {
337    json!({
338        "type": "string",
339        "enum": TASK_STATUS_VALUES
340    })
341}
342
343/// Base `files` type schema without a description.
344pub(crate) fn task_files_schema() -> Value {
345    json!({
346        "type": "array",
347        "items": { "type": "string" }
348    })
349}
350
351/// Base `verify` type schema without a description (string or string list).
352pub(crate) fn task_verify_schema() -> Value {
353    json!({
354        "anyOf": [
355            { "type": "string" },
356            {
357                "type": "array",
358                "items": { "type": "string" }
359            }
360        ]
361    })
362}
363
364fn with_description(mut schema: Value, description: &str) -> Value {
365    if let Value::Object(map) = &mut schema {
366        map.insert("description".to_string(), Value::String(description.to_string()));
367    }
368    schema
369}
370
371/// Shared `allOf` conditional blocks for both tracker parameter schemas.
372///
373/// The create, update, no-indices, and add blocks are identical across
374/// trackers; the update `anyOf` arms are order-normalized (validation is
375/// order-independent and no test indexes arm positions). The `index == 0`
376/// completion rule is standard-tracker-only (planning indices start at 1):
377/// `include_index_zero_rule` inserts it at position 2, preserving the
378/// `allOf[2]` contract asserted by the standard schema tests.
379pub(crate) fn tracker_schema_allof(include_index_zero_rule: bool) -> Vec<Value> {
380    let mut allof = vec![
381        json!({
382            "if": {
383                "properties": { "action": { "const": "create" } },
384                "required": ["action"]
385            },
386            "then": {
387                "required": ["items"]
388            }
389        }),
390        json!({
391            "if": {
392                "properties": { "action": { "const": "update" } },
393                "required": ["action"]
394            },
395            "then": {
396                "anyOf": [
397                    {
398                        "required": ["index", "status"],
399                        "not": {
400                            "anyOf": [
401                                { "required": ["items"] },
402                                { "required": ["index_path"] }
403                            ]
404                        }
405                    },
406                    {
407                        "required": ["index_path", "status"],
408                        "not": {
409                            "anyOf": [
410                                { "required": ["items"] },
411                                { "required": ["index"] }
412                            ]
413                        }
414                    },
415                    {
416                        "required": ["items"],
417                        "not": {
418                            "anyOf": [
419                                { "required": ["index"] },
420                                { "required": ["index_path"] },
421                                { "required": ["status"] }
422                            ]
423                        }
424                    }
425                ]
426            }
427        }),
428        json!({
429            "if": {
430                "properties": { "action": { "enum": ["create", "list", "add"] } },
431                "required": ["action"]
432            },
433            "then": {
434                "not": {
435                    "anyOf": [
436                        { "required": ["index"] },
437                        { "required": ["index_path"] }
438                    ]
439                }
440            }
441        }),
442        json!({
443            "if": {
444                "properties": { "action": { "const": "add" } },
445                "required": ["action"]
446            },
447            "then": {
448                "required": ["description"]
449            }
450        }),
451    ];
452    if include_index_zero_rule {
453        allof.insert(
454            2,
455            json!({
456                "if": {
457                    "properties": { "index": { "const": 0 } },
458                    "required": ["index"]
459                },
460                "then": {
461                    "properties": {
462                        "action": { "const": "update" },
463                        "status": { "const": "completed" }
464                    },
465                    "required": ["action", "status"]
466                }
467            }),
468        );
469    }
470    allof
471}
472
473/// Shared nested item-object schema (description + optional status/files/
474/// outcome/verify). Used inside the `items` array of both tracker schemas.
475pub(crate) fn task_item_object_schema() -> Value {
476    json!({
477        "type": "object",
478        "properties": {
479            "description": { "type": "string" },
480            "status": task_status_schema(),
481            "files": task_files_schema(),
482            "outcome": { "type": "string" },
483            "verify": task_verify_schema(),
484            "scope_review": with_description(task_verify_schema(), "Workspace scope checks; do not satisfy functional verification.")
485        },
486        "required": ["description"]
487    })
488}
489
490/// Shared `items` array schema with a caller-supplied description.
491pub(crate) fn task_items_array_schema(items_description: &str) -> Value {
492    with_description(
493        json!({
494            "type": "array",
495            "items": {
496                "anyOf": [
497                    { "type": "string" },
498                    task_item_object_schema()
499                ]
500            }
501        }),
502        items_description,
503    )
504}
505
506/// Top-level `status` property with its own description.
507pub(crate) fn task_status_property_schema(description: &str) -> Value {
508    with_description(task_status_schema(), description)
509}
510
511/// Top-level `files` property with its own description.
512pub(crate) fn task_files_property_schema(description: &str) -> Value {
513    with_description(task_files_schema(), description)
514}
515
516/// Top-level `verify` property with its own description.
517pub(crate) fn task_verify_property_schema(description: &str) -> Value {
518    with_description(task_verify_schema(), description)
519}
520
521/// Checklist replacement must not interpret encoded update commands as descriptions.
522pub(crate) fn validate_task_item_inputs(items: &[TaskItemInput]) -> Result<()> {
523    for item in items {
524        let TaskItemInput::Text(text) = item else {
525            continue;
526        };
527        let (_, description) = parse_status_prefix(text.trim());
528        if let Ok(Value::Object(object)) = serde_json::from_str::<Value>(&description)
529            && ["index", "index_path", "description", "status"]
530                .iter()
531                .any(|key| object.contains_key(*key))
532        {
533            bail!(
534                "'items' replaces the complete checklist; JSON-encoded task updates are not task descriptions. \
535                 Update an existing step directly: {{\"action\":\"update\",\"index_path\":\"1\",\"status\":\"completed\"}}. \
536                 For full synchronization, send descriptions with statuses, for example \
537                 {{\"action\":\"update\",\"items\":[{{\"description\":\"Original step\",\"status\":\"completed\"}}]}}. \
538                 The checklist was not changed. Retry once with the intended shape."
539            );
540        }
541    }
542    Ok(())
543}
544
545pub fn is_bulk_sync_update<T>(
546    items: Option<&[T]>,
547    index: Option<usize>,
548    index_path: Option<&str>,
549    status: Option<&str>,
550) -> bool {
551    items.is_some() && index.is_none() && index_path.is_none() && status.is_none()
552}
553
554pub fn deserialize_optional_string_list<'de, D>(deserializer: D) -> std::result::Result<Option<Vec<String>>, D::Error>
555where
556    D: serde::Deserializer<'de>,
557{
558    #[derive(Deserialize)]
559    #[serde(untagged)]
560    enum OneOrMany {
561        One(String),
562        Many(Vec<String>),
563    }
564
565    let parsed = Option::<OneOrMany>::deserialize(deserializer)?;
566    Ok(parsed.map(|value| match value {
567        OneOrMany::One(item) => vec![item],
568        OneOrMany::Many(items) => items,
569    }))
570}
571
572/// Strip one balanced markdown code-span pair from a `verify` entry.
573///
574/// `verify` values are shell commands, and models faithfully emit them in the
575/// code-spans the prompt examples use (`verify: [`cargo check`]`). A stored
576/// code span is never valid shell, so the decoration must not reach
577/// strings that are later compared literally or re-executed — otherwise the
578/// completion gate demands an "exact command" the executor is forbidden to
579/// type (preflight rejects code spans as command substitution).
580/// Callers choose where to apply this: producer ingestion
581/// (`apply_metadata_input`/`apply_metadata_line`) for canonical storage, or
582/// a consumer defense boundary. Markdown mirrors keep code spans.
583pub(crate) fn unwrap_verify_code_span(command: &str) -> &str {
584    let trimmed = command.trim();
585    if trimmed.starts_with('`') && trimmed.ends_with('`') && trimmed.len() >= 2 {
586        let inner = &trimmed[1..trimmed.len() - 1];
587        if !inner.contains('`') {
588            return inner;
589        }
590    }
591    trimmed
592}
593
594/// Normalize the executable `verify` item: trim, drop the code-span
595/// decoration, and drop empties.
596pub(crate) fn normalize_verify_items<'a>(items: impl IntoIterator<Item = &'a str>) -> Vec<String> {
597    items
598        .into_iter()
599        .filter_map(|item| {
600            let unwrapped = unwrap_verify_code_span(item);
601            (!unwrapped.is_empty()).then(|| unwrapped.to_owned())
602        })
603        .collect()
604}
605
606pub fn normalize_string_items(items: Option<&[String]>) -> Vec<String> {
607    items
608        .unwrap_or(&[])
609        .iter()
610        .map(|item| item.trim())
611        .filter(|item| !item.is_empty())
612        .map(ToOwned::to_owned)
613        .collect()
614}
615
616pub fn normalize_optional_text(value: Option<&str>) -> Option<String> {
617    value.map(str::trim).filter(|value| !value.is_empty()).map(ToOwned::to_owned)
618}
619
620/// Parse a `files: [...]` metadata value into trimmed non-empty paths.
621/// Commas inside single/double quotes stay part of one item.
622pub fn parse_files_metadata(value: &str) -> Vec<String> {
623    super::planning_workflow::split_bracket_items(value)
624        .into_iter()
625        .map(|item| item.trim().to_owned())
626        .filter(|item| !item.is_empty())
627        .collect()
628}
629
630/// Consume one indented markdown metadata line (`files:`, `outcome:`,
631/// `verify:`, `scope-review:`) into `metadata`, tracking multi-line `verify:` blocks through
632/// `in_verify_block`. Returns `true` when the line was metadata.
633pub fn apply_metadata_line(metadata: &mut TaskStepMetadata, raw: &str, in_verify_block: &mut bool) -> bool {
634    let trimmed = raw.trim_start();
635
636    if *in_verify_block {
637        if let Some(command) = trimmed
638            .strip_prefix("- ")
639            .or_else(|| trimmed.strip_prefix("* "))
640            .or_else(|| trimmed.strip_prefix("+ "))
641        {
642            if let Some(command) = normalize_verify_items([command]).pop() {
643                metadata.verify.push(command);
644            }
645            return true;
646        }
647        *in_verify_block = false;
648    }
649
650    if let Some(rest) = trimmed.strip_prefix("files:") {
651        metadata.files = parse_files_metadata(rest);
652        return true;
653    }
654    if let Some(rest) = trimmed.strip_prefix("outcome:") {
655        metadata.outcome = normalize_optional_text(Some(rest));
656        return true;
657    }
658    if let Some(rest) = trimmed.strip_prefix("scope-review:") {
659        if rest.trim().is_empty() {
660            metadata.scope_review.clear();
661        } else {
662            metadata.scope_review.extend(normalize_verify_items([rest]));
663        }
664        return true;
665    }
666    if trimmed == "verify:" {
667        metadata.verify.clear();
668        *in_verify_block = true;
669        return true;
670    }
671    if let Some(rest) = trimmed.strip_prefix("verify:") {
672        metadata.verify = normalize_verify_items([rest]);
673        return true;
674    }
675
676    false
677}
678
679pub fn append_task_step_metadata(markdown: &mut String, indent: &str, metadata: &TaskStepMetadata) {
680    if !metadata.files.is_empty() {
681        markdown.push_str(indent);
682        markdown.push_str("  files: ");
683        markdown.push_str(&metadata.files.join(", "));
684        markdown.push('\n');
685    }
686
687    if let Some(outcome) = metadata.outcome.as_deref() {
688        markdown.push_str(indent);
689        markdown.push_str("  outcome: ");
690        markdown.push_str(outcome);
691        markdown.push('\n');
692    }
693
694    for command in &metadata.scope_review {
695        markdown.push_str(indent);
696        markdown.push_str("  scope-review: ");
697        markdown.push_str(command);
698        markdown.push('\n');
699    }
700
701    if metadata.verify.len() == 1 {
702        markdown.push_str(indent);
703        markdown.push_str("  verify: ");
704        markdown.push_str(&metadata.verify[0]);
705        markdown.push('\n');
706    } else if !metadata.verify.is_empty() {
707        markdown.push_str(indent);
708        markdown.push_str("  verify:\n");
709        for command in &metadata.verify {
710            markdown.push_str(indent);
711            markdown.push_str("    - ");
712            markdown.push_str(command);
713            markdown.push('\n');
714        }
715    }
716}
717
718pub fn metadata_from_input(
719    files: Option<&[String]>,
720    outcome: Option<&str>,
721    verify: Option<&[String]>,
722) -> TaskStepMetadata {
723    let mut metadata = TaskStepMetadata::default();
724    apply_metadata_input(&mut metadata, files, outcome, verify);
725    metadata
726}
727
728/// Markers that may trail a task description as inline `Action -> files: [...]
729/// -> verify: [...]` metadata. `outcome` is accepted so a polluted suffix is
730/// still stripped from the visible row even though the compact view never
731/// renders it.
732const INLINE_TASK_METADATA_MARKERS: &[&str] = &[" -> files:", " -> verify:", " -> outcome:"];
733
734fn parse_inline_bracket_list(raw: &str) -> Vec<String> {
735    let trimmed = raw.trim();
736    let inner = trimmed
737        .strip_prefix('[')
738        .and_then(|value| value.strip_suffix(']'))
739        .unwrap_or(trimmed);
740    super::planning_workflow::split_bracket_items(inner)
741        .into_iter()
742        .map(|item| item.trim().to_owned())
743        .filter(|value| !value.is_empty())
744        .collect()
745}
746
747/// Split an inline `Action -> files: [...] -> verify: [...]` suffix out of a
748/// task description.
749///
750/// Returns `(clean_description, files, verify)`. Markers are recognized only
751/// outside inline-code spans so `` `a -> files: b` `` stays intact, and the
752/// Unicode `→` arrow is normalized first so both spellings agree with plan
753/// validation. When no marker exists outside backticks the description is
754/// returned trimmed with empty metadata.
755pub fn split_task_description_metadata(description: &str) -> (String, Vec<String>, Vec<String>) {
756    let normalized;
757    let source = if description.contains('→') {
758        normalized = description.replace('→', "->");
759        normalized.as_str()
760    } else {
761        description
762    };
763    let Some(first) = find_inline_metadata_marker(source, 0) else {
764        return (source.trim().to_string(), Vec::new(), Vec::new());
765    };
766    let head = source[..first.0].trim();
767    if head.is_empty() {
768        return (source.trim().to_string(), Vec::new(), Vec::new());
769    }
770
771    let mut files = Vec::new();
772    let mut verify = Vec::new();
773    let mut cursor = first.0;
774    while let Some((marker_start, marker)) = find_inline_metadata_marker(source, cursor) {
775        let value_start = marker_start + marker.len();
776        let next = find_inline_metadata_marker(source, value_start)
777            .map(|(start, _)| start)
778            .unwrap_or(source.len());
779        let value = source[value_start..next].trim();
780        if marker.contains("files:") {
781            files.extend(parse_inline_bracket_list(value));
782        } else if marker.contains("verify:") {
783            verify.extend(parse_inline_bracket_list(value));
784        }
785        cursor = next;
786        if cursor >= source.len() {
787            break;
788        }
789    }
790    (head.to_string(), files, verify)
791}
792
793/// Strip an inline `-> files:` / `-> verify:` / `-> outcome:` suffix for
794/// display. Structured metadata stays in the payload; the visible compact row
795/// must not reintroduce it as detail text.
796pub fn strip_task_description_metadata(description: &str) -> String {
797    split_task_description_metadata(description).0
798}
799
800/// One short description for a task row: the leading clause before detail
801/// separators (` — `/` – `/` - `/`: `, `; `, `. `, ` (`).
802///
803/// Plan steps often carry a long detail tail
804/// (`"Add X – document Y in Z, sourced from W"`); the TODO transcript and
805/// panel must show only `"Add X"` so each item stays on one scannable row.
806/// Inline `-> files:`/`-> verify:` suffixes are stripped first; the full text
807/// stays in structured tracker metadata.
808pub fn short_task_description(description: &str) -> String {
809    let (clean, _, _) = split_task_description_metadata(description);
810    let base = if clean.trim().is_empty() {
811        description.trim()
812    } else {
813        clean.trim()
814    };
815    let first_line = base.lines().map(str::trim).find(|line| !line.is_empty()).unwrap_or("");
816    let collapsed = vtcode_commons::formatting::collapse_whitespace(first_line);
817    if collapsed.is_empty() {
818        return String::new();
819    }
820    let mut cut = collapsed.len();
821    for separator in [" — ", " – ", " - ", ": ", "; ", ". ", " ("] {
822        if let Some(index) = collapsed.find(separator) {
823            cut = cut.min(index);
824        }
825    }
826    let short = collapsed[..cut].trim().trim_end_matches([',', ';', ':', '.']).trim();
827    if short.is_empty() { collapsed } else { short.to_string() }
828}
829
830fn find_inline_metadata_marker(source: &str, from: usize) -> Option<(usize, &'static str)> {
831    let mut inline_ticks: Option<usize> = None;
832    let mut cursor = from.min(source.len());
833    while cursor < source.len() {
834        let remainder = &source[cursor..];
835        if remainder.starts_with('`') {
836            let run = remainder.bytes().take_while(|byte| *byte == b'`').count();
837            if inline_ticks.is_some_and(|ticks| ticks == run) {
838                inline_ticks = None;
839            } else if inline_ticks.is_none() {
840                inline_ticks = Some(run);
841            }
842            cursor += run;
843            continue;
844        }
845        if inline_ticks.is_none() {
846            for marker in INLINE_TASK_METADATA_MARKERS {
847                if remainder.starts_with(marker) {
848                    return Some((cursor, marker));
849                }
850            }
851        }
852        let character = remainder.chars().next()?;
853        cursor += character.len_utf8();
854    }
855    None
856}
857
858/// A renderer-independent task tree used by both task-tracker implementations.
859///
860/// The persisted checklist formats remain implementation-specific; this type is
861/// only the shared shape required to produce the compact visible view.
862#[derive(Debug, Clone, PartialEq, Eq)]
863pub(crate) struct TaskTreeNode {
864    pub(crate) index_path: String,
865    pub(crate) description: String,
866    pub(crate) status: TaskTrackingStatus,
867    pub(crate) metadata: TaskStepMetadata,
868    pub(crate) children: Vec<TaskTreeNode>,
869}
870
871/// Format task nodes as the compact tree shared by inline output and the task
872/// panel. Root leaves retain `├`/`└` connectors; nested leaves use their status
873/// glyph as the connector so the hierarchy stays readable without redundant
874/// branch characters.
875pub(crate) fn compact_task_tree_view(nodes: &[TaskTreeNode]) -> Vec<Value> {
876    let mut lines = Vec::new();
877    append_compact_task_tree_view(nodes, "  ", &mut lines);
878    lines
879}
880
881fn append_compact_task_tree_view(nodes: &[TaskTreeNode], tree_prefix: &str, out: &mut Vec<Value>) {
882    for (index, node) in nodes.iter().enumerate() {
883        let is_last = index + 1 == nodes.len();
884        let branch = if is_last { "└" } else { "├" };
885        let display = if node.children.is_empty() {
886            if tree_prefix == "  " {
887                format!("{tree_prefix}{branch} {} {}", node.status.compact_view_symbol(), node.description)
888            } else {
889                format!("{tree_prefix}{} {}", node.status.compact_view_symbol(), node.description)
890            }
891        } else {
892            format!("{tree_prefix}{branch} {}", node.description)
893        };
894
895        out.push(json!({
896            "display": display,
897            "index_path": node.index_path.clone(),
898            "status": node.status.as_str(),
899            "text": node.description.clone(),
900            "files": node.metadata.files.clone(),
901            "outcome": node.metadata.outcome.clone(),
902            "verify": node.metadata.verify.clone(),
903            "scope_review": node.metadata.scope_review.clone(),
904        }));
905
906        let next_prefix = if is_last {
907            format!("{tree_prefix}  ")
908        } else {
909            format!("{tree_prefix}│ ")
910        };
911        append_compact_task_tree_view(&node.children, &next_prefix, out);
912    }
913}
914
915/// Build the compact tree from a flattened checklist summary.
916///
917/// Standard task trackers expose numeric `index` values while planning
918/// trackers expose dotted `index_path` values. Accept both forms so callers at
919/// the UI boundary do not need to know which tracker produced the payload.
920pub fn compact_task_tree_view_from_items(items: &[Value]) -> Vec<Value> {
921    let mut ordered_paths = Vec::with_capacity(items.len());
922    let mut nodes_by_path = std::collections::HashMap::with_capacity(items.len());
923
924    for (position, item) in items.iter().enumerate() {
925        let index_path = item
926            .get("index_path")
927            .and_then(Value::as_str)
928            .filter(|path| !path.trim().is_empty())
929            .map(ToOwned::to_owned)
930            .or_else(|| item.get("index").and_then(Value::as_u64).map(|index| index.to_string()))
931            .unwrap_or_else(|| (position + 1).to_string());
932        if nodes_by_path.contains_key(&index_path) {
933            continue;
934        }
935
936        let status = match item.get("status").and_then(Value::as_str) {
937            Some(value) => match TaskTrackingStatus::from_str(value) {
938                Ok(status) => status,
939                Err(_) => continue,
940            },
941            None => TaskTrackingStatus::Pending,
942        };
943        let Some(description) = item
944            .get("description")
945            .and_then(Value::as_str)
946            .or_else(|| item.get("text").and_then(Value::as_str))
947            .filter(|description| !description.trim().is_empty())
948        else {
949            continue;
950        };
951        // Descriptions copied from plan steps may still carry an inline
952        // `Action -> files: [...] -> verify: [...]` suffix plus a long detail
953        // tail (`"Add X – document Y, sourced from Z"`). Keep only the short
954        // leading clause for the visible row and fold the rest into structured
955        // metadata so the compact view never reintroduces files/verify/detail
956        // text.
957        let (clean_description, parsed_files, parsed_verify) = split_task_description_metadata(description);
958        let raw = if clean_description.trim().is_empty() {
959            description.trim()
960        } else {
961            clean_description.trim()
962        };
963        let description = short_task_description(raw);
964        let mut metadata = TaskStepMetadata {
965            files: string_array(item.get("files")),
966            outcome: item.get("outcome").and_then(Value::as_str).map(ToOwned::to_owned),
967            verify: string_or_string_array(item.get("verify")),
968            scope_review: string_or_string_array(item.get("scope_review")),
969        };
970        if metadata.files.is_empty() {
971            metadata.files = parsed_files;
972        }
973        if metadata.verify.is_empty() {
974            metadata.verify = parsed_verify;
975        }
976
977        ordered_paths.push(index_path.clone());
978        nodes_by_path.insert(
979            index_path.clone(),
980            TaskTreeNode {
981                index_path,
982                description,
983                status,
984                metadata,
985                children: Vec::new(),
986            },
987        );
988    }
989
990    let mut attachment_order = ordered_paths.clone();
991    attachment_order.sort_by_key(|path| std::cmp::Reverse(path.split('.').count()));
992    for path in attachment_order {
993        let Some(parent_path) = path.rsplit_once('.').map(|(parent, _)| parent.to_string()) else {
994            continue;
995        };
996        let Some(child) = nodes_by_path.remove(&path) else {
997            continue;
998        };
999        if let Some(parent) = nodes_by_path.get_mut(&parent_path) {
1000            parent.children.push(child);
1001        } else {
1002            nodes_by_path.insert(path, child);
1003        }
1004    }
1005
1006    let roots = ordered_paths
1007        .into_iter()
1008        .filter_map(|path| nodes_by_path.remove(&path))
1009        .collect::<Vec<_>>();
1010    compact_task_tree_view(&roots)
1011}
1012
1013fn string_array(value: Option<&Value>) -> Vec<String> {
1014    value
1015        .and_then(Value::as_array)
1016        .into_iter()
1017        .flatten()
1018        .filter_map(Value::as_str)
1019        .map(ToOwned::to_owned)
1020        .collect()
1021}
1022
1023fn string_or_string_array(value: Option<&Value>) -> Vec<String> {
1024    match value {
1025        Some(Value::String(value)) => vec![value.clone()],
1026        Some(Value::Array(_)) => string_array(value),
1027        _ => Vec::new(),
1028    }
1029}
1030
1031#[derive(Default)]
1032pub struct TaskCounts {
1033    pub total: usize,
1034    pub completed: usize,
1035    pub in_progress: usize,
1036    pub pending: usize,
1037    pub blocked: usize,
1038}
1039
1040impl TaskCounts {
1041    pub fn add(&mut self, status: &TaskTrackingStatus) {
1042        self.total += 1;
1043        match status {
1044            TaskTrackingStatus::Pending => self.pending += 1,
1045            TaskTrackingStatus::InProgress => self.in_progress += 1,
1046            TaskTrackingStatus::Completed => self.completed += 1,
1047            TaskTrackingStatus::Blocked => self.blocked += 1,
1048        }
1049    }
1050
1051    pub fn progress_percent(&self) -> usize {
1052        if self.total > 0 {
1053            #[allow(
1054                clippy::cast_sign_loss,
1055                clippy::let_and_return,
1056                reason = "Intentional compatibility, platform, or test-only suppression."
1057            )]
1058            let progress = ((self.completed as f64 / self.total as f64 * 100.0).round()).max(0.0) as usize;
1059            progress
1060        } else {
1061            0
1062        }
1063    }
1064}
1065
1066#[cfg(test)]
1067mod tests {
1068    use super::*;
1069
1070    #[test]
1071    fn scope_review_rows_round_trip_without_functional_verification_credit() {
1072        let mut metadata = TaskStepMetadata::default();
1073        let mut in_verify_block = false;
1074        for row in [
1075            "  files: README.md",
1076            "  scope-review: `git status --porcelain`",
1077            "  scope-review: git diff --stat HEAD -- README.md",
1078        ] {
1079            assert!(apply_metadata_line(&mut metadata, row, &mut in_verify_block));
1080        }
1081        assert_eq!(metadata.scope_review, vec!["git status --porcelain", "git diff --stat HEAD -- README.md"]);
1082        assert!(metadata.verify.is_empty());
1083        let mut markdown = String::new();
1084        append_task_step_metadata(&mut markdown, "", &metadata);
1085        assert_eq!(
1086            markdown,
1087            "  files: README.md\n  scope-review: git status --porcelain\n  scope-review: git diff --stat HEAD -- README.md\n"
1088        );
1089        let old: TaskStepMetadata = serde_json::from_value(json!({"verify": ["cargo check"]})).unwrap();
1090        assert!(old.scope_review.is_empty());
1091        assert_eq!(old.verify, vec!["cargo check"]);
1092        let restored: TaskStepMetadata = serde_json::from_value(serde_json::to_value(&metadata).unwrap()).unwrap();
1093        assert_eq!(restored, metadata);
1094        let previous = [TaskMetadataRef { description: "Review scope", metadata: &metadata }];
1095        let updated = parse_task_items(&[TaskItemInput::Text("[x] Review scope".to_string())], &previous).unwrap();
1096        assert_eq!(updated[0].metadata.scope_review, metadata.scope_review);
1097        assert!(updated[0].metadata.verify.is_empty());
1098        let cleared = parse_task_items(
1099            &[TaskItemInput::Structured(TaskItemInputObject {
1100                description: "Review scope".to_string(),
1101                scope_review: Some(Vec::new()),
1102                ..Default::default()
1103            })],
1104            &previous,
1105        )
1106        .unwrap();
1107        assert!(cleared[0].metadata.scope_review.is_empty());
1108    }
1109
1110    #[test]
1111    fn compact_tree_retains_scope_metadata_in_a_distinct_field() {
1112        let rows = compact_task_tree_view_from_items(&[json!({
1113            "description": "Review scope", "scope_review": ["git status --porcelain"],
1114            "verify": ["rg -n 'Overview' README.md"],
1115        })]);
1116        assert_eq!(rows[0]["scope_review"], json!(["git status --porcelain"]));
1117        assert_eq!(rows[0]["verify"], json!(["rg -n 'Overview' README.md"]));
1118    }
1119
1120    #[test]
1121    fn parse_files_metadata_keeps_quoted_commas_as_single_item() {
1122        let items = parse_files_metadata("'src/a.rs, b.rs', src/c.rs");
1123        assert_eq!(items, vec!["'src/a.rs, b.rs'".to_string(), "src/c.rs".to_string()]);
1124    }
1125
1126    #[test]
1127    fn apply_metadata_line_drives_verify_block_state_machine() {
1128        let mut metadata = TaskStepMetadata::default();
1129        let mut in_verify_block = false;
1130
1131        // Non-metadata lines are rejected without touching state.
1132        assert!(!apply_metadata_line(&mut metadata, "just a description", &mut in_verify_block));
1133        assert!(!in_verify_block);
1134        assert!(metadata.verify.is_empty());
1135
1136        // files:/outcome: lines are consumed directly (persisted bracket-free).
1137        assert!(apply_metadata_line(&mut metadata, "  files: a.rs, b.rs", &mut in_verify_block));
1138        assert!(apply_metadata_line(&mut metadata, "  outcome: did the thing", &mut in_verify_block));
1139        assert_eq!(metadata.files, vec!["a.rs".to_string(), "b.rs".to_string()]);
1140        assert_eq!(metadata.outcome.as_deref(), Some("did the thing"));
1141
1142        // Bare `verify:` opens a block; mixed bullet markers accumulate.
1143        assert!(apply_metadata_line(&mut metadata, "  verify:", &mut in_verify_block));
1144        assert!(in_verify_block);
1145        assert!(apply_metadata_line(&mut metadata, "    - cargo test", &mut in_verify_block));
1146        assert!(apply_metadata_line(&mut metadata, "    * cargo clippy", &mut in_verify_block));
1147        assert_eq!(metadata.verify, vec!["cargo test".to_string(), "cargo clippy".to_string()]);
1148
1149        // A non-bullet line closes the block and is itself rejected.
1150        assert!(!apply_metadata_line(&mut metadata, "  other: x", &mut in_verify_block));
1151        assert!(!in_verify_block);
1152
1153        // Inline `verify:` replaces the accumulated block.
1154        assert!(apply_metadata_line(&mut metadata, "  verify: make check", &mut in_verify_block));
1155        assert_eq!(metadata.verify, vec!["make check".to_string()]);
1156    }
1157
1158    #[test]
1159    fn verify_ingestion_strips_code_span_decoration() {
1160        // Regression for session-vtcode-20261019T075619Z: models emit verify
1161        // in the taught code-span form, and a stored code span is (a) never
1162        // valid shell and (b) forbidden to type back at preflight, which
1163        // deadlocked the completion-verification gate. Ingestion must store
1164        // the executable command in every input shape.
1165        let mut metadata = TaskStepMetadata::default();
1166        let mut in_verify_block = false;
1167        assert!(apply_metadata_line(
1168            &mut metadata,
1169            "  verify: `./scripts/update-contributors-readme.sh --dry-run`",
1170            &mut in_verify_block
1171        ));
1172        assert_eq!(metadata.verify, vec!["./scripts/update-contributors-readme.sh --dry-run".to_string()]);
1173        // Multi-line block entries unwrap too.
1174        assert!(apply_metadata_line(&mut metadata, "  verify:", &mut in_verify_block));
1175        assert!(apply_metadata_line(&mut metadata, "    - `git show --stat HEAD`", &mut in_verify_block));
1176        assert_eq!(metadata.verify, vec!["git show --stat HEAD".to_string()]);
1177        // Structured API input (create/update items) unwraps as well.
1178        let mut structured = TaskStepMetadata::default();
1179        apply_metadata_input(
1180            &mut structured,
1181            Some(&["README.md".to_string()]),
1182            None,
1183            Some(&["`cargo check --locked`".to_string()]),
1184        );
1185        assert_eq!(structured.verify, vec!["cargo check --locked".to_string()]);
1186        // Nested/unbalanced spans are left untouched (fail-safe).
1187        let mut nested = TaskStepMetadata::default();
1188        apply_metadata_input(&mut nested, None, None, Some(&["`grep -n '`x`' f`".to_string()]));
1189        assert_eq!(nested.verify, vec!["`grep -n '`x`' f`".to_string()]);
1190    }
1191
1192    #[test]
1193    fn parse_marked_status_prefix_rejects_unmarked_text() {
1194        let parsed = parse_marked_status_prefix("plain text without marker");
1195        assert!(parsed.is_none());
1196    }
1197
1198    #[test]
1199    fn parse_status_prefix_defaults_to_pending_for_unmarked_text() {
1200        let (status, description) = parse_status_prefix("plain text without marker");
1201        assert_eq!(status, TaskTrackingStatus::Pending);
1202        assert_eq!(description, "plain text without marker");
1203    }
1204
1205    #[test]
1206    fn parse_status_prefix_supports_both_in_progress_markers() {
1207        let (status_tilde, text_tilde) = parse_status_prefix("[~] do thing");
1208        let (status_slash, text_slash) = parse_status_prefix("[/] do thing");
1209        assert_eq!(status_tilde, TaskTrackingStatus::InProgress);
1210        assert_eq!(status_slash, TaskTrackingStatus::InProgress);
1211        assert_eq!(text_tilde, "do thing");
1212        assert_eq!(text_slash, "do thing");
1213    }
1214
1215    #[test]
1216    fn append_notes_joins_with_single_newline() {
1217        let merged = append_notes(Some("left".to_string()), Some("right"));
1218        assert_eq!(merged, Some("left\nright".to_string()));
1219    }
1220
1221    #[test]
1222    fn append_notes_section_ignores_blank_notes() {
1223        let mut markdown = "# Title\n".to_string();
1224        append_notes_section(&mut markdown, Some("   "));
1225        assert_eq!(markdown, "# Title\n");
1226    }
1227
1228    #[test]
1229    fn bulk_sync_validation_preserves_text_and_actual_structured_items() {
1230        let valid = vec![
1231            TaskItemInput::Text(r#"[x] Document {"status":"completed"}"#.to_string()),
1232            TaskItemInput::Text(r#"{"example":"literal JSON"}"#.to_string()),
1233            TaskItemInput::Structured(TaskItemInputObject {
1234                description: "Original step".to_string(),
1235                status: Some("completed".to_string()),
1236                ..Default::default()
1237            }),
1238        ];
1239        validate_task_item_inputs(&valid).unwrap();
1240        for text in [
1241            r#"{"index":1,"status":"completed"}"#,
1242            r#"{"description":"Encoded step","status":"completed"}"#,
1243        ] {
1244            for prefix in ["", "[x] ", "[X] ", "[~] ", "[/] ", "[!] ", "[ ] "] {
1245                let item = TaskItemInput::Text(format!("  {prefix}{text}  "));
1246                assert!(validate_task_item_inputs(&[item]).is_err(), "prefix {prefix:?}");
1247            }
1248        }
1249    }
1250
1251    #[test]
1252    fn is_bulk_sync_update_requires_items_and_missing_single_item_fields() {
1253        let items = vec!["Step".to_string()];
1254        let no_items: Option<&[String]> = None;
1255        assert!(is_bulk_sync_update(Some(&items), None, None, None));
1256        assert!(!is_bulk_sync_update(no_items, Some(1), None, Some("completed")));
1257    }
1258
1259    #[test]
1260    fn is_bulk_sync_update_rejects_mixed_single_item_fields() {
1261        let items = vec!["Step".to_string()];
1262        let error = validate_update_shape(Some(&items), Some(1), None, Some("completed"))
1263            .expect_err("mixed bulk and single update fields must fail closed");
1264
1265        assert!(error.to_string().contains("cannot combine 'items'"));
1266    }
1267
1268    #[test]
1269    fn task_tracker_update_rejects_both_index_forms() {
1270        let error = validate_update_shape::<String>(None, Some(1), Some("1"), Some("completed"))
1271            .expect_err("an update must select exactly one index form");
1272
1273        assert!(error.to_string().contains("cannot combine 'index' and 'index_path'"));
1274    }
1275
1276    #[test]
1277    fn task_counts_tracks_progress() {
1278        let mut counts = TaskCounts::default();
1279        counts.add(&TaskTrackingStatus::Completed);
1280        counts.add(&TaskTrackingStatus::Pending);
1281        counts.add(&TaskTrackingStatus::Blocked);
1282        counts.add(&TaskTrackingStatus::InProgress);
1283        assert_eq!(counts.total, 4);
1284        assert_eq!(counts.completed, 1);
1285        assert_eq!(counts.pending, 1);
1286        assert_eq!(counts.blocked, 1);
1287        assert_eq!(counts.in_progress, 1);
1288        assert_eq!(counts.progress_percent(), 25);
1289    }
1290
1291    #[test]
1292    fn compact_task_tree_view_formats_flat_leaf_statuses_exactly() {
1293        let nodes = [
1294            TaskTreeNode {
1295                index_path: "1".to_string(),
1296                description: "Pending".to_string(),
1297                status: TaskTrackingStatus::Pending,
1298                metadata: TaskStepMetadata::default(),
1299                children: Vec::new(),
1300            },
1301            TaskTreeNode {
1302                index_path: "2".to_string(),
1303                description: "In progress".to_string(),
1304                status: TaskTrackingStatus::InProgress,
1305                metadata: TaskStepMetadata::default(),
1306                children: Vec::new(),
1307            },
1308            TaskTreeNode {
1309                index_path: "3".to_string(),
1310                description: "Completed".to_string(),
1311                status: TaskTrackingStatus::Completed,
1312                metadata: TaskStepMetadata::default(),
1313                children: Vec::new(),
1314            },
1315            TaskTreeNode {
1316                index_path: "4".to_string(),
1317                description: "Blocked".to_string(),
1318                status: TaskTrackingStatus::Blocked,
1319                metadata: TaskStepMetadata::default(),
1320                children: Vec::new(),
1321            },
1322        ];
1323
1324        let displays = compact_task_tree_view(&nodes)
1325            .into_iter()
1326            .filter_map(|line| line.get("display").and_then(Value::as_str).map(ToOwned::to_owned))
1327            .collect::<Vec<_>>();
1328        assert_eq!(
1329            displays,
1330            vec![
1331                "  ├ □ Pending".to_string(),
1332                "  ├ [-] In progress".to_string(),
1333                "  ├ [x] Completed".to_string(),
1334                "  └ [!] Blocked".to_string(),
1335            ]
1336        );
1337    }
1338
1339    #[test]
1340    fn compact_task_tree_view_omits_parent_status_but_keeps_metadata_fields() {
1341        let nodes = [TaskTreeNode {
1342            index_path: "1".to_string(),
1343            description: "Parent".to_string(),
1344            status: TaskTrackingStatus::InProgress,
1345            metadata: TaskStepMetadata {
1346                files: vec!["Cargo.toml".to_string()],
1347                outcome: Some("Ready".to_string()),
1348                verify: vec!["cargo check".to_string()],
1349                ..Default::default()
1350            },
1351            children: vec![TaskTreeNode {
1352                index_path: "1.1".to_string(),
1353                description: "Child".to_string(),
1354                status: TaskTrackingStatus::Completed,
1355                metadata: TaskStepMetadata::default(),
1356                children: Vec::new(),
1357            }],
1358        }];
1359
1360        let lines = compact_task_tree_view(&nodes);
1361        assert_eq!(lines[0]["display"], "  └ Parent");
1362        assert_eq!(lines[1]["display"], "    [x] Child");
1363        assert_eq!(lines[0]["files"], json!(["Cargo.toml"]));
1364        assert_eq!(lines[0]["outcome"], "Ready");
1365        assert_eq!(lines[0]["verify"], json!(["cargo check"]));
1366    }
1367
1368    #[test]
1369    fn split_task_description_metadata_strips_files_and_verify_suffix() {
1370        let (clean, files, verify) =
1371            split_task_description_metadata("Emit summary -> files: [src/a.rs, src/b.rs] -> verify: [cargo check]");
1372        assert_eq!(clean, "Emit summary");
1373        assert_eq!(files, vec!["src/a.rs".to_string(), "src/b.rs".to_string()]);
1374        assert_eq!(verify, vec!["cargo check".to_string()]);
1375    }
1376
1377    #[test]
1378    fn split_task_description_metadata_keeps_inline_code_arrows_intact() {
1379        let (clean, files, verify) =
1380            split_task_description_metadata("Use `a -> files: b` in code -> files: [src/a.rs]");
1381        assert_eq!(clean, "Use `a -> files: b` in code");
1382        assert_eq!(files, vec!["src/a.rs".to_string()]);
1383        assert!(verify.is_empty());
1384    }
1385
1386    #[test]
1387    fn split_task_description_metadata_without_markers_returns_trimmed_description() {
1388        let (clean, files, verify) = split_task_description_metadata("  Just an action  ");
1389        assert_eq!(clean, "Just an action");
1390        assert!(files.is_empty());
1391        assert!(verify.is_empty());
1392    }
1393
1394    #[test]
1395    fn split_task_description_metadata_preserves_quoted_commas_in_files_and_verify() {
1396        let (clean, files, verify) = split_task_description_metadata(
1397            "Inspect range -> files: ['src/a.rs, b.rs', src/c.rs] -> verify: [sed -n '/^## A/,/^## B/p']",
1398        );
1399        assert_eq!(clean, "Inspect range");
1400        assert_eq!(files, vec!["'src/a.rs, b.rs'".to_string(), "src/c.rs".to_string()]);
1401        assert_eq!(verify, vec!["sed -n '/^## A/,/^## B/p'".to_string()]);
1402    }
1403
1404    #[test]
1405    fn compact_task_tree_view_from_items_strips_inline_metadata_into_fields() {
1406        let items = vec![json!({
1407            "index_path": "1",
1408            "description": "Update parser -> files: [src/a.rs] -> verify: [cargo check]",
1409            "status": "pending",
1410        })];
1411        let rows = compact_task_tree_view_from_items(&items);
1412        assert_eq!(rows.len(), 1);
1413        assert_eq!(rows[0]["display"], "  └ □ Update parser");
1414        assert_eq!(rows[0]["text"], "Update parser");
1415        assert_eq!(rows[0]["files"], json!(["src/a.rs"]));
1416        assert_eq!(rows[0]["verify"], json!(["cargo check"]));
1417    }
1418
1419    #[test]
1420    fn short_task_description_keeps_leading_clause_only() {
1421        assert_eq!(
1422            short_task_description(
1423                "Add vtcode exec resume to the Commands section – document the cross-turn contract, sourced from ExecSubcommand::Resume"
1424            ),
1425            "Add vtcode exec resume to the Commands section"
1426        );
1427        assert_eq!(
1428            short_task_description("Update the Everyday recipes block — add a headless example"),
1429            "Update the Everyday recipes block"
1430        );
1431        assert_eq!(
1432            short_task_description("Emit summary -> files: [src/a.rs] -> verify: [cargo check]"),
1433            "Emit summary"
1434        );
1435        assert_eq!(short_task_description("Verify with cargo check"), "Verify with cargo check");
1436        assert_eq!(short_task_description(""), "");
1437    }
1438
1439    #[test]
1440    fn compact_task_tree_view_from_items_shortens_detail_tail() {
1441        let items = vec![json!({
1442            "index_path": "1",
1443            "description": "Add vtcode exec resume to the Commands section – document the cross-turn contract in the command table",
1444            "status": "pending",
1445        })];
1446        let rows = compact_task_tree_view_from_items(&items);
1447        assert_eq!(rows.len(), 1);
1448        assert_eq!(rows[0]["display"], "  └ □ Add vtcode exec resume to the Commands section");
1449        assert_eq!(rows[0]["text"], "Add vtcode exec resume to the Commands section");
1450    }
1451
1452    #[test]
1453    fn shared_schema_helpers_stay_actionable_and_drift_free() {
1454        assert_eq!(TASK_STATUS_VALUES, ["pending", "in_progress", "completed", "blocked"]);
1455
1456        let status = task_status_schema();
1457        assert_eq!(status["type"], "string");
1458        assert_eq!(status["enum"], json!(TASK_STATUS_VALUES));
1459        assert!(status.get("description").is_none());
1460
1461        let with_desc = task_status_property_schema("New status.");
1462        assert_eq!(with_desc["description"], "New status.");
1463        assert_eq!(with_desc["enum"], json!(TASK_STATUS_VALUES));
1464
1465        // Asymmetric: plain string item vs structured item with metadata.
1466        let items_schema = task_items_array_schema("Items desc.");
1467        let validator = jsonschema::validator_for(&items_schema).expect("items schema is valid");
1468        assert!(validator.validate(&json!(["plain step"])).is_ok());
1469        assert!(
1470            validator
1471                .validate(&json!([{
1472                    "description": "Structured step",
1473                    "status": "in_progress",
1474                    "files": ["src/a.rs"],
1475                    "outcome": "Done",
1476                    "verify": ["cargo check"],
1477                }]))
1478                .is_ok()
1479        );
1480        // Boundary: verify also accepts a bare string; missing description fails.
1481        assert!(validator.validate(&json!([{"status": "completed"}])).is_err());
1482        assert!(validator.validate(&json!([{"description": "Bad", "status": "done"}])).is_err());
1483
1484        assert_eq!(task_files_property_schema("F.")["description"], "F.");
1485        assert_eq!(task_verify_property_schema("V.")["description"], "V.");
1486    }
1487
1488    #[test]
1489    fn shared_status_values_match_runtime_parser() {
1490        use std::str::FromStr;
1491        for status in TASK_STATUS_VALUES {
1492            assert!(TaskTrackingStatus::from_str(status).is_ok(), "schema status {status:?} must parse");
1493        }
1494        assert!(TaskTrackingStatus::from_str("done").is_err());
1495    }
1496
1497    /// Drift guard: `TaskTrackingStatus` reaches the wire through three
1498    /// independent paths — the derived serde `snake_case` form, `as_str()`, and
1499    /// the hand-written `FromStr`. Nothing in the type system ties them
1500    /// together, so this locks the as_str <-> serde <-> FromStr triangle for
1501    /// every variant and pins the schema enum list to the same source. A
1502    /// one-sided edit to any path fails here instead of silently producing a
1503    /// value the runtime cannot parse back.
1504    #[test]
1505    fn task_status_as_str_serde_and_from_str_stay_in_lockstep() {
1506        use std::str::FromStr;
1507        let variants = [
1508            TaskTrackingStatus::Pending,
1509            TaskTrackingStatus::InProgress,
1510            TaskTrackingStatus::Completed,
1511            TaskTrackingStatus::Blocked,
1512        ];
1513        let strings: Vec<&str> = variants.iter().map(TaskTrackingStatus::as_str).collect();
1514        assert_eq!(strings, TASK_STATUS_VALUES);
1515
1516        for variant in variants {
1517            let expected = variant.as_str();
1518            assert_eq!(
1519                serde_json::to_value(variant).expect("serializes"),
1520                json!(expected),
1521                "serde form drifted for {variant:?}"
1522            );
1523            assert_eq!(
1524                TaskTrackingStatus::from_str(expected).expect("as_str output must parse back"),
1525                variant,
1526                "FromStr drift for {variant:?}"
1527            );
1528        }
1529    }
1530
1531    /// Cross-crate drift guard. `vtcode-commons::ui_protocol::TaskItemStatus`
1532    /// (the TUI-facing row status) is a distinct type from
1533    /// `TaskTrackingStatus` but must carry the *same* canonical strings — its
1534    /// doc comment promises they match, and the TUI parses runtime strings
1535    /// through it (`raw.parse::<TaskItemStatus>()`). The type system does not
1536    /// connect the two enums, so pin them token-for-token here.
1537    #[test]
1538    fn task_item_status_matches_tracking_status_strings() {
1539        use std::str::FromStr;
1540        use vtcode_commons::ui_protocol::TaskItemStatus;
1541
1542        for variant in [
1543            TaskTrackingStatus::Pending,
1544            TaskTrackingStatus::InProgress,
1545            TaskTrackingStatus::Completed,
1546            TaskTrackingStatus::Blocked,
1547        ] {
1548            let canonical = variant.as_str();
1549            let display = TaskItemStatus::from_str(canonical)
1550                .unwrap_or_else(|_| panic!("TaskItemStatus must parse runtime status {canonical:?}"));
1551            assert_eq!(display.as_str(), canonical, "TaskItemStatus/TaskTrackingStatus string drift for {variant:?}");
1552        }
1553    }
1554}