Skip to main content

blyte_cli/
plans.rs

1//! Plan parser and plans collector for the dashboard (plan 2026-10-01).
2
3use std::collections::{HashMap, HashSet};
4use std::path::{Path, PathBuf};
5use std::sync::atomic::{AtomicUsize, Ordering};
6use std::sync::{LazyLock, RwLock};
7
8use crate::dashboard::{self, Job, Sources};
9
10static IS_MERGED_GIT_CALLS: AtomicUsize = AtomicUsize::new(0);
11
12type IsMergedKey = (PathBuf, String, String);
13type IsMergedCache = LazyLock<RwLock<HashMap<IsMergedKey, bool>>>;
14
15static IS_MERGED_CACHE: IsMergedCache = LazyLock::new(|| RwLock::new(HashMap::new()));
16static REPORTED_REMOVAL_ERRORS: LazyLock<RwLock<HashSet<String>>> =
17    LazyLock::new(|| RwLock::new(HashSet::new()));
18
19fn report_removal_record_error_with(err: &str, emit: impl FnOnce(&str)) {
20    let should_print = match REPORTED_REMOVAL_ERRORS.write() {
21        Ok(mut seen) => seen.insert(err.to_string()),
22        Err(_) => true,
23    };
24    if should_print {
25        emit(err);
26    }
27}
28
29pub(crate) fn is_merged_when_branch_gone(
30    root: &Path,
31    id: &str,
32    verdict: Option<&str>,
33) -> Result<bool, String> {
34    let removed_as_merged = crate::removal_record::read(root, id)?
35        .is_some_and(|rec| crate::removal_record::is_merged(&rec));
36    let accepted_or_fixed = verdict
37        .is_some_and(|v| v.eq_ignore_ascii_case("accepted") || v.eq_ignore_ascii_case("fixed"));
38    Ok(accepted_or_fixed || removed_as_merged)
39}
40
41pub fn is_merged_git_call_count() -> usize {
42    IS_MERGED_GIT_CALLS.load(Ordering::SeqCst)
43}
44
45pub fn reset_is_merged_git_call_count() {
46    IS_MERGED_GIT_CALLS.store(0, Ordering::SeqCst);
47}
48
49pub fn clear_is_merged_cache() {
50    if let Ok(mut cache) = IS_MERGED_CACHE.write() {
51        cache.clear();
52    }
53}
54
55#[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize)]
56pub struct PlanDoc {
57    pub title: String,
58    pub tasks: Vec<PlanTask>,
59    pub decisions: Vec<String>,
60}
61
62#[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize)]
63pub struct PlanTask {
64    pub id: String,
65    pub title: String,
66    pub heading: String,
67    pub deps: Vec<String>,
68    pub lane: String,
69    pub files: Vec<String>,
70}
71
72fn parse_task_deps(lines: &[&str], plan_task_ids: &HashSet<String>) -> Vec<String> {
73    let dep_line = lines
74        .iter()
75        .find(|l| {
76            let plain = l.replace("**", "").replace("__", "");
77            let trimmed = plain
78                .trim_start()
79                .trim_start_matches(['-', '*', '>'])
80                .trim_start();
81            trimmed.to_lowercase().starts_with("depends on:")
82        })
83        .or_else(|| {
84            lines.iter().find(|l| {
85                let plain = l.replace("**", "").replace("__", "");
86                plain.to_lowercase().contains("depends on:")
87            })
88        });
89
90    let target_line = if let Some(l) = dep_line {
91        *l
92    } else if let Some(l) = lines.iter().find(|l| {
93        let plain = l.replace("**", "").replace("__", "");
94        plain.trim_start().to_lowercase().starts_with("needs task")
95    }) {
96        *l
97    } else {
98        return Vec::new();
99    };
100
101    let plain = target_line.replace("**", "").replace("__", "");
102    let lower = plain.to_lowercase();
103
104    let Some(pos) = lower.find("depends on:") else {
105        if lower.contains("none") {
106            return Vec::new();
107        }
108        return extract_task_ids_from_line(&plain);
109    };
110
111    let after = &plain[pos + "depends on:".len()..];
112
113    let mut cut_end = after.len();
114    if let Some(p) = after.find('(') {
115        cut_end = cut_end.min(p);
116    }
117    if let Some(p) = after.find(';') {
118        cut_end = cut_end.min(p);
119    }
120    if let Some(p) = after.find(". ") {
121        cut_end = cut_end.min(p);
122    }
123    for (i, _) in after.char_indices() {
124        if let Some(sub) = after[i..].get(..9) {
125            if sub.eq_ignore_ascii_case("siblings:") {
126                cut_end = cut_end.min(i);
127                break;
128            }
129        }
130    }
131    let trimmed_end = after.trim_end();
132    if trimmed_end.ends_with('.') {
133        let dot_pos = trimmed_end.len() - 1;
134        cut_end = cut_end.min(dot_pos);
135    }
136
137    let clause = &after[..cut_end];
138
139    let lower_clause = clause.to_lowercase();
140    let trimmed = lower_clause
141        .trim()
142        .trim_matches(['.', '*', '`', '_', ';'])
143        .trim();
144    if trimmed == "none" || trimmed.starts_with("none ") || trimmed.starts_with("none,") {
145        return Vec::new();
146    }
147
148    let mut result = extract_task_ids_from_line(clause);
149
150    for token in clause.split([',', ' ', '\t', '\r', '\n']) {
151        let t = token
152            .trim()
153            .trim_matches(['`', '*', '_', '.', ':', '[', ']'])
154            .trim();
155        if t.is_empty() || t.eq_ignore_ascii_case("and") {
156            continue;
157        }
158        if plan_task_ids.contains(t) && !result.contains(&t.to_string()) {
159            result.push(t.to_string());
160        }
161    }
162
163    result
164}
165
166fn extract_task_ids_from_line(line: &str) -> Vec<String> {
167    let mut ids = Vec::new();
168    let chars: Vec<char> = line.chars().collect();
169    let len = chars.len();
170    let mut i = 0;
171
172    while i + 4 <= len {
173        let slice: String = chars[i..i + 4].iter().collect();
174        if slice.eq_ignore_ascii_case("task") {
175            let prev_ok = i == 0 || !chars[i - 1].is_alphanumeric();
176            let next_ok = i + 4 < len && (chars[i + 4] == ' ' || chars[i + 4] == '\t');
177            if prev_ok && next_ok {
178                let mut j = i + 4;
179                while j < len && (chars[j] == ' ' || chars[j] == '\t') {
180                    j += 1;
181                }
182                let id_start = j;
183                while j < len && (chars[j].is_alphanumeric() || chars[j] == '_' || chars[j] == '-')
184                {
185                    j += 1;
186                }
187                let token: String = chars[id_start..j].iter().collect();
188                if !token.is_empty() {
189                    let id = if token.chars().all(|c| c.is_ascii_digit()) {
190                        format!("T{token}")
191                    } else {
192                        token
193                    };
194                    if !ids.contains(&id) {
195                        ids.push(id);
196                    }
197                }
198                i = j;
199                continue;
200            }
201        }
202        i += 1;
203    }
204    ids
205}
206
207fn parse_task_files(lines: &[&str]) -> Vec<String> {
208    for line in lines {
209        let trimmed = line.trim();
210        if trimmed.starts_with("**Files:**")
211            || trimmed.starts_with("Files:")
212            || trimmed.contains("**Files:**")
213            || trimmed.contains("Files:")
214        {
215            let mut files = Vec::new();
216            let mut in_backtick = false;
217            let mut current = String::new();
218            for c in line.chars() {
219                if c == '`' {
220                    if in_backtick {
221                        let path = current.trim().to_string();
222                        if (path.contains('/') || path.contains('.'))
223                            && !path.contains(' ')
224                            && !path.is_empty()
225                        {
226                            files.push(path);
227                        }
228                        current.clear();
229                        in_backtick = false;
230                    } else {
231                        in_backtick = true;
232                    }
233                } else if in_backtick {
234                    current.push(c);
235                }
236            }
237            return files;
238        }
239    }
240    Vec::new()
241}
242
243fn parse_task_lane(lines: &[&str], files: &[String]) -> String {
244    for line in lines {
245        let trimmed = line.trim();
246        let plain = trimmed.replace("**", "");
247        if let Some(rest) = plain.strip_prefix("Lane:") {
248            let l = rest.trim();
249            if !l.is_empty() {
250                return l.to_string();
251            }
252        }
253    }
254    if let Some(first_file) = files.first() {
255        if let Some(rest) = first_file.strip_prefix("crates/") {
256            let x = rest.split('/').next().unwrap_or(rest);
257            x.to_string()
258        } else {
259            let first_comp = first_file.split('/').next().unwrap_or(first_file);
260            first_comp.to_string()
261        }
262    } else {
263        "Tasks".to_string()
264    }
265}
266
267fn parse_task_heading_id_title(h_text: &str) -> Option<(String, String)> {
268    let after_task = h_text.strip_prefix("Task ")?;
269    let (n_part, title_part) = after_task.split_once(':')?;
270    let n = n_part.trim();
271    let (first_word, rest_of_n) = match n.split_once(char::is_whitespace) {
272        Some((w, r)) => (w, r.trim()),
273        None => (n, ""),
274    };
275    if first_word.is_empty() {
276        return None;
277    }
278    let id = if first_word.chars().all(|c| c.is_ascii_digit()) {
279        format!("T{first_word}")
280    } else {
281        first_word.to_string()
282    };
283
284    let raw_title = if rest_of_n.is_empty() {
285        title_part.trim().to_string()
286    } else if title_part.trim().is_empty() {
287        rest_of_n.to_string()
288    } else {
289        format!("{rest_of_n} {}", title_part.trim())
290    };
291
292    let task_title = raw_title.replace('`', "").trim().to_string();
293    if task_title.is_empty() {
294        return None;
295    }
296
297    Some((id, task_title))
298}
299
300pub fn parse_plan(text: &str) -> PlanDoc {
301    let mut lines = Vec::new();
302    let mut in_fence = false;
303    for line in text.lines() {
304        let trimmed = line.trim();
305        if trimmed.starts_with("```") {
306            in_fence = !in_fence;
307            continue;
308        }
309        if !in_fence {
310            lines.push(line);
311        }
312    }
313
314    let mut title = String::new();
315    for line in &lines {
316        let trimmed = line.trim();
317        if let Some(rest) = trimmed.strip_prefix("# ") {
318            let t = rest.trim();
319            let t = t
320                .strip_suffix(" — Plan")
321                .or_else(|| t.strip_suffix(" – Plan"))
322                .or_else(|| t.strip_suffix(" - Plan"))
323                .unwrap_or(t);
324            title = t.trim().to_string();
325            break;
326        }
327    }
328
329    struct Heading {
330        level: usize,
331        text: String,
332        line_idx: usize,
333    }
334
335    let mut headings = Vec::new();
336
337    for (idx, line) in lines.iter().enumerate() {
338        let trimmed = line.trim();
339        let hashes = trimmed.chars().take_while(|&c| c == '#').count();
340        if (1..=4).contains(&hashes) {
341            let after = &trimmed[hashes..];
342            if after.starts_with(' ') || after.starts_with('\t') {
343                headings.push(Heading {
344                    level: hashes,
345                    text: after.trim().to_string(),
346                    line_idx: idx,
347                });
348            }
349        }
350    }
351
352    let mut plan_task_ids = HashSet::new();
353    for h in &headings {
354        if (2..=4).contains(&h.level) {
355            if let Some((id, _)) = parse_task_heading_id_title(&h.text) {
356                plan_task_ids.insert(id);
357            }
358        }
359    }
360
361    let mut tasks = Vec::new();
362    let mut decisions = Vec::new();
363
364    for (h_idx, h) in headings.iter().enumerate() {
365        let mut end_line = lines.len();
366        for next_h in &headings[h_idx + 1..] {
367            if next_h.level <= h.level {
368                end_line = next_h.line_idx;
369                break;
370            }
371        }
372        let section_lines = &lines[h.line_idx + 1..end_line];
373
374        if (2..=4).contains(&h.level) {
375            if let Some((id, task_title)) = parse_task_heading_id_title(&h.text) {
376                let heading = h.text.clone();
377                let deps = parse_task_deps(section_lines, &plan_task_ids);
378                let files = parse_task_files(section_lines);
379                let lane = parse_task_lane(section_lines, &files);
380
381                tasks.push(PlanTask {
382                    id,
383                    title: task_title,
384                    heading,
385                    deps,
386                    lane,
387                    files,
388                });
389            }
390        }
391
392        if h.text.eq_ignore_ascii_case("Decisions") {
393            for line in section_lines {
394                let trimmed = line.trim();
395                if let Some(bullet) = trimmed.strip_prefix("- ") {
396                    let b = bullet.trim();
397                    if !b.is_empty() {
398                        decisions.push(b.to_string());
399                    }
400                }
401            }
402        }
403    }
404
405    PlanDoc {
406        title,
407        tasks,
408        decisions,
409    }
410}
411
412fn matches_task(task: &PlanTask, pt: &str) -> bool {
413    let pt = pt.trim();
414    if pt.is_empty() {
415        return false;
416    }
417    let pt_clean = pt.replace('`', "");
418    let heading_clean = task.heading.replace('`', "");
419    if pt == task.heading
420        || pt == task.title
421        || pt == task.id
422        || pt_clean == task.title
423        || pt_clean == heading_clean
424    {
425        return true;
426    }
427    if let Some(after_task) = task.heading.strip_prefix("Task ") {
428        let n = after_task
429            .split_once(':')
430            .map(|(n, _)| n.trim())
431            .unwrap_or(after_task.trim());
432        let prefix = format!("Task {n}");
433        if let Some(rest) = pt.strip_prefix(&prefix) {
434            if rest.is_empty() || rest.starts_with(|c: char| !c.is_alphanumeric() && c != '_') {
435                return true;
436            }
437        }
438    }
439    let id_num = task.id.strip_prefix('T').unwrap_or(&task.id);
440    let id_prefix = format!("Task {id_num}");
441    if let Some(rest) = pt.strip_prefix(&id_prefix) {
442        if rest.is_empty() || rest.starts_with(|c: char| !c.is_alphanumeric() && c != '_') {
443            return true;
444        }
445    }
446    false
447}
448
449fn parse_added_task_id_and_title(
450    name: &str,
451    fallback_job_id: &str,
452    fallback_job_title: &str,
453) -> (String, String) {
454    let clean = name.replace('`', "");
455    let trimmed = clean.trim();
456    let after_task = if let Some(rest) = trimmed.strip_prefix("Task ") {
457        rest.trim_start()
458    } else {
459        trimmed
460    };
461
462    let first_token = after_task
463        .split(|c: char| c.is_whitespace() || c == ':')
464        .find(|s| !s.is_empty())
465        .unwrap_or("");
466    let id = if first_token.is_empty() {
467        fallback_job_id.to_string()
468    } else {
469        first_token.to_string()
470    };
471
472    let title_candidate = if let Some(rest) = after_task.strip_prefix(&id) {
473        let rest = rest.trim_start();
474        let rest = rest.strip_prefix(':').unwrap_or(rest);
475        rest.trim()
476    } else {
477        ""
478    };
479
480    let title = if title_candidate.is_empty() {
481        fallback_job_title.to_string()
482    } else {
483        title_candidate.to_string()
484    };
485
486    (id, title)
487}
488
489fn first_backticked_plan_path(text: &str) -> Option<String> {
490    let mut in_code_fence = false;
491    for line in text.lines() {
492        let trimmed = line.trim();
493        if trimmed.starts_with("```") {
494            in_code_fence = !in_code_fence;
495            continue;
496        }
497        if in_code_fence {
498            continue;
499        }
500        let mut in_backtick = false;
501        let mut current = String::new();
502        for c in line.chars() {
503            if c == '`' {
504                if in_backtick {
505                    let s = current.trim();
506                    if s.ends_with(".md") && s.contains("plans/") {
507                        return Some(s.to_string());
508                    }
509                    current.clear();
510                    in_backtick = false;
511                } else {
512                    in_backtick = true;
513                }
514            } else if in_backtick {
515                current.push(c);
516            }
517        }
518    }
519    None
520}
521
522fn find_tag_plan_stem(job: &Job) -> Option<String> {
523    for tag in &job.file_tags {
524        if let Some(rest) = tag.strip_prefix("plan:") {
525            let stem = rest.trim();
526            if !stem.is_empty() {
527                return Some(stem.to_string());
528            }
529        }
530    }
531    let synth = job.plan.as_ref().and_then(|p| {
532        Path::new(p)
533            .file_stem()
534            .and_then(|s| s.to_str())
535            .map(|s| format!("plan: {s}"))
536    });
537    for tag in &job.tags {
538        if let Some(ref s) = synth {
539            if tag == s {
540                continue;
541            }
542        }
543        if let Some(rest) = tag.strip_prefix("plan:") {
544            let stem = rest.trim();
545            if !stem.is_empty() {
546                return Some(stem.to_string());
547            }
548        }
549    }
550    None
551}
552
553fn resolve_bare_stem(
554    root: &Path,
555    stem: &str,
556    git_names_cache: &mut HashMap<PathBuf, Vec<String>>,
557) -> Option<PathBuf> {
558    let target = format!("{stem}.md");
559    let names = git_names_cache
560        .entry(root.to_path_buf())
561        .or_insert_with(|| {
562            let Ok(out) = std::process::Command::new("git")
563                .args(["log", "--all", "--format=", "--name-only"])
564                .current_dir(root)
565                .output()
566            else {
567                return Vec::new();
568            };
569            if !out.status.success() {
570                return Vec::new();
571            }
572            String::from_utf8_lossy(&out.stdout)
573                .lines()
574                .map(|l| l.trim().to_string())
575                .filter(|l| !l.is_empty())
576                .collect()
577        });
578
579    for name in names {
580        if Path::new(name).file_name().and_then(|n| n.to_str()) == Some(&target) {
581            return Some(PathBuf::from(name.as_str()));
582        }
583    }
584
585    if root.join(&target).is_file() {
586        return Some(PathBuf::from(&target));
587    }
588    for sub in &["docs/plans", "docs", "plans"] {
589        let candidate = Path::new(sub).join(&target);
590        if root.join(&candidate).is_file() {
591            return Some(candidate);
592        }
593    }
594
595    None
596}
597
598fn is_plan_task_file(path: &Path) -> bool {
599    let s = path.to_string_lossy();
600    if !s.ends_with(".md") {
601        return false;
602    }
603    let norm = s.replace('\\', "/");
604    let norm_path = Path::new(&norm);
605    let comps: Vec<&std::ffi::OsStr> = norm_path.components().map(|c| c.as_os_str()).collect();
606    for window in comps.windows(3) {
607        if window[0] == "docs" && window[1] == "superpowers" && window[2] == "plans" {
608            return true;
609        }
610    }
611    for window in comps.windows(2) {
612        if window[0] == "docs" && window[1] == "plans" {
613            return true;
614        }
615    }
616    false
617}
618
619fn extract_relpath(root: &Path, plan_path: &Path, job_wt: Option<&str>) -> PathBuf {
620    if plan_path.is_relative() {
621        let p_str = plan_path.to_string_lossy();
622        if let Some(stripped) = p_str.strip_prefix("./") {
623            return PathBuf::from(stripped);
624        }
625        return plan_path.to_path_buf();
626    }
627
628    // 1. inside <root>/.wt/<id>/
629    let wt_base = root.join(".wt");
630    if let Ok(rest) = plan_path.strip_prefix(&wt_base) {
631        let mut comps = rest.components();
632        if comps.next().is_some() {
633            let after_id = comps.as_path();
634            if !after_id.as_os_str().is_empty() {
635                return after_id.to_path_buf();
636            }
637        }
638    }
639
640    // 2. inside <root>/.claude/worktrees/<x>/
641    let claude_base = root.join(".claude").join("worktrees");
642    if let Ok(rest) = plan_path.strip_prefix(&claude_base) {
643        let mut comps = rest.components();
644        if comps.next().is_some() {
645            let after_x = comps.as_path();
646            if !after_x.as_os_str().is_empty() {
647                return after_x.to_path_buf();
648            }
649        }
650    }
651
652    // 3. sibling <root>--<x>/
653    if let (Some(root_parent), Some(root_name)) =
654        (root.parent(), root.file_name().and_then(|n| n.to_str()))
655    {
656        if let Ok(rest) = plan_path.strip_prefix(root_parent) {
657            let mut comps = rest.components();
658            if let Some(first) = comps.next() {
659                if let Some(first_str) = first.as_os_str().to_str() {
660                    let prefix = format!("{root_name}--");
661                    if first_str.starts_with(&prefix) {
662                        let after_prefix = comps.as_path();
663                        if !after_prefix.as_os_str().is_empty() {
664                            return after_prefix.to_path_buf();
665                        }
666                    }
667                }
668            }
669        }
670    }
671
672    // 4. inside root
673    if let Ok(rel) = plan_path.strip_prefix(root) {
674        if !rel.as_os_str().is_empty() {
675            return rel.to_path_buf();
676        }
677    }
678
679    // 5. inside job's worktree
680    if let Some(wt) = job_wt {
681        if let Ok(rel) = plan_path.strip_prefix(wt) {
682            if !rel.as_os_str().is_empty() {
683                return rel.to_path_buf();
684            }
685        }
686    }
687
688    plan_path.to_path_buf()
689}
690
691fn first_heading(text: &str) -> Option<String> {
692    let mut in_fence = false;
693    for line in text.lines() {
694        let trimmed = line.trim();
695        if trimmed.starts_with("```") {
696            in_fence = !in_fence;
697            continue;
698        }
699        if !in_fence && trimmed.starts_with('#') {
700            let without_hashes = trimmed.trim_start_matches('#').trim();
701            let without_suffix = without_hashes
702                .strip_suffix(" — Plan")
703                .or_else(|| without_hashes.strip_suffix(" – Plan"))
704                .or_else(|| without_hashes.strip_suffix(" - Plan"))
705                .unwrap_or(without_hashes);
706            let cleaned = without_suffix.trim().replace('`', "");
707            if !cleaned.is_empty() {
708                return Some(cleaned);
709            }
710        }
711    }
712    None
713}
714
715fn find_home_repo(plan_file_abs: &Path, jobs: &[&Job]) -> String {
716    // 1. For a plan inside a repository root, that root
717    for job in jobs {
718        if let Some(ref root) = job.root {
719            if plan_file_abs.starts_with(root) {
720                return dashboard::repo_name(root);
721            }
722        }
723    }
724
725    // 2. For an absolute plan path, the nearest ancestor directory containing .git
726    let mut curr = plan_file_abs.parent();
727    while let Some(dir) = curr {
728        if dir.join(".git").exists() {
729            return dashboard::repo_name(dir);
730        }
731        curr = dir.parent();
732    }
733
734    // 3. If none is found, the first job's repository
735    if let Some(first) = jobs.first() {
736        return first.repo.clone();
737    }
738
739    String::new()
740}
741
742fn read_plan_content(
743    plan_file_abs: &Path,
744    jobs: &[&Job],
745    cache: &mut HashMap<PathBuf, Option<String>>,
746) -> Option<String> {
747    if let Some(cached) = cache.get(plan_file_abs) {
748        return cached.clone();
749    }
750
751    // 1. <plan_file_abs> on disk
752    if let Ok(content) = std::fs::read_to_string(plan_file_abs) {
753        cache.insert(plan_file_abs.to_path_buf(), Some(content.clone()));
754        return Some(content);
755    }
756
757    // 2. the job's own worktree + relpath
758    for job in jobs {
759        if let Some(ref wt) = job.worktree {
760            let wt_base = Path::new(wt);
761            if let Some(ref r) = job.root {
762                if let Ok(rel) = plan_file_abs.strip_prefix(r) {
763                    let wt_path = wt_base.join(rel);
764                    if let Ok(content) = std::fs::read_to_string(&wt_path) {
765                        cache.insert(plan_file_abs.to_path_buf(), Some(content.clone()));
766                        return Some(content);
767                    }
768                }
769            }
770        }
771    }
772
773    // 3. each group job's absolute plan source path (the task_file, or an absolute start_plan) directly from disk
774    for job in jobs {
775        if let Some(ref tf) = job.task_file {
776            let p = Path::new(tf);
777            let matches_plan = p == plan_file_abs
778                || job.root.as_ref().is_some_and(|r| {
779                    r.join(extract_relpath(r, p, job.worktree.as_deref())) == *plan_file_abs
780                });
781            if matches_plan && p.is_file() {
782                if let Ok(content) = std::fs::read_to_string(p) {
783                    cache.insert(plan_file_abs.to_path_buf(), Some(content.clone()));
784                    return Some(content);
785                }
786            }
787        }
788        if let Some(ref sp) = job.start_plan {
789            let p = Path::new(sp);
790            let matches_plan = p == plan_file_abs
791                || job.root.as_ref().is_some_and(|r| {
792                    r.join(extract_relpath(r, p, job.worktree.as_deref())) == *plan_file_abs
793                });
794            if matches_plan && p.is_file() {
795                if let Ok(content) = std::fs::read_to_string(p) {
796                    cache.insert(plan_file_abs.to_path_buf(), Some(content.clone()));
797                    return Some(content);
798                }
799            }
800        }
801    }
802
803    // 4. git: git -C <root> log --all -1 --format=%H -- <relpath> and git -C <root> show <sha>:<relpath>
804    let mut git_roots = Vec::new();
805    for job in jobs {
806        if let Some(ref r) = job.root {
807            if !git_roots.contains(r) {
808                git_roots.push(r.clone());
809            }
810        }
811    }
812    let mut curr = plan_file_abs.parent();
813    while let Some(dir) = curr {
814        if dir.join(".git").exists() {
815            let d_buf = dir.to_path_buf();
816            if !git_roots.contains(&d_buf) {
817                git_roots.push(d_buf);
818            }
819            break;
820        }
821        curr = dir.parent();
822    }
823
824    for git_root in &git_roots {
825        if let Ok(rel) = plan_file_abs.strip_prefix(git_root) {
826            let rel_str = rel.to_string_lossy().to_string();
827            if let Ok(out) = std::process::Command::new("git")
828                .args(["log", "--all", "-1", "--format=%H", "--", &rel_str])
829                .current_dir(git_root)
830                .output()
831            {
832                if out.status.success() {
833                    let sha = String::from_utf8_lossy(&out.stdout).trim().to_string();
834                    if !sha.is_empty() {
835                        if let Ok(show_out) = std::process::Command::new("git")
836                            .args(["show", &format!("{sha}:{rel_str}")])
837                            .current_dir(git_root)
838                            .output()
839                        {
840                            if show_out.status.success() {
841                                let content = String::from_utf8_lossy(&show_out.stdout).to_string();
842                                cache.insert(plan_file_abs.to_path_buf(), Some(content.clone()));
843                                return Some(content);
844                            }
845                        }
846                    }
847                }
848            }
849        }
850    }
851
852    cache.insert(plan_file_abs.to_path_buf(), None);
853    None
854}
855
856pub fn is_merged(root: &Path, branch: &str, head: &str) -> bool {
857    let key = (root.to_path_buf(), branch.to_string(), head.to_string());
858    if let Ok(cache) = IS_MERGED_CACHE.read() {
859        if let Some(&res) = cache.get(&key) {
860            return res;
861        }
862    }
863
864    IS_MERGED_GIT_CALLS.fetch_add(1, Ordering::SeqCst);
865
866    let clean_branch = branch.strip_prefix("refs/heads/").unwrap_or(branch);
867    let mut merged = false;
868    if !head.is_empty() {
869        if let Ok(output) = std::process::Command::new("git")
870            .args(["branch", "--contains", head, "--format=%(refname:short)"])
871            .current_dir(root)
872            .output()
873        {
874            if output.status.success() {
875                let stdout = String::from_utf8_lossy(&output.stdout);
876                for line in stdout.lines() {
877                    let b = line.trim();
878                    if !b.is_empty()
879                        && b != clean_branch
880                        && !b.starts_with("wip/")
881                        && !b.starts_with('(')
882                    {
883                        merged = true;
884                        break;
885                    }
886                }
887            }
888        }
889    }
890
891    if let Ok(mut cache) = IS_MERGED_CACHE.write() {
892        cache.insert(key, merged);
893    }
894    merged
895}
896
897fn is_job_merged_with_error_reporter(job: &Job, emit_error: impl FnOnce(&str)) -> bool {
898    let Some(ref root) = job.root else {
899        return false;
900    };
901    let branch = format!("wip/{}", job.id);
902    if let Some(last_commit) = job.commits.last() {
903        if is_merged(root, &branch, &last_commit.sha) {
904            return true;
905        }
906    }
907
908    if job.id.is_empty() {
909        return false;
910    }
911
912    let branch_ref = format!("refs/heads/wip/{}", job.id);
913    let Ok(output) = std::process::Command::new("git")
914        .args(["rev-parse", "--verify", "--quiet", &branch_ref])
915        .current_dir(root)
916        .output()
917    else {
918        return false;
919    };
920    if output.status.success() {
921        return false;
922    }
923
924    match is_merged_when_branch_gone(root, &job.id, job.verdict.as_deref()) {
925        Ok(merged) => merged,
926        Err(e) => {
927            report_removal_record_error_with(&e, emit_error);
928            false
929        }
930    }
931}
932
933fn is_job_merged(job: &Job) -> bool {
934    is_job_merged_with_error_reporter(job, |e| eprintln!("blyte: {e}"))
935}
936
937fn choose_task_job<'a>(jobs: &[&'a Job]) -> Option<&'a Job> {
938    // 1. a job that is running (the latest running one);
939    if let Some(j) = jobs
940        .iter()
941        .copied()
942        .filter(|j| j.status == "running")
943        .max_by_key(|j| j.started_at.unwrap_or(0))
944    {
945        return Some(j);
946    }
947
948    // 2. else a verified job for which is_job_merged(job) is true (the latest such one);
949    if let Some(j) = jobs
950        .iter()
951        .copied()
952        .filter(|j| j.status == "verified" && is_job_merged(j))
953        .max_by_key(|j| j.started_at.unwrap_or(0))
954    {
955        return Some(j);
956    }
957
958    // 3. else a job whose verdict is accepted or fixed (the latest such one);
959    if let Some(j) = jobs
960        .iter()
961        .copied()
962        .filter(|j| {
963            j.verdict.as_deref().is_some_and(|v| {
964                v.eq_ignore_ascii_case("accepted") || v.eq_ignore_ascii_case("fixed")
965            })
966        })
967        .max_by_key(|j| j.started_at.unwrap_or(0))
968    {
969        return Some(j);
970    }
971
972    // 4. else the latest job, as today.
973    jobs.iter()
974        .copied()
975        .max_by_key(|j| j.started_at.unwrap_or(0))
976}
977
978struct PlanItem {
979    key: String,
980    has_running: bool,
981    latest_activity: u64,
982    val: serde_json::Value,
983}
984
985struct PlanEvent {
986    at: u64,
987    task: String,
988    text: String,
989}
990
991fn job_explicit_plan_relpath(
992    job: &Job,
993    git_names_cache: &mut HashMap<PathBuf, Vec<String>>,
994) -> Option<PathBuf> {
995    let root = job.root.as_ref()?;
996    if let Some(ref p) = job.start_plan {
997        if !p.contains('/') && !p.ends_with(".md") {
998            if let Some(rp) = resolve_bare_stem(root, p, git_names_cache) {
999                Some(rp)
1000            } else {
1001                Some(extract_relpath(root, Path::new(p), job.worktree.as_deref()))
1002            }
1003        } else {
1004            Some(extract_relpath(root, Path::new(p), job.worktree.as_deref()))
1005        }
1006    } else if let Some(stem) = find_tag_plan_stem(job) {
1007        if stem.contains('/') {
1008            Some(extract_relpath(
1009                root,
1010                Path::new(&stem),
1011                job.worktree.as_deref(),
1012            ))
1013        } else {
1014            let stem_clean = stem.strip_suffix(".md").unwrap_or(&stem);
1015            resolve_bare_stem(root, stem_clean, git_names_cache)
1016        }
1017    } else if let Some(ref p) = job.plan {
1018        Some(extract_relpath(root, Path::new(p), job.worktree.as_deref()))
1019    } else if let Some(ref tf) = job
1020        .task_file
1021        .as_ref()
1022        .filter(|tf| is_plan_task_file(Path::new(tf)))
1023    {
1024        Some(extract_relpath(
1025            root,
1026            Path::new(tf),
1027            job.worktree.as_deref(),
1028        ))
1029    } else {
1030        first_backticked_plan_path(&job.task)
1031            .map(|p| extract_relpath(root, Path::new(&p), job.worktree.as_deref()))
1032    }
1033}
1034
1035fn build_standalone_plan(
1036    job: &Job,
1037    plan_file_abs: &Path,
1038    content: &str,
1039    doc: &PlanDoc,
1040    now: u64,
1041) -> Option<PlanItem> {
1042    let seven_days = 7 * 24 * 3600;
1043    let is_active = job.status == "running"
1044        || job
1045            .started_at
1046            .is_some_and(|st| st >= now.saturating_sub(seven_days));
1047    if !is_active {
1048        return None;
1049    }
1050
1051    let heading_title = first_heading(content);
1052    let title = heading_title.unwrap_or_else(|| job.id.clone());
1053    let task_title = title.clone();
1054    let task_heading = title.clone();
1055
1056    let state = if job.status == "running" {
1057        "running".to_string()
1058    } else if job.verdict.as_deref() == Some("redone") {
1059        "redone".to_string()
1060    } else if job.status == "verified" {
1061        if is_job_merged(job) {
1062            "merged".to_string()
1063        } else {
1064            "verified".to_string()
1065        }
1066    } else {
1067        "failed".to_string()
1068    };
1069
1070    let files = if !job.changed_files.is_empty() {
1071        job.changed_files.clone()
1072    } else {
1073        Vec::new()
1074    };
1075
1076    let task_val = serde_json::json!({
1077        "id": job.id,
1078        "title": task_title,
1079        "heading": task_heading,
1080        "lane": "tasks",
1081        "deps": [],
1082        "state": state,
1083        "dispatch": job.key,
1084        "now": job.now,
1085        "gate_running": job.gate_running,
1086        "gate_attempts": job.gate_attempts,
1087        "elapsed_s": job.elapsed_s,
1088        "cost_usd": job.cost_usd,
1089        "turns": job.turns,
1090        "files": files,
1091        "commits": job.commits,
1092        "verdict": job.verdict,
1093        "notes": job.verdict_notes,
1094        "added": false,
1095    });
1096
1097    let mut events = Vec::new();
1098    if let Some(st) = job.started_at {
1099        events.push(PlanEvent {
1100            at: st,
1101            task: job.id.clone(),
1102            text: "dispatched".to_string(),
1103        });
1104    }
1105    if job.status != "running" {
1106        if let Some(fin) = job.finished_at.or(job.log_mtime) {
1107            events.push(PlanEvent {
1108                at: fin,
1109                task: job.id.clone(),
1110                text: job.status.clone(),
1111            });
1112        }
1113    }
1114    if let Some(ref v) = job.verdict {
1115        if let Some(ts) = job.verdict_ts {
1116            events.push(PlanEvent {
1117                at: ts,
1118                task: job.id.clone(),
1119                text: format!("verdict {v}"),
1120            });
1121        }
1122    }
1123    events.sort_by_key(|e| std::cmp::Reverse(e.at));
1124    let events_json: Vec<serde_json::Value> = events
1125        .into_iter()
1126        .map(|e| {
1127            serde_json::json!({
1128                "at": e.at,
1129                "task": e.task,
1130                "text": e.text,
1131            })
1132        })
1133        .collect();
1134
1135    let mut decisions_json = Vec::new();
1136    for d in &doc.decisions {
1137        decisions_json.push(serde_json::json!({
1138            "text": d,
1139            "source": "plan",
1140        }));
1141    }
1142    if let Some(ref notes) = job.verdict_notes {
1143        if !notes.trim().is_empty() {
1144            decisions_json.push(serde_json::json!({
1145                "text": notes,
1146                "source": format!("{} verdict note", job.id),
1147            }));
1148        }
1149    }
1150
1151    let (merged, verified, running, not_started) = match state.as_str() {
1152        "merged" => (1, 0, 0, 0),
1153        "verified" => (0, 1, 0, 0),
1154        "running" => (0, 0, 1, 0),
1155        "ready" | "waiting" => (0, 0, 0, 1),
1156        _ => (0, 0, 0, 0),
1157    };
1158    let cost_usd = job.cost_usd.unwrap_or(0.0);
1159    let cost_usd = (cost_usd * 100.0).round() / 100.0;
1160    let stats_json = serde_json::json!({
1161        "tasks": 1,
1162        "merged": merged,
1163        "verified": verified,
1164        "running": running,
1165        "not_started": not_started,
1166        "cost_usd": cost_usd,
1167        "first_dispatch_at": job.started_at,
1168        "max_parallel": if running > 0 { 1 } else { 0 },
1169    });
1170
1171    let key = format!("{}/{}", job.repo, job.id);
1172    let repo = job.repo.clone();
1173    let repos = vec![job.repo.clone()];
1174    let lanes = vec![serde_json::json!({
1175        "id": "tasks",
1176        "label": "Tasks",
1177    })];
1178    let path_str = plan_file_abs.to_string_lossy().to_string();
1179
1180    let has_running = running > 0;
1181    let latest_activity = events_json
1182        .first()
1183        .and_then(|e| e["at"].as_u64())
1184        .or(job.started_at)
1185        .unwrap_or(0);
1186
1187    let plan_val = serde_json::json!({
1188        "key": key,
1189        "repo": repo,
1190        "repos": repos,
1191        "path": path_str,
1192        "title": title,
1193        "lanes": lanes,
1194        "tasks": [task_val],
1195        "events": events_json,
1196        "decisions": decisions_json,
1197        "stats": stats_json,
1198    });
1199
1200    Some(PlanItem {
1201        key,
1202        has_running,
1203        latest_activity,
1204        val: plan_val,
1205    })
1206}
1207
1208#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
1209pub struct CollectPlansOptions {
1210    pub running_only: bool,
1211}
1212
1213pub fn collect_plans(src: &Sources, now: u64) -> serde_json::Value {
1214    collect_plans_with_options(src, now, CollectPlansOptions::default())
1215}
1216
1217pub fn collect_plans_running(src: &Sources, now: u64) -> serde_json::Value {
1218    collect_plans_with_options(src, now, CollectPlansOptions { running_only: true })
1219}
1220
1221pub fn collect_plans_filtered(src: &Sources, now: u64, running_only: bool) -> serde_json::Value {
1222    collect_plans_with_options(src, now, CollectPlansOptions { running_only })
1223}
1224
1225pub fn collect_plans_with_options(
1226    src: &Sources,
1227    now: u64,
1228    opts: CollectPlansOptions,
1229) -> serde_json::Value {
1230    let mut plan_src = src.clone();
1231    plan_src.hours = plan_src.hours.max(7 * 24);
1232    let jobs = dashboard::collect_jobs(&plan_src, now);
1233
1234    let mut git_names_cache: HashMap<PathBuf, Vec<String>> = HashMap::new();
1235    let mut plan_content_cache: HashMap<PathBuf, Option<String>> = HashMap::new();
1236
1237    let (active_plan_files, active_standalone_job_ids) = if opts.running_only {
1238        let running_jobs: Vec<&Job> = jobs
1239            .iter()
1240            .filter(|j| !j.research && j.root.is_some() && j.status == "running")
1241            .collect();
1242        if running_jobs.is_empty() {
1243            return serde_json::json!({
1244                "generated_at": now,
1245                "plans": [],
1246            });
1247        }
1248
1249        let mut plan_files = HashSet::new();
1250        let mut standalone_ids = HashSet::new();
1251
1252        for job in &running_jobs {
1253            let root = job.root.as_ref().unwrap();
1254            if let Some(rp) = job_explicit_plan_relpath(job, &mut git_names_cache) {
1255                let plan_file_abs = root.join(rp);
1256                plan_files.insert(plan_file_abs);
1257            } else if let Some(ref tf) = job.task_file {
1258                let tf_path = Path::new(tf);
1259                let relpath = extract_relpath(root, tf_path, job.worktree.as_deref());
1260                let plan_file_abs = root.join(&relpath);
1261                if let Some(content) =
1262                    read_plan_content(&plan_file_abs, &[job], &mut plan_content_cache)
1263                {
1264                    let doc = parse_plan(&content);
1265                    let pt = job.plan_task.as_deref().unwrap_or(&job.id);
1266                    if doc.tasks.iter().any(|t| matches_task(t, pt)) {
1267                        plan_files.insert(plan_file_abs);
1268                    } else {
1269                        standalone_ids.insert(job.id.clone());
1270                    }
1271                } else {
1272                    standalone_ids.insert(job.id.clone());
1273                }
1274            }
1275        }
1276
1277        if plan_files.is_empty() && standalone_ids.is_empty() {
1278            return serde_json::json!({
1279                "generated_at": now,
1280                "plans": [],
1281            });
1282        }
1283
1284        (Some(plan_files), Some(standalone_ids))
1285    } else {
1286        (None, None)
1287    };
1288
1289    let mut groups: HashMap<PathBuf, Vec<&Job>> = HashMap::new();
1290    let mut standalone_plans: Vec<PlanItem> = Vec::new();
1291
1292    for job in &jobs {
1293        if job.research {
1294            continue;
1295        }
1296        let Some(ref root) = job.root else {
1297            continue;
1298        };
1299
1300        if let Some(ref active_files) = active_plan_files {
1301            if let Some(rp) = job_explicit_plan_relpath(job, &mut git_names_cache) {
1302                let plan_file_abs = root.join(rp);
1303                if active_files.contains(&plan_file_abs) {
1304                    groups.entry(plan_file_abs).or_default().push(job);
1305                }
1306            } else if let Some(ref tf) = job.task_file {
1307                let tf_path = Path::new(tf);
1308                let relpath = extract_relpath(root, tf_path, job.worktree.as_deref());
1309                let plan_file_abs = root.join(&relpath);
1310                if active_files.contains(&plan_file_abs) {
1311                    if let Some(content) =
1312                        read_plan_content(&plan_file_abs, &[job], &mut plan_content_cache)
1313                    {
1314                        let doc = parse_plan(&content);
1315                        let pt = job.plan_task.as_deref().unwrap_or(&job.id);
1316                        if doc.tasks.iter().any(|t| matches_task(t, pt)) {
1317                            groups.entry(plan_file_abs).or_default().push(job);
1318                            continue;
1319                        }
1320                    }
1321                }
1322                if let Some(ref standalone_ids) = active_standalone_job_ids {
1323                    if standalone_ids.contains(&job.id) {
1324                        if let Some(content) =
1325                            read_plan_content(&plan_file_abs, &[job], &mut plan_content_cache)
1326                        {
1327                            let doc = parse_plan(&content);
1328                            if let Some(item) =
1329                                build_standalone_plan(job, &plan_file_abs, &content, &doc, now)
1330                            {
1331                                standalone_plans.push(item);
1332                            }
1333                        }
1334                    }
1335                }
1336            }
1337        } else {
1338            if let Some(rp) = job_explicit_plan_relpath(job, &mut git_names_cache) {
1339                let plan_file_abs = root.join(rp);
1340                groups.entry(plan_file_abs).or_default().push(job);
1341            } else {
1342                let Some(ref tf) = job.task_file else {
1343                    continue;
1344                };
1345                let tf_path = Path::new(tf);
1346                let relpath = extract_relpath(root, tf_path, job.worktree.as_deref());
1347                let plan_file_abs = root.join(&relpath);
1348                let Some(content) =
1349                    read_plan_content(&plan_file_abs, &[job], &mut plan_content_cache)
1350                else {
1351                    continue;
1352                };
1353                let doc = parse_plan(&content);
1354                let pt = job.plan_task.as_deref().unwrap_or(&job.id);
1355                let has_matching_task = doc.tasks.iter().any(|t| matches_task(t, pt));
1356                if has_matching_task {
1357                    groups.entry(plan_file_abs).or_default().push(job);
1358                    continue;
1359                }
1360
1361                if let Some(item) = build_standalone_plan(job, &plan_file_abs, &content, &doc, now)
1362                {
1363                    standalone_plans.push(item);
1364                }
1365            }
1366        }
1367    }
1368
1369    let mut plan_items = standalone_plans;
1370
1371    for (plan_file_abs, jobs_in_group) in groups {
1372        let Some(content) =
1373            read_plan_content(&plan_file_abs, &jobs_in_group, &mut plan_content_cache)
1374        else {
1375            continue;
1376        };
1377        let doc = parse_plan(&content);
1378        let repo = find_home_repo(&plan_file_abs, &jobs_in_group);
1379        let stem = plan_file_abs
1380            .file_stem()
1381            .and_then(|s| s.to_str())
1382            .unwrap_or("plan");
1383        let key = format!("{repo}/{stem}");
1384        let path_str = plan_file_abs.to_string_lossy().to_string();
1385
1386        let mut task_jobs: HashMap<String, Vec<&Job>> = HashMap::new();
1387        let mut all_matched_jobs: Vec<&Job> = Vec::new();
1388
1389        for task in &doc.tasks {
1390            let mut matched = Vec::new();
1391            for job in &jobs_in_group {
1392                // A plan file dispatched as the task, with no --plan-task: the run id names the task
1393                // (`blyte dispatch S1 <plan>.md`, 2026-10-02).
1394                let pt = job
1395                    .plan_task
1396                    .as_deref()
1397                    .or_else(|| {
1398                        job.task_file
1399                            .as_deref()
1400                            .filter(|tf| {
1401                                is_plan_task_file(Path::new(tf))
1402                                    || job.root.as_ref().is_some_and(|r| {
1403                                        r.join(extract_relpath(
1404                                            r,
1405                                            Path::new(tf),
1406                                            job.worktree.as_deref(),
1407                                        )) == plan_file_abs
1408                                    })
1409                            })
1410                            .map(|_| job.id.as_str())
1411                    })
1412                    .or(Some(job.id.as_str()));
1413                if let Some(pt) = pt {
1414                    if matches_task(task, pt) {
1415                        matched.push(*job);
1416                        if !all_matched_jobs.iter().any(|j| j.id == job.id) {
1417                            all_matched_jobs.push(*job);
1418                        }
1419                    }
1420                }
1421            }
1422            task_jobs.insert(task.id.clone(), matched);
1423        }
1424
1425        let mut added_groups: Vec<(String, Vec<&Job>)> = Vec::new();
1426        for job in &jobs_in_group {
1427            if all_matched_jobs.iter().any(|j| j.id == job.id) {
1428                continue;
1429            }
1430            let is_explicit = job.start_plan.is_some() || find_tag_plan_stem(job).is_some();
1431            if !is_explicit {
1432                continue;
1433            }
1434            let name = job
1435                .plan_task
1436                .as_deref()
1437                .map(str::trim)
1438                .filter(|s| !s.is_empty())
1439                .unwrap_or(&job.id)
1440                .to_string();
1441
1442            if let Some((_, group_jobs)) = added_groups.iter_mut().find(|(n, _)| *n == name) {
1443                group_jobs.push(*job);
1444            } else {
1445                added_groups.push((name, vec![*job]));
1446            }
1447        }
1448
1449        struct AddedTaskInfo<'a> {
1450            id: String,
1451            title: String,
1452            heading: String,
1453            jobs: Vec<&'a Job>,
1454            chosen: &'a Job,
1455            state: String,
1456        }
1457
1458        let mut added_tasks: Vec<AddedTaskInfo> = Vec::new();
1459        for (name, group_jobs) in added_groups {
1460            let Some(chosen) = choose_task_job(&group_jobs) else {
1461                continue;
1462            };
1463            let (id, title) = parse_added_task_id_and_title(&name, &chosen.id, &chosen.title);
1464            let state = if chosen.status == "running" {
1465                "running".to_string()
1466            } else if chosen.verdict.as_deref() == Some("redone") {
1467                "redone".to_string()
1468            } else if chosen.status == "verified" {
1469                if is_job_merged(chosen) {
1470                    "merged".to_string()
1471                } else {
1472                    "verified".to_string()
1473                }
1474            } else {
1475                "failed".to_string()
1476            };
1477
1478            for job in &group_jobs {
1479                if !all_matched_jobs.iter().any(|j| j.id == job.id) {
1480                    all_matched_jobs.push(*job);
1481                }
1482            }
1483
1484            added_tasks.push(AddedTaskInfo {
1485                id,
1486                title,
1487                heading: name,
1488                jobs: group_jobs,
1489                chosen,
1490                state,
1491            });
1492        }
1493
1494        let seven_days = 7 * 24 * 3600;
1495        let any_dispatched = all_matched_jobs.iter().any(|j| {
1496            j.status == "running"
1497                || j.started_at
1498                    .is_some_and(|st| st >= now.saturating_sub(seven_days))
1499        });
1500        if !any_dispatched {
1501            continue;
1502        }
1503
1504        let mut task_states: HashMap<String, String> = HashMap::new();
1505        let mut chosen_jobs: HashMap<String, &Job> = HashMap::new();
1506
1507        for task in &doc.tasks {
1508            if let Some(m_jobs) = task_jobs.get(&task.id) {
1509                if let Some(chosen) = choose_task_job(m_jobs) {
1510                    chosen_jobs.insert(task.id.clone(), chosen);
1511                    let state = if chosen.status == "running" {
1512                        "running".to_string()
1513                    } else if chosen.verdict.as_deref() == Some("redone") {
1514                        "redone".to_string()
1515                    } else if chosen.status == "verified" {
1516                        if is_job_merged(chosen) {
1517                            "merged".to_string()
1518                        } else {
1519                            "verified".to_string()
1520                        }
1521                    } else {
1522                        "failed".to_string()
1523                    };
1524                    task_states.insert(task.id.clone(), state);
1525                }
1526            }
1527        }
1528
1529        for task in &doc.tasks {
1530            if !task_states.contains_key(&task.id) {
1531                let all_deps_merged = task
1532                    .deps
1533                    .iter()
1534                    .all(|dep_id| task_states.get(dep_id).map(|s| s.as_str()) == Some("merged"));
1535                let state = if all_deps_merged { "ready" } else { "waiting" };
1536                task_states.insert(task.id.clone(), state.to_string());
1537            }
1538        }
1539
1540        for added in &added_tasks {
1541            task_jobs.insert(added.id.clone(), added.jobs.clone());
1542            task_states.insert(added.id.clone(), added.state.clone());
1543            chosen_jobs.insert(added.id.clone(), added.chosen);
1544        }
1545
1546        let mut repos: Vec<String> = all_matched_jobs.iter().map(|j| j.repo.clone()).collect();
1547        repos.sort();
1548        repos.dedup();
1549
1550        let is_multi_repo = repos.len() > 1;
1551        let mut lanes = Vec::new();
1552
1553        if is_multi_repo {
1554            for r in &repos {
1555                lanes.push(serde_json::json!({
1556                    "id": r.to_lowercase().replace(' ', "-"),
1557                    "label": r,
1558                }));
1559            }
1560            let any_unrun = doc.tasks.iter().any(|t| !chosen_jobs.contains_key(&t.id));
1561            if any_unrun {
1562                lanes.push(serde_json::json!({
1563                    "id": "not-dispatched",
1564                    "label": "Not dispatched",
1565                }));
1566            }
1567        } else {
1568            let mut seen_lanes = HashSet::new();
1569            for t in &doc.tasks {
1570                if seen_lanes.insert(t.lane.clone()) {
1571                    let id = t.lane.to_lowercase().replace(' ', "-");
1572                    lanes.push(serde_json::json!({
1573                        "id": id,
1574                        "label": t.lane,
1575                    }));
1576                }
1577            }
1578            if !added_tasks.is_empty() {
1579                lanes.push(serde_json::json!({
1580                    "id": "added",
1581                    "label": "Added during the work",
1582                }));
1583            }
1584        }
1585
1586        let mut tasks_json = Vec::new();
1587        for task in &doc.tasks {
1588            let state = task_states.get(&task.id).unwrap().clone();
1589            let lane_id = if is_multi_repo {
1590                if let Some(chosen) = chosen_jobs.get(&task.id) {
1591                    chosen.repo.to_lowercase().replace(' ', "-")
1592                } else {
1593                    "not-dispatched".to_string()
1594                }
1595            } else {
1596                task.lane.to_lowercase().replace(' ', "-")
1597            };
1598            let task_val = if let Some(job) = chosen_jobs.get(&task.id) {
1599                let files = if !job.changed_files.is_empty() {
1600                    job.changed_files.clone()
1601                } else {
1602                    task.files.clone()
1603                };
1604                serde_json::json!({
1605                    "id": task.id,
1606                    "title": task.title,
1607                    "heading": task.heading,
1608                    "lane": lane_id,
1609                    "deps": task.deps,
1610                    "state": state,
1611                    "dispatch": job.key,
1612                    "now": job.now,
1613                    "gate_running": job.gate_running,
1614                    "gate_attempts": job.gate_attempts,
1615                    "elapsed_s": job.elapsed_s,
1616                    "cost_usd": job.cost_usd,
1617                    "turns": job.turns,
1618                    "files": files,
1619                    "commits": job.commits,
1620                    "verdict": job.verdict,
1621                    "notes": job.verdict_notes,
1622                    "added": false,
1623                })
1624            } else {
1625                serde_json::json!({
1626                    "id": task.id,
1627                    "title": task.title,
1628                    "heading": task.heading,
1629                    "lane": lane_id,
1630                    "deps": task.deps,
1631                    "state": state,
1632                    "dispatch": serde_json::Value::Null,
1633                    "now": "",
1634                    "gate_running": false,
1635                    "gate_attempts": 0,
1636                    "elapsed_s": serde_json::Value::Null,
1637                    "cost_usd": serde_json::Value::Null,
1638                    "turns": 0,
1639                    "files": task.files,
1640                    "commits": [],
1641                    "verdict": serde_json::Value::Null,
1642                    "notes": serde_json::Value::Null,
1643                    "added": false,
1644                })
1645            };
1646            tasks_json.push(task_val);
1647        }
1648
1649        for added in &added_tasks {
1650            let state = task_states.get(&added.id).unwrap().clone();
1651            let job = added.chosen;
1652            let lane_id = if is_multi_repo {
1653                job.repo.to_lowercase().replace(' ', "-")
1654            } else {
1655                "added".to_string()
1656            };
1657            let files = if !job.changed_files.is_empty() {
1658                job.changed_files.clone()
1659            } else {
1660                Vec::new()
1661            };
1662            let task_val = serde_json::json!({
1663                "id": added.id,
1664                "title": added.title,
1665                "heading": added.heading,
1666                "lane": lane_id,
1667                "deps": serde_json::json!([]),
1668                "state": state,
1669                "dispatch": job.key,
1670                "now": job.now,
1671                "gate_running": job.gate_running,
1672                "gate_attempts": job.gate_attempts,
1673                "elapsed_s": job.elapsed_s,
1674                "cost_usd": job.cost_usd,
1675                "turns": job.turns,
1676                "files": files,
1677                "commits": job.commits,
1678                "verdict": job.verdict,
1679                "notes": job.verdict_notes,
1680                "added": true,
1681            });
1682            tasks_json.push(task_val);
1683        }
1684
1685        let all_task_ids: Vec<String> = doc
1686            .tasks
1687            .iter()
1688            .map(|t| t.id.clone())
1689            .chain(added_tasks.iter().map(|t| t.id.clone()))
1690            .collect();
1691
1692        let mut events: Vec<PlanEvent> = Vec::new();
1693        for task_id in &all_task_ids {
1694            if let Some(m_jobs) = task_jobs.get(task_id) {
1695                for job in m_jobs {
1696                    if let Some(st) = job.started_at {
1697                        events.push(PlanEvent {
1698                            at: st,
1699                            task: task_id.clone(),
1700                            text: "dispatched".to_string(),
1701                        });
1702                    }
1703                    if job.status != "running" {
1704                        if let Some(fin) = job.finished_at.or(job.log_mtime) {
1705                            events.push(PlanEvent {
1706                                at: fin,
1707                                task: task_id.clone(),
1708                                text: job.status.clone(),
1709                            });
1710                        }
1711                    }
1712                    if let Some(ref v) = job.verdict {
1713                        if let Some(ts) = job.verdict_ts {
1714                            events.push(PlanEvent {
1715                                at: ts,
1716                                task: task_id.clone(),
1717                                text: format!("verdict {v}"),
1718                            });
1719                        }
1720                    }
1721                }
1722            }
1723        }
1724        events.sort_by_key(|e| std::cmp::Reverse(e.at));
1725        let events_json: Vec<serde_json::Value> = events
1726            .into_iter()
1727            .map(|e| {
1728                serde_json::json!({
1729                    "at": e.at,
1730                    "task": e.task,
1731                    "text": e.text,
1732                })
1733            })
1734            .collect();
1735
1736        let mut decisions_json = Vec::new();
1737        for d in &doc.decisions {
1738            decisions_json.push(serde_json::json!({
1739                "text": d,
1740                "source": "plan",
1741            }));
1742        }
1743        for task_id in &all_task_ids {
1744            if let Some(job) = chosen_jobs.get(task_id) {
1745                if let Some(ref notes) = job.verdict_notes {
1746                    if !notes.trim().is_empty() {
1747                        decisions_json.push(serde_json::json!({
1748                            "text": notes,
1749                            "source": format!("{} verdict note", task_id),
1750                        }));
1751                    }
1752                }
1753            }
1754        }
1755
1756        let tasks_count = doc.tasks.len() + added_tasks.len();
1757        let merged_count = task_states
1758            .values()
1759            .filter(|s| s.as_str() == "merged")
1760            .count();
1761        let verified_count = task_states
1762            .values()
1763            .filter(|s| s.as_str() == "verified")
1764            .count();
1765        let running_count = task_states
1766            .values()
1767            .filter(|s| s.as_str() == "running")
1768            .count();
1769        let not_started_count = task_states
1770            .values()
1771            .filter(|s| s.as_str() == "ready" || s.as_str() == "waiting")
1772            .count();
1773        let cost_usd: f64 = all_matched_jobs.iter().filter_map(|j| j.cost_usd).sum();
1774        let cost_usd = (cost_usd * 100.0).round() / 100.0;
1775        let first_dispatch_at = all_matched_jobs.iter().filter_map(|j| j.started_at).min();
1776
1777        let intervals: Vec<(u64, u64)> = all_matched_jobs
1778            .iter()
1779            .filter_map(|j| {
1780                let st = j.started_at?;
1781                let fin = j.finished_at.unwrap_or(now);
1782                Some((st, fin))
1783            })
1784            .collect();
1785        let mut max_parallel = 0;
1786        for (t, _) in &intervals {
1787            let count = intervals
1788                .iter()
1789                .filter(|(st, fin)| *st <= *t && *t <= *fin)
1790                .count();
1791            if count > max_parallel {
1792                max_parallel = count;
1793            }
1794        }
1795
1796        let stats_json = serde_json::json!({
1797            "tasks": tasks_count,
1798            "merged": merged_count,
1799            "verified": verified_count,
1800            "running": running_count,
1801            "not_started": not_started_count,
1802            "cost_usd": cost_usd,
1803            "first_dispatch_at": first_dispatch_at,
1804            "max_parallel": max_parallel,
1805        });
1806
1807        let has_running = running_count > 0;
1808        if opts.running_only && !has_running {
1809            continue;
1810        }
1811        let latest_activity = events_json
1812            .first()
1813            .and_then(|e| e["at"].as_u64())
1814            .or(first_dispatch_at)
1815            .unwrap_or(0);
1816
1817        let plan_val = serde_json::json!({
1818            "key": key,
1819            "repo": repo,
1820            "repos": repos,
1821            "path": path_str,
1822            "title": doc.title,
1823            "lanes": lanes,
1824            "tasks": tasks_json,
1825            "events": events_json,
1826            "decisions": decisions_json,
1827            "stats": stats_json,
1828        });
1829
1830        plan_items.push(PlanItem {
1831            key,
1832            has_running,
1833            latest_activity,
1834            val: plan_val,
1835        });
1836    }
1837
1838    if opts.running_only {
1839        plan_items.retain(|p| p.has_running);
1840    }
1841
1842    plan_items.sort_by(|a, b| match (a.has_running, b.has_running) {
1843        (true, false) => std::cmp::Ordering::Less,
1844        (false, true) => std::cmp::Ordering::Greater,
1845        _ => b
1846            .latest_activity
1847            .cmp(&a.latest_activity)
1848            .then_with(|| a.key.cmp(&b.key)),
1849    });
1850
1851    serde_json::json!({
1852        "generated_at": now,
1853        "plans": plan_items.into_iter().map(|p| p.val).collect::<Vec<_>>(),
1854    })
1855}
1856
1857#[cfg(test)]
1858mod tests {
1859    use super::*;
1860
1861    #[test]
1862    fn test_1_depends_on_clause_with_trailing_parens() {
1863        let plan = r#"# Test Plan
1864### Task OC2b: b
1865### Task OC3: c
1866### Task OC4: d
1867### Task OC5: e
1868**Depends on:** OC2b, OC3, OC4 (all on main before this is dispatched).
1869"#;
1870        let doc = parse_plan(plan);
1871        assert_eq!(doc.tasks[3].deps, ["OC2b", "OC3", "OC4"]);
1872    }
1873
1874    #[test]
1875    fn test_2_depends_on_none_with_siblings() {
1876        let plan = r#"# Test Plan
1877### Task SL2: skill
1878### Task OC6: repl
1879**Depends on:** none. **Siblings:** SL2 changes skill.rs
1880"#;
1881        let doc = parse_plan(plan);
1882        assert!(doc.tasks[1].deps.is_empty());
1883    }
1884
1885    #[test]
1886    fn test_3_depends_on_task_with_siblings() {
1887        let plan = r#"# Test Plan
1888### Task C1: cost
1889### Task ST1: state
1890### Task X: test
1891**Depends on:** C1. **Siblings:** ST1 changes repl.rs
1892"#;
1893        let doc = parse_plan(plan);
1894        assert_eq!(doc.tasks[2].deps, ["C1"]);
1895    }
1896
1897    #[test]
1898    fn test_4_depends_on_with_paren_explanation() {
1899        let plan = r#"# Test Plan
1900### Task S1: setup
1901### Task S2: init
1902**Depends on:** S1 (uses setup::run_setup).
1903"#;
1904        let doc = parse_plan(plan);
1905        assert_eq!(doc.tasks[1].deps, ["S1"]);
1906    }
1907
1908    #[test]
1909    fn test_5_depends_on_u1_and_u2() {
1910        let plan = r#"# Test Plan
1911### Task U1: usage
1912### Task U2: ids
1913### Task U3: cost
1914**Depends on:** U1 and U2
1915"#;
1916        let doc = parse_plan(plan);
1917        assert_eq!(doc.tasks[2].deps, ["U1", "U2"]);
1918    }
1919
1920    #[test]
1921    fn test_6_single_and_short_task_ids() {
1922        let plan_t = r#"# Test Plan
1923### Task T1: first
1924### Task T2: second
1925### Task T3: third
1926**Depends on:** T1
1927"#;
1928        let doc_t = parse_plan(plan_t);
1929        assert_eq!(doc_t.tasks[2].deps, ["T1"]);
1930
1931        let plan_ab = r#"# Test Plan
1932### Task A: first
1933### Task B: second
1934**Depends on:** A
1935"#;
1936        let doc_ab = parse_plan(plan_ab);
1937        assert_eq!(doc_ab.tasks[1].deps, ["A"]);
1938    }
1939
1940    #[test]
1941    fn test_7_depends_on_numeric_form() {
1942        let plan = r#"# Test Plan
1943### Task 1: first
1944### Task 2: second
1945### Task 3: third
1946Depends on: Task 2
1947"#;
1948        let doc = parse_plan(plan);
1949        assert_eq!(doc.tasks[0].id, "T1");
1950        assert_eq!(doc.tasks[1].id, "T2");
1951        assert_eq!(doc.tasks[2].deps, ["T2"]);
1952    }
1953
1954    #[test]
1955    fn test_8_non_plan_task_dropped_unless_written_as_task_x() {
1956        let plan = r#"# Test Plan
1957### Task A: first
1958**Depends on:** X9
1959### Task B: second
1960Depends on: Task X9
1961"#;
1962        let doc = parse_plan(plan);
1963        assert!(doc.tasks[0].deps.is_empty());
1964        assert_eq!(doc.tasks[1].deps, ["X9"]);
1965    }
1966
1967    #[test]
1968    fn test_9_real_plan() {
1969        let doc = parse_plan(include_str!(
1970            "../../../docs/superpowers/plans/2026-10-07-orchestrate-mode.md"
1971        ));
1972        let find = |id: &str| {
1973            doc.tasks
1974                .iter()
1975                .find(|t| t.id == id)
1976                .unwrap_or_else(|| panic!("task {id} not found in plan"))
1977                .deps
1978                .clone()
1979        };
1980        assert_eq!(find("OC5"), ["OC2", "OC3", "OC4"]);
1981        assert!(find("OC6").is_empty());
1982        assert_eq!(find("U2"), ["OC9"]);
1983        assert_eq!(find("S2"), ["S1"]);
1984        assert_eq!(find("U3"), ["U1", "U2"]);
1985
1986        let plan_ids: HashSet<&str> = doc.tasks.iter().map(|t| t.id.as_str()).collect();
1987        for task in &doc.tasks {
1988            for dep in &task.deps {
1989                assert!(
1990                    plan_ids.contains(dep.as_str()),
1991                    "task {} has dependency {} which is not a task id in the plan",
1992                    task.id,
1993                    dep
1994                );
1995            }
1996        }
1997    }
1998
1999    fn make_test_job(root: PathBuf, id: &str, verdict: Option<&str>) -> Job {
2000        Job {
2001            problems: Vec::new(),
2002            key: format!("app/{id}"),
2003            id: id.to_string(),
2004            repo: "app".to_string(),
2005            status: "verified".to_string(),
2006            gate_running: false,
2007            title: id.to_string(),
2008            task: String::new(),
2009            plan: None,
2010            now: String::new(),
2011            started_at: Some(100),
2012            finished_at: Some(200),
2013            elapsed_s: Some(100),
2014            cost_usd: None,
2015            turns: 1,
2016            gate_attempts: 1,
2017            gate_failures: Vec::new(),
2018            model: None,
2019            last_tool: None,
2020            worktree: None,
2021            worktree_exists: Some(false),
2022            log: String::new(),
2023            commits: Vec::new(),
2024            changed_files: Vec::new(),
2025            tags: Vec::new(),
2026            verdict: verdict.map(String::from),
2027            root: Some(root),
2028            plan_file: None,
2029            plan_task: None,
2030            request: None,
2031            task_file: None,
2032            research: false,
2033            start_plan: None,
2034            file_tags: Vec::new(),
2035            verdict_notes: None,
2036            verdict_ts: None,
2037            log_mtime: None,
2038        }
2039    }
2040
2041    #[test]
2042    fn job_without_verdict_branch_gone_merged_only_with_merged_removal_record() {
2043        let dir = tempfile::tempdir().unwrap();
2044        let root = dir.path();
2045        let run_git = |args: &[&str]| {
2046            let ok = std::process::Command::new("git")
2047                .args(["-c", "user.name=t", "-c", "user.email=t@t"])
2048                .args(args)
2049                .current_dir(root)
2050                .status()
2051                .unwrap()
2052                .success();
2053            assert!(ok, "git {args:?}");
2054        };
2055        run_git(&["init", "-q", "-b", "main"]);
2056        std::fs::write(root.join("a.txt"), "hello\n").unwrap();
2057        run_git(&["add", "."]);
2058        run_git(&["commit", "-qm", "init", "--no-gpg-sign"]);
2059
2060        let job = make_test_job(root.to_path_buf(), "J1", None);
2061        assert!(!is_job_merged(&job));
2062
2063        for reason in ["merged", "merged_into", "merged_through", "session_merged"] {
2064            let rec = crate::removal_record::RemovalRecord {
2065                id: "J1".to_string(),
2066                reason: reason.to_string(),
2067                detail: None,
2068                removed_at: 1_795_000_000,
2069            };
2070            crate::removal_record::write(root, &rec).unwrap();
2071            assert!(is_job_merged(&job), "reason {reason} should be merged");
2072        }
2073
2074        for reason in ["no_changes", "older_than", "verdict"] {
2075            let rec = crate::removal_record::RemovalRecord {
2076                id: "J1".to_string(),
2077                reason: reason.to_string(),
2078                detail: None,
2079                removed_at: 1_795_000_000,
2080            };
2081            crate::removal_record::write(root, &rec).unwrap();
2082            assert!(!is_job_merged(&job), "reason {reason} should not be merged");
2083        }
2084
2085        let corrupt_path = crate::removal_record::path(root, "J1");
2086        std::fs::write(&corrupt_path, "{corrupt").unwrap();
2087        let mut reported = Vec::new();
2088        assert!(!is_job_merged_with_error_reporter(&job, |e| {
2089            reported.push(e.to_string());
2090        }));
2091        assert_eq!(reported.len(), 1);
2092        assert!(
2093            reported[0].contains(&corrupt_path.display().to_string()),
2094            "expected error naming {}, got: {}",
2095            corrupt_path.display(),
2096            reported[0]
2097        );
2098        assert!(!is_job_merged_with_error_reporter(&job, |e| {
2099            reported.push(e.to_string());
2100        }));
2101        assert_eq!(
2102            reported.len(),
2103            1,
2104            "corrupt removal record error should be reported only once"
2105        );
2106
2107        let job2 = make_test_job(root.to_path_buf(), "J2", None);
2108        let corrupt_path2 = crate::removal_record::path(root, "J2");
2109        std::fs::write(&corrupt_path2, "{corrupt").unwrap();
2110        assert!(!is_job_merged(&job2));
2111        assert!(
2112            REPORTED_REMOVAL_ERRORS
2113                .read()
2114                .unwrap()
2115                .iter()
2116                .any(|msg| msg.contains(&corrupt_path2.display().to_string())),
2117            "expected is_job_merged to record error naming {}",
2118            corrupt_path2.display()
2119        );
2120
2121        let rec = crate::removal_record::RemovalRecord {
2122            id: "J1".to_string(),
2123            reason: "merged".to_string(),
2124            detail: None,
2125            removed_at: 1_795_000_000,
2126        };
2127        crate::removal_record::write(root, &rec).unwrap();
2128        run_git(&["branch", "wip/J1"]);
2129        assert!(!is_job_merged(&job));
2130    }
2131}