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