1use std::fmt::Write as _;
23use std::path::{Path, PathBuf};
24use std::time::Duration;
25
26use anyhow::{Context as _, Result, bail};
27use serde::{Deserialize, Serialize};
28
29use crate::agent::{self, Invocation, SeatState};
30use crate::ask;
31use crate::config::AgentSpec;
32use crate::git;
33use crate::land;
34use crate::proc::Quiet as _;
35use crate::run::{self, RunState, RunStatus};
36use crate::verdict;
37
38const DECISION_TIMEOUT: Duration = Duration::from_secs(600);
45
46pub fn should_release_bump(status: RunStatus) -> bool {
62 status == RunStatus::Merged
63}
64
65#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
67#[serde(rename_all = "lowercase")]
68pub enum BumpLevel {
69 Major,
71 Minor,
73 Patch,
75}
76
77impl BumpLevel {
78 pub fn as_str(self) -> &'static str {
80 match self {
81 Self::Major => "major",
82 Self::Minor => "minor",
83 Self::Patch => "patch",
84 }
85 }
86
87 fn severity(self) -> u8 {
92 match self {
93 Self::Patch => 0,
94 Self::Minor => 1,
95 Self::Major => 2,
96 }
97 }
98}
99
100#[derive(Debug, Clone, Deserialize)]
107pub struct BumpDecision {
108 pub level: BumpLevel,
110 pub reason: String,
113}
114
115pub fn parse_decision(text: &str) -> Result<BumpDecision> {
119 let decision: BumpDecision = verdict::extract_json(text)?;
120 if decision.reason.trim().is_empty() {
121 bail!("the bump decision carried no reason");
122 }
123 Ok(decision)
124}
125
126#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
129pub struct Version {
130 pub major: u64,
132 pub minor: u64,
134 pub patch: u64,
136}
137
138impl Version {
139 pub fn parse(s: &str) -> Result<Self> {
144 let s = s.trim();
145 let mut parts = s.splitn(3, '.');
146 let major = parts
147 .next()
148 .with_context(|| format!("`{s}` has no major component"))?;
149 let minor = parts
150 .next()
151 .with_context(|| format!("`{s}` has no minor component"))?;
152 let patch = parts
153 .next()
154 .with_context(|| format!("`{s}` has no patch component"))?;
155 let patch_digits: String = patch.chars().take_while(char::is_ascii_digit).collect();
156 Ok(Self {
157 major: major
158 .trim()
159 .parse()
160 .with_context(|| format!("`{major}` is not a number"))?,
161 minor: minor
162 .trim()
163 .parse()
164 .with_context(|| format!("`{minor}` is not a number"))?,
165 patch: patch_digits
166 .parse()
167 .with_context(|| format!("`{patch}` has no numeric patch component"))?,
168 })
169 }
170
171 #[must_use]
174 pub fn bump(self, level: BumpLevel) -> Self {
175 match level {
176 BumpLevel::Major => Self {
177 major: self.major + 1,
178 minor: 0,
179 patch: 0,
180 },
181 BumpLevel::Minor => Self {
182 major: self.major,
183 minor: self.minor + 1,
184 patch: 0,
185 },
186 BumpLevel::Patch => Self {
187 major: self.major,
188 minor: self.minor,
189 patch: self.patch + 1,
190 },
191 }
192 }
193}
194
195impl std::fmt::Display for Version {
196 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
197 write!(f, "{}.{}.{}", self.major, self.minor, self.patch)
198 }
199}
200
201pub fn is_release_only(files: &[String]) -> bool {
210 !files.is_empty() && files.iter().all(|f| f == "Cargo.toml" || f == "Cargo.lock")
211}
212
213fn rewrite_table_version(toml: &str, table: &str, new_version: &str) -> Result<String> {
224 let mut out = String::with_capacity(toml.len() + 8);
225 let mut in_table = false;
226 let mut done = false;
227 for line in toml.split_inclusive('\n') {
228 let trimmed = line.trim();
229 if trimmed.starts_with('[') {
230 in_table = trimmed == table;
231 }
232 if !done && in_table && trimmed.split('=').next().map(str::trim) == Some("version") {
233 let newline = if line.ends_with("\r\n") { "\r\n" } else { "\n" };
234 let _ = write!(out, "version = \"{new_version}\"{newline}");
235 done = true;
236 continue;
237 }
238 out.push_str(line);
239 }
240 if !done {
241 bail!("no `version` field found under `{table}`");
242 }
243 Ok(out)
244}
245
246pub fn rewrite_cargo_version(toml: &str, new_version: &str) -> Result<String> {
258 rewrite_table_version(toml, "[package]", new_version)
259 .or_else(|_| rewrite_table_version(toml, "[workspace.package]", new_version))
260 .context("no `version` field found under `[package]` or `[workspace.package]`")
261}
262
263fn version_in_table(toml: &str, table: &str) -> Option<String> {
265 let mut in_table = false;
266 for line in toml.lines() {
267 let trimmed = line.trim();
268 if trimmed.starts_with('[') {
269 in_table = trimmed == table;
270 continue;
271 }
272 if !in_table {
273 continue;
274 }
275 let mut parts = trimmed.splitn(2, '=');
276 let key = parts.next().map(str::trim);
277 let Some(value) = parts.next() else {
278 continue;
279 };
280 if key == Some("version") {
281 return Some(value.trim().trim_matches('"').to_owned());
282 }
283 }
284 None
285}
286
287fn current_version(toml: &str) -> Result<String> {
292 version_in_table(toml, "[package]")
293 .or_else(|| version_in_table(toml, "[workspace.package]"))
294 .context("no `version` field found under `[package]` or `[workspace.package]`")
295}
296
297pub fn decision_prompt(
307 subject: &str,
308 instruction: &str,
309 diffstat: &str,
310 files: &[String],
311 current_version: &str,
312) -> String {
313 let mut s = format!(
314 "A pull request just merged into the base branch. Decide which digit \
315 of this project's `major.minor.patch` version this change earns, so \
316 a release bump can be opened for exactly it.\n\n\
317 Current version: {current_version}\n\n\
318 # Merge subject\n\n{subject}\n\n\
319 # The task that produced it\n\n{instruction}\n\n\
320 # Files changed ({} total)\n\n",
321 files.len()
322 );
323 const MAX_FILES: usize = 50;
324 for f in files.iter().take(MAX_FILES) {
325 let _ = writeln!(s, "- {f}");
326 }
327 if files.len() > MAX_FILES {
328 let _ = writeln!(s, "- ... and {} more", files.len() - MAX_FILES);
329 }
330 let _ = write!(s, "\n# Diffstat\n\n```\n{}\n```\n", diffstat.trim());
331
332 s.push_str(
333 "\n# How to decide\n\n\
334 This project is below version `1.0.0`. At that stage **`minor` is \
335 the digit that carries a breaking change** - do not spend `major` \
336 below `1.0.0`.\n\n\
337 A change is breaking, and earns `minor`, when it changes any of: \
338 the public API reachable from `src/lib.rs`, a CLI subcommand or \
339 flag, an HTTP API route or response shape, a configuration key, or \
340 the on-disk shape of persisted state.\n\n\
341 A user-visible new capability that breaks none of the above also \
342 earns `minor`.\n\n\
343 A fix, an internal refactor, or a dependency update earns `patch`.\n\n\
344 **When it is not obvious which digit applies, choose the larger \
345 one.** An oversized bump costs nothing; a breaking change shipped as \
346 `patch` breaks every downstream update that pins a range.\n\n\
347 # Output\n\n\
348 Reply with exactly one fenced JSON object and nothing that matters \
349 outside it:\n\n\
350 ```json\n\
351 {\"level\": \"major\" | \"minor\" | \"patch\", \"reason\": \"one line\"}\n\
352 ```\n",
353 );
354 let _ = write!(
356 s,
357 "\n{}\n\nThe `reason` goes into a GitHub pull request body, so write it \
358 in English.\n",
359 crate::prompt::GITHUB_ENGLISH_HEADING
360 );
361 s
362}
363
364#[derive(Debug, Clone, Serialize, Deserialize)]
380pub struct PendingBump {
381 pub target_version: String,
383 pub level: BumpLevel,
386 pub branch: String,
389 pub pr_url: String,
392}
393
394pub fn marker_path(home: &Path, repo: &Path) -> PathBuf {
398 let key = repo.to_string_lossy();
399 home.join("bump")
400 .join(format!("{:016x}.json", crate::rng::fnv1a(&key)))
401}
402
403pub fn read_marker(path: &Path) -> Option<PendingBump> {
407 let body = std::fs::read_to_string(path).ok()?;
408 serde_json::from_str(&body).ok()
409}
410
411pub fn write_marker(path: &Path, marker: &PendingBump) -> Result<()> {
415 if let Some(parent) = path.parent() {
416 std::fs::create_dir_all(parent).with_context(|| format!("create {}", parent.display()))?;
417 }
418 let body = serde_json::to_string_pretty(marker).context("serialize pending bump")?;
419 let tmp = path.with_extension("json.tmp");
420 std::fs::write(&tmp, &body).with_context(|| format!("write {}", tmp.display()))?;
421 std::fs::rename(&tmp, path).with_context(|| format!("replace {}", path.display()))?;
422 Ok(())
423}
424
425pub fn clear_marker(path: &Path) {
428 let _ = std::fs::remove_file(path);
429}
430
431#[derive(Debug, Clone, PartialEq, Eq)]
435pub enum Coalesce {
436 Proceed,
439 Skip {
441 target_version: String,
443 },
444}
445
446pub fn coalesce(pending: Option<&PendingBump>, current_version: &str) -> Result<Coalesce> {
448 let Some(pending) = pending else {
449 return Ok(Coalesce::Proceed);
450 };
451 let current = Version::parse(current_version)?;
452 let target = Version::parse(&pending.target_version)?;
453 if current >= target {
454 return Ok(Coalesce::Proceed);
455 }
456 Ok(Coalesce::Skip {
457 target_version: pending.target_version.clone(),
458 })
459}
460
461#[derive(Debug, Clone, Copy, PartialEq, Eq)]
463pub enum PendingAction {
464 AlreadyCovered,
467 Escalate,
470}
471
472pub fn pending_action(pending_level: BumpLevel, decision_level: BumpLevel) -> PendingAction {
481 if decision_level.severity() > pending_level.severity() {
482 PendingAction::Escalate
483 } else {
484 PendingAction::AlreadyCovered
485 }
486}
487
488fn parse_pr_state(json: &str) -> Result<bool> {
490 #[derive(Deserialize)]
491 struct State {
492 state: String,
493 }
494 let parsed: State =
495 serde_json::from_str(json).context("parse `gh pr view --json state` output")?;
496 Ok(parsed.state.eq_ignore_ascii_case("OPEN"))
497}
498
499async fn pr_is_open(repo: &Path, pr_url: &str) -> Result<bool> {
512 let out = tokio::process::Command::new("gh")
513 .args(["pr", "view", pr_url, "--json", "state"])
514 .current_dir(repo)
515 .quiet()
516 .stdin(std::process::Stdio::null())
517 .output()
518 .await
519 .context("spawn gh pr view")?;
520 if !out.status.success() {
521 bail!(
522 "gh pr view {pr_url}: {}",
523 String::from_utf8_lossy(&out.stderr).trim()
524 );
525 }
526 parse_pr_state(&String::from_utf8_lossy(&out.stdout))
527}
528
529const LOCK_STALE_AFTER: Duration = Duration::from_secs(30 * 60);
537
538struct MarkerLock {
550 path: PathBuf,
551}
552
553impl MarkerLock {
554 fn acquire(marker: &Path) -> Result<Option<Self>> {
558 let path = marker.with_extension("lock");
559 if let Some(parent) = path.parent() {
560 std::fs::create_dir_all(parent)
561 .with_context(|| format!("create {}", parent.display()))?;
562 }
563 if Self::try_create(&path)? {
564 return Ok(Some(Self { path }));
565 }
566 if Self::is_stale(&path) {
567 let _ = std::fs::remove_file(&path);
568 if Self::try_create(&path)? {
569 return Ok(Some(Self { path }));
570 }
571 }
572 Ok(None)
573 }
574
575 fn try_create(path: &Path) -> Result<bool> {
576 match std::fs::OpenOptions::new()
577 .write(true)
578 .create_new(true)
579 .open(path)
580 {
581 Ok(_) => Ok(true),
582 Err(e) if e.kind() == std::io::ErrorKind::AlreadyExists => Ok(false),
583 Err(e) => Err(e).with_context(|| format!("create {}", path.display())),
584 }
585 }
586
587 fn is_stale(path: &Path) -> bool {
588 std::fs::metadata(path)
589 .and_then(|m| m.modified())
590 .ok()
591 .and_then(|m| m.elapsed().ok())
592 .is_some_and(|age| age >= LOCK_STALE_AFTER)
593 }
594}
595
596impl Drop for MarkerLock {
597 fn drop(&mut self) {
598 let _ = std::fs::remove_file(&self.path);
599 }
600}
601
602const LOCK_POLL: Duration = Duration::from_secs(5);
604
605const LOCK_WAIT_CEILING: Duration = Duration::from_secs(25 * 60);
618
619async fn wait_for_marker_lock(marker: &Path) -> Result<Option<MarkerLock>> {
622 wait_for_marker_lock_with(marker, LOCK_POLL, LOCK_WAIT_CEILING).await
623}
624
625async fn wait_for_marker_lock_with(
629 marker: &Path,
630 poll: Duration,
631 ceiling: Duration,
632) -> Result<Option<MarkerLock>> {
633 let mut waited = Duration::ZERO;
634 loop {
635 if let Some(lock) = MarkerLock::acquire(marker)? {
636 return Ok(Some(lock));
637 }
638 if waited >= ceiling {
639 return Ok(None);
640 }
641 tokio::time::sleep(poll).await;
642 waited += poll;
643 }
644}
645
646fn level_between(from: Version, to: Version) -> Option<BumpLevel> {
654 if to.major != from.major {
655 Some(BumpLevel::Major)
656 } else if to.minor != from.minor {
657 Some(BumpLevel::Minor)
658 } else if to.patch != from.patch {
659 Some(BumpLevel::Patch)
660 } else {
661 None
662 }
663}
664
665fn parse_open_release_pr(json: &str) -> Result<Option<(String, String)>> {
668 #[derive(Deserialize)]
669 struct Pr {
670 url: String,
671 #[serde(rename = "headRefName")]
672 head_ref_name: String,
673 }
674 let list: Vec<Pr> =
675 serde_json::from_str(json).context("parse `gh pr list --json url,headRefName` output")?;
676 Ok(list
677 .into_iter()
678 .find(|p| p.head_ref_name.starts_with("chore/release-v"))
679 .map(|p| (p.head_ref_name, p.url)))
680}
681
682async fn find_open_release_pr(repo: &Path) -> Result<Option<(String, String)>> {
697 let out = tokio::process::Command::new("gh")
698 .args(["pr", "list", "--state", "open", "--json", "url,headRefName"])
699 .current_dir(repo)
700 .quiet()
701 .stdin(std::process::Stdio::null())
702 .output()
703 .await
704 .context("spawn gh pr list")?;
705 if !out.status.success() {
706 bail!(
707 "gh pr list: {}",
708 String::from_utf8_lossy(&out.stderr).trim()
709 );
710 }
711 parse_open_release_pr(&String::from_utf8_lossy(&out.stdout))
712}
713
714pub async fn after_merge(state: &mut RunState, pr_url: &str) -> Result<()> {
723 after_merge_at(state, pr_url, None).await
724}
725
726async fn base_has_cargo_toml(repo: &Path, remote: &str, base: &str) -> Result<bool> {
732 let out = git::git(
733 repo,
734 &[
735 "ls-tree",
736 "--name-only",
737 &format!("{remote}/{base}"),
738 "--",
739 "Cargo.toml",
740 ],
741 )
742 .await
743 .context("look for Cargo.toml on the base branch")?;
744 Ok(!out.trim().is_empty())
745}
746
747async fn after_merge_at(state: &mut RunState, pr_url: &str, home: Option<&Path>) -> Result<()> {
750 if !state.config.merge.release_bump {
751 return Ok(());
752 }
753 let Some(winner) = state.winner().cloned() else {
754 return Ok(());
755 };
756 let repo = state.repo.clone();
757 let base = state.base_branch.clone();
758 let remote = state.config.merge.remote.clone();
759
760 let files = git::changed_files(&winner.worktree, &base, &winner.branch)
761 .await
762 .unwrap_or_default();
763 if is_release_only(&files) {
764 state.event(
765 "bump",
766 "the merged change touches only the release manifest; not treating it as a trigger",
767 );
768 return Ok(());
769 }
770
771 git::fetch(&repo, &remote, &base).await.ok();
774 if !base_has_cargo_toml(&repo, &remote, &base).await? {
775 state.event(
776 "bump",
777 "release bump: no Cargo.toml on the base branch; release bumps are Rust-only, skipping",
778 );
779 return Ok(());
780 }
781
782 let marker = marker_path(&home.map_or_else(run::home, Path::to_path_buf), &repo);
783 let Some(_lock) = wait_for_marker_lock(&marker).await? else {
790 state.event(
791 "bump",
792 "another release bump decision held the lock past the wait ceiling; skipping this round",
793 );
794 return Ok(());
795 };
796
797 git::fetch(&repo, &remote, &base).await.ok();
798 let cargo_toml = git::git(&repo, &["show", &format!("{remote}/{base}:Cargo.toml")])
799 .await
800 .context("read Cargo.toml from the base branch")?;
801 let base_version = current_version(&cargo_toml)?;
802
803 let mut pending = read_marker(&marker);
804 if let Some(p) = &pending {
805 match coalesce(Some(p), &base_version)? {
806 Coalesce::Proceed => {
807 clear_marker(&marker);
810 pending = None;
811 }
812 Coalesce::Skip { target_version } => {
813 if !pr_is_open(&repo, &p.pr_url).await.unwrap_or(true) {
814 state.event(
815 "bump",
816 format!(
817 "the pending release bump to v{target_version} ({}) is no longer \
818 open; treating it as abandoned",
819 p.pr_url
820 ),
821 );
822 clear_marker(&marker);
823 pending = None;
824 }
825 }
830 }
831 }
832
833 if pending.is_none() {
834 if let Ok(Some((branch, url))) = find_open_release_pr(&repo).await
839 && let Some(target) = branch
840 .strip_prefix("chore/release-v")
841 .and_then(|v| Version::parse(v).ok())
842 {
843 let base_parsed = Version::parse(&base_version)?;
844 if target > base_parsed
845 && let Some(level) = level_between(base_parsed, target)
846 {
847 let adopted = PendingBump {
848 target_version: target.to_string(),
849 level,
850 branch,
851 pr_url: url,
852 };
853 let _ = write_marker(&marker, &adopted);
856 pending = Some(adopted);
857 }
858 }
859 }
860
861 let title = pr_title(&repo, pr_url).await.unwrap_or_default();
862 let subject = land::merge_subject(&title, &state.instruction);
863 let stat = git::diff_stat(&winner.worktree, &base, &winner.branch)
864 .await
865 .unwrap_or_default();
866 let prompt = decision_prompt(&subject, &state.instruction, &stat, &files, &base_version);
867
868 let spec: AgentSpec = agent::pick(
874 &state.config.agents,
875 state.config.roles.chatter.as_deref(),
876 &agent::installed,
877 )
878 .context("choose an agent for the release-bump decision")?;
879 let mut seat = SeatState::new("bump", &spec.id, state.seed);
880 let artifacts = agent::artifacts_dir(&state.dir());
881 let out = agent::invoke(
882 &spec,
883 &mut seat,
884 &Invocation {
885 cwd: &repo,
886 prompt: &prompt,
887 timeout: DECISION_TIMEOUT,
888 allow_write: false,
891 sessions: false,
892 artifacts: &artifacts,
893 stem: "bump-decision",
894 run: &state.id,
895 node: "bump",
896 cache_dir: state.config.cache_dir().as_deref(),
897 attachments: &[],
898 },
899 )
900 .await
901 .context("ask an agent how big the merged change was")?;
902 if !out.usable() {
903 bail!(
904 "the release-bump decision produced nothing usable (exit {:?}, timed out: {})",
905 out.exit_code,
906 out.timed_out
907 );
908 }
909 let decision = parse_decision(&out.text).context("parse the release-bump decision")?;
910
911 if let Some(p) = pending {
912 return match pending_action(p.level, decision.level) {
913 PendingAction::AlreadyCovered => {
914 state.event(
915 "bump",
916 format!(
917 "a release bump to v{} ({}) already covers at least a {} change; not \
918 opening another",
919 p.target_version,
920 p.pr_url,
921 decision.level.as_str()
922 ),
923 );
924 Ok(())
925 }
926 PendingAction::Escalate => {
927 escalate_pending(state, &repo, &remote, &p, &decision, &base_version, &marker).await
928 }
929 };
930 }
931
932 let next = Version::parse(&base_version)?
933 .bump(decision.level)
934 .to_string();
935 let branch = format!("chore/release-v{next}");
936 let worktree = state.dir().join("bump");
937 git::worktree_remove(&repo, &worktree).await.ok();
938 git::worktree_add_branch(&repo, &worktree, &branch, &format!("{remote}/{base}"))
939 .await
940 .context("create the release-bump worktree")?;
941 let opened = open_bump_pr(state, &worktree, &branch, &next, &decision, pr_url).await;
942 git::worktree_remove(&repo, &worktree).await.ok();
946 let (pr_url_opened, automerge_warning) = opened?;
947
948 let marker_write = write_marker(
957 &marker,
958 &PendingBump {
959 target_version: next.clone(),
960 level: decision.level,
961 branch,
962 pr_url: pr_url_opened.clone(),
963 },
964 );
965 state.event(
966 "bump",
967 format!(
968 "opened a {} release bump to v{next} ({}): {pr_url_opened}",
969 decision.level.as_str(),
970 decision.reason
971 ),
972 );
973 if let Err(e) = marker_write {
974 state.event(
975 "bump",
976 format!(
977 "could not record the pending release bump marker for v{next}: {e:#}; a later \
978 merge may open a duplicate pull request if it cannot find {pr_url_opened} on \
979 the forge either"
980 ),
981 );
982 }
983 state.release_bump = Some(run::ReleaseBump {
984 pr_url: Some(pr_url_opened.clone()),
985 version: Some(next.clone()),
986 automerge_enabled: automerge_warning.is_none(),
987 ..run::ReleaseBump::default()
988 });
989 if let Some(warning) = automerge_warning {
990 state.event(
991 "bump",
992 format!("could not enable automerge on {pr_url_opened}: {warning}; merge it by hand"),
993 );
994 report_problem(state, Some(&pr_url_opened), Some(&next), &warning).await;
995 }
996 Ok(())
997}
998
999pub const NOTICE_NODE: &str = "release-bump";
1003const NOTICE_DONE: &str = "merged by hand";
1005const NOTICE_DISMISS: &str = "dismiss";
1007
1008fn automerge_hint(reason: &str) -> &'static str {
1015 let r = reason.to_lowercase();
1016 if r.contains("enablepullrequestautomerge") || r.contains("protected branch rules") {
1017 "merge the release pull request by hand, and enable branch protection with required \
1018 status checks on the base branch so automerge can work next time"
1019 } else {
1020 "merge the release pull request by hand"
1021 }
1022}
1023
1024fn automerge_failure_comment(reason: &str) -> String {
1026 format!(
1027 "magi could not enable automerge on this pull request: {reason}\n\n\
1028 Action required: {}. Until then the release does not happen.",
1029 automerge_hint(reason)
1030 )
1031}
1032
1033fn surface_problem(
1040 state: &mut RunState,
1041 store: &ask::Questions,
1042 pr_url: Option<&str>,
1043 version: Option<&str>,
1044 reason: &str,
1045) -> Result<(ask::Question, Option<String>)> {
1046 let action = if pr_url.is_some() {
1047 automerge_hint(reason).to_owned()
1048 } else {
1049 "the release bump did not run; open the release pull request by hand".to_owned()
1050 };
1051 let record = state.release_bump.get_or_insert_with(Default::default);
1052 record.pr_url = pr_url.map(str::to_owned).or(record.pr_url.take());
1053 record.version = version.map(str::to_owned).or(record.version.take());
1054 record.automerge_enabled = false;
1055 record.problem = Some(reason.to_owned());
1056 record.action_required = Some(action.clone());
1057
1058 let summary = match pr_url {
1059 Some(url) => format!("Release PR needs a human: {url}"),
1060 None => "Release bump did not run".to_owned(),
1061 };
1062 let detail = format!(
1063 "Run {} merged, but the release step after it failed.\n\n{reason}\n\n\
1064 Action required: {action}.",
1065 state.id
1066 );
1067 let mut q = ask::Question::new(
1068 state.id.clone(),
1069 NOTICE_NODE.to_owned(),
1070 "bump".to_owned(),
1071 summary,
1072 detail,
1073 vec![NOTICE_DONE.to_owned(), NOTICE_DISMISS.to_owned()],
1074 );
1075 store.put(&mut q).context("file the release-bump notice")?;
1076 state.event(
1077 "bump",
1078 format!("needs attention: notice {} filed - {action}", q.short()),
1079 );
1080 let comment = pr_url.map(|_| automerge_failure_comment(reason));
1081 Ok((q, comment))
1082}
1083
1084pub async fn report_problem(
1089 state: &mut RunState,
1090 pr_url: Option<&str>,
1091 version: Option<&str>,
1092 reason: &str,
1093) {
1094 match surface_problem(state, &ask::Questions::open(), pr_url, version, reason) {
1095 Ok((q, comment)) => {
1096 if let (Some(url), Some(body)) = (pr_url, comment)
1097 && let Err(e) = gh_pr_comment(
1098 &state.repo,
1099 url,
1100 &crate::scrub::scrub(&body, &crate::scrub::Identity::current()),
1101 )
1102 .await
1103 {
1104 state.event("bump", format!("could not comment on {url}: {e:#}"));
1105 }
1106 if let Err(e) = ask::notify(&state.config.notify, &q).await {
1107 tracing::warn!(
1108 "could not notify about release-bump notice {}: {e:#}",
1109 q.short()
1110 );
1111 }
1112 }
1113 Err(e) => state.event("bump", format!("could not raise a notice: {e:#}")),
1114 }
1115}
1116
1117async fn gh_pr_comment(cwd: &Path, pr_url: &str, body: &str) -> Result<()> {
1118 let out = tokio::process::Command::new("gh")
1119 .args(["pr", "comment", pr_url, "--body", body])
1120 .current_dir(cwd)
1121 .quiet()
1122 .stdin(std::process::Stdio::null())
1123 .output()
1124 .await
1125 .context("spawn gh pr comment")?;
1126 if out.status.success() {
1127 Ok(())
1128 } else {
1129 bail!(
1130 "gh pr comment: {}",
1131 String::from_utf8_lossy(&out.stderr).trim()
1132 )
1133 }
1134}
1135
1136async fn escalate_pending(
1145 state: &mut RunState,
1146 repo: &Path,
1147 remote: &str,
1148 pending: &PendingBump,
1149 decision: &BumpDecision,
1150 base_version: &str,
1151 marker: &Path,
1152) -> Result<()> {
1153 let next = Version::parse(base_version)?
1154 .bump(decision.level)
1155 .to_string();
1156 let worktree = state.dir().join("bump");
1157 git::worktree_remove(repo, &worktree).await.ok();
1158 let checked_out = git::git_raw(
1159 repo,
1160 &[
1161 "worktree",
1162 "add",
1163 "--force",
1164 &worktree.to_string_lossy(),
1165 &pending.branch,
1166 ],
1167 )
1168 .await?;
1169 if !checked_out.ok() {
1170 bail!(
1171 "checking out the pending release branch {} failed: {}",
1172 pending.branch,
1173 checked_out.stderr
1174 );
1175 }
1176
1177 let pushed: Result<()> = async {
1182 let cargo_toml_path = worktree.join("Cargo.toml");
1183 let toml = tokio::fs::read_to_string(&cargo_toml_path)
1184 .await
1185 .with_context(|| format!("read {}", cargo_toml_path.display()))?;
1186 let rewritten = rewrite_cargo_version(&toml, &next)?;
1187 tokio::fs::write(&cargo_toml_path, rewritten)
1188 .await
1189 .with_context(|| format!("write {}", cargo_toml_path.display()))?;
1190 sync_lockfile(&worktree, state.config.cache_dir().as_deref()).await?;
1191 let committed = git::commit_all(
1192 &worktree,
1193 &format!(
1194 "chore: release v{next} (supersedes v{})",
1195 pending.target_version
1196 ),
1197 )
1198 .await
1199 .context("commit the escalated version bump")?;
1200 if !committed {
1201 bail!("escalating the version bump left nothing to commit");
1202 }
1203 let pushed = git::push(&worktree, remote, &pending.branch).await?;
1204 if !pushed.ok() {
1205 bail!("pushing {} failed: {}", pending.branch, pushed.stderr);
1206 }
1207 Ok(())
1208 }
1209 .await;
1210 if let Err(e) = pushed {
1211 git::worktree_remove(repo, &worktree).await.ok();
1212 return Err(e);
1213 }
1214
1215 let title_warning = match gh_pr_edit_title(
1219 &worktree,
1220 &pending.pr_url,
1221 &crate::scrub::scrub(
1222 &format!("chore: release v{next} ({} bump)", decision.level.as_str()),
1223 &crate::scrub::Identity::current(),
1224 ),
1225 )
1226 .await
1227 {
1228 Ok(()) => None,
1229 Err(e) => Some(e.to_string()),
1230 };
1231 git::worktree_remove(repo, &worktree).await.ok();
1232
1233 let marker_write = write_marker(
1234 marker,
1235 &PendingBump {
1236 target_version: next.clone(),
1237 level: decision.level,
1238 branch: pending.branch.clone(),
1239 pr_url: pending.pr_url.clone(),
1240 },
1241 );
1242 state.event(
1243 "bump",
1244 format!(
1245 "escalated the pending release bump from v{} to v{next} to a {} change ({}): {}",
1246 pending.target_version,
1247 decision.level.as_str(),
1248 decision.reason,
1249 pending.pr_url
1250 ),
1251 );
1252 if let Err(e) = marker_write {
1253 state.event(
1254 "bump",
1255 format!(
1256 "could not update the pending release bump marker to v{next}: {e:#}; a later \
1257 merge may misjudge whether it is already covered"
1258 ),
1259 );
1260 }
1261 if let Some(warning) = title_warning {
1262 state.event(
1263 "bump",
1264 format!(
1265 "pushed v{next} to {} but could not update its title: {warning}; the squashed \
1266 subject may still read the superseded version",
1267 pending.pr_url
1268 ),
1269 );
1270 }
1271 Ok(())
1272}
1273
1274async fn open_bump_pr(
1280 state: &RunState,
1281 worktree: &Path,
1282 branch: &str,
1283 next_version: &str,
1284 decision: &BumpDecision,
1285 source_pr_url: &str,
1286) -> Result<(String, Option<String>)> {
1287 let cargo_toml_path = worktree.join("Cargo.toml");
1288 let toml = tokio::fs::read_to_string(&cargo_toml_path)
1289 .await
1290 .with_context(|| format!("read {}", cargo_toml_path.display()))?;
1291 let rewritten = rewrite_cargo_version(&toml, next_version)?;
1292 tokio::fs::write(&cargo_toml_path, rewritten)
1293 .await
1294 .with_context(|| format!("write {}", cargo_toml_path.display()))?;
1295
1296 sync_lockfile(worktree, state.config.cache_dir().as_deref()).await?;
1297
1298 let committed = git::commit_all(worktree, &format!("chore: release v{next_version}"))
1299 .await
1300 .context("commit the version bump")?;
1301 if !committed {
1302 bail!("the version bump left nothing to commit");
1303 }
1304
1305 let remote = state.config.merge.remote.clone();
1306 let pushed = git::push(worktree, &remote, branch).await?;
1307 if !pushed.ok() {
1308 bail!("pushing {branch} failed: {}", pushed.stderr);
1309 }
1310
1311 let (title, body) = release_pr(
1312 decision.level.as_str(),
1313 &decision.reason,
1314 next_version,
1315 &state.id,
1316 source_pr_url,
1317 );
1318 let who = crate::scrub::Identity::current();
1319 let (title, body) = (
1320 crate::scrub::scrub(&title, &who),
1321 crate::scrub::scrub(&body, &who),
1322 );
1323 let url = gh_pr_create(worktree, &state.base_branch, branch, &title, &body).await?;
1324 let automerge_warning = match gh_enable_automerge(worktree, &url).await {
1325 Ok(()) => None,
1326 Err(e) => Some(e.to_string()),
1327 };
1328 Ok((url, automerge_warning))
1329}
1330
1331async fn sync_lockfile(worktree: &Path, cache_dir: Option<&Path>) -> Result<()> {
1339 let mut cmd = tokio::process::Command::new("cargo");
1340 cmd.arg("build").current_dir(worktree).quiet();
1341 if let Some(dir) = cache_dir {
1342 cmd.env("CARGO_TARGET_DIR", dir);
1343 }
1344 let out = cmd
1345 .stdin(std::process::Stdio::null())
1346 .output()
1347 .await
1348 .context("spawn cargo build")?;
1349 if !out.status.success() {
1350 bail!(
1351 "cargo build failed while syncing Cargo.lock: {}",
1352 String::from_utf8_lossy(&out.stderr).trim()
1353 );
1354 }
1355 Ok(())
1356}
1357
1358fn release_pr(
1363 level: &str,
1364 reason: &str,
1365 next_version: &str,
1366 run_id: &str,
1367 source_pr_url: &str,
1368) -> (String, String) {
1369 let title = format!("chore: release v{next_version} ({level} bump)");
1370 let body = format!(
1371 "## Background\n\n\
1372 A change that was just merged is a `{level}` change, so the crate needs a new \
1373 release: {reason}\n\n\
1374 Triggered by magi run `{run_id}`, which landed {source}.\n\n\
1375 ## Change\n\n\
1376 Raises the package version to `v{next_version}` in `Cargo.toml`, with \
1377 `Cargo.lock` following it. Nothing else changes.\n\n\
1378 ## Risk\n\n\
1379 Version-bump-only, so there is nothing here for a reviewer to find. Merging \
1380 it starts the release pipeline (auto-tag, then the release workflow).",
1381 source = source_pr_url,
1382 );
1383 (title, body)
1384}
1385
1386async fn pr_title(repo: &Path, pr_url: &str) -> Result<String> {
1388 let out = tokio::process::Command::new("gh")
1389 .args(["pr", "view", pr_url, "--json", "title"])
1390 .current_dir(repo)
1391 .quiet()
1392 .stdin(std::process::Stdio::null())
1393 .output()
1394 .await
1395 .context("spawn gh pr view")?;
1396 if !out.status.success() {
1397 bail!(
1398 "gh pr view {pr_url}: {}",
1399 String::from_utf8_lossy(&out.stderr).trim()
1400 );
1401 }
1402 #[derive(Deserialize)]
1403 struct Title {
1404 title: String,
1405 }
1406 let parsed: Title = serde_json::from_str(&String::from_utf8_lossy(&out.stdout))
1407 .context("parse `gh pr view --json title` output")?;
1408 Ok(parsed.title)
1409}
1410
1411async fn gh_pr_create(
1412 cwd: &Path,
1413 base: &str,
1414 head: &str,
1415 title: &str,
1416 body: &str,
1417) -> Result<String> {
1418 let out = tokio::process::Command::new("gh")
1419 .args([
1420 "pr", "create", "--base", base, "--head", head, "--title", title, "--body", body,
1421 ])
1422 .current_dir(cwd)
1423 .quiet()
1424 .stdin(std::process::Stdio::null())
1425 .output()
1426 .await
1427 .context("spawn gh pr create")?;
1428 if out.status.success() {
1429 Ok(String::from_utf8_lossy(&out.stdout).trim().to_owned())
1430 } else {
1431 bail!(
1432 "gh pr create: {}",
1433 String::from_utf8_lossy(&out.stderr).trim()
1434 )
1435 }
1436}
1437
1438async fn gh_enable_automerge(cwd: &Path, pr_url: &str) -> Result<()> {
1442 let out = tokio::process::Command::new("gh")
1443 .args([
1444 "pr",
1445 "merge",
1446 pr_url,
1447 "--auto",
1448 "--squash",
1449 "--delete-branch",
1450 ])
1451 .current_dir(cwd)
1452 .quiet()
1453 .stdin(std::process::Stdio::null())
1454 .output()
1455 .await
1456 .context("spawn gh pr merge --auto")?;
1457 if out.status.success() {
1458 Ok(())
1459 } else {
1460 bail!(
1461 "gh pr merge --auto: {}",
1462 String::from_utf8_lossy(&out.stderr).trim()
1463 )
1464 }
1465}
1466
1467async fn gh_pr_edit_title(cwd: &Path, pr_url: &str, title: &str) -> Result<()> {
1471 let out = tokio::process::Command::new("gh")
1472 .args(["pr", "edit", pr_url, "--title", title])
1473 .current_dir(cwd)
1474 .quiet()
1475 .stdin(std::process::Stdio::null())
1476 .output()
1477 .await
1478 .context("spawn gh pr edit")?;
1479 if out.status.success() {
1480 Ok(())
1481 } else {
1482 bail!(
1483 "gh pr edit --title: {}",
1484 String::from_utf8_lossy(&out.stderr).trim()
1485 )
1486 }
1487}
1488
1489#[cfg(test)]
1490mod tests {
1491 use super::*;
1492
1493 #[test]
1494 fn github_facing_bump_text_is_english() {
1495 let (title, body) =
1496 release_pr("minor", "adds a flag", "0.37.0", "ab12", "https://x/pull/1");
1497 assert!(title.is_ascii() && body.is_ascii(), "{title}\n{body}");
1498 assert_eq!(title, "chore: release v0.37.0 (minor bump)");
1499 assert!(
1500 body.contains("## Background") && body.contains("## Change"),
1501 "{body}"
1502 );
1503 let p = decision_prompt("s", "i", "d", &[], "0.36.5");
1504 assert!(p.contains(crate::prompt::GITHUB_ENGLISH_HEADING), "{p}");
1505 }
1506 use crate::config::Config;
1507 use crate::land::PrLifecycle;
1508
1509 #[tokio::test]
1515 async fn a_disabled_config_does_nothing() {
1516 let config = Config {
1517 merge: crate::config::Merge {
1518 release_bump: false,
1519 ..crate::config::Merge::default()
1520 },
1521 ..Config::default()
1522 };
1523 let mut state = RunState::new(
1524 PathBuf::from("/no/such/repo"),
1525 "main".to_owned(),
1526 "0000000000000000000000000000000000000000".to_owned(),
1527 "irrelevant".to_owned(),
1528 config,
1529 );
1530 after_merge(&mut state, "https://example.invalid/pull/1")
1531 .await
1532 .expect("a disabled config must return Ok without touching anything");
1533 assert!(
1534 state.events.is_empty(),
1535 "nothing should happen at all, not even a logged event"
1536 );
1537 }
1538
1539 async fn origin_with(files: &[(&str, &str)]) -> (tempfile::TempDir, PathBuf) {
1541 let dir = tempfile::tempdir().unwrap();
1542 let origin = dir.path().join("origin.git");
1543 let repo = dir.path().join("repo");
1544 let o = origin.to_string_lossy().into_owned();
1545 git::git(dir.path(), &["init", "--bare", "-b", "main", &o])
1546 .await
1547 .unwrap();
1548 tokio::fs::create_dir_all(&repo).await.unwrap();
1549 git::git(&repo, &["init", "-b", "main"]).await.unwrap();
1550 git::git(&repo, &["config", "user.name", "test"])
1551 .await
1552 .unwrap();
1553 git::git(&repo, &["config", "user.email", "test@example.com"])
1554 .await
1555 .unwrap();
1556 for (name, body) in files {
1557 tokio::fs::write(repo.join(name), body).await.unwrap();
1558 }
1559 git::git(&repo, &["add", "-A"]).await.unwrap();
1560 git::git(&repo, &["commit", "-m", "init"]).await.unwrap();
1561 git::git(&repo, &["remote", "add", "origin", &o])
1562 .await
1563 .unwrap();
1564 git::git(&repo, &["push", "origin", "main"]).await.unwrap();
1565 (dir, repo)
1566 }
1567
1568 #[tokio::test]
1569 async fn base_has_cargo_toml_tells_rust_from_non_rust() {
1570 let (_d, rust) = origin_with(&[("Cargo.toml", "[package]\nversion = \"0.1.0\"\n")]).await;
1571 assert!(base_has_cargo_toml(&rust, "origin", "main").await.unwrap());
1572 let (_d2, other) = origin_with(&[("README.md", "hi\n")]).await;
1573 assert!(!base_has_cargo_toml(&other, "origin", "main").await.unwrap());
1574 assert!(base_has_cargo_toml(&other, "origin", "nope").await.is_err());
1576 }
1577
1578 #[tokio::test]
1579 async fn a_repo_without_cargo_toml_skips_with_one_event_and_no_lock() {
1580 let (_d, repo) = origin_with(&[("README.md", "hi\n")]).await;
1581 let home = tempfile::tempdir().unwrap();
1582 let mut state = RunState::new(
1583 repo.clone(),
1584 "main".to_owned(),
1585 "0000000000000000000000000000000000000000".to_owned(),
1586 "task".to_owned(),
1587 Config::default(),
1588 );
1589 state.candidates.push(crate::run::Candidate {
1590 index: 0,
1591 label: 'A',
1592 agent: "x".to_owned(),
1593 branch: "main".to_owned(),
1594 worktree: repo.clone(),
1595 summary: String::new(),
1596 stat: String::new(),
1597 files: 1,
1598 commits: 1,
1599 empty: false,
1600 failed: None,
1601 verified_noop: None,
1602 duration_ms: 0,
1603 folded: false,
1604 });
1605 state.tally = Some(
1606 serde_json::from_value(serde_json::json!({
1607 "first_choice": {}, "borda": {}, "winner": "A",
1608 "unanimous_initial": true, "deliberated": false,
1609 "changed_votes": 0, "unanimous_final": true,
1610 }))
1611 .unwrap(),
1612 );
1613 after_merge_at(
1614 &mut state,
1615 "https://example.invalid/pull/1",
1616 Some(home.path()),
1617 )
1618 .await
1619 .expect("a non-Rust repository is not an error");
1620 let bumps: Vec<_> = state.events.iter().filter(|e| e.node == "bump").collect();
1621 assert_eq!(bumps.len(), 1, "{:?}", state.events);
1622 assert_eq!(
1623 bumps[0].message,
1624 "release bump: no Cargo.toml on the base branch; release bumps are Rust-only, skipping"
1625 );
1626 assert!(
1627 std::fs::read_dir(home.path()).unwrap().next().is_none(),
1628 "no marker and no lock may be created"
1629 );
1630 }
1631
1632 const NO_RULES: &str = "gh pr merge --auto: GraphQL: Pull request Branch does not have \
1633 required protected branch rules (enablePullRequestAutoMerge)";
1634
1635 fn merged_state() -> RunState {
1636 run::set_home(std::env::temp_dir().join("magi-report-test-home"));
1639 let mut s = RunState::new(
1640 PathBuf::from("/no/such/repo"),
1641 "main".to_owned(),
1642 "0000000000000000000000000000000000000000".to_owned(),
1643 "task".to_owned(),
1644 Config::default(),
1645 );
1646 s.status = RunStatus::Merged;
1647 s
1648 }
1649
1650 #[test]
1651 fn the_known_automerge_refusal_names_branch_protection() {
1652 assert!(automerge_hint(NO_RULES).contains("branch protection with required"));
1653 let other = automerge_hint("gh: network unreachable");
1654 assert!(!other.contains("branch protection"), "{other}");
1655 let body = automerge_failure_comment(NO_RULES);
1656 assert!(body.contains("enablePullRequestAutoMerge"), "{body}");
1657 assert!(body.contains("Action required"), "{body}");
1658 }
1659
1660 #[test]
1661 fn an_automerge_failure_is_recorded_shown_and_filed_and_survives_settling() {
1662 let dir = tempfile::tempdir().unwrap();
1663 let store = ask::Questions::at(dir.path().join("questions"));
1664 let mut state = merged_state();
1665 let url = "https://github.com/o/r/pull/35";
1666
1667 let (q, comment) =
1668 surface_problem(&mut state, &store, Some(url), Some("0.8.0"), NO_RULES).unwrap();
1669
1670 let comment = comment.expect("a PR was opened, so it gets a comment");
1672 assert!(comment.contains("branch protection"), "{comment}");
1673
1674 assert_eq!(state.status, RunStatus::Merged);
1676 assert!(state.needs_attention());
1677 let text = crate::report::run(&state);
1678 assert!(text.contains("release bump"), "{text}");
1679 assert!(text.contains("FAILED"), "{text}");
1680 assert!(text.contains(url), "{text}");
1681 assert!(text.contains("action required"), "{text}");
1682 assert!(crate::report::line(&state).contains("release needs a human"));
1683
1684 assert_eq!(q.node, NOTICE_NODE);
1686 assert_eq!(store.open_for(&state.id).len(), 1);
1687 assert_eq!(store.settle_run(&state.id, RunStatus::Merged).unwrap(), 0);
1688 assert!(store.get(&q.id).unwrap().status.open());
1689 }
1690
1691 #[test]
1692 fn a_bump_that_never_ran_is_surfaced_without_a_pr_comment() {
1693 let dir = tempfile::tempdir().unwrap();
1694 let store = ask::Questions::at(dir.path().join("questions"));
1695 let mut state = merged_state();
1696 let (_, comment) = surface_problem(&mut state, &store, None, None, "no agent").unwrap();
1697 assert!(comment.is_none());
1698 assert!(state.needs_attention());
1699 }
1700
1701 #[test]
1702 fn version_parses_and_bumps_each_digit() {
1703 let v = Version::parse("0.4.0").unwrap();
1704 assert_eq!(
1705 v,
1706 Version {
1707 major: 0,
1708 minor: 4,
1709 patch: 0
1710 }
1711 );
1712
1713 assert_eq!(v.bump(BumpLevel::Major).to_string(), "1.0.0");
1714 assert_eq!(v.bump(BumpLevel::Minor).to_string(), "0.5.0");
1715 assert_eq!(v.bump(BumpLevel::Patch).to_string(), "0.4.1");
1716 }
1717
1718 #[test]
1719 fn version_tolerates_a_prerelease_suffix_on_patch() {
1720 let v = Version::parse("1.2.3-rc1").unwrap();
1721 assert_eq!(
1722 v,
1723 Version {
1724 major: 1,
1725 minor: 2,
1726 patch: 3
1727 }
1728 );
1729 }
1730
1731 #[test]
1732 fn version_rejects_garbage() {
1733 assert!(Version::parse("not-a-version").is_err());
1734 assert!(Version::parse("1.2").is_err());
1735 }
1736
1737 #[test]
1738 fn decision_parses_each_level() {
1739 for (json, level) in [
1740 (
1741 r#"{"level":"major","reason":"drops a config key"}"#,
1742 BumpLevel::Major,
1743 ),
1744 (
1745 r#"{"level":"minor","reason":"adds a new flag"}"#,
1746 BumpLevel::Minor,
1747 ),
1748 (
1749 r#"{"level":"patch","reason":"fixes a race"}"#,
1750 BumpLevel::Patch,
1751 ),
1752 ] {
1753 let decision = parse_decision(json).unwrap();
1754 assert_eq!(decision.level, level);
1755 assert!(!decision.reason.is_empty());
1756 }
1757 }
1758
1759 #[test]
1760 fn decision_wrapped_in_a_fence_and_prose_still_parses() {
1761 let text = "Here is my call.\n\n```json\n{\"level\":\"minor\",\"reason\":\"new HTTP route\"}\n```\n\nDone.";
1762 let decision = parse_decision(text).unwrap();
1763 assert_eq!(decision.level, BumpLevel::Minor);
1764 assert_eq!(decision.reason, "new HTTP route");
1765 }
1766
1767 #[test]
1768 fn a_broken_reply_is_an_error_not_a_default() {
1769 assert!(parse_decision("I decline to answer.").is_err());
1770 assert!(parse_decision(r#"{"level":"huge","reason":"go big"}"#).is_err());
1771 assert!(
1772 parse_decision(r#"{"level":"patch","reason":""}"#).is_err(),
1773 "an empty reason must not pass either"
1774 );
1775 assert!(
1776 parse_decision(r#"{"level":"patch"}"#).is_err(),
1777 "a reply with no reason at all must not pass"
1778 );
1779 }
1780
1781 #[test]
1782 fn prompt_states_the_zero_x_rule_and_the_tie_break() {
1783 let prompt = decision_prompt(
1784 "feat: add a phone endpoint",
1785 "add POST /api/widgets",
1786 "1 file changed, 10 insertions(+)",
1787 &["src/web.rs".to_owned()],
1788 "0.8.0",
1789 );
1790 assert!(prompt.contains("0.8.0"), "the current version is stated");
1791 assert!(
1792 prompt.contains("below `1.0.0`")
1793 && prompt.contains("`minor` is the digit that carries a breaking change"),
1794 "the 0.x rule must be explicit: {prompt}"
1795 );
1796 assert!(
1797 prompt.contains("choose the larger"),
1798 "the tie-break toward the bigger digit must be explicit: {prompt}"
1799 );
1800 }
1801
1802 #[test]
1803 fn release_only_diffs_are_recognised() {
1804 assert!(is_release_only(&["Cargo.toml".to_owned()]));
1805 assert!(is_release_only(&[
1806 "Cargo.toml".to_owned(),
1807 "Cargo.lock".to_owned()
1808 ]));
1809 assert!(!is_release_only(&[]));
1810 assert!(!is_release_only(&[
1811 "Cargo.toml".to_owned(),
1812 "src/main.rs".to_owned()
1813 ]));
1814 }
1815
1816 #[test]
1817 fn cargo_version_rewrite_touches_only_the_package_table() {
1818 let toml = "\
1819[package]\n\
1820# a comment mentioning version on purpose\n\
1821name = \"magi-cli\"\n\
1822version = \"0.8.0\"\n\
1823edition = \"2024\"\n\
1824\n\
1825[dependencies]\n\
1826foo = { version = \"1.2.3\" }\n";
1827 let out = rewrite_cargo_version(toml, "0.9.0").unwrap();
1828 assert!(out.contains("version = \"0.9.0\""));
1829 assert!(
1830 out.contains("foo = { version = \"1.2.3\" }"),
1831 "a dependency's own version pin must survive: {out}"
1832 );
1833 assert!(
1834 out.contains("# a comment mentioning version on purpose"),
1835 "unrelated lines, comments included, must be byte-for-byte preserved: {out}"
1836 );
1837 assert_eq!(
1838 out.lines().count(),
1839 toml.lines().count(),
1840 "the rewrite replaces one line, it does not add or remove any"
1841 );
1842 }
1843
1844 #[test]
1845 fn cargo_version_rewrite_fails_without_a_package_table() {
1846 let toml = "[dependencies]\nfoo = \"1\"\n";
1847 assert!(rewrite_cargo_version(toml, "1.0.0").is_err());
1848 }
1849
1850 #[test]
1856 fn cargo_version_rewrite_falls_back_to_workspace_package_without_a_package_table() {
1857 let toml = "\
1858[workspace]\n\
1859members = [\"crates/a\", \"crates/b\"]\n\
1860\n\
1861[workspace.package]\n\
1862version = \"0.45.18\"\n\
1863edition = \"2024\"\n\
1864\n\
1865[workspace.dependencies]\n\
1866foo = { version = \"1.2.3\" }\n";
1867 let out = rewrite_cargo_version(toml, "0.45.19").unwrap();
1868 assert!(out.contains("version = \"0.45.19\""));
1869 assert!(
1870 out.contains("foo = { version = \"1.2.3\" }"),
1871 "a workspace dependency's own version pin must survive: {out}"
1872 );
1873 assert_eq!(
1874 out.lines().count(),
1875 toml.lines().count(),
1876 "the rewrite replaces one line, it does not add or remove any"
1877 );
1878 }
1879
1880 #[test]
1881 fn current_version_prefers_the_package_table_when_both_exist() {
1882 let toml = "[workspace.package]\nversion = \"9.9.9\"\n\n[package]\nversion = \"0.8.0\"\n";
1883 assert_eq!(current_version(toml).unwrap(), "0.8.0");
1884 }
1885
1886 #[test]
1889 fn current_version_falls_back_to_workspace_package_without_a_package_table() {
1890 let toml = "\
1891[workspace]\n\
1892members = [\"crates/a\", \"crates/b\"]\n\
1893\n\
1894[workspace.package]\n\
1895version = \"0.45.18\"\n";
1896 assert_eq!(current_version(toml).unwrap(), "0.45.18");
1897 }
1898
1899 #[test]
1900 fn coalesce_proceeds_with_nothing_pending() {
1901 assert_eq!(coalesce(None, "0.8.0").unwrap(), Coalesce::Proceed);
1902 }
1903
1904 fn test_pending(target_version: &str, level: BumpLevel) -> PendingBump {
1907 PendingBump {
1908 target_version: target_version.to_owned(),
1909 level,
1910 branch: format!("chore/release-v{target_version}"),
1911 pr_url: "https://example.invalid/pull/9".to_owned(),
1912 }
1913 }
1914
1915 #[test]
1916 fn coalesce_skips_while_the_pending_target_is_still_ahead() {
1917 let pending = test_pending("0.9.0", BumpLevel::Minor);
1918 assert_eq!(
1919 coalesce(Some(&pending), "0.8.0").unwrap(),
1920 Coalesce::Skip {
1921 target_version: "0.9.0".to_owned()
1922 }
1923 );
1924 }
1925
1926 #[test]
1927 fn coalesce_treats_a_landed_or_superseded_pending_bump_as_stale() {
1928 let pending = test_pending("0.9.0", BumpLevel::Minor);
1929 assert_eq!(
1931 coalesce(Some(&pending), "0.9.0").unwrap(),
1932 Coalesce::Proceed
1933 );
1934 assert_eq!(
1936 coalesce(Some(&pending), "1.0.0").unwrap(),
1937 Coalesce::Proceed
1938 );
1939 }
1940
1941 #[test]
1942 fn pending_action_escalates_only_for_a_more_severe_decision() {
1943 assert_eq!(
1944 pending_action(BumpLevel::Patch, BumpLevel::Patch),
1945 PendingAction::AlreadyCovered
1946 );
1947 assert_eq!(
1948 pending_action(BumpLevel::Patch, BumpLevel::Minor),
1949 PendingAction::Escalate
1950 );
1951 assert_eq!(
1952 pending_action(BumpLevel::Patch, BumpLevel::Major),
1953 PendingAction::Escalate
1954 );
1955 assert_eq!(
1956 pending_action(BumpLevel::Minor, BumpLevel::Patch),
1957 PendingAction::AlreadyCovered
1958 );
1959 assert_eq!(
1960 pending_action(BumpLevel::Major, BumpLevel::Minor),
1961 PendingAction::AlreadyCovered
1962 );
1963 assert_eq!(
1964 pending_action(BumpLevel::Major, BumpLevel::Major),
1965 PendingAction::AlreadyCovered
1966 );
1967 }
1968
1969 #[test]
1970 fn pr_state_parsing_reads_open_and_not_open() {
1971 assert!(parse_pr_state(r#"{"state":"OPEN"}"#).unwrap());
1972 assert!(!parse_pr_state(r#"{"state":"CLOSED"}"#).unwrap());
1973 assert!(!parse_pr_state(r#"{"state":"MERGED"}"#).unwrap());
1974 }
1975
1976 #[test]
1977 fn a_lock_is_exclusive_until_dropped() {
1978 let dir = tempfile::tempdir().unwrap();
1979 let marker = dir.path().join("bump").join("deadbeefdeadbeef.json");
1980 let first = MarkerLock::acquire(&marker)
1981 .unwrap()
1982 .expect("first attempt takes the lock");
1983 assert!(
1984 MarkerLock::acquire(&marker).unwrap().is_none(),
1985 "a second attempt must be refused while the first holds it"
1986 );
1987 drop(first);
1988 assert!(
1989 MarkerLock::acquire(&marker).unwrap().is_some(),
1990 "dropping the guard releases the lock for the next attempt"
1991 );
1992 }
1993
1994 #[test]
1995 fn a_stale_lock_is_reclaimed() {
1996 let dir = tempfile::tempdir().unwrap();
1997 let marker = dir.path().join("bump").join("deadbeefdeadbeef.json");
1998 let lock_path = marker.with_extension("lock");
1999 std::fs::create_dir_all(lock_path.parent().unwrap()).unwrap();
2000 std::fs::write(&lock_path, b"").unwrap();
2001 let old = std::time::SystemTime::now() - LOCK_STALE_AFTER - Duration::from_secs(1);
2002 std::fs::OpenOptions::new()
2003 .write(true)
2004 .open(&lock_path)
2005 .unwrap()
2006 .set_modified(old)
2007 .unwrap();
2008 assert!(
2009 MarkerLock::acquire(&marker).unwrap().is_some(),
2010 "a lock older than the stale window must be reclaimed rather than block forever"
2011 );
2012 }
2013
2014 #[tokio::test]
2015 async fn a_contended_lock_is_retried_until_the_holder_releases_it() {
2016 let dir = tempfile::tempdir().unwrap();
2017 let marker = dir.path().join("bump").join("deadbeefdeadbeef.json");
2018 let held = MarkerLock::acquire(&marker)
2019 .unwrap()
2020 .expect("seed the contention");
2021 let releaser = tokio::spawn(async move {
2022 tokio::time::sleep(Duration::from_millis(20)).await;
2023 drop(held);
2024 });
2025 let waited =
2026 wait_for_marker_lock_with(&marker, Duration::from_millis(5), Duration::from_secs(5))
2027 .await
2028 .unwrap();
2029 assert!(
2030 waited.is_some(),
2031 "a merge landing behind another's still-running decision must not be dropped - it \
2032 must wait for that decision to finish and then judge against what it left behind"
2033 );
2034 releaser.await.unwrap();
2035 }
2036
2037 #[tokio::test]
2038 async fn a_lock_held_past_the_ceiling_gives_up() {
2039 let dir = tempfile::tempdir().unwrap();
2040 let marker = dir.path().join("bump").join("deadbeefdeadbeef.json");
2041 let _held = MarkerLock::acquire(&marker).unwrap().unwrap();
2042 let waited =
2043 wait_for_marker_lock_with(&marker, Duration::from_millis(2), Duration::from_millis(10))
2044 .await
2045 .unwrap();
2046 assert!(
2047 waited.is_none(),
2048 "a lock genuinely held past the ceiling must eventually give up rather than wait \
2049 forever"
2050 );
2051 }
2052
2053 #[test]
2054 fn level_between_reads_off_the_differing_digit() {
2055 assert_eq!(
2056 level_between(
2057 Version::parse("0.8.0").unwrap(),
2058 Version::parse("1.0.0").unwrap()
2059 ),
2060 Some(BumpLevel::Major)
2061 );
2062 assert_eq!(
2063 level_between(
2064 Version::parse("0.8.0").unwrap(),
2065 Version::parse("0.9.0").unwrap()
2066 ),
2067 Some(BumpLevel::Minor)
2068 );
2069 assert_eq!(
2070 level_between(
2071 Version::parse("0.8.0").unwrap(),
2072 Version::parse("0.8.1").unwrap()
2073 ),
2074 Some(BumpLevel::Patch)
2075 );
2076 assert_eq!(
2077 level_between(
2078 Version::parse("0.8.0").unwrap(),
2079 Version::parse("0.8.0").unwrap()
2080 ),
2081 None
2082 );
2083 }
2084
2085 #[test]
2086 fn open_release_pr_is_found_among_unrelated_pull_requests() {
2087 let json = r#"[
2088 {"url": "https://example.invalid/pull/1", "headRefName": "feat/something"},
2089 {"url": "https://example.invalid/pull/2", "headRefName": "chore/release-v0.9.0"}
2090 ]"#;
2091 let found = parse_open_release_pr(json).unwrap();
2092 assert_eq!(
2093 found,
2094 Some((
2095 "chore/release-v0.9.0".to_owned(),
2096 "https://example.invalid/pull/2".to_owned()
2097 ))
2098 );
2099 }
2100
2101 #[test]
2102 fn no_open_release_pr_reads_as_none_not_an_error() {
2103 let json =
2104 r#"[{"url": "https://example.invalid/pull/1", "headRefName": "feat/something"}]"#;
2105 assert_eq!(parse_open_release_pr(json).unwrap(), None);
2106 assert_eq!(parse_open_release_pr("[]").unwrap(), None);
2107 }
2108
2109 #[test]
2110 fn marker_round_trips_through_disk() {
2111 let dir = tempfile::tempdir().unwrap();
2112 let path = marker_path(dir.path(), Path::new("/repos/magi"));
2113 assert!(read_marker(&path).is_none());
2114
2115 let marker = test_pending("0.9.0", BumpLevel::Patch);
2116 write_marker(&path, &marker).unwrap();
2117 let read_back = read_marker(&path).unwrap();
2118 assert_eq!(read_back.target_version, "0.9.0");
2119 assert_eq!(read_back.level, BumpLevel::Patch);
2120 assert_eq!(read_back.pr_url, marker.pr_url);
2121
2122 clear_marker(&path);
2123 assert!(read_marker(&path).is_none());
2124 }
2125
2126 #[test]
2127 fn different_repos_get_different_marker_files() {
2128 let dir = tempfile::tempdir().unwrap();
2129 let a = marker_path(dir.path(), Path::new("/repos/a"));
2130 let b = marker_path(dir.path(), Path::new("/repos/b"));
2131 assert_ne!(a, b);
2132 }
2133
2134 #[test]
2138 fn a_bump_pull_requests_own_merge_does_not_retrigger() {
2139 let files = vec!["Cargo.toml".to_owned(), "Cargo.lock".to_owned()];
2140 assert!(
2141 is_release_only(&files),
2142 "the bump pull request's own diff must read as release-only"
2143 );
2144 }
2145
2146 #[test]
2147 fn should_release_bump_reads_only_a_merged_status() {
2148 assert!(should_release_bump(RunStatus::Merged));
2149 for other in [RunStatus::Blocked, RunStatus::Ready, RunStatus::Prep] {
2150 assert!(!should_release_bump(other));
2151 }
2152 }
2153
2154 #[test]
2158 fn all_three_merge_paths_report_pr_lifecycle_merged_case_done() {
2159 let pr = land::PrState {
2160 url: "https://github.com/o/r/pull/1".to_owned(),
2161 number: 1,
2162 state: PrLifecycle::Merged,
2163 checks: land::Checks::Green,
2164 failing: Vec::new(),
2165 review_comments: Vec::new(),
2166 blocking: land::Blocking::No,
2167 };
2168 assert_eq!(
2169 land::decide(&pr, 0, 4, Duration::ZERO),
2170 land::Step::Done { merged: true }
2171 );
2172 assert!(should_release_bump(RunStatus::Merged));
2173 }
2174
2175 #[test]
2180 fn all_three_merge_paths_report_pr_lifecycle_merged_case_direct_merge() {
2181 let pr = land::PrState {
2182 url: "https://github.com/o/r/pull/2".to_owned(),
2183 number: 2,
2184 state: PrLifecycle::Open,
2185 checks: land::Checks::Green,
2186 failing: Vec::new(),
2187 review_comments: Vec::new(),
2188 blocking: land::Blocking::No,
2189 };
2190 assert_eq!(land::decide(&pr, 0, 4, Duration::ZERO), land::Step::Merge);
2191 assert!(should_release_bump(RunStatus::Merged));
2194 }
2195
2196 #[test]
2199 fn all_three_merge_paths_report_pr_lifecycle_merged_case_merged_after_all() {
2200 let argv = land::merge_argv(3, "feat: something");
2201 let outcome = land::merged_after_all(
2202 &argv,
2203 "could not determine current branch: not on any branch",
2204 Some(PrLifecycle::Merged),
2205 );
2206 assert!(outcome.is_some(), "the forge's confirmation must win");
2207 assert!(should_release_bump(RunStatus::Merged));
2208
2209 assert!(land::merged_after_all(&argv, "network error", Some(PrLifecycle::Open)).is_none());
2212 assert!(land::merged_after_all(&argv, "network error", None).is_none());
2213 }
2214
2215 #[test]
2217 fn a_close_or_a_give_up_does_not_trigger_a_bump() {
2218 let pr = land::PrState {
2219 url: "https://github.com/o/r/pull/4".to_owned(),
2220 number: 4,
2221 state: PrLifecycle::Closed,
2222 checks: land::Checks::Green,
2223 failing: Vec::new(),
2224 review_comments: Vec::new(),
2225 blocking: land::Blocking::No,
2226 };
2227 assert_eq!(
2228 land::decide(&pr, 0, 4, Duration::ZERO),
2229 land::Step::Done { merged: false }
2230 );
2231 assert!(!should_release_bump(RunStatus::Blocked));
2232 }
2233}