blyte 0.84.0

The blyte coding-agent harness: headless runs with a sealed verification gate, and a REPL.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
use std::collections::HashSet;
use std::path::{Path, PathBuf};
use std::process::Command;

#[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize)]
pub struct TaskStatus {
    pub id: String,
    pub heading: String, // PlanTask.heading
    pub deps: Vec<String>,
    pub state: String, // "merged" | "review" | "running" | "dead" | "ready" | "waiting"
    pub run: Option<String>, // the run id it was matched to
    pub outcome: Option<String>, // the summary's outcome, when there is one
    pub verdict: Option<String>,
    pub waiting_on: Vec<String>, // deps not merged, only for "waiting"
    pub command: Option<String>, // only for "ready"
    pub problem: Option<String>, // only when the plan-task text does not resolve
}

fn is_pid_alive(pid: libc::pid_t) -> bool {
    if pid <= 0 {
        return false;
    }
    let ret = unsafe { libc::kill(pid, 0) };
    if ret == 0 {
        true
    } else {
        std::io::Error::last_os_error().raw_os_error() == Some(libc::EPERM)
    }
}

pub fn plan_task_text(id: &str, heading: &str) -> String {
    let prefix = format!("Task {id}");
    if heading.starts_with(&prefix) {
        let rest = &heading[prefix.len()..];
        if rest.is_empty() || rest.starts_with(':') || rest.starts_with(' ') {
            return prefix;
        }
    }
    heading.to_string()
}

fn normalize_components(p: &Path) -> PathBuf {
    use std::path::Component;
    let mut out = PathBuf::new();
    for c in p.components() {
        if c != Component::CurDir {
            out.push(c);
        }
    }
    out
}

fn canonicalize_with_tail(p: &Path) -> Option<PathBuf> {
    let mut cur = p;
    let mut tail = Vec::new();
    loop {
        if let Ok(canon) = cur.canonicalize() {
            let mut out = canon;
            for part in tail.into_iter().rev() {
                out.push(part);
            }
            return Some(out);
        }
        let name = cur.file_name()?;
        tail.push(name.to_os_string());
        cur = cur.parent()?;
    }
}

fn strip_root_prefix(root: &Path, norm_plan: &Path) -> Option<PathBuf> {
    let norm_root = normalize_components(root);
    if let Ok(r) = norm_plan.strip_prefix(&norm_root) {
        return Some(r.to_path_buf());
    }
    let canon_root = root.canonicalize().ok()?;
    if let Ok(r) = norm_plan.strip_prefix(&canon_root) {
        return Some(r.to_path_buf());
    }
    let canon_plan = canonicalize_with_tail(norm_plan)?;
    canon_plan
        .strip_prefix(&canon_root)
        .ok()
        .map(Path::to_path_buf)
}

fn strip_worktree_prefix(rel: &Path) -> PathBuf {
    use std::path::Component;
    let mut comps = rel.components();
    if matches!(comps.next(), Some(Component::Normal(first)) if first == ".wt")
        && matches!(comps.next(), Some(Component::Normal(_)))
    {
        let rest = comps.as_path();
        if !rest.as_os_str().is_empty() {
            return rest.to_path_buf();
        }
    }
    rel.to_path_buf()
}

fn repo_relative_plan(root: &Path, plan: &str) -> PathBuf {
    let norm_plan = normalize_components(Path::new(plan));
    let rel = if norm_plan.is_absolute() {
        match strip_root_prefix(root, &norm_plan) {
            Some(r) => r,
            None => return norm_plan,
        }
    } else {
        norm_plan
    };
    strip_worktree_prefix(&rel)
}

fn paths_match(root: &Path, start_plan: &str, plan_rel: &str) -> bool {
    let p1 = root.join(repo_relative_plan(root, start_plan));
    let p2 = root.join(repo_relative_plan(root, plan_rel));
    match (p1.canonicalize(), p2.canonicalize()) {
        (Ok(c1), Ok(c2)) => c1 == c2,
        _ => normalize_components(&p1) == normalize_components(&p2),
    }
}

