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 out = Command::new("git")
438        .args(["rev-parse", "--show-toplevel"])
439        .current_dir(&current_dir)
440        .output();
441    let Ok(out) = out else {
442        eprintln!("error: git not found");
443        return 2;
444    };
445    if !out.status.success() {
446        eprintln!("error: not in a git repository");
447        return 2;
448    }
449
450    let toplevel = PathBuf::from(String::from_utf8_lossy(&out.stdout).trim());
451    let root = crate::config::main_checkout(&current_dir).unwrap_or(toplevel);
452
453    let full_plan_path = if plan.is_absolute() {
454        plan.to_path_buf()
455    } else {
456        current_dir.join(plan)
457    };
458
459    let text = match std::fs::read_to_string(&full_plan_path) {
460        Ok(t) => t,
461        Err(e) => {
462            eprintln!("error: cannot read plan file '{}': {e}", plan.display());
463            return 2;
464        }
465    };
466
467    let doc = crate::plans::parse_plan(&text);
468    if doc.tasks.is_empty() {
469        eprintln!("error: plan has no ### Task sections");
470        return 2;
471    }
472
473    let plan_rel = compute_plan_rel(&root, plan, &full_plan_path);
474    let rows = statuses(&root, &plan_rel, &text);
475
476    if json {
477        let json_str = serde_json::to_string_pretty(&rows).unwrap_or_default();
478        println!("{json_str}");
479    } else {
480        let rendered = render(&plan_rel, &rows);
481        println!("{rendered}");
482    }
483
484    0
485}
486
487#[cfg(test)]
488mod tests {
489    use super::*;
490    use std::fs;
491    use tempfile::TempDir;
492
493    fn git(dir: &Path, args: &[&str]) {
494        let ok = Command::new("git")
495            .args(["-c", "user.name=t", "-c", "user.email=t@t"])
496            .args(args)
497            .current_dir(dir)
498            .status()
499            .unwrap()
500            .success();
501        assert!(ok, "git {args:?}");
502    }
503
504    fn setup_test_repo() -> TempDir {
505        let dir = tempfile::tempdir().unwrap();
506        let root = dir.path();
507        git(root, &["init", "-q", "-b", "main"]);
508        fs::write(root.join("f.txt"), "hello\n").unwrap();
509        git(root, &["add", "."]);
510        git(root, &["commit", "-qm", "initial", "--no-gpg-sign"]);
511        fs::create_dir_all(root.join(".wt")).unwrap();
512        dir
513    }
514
515    fn write_start_json(
516        root: &Path,
517        run_id: &str,
518        plan: &str,
519        plan_task: &str,
520        pid: u32,
521        started_at: u64,
522    ) {
523        let json = serde_json::json!({
524            "id": run_id,
525            "plan": plan,
526            "plan_task": plan_task,
527            "pid": pid,
528            "started_at": started_at,
529        });
530        fs::write(
531            root.join(".wt").join(format!("{run_id}.start.json")),
532            serde_json::to_string_pretty(&json).unwrap(),
533        )
534        .unwrap();
535    }
536
537    fn write_summary_json(root: &Path, run_id: &str, outcome: &str) {
538        let json = serde_json::json!({
539            "id": run_id,
540            "outcome": outcome,
541        });
542        fs::write(
543            root.join(".wt").join(format!("{run_id}.json")),
544            serde_json::to_string_pretty(&json).unwrap(),
545        )
546        .unwrap();
547    }
548
549    fn write_verdict_json(root: &Path, run_id: &str, verdict: &str) {
550        let json = serde_json::json!({
551            "verdict": verdict,
552        });
553        fs::write(
554            root.join(".wt").join(format!("{run_id}.verdict.json")),
555            serde_json::to_string_pretty(&json).unwrap(),
556        )
557        .unwrap();
558    }
559
560    const TWO_TASK_PLAN: &str = r#"# Sample Plan
561
562### Task A: one
563
564Depends on: none
565
566Do task A.
567
568### Task B: two
569
570**Depends on:** A
571
572Do task B.
573"#;
574
575    // Test 1: A plan with ### Task A: one (Depends on: none) and ### Task B: two (**Depends on:** A), no runs:
576    // A is ready with command blyte dispatch A --plan docs/p.md --plan-task "Task A"; B is waiting,
577    // waiting_on == ["A"], no command.
578    #[test]
579    fn test_1_plan_dependencies_no_runs() {
580        let repo = setup_test_repo();
581        let rows = statuses(repo.path(), "docs/p.md", TWO_TASK_PLAN);
582
583        assert_eq!(rows.len(), 2);
584        let a = &rows[0];
585        assert_eq!(a.id, "A");
586        assert_eq!(a.state, "ready");
587        assert_eq!(
588            a.command.as_deref(),
589            Some("blyte dispatch A --plan docs/p.md --plan-task \"Task A\"")
590        );
591        assert!(a.waiting_on.is_empty());
592
593        let b = &rows[1];
594        assert_eq!(b.id, "B");
595        assert_eq!(b.state, "waiting");
596        assert_eq!(b.waiting_on, vec!["A"]);
597        assert!(b.command.is_none());
598    }
599
600    // Test 2: A start file for A (plan docs/p.md, plan_task Task A, pid of the test process) and no summary:
601    // A is running, run A.
602    #[test]
603    fn test_2_start_file_alive_pid_running() {
604        let repo = setup_test_repo();
605        let pid = std::process::id();
606        write_start_json(repo.path(), "A", "docs/p.md", "Task A", pid, 100);
607
608        let rows = statuses(repo.path(), "docs/p.md", TWO_TASK_PLAN);
609        assert_eq!(rows[0].id, "A");
610        assert_eq!(rows[0].state, "running");
611        assert_eq!(rows[0].run.as_deref(), Some("A"));
612    }
613
614    // Test 3: Same with pid 999999 (not alive): dead.
615    #[test]
616    fn test_3_start_file_dead_pid() {
617        let repo = setup_test_repo();
618        write_start_json(repo.path(), "A", "docs/p.md", "Task A", 999999, 100);
619
620        let rows = statuses(repo.path(), "docs/p.md", TWO_TASK_PLAN);
621        assert_eq!(rows[0].id, "A");
622        assert_eq!(rows[0].state, "dead");
623        assert_eq!(rows[0].run.as_deref(), Some("A"));
624    }
625
626    // Test 4: A start file plus .wt/A.json with "outcome":"verified": review, outcome verified.
627    #[test]
628    fn test_4_start_and_summary_review() {
629        let repo = setup_test_repo();
630        write_start_json(repo.path(), "A", "docs/p.md", "Task A", 999999, 100);
631        write_summary_json(repo.path(), "A", "verified");
632
633        let rows = statuses(repo.path(), "docs/p.md", TWO_TASK_PLAN);
634        assert_eq!(rows[0].id, "A");
635        assert_eq!(rows[0].state, "review");
636        assert_eq!(rows[0].run.as_deref(), Some("A"));
637        assert_eq!(rows[0].outcome.as_deref(), Some("verified"));
638    }
639
640    // Test 5: A run whose branch wip/A1 is an ancestor of HEAD (create the branch at HEAD), run id A1 different
641    // from the task id, plan_task Task A: A is merged with run A1, and B is ready.
642    #[test]
643    fn test_5_branch_merged_makes_dependent_ready() {
644        let repo = setup_test_repo();
645        git(repo.path(), &["branch", "wip/A1"]);
646        write_start_json(repo.path(), "A1", "docs/p.md", "Task A", 999999, 100);
647        fs::write(
648            repo.path().join(".wt/A1.json"),
649            r#"{"id":"A1","outcome":"verified","commits":[{"sha":"abc","subject":"work"}]}"#,
650        )
651        .unwrap();
652
653        let rows = statuses(repo.path(), "docs/p.md", TWO_TASK_PLAN);
654        assert_eq!(rows[0].id, "A");
655        assert_eq!(rows[0].state, "merged");
656        assert_eq!(rows[0].run.as_deref(), Some("A1"));
657
658        assert_eq!(rows[1].id, "B");
659        assert_eq!(rows[1].state, "ready");
660        assert_eq!(
661            rows[1].command.as_deref(),
662            Some("blyte dispatch B --plan docs/p.md --plan-task \"Task B\"")
663        );
664    }
665
666    // Test 6: No branch, verdict accepted: merged. Verdict redone with a summary: A is ready again.
667    #[test]
668    fn test_6_verdict_accepted_then_redone() {
669        let repo = setup_test_repo();
670        write_start_json(repo.path(), "A", "docs/p.md", "Task A", 999999, 100);
671        write_verdict_json(repo.path(), "A", "accepted");
672
673        let rows = statuses(repo.path(), "docs/p.md", TWO_TASK_PLAN);
674        assert_eq!(rows[0].id, "A");
675        assert_eq!(rows[0].state, "merged");
676
677        // Now change verdict to redone and add a summary: A is ready again.
678        write_summary_json(repo.path(), "A", "gate_failed");
679        write_verdict_json(repo.path(), "A", "redone");
680
681        let rows2 = statuses(repo.path(), "docs/p.md", TWO_TASK_PLAN);
682        assert_eq!(rows2[0].id, "A");
683        assert_eq!(rows2[0].state, "ready");
684        assert_eq!(
685            rows2[0].command.as_deref(),
686            Some("blyte dispatch A --plan docs/p.md --plan-task \"Task A\"")
687        );
688    }
689
690    // Test 7: A start file for the same task in a different plan file: ignored (A stays ready).
691    #[test]
692    fn test_7_different_plan_file_ignored() {
693        let repo = setup_test_repo();
694        write_start_json(
695            repo.path(),
696            "A",
697            "docs/other.md",
698            "Task A",
699            std::process::id(),
700            100,
701        );
702
703        let rows = statuses(repo.path(), "docs/p.md", TWO_TASK_PLAN);
704        assert_eq!(rows[0].id, "A");
705        assert_eq!(rows[0].state, "ready");
706    }
707
708    // Test 8: Two matching start files: the later started_at wins.
709    #[test]
710    fn test_8_later_started_at_wins() {
711        let repo = setup_test_repo();
712        let pid = std::process::id();
713        // A1 has earlier started_at and is dead
714        write_start_json(repo.path(), "A1", "docs/p.md", "Task A", 999999, 100);
715        // A2 has later started_at and is alive
716        write_start_json(repo.path(), "A2", "docs/p.md", "Task A", pid, 200);
717
718        let rows = statuses(repo.path(), "docs/p.md", TWO_TASK_PLAN);
719        assert_eq!(rows[0].id, "A");
720        assert_eq!(rows[0].state, "running");
721        assert_eq!(rows[0].run.as_deref(), Some("A2"));
722    }
723
724    // Test 9: A heading ### Setup step that parse_plan returns as a task (check what parse_plan does with it;
725    // if it does not, use a heading shape it does return that does not start with Task <ID>): the command
726    // uses the whole heading as --plan-task.
727    #[test]
728    fn test_9_heading_shape_without_task_id_prefix() {
729        // parse_plan requires 'Task ' prefix and ':'.
730        // For '### Task 1: setup step', first_word is '1', which is digits, so id becomes 'T1'.
731        // Heading is 'Task 1: setup step', which does not start with 'Task T1'.
732        // Therefore plan_task_text returns the full heading: "Task 1: setup step".
733        let plan = r#"# Plan
734
735### Task 1: setup step
736
737Do setup.
738"#;
739        let repo = setup_test_repo();
740        let rows = statuses(repo.path(), "docs/p.md", plan);
741        assert_eq!(rows.len(), 1);
742        assert_eq!(rows[0].id, "T1");
743        assert_eq!(rows[0].state, "ready");
744        assert_eq!(
745            rows[0].command.as_deref(),
746            Some("blyte dispatch T1 --plan docs/p.md --plan-task \"Task 1: setup step\"")
747        );
748    }
749
750    // Test 10: problem set when extract fails: build a TaskStatus path where the plan-task text does not
751    // resolve (for example a task heading inside an unclosed fence that parse_plan still lists, or test the
752    // helper that picks the plan-task text plus extract directly) and check command is None and problem is Some.
753    #[test]
754    fn test_10_problem_set_when_extract_fails() {
755        // In markdown, `~~~` is a code fence for plan_section::extract, but parse_plan only treats ```` ``` ```` as fences.
756        // Therefore parse_plan parses the task, but extract fails to find it.
757        let plan = "~~~\n### Task A: fenced\n~~~\n";
758        let repo = setup_test_repo();
759        let rows = statuses(repo.path(), "docs/p.md", plan);
760        assert_eq!(rows.len(), 1);
761        assert_eq!(rows[0].id, "A");
762        assert!(rows[0].command.is_none());
763        assert!(rows[0].problem.is_some());
764    }
765
766    // 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
767    // ends with (waiting on A).
768    #[test]
769    fn test_11_render_output() {
770        let repo = setup_test_repo();
771        let rows = statuses(repo.path(), "docs/p.md", TWO_TASK_PLAN);
772        let rendered = render("docs/p.md", &rows);
773        let lines: Vec<&str> = rendered.lines().collect();
774
775        assert_eq!(lines[0], "docs/p.md: 2 tasks (1 ready, 1 waiting)");
776        assert!(lines[2].ends_with("(waiting on A)"));
777    }
778
779    // Test 12: run with a missing file returns 2.
780    #[test]
781    fn test_12_run_missing_file_returns_2() {
782        let repo = setup_test_repo();
783        let missing = repo.path().join("does_not_exist.md");
784        let code = run(&missing, false);
785        assert_eq!(code, 2);
786    }
787}