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