1use std::fmt::Write as _;
23use std::path::{Path, PathBuf};
24use std::time::Duration;
25
26use anyhow::{Context as _, Result, anyhow, 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::notices::{Link, Notice, Notices};
35use crate::proc::Quiet as _;
36use crate::run::{self, RunState, RunStatus};
37use crate::verdict;
38
39const DECISION_TIMEOUT: Duration = Duration::from_secs(600);
46
47pub fn should_release_bump(status: RunStatus) -> bool {
63 status == RunStatus::Merged
64}
65
66#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
68#[serde(rename_all = "lowercase")]
69pub enum BumpLevel {
70 Major,
72 Minor,
74 Patch,
76}
77
78impl BumpLevel {
79 pub fn as_str(self) -> &'static str {
81 match self {
82 Self::Major => "major",
83 Self::Minor => "minor",
84 Self::Patch => "patch",
85 }
86 }
87
88 fn severity(self) -> u8 {
93 match self {
94 Self::Patch => 0,
95 Self::Minor => 1,
96 Self::Major => 2,
97 }
98 }
99}
100
101#[derive(Debug, Clone, Deserialize)]
108pub struct BumpDecision {
109 pub level: BumpLevel,
111 pub reason: String,
114}
115
116pub fn parse_decision(text: &str) -> Result<BumpDecision> {
120 let decision: BumpDecision = verdict::extract_json(text)?;
121 if decision.reason.trim().is_empty() {
122 bail!("the bump decision carried no reason");
123 }
124 Ok(decision)
125}
126
127#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
130pub struct Version {
131 pub major: u64,
133 pub minor: u64,
135 pub patch: u64,
137}
138
139impl Version {
140 pub fn parse(s: &str) -> Result<Self> {
145 let s = s.trim();
146 let mut parts = s.splitn(3, '.');
147 let major = parts
148 .next()
149 .with_context(|| format!("`{s}` has no major component"))?;
150 let minor = parts
151 .next()
152 .with_context(|| format!("`{s}` has no minor component"))?;
153 let patch = parts
154 .next()
155 .with_context(|| format!("`{s}` has no patch component"))?;
156 let patch_digits: String = patch.chars().take_while(char::is_ascii_digit).collect();
157 Ok(Self {
158 major: major
159 .trim()
160 .parse()
161 .with_context(|| format!("`{major}` is not a number"))?,
162 minor: minor
163 .trim()
164 .parse()
165 .with_context(|| format!("`{minor}` is not a number"))?,
166 patch: patch_digits
167 .parse()
168 .with_context(|| format!("`{patch}` has no numeric patch component"))?,
169 })
170 }
171
172 #[must_use]
175 pub fn bump(self, level: BumpLevel) -> Self {
176 match level {
177 BumpLevel::Major => Self {
178 major: self.major + 1,
179 minor: 0,
180 patch: 0,
181 },
182 BumpLevel::Minor => Self {
183 major: self.major,
184 minor: self.minor + 1,
185 patch: 0,
186 },
187 BumpLevel::Patch => Self {
188 major: self.major,
189 minor: self.minor,
190 patch: self.patch + 1,
191 },
192 }
193 }
194}
195
196impl std::fmt::Display for Version {
197 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
198 write!(f, "{}.{}.{}", self.major, self.minor, self.patch)
199 }
200}
201
202pub fn is_release_only(files: &[String]) -> bool {
211 !files.is_empty() && files.iter().all(|f| f == "Cargo.toml" || f == "Cargo.lock")
212}
213
214fn rewrite_table_version(toml: &str, table: &str, new_version: &str) -> Result<String> {
225 let mut out = String::with_capacity(toml.len() + 8);
226 let mut in_table = false;
227 let mut done = false;
228 for line in toml.split_inclusive('\n') {
229 let trimmed = line.trim();
230 if trimmed.starts_with('[') {
231 in_table = trimmed == table;
232 }
233 if !done && in_table && trimmed.split('=').next().map(str::trim) == Some("version") {
234 let newline = if line.ends_with("\r\n") { "\r\n" } else { "\n" };
235 let _ = write!(out, "version = \"{new_version}\"{newline}");
236 done = true;
237 continue;
238 }
239 out.push_str(line);
240 }
241 if !done {
242 bail!("no `version` field found under `{table}`");
243 }
244 Ok(out)
245}
246
247fn strip_trailing_comment(s: &str) -> &str {
253 let mut in_string = false;
254 let mut quote = '"';
255 for (i, c) in s.char_indices() {
256 if in_string {
257 if c == quote {
258 in_string = false;
259 }
260 } else if c == '"' || c == '\'' {
261 in_string = true;
262 quote = c;
263 } else if c == '#' {
264 return s[..i].trim_end();
265 }
266 }
267 s
268}
269
270fn unquote_key(key: &str) -> &str {
276 for quote in ['"', '\''] {
277 if let Some(inner) = key.strip_prefix(quote).and_then(|k| k.strip_suffix(quote)) {
278 return inner;
279 }
280 }
281 key
282}
283
284fn extract_workspace_dependencies_fragment(toml: &str) -> String {
296 let mut fragment = String::new();
297 let mut capturing = false;
298 for line in toml.split_inclusive('\n') {
299 let header = strip_trailing_comment(line.trim());
300 if header.starts_with('[') {
301 if header == "[workspace.dependencies]" {
302 capturing = true;
303 fragment.push_str("[dependencies]\n");
304 } else if let Some(name) = header
305 .strip_prefix("[workspace.dependencies.")
306 .and_then(|rest| rest.strip_suffix(']'))
307 {
308 capturing = true;
309 let _ = writeln!(fragment, "[dependencies.{name}]");
310 } else {
311 capturing = false;
312 }
313 continue;
314 }
315 if capturing {
316 fragment.push_str(line);
317 }
318 }
319 fragment
320}
321
322fn internal_pin_names(toml: &str) -> Result<Vec<String>> {
340 let fragment = extract_workspace_dependencies_fragment(toml);
341 if fragment.trim().is_empty() {
342 return Ok(Vec::new());
343 }
344 let value: toml::Value =
345 toml::from_str(&fragment).context("failed to parse `[workspace.dependencies]` as TOML")?;
346 let mut names: Vec<String> = value
347 .get("dependencies")
348 .and_then(|d| d.as_table())
349 .into_iter()
350 .flatten()
351 .filter(|(_, dep)| {
352 dep.as_table()
353 .is_some_and(|t| t.contains_key("path") && t.contains_key("version"))
354 })
355 .map(|(name, _)| name.clone())
356 .collect();
357 names.sort();
358 Ok(names)
359}
360
361fn rewrite_quoted_field(line: &str, key: &str, new_value: &str) -> Option<String> {
371 let is_ident = |c: char| c.is_ascii_alphanumeric() || c == '_' || c == '-';
372 let mut search_from = 0;
373 while let Some(rel) = line[search_from..].find(key) {
374 let key_start = search_from + rel;
375 let before_ok = key_start == 0 || !is_ident(line[..key_start].chars().next_back().unwrap());
376 let eq_pos = key_start
377 + key.len()
378 + (line[key_start + key.len()..].len()
379 - line[key_start + key.len()..].trim_start().len());
380 if before_ok && line[eq_pos..].starts_with('=') {
381 let after_eq = &line[eq_pos + 1..];
382 let ws_len = after_eq.len() - after_eq.trim_start().len();
383 let quote_pos = eq_pos + 1 + ws_len;
384 if let Some(quote_char) = line[quote_pos..]
385 .chars()
386 .next()
387 .filter(|c| *c == '"' || *c == '\'')
388 {
389 let value_begin = quote_pos + quote_char.len_utf8();
390 if let Some(end_rel) = line[value_begin..].find(quote_char) {
391 let value_end = value_begin + end_rel;
392 let mut out = String::with_capacity(line.len());
393 out.push_str(&line[..value_begin]);
394 out.push_str(new_value);
395 out.push_str(&line[value_end..]);
396 return Some(out);
397 }
398 }
399 }
400 search_from = key_start + key.len();
401 }
402 None
403}
404
405fn rewrite_workspace_dependency_pins(
420 toml: &str,
421 names: &[String],
422 new_version: &str,
423) -> Result<String> {
424 if names.is_empty() {
425 return Ok(toml.to_owned());
426 }
427 let mut out = String::with_capacity(toml.len() + names.len() * 8);
428 let mut in_flat_table = false;
429 let mut in_named_table: Option<String> = None;
430 let mut rewritten: std::collections::HashSet<String> = std::collections::HashSet::new();
431
432 for line in toml.split_inclusive('\n') {
433 let trimmed = line.trim();
434 if trimmed.starts_with('[') {
435 let header = strip_trailing_comment(trimmed);
436 in_flat_table = header == "[workspace.dependencies]";
437 in_named_table = header
438 .strip_prefix("[workspace.dependencies.")
439 .and_then(|rest| rest.strip_suffix(']'))
440 .map(str::to_owned);
441 out.push_str(line);
442 continue;
443 }
444
445 let key = trimmed.split('=').next().map(str::trim).map(unquote_key);
446
447 if in_flat_table {
448 if let Some(name) = key.and_then(|k| names.iter().find(|n| n.as_str() == k)) {
450 if let Some(rewritten_line) = rewrite_quoted_field(line, "version", new_version) {
451 rewritten.insert(name.clone());
452 out.push_str(&rewritten_line);
453 continue;
454 }
455 } else if let Some(name) = key.and_then(|k| {
456 k.strip_suffix(".version")
457 .and_then(|prefix| names.iter().find(|n| n.as_str() == prefix))
458 }) {
459 if let Some(rewritten_line) = rewrite_quoted_field(line, "version", new_version) {
464 rewritten.insert(name.clone());
465 out.push_str(&rewritten_line);
466 continue;
467 }
468 }
469 } else if let Some(table_name) = &in_named_table {
470 if key == Some("version") && names.iter().any(|n| n == table_name) {
471 if let Some(rewritten_line) = rewrite_quoted_field(line, "version", new_version) {
472 rewritten.insert(table_name.clone());
473 out.push_str(&rewritten_line);
474 continue;
475 }
476 }
477 }
478
479 out.push_str(line);
480 }
481
482 for name in names {
483 if !rewritten.contains(name) {
484 bail!(
485 "could not rewrite the `[workspace.dependencies]` version pin \
486 for `{name}` - its `version` field was not found in a shape \
487 this rewrite understands"
488 );
489 }
490 }
491 Ok(out)
492}
493
494fn verify_pins_rewritten(toml: &str, names: &[String], new_version: &str) -> Result<()> {
502 let fragment = extract_workspace_dependencies_fragment(toml);
503 let value: toml::Value = toml::from_str(&fragment)
504 .context("rewritten `[workspace.dependencies]` failed to parse")?;
505 let deps = value.get("dependencies").and_then(|d| d.as_table());
506 for name in names {
507 let actual = deps
508 .and_then(|d| d.get(name))
509 .and_then(|dep| dep.as_table())
510 .and_then(|t| t.get("version"))
511 .and_then(|v| v.as_str());
512 if actual != Some(new_version) {
513 bail!(
514 "the `[workspace.dependencies]` version pin for `{name}` did \
515 not end up at `{new_version}` after the rewrite"
516 );
517 }
518 }
519 Ok(())
520}
521
522pub fn rewrite_cargo_version(toml: &str, new_version: &str) -> Result<String> {
544 let rewritten = rewrite_table_version(toml, "[package]", new_version)
545 .or_else(|_| rewrite_table_version(toml, "[workspace.package]", new_version))
546 .context("no `version` field found under `[package]` or `[workspace.package]`")?;
547
548 let pin_names = internal_pin_names(&rewritten)?;
549 if pin_names.is_empty() {
550 return Ok(rewritten);
551 }
552
553 let rewritten = rewrite_workspace_dependency_pins(&rewritten, &pin_names, new_version)?;
554 verify_pins_rewritten(&rewritten, &pin_names, new_version)?;
555 Ok(rewritten)
556}
557
558fn version_in_table(toml: &str, table: &str) -> Option<String> {
560 let mut in_table = false;
561 for line in toml.lines() {
562 let trimmed = line.trim();
563 if trimmed.starts_with('[') {
564 in_table = trimmed == table;
565 continue;
566 }
567 if !in_table {
568 continue;
569 }
570 let mut parts = trimmed.splitn(2, '=');
571 let key = parts.next().map(str::trim);
572 let Some(value) = parts.next() else {
573 continue;
574 };
575 if key == Some("version") {
576 return Some(value.trim().trim_matches('"').to_owned());
577 }
578 }
579 None
580}
581
582pub(crate) fn current_version(toml: &str) -> Result<String> {
587 version_in_table(toml, "[package]")
588 .or_else(|| version_in_table(toml, "[workspace.package]"))
589 .context("no `version` field found under `[package]` or `[workspace.package]`")
590}
591
592async fn branch_version(repo: &Path, remote: &str, branch: &str) -> Option<String> {
596 let from_name = branch.strip_prefix("chore/release-v").map(str::to_owned);
597 let tracking = format!("refs/remotes/{remote}/{branch}");
600 let spec = format!("+refs/heads/{branch}:{tracking}");
601 let fetched = git::git_raw(repo, &["fetch", "--quiet", remote, &spec]).await;
602 if fetched.is_ok_and(|o| o.code == Some(0))
603 && let Ok(out) = git::git_raw(repo, &["show", &format!("{tracking}:Cargo.toml")]).await
604 && out.code == Some(0)
605 && let Ok(v) = current_version(&out.stdout)
606 {
607 return Some(v);
608 }
609 from_name
610}
611
612pub fn decision_prompt(
622 subject: &str,
623 instruction: &str,
624 diffstat: &str,
625 files: &[String],
626 current_version: &str,
627) -> String {
628 let mut s = format!(
629 "A pull request just merged into the base branch. Decide which digit \
630 of this project's `major.minor.patch` version this change earns, so \
631 a release bump can be opened for exactly it.\n\n\
632 Current version: {current_version}\n\n\
633 # Merge subject\n\n{subject}\n\n\
634 # The task that produced it\n\n{instruction}\n\n\
635 # Files changed ({} total)\n\n",
636 files.len()
637 );
638 const MAX_FILES: usize = 50;
639 for f in files.iter().take(MAX_FILES) {
640 let _ = writeln!(s, "- {f}");
641 }
642 if files.len() > MAX_FILES {
643 let _ = writeln!(s, "- ... and {} more", files.len() - MAX_FILES);
644 }
645 let _ = write!(s, "\n# Diffstat\n\n```\n{}\n```\n", diffstat.trim());
646
647 s.push_str(
648 "\n# How to decide\n\n\
649 This project is below version `1.0.0`. At that stage **`minor` is \
650 the digit that carries a breaking change** - do not spend `major` \
651 below `1.0.0`.\n\n\
652 A change is breaking, and earns `minor`, when it changes any of: \
653 the public API reachable from `src/lib.rs`, a CLI subcommand or \
654 flag, an HTTP API route or response shape, a configuration key, or \
655 the on-disk shape of persisted state.\n\n\
656 A user-visible new capability that breaks none of the above also \
657 earns `minor`.\n\n\
658 A fix, an internal refactor, or a dependency update earns `patch`.\n\n\
659 **When it is not obvious which digit applies, choose the larger \
660 one.** An oversized bump costs nothing; a breaking change shipped as \
661 `patch` breaks every downstream update that pins a range.\n\n\
662 # Output\n\n\
663 Reply with exactly one fenced JSON object and nothing that matters \
664 outside it:\n\n\
665 ```json\n\
666 {\"level\": \"major\" | \"minor\" | \"patch\", \"reason\": \"one line\"}\n\
667 ```\n",
668 );
669 let _ = write!(
671 s,
672 "\n{}\n\nThe `reason` goes into a GitHub pull request body, so write it \
673 in English.\n",
674 crate::prompt::GITHUB_ENGLISH_HEADING
675 );
676 s
677}
678
679#[derive(Debug, Clone, Serialize, Deserialize)]
695pub struct PendingBump {
696 pub target_version: String,
698 pub level: BumpLevel,
701 pub branch: String,
704 pub pr_url: String,
707}
708
709pub fn marker_path(home: &Path, repo: &Path) -> PathBuf {
713 let key = repo.to_string_lossy();
714 home.join("bump")
715 .join(format!("{:016x}.json", crate::rng::fnv1a(&key)))
716}
717
718pub fn read_marker(path: &Path) -> Option<PendingBump> {
722 let body = std::fs::read_to_string(path).ok()?;
723 serde_json::from_str(&body).ok()
724}
725
726pub fn write_marker(path: &Path, marker: &PendingBump) -> Result<()> {
730 if let Some(parent) = path.parent() {
731 std::fs::create_dir_all(parent).with_context(|| format!("create {}", parent.display()))?;
732 }
733 let body = serde_json::to_string_pretty(marker).context("serialize pending bump")?;
734 let tmp = path.with_extension("json.tmp");
735 std::fs::write(&tmp, &body).with_context(|| format!("write {}", tmp.display()))?;
736 std::fs::rename(&tmp, path).with_context(|| format!("replace {}", path.display()))?;
737 Ok(())
738}
739
740pub fn clear_marker(path: &Path) {
743 let _ = std::fs::remove_file(path);
744}
745
746#[derive(Debug, Clone, PartialEq, Eq)]
750pub enum Coalesce {
751 Proceed,
754 Skip {
756 target_version: String,
758 },
759}
760
761pub fn coalesce(pending: Option<&PendingBump>, current_version: &str) -> Result<Coalesce> {
763 let Some(pending) = pending else {
764 return Ok(Coalesce::Proceed);
765 };
766 let current = Version::parse(current_version)?;
767 let target = Version::parse(&pending.target_version)?;
768 if current >= target {
769 return Ok(Coalesce::Proceed);
770 }
771 Ok(Coalesce::Skip {
772 target_version: pending.target_version.clone(),
773 })
774}
775
776#[derive(Debug, Clone, Copy, PartialEq, Eq)]
778pub enum PendingAction {
779 AlreadyCovered,
782 Escalate,
785}
786
787pub fn pending_action(pending_level: BumpLevel, decision_level: BumpLevel) -> PendingAction {
796 if decision_level.severity() > pending_level.severity() {
797 PendingAction::Escalate
798 } else {
799 PendingAction::AlreadyCovered
800 }
801}
802
803fn parse_pr_state(json: &str) -> Result<bool> {
805 #[derive(Deserialize)]
806 struct State {
807 state: String,
808 }
809 let parsed: State =
810 serde_json::from_str(json).context("parse `gh pr view --json state` output")?;
811 Ok(parsed.state.eq_ignore_ascii_case("OPEN"))
812}
813
814async fn pr_is_open(repo: &Path, pr_url: &str) -> Result<bool> {
827 let out = tokio::process::Command::new("gh")
828 .args(["pr", "view", pr_url, "--json", "state"])
829 .current_dir(repo)
830 .quiet()
831 .stdin(std::process::Stdio::null())
832 .output()
833 .await
834 .context("spawn gh pr view")?;
835 if !out.status.success() {
836 bail!(
837 "gh pr view {pr_url}: {}",
838 String::from_utf8_lossy(&out.stderr).trim()
839 );
840 }
841 parse_pr_state(&String::from_utf8_lossy(&out.stdout))
842}
843
844const LOCK_STALE_AFTER: Duration = Duration::from_secs(30 * 60);
852
853struct MarkerLock {
865 path: PathBuf,
866}
867
868impl MarkerLock {
869 fn acquire(marker: &Path) -> Result<Option<Self>> {
873 let path = marker.with_extension("lock");
874 if let Some(parent) = path.parent() {
875 std::fs::create_dir_all(parent)
876 .with_context(|| format!("create {}", parent.display()))?;
877 }
878 if Self::try_create(&path)? {
879 return Ok(Some(Self { path }));
880 }
881 if Self::is_stale(&path) {
882 let _ = std::fs::remove_file(&path);
883 if Self::try_create(&path)? {
884 return Ok(Some(Self { path }));
885 }
886 }
887 Ok(None)
888 }
889
890 fn try_create(path: &Path) -> Result<bool> {
891 match std::fs::OpenOptions::new()
892 .write(true)
893 .create_new(true)
894 .open(path)
895 {
896 Ok(_) => Ok(true),
897 Err(e) if e.kind() == std::io::ErrorKind::AlreadyExists => Ok(false),
898 Err(e) => Err(e).with_context(|| format!("create {}", path.display())),
899 }
900 }
901
902 fn is_stale(path: &Path) -> bool {
903 std::fs::metadata(path)
904 .and_then(|m| m.modified())
905 .ok()
906 .and_then(|m| m.elapsed().ok())
907 .is_some_and(|age| age >= LOCK_STALE_AFTER)
908 }
909}
910
911impl Drop for MarkerLock {
912 fn drop(&mut self) {
913 let _ = std::fs::remove_file(&self.path);
914 }
915}
916
917const LOCK_POLL: Duration = Duration::from_secs(5);
919
920const LOCK_WAIT_CEILING: Duration = Duration::from_secs(25 * 60);
933
934async fn wait_for_marker_lock(marker: &Path) -> Result<Option<MarkerLock>> {
937 wait_for_marker_lock_with(marker, LOCK_POLL, LOCK_WAIT_CEILING).await
938}
939
940async fn wait_for_marker_lock_with(
944 marker: &Path,
945 poll: Duration,
946 ceiling: Duration,
947) -> Result<Option<MarkerLock>> {
948 let mut waited = Duration::ZERO;
949 loop {
950 if let Some(lock) = MarkerLock::acquire(marker)? {
951 return Ok(Some(lock));
952 }
953 if waited >= ceiling {
954 return Ok(None);
955 }
956 tokio::time::sleep(poll).await;
957 waited += poll;
958 }
959}
960
961fn level_between(from: Version, to: Version) -> Option<BumpLevel> {
969 if to.major != from.major {
970 Some(BumpLevel::Major)
971 } else if to.minor != from.minor {
972 Some(BumpLevel::Minor)
973 } else if to.patch != from.patch {
974 Some(BumpLevel::Patch)
975 } else {
976 None
977 }
978}
979
980fn parse_open_release_pr(json: &str) -> Result<Option<(String, String)>> {
983 #[derive(Deserialize)]
984 struct Pr {
985 url: String,
986 #[serde(rename = "headRefName")]
987 head_ref_name: String,
988 }
989 let list: Vec<Pr> =
990 serde_json::from_str(json).context("parse `gh pr list --json url,headRefName` output")?;
991 Ok(list
992 .into_iter()
993 .find(|p| p.head_ref_name.starts_with("chore/release-v"))
994 .map(|p| (p.head_ref_name, p.url)))
995}
996
997pub(crate) fn parse_open_release_prs(json: &str) -> Result<Vec<(String, String)>> {
1000 #[derive(Deserialize)]
1001 struct Pr {
1002 url: String,
1003 #[serde(rename = "headRefName")]
1004 head_ref_name: String,
1005 }
1006 let list: Vec<Pr> =
1007 serde_json::from_str(json).context("parse `gh pr list --json url,headRefName` output")?;
1008 Ok(list
1009 .into_iter()
1010 .filter(|p| p.head_ref_name.starts_with("chore/release-v"))
1011 .map(|p| (p.head_ref_name, p.url))
1012 .collect())
1013}
1014
1015pub(crate) async fn list_open_release_prs(repo: &Path) -> Result<Vec<(String, String)>> {
1017 let out = tokio::process::Command::new("gh")
1018 .args([
1019 "pr",
1020 "list",
1021 "--state",
1022 "open",
1023 "--limit",
1024 "100",
1025 "--json",
1026 "url,headRefName",
1027 ])
1028 .current_dir(repo)
1029 .env_remove("GH_REPO")
1030 .quiet()
1031 .stdin(std::process::Stdio::null())
1032 .output()
1033 .await
1034 .context("spawn gh pr list")?;
1035 if !out.status.success() {
1036 bail!(
1037 "gh pr list: {}",
1038 String::from_utf8_lossy(&out.stderr).trim()
1039 );
1040 }
1041 parse_open_release_prs(&String::from_utf8_lossy(&out.stdout))
1042}
1043
1044async fn find_open_release_pr(repo: &Path) -> Result<Option<(String, String)>> {
1059 let out = tokio::process::Command::new("gh")
1060 .args(["pr", "list", "--state", "open", "--json", "url,headRefName"])
1061 .current_dir(repo)
1062 .quiet()
1063 .stdin(std::process::Stdio::null())
1064 .output()
1065 .await
1066 .context("spawn gh pr list")?;
1067 if !out.status.success() {
1068 bail!(
1069 "gh pr list: {}",
1070 String::from_utf8_lossy(&out.stderr).trim()
1071 );
1072 }
1073 parse_open_release_pr(&String::from_utf8_lossy(&out.stdout))
1074}
1075
1076pub async fn after_merge(state: &mut RunState, pr_url: &str) -> Result<()> {
1096 after_merge_at(state, pr_url, None, None).await
1097}
1098
1099#[derive(Debug, Default)]
1101struct Progress {
1102 version: Option<String>,
1104 pending_pr: Option<String>,
1106}
1107
1108fn notice_for_failure(progress: &Progress, err: &anyhow::Error) -> (Option<String>, String) {
1114 let chain = format!("{err:#}");
1115 let first = chain.lines().next().unwrap_or_default().trim();
1116 (progress.version.clone(), first.to_owned())
1117}
1118
1119async fn base_has_cargo_toml(repo: &Path, remote: &str, base: &str) -> Result<bool> {
1125 let out = git::git(
1126 repo,
1127 &[
1128 "ls-tree",
1129 "--name-only",
1130 &format!("{remote}/{base}"),
1131 "--",
1132 "Cargo.toml",
1133 ],
1134 )
1135 .await
1136 .context("look for Cargo.toml on the base branch")?;
1137 Ok(!out.trim().is_empty())
1138}
1139
1140async fn after_merge_at(
1144 state: &mut RunState,
1145 pr_url: &str,
1146 home: Option<&Path>,
1147 store: Option<&Notices>,
1148) -> Result<()> {
1149 let mut progress = Progress::default();
1150 let result = after_merge_inner(state, pr_url, home, &mut progress).await;
1151 if let Err(e) = &result {
1152 let (version, reason) = notice_for_failure(&progress, e);
1153 let pending = progress.pending_pr.as_deref();
1154 let store = store.cloned().unwrap_or_else(Notices::open);
1155 report_problem_in(
1156 state,
1157 &store,
1158 pending,
1159 version.as_deref(),
1160 &reason,
1161 pending.is_some(),
1162 )
1163 .await;
1164 }
1165 result
1166}
1167
1168async fn after_merge_inner(
1169 state: &mut RunState,
1170 pr_url: &str,
1171 home: Option<&Path>,
1172 progress: &mut Progress,
1173) -> Result<()> {
1174 if !state.config.merge.release_bump {
1175 return Ok(());
1176 }
1177 let Some(winner) = state.winner().cloned() else {
1178 return Ok(());
1179 };
1180 let repo = state.repo.clone();
1181 let base = state.base_branch.clone();
1182 let remote = state.config.merge.remote.clone();
1183
1184 let files = git::changed_files(&winner.worktree, &base, &winner.branch)
1185 .await
1186 .unwrap_or_default();
1187 if is_release_only(&files) {
1188 state.event(
1189 "bump",
1190 "the merged change touches only the release manifest; not treating it as a trigger",
1191 );
1192 return Ok(());
1193 }
1194
1195 git::fetch(&repo, &remote, &base).await.ok();
1198 if !base_has_cargo_toml(&repo, &remote, &base).await? {
1199 state.event(
1200 "bump",
1201 "release bump: no Cargo.toml on the base branch; release bumps are Rust-only, skipping",
1202 );
1203 return Ok(());
1204 }
1205
1206 let marker = marker_path(&home.map_or_else(run::home, Path::to_path_buf), &repo);
1207 let Some(_lock) = wait_for_marker_lock(&marker).await? else {
1214 state.event(
1215 "bump",
1216 "another release bump decision held the lock past the wait ceiling; skipping this round",
1217 );
1218 return Ok(());
1219 };
1220
1221 git::fetch(&repo, &remote, &base).await.ok();
1222 let cargo_toml = git::git(&repo, &["show", &format!("{remote}/{base}:Cargo.toml")])
1223 .await
1224 .context("read Cargo.toml from the base branch")?;
1225 let base_version = current_version(&cargo_toml)?;
1226
1227 let mut pending = read_marker(&marker);
1228 if let Some(p) = &pending {
1229 match coalesce(Some(p), &base_version)? {
1230 Coalesce::Proceed => {
1231 clear_marker(&marker);
1234 pending = None;
1235 }
1236 Coalesce::Skip { target_version } => {
1237 if !pr_is_open(&repo, &p.pr_url).await.unwrap_or(true) {
1238 state.event(
1239 "bump",
1240 format!(
1241 "the pending release bump to v{target_version} ({}) is no longer \
1242 open; treating it as abandoned",
1243 p.pr_url
1244 ),
1245 );
1246 clear_marker(&marker);
1247 pending = None;
1248 }
1249 }
1254 }
1255 }
1256
1257 if pending.is_none() {
1258 if let Ok(Some((branch, url))) = find_open_release_pr(&repo).await
1263 && let Some(target) = branch_version(&repo, &remote, &branch)
1264 .await
1265 .and_then(|v| Version::parse(&v).ok())
1266 {
1267 let base_parsed = Version::parse(&base_version)?;
1268 if target > base_parsed
1269 && let Some(level) = level_between(base_parsed, target)
1270 {
1271 let adopted = PendingBump {
1272 target_version: target.to_string(),
1273 level,
1274 branch,
1275 pr_url: url,
1276 };
1277 let _ = write_marker(&marker, &adopted);
1280 pending = Some(adopted);
1281 }
1282 }
1283 }
1284
1285 progress.pending_pr = pending.as_ref().map(|p| p.pr_url.clone());
1286 let title = pr_title(&repo, pr_url).await.unwrap_or_default();
1287 let subject = land::merge_subject(
1288 crate::graph::landing_title(state, &title),
1289 &crate::graph::landing_subject_source(state),
1290 );
1291 let stat = git::diff_stat(&winner.worktree, &base, &winner.branch)
1292 .await
1293 .unwrap_or_default();
1294 let prompt = decision_prompt(&subject, &state.instruction, &stat, &files, &base_version);
1295
1296 let spec: AgentSpec = agent::pick(
1302 &state.config.agents,
1303 crate::config::primary(state.config.roles.chatter.as_ref()),
1304 &agent::installed,
1305 )
1306 .context("choose an agent for the release-bump decision")?;
1307 let mut seat = SeatState::new("bump", &spec.id, state.seed);
1308 let artifacts = agent::artifacts_dir(&state.dir());
1309 let out = agent::invoke(
1310 &spec,
1311 &mut seat,
1312 &Invocation {
1313 cwd: &repo,
1314 prompt: &prompt,
1315 timeout: DECISION_TIMEOUT,
1316 allow_write: false,
1319 unsandboxed: false,
1320 sessions: false,
1321 artifacts: &artifacts,
1322 stem: "bump-decision",
1323 run: &state.id,
1324 node: "bump",
1325 cache_dir: state.config.cache_dir().as_deref(),
1326 attachments: &[],
1327 writable: &[],
1328 },
1329 )
1330 .await
1331 .context("ask an agent how big the merged change was")?;
1332 if !out.usable() {
1333 bail!(
1334 "the release-bump decision produced nothing usable (exit {:?}, timed out: {})",
1335 out.exit_code,
1336 out.timed_out
1337 );
1338 }
1339 let mut decision = parse_decision(&out.text).context("parse the release-bump decision")?;
1340 let mut violations = crate::github_text::check("", &decision.reason);
1341 violations.retain(|v| *v != crate::github_text::Violation::SensitiveData);
1343 if violations.is_empty() {
1344 decision.reason = crate::scrub::scrub(&decision.reason, &crate::scrub::Identity::current());
1345 }
1346 if state.config.graph.github_text_guard && !violations.is_empty() {
1347 state.event(
1348 "github-text",
1349 format!("release reason rejected: {violations:?}; requesting one rewrite"),
1350 );
1351 let rewrite = format!(
1352 "{prompt}\n\nYour release reason failed the GitHub text gate: {violations:?}. Return the same decision JSON with an English reason containing no local identity or secrets. Previous reason: {}",
1353 decision.reason
1354 );
1355 let retry = agent::invoke(
1356 &spec,
1357 &mut seat,
1358 &Invocation {
1359 cwd: &repo,
1360 prompt: &rewrite,
1361 timeout: crate::graph::retry_budget(DECISION_TIMEOUT, true),
1362 allow_write: false,
1363 unsandboxed: false,
1364 sessions: false,
1365 artifacts: &artifacts,
1366 stem: "bump-rewrite",
1367 run: &state.id,
1368 node: "bump",
1369 cache_dir: state.config.cache_dir().as_deref(),
1370 attachments: &[],
1371 writable: &[],
1372 },
1373 )
1374 .await;
1375 let reason = retry
1376 .ok()
1377 .filter(|o| o.usable())
1378 .and_then(|o| parse_decision(&o.text).ok())
1379 .filter(|d| {
1380 d.level == decision.level && crate::github_text::check("", &d.reason).is_empty()
1381 })
1382 .map(|d| d.reason);
1383 if let Some(reason) = reason {
1384 decision.reason = reason;
1385 state.event("github-text", "release reason rewrite passed");
1386 } else {
1387 decision.reason = "The merged change requires a release.".to_owned();
1388 state.event(
1389 "github-text",
1390 "release reason rewrite unavailable or rejected; using neutral text",
1391 );
1392 }
1393 }
1394
1395 if let Some(p) = pending {
1396 return match pending_action(p.level, decision.level) {
1397 PendingAction::AlreadyCovered => {
1398 state.event(
1399 "bump",
1400 format!(
1401 "a release bump to v{} ({}) already covers at least a {} change; not \
1402 opening another",
1403 p.target_version,
1404 p.pr_url,
1405 decision.level.as_str()
1406 ),
1407 );
1408 Ok(())
1409 }
1410 PendingAction::Escalate => {
1411 progress.version = Some(
1412 Version::parse(&base_version)?
1413 .bump(decision.level)
1414 .to_string(),
1415 );
1416 escalate_pending(state, &repo, &remote, &p, &decision, &base_version, &marker).await
1417 }
1418 };
1419 }
1420
1421 let next = Version::parse(&base_version)?
1422 .bump(decision.level)
1423 .to_string();
1424 progress.version = Some(next.clone());
1425 let branch = format!("chore/release-v{next}");
1426 let worktree = state.dir().join("bump");
1427 let (shared, branch_ref, next_ref, decision_ref) = (&mut *state, &branch, &next, &decision);
1428 let (pr_url_opened, outcome) =
1429 release_attempt(
1430 &repo,
1431 &remote,
1432 &base,
1433 &worktree,
1434 &branch,
1435 |head| {
1436 let repo = repo.clone();
1437 async move { gh_open_pr_for_head(&repo, &head).await }
1438 },
1439 |wt| async move {
1440 open_bump_pr(shared, &wt, branch_ref, next_ref, decision_ref, pr_url).await
1441 },
1442 )
1443 .await?;
1444 let local = outcome == AutomergeOutcome::LocalGate;
1445 let (automerge_warning, merged_detail) = match outcome {
1446 AutomergeOutcome::Enabled | AutomergeOutcome::LocalGate => (None, None),
1447 AutomergeOutcome::MergedDirectly { detail } => (None, Some(detail)),
1448 AutomergeOutcome::Failed { reason } => (Some(reason), None),
1449 };
1450
1451 let marker_write = write_marker(
1460 &marker,
1461 &PendingBump {
1462 target_version: next.clone(),
1463 level: decision.level,
1464 branch,
1465 pr_url: pr_url_opened.clone(),
1466 },
1467 );
1468 state.event(
1469 "bump",
1470 format!(
1471 "opened a {} release bump to v{next} ({}): {pr_url_opened}",
1472 decision.level.as_str(),
1473 decision.reason
1474 ),
1475 );
1476 if let Err(e) = marker_write {
1477 state.event(
1478 "bump",
1479 format!(
1480 "could not record the pending release bump marker for v{next}: {e:#}; a later \
1481 merge may open a duplicate pull request if it cannot find {pr_url_opened} on \
1482 the forge either"
1483 ),
1484 );
1485 }
1486 state.release_bump = Some(run::ReleaseBump {
1487 pr_url: Some(pr_url_opened.clone()),
1488 version: Some(next.clone()),
1489 automerge_enabled: automerge_warning.is_none() && merged_detail.is_none() && !local,
1490 merged_directly: merged_detail.is_some(),
1491 local,
1492 ..run::ReleaseBump::default()
1493 });
1494 if let Some(detail) = merged_detail {
1495 clear_marker(&marker);
1498 state.event("bump", format!("merged v{next} directly: {detail}"));
1499 }
1500 if let Some(warning) = automerge_warning {
1501 state.event(
1502 "bump",
1503 format!("could not enable automerge on {pr_url_opened}: {warning}; merge it by hand"),
1504 );
1505 report_problem(state, Some(&pr_url_opened), Some(&next), &warning).await;
1506 }
1507 Ok(())
1508}
1509
1510pub const NOTICE_NODE: &str = "release-bump";
1515
1516fn automerge_hint(reason: &str) -> &'static str {
1523 let r = reason.to_lowercase();
1524 if is_clean_status_refusal(reason) {
1525 "merge the release pull request by hand; CI is already green"
1526 } else if r.contains("enablepullrequestautomerge") || r.contains("protected branch rules") {
1527 "merge the release pull request by hand, and enable branch protection with required \
1528 status checks on the base branch so automerge can work next time"
1529 } else {
1530 "merge the release pull request by hand"
1531 }
1532}
1533
1534fn automerge_failure_comment(reason: &str) -> String {
1536 format!(
1537 "magi could not enable automerge on this pull request: {reason}\n\n\
1538 Action required: {}. Until then the release does not happen.",
1539 automerge_hint(reason)
1540 )
1541}
1542
1543#[cfg(test)]
1551fn surface_problem(
1552 state: &mut RunState,
1553 store: &Notices,
1554 pr_url: Option<&str>,
1555 version: Option<&str>,
1556 reason: &str,
1557) -> Result<(Notice, Option<String>)> {
1558 surface_problem_in(state, store, pr_url, version, reason, false)
1559}
1560
1561fn surface_problem_in(
1565 state: &mut RunState,
1566 store: &Notices,
1567 pr_url: Option<&str>,
1568 version: Option<&str>,
1569 reason: &str,
1570 pending: bool,
1571) -> Result<(Notice, Option<String>)> {
1572 let action = if let (true, Some(url)) = (pending, pr_url) {
1573 let ja = crate::lang::is_japanese(&state.config.graph.language);
1574 let first = reason.lines().next().filter(|l| !l.is_empty());
1575 let cause = first.map(|l| format!(" ({l})")).unwrap_or_default();
1576 if ja {
1577 let target = version.map(|v| format!(" v{v}")).unwrap_or_default();
1578 format!(
1579 "既存のリリース PR {url} を{target}へ更新できませんでした{cause}。PR を手で更新してください"
1580 )
1581 } else {
1582 let target = version.map(|v| format!(" to v{v}")).unwrap_or_default();
1583 format!(
1584 "the pending release pull request {url} could not be updated{target}{cause}; update it by hand"
1585 )
1586 }
1587 } else if pr_url.is_some() {
1588 automerge_hint(reason).to_owned()
1589 } else {
1590 let ja = crate::lang::is_japanese(&state.config.graph.language);
1591 let first = reason.lines().next().filter(|l| !l.is_empty());
1592 if ja {
1593 let target = version.map(|v| format!(" (v{v})")).unwrap_or_default();
1594 let cause = first.map(|l| format!(" ({l})")).unwrap_or_default();
1595 format!(
1596 "リリースバンプ{target}は実行されませんでした{cause}。リリース PR を手で開いてください"
1597 )
1598 } else {
1599 let target = version.map(|v| format!(" to v{v}")).unwrap_or_default();
1600 let cause = first.map(|l| format!(" ({l})")).unwrap_or_default();
1601 format!(
1602 "the release bump{target} did not run{cause}; open the release pull request by hand"
1603 )
1604 }
1605 };
1606 let record = state.release_bump.get_or_insert_with(Default::default);
1607 record.pr_url = pr_url.map(str::to_owned).or(record.pr_url.take());
1608 record.version = version.map(str::to_owned).or(record.version.take());
1609 record.automerge_enabled = false;
1610 record.problem = Some(reason.to_owned());
1611 record.action_required = Some(action.clone());
1612
1613 let mut notice = Notice::error(
1614 &format!("release-bump:{}", state.id),
1615 format!(
1616 "Run {} merged, but its release step failed: {action}.",
1617 state.id
1618 ),
1619 );
1620 notice = match pr_url {
1621 Some(url) => notice.link(Link::Url {
1622 url: url.to_owned(),
1623 }),
1624 None => notice.link(Link::Run {
1625 id: state.id.clone(),
1626 }),
1627 };
1628 let notice = store
1629 .raise(notice)
1630 .context("raise the release-bump notification")?;
1631 state.event("bump", format!("needs attention: {action}"));
1632 let comment = pr_url
1633 .filter(|_| !pending)
1634 .map(|_| automerge_failure_comment(reason));
1635 Ok((notice, comment))
1636}
1637
1638pub async fn report_problem(
1643 state: &mut RunState,
1644 pr_url: Option<&str>,
1645 version: Option<&str>,
1646 reason: &str,
1647) {
1648 report_problem_in(state, &Notices::open(), pr_url, version, reason, false).await;
1649}
1650
1651async fn report_problem_in(
1653 state: &mut RunState,
1654 store: &Notices,
1655 pr_url: Option<&str>,
1656 version: Option<&str>,
1657 reason: &str,
1658 pending: bool,
1659) {
1660 match surface_problem_in(state, store, pr_url, version, reason, pending) {
1661 Ok((notice, comment)) => {
1662 if let (Some(url), Some(body)) = (pr_url, comment)
1663 && let Err(e) = gh_pr_comment(state, url, &body).await
1664 {
1665 state.event("bump", format!("could not comment on {url}: {e:#}"));
1666 }
1667 let summary = match pr_url {
1670 Some(url) if pending => format!("Release PR could not be updated: {url}"),
1671 Some(url) => format!("Release PR needs a human: {url}"),
1672 None if crate::lang::is_japanese(&state.config.graph.language) => {
1673 "リリースバンプが実行されませんでした".to_owned()
1674 }
1675 None => "Release bump did not run".to_owned(),
1676 };
1677 let q = ask::Question::new(
1678 state.id.clone(),
1679 NOTICE_NODE.to_owned(),
1680 "bump".to_owned(),
1681 summary,
1682 notice.message.clone(),
1683 Vec::new(),
1684 );
1685 if let Err(e) = ask::notify(&state.config.notify, &q).await {
1686 tracing::warn!(
1687 "could not notify about the release bump of {}: {e:#}",
1688 state.id
1689 );
1690 }
1691 }
1692 Err(e) => state.event("bump", format!("could not raise a notice: {e:#}")),
1693 }
1694}
1695
1696pub(crate) async fn gh_pr_comment(state: &mut RunState, pr_url: &str, body: &str) -> Result<()> {
1697 let (_, body) = crate::github_text::prepare(state, "", body);
1698 let cwd = &state.repo;
1699 let out = tokio::process::Command::new("gh")
1700 .args(["pr", "comment", pr_url, "--body", &body])
1701 .current_dir(cwd)
1702 .quiet()
1703 .stdin(std::process::Stdio::null())
1704 .output()
1705 .await
1706 .context("spawn gh pr comment")?;
1707 if out.status.success() {
1708 Ok(())
1709 } else {
1710 bail!(
1711 "gh pr comment: {}",
1712 String::from_utf8_lossy(&out.stderr).trim()
1713 )
1714 }
1715}
1716
1717async fn escalate_pending(
1726 state: &mut RunState,
1727 repo: &Path,
1728 remote: &str,
1729 pending: &PendingBump,
1730 decision: &BumpDecision,
1731 base_version: &str,
1732 marker: &Path,
1733) -> Result<()> {
1734 let next = Version::parse(base_version)?
1735 .bump(decision.level)
1736 .to_string();
1737 let worktree = state.dir().join("bump");
1738 git::worktree_remove(repo, &worktree).await.ok();
1739 let checked_out = git::git_raw(
1740 repo,
1741 &[
1742 "worktree",
1743 "add",
1744 "--force",
1745 &worktree.to_string_lossy(),
1746 &pending.branch,
1747 ],
1748 )
1749 .await?;
1750 if !checked_out.ok() {
1751 bail!(
1752 "checking out the pending release branch {} failed: {}",
1753 pending.branch,
1754 checked_out.stderr
1755 );
1756 }
1757
1758 let pushed: Result<()> = async {
1763 let cargo_toml_path = worktree.join("Cargo.toml");
1764 let toml = tokio::fs::read_to_string(&cargo_toml_path)
1765 .await
1766 .with_context(|| format!("read {}", cargo_toml_path.display()))?;
1767 let rewritten = rewrite_cargo_version(&toml, &next)?;
1768 tokio::fs::write(&cargo_toml_path, rewritten)
1769 .await
1770 .with_context(|| format!("write {}", cargo_toml_path.display()))?;
1771 sync_lockfile(&worktree, state.config.cache_dir().as_deref()).await?;
1772 let committed = git::commit_all(
1773 &worktree,
1774 &format!(
1775 "chore: release v{next} (supersedes v{})",
1776 pending.target_version
1777 ),
1778 )
1779 .await
1780 .context("commit the escalated version bump")?;
1781 if !committed {
1782 bail!("escalating the version bump left nothing to commit");
1783 }
1784 let pushed = git::push(&worktree, remote, &pending.branch).await?;
1785 if !pushed.ok() {
1786 bail!("pushing {} failed: {}", pending.branch, pushed.stderr);
1787 }
1788 Ok(())
1789 }
1790 .await;
1791 if let Err(e) = pushed {
1792 git::worktree_remove(repo, &worktree).await.ok();
1793 return Err(e);
1794 }
1795
1796 let (title, _) = crate::github_text::prepare(
1800 state,
1801 &format!("chore: release v{next} ({} bump)", decision.level.as_str()),
1802 "",
1803 );
1804 let title_warning = match gh_pr_edit_title(&worktree, &pending.pr_url, &title).await {
1805 Ok(()) => None,
1806 Err(e) => Some(e.to_string()),
1807 };
1808 git::worktree_remove(repo, &worktree).await.ok();
1809
1810 let marker_write = write_marker(
1811 marker,
1812 &PendingBump {
1813 target_version: next.clone(),
1814 level: decision.level,
1815 branch: pending.branch.clone(),
1816 pr_url: pending.pr_url.clone(),
1817 },
1818 );
1819 state.event(
1820 "bump",
1821 format!(
1822 "escalated the pending release bump from v{} to v{next} to a {} change ({}): {}",
1823 pending.target_version,
1824 decision.level.as_str(),
1825 decision.reason,
1826 pending.pr_url
1827 ),
1828 );
1829 if let Err(e) = marker_write {
1830 state.event(
1831 "bump",
1832 format!(
1833 "could not update the pending release bump marker to v{next}: {e:#}; a later \
1834 merge may misjudge whether it is already covered"
1835 ),
1836 );
1837 }
1838 if let Some(warning) = title_warning {
1839 state.event(
1840 "bump",
1841 format!(
1842 "pushed v{next} to {} but could not update its title: {warning}; the squashed \
1843 subject may still read the superseded version",
1844 pending.pr_url
1845 ),
1846 );
1847 }
1848 Ok(())
1849}
1850
1851async fn gh_open_pr_for_head(repo: &Path, branch: &str) -> Result<bool> {
1854 let out = tokio::process::Command::new("gh")
1855 .args([
1856 "pr", "list", "--head", branch, "--state", "open", "--json", "url",
1857 ])
1858 .current_dir(repo)
1859 .quiet()
1860 .stdin(std::process::Stdio::null())
1861 .output()
1862 .await
1863 .context("spawn gh pr list")?;
1864 if !out.status.success() {
1865 bail!(
1866 "gh pr list --head {branch}: {}",
1867 String::from_utf8_lossy(&out.stderr).trim()
1868 );
1869 }
1870 let prs: Vec<serde_json::Value> = serde_json::from_slice(&out.stdout)
1871 .with_context(|| format!("parse the pull requests headed by {branch}"))?;
1872 Ok(!prs.is_empty())
1873}
1874
1875async fn release_attempt<T, F, Fut, P, PFut>(
1884 repo: &Path,
1885 remote: &str,
1886 base: &str,
1887 worktree: &Path,
1888 branch: &str,
1889 open_pr: P,
1890 fill: F,
1891) -> Result<T>
1892where
1893 F: FnOnce(PathBuf) -> Fut,
1894 Fut: std::future::Future<Output = Result<T>>,
1895 P: Fn(String) -> PFut,
1896 PFut: std::future::Future<Output = Result<bool>>,
1897{
1898 let start = format!("{remote}/{base}");
1899 git::worktree_remove(repo, worktree).await.ok();
1900 let mut retried = false;
1901 if git::branch_exists(repo, branch).await? {
1902 reclaim_stale_branch(repo, remote, &start, branch, &open_pr).await?;
1903 retried = true;
1904 }
1905 loop {
1906 if let Err(e) = git::git(repo, &["branch", branch, &start]).await {
1911 let e = e.context("create the release branch");
1912 if !git::branch_exists(repo, branch).await.unwrap_or(false) {
1913 return Err(e);
1914 }
1915 if retried {
1917 return Err(anyhow!(
1918 "{e:#}; left {branch} in place: it is not one this attempt created"
1919 ));
1920 }
1921 retried = true;
1922 if let Err(r) = reclaim_stale_branch(repo, remote, &start, branch, &open_pr).await {
1923 return Err(anyhow!("{r:#} (after: {e:#})"));
1924 }
1925 continue;
1926 }
1927 if let Some(parent) = worktree.parent() {
1928 tokio::fs::create_dir_all(parent).await.ok();
1929 }
1930 let path = worktree.to_string_lossy();
1931 if let Err(e) = git::git(repo, &["worktree", "add", &path, branch]).await {
1932 let e = e.context("create the release-bump worktree");
1933 return Err(discard_attempt(repo, remote, worktree, branch, e).await);
1934 }
1935 break;
1936 }
1937 match fill(worktree.to_path_buf()).await {
1938 Ok(v) => {
1939 git::worktree_remove(repo, worktree).await.ok();
1942 Ok(v)
1943 }
1944 Err(e) => Err(discard_attempt(repo, remote, worktree, branch, e).await),
1945 }
1946}
1947
1948async fn discard_attempt(
1950 repo: &Path,
1951 remote: &str,
1952 worktree: &Path,
1953 branch: &str,
1954 cause: anyhow::Error,
1955) -> anyhow::Error {
1956 git::worktree_remove(repo, worktree).await.ok();
1957 if !git::branch_exists(repo, branch).await.unwrap_or(false) {
1958 return cause;
1959 }
1960 let note = match git::remote_has_branch(repo, remote, branch).await {
1963 Ok(false) => match git::branch_delete(repo, branch).await {
1964 Ok(true) => return cause,
1965 _ => format!("could not delete the local branch {branch}"),
1966 },
1967 Ok(true) => format!("left {branch} in place: it was pushed to {remote}"),
1968 Err(e) => format!(
1969 "left {branch} in place: could not tell whether it was pushed to {remote} ({e:#})"
1970 ),
1971 };
1972 anyhow!("{cause:#}; {note}")
1973}
1974
1975async fn reclaim_stale_branch<P, PFut>(
1980 repo: &Path,
1981 remote: &str,
1982 start: &str,
1983 branch: &str,
1984 open_pr: &P,
1985) -> Result<()>
1986where
1987 P: Fn(String) -> PFut,
1988 PFut: std::future::Future<Output = Result<bool>>,
1989{
1990 match git::remote_has_branch(repo, remote, branch).await {
1991 Ok(false) => {}
1992 Ok(true) => bail!("the branch {branch} already exists and is on {remote}; left alone"),
1993 Err(e) => bail!(
1994 "the branch {branch} already exists and could not check whether {remote} has it ({e:#}); left alone"
1995 ),
1996 }
1997 match open_pr(branch.to_string()).await {
1998 Ok(false) => {}
1999 Ok(true) => {
2000 bail!("the branch {branch} already exists and has an open pull request; left alone")
2001 }
2002 Err(e) => bail!(
2003 "the branch {branch} already exists and could not check for an open pull request \
2004 ({e:#}); left alone"
2005 ),
2006 }
2007 match git::commits_ahead(repo, start, branch).await {
2008 Ok(0) => {}
2009 Ok(n) => bail!(
2010 "the branch {branch} already exists with {n} commit(s) not in {start}; left alone"
2011 ),
2012 Err(e) => bail!(
2013 "the branch {branch} already exists and could not compare it with {start} ({e:#}); \
2014 left alone"
2015 ),
2016 }
2017 if let Some(held) = git::worktree_holding(repo, branch).await? {
2018 let same = |a: &Path, b: &Path| match (a.canonicalize(), b.canonicalize()) {
2019 (Ok(a), Ok(b)) => a == b,
2020 _ => a == b,
2021 };
2022 if same(&held, repo) {
2023 bail!(
2024 "the branch {branch} already exists and is checked out in the main checkout; left alone"
2025 );
2026 }
2027 git::worktree_remove(repo, &held).await.ok();
2028 }
2029 if !git::branch_delete(repo, branch).await? {
2030 bail!("the branch {branch} already exists and could not be deleted; left alone");
2031 }
2032 Ok(())
2033}
2034
2035async fn open_bump_pr(
2041 state: &mut RunState,
2042 worktree: &Path,
2043 branch: &str,
2044 next_version: &str,
2045 decision: &BumpDecision,
2046 source_pr_url: &str,
2047) -> Result<(String, AutomergeOutcome)> {
2048 let cargo_toml_path = worktree.join("Cargo.toml");
2049 let toml = tokio::fs::read_to_string(&cargo_toml_path)
2050 .await
2051 .with_context(|| format!("read {}", cargo_toml_path.display()))?;
2052 let rewritten = rewrite_cargo_version(&toml, next_version)?;
2053 tokio::fs::write(&cargo_toml_path, rewritten)
2054 .await
2055 .with_context(|| format!("write {}", cargo_toml_path.display()))?;
2056
2057 sync_lockfile(worktree, state.config.cache_dir().as_deref()).await?;
2058
2059 let committed = git::commit_all(worktree, &format!("chore: release v{next_version}"))
2060 .await
2061 .context("commit the version bump")?;
2062 if !committed {
2063 bail!("the version bump left nothing to commit");
2064 }
2065
2066 let remote = state.config.merge.remote.clone();
2067 let pushed = git::push(worktree, &remote, branch).await?;
2068 if !pushed.ok() {
2069 bail!("pushing {branch} failed: {}", pushed.stderr);
2070 }
2071
2072 let (title, body) = release_pr(
2073 decision.level.as_str(),
2074 &decision.reason,
2075 next_version,
2076 &state.id,
2077 source_pr_url,
2078 );
2079 let (title, body) = crate::github_text::prepare(state, &title, &body);
2080 let url = gh_pr_create(worktree, &state.base_branch, branch, &title, &body).await?;
2081 if state.config.release.is_local() {
2085 crate::release_watch::register(&crate::run::home(), &state.repo, &url, &state.id);
2088 return Ok((url, AutomergeOutcome::LocalGate));
2089 }
2090 let outcome = match gh_enable_automerge(worktree, &url).await {
2091 Ok(()) => AutomergeOutcome::Enabled,
2092 Err(e) => {
2093 let reason = e.to_string();
2094 if is_clean_status_refusal(&reason) {
2095 gh_merge_directly(worktree, &url, &title, reason).await
2096 } else {
2097 AutomergeOutcome::Failed { reason }
2098 }
2099 }
2100 };
2101 Ok((url, outcome))
2102}
2103
2104#[derive(Debug, Clone, PartialEq, Eq)]
2106enum AutomergeOutcome {
2107 Enabled,
2109 MergedDirectly { detail: String },
2111 LocalGate,
2113 Failed { reason: String },
2115}
2116
2117fn is_clean_status_refusal(reason: &str) -> bool {
2123 let r = reason.to_lowercase();
2124 r.contains("is in clean status") && r.contains("enablepullrequestautomerge")
2125}
2126
2127pub(crate) fn bump_merge_argv(pr_url: &str, subject: &str) -> Vec<String> {
2130 [
2131 "pr",
2132 "merge",
2133 pr_url,
2134 "--squash",
2135 "--delete-branch",
2136 "--subject",
2137 subject,
2138 ]
2139 .map(str::to_owned)
2140 .to_vec()
2141}
2142
2143fn resolve_direct_merge(
2147 refusal: &str,
2148 argv: &[String],
2149 merge_ok: bool,
2150 stderr: &str,
2151 after: Option<land::PrLifecycle>,
2152) -> AutomergeOutcome {
2153 if merge_ok {
2154 return AutomergeOutcome::MergedDirectly {
2155 detail: format!("automerge was refused ({refusal}); gh {}", argv.join(" ")),
2156 };
2157 }
2158 match land::merged_after_all(argv, stderr, after) {
2159 Some(m) => AutomergeOutcome::MergedDirectly { detail: m.detail },
2160 None => AutomergeOutcome::Failed {
2161 reason: format!("{refusal}; merging directly failed too: {}", stderr.trim()),
2162 },
2163 }
2164}
2165
2166async fn gh_merge_directly(
2170 cwd: &Path,
2171 pr_url: &str,
2172 subject: &str,
2173 refusal: String,
2174) -> AutomergeOutcome {
2175 let argv = bump_merge_argv(pr_url, subject);
2176 let out = match tokio::process::Command::new("gh")
2177 .args(&argv)
2178 .current_dir(cwd)
2179 .quiet()
2180 .stdin(std::process::Stdio::null())
2181 .output()
2182 .await
2183 {
2184 Ok(o) => o,
2185 Err(e) => {
2186 return AutomergeOutcome::Failed {
2187 reason: format!("{refusal}; could not spawn gh to merge directly: {e}"),
2188 };
2189 }
2190 };
2191 let stderr = String::from_utf8_lossy(&out.stderr).into_owned();
2192 let after = if out.status.success() {
2195 None
2196 } else {
2197 land::lifecycle(cwd, pr_url).await.ok()
2198 };
2199 resolve_direct_merge(&refusal, &argv, out.status.success(), &stderr, after)
2200}
2201
2202async fn sync_lockfile(worktree: &Path, cache_dir: Option<&Path>) -> Result<()> {
2210 let mut cmd = tokio::process::Command::new("cargo");
2211 cmd.arg("build").current_dir(worktree).quiet();
2212 if let Some(dir) = cache_dir {
2213 cmd.env("CARGO_TARGET_DIR", dir);
2214 }
2215 let out = cmd
2216 .stdin(std::process::Stdio::null())
2217 .output()
2218 .await
2219 .context("spawn cargo build")?;
2220 if !out.status.success() {
2221 bail!(
2222 "cargo build failed while syncing Cargo.lock: {}",
2223 String::from_utf8_lossy(&out.stderr).trim()
2224 );
2225 }
2226 Ok(())
2227}
2228
2229fn release_pr(
2234 level: &str,
2235 reason: &str,
2236 next_version: &str,
2237 run_id: &str,
2238 source_pr_url: &str,
2239) -> (String, String) {
2240 let title = format!("chore: release v{next_version} ({level} bump)");
2241 let body = format!(
2242 "## Background\n\n\
2243 A change that was just merged is a `{level}` change, so the crate needs a new \
2244 release: {reason}\n\n\
2245 Triggered by magi run `{run_id}`, which landed {source}.\n\n\
2246 ## Change\n\n\
2247 Raises the package version to `v{next_version}` in `Cargo.toml`, with \
2248 `Cargo.lock` following it. Nothing else changes.\n\n\
2249 ## Risk\n\n\
2250 Version-bump-only, so there is nothing here for a reviewer to find. Merging \
2251 it starts the release pipeline (auto-tag, then the release workflow).",
2252 source = source_pr_url,
2253 );
2254 (title, body)
2255}
2256
2257async fn pr_title(repo: &Path, pr_url: &str) -> Result<String> {
2259 let out = tokio::process::Command::new("gh")
2260 .args(["pr", "view", pr_url, "--json", "title"])
2261 .current_dir(repo)
2262 .quiet()
2263 .stdin(std::process::Stdio::null())
2264 .output()
2265 .await
2266 .context("spawn gh pr view")?;
2267 if !out.status.success() {
2268 bail!(
2269 "gh pr view {pr_url}: {}",
2270 String::from_utf8_lossy(&out.stderr).trim()
2271 );
2272 }
2273 #[derive(Deserialize)]
2274 struct Title {
2275 title: String,
2276 }
2277 let parsed: Title = serde_json::from_str(&String::from_utf8_lossy(&out.stdout))
2278 .context("parse `gh pr view --json title` output")?;
2279 Ok(parsed.title)
2280}
2281
2282async fn gh_pr_create(
2283 cwd: &Path,
2284 base: &str,
2285 head: &str,
2286 title: &str,
2287 body: &str,
2288) -> Result<String> {
2289 let out = tokio::process::Command::new("gh")
2290 .args([
2291 "pr", "create", "--base", base, "--head", head, "--title", title, "--body", body,
2292 ])
2293 .current_dir(cwd)
2294 .quiet()
2295 .stdin(std::process::Stdio::null())
2296 .output()
2297 .await
2298 .context("spawn gh pr create")?;
2299 if out.status.success() {
2300 Ok(String::from_utf8_lossy(&out.stdout).trim().to_owned())
2301 } else {
2302 bail!(
2303 "gh pr create: {}",
2304 String::from_utf8_lossy(&out.stderr).trim()
2305 )
2306 }
2307}
2308
2309async fn gh_enable_automerge(cwd: &Path, pr_url: &str) -> Result<()> {
2313 let out = tokio::process::Command::new("gh")
2314 .args([
2315 "pr",
2316 "merge",
2317 pr_url,
2318 "--auto",
2319 "--squash",
2320 "--delete-branch",
2321 ])
2322 .current_dir(cwd)
2323 .quiet()
2324 .stdin(std::process::Stdio::null())
2325 .output()
2326 .await
2327 .context("spawn gh pr merge --auto")?;
2328 if out.status.success() {
2329 Ok(())
2330 } else {
2331 bail!(
2332 "gh pr merge --auto: {}",
2333 String::from_utf8_lossy(&out.stderr).trim()
2334 )
2335 }
2336}
2337
2338async fn gh_pr_edit_title(cwd: &Path, pr_url: &str, title: &str) -> Result<()> {
2342 let out = tokio::process::Command::new("gh")
2343 .args(["pr", "edit", pr_url, "--title", title])
2344 .current_dir(cwd)
2345 .quiet()
2346 .stdin(std::process::Stdio::null())
2347 .output()
2348 .await
2349 .context("spawn gh pr edit")?;
2350 if out.status.success() {
2351 Ok(())
2352 } else {
2353 bail!(
2354 "gh pr edit --title: {}",
2355 String::from_utf8_lossy(&out.stderr).trim()
2356 )
2357 }
2358}
2359
2360#[cfg(test)]
2361mod tests {
2362 use super::*;
2363 use crate::notices::Severity;
2364
2365 #[test]
2366 fn github_facing_bump_text_is_english() {
2367 let (title, body) =
2368 release_pr("minor", "adds a flag", "0.37.0", "ab12", "https://x/pull/1");
2369 assert!(crate::github_text::check(&title, &body).is_empty());
2370 assert!(title.is_ascii() && body.is_ascii(), "{title}\n{body}");
2371 assert_eq!(title, "chore: release v0.37.0 (minor bump)");
2372 assert!(
2373 body.contains("## Background") && body.contains("## Change"),
2374 "{body}"
2375 );
2376 let p = decision_prompt("s", "i", "d", &[], "0.36.5");
2377 assert!(p.contains(crate::prompt::GITHUB_ENGLISH_HEADING), "{p}");
2378 }
2379 use crate::config::Config;
2380 use crate::land::PrLifecycle;
2381
2382 #[tokio::test]
2388 async fn a_disabled_config_does_nothing() {
2389 let config = Config {
2390 merge: crate::config::Merge {
2391 release_bump: false,
2392 ..crate::config::Merge::default()
2393 },
2394 ..Config::default()
2395 };
2396 let mut state = RunState::new(
2397 PathBuf::from("/no/such/repo"),
2398 "main".to_owned(),
2399 "0000000000000000000000000000000000000000".to_owned(),
2400 "irrelevant".to_owned(),
2401 config,
2402 );
2403 after_merge(&mut state, "https://example.invalid/pull/1")
2404 .await
2405 .expect("a disabled config must return Ok without touching anything");
2406 assert!(
2407 state.events.is_empty(),
2408 "nothing should happen at all, not even a logged event"
2409 );
2410 }
2411
2412 async fn origin_with(files: &[(&str, &str)]) -> (tempfile::TempDir, PathBuf) {
2414 let dir = tempfile::tempdir().unwrap();
2415 let origin = dir.path().join("origin.git");
2416 let repo = dir.path().join("repo");
2417 let o = origin.to_string_lossy().into_owned();
2418 git::git(dir.path(), &["init", "--bare", "-b", "main", &o])
2419 .await
2420 .unwrap();
2421 tokio::fs::create_dir_all(&repo).await.unwrap();
2422 git::git(&repo, &["init", "-b", "main"]).await.unwrap();
2423 git::git(&repo, &["config", "user.name", "test"])
2424 .await
2425 .unwrap();
2426 git::git(&repo, &["config", "user.email", "test@example.com"])
2427 .await
2428 .unwrap();
2429 for (name, body) in files {
2430 tokio::fs::write(repo.join(name), body).await.unwrap();
2431 }
2432 git::git(&repo, &["add", "-A"]).await.unwrap();
2433 git::git(&repo, &["commit", "-m", "init"]).await.unwrap();
2434 git::git(&repo, &["remote", "add", "origin", &o])
2435 .await
2436 .unwrap();
2437 git::git(&repo, &["push", "origin", "main"]).await.unwrap();
2438 (dir, repo)
2439 }
2440
2441 async fn no_pr(_: String) -> Result<bool> {
2442 Ok(false)
2443 }
2444
2445 async fn with_branch(ahead: bool) -> (tempfile::TempDir, PathBuf) {
2448 let (d, repo) = origin_with(&[("f", "x\n")]).await;
2449 git::git(&repo, &["branch", "b"]).await.unwrap();
2450 if ahead {
2451 git::git(&repo, &["checkout", "-q", "b"]).await.unwrap();
2452 git::git(&repo, &["commit", "--allow-empty", "-m", "wip"])
2453 .await
2454 .unwrap();
2455 git::git(&repo, &["checkout", "-q", "main"]).await.unwrap();
2456 }
2457 (d, repo)
2458 }
2459
2460 async fn attempt(repo: &Path, open_pr: bool, fail_after_push: Option<bool>) -> Result<()> {
2461 let wt = repo.parent().unwrap().join("bump");
2462 release_attempt(
2463 repo,
2464 "origin",
2465 "main",
2466 &wt,
2467 "b",
2468 |_| async move { Ok(open_pr) },
2469 |w| async move {
2470 if fail_after_push == Some(true) {
2471 git::push(&w, "origin", "b").await?;
2472 }
2473 if fail_after_push.is_some() {
2474 bail!("cargo build failed");
2475 }
2476 Ok(())
2477 },
2478 )
2479 .await
2480 }
2481
2482 #[tokio::test]
2483 async fn a_stale_ancestor_branch_is_deleted_and_the_attempt_proceeds() {
2484 let (_d, repo) = with_branch(false).await;
2485 attempt(&repo, false, None).await.unwrap();
2486 assert!(git::branch_exists(&repo, "b").await.unwrap());
2488 }
2489
2490 #[tokio::test]
2491 async fn a_stale_branch_holding_a_leftover_worktree_is_reclaimed() {
2492 let (_d, repo) = with_branch(false).await;
2493 let old = repo.parent().unwrap().join("old");
2494 git::git(&repo, &["worktree", "add", &old.to_string_lossy(), "b"])
2495 .await
2496 .unwrap();
2497 attempt(&repo, false, None).await.unwrap();
2498 assert!(!old.exists());
2499 }
2500
2501 #[tokio::test]
2502 async fn a_stale_branch_with_an_unmerged_commit_is_kept_with_a_reason() {
2503 let (_d, repo) = with_branch(true).await;
2504 let e = attempt(&repo, false, None).await.unwrap_err().to_string();
2505 assert!(e.contains("`b`") || e.contains("branch b"), "{e}");
2506 assert!(e.contains("1 commit(s) not in origin/main"), "{e}");
2507 assert!(git::branch_exists(&repo, "b").await.unwrap());
2508 }
2509
2510 #[tokio::test]
2511 async fn a_stale_branch_on_the_remote_is_kept() {
2512 let (_d, repo) = with_branch(false).await;
2513 git::git(&repo, &["push", "origin", "b"]).await.unwrap();
2514 let e = attempt(&repo, false, None).await.unwrap_err().to_string();
2515 assert!(e.contains("branch b") && e.contains("is on origin"), "{e}");
2516 assert!(git::branch_exists(&repo, "b").await.unwrap());
2517 }
2518
2519 #[tokio::test]
2520 async fn a_stale_branch_with_an_open_pull_request_is_kept() {
2521 let (_d, repo) = with_branch(false).await;
2522 let e = attempt(&repo, true, None).await.unwrap_err().to_string();
2523 assert!(e.contains("open pull request"), "{e}");
2524 assert!(git::branch_exists(&repo, "b").await.unwrap());
2525 }
2526
2527 #[tokio::test]
2528 async fn an_unanswerable_pull_request_check_keeps_the_branch() {
2529 let (_d, repo) = with_branch(false).await;
2530 let wt = repo.parent().unwrap().join("bump");
2531 let e = release_attempt(
2532 &repo,
2533 "origin",
2534 "main",
2535 &wt,
2536 "b",
2537 |_| async { bail!("offline") },
2538 |_| async { Ok(()) },
2539 )
2540 .await
2541 .unwrap_err()
2542 .to_string();
2543 assert!(
2544 e.contains("could not check for an open pull request"),
2545 "{e}"
2546 );
2547 assert!(git::branch_exists(&repo, "b").await.unwrap());
2548 }
2549
2550 #[tokio::test]
2551 async fn a_failed_attempt_removes_its_own_worktree_and_branch() {
2552 let (_d, repo) = origin_with(&[("f", "x\n")]).await;
2553 let wt = repo.parent().unwrap().join("bump");
2554 let e = attempt(&repo, false, Some(false)).await.unwrap_err();
2555 assert!(format!("{e:#}").contains("cargo build failed"));
2556 assert!(!wt.exists());
2557 assert!(!git::branch_exists(&repo, "b").await.unwrap());
2558 }
2559
2560 #[tokio::test]
2561 async fn a_pushed_branch_survives_a_failed_attempt_and_the_reason_says_so() {
2562 let (_d, repo) = origin_with(&[("f", "x\n")]).await;
2563 let e = attempt(&repo, false, Some(true)).await.unwrap_err();
2564 let e = format!("{e:#}");
2565 assert!(
2566 e.contains("cargo build failed") && e.contains("pushed to origin"),
2567 "{e}"
2568 );
2569 assert!(git::branch_exists(&repo, "b").await.unwrap());
2570 }
2571
2572 #[tokio::test]
2573 async fn a_branch_left_by_a_half_done_worktree_add_is_removed() {
2574 let (_d, repo) = origin_with(&[("f", "x\n")]).await;
2577 let blocker = repo.parent().unwrap().join("blocker");
2578 tokio::fs::write(&blocker, "file").await.unwrap();
2579 let wt = blocker.join("bump");
2580 let r = release_attempt(
2581 &repo,
2582 "origin",
2583 "main",
2584 &wt,
2585 "b",
2586 |_| async { bail!("offline") },
2587 |_| async { Ok(()) },
2588 )
2589 .await;
2590 assert!(r.is_err());
2591 assert!(!git::branch_exists(&repo, "b").await.unwrap());
2592 }
2593
2594 #[tokio::test]
2595 async fn the_retry_is_taken_at_most_once() {
2596 let (_d, repo) = with_branch(false).await;
2599 let blocker = repo.parent().unwrap().join("blocker");
2600 tokio::fs::write(&blocker, "file").await.unwrap();
2601 let wt = blocker.join("bump");
2602 let r = release_attempt(&repo, "origin", "main", &wt, "b", no_pr, |_| async {
2603 Ok(())
2604 })
2605 .await;
2606 assert!(r.is_err());
2607 assert!(!git::branch_exists(&repo, "b").await.unwrap());
2608 }
2609
2610 #[tokio::test]
2611 async fn base_has_cargo_toml_tells_rust_from_non_rust() {
2612 let (_d, rust) = origin_with(&[("Cargo.toml", "[package]\nversion = \"0.1.0\"\n")]).await;
2613 assert!(base_has_cargo_toml(&rust, "origin", "main").await.unwrap());
2614 let (_d2, other) = origin_with(&[("README.md", "hi\n")]).await;
2615 assert!(!base_has_cargo_toml(&other, "origin", "main").await.unwrap());
2616 assert!(base_has_cargo_toml(&other, "origin", "nope").await.is_err());
2618 }
2619
2620 #[tokio::test]
2621 async fn a_repo_without_cargo_toml_skips_with_one_event_and_no_lock() {
2622 let (_d, repo) = origin_with(&[("README.md", "hi\n")]).await;
2623 let home = tempfile::tempdir().unwrap();
2624 let mut state = RunState::new(
2625 repo.clone(),
2626 "main".to_owned(),
2627 "0000000000000000000000000000000000000000".to_owned(),
2628 "task".to_owned(),
2629 Config::default(),
2630 );
2631 state.candidates.push(crate::run::Candidate {
2632 index: 0,
2633 label: 'A',
2634 agent: "x".to_owned(),
2635 branch: "main".to_owned(),
2636 worktree: repo.clone(),
2637 summary: String::new(),
2638 stat: String::new(),
2639 files: 1,
2640 commits: 1,
2641 empty: false,
2642 failed: None,
2643 verified_noop: None,
2644 duration_ms: 0,
2645 folded: false,
2646 });
2647 state.tally = Some(
2648 serde_json::from_value(serde_json::json!({
2649 "first_choice": {}, "borda": {}, "winner": "A",
2650 "unanimous_initial": true, "deliberated": false,
2651 "changed_votes": 0, "unanimous_final": true,
2652 }))
2653 .unwrap(),
2654 );
2655 after_merge_at(
2656 &mut state,
2657 "https://example.invalid/pull/1",
2658 Some(home.path()),
2659 None,
2660 )
2661 .await
2662 .expect("a non-Rust repository is not an error");
2663 let bumps: Vec<_> = state.events.iter().filter(|e| e.node == "bump").collect();
2664 assert_eq!(bumps.len(), 1, "{:?}", state.events);
2665 assert_eq!(
2666 bumps[0].message,
2667 "release bump: no Cargo.toml on the base branch; release bumps are Rust-only, skipping"
2668 );
2669 assert!(
2670 std::fs::read_dir(home.path()).unwrap().next().is_none(),
2671 "no marker and no lock may be created"
2672 );
2673 }
2674
2675 fn winner_state(repo: &Path, base: &str) -> RunState {
2676 let mut state = RunState::new(
2677 repo.to_path_buf(),
2678 base.to_owned(),
2679 "0000000000000000000000000000000000000000".to_owned(),
2680 "task".to_owned(),
2681 Config::default(),
2682 );
2683 state.candidates.push(crate::run::Candidate {
2684 index: 0,
2685 label: 'A',
2686 agent: "x".to_owned(),
2687 branch: "main".to_owned(),
2688 worktree: repo.to_path_buf(),
2689 summary: String::new(),
2690 stat: String::new(),
2691 files: 1,
2692 commits: 1,
2693 empty: false,
2694 failed: None,
2695 verified_noop: None,
2696 duration_ms: 0,
2697 folded: false,
2698 });
2699 state.tally = Some(
2700 serde_json::from_value(serde_json::json!({
2701 "first_choice": {}, "borda": {}, "winner": "A",
2702 "unanimous_initial": true, "deliberated": false,
2703 "changed_votes": 0, "unanimous_final": true,
2704 }))
2705 .unwrap(),
2706 );
2707 state
2708 }
2709
2710 #[tokio::test]
2711 async fn a_real_failure_without_a_pr_raises_one_notice_and_a_retry_folds_into_it() {
2712 let (_d, repo) =
2713 origin_with(&[("Cargo.toml", "[package]\nname=\"x\"\nversion=\"0.1.0\"\n")]).await;
2714 let home = tempfile::tempdir().unwrap();
2715 let store = Notices::at(home.path().join("notifications"));
2716 let mut state = winner_state(&repo, "nope");
2718 let url = "https://example.invalid/pull/1";
2719 after_merge_at(&mut state, url, Some(home.path()), Some(&store))
2720 .await
2721 .expect_err("an unresolvable base is a failure");
2722 let listed = store.list();
2723 assert_eq!(listed.len(), 1, "{listed:?}");
2724 assert!(
2725 listed[0].message.contains("did not run"),
2726 "{}",
2727 listed[0].message
2728 );
2729 assert!(
2730 listed[0].message.contains("Cargo.toml"),
2731 "{}",
2732 listed[0].message
2733 );
2734 assert!(state.events.iter().any(|e| e.node == "bump"));
2735 after_merge_at(&mut state, url, Some(home.path()), Some(&store))
2736 .await
2737 .expect_err("still failing");
2738 let listed = store.list();
2739 assert_eq!(listed.len(), 1, "{listed:?}");
2740 assert_eq!(listed[0].count, 2);
2741 }
2742
2743 #[tokio::test]
2744 async fn not_eligible_cases_raise_no_notice() {
2745 let home = tempfile::tempdir().unwrap();
2746 let store = Notices::at(home.path().join("notifications"));
2747 let url = "https://example.invalid/pull/1";
2748 let (_d, repo) = origin_with(&[("README.md", "hi\n")]).await;
2750 let mut state = winner_state(&repo, "main");
2751 after_merge_at(&mut state, url, Some(home.path()), Some(&store))
2752 .await
2753 .unwrap();
2754 let mut state = winner_state(&repo, "nope");
2756 state.config.merge.release_bump = false;
2757 after_merge_at(&mut state, url, Some(home.path()), Some(&store))
2758 .await
2759 .unwrap();
2760 let mut state = winner_state(&repo, "nope");
2762 state.tally = None;
2763 after_merge_at(&mut state, url, Some(home.path()), Some(&store))
2764 .await
2765 .unwrap();
2766 assert!(store.list().is_empty(), "{:?}", store.list());
2767 }
2768
2769 #[test]
2770 fn the_no_pr_notice_follows_the_configured_language() {
2771 let dir = tempfile::tempdir().unwrap();
2772 let store = Notices::at(dir.path().join("notifications"));
2773 let mut state = merged_state();
2774 state.config.graph.language = "ja".to_owned();
2775 let (n, _) = surface_problem(&mut state, &store, None, Some("0.2.0"), "boom").unwrap();
2776 assert!(n.message.contains("実行されませんでした"), "{}", n.message);
2777 assert!(n.message.contains("boom") && n.message.contains("v0.2.0"));
2778 }
2779
2780 #[test]
2781 fn a_failed_escalation_points_at_the_pending_pr_without_commenting() {
2782 let dir = tempfile::tempdir().unwrap();
2783 let store = Notices::at(dir.path().join("notifications"));
2784 let mut state = merged_state();
2785 let url = "https://example.invalid/pull/9";
2786 let (n, comment) = surface_problem_in(
2787 &mut state,
2788 &store,
2789 Some(url),
2790 Some("0.3.0"),
2791 "push failed",
2792 true,
2793 )
2794 .unwrap();
2795 assert!(comment.is_none());
2796 assert!(
2797 n.message.contains(url) && n.message.contains("v0.3.0"),
2798 "{}",
2799 n.message
2800 );
2801 assert!(!n.message.contains("open the release pull request by hand"));
2802 assert!(matches!(n.link, Some(Link::Url { .. })));
2803 }
2804
2805 #[test]
2806 fn a_failure_notice_names_the_pending_pr_and_the_first_line_of_the_cause() {
2807 let err = anyhow!("outer context").context("cargo build failed\nsecond line");
2808 let with_pr = Progress {
2809 version: Some("0.2.0".into()),
2810 pending_pr: Some("https://example.invalid/pull/9".into()),
2811 };
2812 let (v, reason) = notice_for_failure(&with_pr, &err);
2813 assert_eq!(v.as_deref(), Some("0.2.0"));
2814 assert_eq!(reason, "cargo build failed");
2815 let (v, reason) = notice_for_failure(&Progress::default(), &err);
2816 assert_eq!(v, None);
2817 assert_eq!(reason, "cargo build failed");
2818 }
2819
2820 const NO_RULES: &str = "gh pr merge --auto: GraphQL: Pull request Branch does not have \
2821 required protected branch rules (enablePullRequestAutoMerge)";
2822
2823 fn merged_state() -> RunState {
2824 run::pin_test_home();
2827 let mut s = RunState::new(
2828 PathBuf::from("/no/such/repo"),
2829 "main".to_owned(),
2830 "0000000000000000000000000000000000000000".to_owned(),
2831 "task".to_owned(),
2832 Config::default(),
2833 );
2834 s.status = RunStatus::Merged;
2835 s
2836 }
2837
2838 #[test]
2839 fn the_known_automerge_refusal_names_branch_protection() {
2840 assert!(automerge_hint(NO_RULES).contains("branch protection with required"));
2841 let other = automerge_hint("gh: network unreachable");
2842 assert!(!other.contains("branch protection"), "{other}");
2843 let body = automerge_failure_comment(NO_RULES);
2844 assert!(body.contains("enablePullRequestAutoMerge"), "{body}");
2845 assert!(body.contains("Action required"), "{body}");
2846 }
2847
2848 const CLEAN: &str = "gh pr merge --auto: GraphQL: Pull request Pull request is in clean \
2849 status (enablePullRequestAutoMerge)";
2850
2851 #[test]
2852 fn clean_status_refusal_is_matched_narrowly() {
2853 assert!(is_clean_status_refusal(CLEAN));
2854 assert!(!is_clean_status_refusal(NO_RULES));
2855 assert!(!is_clean_status_refusal("gh: network unreachable"));
2856 assert!(!is_clean_status_refusal("Pull request is in clean status"));
2857 assert!(automerge_hint(CLEAN).contains("already green"));
2858 }
2859
2860 #[test]
2861 fn the_direct_merge_argv_matches_the_land_flags() {
2862 let a = bump_merge_argv("https://github.com/o/r/pull/9", "chore: release v1.0.0");
2863 let l = land::merge_argv(9, "chore: release v1.0.0");
2864 assert_eq!(a[..2], l[..2]);
2865 assert_eq!(a[3..], l[3..]);
2866 assert_eq!(a[2], "https://github.com/o/r/pull/9");
2867 }
2868
2869 #[test]
2870 fn a_direct_merge_is_judged_by_the_forge_not_the_exit_code() {
2871 let argv = bump_merge_argv("u", "t");
2872 let merged = |o: &AutomergeOutcome| matches!(o, AutomergeOutcome::MergedDirectly { .. });
2873 assert!(merged(&resolve_direct_merge(CLEAN, &argv, true, "", None)));
2874 let detached = "not on any branch";
2875 assert!(merged(&resolve_direct_merge(
2876 CLEAN,
2877 &argv,
2878 false,
2879 detached,
2880 Some(PrLifecycle::Merged)
2881 )));
2882 for after in [Some(PrLifecycle::Open), None] {
2883 let o = resolve_direct_merge(CLEAN, &argv, false, "boom", after);
2884 match o {
2885 AutomergeOutcome::Failed { reason } => {
2886 assert!(
2887 reason.contains("clean status") && reason.contains("boom"),
2888 "{reason}"
2889 )
2890 }
2891 other => panic!("expected Failed, got {other:?}"),
2892 }
2893 }
2894 }
2895
2896 #[test]
2897 fn a_local_mode_bump_reads_back_and_old_records_are_not_local() {
2898 let old: run::ReleaseBump =
2899 serde_json::from_str(r#"{"pr_url":"u","automerge_enabled":true}"#).unwrap();
2900 assert!(!old.local);
2901 let mut state = merged_state();
2902 state.release_bump = Some(run::ReleaseBump {
2903 pr_url: Some("https://github.com/o/r/pull/9".to_owned()),
2904 version: Some("1.0.0".to_owned()),
2905 local: true,
2906 ..run::ReleaseBump::default()
2907 });
2908 assert!(!state.needs_attention());
2910 let text = crate::report::run(&state);
2911 assert!(text.contains("release.mode = local"), "{text}");
2912 assert!(!text.contains("FAILED"), "{text}");
2913 }
2914
2915 #[test]
2916 fn a_directly_merged_bump_is_not_reported_as_pending_or_failed() {
2917 let mut state = merged_state();
2918 state.release_bump = Some(run::ReleaseBump {
2919 pr_url: Some("https://github.com/o/r/pull/9".to_owned()),
2920 version: Some("1.0.0".to_owned()),
2921 merged_directly: true,
2922 ..run::ReleaseBump::default()
2923 });
2924 assert!(!state.needs_attention());
2925 let text = crate::report::run(&state);
2926 assert!(text.contains("merged directly"), "{text}");
2927 assert!(!text.contains("FAILED"), "{text}");
2928 }
2929
2930 #[test]
2931 fn an_automerge_failure_is_recorded_shown_and_filed_and_survives_settling() {
2932 let dir = tempfile::tempdir().unwrap();
2933 let store = Notices::at(dir.path().join("notifications"));
2934 let questions = ask::Questions::at(dir.path().join("questions"));
2935 let mut state = merged_state();
2936 let url = "https://github.com/o/r/pull/35";
2937
2938 let (n, comment) =
2939 surface_problem(&mut state, &store, Some(url), Some("0.8.0"), NO_RULES).unwrap();
2940
2941 let comment = comment.expect("a PR was opened, so it gets a comment");
2943 assert!(comment.contains("branch protection"), "{comment}");
2944
2945 assert_eq!(state.status, RunStatus::Merged);
2947 assert!(state.needs_attention());
2948 let text = crate::report::run(&state);
2949 assert!(text.contains("release bump"), "{text}");
2950 assert!(text.contains("FAILED"), "{text}");
2951 assert!(text.contains(url), "{text}");
2952 assert!(text.contains("action required"), "{text}");
2953 assert!(crate::report::line(&state).contains("release needs a human"));
2954
2955 assert_eq!(n.severity, Severity::Error);
2957 assert_eq!(
2958 n.link,
2959 Some(Link::Url {
2960 url: url.to_owned()
2961 })
2962 );
2963 assert_eq!(store.list().len(), 1);
2964 assert!(questions.open_for(&state.id).is_empty());
2965
2966 surface_problem(&mut state, &store, Some(url), Some("0.8.0"), NO_RULES).unwrap();
2968 let listed = store.list();
2969 assert_eq!(listed.len(), 1);
2970 assert_eq!(listed[0].count, 2);
2971 }
2972
2973 #[test]
2974 fn a_bump_that_never_ran_is_surfaced_without_a_pr_comment() {
2975 let dir = tempfile::tempdir().unwrap();
2976 let store = Notices::at(dir.path().join("notifications"));
2977 let mut state = merged_state();
2978 let (n, comment) = surface_problem(&mut state, &store, None, None, "no agent").unwrap();
2979 assert!(comment.is_none());
2980 assert!(matches!(n.link, Some(Link::Run { .. })));
2981 assert!(state.needs_attention());
2982 }
2983
2984 #[test]
2985 fn version_parses_and_bumps_each_digit() {
2986 let v = Version::parse("0.4.0").unwrap();
2987 assert_eq!(
2988 v,
2989 Version {
2990 major: 0,
2991 minor: 4,
2992 patch: 0
2993 }
2994 );
2995
2996 assert_eq!(v.bump(BumpLevel::Major).to_string(), "1.0.0");
2997 assert_eq!(v.bump(BumpLevel::Minor).to_string(), "0.5.0");
2998 assert_eq!(v.bump(BumpLevel::Patch).to_string(), "0.4.1");
2999 }
3000
3001 #[test]
3002 fn version_tolerates_a_prerelease_suffix_on_patch() {
3003 let v = Version::parse("1.2.3-rc1").unwrap();
3004 assert_eq!(
3005 v,
3006 Version {
3007 major: 1,
3008 minor: 2,
3009 patch: 3
3010 }
3011 );
3012 }
3013
3014 #[test]
3015 fn version_rejects_garbage() {
3016 assert!(Version::parse("not-a-version").is_err());
3017 assert!(Version::parse("1.2").is_err());
3018 }
3019
3020 #[test]
3021 fn decision_parses_each_level() {
3022 for (json, level) in [
3023 (
3024 r#"{"level":"major","reason":"drops a config key"}"#,
3025 BumpLevel::Major,
3026 ),
3027 (
3028 r#"{"level":"minor","reason":"adds a new flag"}"#,
3029 BumpLevel::Minor,
3030 ),
3031 (
3032 r#"{"level":"patch","reason":"fixes a race"}"#,
3033 BumpLevel::Patch,
3034 ),
3035 ] {
3036 let decision = parse_decision(json).unwrap();
3037 assert_eq!(decision.level, level);
3038 assert!(!decision.reason.is_empty());
3039 }
3040 }
3041
3042 #[test]
3043 fn decision_wrapped_in_a_fence_and_prose_still_parses() {
3044 let text = "Here is my call.\n\n```json\n{\"level\":\"minor\",\"reason\":\"new HTTP route\"}\n```\n\nDone.";
3045 let decision = parse_decision(text).unwrap();
3046 assert_eq!(decision.level, BumpLevel::Minor);
3047 assert_eq!(decision.reason, "new HTTP route");
3048 }
3049
3050 #[test]
3051 fn a_broken_reply_is_an_error_not_a_default() {
3052 assert!(parse_decision("I decline to answer.").is_err());
3053 assert!(parse_decision(r#"{"level":"huge","reason":"go big"}"#).is_err());
3054 assert!(
3055 parse_decision(r#"{"level":"patch","reason":""}"#).is_err(),
3056 "an empty reason must not pass either"
3057 );
3058 assert!(
3059 parse_decision(r#"{"level":"patch"}"#).is_err(),
3060 "a reply with no reason at all must not pass"
3061 );
3062 }
3063
3064 #[test]
3065 fn prompt_states_the_zero_x_rule_and_the_tie_break() {
3066 let prompt = decision_prompt(
3067 "feat: add a phone endpoint",
3068 "add POST /api/widgets",
3069 "1 file changed, 10 insertions(+)",
3070 &["src/web.rs".to_owned()],
3071 "0.8.0",
3072 );
3073 assert!(prompt.contains("0.8.0"), "the current version is stated");
3074 assert!(
3075 prompt.contains("below `1.0.0`")
3076 && prompt.contains("`minor` is the digit that carries a breaking change"),
3077 "the 0.x rule must be explicit: {prompt}"
3078 );
3079 assert!(
3080 prompt.contains("choose the larger"),
3081 "the tie-break toward the bigger digit must be explicit: {prompt}"
3082 );
3083 }
3084
3085 #[test]
3086 fn release_only_diffs_are_recognised() {
3087 assert!(is_release_only(&["Cargo.toml".to_owned()]));
3088 assert!(is_release_only(&[
3089 "Cargo.toml".to_owned(),
3090 "Cargo.lock".to_owned()
3091 ]));
3092 assert!(!is_release_only(&[]));
3093 assert!(!is_release_only(&[
3094 "Cargo.toml".to_owned(),
3095 "src/main.rs".to_owned()
3096 ]));
3097 }
3098
3099 #[test]
3100 fn cargo_version_rewrite_touches_only_the_package_table() {
3101 let toml = "\
3102[package]\n\
3103# a comment mentioning version on purpose\n\
3104name = \"magi-cli\"\n\
3105version = \"0.8.0\"\n\
3106edition = \"2024\"\n\
3107\n\
3108[dependencies]\n\
3109foo = { version = \"1.2.3\" }\n";
3110 let out = rewrite_cargo_version(toml, "0.9.0").unwrap();
3111 assert!(out.contains("version = \"0.9.0\""));
3112 assert!(
3113 out.contains("foo = { version = \"1.2.3\" }"),
3114 "a dependency's own version pin must survive: {out}"
3115 );
3116 assert!(
3117 out.contains("# a comment mentioning version on purpose"),
3118 "unrelated lines, comments included, must be byte-for-byte preserved: {out}"
3119 );
3120 assert_eq!(
3121 out.lines().count(),
3122 toml.lines().count(),
3123 "the rewrite replaces one line, it does not add or remove any"
3124 );
3125 }
3126
3127 #[test]
3128 fn cargo_version_rewrite_fails_without_a_package_table() {
3129 let toml = "[dependencies]\nfoo = \"1\"\n";
3130 assert!(rewrite_cargo_version(toml, "1.0.0").is_err());
3131 }
3132
3133 #[test]
3139 fn cargo_version_rewrite_falls_back_to_workspace_package_without_a_package_table() {
3140 let toml = "\
3141[workspace]\n\
3142members = [\"crates/a\", \"crates/b\"]\n\
3143\n\
3144[workspace.package]\n\
3145version = \"0.45.18\"\n\
3146edition = \"2024\"\n\
3147\n\
3148[workspace.dependencies]\n\
3149foo = { version = \"1.2.3\" }\n";
3150 let out = rewrite_cargo_version(toml, "0.45.19").unwrap();
3151 assert!(out.contains("version = \"0.45.19\""));
3152 assert!(
3153 out.contains("foo = { version = \"1.2.3\" }"),
3154 "a workspace dependency's own version pin must survive: {out}"
3155 );
3156 assert_eq!(
3157 out.lines().count(),
3158 toml.lines().count(),
3159 "the rewrite replaces one line, it does not add or remove any"
3160 );
3161 }
3162
3163 #[test]
3167 fn cargo_version_rewrite_bumps_an_internal_workspace_dependency_pin() {
3168 let toml = "\
3169[workspace]\n\
3170members = [\"crates/kanade-shared\"]\n\
3171\n\
3172[workspace.package]\n\
3173version = \"0.48.2\"\n\
3174\n\
3175[workspace.dependencies]\n\
3176kanade-shared = { path = \"crates/kanade-shared\", version = \"0.48.2\" }\n";
3177 let out = rewrite_cargo_version(toml, "0.48.3").unwrap();
3178 assert!(out.contains("[workspace.package]\nversion = \"0.48.3\"\n"));
3179 assert!(
3180 out.contains(
3181 "kanade-shared = { path = \"crates/kanade-shared\", version = \"0.48.3\" }"
3182 ),
3183 "the internal pin must move with the workspace version: {out}"
3184 );
3185 }
3186
3187 #[test]
3189 fn cargo_version_rewrite_bumps_an_internal_pin_with_version_before_path() {
3190 let toml = "\
3191[workspace.package]\n\
3192version = \"1.0.0\"\n\
3193\n\
3194[workspace.dependencies]\n\
3195inner = { version = \"1.0.0\", path = \"crates/inner\" }\n";
3196 let out = rewrite_cargo_version(toml, "1.0.1").unwrap();
3197 assert!(out.contains("inner = { version = \"1.0.1\", path = \"crates/inner\" }"));
3198 }
3199
3200 #[test]
3203 fn cargo_version_rewrite_bumps_an_internal_pin_in_dotted_table_form() {
3204 let toml = "\
3205[workspace.package]\n\
3206version = \"2.3.0\"\n\
3207\n\
3208[workspace.dependencies.inner]\n\
3209path = \"crates/inner\"\n\
3210version = \"2.3.0\"\n";
3211 let out = rewrite_cargo_version(toml, "2.4.0").unwrap();
3212 assert!(out.contains("[workspace.package]\nversion = \"2.4.0\"\n"));
3213 assert!(out.contains(
3214 "[workspace.dependencies.inner]\npath = \"crates/inner\"\nversion = \"2.4.0\"\n"
3215 ));
3216 }
3217
3218 #[test]
3223 fn cargo_version_rewrite_bumps_an_internal_pin_in_dotted_key_form() {
3224 let toml = "\
3225[workspace.package]\n\
3226version = \"2.3.0\"\n\
3227\n\
3228[workspace.dependencies]\n\
3229inner.path = \"crates/inner\"\n\
3230inner.version = \"2.3.0\"\n";
3231 let out = rewrite_cargo_version(toml, "2.4.0").unwrap();
3232 assert!(out.contains("[workspace.package]\nversion = \"2.4.0\"\n"));
3233 assert!(out.contains("inner.path = \"crates/inner\"\ninner.version = \"2.4.0\"\n"));
3234 }
3235
3236 #[test]
3239 fn cargo_version_rewrite_leaves_a_path_only_workspace_dependency_untouched() {
3240 let toml = "\
3241[workspace.package]\n\
3242version = \"0.1.0\"\n\
3243\n\
3244[workspace.dependencies]\n\
3245internal-only = { path = \"crates/internal-only\" }\n";
3246 let out = rewrite_cargo_version(toml, "0.2.0").unwrap();
3247 assert!(out.contains("internal-only = { path = \"crates/internal-only\" }"));
3248 }
3249
3250 #[test]
3254 fn cargo_version_rewrite_leaves_an_external_dependency_untouched() {
3255 let toml = "\
3256[workspace.package]\n\
3257version = \"0.1.0\"\n\
3258\n\
3259[workspace.dependencies]\n\
3260serde = { version = \"1\", features = [\"derive\"] }\n\
3261inner = { path = \"crates/inner\", version = \"0.1.0\" }\n";
3262 let out = rewrite_cargo_version(toml, "0.2.0").unwrap();
3263 assert!(out.contains("serde = { version = \"1\", features = [\"derive\"] }"));
3264 assert!(out.contains("inner = { path = \"crates/inner\", version = \"0.2.0\" }"));
3265 }
3266
3267 #[test]
3271 fn cargo_version_rewrite_without_workspace_dependencies_table_still_bumps_package() {
3272 let toml = "[workspace.package]\nversion = \"0.9.0\"\nedition = \"2024\"\n";
3273 let out = rewrite_cargo_version(toml, "0.10.0").unwrap();
3274 assert_eq!(
3275 out,
3276 "[workspace.package]\nversion = \"0.10.0\"\nedition = \"2024\"\n"
3277 );
3278 }
3279
3280 #[test]
3283 fn cargo_version_rewrite_handles_a_kanade_shaped_workspace_dependencies_table() {
3284 let toml = "\
3285[workspace.package]\n\
3286version = \"0.48.2\"\n\
3287\n\
3288[workspace.dependencies]\n\
3289anyhow = { version = \"1\" }\n\
3290serde = { version = \"1\", features = [\"derive\"] }\n\
3291kanade-shared = { path = \"crates/kanade-shared\", version = \"0.48.2\" }\n\
3292kanade-core = { path = \"crates/kanade-core\", version = \"0.48.2\" }\n\
3293kanade-internal-tool = { path = \"crates/kanade-internal-tool\" }\n";
3294 let out = rewrite_cargo_version(toml, "0.48.3").unwrap();
3295 assert!(out.contains("anyhow = { version = \"1\" }"));
3296 assert!(out.contains("serde = { version = \"1\", features = [\"derive\"] }"));
3297 assert!(
3298 out.contains(
3299 "kanade-shared = { path = \"crates/kanade-shared\", version = \"0.48.3\" }"
3300 )
3301 );
3302 assert!(
3303 out.contains("kanade-core = { path = \"crates/kanade-core\", version = \"0.48.3\" }")
3304 );
3305 assert!(out.contains("kanade-internal-tool = { path = \"crates/kanade-internal-tool\" }"));
3306 }
3307
3308 #[test]
3312 fn cargo_version_rewrite_bails_on_an_unrepresentable_inline_table() {
3313 let toml = "\
3314[workspace.package]\n\
3315version = \"0.1.0\"\n\
3316\n\
3317[workspace.dependencies]\n\
3318inner = { path = \"crates/inner\",\n\
3319 version = \"0.1.0\" }\n";
3320 assert!(rewrite_cargo_version(toml, "0.2.0").is_err());
3321 }
3322
3323 #[test]
3326 fn cargo_version_rewrite_recognises_a_commented_workspace_dependencies_header() {
3327 let toml = "\
3328[workspace.package]\n\
3329version = \"0.1.0\"\n\
3330\n\
3331[workspace.dependencies] # internal pins\n\
3332inner = { path = \"crates/inner\", version = \"0.1.0\" }\n";
3333 let out = rewrite_cargo_version(toml, "0.2.0").unwrap();
3334 assert!(out.contains("inner = { path = \"crates/inner\", version = \"0.2.0\" }"));
3335 }
3336
3337 #[test]
3340 fn cargo_version_rewrite_bumps_a_quoted_dependency_key() {
3341 let toml = "\
3342[workspace.package]\n\
3343version = \"0.1.0\"\n\
3344\n\
3345[workspace.dependencies]\n\
3346\"inner\" = { path = \"crates/inner\", version = \"0.1.0\" }\n";
3347 let out = rewrite_cargo_version(toml, "0.2.0").unwrap();
3348 assert!(out.contains("\"inner\" = { path = \"crates/inner\", version = \"0.2.0\" }"));
3349 }
3350
3351 #[test]
3355 fn cargo_version_rewrite_bumps_a_literal_string_version_pin() {
3356 let toml = "\
3357[workspace.package]\n\
3358version = \"0.1.0\"\n\
3359\n\
3360[workspace.dependencies]\n\
3361inner = { path = 'crates/inner', version = '0.1.0' }\n";
3362 let out = rewrite_cargo_version(toml, "0.2.0").unwrap();
3363 assert!(out.contains("inner = { path = 'crates/inner', version = '0.2.0' }"));
3364 }
3365
3366 #[test]
3372 fn cargo_version_rewrite_does_not_require_the_whole_file_to_parse() {
3373 let toml = "\
3374[workspace.package]\n\
3375version = \"0.1.0\"\n\
3376\n\
3377[workspace.dependencies]\n\
3378inner = { path = \"crates/inner\", version = \"0.1.0\" }\n\
3379\n\
3380[workspace.package]\n\
3381edition = \"2024\"\n";
3382 let out = rewrite_cargo_version(toml, "0.2.0").unwrap();
3383 assert!(out.contains("inner = { path = \"crates/inner\", version = \"0.2.0\" }"));
3384 assert!(
3385 toml::from_str::<toml::Value>(toml).is_err(),
3386 "the fixture itself must be invalid as a whole file, or this test proves nothing"
3387 );
3388 }
3389
3390 #[test]
3391 fn current_version_prefers_the_package_table_when_both_exist() {
3392 let toml = "[workspace.package]\nversion = \"9.9.9\"\n\n[package]\nversion = \"0.8.0\"\n";
3393 assert_eq!(current_version(toml).unwrap(), "0.8.0");
3394 }
3395
3396 #[test]
3399 fn current_version_falls_back_to_workspace_package_without_a_package_table() {
3400 let toml = "\
3401[workspace]\n\
3402members = [\"crates/a\", \"crates/b\"]\n\
3403\n\
3404[workspace.package]\n\
3405version = \"0.45.18\"\n";
3406 assert_eq!(current_version(toml).unwrap(), "0.45.18");
3407 }
3408
3409 #[test]
3410 fn coalesce_proceeds_with_nothing_pending() {
3411 assert_eq!(coalesce(None, "0.8.0").unwrap(), Coalesce::Proceed);
3412 }
3413
3414 fn test_pending(target_version: &str, level: BumpLevel) -> PendingBump {
3417 PendingBump {
3418 target_version: target_version.to_owned(),
3419 level,
3420 branch: format!("chore/release-v{target_version}"),
3421 pr_url: "https://example.invalid/pull/9".to_owned(),
3422 }
3423 }
3424
3425 #[test]
3426 fn coalesce_skips_while_the_pending_target_is_still_ahead() {
3427 let pending = test_pending("0.9.0", BumpLevel::Minor);
3428 assert_eq!(
3429 coalesce(Some(&pending), "0.8.0").unwrap(),
3430 Coalesce::Skip {
3431 target_version: "0.9.0".to_owned()
3432 }
3433 );
3434 }
3435
3436 #[test]
3437 fn coalesce_treats_a_landed_or_superseded_pending_bump_as_stale() {
3438 let pending = test_pending("0.9.0", BumpLevel::Minor);
3439 assert_eq!(
3441 coalesce(Some(&pending), "0.9.0").unwrap(),
3442 Coalesce::Proceed
3443 );
3444 assert_eq!(
3446 coalesce(Some(&pending), "1.0.0").unwrap(),
3447 Coalesce::Proceed
3448 );
3449 }
3450
3451 #[test]
3452 fn pending_action_escalates_only_for_a_more_severe_decision() {
3453 assert_eq!(
3454 pending_action(BumpLevel::Patch, BumpLevel::Patch),
3455 PendingAction::AlreadyCovered
3456 );
3457 assert_eq!(
3458 pending_action(BumpLevel::Patch, BumpLevel::Minor),
3459 PendingAction::Escalate
3460 );
3461 assert_eq!(
3462 pending_action(BumpLevel::Patch, BumpLevel::Major),
3463 PendingAction::Escalate
3464 );
3465 assert_eq!(
3466 pending_action(BumpLevel::Minor, BumpLevel::Patch),
3467 PendingAction::AlreadyCovered
3468 );
3469 assert_eq!(
3470 pending_action(BumpLevel::Major, BumpLevel::Minor),
3471 PendingAction::AlreadyCovered
3472 );
3473 assert_eq!(
3474 pending_action(BumpLevel::Major, BumpLevel::Major),
3475 PendingAction::AlreadyCovered
3476 );
3477 }
3478
3479 #[test]
3480 fn pr_state_parsing_reads_open_and_not_open() {
3481 assert!(parse_pr_state(r#"{"state":"OPEN"}"#).unwrap());
3482 assert!(!parse_pr_state(r#"{"state":"CLOSED"}"#).unwrap());
3483 assert!(!parse_pr_state(r#"{"state":"MERGED"}"#).unwrap());
3484 }
3485
3486 #[test]
3487 fn a_lock_is_exclusive_until_dropped() {
3488 let dir = tempfile::tempdir().unwrap();
3489 let marker = dir.path().join("bump").join("deadbeefdeadbeef.json");
3490 let first = MarkerLock::acquire(&marker)
3491 .unwrap()
3492 .expect("first attempt takes the lock");
3493 assert!(
3494 MarkerLock::acquire(&marker).unwrap().is_none(),
3495 "a second attempt must be refused while the first holds it"
3496 );
3497 drop(first);
3498 assert!(
3499 MarkerLock::acquire(&marker).unwrap().is_some(),
3500 "dropping the guard releases the lock for the next attempt"
3501 );
3502 }
3503
3504 #[test]
3505 fn a_stale_lock_is_reclaimed() {
3506 let dir = tempfile::tempdir().unwrap();
3507 let marker = dir.path().join("bump").join("deadbeefdeadbeef.json");
3508 let lock_path = marker.with_extension("lock");
3509 std::fs::create_dir_all(lock_path.parent().unwrap()).unwrap();
3510 std::fs::write(&lock_path, b"").unwrap();
3511 let old = std::time::SystemTime::now() - LOCK_STALE_AFTER - Duration::from_secs(1);
3512 std::fs::OpenOptions::new()
3513 .write(true)
3514 .open(&lock_path)
3515 .unwrap()
3516 .set_modified(old)
3517 .unwrap();
3518 assert!(
3519 MarkerLock::acquire(&marker).unwrap().is_some(),
3520 "a lock older than the stale window must be reclaimed rather than block forever"
3521 );
3522 }
3523
3524 #[tokio::test]
3525 async fn a_contended_lock_is_retried_until_the_holder_releases_it() {
3526 let dir = tempfile::tempdir().unwrap();
3527 let marker = dir.path().join("bump").join("deadbeefdeadbeef.json");
3528 let held = MarkerLock::acquire(&marker)
3529 .unwrap()
3530 .expect("seed the contention");
3531 let releaser = tokio::spawn(async move {
3532 tokio::time::sleep(Duration::from_millis(20)).await;
3533 drop(held);
3534 });
3535 let waited =
3536 wait_for_marker_lock_with(&marker, Duration::from_millis(5), Duration::from_secs(5))
3537 .await
3538 .unwrap();
3539 assert!(
3540 waited.is_some(),
3541 "a merge landing behind another's still-running decision must not be dropped - it \
3542 must wait for that decision to finish and then judge against what it left behind"
3543 );
3544 releaser.await.unwrap();
3545 }
3546
3547 #[tokio::test]
3548 async fn a_lock_held_past_the_ceiling_gives_up() {
3549 let dir = tempfile::tempdir().unwrap();
3550 let marker = dir.path().join("bump").join("deadbeefdeadbeef.json");
3551 let _held = MarkerLock::acquire(&marker).unwrap().unwrap();
3552 let waited =
3553 wait_for_marker_lock_with(&marker, Duration::from_millis(2), Duration::from_millis(10))
3554 .await
3555 .unwrap();
3556 assert!(
3557 waited.is_none(),
3558 "a lock genuinely held past the ceiling must eventually give up rather than wait \
3559 forever"
3560 );
3561 }
3562
3563 #[test]
3564 fn level_between_reads_off_the_differing_digit() {
3565 assert_eq!(
3566 level_between(
3567 Version::parse("0.8.0").unwrap(),
3568 Version::parse("1.0.0").unwrap()
3569 ),
3570 Some(BumpLevel::Major)
3571 );
3572 assert_eq!(
3573 level_between(
3574 Version::parse("0.8.0").unwrap(),
3575 Version::parse("0.9.0").unwrap()
3576 ),
3577 Some(BumpLevel::Minor)
3578 );
3579 assert_eq!(
3580 level_between(
3581 Version::parse("0.8.0").unwrap(),
3582 Version::parse("0.8.1").unwrap()
3583 ),
3584 Some(BumpLevel::Patch)
3585 );
3586 assert_eq!(
3587 level_between(
3588 Version::parse("0.8.0").unwrap(),
3589 Version::parse("0.8.0").unwrap()
3590 ),
3591 None
3592 );
3593 }
3594
3595 #[test]
3596 fn open_release_pr_is_found_among_unrelated_pull_requests() {
3597 let json = r#"[
3598 {"url": "https://example.invalid/pull/1", "headRefName": "feat/something"},
3599 {"url": "https://example.invalid/pull/2", "headRefName": "chore/release-v0.9.0"}
3600 ]"#;
3601 let found = parse_open_release_pr(json).unwrap();
3602 assert_eq!(
3603 found,
3604 Some((
3605 "chore/release-v0.9.0".to_owned(),
3606 "https://example.invalid/pull/2".to_owned()
3607 ))
3608 );
3609 }
3610
3611 #[test]
3612 fn no_open_release_pr_reads_as_none_not_an_error() {
3613 let json =
3614 r#"[{"url": "https://example.invalid/pull/1", "headRefName": "feat/something"}]"#;
3615 assert_eq!(parse_open_release_pr(json).unwrap(), None);
3616 assert_eq!(parse_open_release_pr("[]").unwrap(), None);
3617 }
3618
3619 #[test]
3620 fn marker_round_trips_through_disk() {
3621 let dir = tempfile::tempdir().unwrap();
3622 let path = marker_path(dir.path(), Path::new("/repos/magi"));
3623 assert!(read_marker(&path).is_none());
3624
3625 let marker = test_pending("0.9.0", BumpLevel::Patch);
3626 write_marker(&path, &marker).unwrap();
3627 let read_back = read_marker(&path).unwrap();
3628 assert_eq!(read_back.target_version, "0.9.0");
3629 assert_eq!(read_back.level, BumpLevel::Patch);
3630 assert_eq!(read_back.pr_url, marker.pr_url);
3631
3632 clear_marker(&path);
3633 assert!(read_marker(&path).is_none());
3634 }
3635
3636 #[test]
3637 fn different_repos_get_different_marker_files() {
3638 let dir = tempfile::tempdir().unwrap();
3639 let a = marker_path(dir.path(), Path::new("/repos/a"));
3640 let b = marker_path(dir.path(), Path::new("/repos/b"));
3641 assert_ne!(a, b);
3642 }
3643
3644 #[test]
3648 fn a_bump_pull_requests_own_merge_does_not_retrigger() {
3649 let files = vec!["Cargo.toml".to_owned(), "Cargo.lock".to_owned()];
3650 assert!(
3651 is_release_only(&files),
3652 "the bump pull request's own diff must read as release-only"
3653 );
3654 }
3655
3656 #[test]
3657 fn should_release_bump_reads_only_a_merged_status() {
3658 assert!(should_release_bump(RunStatus::Merged));
3659 for other in [RunStatus::Blocked, RunStatus::Ready, RunStatus::Prep] {
3660 assert!(!should_release_bump(other));
3661 }
3662 }
3663
3664 #[test]
3668 fn all_three_merge_paths_report_pr_lifecycle_merged_case_done() {
3669 let pr = land::PrState {
3670 url: "https://github.com/o/r/pull/1".to_owned(),
3671 number: 1,
3672 state: PrLifecycle::Merged,
3673 checks: land::Checks::Green,
3674 failing: Vec::new(),
3675 review_comments: Vec::new(),
3676 blocking: land::Blocking::No,
3677 };
3678 assert_eq!(
3679 land::decide(&pr, 0, 4, Duration::ZERO),
3680 land::Step::Done { merged: true }
3681 );
3682 assert!(should_release_bump(RunStatus::Merged));
3683 }
3684
3685 #[test]
3690 fn all_three_merge_paths_report_pr_lifecycle_merged_case_direct_merge() {
3691 let pr = land::PrState {
3692 url: "https://github.com/o/r/pull/2".to_owned(),
3693 number: 2,
3694 state: PrLifecycle::Open,
3695 checks: land::Checks::Green,
3696 failing: Vec::new(),
3697 review_comments: Vec::new(),
3698 blocking: land::Blocking::No,
3699 };
3700 assert_eq!(land::decide(&pr, 0, 4, Duration::ZERO), land::Step::Merge);
3701 assert!(should_release_bump(RunStatus::Merged));
3704 }
3705
3706 #[test]
3709 fn all_three_merge_paths_report_pr_lifecycle_merged_case_merged_after_all() {
3710 let argv = land::merge_argv(3, "feat: something");
3711 let outcome = land::merged_after_all(
3712 &argv,
3713 "could not determine current branch: not on any branch",
3714 Some(PrLifecycle::Merged),
3715 );
3716 assert!(outcome.is_some(), "the forge's confirmation must win");
3717 assert!(should_release_bump(RunStatus::Merged));
3718
3719 assert!(land::merged_after_all(&argv, "network error", Some(PrLifecycle::Open)).is_none());
3722 assert!(land::merged_after_all(&argv, "network error", None).is_none());
3723 }
3724
3725 #[test]
3727 fn a_close_or_a_give_up_does_not_trigger_a_bump() {
3728 let pr = land::PrState {
3729 url: "https://github.com/o/r/pull/4".to_owned(),
3730 number: 4,
3731 state: PrLifecycle::Closed,
3732 checks: land::Checks::Green,
3733 failing: Vec::new(),
3734 review_comments: Vec::new(),
3735 blocking: land::Blocking::No,
3736 };
3737 assert_eq!(
3738 land::decide(&pr, 0, 4, Duration::ZERO),
3739 land::Step::Done { merged: false }
3740 );
3741 assert!(!should_release_bump(RunStatus::Blocked));
3742 }
3743}