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 root: Option<PathBuf>,
143    pub plan_file: Option<String>,
144    pub plan_task: Option<String>,
145    pub task_file: Option<String>,
146    #[serde(skip)]
147    pub research: bool,
148    #[serde(skip)]
149    pub start_plan: Option<String>,
150    #[serde(skip)]
151    pub file_tags: Vec<String>,
152    #[serde(skip)]
153    pub verdict_notes: Option<String>,
154    #[serde(skip)]
155    pub verdict_ts: Option<u64>,
156    #[serde(skip)]
157    pub log_mtime: Option<u64>,
158}
159
160#[derive(serde::Serialize, Debug, Clone)]
161pub struct Summary {
162    pub running: usize,
163    pub last_24h: usize,
164    pub repos: usize,
165    pub finished_24h: usize,
166    pub passed_24h: usize,
167    pub cost_24h_usd: f64,
168}
169
170#[derive(serde::Serialize, Debug, Clone)]
171pub struct DashboardResponse {
172    pub generated_at: u64,
173    pub summary: Summary,
174    pub jobs: Vec<Job>,
175}
176
177fn strip_ansi(s: &str) -> String {
178    let mut out = String::with_capacity(s.len());
179    let mut chars = s.chars().peekable();
180    while let Some(c) = chars.next() {
181        if c == '\x1b' && chars.peek() == Some(&'[') {
182            chars.next();
183            while let Some(&next_c) = chars.peek() {
184                chars.next();
185                if ('\x40'..='\x7e').contains(&next_c) {
186                    break;
187                }
188                if next_c == '\n' || next_c == '\x1b' {
189                    out.push(next_c);
190                    break;
191                }
192            }
193            continue;
194        }
195        out.push(c);
196    }
197    out
198}
199
200fn extract_title(task: &str) -> String {
201    for line in task.lines() {
202        let trimmed = line.trim();
203        if let Some(pos) = trimmed.find("Task: \"") {
204            let rest = &trimmed[pos + "Task: \"".len()..];
205            if let Some(end) = rest.find('"') {
206                return rest[..end].chars().take(120).collect();
207            }
208        }
209    }
210    for line in task.lines() {
211        let trimmed = line.trim();
212        if trimmed.starts_with('#') {
213            let text = trimmed.trim_start_matches('#').trim();
214            if !text.is_empty() {
215                return text.chars().take(120).collect();
216            }
217        }
218    }
219    for line in task.lines() {
220        let trimmed = line.trim_start_matches(['#', ' ']).trim_end();
221        if !trimmed.is_empty() {
222            return trimmed.chars().take(120).collect();
223        }
224    }
225    String::new()
226}
227
228fn job_title(task: &str, id: &str) -> String {
229    let title = extract_title(task);
230    if id.is_empty() {
231        return title;
232    }
233    let p_colon = format!("Task {id}:");
234    let p_space = format!("Task {id} ");
235    let rest = if let Some(after) = title.strip_prefix(&p_colon) {
236        after.trim()
237    } else if let Some(after) = title.strip_prefix(&p_space) {
238        after.trim()
239    } else {
240        return title;
241    };
242    if rest.is_empty() {
243        title
244    } else {
245        rest.chars().take(120).collect()
246    }
247}
248
249fn extract_plan(task: &str) -> Option<String> {
250    for line in task.lines() {
251        let trimmed = line.trim();
252        if let Some(rest) = trimmed.strip_prefix("Plan: ") {
253            let plan = rest.trim();
254            if !plan.is_empty() {
255                return Some(plan.to_string());
256            }
257        }
258    }
259    None
260}
261
262fn extract_prompt_task_title(prompt: &str) -> Option<String> {
263    for line in prompt.lines() {
264        let trimmed = line.trim();
265        if let Some(pos) = trimmed.find("Task: \"") {
266            let rest = &trimmed[pos + "Task: \"".len()..];
267            if let Some(end) = rest.find('"') {
268                return Some(rest[..end].to_string());
269            }
270        }
271    }
272    None
273}
274
275fn extract_first_task_id(text: &str) -> Option<String> {
276    for line in text.lines() {
277        let plain = plain_line(line);
278        let mut idx = 0;
279        while let Some(pos) = plain[idx..].find("Task") {
280            let start = idx + pos;
281            let after = &plain[start + 4..];
282            if after.starts_with(' ') || after.starts_with('\t') {
283                let trimmed = after.trim_start();
284                let id: String = trimmed
285                    .chars()
286                    .take_while(|c| c.is_alphanumeric() || *c == '_' || *c == '-')
287                    .collect();
288                if !id.is_empty() {
289                    return Some(format!("Task {id}"));
290                }
291            }
292            idx = start + 4;
293        }
294    }
295    None
296}
297
298fn parse_heading(line: &str) -> Option<(usize, &str)> {
299    let trimmed = line.trim_start();
300    let hashes = trimmed.chars().take_while(|&c| c == '#').count();
301    if hashes > 0 {
302        let after = &trimmed[hashes..];
303        if after.is_empty() || after.starts_with(' ') || after.starts_with('\t') {
304            return Some((hashes, after.trim()));
305        }
306    }
307    None
308}
309
310fn extract_task_from_plan(plan_content: &str, title: &str) -> Option<String> {
311    let mut target_heading = None;
312    let mut offset = 0;
313
314    for line in plan_content.split_inclusive('\n') {
315        let line_len = line.len();
316        let trimmed = line.trim_end_matches(['\r', '\n']);
317        if let Some((level, text)) = parse_heading(trimmed) {
318            if text == title {
319                target_heading = Some((offset, level));
320                break;
321            }
322        }
323        offset += line_len;
324    }
325
326    let (start_offset, target_level) = target_heading?;
327
328    // A `#` line inside a fenced code block (a shell comment, say) is not a heading.
329    let mut end_offset = plan_content.len();
330    let mut curr_offset = 0;
331    let mut in_fence = false;
332    for line in plan_content.split_inclusive('\n') {
333        let line_len = line.len();
334        if line.trim_start().starts_with("```") {
335            in_fence = !in_fence;
336        } else if curr_offset > start_offset && !in_fence {
337            let trimmed = line.trim_end_matches(['\r', '\n']);
338            if let Some((level, _)) = parse_heading(trimmed) {
339                if level <= target_level {
340                    end_offset = curr_offset;
341                    break;
342                }
343            }
344        }
345        curr_offset += line_len;
346    }
347
348    Some(plan_content[start_offset..end_offset].to_string())
349}
350
351fn extract_now_from_final_message(msg: &str) -> String {
352    let pick = msg
353        .lines()
354        .map(str::trim)
355        .find(|l| !l.is_empty() && !l.starts_with('#'))
356        .or_else(|| msg.lines().map(str::trim).find(|l| !l.is_empty()))
357        .unwrap_or("");
358    plain_line(pick.trim_start_matches(['#', ' ']))
359        .chars()
360        .take(200)
361        .collect()
362}
363
364/// One line of markdown as plain text: no list marker, no `**`, `__` or backticks.
365fn plain_line(line: &str) -> String {
366    let mut l = line.trim();
367    if let Some(rest) = l.strip_prefix("- ").or_else(|| l.strip_prefix("* ")) {
368        l = rest;
369    } else if let Some((n, rest)) = l.split_once(". ") {
370        if !n.is_empty() && n.chars().all(|c| c.is_ascii_digit()) {
371            l = rest;
372        }
373    }
374    l.replace("**", "")
375        .replace("__", "")
376        .replace('`', "")
377        .trim()
378        .to_string()
379}
380
381struct LogInfo {
382    turns: u64,
383    last_tool: Option<String>,
384    gate_attempts: u64,
385    gate_running: bool,
386    mtime: Option<u64>,
387}
388
389fn parse_log(path: &Path) -> LogInfo {
390    let mtime = std::fs::metadata(path)
391        .ok()
392        .and_then(|m| m.modified().ok())
393        .and_then(|t| t.duration_since(UNIX_EPOCH).ok())
394        .map(|d| d.as_secs());
395
396    let raw = std::fs::read_to_string(path).unwrap_or_default();
397    let text = strip_ansi(&raw);
398
399    let mut max_turn = 0u64;
400    let mut last_tool = None;
401    let mut gate_attempts = 0u64;
402    let mut last_event_line: Option<String> = None;
403
404    for line in text.lines() {
405        let trimmed = line.trim();
406        if let Some(pos) = trimmed.find("[Turn ") {
407            let rest = &trimmed[pos + "[Turn ".len()..];
408            if let Some(end) = rest.find(']') {
409                if let Ok(n) = rest[..end].trim().parse::<u64>() {
410                    if n > max_turn {
411                        max_turn = n;
412                    }
413                }
414            }
415        }
416
417        if let Some(pos) = trimmed.find("● ") {
418            let tool = trimmed[pos + "● ".len()..].trim();
419            last_tool = Some(tool.chars().take(200).collect());
420        }
421
422        if trimmed.starts_with("✓ Gate passed") || trimmed.starts_with("✗ Gate failed") {
423            gate_attempts += 1;
424        }
425
426        if trimmed.contains("[Turn ")
427            || trimmed.contains("● ")
428            || trimmed.starts_with("⏳ Gate running")
429            || trimmed.starts_with("✓ Gate passed")
430            || trimmed.starts_with("✗ Gate failed")
431        {
432            last_event_line = Some(trimmed.to_string());
433        }
434    }
435
436    let gate_running = last_event_line
437        .map(|l| l.starts_with("⏳ Gate running"))
438        .unwrap_or(false);
439
440    LogInfo {
441        turns: max_turn,
442        last_tool,
443        gate_attempts,
444        gate_running,
445        mtime,
446    }
447}
448
449fn file_mtime(path: &Path) -> Option<u64> {
450    std::fs::metadata(path)
451        .ok()
452        .and_then(|m| m.modified().ok())
453        .and_then(|t| t.duration_since(UNIX_EPOCH).ok())
454        .map(|d| d.as_secs())
455}
456
457pub fn parse_etime(s: &str) -> Option<u64> {
458    let s = s.trim();
459    if s.is_empty() {
460        return None;
461    }
462
463    let (days, time_str) = match s.split_once('-') {
464        Some((d, rest)) => {
465            let days = d.parse::<u64>().ok()?;
466            (days, rest)
467        }
468        None => (0, s),
469    };
470
471    let parts: Vec<&str> = time_str.split(':').collect();
472    match parts.len() {
473        2 => {
474            let m = parts[0].parse::<u64>().ok()?;
475            let sec = parts[1].parse::<u64>().ok()?;
476            Some(days * 86400 + m * 60 + sec)
477        }
478        3 => {
479            let h = parts[0].parse::<u64>().ok()?;
480            let m = parts[1].parse::<u64>().ok()?;
481            let sec = parts[2].parse::<u64>().ok()?;
482            Some(days * 86400 + h * 3600 + m * 60 + sec)
483        }
484        _ => None,
485    }
486}
487
488fn get_process_etime(pid: i64) -> Option<u64> {
489    // macOS: ask the kernel for the start time. `ps` is setuid there, so blyte's own sandbox
490    // cannot run it, and this also saves a process per PID.
491    #[cfg(target_os = "macos")]
492    {
493        let mut info: libc::proc_bsdinfo = unsafe { std::mem::zeroed() };
494        let size = std::mem::size_of::<libc::proc_bsdinfo>() as libc::c_int;
495        let ret = unsafe {
496            libc::proc_pidinfo(
497                pid as libc::c_int,
498                libc::PROC_PIDTBSDINFO,
499                0,
500                &mut info as *mut _ as *mut libc::c_void,
501                size,
502            )
503        };
504        if ret == size && info.pbi_start_tvsec > 0 {
505            let now = std::time::SystemTime::now()
506                .duration_since(UNIX_EPOCH)
507                .map(|d| d.as_secs())
508                .unwrap_or(0);
509            return Some(now.saturating_sub(info.pbi_start_tvsec));
510        }
511    }
512
513    if let Ok(output) = std::process::Command::new("ps")
514        .args(["-o", "etime=", "-p", &pid.to_string()])
515        .output()
516    {
517        if output.status.success() {
518            let s = String::from_utf8_lossy(&output.stdout);
519            if let Some(sec) = parse_etime(&s) {
520                return Some(sec);
521            }
522        }
523    }
524
525    None
526}
527
528#[derive(serde::Deserialize, Debug)]
529struct AgySummary {
530    status: Option<String>,
531    error: Option<String>,
532    duration_seconds: Option<f64>,
533    num_turns: Option<u64>,
534    response: Option<String>,
535}
536
537struct RawJob {
538    id: String,
539    repo: String,
540    root: Option<PathBuf>,
541    task: String,
542    task_file: Option<String>,
543    pid: Option<i64>,
544    started_at: Option<u64>,
545    research: bool,
546    start_plan: Option<String>,
547    start_plan_task: Option<String>,
548    file_tags: Vec<String>,
549    log_path: PathBuf,
550    report_path: PathBuf,
551    tags_path: PathBuf,
552    verdict_path: PathBuf,
553    worktree: Option<String>,
554    commits: Vec<CommitRecord>,
555    changed_files: Vec<String>,
556    summary_final_msg: Option<String>,
557    is_runs_dir: bool,
558    agy_summary_path: Option<PathBuf>,
559}
560
561pub fn repo_name(checkout: &Path) -> String {
562    let from_git = std::process::Command::new("git")
563        .args(["rev-parse", "--path-format=absolute", "--git-common-dir"])
564        .current_dir(checkout)
565        .output()
566        .ok()
567        .filter(|out| out.status.success())
568        .and_then(|out| {
569            let s = String::from_utf8_lossy(&out.stdout);
570            let common = PathBuf::from(s.trim());
571            if common.file_name().and_then(|n| n.to_str()) == Some(".git") {
572                common
573                    .parent()
574                    .and_then(|p| p.file_name())
575                    .and_then(|n| n.to_str())
576                    .map(|n| n.to_string())
577            } else {
578                None
579            }
580        });
581
582    let raw = from_git.unwrap_or_else(|| {
583        checkout
584            .file_name()
585            .and_then(|n| n.to_str())
586            .map(|n| n.to_string())
587            .or_else(|| {
588                checkout
589                    .canonicalize()
590                    .ok()
591                    .as_deref()
592                    .and_then(Path::file_name)
593                    .and_then(|n| n.to_str())
594                    .map(|n| n.to_string())
595            })
596            .unwrap_or_else(|| "unknown".to_string())
597    });
598
599    if let Some((prefix, _)) = raw.split_once("--") {
600        if !prefix.is_empty() {
601            return prefix.to_string();
602        }
603    }
604    raw
605}
606
607pub fn collect_jobs(src: &Sources, now: u64) -> Vec<Job> {
608    let mut raw_jobs = Vec::new();
609    let mut seen_keys = HashSet::new();
610
611    // 1. Dispatch layout
612    let mut wt_dirs = Vec::new();
613    for root in &src.roots {
614        let r_wt = root.join(".wt");
615        if r_wt.is_dir() && !wt_dirs.contains(&r_wt) {
616            wt_dirs.push(r_wt);
617        }
618        if let Ok(entries) = std::fs::read_dir(root) {
619            for entry in entries.flatten() {
620                let path = entry.path();
621                if path.is_dir() {
622                    let c_wt = path.join(".wt");
623                    if c_wt.is_dir() && !wt_dirs.contains(&c_wt) {
624                        wt_dirs.push(c_wt);
625                    }
626                }
627            }
628        }
629    }
630
631    for wt_dir in &wt_dirs {
632        let repo = wt_dir
633            .parent()
634            .map(repo_name)
635            .unwrap_or_else(|| "unknown".to_string());
636
637        if let Ok(entries) = std::fs::read_dir(wt_dir) {
638            for entry in entries.flatten() {
639                let fname = entry.file_name().to_string_lossy().to_string();
640                if let Some(id) = fname.strip_suffix(".start.json") {
641                    let id = id.to_string();
642                    let key = format!("{repo}/{id}");
643                    if !seen_keys.insert(key) {
644                        continue;
645                    }
646
647                    let start_path = wt_dir.join(format!("{id}.start.json"));
648                    let start_val = std::fs::read_to_string(&start_path)
649                        .ok()
650                        .and_then(|s| serde_json::from_str::<serde_json::Value>(&s).ok());
651                    let pid = start_val.as_ref().and_then(|v| v["pid"].as_i64());
652                    let started_at = start_val.as_ref().and_then(|v| v["started_at"].as_u64());
653                    let research = start_val
654                        .as_ref()
655                        .and_then(|v| v.get("research"))
656                        .and_then(|v| v.as_bool())
657                        .unwrap_or(false);
658                    let start_plan = start_val
659                        .as_ref()
660                        .and_then(|v| v["plan"].as_str())
661                        .map(|s| s.to_string())
662                        .filter(|s| !s.is_empty());
663                    let start_plan_task = start_val
664                        .as_ref()
665                        .and_then(|v| v["plan_task"].as_str())
666                        .map(|s| s.to_string())
667                        .filter(|s| !s.is_empty());
668                    let task_file = start_val
669                        .as_ref()
670                        .and_then(|v| v["task_file"].as_str())
671                        .map(|s| s.to_string());
672                    let task = task_file
673                        .as_deref()
674                        .and_then(|p| std::fs::read_to_string(p).ok())
675                        .unwrap_or_default();
676                    let mut file_tags = Vec::new();
677                    if let Some(tags_arr) = start_val.as_ref().and_then(|v| v["tags"].as_array()) {
678                        for t in tags_arr {
679                            if let Some(s) = t.as_str() {
680                                file_tags.push(s.to_string());
681                            }
682                        }
683                    }
684                    if let Some(s) = start_val
685                        .as_ref()
686                        .and_then(|v| v["session"].as_str())
687                        .filter(|s| !s.is_empty())
688                    {
689                        let prefix: String = s.chars().take(8).collect();
690                        let tag = format!("session:{prefix}");
691                        if !file_tags.contains(&tag) {
692                            file_tags.push(tag);
693                        }
694                    }
695
696                    let summary_path = wt_dir.join(format!("{id}.json"));
697                    let mut commits = Vec::new();
698                    let mut changed_files = Vec::new();
699                    let mut summary_final_msg = None;
700                    let mut worktree = None;
701                    if summary_path.is_file() {
702                        if let Ok(content) = std::fs::read_to_string(&summary_path) {
703                            if let Ok(val) = serde_json::from_str::<serde_json::Value>(&content) {
704                                if let Some(arr) = val["commits"].as_array() {
705                                    for c in arr {
706                                        if let (Some(sha), Some(subject)) =
707                                            (c["sha"].as_str(), c["subject"].as_str())
708                                        {
709                                            commits.push(CommitRecord {
710                                                sha: sha.to_string(),
711                                                subject: subject.to_string(),
712                                            });
713                                        }
714                                    }
715                                }
716                                if let Some(arr) = val["changed_files"].as_array() {
717                                    for f in arr {
718                                        if let Some(s) = f.as_str() {
719                                            changed_files.push(s.to_string());
720                                        }
721                                    }
722                                }
723                                summary_final_msg =
724                                    val["final_message"].as_str().map(|s| s.to_string());
725                                worktree = val["worktree"].as_str().map(|s| s.to_string());
726                            }
727                        }
728                    }
729
730                    raw_jobs.push(RawJob {
731                        id: id.clone(),
732                        repo: repo.clone(),
733                        root: wt_dir.parent().map(|p| p.to_path_buf()),
734                        task,
735                        task_file,
736                        pid,
737                        started_at,
738                        research,
739                        start_plan,
740                        start_plan_task,
741                        file_tags,
742                        log_path: wt_dir.join(format!("{id}.log")),
743                        report_path: wt_dir.join(format!("{id}.report.json")),
744                        tags_path: wt_dir.join(format!("{id}.tags.json")),
745                        verdict_path: wt_dir.join(format!("{id}.verdict.json")),
746                        worktree,
747                        commits,
748                        changed_files,
749                        summary_final_msg,
750                        is_runs_dir: false,
751                        agy_summary_path: None,
752                    });
753                }
754            }
755        }
756    }
757
758    // 2. Runs-dir layout
759    for runs_dir in &src.runs_dirs {
760        if let Ok(repo_entries) = std::fs::read_dir(runs_dir) {
761            for repo_entry in repo_entries.flatten() {
762                let repo_path = repo_entry.path();
763                if repo_path.is_dir() {
764                    let repo = repo_path
765                        .file_name()
766                        .and_then(|n| n.to_str())
767                        .unwrap_or("unknown")
768                        .to_string();
769
770                    if let Ok(entries) = std::fs::read_dir(&repo_path) {
771                        for entry in entries.flatten() {
772                            let fname = entry.file_name().to_string_lossy().to_string();
773                            if let Some(id) = fname.strip_suffix(".log") {
774                                let id = id.to_string();
775                                let key = format!("{repo}/{id}");
776                                if !seen_keys.insert(key) {
777                                    continue;
778                                }
779
780                                let pid_path = repo_path.join(format!("{id}.pid"));
781                                let (pid, started_at) = if pid_path.is_file() {
782                                    let pid_text =
783                                        std::fs::read_to_string(&pid_path).unwrap_or_default();
784                                    let pid = pid_text.trim().parse::<i64>().ok();
785                                    let mtime = file_mtime(&pid_path);
786                                    (pid, mtime)
787                                } else {
788                                    (None, None)
789                                };
790
791                                let prompt_path = repo_path.join(format!("{id}.prompt"));
792                                let task = if prompt_path.is_file() {
793                                    std::fs::read_to_string(&prompt_path).unwrap_or_default()
794                                } else {
795                                    String::new()
796                                };
797
798                                let worktree_path = repo_path.join(format!("{id}.worktree"));
799                                let worktree = if worktree_path.is_file() {
800                                    std::fs::read_to_string(&worktree_path)
801                                        .ok()
802                                        .map(|s| s.trim().to_string())
803                                        .filter(|s| !s.is_empty())
804                                } else {
805                                    None
806                                };
807
808                                let root = worktree.as_ref().and_then(|wt_str| {
809                                    let p = Path::new(wt_str.trim_end_matches('/'));
810                                    if p.exists() {
811                                        if let Ok(out) = std::process::Command::new("git")
812                                            .args(["rev-parse", "--git-common-dir"])
813                                            .current_dir(p)
814                                            .output()
815                                        {
816                                            if out.status.success() {
817                                                let s = String::from_utf8_lossy(&out.stdout)
818                                                    .trim()
819                                                    .to_string();
820                                                let common = PathBuf::from(s);
821                                                let abs = if common.is_relative() {
822                                                    p.join(common)
823                                                } else {
824                                                    common
825                                                };
826                                                if abs.file_name().and_then(|n| n.to_str())
827                                                    == Some(".git")
828                                                {
829                                                    if let Some(parent) = abs.parent() {
830                                                        return Some(parent.to_path_buf());
831                                                    }
832                                                }
833                                            }
834                                        }
835                                    }
836                                    if p.parent()
837                                        .and_then(|par| par.file_name())
838                                        .and_then(|n| n.to_str())
839                                        == Some(".wt")
840                                    {
841                                        return p
842                                            .parent()
843                                            .and_then(|par| par.parent())
844                                            .map(Path::to_path_buf);
845                                    }
846                                    if let (Some(par), Some(grandpar)) =
847                                        (p.parent(), p.parent().and_then(|par| par.parent()))
848                                    {
849                                        if par.file_name().and_then(|n| n.to_str())
850                                            == Some("worktrees")
851                                            && grandpar.file_name().and_then(|n| n.to_str())
852                                                == Some(".claude")
853                                        {
854                                            return grandpar.parent().map(Path::to_path_buf);
855                                        }
856                                    }
857                                    if let Some(file_name) = p.file_name().and_then(|n| n.to_str())
858                                    {
859                                        if let Some((base, _)) = file_name.split_once("--") {
860                                            if !base.is_empty() {
861                                                return p.parent().map(|par| par.join(base));
862                                            }
863                                        }
864                                    }
865                                    Some(p.to_path_buf())
866                                });
867
868                                let agy_summary_path = {
869                                    let p = repo_path.join(format!("{id}.json"));
870                                    if p.is_file() {
871                                        Some(p)
872                                    } else {
873                                        None
874                                    }
875                                };
876
877                                raw_jobs.push(RawJob {
878                                    id: id.clone(),
879                                    repo: repo.clone(),
880                                    root,
881                                    task,
882                                    task_file: None,
883                                    pid,
884                                    started_at,
885                                    research: false,
886                                    start_plan: None,
887                                    start_plan_task: None,
888                                    file_tags: Vec::new(),
889                                    log_path: repo_path.join(format!("{id}.log")),
890                                    report_path: repo_path.join(format!("{id}.report.json")),
891                                    tags_path: repo_path.join(format!("{id}.tags.json")),
892                                    verdict_path: repo_path.join(format!("{id}.verdict.json")),
893                                    worktree,
894                                    commits: Vec::new(),
895                                    changed_files: Vec::new(),
896                                    summary_final_msg: None,
897                                    is_runs_dir: true,
898                                    agy_summary_path,
899                                });
900                            }
901                        }
902                    }
903                }
904            }
905        }
906    }
907
908    let mut jobs = Vec::new();
909    let mut plan_cache: std::collections::HashMap<PathBuf, Option<String>> =
910        std::collections::HashMap::new();
911
912    for raw in raw_jobs {
913        let title = job_title(&raw.task, &raw.id);
914        let plan = extract_plan(&raw.task);
915        let prompt_task_title = extract_prompt_task_title(&raw.task);
916        let plan_file = raw.start_plan.clone().or_else(|| plan.clone());
917        let plan_task = raw.start_plan_task.clone().or_else(|| {
918            prompt_task_title
919                .clone()
920                .or_else(|| extract_first_task_id(&raw.task))
921        });
922
923        let task_content = if let (Some(ref p_str), Some(ref t_title)) = (&plan, &prompt_task_title)
924        {
925            let p_path = if let Some(home) = std::env::var_os("HOME").map(PathBuf::from) {
926                expand_home(p_str, &home)
927            } else {
928                PathBuf::from(p_str)
929            };
930            let cached_plan = plan_cache
931                .entry(p_path.clone())
932                .or_insert_with(|| std::fs::read_to_string(&p_path).ok());
933            if let Some(plan_text) = cached_plan {
934                extract_task_from_plan(plan_text, t_title).unwrap_or_else(|| raw.task.clone())
935            } else {
936                raw.task.clone()
937            }
938        } else {
939            raw.task.clone()
940        };
941
942        let mut file_tags = raw.file_tags.clone();
943        if raw.tags_path.is_file() {
944            if let Ok(content) = std::fs::read_to_string(&raw.tags_path) {
945                if let Ok(arr) = serde_json::from_str::<Vec<String>>(&content) {
946                    for t in arr {
947                        if !file_tags.contains(&t) {
948                            file_tags.push(t);
949                        }
950                    }
951                }
952            }
953        }
954
955        let mut tags = Vec::new();
956        tags.push(format!("repo: {}", raw.repo));
957        if let Some(ref p) = plan {
958            if let Some(stem) = Path::new(p).file_stem().and_then(|s| s.to_str()) {
959                tags.push(format!("plan: {stem}"));
960            }
961        }
962        for t in &file_tags {
963            if !tags.contains(t) {
964                tags.push(t.clone());
965            }
966        }
967
968        let (verdict, verdict_notes, verdict_ts) = if raw.verdict_path.is_file() {
969            let val = std::fs::read_to_string(&raw.verdict_path)
970                .ok()
971                .and_then(|s| serde_json::from_str::<serde_json::Value>(&s).ok());
972            let v = val
973                .as_ref()
974                .and_then(|obj| obj["verdict"].as_str().map(|s| s.to_string()));
975            let notes = val
976                .as_ref()
977                .and_then(|obj| obj["notes"].as_str().map(|s| s.to_string()));
978            let ts = val
979                .as_ref()
980                .and_then(|obj| obj["ts"].as_u64())
981                .or_else(|| file_mtime(&raw.verdict_path));
982            (v, notes, ts)
983        } else {
984            (None, None, None)
985        };
986
987        let log_info = parse_log(&raw.log_path);
988
989        let report_json = if raw.report_path.is_file() {
990            std::fs::read_to_string(&raw.report_path)
991                .ok()
992                .and_then(|s| serde_json::from_str::<serde_json::Value>(&s).ok())
993        } else {
994            None
995        };
996
997        let report_mtime = if raw.report_path.is_file() {
998            file_mtime(&raw.report_path)
999        } else {
1000            None
1001        };
1002
1003        let agy_summary = if report_json.is_none() {
1004            raw.agy_summary_path.as_ref().and_then(|p| {
1005                std::fs::read_to_string(p)
1006                    .ok()
1007                    .and_then(|s| serde_json::from_str::<AgySummary>(&s).ok())
1008            })
1009        } else {
1010            None
1011        };
1012
1013        let (
1014            status,
1015            gate_running,
1016            cost_usd,
1017            turns,
1018            gate_attempts,
1019            gate_failures,
1020            model,
1021            finished_at,
1022            elapsed_s,
1023            now_str,
1024        ) = if let Some(ref report) = report_json {
1025            let outcome = report["outcome"].as_str().unwrap_or("unknown").to_string();
1026            let cost = report["cost_usd"].as_f64();
1027            let turns = report["turns"].as_u64().unwrap_or(log_info.turns);
1028            let gate_attempts = report["gate_attempts"]
1029                .as_u64()
1030                .unwrap_or(log_info.gate_attempts);
1031            let model = report["model_id"].as_str().map(|s| s.to_string());
1032
1033            let gate_failures = report["gate_failures"]
1034                .as_array()
1035                .map(|arr| {
1036                    let skip = arr.len().saturating_sub(2);
1037                    arr.iter()
1038                        .skip(skip)
1039                        .map(|v| {
1040                            let s = v.as_str().unwrap_or("");
1041                            let count = s.chars().count();
1042                            if count > 1500 {
1043                                s.chars().skip(count - 1500).collect()
1044                            } else {
1045                                s.to_string()
1046                            }
1047                        })
1048                        .collect()
1049                })
1050                .unwrap_or_default();
1051
1052            let finished_at = report_mtime;
1053            let elapsed_s = if let Some(dur) = report["duration_seconds"].as_f64() {
1054                Some(dur.round() as u64)
1055            } else if let (Some(fin), Some(st)) = (finished_at, raw.started_at) {
1056                if fin >= st {
1057                    Some(fin - st)
1058                } else {
1059                    None
1060                }
1061            } else {
1062                None
1063            };
1064
1065            let report_final_msg = report["final_message"].as_str();
1066            let now_from_msg = raw
1067                .summary_final_msg
1068                .as_deref()
1069                .or(report_final_msg)
1070                .map(extract_now_from_final_message)
1071                .filter(|s| !s.is_empty());
1072            let now_str = if let Some(s) = now_from_msg {
1073                s
1074            } else if let Some(ref tool) = log_info.last_tool {
1075                tool.clone()
1076            } else {
1077                String::new()
1078            };
1079
1080            (
1081                outcome,
1082                false,
1083                cost,
1084                turns,
1085                gate_attempts,
1086                gate_failures,
1087                model,
1088                finished_at,
1089                elapsed_s,
1090                now_str,
1091            )
1092        } else if let Some(ref agy) = agy_summary {
1093            let status = if agy.status.as_deref() == Some("ERROR") {
1094                "error".to_string()
1095            } else {
1096                "finished".to_string()
1097            };
1098            let cost = None;
1099            let turns = agy.num_turns.unwrap_or(log_info.turns);
1100            let gate_attempts = log_info.gate_attempts;
1101            let gate_failures = Vec::new();
1102            let model = None;
1103            let finished_at = raw.agy_summary_path.as_ref().and_then(|p| file_mtime(p));
1104            let elapsed_s = agy.duration_seconds.map(|d| d.round() as u64);
1105            let now_str = if status == "error" {
1106                let err = agy.error.as_deref().unwrap_or("");
1107                let s = extract_now_from_final_message(err);
1108                if !s.is_empty() {
1109                    s
1110                } else {
1111                    err.lines().next().unwrap_or("").chars().take(200).collect()
1112                }
1113            } else {
1114                let resp = agy.response.as_deref().unwrap_or("");
1115                let s = extract_now_from_final_message(resp);
1116                if !s.is_empty() {
1117                    s
1118                } else {
1119                    resp.lines()
1120                        .next()
1121                        .unwrap_or("")
1122                        .chars()
1123                        .take(200)
1124                        .collect()
1125                }
1126            };
1127
1128            (
1129                status,
1130                false,
1131                cost,
1132                turns,
1133                gate_attempts,
1134                gate_failures,
1135                model,
1136                finished_at,
1137                elapsed_s,
1138                now_str,
1139            )
1140        } else {
1141            // A live PID is this job's only if that process started with the job, not after it.
1142            // Only runs-dir jobs are checked: their PID files outlive the job for days, and the
1143            // dispatch layout's test fixture fakes a start time before its own process.
1144            let started_with_job = |p: i64| match (get_process_etime(p), raw.started_at) {
1145                (Some(elapsed), Some(started_at)) => now.saturating_sub(elapsed) <= started_at + 60,
1146                _ => true,
1147            };
1148            let is_alive = raw.pid.is_some_and(|p| {
1149                p > 0
1150                    && unsafe { libc::kill(p as libc::pid_t, 0) == 0 }
1151                    && (!raw.is_runs_dir || started_with_job(p))
1152            });
1153            let status = if is_alive {
1154                "running".to_string()
1155            } else {
1156                "stopped".to_string()
1157            };
1158            let gate_running = if status == "running" {
1159                log_info.gate_running
1160            } else {
1161                false
1162            };
1163            let cost = None;
1164            let turns = log_info.turns;
1165            let gate_attempts = log_info.gate_attempts;
1166            let gate_failures = Vec::new();
1167            let model = None;
1168            let finished_at = None;
1169            let elapsed_s = if status == "running" {
1170                raw.started_at.map(|s| now.saturating_sub(s))
1171            } else {
1172                None
1173            };
1174            let now_str = log_info.last_tool.clone().unwrap_or_default();
1175
1176            (
1177                status,
1178                gate_running,
1179                cost,
1180                turns,
1181                gate_attempts,
1182                gate_failures,
1183                model,
1184                finished_at,
1185                elapsed_s,
1186                now_str,
1187            )
1188        };
1189
1190        // Rule 7: Kept: every running job, and any other job whose finished_at (or, with no
1191        // report, the log's modified time) is within hours of now.
1192        let keep = if status == "running" {
1193            true
1194        } else {
1195            let effective_finished = finished_at.or(log_info.mtime);
1196            if let Some(fin) = effective_finished {
1197                fin >= now.saturating_sub(src.hours * 3600)
1198            } else {
1199                false
1200            }
1201        };
1202        if !keep {
1203            continue;
1204        }
1205
1206        let task_truncated: String = task_content.chars().take(2000).collect();
1207        let worktree_exists = raw.worktree.as_deref().map(|wt| Path::new(wt).is_dir());
1208
1209        jobs.push(Job {
1210            key: format!("{}/{}", raw.repo, raw.id),
1211            id: raw.id,
1212            repo: raw.repo,
1213            status,
1214            gate_running,
1215            title,
1216            task: task_truncated,
1217            plan,
1218            now: now_str,
1219            started_at: raw.started_at,
1220            finished_at,
1221            elapsed_s,
1222            cost_usd,
1223            turns,
1224            gate_attempts,
1225            gate_failures,
1226            model,
1227            last_tool: log_info.last_tool,
1228            worktree: raw.worktree,
1229            worktree_exists,
1230            log: raw.log_path.display().to_string(),
1231            commits: raw.commits,
1232            changed_files: raw.changed_files,
1233            tags,
1234            verdict,
1235            root: raw.root,
1236            plan_file,
1237            plan_task,
1238            task_file: raw.task_file,
1239            start_plan: raw.start_plan,
1240            file_tags,
1241            verdict_notes,
1242            verdict_ts,
1243            log_mtime: log_info.mtime,
1244            research: raw.research,
1245        });
1246    }
1247
1248    // Sort jobs: running jobs first, newest started_at first; then the rest, newest finished_at first.
1249    jobs.sort_by(|a, b| {
1250        let a_running = a.status == "running";
1251        let b_running = b.status == "running";
1252        match (a_running, b_running) {
1253            (true, false) => std::cmp::Ordering::Less,
1254            (false, true) => std::cmp::Ordering::Greater,
1255            (true, true) => b
1256                .started_at
1257                .unwrap_or(0)
1258                .cmp(&a.started_at.unwrap_or(0))
1259                .then_with(|| a.key.cmp(&b.key)),
1260            (false, false) => {
1261                let a_fin = a.finished_at.or(a.log_mtime).unwrap_or(0);
1262                let b_fin = b.finished_at.or(b.log_mtime).unwrap_or(0);
1263                b_fin.cmp(&a_fin).then_with(|| a.key.cmp(&b.key))
1264            }
1265        }
1266    });
1267
1268    jobs
1269}
1270
1271pub fn collect(src: &Sources, now: u64) -> serde_json::Value {
1272    let jobs = collect_jobs(src, now);
1273    let running = jobs.iter().filter(|j| j.status == "running").count();
1274    let last_24h = jobs
1275        .iter()
1276        .filter(|j| {
1277            j.started_at
1278                .is_some_and(|s| s >= now.saturating_sub(24 * 3600))
1279        })
1280        .count();
1281    let repos = jobs.iter().map(|j| &j.repo).collect::<HashSet<_>>().len();
1282
1283    let finished_jobs: Vec<_> = jobs
1284        .iter()
1285        .filter(|j| {
1286            j.status != "running"
1287                && j.finished_at
1288                    .or(j.log_mtime)
1289                    .is_some_and(|f| f >= now.saturating_sub(24 * 3600))
1290        })
1291        .collect();
1292
1293    let finished_24h = finished_jobs.len();
1294    let passed_24h = finished_jobs
1295        .iter()
1296        .filter(|j| j.status == "verified")
1297        .count();
1298    let sum_cost: f64 = finished_jobs.iter().filter_map(|j| j.cost_usd).sum();
1299    let cost_24h_usd = (sum_cost * 100.0).round() / 100.0;
1300
1301    let response = DashboardResponse {
1302        generated_at: now,
1303        summary: Summary {
1304            running,
1305            last_24h,
1306            repos,
1307            finished_24h,
1308            passed_24h,
1309            cost_24h_usd,
1310        },
1311        jobs,
1312    };
1313
1314    serde_json::to_value(&response).unwrap()
1315}
1316
1317pub fn route(path: &str, src: &Sources) -> (u16, &'static str, Vec<u8>) {
1318    let clean_path = path.split('?').next().unwrap_or(path);
1319    match clean_path {
1320        "/" | "/index.html" => {
1321            let html = include_str!("../assets/dashboard/index.html");
1322            (200, "text/html; charset=utf-8", html.as_bytes().to_vec())
1323        }
1324        "/favicon.svg" => {
1325            let svg = include_bytes!("../assets/dashboard/favicon.svg");
1326            (200, "image/svg+xml", svg.to_vec())
1327        }
1328        "/fonts/archivo.woff2" => {
1329            let font = include_bytes!("../assets/dashboard/fonts/archivo.woff2");
1330            (200, "font/woff2", font.to_vec())
1331        }
1332        "/fonts/plex-mono-400.woff2" => {
1333            let font = include_bytes!("../assets/dashboard/fonts/plex-mono-400.woff2");
1334            (200, "font/woff2", font.to_vec())
1335        }
1336        "/fonts/plex-mono-500.woff2" => {
1337            let font = include_bytes!("../assets/dashboard/fonts/plex-mono-500.woff2");
1338            (200, "font/woff2", font.to_vec())
1339        }
1340        "/api/jobs" => {
1341            let now = std::time::SystemTime::now()
1342                .duration_since(UNIX_EPOCH)
1343                .map(|d| d.as_secs())
1344                .unwrap_or(0);
1345            let val = collect(src, now);
1346            let body = serde_json::to_vec(&val).unwrap_or_default();
1347            (200, "application/json", body)
1348        }
1349        "/api/plans" => {
1350            let now = std::time::SystemTime::now()
1351                .duration_since(UNIX_EPOCH)
1352                .map(|d| d.as_secs())
1353                .unwrap_or(0);
1354            let query = path.split_once('?').map(|(_, q)| q).unwrap_or("");
1355            let running_only = query
1356                .split('&')
1357                .any(|p| p == "running=1" || p == "running=true");
1358            let val = crate::plans::collect_plans_filtered(src, now, running_only);
1359            let body = serde_json::to_vec(&val).unwrap_or_default();
1360            (200, "application/json", body)
1361        }
1362        _ => (404, "text/plain; charset=utf-8", b"Not Found\n".to_vec()),
1363    }
1364}
1365
1366fn handle_connection(mut stream: std::net::TcpStream, src: &Sources) {
1367    let mut reader = std::io::BufReader::new(&mut stream);
1368    let mut request_line = String::new();
1369    if reader.read_line(&mut request_line).is_err() || request_line.is_empty() {
1370        return;
1371    }
1372    drop(reader);
1373
1374    let parts: Vec<&str> = request_line.split_whitespace().collect();
1375    if parts.len() < 2 || parts[0] != "GET" {
1376        let not_found = b"Not Found\n";
1377        let header = format!(
1378            "HTTP/1.1 404 Not Found\r\nContent-Type: text/plain; charset=utf-8\r\nContent-Length: {}\r\nConnection: close\r\n\r\n",
1379            not_found.len()
1380        );
1381        let _ = stream.write_all(header.as_bytes());
1382        let _ = stream.write_all(not_found);
1383        let _ = stream.flush();
1384        return;
1385    }
1386
1387    let path = parts[1];
1388    let (code, ctype, body) = route(path, src);
1389    let clean_path = path.split('?').next().unwrap_or(path);
1390    let reason = match code {
1391        200 => "OK",
1392        404 => "Not Found",
1393        _ => "OK",
1394    };
1395    let extra = if clean_path == "/api/jobs" || clean_path == "/api/plans" {
1396        "Cache-Control: no-store\r\n"
1397    } else {
1398        ""
1399    };
1400    let header = format!(
1401        "HTTP/1.1 {code} {reason}\r\nContent-Type: {ctype}\r\nContent-Length: {}\r\n{extra}Connection: close\r\n\r\n",
1402        body.len()
1403    );
1404    let _ = stream.write_all(header.as_bytes());
1405    let _ = stream.write_all(&body);
1406    let _ = stream.flush();
1407}
1408
1409pub fn run(args: &crate::cli::DashboardArgs) -> i32 {
1410    let (sources, where_from) = Sources::from_args_with_where(args);
1411    let listener = match std::net::TcpListener::bind(format!("127.0.0.1:{}", args.port)) {
1412        Ok(l) => l,
1413        Err(e) => {
1414            eprintln!("error binding 127.0.0.1:{}: {e}", args.port);
1415            return 1;
1416        }
1417    };
1418
1419    let local_addr = match listener.local_addr() {
1420        Ok(a) => a,
1421        Err(e) => {
1422            eprintln!("error getting local address: {e}");
1423            return 1;
1424        }
1425    };
1426    let port = local_addr.port();
1427    let url = format!("http://127.0.0.1:{port}");
1428    if sources.roots.is_empty() && sources.runs_dirs.is_empty() {
1429        eprintln!(
1430            "blyte dashboard: nothing to watch yet: run blyte dispatch in a repository, or list roots in ~/.config/blyte/dashboard.toml"
1431        );
1432    } else {
1433        eprintln!(
1434            "blyte dashboard: watching {} repositories and {} run directories ({where_from})",
1435            sources.roots.len(),
1436            sources.runs_dirs.len()
1437        );
1438    }
1439    println!("blyte dashboard: {url}");
1440    let _ = std::io::stdout().flush();
1441
1442    if args.open {
1443        let cmd = if cfg!(target_os = "macos") {
1444            "open"
1445        } else {
1446            "xdg-open"
1447        };
1448        if let Err(e) = std::process::Command::new(cmd).arg(&url).spawn() {
1449            eprintln!("warning: failed to open browser: {e}");
1450        }
1451    }
1452
1453    let live = args.roots.is_empty() && args.runs_dirs.is_empty();
1454    let fixed_src = std::sync::Arc::new(sources);
1455    let args = std::sync::Arc::new(args.clone());
1456    for stream in listener.incoming() {
1457        match stream {
1458            Ok(stream) => {
1459                let fixed = std::sync::Arc::clone(&fixed_src);
1460                let args = std::sync::Arc::clone(&args);
1461                std::thread::spawn(move || {
1462                    if live {
1463                        let src = Sources::from_args(&args);
1464                        handle_connection(stream, &src);
1465                    } else {
1466                        handle_connection(stream, &fixed);
1467                    }
1468                });
1469            }
1470            Err(_) => {
1471                // Ignore transient errors
1472            }
1473        }
1474    }
1475
1476    0
1477}
1478
1479#[cfg(test)]
1480mod tests {
1481    use super::*;
1482
1483    #[test]
1484    fn extract_title_first_markdown_heading() {
1485        assert_eq!(
1486            extract_title(
1487                "From the plan docs/p.md:\n\n### Task G2: an empty gate is skipped\n\nbody"
1488            ),
1489            "Task G2: an empty gate is skipped"
1490        );
1491    }
1492
1493    #[test]
1494    fn extract_title_no_heading_fallback() {
1495        assert_eq!(extract_title("fix the bug\nmore"), "fix the bug");
1496    }
1497
1498    #[test]
1499    fn extract_title_task_rule_wins() {
1500        assert_eq!(
1501            extract_title("# Heading\nTask: \"explicit title\"\nmore"),
1502            "explicit title"
1503        );
1504    }
1505
1506    #[test]
1507    fn job_title_strips_task_id_prefix() {
1508        let text1 = "From the plan docs/p.md:\n\n### Task G2: an empty gate is skipped\n\nbody";
1509        assert_eq!(job_title(text1, "G2"), "an empty gate is skipped");
1510        assert_eq!(job_title("Task G3: x", "G2"), "Task G3: x");
1511        assert_eq!(job_title("Task G2:", "G2"), "Task G2:");
1512    }
1513
1514    #[test]
1515    fn session_tag_from_start_file() {
1516        let d = tempfile::tempdir().unwrap();
1517        let wt = d.path().join("repos/repo-a/.wt");
1518        std::fs::create_dir_all(&wt).unwrap();
1519
1520        let me = std::process::id();
1521        std::fs::write(
1522            wt.join("T1.start.json"),
1523            format!(r#"{{"id":"T1","pid":{me},"session":"4f83bf80-a445-4090","tags":["x"]}}"#),
1524        )
1525        .unwrap();
1526        std::fs::write(
1527            wt.join("T2.start.json"),
1528            format!(r#"{{"id":"T2","pid":{me},"session":"abc"}}"#),
1529        )
1530        .unwrap();
1531        std::fs::write(
1532            wt.join("T3.start.json"),
1533            format!(r#"{{"id":"T3","pid":{me},"tags":["x"]}}"#),
1534        )
1535        .unwrap();
1536        std::fs::write(
1537            wt.join("T4.start.json"),
1538            format!(r#"{{"id":"T4","pid":{me},"session":"4f83bf80-a445-4090","tags":["session:4f83bf80"]}}"#),
1539        )
1540        .unwrap();
1541
1542        let src = Sources {
1543            roots: vec![d.path().join("repos")],
1544            runs_dirs: vec![],
1545            hours: 24,
1546        };
1547        let now = std::time::SystemTime::now()
1548            .duration_since(std::time::UNIX_EPOCH)
1549            .unwrap()
1550            .as_secs();
1551        let jobs = collect_jobs(&src, now);
1552
1553        let t1 = jobs.iter().find(|j| j.id == "T1").unwrap();
1554        assert!(t1.tags.contains(&"x".to_string()));
1555        assert!(t1.tags.contains(&"session:4f83bf80".to_string()));
1556
1557        let t2 = jobs.iter().find(|j| j.id == "T2").unwrap();
1558        assert!(t2.tags.contains(&"session:abc".to_string()));
1559
1560        let t3 = jobs.iter().find(|j| j.id == "T3").unwrap();
1561        assert!(!t3.tags.iter().any(|t| t.starts_with("session:")));
1562
1563        let t4 = jobs.iter().find(|j| j.id == "T4").unwrap();
1564        assert_eq!(
1565            t4.tags
1566                .iter()
1567                .filter(|t| t.as_str() == "session:4f83bf80")
1568                .count(),
1569            1
1570        );
1571    }
1572}