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