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