Skip to main content

blyte_cli/
wait.rs

1use std::collections::HashSet;
2use std::io::Write;
3use std::path::Path;
4use std::time::{Duration, Instant, SystemTime};
5
6const PARTIAL_WRITE_WINDOW: Duration = Duration::from_secs(2);
7
8pub fn run(ids: &[String], any: bool, timeout_secs: u64) -> i32 {
9    let cwd = match std::env::current_dir() {
10        Ok(d) => d,
11        Err(e) => {
12            eprintln!("error: {e}");
13            return 2;
14        }
15    };
16    let records_dir = match crate::dispatch_in_place::records_dir_for(&cwd) {
17        Ok(d) => d,
18        Err(e) => {
19            eprintln!("error: {e}");
20            return 2;
21        }
22    };
23    wait_in(
24        &records_dir,
25        ids,
26        any,
27        Duration::from_secs(timeout_secs),
28        Duration::from_secs(2),
29        Duration::from_secs(15),
30        &mut std::io::stdout(),
31        &mut std::io::stderr(),
32    )
33}
34
35enum SummaryState {
36    Absent,
37    InProgress,
38    Ready(serde_json::Value),
39    Corrupt(String),
40}
41
42fn is_recently_modified(path: &Path, window: Duration) -> bool {
43    let Ok(meta) = std::fs::metadata(path) else {
44        return false;
45    };
46    let Ok(mtime) = meta.modified() else {
47        return false;
48    };
49    match SystemTime::now().duration_since(mtime) {
50        Ok(age) => age < window,
51        Err(_) => true,
52    }
53}
54
55fn read_summary(path: &Path) -> SummaryState {
56    let raw = match std::fs::read_to_string(path) {
57        Ok(s) => s,
58        Err(e) if e.kind() == std::io::ErrorKind::NotFound => return SummaryState::Absent,
59        Err(e) => return SummaryState::Corrupt(format!("cannot read {}: {e}", path.display())),
60    };
61    match serde_json::from_str::<serde_json::Value>(&raw) {
62        Ok(val) => SummaryState::Ready(val),
63        Err(e) => {
64            if is_recently_modified(path, PARTIAL_WRITE_WINDOW) {
65                SummaryState::InProgress
66            } else {
67                SummaryState::Corrupt(format!("cannot parse {}: {e}", path.display()))
68            }
69        }
70    }
71}
72
73fn check_start_alive(path: &Path) -> Result<Option<bool>, String> {
74    let raw = match std::fs::read_to_string(path) {
75        Ok(s) => s,
76        Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(None),
77        Err(e) => return Err(format!("cannot read {}: {e}", path.display())),
78    };
79    let val: serde_json::Value =
80        serde_json::from_str(&raw).map_err(|e| format!("cannot parse {}: {e}", path.display()))?;
81    crate::clean::run_process_alive(&val)
82        .map(Some)
83        .map_err(|e| format!("{}: {e}", path.display()))
84}
85
86fn format_summary_line(
87    path: &Path,
88    id: &str,
89    summary: &serde_json::Value,
90) -> Result<String, String> {
91    if !summary.is_object() {
92        return Err(format!("{} is not a JSON object", path.display()));
93    }
94    let outcome = summary
95        .get("outcome")
96        .and_then(|v| v.as_str())
97        .ok_or_else(|| format!("{} is missing string field \"outcome\"", path.display()))?;
98    let turns = summary
99        .get("turns")
100        .and_then(|v| {
101            v.as_i64()
102                .map(|t| t.to_string())
103                .or_else(|| v.as_u64().map(|t| t.to_string()))
104        })
105        .ok_or_else(|| format!("{} is missing integer field \"turns\"", path.display()))?;
106    let cost = match summary.get("cost_usd").and_then(|v| v.as_f64()) {
107        Some(c) => format!("${:.2}", c),
108        None => "-".to_string(),
109    };
110    Ok(format!("{id} {outcome} {turns} {cost}"))
111}
112
113#[derive(serde::Deserialize)]
114struct RefusedRecord {
115    refused_at: u64,
116    error: String,
117}
118
119fn read_refusal(path: &Path) -> Result<Option<RefusedRecord>, String> {
120    let raw = match std::fs::read_to_string(path) {
121        Ok(s) => s,
122        Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(None),
123        Err(e) => return Err(format!("cannot read {}: {e}", path.display())),
124    };
125    let record: RefusedRecord =
126        serde_json::from_str(&raw).map_err(|e| format!("cannot parse {}: {e}", path.display()))?;
127    Ok(Some(record))
128}
129
130fn start_newer_than_refusal(start_path: &Path, refused_at: u64) -> Result<bool, String> {
131    let meta = match std::fs::metadata(start_path) {
132        Ok(m) => m,
133        Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(false),
134        Err(e) => return Err(format!("cannot stat {}: {e}", start_path.display())),
135    };
136    let mtime = meta
137        .modified()
138        .map_err(|e| format!("cannot read mtime of {}: {e}", start_path.display()))?;
139    let mtime_secs = mtime
140        .duration_since(std::time::UNIX_EPOCH)
141        .map_err(|e| {
142            format!(
143                "mtime of {} is before UNIX_EPOCH: {e}",
144                start_path.display()
145            )
146        })?
147        .as_secs();
148    Ok(mtime_secs > refused_at)
149}
150
151enum IdStatus {
152    Finished(String),
153    Refused(String),
154    Running,
155    LooksDead,
156    Unknown,
157    Corrupt(String),
158}
159
160fn check_id_status(wt: &Path, id: &str) -> IdStatus {
161    let start_path = wt.join(format!("{id}.start.json"));
162    let refused_path = wt.join(format!("{id}.refused.json"));
163    match read_refusal(&refused_path) {
164        Ok(Some(refusal)) => match start_newer_than_refusal(&start_path, refusal.refused_at) {
165            Ok(true) => {}
166            Ok(false) => return IdStatus::Refused(refusal.error),
167            Err(e) => return IdStatus::Corrupt(e),
168        },
169        Ok(None) => {}
170        Err(e) => return IdStatus::Corrupt(e),
171    }
172
173    let summary_path = wt.join(format!("{id}.json"));
174    match read_summary(&summary_path) {
175        SummaryState::Ready(summary) => match format_summary_line(&summary_path, id, &summary) {
176            Ok(line) => return IdStatus::Finished(line),
177            Err(e) => return IdStatus::Corrupt(e),
178        },
179        SummaryState::Corrupt(e) => return IdStatus::Corrupt(e),
180        SummaryState::InProgress => return IdStatus::Running,
181        SummaryState::Absent => {}
182    }
183
184    match check_start_alive(&start_path) {
185        Ok(Some(true)) => IdStatus::Running,
186        Ok(Some(false)) => match read_summary(&summary_path) {
187            SummaryState::Ready(summary) => {
188                match format_summary_line(&summary_path, id, &summary) {
189                    Ok(line) => IdStatus::Finished(line),
190                    Err(e) => IdStatus::Corrupt(e),
191                }
192            }
193            SummaryState::Corrupt(e) => IdStatus::Corrupt(e),
194            SummaryState::InProgress => IdStatus::Running,
195            SummaryState::Absent => IdStatus::LooksDead,
196        },
197        Ok(None) => IdStatus::Unknown,
198        Err(e) => IdStatus::Corrupt(e),
199    }
200}
201
202fn is_known(wt: &Path, id: &str) -> bool {
203    wt.join(format!("{id}.json")).exists()
204        || wt.join(format!("{id}.start.json")).exists()
205        || wt.join(format!("{id}.refused.json")).exists()
206}
207
208#[allow(clippy::too_many_arguments)]
209pub fn wait_in(
210    wt: &Path,
211    ids: &[String],
212    any: bool,
213    timeout: Duration,
214    poll: Duration,
215    grace: Duration,
216    out: &mut impl Write,
217    err: &mut impl Write,
218) -> i32 {
219    let mut unique_ids: Vec<&str> = Vec::new();
220    let mut seen = HashSet::new();
221    for id in ids {
222        if seen.insert(id.as_str()) {
223            unique_ids.push(id.as_str());
224        }
225    }
226
227    if unique_ids.is_empty() {
228        return 0;
229    }
230
231    let start_time = Instant::now();
232    let mut printed = vec![false; unique_ids.len()];
233    let mut first_dead = vec![None; unique_ids.len()];
234    let mut printed_count = 0;
235
236    loop {
237        let mut printed_this_poll = false;
238        for (i, id) in unique_ids.iter().enumerate() {
239            if printed[i] {
240                continue;
241            }
242            match check_id_status(wt, id) {
243                IdStatus::Finished(line) => {
244                    let _ = writeln!(out, "{line}");
245                    let _ = out.flush();
246                    printed[i] = true;
247                    first_dead[i] = None;
248                    printed_count += 1;
249                    printed_this_poll = true;
250                }
251                IdStatus::Refused(error) => {
252                    let _ = writeln!(out, "{id} refused - -");
253                    let _ = out.flush();
254                    let _ = writeln!(err, "{id}: {error}");
255                    let _ = err.flush();
256                    printed[i] = true;
257                    first_dead[i] = None;
258                    printed_count += 1;
259                    printed_this_poll = true;
260                }
261                IdStatus::Running => {
262                    first_dead[i] = None;
263                }
264                IdStatus::LooksDead => {
265                    let first_seen = *first_dead[i].get_or_insert_with(Instant::now);
266                    if grace.is_zero() || first_seen.elapsed() >= grace {
267                        let _ = writeln!(out, "{id} dead - -");
268                        let _ = out.flush();
269                        printed[i] = true;
270                        first_dead[i] = None;
271                        printed_count += 1;
272                        printed_this_poll = true;
273                    }
274                }
275                IdStatus::Unknown => {
276                    first_dead[i] = None;
277                }
278                IdStatus::Corrupt(msg) => {
279                    let _ = writeln!(err, "error: {msg}");
280                    let _ = err.flush();
281                    return 1;
282                }
283            }
284        }
285
286        if printed_count == unique_ids.len() {
287            return 0;
288        }
289
290        if any && printed_this_poll {
291            return 0;
292        }
293
294        let elapsed = start_time.elapsed();
295
296        if elapsed >= timeout && timeout < grace {
297            let unprinted: Vec<&str> = unique_ids
298                .iter()
299                .enumerate()
300                .filter(|(i, _)| !printed[*i])
301                .map(|(_, id)| *id)
302                .collect();
303            let _ = writeln!(err, "still running: {}", unprinted.join(" "));
304            let _ = err.flush();
305            return 2;
306        }
307
308        if elapsed >= grace {
309            let unknown_ids: Vec<&str> = unique_ids
310                .iter()
311                .enumerate()
312                .filter(|(i, id)| !printed[*i] && !is_known(wt, id))
313                .map(|(_, id)| *id)
314                .collect();
315            if !unknown_ids.is_empty() {
316                for id in unknown_ids {
317                    let _ = writeln!(err, "no dispatch {id} here");
318                }
319                let _ = err.flush();
320                return 1;
321            }
322        }
323
324        if elapsed >= timeout {
325            let unprinted: Vec<&str> = unique_ids
326                .iter()
327                .enumerate()
328                .filter(|(i, _)| !printed[*i])
329                .map(|(_, id)| *id)
330                .collect();
331            let _ = writeln!(err, "still running: {}", unprinted.join(" "));
332            let _ = err.flush();
333            return 2;
334        }
335
336        let remaining = timeout.saturating_sub(start_time.elapsed());
337        let sleep_dur = poll.min(remaining);
338        std::thread::sleep(sleep_dur);
339    }
340}
341
342#[cfg(test)]
343mod tests {
344    use super::*;
345
346    #[test]
347    fn finished_run_prints_summary_line() {
348        let dir = tempfile::tempdir().unwrap();
349        let wt = dir.path();
350        std::fs::write(
351            wt.join("T1.json"),
352            r#"{"outcome":"verified","turns":41,"cost_usd":0.374}"#,
353        )
354        .unwrap();
355        let mut out = Vec::new();
356        let mut err = Vec::new();
357        let code = wait_in(
358            wt,
359            &["T1".to_string()],
360            false,
361            Duration::from_secs(5),
362            Duration::from_millis(10),
363            Duration::ZERO,
364            &mut out,
365            &mut err,
366        );
367        assert_eq!(code, 0);
368        assert_eq!(String::from_utf8(out).unwrap(), "T1 verified 41 $0.37\n");
369        assert!(err.is_empty());
370    }
371
372    #[test]
373    fn missing_cost_prints_dash() {
374        let dir = tempfile::tempdir().unwrap();
375        let wt = dir.path();
376        std::fs::write(
377            wt.join("T1.json"),
378            r#"{"outcome":"gate_failed","turns":7,"cost_usd":null}"#,
379        )
380        .unwrap();
381        let mut out = Vec::new();
382        let mut err = Vec::new();
383        let code = wait_in(
384            wt,
385            &["T1".to_string()],
386            false,
387            Duration::from_secs(5),
388            Duration::from_millis(10),
389            Duration::ZERO,
390            &mut out,
391            &mut err,
392        );
393        assert_eq!(code, 0);
394        assert_eq!(String::from_utf8(out).unwrap(), "T1 gate_failed 7 -\n");
395        assert!(err.is_empty());
396    }
397
398    #[test]
399    fn dead_run() {
400        let dir = tempfile::tempdir().unwrap();
401        let wt = dir.path();
402        let mut child = std::process::Command::new("true").spawn().unwrap();
403        let pid = child.id();
404        child.wait().unwrap();
405        std::fs::write(wt.join("T1.start.json"), format!(r#"{{"pid": {pid}}}"#)).unwrap();
406        let mut out = Vec::new();
407        let mut err = Vec::new();
408        let code = wait_in(
409            wt,
410            &["T1".to_string()],
411            false,
412            Duration::from_secs(5),
413            Duration::from_millis(10),
414            Duration::ZERO,
415            &mut out,
416            &mut err,
417        );
418        assert_eq!(code, 0);
419        assert_eq!(String::from_utf8(out).unwrap(), "T1 dead - -\n");
420        assert!(err.is_empty());
421    }
422
423    #[test]
424    fn zero_pid_is_dead() {
425        let dir = tempfile::tempdir().unwrap();
426        let wt = dir.path();
427        std::fs::write(wt.join("T1.start.json"), r#"{"pid": 0}"#).unwrap();
428        let mut out = Vec::new();
429        let mut err = Vec::new();
430        let code = wait_in(
431            wt,
432            &["T1".to_string()],
433            false,
434            Duration::from_secs(5),
435            Duration::from_millis(10),
436            Duration::ZERO,
437            &mut out,
438            &mut err,
439        );
440        assert_eq!(code, 0);
441        assert_eq!(String::from_utf8(out).unwrap(), "T1 dead - -\n");
442        assert!(err.is_empty());
443    }
444
445    #[test]
446    fn unknown_id_errors_without_waiting() {
447        let dir = tempfile::tempdir().unwrap();
448        let wt = dir.path();
449        let mut out = Vec::new();
450        let mut err = Vec::new();
451        let start = Instant::now();
452        let code = wait_in(
453            wt,
454            &["T9".to_string()],
455            false,
456            Duration::from_secs(5),
457            Duration::from_millis(10),
458            Duration::from_millis(50),
459            &mut out,
460            &mut err,
461        );
462        let elapsed = start.elapsed();
463        assert_eq!(code, 1);
464        let err_str = String::from_utf8(err).unwrap();
465        assert!(err_str.contains("no dispatch T9 here"));
466        assert!(out.is_empty());
467        assert!(elapsed < Duration::from_secs(1));
468    }
469
470    #[test]
471    fn timeout_with_running_run() {
472        let dir = tempfile::tempdir().unwrap();
473        let wt = dir.path();
474        let pid = std::process::id();
475        std::fs::write(wt.join("T1.start.json"), format!(r#"{{"pid": {pid}}}"#)).unwrap();
476        let mut out = Vec::new();
477        let mut err = Vec::new();
478        let code = wait_in(
479            wt,
480            &["T1".to_string()],
481            false,
482            Duration::from_millis(50),
483            Duration::from_millis(10),
484            Duration::ZERO,
485            &mut out,
486            &mut err,
487        );
488        assert_eq!(code, 2);
489        assert!(out.is_empty());
490        let err_str = String::from_utf8(err).unwrap();
491        assert!(err_str.contains("still running: T1"));
492    }
493
494    #[test]
495    fn all_mode_waits_for_every_run() {
496        let dir = tempfile::tempdir().unwrap();
497        let wt = dir.path();
498        std::fs::write(
499            wt.join("T1.json"),
500            r#"{"outcome":"verified","turns":41,"cost_usd":0.374}"#,
501        )
502        .unwrap();
503        let pid = std::process::id();
504        std::fs::write(wt.join("T2.start.json"), format!(r#"{{"pid": {pid}}}"#)).unwrap();
505        let wt_clone = wt.to_path_buf();
506        std::thread::spawn(move || {
507            std::thread::sleep(Duration::from_millis(100));
508            std::fs::write(
509                wt_clone.join("T2.json"),
510                r#"{"outcome":"verified","turns":10,"cost_usd":0.10}"#,
511            )
512            .unwrap();
513        });
514        let mut out = Vec::new();
515        let mut err = Vec::new();
516        let code = wait_in(
517            wt,
518            &["T1".to_string(), "T2".to_string()],
519            false,
520            Duration::from_secs(5),
521            Duration::from_millis(10),
522            Duration::ZERO,
523            &mut out,
524            &mut err,
525        );
526        assert_eq!(code, 0);
527        let out_str = String::from_utf8(out).unwrap();
528        assert_eq!(out_str, "T1 verified 41 $0.37\nT2 verified 10 $0.10\n");
529        assert!(err.is_empty());
530    }
531
532    #[test]
533    fn any_mode_returns_after_first() {
534        let dir = tempfile::tempdir().unwrap();
535        let wt = dir.path();
536        let pid = std::process::id();
537        std::fs::write(wt.join("T1.start.json"), format!(r#"{{"pid": {pid}}}"#)).unwrap();
538        std::fs::write(
539            wt.join("T2.json"),
540            r#"{"outcome":"verified","turns":12,"cost_usd":0.20}"#,
541        )
542        .unwrap();
543        let mut out = Vec::new();
544        let mut err = Vec::new();
545        let code = wait_in(
546            wt,
547            &["T1".to_string(), "T2".to_string()],
548            true,
549            Duration::from_secs(5),
550            Duration::from_millis(10),
551            Duration::ZERO,
552            &mut out,
553            &mut err,
554        );
555        assert_eq!(code, 0);
556        assert_eq!(String::from_utf8(out).unwrap(), "T2 verified 12 $0.20\n");
557        assert!(err.is_empty());
558    }
559
560    #[test]
561    fn any_mode_prints_all_already_finished() {
562        let dir = tempfile::tempdir().unwrap();
563        let wt = dir.path();
564        std::fs::write(
565            wt.join("T1.json"),
566            r#"{"outcome":"verified","turns":1,"cost_usd":0.01}"#,
567        )
568        .unwrap();
569        std::fs::write(
570            wt.join("T2.json"),
571            r#"{"outcome":"gate_failed","turns":2,"cost_usd":0.02}"#,
572        )
573        .unwrap();
574        let mut out = Vec::new();
575        let mut err = Vec::new();
576        let code = wait_in(
577            wt,
578            &["T1".to_string(), "T2".to_string()],
579            true,
580            Duration::from_secs(5),
581            Duration::from_millis(10),
582            Duration::ZERO,
583            &mut out,
584            &mut err,
585        );
586        assert_eq!(code, 0);
587        let out_str = String::from_utf8(out).unwrap();
588        let lines: Vec<&str> = out_str.lines().collect();
589        assert_eq!(lines, vec!["T1 verified 1 $0.01", "T2 gate_failed 2 $0.02"]);
590        assert!(err.is_empty());
591    }
592
593    #[test]
594    fn any_mode_timeout() {
595        let dir = tempfile::tempdir().unwrap();
596        let wt = dir.path();
597        let pid = std::process::id();
598        std::fs::write(wt.join("T1.start.json"), format!(r#"{{"pid": {pid}}}"#)).unwrap();
599        let mut out = Vec::new();
600        let mut err = Vec::new();
601        let code = wait_in(
602            wt,
603            &["T1".to_string()],
604            true,
605            Duration::from_millis(50),
606            Duration::from_millis(10),
607            Duration::ZERO,
608            &mut out,
609            &mut err,
610        );
611        assert_eq!(code, 2);
612        assert!(out.is_empty());
613        let err_str = String::from_utf8(err).unwrap();
614        assert!(err_str.contains("still running: T1"));
615    }
616
617    #[test]
618    fn summary_written_after_start_counts_as_finished() {
619        let dir = tempfile::tempdir().unwrap();
620        let wt = dir.path();
621        let mut child = std::process::Command::new("true").spawn().unwrap();
622        let pid = child.id();
623        child.wait().unwrap();
624        std::fs::write(wt.join("T1.start.json"), format!(r#"{{"pid": {pid}}}"#)).unwrap();
625        std::fs::write(
626            wt.join("T1.json"),
627            r#"{"outcome":"verified","turns":5,"cost_usd":0.05}"#,
628        )
629        .unwrap();
630        let mut out = Vec::new();
631        let mut err = Vec::new();
632        let code = wait_in(
633            wt,
634            &["T1".to_string()],
635            false,
636            Duration::from_secs(5),
637            Duration::from_millis(10),
638            Duration::ZERO,
639            &mut out,
640            &mut err,
641        );
642        assert_eq!(code, 0);
643        assert_eq!(String::from_utf8(out).unwrap(), "T1 verified 5 $0.05\n");
644        assert!(err.is_empty());
645    }
646
647    #[test]
648    fn unparseable_summary_is_not_finished() {
649        let dir = tempfile::tempdir().unwrap();
650        let wt = dir.path();
651        std::fs::write(wt.join("T1.json"), r#"{"outc"#).unwrap();
652        let pid = std::process::id();
653        std::fs::write(wt.join("T1.start.json"), format!(r#"{{"pid": {pid}}}"#)).unwrap();
654        let mut out = Vec::new();
655        let mut err = Vec::new();
656        let code = wait_in(
657            wt,
658            &["T1".to_string()],
659            false,
660            Duration::from_millis(50),
661            Duration::from_millis(10),
662            Duration::ZERO,
663            &mut out,
664            &mut err,
665        );
666        assert_eq!(code, 2);
667        assert!(out.is_empty());
668        let err_str = String::from_utf8(err).unwrap();
669        assert!(err_str.contains("still running: T1"));
670    }
671
672    #[test]
673    fn duplicate_ids_reported_once() {
674        let dir = tempfile::tempdir().unwrap();
675        let wt = dir.path();
676        std::fs::write(
677            wt.join("T1.json"),
678            r#"{"outcome":"verified","turns":41,"cost_usd":0.374}"#,
679        )
680        .unwrap();
681        let mut out = Vec::new();
682        let mut err = Vec::new();
683        let code = wait_in(
684            wt,
685            &["T1".to_string(), "T1".to_string()],
686            false,
687            Duration::from_secs(5),
688            Duration::from_millis(10),
689            Duration::ZERO,
690            &mut out,
691            &mut err,
692        );
693        assert_eq!(code, 0);
694        assert_eq!(String::from_utf8(out).unwrap(), "T1 verified 41 $0.37\n");
695        assert!(err.is_empty());
696    }
697
698    #[test]
699    fn finishing_run_within_grace_reports_summary() {
700        let dir = tempfile::tempdir().unwrap();
701        let wt = dir.path();
702        let mut child = std::process::Command::new("true").spawn().unwrap();
703        let pid = child.id();
704        child.wait().unwrap();
705        std::fs::write(wt.join("T1.start.json"), format!(r#"{{"pid": {pid}}}"#)).unwrap();
706        let wt_clone = wt.to_path_buf();
707        std::thread::spawn(move || {
708            std::thread::sleep(Duration::from_millis(100));
709            std::fs::write(
710                wt_clone.join("T1.json"),
711                r#"{"outcome":"verified","turns":3,"cost_usd":0.1}"#,
712            )
713            .unwrap();
714        });
715        let mut out = Vec::new();
716        let mut err = Vec::new();
717        let code = wait_in(
718            wt,
719            &["T1".to_string()],
720            false,
721            Duration::from_secs(5),
722            Duration::from_millis(10),
723            Duration::from_secs(2),
724            &mut out,
725            &mut err,
726        );
727        assert_eq!(code, 0);
728        assert_eq!(String::from_utf8(out).unwrap(), "T1 verified 3 $0.10\n");
729        assert!(err.is_empty());
730    }
731
732    #[test]
733    fn dead_run_reported_after_grace() {
734        let dir = tempfile::tempdir().unwrap();
735        let wt = dir.path();
736        let mut child = std::process::Command::new("true").spawn().unwrap();
737        let pid = child.id();
738        child.wait().unwrap();
739        std::fs::write(wt.join("T1.start.json"), format!(r#"{{"pid": {pid}}}"#)).unwrap();
740        let mut out = Vec::new();
741        let mut err = Vec::new();
742        let start = Instant::now();
743        let code = wait_in(
744            wt,
745            &["T1".to_string()],
746            false,
747            Duration::from_secs(5),
748            Duration::from_millis(10),
749            Duration::from_millis(150),
750            &mut out,
751            &mut err,
752        );
753        let elapsed = start.elapsed();
754        assert_eq!(code, 0);
755        assert_eq!(String::from_utf8(out).unwrap(), "T1 dead - -\n");
756        assert!(elapsed >= Duration::from_millis(150));
757        assert!(err.is_empty());
758    }
759
760    #[test]
761    fn timeout_inside_grace_is_still_running() {
762        let dir = tempfile::tempdir().unwrap();
763        let wt = dir.path();
764        let mut child = std::process::Command::new("true").spawn().unwrap();
765        let pid = child.id();
766        child.wait().unwrap();
767        std::fs::write(wt.join("T1.start.json"), format!(r#"{{"pid": {pid}}}"#)).unwrap();
768        let mut out = Vec::new();
769        let mut err = Vec::new();
770        let code = wait_in(
771            wt,
772            &["T1".to_string()],
773            false,
774            Duration::from_millis(100),
775            Duration::from_millis(10),
776            Duration::from_secs(5),
777            &mut out,
778            &mut err,
779        );
780        assert_eq!(code, 2);
781        assert!(out.is_empty());
782        let err_str = String::from_utf8(err).unwrap();
783        assert!(err_str.contains("still running: T1"));
784    }
785
786    #[test]
787    fn summary_without_start_file_written_after_start() {
788        let dir = tempfile::tempdir().unwrap();
789        let wt = dir.path();
790        let wt_clone = wt.to_path_buf();
791        std::thread::spawn(move || {
792            std::thread::sleep(Duration::from_millis(100));
793            std::fs::write(
794                wt_clone.join("T1.json"),
795                r#"{"outcome":"verified","turns":15,"cost_usd":0.25}"#,
796            )
797            .unwrap();
798        });
799        let mut out = Vec::new();
800        let mut err = Vec::new();
801        let code = wait_in(
802            wt,
803            &["T1".to_string()],
804            false,
805            Duration::from_secs(5),
806            Duration::from_millis(10),
807            Duration::from_secs(2),
808            &mut out,
809            &mut err,
810        );
811        assert_eq!(code, 0);
812        assert_eq!(String::from_utf8(out).unwrap(), "T1 verified 15 $0.25\n");
813        assert!(err.is_empty());
814    }
815
816    #[test]
817    fn one_summary_one_never_appearing() {
818        let dir = tempfile::tempdir().unwrap();
819        let wt = dir.path();
820        std::fs::write(
821            wt.join("T1.json"),
822            r#"{"outcome":"verified","turns":10,"cost_usd":0.10}"#,
823        )
824        .unwrap();
825        let mut out = Vec::new();
826        let mut err = Vec::new();
827        let code = wait_in(
828            wt,
829            &["T1".to_string(), "T2".to_string()],
830            false,
831            Duration::from_secs(5),
832            Duration::from_millis(10),
833            Duration::from_millis(50),
834            &mut out,
835            &mut err,
836        );
837        assert_eq!(code, 1);
838        let err_str = String::from_utf8(err).unwrap();
839        assert!(err_str.contains("no dispatch T2 here"));
840        assert!(!err_str.contains("no dispatch T1 here"));
841        assert_eq!(String::from_utf8(out).unwrap(), "T1 verified 10 $0.10\n");
842    }
843
844    #[test]
845    fn timeout_before_grace_with_unknown_id() {
846        let dir = tempfile::tempdir().unwrap();
847        let wt = dir.path();
848        let mut out = Vec::new();
849        let mut err = Vec::new();
850        let code = wait_in(
851            wt,
852            &["T9".to_string()],
853            false,
854            Duration::from_millis(50),
855            Duration::from_millis(10),
856            Duration::from_secs(5),
857            &mut out,
858            &mut err,
859        );
860        assert_eq!(code, 2);
861        assert!(out.is_empty());
862        let err_str = String::from_utf8(err).unwrap();
863        assert!(err_str.contains("still running: T9"));
864    }
865
866    #[test]
867    fn multiple_unknown_ids_reported_in_argument_order() {
868        let dir = tempfile::tempdir().unwrap();
869        let wt = dir.path();
870        let mut out = Vec::new();
871        let mut err = Vec::new();
872        let code = wait_in(
873            wt,
874            &["B".to_string(), "A".to_string()],
875            false,
876            Duration::from_secs(5),
877            Duration::from_millis(10),
878            Duration::from_millis(50),
879            &mut out,
880            &mut err,
881        );
882        assert_eq!(code, 1);
883        assert!(out.is_empty());
884        let err_str = String::from_utf8(err).unwrap();
885        assert_eq!(err_str, "no dispatch B here\nno dispatch A here\n");
886    }
887
888    #[test]
889    fn cli_parses_wait() {
890        use crate::cli::{Cli, Command};
891        use clap::Parser;
892
893        let cli =
894            Cli::try_parse_from(["blyte", "wait", "A", "B", "--any", "--timeout", "10"]).unwrap();
895        assert_eq!(
896            cli.command,
897            Some(Command::Wait {
898                ids: vec!["A".to_string(), "B".to_string()],
899                any: true,
900                timeout: 10,
901            })
902        );
903
904        let cli = Cli::try_parse_from(["blyte", "wait", "A"]).unwrap();
905        assert_eq!(
906            cli.command,
907            Some(Command::Wait {
908                ids: vec!["A".to_string()],
909                any: false,
910                timeout: 280,
911            })
912        );
913
914        assert!(Cli::try_parse_from(["blyte", "wait"]).is_err());
915    }
916
917    fn set_older_than_window(path: &Path) {
918        let old_time = SystemTime::now() - Duration::from_secs(10);
919        let file = std::fs::OpenOptions::new().write(true).open(path).unwrap();
920        file.set_modified(old_time).unwrap();
921    }
922
923    #[test]
924    fn missing_outcome_in_summary_exits_1_and_names_file_and_field() {
925        let dir = tempfile::tempdir().unwrap();
926        let wt = dir.path();
927        let path = wt.join("X.json");
928        std::fs::write(&path, r#"{"id":"X"}"#).unwrap();
929        set_older_than_window(&path);
930
931        let mut out = Vec::new();
932        let mut err = Vec::new();
933        let code = wait_in(
934            wt,
935            &["X".to_string()],
936            false,
937            Duration::from_secs(5),
938            Duration::from_millis(10),
939            Duration::ZERO,
940            &mut out,
941            &mut err,
942        );
943        let out_str = String::from_utf8(out).unwrap();
944        let err_str = String::from_utf8(err).unwrap();
945        assert_eq!(code, 1, "stdout={out_str:?} stderr={err_str:?}");
946        assert!(!out_str.contains('?'), "stdout={out_str:?}");
947        assert!(!err_str.contains('?'), "stderr={err_str:?}");
948        assert!(
949            err_str.contains(&path.display().to_string()),
950            "stderr={err_str:?}"
951        );
952        assert!(err_str.contains("outcome"), "stderr={err_str:?}");
953    }
954
955    #[test]
956    fn missing_turns_in_summary_exits_1_and_names_file_and_field() {
957        let dir = tempfile::tempdir().unwrap();
958        let wt = dir.path();
959        let path = wt.join("X.json");
960        std::fs::write(&path, r#"{"id":"X","outcome":"verified"}"#).unwrap();
961        set_older_than_window(&path);
962
963        let mut out = Vec::new();
964        let mut err = Vec::new();
965        let code = wait_in(
966            wt,
967            &["X".to_string()],
968            false,
969            Duration::from_secs(5),
970            Duration::from_millis(10),
971            Duration::ZERO,
972            &mut out,
973            &mut err,
974        );
975        let out_str = String::from_utf8(out).unwrap();
976        let err_str = String::from_utf8(err).unwrap();
977        assert_eq!(code, 1, "stdout={out_str:?} stderr={err_str:?}");
978        assert!(!out_str.contains('?'), "stdout={out_str:?}");
979        assert!(!err_str.contains('?'), "stderr={err_str:?}");
980        assert!(
981            err_str.contains(&path.display().to_string()),
982            "stderr={err_str:?}"
983        );
984        assert!(err_str.contains("turns"), "stderr={err_str:?}");
985    }
986
987    #[test]
988    fn old_corrupt_summary_json_exits_1_and_names_file() {
989        let dir = tempfile::tempdir().unwrap();
990        let wt = dir.path();
991        let path = wt.join("X.json");
992        std::fs::write(&path, r#"{"outc"#).unwrap();
993        set_older_than_window(&path);
994
995        let mut out = Vec::new();
996        let mut err = Vec::new();
997        let code = wait_in(
998            wt,
999            &["X".to_string()],
1000            false,
1001            Duration::from_secs(5),
1002            Duration::from_millis(10),
1003            Duration::ZERO,
1004            &mut out,
1005            &mut err,
1006        );
1007        let out_str = String::from_utf8(out).unwrap();
1008        let err_str = String::from_utf8(err).unwrap();
1009        assert_eq!(code, 1, "stdout={out_str:?} stderr={err_str:?}");
1010        assert!(out_str.is_empty(), "stdout={out_str:?}");
1011        assert!(
1012            err_str.contains(&path.display().to_string()),
1013            "stderr={err_str:?}"
1014        );
1015    }
1016
1017    #[test]
1018    fn corrupt_start_json_exits_1_and_names_file() {
1019        let dir = tempfile::tempdir().unwrap();
1020        let wt = dir.path();
1021        let start_path = wt.join("X.start.json");
1022        std::fs::write(&start_path, "{broken").unwrap();
1023
1024        let mut out = Vec::new();
1025        let mut err = Vec::new();
1026        let code = wait_in(
1027            wt,
1028            &["X".to_string()],
1029            false,
1030            Duration::from_secs(5),
1031            Duration::from_millis(10),
1032            Duration::ZERO,
1033            &mut out,
1034            &mut err,
1035        );
1036        let out_str = String::from_utf8(out).unwrap();
1037        let err_str = String::from_utf8(err).unwrap();
1038        assert_eq!(code, 1, "stdout={out_str:?} stderr={err_str:?}");
1039        assert!(out_str.is_empty(), "stdout={out_str:?}");
1040        assert!(
1041            err_str.contains(&start_path.display().to_string()),
1042            "stderr={err_str:?}"
1043        );
1044    }
1045
1046    #[test]
1047    fn refused_run_prints_refused_line() {
1048        let dir = tempfile::tempdir().unwrap();
1049        let wt = dir.path();
1050        std::fs::write(
1051            wt.join("T1.refused.json"),
1052            r#"{"id":"T1","refused_at":1700000000,"error":"error: branch wip/T1 already exists"}"#,
1053        )
1054        .unwrap();
1055        let mut out = Vec::new();
1056        let mut err = Vec::new();
1057        let code = wait_in(
1058            wt,
1059            &["T1".to_string()],
1060            false,
1061            Duration::from_secs(5),
1062            Duration::from_millis(10),
1063            Duration::ZERO,
1064            &mut out,
1065            &mut err,
1066        );
1067        assert_eq!(code, 0);
1068        assert_eq!(String::from_utf8(out).unwrap(), "T1 refused - -\n");
1069        assert_eq!(
1070            String::from_utf8(err).unwrap(),
1071            "T1: error: branch wip/T1 already exists\n"
1072        );
1073    }
1074
1075    #[test]
1076    fn run_started_after_refusal_is_not_refused() {
1077        let dir = tempfile::tempdir().unwrap();
1078        let wt = dir.path();
1079        std::fs::write(
1080            wt.join("T1.refused.json"),
1081            r#"{"id":"T1","refused_at":1,"error":"error: branch wip/T1 already exists"}"#,
1082        )
1083        .unwrap();
1084        let pid = std::process::id();
1085        std::fs::write(wt.join("T1.start.json"), format!(r#"{{"pid": {pid}}}"#)).unwrap();
1086        let mut out = Vec::new();
1087        let mut err = Vec::new();
1088        let code = wait_in(
1089            wt,
1090            &["T1".to_string()],
1091            false,
1092            Duration::from_millis(50),
1093            Duration::from_millis(10),
1094            Duration::ZERO,
1095            &mut out,
1096            &mut err,
1097        );
1098        let out_str = String::from_utf8(out).unwrap();
1099        let err_str = String::from_utf8(err).unwrap();
1100        assert_eq!(code, 2, "stdout={out_str:?} stderr={err_str:?}");
1101        assert!(!out_str.contains("refused"), "stdout={out_str:?}");
1102        assert!(err_str.contains("still running: T1"), "stderr={err_str:?}");
1103    }
1104
1105    #[test]
1106    fn unparsable_refusal_is_corrupt() {
1107        let dir = tempfile::tempdir().unwrap();
1108        let wt = dir.path();
1109        let refused_path = wt.join("T1.refused.json");
1110        std::fs::write(&refused_path, "not json").unwrap();
1111        let mut out = Vec::new();
1112        let mut err = Vec::new();
1113        let code = wait_in(
1114            wt,
1115            &["T1".to_string()],
1116            false,
1117            Duration::from_secs(5),
1118            Duration::from_millis(10),
1119            Duration::ZERO,
1120            &mut out,
1121            &mut err,
1122        );
1123        let out_str = String::from_utf8(out).unwrap();
1124        let err_str = String::from_utf8(err).unwrap();
1125        assert_eq!(code, 1, "stdout={out_str:?} stderr={err_str:?}");
1126        assert!(out_str.is_empty(), "stdout={out_str:?}");
1127        assert!(
1128            err_str.contains(&refused_path.display().to_string()),
1129            "stderr={err_str:?}"
1130        );
1131    }
1132}