Skip to main content

blyte_cli/
dashboard.rs

1//! `blyte dashboard` local HTTP server and job collector (plan 2026-09-30).
2
3use std::collections::HashSet;
4use std::io::{BufRead, Write};
5use std::path::{Path, PathBuf};
6use std::time::UNIX_EPOCH;
7
8#[derive(Debug, Clone)]
9pub struct Sources {
10    pub roots: Vec<PathBuf>,
11    pub runs_dirs: Vec<PathBuf>,
12    pub hours: u64,
13}
14
15#[derive(serde::Deserialize)]
16struct DashboardConfig {
17    roots: Option<Vec<String>>,
18    runs_dirs: Option<Vec<String>>,
19}
20
21fn expand_home(path_str: &str, home: &Path) -> PathBuf {
22    if let Some(rest) = path_str.strip_prefix("~/") {
23        home.join(rest)
24    } else if path_str == "~" {
25        home.to_path_buf()
26    } else {
27        PathBuf::from(path_str)
28    }
29}
30
31impl Sources {
32    pub fn from_args(args: &crate::cli::DashboardArgs) -> Self {
33        Self::from_args_with_where(args).0
34    }
35
36    pub fn from_args_with_where(args: &crate::cli::DashboardArgs) -> (Self, String) {
37        if !args.roots.is_empty() || !args.runs_dirs.is_empty() {
38            return (
39                Self {
40                    roots: args.roots.clone(),
41                    runs_dirs: args.runs_dirs.clone(),
42                    hours: args.hours,
43                },
44                "--root/--runs-dir".to_string(),
45            );
46        }
47
48        let mut roots = Vec::new();
49        let mut runs_dirs = Vec::new();
50        let mut dashboard_contributed = false;
51
52        if let Some(home) = std::env::var_os("HOME").map(PathBuf::from) {
53            let config_path = home.join(".config/blyte/dashboard.toml");
54            if let Ok(content) = std::fs::read_to_string(&config_path) {
55                if let Ok(cfg) = toml::from_str::<DashboardConfig>(&content) {
56                    if let Some(r) = cfg.roots {
57                        for p in r {
58                            let expanded = expand_home(&p, &home);
59                            if !roots.contains(&expanded) {
60                                roots.push(expanded);
61                                dashboard_contributed = true;
62                            }
63                        }
64                    }
65                    if let Some(d) = cfg.runs_dirs {
66                        for p in d {
67                            let expanded = expand_home(&p, &home);
68                            if !runs_dirs.contains(&expanded) {
69                                runs_dirs.push(expanded);
70                                dashboard_contributed = true;
71                            }
72                        }
73                    }
74                }
75            }
76        }
77
78        let mut dispatch_contributed = false;
79        for reg in crate::registry::registered() {
80            let already_listed = roots
81                .iter()
82                .any(|r| r == &reg || std::fs::canonicalize(r).map(|c| c == reg).unwrap_or(false));
83            if !already_listed {
84                roots.push(reg);
85                dispatch_contributed = true;
86            }
87        }
88
89        let mut parts = Vec::new();
90        if dashboard_contributed {
91            parts.push("dashboard.toml");
92        }
93        if dispatch_contributed {
94            parts.push("dispatch history");
95        }
96        let where_from = parts.join(" and ");
97
98        (
99            Self {
100                roots,
101                runs_dirs,
102                hours: args.hours,
103            },
104            where_from,
105        )
106    }
107}
108
109#[derive(serde::Serialize, serde::Deserialize, Debug, Clone, PartialEq, Eq)]
110pub struct CommitRecord {
111    pub sha: String,
112    pub subject: String,
113}
114
115#[derive(serde::Serialize, Debug, Clone)]
116pub struct Job {
117    pub key: String,
118    pub id: String,
119    pub repo: String,
120    pub status: String,
121    pub gate_running: bool,
122    pub title: String,
123    pub task: String,
124    pub plan: Option<String>,
125    pub now: String,
126    pub started_at: Option<u64>,
127    pub finished_at: Option<u64>,
128    pub elapsed_s: Option<u64>,
129    pub cost_usd: Option<f64>,
130    pub turns: u64,
131    pub gate_attempts: u64,
132    pub gate_failures: Vec<String>,
133    pub model: Option<String>,
134    pub last_tool: Option<String>,
135    pub worktree: Option<String>,
136    pub worktree_exists: Option<bool>,
137    pub log: String,
138    pub commits: Vec<CommitRecord>,
139    pub changed_files: Vec<String>,
140    pub tags: Vec<String>,
141    pub verdict: Option<String>,
142    pub problems: Vec<String>,
143    pub root: Option<PathBuf>,
144    pub plan_file: Option<String>,
145    pub plan_task: Option<String>,
146    pub request: Option<String>,
147    pub task_file: Option<String>,
148    #[serde(skip)]
149    pub research: bool,
150    #[serde(skip)]
151    pub start_plan: Option<String>,
152    #[serde(skip)]
153    pub file_tags: Vec<String>,
154    #[serde(skip)]
155    pub verdict_notes: Option<String>,
156    #[serde(skip)]
157    pub verdict_ts: Option<u64>,
158    #[serde(skip)]
159    pub log_mtime: Option<u64>,
160}
161
162#[derive(serde::Serialize, Debug, Clone)]
163pub struct Summary {
164    pub running: usize,
165    pub last_24h: usize,
166    pub repos: usize,
167    pub finished_24h: usize,
168    pub passed_24h: usize,
169    pub cost_24h_usd: f64,
170}
171
172#[derive(serde::Serialize, Debug, Clone)]
173pub struct DashboardResponse {
174    pub generated_at: u64,
175    pub summary: Summary,
176    pub jobs: Vec<Job>,
177}
178
179fn strip_ansi(s: &str) -> std::borrow::Cow<'_, str> {
180    let bytes = s.as_bytes();
181    let Some(first_esc) = bytes.iter().position(|&b| b == 0x1b) else {
182        return std::borrow::Cow::Borrowed(s);
183    };
184
185    let mut out = String::with_capacity(s.len());
186    let mut seg_start = 0;
187    let mut i = first_esc;
188
189    while i < bytes.len() {
190        if bytes[i] == 0x1b && i + 1 < bytes.len() && bytes[i + 1] == b'[' {
191            out.push_str(&s[seg_start..i]);
192            i += 2;
193            while i < bytes.len() {
194                let b = bytes[i];
195                if (0x40..=0x7e).contains(&b) {
196                    i += 1;
197                    break;
198                }
199                if b == b'\n' || b == 0x1b {
200                    out.push(b as char);
201                    i += 1;
202                    break;
203                }
204                i += 1;
205            }
206            seg_start = i;
207        } else {
208            i += 1;
209        }
210        if let Some(rel) = bytes[i..].iter().position(|&b| b == 0x1b) {
211            i += rel;
212        } else {
213            break;
214        }
215    }
216
217    out.push_str(&s[seg_start..]);
218    std::borrow::Cow::Owned(out)
219}
220
221fn extract_title(task: &str) -> String {
222    for line in task.lines() {
223        let trimmed = line.trim();
224        if let Some(pos) = trimmed.find("Task: \"") {
225            let rest = &trimmed[pos + "Task: \"".len()..];
226            if let Some(end) = rest.find('"') {
227                return rest[..end].chars().take(120).collect();
228            }
229        }
230    }
231    for line in task.lines() {
232        let trimmed = line.trim();
233        if trimmed.starts_with('#') {
234            let text = trimmed.trim_start_matches('#').trim();
235            if !text.is_empty() {
236                return text.chars().take(120).collect();
237            }
238        }
239    }
240    for line in task.lines() {
241        let trimmed = line.trim_start_matches(['#', ' ']).trim_end();
242        if !trimmed.is_empty() {
243            return trimmed.chars().take(120).collect();
244        }
245    }
246    String::new()
247}
248
249fn job_title(task: &str, id: &str) -> String {
250    let title = extract_title(task);
251    if id.is_empty() {
252        return title;
253    }
254    let p_colon = format!("Task {id}:");
255    let p_space = format!("Task {id} ");
256    let rest = if let Some(after) = title.strip_prefix(&p_colon) {
257        after.trim()
258    } else if let Some(after) = title.strip_prefix(&p_space) {
259        after.trim()
260    } else {
261        return title;
262    };
263    if rest.is_empty() {
264        title
265    } else {
266        rest.chars().take(120).collect()
267    }
268}
269
270fn extract_plan(task: &str) -> Option<String> {
271    for line in task.lines() {
272        let trimmed = line.trim();
273        if let Some(rest) = trimmed.strip_prefix("Plan: ") {
274            let plan = rest.trim();
275            if !plan.is_empty() {
276                return Some(plan.to_string());
277            }
278        }
279    }
280    None
281}
282
283fn extract_prompt_task_title(prompt: &str) -> Option<String> {
284    for line in prompt.lines() {
285        let trimmed = line.trim();
286        if let Some(pos) = trimmed.find("Task: \"") {
287            let rest = &trimmed[pos + "Task: \"".len()..];
288            if let Some(end) = rest.find('"') {
289                return Some(rest[..end].to_string());
290            }
291        }
292    }
293    None
294}
295
296fn extract_first_task_id(text: &str) -> Option<String> {
297    for line in text.lines() {
298        let plain = plain_line(line);
299        let mut idx = 0;
300        while let Some(pos) = plain[idx..].find("Task") {
301            let start = idx + pos;
302            let after = &plain[start + 4..];
303            if after.starts_with(' ') || after.starts_with('\t') {
304                let trimmed = after.trim_start();
305                let id: String = trimmed
306                    .chars()
307                    .take_while(|c| c.is_alphanumeric() || *c == '_' || *c == '-')
308                    .collect();
309                if !id.is_empty() {
310                    return Some(format!("Task {id}"));
311                }
312            }
313            idx = start + 4;
314        }
315    }
316    None
317}
318
319fn parse_heading(line: &str) -> Option<(usize, &str)> {
320    let trimmed = line.trim_start();
321    let hashes = trimmed.chars().take_while(|&c| c == '#').count();
322    if hashes > 0 {
323        let after = &trimmed[hashes..];
324        if after.is_empty() || after.starts_with(' ') || after.starts_with('\t') {
325            return Some((hashes, after.trim()));
326        }
327    }
328    None
329}
330
331fn extract_task_from_plan(plan_content: &str, title: &str) -> Option<String> {
332    let mut target_heading = None;
333    let mut offset = 0;
334
335    for line in plan_content.split_inclusive('\n') {
336        let line_len = line.len();
337        let trimmed = line.trim_end_matches(['\r', '\n']);
338        if let Some((level, text)) = parse_heading(trimmed) {
339            if text == title {
340                target_heading = Some((offset, level));
341                break;
342            }
343        }
344        offset += line_len;
345    }
346
347    let (start_offset, target_level) = target_heading?;
348
349    // A `#` line inside a fenced code block (a shell comment, say) is not a heading.
350    let mut end_offset = plan_content.len();
351    let mut curr_offset = 0;
352    let mut in_fence = false;
353    for line in plan_content.split_inclusive('\n') {
354        let line_len = line.len();
355        if line.trim_start().starts_with("```") {
356            in_fence = !in_fence;
357        } else if curr_offset > start_offset && !in_fence {
358            let trimmed = line.trim_end_matches(['\r', '\n']);
359            if let Some((level, _)) = parse_heading(trimmed) {
360                if level <= target_level {
361                    end_offset = curr_offset;
362                    break;
363                }
364            }
365        }
366        curr_offset += line_len;
367    }
368
369    Some(plan_content[start_offset..end_offset].to_string())
370}
371
372fn extract_now_from_final_message(msg: &str) -> String {
373    let pick = msg
374        .lines()
375        .map(str::trim)
376        .find(|l| !l.is_empty() && !l.starts_with('#'))
377        .or_else(|| msg.lines().map(str::trim).find(|l| !l.is_empty()))
378        .unwrap_or("");
379    plain_line(pick.trim_start_matches(['#', ' ']))
380        .chars()
381        .take(200)
382        .collect()
383}
384
385/// One line of markdown as plain text: no list marker, no `**`, `__` or backticks.
386fn plain_line(line: &str) -> String {
387    let mut l = line.trim();
388    if let Some(rest) = l.strip_prefix("- ").or_else(|| l.strip_prefix("* ")) {
389        l = rest;
390    } else if let Some((n, rest)) = l.split_once(". ") {
391        if !n.is_empty() && n.chars().all(|c| c.is_ascii_digit()) {
392            l = rest;
393        }
394    }
395    l.replace("**", "")
396        .replace("__", "")
397        .replace('`', "")
398        .trim()
399        .to_string()
400}
401
402struct LogInfo {
403    turns: u64,
404    last_tool: Option<String>,
405    gate_attempts: u64,
406    gate_running: bool,
407    mtime: Option<u64>,
408}
409
410enum OptionalFile<T> {
411    Missing,
412    Ok(T),
413    Err,
414}
415
416fn read_optional_string(path: &Path, problems: &mut Vec<String>) -> OptionalFile<String> {
417    match std::fs::read_to_string(path) {
418        Ok(s) => OptionalFile::Ok(s),
419        Err(e) if e.kind() == std::io::ErrorKind::NotFound => OptionalFile::Missing,
420        Err(e) => {
421            problems.push(format!("{}: {e}", path.display()));
422            OptionalFile::Err
423        }
424    }
425}
426
427fn read_optional_json<T: serde::de::DeserializeOwned>(
428    path: &Path,
429    problems: &mut Vec<String>,
430) -> OptionalFile<T> {
431    let raw = match read_optional_string(path, problems) {
432        OptionalFile::Missing => return OptionalFile::Missing,
433        OptionalFile::Err => return OptionalFile::Err,
434        OptionalFile::Ok(s) => s,
435    };
436    match serde_json::from_str(&raw) {
437        Ok(v) => OptionalFile::Ok(v),
438        Err(e) => {
439            problems.push(format!("{}: {e}", path.display()));
440            OptionalFile::Err
441        }
442    }
443}
444
445fn read_required_u64(
446    report: &serde_json::Value,
447    field: &str,
448    path: &Path,
449    problems: &mut Vec<String>,
450) -> u64 {
451    match report.get(field) {
452        Some(v) => match v.as_u64() {
453            Some(n) => n,
454            None => {
455                problems.push(format!(
456                    "{}: invalid '{field}' field (expected non-negative integer)",
457                    path.display()
458                ));
459                0
460            }
461        },
462        None => {
463            problems.push(format!(
464                "{}: missing required field '{field}'",
465                path.display()
466            ));
467            0
468        }
469    }
470}
471
472fn parse_log(path: &Path, problems: &mut Vec<String>) -> LogInfo {
473    let mtime = std::fs::metadata(path)
474        .ok()
475        .and_then(|m| m.modified().ok())
476        .and_then(|t| t.duration_since(UNIX_EPOCH).ok())
477        .map(|d| d.as_secs());
478
479    let raw = match read_optional_string(path, problems) {
480        OptionalFile::Ok(s) => s,
481        OptionalFile::Missing | OptionalFile::Err => String::new(),
482    };
483    let text = strip_ansi(&raw);
484
485    let mut max_turn = 0u64;
486    let mut last_tool = None;
487    let mut gate_attempts = 0u64;
488    let mut last_event_line: Option<String> = None;
489
490    for line in text.lines() {
491        let trimmed = line.trim();
492        if let Some(pos) = trimmed.find("[Turn ") {
493            let rest = &trimmed[pos + "[Turn ".len()..];
494            if let Some(end) = rest.find(']') {
495                if let Ok(n) = rest[..end].trim().parse::<u64>() {
496                    if n > max_turn {
497                        max_turn = n;
498                    }
499                }
500            }
501        }
502
503        if let Some(pos) = trimmed.find("● ") {
504            let tool = trimmed[pos + "● ".len()..].trim();
505            last_tool = Some(tool.chars().take(200).collect());
506        }
507
508        if trimmed.starts_with("✓ Gate passed") || trimmed.starts_with("✗ Gate failed") {
509            gate_attempts += 1;
510        }
511
512        if trimmed.contains("[Turn ")
513            || trimmed.contains("● ")
514            || trimmed.starts_with("⏳ Gate running")
515            || trimmed.starts_with("✓ Gate passed")
516            || trimmed.starts_with("✗ Gate failed")
517        {
518            last_event_line = Some(trimmed.to_string());
519        }
520    }
521
522    let gate_running = last_event_line
523        .map(|l| l.starts_with("⏳ Gate running"))
524        .unwrap_or(false);
525
526    LogInfo {
527        turns: max_turn,
528        last_tool,
529        gate_attempts,
530        gate_running,
531        mtime,
532    }
533}
534
535fn file_mtime(path: &Path) -> Option<u64> {
536    std::fs::metadata(path)
537        .ok()
538        .and_then(|m| m.modified().ok())
539        .and_then(|t| t.duration_since(UNIX_EPOCH).ok())
540        .map(|d| d.as_secs())
541}
542
543fn started_with_job(pid: i64, started_at: Option<u64>, now: u64) -> bool {
544    match (get_process_etime(pid), started_at) {
545        (Some(elapsed), Some(started_at)) => now.saturating_sub(elapsed) <= started_at + 60,
546        _ => true,
547    }
548}
549
550fn normalize_path(path: &Path) -> PathBuf {
551    let mut out = PathBuf::new();
552    for comp in path.components() {
553        match comp {
554            std::path::Component::CurDir => {}
555            std::path::Component::ParentDir => match out.components().next_back() {
556                Some(std::path::Component::Normal(_)) => {
557                    out.pop();
558                }
559                Some(std::path::Component::RootDir | std::path::Component::Prefix(_)) => {}
560                _ => out.push(comp.as_os_str()),
561            },
562            other => out.push(other.as_os_str()),
563        }
564    }
565    out
566}
567
568fn git_common_dir(start: &Path) -> Option<PathBuf> {
569    if !start.exists() {
570        return None;
571    }
572    let resolved_start = if start.is_absolute() {
573        start.to_path_buf()
574    } else {
575        std::fs::canonicalize(start).ok()?
576    };
577    for dir in resolved_start.ancestors() {
578        let dot_git = dir.join(".git");
579        let Ok(meta) = std::fs::metadata(&dot_git) else {
580            continue;
581        };
582        if meta.is_dir() {
583            return Some(
584                std::fs::canonicalize(&dot_git).unwrap_or_else(|_| normalize_path(&dot_git)),
585            );
586        }
587        if meta.is_file() {
588            let content = std::fs::read_to_string(&dot_git).ok()?;
589            let first_line = content.lines().next()?.trim();
590            let raw_gitdir = first_line.strip_prefix("gitdir:")?.trim();
591            if raw_gitdir.is_empty() {
592                return None;
593            }
594            let gitdir_path = Path::new(raw_gitdir);
595            let gitdir = if gitdir_path.is_absolute() {
596                gitdir_path.to_path_buf()
597            } else {
598                dir.join(gitdir_path)
599            };
600            let commondir_file = gitdir.join("commondir");
601            let common = if commondir_file.is_file() {
602                let raw_common = std::fs::read_to_string(&commondir_file).ok()?;
603                let trimmed = raw_common.trim();
604                if trimmed.is_empty() {
605                    gitdir
606                } else {
607                    let common_path = Path::new(trimmed);
608                    if common_path.is_absolute() {
609                        common_path.to_path_buf()
610                    } else {
611                        gitdir.join(common_path)
612                    }
613                }
614            } else {
615                gitdir
616            };
617            return Some(
618                std::fs::canonicalize(&common).unwrap_or_else(|_| normalize_path(&common)),
619            );
620        }
621    }
622    None
623}
624
625pub fn parse_etime(s: &str) -> Option<u64> {
626    let s = s.trim();
627    if s.is_empty() {
628        return None;
629    }
630
631    let (days, time_str) = match s.split_once('-') {
632        Some((d, rest)) => {
633            let days = d.parse::<u64>().ok()?;
634            (days, rest)
635        }
636        None => (0, s),
637    };
638
639    let parts: Vec<&str> = time_str.split(':').collect();
640    match parts.len() {
641        2 => {
642            let m = parts[0].parse::<u64>().ok()?;
643            let sec = parts[1].parse::<u64>().ok()?;
644            Some(days * 86400 + m * 60 + sec)
645        }
646        3 => {
647            let h = parts[0].parse::<u64>().ok()?;
648            let m = parts[1].parse::<u64>().ok()?;
649            let sec = parts[2].parse::<u64>().ok()?;
650            Some(days * 86400 + h * 3600 + m * 60 + sec)
651        }
652        _ => None,
653    }
654}
655
656fn get_process_etime(pid: i64) -> Option<u64> {
657    // macOS: ask the kernel for the start time. `ps` is setuid there, so blyte's own sandbox
658    // cannot run it, and this also saves a process per PID.
659    #[cfg(target_os = "macos")]
660    {
661        let mut info: libc::proc_bsdinfo = unsafe { std::mem::zeroed() };
662        let size = std::mem::size_of::<libc::proc_bsdinfo>() as libc::c_int;
663        let ret = unsafe {
664            libc::proc_pidinfo(
665                pid as libc::c_int,
666                libc::PROC_PIDTBSDINFO,
667                0,
668                &mut info as *mut _ as *mut libc::c_void,
669                size,
670            )
671        };
672        if ret == size && info.pbi_start_tvsec > 0 {
673            let now = std::time::SystemTime::now()
674                .duration_since(UNIX_EPOCH)
675                .map(|d| d.as_secs())
676                .unwrap_or(0);
677            return Some(now.saturating_sub(info.pbi_start_tvsec));
678        }
679    }
680
681    if let Ok(output) = std::process::Command::new("ps")
682        .args(["-o", "etime=", "-p", &pid.to_string()])
683        .output()
684    {
685        if output.status.success() {
686            let s = String::from_utf8_lossy(&output.stdout);
687            if let Some(sec) = parse_etime(&s) {
688                return Some(sec);
689            }
690        }
691    }
692
693    None
694}
695
696#[derive(serde::Deserialize, Debug)]
697struct AgySummary {
698    status: Option<String>,
699    error: Option<String>,
700    duration_seconds: Option<f64>,
701    num_turns: Option<u64>,
702    response: Option<String>,
703}
704
705struct RawJob {
706    id: String,
707    repo: String,
708    root: Option<PathBuf>,
709    task: String,
710    task_file: Option<String>,
711    pid: Option<i64>,
712    started_at: Option<u64>,
713    research: bool,
714    start_plan: Option<String>,
715    start_plan_task: Option<String>,
716    request: Option<String>,
717    file_tags: Vec<String>,
718    log_path: PathBuf,
719    report_path: PathBuf,
720    tags_path: PathBuf,
721    verdict_path: PathBuf,
722    worktree: Option<String>,
723    commits: Vec<CommitRecord>,
724    changed_files: Vec<String>,
725    summary_final_msg: Option<String>,
726    is_runs_dir: bool,
727    agy_summary_path: Option<PathBuf>,
728    problems: Vec<String>,
729    problem_mtime: Option<u64>,
730}
731
732pub fn repo_name(checkout: &Path) -> String {
733    let from_git = git_common_dir(checkout).and_then(|common| {
734        if common.file_name().and_then(|n| n.to_str()) == Some(".git") {
735            common
736                .parent()
737                .and_then(|p| p.file_name())
738                .and_then(|n| n.to_str())
739                .map(|n| n.to_string())
740        } else {
741            None
742        }
743    });
744
745    let raw = from_git.unwrap_or_else(|| {
746        checkout
747            .file_name()
748            .and_then(|n| n.to_str())
749            .map(|n| n.to_string())
750            .or_else(|| {
751                checkout
752                    .canonicalize()
753                    .ok()
754                    .as_deref()
755                    .and_then(Path::file_name)
756                    .and_then(|n| n.to_str())
757                    .map(|n| n.to_string())
758            })
759            .unwrap_or_else(|| "unknown".to_string())
760    });
761
762    if let Some((prefix, _)) = raw.split_once("--") {
763        if !prefix.is_empty() {
764            return prefix.to_string();
765        }
766    }
767    raw
768}
769
770pub fn collect_jobs(src: &Sources, now: u64) -> Vec<Job> {
771    let cutoff = now.saturating_sub(src.hours.saturating_mul(3600));
772    let mut raw_jobs = Vec::new();
773    let mut seen_keys = HashSet::new();
774
775    // 1. Dispatch layout
776    let mut wt_dirs = Vec::new();
777    for root in &src.roots {
778        let r_wt = root.join(".wt");
779        if r_wt.is_dir() && !wt_dirs.contains(&r_wt) {
780            wt_dirs.push(r_wt);
781        }
782        if let Ok(entries) = std::fs::read_dir(root) {
783            for entry in entries.flatten() {
784                let path = entry.path();
785                if path.is_dir() {
786                    let c_wt = path.join(".wt");
787                    if c_wt.is_dir() && !wt_dirs.contains(&c_wt) {
788                        wt_dirs.push(c_wt);
789                    }
790                }
791            }
792        }
793    }
794
795    for wt_dir in &wt_dirs {
796        let repo = wt_dir
797            .parent()
798            .map(repo_name)
799            .unwrap_or_else(|| "unknown".to_string());
800
801        if let Ok(entries) = std::fs::read_dir(wt_dir) {
802            for entry in entries.flatten() {
803                let fname = entry.file_name().to_string_lossy().to_string();
804                let id = if let Some(id) = fname.strip_suffix(".start.json") {
805                    Some(id)
806                } else if let Some(id) = fname.strip_suffix(".report.json") {
807                    (!id.ends_with(".fix") && !id.is_empty()).then_some(id)
808                } else {
809                    None
810                };
811                if let Some(id) = id {
812                    let id = id.to_string();
813                    let key = format!("{repo}/{id}");
814                    if !seen_keys.insert(key) {
815                        continue;
816                    }
817
818                    let report_path = wt_dir.join(format!("{id}.report.json"));
819                    let log_path = wt_dir.join(format!("{id}.log"));
820                    let report_mtime = file_mtime(&report_path);
821                    let log_mtime = file_mtime(&log_path);
822                    if report_mtime.is_some_and(|m| m < cutoff)
823                        && log_mtime.is_none_or(|m| m < cutoff)
824                    {
825                        continue;
826                    }
827
828                    let mut problems = Vec::new();
829                    let start_path = wt_dir.join(format!("{id}.start.json"));
830                    let start_val =
831                        match read_optional_json::<serde_json::Value>(&start_path, &mut problems) {
832                            OptionalFile::Ok(v) => Some(v),
833                            OptionalFile::Missing | OptionalFile::Err => None,
834                        };
835                    let start_mtime = file_mtime(&start_path);
836                    let pid = start_val.as_ref().and_then(|v| v["pid"].as_i64());
837
838                    if report_mtime.is_none() && log_mtime.is_none_or(|m| m < cutoff) {
839                        let has_recent_problem =
840                            !problems.is_empty() && start_mtime.is_some_and(|m| m >= cutoff);
841                        let is_alive = pid.is_some_and(|p| {
842                            p > 0 && unsafe { libc::kill(p as libc::pid_t, 0) == 0 }
843                        });
844                        if !is_alive && !has_recent_problem {
845                            continue;
846                        }
847                    }
848
849                    let started_at = start_val.as_ref().and_then(|v| v["started_at"].as_u64());
850                    let research = start_val
851                        .as_ref()
852                        .and_then(|v| v.get("research"))
853                        .and_then(|v| v.as_bool())
854                        .unwrap_or(false);
855                    let start_plan = start_val
856                        .as_ref()
857                        .and_then(|v| v["plan"].as_str())
858                        .map(|s| s.to_string())
859                        .filter(|s| !s.is_empty());
860                    let start_plan_task = start_val
861                        .as_ref()
862                        .and_then(|v| v["plan_task"].as_str())
863                        .map(|s| s.to_string())
864                        .filter(|s| !s.is_empty());
865                    let request = start_val
866                        .as_ref()
867                        .and_then(|v| v["request"].as_str())
868                        .map(|s| s.to_string())
869                        .filter(|s| !s.is_empty());
870                    let task_file = start_val
871                        .as_ref()
872                        .and_then(|v| v["task_file"].as_str())
873                        .map(|s| s.to_string());
874                    let task = match task_file.as_deref() {
875                        Some(p) => match read_optional_string(Path::new(p), &mut problems) {
876                            OptionalFile::Ok(s) => s,
877                            OptionalFile::Missing | OptionalFile::Err => String::new(),
878                        },
879                        None => String::new(),
880                    };
881                    let mut file_tags = Vec::new();
882                    if let Some(tags_arr) = start_val.as_ref().and_then(|v| v["tags"].as_array()) {
883                        for t in tags_arr {
884                            if let Some(s) = t.as_str() {
885                                file_tags.push(s.to_string());
886                            }
887                        }
888                    }
889                    if let Some(s) = start_val
890                        .as_ref()
891                        .and_then(|v| v["session"].as_str())
892                        .filter(|s| !s.is_empty())
893                    {
894                        let prefix: String = s.chars().take(8).collect();
895                        let tag = format!("session:{prefix}");
896                        if !file_tags.contains(&tag) {
897                            file_tags.push(tag);
898                        }
899                    }
900
901                    let summary_path = wt_dir.join(format!("{id}.json"));
902                    let mut commits = Vec::new();
903                    let mut changed_files = Vec::new();
904                    let mut summary_final_msg = None;
905                    let mut worktree = None;
906                    if let OptionalFile::Ok(val) =
907                        read_optional_json::<serde_json::Value>(&summary_path, &mut problems)
908                    {
909                        if let Some(arr) = val["commits"].as_array() {
910                            for c in arr {
911                                if let (Some(sha), Some(subject)) =
912                                    (c["sha"].as_str(), c["subject"].as_str())
913                                {
914                                    commits.push(CommitRecord {
915                                        sha: sha.to_string(),
916                                        subject: subject.to_string(),
917                                    });
918                                }
919                            }
920                        }
921                        if let Some(arr) = val["changed_files"].as_array() {
922                            for f in arr {
923                                if let Some(s) = f.as_str() {
924                                    changed_files.push(s.to_string());
925                                }
926                            }
927                        }
928                        summary_final_msg = val["final_message"].as_str().map(|s| s.to_string());
929                        worktree = val["worktree"].as_str().map(|s| s.to_string());
930                    }
931
932                    raw_jobs.push(RawJob {
933                        id: id.clone(),
934                        repo: repo.clone(),
935                        root: wt_dir.parent().map(|p| p.to_path_buf()),
936                        task,
937                        task_file,
938                        pid,
939                        started_at,
940                        research,
941                        start_plan,
942                        start_plan_task,
943                        request,
944                        file_tags,
945                        log_path,
946                        report_path,
947                        tags_path: wt_dir.join(format!("{id}.tags.json")),
948                        verdict_path: wt_dir.join(format!("{id}.verdict.json")),
949                        worktree,
950                        commits,
951                        changed_files,
952                        summary_final_msg,
953                        is_runs_dir: false,
954                        agy_summary_path: None,
955                        problems,
956                        problem_mtime: start_mtime,
957                    });
958                }
959            }
960        }
961    }
962
963    // 2. Runs-dir layout
964    for runs_dir in &src.runs_dirs {
965        if let Ok(repo_entries) = std::fs::read_dir(runs_dir) {
966            for repo_entry in repo_entries.flatten() {
967                let repo_path = repo_entry.path();
968                if repo_path.is_dir() {
969                    let repo = repo_path
970                        .file_name()
971                        .and_then(|n| n.to_str())
972                        .unwrap_or("unknown")
973                        .to_string();
974
975                    if let Ok(entries) = std::fs::read_dir(&repo_path) {
976                        for entry in entries.flatten() {
977                            let fname = entry.file_name().to_string_lossy().to_string();
978                            if let Some(id) = fname.strip_suffix(".log") {
979                                let id = id.to_string();
980                                let key = format!("{repo}/{id}");
981                                if !seen_keys.insert(key) {
982                                    continue;
983                                }
984
985                                let report_path = repo_path.join(format!("{id}.report.json"));
986                                let agy_path = repo_path.join(format!("{id}.json"));
987                                let log_path = repo_path.join(format!("{id}.log"));
988                                let report_mtime = file_mtime(&report_path);
989                                let agy_mtime = file_mtime(&agy_path);
990                                let log_mtime = file_mtime(&log_path);
991
992                                if report_mtime.is_some_and(|m| m < cutoff)
993                                    && agy_mtime.is_none_or(|m| m < cutoff)
994                                    && log_mtime.is_none_or(|m| m < cutoff)
995                                {
996                                    continue;
997                                }
998                                if report_mtime.is_none()
999                                    && agy_mtime.is_some_and(|m| m < cutoff)
1000                                    && log_mtime.is_none_or(|m| m < cutoff)
1001                                {
1002                                    continue;
1003                                }
1004
1005                                let mut problems = Vec::new();
1006                                let pid_path = repo_path.join(format!("{id}.pid"));
1007                                let (pid, started_at) =
1008                                    match read_optional_string(&pid_path, &mut problems) {
1009                                        OptionalFile::Ok(pid_text) => {
1010                                            let trimmed = pid_text.trim();
1011                                            let pid = if trimmed.is_empty() {
1012                                                None
1013                                            } else {
1014                                                match trimmed.parse::<i64>() {
1015                                                    Ok(p) => Some(p),
1016                                                    Err(e) => {
1017                                                        problems.push(format!(
1018                                                            "{}: {e}",
1019                                                            pid_path.display()
1020                                                        ));
1021                                                        None
1022                                                    }
1023                                                }
1024                                            };
1025                                            let mtime = file_mtime(&pid_path);
1026                                            (pid, mtime)
1027                                        }
1028                                        OptionalFile::Missing | OptionalFile::Err => (None, None),
1029                                    };
1030
1031                                if report_mtime.is_none()
1032                                    && agy_mtime.is_none()
1033                                    && log_mtime.is_none_or(|m| m < cutoff)
1034                                {
1035                                    let is_alive = pid.is_some_and(|p| {
1036                                        p > 0
1037                                            && unsafe { libc::kill(p as libc::pid_t, 0) == 0 }
1038                                            && started_with_job(p, started_at, now)
1039                                    });
1040                                    if !is_alive {
1041                                        continue;
1042                                    }
1043                                }
1044
1045                                let prompt_path = repo_path.join(format!("{id}.prompt"));
1046                                let task = match read_optional_string(&prompt_path, &mut problems) {
1047                                    OptionalFile::Ok(s) => s,
1048                                    OptionalFile::Missing | OptionalFile::Err => String::new(),
1049                                };
1050
1051                                let worktree_path = repo_path.join(format!("{id}.worktree"));
1052                                let worktree =
1053                                    match read_optional_string(&worktree_path, &mut problems) {
1054                                        OptionalFile::Ok(s) => {
1055                                            let trimmed = s.trim().to_string();
1056                                            if trimmed.is_empty() {
1057                                                None
1058                                            } else {
1059                                                Some(trimmed)
1060                                            }
1061                                        }
1062                                        OptionalFile::Missing | OptionalFile::Err => None,
1063                                    };
1064
1065                                let root = worktree.as_ref().and_then(|wt_str| {
1066                                    let p = Path::new(wt_str.trim_end_matches('/'));
1067                                    if let Some(common) = git_common_dir(p) {
1068                                        if common.file_name().and_then(|n| n.to_str())
1069                                            == Some(".git")
1070                                        {
1071                                            if let Some(parent) = common.parent() {
1072                                                return Some(parent.to_path_buf());
1073                                            }
1074                                        }
1075                                    }
1076                                    if p.parent()
1077                                        .and_then(|par| par.file_name())
1078                                        .and_then(|n| n.to_str())
1079                                        == Some(".wt")
1080                                    {
1081                                        return p
1082                                            .parent()
1083                                            .and_then(|par| par.parent())
1084                                            .map(Path::to_path_buf);
1085                                    }
1086                                    if let (Some(par), Some(grandpar)) =
1087                                        (p.parent(), p.parent().and_then(|par| par.parent()))
1088                                    {
1089                                        if par.file_name().and_then(|n| n.to_str())
1090                                            == Some("worktrees")
1091                                            && grandpar.file_name().and_then(|n| n.to_str())
1092                                                == Some(".claude")
1093                                        {
1094                                            return grandpar.parent().map(Path::to_path_buf);
1095                                        }
1096                                    }
1097                                    if let Some(file_name) = p.file_name().and_then(|n| n.to_str())
1098                                    {
1099                                        if let Some((base, _)) = file_name.split_once("--") {
1100                                            if !base.is_empty() {
1101                                                return p.parent().map(|par| par.join(base));
1102                                            }
1103                                        }
1104                                    }
1105                                    Some(p.to_path_buf())
1106                                });
1107
1108                                let agy_summary_path = Some(agy_path);
1109
1110                                raw_jobs.push(RawJob {
1111                                    id: id.clone(),
1112                                    repo: repo.clone(),
1113                                    root,
1114                                    task,
1115                                    task_file: None,
1116                                    pid,
1117                                    started_at,
1118                                    research: false,
1119                                    start_plan: None,
1120                                    start_plan_task: None,
1121                                    request: None,
1122                                    file_tags: Vec::new(),
1123                                    log_path,
1124                                    report_path,
1125                                    tags_path: repo_path.join(format!("{id}.tags.json")),
1126                                    verdict_path: repo_path.join(format!("{id}.verdict.json")),
1127                                    worktree,
1128                                    commits: Vec::new(),
1129                                    changed_files: Vec::new(),
1130                                    summary_final_msg: None,
1131                                    is_runs_dir: true,
1132                                    agy_summary_path,
1133                                    problems,
1134                                    problem_mtime: log_mtime,
1135                                });
1136                            }
1137                        }
1138                    }
1139                }
1140            }
1141        }
1142    }
1143
1144    let mut jobs = Vec::new();
1145    let mut plan_cache: std::collections::HashMap<PathBuf, Option<String>> =
1146        std::collections::HashMap::new();
1147
1148    for raw in raw_jobs {
1149        let title = job_title(&raw.task, &raw.id);
1150        let plan = extract_plan(&raw.task);
1151        let prompt_task_title = extract_prompt_task_title(&raw.task);
1152        let plan_file = raw.start_plan.clone().or_else(|| plan.clone());
1153        let plan_task = raw.start_plan_task.clone().or_else(|| {
1154            prompt_task_title
1155                .clone()
1156                .or_else(|| extract_first_task_id(&raw.task))
1157        });
1158
1159        let task_content = if let (Some(ref p_str), Some(ref t_title)) = (&plan, &prompt_task_title)
1160        {
1161            let p_path = if let Some(home) = std::env::var_os("HOME").map(PathBuf::from) {
1162                expand_home(p_str, &home)
1163            } else {
1164                PathBuf::from(p_str)
1165            };
1166            let cached_plan = plan_cache
1167                .entry(p_path.clone())
1168                .or_insert_with(|| std::fs::read_to_string(&p_path).ok());
1169            if let Some(plan_text) = cached_plan {
1170                extract_task_from_plan(plan_text, t_title).unwrap_or_else(|| raw.task.clone())
1171            } else {
1172                raw.task.clone()
1173            }
1174        } else {
1175            raw.task.clone()
1176        };
1177
1178        let mut problems = raw.problems;
1179
1180        let mut file_tags = raw.file_tags.clone();
1181        if let OptionalFile::Ok(arr) =
1182            read_optional_json::<Vec<String>>(&raw.tags_path, &mut problems)
1183        {
1184            for t in arr {
1185                if !file_tags.contains(&t) {
1186                    file_tags.push(t);
1187                }
1188            }
1189        }
1190
1191        let mut tags = Vec::new();
1192        tags.push(format!("repo: {}", raw.repo));
1193        if let Some(ref p) = plan {
1194            if let Some(stem) = Path::new(p).file_stem().and_then(|s| s.to_str()) {
1195                tags.push(format!("plan: {stem}"));
1196            }
1197        }
1198        for t in &file_tags {
1199            if !tags.contains(t) {
1200                tags.push(t.clone());
1201            }
1202        }
1203
1204        let (verdict, verdict_notes, verdict_ts) =
1205            match read_optional_json::<serde_json::Value>(&raw.verdict_path, &mut problems) {
1206                OptionalFile::Ok(val) => {
1207                    let v = val["verdict"]
1208                        .as_str()
1209                        .filter(|s| !s.is_empty())
1210                        .map(|s| s.to_string());
1211                    if v.is_none() {
1212                        problems.push(format!(
1213                            "{}: missing required field 'verdict'",
1214                            raw.verdict_path.display()
1215                        ));
1216                    }
1217                    let notes = val["notes"].as_str().map(|s| s.to_string());
1218                    let ts = val["ts"].as_u64().or_else(|| file_mtime(&raw.verdict_path));
1219                    (v, notes, ts)
1220                }
1221                OptionalFile::Missing | OptionalFile::Err => (None, None, None),
1222            };
1223
1224        let log_info = parse_log(&raw.log_path, &mut problems);
1225
1226        let report_state = read_optional_json::<serde_json::Value>(&raw.report_path, &mut problems);
1227        let report_mtime = file_mtime(&raw.report_path);
1228
1229        let agy_state = match report_state {
1230            OptionalFile::Missing => match raw.agy_summary_path.as_ref() {
1231                Some(p) => read_optional_json::<AgySummary>(p, &mut problems),
1232                None => OptionalFile::Missing,
1233            },
1234            OptionalFile::Ok(_) | OptionalFile::Err => OptionalFile::Missing,
1235        };
1236
1237        let (
1238            status,
1239            gate_running,
1240            cost_usd,
1241            turns,
1242            gate_attempts,
1243            gate_failures,
1244            model,
1245            finished_at,
1246            elapsed_s,
1247            now_str,
1248        ) = match (report_state, agy_state) {
1249            (OptionalFile::Ok(report), _) => {
1250                let outcome = match report.get("outcome") {
1251                    Some(v) => match v.as_str() {
1252                        Some(s) if !s.is_empty() => s.to_string(),
1253                        _ => {
1254                            problems.push(format!(
1255                                "{}: invalid 'outcome' field (expected non-empty string)",
1256                                raw.report_path.display()
1257                            ));
1258                            "error".to_string()
1259                        }
1260                    },
1261                    None => {
1262                        problems.push(format!(
1263                            "{}: missing required field 'outcome'",
1264                            raw.report_path.display()
1265                        ));
1266                        "error".to_string()
1267                    }
1268                };
1269                let cost = report["cost_usd"].as_f64();
1270                let turns = read_required_u64(&report, "turns", &raw.report_path, &mut problems);
1271                let gate_attempts =
1272                    read_required_u64(&report, "gate_attempts", &raw.report_path, &mut problems);
1273                let model = report["model_id"].as_str().map(|s| s.to_string());
1274
1275                let gate_failures = match report.get("gate_failures") {
1276                    None | Some(serde_json::Value::Null) => Vec::new(),
1277                    Some(serde_json::Value::Array(arr)) => {
1278                        let skip = arr.len().saturating_sub(2);
1279                        let mut failures = Vec::new();
1280                        for (idx, v) in arr.iter().enumerate() {
1281                            match v.as_str() {
1282                                Some(s) => {
1283                                    if idx >= skip {
1284                                        let count = s.chars().count();
1285                                        if count > 1500 {
1286                                            failures.push(s.chars().skip(count - 1500).collect());
1287                                        } else {
1288                                            failures.push(s.to_string());
1289                                        }
1290                                    }
1291                                }
1292                                None => {
1293                                    problems.push(format!(
1294                                        "{}: gate_failures[{idx}] is not a string",
1295                                        raw.report_path.display()
1296                                    ));
1297                                }
1298                            }
1299                        }
1300                        failures
1301                    }
1302                    Some(_) => {
1303                        problems.push(format!(
1304                            "{}: invalid 'gate_failures' field (expected array)",
1305                            raw.report_path.display()
1306                        ));
1307                        Vec::new()
1308                    }
1309                };
1310
1311                let finished_at = report_mtime;
1312                let elapsed_s = if let Some(dur) = report["duration_seconds"].as_f64() {
1313                    Some(dur.round() as u64)
1314                } else if let (Some(fin), Some(st)) = (finished_at, raw.started_at) {
1315                    if fin >= st {
1316                        Some(fin - st)
1317                    } else {
1318                        None
1319                    }
1320                } else {
1321                    None
1322                };
1323
1324                let report_final_msg = report["final_message"].as_str();
1325                let now_from_msg = raw
1326                    .summary_final_msg
1327                    .as_deref()
1328                    .or(report_final_msg)
1329                    .map(extract_now_from_final_message)
1330                    .filter(|s| !s.is_empty());
1331                let now_str = if let Some(s) = now_from_msg {
1332                    s
1333                } else if let Some(ref tool) = log_info.last_tool {
1334                    tool.clone()
1335                } else {
1336                    String::new()
1337                };
1338
1339                (
1340                    outcome,
1341                    false,
1342                    cost,
1343                    turns,
1344                    gate_attempts,
1345                    gate_failures,
1346                    model,
1347                    finished_at,
1348                    elapsed_s,
1349                    now_str,
1350                )
1351            }
1352            (OptionalFile::Err, _) => {
1353                let finished_at = report_mtime;
1354                let elapsed_s = match (finished_at, raw.started_at) {
1355                    (Some(fin), Some(st)) if fin >= st => Some(fin - st),
1356                    _ => None,
1357                };
1358                let now_str = log_info.last_tool.clone().unwrap_or_default();
1359                (
1360                    "error".to_string(),
1361                    false,
1362                    None,
1363                    log_info.turns,
1364                    log_info.gate_attempts,
1365                    Vec::new(),
1366                    None,
1367                    finished_at,
1368                    elapsed_s,
1369                    now_str,
1370                )
1371            }
1372            (OptionalFile::Missing, OptionalFile::Ok(agy)) => {
1373                let status = if agy.status.as_deref() == Some("ERROR") {
1374                    "error".to_string()
1375                } else {
1376                    "finished".to_string()
1377                };
1378                let cost = None;
1379                let turns = agy.num_turns.unwrap_or(log_info.turns);
1380                let gate_attempts = log_info.gate_attempts;
1381                let gate_failures = Vec::new();
1382                let model = None;
1383                let finished_at = raw.agy_summary_path.as_ref().and_then(|p| file_mtime(p));
1384                let elapsed_s = agy.duration_seconds.map(|d| d.round() as u64);
1385                let now_str = if status == "error" {
1386                    let err = agy.error.as_deref().unwrap_or("");
1387                    let s = extract_now_from_final_message(err);
1388                    if !s.is_empty() {
1389                        s
1390                    } else {
1391                        err.lines().next().unwrap_or("").chars().take(200).collect()
1392                    }
1393                } else {
1394                    let resp = agy.response.as_deref().unwrap_or("");
1395                    let s = extract_now_from_final_message(resp);
1396                    if !s.is_empty() {
1397                        s
1398                    } else {
1399                        resp.lines()
1400                            .next()
1401                            .unwrap_or("")
1402                            .chars()
1403                            .take(200)
1404                            .collect()
1405                    }
1406                };
1407
1408                (
1409                    status,
1410                    false,
1411                    cost,
1412                    turns,
1413                    gate_attempts,
1414                    gate_failures,
1415                    model,
1416                    finished_at,
1417                    elapsed_s,
1418                    now_str,
1419                )
1420            }
1421            (OptionalFile::Missing, OptionalFile::Err) => {
1422                let finished_at = raw.agy_summary_path.as_ref().and_then(|p| file_mtime(p));
1423                let now_str = log_info.last_tool.clone().unwrap_or_default();
1424                (
1425                    "error".to_string(),
1426                    false,
1427                    None,
1428                    log_info.turns,
1429                    log_info.gate_attempts,
1430                    Vec::new(),
1431                    None,
1432                    finished_at,
1433                    None,
1434                    now_str,
1435                )
1436            }
1437            (OptionalFile::Missing, OptionalFile::Missing) => {
1438                let is_alive = raw.pid.is_some_and(|p| {
1439                    p > 0
1440                        && unsafe { libc::kill(p as libc::pid_t, 0) == 0 }
1441                        && (!raw.is_runs_dir || started_with_job(p, raw.started_at, now))
1442                });
1443                let status = if is_alive {
1444                    "running".to_string()
1445                } else {
1446                    "stopped".to_string()
1447                };
1448                let gate_running = if status == "running" {
1449                    log_info.gate_running
1450                } else {
1451                    false
1452                };
1453                let cost = None;
1454                let turns = log_info.turns;
1455                let gate_attempts = log_info.gate_attempts;
1456                let gate_failures = Vec::new();
1457                let model = None;
1458                let finished_at = None;
1459                let elapsed_s = if status == "running" {
1460                    raw.started_at.map(|s| now.saturating_sub(s))
1461                } else {
1462                    None
1463                };
1464                let now_str = log_info.last_tool.clone().unwrap_or_default();
1465
1466                (
1467                    status,
1468                    gate_running,
1469                    cost,
1470                    turns,
1471                    gate_attempts,
1472                    gate_failures,
1473                    model,
1474                    finished_at,
1475                    elapsed_s,
1476                    now_str,
1477                )
1478            }
1479        };
1480
1481        let keep = if status == "running" {
1482            true
1483        } else {
1484            let effective_finished = finished_at.or(log_info.mtime).or(if !problems.is_empty() {
1485                raw.problem_mtime
1486            } else {
1487                None
1488            });
1489            if let Some(fin) = effective_finished {
1490                fin >= cutoff
1491            } else {
1492                false
1493            }
1494        };
1495        if !keep {
1496            continue;
1497        }
1498
1499        let task_truncated: String = task_content.chars().take(2000).collect();
1500        let worktree_exists = raw.worktree.as_deref().map(|wt| Path::new(wt).is_dir());
1501
1502        jobs.push(Job {
1503            key: format!("{}/{}", raw.repo, raw.id),
1504            id: raw.id,
1505            repo: raw.repo,
1506            status,
1507            gate_running,
1508            title,
1509            task: task_truncated,
1510            plan,
1511            now: now_str,
1512            started_at: raw.started_at,
1513            finished_at,
1514            elapsed_s,
1515            cost_usd,
1516            turns,
1517            gate_attempts,
1518            gate_failures,
1519            model,
1520            last_tool: log_info.last_tool,
1521            worktree: raw.worktree,
1522            worktree_exists,
1523            log: raw.log_path.display().to_string(),
1524            commits: raw.commits,
1525            changed_files: raw.changed_files,
1526            tags,
1527            verdict,
1528            problems,
1529            root: raw.root,
1530            plan_file,
1531            plan_task,
1532            request: raw.request,
1533            task_file: raw.task_file,
1534            start_plan: raw.start_plan,
1535            file_tags,
1536            verdict_notes,
1537            verdict_ts,
1538            log_mtime: log_info.mtime,
1539            research: raw.research,
1540        });
1541    }
1542
1543    // Sort jobs: running jobs first, newest started_at first; then the rest, newest finished_at first.
1544    jobs.sort_by(|a, b| {
1545        let a_running = a.status == "running";
1546        let b_running = b.status == "running";
1547        match (a_running, b_running) {
1548            (true, false) => std::cmp::Ordering::Less,
1549            (false, true) => std::cmp::Ordering::Greater,
1550            (true, true) => b
1551                .started_at
1552                .unwrap_or(0)
1553                .cmp(&a.started_at.unwrap_or(0))
1554                .then_with(|| a.key.cmp(&b.key)),
1555            (false, false) => {
1556                let a_fin = a.finished_at.or(a.log_mtime).unwrap_or(0);
1557                let b_fin = b.finished_at.or(b.log_mtime).unwrap_or(0);
1558                b_fin.cmp(&a_fin).then_with(|| a.key.cmp(&b.key))
1559            }
1560        }
1561    });
1562
1563    jobs
1564}
1565
1566pub fn collect(src: &Sources, now: u64) -> serde_json::Value {
1567    let jobs = collect_jobs(src, now);
1568    let running = jobs.iter().filter(|j| j.status == "running").count();
1569    let last_24h = jobs
1570        .iter()
1571        .filter(|j| {
1572            j.started_at
1573                .is_some_and(|s| s >= now.saturating_sub(24 * 3600))
1574        })
1575        .count();
1576    let repos = jobs.iter().map(|j| &j.repo).collect::<HashSet<_>>().len();
1577
1578    let finished_jobs: Vec<_> = jobs
1579        .iter()
1580        .filter(|j| {
1581            j.status != "running"
1582                && j.finished_at
1583                    .or(j.log_mtime)
1584                    .is_some_and(|f| f >= now.saturating_sub(24 * 3600))
1585        })
1586        .collect();
1587
1588    let finished_24h = finished_jobs.len();
1589    let passed_24h = finished_jobs
1590        .iter()
1591        .filter(|j| j.status == "verified")
1592        .count();
1593    let sum_cost: f64 = finished_jobs.iter().filter_map(|j| j.cost_usd).sum();
1594    let cost_24h_usd = (sum_cost * 100.0).round() / 100.0;
1595
1596    let response = DashboardResponse {
1597        generated_at: now,
1598        summary: Summary {
1599            running,
1600            last_24h,
1601            repos,
1602            finished_24h,
1603            passed_24h,
1604            cost_24h_usd,
1605        },
1606        jobs,
1607    };
1608
1609    serde_json::to_value(&response).unwrap()
1610}
1611
1612pub(crate) fn shared_asset(clean_path: &str) -> Option<(u16, &'static str, Vec<u8>)> {
1613    match clean_path {
1614        "/favicon.svg" => {
1615            let svg = include_bytes!("../assets/dashboard/favicon.svg");
1616            Some((200, "image/svg+xml", svg.to_vec()))
1617        }
1618        "/fonts/archivo.woff2" => {
1619            let font = include_bytes!("../assets/dashboard/fonts/archivo.woff2");
1620            Some((200, "font/woff2", font.to_vec()))
1621        }
1622        "/fonts/plex-mono-400.woff2" => {
1623            let font = include_bytes!("../assets/dashboard/fonts/plex-mono-400.woff2");
1624            Some((200, "font/woff2", font.to_vec()))
1625        }
1626        "/fonts/plex-mono-500.woff2" => {
1627            let font = include_bytes!("../assets/dashboard/fonts/plex-mono-500.woff2");
1628            Some((200, "font/woff2", font.to_vec()))
1629        }
1630        _ => None,
1631    }
1632}
1633
1634pub fn route(path: &str, src: &Sources) -> (u16, &'static str, Vec<u8>) {
1635    let clean_path = match path.split_once('?') {
1636        Some((p, _)) => p,
1637        None => path,
1638    };
1639    if let Some(asset) = shared_asset(clean_path) {
1640        return asset;
1641    }
1642    match clean_path {
1643        "/" | "/index.html" => {
1644            let html = include_str!("../assets/dashboard/index.html");
1645            (200, "text/html; charset=utf-8", html.as_bytes().to_vec())
1646        }
1647        "/api/jobs" => {
1648            let now = std::time::SystemTime::now()
1649                .duration_since(UNIX_EPOCH)
1650                .map(|d| d.as_secs())
1651                .unwrap_or(0);
1652            let val = collect(src, now);
1653            let body = serde_json::to_vec(&val).unwrap_or_default();
1654            (200, "application/json", body)
1655        }
1656        "/api/plans" => {
1657            let now = std::time::SystemTime::now()
1658                .duration_since(UNIX_EPOCH)
1659                .map(|d| d.as_secs())
1660                .unwrap_or(0);
1661            let query = path.split_once('?').map(|(_, q)| q).unwrap_or("");
1662            let running_only = query
1663                .split('&')
1664                .any(|p| p == "running=1" || p == "running=true");
1665            let val = crate::plans::collect_plans_filtered(src, now, running_only);
1666            let body = serde_json::to_vec(&val).unwrap_or_default();
1667            (200, "application/json", body)
1668        }
1669        _ => (404, "text/plain; charset=utf-8", b"Not Found\n".to_vec()),
1670    }
1671}
1672
1673pub(crate) fn serve_http<F>(
1674    listener: std::net::TcpListener,
1675    no_store_paths: &'static [&'static str],
1676    handler: F,
1677) where
1678    F: Fn(&str) -> (u16, &'static str, Vec<u8>) + Send + Sync + 'static,
1679{
1680    let handler = std::sync::Arc::new(handler);
1681    for stream in listener.incoming().flatten() {
1682        let handler = std::sync::Arc::clone(&handler);
1683        std::thread::spawn(move || {
1684            handle_http_connection(stream, no_store_paths, handler.as_ref());
1685        });
1686    }
1687}
1688
1689fn handle_http_connection<F>(mut stream: std::net::TcpStream, no_store_paths: &[&str], handler: &F)
1690where
1691    F: Fn(&str) -> (u16, &'static str, Vec<u8>),
1692{
1693    let mut reader = std::io::BufReader::new(&mut stream);
1694    let mut request_line = String::new();
1695    if reader.read_line(&mut request_line).is_err() || request_line.is_empty() {
1696        return;
1697    }
1698    drop(reader);
1699
1700    let parts: Vec<&str> = request_line.split_whitespace().collect();
1701    if parts.len() < 2 || parts[0] != "GET" {
1702        let not_found = b"Not Found\n";
1703        let header = format!(
1704            "HTTP/1.1 404 Not Found\r\nContent-Type: text/plain; charset=utf-8\r\nContent-Length: {}\r\nConnection: close\r\n\r\n",
1705            not_found.len()
1706        );
1707        let _ = stream.write_all(header.as_bytes());
1708        let _ = stream.write_all(not_found);
1709        let _ = stream.flush();
1710        return;
1711    }
1712
1713    let path = parts[1];
1714    let (code, ctype, body) = handler(path);
1715    let clean_path = match path.split_once('?') {
1716        Some((p, _)) => p,
1717        None => path,
1718    };
1719    let reason = match code {
1720        200 => "OK",
1721        404 => "Not Found",
1722        500 => "Internal Server Error",
1723        _ => "OK",
1724    };
1725    let extra = if no_store_paths.contains(&clean_path) {
1726        "Cache-Control: no-store\r\n"
1727    } else {
1728        ""
1729    };
1730    let header = format!(
1731        "HTTP/1.1 {code} {reason}\r\nContent-Type: {ctype}\r\nContent-Length: {}\r\n{extra}Connection: close\r\n\r\n",
1732        body.len()
1733    );
1734    let _ = stream.write_all(header.as_bytes());
1735    let _ = stream.write_all(&body);
1736    let _ = stream.flush();
1737}
1738
1739pub fn run(args: &crate::cli::DashboardArgs) -> i32 {
1740    let (sources, where_from) = Sources::from_args_with_where(args);
1741    let listener = match std::net::TcpListener::bind(format!("127.0.0.1:{}", args.port)) {
1742        Ok(l) => l,
1743        Err(e) => {
1744            eprintln!("error binding 127.0.0.1:{}: {e}", args.port);
1745            return 1;
1746        }
1747    };
1748
1749    let local_addr = match listener.local_addr() {
1750        Ok(a) => a,
1751        Err(e) => {
1752            eprintln!("error getting local address: {e}");
1753            return 1;
1754        }
1755    };
1756    let port = local_addr.port();
1757    let url = format!("http://127.0.0.1:{port}");
1758    if sources.roots.is_empty() && sources.runs_dirs.is_empty() {
1759        eprintln!(
1760            "blyte dashboard: nothing to watch yet: run blyte dispatch in a repository, or list roots in ~/.config/blyte/dashboard.toml"
1761        );
1762    } else {
1763        eprintln!(
1764            "blyte dashboard: watching {} repositories and {} run directories ({where_from})",
1765            sources.roots.len(),
1766            sources.runs_dirs.len()
1767        );
1768    }
1769    println!("blyte dashboard: {url}");
1770    let _ = std::io::stdout().flush();
1771
1772    if args.open {
1773        let cmd = if cfg!(target_os = "macos") {
1774            "open"
1775        } else {
1776            "xdg-open"
1777        };
1778        if let Err(e) = std::process::Command::new(cmd).arg(&url).spawn() {
1779            eprintln!("warning: failed to open browser: {e}");
1780        }
1781    }
1782
1783    let live = args.roots.is_empty() && args.runs_dirs.is_empty();
1784    let args = args.clone();
1785    serve_http(listener, &["/api/jobs", "/api/plans"], move |path| {
1786        if live {
1787            let src = Sources::from_args(&args);
1788            route(path, &src)
1789        } else {
1790            route(path, &sources)
1791        }
1792    });
1793
1794    0
1795}
1796
1797#[cfg(test)]
1798mod tests {
1799    use super::*;
1800
1801    #[test]
1802    fn extract_title_first_markdown_heading() {
1803        assert_eq!(
1804            extract_title(
1805                "From the plan docs/p.md:\n\n### Task G2: an empty gate is skipped\n\nbody"
1806            ),
1807            "Task G2: an empty gate is skipped"
1808        );
1809    }
1810
1811    #[test]
1812    fn extract_title_no_heading_fallback() {
1813        assert_eq!(extract_title("fix the bug\nmore"), "fix the bug");
1814    }
1815
1816    #[test]
1817    fn extract_title_task_rule_wins() {
1818        assert_eq!(
1819            extract_title("# Heading\nTask: \"explicit title\"\nmore"),
1820            "explicit title"
1821        );
1822    }
1823
1824    #[test]
1825    fn job_title_strips_task_id_prefix() {
1826        let text1 = "From the plan docs/p.md:\n\n### Task G2: an empty gate is skipped\n\nbody";
1827        assert_eq!(job_title(text1, "G2"), "an empty gate is skipped");
1828        assert_eq!(job_title("Task G3: x", "G2"), "Task G3: x");
1829        assert_eq!(job_title("Task G2:", "G2"), "Task G2:");
1830    }
1831
1832    #[test]
1833    fn session_tag_from_start_file() {
1834        let d = tempfile::tempdir().unwrap();
1835        let wt = d.path().join("repos/repo-a/.wt");
1836        std::fs::create_dir_all(&wt).unwrap();
1837
1838        let me = std::process::id();
1839        std::fs::write(
1840            wt.join("T1.start.json"),
1841            format!(r#"{{"id":"T1","pid":{me},"session":"4f83bf80-a445-4090","tags":["x"]}}"#),
1842        )
1843        .unwrap();
1844        std::fs::write(
1845            wt.join("T2.start.json"),
1846            format!(r#"{{"id":"T2","pid":{me},"session":"abc"}}"#),
1847        )
1848        .unwrap();
1849        std::fs::write(
1850            wt.join("T3.start.json"),
1851            format!(r#"{{"id":"T3","pid":{me},"tags":["x"]}}"#),
1852        )
1853        .unwrap();
1854        std::fs::write(
1855            wt.join("T4.start.json"),
1856            format!(r#"{{"id":"T4","pid":{me},"session":"4f83bf80-a445-4090","tags":["session:4f83bf80"]}}"#),
1857        )
1858        .unwrap();
1859
1860        let src = Sources {
1861            roots: vec![d.path().join("repos")],
1862            runs_dirs: vec![],
1863            hours: 24,
1864        };
1865        let now = std::time::SystemTime::now()
1866            .duration_since(std::time::UNIX_EPOCH)
1867            .unwrap()
1868            .as_secs();
1869        let jobs = collect_jobs(&src, now);
1870
1871        let t1 = jobs.iter().find(|j| j.id == "T1").unwrap();
1872        assert!(t1.tags.contains(&"x".to_string()));
1873        assert!(t1.tags.contains(&"session:4f83bf80".to_string()));
1874
1875        let t2 = jobs.iter().find(|j| j.id == "T2").unwrap();
1876        assert!(t2.tags.contains(&"session:abc".to_string()));
1877
1878        let t3 = jobs.iter().find(|j| j.id == "T3").unwrap();
1879        assert!(!t3.tags.iter().any(|t| t.starts_with("session:")));
1880
1881        let t4 = jobs.iter().find(|j| j.id == "T4").unwrap();
1882        assert_eq!(
1883            t4.tags
1884                .iter()
1885                .filter(|t| t.as_str() == "session:4f83bf80")
1886                .count(),
1887            1
1888        );
1889    }
1890
1891    #[test]
1892    fn strip_ansi_borrows_plain_and_strips_csi_sequences() {
1893        let plain = "[Turn 4]\n● bash\n✓ Gate passed\n";
1894        let res = strip_ansi(plain);
1895        assert!(matches!(res, std::borrow::Cow::Borrowed(_)));
1896        assert_eq!(res.as_ref(), plain);
1897
1898        let colored =
1899            "\x1b[32m[Turn 4]\x1b[0m\n\x1b[1m● bash\x1b[0m\n\x1b[32m✓ Gate passed\x1b[0m\n";
1900        let stripped = strip_ansi(colored);
1901        assert!(matches!(stripped, std::borrow::Cow::Owned(_)));
1902        assert_eq!(stripped.as_ref(), plain);
1903
1904        assert_eq!(strip_ansi("\x1b[32\nhello").as_ref(), "\nhello");
1905        assert_eq!(strip_ansi("\x1b[32\x1b[0mhello").as_ref(), "\x1b[0mhello");
1906        assert_eq!(strip_ansi("\x1bXhello").as_ref(), "\x1bXhello");
1907        assert_eq!(strip_ansi("tail\x1b").as_ref(), "tail\x1b");
1908        assert_eq!(strip_ansi("\x1b[32").as_ref(), "");
1909        assert_eq!(strip_ansi("\x1b[✓mhello").as_ref(), "hello");
1910    }
1911
1912    #[test]
1913    fn git_common_dir_resolves_relative_gitdir_and_commondir() {
1914        let tmp = tempfile::tempdir().unwrap();
1915        let main = tmp.path().join("myrepo");
1916        let worktree_git = main.join(".git/worktrees/wt1");
1917        let wt = tmp.path().join("wt1");
1918        std::fs::create_dir_all(&worktree_git).unwrap();
1919        std::fs::create_dir_all(wt.join("nested")).unwrap();
1920        std::fs::write(worktree_git.join("commondir"), "../..\n").unwrap();
1921        std::fs::write(wt.join(".git"), "gitdir: ../myrepo/.git/worktrees/wt1\n").unwrap();
1922
1923        let common = git_common_dir(&wt.join("nested")).unwrap();
1924        assert_eq!(common.file_name().and_then(|n| n.to_str()), Some(".git"));
1925        assert_eq!(
1926            common
1927                .parent()
1928                .and_then(|p| p.file_name())
1929                .and_then(|n| n.to_str()),
1930            Some("myrepo")
1931        );
1932        assert_eq!(repo_name(&wt.join("nested")), "myrepo");
1933    }
1934}