Skip to main content

blyte_cli/
plan_cmd.rs

1use std::collections::HashSet;
2use std::path::{Path, PathBuf};
3use std::process::Command;
4
5#[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize)]
6pub struct TaskStatus {
7    pub id: String,
8    pub heading: String, // PlanTask.heading
9    pub deps: Vec<String>,
10    pub state: String, // "merged" | "review" | "running" | "dead" | "ready" | "waiting"
11    pub run: Option<String>, // the run id it was matched to
12    pub outcome: Option<String>, // the summary's outcome, when there is one
13    pub verdict: Option<String>,
14    pub waiting_on: Vec<String>, // deps not merged, only for "waiting"
15    pub command: Option<String>, // only for "ready"
16    pub problem: Option<String>, // only when the plan-task text does not resolve
17}
18
19fn is_pid_alive(pid: libc::pid_t) -> bool {
20    if pid <= 0 {
21        return false;
22    }
23    let ret = unsafe { libc::kill(pid, 0) };
24    if ret == 0 {
25        true
26    } else {
27        std::io::Error::last_os_error().raw_os_error() == Some(libc::EPERM)
28    }
29}
30
31pub fn plan_task_text(id: &str, heading: &str) -> String {
32    let prefix = format!("Task {id}");
33    if heading.starts_with(&prefix) {
34        let rest = &heading[prefix.len()..];
35        if rest.is_empty() || rest.starts_with(':') || rest.starts_with(' ') {
36            return prefix;
37        }
38    }
39    heading.to_string()
40}
41
42fn normalize_components(p: &Path) -> PathBuf {
43    use std::path::Component;
44    let mut out = PathBuf::new();
45    for c in p.components() {
46        if c != Component::CurDir {
47            out.push(c);
48        }
49    }
50    out
51}
52
53fn paths_match(root: &Path, start_plan: &str, plan_rel: &str) -> bool {
54    let p1 = root.join(start_plan);
55    let p2 = root.join(plan_rel);
56    match (p1.canonicalize(), p2.canonicalize()) {
57        (Ok(c1), Ok(c2)) => c1 == c2,
58        _ => normalize_components(&p1) == normalize_components(&p2),
59    }
60}
61
62#[derive(Debug, Clone)]
63struct StartRecord {
64    run_id: String,
65    started_at: u64,
66    plan: Option<String>,
67    plan_task: Option<String>,
68    pid: Option<libc::pid_t>,
69}
70
71fn read_start_files(root: &Path) -> Vec<StartRecord> {
72    let wt_dir = root.join(".wt");
73    let entries = match std::fs::read_dir(&wt_dir) {
74        Ok(e) => e,
75        Err(_) => return Vec::new(),
76    };
77    let mut records = Vec::new();
78    for entry in entries.flatten() {
79        let name = entry.file_name();
80        let name_str = name.to_string_lossy();
81        if let Some(run_id) = name_str.strip_suffix(".start.json") {
82            let path = entry.path();
83            let content = match std::fs::read_to_string(&path) {
84                Ok(c) => c,
85                Err(_) => continue,
86            };
87            let val: serde_json::Value = match serde_json::from_str(&content) {
88                Ok(v) => v,
89                Err(_) => continue,
90            };
91            let started_at = val
92                .get("started_at")
93                .and_then(|v| {
94                    v.as_u64()
95                        .or_else(|| v.as_str().and_then(|s| s.parse::<u64>().ok()))
96                })
97                .unwrap_or(0);
98            let plan = val.get("plan").and_then(|v| v.as_str()).map(String::from);
99            let plan_task = val
100                .get("plan_task")
101                .and_then(|v| v.as_str())
102                .map(String::from);
103            let pid = val
104                .get("pid")
105                .and_then(|v| v.as_i64())
106                .map(|p| p as libc::pid_t);
107            records.push(StartRecord {
108                run_id: run_id.to_string(),
109                started_at,
110                plan,
111                plan_task,
112                pid,
113            });
114        }
115    }
116    records
117}
118
119fn check_is_ancestor(root: &Path, run_id: &str) -> bool {
120    Command::new("git")
121        .args([
122            "merge-base",
123            "--is-ancestor",
124            &format!("wip/{run_id}"),
125            "HEAD",
126        ])
127        .current_dir(root)
128        .output()
129        .map(|o| o.status.success())
130        .unwrap_or(false)
131}
132
133fn check_branch_exists(root: &Path, run_id: &str) -> bool {
134    Command::new("git")
135        .args(["rev-parse", "--verify", &format!("refs/heads/wip/{run_id}")])
136        .current_dir(root)
137        .output()
138        .map(|o| o.status.success())
139        .unwrap_or(false)
140}
141
142fn read_verdict(root: &Path, run_id: &str) -> Option<String> {
143    let verdict_file = root.join(".wt").join(format!("{run_id}.verdict.json"));
144    std::fs::read_to_string(&verdict_file)
145        .ok()
146        .and_then(|s| serde_json::from_str::<serde_json::Value>(&s).ok())
147        .and_then(|v| v.get("verdict").and_then(|x| x.as_str()).map(String::from))
148}
149
150fn read_summary(root: &Path, run_id: &str) -> Option<(Option<String>, bool)> {
151    let summary_file = root.join(".wt").join(format!("{run_id}.json"));
152    std::fs::read_to_string(&summary_file)
153        .ok()
154        .and_then(|s| serde_json::from_str::<serde_json::Value>(&s).ok())
155        .map(|v| {
156            let outcome = v.get("outcome").and_then(|x| x.as_str()).map(String::from);
157            let has_commits = v
158                .get("commits")
159                .and_then(|x| x.as_array())
160                .is_some_and(|a| !a.is_empty());
161            (outcome, has_commits)
162        })
163}
164
165struct TaskIntermediate {
166    task: crate::plans::PlanTask,
167    plan_task_t: String,
168    problem: Option<String>,
169    state: Option<String>,
170    run: Option<String>,
171    outcome: Option<String>,
172    verdict: Option<String>,
173}
174
175/// `root` is the main checkout (holds `.wt/`), `plan_rel` the plan path relative to it, as dispatch takes it.
176pub fn statuses(root: &Path, plan_rel: &str, text: &str) -> Vec<TaskStatus> {
177    let doc = crate::plans::parse_plan(text);
178    let start_files = read_start_files(root);
179
180    let all_task_ids: Vec<String> = doc.tasks.iter().map(|t| t.id.clone()).collect();
181    let mut intermediates = Vec::new();
182
183    for task in doc.tasks {
184        let t = plan_task_text(&task.id, &task.heading);
185        let problem = if crate::plan_section::extract(text, &t).is_none() {
186            Some(
187                crate::plan_section::explain_missing(text, &t)
188                    .unwrap_or_else(|| "heading not found".to_string()),
189            )
190        } else {
191            None
192        };
193
194        let task_id_label = format!("Task {}", task.id);
195        let mut matching: Vec<&StartRecord> = start_files
196            .iter()
197            .filter(|s| {
198                let Some(ref sp) = s.plan else {
199                    return false;
200                };
201                if !paths_match(root, sp, plan_rel) {
202                    return false;
203                }
204                let Some(ref spt) = s.plan_task else {
205                    return false;
206                };
207                spt == &t || spt == &task_id_label || spt == &task.heading
208            })
209            .collect();
210        matching.sort_by_key(|r| r.started_at);
211        let matched_run = matching.last().copied();
212
213        let mut state = None;
214        let mut run_out = None;
215        let mut outcome_out = None;
216        let mut verdict_out = None;
217
218        if let Some(run) = matched_run {
219            let is_ancestor = check_is_ancestor(root, &run.run_id);
220            let branch_exists = check_branch_exists(root, &run.run_id);
221            let verdict_opt = read_verdict(root, &run.run_id);
222            let summary = read_summary(root, &run.run_id);
223            let has_commits = summary.as_ref().is_some_and(|(_, c)| *c);
224            let is_merged = (has_commits && is_ancestor)
225                || (!branch_exists && matches!(verdict_opt.as_deref(), Some("accepted" | "fixed")));
226
227            if summary.is_none() && run.pid.map(is_pid_alive).unwrap_or(false) {
228                // Rule 1: running
229                state = Some("running".to_string());
230                run_out = Some(run.run_id.clone());
231                verdict_out = verdict_opt;
232            } else if is_merged {
233                // Rule 2: merged
234                state = Some("merged".to_string());
235                run_out = Some(run.run_id.clone());
236                outcome_out = summary.and_then(|(o, _)| o);
237                verdict_out = verdict_opt;
238            } else if verdict_opt.as_deref() == Some("redone") {
239                // Rule 3: A run with verdict redone is not review: treat the task as if no run matched (go on to rule 5).
240                // Leave state as None, run_out as None
241            } else if let Some((outcome, _)) = summary {
242                // Rule 3: review
243                state = Some("review".to_string());
244                run_out = Some(run.run_id.clone());
245                outcome_out = outcome;
246                verdict_out = verdict_opt;
247            } else {
248                // Rule 4: dead
249                state = Some("dead".to_string());
250                run_out = Some(run.run_id.clone());
251                verdict_out = verdict_opt;
252            }
253        }
254
255        intermediates.push(TaskIntermediate {
256            task,
257            plan_task_t: t,
258            problem,
259            state,
260            run: run_out,
261            outcome: outcome_out,
262            verdict: verdict_out,
263        });
264    }
265
266    let merged_task_ids: HashSet<String> = intermediates
267        .iter()
268        .filter(|item| item.state.as_deref() == Some("merged"))
269        .map(|item| item.task.id.clone())
270        .collect();
271
272    intermediates
273        .into_iter()
274        .map(|item| {
275            let (state, waiting_on, command) = if let Some(st) = item.state {
276                (st, Vec::new(), None)
277            } else {
278                // Rule 5: ready when every dep is merged (deps that are not tasks in this plan count as merged),
279                // else waiting with waiting_on = the deps not merged, in plan order.
280                let waiting_on: Vec<String> =
281                    doc_task_order(&all_task_ids, &item.task.deps, &merged_task_ids);
282                if waiting_on.is_empty() {
283                    let cmd = if item.problem.is_none() {
284                        Some(format!(
285                            "blyte dispatch {} --plan {} --plan-task \"{}\"",
286                            item.task.id, plan_rel, item.plan_task_t
287                        ))
288                    } else {
289                        None
290                    };
291                    ("ready".to_string(), Vec::new(), cmd)
292                } else {
293                    ("waiting".to_string(), waiting_on, None)
294                }
295            };
296
297            TaskStatus {
298                id: item.task.id,
299                heading: item.task.heading,
300                deps: item.task.deps,
301                state,
302                run: item.run,
303                outcome: item.outcome,
304                verdict: item.verdict,
305                waiting_on,
306                command,
307                problem: item.problem,
308            }
309        })
310        .collect()
311}
312
313fn doc_task_order(
314    all_task_ids: &[String],
315    deps: &[String],
316    merged_task_ids: &HashSet<String>,
317) -> Vec<String> {
318    all_task_ids
319        .iter()
320        .filter(|id| deps.contains(id) && !merged_task_ids.contains(*id))
321        .cloned()
322        .collect()
323}
324
325pub fn render(plan_rel: &str, rows: &[TaskStatus]) -> String {
326    let mut counts = Vec::new();
327    let n_merged = rows.iter().filter(|r| r.state == "merged").count();
328    if n_merged > 0 {
329        counts.push(format!("{n_merged} merged"));
330    }
331    let n_review = rows.iter().filter(|r| r.state == "review").count();
332    if n_review > 0 {
333        counts.push(format!("{n_review} review"));
334    }
335    let n_running = rows.iter().filter(|r| r.state == "running").count();
336    if n_running > 0 {
337        counts.push(format!("{n_running} running"));
338    }
339    let n_dead = rows.iter().filter(|r| r.state == "dead").count();
340    if n_dead > 0 {
341        counts.push(format!("{n_dead} dead"));
342    }
343    let n_ready = rows.iter().filter(|r| r.state == "ready").count();
344    if n_ready > 0 {
345        counts.push(format!("{n_ready} ready"));
346    }
347    let n_waiting = rows.iter().filter(|r| r.state == "waiting").count();
348    if n_waiting > 0 {
349        counts.push(format!("{n_waiting} waiting"));
350    }
351
352    let first_line = if counts.is_empty() {
353        format!("{plan_rel}: {} tasks", rows.len())
354    } else {
355        format!("{plan_rel}: {} tasks ({})", rows.len(), counts.join(", "))
356    };
357
358    let max_id_len = rows.iter().map(|r| r.id.len()).max().unwrap_or(0);
359
360    let mut lines = Vec::with_capacity(rows.len() + 1);
361    lines.push(first_line);
362
363    for r in rows {
364        let detail = match r.state.as_str() {
365            "merged" => {
366                if let Some(ref problem) = r.problem {
367                    format!("PROBLEM: {problem}")
368                } else {
369                    r.heading.clone()
370                }
371            }
372            "waiting" => {
373                if let Some(ref problem) = r.problem {
374                    format!("PROBLEM: {problem}")
375                } else if r.waiting_on.is_empty() {
376                    r.heading.clone()
377                } else {
378                    format!("{}  (waiting on {})", r.heading, r.waiting_on.join(", "))
379                }
380            }
381            "review" => {
382                if let Some(ref problem) = r.problem {
383                    format!("PROBLEM: {problem}")
384                } else {
385                    let outcome = r.outcome.as_deref().unwrap_or("unknown");
386                    let run = r.run.as_deref().unwrap_or("");
387                    format!("{outcome}, run {run}: blyte review {run}")
388                }
389            }
390            "running" | "dead" => {
391                if let Some(ref problem) = r.problem {
392                    format!("PROBLEM: {problem}")
393                } else {
394                    let run = r.run.as_deref().unwrap_or("");
395                    format!("run {run}: blyte status {run}")
396                }
397            }
398            "ready" => {
399                if let Some(ref problem) = r.problem {
400                    format!("PROBLEM: {problem}")
401                } else {
402                    r.command.clone().unwrap_or_default()
403                }
404            }
405            _ => {
406                if let Some(ref problem) = r.problem {
407                    format!("PROBLEM: {problem}")
408                } else {
409                    r.heading.clone()
410                }
411            }
412        };
413
414        lines.push(format!("{:<max_id_len$}  {:<7}  {detail}", r.id, r.state));
415    }
416
417    lines.join("\n")
418}
419
420fn compute_plan_rel(root: &Path, plan: &Path, full_plan_path: &Path) -> String {
421    let canon_root = root.canonicalize().unwrap_or_else(|_| root.to_path_buf());
422    let canon_plan = full_plan_path
423        .canonicalize()
424        .unwrap_or_else(|_| full_plan_path.to_path_buf());
425    if let Ok(rel) = canon_plan.strip_prefix(&canon_root) {
426        return rel.to_string_lossy().to_string();
427    }
428    if let Ok(rel) = full_plan_path.strip_prefix(root) {
429        return rel.to_string_lossy().to_string();
430    }
431    plan.to_string_lossy().to_string()
432}
433
434pub fn run(plan: &Path, json: bool) -> i32 {
435    let current_dir = std::env::current_dir().unwrap_or_else(|_| PathBuf::from("."));
436
437    let root = match crate::clean::find_repo_root() {
438        Ok(r) => r,
439        Err(e) => {
440            eprintln!("error: {e}");
441            return 2;
442        }
443    };
444
445    let full_plan_path = if plan.is_absolute() {
446        plan.to_path_buf()
447    } else {
448        current_dir.join(plan)
449    };
450
451    let text = match std::fs::read_to_string(&full_plan_path) {
452        Ok(t) => t,
453        Err(e) => {
454            eprintln!("error: cannot read plan file '{}': {e}", plan.display());
455            return 2;
456        }
457    };
458
459    let doc = crate::plans::parse_plan(&text);
460    if doc.tasks.is_empty() {
461        eprintln!("error: plan has no ### Task sections");
462        return 2;
463    }
464
465    let plan_rel = compute_plan_rel(&root, plan, &full_plan_path);
466    let rows = statuses(&root, &plan_rel, &text);
467
468    if json {
469        let json_str = serde_json::to_string_pretty(&rows).unwrap_or_default();
470        println!("{json_str}");
471    } else {
472        let rendered = render(&plan_rel, &rows);
473        println!("{rendered}");
474    }
475
476    0
477}
478
479#[cfg(test)]
480mod tests {
481    use super::*;
482    use std::fs;
483    use tempfile::TempDir;
484
485    fn git(dir: &Path, args: &[&str]) {
486        let ok = Command::new("git")
487            .args(["-c", "user.name=t", "-c", "user.email=t@t"])
488            .args(args)
489            .current_dir(dir)
490            .status()
491            .unwrap()
492            .success();
493        assert!(ok, "git {args:?}");
494    }
495
496    fn setup_test_repo() -> TempDir {
497        let dir = tempfile::tempdir().unwrap();
498        let root = dir.path();
499        git(root, &["init", "-q", "-b", "main"]);
500        fs::write(root.join("f.txt"), "hello\n").unwrap();
501        git(root, &["add", "."]);
502        git(root, &["commit", "-qm", "initial", "--no-gpg-sign"]);
503        fs::create_dir_all(root.join(".wt")).unwrap();
504        dir
505    }
506
507    fn write_start_json(
508        root: &Path,
509        run_id: &str,
510        plan: &str,
511        plan_task: &str,
512        pid: u32,
513        started_at: u64,
514    ) {
515        let json = serde_json::json!({
516            "id": run_id,
517            "plan": plan,
518            "plan_task": plan_task,
519            "pid": pid,
520            "started_at": started_at,
521        });
522        fs::write(
523            root.join(".wt").join(format!("{run_id}.start.json")),
524            serde_json::to_string_pretty(&json).unwrap(),
525        )
526        .unwrap();
527    }
528
529    fn write_summary_json(root: &Path, run_id: &str, outcome: &str) {
530        let json = serde_json::json!({
531            "id": run_id,
532            "outcome": outcome,
533        });
534        fs::write(
535            root.join(".wt").join(format!("{run_id}.json")),
536            serde_json::to_string_pretty(&json).unwrap(),
537        )
538        .unwrap();
539    }
540
541    fn write_verdict_json(root: &Path, run_id: &str, verdict: &str) {
542        let json = serde_json::json!({
543            "verdict": verdict,
544        });
545        fs::write(
546            root.join(".wt").join(format!("{run_id}.verdict.json")),
547            serde_json::to_string_pretty(&json).unwrap(),
548        )
549        .unwrap();
550    }
551
552    const TWO_TASK_PLAN: &str = r#"# Sample Plan
553
554### Task A: one
555
556Depends on: none
557
558Do task A.
559
560### Task B: two
561
562**Depends on:** A
563
564Do task B.
565"#;
566
567    // Test 1: A plan with ### Task A: one (Depends on: none) and ### Task B: two (**Depends on:** A), no runs:
568    // A is ready with command blyte dispatch A --plan docs/p.md --plan-task "Task A"; B is waiting,
569    // waiting_on == ["A"], no command.
570    #[test]
571    fn test_1_plan_dependencies_no_runs() {
572        let repo = setup_test_repo();
573        let rows = statuses(repo.path(), "docs/p.md", TWO_TASK_PLAN);
574
575        assert_eq!(rows.len(), 2);
576        let a = &rows[0];
577        assert_eq!(a.id, "A");
578        assert_eq!(a.state, "ready");
579        assert_eq!(
580            a.command.as_deref(),
581            Some("blyte dispatch A --plan docs/p.md --plan-task \"Task A\"")
582        );
583        assert!(a.waiting_on.is_empty());
584
585        let b = &rows[1];
586        assert_eq!(b.id, "B");
587        assert_eq!(b.state, "waiting");
588        assert_eq!(b.waiting_on, vec!["A"]);
589        assert!(b.command.is_none());
590    }
591
592    // Test 2: A start file for A (plan docs/p.md, plan_task Task A, pid of the test process) and no summary:
593    // A is running, run A.
594    #[test]
595    fn test_2_start_file_alive_pid_running() {
596        let repo = setup_test_repo();
597        let pid = std::process::id();
598        write_start_json(repo.path(), "A", "docs/p.md", "Task A", pid, 100);
599
600        let rows = statuses(repo.path(), "docs/p.md", TWO_TASK_PLAN);
601        assert_eq!(rows[0].id, "A");
602        assert_eq!(rows[0].state, "running");
603        assert_eq!(rows[0].run.as_deref(), Some("A"));
604    }
605
606    // Test 3: Same with pid 999999 (not alive): dead.
607    #[test]
608    fn test_3_start_file_dead_pid() {
609        let repo = setup_test_repo();
610        write_start_json(repo.path(), "A", "docs/p.md", "Task A", 999999, 100);
611
612        let rows = statuses(repo.path(), "docs/p.md", TWO_TASK_PLAN);
613        assert_eq!(rows[0].id, "A");
614        assert_eq!(rows[0].state, "dead");
615        assert_eq!(rows[0].run.as_deref(), Some("A"));
616    }
617
618    // Test 4: A start file plus .wt/A.json with "outcome":"verified": review, outcome verified.
619    #[test]
620    fn test_4_start_and_summary_review() {
621        let repo = setup_test_repo();
622        write_start_json(repo.path(), "A", "docs/p.md", "Task A", 999999, 100);
623        write_summary_json(repo.path(), "A", "verified");
624
625        let rows = statuses(repo.path(), "docs/p.md", TWO_TASK_PLAN);
626        assert_eq!(rows[0].id, "A");
627        assert_eq!(rows[0].state, "review");
628        assert_eq!(rows[0].run.as_deref(), Some("A"));
629        assert_eq!(rows[0].outcome.as_deref(), Some("verified"));
630    }
631
632    // Test 5: A run whose branch wip/A1 is an ancestor of HEAD (create the branch at HEAD), run id A1 different
633    // from the task id, plan_task Task A: A is merged with run A1, and B is ready.
634    #[test]
635    fn test_5_branch_merged_makes_dependent_ready() {
636        let repo = setup_test_repo();
637        git(repo.path(), &["branch", "wip/A1"]);
638        write_start_json(repo.path(), "A1", "docs/p.md", "Task A", 999999, 100);
639        fs::write(
640            repo.path().join(".wt/A1.json"),
641            r#"{"id":"A1","outcome":"verified","commits":[{"sha":"abc","subject":"work"}]}"#,
642        )
643        .unwrap();
644
645        let rows = statuses(repo.path(), "docs/p.md", TWO_TASK_PLAN);
646        assert_eq!(rows[0].id, "A");
647        assert_eq!(rows[0].state, "merged");
648        assert_eq!(rows[0].run.as_deref(), Some("A1"));
649
650        assert_eq!(rows[1].id, "B");
651        assert_eq!(rows[1].state, "ready");
652        assert_eq!(
653            rows[1].command.as_deref(),
654            Some("blyte dispatch B --plan docs/p.md --plan-task \"Task B\"")
655        );
656    }
657
658    // Test 6: No branch, verdict accepted: merged. Verdict redone with a summary: A is ready again.
659    #[test]
660    fn test_6_verdict_accepted_then_redone() {
661        let repo = setup_test_repo();
662        write_start_json(repo.path(), "A", "docs/p.md", "Task A", 999999, 100);
663        write_verdict_json(repo.path(), "A", "accepted");
664
665        let rows = statuses(repo.path(), "docs/p.md", TWO_TASK_PLAN);
666        assert_eq!(rows[0].id, "A");
667        assert_eq!(rows[0].state, "merged");
668
669        // Now change verdict to redone and add a summary: A is ready again.
670        write_summary_json(repo.path(), "A", "gate_failed");
671        write_verdict_json(repo.path(), "A", "redone");
672
673        let rows2 = statuses(repo.path(), "docs/p.md", TWO_TASK_PLAN);
674        assert_eq!(rows2[0].id, "A");
675        assert_eq!(rows2[0].state, "ready");
676        assert_eq!(
677            rows2[0].command.as_deref(),
678            Some("blyte dispatch A --plan docs/p.md --plan-task \"Task A\"")
679        );
680    }
681
682    // Test 7: A start file for the same task in a different plan file: ignored (A stays ready).
683    #[test]
684    fn test_7_different_plan_file_ignored() {
685        let repo = setup_test_repo();
686        write_start_json(
687            repo.path(),
688            "A",
689            "docs/other.md",
690            "Task A",
691            std::process::id(),
692            100,
693        );
694
695        let rows = statuses(repo.path(), "docs/p.md", TWO_TASK_PLAN);
696        assert_eq!(rows[0].id, "A");
697        assert_eq!(rows[0].state, "ready");
698    }
699
700    // Test 8: Two matching start files: the later started_at wins.
701    #[test]
702    fn test_8_later_started_at_wins() {
703        let repo = setup_test_repo();
704        let pid = std::process::id();
705        // A1 has earlier started_at and is dead
706        write_start_json(repo.path(), "A1", "docs/p.md", "Task A", 999999, 100);
707        // A2 has later started_at and is alive
708        write_start_json(repo.path(), "A2", "docs/p.md", "Task A", pid, 200);
709
710        let rows = statuses(repo.path(), "docs/p.md", TWO_TASK_PLAN);
711        assert_eq!(rows[0].id, "A");
712        assert_eq!(rows[0].state, "running");
713        assert_eq!(rows[0].run.as_deref(), Some("A2"));
714    }
715
716    // Test 9: A heading ### Setup step that parse_plan returns as a task (check what parse_plan does with it;
717    // if it does not, use a heading shape it does return that does not start with Task <ID>): the command
718    // uses the whole heading as --plan-task.
719    #[test]
720    fn test_9_heading_shape_without_task_id_prefix() {
721        // parse_plan requires 'Task ' prefix and ':'.
722        // For '### Task 1: setup step', first_word is '1', which is digits, so id becomes 'T1'.
723        // Heading is 'Task 1: setup step', which does not start with 'Task T1'.
724        // Therefore plan_task_text returns the full heading: "Task 1: setup step".
725        let plan = r#"# Plan
726
727### Task 1: setup step
728
729Do setup.
730"#;
731        let repo = setup_test_repo();
732        let rows = statuses(repo.path(), "docs/p.md", plan);
733        assert_eq!(rows.len(), 1);
734        assert_eq!(rows[0].id, "T1");
735        assert_eq!(rows[0].state, "ready");
736        assert_eq!(
737            rows[0].command.as_deref(),
738            Some("blyte dispatch T1 --plan docs/p.md --plan-task \"Task 1: setup step\"")
739        );
740    }
741
742    // Test 10: problem set when extract fails: build a TaskStatus path where the plan-task text does not
743    // resolve (for example a task heading inside an unclosed fence that parse_plan still lists, or test the
744    // helper that picks the plan-task text plus extract directly) and check command is None and problem is Some.
745    #[test]
746    fn test_10_problem_set_when_extract_fails() {
747        // In markdown, `~~~` is a code fence for plan_section::extract, but parse_plan only treats ```` ``` ```` as fences.
748        // Therefore parse_plan parses the task, but extract fails to find it.
749        let plan = "~~~\n### Task A: fenced\n~~~\n";
750        let repo = setup_test_repo();
751        let rows = statuses(repo.path(), "docs/p.md", plan);
752        assert_eq!(rows.len(), 1);
753        assert_eq!(rows[0].id, "A");
754        assert!(rows[0].command.is_none());
755        assert!(rows[0].problem.is_some());
756    }
757
758    // Test 11: render on test 1's rows: the first line is docs/p.md: 2 tasks (1 ready, 1 waiting) and B's line
759    // ends with (waiting on A).
760    #[test]
761    fn test_11_render_output() {
762        let repo = setup_test_repo();
763        let rows = statuses(repo.path(), "docs/p.md", TWO_TASK_PLAN);
764        let rendered = render("docs/p.md", &rows);
765        let lines: Vec<&str> = rendered.lines().collect();
766
767        assert_eq!(lines[0], "docs/p.md: 2 tasks (1 ready, 1 waiting)");
768        assert!(lines[2].ends_with("(waiting on A)"));
769    }
770
771    // Test 12: run with a missing file returns 2.
772    #[test]
773    fn test_12_run_missing_file_returns_2() {
774        let repo = setup_test_repo();
775        let missing = repo.path().join("does_not_exist.md");
776        let code = run(&missing, false);
777        assert_eq!(code, 2);
778    }
779}