1use std::collections::{HashMap, HashSet};
4use std::env;
5use std::fs;
6use std::io::{self, Write};
7use std::path::{Path, PathBuf};
8use std::process::Command;
9
10use anyhow::Context;
11
12use crate::backends::BlockedByFetch;
13use crate::cli;
14use crate::config;
15use crate::control;
16use crate::github::http::GhHttp;
17use crate::github::types::GitHubIssue;
18use crate::plan::{
19 self, Binding, ChangeKind, DepRef, ExistingIssue, HOLD_LABEL, HUMAN_LABEL, LinkEdit,
20 NO_AGENT_LABEL, PLAN_LABEL, PlanDiff, Roadmap, Task, UnmetExternal, diff_import, diff_links,
21 issue_body_with, issue_title, labels_for, marker_id, render_report, skip_unmet_ids,
22 unmet_externals,
23};
24use crate::store::TaskStore;
25
26pub async fn from_plan(file: &str, yes: bool) -> anyhow::Result<()> {
28 let path = Path::new(file);
29 let markdown =
30 fs::read_to_string(path).with_context(|| format!("failed to read {}", path.display()))?;
31 if markdown.trim().is_empty() {
32 anyhow::bail!("{} is empty", path.display());
33 }
34 let dest = roadmap_path(path);
35 let existing = fs::read_to_string(&dest).ok();
36 let (roadmap_md, roadmap) = draft_roadmap(&markdown, existing.as_deref()).await?;
37 let dest_str = dest
38 .to_str()
39 .with_context(|| format!("roadmap path {} is not utf-8", dest.display()))?;
40 fs::write(&dest, with_trailing_newline(&roadmap_md))
42 .with_context(|| format!("failed to write {dest_str}"))?;
43 print!("{}", plan::render_outline(&roadmap));
44 println!("Wrote {dest_str}");
45 if !yes && !prompt_import()? {
46 println!("aborted");
47 return Ok(());
48 }
49 import(dest_str, false, None, false).await
50}
51
52pub async fn import(
53 file: &str,
54 dry_run: bool,
55 milestone: Option<&str>,
56 skip_unmet: bool,
57) -> anyhow::Result<()> {
58 let path = Path::new(file);
59 let markdown =
60 fs::read_to_string(path).with_context(|| format!("failed to read {}", path.display()))?;
61 let repo = config::get_current_repo()
62 .context("'repo' not set — run `orch init` or set gh.repo in .orch.yml")?;
63 let rel_path = repo_relative(path).unwrap_or_else(|| {
64 let name = path.file_name().map_or_else(
65 || file.to_string(),
66 |name| name.to_string_lossy().into_owned(),
67 );
68 eprintln!("warning: {file} is outside the git checkout, the issue link uses {name}");
69 name
70 });
71 let outcome =
72 import_roadmap(&repo, &markdown, &rel_path, milestone, skip_unmet, dry_run).await?;
73 for warning in outcome.warnings {
74 eprintln!("warning: {warning}");
75 }
76 print!("{}", outcome.report);
77 Ok(())
78}
79
80#[derive(Debug, Clone)]
82pub(crate) struct ImportOutcome {
83 pub(crate) report: String,
84 pub(crate) warnings: Vec<String>,
85}
86
87pub(crate) async fn import_roadmap(
89 repo: &str,
90 markdown: &str,
91 rel_path: &str,
92 milestone: Option<&str>,
93 skip_unmet: bool,
94 dry_run: bool,
95) -> anyhow::Result<ImportOutcome> {
96 let repo = repo.to_string();
97 let rel_path = rel_path.to_string();
98 let (mut roadmap, warnings) = plan::parse_roadmap_for(markdown, milestone)?;
99 if let Some(id) = milestone {
100 plan::select(&roadmap, Some(id))?;
101 }
102
103 let http = GhHttp::new()?;
104 let branch = http.get_default_branch(&repo).await?;
105 let existing = load_existing(&http, &repo).await?;
106 let has_workflow = http.has_workflow_on_branch(&repo, &branch).await?;
107 let ci_open = existing.iter().any(|issue| {
108 plan::is_ci_bootstrap_id(&issue.task_id) && issue.state.eq_ignore_ascii_case("open")
109 });
110 if plan::needs_ci_bootstrap(has_workflow, ci_open) {
111 let shipcheck = http
112 .has_file_on_branch(&repo, "shipcheck.toml", &branch)
113 .await?;
114 plan::inject_ci_bootstrap(&mut roadmap, shipcheck);
115 }
116 let known: HashSet<String> = existing.iter().map(|issue| issue.task_id.clone()).collect();
117 let selected_all: Vec<Task> = plan::select(&roadmap, milestone)?
118 .into_iter()
119 .cloned()
120 .collect();
121 let unmet = unmet_externals(&selected_all, &roadmap, &known)?;
122 let extras = extras_by_task(&unmet);
123 let body_for = |task: &Task| {
124 let extra = extras.get(&task.id).map_or(&[][..], Vec::as_slice);
125 issue_body_with(task, &repo, &branch, &rel_path, extra)
126 };
127 let mut diff = diff_import(&roadmap, &existing, milestone, body_for)?;
128 let skipped = if skip_unmet {
129 let skip = skip_unmet_ids(&selected_all, &unmet);
130 let mut skipped = Vec::new();
131 diff.tasks.retain(|plan| {
132 if plan.kind == ChangeKind::Create && skip.contains(&plan.task.id) {
133 skipped.push(plan.task.id.clone());
134 false
135 } else {
136 true
137 }
138 });
139 skipped
140 } else {
141 Vec::new()
142 };
143
144 let selected: Vec<Task> = diff.tasks.iter().map(|plan| plan.task.clone()).collect();
145 let bindings = bindings_for(&diff, &existing);
146 let current = load_blocked_by(&http, &repo, &diff).await?;
147 let links = diff_links(&selected, &bindings, ¤t)?;
148 if dry_run {
149 return Ok(ImportOutcome {
150 report: render_report(&diff, &links, &unmet, &skipped, true),
151 warnings,
152 });
153 }
154
155 apply(&http, &repo, &diff, &links, &rel_path, &branch, &extras).await?;
156 Ok(ImportOutcome {
157 report: render_report(&diff, &links, &unmet, &skipped, false),
158 warnings,
159 })
160}
161
162fn extras_by_task(unmet: &[UnmetExternal]) -> HashMap<String, Vec<String>> {
163 let mut extras: HashMap<String, Vec<String>> = HashMap::new();
164 for item in unmet {
165 extras
166 .entry(item.task_id.clone())
167 .or_default()
168 .push(item.blocking_task_id.clone());
169 }
170 extras
171}
172
173async fn load_existing(http: &GhHttp, repo: &str) -> anyhow::Result<Vec<ExistingIssue>> {
174 let issues = match http.list_issues_with_state(repo, "", "all").await {
176 Ok(issues) => issues,
177 Err(err) if err.to_string().contains("404") => Vec::new(),
178 Err(err) => return Err(err),
179 };
180 existing_from_issues(issues)
181}
182
183fn existing_from_issues(issues: Vec<GitHubIssue>) -> anyhow::Result<Vec<ExistingIssue>> {
184 let mut existing = Vec::new();
185 for issue in issues {
186 let labeled = issue.labels.iter().any(|label| label.name == PLAN_LABEL);
187 let trusted = labeled
189 || matches!(
190 issue.author_association.as_deref(),
191 Some("OWNER" | "MEMBER" | "COLLABORATOR")
192 );
193 let body = issue.body.unwrap_or_default();
194 let Some(task_id) = marker_id(&body).filter(|_| trusted) else {
195 if labeled {
196 eprintln!(
197 "warning: #{} has the {PLAN_LABEL} label and no plan marker",
198 issue.number
199 );
200 }
201 continue;
202 };
203 if issue.id == 0 {
204 anyhow::bail!("issue #{} did not include a database id", issue.number);
205 }
206 existing.push(ExistingIssue {
207 task_id,
208 number: issue.number,
209 database_id: issue.id,
210 title: issue.title,
211 body,
212 labels: issue.labels.into_iter().map(|label| label.name).collect(),
213 state: issue.state,
214 });
215 }
216 Ok(existing)
217}
218
219fn bindings_for(diff: &PlanDiff, existing: &[ExistingIssue]) -> Vec<Binding> {
220 let mut bindings: Vec<Binding> = diff
221 .tasks
222 .iter()
223 .map(|plan| Binding {
224 task_id: plan.task.id.clone(),
225 number: plan.number,
226 database_id: plan.database_id,
227 })
228 .collect();
229 for issue in existing {
230 if bindings
231 .iter()
232 .any(|binding| binding.task_id == issue.task_id)
233 {
234 continue;
235 }
236 bindings.push(Binding {
237 task_id: issue.task_id.clone(),
238 number: Some(issue.number),
239 database_id: Some(issue.database_id),
240 });
241 }
242 bindings
243}
244
245async fn load_blocked_by(
246 http: &GhHttp,
247 repo: &str,
248 diff: &PlanDiff,
249) -> anyhow::Result<HashMap<u64, Vec<DepRef>>> {
250 let mut current = HashMap::new();
251 for plan in &diff.tasks {
252 let Some(number) = plan.number else {
253 continue;
254 };
255 if current.contains_key(&number) {
256 continue;
257 }
258 let blocked = match http.list_blocked_by(repo, number).await? {
259 BlockedByFetch::Native(items) => items,
260 BlockedByFetch::Unavailable => {
261 anyhow::bail!("blocked-by API unavailable for #{number}");
262 }
263 BlockedByFetch::Failed(err) | BlockedByFetch::Unreachable(err) => {
264 anyhow::bail!("blocked-by API failed for #{number}: {err}");
265 }
266 };
267 current.insert(
268 number,
269 blocked
270 .into_iter()
271 .map(|item| DepRef {
272 number: u64::try_from(item.number).unwrap_or(0),
273 database_id: u64::try_from(item.github_id).unwrap_or(0),
274 })
275 .collect(),
276 );
277 }
278 Ok(current)
279}
280
281async fn apply(
282 http: &GhHttp,
283 repo: &str,
284 diff: &PlanDiff,
285 links: &[LinkEdit],
286 rel_path: &str,
287 branch: &str,
288 blocked_external: &HashMap<String, Vec<String>>,
289) -> anyhow::Result<()> {
290 http.ensure_label(repo, PLAN_LABEL, "6f42c1", "Imported from a roadmap file")
291 .await?;
292 http.ensure_label(repo, HUMAN_LABEL, "fbca04", "A person does this task")
293 .await?;
294 http.ensure_label(repo, NO_AGENT_LABEL, "ededed", "Skip agent dispatch")
295 .await?;
296 http.ensure_label(
297 repo,
298 HOLD_LABEL,
299 "ededed",
300 "Held by orch until its blocked-by links exist",
301 )
302 .await?;
303
304 let mut numbers: HashMap<String, (u64, u64)> = HashMap::new();
305 let mut held: Vec<u64> = Vec::new();
306 for plan in &diff.tasks {
307 if let (Some(number), Some(database_id)) = (plan.number, plan.database_id) {
308 numbers.insert(plan.task.id.clone(), (number, database_id));
309 }
310 }
311
312 for plan in &diff.tasks {
314 if plan.kind != ChangeKind::Create
315 && plan.existing_labels.iter().any(|l| l == HOLD_LABEL)
316 && let Some(number) = plan.number
317 {
318 held.push(number);
319 }
320 }
321
322 for plan in &diff.tasks {
323 match plan.kind {
324 ChangeKind::Unchanged => {}
325 ChangeKind::Create => {
326 let title = issue_title(&plan.task);
327 let extra = blocked_external
328 .get(&plan.task.id)
329 .map_or(&[][..], Vec::as_slice);
330 let body = issue_body_with(&plan.task, repo, branch, rel_path, extra);
331 let mut labels = labels_for(&[], plan.task.owner_human);
332 if !plan.task.owner_human {
334 labels.push(NO_AGENT_LABEL.to_string());
335 labels.push(HOLD_LABEL.to_string());
336 }
337 let issue = http.create_issue(repo, &title, &body, &labels).await?;
338 if !plan.task.owner_human {
339 held.push(issue.number);
340 }
341 if issue.id == 0 {
342 anyhow::bail!(
343 "created issue #{} did not include a database id",
344 issue.number
345 );
346 }
347 numbers.insert(plan.task.id.clone(), (issue.number, issue.id));
348 }
349 ChangeKind::Update => {
350 let number = plan.number.context("update is missing an issue number")?;
351 let title = issue_title(&plan.task);
352 let extra = blocked_external
353 .get(&plan.task.id)
354 .map_or(&[][..], Vec::as_slice);
355 let body = issue_body_with(&plan.task, repo, branch, rel_path, extra);
356 let labels = labels_for(&plan.existing_labels, plan.task.owner_human);
357 let issue = http
358 .update_issue(repo, number, &title, &body, &labels)
359 .await?;
360 let database_id = if issue.id == 0 {
361 plan.database_id.unwrap_or(0)
362 } else {
363 issue.id
364 };
365 if database_id == 0 {
366 anyhow::bail!("issue #{number} did not include a database id");
367 }
368 numbers.insert(plan.task.id.clone(), (issue.number, database_id));
369 }
370 }
371 }
372
373 for link in links {
374 match link {
375 LinkEdit::Add {
376 task_id,
377 blocking_task_id,
378 blocking_database_id,
379 ..
380 } => {
381 let (number, _) = numbers
382 .get(task_id)
383 .with_context(|| format!("{task_id} has no issue number"))?;
384 let blocking_id = blocking_database_id.or_else(|| {
385 numbers
386 .get(blocking_task_id)
387 .map(|(_, database_id)| *database_id)
388 });
389 let Some(blocking_id) = blocking_id else {
390 anyhow::bail!("{task_id} depends on {blocking_task_id}, which has no issue id");
391 };
392 let blocking_id =
393 i64::try_from(blocking_id).context("issue database id is out of range")?;
394 http.add_blocked_by(repo, *number, blocking_id).await?;
395 }
396 LinkEdit::Remove {
397 issue_number,
398 blocking_database_id,
399 ..
400 } => {
401 http.remove_blocked_by(repo, *issue_number, *blocking_database_id)
402 .await?;
403 }
404 }
405 }
406
407 for number in held {
410 let issue = number.to_string();
411 http.remove_label(repo, &issue, NO_AGENT_LABEL).await?;
412 http.remove_label(repo, &issue, HOLD_LABEL).await?;
413 }
414 Ok(())
415}
416
417fn repo_relative(path: &Path) -> Option<String> {
418 let output = Command::new("git")
419 .args(["rev-parse", "--show-toplevel"])
420 .output()
421 .ok()?;
422 if !output.status.success() {
423 return None;
424 }
425 let top = String::from_utf8(output.stdout).ok()?;
426 let top = Path::new(top.trim()).to_path_buf();
427 let abs = if path.is_absolute() {
428 path.to_path_buf()
429 } else {
430 env::current_dir().ok()?.join(path)
431 };
432 let abs = abs.canonicalize().unwrap_or(abs);
433 let top = top.canonicalize().unwrap_or(top);
434 let rel = abs.strip_prefix(&top).ok()?;
435 Some(
436 rel.components()
437 .map(|component| component.as_os_str().to_string_lossy())
438 .collect::<Vec<_>>()
439 .join("/"),
440 )
441}
442
443async fn draft_roadmap(plan: &str, existing: Option<&str>) -> anyhow::Result<(String, Roadmap)> {
444 let store = cli::init_store().await?;
445 draft_roadmap_with(&store, plan, existing).await
446}
447
448pub(crate) async fn draft_roadmap_with(
450 store: &TaskStore,
451 plan: &str,
452 existing: Option<&str>,
453) -> anyhow::Result<(String, Roadmap)> {
454 let agent = control::get_agent(store).await?;
455 let model = control::get_model(store).await?;
456 if model.is_empty() {
457 eprintln!("Drafting a roadmap with {agent}…");
458 } else {
459 eprintln!("Drafting a roadmap with {agent}:{model}…");
460 }
461 let prompt = build_prompt(plan, existing);
462 let result = control::invoke_agent_unsandboxed(&agent, &model, "", &prompt).await?;
463 match accept_roadmap(&result.text) {
464 Ok(ok) => Ok(ok),
465 Err(first) => {
466 tracing::warn!(error = %first, "plan draft did not parse, retrying once");
467 let retry = retry_prompt(plan, existing, &result.text, &first);
468 let second = control::invoke_agent_unsandboxed(&agent, &model, "", &retry).await?;
469 accept_roadmap(&second.text)
470 }
471 }
472}
473
474fn build_prompt(plan: &str, existing: Option<&str>) -> String {
475 let existing = match existing.map(str::trim).filter(|text| !text.is_empty()) {
476 Some(text) => text.to_string(),
477 None => "(empty)".to_string(),
478 };
479 include_str!("../../prompts/plan_roadmap.md")
480 .replace("{{EXISTING}}", &existing)
481 .replace("{{PLAN}}", plan)
482}
483
484fn retry_prompt(
485 plan: &str,
486 existing: Option<&str>,
487 previous: &str,
488 error: &anyhow::Error,
489) -> String {
490 let mut prompt = build_prompt(plan, existing);
491 prompt.push_str("\n\nThe previous attempt was not a valid roadmap:\n\n");
492 prompt.push_str(&error.to_string());
493 prompt.push_str("\n\nPrevious output:\n\n");
494 prompt.push_str(previous.trim());
495 prompt.push_str("\n\nWrite a corrected roadmap. Output only the markdown.\n");
496 prompt
497}
498
499fn accept_roadmap(raw: &str) -> anyhow::Result<(String, Roadmap)> {
500 let mut last = anyhow::anyhow!("agent returned no roadmap");
501 for candidate in roadmap_candidates(raw) {
502 let slices = milestone_slices(&candidate);
503 let preferred: Vec<&str> = slices
504 .iter()
505 .copied()
506 .filter(|slice| starts_with_milestone(slice))
507 .collect();
508 let fallback = if preferred.is_empty() {
509 if slices.is_empty() {
510 vec![candidate.as_str()]
511 } else {
512 slices
513 }
514 } else {
515 preferred
516 };
517 for slice in fallback {
518 match try_parse(slice) {
519 Ok(ok) => return Ok(ok),
520 Err(err) => last = err,
521 }
522 }
523 }
524 Err(last)
525}
526
527fn starts_with_milestone(text: &str) -> bool {
528 text.lines()
529 .find(|line| !line.trim().is_empty())
530 .is_some_and(plan::is_milestone_heading)
531}
532
533fn milestone_slices(text: &str) -> Vec<&str> {
534 let mut slices = Vec::new();
535 let mut offset = 0;
536 for line in text.split_inclusive('\n') {
537 if line.trim_start().starts_with("## ") {
538 slices.push(text[offset..].trim());
539 }
540 offset += line.len();
541 }
542 slices
543}
544
545fn try_parse(markdown: &str) -> anyhow::Result<(String, Roadmap)> {
546 let markdown = markdown.trim();
547 let roadmap = plan::parse_roadmap(markdown)?;
548 if roadmap.tasks.is_empty() {
549 anyhow::bail!("roadmap has no tasks");
550 }
551 Ok((markdown.to_string(), roadmap))
552}
553
554fn roadmap_candidates(raw: &str) -> Vec<String> {
555 let mut out = Vec::new();
556 for block in fenced_blocks(raw) {
557 push_unique(&mut out, &block);
558 }
559 let stripped = strip_outer_fence(raw);
560 push_unique(&mut out, &stripped);
561 out
562}
563
564fn push_unique(out: &mut Vec<String>, text: &str) {
565 let trimmed = text.trim();
566 if trimmed.is_empty() || out.iter().any(|have| have == trimmed) {
567 return;
568 }
569 out.push(trimmed.to_string());
570}
571
572fn strip_outer_fence(raw: &str) -> String {
573 let trimmed = raw.trim();
574 let without_open = if let Some(rest) = trimmed.strip_prefix("```") {
575 match rest.find('\n') {
576 Some(i) => &rest[i + 1..],
577 None => rest,
578 }
579 } else {
580 trimmed
581 };
582 without_open
583 .trim_end()
584 .strip_suffix("```")
585 .unwrap_or(without_open)
586 .trim()
587 .to_string()
588}
589
590fn fenced_blocks(raw: &str) -> Vec<String> {
591 let mut blocks = Vec::new();
592 let mut index = 0;
593 while let Some(rel) = raw[index..].find("```") {
594 let start = index + rel + 3;
595 let after_open = &raw[start..];
596 let content_start = match after_open.find('\n') {
597 Some(i) => start + i + 1,
598 None => break,
599 };
600 if let Some(rel_end) = raw[content_start..].find("```") {
601 let end = content_start + rel_end;
602 blocks.push(raw[content_start..end].trim().to_string());
603 index = end + 3;
604 } else {
605 blocks.push(raw[content_start..].trim().to_string());
606 break;
607 }
608 }
609 blocks
610}
611
612pub(crate) fn roadmap_path(plan: &Path) -> PathBuf {
613 let name = plan.file_name().map_or_else(
614 || "plan.md".to_string(),
615 |name| name.to_string_lossy().into_owned(),
616 );
617 let file_name = match name.rsplit_once('.') {
618 Some((stem, ext)) if !stem.is_empty() => format!("{stem}.roadmap.{ext}"),
619 _ => format!("{name}.roadmap.md"),
620 };
621 match plan.parent() {
622 Some(parent) if !parent.as_os_str().is_empty() => parent.join(file_name),
623 _ => PathBuf::from(file_name),
624 }
625}
626
627fn with_trailing_newline(text: &str) -> String {
628 if text.ends_with('\n') {
629 text.to_string()
630 } else {
631 format!("{text}\n")
632 }
633}
634
635fn prompt_import() -> anyhow::Result<bool> {
636 print!("\nImport these issues? [y/n] ");
637 io::stdout().flush().ok();
638 let mut input = String::new();
639 io::stdin().read_line(&mut input)?;
640 Ok(is_yes(&input))
641}
642
643fn is_yes(input: &str) -> bool {
644 matches!(input.trim().to_ascii_lowercase().as_str(), "y" | "yes")
645}
646
647#[cfg(test)]
648mod tests {
649 use super::*;
650 use crate::github::types::{GitHubLabel, GitHubUser};
651
652 fn issue(number: u64, body: &str, labels: &[&str]) -> GitHubIssue {
653 issue_by(number, body, labels, "OWNER")
654 }
655
656 fn issue_by(number: u64, body: &str, labels: &[&str], association: &str) -> GitHubIssue {
657 GitHubIssue {
658 number,
659 id: number * 10,
660 title: format!("issue {number}"),
661 body: Some(body.to_string()),
662 state: "open".to_string(),
663 labels: labels
664 .iter()
665 .map(|name| GitHubLabel {
666 name: name.to_string(),
667 color: None,
668 })
669 .collect(),
670 user: GitHubUser {
671 login: "u".to_string(),
672 },
673 created_at: String::new(),
674 updated_at: String::new(),
675 html_url: String::new(),
676 node_id: None,
677 pull_request: None,
678 author_association: Some(association.to_string()),
679 state_reason: None,
680 }
681 }
682
683 #[test]
684 fn marker_matches_with_or_without_the_label_and_no_marker_is_skipped() {
685 let found = existing_from_issues(vec![
686 issue(1, "<!-- orch-plan: M1-01 -->", &[]),
687 issue(2, "<!-- orch-plan: M1-02 -->", &[PLAN_LABEL]),
688 issue(3, "no marker", &[PLAN_LABEL]),
689 issue(4, "no marker", &[]),
690 issue_by(5, "<!-- orch-plan: M1-03 -->", &[], "NONE"),
691 ])
692 .unwrap();
693 let ids: Vec<&str> = found.iter().map(|item| item.task_id.as_str()).collect();
694 assert_eq!(ids, ["M1-01", "M1-02"]);
695 }
696
697 const VALID_ROADMAP: &str = "\
698## M1. Workspace
699
700### M1-01 Create the crate
701
702- Goal: a crate that builds.
703- Scope: the library crate.
704- Acceptance:
705 - `cargo test` passes.
706- Depends on: none.
707
708### M1-02 Add a parser
709
710- Goal: parse the config file.
711- Acceptance:
712 - A sample file round-trips.
713- Depends on: M1-01.
714";
715
716 #[test]
717 fn accept_roadmap_reads_a_fenced_response_with_preamble() {
718 let raw = format!(
719 "Here is the roadmap:\n\n```markdown\n{VALID_ROADMAP}```\n\nLet me know if you want edits.\n"
720 );
721 let (markdown, roadmap) = accept_roadmap(&raw).unwrap();
722 assert_eq!(markdown, VALID_ROADMAP.trim());
723 assert_eq!(
724 roadmap
725 .tasks
726 .iter()
727 .map(|task| task.id.as_str())
728 .collect::<Vec<_>>(),
729 ["M1-01", "M1-02"]
730 );
731 assert_eq!(roadmap.tasks[1].depends_on, ["M1-01".to_string()]);
732 }
733
734 #[test]
735 fn accept_roadmap_reads_plain_markdown() {
736 let (markdown, roadmap) = accept_roadmap(VALID_ROADMAP).unwrap();
737 assert_eq!(markdown, VALID_ROADMAP.trim());
738 assert_eq!(roadmap.milestones[0].id, "M1");
739 }
740
741 #[test]
742 fn accept_roadmap_starts_at_the_first_milestone() {
743 let raw = format!("Notes from the meeting.\n\n{VALID_ROADMAP}");
744 let (markdown, roadmap) = accept_roadmap(&raw).unwrap();
745 assert!(markdown.starts_with("## M1. Workspace"), "{markdown}");
746 assert_eq!(roadmap.tasks.len(), 2);
747 }
748
749 #[test]
750 fn accept_roadmap_skips_a_leading_notes_heading() {
751 let raw = format!("## Notes\n\nFrom the meeting.\n\n{VALID_ROADMAP}");
752 let (markdown, roadmap) = accept_roadmap(&raw).unwrap();
753 assert!(markdown.starts_with("## M1. Workspace"), "{markdown}");
754 assert_eq!(roadmap.tasks.len(), 2);
755 }
756
757 #[test]
758 fn accept_roadmap_reads_an_unclosed_fence() {
759 let raw = format!("```markdown\n{VALID_ROADMAP}");
760 let (markdown, roadmap) = accept_roadmap(&raw).unwrap();
761 assert!(markdown.starts_with("## M1. Workspace"), "{markdown}");
762 assert_eq!(roadmap.tasks.len(), 2);
763 }
764
765 #[test]
766 fn accept_roadmap_rejects_a_plan_with_no_ids() {
767 let err = accept_roadmap("# Ship it\n\nBuild the app and write tests.\n").unwrap_err();
768 assert!(!err.to_string().is_empty(), "{err}");
769 }
770
771 #[test]
772 fn one_page_plan_without_ids_has_a_roadmap_import_accepts() {
773 let plan = "\
774# Notes app
775
776Build a local notes app.
777
778First, set up a Rust crate that builds and tests on a clean checkout.
779
780Then add a notes file format and a command that lists notes.
781
782A person has to create the GitHub repo.
783";
784 assert!(plan::parse_roadmap(plan).unwrap().tasks.is_empty());
785 assert!(accept_roadmap(plan).is_err());
786 let dir = tempfile::tempdir().unwrap();
787 let plan_file = dir.path().join("notes.md");
788 fs::write(&plan_file, plan).unwrap();
789 let dest = roadmap_path(&plan_file);
790 let (markdown, imported) = accept_roadmap(VALID_ROADMAP).unwrap();
791 fs::write(&dest, with_trailing_newline(&markdown)).unwrap();
792 let saved = fs::read_to_string(&dest).unwrap();
793 let (roadmap, warnings) = plan::parse_roadmap_for(&saved, None).unwrap();
794 assert!(warnings.is_empty(), "{warnings:?}");
795 assert!(!imported.tasks.is_empty());
796 assert_eq!(roadmap.tasks.len(), imported.tasks.len());
797 assert!(roadmap.tasks.iter().all(|task| !task.id.is_empty()));
798 assert_eq!(dest.file_name().unwrap(), "notes.roadmap.md");
799 }
800
801 #[test]
802 fn retry_prompt_includes_the_error_and_previous_output() {
803 let prompt = retry_prompt(
804 "# Build it\n",
805 None,
806 "not a roadmap",
807 &anyhow::anyhow!("roadmap has no tasks"),
808 );
809 assert!(prompt.contains("# Build it"));
810 assert!(prompt.contains("not a roadmap"));
811 assert!(prompt.contains("roadmap has no tasks"));
812 assert!(prompt.contains("Write a corrected roadmap"));
813 }
814
815 #[test]
816 fn roadmap_path_sits_next_to_the_plan() {
817 assert_eq!(
818 roadmap_path(Path::new("docs/PLAN.md")),
819 PathBuf::from("docs/PLAN.roadmap.md")
820 );
821 assert_eq!(
822 roadmap_path(Path::new("plan.md")),
823 PathBuf::from("plan.roadmap.md")
824 );
825 assert_eq!(
826 roadmap_path(Path::new("/tmp/idea")),
827 PathBuf::from("/tmp/idea.roadmap.md")
828 );
829 }
830
831 #[test]
832 fn prompt_keeps_existing_ids_and_the_plan_body() {
833 let prompt = build_prompt("# Build it\n", Some(VALID_ROADMAP));
834 assert!(prompt.contains("# Build it"));
835 assert!(prompt.contains("### M1-01 Create the crate"));
836 assert!(prompt.contains("keep every task id"));
837 }
838
839 #[test]
840 fn yes_accepts_y_and_yes() {
841 assert!(is_yes("y\n"));
842 assert!(is_yes(" Yes "));
843 assert!(!is_yes("n"));
844 assert!(!is_yes(""));
845 }
846
847 #[test]
848 fn trailing_newline_is_added_once() {
849 assert_eq!(with_trailing_newline("a"), "a\n");
850 assert_eq!(with_trailing_newline("a\n"), "a\n");
851 }
852}