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