#[derive(Debug, Clone)]
struct StartRecord {
    run_id: String,
    started_at: Option<u64>,
    plan: Option<String>,
    plan_task: Option<String>,
    pid: Option<libc::pid_t>,
}

fn read_start_files(root: &Path) -> Result<Vec<StartRecord>, String> {
    let wt_dir = root.join(".wt");
    let entries = match std::fs::read_dir(&wt_dir) {
        Ok(e) => e,
        Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(Vec::new()),
        Err(e) => return Err(format!("{}: {e}", wt_dir.display())),
    };
    let mut records = Vec::new();
    for entry in entries {
        let entry = entry.map_err(|e| format!("{}: {e}", wt_dir.display()))?;
        let name = entry.file_name();
        let name_str = name.to_string_lossy();
        if let Some(run_id) = name_str.strip_suffix(".start.json") {
            let path = entry.path();
            let content =
                std::fs::read_to_string(&path).map_err(|e| format!("{}: {e}", path.display()))?;
            let val: serde_json::Value =
                serde_json::from_str(&content).map_err(|e| format!("{}: {e}", path.display()))?;
            let obj = val
                .as_object()
                .ok_or_else(|| format!("{}: expected JSON object", path.display()))?;
            let started_at = match obj.get("started_at") {
                None | Some(serde_json::Value::Null) => None,
                Some(v) => Some(
                    v.as_u64()
                        .or_else(|| v.as_str().and_then(|s| s.parse::<u64>().ok()))
                        .ok_or_else(|| format!("{}: invalid 'started_at' field", path.display()))?,
                ),
            };
            let plan = match obj.get("plan") {
                None | Some(serde_json::Value::Null) => None,
                Some(serde_json::Value::String(s)) => Some(s.clone()),
                Some(_) => {
                    return Err(format!("{}: invalid 'plan' field", path.display()));
                }
            };
            let plan_task = match obj.get("plan_task") {
                None | Some(serde_json::Value::Null) => None,
                Some(serde_json::Value::String(s)) => Some(s.clone()),
                Some(_) => {
                    return Err(format!("{}: invalid 'plan_task' field", path.display()));
                }
            };
            let pid = match obj.get("pid") {
                None | Some(serde_json::Value::Null) => None,
                Some(v) => Some(
                    v.as_i64()
                        .ok_or_else(|| format!("{}: invalid 'pid' field", path.display()))?
                        as libc::pid_t,
                ),
            };
            records.push(StartRecord {
                run_id: run_id.to_string(),
                started_at,
                plan,
                plan_task,
                pid,
            });
        }
    }
    Ok(records)
}

fn check_is_ancestor(root: &Path, run_id: &str) -> bool {
    Command::new("git")
        .args([
            "merge-base",
            "--is-ancestor",
            &format!("wip/{run_id}"),
            "HEAD",
        ])
        .current_dir(root)
        .output()
        .map(|o| o.status.success())
        .unwrap_or(false)
}

fn check_branch_exists(root: &Path, run_id: &str) -> bool {
    Command::new("git")
        .args(["rev-parse", "--verify", &format!("refs/heads/wip/{run_id}")])
        .current_dir(root)
        .output()
        .map(|o| o.status.success())
        .unwrap_or(false)
}

fn read_verdict(root: &Path, run_id: &str) -> Result<Option<String>, String> {
    let verdict_file = root.join(".wt").join(format!("{run_id}.verdict.json"));
    let content = match std::fs::read_to_string(&verdict_file) {
        Ok(s) => s,
        Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(None),
        Err(e) => return Err(format!("{}: {e}", verdict_file.display())),
    };
    let val: serde_json::Value =
        serde_json::from_str(&content).map_err(|e| format!("{}: {e}", verdict_file.display()))?;
    let verdict = val
        .get("verdict")
        .and_then(|x| x.as_str())
        .filter(|s| !s.is_empty())
        .ok_or_else(|| {
            format!(
                "{}: missing or invalid 'verdict' string",
                verdict_file.display()
            )
        })?;
    Ok(Some(verdict.to_string()))
}

