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_filtered(src: &Sources, now: u64, running_only: bool) -> serde_json::Value {
1218    collect_plans_with_options(src, now, CollectPlansOptions { running_only })
1219}
1220
1221pub fn collect_plans_with_options(
1222    src: &Sources,
1223    now: u64,
1224    opts: CollectPlansOptions,
1225) -> serde_json::Value {
1226    let mut plan_src = src.clone();
1227    plan_src.hours = plan_src.hours.max(7 * 24);
1228    let jobs = dashboard::collect_jobs(&plan_src, now);
1229
1230    let mut git_names_cache: HashMap<PathBuf, Vec<String>> = HashMap::new();
1231    let mut plan_content_cache: HashMap<PathBuf, Option<String>> = HashMap::new();
1232
1233    let (active_plan_files, active_standalone_job_ids) = if opts.running_only {
1234        let running_jobs: Vec<&Job> = jobs
1235            .iter()
1236            .filter(|j| !j.research && j.root.is_some() && j.status == "running")
1237            .collect();
1238        if running_jobs.is_empty() {
1239            return serde_json::json!({
1240                "generated_at": now,
1241                "plans": [],
1242            });
1243        }
1244
1245        let mut plan_files = HashSet::new();
1246        let mut standalone_ids = HashSet::new();
1247
1248        for job in &running_jobs {
1249            let root = job.root.as_ref().unwrap();
1250            if let Some(rp) = job_explicit_plan_relpath(job, &mut git_names_cache) {
1251                let plan_file_abs = root.join(rp);
1252                plan_files.insert(plan_file_abs);
1253            } else if let Some(ref tf) = job.task_file {
1254                let tf_path = Path::new(tf);
1255                let relpath = extract_relpath(root, tf_path, job.worktree.as_deref());
1256                let plan_file_abs = root.join(&relpath);
1257                if let Some(content) =
1258                    read_plan_content(&plan_file_abs, &[job], &mut plan_content_cache)
1259                {
1260                    let doc = parse_plan(&content);
1261                    let pt = job.plan_task.as_deref().unwrap_or(&job.id);
1262                    if doc.tasks.iter().any(|t| matches_task(t, pt)) {
1263                        plan_files.insert(plan_file_abs);
1264                    } else {
1265                        standalone_ids.insert(job.id.clone());
1266                    }
1267                } else {
1268                    standalone_ids.insert(job.id.clone());
1269                }
1270            }
1271        }
1272
1273        if plan_files.is_empty() && standalone_ids.is_empty() {
1274            return serde_json::json!({
1275                "generated_at": now,
1276                "plans": [],
1277            });
1278        }
1279
1280        (Some(plan_files), Some(standalone_ids))
1281    } else {
1282        (None, None)
1283    };
1284
1285    let mut groups: HashMap<PathBuf, Vec<&Job>> = HashMap::new();
1286    let mut standalone_plans: Vec<PlanItem> = Vec::new();
1287
1288    for job in &jobs {
1289        if job.research {
1290            continue;
1291        }
1292        let Some(ref root) = job.root else {
1293            continue;
1294        };
1295
1296        if let Some(ref active_files) = active_plan_files {
1297            if let Some(rp) = job_explicit_plan_relpath(job, &mut git_names_cache) {
1298                let plan_file_abs = root.join(rp);
1299                if active_files.contains(&plan_file_abs) {
1300                    groups.entry(plan_file_abs).or_default().push(job);
1301                }
1302            } else if let Some(ref tf) = job.task_file {
1303                let tf_path = Path::new(tf);
1304                let relpath = extract_relpath(root, tf_path, job.worktree.as_deref());
1305                let plan_file_abs = root.join(&relpath);
1306                if active_files.contains(&plan_file_abs) {
1307                    if let Some(content) =
1308                        read_plan_content(&plan_file_abs, &[job], &mut plan_content_cache)
1309                    {
1310                        let doc = parse_plan(&content);
1311                        let pt = job.plan_task.as_deref().unwrap_or(&job.id);
1312                        if doc.tasks.iter().any(|t| matches_task(t, pt)) {
1313                            groups.entry(plan_file_abs).or_default().push(job);
1314                            continue;
1315                        }
1316                    }
1317                }
1318                if let Some(ref standalone_ids) = active_standalone_job_ids {
1319                    if standalone_ids.contains(&job.id) {
1320                        if let Some(content) =
1321                            read_plan_content(&plan_file_abs, &[job], &mut plan_content_cache)
1322                        {
1323                            let doc = parse_plan(&content);
1324                            if let Some(item) =
1325                                build_standalone_plan(job, &plan_file_abs, &content, &doc, now)
1326                            {
1327                                standalone_plans.push(item);
1328                            }
1329                        }
1330                    }
1331                }
1332            }
1333        } else {
1334            if let Some(rp) = job_explicit_plan_relpath(job, &mut git_names_cache) {
1335                let plan_file_abs = root.join(rp);
1336                groups.entry(plan_file_abs).or_default().push(job);
1337            } else {
1338                let Some(ref tf) = job.task_file else {
1339                    continue;
1340                };
1341                let tf_path = Path::new(tf);
1342                let relpath = extract_relpath(root, tf_path, job.worktree.as_deref());
1343                let plan_file_abs = root.join(&relpath);
1344                let Some(content) =
1345                    read_plan_content(&plan_file_abs, &[job], &mut plan_content_cache)
1346                else {
1347                    continue;
1348                };
1349                let doc = parse_plan(&content);
1350                let pt = job.plan_task.as_deref().unwrap_or(&job.id);
1351                let has_matching_task = doc.tasks.iter().any(|t| matches_task(t, pt));
1352                if has_matching_task {
1353                    groups.entry(plan_file_abs).or_default().push(job);
1354                    continue;
1355                }
1356
1357                if let Some(item) = build_standalone_plan(job, &plan_file_abs, &content, &doc, now)
1358                {
1359                    standalone_plans.push(item);
1360                }
1361            }
1362        }
1363    }
1364
1365    let mut plan_items = standalone_plans;
1366
1367    for (plan_file_abs, jobs_in_group) in groups {
1368        let Some(content) =
1369            read_plan_content(&plan_file_abs, &jobs_in_group, &mut plan_content_cache)
1370        else {
1371            continue;
1372        };
1373        let doc = parse_plan(&content);
1374        let repo = find_home_repo(&plan_file_abs, &jobs_in_group);
1375        let stem = plan_file_abs
1376            .file_stem()
1377            .and_then(|s| s.to_str())
1378            .unwrap_or("plan");
1379        let key = format!("{repo}/{stem}");
1380        let path_str = plan_file_abs.to_string_lossy().to_string();
1381
1382        let mut task_jobs: HashMap<String, Vec<&Job>> = HashMap::new();
1383        let mut all_matched_jobs: Vec<&Job> = Vec::new();
1384
1385        for task in &doc.tasks {
1386            let mut matched = Vec::new();
1387            for job in &jobs_in_group {
1388                // A plan file dispatched as the task, with no --plan-task: the run id names the task
1389                // (`blyte dispatch S1 <plan>.md`, 2026-10-02).
1390                let pt = job
1391                    .plan_task
1392                    .as_deref()
1393                    .or_else(|| {
1394                        job.task_file
1395                            .as_deref()
1396                            .filter(|tf| {
1397                                is_plan_task_file(Path::new(tf))
1398                                    || job.root.as_ref().is_some_and(|r| {
1399                                        r.join(extract_relpath(
1400                                            r,
1401                                            Path::new(tf),
1402                                            job.worktree.as_deref(),
1403                                        )) == plan_file_abs
1404                                    })
1405                            })
1406                            .map(|_| job.id.as_str())
1407                    })
1408                    .or(Some(job.id.as_str()));
1409                if let Some(pt) = pt {
1410                    if matches_task(task, pt) {
1411                        matched.push(*job);
1412                        if !all_matched_jobs.iter().any(|j| j.id == job.id) {
1413                            all_matched_jobs.push(*job);
1414                        }
1415                    }
1416                }
1417            }
1418            task_jobs.insert(task.id.clone(), matched);
1419        }
1420
1421        let mut added_groups: Vec<(String, Vec<&Job>)> = Vec::new();
1422        for job in &jobs_in_group {
1423            if all_matched_jobs.iter().any(|j| j.id == job.id) {
1424                continue;
1425            }
1426            let is_explicit = job.start_plan.is_some() || find_tag_plan_stem(job).is_some();
1427            if !is_explicit {
1428                continue;
1429            }
1430            let name = job
1431                .plan_task
1432                .as_deref()
1433                .map(str::trim)
1434                .filter(|s| !s.is_empty())
1435                .unwrap_or(&job.id)
1436                .to_string();
1437
1438            if let Some((_, group_jobs)) = added_groups.iter_mut().find(|(n, _)| *n == name) {
1439                group_jobs.push(*job);
1440            } else {
1441                added_groups.push((name, vec![*job]));
1442            }
1443        }
1444
1445        struct AddedTaskInfo<'a> {
1446            id: String,
1447            title: String,
1448            heading: String,
1449            jobs: Vec<&'a Job>,
1450            chosen: &'a Job,
1451            state: String,
1452        }
1453
1454        let mut added_tasks: Vec<AddedTaskInfo> = Vec::new();
1455        for (name, group_jobs) in added_groups {
1456            let Some(chosen) = choose_task_job(&group_jobs) else {
1457                continue;
1458            };
1459            let (id, title) = parse_added_task_id_and_title(&name, &chosen.id, &chosen.title);
1460            let state = if chosen.status == "running" {
1461                "running".to_string()
1462            } else if chosen.verdict.as_deref() == Some("redone") {
1463                "redone".to_string()
1464            } else if chosen.status == "verified" {
1465                if is_job_merged(chosen) {
1466                    "merged".to_string()
1467                } else {
1468                    "verified".to_string()
1469                }
1470            } else {
1471                "failed".to_string()
1472            };
1473
1474            for job in &group_jobs {
1475                if !all_matched_jobs.iter().any(|j| j.id == job.id) {
1476                    all_matched_jobs.push(*job);
1477                }
1478            }
1479
1480            added_tasks.push(AddedTaskInfo {
1481                id,
1482                title,
1483                heading: name,
1484                jobs: group_jobs,
1485                chosen,
1486                state,
1487            });
1488        }
1489
1490        let seven_days = 7 * 24 * 3600;
1491        let any_dispatched = all_matched_jobs.iter().any(|j| {
1492            j.status == "running"
1493                || j.started_at
1494                    .is_some_and(|st| st >= now.saturating_sub(seven_days))
1495        });
1496        if !any_dispatched {
1497            continue;
1498        }
1499
1500        let mut task_states: HashMap<String, String> = HashMap::new();
1501        let mut chosen_jobs: HashMap<String, &Job> = HashMap::new();
1502
1503        for task in &doc.tasks {
1504            if let Some(m_jobs) = task_jobs.get(&task.id) {
1505                if let Some(chosen) = choose_task_job(m_jobs) {
1506                    chosen_jobs.insert(task.id.clone(), chosen);
1507                    let state = if chosen.status == "running" {
1508                        "running".to_string()
1509                    } else if chosen.verdict.as_deref() == Some("redone") {
1510                        "redone".to_string()
1511                    } else if chosen.status == "verified" {
1512                        if is_job_merged(chosen) {
1513                            "merged".to_string()
1514                        } else {
1515                            "verified".to_string()
1516                        }
1517                    } else {
1518                        "failed".to_string()
1519                    };
1520                    task_states.insert(task.id.clone(), state);
1521                }
1522            }
1523        }
1524
1525        for task in &doc.tasks {
1526            if !task_states.contains_key(&task.id) {
1527                let all_deps_merged = task
1528                    .deps
1529                    .iter()
1530                    .all(|dep_id| task_states.get(dep_id).map(|s| s.as_str()) == Some("merged"));
1531                let state = if all_deps_merged { "ready" } else { "waiting" };
1532                task_states.insert(task.id.clone(), state.to_string());
1533            }
1534        }
1535
1536        for added in &added_tasks {
1537            task_jobs.insert(added.id.clone(), added.jobs.clone());
1538            task_states.insert(added.id.clone(), added.state.clone());
1539            chosen_jobs.insert(added.id.clone(), added.chosen);
1540        }
1541
1542        let mut repos: Vec<String> = all_matched_jobs.iter().map(|j| j.repo.clone()).collect();
1543        repos.sort();
1544        repos.dedup();
1545
1546        let is_multi_repo = repos.len() > 1;
1547        let mut lanes = Vec::new();
1548
1549        if is_multi_repo {
1550            for r in &repos {
1551                lanes.push(serde_json::json!({
1552                    "id": r.to_lowercase().replace(' ', "-"),
1553                    "label": r,
1554                }));
1555            }
1556            let any_unrun = doc.tasks.iter().any(|t| !chosen_jobs.contains_key(&t.id));
1557            if any_unrun {
1558                lanes.push(serde_json::json!({
1559                    "id": "not-dispatched",
1560                    "label": "Not dispatched",
1561                }));
1562            }
1563        } else {
1564            let mut seen_lanes = HashSet::new();
1565            for t in &doc.tasks {
1566                if seen_lanes.insert(t.lane.clone()) {
1567                    let id = t.lane.to_lowercase().replace(' ', "-");
1568                    lanes.push(serde_json::json!({
1569                        "id": id,
1570                        "label": t.lane,
1571                    }));
1572                }
1573            }
1574            if !added_tasks.is_empty() {
1575                lanes.push(serde_json::json!({
1576                    "id": "added",
1577                    "label": "Added during the work",
1578                }));
1579            }
1580        }
1581
1582        let mut tasks_json = Vec::new();
1583        for task in &doc.tasks {
1584            let state = task_states.get(&task.id).unwrap().clone();
1585            let lane_id = if is_multi_repo {
1586                if let Some(chosen) = chosen_jobs.get(&task.id) {
1587                    chosen.repo.to_lowercase().replace(' ', "-")
1588                } else {
1589                    "not-dispatched".to_string()
1590                }
1591            } else {
1592                task.lane.to_lowercase().replace(' ', "-")
1593            };
1594            let task_val = if let Some(job) = chosen_jobs.get(&task.id) {
1595                let files = if !job.changed_files.is_empty() {
1596                    job.changed_files.clone()
1597                } else {
1598                    task.files.clone()
1599                };
1600                serde_json::json!({
1601                    "id": task.id,
1602                    "title": task.title,
1603                    "heading": task.heading,
1604                    "lane": lane_id,
1605                    "deps": task.deps,
1606                    "state": state,
1607                    "dispatch": job.key,
1608                    "now": job.now,
1609                    "gate_running": job.gate_running,
1610                    "gate_attempts": job.gate_attempts,
1611                    "elapsed_s": job.elapsed_s,
1612                    "cost_usd": job.cost_usd,
1613                    "turns": job.turns,
1614                    "files": files,
1615                    "commits": job.commits,
1616                    "verdict": job.verdict,
1617                    "notes": job.verdict_notes,
1618                    "added": false,
1619                })
1620            } else {
1621                serde_json::json!({
1622                    "id": task.id,
1623                    "title": task.title,
1624                    "heading": task.heading,
1625                    "lane": lane_id,
1626                    "deps": task.deps,
1627                    "state": state,
1628                    "dispatch": serde_json::Value::Null,
1629                    "now": "",
1630                    "gate_running": false,
1631                    "gate_attempts": 0,
1632                    "elapsed_s": serde_json::Value::Null,
1633                    "cost_usd": serde_json::Value::Null,
1634                    "turns": 0,
1635                    "files": task.files,
1636                    "commits": [],
1637                    "verdict": serde_json::Value::Null,
1638                    "notes": serde_json::Value::Null,
1639                    "added": false,
1640                })
1641            };
1642            tasks_json.push(task_val);
1643        }
1644
1645        for added in &added_tasks {
1646            let state = task_states.get(&added.id).unwrap().clone();
1647            let job = added.chosen;
1648            let lane_id = if is_multi_repo {
1649                job.repo.to_lowercase().replace(' ', "-")
1650            } else {
1651                "added".to_string()
1652            };
1653            let files = if !job.changed_files.is_empty() {
1654                job.changed_files.clone()
1655            } else {
1656                Vec::new()
1657            };
1658            let task_val = serde_json::json!({
1659                "id": added.id,
1660                "title": added.title,
1661                "heading": added.heading,
1662                "lane": lane_id,
1663                "deps": serde_json::json!([]),
1664                "state": state,
1665                "dispatch": job.key,
1666                "now": job.now,
1667                "gate_running": job.gate_running,
1668                "gate_attempts": job.gate_attempts,
1669                "elapsed_s": job.elapsed_s,
1670                "cost_usd": job.cost_usd,
1671                "turns": job.turns,
1672                "files": files,
1673                "commits": job.commits,
1674                "verdict": job.verdict,
1675                "notes": job.verdict_notes,
1676                "added": true,
1677            });
1678            tasks_json.push(task_val);
1679        }
1680
1681        let all_task_ids: Vec<String> = doc
1682            .tasks
1683            .iter()
1684            .map(|t| t.id.clone())
1685            .chain(added_tasks.iter().map(|t| t.id.clone()))
1686            .collect();
1687
1688        let mut events: Vec<PlanEvent> = Vec::new();
1689        for task_id in &all_task_ids {
1690            if let Some(m_jobs) = task_jobs.get(task_id) {
1691                for job in m_jobs {
1692                    if let Some(st) = job.started_at {
1693                        events.push(PlanEvent {
1694                            at: st,
1695                            task: task_id.clone(),
1696                            text: "dispatched".to_string(),
1697                        });
1698                    }
1699                    if job.status != "running" {
1700                        if let Some(fin) = job.finished_at.or(job.log_mtime) {
1701                            events.push(PlanEvent {
1702                                at: fin,
1703                                task: task_id.clone(),
1704                                text: job.status.clone(),
1705                            });
1706                        }
1707                    }
1708                    if let Some(ref v) = job.verdict {
1709                        if let Some(ts) = job.verdict_ts {
1710                            events.push(PlanEvent {
1711                                at: ts,
1712                                task: task_id.clone(),
1713                                text: format!("verdict {v}"),
1714                            });
1715                        }
1716                    }
1717                }
1718            }
1719        }
1720        events.sort_by_key(|e| std::cmp::Reverse(e.at));
1721        let events_json: Vec<serde_json::Value> = events
1722            .into_iter()
1723            .map(|e| {
1724                serde_json::json!({
1725                    "at": e.at,
1726                    "task": e.task,
1727                    "text": e.text,
1728                })
1729            })
1730            .collect();
1731
1732        let mut decisions_json = Vec::new();
1733        for d in &doc.decisions {
1734            decisions_json.push(serde_json::json!({
1735                "text": d,
1736                "source": "plan",
1737            }));
1738        }
1739        for task_id in &all_task_ids {
1740            if let Some(job) = chosen_jobs.get(task_id) {
1741                if let Some(ref notes) = job.verdict_notes {
1742                    if !notes.trim().is_empty() {
1743                        decisions_json.push(serde_json::json!({
1744                            "text": notes,
1745                            "source": format!("{} verdict note", task_id),
1746                        }));
1747                    }
1748                }
1749            }
1750        }
1751
1752        let tasks_count = doc.tasks.len() + added_tasks.len();
1753        let merged_count = task_states
1754            .values()
1755            .filter(|s| s.as_str() == "merged")
1756            .count();
1757        let verified_count = task_states
1758            .values()
1759            .filter(|s| s.as_str() == "verified")
1760            .count();
1761        let running_count = task_states
1762            .values()
1763            .filter(|s| s.as_str() == "running")
1764            .count();
1765        let not_started_count = task_states
1766            .values()
1767            .filter(|s| s.as_str() == "ready" || s.as_str() == "waiting")
1768            .count();
1769        let cost_usd: f64 = all_matched_jobs.iter().filter_map(|j| j.cost_usd).sum();
1770        let cost_usd = (cost_usd * 100.0).round() / 100.0;
1771        let first_dispatch_at = all_matched_jobs.iter().filter_map(|j| j.started_at).min();
1772
1773        let intervals: Vec<(u64, u64)> = all_matched_jobs
1774            .iter()
1775            .filter_map(|j| {
1776                let st = j.started_at?;
1777                let fin = j.finished_at.unwrap_or(now);
1778                Some((st, fin))
1779            })
1780            .collect();
1781        let mut max_parallel = 0;
1782        for (t, _) in &intervals {
1783            let count = intervals
1784                .iter()
1785                .filter(|(st, fin)| *st <= *t && *t <= *fin)
1786                .count();
1787            if count > max_parallel {
1788                max_parallel = count;
1789            }
1790        }
1791
1792        let stats_json = serde_json::json!({
1793            "tasks": tasks_count,
1794            "merged": merged_count,
1795            "verified": verified_count,
1796            "running": running_count,
1797            "not_started": not_started_count,
1798            "cost_usd": cost_usd,
1799            "first_dispatch_at": first_dispatch_at,
1800            "max_parallel": max_parallel,
1801        });
1802
1803        let has_running = running_count > 0;
1804        if opts.running_only && !has_running {
1805            continue;
1806        }
1807        let latest_activity = events_json
1808            .first()
1809            .and_then(|e| e["at"].as_u64())
1810            .or(first_dispatch_at)
1811            .unwrap_or(0);
1812
1813        let plan_val = serde_json::json!({
1814            "key": key,
1815            "repo": repo,
1816            "repos": repos,
1817            "path": path_str,
1818            "title": doc.title,
1819            "lanes": lanes,
1820            "tasks": tasks_json,
1821            "events": events_json,
1822            "decisions": decisions_json,
1823            "stats": stats_json,
1824        });
1825
1826        plan_items.push(PlanItem {
1827            key,
1828            has_running,
1829            latest_activity,
1830            val: plan_val,
1831        });
1832    }
1833
1834    if opts.running_only {
1835        plan_items.retain(|p| p.has_running);
1836    }
1837
1838    plan_items.sort_by(|a, b| match (a.has_running, b.has_running) {
1839        (true, false) => std::cmp::Ordering::Less,
1840        (false, true) => std::cmp::Ordering::Greater,
1841        _ => b
1842            .latest_activity
1843            .cmp(&a.latest_activity)
1844            .then_with(|| a.key.cmp(&b.key)),
1845    });
1846
1847    serde_json::json!({
1848        "generated_at": now,
1849        "plans": plan_items.into_iter().map(|p| p.val).collect::<Vec<_>>(),
1850    })
1851}
1852
1853#[cfg(test)]
1854mod tests {
1855    use super::*;
1856
1857    #[test]
1858    fn test_1_depends_on_clause_with_trailing_parens() {
1859        let plan = r#"# Test Plan
1860### Task OC2b: b
1861### Task OC3: c
1862### Task OC4: d
1863### Task OC5: e
1864**Depends on:** OC2b, OC3, OC4 (all on main before this is dispatched).
1865"#;
1866        let doc = parse_plan(plan);
1867        assert_eq!(doc.tasks[3].deps, ["OC2b", "OC3", "OC4"]);
1868    }
1869
1870    #[test]
1871    fn test_2_depends_on_none_with_siblings() {
1872        let plan = r#"# Test Plan
1873### Task SL2: skill
1874### Task OC6: repl
1875**Depends on:** none. **Siblings:** SL2 changes skill.rs
1876"#;
1877        let doc = parse_plan(plan);
1878        assert!(doc.tasks[1].deps.is_empty());
1879    }
1880
1881    #[test]
1882    fn test_3_depends_on_task_with_siblings() {
1883        let plan = r#"# Test Plan
1884### Task C1: cost
1885### Task ST1: state
1886### Task X: test
1887**Depends on:** C1. **Siblings:** ST1 changes repl.rs
1888"#;
1889        let doc = parse_plan(plan);
1890        assert_eq!(doc.tasks[2].deps, ["C1"]);
1891    }
1892
1893    #[test]
1894    fn test_4_depends_on_with_paren_explanation() {
1895        let plan = r#"# Test Plan
1896### Task S1: setup
1897### Task S2: init
1898**Depends on:** S1 (uses setup::run_setup).
1899"#;
1900        let doc = parse_plan(plan);
1901        assert_eq!(doc.tasks[1].deps, ["S1"]);
1902    }
1903
1904    #[test]
1905    fn test_5_depends_on_u1_and_u2() {
1906        let plan = r#"# Test Plan
1907### Task U1: usage
1908### Task U2: ids
1909### Task U3: cost
1910**Depends on:** U1 and U2
1911"#;
1912        let doc = parse_plan(plan);
1913        assert_eq!(doc.tasks[2].deps, ["U1", "U2"]);
1914    }
1915
1916    #[test]
1917    fn test_6_single_and_short_task_ids() {
1918        let plan_t = r#"# Test Plan
1919### Task T1: first
1920### Task T2: second
1921### Task T3: third
1922**Depends on:** T1
1923"#;
1924        let doc_t = parse_plan(plan_t);
1925        assert_eq!(doc_t.tasks[2].deps, ["T1"]);
1926
1927        let plan_ab = r#"# Test Plan
1928### Task A: first
1929### Task B: second
1930**Depends on:** A
1931"#;
1932        let doc_ab = parse_plan(plan_ab);
1933        assert_eq!(doc_ab.tasks[1].deps, ["A"]);
1934    }
1935
1936    #[test]
1937    fn test_7_depends_on_numeric_form() {
1938        let plan = r#"# Test Plan
1939### Task 1: first
1940### Task 2: second
1941### Task 3: third
1942Depends on: Task 2
1943"#;
1944        let doc = parse_plan(plan);
1945        assert_eq!(doc.tasks[0].id, "T1");
1946        assert_eq!(doc.tasks[1].id, "T2");
1947        assert_eq!(doc.tasks[2].deps, ["T2"]);
1948    }
1949
1950    #[test]
1951    fn test_8_non_plan_task_dropped_unless_written_as_task_x() {
1952        let plan = r#"# Test Plan
1953### Task A: first
1954**Depends on:** X9
1955### Task B: second
1956Depends on: Task X9
1957"#;
1958        let doc = parse_plan(plan);
1959        assert!(doc.tasks[0].deps.is_empty());
1960        assert_eq!(doc.tasks[1].deps, ["X9"]);
1961    }
1962
1963    #[test]
1964    fn test_9_real_plan() {
1965        let doc = parse_plan(include_str!(
1966            "../../../docs/superpowers/plans/2026-10-07-orchestrate-mode.md"
1967        ));
1968        let find = |id: &str| {
1969            doc.tasks
1970                .iter()
1971                .find(|t| t.id == id)
1972                .unwrap_or_else(|| panic!("task {id} not found in plan"))
1973                .deps
1974                .clone()
1975        };
1976        assert_eq!(find("OC5"), ["OC2", "OC3", "OC4"]);
1977        assert!(find("OC6").is_empty());
1978        assert_eq!(find("U2"), ["OC9"]);
1979        assert_eq!(find("S2"), ["S1"]);
1980        assert_eq!(find("U3"), ["U1", "U2"]);
1981
1982        let plan_ids: HashSet<&str> = doc.tasks.iter().map(|t| t.id.as_str()).collect();
1983        for task in &doc.tasks {
1984            for dep in &task.deps {
1985                assert!(
1986                    plan_ids.contains(dep.as_str()),
1987                    "task {} has dependency {} which is not a task id in the plan",
1988                    task.id,
1989                    dep
1990                );
1991            }
1992        }
1993    }
1994
1995    fn make_test_job(root: PathBuf, id: &str, verdict: Option<&str>) -> Job {
1996        Job {
1997            problems: Vec::new(),
1998            key: format!("app/{id}"),
1999            id: id.to_string(),
2000            repo: "app".to_string(),
2001            status: "verified".to_string(),
2002            gate_running: false,
2003            title: id.to_string(),
2004            task: String::new(),
2005            plan: None,
2006            now: String::new(),
2007            started_at: Some(100),
2008            finished_at: Some(200),
2009            elapsed_s: Some(100),
2010            cost_usd: None,
2011            turns: 1,
2012            gate_attempts: 1,
2013            gate_failures: Vec::new(),
2014            model: None,
2015            last_tool: None,
2016            worktree: None,
2017            worktree_exists: Some(false),
2018            log: String::new(),
2019            commits: Vec::new(),
2020            changed_files: Vec::new(),
2021            tags: Vec::new(),
2022            verdict: verdict.map(String::from),
2023            root: Some(root),
2024            plan_file: None,
2025            plan_task: None,
2026            request: None,
2027            task_file: None,
2028            research: false,
2029            start_plan: None,
2030            file_tags: Vec::new(),
2031            verdict_notes: None,
2032            verdict_ts: None,
2033            log_mtime: None,
2034        }
2035    }
2036
2037    #[test]
2038    fn job_without_verdict_branch_gone_merged_only_with_merged_removal_record() {
2039        let dir = tempfile::tempdir().unwrap();
2040        let root = dir.path();
2041        let run_git = |args: &[&str]| {
2042            let ok = std::process::Command::new("git")
2043                .args(["-c", "user.name=t", "-c", "user.email=t@t"])
2044                .args(args)
2045                .current_dir(root)
2046                .status()
2047                .unwrap()
2048                .success();
2049            assert!(ok, "git {args:?}");
2050        };
2051        run_git(&["init", "-q", "-b", "main"]);
2052        std::fs::write(root.join("a.txt"), "hello\n").unwrap();
2053        run_git(&["add", "."]);
2054        run_git(&["commit", "-qm", "init", "--no-gpg-sign"]);
2055
2056        let job = make_test_job(root.to_path_buf(), "J1", None);
2057        assert!(!is_job_merged(&job));
2058
2059        for reason in ["merged", "merged_into", "merged_through", "session_merged"] {
2060            let rec = crate::removal_record::RemovalRecord {
2061                id: "J1".to_string(),
2062                reason: reason.to_string(),
2063                detail: None,
2064                removed_at: 1_795_000_000,
2065            };
2066            crate::removal_record::write(root, &rec).unwrap();
2067            assert!(is_job_merged(&job), "reason {reason} should be merged");
2068        }
2069
2070        for reason in ["no_changes", "older_than", "verdict"] {
2071            let rec = crate::removal_record::RemovalRecord {
2072                id: "J1".to_string(),
2073                reason: reason.to_string(),
2074                detail: None,
2075                removed_at: 1_795_000_000,
2076            };
2077            crate::removal_record::write(root, &rec).unwrap();
2078            assert!(!is_job_merged(&job), "reason {reason} should not be merged");
2079        }
2080
2081        let corrupt_path = crate::removal_record::path(root, "J1");
2082        std::fs::write(&corrupt_path, "{corrupt").unwrap();
2083        let mut reported = Vec::new();
2084        assert!(!is_job_merged_with_error_reporter(&job, |e| {
2085            reported.push(e.to_string());
2086        }));
2087        assert_eq!(reported.len(), 1);
2088        assert!(
2089            reported[0].contains(&corrupt_path.display().to_string()),
2090            "expected error naming {}, got: {}",
2091            corrupt_path.display(),
2092            reported[0]
2093        );
2094        assert!(!is_job_merged_with_error_reporter(&job, |e| {
2095            reported.push(e.to_string());
2096        }));
2097        assert_eq!(
2098            reported.len(),
2099            1,
2100            "corrupt removal record error should be reported only once"
2101        );
2102
2103        let job2 = make_test_job(root.to_path_buf(), "J2", None);
2104        let corrupt_path2 = crate::removal_record::path(root, "J2");
2105        std::fs::write(&corrupt_path2, "{corrupt").unwrap();
2106        assert!(!is_job_merged(&job2));
2107        assert!(
2108            REPORTED_REMOVAL_ERRORS
2109                .read()
2110                .unwrap()
2111                .iter()
2112                .any(|msg| msg.contains(&corrupt_path2.display().to_string())),
2113            "expected is_job_merged to record error naming {}",
2114            corrupt_path2.display()
2115        );
2116
2117        let rec = crate::removal_record::RemovalRecord {
2118            id: "J1".to_string(),
2119            reason: "merged".to_string(),
2120            detail: None,
2121            removed_at: 1_795_000_000,
2122        };
2123        crate::removal_record::write(root, &rec).unwrap();
2124        run_git(&["branch", "wip/J1"]);
2125        assert!(!is_job_merged(&job));
2126    }
2127}