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 is_alive = match crate::clean::run_process_alive(&start_val) {
287 Ok(alive) => alive,
288 Err(err) => {
289 skipped.push(Skipped {
290 key,
291 reason: format!("start file unreadable: {err}"),
292 });
293 continue;
294 }
295 };
296 if is_alive {
297 let (turns, gate_running, activity) =
298 match parse_running_log(&records_dir.join(format!("{id}.log"))) {
299 Ok(parsed) => parsed,
300 Err(reason) => {
301 skipped.push(Skipped { key, reason });
302 continue;
303 }
304 };
305 running.push(RunningRun {
306 key,
307 id,
308 research,
309 title,
310 task,
311 plan_file,
312 plan_task,
313 request,
314 started_at,
315 turns,
316 gate_running,
317 activity,
318 });
319 } else {
320 skipped.push(Skipped {
321 key,
322 reason: "no summary file".to_string(),
323 });
324 }
325 continue;
326 }
327
328 let Some(started_at) = started_at else {
329 skipped.push(Skipped {
330 key,
331 reason: "no start time".to_string(),
332 });
333 continue;
334 };
335
336 let summary_raw = match std::fs::read_to_string(&summary_path) {
337 Ok(s) => s,
338 Err(e) => {
339 skipped.push(Skipped {
340 key,
341 reason: format!("summary unreadable: {e}"),
342 });
343 continue;
344 }
345 };
346 let summary_val: serde_json::Value = match serde_json::from_str(&summary_raw) {
347 Ok(v) => v,
348 Err(e) => {
349 skipped.push(Skipped {
350 key,
351 reason: format!("summary unreadable: {e}"),
352 });
353 continue;
354 }
355 };
356 let outcome = match summary_val.get("outcome").and_then(|v| v.as_str()) {
357 Some(s) if !s.is_empty() => s.to_string(),
358 Some(_) => {
359 skipped.push(Skipped {
360 key,
361 reason: "summary unreadable: empty outcome".to_string(),
362 });
363 continue;
364 }
365 None => {
366 skipped.push(Skipped {
367 key,
368 reason: "summary unreadable: missing outcome".to_string(),
369 });
370 continue;
371 }
372 };
373 let seconds = match parse_summary_seconds(&summary_val) {
374 Ok(s) => s,
375 Err(err) => {
376 skipped.push(Skipped {
377 key,
378 reason: format!("summary unreadable: {err}"),
379 });
380 continue;
381 }
382 };
383 let Some(finished_at) = started_at.checked_add(seconds) else {
384 skipped.push(Skipped {
385 key,
386 reason: "summary unreadable: finished_at overflow".to_string(),
387 });
388 continue;
389 };
390 let final_message = match summary_val.get("final_message") {
391 None | Some(serde_json::Value::Null) => None,
392 Some(serde_json::Value::String(s)) => Some(s.clone()),
393 Some(_) => {
394 skipped.push(Skipped {
395 key,
396 reason: "summary unreadable: final_message is not a string".to_string(),
397 });
398 continue;
399 }
400 };
401 let turns = match summary_val.get("turns") {
402 Some(v) => match v.as_u64() {
403 Some(n) => n,
404 None => {
405 skipped.push(Skipped {
406 key,
407 reason: "summary unreadable: turns is not a non-negative integer"
408 .to_string(),
409 });
410 continue;
411 }
412 },
413 None => {
414 skipped.push(Skipped {
415 key,
416 reason: "summary unreadable: missing turns".to_string(),
417 });
418 continue;
419 }
420 };
421 let cost_usd = summary_val.get("cost_usd").and_then(|v| v.as_f64());
422 let mut changed_files = Vec::new();
423 if let Some(arr) = summary_val.get("changed_files").and_then(|v| v.as_array()) {
424 for item in arr {
425 if let Some(s) = item.as_str() {
426 changed_files.push(s.to_string());
427 }
428 }
429 }
430
431 let (checks_recorded, flags) = match crate::in_place_review::checks_for_run(
432 root,
433 records_dir,
434 &id,
435 &summary_val,
436 &summary_path,
437 ) {
438 Ok(c) => (true, c.flags),
439 Err(err) => {
440 skipped.push(Skipped {
441 key,
442 reason: format!("checks unreadable: {err}"),
443 });
444 continue;
445 }
446 };
447
448 let verdict_path = records_dir.join(format!("{id}.verdict.json"));
449 let (verdict, verdict_notes, verdict_ts) = match std::fs::read_to_string(&verdict_path) {
450 Ok(raw) => match serde_json::from_str::<serde_json::Value>(&raw) {
451 Ok(val) => {
452 let v = match val.get("verdict").and_then(|x| x.as_str()) {
453 Some(s) if !s.is_empty() => Some(s.to_string()),
454 _ => {
455 skipped.push(Skipped {
456 key,
457 reason: format!(
458 "verdict unreadable ({}): missing or invalid verdict",
459 verdict_path.display()
460 ),
461 });
462 continue;
463 }
464 };
465 let notes = match val.get("notes") {
466 None | Some(serde_json::Value::Null) => None,
467 Some(serde_json::Value::String(s)) => Some(s.clone()),
468 Some(_) => {
469 skipped.push(Skipped {
470 key,
471 reason: format!(
472 "verdict unreadable ({}): notes is not a string",
473 verdict_path.display()
474 ),
475 });
476 continue;
477 }
478 };
479 let ts = match val.get("ts") {
480 Some(x) => match x.as_u64() {
481 Some(n) => Some(n),
482 None => {
483 skipped.push(Skipped {
484 key,
485 reason: format!(
486 "verdict unreadable ({}): ts is not a non-negative integer",
487 verdict_path.display()
488 ),
489 });
490 continue;
491 }
492 },
493 None => {
494 skipped.push(Skipped {
495 key,
496 reason: format!(
497 "verdict unreadable ({}): missing ts",
498 verdict_path.display()
499 ),
500 });
501 continue;
502 }
503 };
504 (v, notes, ts)
505 }
506 Err(e) => {
507 skipped.push(Skipped {
508 key,
509 reason: format!("verdict unreadable ({}): {e}", verdict_path.display()),
510 });
511 continue;
512 }
513 },
514 Err(e) if e.kind() == ErrorKind::NotFound => (None, None, None),
515 Err(e) => {
516 skipped.push(Skipped {
517 key,
518 reason: format!("verdict unreadable ({}): {e}", verdict_path.display()),
519 });
520 continue;
521 }
522 };
523
524 let report = if research {
525 let report_path = records_dir.join(format!("{id}.report.md"));
526 match std::fs::read_to_string(&report_path) {
527 Ok(content) => Some(content),
528 Err(e) if e.kind() == ErrorKind::NotFound => None,
529 Err(e) => {
530 skipped.push(Skipped {
531 key,
532 reason: format!("report unreadable: {e}"),
533 });
534 continue;
535 }
536 }
537 } else {
538 None
539 };
540
541 let group = group_of(&changed_files);
542 let card = if research {
543 "research".to_string()
544 } else if matches!(outcome.as_str(), "verified" | "finished")
545 && checks_recorded
546 && flags.is_empty()
547 {
548 "clean".to_string()
549 } else {
550 "exception".to_string()
551 };
552
553 runs.push(Run {
554 key,
555 id,
556 repo: repo.clone(),
557 research,
558 title,
559 task,
560 plan_file,
561 plan_task,
562 request,
563 started_at,
564 finished_at,
565 outcome,
566 final_message,
567 turns,
568 cost_usd,
569 commits: Vec::new(),
570 changed_files,
571 group,
572 checks_recorded,
573 flags,
574 card,
575 verdict,
576 verdict_notes,
577 verdict_ts,
578 report,
579 });
580 }
581
582 running.sort_by(|a, b| {
583 a.started_at
584 .unwrap_or(u64::MAX)
585 .cmp(&b.started_at.unwrap_or(u64::MAX))
586 .then_with(|| a.key.cmp(&b.key))
587 });
588 runs.sort_by(|a, b| {
589 b.finished_at
590 .cmp(&a.finished_at)
591 .then_with(|| a.key.cmp(&b.key))
592 });
593 skipped.sort_by(|a, b| a.key.cmp(&b.key));
594
595 Ok(LiveRuns {
596 generated_at: now,
597 repo,
598 running,
599 runs,
600 skipped,
601 })
602}