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