fn read_summary(root: &Path, run_id: &str) -> Result<Option<(String, bool)>, String> {
    let summary_file = root.join(".wt").join(format!("{run_id}.json"));
    let content = match std::fs::read_to_string(&summary_file) {
        Ok(s) => s,
        Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(None),
        Err(e) => return Err(format!("{}: {e}", summary_file.display())),
    };
    let val: serde_json::Value =
        serde_json::from_str(&content).map_err(|e| format!("{}: {e}", summary_file.display()))?;
    let outcome = val
        .get("outcome")
        .and_then(|x| x.as_str())
        .filter(|s| !s.is_empty())
        .ok_or_else(|| {
            format!(
                "{}: missing or invalid 'outcome' string",
                summary_file.display()
            )
        })?
        .to_string();
    let has_commits = match val.get("commits") {
        None | Some(serde_json::Value::Null) => false,
        Some(serde_json::Value::Array(a)) => !a.is_empty(),
        Some(_) => {
            return Err(format!(
                "{}: 'commits' must be an array",
                summary_file.display()
            ));
        }
    };
    Ok(Some((outcome, has_commits)))
}

struct TaskIntermediate {
    task: crate::plans::PlanTask,
    plan_task_t: String,
    problem: Option<String>,
    state: Option<String>,
    run: Option<String>,
    outcome: Option<String>,
    verdict: Option<String>,
}

/// `root` is the main checkout (holds `.wt/`), `plan_rel` the plan path relative to it, as dispatch takes it.
pub fn statuses(root: &Path, plan_rel: &str, text: &str) -> Result<Vec<TaskStatus>, String> {
    let doc = crate::plans::parse_plan(text);
    let start_files = read_start_files(root)?;

    let all_task_ids: Vec<String> = doc.tasks.iter().map(|t| t.id.clone()).collect();
    let mut intermediates = Vec::new();

    for task in doc.tasks {
        let t = plan_task_text(&task.id, &task.heading);
        let problem = if crate::plan_section::extract(text, &t).is_none() {
            Some(
                crate::plan_section::explain_missing(text, &t)
                    .unwrap_or_else(|| "heading not found".to_string()),
            )
        } else {
            None
        };

        let task_id_label = format!("Task {}", task.id);
        let mut matching: Vec<&StartRecord> = start_files
            .iter()
            .filter(|s| {
                let Some(ref sp) = s.plan else {
                    return false;
                };
                if !paths_match(root, sp, plan_rel) {
                    return false;
                }
                let Some(ref spt) = s.plan_task else {
                    return false;
                };
                spt == &t || spt == &task_id_label || spt == &task.heading
            })
            .collect();
        matching.sort_by_key(|r| r.started_at);
        let matched_run = matching.last().copied();

        let mut state = None;
        let mut run_out = None;
        let mut outcome_out = None;
        let mut verdict_out = None;

        if let Some(run) = matched_run {
            let branch_exists = check_branch_exists(root, &run.run_id);
            let verdict_opt = read_verdict(root, &run.run_id)?;
            let summary = read_summary(root, &run.run_id)?;
            let has_commits = summary.as_ref().is_some_and(|(_, c)| *c);
            let is_merged = if branch_exists {
                has_commits && check_is_ancestor(root, &run.run_id)
            } else {
                crate::plans::is_merged_when_branch_gone(root, &run.run_id, verdict_opt.as_deref())?
            };

            if summary.is_none() && run.pid.map(is_pid_alive).unwrap_or(false) {
                state = Some("running".to_string());
                run_out = Some(run.run_id.clone());
                verdict_out = verdict_opt;
            } else if is_merged {
                state = Some("merged".to_string());
                run_out = Some(run.run_id.clone());
                outcome_out = summary.map(|(o, _)| o);
                verdict_out = verdict_opt;
            } else if verdict_opt.as_deref() == Some("redone") {
            } else if let Some((outcome, _)) = summary {
                state = Some("review".to_string());
                run_out = Some(run.run_id.clone());
                outcome_out = Some(outcome);
                verdict_out = verdict_opt;
            } else {
                state = Some("dead".to_string());
                run_out = Some(run.run_id.clone());
                verdict_out = verdict_opt;
            }
        }

        intermediates.push(TaskIntermediate {
            task,
            plan_task_t: t,
            problem,
            state,
            run: run_out,
            outcome: outcome_out,
            verdict: verdict_out,
        });
    }

    let merged_task_ids: HashSet<String> = intermediates
        .iter()
        .filter(|item| item.state.as_deref() == Some("merged"))
        .map(|item| item.task.id.clone())
        .collect();

    Ok(intermediates
        .into_iter()
        .map(|item| {
            let (state, waiting_on, command) = if let Some(st) = item.state {
                (st, Vec::new(), None)
            } else {
                let waiting_on: Vec<String> =
                    doc_task_order(&all_task_ids, &item.task.deps, &merged_task_ids);
                if waiting_on.is_empty() {
                    let cmd = if item.problem.is_none() {
                        Some(format!(
                            "blyte dispatch {} --plan {} --plan-task \"{}\"",
                            item.task.id, plan_rel, item.plan_task_t
                        ))
                    } else {
                        None
                    };
                    ("ready".to_string(), Vec::new(), cmd)
                } else {
                    ("waiting".to_string(), waiting_on, None)
                }
            };

            TaskStatus {
                id: item.task.id,
                heading: item.task.heading,
                deps: item.task.deps,
                state,
                run: item.run,
                outcome: item.outcome,
                verdict: item.verdict,
                waiting_on,
                command,
                problem: item.problem,
            }
        })
        .collect())
}

