Skip to main content

blyte_cli/
live_runs.rs

1use std::io::ErrorKind;
2use std::path::Path;
3use std::time::UNIX_EPOCH;
4
5use crate::dashboard::{collect_jobs, repo_name, Sources};
6use crate::replay::{classify_jobs, group_of, Run, Skipped};
7
8#[derive(Clone, Debug, serde::Serialize)]
9pub struct LiveRuns {
10    pub generated_at: u64,
11    pub repo: String,
12    pub running: Vec<RunningRun>,
13    pub runs: Vec<Run>,
14    pub skipped: Vec<Skipped>,
15}
16
17#[derive(Clone, Debug, serde::Serialize)]
18pub struct RunningRun {
19    pub key: String,
20    pub id: String,
21    pub research: bool,
22    pub title: String,
23    pub task: String,
24    pub plan_file: Option<String>,
25    pub plan_task: Option<String>,
26    pub request: Option<String>,
27    pub started_at: Option<u64>,
28    pub turns: u64,
29    pub gate_running: bool,
30    pub activity: String,
31}
32
33pub fn collect(root: &Path, now: u64, days: u64) -> Result<LiveRuns, String> {
34    if !root.is_dir() {
35        return Err(format!("not a directory: {}", root.display()));
36    }
37
38    let repo = repo_name(root);
39    let wt_dir = root.join(".wt");
40    if !wt_dir.is_dir() {
41        return Ok(LiveRuns {
42            generated_at: now,
43            repo,
44            running: Vec::new(),
45            runs: Vec::new(),
46            skipped: Vec::new(),
47        });
48    }
49
50    let expected_root = wt_dir.parent();
51    let src = Sources {
52        roots: vec![root.to_path_buf()],
53        runs_dirs: Vec::new(),
54        hours: days.saturating_mul(24),
55    };
56    let jobs = collect_jobs(&src, now)
57        .into_iter()
58        .filter(|job| job.root.as_deref() == expected_root)
59        .collect();
60
61    let (running_jobs, mut runs, mut skipped) = classify_jobs(jobs, now, days);
62
63    let mut running: Vec<RunningRun> = running_jobs
64        .into_iter()
65        .map(|job| RunningRun {
66            key: job.key,
67            id: job.id,
68            research: job.research,
69            title: job.title,
70            task: job.task,
71            plan_file: job.plan_file,
72            plan_task: job.plan_task,
73            request: job.request,
74            started_at: job.started_at,
75            turns: job.turns,
76            gate_running: job.gate_running,
77            activity: job.now,
78        })
79        .collect();
80
81    running.sort_by(|a, b| {
82        a.started_at
83            .unwrap_or(u64::MAX)
84            .cmp(&b.started_at.unwrap_or(u64::MAX))
85            .then_with(|| a.key.cmp(&b.key))
86    });
87    runs.sort_by(|a, b| {
88        b.finished_at
89            .cmp(&a.finished_at)
90            .then_with(|| a.key.cmp(&b.key))
91    });
92    skipped.sort_by(|a, b| a.key.cmp(&b.key));
93
94    Ok(LiveRuns {
95        generated_at: now,
96        repo,
97        running,
98        runs,
99        skipped,
100    })
101}
102
103fn file_mtime(path: &Path) -> Option<u64> {
104    std::fs::metadata(path)
105        .ok()?
106        .modified()
107        .ok()?
108        .duration_since(UNIX_EPOCH)
109        .ok()
110        .map(|d| d.as_secs())
111}
112
113fn non_empty_str(val: Option<&serde_json::Value>) -> Option<String> {
114    val.and_then(|v| v.as_str())
115        .map(str::trim)
116        .filter(|s| !s.is_empty())
117        .map(String::from)
118}
119
120fn title_from_task(task: &str, id: &str) -> String {
121    for line in task.lines() {
122        let trimmed = line.trim().trim_start_matches('#').trim();
123        if !trimmed.is_empty() {
124            return trimmed.chars().take(120).collect();
125        }
126    }
127    id.to_string()
128}
129
130fn parse_running_log(path: &Path) -> Result<(u64, bool, String), String> {
131    let text = match std::fs::read_to_string(path) {
132        Ok(t) => t,
133        Err(e) if e.kind() == ErrorKind::NotFound => return Ok((0, false, String::new())),
134        Err(e) => return Err(format!("log unreadable ({}): {e}", path.display())),
135    };
136    let mut turns: u64 = 0;
137    let mut gate_running = false;
138    let mut activity = String::new();
139    for line in text.lines() {
140        let trimmed = line.trim();
141        if trimmed.is_empty() {
142            continue;
143        }
144        if trimmed.starts_with("== turn ") || trimmed.starts_with("turn ") {
145            turns = turns.saturating_add(1);
146        }
147        if trimmed.starts_with("== gate") {
148            gate_running = true;
149        } else if trimmed.starts_with("== ") {
150            gate_running = false;
151        }
152        activity = trimmed.chars().take(120).collect();
153    }
154    Ok((turns, gate_running, activity))
155}
156
157fn parse_summary_seconds(val: &serde_json::Value) -> Result<u64, String> {
158    let Some(sec_val) = val.get("seconds") else {
159        return Err("missing seconds".to_string());
160    };
161    if let Some(n) = sec_val.as_u64() {
162        return Ok(n);
163    }
164    if let Some(f) = sec_val.as_f64() {
165        if f.is_finite() && f >= 0.0 && f < (u64::MAX as f64) {
166            return Ok(f.floor() as u64);
167        }
168        return Err("seconds must be a non-negative finite number".to_string());
169    }
170    Err("seconds is not a number".to_string())
171}
172
173pub fn collect_in_place(
174    root: &Path,
175    records_dir: &Path,
176    now: u64,
177    days: u64,
178) -> Result<LiveRuns, String> {
179    if !root.is_dir() {
180        return Err(format!("not a directory: {}", root.display()));
181    }
182
183    let repo = repo_name(root);
184    if !records_dir.is_dir() {
185        return Ok(LiveRuns {
186            generated_at: now,
187            repo,
188            running: Vec::new(),
189            runs: Vec::new(),
190            skipped: Vec::new(),
191        });
192    }
193
194    let cutoff = now.saturating_sub(days.saturating_mul(86_400));
195    let mut start_entries: Vec<(String, std::path::PathBuf)> = Vec::new();
196    let rd = std::fs::read_dir(records_dir)
197        .map_err(|e| format!("cannot read {}: {e}", records_dir.display()))?;
198    for entry in rd {
199        let entry = entry.map_err(|e| format!("cannot read {}: {e}", records_dir.display()))?;
200        let fname = entry.file_name().to_string_lossy().to_string();
201        if let Some(id) = fname.strip_suffix(".start.json") {
202            if !id.is_empty() {
203                start_entries.push((id.to_string(), entry.path()));
204            }
205        }
206    }
207    start_entries.sort_by(|a, b| a.0.cmp(&b.0));
208
209    let mut running = Vec::new();
210    let mut runs = Vec::new();
211    let mut skipped = Vec::new();
212
213    for (id, start_path) in start_entries {
214        let key = format!("{repo}/{id}");
215        let start_raw = match std::fs::read_to_string(&start_path) {
216            Ok(s) => s,
217            Err(e) => {
218                skipped.push(Skipped {
219                    key,
220                    reason: format!("start file unreadable: {e}"),
221                });
222                continue;
223            }
224        };
225        let start_val: serde_json::Value = match serde_json::from_str(&start_raw) {
226            Ok(v) => v,
227            Err(e) => {
228                skipped.push(Skipped {
229                    key,
230                    reason: format!("start file unreadable: {e}"),
231                });
232                continue;
233            }
234        };
235
236        let started_at = start_val
237            .get("started_at")
238            .and_then(|v| v.as_u64())
239            .or_else(|| file_mtime(&start_path));
240        if started_at.is_some_and(|s| s < cutoff) {
241            continue;
242        }
243
244        let research = match crate::in_place_review::parse_research_flag(&start_val, &start_path) {
245            Ok(b) => b,
246            Err(err) => {
247                skipped.push(Skipped {
248                    key,
249                    reason: format!("start file unreadable: {err}"),
250                });
251                continue;
252            }
253        };
254        let plan_file = non_empty_str(start_val.get("plan"));
255        let plan_task = non_empty_str(start_val.get("plan_task"));
256        let request = non_empty_str(start_val.get("request"));
257
258        let task_path = match start_val.get("task_file") {
259            None | Some(serde_json::Value::Null) => records_dir.join(format!("{id}.task.md")),
260            Some(serde_json::Value::String(s)) if s.is_empty() => {
261                records_dir.join(format!("{id}.task.md"))
262            }
263            Some(serde_json::Value::String(s)) => std::path::PathBuf::from(s),
264            Some(_) => {
265                skipped.push(Skipped {
266                    key,
267                    reason: "start file unreadable: task_file is not a string".to_string(),
268                });
269                continue;
270            }
271        };
272        let task = match std::fs::read_to_string(&task_path) {
273            Ok(t) => t,
274            Err(e) => {
275                skipped.push(Skipped {
276                    key,
277                    reason: format!("task file unreadable ({}): {e}", task_path.display()),
278                });
279                continue;
280            }
281        };
282        let title = title_from_task(&task, &id);
283
284        let summary_path = records_dir.join(format!("{id}.json"));
285        if !summary_path.exists() {
286            let pid = start_val.get("pid").and_then(|v| v.as_i64());
287            let is_alive = pid.is_some_and(crate::clean::is_pid_alive);
288            if is_alive {
289                let (turns, gate_running, activity) =
290                    match parse_running_log(&records_dir.join(format!("{id}.log"))) {
291                        Ok(parsed) => parsed,
292                        Err(reason) => {
293                            skipped.push(Skipped { key, reason });
294                            continue;
295                        }
296                    };
297                running.push(RunningRun {
298                    key,
299                    id,
300                    research,
301                    title,
302                    task,
303                    plan_file,
304                    plan_task,
305                    request,
306                    started_at,
307                    turns,
308                    gate_running,
309                    activity,
310                });
311            } else {
312                skipped.push(Skipped {
313                    key,
314                    reason: "no summary file".to_string(),
315                });
316            }
317            continue;
318        }
319
320        let Some(started_at) = started_at else {
321            skipped.push(Skipped {
322                key,
323                reason: "no start time".to_string(),
324            });
325            continue;
326        };
327
328        let summary_raw = match std::fs::read_to_string(&summary_path) {
329            Ok(s) => s,
330            Err(e) => {
331                skipped.push(Skipped {
332                    key,
333                    reason: format!("summary unreadable: {e}"),
334                });
335                continue;
336            }
337        };
338        let summary_val: serde_json::Value = match serde_json::from_str(&summary_raw) {
339            Ok(v) => v,
340            Err(e) => {
341                skipped.push(Skipped {
342                    key,
343                    reason: format!("summary unreadable: {e}"),
344                });
345                continue;
346            }
347        };
348        let outcome = match summary_val.get("outcome").and_then(|v| v.as_str()) {
349            Some(s) if !s.is_empty() => s.to_string(),
350            Some(_) => {
351                skipped.push(Skipped {
352                    key,
353                    reason: "summary unreadable: empty outcome".to_string(),
354                });
355                continue;
356            }
357            None => {
358                skipped.push(Skipped {
359                    key,
360                    reason: "summary unreadable: missing outcome".to_string(),
361                });
362                continue;
363            }
364        };
365        let seconds = match parse_summary_seconds(&summary_val) {
366            Ok(s) => s,
367            Err(err) => {
368                skipped.push(Skipped {
369                    key,
370                    reason: format!("summary unreadable: {err}"),
371                });
372                continue;
373            }
374        };
375        let Some(finished_at) = started_at.checked_add(seconds) else {
376            skipped.push(Skipped {
377                key,
378                reason: "summary unreadable: finished_at overflow".to_string(),
379            });
380            continue;
381        };
382        let final_message = match summary_val.get("final_message") {
383            None | Some(serde_json::Value::Null) => None,
384            Some(serde_json::Value::String(s)) => Some(s.clone()),
385            Some(_) => {
386                skipped.push(Skipped {
387                    key,
388                    reason: "summary unreadable: final_message is not a string".to_string(),
389                });
390                continue;
391            }
392        };
393        let turns = match summary_val.get("turns") {
394            Some(v) => match v.as_u64() {
395                Some(n) => n,
396                None => {
397                    skipped.push(Skipped {
398                        key,
399                        reason: "summary unreadable: turns is not a non-negative integer"
400                            .to_string(),
401                    });
402                    continue;
403                }
404            },
405            None => {
406                skipped.push(Skipped {
407                    key,
408                    reason: "summary unreadable: missing turns".to_string(),
409                });
410                continue;
411            }
412        };
413        let cost_usd = summary_val.get("cost_usd").and_then(|v| v.as_f64());
414        let mut changed_files = Vec::new();
415        if let Some(arr) = summary_val.get("changed_files").and_then(|v| v.as_array()) {
416            for item in arr {
417                if let Some(s) = item.as_str() {
418                    changed_files.push(s.to_string());
419                }
420            }
421        }
422
423        let (checks_recorded, flags) = match crate::in_place_review::checks_for_run(
424            root,
425            records_dir,
426            &id,
427            &summary_val,
428            &summary_path,
429        ) {
430            Ok(c) => (true, c.flags),
431            Err(err) => {
432                skipped.push(Skipped {
433                    key,
434                    reason: format!("checks unreadable: {err}"),
435                });
436                continue;
437            }
438        };
439
440        let verdict_path = records_dir.join(format!("{id}.verdict.json"));
441        let (verdict, verdict_notes, verdict_ts) = match std::fs::read_to_string(&verdict_path) {
442            Ok(raw) => match serde_json::from_str::<serde_json::Value>(&raw) {
443                Ok(val) => {
444                    let v = match val.get("verdict").and_then(|x| x.as_str()) {
445                        Some(s) if !s.is_empty() => Some(s.to_string()),
446                        _ => {
447                            skipped.push(Skipped {
448                                key,
449                                reason: format!(
450                                    "verdict unreadable ({}): missing or invalid verdict",
451                                    verdict_path.display()
452                                ),
453                            });
454                            continue;
455                        }
456                    };
457                    let notes = match val.get("notes") {
458                        None | Some(serde_json::Value::Null) => None,
459                        Some(serde_json::Value::String(s)) => Some(s.clone()),
460                        Some(_) => {
461                            skipped.push(Skipped {
462                                key,
463                                reason: format!(
464                                    "verdict unreadable ({}): notes is not a string",
465                                    verdict_path.display()
466                                ),
467                            });
468                            continue;
469                        }
470                    };
471                    let ts = match val.get("ts") {
472                        Some(x) => match x.as_u64() {
473                            Some(n) => Some(n),
474                            None => {
475                                skipped.push(Skipped {
476                                    key,
477                                    reason: format!(
478                                        "verdict unreadable ({}): ts is not a non-negative integer",
479                                        verdict_path.display()
480                                    ),
481                                });
482                                continue;
483                            }
484                        },
485                        None => {
486                            skipped.push(Skipped {
487                                key,
488                                reason: format!(
489                                    "verdict unreadable ({}): missing ts",
490                                    verdict_path.display()
491                                ),
492                            });
493                            continue;
494                        }
495                    };
496                    (v, notes, ts)
497                }
498                Err(e) => {
499                    skipped.push(Skipped {
500                        key,
501                        reason: format!("verdict unreadable ({}): {e}", verdict_path.display()),
502                    });
503                    continue;
504                }
505            },
506            Err(e) if e.kind() == ErrorKind::NotFound => (None, None, None),
507            Err(e) => {
508                skipped.push(Skipped {
509                    key,
510                    reason: format!("verdict unreadable ({}): {e}", verdict_path.display()),
511                });
512                continue;
513            }
514        };
515
516        let report = if research {
517            let report_path = records_dir.join(format!("{id}.report.md"));
518            match std::fs::read_to_string(&report_path) {
519                Ok(content) => Some(content),
520                Err(e) if e.kind() == ErrorKind::NotFound => None,
521                Err(e) => {
522                    skipped.push(Skipped {
523                        key,
524                        reason: format!("report unreadable: {e}"),
525                    });
526                    continue;
527                }
528            }
529        } else {
530            None
531        };
532
533        let group = group_of(&changed_files);
534        let card = if research {
535            "research".to_string()
536        } else if matches!(outcome.as_str(), "verified" | "finished")
537            && checks_recorded
538            && flags.is_empty()
539        {
540            "clean".to_string()
541        } else {
542            "exception".to_string()
543        };
544
545        runs.push(Run {
546            key,
547            id,
548            repo: repo.clone(),
549            research,
550            title,
551            task,
552            plan_file,
553            plan_task,
554            request,
555            started_at,
556            finished_at,
557            outcome,
558            final_message,
559            turns,
560            cost_usd,
561            commits: Vec::new(),
562            changed_files,
563            group,
564            checks_recorded,
565            flags,
566            card,
567            verdict,
568            verdict_notes,
569            verdict_ts,
570            report,
571        });
572    }
573
574    running.sort_by(|a, b| {
575        a.started_at
576            .unwrap_or(u64::MAX)
577            .cmp(&b.started_at.unwrap_or(u64::MAX))
578            .then_with(|| a.key.cmp(&b.key))
579    });
580    runs.sort_by(|a, b| {
581        b.finished_at
582            .cmp(&a.finished_at)
583            .then_with(|| a.key.cmp(&b.key))
584    });
585    skipped.sort_by(|a, b| a.key.cmp(&b.key));
586
587    Ok(LiveRuns {
588        generated_at: now,
589        repo,
590        running,
591        runs,
592        skipped,
593    })
594}