Skip to main content

orch/plan/
mod.rs

1//! Roadmap files and the issue plan `orch plan import` applies.
2//!
3//! A milestone is `## M1. Title`. A task is `### M1-03 Title` with Goal, Scope,
4//! Acceptance, Depends on and Owner lines. Later milestones may be a table with
5//! those columns. An unknown table column or a task with no title is an error.
6//! `none` is no dependency.
7
8use std::collections::{HashMap, HashSet};
9use std::error;
10use std::fmt;
11use std::fmt::Display;
12use std::fmt::Formatter;
13use std::fmt::Write as _;
14use std::hash::BuildHasher;
15
16pub const PLAN_LABEL: &str = "orch-plan";
17pub const HUMAN_LABEL: &str = "owner:human";
18pub const NO_AGENT_LABEL: &str = "no-agent";
19/// Marks the `no-agent` that an import adds while it links blocked-by, so a later import releases
20/// that hold and never a `no-agent` the owner set by hand
21pub const HOLD_LABEL: &str = "orch-plan-hold";
22pub const CI_BOOTSTRAP_ID: &str = "CI-01";
23pub const CI_BOOTSTRAP_MARKER: &str = "<!-- orch-ci-bootstrap -->";
24
25#[derive(Debug, Clone, PartialEq, Eq)]
26pub struct PlanError {
27    pub message: String,
28}
29
30impl Display for PlanError {
31    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
32        f.write_str(&self.message)
33    }
34}
35
36impl error::Error for PlanError {}
37
38impl PlanError {
39    fn new(message: impl Into<String>) -> Self {
40        Self {
41            message: message.into(),
42        }
43    }
44}
45
46#[derive(Debug, Clone, PartialEq, Eq)]
47pub struct Milestone {
48    pub id: String,
49    pub title: String,
50    /// Text after `## `, used for the GitHub heading anchor
51    pub heading: String,
52}
53
54#[derive(Debug, Clone, PartialEq, Eq)]
55pub struct Task {
56    pub id: String,
57    pub title: String,
58    pub milestone_id: String,
59    pub milestone_title: String,
60    pub milestone_heading: String,
61    /// Full `###` heading. Empty for a table row, which links to the milestone heading
62    pub anchor_heading: String,
63    pub goal: String,
64    pub scope: String,
65    pub acceptance: Vec<String>,
66    pub depends_on: Vec<String>,
67    pub owner_human: bool,
68}
69
70#[derive(Debug, Clone, PartialEq, Eq)]
71pub struct Roadmap {
72    pub milestones: Vec<Milestone>,
73    pub tasks: Vec<Task>,
74}
75
76#[derive(Debug, Clone, Copy, PartialEq, Eq)]
77pub enum ChangeKind {
78    Create,
79    Update,
80    Unchanged,
81}
82
83#[derive(Debug, Clone, PartialEq, Eq)]
84pub struct ExistingIssue {
85    pub task_id: String,
86    pub number: u64,
87    pub database_id: u64,
88    pub title: String,
89    pub body: String,
90    pub labels: Vec<String>,
91    pub state: String,
92}
93
94#[derive(Debug, Clone, PartialEq, Eq)]
95pub struct TaskPlan {
96    pub task: Task,
97    pub kind: ChangeKind,
98    pub number: Option<u64>,
99    pub database_id: Option<u64>,
100    pub existing_labels: Vec<String>,
101}
102
103#[derive(Debug, Clone, PartialEq, Eq)]
104pub struct RemovedTask {
105    pub task_id: String,
106    pub number: u64,
107    pub state: String,
108}
109
110#[derive(Debug, Clone, PartialEq, Eq)]
111pub struct PlanDiff {
112    pub tasks: Vec<TaskPlan>,
113    pub removed: Vec<RemovedTask>,
114}
115
116/// A selected task depends on a roadmap id outside the import that has no issue yet
117#[derive(Debug, Clone, PartialEq, Eq)]
118pub struct UnmetExternal {
119    pub task_id: String,
120    pub blocking_task_id: String,
121}
122
123#[derive(Debug, Clone, PartialEq, Eq)]
124pub struct Binding {
125    pub task_id: String,
126    pub number: Option<u64>,
127    pub database_id: Option<u64>,
128}
129
130#[derive(Debug, Clone, PartialEq, Eq)]
131pub struct DepRef {
132    pub number: u64,
133    pub database_id: u64,
134}
135
136#[derive(Debug, Clone, PartialEq, Eq)]
137pub enum LinkEdit {
138    Add {
139        task_id: String,
140        issue_number: Option<u64>,
141        blocking_task_id: String,
142        blocking_number: Option<u64>,
143        blocking_database_id: Option<u64>,
144    },
145    Remove {
146        task_id: String,
147        issue_number: u64,
148        blocking_number: u64,
149        blocking_database_id: u64,
150    },
151}
152
153struct Draft {
154    id: String,
155    title: String,
156    milestone_id: String,
157    milestone_title: String,
158    milestone_heading: String,
159    anchor_heading: String,
160    goal: String,
161    scope: String,
162    acceptance: Vec<String>,
163    depends_raw: Option<String>,
164    owner_human: bool,
165    in_acceptance: bool,
166    line: usize,
167}
168
169#[derive(Clone, Copy)]
170struct TableCols {
171    task: usize,
172    goal: Option<usize>,
173    scope: Option<usize>,
174    acceptance: Option<usize>,
175    depends: Option<usize>,
176    owner: Option<usize>,
177}
178
179pub fn parse_roadmap(markdown: &str) -> Result<Roadmap, PlanError> {
180    parse_roadmap_for(markdown, None).map(|(roadmap, _)| roadmap)
181}
182
183/// With a milestone, errors that belong to other milestones come back as warnings
184pub fn parse_roadmap_for(
185    markdown: &str,
186    milestone: Option<&str>,
187) -> Result<(Roadmap, Vec<String>), PlanError> {
188    let mut milestones = Vec::new();
189    let mut tasks = Vec::new();
190    let mut errors = Vec::new();
191    let mut current: Option<Milestone> = None;
192    let mut draft: Option<Draft> = None;
193    let mut table: Option<TableCols> = None;
194    let mut seen = HashSet::new();
195    let mut tags: Vec<Option<String>> = Vec::new();
196    let mut tag: Option<String> = None;
197
198    for (idx, raw) in markdown.lines().enumerate() {
199        tags.resize(errors.len(), tag.clone());
200        tag = current.as_ref().map(|item| item.id.clone());
201        let line = raw.trim_end_matches('\r');
202        let line_no = idx + 1;
203
204        if let Some(cols) = table {
205            if line.trim().starts_with('|') {
206                if !is_separator_row(line)
207                    && let Some(milestone) = current.as_ref()
208                {
209                    match task_from_row(line, &cols, milestone, line_no) {
210                        Ok(Some(task)) => {
211                            push_task(task, &mut tasks, &mut seen, &mut errors);
212                        }
213                        Ok(None) => {}
214                        Err(err) => errors.push(err),
215                    }
216                }
217                continue;
218            }
219            table = None;
220        }
221
222        if let Some(rest) = line.strip_prefix("### ") {
223            flush_draft(&mut draft, &mut tasks, &mut seen, &mut errors);
224            let Some(milestone) = current.as_ref() else {
225                errors.push(format!(
226                    "line {line_no}: task heading is outside a milestone"
227                ));
228                continue;
229            };
230            if let Some((id, title)) = parse_task_heading(rest) {
231                if title.is_empty() {
232                    errors.push(format!("line {line_no}: {id} has no title"));
233                } else {
234                    draft = Some(Draft::new(id, title, milestone, rest.trim(), line_no));
235                }
236            }
237            continue;
238        }
239
240        if let Some(rest) = line.strip_prefix("## ") {
241            flush_draft(&mut draft, &mut tasks, &mut seen, &mut errors);
242            if let Some((id, title)) = parse_milestone_heading(rest) {
243                let milestone = Milestone {
244                    id,
245                    title,
246                    heading: rest.trim().to_string(),
247                };
248                current = Some(milestone.clone());
249                milestones.push(milestone);
250            } else {
251                current = None;
252            }
253            continue;
254        }
255
256        if let Some((cols, unknown)) = table_cols(line) {
257            flush_draft(&mut draft, &mut tasks, &mut seen, &mut errors);
258            if current.is_some() {
259                if !unknown.is_empty() {
260                    errors.push(format!(
261                        "line {line_no}: unknown table column {}",
262                        unknown.join(", ")
263                    ));
264                }
265                table = Some(cols);
266            }
267            continue;
268        }
269
270        if let Some(draft) = draft.as_mut() {
271            if let Some((name, value)) = top_level_field(line) {
272                draft.apply_field(name, value);
273                continue;
274            }
275            draft.take_acceptance_line(line);
276        }
277    }
278
279    flush_draft(&mut draft, &mut tasks, &mut seen, &mut errors);
280    tags.resize(errors.len(), tag);
281    check_dependencies(&tasks, &mut errors);
282    for message in &errors[tags.len()..] {
283        let id = message
284            .split_whitespace()
285            .next()
286            .and_then(task_milestone_id);
287        tags.push(id.map(str::to_string));
288    }
289
290    let (mut fatal, mut warnings) = (Vec::new(), Vec::new());
291    for (message, tag) in errors.into_iter().zip(tags) {
292        let elsewhere = match (milestone, tag) {
293            (Some(wanted), Some(id)) => !id.eq_ignore_ascii_case(wanted),
294            _ => false,
295        };
296        if elsewhere {
297            warnings.push(message);
298        } else {
299            fatal.push(message);
300        }
301    }
302    if fatal.is_empty() {
303        Ok((Roadmap { milestones, tasks }, warnings))
304    } else {
305        Err(PlanError::new(fatal.join("\n")))
306    }
307}
308
309pub fn select<'a>(
310    roadmap: &'a Roadmap,
311    milestone: Option<&str>,
312) -> Result<Vec<&'a Task>, PlanError> {
313    let Some(wanted) = milestone else {
314        return Ok(roadmap.tasks.iter().collect());
315    };
316    if !roadmap
317        .milestones
318        .iter()
319        .any(|item| item.id.eq_ignore_ascii_case(wanted))
320    {
321        return Err(PlanError::new(format!("no milestone {wanted}")));
322    }
323    Ok(roadmap
324        .tasks
325        .iter()
326        .filter(|task| {
327            task.milestone_id.eq_ignore_ascii_case(wanted) || is_ci_bootstrap_id(&task.id)
328        })
329        .collect())
330}
331
332pub fn issue_title(task: &Task) -> String {
333    if task.title.is_empty() {
334        task.id.clone()
335    } else {
336        format!("{} {}", task.id, task.title)
337    }
338}
339
340pub fn task_anchor(task: &Task) -> String {
341    if task.anchor_heading.is_empty() {
342        github_anchor(&task.milestone_heading)
343    } else {
344        github_anchor(&task.anchor_heading)
345    }
346}
347
348pub fn issue_body(task: &Task, repo: &str, branch: &str, rel_path: &str) -> String {
349    issue_body_with(task, repo, branch, rel_path, &[])
350}
351
352pub fn issue_body_with(
353    task: &Task,
354    repo: &str,
355    branch: &str,
356    rel_path: &str,
357    blocked_external: &[String],
358) -> String {
359    let mut out = String::new();
360    if is_ci_bootstrap_id(&task.id) {
361        out.push_str(CI_BOOTSTRAP_MARKER);
362        out.push('\n');
363    }
364    if !task.goal.is_empty() {
365        out.push_str("## Goal\n\n");
366        out.push_str(task.goal.trim());
367        out.push_str("\n\n");
368    }
369    if !task.scope.is_empty() {
370        out.push_str("## Scope\n\n");
371        out.push_str(task.scope.trim());
372        out.push_str("\n\n");
373    }
374    if !task.acceptance.is_empty() {
375        out.push_str("## Acceptance\n\n");
376        for item in &task.acceptance {
377            let item = item.trim_end();
378            if item.starts_with('-') || item.starts_with('*') || item.starts_with(' ') {
379                out.push_str(item);
380            } else {
381                out.push_str("- ");
382                out.push_str(item);
383            }
384            out.push('\n');
385        }
386        out.push('\n');
387    }
388    if !blocked_external.is_empty() {
389        out.push_str("blocked-external: ");
390        out.push_str(&blocked_external.join(", "));
391        out.push_str(" (no issue yet)\n\n");
392    }
393    if !is_ci_bootstrap_id(&task.id) {
394        let url = format!(
395            "https://github.com/{repo}/blob/{branch}/{path}#{anchor}",
396            branch = encode_git_path(branch),
397            path = encode_git_path(rel_path),
398            anchor = urlencoding::encode(&task_anchor(task)),
399        );
400        let _ = write!(out, "[{rel_path}]({url})\n\n");
401    }
402    if !blocked_external.is_empty() {
403        out.push_str("<!-- orch-blocked-external: ");
404        out.push_str(&blocked_external.join(", "));
405        out.push_str(" -->\n");
406    }
407    out.push_str(&marker_for(&task.id));
408    out.push('\n');
409    out
410}
411
412pub fn marker_for(id: &str) -> String {
413    format!("<!-- orch-plan: {id} -->")
414}
415
416pub fn marker_id(body: &str) -> Option<String> {
417    let start = body.find("<!-- orch-plan:")?;
418    let rest = &body[start + "<!-- orch-plan:".len()..];
419    let end = rest.find("-->")?;
420    let id = rest[..end].trim();
421    is_task_id(id).then(|| id.to_string())
422}
423
424pub fn is_ci_bootstrap_id(id: &str) -> bool {
425    id.eq_ignore_ascii_case(CI_BOOTSTRAP_ID)
426}
427
428pub fn is_ci_bootstrap_body(body: &str) -> bool {
429    body.contains(CI_BOOTSTRAP_MARKER)
430}
431
432/// True when import should add CI-01, because the default branch has no workflow or CI-01 is still open
433pub fn needs_ci_bootstrap(has_workflow: bool, ci_issue_open: bool) -> bool {
434    !has_workflow || ci_issue_open
435}
436
437/// Prepend the CI bootstrap task and make every other task wait on it
438pub fn inject_ci_bootstrap(roadmap: &mut Roadmap, include_shipcheck: bool) {
439    if !roadmap
440        .tasks
441        .iter()
442        .any(|task| is_ci_bootstrap_id(&task.id))
443    {
444        if !roadmap
445            .milestones
446            .iter()
447            .any(|milestone| milestone.id.eq_ignore_ascii_case("CI"))
448        {
449            roadmap.milestones.insert(
450                0,
451                Milestone {
452                    id: "CI".to_string(),
453                    title: "CI bootstrap".to_string(),
454                    heading: "CI. CI bootstrap".to_string(),
455                },
456            );
457        }
458        roadmap
459            .tasks
460            .insert(0, ci_bootstrap_task(include_shipcheck));
461    }
462    for task in &mut roadmap.tasks {
463        if is_ci_bootstrap_id(&task.id) {
464            continue;
465        }
466        if !task.depends_on.iter().any(|dep| is_ci_bootstrap_id(dep)) {
467            task.depends_on.insert(0, CI_BOOTSTRAP_ID.to_string());
468        }
469    }
470}
471
472pub(crate) fn ci_bootstrap_task(include_shipcheck: bool) -> Task {
473    let mut scope = String::from(
474        "Add the smallest project layout that can run tests for this repository's language.\n\
475         Add at least one test that fails if that layout is broken.\n\
476         Add a GitHub Actions workflow under `.github/workflows/` that runs those tests on every push to the default branch.\n\
477         Do not add product features.",
478    );
479    let mut acceptance = vec![
480        "A workflow file exists on the default branch after merge.".to_string(),
481        "Pushing to the default branch runs the workflow.".to_string(),
482        "The workflow reports a passing check.".to_string(),
483        "Tests fail when the skeleton is broken.".to_string(),
484    ];
485    if include_shipcheck {
486        scope.push_str("\nAdd or keep `shipcheck.toml` so local checks match the workflow jobs.");
487        acceptance.push("`shipcheck.toml` lists the same checks the workflow runs.".to_string());
488    }
489    Task {
490        id: CI_BOOTSTRAP_ID.to_string(),
491        title: "Set up CI and tests".to_string(),
492        milestone_id: "CI".to_string(),
493        milestone_title: "CI bootstrap".to_string(),
494        milestone_heading: "CI. CI bootstrap".to_string(),
495        anchor_heading: "CI-01 Set up CI and tests".to_string(),
496        goal: "Give this repository a project skeleton, tests, and a GitHub Actions workflow that runs on every push to the default branch, so later tasks can rely on required checks.".to_string(),
497        scope,
498        acceptance,
499        depends_on: Vec::new(),
500        owner_human: false,
501    }
502}
503
504/// Labels for a plan issue. Human tasks also get `no-agent`, which the dispatcher already skips
505pub fn labels_for(existing: &[String], human: bool) -> Vec<String> {
506    let drop_no_agent = existing.iter().any(|label| label == HUMAN_LABEL);
507    let mut labels = vec![PLAN_LABEL.to_string()];
508    if human {
509        labels.push(HUMAN_LABEL.to_string());
510        labels.push(NO_AGENT_LABEL.to_string());
511    }
512    for label in existing {
513        if label == PLAN_LABEL || label == HUMAN_LABEL {
514            continue;
515        }
516        if label == NO_AGENT_LABEL && (human || drop_no_agent) {
517            continue;
518        }
519        if !labels.iter().any(|have| have == label) {
520            labels.push(label.clone());
521        }
522    }
523    labels
524}
525
526pub fn diff_import(
527    roadmap: &Roadmap,
528    existing: &[ExistingIssue],
529    milestone: Option<&str>,
530    mut body_for: impl FnMut(&Task) -> String,
531) -> Result<PlanDiff, PlanError> {
532    let selected = select(roadmap, milestone)?;
533    let mut by_id: HashMap<&str, &ExistingIssue> = HashMap::new();
534    let mut errors = Vec::new();
535    for issue in existing {
536        if by_id.insert(issue.task_id.as_str(), issue).is_some() {
537            errors.push(format!(
538                "more than one issue is marked as {}",
539                issue.task_id
540            ));
541        }
542    }
543    if !errors.is_empty() {
544        return Err(PlanError::new(errors.join("\n")));
545    }
546
547    let mut tasks = Vec::new();
548    let mut selected_ids = HashSet::new();
549    for task in selected {
550        selected_ids.insert(task.id.as_str());
551        let title = issue_title(task);
552        let body = body_for(task);
553        let kind = if let Some(issue) = by_id.get(task.id.as_str()) {
554            let same = issue.title == title
555                && normalize_body(&issue.body) == normalize_body(&body)
556                && same_labels(&issue.labels, &labels_for(&issue.labels, task.owner_human));
557            if same {
558                ChangeKind::Unchanged
559            } else {
560                ChangeKind::Update
561            }
562        } else {
563            ChangeKind::Create
564        };
565        let issue = by_id.get(task.id.as_str()).copied();
566        tasks.push(TaskPlan {
567            task: task.clone(),
568            kind,
569            number: issue.map(|item| item.number),
570            database_id: issue.map(|item| item.database_id),
571            existing_labels: issue.map(|item| item.labels.clone()).unwrap_or_default(),
572        });
573    }
574
575    let mut removed = Vec::new();
576    for issue in existing {
577        if selected_ids.contains(issue.task_id.as_str()) || is_ci_bootstrap_id(&issue.task_id) {
578            continue;
579        }
580        if let Some(wanted) = milestone {
581            let Some(prefix) = task_milestone_id(&issue.task_id) else {
582                continue;
583            };
584            if !prefix.eq_ignore_ascii_case(wanted) {
585                continue;
586            }
587        }
588        removed.push(RemovedTask {
589            task_id: issue.task_id.clone(),
590            number: issue.number,
591            state: issue.state.clone(),
592        });
593    }
594
595    Ok(PlanDiff { tasks, removed })
596}
597
598/// Dependencies outside the selected set that have no GitHub issue yet.
599///
600/// An id that is not in the roadmap is an error. An id in the roadmap is reported
601pub fn unmet_externals<S: BuildHasher>(
602    tasks: &[Task],
603    roadmap: &Roadmap,
604    known_ids: &HashSet<String, S>,
605) -> Result<Vec<UnmetExternal>, PlanError> {
606    let selected: HashSet<&str> = tasks.iter().map(|task| task.id.as_str()).collect();
607    let roadmap_ids: HashSet<&str> = roadmap.tasks.iter().map(|task| task.id.as_str()).collect();
608    let mut unmet = Vec::new();
609    let mut errors = Vec::new();
610    for task in tasks {
611        for dep in &task.depends_on {
612            if selected.contains(dep.as_str()) || known_ids.contains(dep) {
613                continue;
614            }
615            if roadmap_ids.contains(dep.as_str()) {
616                unmet.push(UnmetExternal {
617                    task_id: task.id.clone(),
618                    blocking_task_id: dep.clone(),
619                });
620            } else {
621                errors.push(format!("{} depends on unknown task {dep}", task.id));
622            }
623        }
624    }
625    if errors.is_empty() {
626        Ok(unmet)
627    } else {
628        Err(PlanError::new(errors.join("\n")))
629    }
630}
631
632/// Task ids to omit when `--skip-unmet` is set, including tasks that depend on a skipped task
633pub fn skip_unmet_ids(tasks: &[Task], unmet: &[UnmetExternal]) -> HashSet<String> {
634    let mut skip: HashSet<String> = unmet.iter().map(|item| item.task_id.clone()).collect();
635    loop {
636        let mut added = false;
637        for task in tasks {
638            if skip.contains(&task.id) {
639                continue;
640            }
641            if task.depends_on.iter().any(|dep| skip.contains(dep)) {
642                skip.insert(task.id.clone());
643                added = true;
644            }
645        }
646        if !added {
647            break;
648        }
649    }
650    skip
651}
652
653pub fn blocked_external_ids<'a>(unmet: &'a [UnmetExternal], task_id: &str) -> Vec<&'a str> {
654    unmet
655        .iter()
656        .filter(|item| item.task_id == task_id)
657        .map(|item| item.blocking_task_id.as_str())
658        .collect()
659}
660
661pub fn diff_links<S: BuildHasher>(
662    tasks: &[Task],
663    bindings: &[Binding],
664    current: &HashMap<u64, Vec<DepRef>, S>,
665) -> Result<Vec<LinkEdit>, PlanError> {
666    let mut edits = Vec::new();
667    let mut errors = Vec::new();
668    let managed: HashSet<u64> = bindings.iter().filter_map(|item| item.number).collect();
669    for task in tasks {
670        let Some(binding) = bindings.iter().find(|item| item.task_id == task.id) else {
671            errors.push(format!("{} has no issue binding", task.id));
672            continue;
673        };
674        let blocked = binding
675            .number
676            .and_then(|number| current.get(&number))
677            .cloned()
678            .unwrap_or_default();
679        let mut desired_numbers = Vec::new();
680        for dep_id in &task.depends_on {
681            let Some(dep) = bindings.iter().find(|item| item.task_id == dep_id.as_str()) else {
682                continue;
683            };
684            if let Some(number) = dep.number {
685                desired_numbers.push(number);
686            }
687            let already = dep
688                .number
689                .is_some_and(|number| blocked.iter().any(|item| item.number == number));
690            if !already {
691                edits.push(LinkEdit::Add {
692                    task_id: task.id.clone(),
693                    issue_number: binding.number,
694                    blocking_task_id: dep_id.clone(),
695                    blocking_number: dep.number,
696                    blocking_database_id: dep.database_id,
697                });
698            }
699        }
700        if let Some(issue_number) = binding.number {
701            for item in &blocked {
702                // Only drop links to other plan issues, a link a person added by hand stays
703                if desired_numbers.contains(&item.number) || !managed.contains(&item.number) {
704                    continue;
705                }
706                edits.push(LinkEdit::Remove {
707                    task_id: task.id.clone(),
708                    issue_number,
709                    blocking_number: item.number,
710                    blocking_database_id: item.database_id,
711                });
712            }
713        }
714    }
715    if errors.is_empty() {
716        Ok(edits)
717    } else {
718        Err(PlanError::new(errors.join("\n")))
719    }
720}
721
722pub fn render(diff: &PlanDiff, links: &[LinkEdit], dry_run: bool) -> String {
723    render_report(diff, links, &[], &[], dry_run)
724}
725
726pub fn render_report(
727    diff: &PlanDiff,
728    links: &[LinkEdit],
729    unmet: &[UnmetExternal],
730    skipped: &[String],
731    dry_run: bool,
732) -> String {
733    let mut out = render_tasks(diff);
734    out.push_str(&render_unmet(unmet, skipped));
735    out.push_str(&render_links(links));
736    out.push_str(&render_summary(diff, links, dry_run));
737    out
738}
739
740fn render_unmet(unmet: &[UnmetExternal], skipped: &[String]) -> String {
741    let skip: HashSet<&str> = skipped.iter().map(String::as_str).collect();
742    let mut out = String::new();
743    for id in skipped {
744        let deps = blocked_external_ids(unmet, id);
745        if deps.is_empty() {
746            let _ = writeln!(out, "skip {id}");
747        } else {
748            let _ = writeln!(
749                out,
750                "skip {id} depends on {}, which has no issue yet",
751                deps.join(", ")
752            );
753        }
754    }
755    let mut seen = HashSet::new();
756    for item in unmet {
757        if skip.contains(item.task_id.as_str()) || !seen.insert(item.task_id.as_str()) {
758            continue;
759        }
760        let deps = blocked_external_ids(unmet, &item.task_id);
761        let _ = writeln!(
762            out,
763            "blocked-external {} depends on {}, which has no issue yet",
764            item.task_id,
765            deps.join(", ")
766        );
767    }
768    out
769}
770
771pub fn render_outline(roadmap: &Roadmap) -> String {
772    let mut out = String::new();
773    for milestone in &roadmap.milestones {
774        let _ = writeln!(out, "{} {}", milestone.id, milestone.title);
775        for task in roadmap
776            .tasks
777            .iter()
778            .filter(|task| task.milestone_id == milestone.id)
779        {
780            let human = if task.owner_human { " [human]" } else { "" };
781            let deps = if task.depends_on.is_empty() {
782                "none".to_string()
783            } else {
784                task.depends_on.join(", ")
785            };
786            let _ = writeln!(out, "  {} {}{human}", task.id, task.title);
787            let _ = writeln!(out, "    depends on: {deps}");
788        }
789        out.push('\n');
790    }
791    out
792}
793
794pub fn render_tasks(diff: &PlanDiff) -> String {
795    let mut out = String::new();
796    for plan in &diff.tasks {
797        let human = if plan.task.owner_human {
798            " [human]"
799        } else {
800            ""
801        };
802        let deps = if plan.task.depends_on.is_empty() {
803            "none".to_string()
804        } else {
805            plan.task.depends_on.join(", ")
806        };
807        let _ = writeln!(
808            out,
809            "{kind} {title}{human}\n  depends on: {deps}",
810            kind = kind_word(plan.kind),
811            title = issue_title(&plan.task),
812        );
813    }
814    for removed in &diff.removed {
815        let _ = writeln!(
816            out,
817            "removed {} issue #{} ({}), not closed",
818            removed.task_id, removed.number, removed.state
819        );
820    }
821    out
822}
823
824pub fn render_links(links: &[LinkEdit]) -> String {
825    let mut out = String::new();
826    for link in links {
827        match link {
828            LinkEdit::Add {
829                task_id,
830                issue_number,
831                blocking_task_id,
832                blocking_number,
833                ..
834            } => {
835                let _ = writeln!(
836                    out,
837                    "link {task_id}{issue} blocked by {blocking_task_id}{blocking}",
838                    issue = number_suffix(*issue_number),
839                    blocking = number_suffix(*blocking_number),
840                );
841            }
842            LinkEdit::Remove {
843                task_id,
844                blocking_number,
845                ..
846            } => {
847                let _ = writeln!(out, "unlink {task_id} blocked by #{blocking_number}");
848            }
849        }
850    }
851    out
852}
853
854pub fn render_summary(diff: &PlanDiff, links: &[LinkEdit], dry_run: bool) -> String {
855    let creates = diff
856        .tasks
857        .iter()
858        .filter(|plan| plan.kind == ChangeKind::Create)
859        .count();
860    let updates = diff
861        .tasks
862        .iter()
863        .filter(|plan| plan.kind == ChangeKind::Update)
864        .count();
865    let unchanged = diff
866        .tasks
867        .iter()
868        .filter(|plan| plan.kind == ChangeKind::Unchanged)
869        .count();
870    let prefix = if dry_run { "dry run: " } else { "" };
871    format!(
872        "{prefix}create {creates}, update {updates}, unchanged {unchanged}, link {}, removed {}\n",
873        links.len(),
874        diff.removed.len()
875    )
876}
877
878pub fn github_anchor(heading: &str) -> String {
879    let mut out = String::new();
880    let mut prev_hyphen = false;
881    for ch in heading.chars() {
882        if ch.is_whitespace() {
883            if !out.is_empty() && !prev_hyphen {
884                out.push('-');
885                prev_hyphen = true;
886            }
887            continue;
888        }
889        if ch == '-' || ch == '_' {
890            if !out.is_empty() && !prev_hyphen {
891                out.push(ch);
892                prev_hyphen = true;
893            }
894            continue;
895        }
896        if ch.is_alphanumeric() {
897            for lower in ch.to_lowercase() {
898                out.push(lower);
899            }
900            prev_hyphen = false;
901        }
902    }
903    while out.ends_with('-') || out.ends_with('_') {
904        out.pop();
905    }
906    out
907}
908
909fn encode_git_path(path: &str) -> String {
910    path.split('/')
911        .map(|segment| urlencoding::encode(segment).into_owned())
912        .collect::<Vec<_>>()
913        .join("/")
914}
915
916fn kind_word(kind: ChangeKind) -> &'static str {
917    match kind {
918        ChangeKind::Create => "create",
919        ChangeKind::Update => "update",
920        ChangeKind::Unchanged => "unchanged",
921    }
922}
923
924fn number_suffix(number: Option<u64>) -> String {
925    match number {
926        Some(number) if number > 0 => format!(" (#{number})"),
927        _ => String::new(),
928    }
929}
930
931fn normalize_body(body: &str) -> String {
932    body.replace("\r\n", "\n").trim().to_string()
933}
934
935fn same_labels(left: &[String], right: &[String]) -> bool {
936    let left: HashSet<&str> = left.iter().map(String::as_str).collect();
937    let right: HashSet<&str> = right.iter().map(String::as_str).collect();
938    left == right
939}
940
941fn task_milestone_id(task_id: &str) -> Option<&str> {
942    if !is_task_id(task_id) {
943        return None;
944    }
945    task_id.split_once('-').map(|(prefix, _)| prefix)
946}
947
948fn push_task(
949    task: Task,
950    tasks: &mut Vec<Task>,
951    seen: &mut HashSet<String>,
952    errors: &mut Vec<String>,
953) {
954    if !seen.insert(task.id.clone()) {
955        errors.push(format!("duplicate task id {}", task.id));
956        return;
957    }
958    tasks.push(task);
959}
960
961fn flush_draft(
962    draft: &mut Option<Draft>,
963    tasks: &mut Vec<Task>,
964    seen: &mut HashSet<String>,
965    errors: &mut Vec<String>,
966) {
967    let Some(draft) = draft.take() else {
968        return;
969    };
970    match draft.into_task() {
971        Ok(task) => push_task(task, tasks, seen, errors),
972        Err(err) => errors.push(err),
973    }
974}
975
976fn check_dependencies(tasks: &[Task], errors: &mut Vec<String>) {
977    let ids: HashSet<&str> = tasks.iter().map(|task| task.id.as_str()).collect();
978    for task in tasks {
979        for dep in &task.depends_on {
980            if dep == &task.id {
981                errors.push(format!("{} depends on itself", task.id));
982            } else if !ids.contains(dep.as_str()) {
983                errors.push(format!("{} depends on unknown task {dep}", task.id));
984            }
985        }
986    }
987}
988
989impl Draft {
990    /// Add `line` to the acceptance list while an `Acceptance:` field is open
991    fn take_acceptance_line(&mut self, line: &str) {
992        if self.in_acceptance && is_acceptance_line(line) {
993            self.acceptance.push(unindent(line));
994        }
995    }
996
997    fn apply_field(&mut self, name: &str, value: &str) {
998        if name.eq_ignore_ascii_case("goal") {
999            self.in_acceptance = false;
1000            self.goal = value.to_string();
1001        } else if name.eq_ignore_ascii_case("scope") {
1002            self.in_acceptance = false;
1003            self.scope = value.to_string();
1004        } else if name.eq_ignore_ascii_case("acceptance") {
1005            self.in_acceptance = true;
1006            if !value.is_empty() {
1007                self.acceptance.push(acceptance_item(value));
1008            }
1009        } else if name.eq_ignore_ascii_case("depends on") {
1010            self.in_acceptance = false;
1011            self.depends_raw = Some(value.to_string());
1012        } else if name.eq_ignore_ascii_case("owner") {
1013            self.in_acceptance = false;
1014            self.owner_human = is_human_owner(value);
1015        }
1016    }
1017}
1018
1019fn acceptance_item(value: &str) -> String {
1020    if value.starts_with('-') || value.starts_with('*') {
1021        value.to_string()
1022    } else {
1023        format!("- {value}")
1024    }
1025}
1026
1027fn is_acceptance_line(line: &str) -> bool {
1028    let trimmed = line.trim();
1029    !trimmed.is_empty()
1030        && (line.starts_with(' ')
1031            || line.starts_with('\t')
1032            || trimmed.starts_with("- ")
1033            || trimmed.starts_with("* "))
1034}
1035
1036fn unindent(line: &str) -> String {
1037    let line = line.trim_end();
1038    line.strip_prefix("  ")
1039        .or_else(|| line.strip_prefix('\t'))
1040        .unwrap_or(line)
1041        .to_string()
1042}
1043
1044fn top_level_field(line: &str) -> Option<(&str, &str)> {
1045    let rest = line.strip_prefix("- ")?;
1046    let (name, value) = rest.split_once(':')?;
1047    let name = name.trim();
1048    is_known_field(name).then_some((name, value.trim()))
1049}
1050
1051fn is_known_field(name: &str) -> bool {
1052    name.eq_ignore_ascii_case("goal")
1053        || name.eq_ignore_ascii_case("scope")
1054        || name.eq_ignore_ascii_case("acceptance")
1055        || name.eq_ignore_ascii_case("depends on")
1056        || name.eq_ignore_ascii_case("owner")
1057}
1058
1059fn is_human_owner(value: &str) -> bool {
1060    let Some(word) = value.split_whitespace().next() else {
1061        return false;
1062    };
1063    word.trim_matches(|ch: char| matches!(ch, '.' | ',' | ';' | ':'))
1064        .eq_ignore_ascii_case("human")
1065}
1066
1067fn parse_depends(raw: &str) -> Result<Vec<String>, String> {
1068    let trimmed = raw.trim().trim_end_matches('.').trim();
1069    if trimmed.is_empty() {
1070        return Ok(Vec::new());
1071    }
1072    let first = trimmed.split_whitespace().next().unwrap_or("");
1073    let first = first.trim_matches(|ch: char| matches!(ch, '.' | ',' | ';' | ':'));
1074    // A leading none is no dependency, even when the rest of the line names a task
1075    if first.eq_ignore_ascii_case("none") {
1076        return Ok(Vec::new());
1077    }
1078    let ids = extract_ids(trimmed);
1079    if ids.is_empty() {
1080        Err(format!("depends on value \"{trimmed}\" has no task id"))
1081    } else {
1082        Ok(ids)
1083    }
1084}
1085
1086fn extract_ids(raw: &str) -> Vec<String> {
1087    let bytes = raw.as_bytes();
1088    let mut ids = Vec::new();
1089    let mut index = 0;
1090    while index < bytes.len() {
1091        if bytes[index].is_ascii_alphabetic() {
1092            let start = index;
1093            index += 1;
1094            while index < bytes.len()
1095                && (bytes[index].is_ascii_alphanumeric() || bytes[index] == b'-')
1096            {
1097                index += 1;
1098            }
1099            let token = &raw[start..index];
1100            if is_task_id(token) && !ids.iter().any(|id| id == token) {
1101                ids.push(token.to_string());
1102            }
1103            continue;
1104        }
1105        index += 1;
1106    }
1107    ids
1108}
1109
1110fn is_task_id(token: &str) -> bool {
1111    if is_ci_bootstrap_id(token) {
1112        return true;
1113    }
1114    let Some((milestone, rest)) = token.split_once('-') else {
1115        return false;
1116    };
1117    if !is_milestone_id(milestone) || rest.is_empty() || !rest.as_bytes()[0].is_ascii_digit() {
1118        return false;
1119    }
1120    rest.bytes().all(|byte| byte.is_ascii_alphanumeric())
1121}
1122
1123fn is_milestone_id(token: &str) -> bool {
1124    let mut chars = token.chars();
1125    let Some(first) = chars.next() else {
1126        return false;
1127    };
1128    if !first.is_ascii_alphabetic() {
1129        return false;
1130    }
1131    let mut saw_digit = false;
1132    for ch in chars {
1133        if ch.is_ascii_digit() {
1134            saw_digit = true;
1135        } else if !ch.is_ascii_alphabetic() {
1136            return false;
1137        }
1138    }
1139    saw_digit
1140}
1141
1142pub(crate) fn is_milestone_heading(line: &str) -> bool {
1143    line.trim_start()
1144        .strip_prefix("## ")
1145        .and_then(parse_milestone_heading)
1146        .is_some()
1147}
1148
1149fn parse_milestone_heading(rest: &str) -> Option<(String, String)> {
1150    let rest = rest.trim();
1151    let (first, title) = rest.split_once(char::is_whitespace)?;
1152    let id = first.trim_end_matches('.');
1153    is_milestone_id(id).then(|| (id.to_string(), title.trim().to_string()))
1154}
1155
1156fn parse_task_heading(rest: &str) -> Option<(String, String)> {
1157    let rest = rest.trim();
1158    let (id, title) = match rest.split_once(char::is_whitespace) {
1159        Some((id, title)) => (id, title.trim()),
1160        None => (rest, ""),
1161    };
1162    is_task_id(id).then(|| (id.to_string(), title.to_string()))
1163}
1164
1165fn table_cols(line: &str) -> Option<(TableCols, Vec<String>)> {
1166    if !line.trim().starts_with('|') {
1167        return None;
1168    }
1169    let cells = split_cells(line);
1170    let names: Vec<String> = cells.iter().map(|cell| cell.to_ascii_lowercase()).collect();
1171    let task = names.iter().position(|name| name == "task")?;
1172    if !names.iter().any(|name| name == "depends on") {
1173        return None;
1174    }
1175    let unknown = cells
1176        .iter()
1177        .zip(names.iter())
1178        .filter(|(_, name)| !name.is_empty() && !is_known_table_column(name))
1179        .map(|(cell, _)| cell.clone())
1180        .collect();
1181    let pos = |label: &str| names.iter().position(|name| name == label);
1182    Some((
1183        TableCols {
1184            task,
1185            goal: pos("goal"),
1186            scope: pos("scope"),
1187            acceptance: pos("acceptance"),
1188            depends: pos("depends on"),
1189            owner: pos("owner"),
1190        },
1191        unknown,
1192    ))
1193}
1194
1195fn is_known_table_column(name: &str) -> bool {
1196    name.eq_ignore_ascii_case("task") || is_known_field(name)
1197}
1198
1199fn is_separator_row(line: &str) -> bool {
1200    let cells = split_cells(line);
1201    !cells.is_empty()
1202        && cells.iter().all(|cell| {
1203            let token = cell.trim_matches(':');
1204            !token.is_empty() && token.chars().all(|ch| ch == '-')
1205        })
1206}
1207
1208fn split_cells(line: &str) -> Vec<String> {
1209    line.trim()
1210        .trim_matches('|')
1211        .split('|')
1212        .map(|cell| cell.trim().to_string())
1213        .collect()
1214}
1215
1216fn cell(cells: &[String], index: Option<usize>) -> &str {
1217    index
1218        .and_then(|index| cells.get(index))
1219        .map_or("", String::as_str)
1220}
1221
1222fn task_from_row(
1223    line: &str,
1224    cols: &TableCols,
1225    milestone: &Milestone,
1226    line_no: usize,
1227) -> Result<Option<Task>, String> {
1228    let cells = split_cells(line);
1229    let task_cell = cell(&cells, Some(cols.task));
1230    let Some((id, title)) = parse_task_heading(task_cell) else {
1231        return Ok(None);
1232    };
1233    if title.is_empty() {
1234        return Err(format!("line {line_no}: {id} has no title"));
1235    }
1236    let depends_raw = cell(&cells, cols.depends);
1237    let depends_on =
1238        parse_depends(depends_raw).map_err(|err| format!("line {line_no}: {id} {err}"))?;
1239    let owner = cell(&cells, cols.owner);
1240    Ok(Some(Task {
1241        id,
1242        title,
1243        milestone_id: milestone.id.clone(),
1244        milestone_title: milestone.title.clone(),
1245        milestone_heading: milestone.heading.clone(),
1246        anchor_heading: String::new(),
1247        goal: cell(&cells, cols.goal).to_string(),
1248        scope: cell(&cells, cols.scope).to_string(),
1249        acceptance: {
1250            let value = cell(&cells, cols.acceptance);
1251            if value.is_empty() {
1252                Vec::new()
1253            } else {
1254                vec![acceptance_item(value)]
1255            }
1256        },
1257        depends_on,
1258        owner_human: is_human_owner(owner),
1259    }))
1260}
1261
1262impl Draft {
1263    fn new(
1264        id: String,
1265        title: String,
1266        milestone: &Milestone,
1267        anchor_heading: &str,
1268        line: usize,
1269    ) -> Self {
1270        Self {
1271            id,
1272            title,
1273            milestone_id: milestone.id.clone(),
1274            milestone_title: milestone.title.clone(),
1275            milestone_heading: milestone.heading.clone(),
1276            anchor_heading: anchor_heading.to_string(),
1277            goal: String::new(),
1278            scope: String::new(),
1279            acceptance: Vec::new(),
1280            depends_raw: None,
1281            owner_human: false,
1282            in_acceptance: false,
1283            line,
1284        }
1285    }
1286
1287    fn into_task(self) -> Result<Task, String> {
1288        let depends_on = match self.depends_raw {
1289            Some(raw) => parse_depends(&raw)
1290                .map_err(|err| format!("line {}: {} {err}", self.line, self.id))?,
1291            None => Vec::new(),
1292        };
1293        Ok(Task {
1294            id: self.id,
1295            title: self.title,
1296            milestone_id: self.milestone_id,
1297            milestone_title: self.milestone_title,
1298            milestone_heading: self.milestone_heading,
1299            anchor_heading: self.anchor_heading,
1300            goal: self.goal,
1301            scope: self.scope,
1302            acceptance: self.acceptance,
1303            depends_on,
1304            owner_human: self.owner_human,
1305        })
1306    }
1307}
1308
1309#[cfg(test)]
1310mod tests;