fn doc_task_order(
    all_task_ids: &[String],
    deps: &[String],
    merged_task_ids: &HashSet<String>,
) -> Vec<String> {
    all_task_ids
        .iter()
        .filter(|id| deps.contains(id) && !merged_task_ids.contains(*id))
        .cloned()
        .collect()
}

pub fn render(plan_rel: &str, rows: &[TaskStatus]) -> Result<String, String> {
    let mut counts = Vec::new();
    let n_merged = rows.iter().filter(|r| r.state == "merged").count();
    if n_merged > 0 {
        counts.push(format!("{n_merged} merged"));
    }
    let n_review = rows.iter().filter(|r| r.state == "review").count();
    if n_review > 0 {
        counts.push(format!("{n_review} review"));
    }
    let n_running = rows.iter().filter(|r| r.state == "running").count();
    if n_running > 0 {
        counts.push(format!("{n_running} running"));
    }
    let n_dead = rows.iter().filter(|r| r.state == "dead").count();
    if n_dead > 0 {
        counts.push(format!("{n_dead} dead"));
    }
    let n_ready = rows.iter().filter(|r| r.state == "ready").count();
    if n_ready > 0 {
        counts.push(format!("{n_ready} ready"));
    }
    let n_waiting = rows.iter().filter(|r| r.state == "waiting").count();
    if n_waiting > 0 {
        counts.push(format!("{n_waiting} waiting"));
    }

    let first_line = if counts.is_empty() {
        format!("{plan_rel}: {} tasks", rows.len())
    } else {
        format!("{plan_rel}: {} tasks ({})", rows.len(), counts.join(", "))
    };

    let max_id_len = rows.iter().map(|r| r.id.len()).max().unwrap_or(0);

    let mut lines = Vec::with_capacity(rows.len() + 1);
    lines.push(first_line);

    for r in rows {
        let detail =
            match r.state.as_str() {
                "merged" => {
                    if let Some(ref problem) = r.problem {
                        format!("PROBLEM: {problem}")
                    } else {
                        r.heading.clone()
                    }
                }
                "waiting" => {
                    if let Some(ref problem) = r.problem {
                        format!("PROBLEM: {problem}")
                    } else if r.waiting_on.is_empty() {
                        r.heading.clone()
                    } else {
                        format!("{}  (waiting on {})", r.heading, r.waiting_on.join(", "))
                    }
                }
                "review" => {
                    if let Some(ref problem) = r.problem {
                        format!("PROBLEM: {problem}")
                    } else {
                        let outcome = r.outcome.as_deref().ok_or_else(|| {
                            format!("task {}: state 'review' missing outcome", r.id)
                        })?;
                        let run = r.run.as_deref().ok_or_else(|| {
                            format!("task {}: state 'review' missing run id", r.id)
                        })?;
                        format!("{outcome}, run {run}: blyte review {run}")
                    }
                }
                "running" | "dead" => {
                    if let Some(ref problem) = r.problem {
                        format!("PROBLEM: {problem}")
                    } else {
                        let run = r.run.as_deref().ok_or_else(|| {
                            format!("task {}: state '{}' missing run id", r.id, r.state)
                        })?;
                        format!("run {run}: blyte status {run}")
                    }
                }
                "ready" => {
                    if let Some(ref problem) = r.problem {
                        format!("PROBLEM: {problem}")
                    } else {
                        r.command.clone().ok_or_else(|| {
                            format!("task {}: state 'ready' missing command", r.id)
                        })?
                    }
                }
                _ => {
                    if let Some(ref problem) = r.problem {
                        format!("PROBLEM: {problem}")
                    } else {
                        r.heading.clone()
                    }
                }
            };

        lines.push(format!("{:<max_id_len$}  {:<7}  {detail}", r.id, r.state));
    }

    Ok(lines.join("\n"))
}

