Skip to main content

blyte_cli/
replay.rs

1use std::collections::BTreeMap;
2use std::io::ErrorKind;
3use std::path::Path;
4
5use serde::Serialize;
6
7use crate::dashboard::{collect_jobs, CommitRecord, Sources};
8
9#[derive(Debug, Serialize, PartialEq)]
10pub struct Replay {
11    pub exported_at: u64,
12    pub window_days: u64,
13    pub skipped: Vec<Skipped>,
14    pub runs: Vec<Run>,
15}
16
17#[derive(Debug, Serialize, PartialEq)]
18pub struct Skipped {
19    pub key: String,
20    pub reason: String,
21}
22
23#[derive(Debug, Serialize, PartialEq)]
24pub struct Run {
25    pub key: String,
26    pub id: String,
27    pub repo: String,
28    pub research: bool,
29    pub title: String,
30    pub task: String,
31    pub plan_file: Option<String>,
32    pub plan_task: Option<String>,
33    pub started_at: u64,
34    pub finished_at: u64,
35    pub outcome: String,
36    pub final_message: Option<String>,
37    pub turns: u64,
38    pub cost_usd: Option<f64>,
39    pub commits: Vec<CommitRecord>,
40    pub changed_files: Vec<String>,
41    pub group: Option<String>,
42    pub checks_recorded: bool,
43    pub flags: Vec<String>,
44    pub card: String,
45    pub verdict: Option<String>,
46    pub verdict_notes: Option<String>,
47    pub verdict_ts: Option<u64>,
48    pub report: Option<String>,
49}
50
51fn file_group(file: &str) -> String {
52    let parts: Vec<&str> = file.split('/').filter(|p| !p.is_empty()).collect();
53    if parts.len() >= 3 && parts[0] == "crates" {
54        format!("crates/{}", parts[1])
55    } else if parts.len() >= 2 {
56        parts[0].to_string()
57    } else {
58        ".".to_string()
59    }
60}
61
62pub fn group_of(changed_files: &[String]) -> Option<String> {
63    if changed_files.is_empty() {
64        return None;
65    }
66    let mut counts: BTreeMap<String, usize> = BTreeMap::new();
67    for file in changed_files {
68        *counts.entry(file_group(file)).or_insert(0) += 1;
69    }
70    let mut best: Option<(String, usize)> = None;
71    for (group, count) in counts {
72        let replace = match &best {
73            None => true,
74            Some((_, best_count)) => count > *best_count,
75        };
76        if replace {
77            best = Some((group, count));
78        }
79    }
80    best.map(|(group, _)| group)
81}
82
83pub fn card_of(outcome: &str, checks_recorded: bool, flags: &[String]) -> &'static str {
84    if outcome == "verified" && checks_recorded && flags.is_empty() {
85        "clean"
86    } else {
87        "exception"
88    }
89}
90
91pub fn card_for_run(
92    research: bool,
93    outcome: &str,
94    checks_recorded: bool,
95    flags: &[String],
96) -> &'static str {
97    if research {
98        "research"
99    } else {
100        card_of(outcome, checks_recorded, flags)
101    }
102}
103
104struct DispatchSummaryFields {
105    outcome: String,
106    seconds: u64,
107    final_message: Option<String>,
108}
109
110enum SummaryReadError {
111    Missing,
112    Unreadable(String),
113}
114
115fn parse_seconds(val: &serde_json::Value) -> Result<u64, String> {
116    let Some(sec_val) = val.get("seconds") else {
117        return Err("missing seconds".to_string());
118    };
119    if let Some(n) = sec_val.as_u64() {
120        return Ok(n);
121    }
122    if let Some(f) = sec_val.as_f64() {
123        if f.is_finite() && f >= 0.0 && f < (u64::MAX as f64) {
124            return Ok(f.floor() as u64);
125        }
126        return Err("seconds must be a non-negative finite number".to_string());
127    }
128    Err("seconds is not a number".to_string())
129}
130
131fn read_summary(path: &Path) -> Result<DispatchSummaryFields, SummaryReadError> {
132    let raw = match std::fs::read_to_string(path) {
133        Ok(s) => s,
134        Err(e) if e.kind() == ErrorKind::NotFound => return Err(SummaryReadError::Missing),
135        Err(e) => return Err(SummaryReadError::Unreadable(e.to_string())),
136    };
137    let val: serde_json::Value =
138        serde_json::from_str(&raw).map_err(|e| SummaryReadError::Unreadable(e.to_string()))?;
139    let outcome = match val.get("outcome").and_then(|v| v.as_str()) {
140        Some(s) if !s.is_empty() => s.to_string(),
141        Some(_) => return Err(SummaryReadError::Unreadable("empty outcome".to_string())),
142        None => return Err(SummaryReadError::Unreadable("missing outcome".to_string())),
143    };
144    let seconds = parse_seconds(&val).map_err(SummaryReadError::Unreadable)?;
145    let final_message = match val.get("final_message") {
146        None | Some(serde_json::Value::Null) => None,
147        Some(serde_json::Value::String(s)) => Some(s.clone()),
148        Some(_) => {
149            return Err(SummaryReadError::Unreadable(
150                "final_message is not a string".to_string(),
151            ));
152        }
153    };
154    Ok(DispatchSummaryFields {
155        outcome,
156        seconds,
157        final_message,
158    })
159}
160
161fn read_checks(path: &Path) -> Result<(bool, Vec<String>), String> {
162    let raw = match std::fs::read_to_string(path) {
163        Ok(s) => s,
164        Err(e) if e.kind() == ErrorKind::NotFound => return Ok((false, Vec::new())),
165        Err(e) => return Err(e.to_string()),
166    };
167    let val: serde_json::Value = serde_json::from_str(&raw).map_err(|e| e.to_string())?;
168    let Some(arr) = val.get("flags").and_then(|v| v.as_array()) else {
169        return Err("missing flags array".to_string());
170    };
171    let mut flags = Vec::with_capacity(arr.len());
172    for item in arr {
173        let Some(s) = item.as_str() else {
174            return Err("flags entry is not a string".to_string());
175        };
176        flags.push(s.to_string());
177    }
178    Ok((true, flags))
179}
180
181fn read_report(path: &Path) -> Result<Option<String>, String> {
182    match std::fs::read_to_string(path) {
183        Ok(content) => Ok(Some(content)),
184        Err(e) if e.kind() == ErrorKind::NotFound => Ok(None),
185        Err(e) => Err(e.to_string()),
186    }
187}
188
189pub fn collect(src: &Sources, now: u64, days: u64) -> Replay {
190    let mut windowed = src.clone();
191    windowed.hours = days.saturating_mul(24);
192    let jobs = collect_jobs(&windowed, now);
193    let cutoff = now.saturating_sub(days.saturating_mul(86_400));
194
195    let mut runs = Vec::new();
196    let mut skipped = Vec::new();
197
198    for job in jobs {
199        if job.started_at.is_some_and(|s| s < cutoff) {
200            continue;
201        }
202
203        if job.status == "running" {
204            skipped.push(Skipped {
205                key: job.key,
206                reason: "still running".to_string(),
207            });
208            continue;
209        }
210
211        let Some(root) = job.root else {
212            skipped.push(Skipped {
213                key: job.key,
214                reason: "no root".to_string(),
215            });
216            continue;
217        };
218
219        let Some(started_at) = job.started_at else {
220            skipped.push(Skipped {
221                key: job.key,
222                reason: "no start time".to_string(),
223            });
224            continue;
225        };
226
227        let summary_path = root.join(".wt").join(format!("{}.json", job.id));
228        let summary = match read_summary(&summary_path) {
229            Ok(s) => s,
230            Err(SummaryReadError::Missing) => {
231                skipped.push(Skipped {
232                    key: job.key,
233                    reason: "no summary file".to_string(),
234                });
235                continue;
236            }
237            Err(SummaryReadError::Unreadable(err)) => {
238                skipped.push(Skipped {
239                    key: job.key,
240                    reason: format!("summary unreadable: {err}"),
241                });
242                continue;
243            }
244        };
245
246        let Some(finished_at) = started_at.checked_add(summary.seconds) else {
247            skipped.push(Skipped {
248                key: job.key,
249                reason: "summary unreadable: finished_at overflow".to_string(),
250            });
251            continue;
252        };
253
254        let checks_path = root.join(".wt").join(format!("{}.checks.json", job.id));
255        let (checks_recorded, flags) = match read_checks(&checks_path) {
256            Ok(c) => c,
257            Err(err) => {
258                skipped.push(Skipped {
259                    key: job.key,
260                    reason: format!("checks unreadable: {err}"),
261                });
262                continue;
263            }
264        };
265
266        let report = if job.research {
267            let report_path = root.join(".wt").join(format!("{}.report.md", job.id));
268            match read_report(&report_path) {
269                Ok(r) => r,
270                Err(err) => {
271                    skipped.push(Skipped {
272                        key: job.key,
273                        reason: format!("report unreadable: {err}"),
274                    });
275                    continue;
276                }
277            }
278        } else {
279            None
280        };
281
282        let group = group_of(&job.changed_files);
283        let card =
284            card_for_run(job.research, &summary.outcome, checks_recorded, &flags).to_string();
285
286        runs.push(Run {
287            key: job.key,
288            id: job.id,
289            repo: job.repo,
290            research: job.research,
291            title: job.title,
292            task: job.task,
293            plan_file: job.plan_file,
294            plan_task: job.plan_task,
295            started_at,
296            finished_at,
297            outcome: summary.outcome,
298            final_message: summary.final_message,
299            turns: job.turns,
300            cost_usd: job.cost_usd,
301            commits: job.commits,
302            changed_files: job.changed_files,
303            group,
304            checks_recorded,
305            flags,
306            card,
307            verdict: job.verdict,
308            verdict_notes: job.verdict_notes,
309            verdict_ts: job.verdict_ts,
310            report,
311        });
312    }
313
314    runs.sort_by(|a, b| {
315        a.started_at
316            .cmp(&b.started_at)
317            .then_with(|| a.key.cmp(&b.key))
318    });
319    skipped.sort_by(|a, b| a.key.cmp(&b.key));
320
321    Replay {
322        exported_at: now,
323        window_days: days,
324        skipped,
325        runs,
326    }
327}