fn compute_plan_rel(root: &Path, plan: &Path, full_plan_path: &Path) -> String {
    let canon_root = root.canonicalize().unwrap_or_else(|_| root.to_path_buf());
    let canon_plan = full_plan_path
        .canonicalize()
        .unwrap_or_else(|_| full_plan_path.to_path_buf());
    if let Ok(rel) = canon_plan.strip_prefix(&canon_root) {
        return rel.to_string_lossy().to_string();
    }
    if let Ok(rel) = full_plan_path.strip_prefix(root) {
        return rel.to_string_lossy().to_string();
    }
    plan.to_string_lossy().to_string()
}

pub fn run(plan: &Path, json: bool) -> i32 {
    let current_dir = std::env::current_dir().unwrap_or_else(|_| PathBuf::from("."));

    let root = match crate::clean::find_repo_root() {
        Ok(r) => r,
        Err(e) => {
            eprintln!("error: {e}");
            return 2;
        }
    };

    let full_plan_path = if plan.is_absolute() {
        plan.to_path_buf()
    } else {
        current_dir.join(plan)
    };

    let text = match std::fs::read_to_string(&full_plan_path) {
        Ok(t) => t,
        Err(e) => {
            eprintln!("error: cannot read plan file '{}': {e}", plan.display());
            return 2;
        }
    };

    let doc = crate::plans::parse_plan(&text);
    if doc.tasks.is_empty() {
        eprintln!("error: plan has no ### Task sections");
        return 2;
    }

    let plan_rel = compute_plan_rel(&root, plan, &full_plan_path);
    let rows = match statuses(&root, &plan_rel, &text) {
        Ok(r) => r,
        Err(e) => {
            eprintln!("error: {e}");
            return 2;
        }
    };

    if json {
        match serde_json::to_string_pretty(&rows) {
            Ok(json_str) => println!("{json_str}"),
            Err(e) => {
                eprintln!("error: {e}");
                return 2;
            }
        }
    } else {
        match render(&plan_rel, &rows) {
            Ok(rendered) => println!("{rendered}"),
            Err(e) => {
                eprintln!("error: {e}");
                return 2;
            }
        }
    }

    0
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::fs;
    use tempfile::TempDir;

    fn git(dir: &Path, args: &[&str]) {
        let ok = Command::new("git")
            .args(["-c", "user.name=t", "-c", "user.email=t@t"])
            .args(args)
            .current_dir(dir)
            .status()
            .unwrap()
            .success();
        assert!(ok, "git {args:?}");
    }

    fn setup_test_repo() -> TempDir {
        let dir = tempfile::tempdir().unwrap();
        let root = dir.path();
        git(root, &["init", "-q", "-b", "main"]);
        fs::write(root.join("f.txt"), "hello\n").unwrap();
        git(root, &["add", "."]);
        git(root, &["commit", "-qm", "initial", "--no-gpg-sign"]);
        fs::create_dir_all(root.join(".wt")).unwrap();
        dir
    }

    fn write_start_json(
        root: &Path,
        run_id: &str,
        plan: &str,
        plan_task: &str,
        pid: u32,
        started_at: u64,
    ) {
        let json = serde_json::json!({
            "id": run_id,
            "plan": plan,
            "plan_task": plan_task,
            "pid": pid,
            "started_at": started_at,
        });
        fs::write(
            root.join(".wt").join(format!("{run_id}.start.json")),
            serde_json::to_string_pretty(&json).unwrap(),
        )
        .unwrap();
    }

    fn write_summary_json(root: &Path, run_id: &str, outcome: &str) {
        let json = serde_json::json!({
            "id": run_id,
            "outcome": outcome,
        });
        fs::write(
            root.join(".wt").join(format!("{run_id}.json")),
            serde_json::to_string_pretty(&json).unwrap(),
        )
        .unwrap();
    }

    fn write_verdict_json(root: &Path, run_id: &str, verdict: &str) {
        let json = serde_json::json!({
            "verdict": verdict,
        });
        fs::write(
            root.join(".wt").join(format!("{run_id}.verdict.json")),
            serde_json::to_string_pretty(&json).unwrap(),
        )
        .unwrap();
    }

    const TWO_TASK_PLAN: &str = r#"# Sample Plan

### Task A: one

Depends on: none

Do task A.

### Task B: two

**Depends on:** A

Do task B.
"#;

    // Test 1: A plan with ### Task A: one (Depends on: none) and ### Task B: two (**Depends on:** A), no runs:
    // A is ready with command blyte dispatch A --plan docs/p.md --plan-task "Task A"; B is waiting,
    // waiting_on == ["A"], no command.
    #[test]
    fn test_1_plan_dependencies_no_runs() {
        let repo = setup_test_repo();
        let rows = statuses(repo.path(), "docs/p.md", TWO_TASK_PLAN).unwrap();

        assert_eq!(rows.len(), 2);
        let a = &rows[0];
        assert_eq!(a.id, "A");
        assert_eq!(a.state, "ready");
        assert_eq!(
            a.command.as_deref(),
            Some("blyte dispatch A --plan docs/p.md --plan-task \"Task A\"")
        );
        assert!(a.waiting_on.is_empty());

        let b = &rows[1];
        assert_eq!(b.id, "B");
        assert_eq!(b.state, "waiting");
        assert_eq!(b.waiting_on, vec!["A"]);
        assert!(b.command.is_none());
    }

    // Test 2: A start file for A (plan docs/p.md, plan_task Task A, pid of the test process) and no summary:
    // A is running, run A.
    #[test]
    fn test_2_start_file_alive_pid_running() {
        let repo = setup_test_repo();
        let pid = std::process::id();
        write_start_json(repo.path(), "A", "docs/p.md", "Task A", pid, 100);

        let rows = statuses(repo.path(), "docs/p.md", TWO_TASK_PLAN).unwrap();
        assert_eq!(rows[0].id, "A");
        assert_eq!(rows[0].state, "running");
        assert_eq!(rows[0].run.as_deref(), Some("A"));
    }

    // Test 3: Same with pid 999999 (not alive): dead.
    #[test]
    fn test_3_start_file_dead_pid() {
        let repo = setup_test_repo();
        write_start_json(repo.path(), "A", "docs/p.md", "Task A", 999999, 100);

        let rows = statuses(repo.path(), "docs/p.md", TWO_TASK_PLAN).unwrap();
        assert_eq!(rows[0].id, "A");
        assert_eq!(rows[0].state, "dead");
        assert_eq!(rows[0].run.as_deref(), Some("A"));
    }

    // Test 4: A start file plus .wt/A.json with "outcome":"verified": review, outcome verified.
    #[test]
    fn test_4_start_and_summary_review() {
        let repo = setup_test_repo();
        write_start_json(repo.path(), "A", "docs/p.md", "Task A", 999999, 100);
        write_summary_json(repo.path(), "A", "verified");

        let rows = statuses(repo.path(), "docs/p.md", TWO_TASK_PLAN).unwrap();
        assert_eq!(rows[0].id, "A");
        assert_eq!(rows[0].state, "review");
        assert_eq!(rows[0].run.as_deref(), Some("A"));
        assert_eq!(rows[0].outcome.as_deref(), Some("verified"));
    }

    // Test 5: A run whose branch wip/A1 is an ancestor of HEAD (create the branch at HEAD), run id A1 different
    // from the task id, plan_task Task A: A is merged with run A1, and B is ready.
    #[test]
    fn test_5_branch_merged_makes_dependent_ready() {
        let repo = setup_test_repo();
        git(repo.path(), &["branch", "wip/A1"]);
        write_start_json(repo.path(), "A1", "docs/p.md", "Task A", 999999, 100);
        fs::write(
            repo.path().join(".wt/A1.json"),
            r#"{"id":"A1","outcome":"verified","commits":[{"sha":"abc","subject":"work"}]}"#,
        )
        .unwrap();

        let rows = statuses(repo.path(), "docs/p.md", TWO_TASK_PLAN).unwrap();
        assert_eq!(rows[0].id, "A");
        assert_eq!(rows[0].state, "merged");
        assert_eq!(rows[0].run.as_deref(), Some("A1"));

        assert_eq!(rows[1].id, "B");
        assert_eq!(rows[1].state, "ready");
        assert_eq!(
            rows[1].command.as_deref(),
            Some("blyte dispatch B --plan docs/p.md --plan-task \"Task B\"")
        );
    }

    // Test 6: No branch, verdict accepted: merged. Verdict redone with a summary: A is ready again.
    #[test]
    fn test_6_verdict_accepted_then_redone() {
        let repo = setup_test_repo();
        write_start_json(repo.path(), "A", "docs/p.md", "Task A", 999999, 100);
        write_verdict_json(repo.path(), "A", "accepted");

        let rows = statuses(repo.path(), "docs/p.md", TWO_TASK_PLAN).unwrap();
        assert_eq!(rows[0].id, "A");
        assert_eq!(rows[0].state, "merged");

        // Now change verdict to redone and add a summary: A is ready again.
        write_summary_json(repo.path(), "A", "gate_failed");
        write_verdict_json(repo.path(), "A", "redone");

        let rows2 = statuses(repo.path(), "docs/p.md", TWO_TASK_PLAN).unwrap();
        assert_eq!(rows2[0].id, "A");
        assert_eq!(rows2[0].state, "ready");
        assert_eq!(
            rows2[0].command.as_deref(),
            Some("blyte dispatch A --plan docs/p.md --plan-task \"Task A\"")
        );
    }

    // Test 7: A start file for the same task in a different plan file: ignored (A stays ready).
    #[test]
    fn test_7_different_plan_file_ignored() {
        let repo = setup_test_repo();
        write_start_json(
            repo.path(),
            "A",
            "docs/other.md",
            "Task A",
            std::process::id(),
            100,
        );

        let rows = statuses(repo.path(), "docs/p.md", TWO_TASK_PLAN).unwrap();
        assert_eq!(rows[0].id, "A");
        assert_eq!(rows[0].state, "ready");
    }

    // Test 8: Two matching start files: the later started_at wins.
    #[test]
    fn test_8_later_started_at_wins() {
        let repo = setup_test_repo();
        let pid = std::process::id();
        // A1 has earlier started_at and is dead
        write_start_json(repo.path(), "A1", "docs/p.md", "Task A", 999999, 100);
        // A2 has later started_at and is alive
        write_start_json(repo.path(), "A2", "docs/p.md", "Task A", pid, 200);

        let rows = statuses(repo.path(), "docs/p.md", TWO_TASK_PLAN).unwrap();
        assert_eq!(rows[0].id, "A");
        assert_eq!(rows[0].state, "running");
        assert_eq!(rows[0].run.as_deref(), Some("A2"));
    }

    // Test 9: A heading ### Setup step that parse_plan returns as a task (check what parse_plan does with it;
    // if it does not, use a heading shape it does return that does not start with Task <ID>): the command
    // uses the whole heading as --plan-task.
    #[test]
    fn test_9_heading_shape_without_task_id_prefix() {
        // parse_plan requires 'Task ' prefix and ':'.
        // For '### Task 1: setup step', first_word is '1', which is digits, so id becomes 'T1'.
        // Heading is 'Task 1: setup step', which does not start with 'Task T1'.
        // Therefore plan_task_text returns the full heading: "Task 1: setup step".
        let plan = r#"# Plan

### Task 1: setup step

Do setup.
"#;
        let repo = setup_test_repo();
        let rows = statuses(repo.path(), "docs/p.md", plan).unwrap();
        assert_eq!(rows.len(), 1);
        assert_eq!(rows[0].id, "T1");
        assert_eq!(rows[0].state, "ready");
        assert_eq!(
            rows[0].command.as_deref(),
            Some("blyte dispatch T1 --plan docs/p.md --plan-task \"Task 1: setup step\"")
        );
    }

    // Test 10: problem set when extract fails: build a TaskStatus path where the plan-task text does not
    // resolve (for example a task heading inside an unclosed fence that parse_plan still lists, or test the
    // helper that picks the plan-task text plus extract directly) and check command is None and problem is Some.
    #[test]
    fn test_10_problem_set_when_extract_fails() {
        // In markdown, `~~~` is a code fence for plan_section::extract, but parse_plan only treats ```` ``` ```` as fences.
        // Therefore parse_plan parses the task, but extract fails to find it.
        let plan = "~~~\n### Task A: fenced\n~~~\n";
        let repo = setup_test_repo();
        let rows = statuses(repo.path(), "docs/p.md", plan).unwrap();
        assert_eq!(rows.len(), 1);
        assert_eq!(rows[0].id, "A");
        assert!(rows[0].command.is_none());
        assert!(rows[0].problem.is_some());
    }

    // 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
    // ends with (waiting on A).
    #[test]
    fn test_11_render_output() {
        let repo = setup_test_repo();
        let rows = statuses(repo.path(), "docs/p.md", TWO_TASK_PLAN).unwrap();
        let rendered = render("docs/p.md", &rows).unwrap();
        let lines: Vec<&str> = rendered.lines().collect();

        assert_eq!(lines[0], "docs/p.md: 2 tasks (1 ready, 1 waiting)");
        assert!(lines[2].ends_with("(waiting on A)"));
    }

    // Test 12: run with a missing file returns 2.
    #[test]
    fn test_12_run_missing_file_returns_2() {
        let repo = setup_test_repo();
        let missing = repo.path().join("does_not_exist.md");
        let code = run(&missing, false);
        assert_eq!(code, 2);
    }

    #[test]
    fn render_errors_on_missing_required_fields() {
        let missing_outcome = TaskStatus {
            id: "A".to_string(),
            heading: "Task A: one".to_string(),
            deps: Vec::new(),
            state: "review".to_string(),
            run: Some("A".to_string()),
            outcome: None,
            verdict: None,
            waiting_on: Vec::new(),
            command: None,
            problem: None,
        };
        assert!(render("docs/p.md", &[missing_outcome]).is_err());

        let missing_run_review = TaskStatus {
            id: "A".to_string(),
            heading: "Task A: one".to_string(),
            deps: Vec::new(),
            state: "review".to_string(),
            run: None,
            outcome: Some("verified".to_string()),
            verdict: None,
            waiting_on: Vec::new(),
            command: None,
            problem: None,
        };
        assert!(render("docs/p.md", &[missing_run_review]).is_err());

        let missing_run_dead = TaskStatus {
            id: "A".to_string(),
            heading: "Task A: one".to_string(),
            deps: Vec::new(),
            state: "dead".to_string(),
            run: None,
            outcome: None,
            verdict: None,
            waiting_on: Vec::new(),
            command: None,
            problem: None,
        };
        assert!(render("docs/p.md", &[missing_run_dead]).is_err());
    }
}