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
592pub fn decision_prompt(
602 subject: &str,
603 instruction: &str,
604 diffstat: &str,
605 files: &[String],
606 current_version: &str,
607) -> String {
608 let mut s = format!(
609 "A pull request just merged into the base branch. Decide which digit \
610 of this project's `major.minor.patch` version this change earns, so \
611 a release bump can be opened for exactly it.\n\n\
612 Current version: {current_version}\n\n\
613 # Merge subject\n\n{subject}\n\n\
614 # The task that produced it\n\n{instruction}\n\n\
615 # Files changed ({} total)\n\n",
616 files.len()
617 );
618 const MAX_FILES: usize = 50;
619 for f in files.iter().take(MAX_FILES) {
620 let _ = writeln!(s, "- {f}");
621 }
622 if files.len() > MAX_FILES {
623 let _ = writeln!(s, "- ... and {} more", files.len() - MAX_FILES);
624 }
625 let _ = write!(s, "\n# Diffstat\n\n```\n{}\n```\n", diffstat.trim());
626
627 s.push_str(
628 "\n# How to decide\n\n\
629 This project is below version `1.0.0`. At that stage **`minor` is \
630 the digit that carries a breaking change** - do not spend `major` \
631 below `1.0.0`.\n\n\
632 A change is breaking, and earns `minor`, when it changes any of: \
633 the public API reachable from `src/lib.rs`, a CLI subcommand or \
634 flag, an HTTP API route or response shape, a configuration key, or \
635 the on-disk shape of persisted state.\n\n\
636 A user-visible new capability that breaks none of the above also \
637 earns `minor`.\n\n\
638 A fix, an internal refactor, or a dependency update earns `patch`.\n\n\
639 **When it is not obvious which digit applies, choose the larger \
640 one.** An oversized bump costs nothing; a breaking change shipped as \
641 `patch` breaks every downstream update that pins a range.\n\n\
642 # Output\n\n\
643 Reply with exactly one fenced JSON object and nothing that matters \
644 outside it:\n\n\
645 ```json\n\
646 {\"level\": \"major\" | \"minor\" | \"patch\", \"reason\": \"one line\"}\n\
647 ```\n",
648 );
649 let _ = write!(
651 s,
652 "\n{}\n\nThe `reason` goes into a GitHub pull request body, so write it \
653 in English.\n",
654 crate::prompt::GITHUB_ENGLISH_HEADING
655 );
656 s
657}
658
659#[derive(Debug, Clone, Serialize, Deserialize)]
675pub struct PendingBump {
676 pub target_version: String,
678 pub level: BumpLevel,
681 pub branch: String,
684 pub pr_url: String,
687}
688
689pub fn marker_path(home: &Path, repo: &Path) -> PathBuf {
693 let key = repo.to_string_lossy();
694 home.join("bump")
695 .join(format!("{:016x}.json", crate::rng::fnv1a(&key)))
696}
697
698pub fn read_marker(path: &Path) -> Option<PendingBump> {
702 let body = std::fs::read_to_string(path).ok()?;
703 serde_json::from_str(&body).ok()
704}
705
706pub fn write_marker(path: &Path, marker: &PendingBump) -> Result<()> {
710 if let Some(parent) = path.parent() {
711 std::fs::create_dir_all(parent).with_context(|| format!("create {}", parent.display()))?;
712 }
713 let body = serde_json::to_string_pretty(marker).context("serialize pending bump")?;
714 let tmp = path.with_extension("json.tmp");
715 std::fs::write(&tmp, &body).with_context(|| format!("write {}", tmp.display()))?;
716 std::fs::rename(&tmp, path).with_context(|| format!("replace {}", path.display()))?;
717 Ok(())
718}
719
720pub fn clear_marker(path: &Path) {
723 let _ = std::fs::remove_file(path);
724}
725
726#[derive(Debug, Clone, PartialEq, Eq)]
730pub enum Coalesce {
731 Proceed,
734 Skip {
736 target_version: String,
738 },
739}
740
741pub fn coalesce(pending: Option<&PendingBump>, current_version: &str) -> Result<Coalesce> {
743 let Some(pending) = pending else {
744 return Ok(Coalesce::Proceed);
745 };
746 let current = Version::parse(current_version)?;
747 let target = Version::parse(&pending.target_version)?;
748 if current >= target {
749 return Ok(Coalesce::Proceed);
750 }
751 Ok(Coalesce::Skip {
752 target_version: pending.target_version.clone(),
753 })
754}
755
756#[derive(Debug, Clone, Copy, PartialEq, Eq)]
758pub enum PendingAction {
759 AlreadyCovered,
762 Escalate,
765}
766
767pub fn pending_action(pending_level: BumpLevel, decision_level: BumpLevel) -> PendingAction {
776 if decision_level.severity() > pending_level.severity() {
777 PendingAction::Escalate
778 } else {
779 PendingAction::AlreadyCovered
780 }
781}
782
783fn parse_pr_state(json: &str) -> Result<bool> {
785 #[derive(Deserialize)]
786 struct State {
787 state: String,
788 }
789 let parsed: State =
790 serde_json::from_str(json).context("parse `gh pr view --json state` output")?;
791 Ok(parsed.state.eq_ignore_ascii_case("OPEN"))
792}
793
794async fn pr_is_open(repo: &Path, pr_url: &str) -> Result<bool> {
807 let out = tokio::process::Command::new("gh")
808 .args(["pr", "view", pr_url, "--json", "state"])
809 .current_dir(repo)
810 .quiet()
811 .stdin(std::process::Stdio::null())
812 .output()
813 .await
814 .context("spawn gh pr view")?;
815 if !out.status.success() {
816 bail!(
817 "gh pr view {pr_url}: {}",
818 String::from_utf8_lossy(&out.stderr).trim()
819 );
820 }
821 parse_pr_state(&String::from_utf8_lossy(&out.stdout))
822}
823
824const LOCK_STALE_AFTER: Duration = Duration::from_secs(30 * 60);
832
833struct MarkerLock {
845 path: PathBuf,
846}
847
848impl MarkerLock {
849 fn acquire(marker: &Path) -> Result<Option<Self>> {
853 let path = marker.with_extension("lock");
854 if let Some(parent) = path.parent() {
855 std::fs::create_dir_all(parent)
856 .with_context(|| format!("create {}", parent.display()))?;
857 }
858 if Self::try_create(&path)? {
859 return Ok(Some(Self { path }));
860 }
861 if Self::is_stale(&path) {
862 let _ = std::fs::remove_file(&path);
863 if Self::try_create(&path)? {
864 return Ok(Some(Self { path }));
865 }
866 }
867 Ok(None)
868 }
869
870 fn try_create(path: &Path) -> Result<bool> {
871 match std::fs::OpenOptions::new()
872 .write(true)
873 .create_new(true)
874 .open(path)
875 {
876 Ok(_) => Ok(true),
877 Err(e) if e.kind() == std::io::ErrorKind::AlreadyExists => Ok(false),
878 Err(e) => Err(e).with_context(|| format!("create {}", path.display())),
879 }
880 }
881
882 fn is_stale(path: &Path) -> bool {
883 std::fs::metadata(path)
884 .and_then(|m| m.modified())
885 .ok()
886 .and_then(|m| m.elapsed().ok())
887 .is_some_and(|age| age >= LOCK_STALE_AFTER)
888 }
889}
890
891impl Drop for MarkerLock {
892 fn drop(&mut self) {
893 let _ = std::fs::remove_file(&self.path);
894 }
895}
896
897const LOCK_POLL: Duration = Duration::from_secs(5);
899
900const LOCK_WAIT_CEILING: Duration = Duration::from_secs(25 * 60);
913
914async fn wait_for_marker_lock(marker: &Path) -> Result<Option<MarkerLock>> {
917 wait_for_marker_lock_with(marker, LOCK_POLL, LOCK_WAIT_CEILING).await
918}
919
920async fn wait_for_marker_lock_with(
924 marker: &Path,
925 poll: Duration,
926 ceiling: Duration,
927) -> Result<Option<MarkerLock>> {
928 let mut waited = Duration::ZERO;
929 loop {
930 if let Some(lock) = MarkerLock::acquire(marker)? {
931 return Ok(Some(lock));
932 }
933 if waited >= ceiling {
934 return Ok(None);
935 }
936 tokio::time::sleep(poll).await;
937 waited += poll;
938 }
939}
940
941fn level_between(from: Version, to: Version) -> Option<BumpLevel> {
949 if to.major != from.major {
950 Some(BumpLevel::Major)
951 } else if to.minor != from.minor {
952 Some(BumpLevel::Minor)
953 } else if to.patch != from.patch {
954 Some(BumpLevel::Patch)
955 } else {
956 None
957 }
958}
959
960fn parse_open_release_pr(json: &str) -> Result<Option<(String, String)>> {
963 #[derive(Deserialize)]
964 struct Pr {
965 url: String,
966 #[serde(rename = "headRefName")]
967 head_ref_name: String,
968 }
969 let list: Vec<Pr> =
970 serde_json::from_str(json).context("parse `gh pr list --json url,headRefName` output")?;
971 Ok(list
972 .into_iter()
973 .find(|p| p.head_ref_name.starts_with("chore/release-v"))
974 .map(|p| (p.head_ref_name, p.url)))
975}
976
977pub(crate) fn parse_open_release_prs(json: &str) -> Result<Vec<(String, String)>> {
980 #[derive(Deserialize)]
981 struct Pr {
982 url: String,
983 #[serde(rename = "headRefName")]
984 head_ref_name: String,
985 }
986 let list: Vec<Pr> =
987 serde_json::from_str(json).context("parse `gh pr list --json url,headRefName` output")?;
988 Ok(list
989 .into_iter()
990 .filter(|p| p.head_ref_name.starts_with("chore/release-v"))
991 .map(|p| (p.head_ref_name, p.url))
992 .collect())
993}
994
995pub(crate) async fn list_open_release_prs(repo: &Path) -> Result<Vec<(String, String)>> {
997 let out = tokio::process::Command::new("gh")
998 .args([
999 "pr",
1000 "list",
1001 "--state",
1002 "open",
1003 "--limit",
1004 "100",
1005 "--json",
1006 "url,headRefName",
1007 ])
1008 .current_dir(repo)
1009 .env_remove("GH_REPO")
1010 .quiet()
1011 .stdin(std::process::Stdio::null())
1012 .output()
1013 .await
1014 .context("spawn gh pr list")?;
1015 if !out.status.success() {
1016 bail!(
1017 "gh pr list: {}",
1018 String::from_utf8_lossy(&out.stderr).trim()
1019 );
1020 }
1021 parse_open_release_prs(&String::from_utf8_lossy(&out.stdout))
1022}
1023
1024async fn find_open_release_pr(repo: &Path) -> Result<Option<(String, String)>> {
1039 let out = tokio::process::Command::new("gh")
1040 .args(["pr", "list", "--state", "open", "--json", "url,headRefName"])
1041 .current_dir(repo)
1042 .quiet()
1043 .stdin(std::process::Stdio::null())
1044 .output()
1045 .await
1046 .context("spawn gh pr list")?;
1047 if !out.status.success() {
1048 bail!(
1049 "gh pr list: {}",
1050 String::from_utf8_lossy(&out.stderr).trim()
1051 );
1052 }
1053 parse_open_release_pr(&String::from_utf8_lossy(&out.stdout))
1054}
1055
1056pub async fn after_merge(state: &mut RunState, pr_url: &str) -> Result<()> {
1076 after_merge_at(state, pr_url, None, None).await
1077}
1078
1079#[derive(Debug, Default)]
1081struct Progress {
1082 version: Option<String>,
1084 pending_pr: Option<String>,
1086}
1087
1088fn notice_for_failure(progress: &Progress, err: &anyhow::Error) -> (Option<String>, String) {
1094 let chain = format!("{err:#}");
1095 let first = chain.lines().next().unwrap_or_default().trim();
1096 (progress.version.clone(), first.to_owned())
1097}
1098
1099async fn base_has_cargo_toml(repo: &Path, remote: &str, base: &str) -> Result<bool> {
1105 let out = git::git(
1106 repo,
1107 &[
1108 "ls-tree",
1109 "--name-only",
1110 &format!("{remote}/{base}"),
1111 "--",
1112 "Cargo.toml",
1113 ],
1114 )
1115 .await
1116 .context("look for Cargo.toml on the base branch")?;
1117 Ok(!out.trim().is_empty())
1118}
1119
1120async fn after_merge_at(
1124 state: &mut RunState,
1125 pr_url: &str,
1126 home: Option<&Path>,
1127 store: Option<&Notices>,
1128) -> Result<()> {
1129 let mut progress = Progress::default();
1130 let result = after_merge_inner(state, pr_url, home, &mut progress).await;
1131 if let Err(e) = &result {
1132 let (version, reason) = notice_for_failure(&progress, e);
1133 let pending = progress.pending_pr.as_deref();
1134 let store = store.cloned().unwrap_or_else(Notices::open);
1135 report_problem_in(
1136 state,
1137 &store,
1138 pending,
1139 version.as_deref(),
1140 &reason,
1141 pending.is_some(),
1142 )
1143 .await;
1144 }
1145 result
1146}
1147
1148async fn after_merge_inner(
1149 state: &mut RunState,
1150 pr_url: &str,
1151 home: Option<&Path>,
1152 progress: &mut Progress,
1153) -> Result<()> {
1154 if !state.config.merge.release_bump {
1155 return Ok(());
1156 }
1157 let Some(winner) = state.winner().cloned() else {
1158 return Ok(());
1159 };
1160 let repo = state.repo.clone();
1161 let base = state.base_branch.clone();
1162 let remote = state.config.merge.remote.clone();
1163
1164 let files = git::changed_files(&winner.worktree, &base, &winner.branch)
1165 .await
1166 .unwrap_or_default();
1167 if is_release_only(&files) {
1168 state.event(
1169 "bump",
1170 "the merged change touches only the release manifest; not treating it as a trigger",
1171 );
1172 return Ok(());
1173 }
1174
1175 git::fetch(&repo, &remote, &base).await.ok();
1178 if !base_has_cargo_toml(&repo, &remote, &base).await? {
1179 state.event(
1180 "bump",
1181 "release bump: no Cargo.toml on the base branch; release bumps are Rust-only, skipping",
1182 );
1183 return Ok(());
1184 }
1185
1186 let marker = marker_path(&home.map_or_else(run::home, Path::to_path_buf), &repo);
1187 let Some(_lock) = wait_for_marker_lock(&marker).await? else {
1194 state.event(
1195 "bump",
1196 "another release bump decision held the lock past the wait ceiling; skipping this round",
1197 );
1198 return Ok(());
1199 };
1200
1201 git::fetch(&repo, &remote, &base).await.ok();
1202 let cargo_toml = git::git(&repo, &["show", &format!("{remote}/{base}:Cargo.toml")])
1203 .await
1204 .context("read Cargo.toml from the base branch")?;
1205 let base_version = current_version(&cargo_toml)?;
1206
1207 let mut pending = read_marker(&marker);
1208 if let Some(p) = &pending {
1209 match coalesce(Some(p), &base_version)? {
1210 Coalesce::Proceed => {
1211 clear_marker(&marker);
1214 pending = None;
1215 }
1216 Coalesce::Skip { target_version } => {
1217 if !pr_is_open(&repo, &p.pr_url).await.unwrap_or(true) {
1218 state.event(
1219 "bump",
1220 format!(
1221 "the pending release bump to v{target_version} ({}) is no longer \
1222 open; treating it as abandoned",
1223 p.pr_url
1224 ),
1225 );
1226 clear_marker(&marker);
1227 pending = None;
1228 }
1229 }
1234 }
1235 }
1236
1237 if pending.is_none() {
1238 if let Ok(Some((branch, url))) = find_open_release_pr(&repo).await
1243 && let Some(target) = branch
1244 .strip_prefix("chore/release-v")
1245 .and_then(|v| Version::parse(v).ok())
1246 {
1247 let base_parsed = Version::parse(&base_version)?;
1248 if target > base_parsed
1249 && let Some(level) = level_between(base_parsed, target)
1250 {
1251 let adopted = PendingBump {
1252 target_version: target.to_string(),
1253 level,
1254 branch,
1255 pr_url: url,
1256 };
1257 let _ = write_marker(&marker, &adopted);
1260 pending = Some(adopted);
1261 }
1262 }
1263 }
1264
1265 progress.pending_pr = pending.as_ref().map(|p| p.pr_url.clone());
1266 let title = pr_title(&repo, pr_url).await.unwrap_or_default();
1267 let subject = land::merge_subject(
1268 crate::graph::landing_title(state, &title),
1269 &crate::graph::landing_subject_source(state),
1270 );
1271 let stat = git::diff_stat(&winner.worktree, &base, &winner.branch)
1272 .await
1273 .unwrap_or_default();
1274 let prompt = decision_prompt(&subject, &state.instruction, &stat, &files, &base_version);
1275
1276 let spec: AgentSpec = agent::pick(
1282 &state.config.agents,
1283 crate::config::primary(state.config.roles.chatter.as_ref()),
1284 &agent::installed,
1285 )
1286 .context("choose an agent for the release-bump decision")?;
1287 let mut seat = SeatState::new("bump", &spec.id, state.seed);
1288 let artifacts = agent::artifacts_dir(&state.dir());
1289 let out = agent::invoke(
1290 &spec,
1291 &mut seat,
1292 &Invocation {
1293 cwd: &repo,
1294 prompt: &prompt,
1295 timeout: DECISION_TIMEOUT,
1296 allow_write: false,
1299 unsandboxed: false,
1300 sessions: false,
1301 artifacts: &artifacts,
1302 stem: "bump-decision",
1303 run: &state.id,
1304 node: "bump",
1305 cache_dir: state.config.cache_dir().as_deref(),
1306 attachments: &[],
1307 writable: &[],
1308 },
1309 )
1310 .await
1311 .context("ask an agent how big the merged change was")?;
1312 if !out.usable() {
1313 bail!(
1314 "the release-bump decision produced nothing usable (exit {:?}, timed out: {})",
1315 out.exit_code,
1316 out.timed_out
1317 );
1318 }
1319 let mut decision = parse_decision(&out.text).context("parse the release-bump decision")?;
1320 let mut violations = crate::github_text::check("", &decision.reason);
1321 violations.retain(|v| *v != crate::github_text::Violation::SensitiveData);
1323 if violations.is_empty() {
1324 decision.reason = crate::scrub::scrub(&decision.reason, &crate::scrub::Identity::current());
1325 }
1326 if state.config.graph.github_text_guard && !violations.is_empty() {
1327 state.event(
1328 "github-text",
1329 format!("release reason rejected: {violations:?}; requesting one rewrite"),
1330 );
1331 let rewrite = format!(
1332 "{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: {}",
1333 decision.reason
1334 );
1335 let retry = agent::invoke(
1336 &spec,
1337 &mut seat,
1338 &Invocation {
1339 cwd: &repo,
1340 prompt: &rewrite,
1341 timeout: crate::graph::retry_budget(DECISION_TIMEOUT, true),
1342 allow_write: false,
1343 unsandboxed: false,
1344 sessions: false,
1345 artifacts: &artifacts,
1346 stem: "bump-rewrite",
1347 run: &state.id,
1348 node: "bump",
1349 cache_dir: state.config.cache_dir().as_deref(),
1350 attachments: &[],
1351 writable: &[],
1352 },
1353 )
1354 .await;
1355 let reason = retry
1356 .ok()
1357 .filter(|o| o.usable())
1358 .and_then(|o| parse_decision(&o.text).ok())
1359 .filter(|d| {
1360 d.level == decision.level && crate::github_text::check("", &d.reason).is_empty()
1361 })
1362 .map(|d| d.reason);
1363 if let Some(reason) = reason {
1364 decision.reason = reason;
1365 state.event("github-text", "release reason rewrite passed");
1366 } else {
1367 decision.reason = "The merged change requires a release.".to_owned();
1368 state.event(
1369 "github-text",
1370 "release reason rewrite unavailable or rejected; using neutral text",
1371 );
1372 }
1373 }
1374
1375 if let Some(p) = pending {
1376 return match pending_action(p.level, decision.level) {
1377 PendingAction::AlreadyCovered => {
1378 state.event(
1379 "bump",
1380 format!(
1381 "a release bump to v{} ({}) already covers at least a {} change; not \
1382 opening another",
1383 p.target_version,
1384 p.pr_url,
1385 decision.level.as_str()
1386 ),
1387 );
1388 Ok(())
1389 }
1390 PendingAction::Escalate => {
1391 progress.version = Some(
1392 Version::parse(&base_version)?
1393 .bump(decision.level)
1394 .to_string(),
1395 );
1396 escalate_pending(state, &repo, &remote, &p, &decision, &base_version, &marker).await
1397 }
1398 };
1399 }
1400
1401 let next = Version::parse(&base_version)?
1402 .bump(decision.level)
1403 .to_string();
1404 progress.version = Some(next.clone());
1405 let branch = format!("chore/release-v{next}");
1406 let worktree = state.dir().join("bump");
1407 let (shared, branch_ref, next_ref, decision_ref) = (&mut *state, &branch, &next, &decision);
1408 let (pr_url_opened, outcome) =
1409 release_attempt(
1410 &repo,
1411 &remote,
1412 &base,
1413 &worktree,
1414 &branch,
1415 |head| {
1416 let repo = repo.clone();
1417 async move { gh_open_pr_for_head(&repo, &head).await }
1418 },
1419 |wt| async move {
1420 open_bump_pr(shared, &wt, branch_ref, next_ref, decision_ref, pr_url).await
1421 },
1422 )
1423 .await?;
1424 let local = outcome == AutomergeOutcome::LocalGate;
1425 let (automerge_warning, merged_detail) = match outcome {
1426 AutomergeOutcome::Enabled | AutomergeOutcome::LocalGate => (None, None),
1427 AutomergeOutcome::MergedDirectly { detail } => (None, Some(detail)),
1428 AutomergeOutcome::Failed { reason } => (Some(reason), None),
1429 };
1430
1431 let marker_write = write_marker(
1440 &marker,
1441 &PendingBump {
1442 target_version: next.clone(),
1443 level: decision.level,
1444 branch,
1445 pr_url: pr_url_opened.clone(),
1446 },
1447 );
1448 state.event(
1449 "bump",
1450 format!(
1451 "opened a {} release bump to v{next} ({}): {pr_url_opened}",
1452 decision.level.as_str(),
1453 decision.reason
1454 ),
1455 );
1456 if let Err(e) = marker_write {
1457 state.event(
1458 "bump",
1459 format!(
1460 "could not record the pending release bump marker for v{next}: {e:#}; a later \
1461 merge may open a duplicate pull request if it cannot find {pr_url_opened} on \
1462 the forge either"
1463 ),
1464 );
1465 }
1466 state.release_bump = Some(run::ReleaseBump {
1467 pr_url: Some(pr_url_opened.clone()),
1468 version: Some(next.clone()),
1469 automerge_enabled: automerge_warning.is_none() && merged_detail.is_none() && !local,
1470 merged_directly: merged_detail.is_some(),
1471 local,
1472 ..run::ReleaseBump::default()
1473 });
1474 if let Some(detail) = merged_detail {
1475 clear_marker(&marker);
1478 state.event("bump", format!("merged v{next} directly: {detail}"));
1479 }
1480 if let Some(warning) = automerge_warning {
1481 state.event(
1482 "bump",
1483 format!("could not enable automerge on {pr_url_opened}: {warning}; merge it by hand"),
1484 );
1485 report_problem(state, Some(&pr_url_opened), Some(&next), &warning).await;
1486 }
1487 Ok(())
1488}
1489
1490pub const NOTICE_NODE: &str = "release-bump";
1495
1496fn automerge_hint(reason: &str) -> &'static str {
1503 let r = reason.to_lowercase();
1504 if is_clean_status_refusal(reason) {
1505 "merge the release pull request by hand; CI is already green"
1506 } else if r.contains("enablepullrequestautomerge") || r.contains("protected branch rules") {
1507 "merge the release pull request by hand, and enable branch protection with required \
1508 status checks on the base branch so automerge can work next time"
1509 } else {
1510 "merge the release pull request by hand"
1511 }
1512}
1513
1514fn automerge_failure_comment(reason: &str) -> String {
1516 format!(
1517 "magi could not enable automerge on this pull request: {reason}\n\n\
1518 Action required: {}. Until then the release does not happen.",
1519 automerge_hint(reason)
1520 )
1521}
1522
1523#[cfg(test)]
1531fn surface_problem(
1532 state: &mut RunState,
1533 store: &Notices,
1534 pr_url: Option<&str>,
1535 version: Option<&str>,
1536 reason: &str,
1537) -> Result<(Notice, Option<String>)> {
1538 surface_problem_in(state, store, pr_url, version, reason, false)
1539}
1540
1541fn surface_problem_in(
1545 state: &mut RunState,
1546 store: &Notices,
1547 pr_url: Option<&str>,
1548 version: Option<&str>,
1549 reason: &str,
1550 pending: bool,
1551) -> Result<(Notice, Option<String>)> {
1552 let action = if let (true, Some(url)) = (pending, pr_url) {
1553 let ja = crate::lang::is_japanese(&state.config.graph.language);
1554 let first = reason.lines().next().filter(|l| !l.is_empty());
1555 let cause = first.map(|l| format!(" ({l})")).unwrap_or_default();
1556 if ja {
1557 let target = version.map(|v| format!(" v{v}")).unwrap_or_default();
1558 format!(
1559 "既存のリリース PR {url} を{target}へ更新できませんでした{cause}。PR を手で更新してください"
1560 )
1561 } else {
1562 let target = version.map(|v| format!(" to v{v}")).unwrap_or_default();
1563 format!(
1564 "the pending release pull request {url} could not be updated{target}{cause}; update it by hand"
1565 )
1566 }
1567 } else if pr_url.is_some() {
1568 automerge_hint(reason).to_owned()
1569 } else {
1570 let ja = crate::lang::is_japanese(&state.config.graph.language);
1571 let first = reason.lines().next().filter(|l| !l.is_empty());
1572 if ja {
1573 let target = version.map(|v| format!(" (v{v})")).unwrap_or_default();
1574 let cause = first.map(|l| format!(" ({l})")).unwrap_or_default();
1575 format!(
1576 "リリースバンプ{target}は実行されませんでした{cause}。リリース PR を手で開いてください"
1577 )
1578 } else {
1579 let target = version.map(|v| format!(" to v{v}")).unwrap_or_default();
1580 let cause = first.map(|l| format!(" ({l})")).unwrap_or_default();
1581 format!(
1582 "the release bump{target} did not run{cause}; open the release pull request by hand"
1583 )
1584 }
1585 };
1586 let record = state.release_bump.get_or_insert_with(Default::default);
1587 record.pr_url = pr_url.map(str::to_owned).or(record.pr_url.take());
1588 record.version = version.map(str::to_owned).or(record.version.take());
1589 record.automerge_enabled = false;
1590 record.problem = Some(reason.to_owned());
1591 record.action_required = Some(action.clone());
1592
1593 let mut notice = Notice::error(
1594 &format!("release-bump:{}", state.id),
1595 format!(
1596 "Run {} merged, but its release step failed: {action}.",
1597 state.id
1598 ),
1599 );
1600 notice = match pr_url {
1601 Some(url) => notice.link(Link::Url {
1602 url: url.to_owned(),
1603 }),
1604 None => notice.link(Link::Run {
1605 id: state.id.clone(),
1606 }),
1607 };
1608 let notice = store
1609 .raise(notice)
1610 .context("raise the release-bump notification")?;
1611 state.event("bump", format!("needs attention: {action}"));
1612 let comment = pr_url
1613 .filter(|_| !pending)
1614 .map(|_| automerge_failure_comment(reason));
1615 Ok((notice, comment))
1616}
1617
1618pub async fn report_problem(
1623 state: &mut RunState,
1624 pr_url: Option<&str>,
1625 version: Option<&str>,
1626 reason: &str,
1627) {
1628 report_problem_in(state, &Notices::open(), pr_url, version, reason, false).await;
1629}
1630
1631async fn report_problem_in(
1633 state: &mut RunState,
1634 store: &Notices,
1635 pr_url: Option<&str>,
1636 version: Option<&str>,
1637 reason: &str,
1638 pending: bool,
1639) {
1640 match surface_problem_in(state, store, pr_url, version, reason, pending) {
1641 Ok((notice, comment)) => {
1642 if let (Some(url), Some(body)) = (pr_url, comment)
1643 && let Err(e) = gh_pr_comment(state, url, &body).await
1644 {
1645 state.event("bump", format!("could not comment on {url}: {e:#}"));
1646 }
1647 let summary = match pr_url {
1650 Some(url) if pending => format!("Release PR could not be updated: {url}"),
1651 Some(url) => format!("Release PR needs a human: {url}"),
1652 None if crate::lang::is_japanese(&state.config.graph.language) => {
1653 "リリースバンプが実行されませんでした".to_owned()
1654 }
1655 None => "Release bump did not run".to_owned(),
1656 };
1657 let q = ask::Question::new(
1658 state.id.clone(),
1659 NOTICE_NODE.to_owned(),
1660 "bump".to_owned(),
1661 summary,
1662 notice.message.clone(),
1663 Vec::new(),
1664 );
1665 if let Err(e) = ask::notify(&state.config.notify, &q).await {
1666 tracing::warn!(
1667 "could not notify about the release bump of {}: {e:#}",
1668 state.id
1669 );
1670 }
1671 }
1672 Err(e) => state.event("bump", format!("could not raise a notice: {e:#}")),
1673 }
1674}
1675
1676pub(crate) async fn gh_pr_comment(state: &mut RunState, pr_url: &str, body: &str) -> Result<()> {
1677 let (_, body) = crate::github_text::prepare(state, "", body);
1678 let cwd = &state.repo;
1679 let out = tokio::process::Command::new("gh")
1680 .args(["pr", "comment", pr_url, "--body", &body])
1681 .current_dir(cwd)
1682 .quiet()
1683 .stdin(std::process::Stdio::null())
1684 .output()
1685 .await
1686 .context("spawn gh pr comment")?;
1687 if out.status.success() {
1688 Ok(())
1689 } else {
1690 bail!(
1691 "gh pr comment: {}",
1692 String::from_utf8_lossy(&out.stderr).trim()
1693 )
1694 }
1695}
1696
1697async fn escalate_pending(
1706 state: &mut RunState,
1707 repo: &Path,
1708 remote: &str,
1709 pending: &PendingBump,
1710 decision: &BumpDecision,
1711 base_version: &str,
1712 marker: &Path,
1713) -> Result<()> {
1714 let next = Version::parse(base_version)?
1715 .bump(decision.level)
1716 .to_string();
1717 let worktree = state.dir().join("bump");
1718 git::worktree_remove(repo, &worktree).await.ok();
1719 let checked_out = git::git_raw(
1720 repo,
1721 &[
1722 "worktree",
1723 "add",
1724 "--force",
1725 &worktree.to_string_lossy(),
1726 &pending.branch,
1727 ],
1728 )
1729 .await?;
1730 if !checked_out.ok() {
1731 bail!(
1732 "checking out the pending release branch {} failed: {}",
1733 pending.branch,
1734 checked_out.stderr
1735 );
1736 }
1737
1738 let pushed: Result<()> = async {
1743 let cargo_toml_path = worktree.join("Cargo.toml");
1744 let toml = tokio::fs::read_to_string(&cargo_toml_path)
1745 .await
1746 .with_context(|| format!("read {}", cargo_toml_path.display()))?;
1747 let rewritten = rewrite_cargo_version(&toml, &next)?;
1748 tokio::fs::write(&cargo_toml_path, rewritten)
1749 .await
1750 .with_context(|| format!("write {}", cargo_toml_path.display()))?;
1751 sync_lockfile(&worktree, state.config.cache_dir().as_deref()).await?;
1752 let committed = git::commit_all(
1753 &worktree,
1754 &format!(
1755 "chore: release v{next} (supersedes v{})",
1756 pending.target_version
1757 ),
1758 )
1759 .await
1760 .context("commit the escalated version bump")?;
1761 if !committed {
1762 bail!("escalating the version bump left nothing to commit");
1763 }
1764 let pushed = git::push(&worktree, remote, &pending.branch).await?;
1765 if !pushed.ok() {
1766 bail!("pushing {} failed: {}", pending.branch, pushed.stderr);
1767 }
1768 Ok(())
1769 }
1770 .await;
1771 if let Err(e) = pushed {
1772 git::worktree_remove(repo, &worktree).await.ok();
1773 return Err(e);
1774 }
1775
1776 let (title, _) = crate::github_text::prepare(
1780 state,
1781 &format!("chore: release v{next} ({} bump)", decision.level.as_str()),
1782 "",
1783 );
1784 let title_warning = match gh_pr_edit_title(&worktree, &pending.pr_url, &title).await {
1785 Ok(()) => None,
1786 Err(e) => Some(e.to_string()),
1787 };
1788 git::worktree_remove(repo, &worktree).await.ok();
1789
1790 let marker_write = write_marker(
1791 marker,
1792 &PendingBump {
1793 target_version: next.clone(),
1794 level: decision.level,
1795 branch: pending.branch.clone(),
1796 pr_url: pending.pr_url.clone(),
1797 },
1798 );
1799 state.event(
1800 "bump",
1801 format!(
1802 "escalated the pending release bump from v{} to v{next} to a {} change ({}): {}",
1803 pending.target_version,
1804 decision.level.as_str(),
1805 decision.reason,
1806 pending.pr_url
1807 ),
1808 );
1809 if let Err(e) = marker_write {
1810 state.event(
1811 "bump",
1812 format!(
1813 "could not update the pending release bump marker to v{next}: {e:#}; a later \
1814 merge may misjudge whether it is already covered"
1815 ),
1816 );
1817 }
1818 if let Some(warning) = title_warning {
1819 state.event(
1820 "bump",
1821 format!(
1822 "pushed v{next} to {} but could not update its title: {warning}; the squashed \
1823 subject may still read the superseded version",
1824 pending.pr_url
1825 ),
1826 );
1827 }
1828 Ok(())
1829}
1830
1831async fn gh_open_pr_for_head(repo: &Path, branch: &str) -> Result<bool> {
1834 let out = tokio::process::Command::new("gh")
1835 .args([
1836 "pr", "list", "--head", branch, "--state", "open", "--json", "url",
1837 ])
1838 .current_dir(repo)
1839 .quiet()
1840 .stdin(std::process::Stdio::null())
1841 .output()
1842 .await
1843 .context("spawn gh pr list")?;
1844 if !out.status.success() {
1845 bail!(
1846 "gh pr list --head {branch}: {}",
1847 String::from_utf8_lossy(&out.stderr).trim()
1848 );
1849 }
1850 let prs: Vec<serde_json::Value> = serde_json::from_slice(&out.stdout)
1851 .with_context(|| format!("parse the pull requests headed by {branch}"))?;
1852 Ok(!prs.is_empty())
1853}
1854
1855async fn release_attempt<T, F, Fut, P, PFut>(
1864 repo: &Path,
1865 remote: &str,
1866 base: &str,
1867 worktree: &Path,
1868 branch: &str,
1869 open_pr: P,
1870 fill: F,
1871) -> Result<T>
1872where
1873 F: FnOnce(PathBuf) -> Fut,
1874 Fut: std::future::Future<Output = Result<T>>,
1875 P: Fn(String) -> PFut,
1876 PFut: std::future::Future<Output = Result<bool>>,
1877{
1878 let start = format!("{remote}/{base}");
1879 git::worktree_remove(repo, worktree).await.ok();
1880 let mut retried = false;
1881 if git::branch_exists(repo, branch).await? {
1882 reclaim_stale_branch(repo, remote, &start, branch, &open_pr).await?;
1883 retried = true;
1884 }
1885 loop {
1886 if let Err(e) = git::git(repo, &["branch", branch, &start]).await {
1891 let e = e.context("create the release branch");
1892 if !git::branch_exists(repo, branch).await.unwrap_or(false) {
1893 return Err(e);
1894 }
1895 if retried {
1897 return Err(anyhow!(
1898 "{e:#}; left {branch} in place: it is not one this attempt created"
1899 ));
1900 }
1901 retried = true;
1902 if let Err(r) = reclaim_stale_branch(repo, remote, &start, branch, &open_pr).await {
1903 return Err(anyhow!("{r:#} (after: {e:#})"));
1904 }
1905 continue;
1906 }
1907 if let Some(parent) = worktree.parent() {
1908 tokio::fs::create_dir_all(parent).await.ok();
1909 }
1910 let path = worktree.to_string_lossy();
1911 if let Err(e) = git::git(repo, &["worktree", "add", &path, branch]).await {
1912 let e = e.context("create the release-bump worktree");
1913 return Err(discard_attempt(repo, remote, worktree, branch, e).await);
1914 }
1915 break;
1916 }
1917 match fill(worktree.to_path_buf()).await {
1918 Ok(v) => {
1919 git::worktree_remove(repo, worktree).await.ok();
1922 Ok(v)
1923 }
1924 Err(e) => Err(discard_attempt(repo, remote, worktree, branch, e).await),
1925 }
1926}
1927
1928async fn discard_attempt(
1930 repo: &Path,
1931 remote: &str,
1932 worktree: &Path,
1933 branch: &str,
1934 cause: anyhow::Error,
1935) -> anyhow::Error {
1936 git::worktree_remove(repo, worktree).await.ok();
1937 if !git::branch_exists(repo, branch).await.unwrap_or(false) {
1938 return cause;
1939 }
1940 let note = match git::remote_has_branch(repo, remote, branch).await {
1943 Ok(false) => match git::branch_delete(repo, branch).await {
1944 Ok(true) => return cause,
1945 _ => format!("could not delete the local branch {branch}"),
1946 },
1947 Ok(true) => format!("left {branch} in place: it was pushed to {remote}"),
1948 Err(e) => format!(
1949 "left {branch} in place: could not tell whether it was pushed to {remote} ({e:#})"
1950 ),
1951 };
1952 anyhow!("{cause:#}; {note}")
1953}
1954
1955async fn reclaim_stale_branch<P, PFut>(
1960 repo: &Path,
1961 remote: &str,
1962 start: &str,
1963 branch: &str,
1964 open_pr: &P,
1965) -> Result<()>
1966where
1967 P: Fn(String) -> PFut,
1968 PFut: std::future::Future<Output = Result<bool>>,
1969{
1970 match git::remote_has_branch(repo, remote, branch).await {
1971 Ok(false) => {}
1972 Ok(true) => bail!("the branch {branch} already exists and is on {remote}; left alone"),
1973 Err(e) => bail!(
1974 "the branch {branch} already exists and could not check whether {remote} has it ({e:#}); left alone"
1975 ),
1976 }
1977 match open_pr(branch.to_string()).await {
1978 Ok(false) => {}
1979 Ok(true) => {
1980 bail!("the branch {branch} already exists and has an open pull request; left alone")
1981 }
1982 Err(e) => bail!(
1983 "the branch {branch} already exists and could not check for an open pull request \
1984 ({e:#}); left alone"
1985 ),
1986 }
1987 match git::commits_ahead(repo, start, branch).await {
1988 Ok(0) => {}
1989 Ok(n) => bail!(
1990 "the branch {branch} already exists with {n} commit(s) not in {start}; left alone"
1991 ),
1992 Err(e) => bail!(
1993 "the branch {branch} already exists and could not compare it with {start} ({e:#}); \
1994 left alone"
1995 ),
1996 }
1997 if let Some(held) = git::worktree_holding(repo, branch).await? {
1998 let same = |a: &Path, b: &Path| match (a.canonicalize(), b.canonicalize()) {
1999 (Ok(a), Ok(b)) => a == b,
2000 _ => a == b,
2001 };
2002 if same(&held, repo) {
2003 bail!(
2004 "the branch {branch} already exists and is checked out in the main checkout; left alone"
2005 );
2006 }
2007 git::worktree_remove(repo, &held).await.ok();
2008 }
2009 if !git::branch_delete(repo, branch).await? {
2010 bail!("the branch {branch} already exists and could not be deleted; left alone");
2011 }
2012 Ok(())
2013}
2014
2015async fn open_bump_pr(
2021 state: &mut RunState,
2022 worktree: &Path,
2023 branch: &str,
2024 next_version: &str,
2025 decision: &BumpDecision,
2026 source_pr_url: &str,
2027) -> Result<(String, AutomergeOutcome)> {
2028 let cargo_toml_path = worktree.join("Cargo.toml");
2029 let toml = tokio::fs::read_to_string(&cargo_toml_path)
2030 .await
2031 .with_context(|| format!("read {}", cargo_toml_path.display()))?;
2032 let rewritten = rewrite_cargo_version(&toml, next_version)?;
2033 tokio::fs::write(&cargo_toml_path, rewritten)
2034 .await
2035 .with_context(|| format!("write {}", cargo_toml_path.display()))?;
2036
2037 sync_lockfile(worktree, state.config.cache_dir().as_deref()).await?;
2038
2039 let committed = git::commit_all(worktree, &format!("chore: release v{next_version}"))
2040 .await
2041 .context("commit the version bump")?;
2042 if !committed {
2043 bail!("the version bump left nothing to commit");
2044 }
2045
2046 let remote = state.config.merge.remote.clone();
2047 let pushed = git::push(worktree, &remote, branch).await?;
2048 if !pushed.ok() {
2049 bail!("pushing {branch} failed: {}", pushed.stderr);
2050 }
2051
2052 let (title, body) = release_pr(
2053 decision.level.as_str(),
2054 &decision.reason,
2055 next_version,
2056 &state.id,
2057 source_pr_url,
2058 );
2059 let (title, body) = crate::github_text::prepare(state, &title, &body);
2060 let url = gh_pr_create(worktree, &state.base_branch, branch, &title, &body).await?;
2061 if state.config.release.is_local() {
2065 crate::release_watch::register(&crate::run::home(), &state.repo, &url, &state.id);
2068 return Ok((url, AutomergeOutcome::LocalGate));
2069 }
2070 let outcome = match gh_enable_automerge(worktree, &url).await {
2071 Ok(()) => AutomergeOutcome::Enabled,
2072 Err(e) => {
2073 let reason = e.to_string();
2074 if is_clean_status_refusal(&reason) {
2075 gh_merge_directly(worktree, &url, &title, reason).await
2076 } else {
2077 AutomergeOutcome::Failed { reason }
2078 }
2079 }
2080 };
2081 Ok((url, outcome))
2082}
2083
2084#[derive(Debug, Clone, PartialEq, Eq)]
2086enum AutomergeOutcome {
2087 Enabled,
2089 MergedDirectly { detail: String },
2091 LocalGate,
2093 Failed { reason: String },
2095}
2096
2097fn is_clean_status_refusal(reason: &str) -> bool {
2103 let r = reason.to_lowercase();
2104 r.contains("is in clean status") && r.contains("enablepullrequestautomerge")
2105}
2106
2107pub(crate) fn bump_merge_argv(pr_url: &str, subject: &str) -> Vec<String> {
2110 [
2111 "pr",
2112 "merge",
2113 pr_url,
2114 "--squash",
2115 "--delete-branch",
2116 "--subject",
2117 subject,
2118 ]
2119 .map(str::to_owned)
2120 .to_vec()
2121}
2122
2123fn resolve_direct_merge(
2127 refusal: &str,
2128 argv: &[String],
2129 merge_ok: bool,
2130 stderr: &str,
2131 after: Option<land::PrLifecycle>,
2132) -> AutomergeOutcome {
2133 if merge_ok {
2134 return AutomergeOutcome::MergedDirectly {
2135 detail: format!("automerge was refused ({refusal}); gh {}", argv.join(" ")),
2136 };
2137 }
2138 match land::merged_after_all(argv, stderr, after) {
2139 Some(m) => AutomergeOutcome::MergedDirectly { detail: m.detail },
2140 None => AutomergeOutcome::Failed {
2141 reason: format!("{refusal}; merging directly failed too: {}", stderr.trim()),
2142 },
2143 }
2144}
2145
2146async fn gh_merge_directly(
2150 cwd: &Path,
2151 pr_url: &str,
2152 subject: &str,
2153 refusal: String,
2154) -> AutomergeOutcome {
2155 let argv = bump_merge_argv(pr_url, subject);
2156 let out = match tokio::process::Command::new("gh")
2157 .args(&argv)
2158 .current_dir(cwd)
2159 .quiet()
2160 .stdin(std::process::Stdio::null())
2161 .output()
2162 .await
2163 {
2164 Ok(o) => o,
2165 Err(e) => {
2166 return AutomergeOutcome::Failed {
2167 reason: format!("{refusal}; could not spawn gh to merge directly: {e}"),
2168 };
2169 }
2170 };
2171 let stderr = String::from_utf8_lossy(&out.stderr).into_owned();
2172 let after = if out.status.success() {
2175 None
2176 } else {
2177 land::lifecycle(cwd, pr_url).await.ok()
2178 };
2179 resolve_direct_merge(&refusal, &argv, out.status.success(), &stderr, after)
2180}
2181
2182async fn sync_lockfile(worktree: &Path, cache_dir: Option<&Path>) -> Result<()> {
2190 let mut cmd = tokio::process::Command::new("cargo");
2191 cmd.arg("build").current_dir(worktree).quiet();
2192 if let Some(dir) = cache_dir {
2193 cmd.env("CARGO_TARGET_DIR", dir);
2194 }
2195 let out = cmd
2196 .stdin(std::process::Stdio::null())
2197 .output()
2198 .await
2199 .context("spawn cargo build")?;
2200 if !out.status.success() {
2201 bail!(
2202 "cargo build failed while syncing Cargo.lock: {}",
2203 String::from_utf8_lossy(&out.stderr).trim()
2204 );
2205 }
2206 Ok(())
2207}
2208
2209fn release_pr(
2214 level: &str,
2215 reason: &str,
2216 next_version: &str,
2217 run_id: &str,
2218 source_pr_url: &str,
2219) -> (String, String) {
2220 let title = format!("chore: release v{next_version} ({level} bump)");
2221 let body = format!(
2222 "## Background\n\n\
2223 A change that was just merged is a `{level}` change, so the crate needs a new \
2224 release: {reason}\n\n\
2225 Triggered by magi run `{run_id}`, which landed {source}.\n\n\
2226 ## Change\n\n\
2227 Raises the package version to `v{next_version}` in `Cargo.toml`, with \
2228 `Cargo.lock` following it. Nothing else changes.\n\n\
2229 ## Risk\n\n\
2230 Version-bump-only, so there is nothing here for a reviewer to find. Merging \
2231 it starts the release pipeline (auto-tag, then the release workflow).",
2232 source = source_pr_url,
2233 );
2234 (title, body)
2235}
2236
2237async fn pr_title(repo: &Path, pr_url: &str) -> Result<String> {
2239 let out = tokio::process::Command::new("gh")
2240 .args(["pr", "view", pr_url, "--json", "title"])
2241 .current_dir(repo)
2242 .quiet()
2243 .stdin(std::process::Stdio::null())
2244 .output()
2245 .await
2246 .context("spawn gh pr view")?;
2247 if !out.status.success() {
2248 bail!(
2249 "gh pr view {pr_url}: {}",
2250 String::from_utf8_lossy(&out.stderr).trim()
2251 );
2252 }
2253 #[derive(Deserialize)]
2254 struct Title {
2255 title: String,
2256 }
2257 let parsed: Title = serde_json::from_str(&String::from_utf8_lossy(&out.stdout))
2258 .context("parse `gh pr view --json title` output")?;
2259 Ok(parsed.title)
2260}
2261
2262async fn gh_pr_create(
2263 cwd: &Path,
2264 base: &str,
2265 head: &str,
2266 title: &str,
2267 body: &str,
2268) -> Result<String> {
2269 let out = tokio::process::Command::new("gh")
2270 .args([
2271 "pr", "create", "--base", base, "--head", head, "--title", title, "--body", body,
2272 ])
2273 .current_dir(cwd)
2274 .quiet()
2275 .stdin(std::process::Stdio::null())
2276 .output()
2277 .await
2278 .context("spawn gh pr create")?;
2279 if out.status.success() {
2280 Ok(String::from_utf8_lossy(&out.stdout).trim().to_owned())
2281 } else {
2282 bail!(
2283 "gh pr create: {}",
2284 String::from_utf8_lossy(&out.stderr).trim()
2285 )
2286 }
2287}
2288
2289async fn gh_enable_automerge(cwd: &Path, pr_url: &str) -> Result<()> {
2293 let out = tokio::process::Command::new("gh")
2294 .args([
2295 "pr",
2296 "merge",
2297 pr_url,
2298 "--auto",
2299 "--squash",
2300 "--delete-branch",
2301 ])
2302 .current_dir(cwd)
2303 .quiet()
2304 .stdin(std::process::Stdio::null())
2305 .output()
2306 .await
2307 .context("spawn gh pr merge --auto")?;
2308 if out.status.success() {
2309 Ok(())
2310 } else {
2311 bail!(
2312 "gh pr merge --auto: {}",
2313 String::from_utf8_lossy(&out.stderr).trim()
2314 )
2315 }
2316}
2317
2318async fn gh_pr_edit_title(cwd: &Path, pr_url: &str, title: &str) -> Result<()> {
2322 let out = tokio::process::Command::new("gh")
2323 .args(["pr", "edit", pr_url, "--title", title])
2324 .current_dir(cwd)
2325 .quiet()
2326 .stdin(std::process::Stdio::null())
2327 .output()
2328 .await
2329 .context("spawn gh pr edit")?;
2330 if out.status.success() {
2331 Ok(())
2332 } else {
2333 bail!(
2334 "gh pr edit --title: {}",
2335 String::from_utf8_lossy(&out.stderr).trim()
2336 )
2337 }
2338}
2339
2340#[cfg(test)]
2341mod tests {
2342 use super::*;
2343 use crate::notices::Severity;
2344
2345 #[test]
2346 fn github_facing_bump_text_is_english() {
2347 let (title, body) =
2348 release_pr("minor", "adds a flag", "0.37.0", "ab12", "https://x/pull/1");
2349 assert!(crate::github_text::check(&title, &body).is_empty());
2350 assert!(title.is_ascii() && body.is_ascii(), "{title}\n{body}");
2351 assert_eq!(title, "chore: release v0.37.0 (minor bump)");
2352 assert!(
2353 body.contains("## Background") && body.contains("## Change"),
2354 "{body}"
2355 );
2356 let p = decision_prompt("s", "i", "d", &[], "0.36.5");
2357 assert!(p.contains(crate::prompt::GITHUB_ENGLISH_HEADING), "{p}");
2358 }
2359 use crate::config::Config;
2360 use crate::land::PrLifecycle;
2361
2362 #[tokio::test]
2368 async fn a_disabled_config_does_nothing() {
2369 let config = Config {
2370 merge: crate::config::Merge {
2371 release_bump: false,
2372 ..crate::config::Merge::default()
2373 },
2374 ..Config::default()
2375 };
2376 let mut state = RunState::new(
2377 PathBuf::from("/no/such/repo"),
2378 "main".to_owned(),
2379 "0000000000000000000000000000000000000000".to_owned(),
2380 "irrelevant".to_owned(),
2381 config,
2382 );
2383 after_merge(&mut state, "https://example.invalid/pull/1")
2384 .await
2385 .expect("a disabled config must return Ok without touching anything");
2386 assert!(
2387 state.events.is_empty(),
2388 "nothing should happen at all, not even a logged event"
2389 );
2390 }
2391
2392 async fn origin_with(files: &[(&str, &str)]) -> (tempfile::TempDir, PathBuf) {
2394 let dir = tempfile::tempdir().unwrap();
2395 let origin = dir.path().join("origin.git");
2396 let repo = dir.path().join("repo");
2397 let o = origin.to_string_lossy().into_owned();
2398 git::git(dir.path(), &["init", "--bare", "-b", "main", &o])
2399 .await
2400 .unwrap();
2401 tokio::fs::create_dir_all(&repo).await.unwrap();
2402 git::git(&repo, &["init", "-b", "main"]).await.unwrap();
2403 git::git(&repo, &["config", "user.name", "test"])
2404 .await
2405 .unwrap();
2406 git::git(&repo, &["config", "user.email", "test@example.com"])
2407 .await
2408 .unwrap();
2409 for (name, body) in files {
2410 tokio::fs::write(repo.join(name), body).await.unwrap();
2411 }
2412 git::git(&repo, &["add", "-A"]).await.unwrap();
2413 git::git(&repo, &["commit", "-m", "init"]).await.unwrap();
2414 git::git(&repo, &["remote", "add", "origin", &o])
2415 .await
2416 .unwrap();
2417 git::git(&repo, &["push", "origin", "main"]).await.unwrap();
2418 (dir, repo)
2419 }
2420
2421 async fn no_pr(_: String) -> Result<bool> {
2422 Ok(false)
2423 }
2424
2425 async fn with_branch(ahead: bool) -> (tempfile::TempDir, PathBuf) {
2428 let (d, repo) = origin_with(&[("f", "x\n")]).await;
2429 git::git(&repo, &["branch", "b"]).await.unwrap();
2430 if ahead {
2431 git::git(&repo, &["checkout", "-q", "b"]).await.unwrap();
2432 git::git(&repo, &["commit", "--allow-empty", "-m", "wip"])
2433 .await
2434 .unwrap();
2435 git::git(&repo, &["checkout", "-q", "main"]).await.unwrap();
2436 }
2437 (d, repo)
2438 }
2439
2440 async fn attempt(repo: &Path, open_pr: bool, fail_after_push: Option<bool>) -> Result<()> {
2441 let wt = repo.parent().unwrap().join("bump");
2442 release_attempt(
2443 repo,
2444 "origin",
2445 "main",
2446 &wt,
2447 "b",
2448 |_| async move { Ok(open_pr) },
2449 |w| async move {
2450 if fail_after_push == Some(true) {
2451 git::push(&w, "origin", "b").await?;
2452 }
2453 if fail_after_push.is_some() {
2454 bail!("cargo build failed");
2455 }
2456 Ok(())
2457 },
2458 )
2459 .await
2460 }
2461
2462 #[tokio::test]
2463 async fn a_stale_ancestor_branch_is_deleted_and_the_attempt_proceeds() {
2464 let (_d, repo) = with_branch(false).await;
2465 attempt(&repo, false, None).await.unwrap();
2466 assert!(git::branch_exists(&repo, "b").await.unwrap());
2468 }
2469
2470 #[tokio::test]
2471 async fn a_stale_branch_holding_a_leftover_worktree_is_reclaimed() {
2472 let (_d, repo) = with_branch(false).await;
2473 let old = repo.parent().unwrap().join("old");
2474 git::git(&repo, &["worktree", "add", &old.to_string_lossy(), "b"])
2475 .await
2476 .unwrap();
2477 attempt(&repo, false, None).await.unwrap();
2478 assert!(!old.exists());
2479 }
2480
2481 #[tokio::test]
2482 async fn a_stale_branch_with_an_unmerged_commit_is_kept_with_a_reason() {
2483 let (_d, repo) = with_branch(true).await;
2484 let e = attempt(&repo, false, None).await.unwrap_err().to_string();
2485 assert!(e.contains("`b`") || e.contains("branch b"), "{e}");
2486 assert!(e.contains("1 commit(s) not in origin/main"), "{e}");
2487 assert!(git::branch_exists(&repo, "b").await.unwrap());
2488 }
2489
2490 #[tokio::test]
2491 async fn a_stale_branch_on_the_remote_is_kept() {
2492 let (_d, repo) = with_branch(false).await;
2493 git::git(&repo, &["push", "origin", "b"]).await.unwrap();
2494 let e = attempt(&repo, false, None).await.unwrap_err().to_string();
2495 assert!(e.contains("branch b") && e.contains("is on origin"), "{e}");
2496 assert!(git::branch_exists(&repo, "b").await.unwrap());
2497 }
2498
2499 #[tokio::test]
2500 async fn a_stale_branch_with_an_open_pull_request_is_kept() {
2501 let (_d, repo) = with_branch(false).await;
2502 let e = attempt(&repo, true, None).await.unwrap_err().to_string();
2503 assert!(e.contains("open pull request"), "{e}");
2504 assert!(git::branch_exists(&repo, "b").await.unwrap());
2505 }
2506
2507 #[tokio::test]
2508 async fn an_unanswerable_pull_request_check_keeps_the_branch() {
2509 let (_d, repo) = with_branch(false).await;
2510 let wt = repo.parent().unwrap().join("bump");
2511 let e = release_attempt(
2512 &repo,
2513 "origin",
2514 "main",
2515 &wt,
2516 "b",
2517 |_| async { bail!("offline") },
2518 |_| async { Ok(()) },
2519 )
2520 .await
2521 .unwrap_err()
2522 .to_string();
2523 assert!(
2524 e.contains("could not check for an open pull request"),
2525 "{e}"
2526 );
2527 assert!(git::branch_exists(&repo, "b").await.unwrap());
2528 }
2529
2530 #[tokio::test]
2531 async fn a_failed_attempt_removes_its_own_worktree_and_branch() {
2532 let (_d, repo) = origin_with(&[("f", "x\n")]).await;
2533 let wt = repo.parent().unwrap().join("bump");
2534 let e = attempt(&repo, false, Some(false)).await.unwrap_err();
2535 assert!(format!("{e:#}").contains("cargo build failed"));
2536 assert!(!wt.exists());
2537 assert!(!git::branch_exists(&repo, "b").await.unwrap());
2538 }
2539
2540 #[tokio::test]
2541 async fn a_pushed_branch_survives_a_failed_attempt_and_the_reason_says_so() {
2542 let (_d, repo) = origin_with(&[("f", "x\n")]).await;
2543 let e = attempt(&repo, false, Some(true)).await.unwrap_err();
2544 let e = format!("{e:#}");
2545 assert!(
2546 e.contains("cargo build failed") && e.contains("pushed to origin"),
2547 "{e}"
2548 );
2549 assert!(git::branch_exists(&repo, "b").await.unwrap());
2550 }
2551
2552 #[tokio::test]
2553 async fn a_branch_left_by_a_half_done_worktree_add_is_removed() {
2554 let (_d, repo) = origin_with(&[("f", "x\n")]).await;
2557 let blocker = repo.parent().unwrap().join("blocker");
2558 tokio::fs::write(&blocker, "file").await.unwrap();
2559 let wt = blocker.join("bump");
2560 let r = release_attempt(
2561 &repo,
2562 "origin",
2563 "main",
2564 &wt,
2565 "b",
2566 |_| async { bail!("offline") },
2567 |_| async { Ok(()) },
2568 )
2569 .await;
2570 assert!(r.is_err());
2571 assert!(!git::branch_exists(&repo, "b").await.unwrap());
2572 }
2573
2574 #[tokio::test]
2575 async fn the_retry_is_taken_at_most_once() {
2576 let (_d, repo) = with_branch(false).await;
2579 let blocker = repo.parent().unwrap().join("blocker");
2580 tokio::fs::write(&blocker, "file").await.unwrap();
2581 let wt = blocker.join("bump");
2582 let r = release_attempt(&repo, "origin", "main", &wt, "b", no_pr, |_| async {
2583 Ok(())
2584 })
2585 .await;
2586 assert!(r.is_err());
2587 assert!(!git::branch_exists(&repo, "b").await.unwrap());
2588 }
2589
2590 #[tokio::test]
2591 async fn base_has_cargo_toml_tells_rust_from_non_rust() {
2592 let (_d, rust) = origin_with(&[("Cargo.toml", "[package]\nversion = \"0.1.0\"\n")]).await;
2593 assert!(base_has_cargo_toml(&rust, "origin", "main").await.unwrap());
2594 let (_d2, other) = origin_with(&[("README.md", "hi\n")]).await;
2595 assert!(!base_has_cargo_toml(&other, "origin", "main").await.unwrap());
2596 assert!(base_has_cargo_toml(&other, "origin", "nope").await.is_err());
2598 }
2599
2600 #[tokio::test]
2601 async fn a_repo_without_cargo_toml_skips_with_one_event_and_no_lock() {
2602 let (_d, repo) = origin_with(&[("README.md", "hi\n")]).await;
2603 let home = tempfile::tempdir().unwrap();
2604 let mut state = RunState::new(
2605 repo.clone(),
2606 "main".to_owned(),
2607 "0000000000000000000000000000000000000000".to_owned(),
2608 "task".to_owned(),
2609 Config::default(),
2610 );
2611 state.candidates.push(crate::run::Candidate {
2612 index: 0,
2613 label: 'A',
2614 agent: "x".to_owned(),
2615 branch: "main".to_owned(),
2616 worktree: repo.clone(),
2617 summary: String::new(),
2618 stat: String::new(),
2619 files: 1,
2620 commits: 1,
2621 empty: false,
2622 failed: None,
2623 verified_noop: None,
2624 duration_ms: 0,
2625 folded: false,
2626 });
2627 state.tally = Some(
2628 serde_json::from_value(serde_json::json!({
2629 "first_choice": {}, "borda": {}, "winner": "A",
2630 "unanimous_initial": true, "deliberated": false,
2631 "changed_votes": 0, "unanimous_final": true,
2632 }))
2633 .unwrap(),
2634 );
2635 after_merge_at(
2636 &mut state,
2637 "https://example.invalid/pull/1",
2638 Some(home.path()),
2639 None,
2640 )
2641 .await
2642 .expect("a non-Rust repository is not an error");
2643 let bumps: Vec<_> = state.events.iter().filter(|e| e.node == "bump").collect();
2644 assert_eq!(bumps.len(), 1, "{:?}", state.events);
2645 assert_eq!(
2646 bumps[0].message,
2647 "release bump: no Cargo.toml on the base branch; release bumps are Rust-only, skipping"
2648 );
2649 assert!(
2650 std::fs::read_dir(home.path()).unwrap().next().is_none(),
2651 "no marker and no lock may be created"
2652 );
2653 }
2654
2655 fn winner_state(repo: &Path, base: &str) -> RunState {
2656 let mut state = RunState::new(
2657 repo.to_path_buf(),
2658 base.to_owned(),
2659 "0000000000000000000000000000000000000000".to_owned(),
2660 "task".to_owned(),
2661 Config::default(),
2662 );
2663 state.candidates.push(crate::run::Candidate {
2664 index: 0,
2665 label: 'A',
2666 agent: "x".to_owned(),
2667 branch: "main".to_owned(),
2668 worktree: repo.to_path_buf(),
2669 summary: String::new(),
2670 stat: String::new(),
2671 files: 1,
2672 commits: 1,
2673 empty: false,
2674 failed: None,
2675 verified_noop: None,
2676 duration_ms: 0,
2677 folded: false,
2678 });
2679 state.tally = Some(
2680 serde_json::from_value(serde_json::json!({
2681 "first_choice": {}, "borda": {}, "winner": "A",
2682 "unanimous_initial": true, "deliberated": false,
2683 "changed_votes": 0, "unanimous_final": true,
2684 }))
2685 .unwrap(),
2686 );
2687 state
2688 }
2689
2690 #[tokio::test]
2691 async fn a_real_failure_without_a_pr_raises_one_notice_and_a_retry_folds_into_it() {
2692 let (_d, repo) =
2693 origin_with(&[("Cargo.toml", "[package]\nname=\"x\"\nversion=\"0.1.0\"\n")]).await;
2694 let home = tempfile::tempdir().unwrap();
2695 let store = Notices::at(home.path().join("notifications"));
2696 let mut state = winner_state(&repo, "nope");
2698 let url = "https://example.invalid/pull/1";
2699 after_merge_at(&mut state, url, Some(home.path()), Some(&store))
2700 .await
2701 .expect_err("an unresolvable base is a failure");
2702 let listed = store.list();
2703 assert_eq!(listed.len(), 1, "{listed:?}");
2704 assert!(
2705 listed[0].message.contains("did not run"),
2706 "{}",
2707 listed[0].message
2708 );
2709 assert!(
2710 listed[0].message.contains("Cargo.toml"),
2711 "{}",
2712 listed[0].message
2713 );
2714 assert!(state.events.iter().any(|e| e.node == "bump"));
2715 after_merge_at(&mut state, url, Some(home.path()), Some(&store))
2716 .await
2717 .expect_err("still failing");
2718 let listed = store.list();
2719 assert_eq!(listed.len(), 1, "{listed:?}");
2720 assert_eq!(listed[0].count, 2);
2721 }
2722
2723 #[tokio::test]
2724 async fn not_eligible_cases_raise_no_notice() {
2725 let home = tempfile::tempdir().unwrap();
2726 let store = Notices::at(home.path().join("notifications"));
2727 let url = "https://example.invalid/pull/1";
2728 let (_d, repo) = origin_with(&[("README.md", "hi\n")]).await;
2730 let mut state = winner_state(&repo, "main");
2731 after_merge_at(&mut state, url, Some(home.path()), Some(&store))
2732 .await
2733 .unwrap();
2734 let mut state = winner_state(&repo, "nope");
2736 state.config.merge.release_bump = false;
2737 after_merge_at(&mut state, url, Some(home.path()), Some(&store))
2738 .await
2739 .unwrap();
2740 let mut state = winner_state(&repo, "nope");
2742 state.tally = None;
2743 after_merge_at(&mut state, url, Some(home.path()), Some(&store))
2744 .await
2745 .unwrap();
2746 assert!(store.list().is_empty(), "{:?}", store.list());
2747 }
2748
2749 #[test]
2750 fn the_no_pr_notice_follows_the_configured_language() {
2751 let dir = tempfile::tempdir().unwrap();
2752 let store = Notices::at(dir.path().join("notifications"));
2753 let mut state = merged_state();
2754 state.config.graph.language = "ja".to_owned();
2755 let (n, _) = surface_problem(&mut state, &store, None, Some("0.2.0"), "boom").unwrap();
2756 assert!(n.message.contains("実行されませんでした"), "{}", n.message);
2757 assert!(n.message.contains("boom") && n.message.contains("v0.2.0"));
2758 }
2759
2760 #[test]
2761 fn a_failed_escalation_points_at_the_pending_pr_without_commenting() {
2762 let dir = tempfile::tempdir().unwrap();
2763 let store = Notices::at(dir.path().join("notifications"));
2764 let mut state = merged_state();
2765 let url = "https://example.invalid/pull/9";
2766 let (n, comment) = surface_problem_in(
2767 &mut state,
2768 &store,
2769 Some(url),
2770 Some("0.3.0"),
2771 "push failed",
2772 true,
2773 )
2774 .unwrap();
2775 assert!(comment.is_none());
2776 assert!(
2777 n.message.contains(url) && n.message.contains("v0.3.0"),
2778 "{}",
2779 n.message
2780 );
2781 assert!(!n.message.contains("open the release pull request by hand"));
2782 assert!(matches!(n.link, Some(Link::Url { .. })));
2783 }
2784
2785 #[test]
2786 fn a_failure_notice_names_the_pending_pr_and_the_first_line_of_the_cause() {
2787 let err = anyhow!("outer context").context("cargo build failed\nsecond line");
2788 let with_pr = Progress {
2789 version: Some("0.2.0".into()),
2790 pending_pr: Some("https://example.invalid/pull/9".into()),
2791 };
2792 let (v, reason) = notice_for_failure(&with_pr, &err);
2793 assert_eq!(v.as_deref(), Some("0.2.0"));
2794 assert_eq!(reason, "cargo build failed");
2795 let (v, reason) = notice_for_failure(&Progress::default(), &err);
2796 assert_eq!(v, None);
2797 assert_eq!(reason, "cargo build failed");
2798 }
2799
2800 const NO_RULES: &str = "gh pr merge --auto: GraphQL: Pull request Branch does not have \
2801 required protected branch rules (enablePullRequestAutoMerge)";
2802
2803 fn merged_state() -> RunState {
2804 run::pin_test_home();
2807 let mut s = RunState::new(
2808 PathBuf::from("/no/such/repo"),
2809 "main".to_owned(),
2810 "0000000000000000000000000000000000000000".to_owned(),
2811 "task".to_owned(),
2812 Config::default(),
2813 );
2814 s.status = RunStatus::Merged;
2815 s
2816 }
2817
2818 #[test]
2819 fn the_known_automerge_refusal_names_branch_protection() {
2820 assert!(automerge_hint(NO_RULES).contains("branch protection with required"));
2821 let other = automerge_hint("gh: network unreachable");
2822 assert!(!other.contains("branch protection"), "{other}");
2823 let body = automerge_failure_comment(NO_RULES);
2824 assert!(body.contains("enablePullRequestAutoMerge"), "{body}");
2825 assert!(body.contains("Action required"), "{body}");
2826 }
2827
2828 const CLEAN: &str = "gh pr merge --auto: GraphQL: Pull request Pull request is in clean \
2829 status (enablePullRequestAutoMerge)";
2830
2831 #[test]
2832 fn clean_status_refusal_is_matched_narrowly() {
2833 assert!(is_clean_status_refusal(CLEAN));
2834 assert!(!is_clean_status_refusal(NO_RULES));
2835 assert!(!is_clean_status_refusal("gh: network unreachable"));
2836 assert!(!is_clean_status_refusal("Pull request is in clean status"));
2837 assert!(automerge_hint(CLEAN).contains("already green"));
2838 }
2839
2840 #[test]
2841 fn the_direct_merge_argv_matches_the_land_flags() {
2842 let a = bump_merge_argv("https://github.com/o/r/pull/9", "chore: release v1.0.0");
2843 let l = land::merge_argv(9, "chore: release v1.0.0");
2844 assert_eq!(a[..2], l[..2]);
2845 assert_eq!(a[3..], l[3..]);
2846 assert_eq!(a[2], "https://github.com/o/r/pull/9");
2847 }
2848
2849 #[test]
2850 fn a_direct_merge_is_judged_by_the_forge_not_the_exit_code() {
2851 let argv = bump_merge_argv("u", "t");
2852 let merged = |o: &AutomergeOutcome| matches!(o, AutomergeOutcome::MergedDirectly { .. });
2853 assert!(merged(&resolve_direct_merge(CLEAN, &argv, true, "", None)));
2854 let detached = "not on any branch";
2855 assert!(merged(&resolve_direct_merge(
2856 CLEAN,
2857 &argv,
2858 false,
2859 detached,
2860 Some(PrLifecycle::Merged)
2861 )));
2862 for after in [Some(PrLifecycle::Open), None] {
2863 let o = resolve_direct_merge(CLEAN, &argv, false, "boom", after);
2864 match o {
2865 AutomergeOutcome::Failed { reason } => {
2866 assert!(
2867 reason.contains("clean status") && reason.contains("boom"),
2868 "{reason}"
2869 )
2870 }
2871 other => panic!("expected Failed, got {other:?}"),
2872 }
2873 }
2874 }
2875
2876 #[test]
2877 fn a_local_mode_bump_reads_back_and_old_records_are_not_local() {
2878 let old: run::ReleaseBump =
2879 serde_json::from_str(r#"{"pr_url":"u","automerge_enabled":true}"#).unwrap();
2880 assert!(!old.local);
2881 let mut state = merged_state();
2882 state.release_bump = Some(run::ReleaseBump {
2883 pr_url: Some("https://github.com/o/r/pull/9".to_owned()),
2884 version: Some("1.0.0".to_owned()),
2885 local: true,
2886 ..run::ReleaseBump::default()
2887 });
2888 assert!(!state.needs_attention());
2890 let text = crate::report::run(&state);
2891 assert!(text.contains("release.mode = local"), "{text}");
2892 assert!(!text.contains("FAILED"), "{text}");
2893 }
2894
2895 #[test]
2896 fn a_directly_merged_bump_is_not_reported_as_pending_or_failed() {
2897 let mut state = merged_state();
2898 state.release_bump = Some(run::ReleaseBump {
2899 pr_url: Some("https://github.com/o/r/pull/9".to_owned()),
2900 version: Some("1.0.0".to_owned()),
2901 merged_directly: true,
2902 ..run::ReleaseBump::default()
2903 });
2904 assert!(!state.needs_attention());
2905 let text = crate::report::run(&state);
2906 assert!(text.contains("merged directly"), "{text}");
2907 assert!(!text.contains("FAILED"), "{text}");
2908 }
2909
2910 #[test]
2911 fn an_automerge_failure_is_recorded_shown_and_filed_and_survives_settling() {
2912 let dir = tempfile::tempdir().unwrap();
2913 let store = Notices::at(dir.path().join("notifications"));
2914 let questions = ask::Questions::at(dir.path().join("questions"));
2915 let mut state = merged_state();
2916 let url = "https://github.com/o/r/pull/35";
2917
2918 let (n, comment) =
2919 surface_problem(&mut state, &store, Some(url), Some("0.8.0"), NO_RULES).unwrap();
2920
2921 let comment = comment.expect("a PR was opened, so it gets a comment");
2923 assert!(comment.contains("branch protection"), "{comment}");
2924
2925 assert_eq!(state.status, RunStatus::Merged);
2927 assert!(state.needs_attention());
2928 let text = crate::report::run(&state);
2929 assert!(text.contains("release bump"), "{text}");
2930 assert!(text.contains("FAILED"), "{text}");
2931 assert!(text.contains(url), "{text}");
2932 assert!(text.contains("action required"), "{text}");
2933 assert!(crate::report::line(&state).contains("release needs a human"));
2934
2935 assert_eq!(n.severity, Severity::Error);
2937 assert_eq!(
2938 n.link,
2939 Some(Link::Url {
2940 url: url.to_owned()
2941 })
2942 );
2943 assert_eq!(store.list().len(), 1);
2944 assert!(questions.open_for(&state.id).is_empty());
2945
2946 surface_problem(&mut state, &store, Some(url), Some("0.8.0"), NO_RULES).unwrap();
2948 let listed = store.list();
2949 assert_eq!(listed.len(), 1);
2950 assert_eq!(listed[0].count, 2);
2951 }
2952
2953 #[test]
2954 fn a_bump_that_never_ran_is_surfaced_without_a_pr_comment() {
2955 let dir = tempfile::tempdir().unwrap();
2956 let store = Notices::at(dir.path().join("notifications"));
2957 let mut state = merged_state();
2958 let (n, comment) = surface_problem(&mut state, &store, None, None, "no agent").unwrap();
2959 assert!(comment.is_none());
2960 assert!(matches!(n.link, Some(Link::Run { .. })));
2961 assert!(state.needs_attention());
2962 }
2963
2964 #[test]
2965 fn version_parses_and_bumps_each_digit() {
2966 let v = Version::parse("0.4.0").unwrap();
2967 assert_eq!(
2968 v,
2969 Version {
2970 major: 0,
2971 minor: 4,
2972 patch: 0
2973 }
2974 );
2975
2976 assert_eq!(v.bump(BumpLevel::Major).to_string(), "1.0.0");
2977 assert_eq!(v.bump(BumpLevel::Minor).to_string(), "0.5.0");
2978 assert_eq!(v.bump(BumpLevel::Patch).to_string(), "0.4.1");
2979 }
2980
2981 #[test]
2982 fn version_tolerates_a_prerelease_suffix_on_patch() {
2983 let v = Version::parse("1.2.3-rc1").unwrap();
2984 assert_eq!(
2985 v,
2986 Version {
2987 major: 1,
2988 minor: 2,
2989 patch: 3
2990 }
2991 );
2992 }
2993
2994 #[test]
2995 fn version_rejects_garbage() {
2996 assert!(Version::parse("not-a-version").is_err());
2997 assert!(Version::parse("1.2").is_err());
2998 }
2999
3000 #[test]
3001 fn decision_parses_each_level() {
3002 for (json, level) in [
3003 (
3004 r#"{"level":"major","reason":"drops a config key"}"#,
3005 BumpLevel::Major,
3006 ),
3007 (
3008 r#"{"level":"minor","reason":"adds a new flag"}"#,
3009 BumpLevel::Minor,
3010 ),
3011 (
3012 r#"{"level":"patch","reason":"fixes a race"}"#,
3013 BumpLevel::Patch,
3014 ),
3015 ] {
3016 let decision = parse_decision(json).unwrap();
3017 assert_eq!(decision.level, level);
3018 assert!(!decision.reason.is_empty());
3019 }
3020 }
3021
3022 #[test]
3023 fn decision_wrapped_in_a_fence_and_prose_still_parses() {
3024 let text = "Here is my call.\n\n```json\n{\"level\":\"minor\",\"reason\":\"new HTTP route\"}\n```\n\nDone.";
3025 let decision = parse_decision(text).unwrap();
3026 assert_eq!(decision.level, BumpLevel::Minor);
3027 assert_eq!(decision.reason, "new HTTP route");
3028 }
3029
3030 #[test]
3031 fn a_broken_reply_is_an_error_not_a_default() {
3032 assert!(parse_decision("I decline to answer.").is_err());
3033 assert!(parse_decision(r#"{"level":"huge","reason":"go big"}"#).is_err());
3034 assert!(
3035 parse_decision(r#"{"level":"patch","reason":""}"#).is_err(),
3036 "an empty reason must not pass either"
3037 );
3038 assert!(
3039 parse_decision(r#"{"level":"patch"}"#).is_err(),
3040 "a reply with no reason at all must not pass"
3041 );
3042 }
3043
3044 #[test]
3045 fn prompt_states_the_zero_x_rule_and_the_tie_break() {
3046 let prompt = decision_prompt(
3047 "feat: add a phone endpoint",
3048 "add POST /api/widgets",
3049 "1 file changed, 10 insertions(+)",
3050 &["src/web.rs".to_owned()],
3051 "0.8.0",
3052 );
3053 assert!(prompt.contains("0.8.0"), "the current version is stated");
3054 assert!(
3055 prompt.contains("below `1.0.0`")
3056 && prompt.contains("`minor` is the digit that carries a breaking change"),
3057 "the 0.x rule must be explicit: {prompt}"
3058 );
3059 assert!(
3060 prompt.contains("choose the larger"),
3061 "the tie-break toward the bigger digit must be explicit: {prompt}"
3062 );
3063 }
3064
3065 #[test]
3066 fn release_only_diffs_are_recognised() {
3067 assert!(is_release_only(&["Cargo.toml".to_owned()]));
3068 assert!(is_release_only(&[
3069 "Cargo.toml".to_owned(),
3070 "Cargo.lock".to_owned()
3071 ]));
3072 assert!(!is_release_only(&[]));
3073 assert!(!is_release_only(&[
3074 "Cargo.toml".to_owned(),
3075 "src/main.rs".to_owned()
3076 ]));
3077 }
3078
3079 #[test]
3080 fn cargo_version_rewrite_touches_only_the_package_table() {
3081 let toml = "\
3082[package]\n\
3083# a comment mentioning version on purpose\n\
3084name = \"magi-cli\"\n\
3085version = \"0.8.0\"\n\
3086edition = \"2024\"\n\
3087\n\
3088[dependencies]\n\
3089foo = { version = \"1.2.3\" }\n";
3090 let out = rewrite_cargo_version(toml, "0.9.0").unwrap();
3091 assert!(out.contains("version = \"0.9.0\""));
3092 assert!(
3093 out.contains("foo = { version = \"1.2.3\" }"),
3094 "a dependency's own version pin must survive: {out}"
3095 );
3096 assert!(
3097 out.contains("# a comment mentioning version on purpose"),
3098 "unrelated lines, comments included, must be byte-for-byte preserved: {out}"
3099 );
3100 assert_eq!(
3101 out.lines().count(),
3102 toml.lines().count(),
3103 "the rewrite replaces one line, it does not add or remove any"
3104 );
3105 }
3106
3107 #[test]
3108 fn cargo_version_rewrite_fails_without_a_package_table() {
3109 let toml = "[dependencies]\nfoo = \"1\"\n";
3110 assert!(rewrite_cargo_version(toml, "1.0.0").is_err());
3111 }
3112
3113 #[test]
3119 fn cargo_version_rewrite_falls_back_to_workspace_package_without_a_package_table() {
3120 let toml = "\
3121[workspace]\n\
3122members = [\"crates/a\", \"crates/b\"]\n\
3123\n\
3124[workspace.package]\n\
3125version = \"0.45.18\"\n\
3126edition = \"2024\"\n\
3127\n\
3128[workspace.dependencies]\n\
3129foo = { version = \"1.2.3\" }\n";
3130 let out = rewrite_cargo_version(toml, "0.45.19").unwrap();
3131 assert!(out.contains("version = \"0.45.19\""));
3132 assert!(
3133 out.contains("foo = { version = \"1.2.3\" }"),
3134 "a workspace dependency's own version pin must survive: {out}"
3135 );
3136 assert_eq!(
3137 out.lines().count(),
3138 toml.lines().count(),
3139 "the rewrite replaces one line, it does not add or remove any"
3140 );
3141 }
3142
3143 #[test]
3147 fn cargo_version_rewrite_bumps_an_internal_workspace_dependency_pin() {
3148 let toml = "\
3149[workspace]\n\
3150members = [\"crates/kanade-shared\"]\n\
3151\n\
3152[workspace.package]\n\
3153version = \"0.48.2\"\n\
3154\n\
3155[workspace.dependencies]\n\
3156kanade-shared = { path = \"crates/kanade-shared\", version = \"0.48.2\" }\n";
3157 let out = rewrite_cargo_version(toml, "0.48.3").unwrap();
3158 assert!(out.contains("[workspace.package]\nversion = \"0.48.3\"\n"));
3159 assert!(
3160 out.contains(
3161 "kanade-shared = { path = \"crates/kanade-shared\", version = \"0.48.3\" }"
3162 ),
3163 "the internal pin must move with the workspace version: {out}"
3164 );
3165 }
3166
3167 #[test]
3169 fn cargo_version_rewrite_bumps_an_internal_pin_with_version_before_path() {
3170 let toml = "\
3171[workspace.package]\n\
3172version = \"1.0.0\"\n\
3173\n\
3174[workspace.dependencies]\n\
3175inner = { version = \"1.0.0\", path = \"crates/inner\" }\n";
3176 let out = rewrite_cargo_version(toml, "1.0.1").unwrap();
3177 assert!(out.contains("inner = { version = \"1.0.1\", path = \"crates/inner\" }"));
3178 }
3179
3180 #[test]
3183 fn cargo_version_rewrite_bumps_an_internal_pin_in_dotted_table_form() {
3184 let toml = "\
3185[workspace.package]\n\
3186version = \"2.3.0\"\n\
3187\n\
3188[workspace.dependencies.inner]\n\
3189path = \"crates/inner\"\n\
3190version = \"2.3.0\"\n";
3191 let out = rewrite_cargo_version(toml, "2.4.0").unwrap();
3192 assert!(out.contains("[workspace.package]\nversion = \"2.4.0\"\n"));
3193 assert!(out.contains(
3194 "[workspace.dependencies.inner]\npath = \"crates/inner\"\nversion = \"2.4.0\"\n"
3195 ));
3196 }
3197
3198 #[test]
3203 fn cargo_version_rewrite_bumps_an_internal_pin_in_dotted_key_form() {
3204 let toml = "\
3205[workspace.package]\n\
3206version = \"2.3.0\"\n\
3207\n\
3208[workspace.dependencies]\n\
3209inner.path = \"crates/inner\"\n\
3210inner.version = \"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("inner.path = \"crates/inner\"\ninner.version = \"2.4.0\"\n"));
3214 }
3215
3216 #[test]
3219 fn cargo_version_rewrite_leaves_a_path_only_workspace_dependency_untouched() {
3220 let toml = "\
3221[workspace.package]\n\
3222version = \"0.1.0\"\n\
3223\n\
3224[workspace.dependencies]\n\
3225internal-only = { path = \"crates/internal-only\" }\n";
3226 let out = rewrite_cargo_version(toml, "0.2.0").unwrap();
3227 assert!(out.contains("internal-only = { path = \"crates/internal-only\" }"));
3228 }
3229
3230 #[test]
3234 fn cargo_version_rewrite_leaves_an_external_dependency_untouched() {
3235 let toml = "\
3236[workspace.package]\n\
3237version = \"0.1.0\"\n\
3238\n\
3239[workspace.dependencies]\n\
3240serde = { version = \"1\", features = [\"derive\"] }\n\
3241inner = { path = \"crates/inner\", version = \"0.1.0\" }\n";
3242 let out = rewrite_cargo_version(toml, "0.2.0").unwrap();
3243 assert!(out.contains("serde = { version = \"1\", features = [\"derive\"] }"));
3244 assert!(out.contains("inner = { path = \"crates/inner\", version = \"0.2.0\" }"));
3245 }
3246
3247 #[test]
3251 fn cargo_version_rewrite_without_workspace_dependencies_table_still_bumps_package() {
3252 let toml = "[workspace.package]\nversion = \"0.9.0\"\nedition = \"2024\"\n";
3253 let out = rewrite_cargo_version(toml, "0.10.0").unwrap();
3254 assert_eq!(
3255 out,
3256 "[workspace.package]\nversion = \"0.10.0\"\nedition = \"2024\"\n"
3257 );
3258 }
3259
3260 #[test]
3263 fn cargo_version_rewrite_handles_a_kanade_shaped_workspace_dependencies_table() {
3264 let toml = "\
3265[workspace.package]\n\
3266version = \"0.48.2\"\n\
3267\n\
3268[workspace.dependencies]\n\
3269anyhow = { version = \"1\" }\n\
3270serde = { version = \"1\", features = [\"derive\"] }\n\
3271kanade-shared = { path = \"crates/kanade-shared\", version = \"0.48.2\" }\n\
3272kanade-core = { path = \"crates/kanade-core\", version = \"0.48.2\" }\n\
3273kanade-internal-tool = { path = \"crates/kanade-internal-tool\" }\n";
3274 let out = rewrite_cargo_version(toml, "0.48.3").unwrap();
3275 assert!(out.contains("anyhow = { version = \"1\" }"));
3276 assert!(out.contains("serde = { version = \"1\", features = [\"derive\"] }"));
3277 assert!(
3278 out.contains(
3279 "kanade-shared = { path = \"crates/kanade-shared\", version = \"0.48.3\" }"
3280 )
3281 );
3282 assert!(
3283 out.contains("kanade-core = { path = \"crates/kanade-core\", version = \"0.48.3\" }")
3284 );
3285 assert!(out.contains("kanade-internal-tool = { path = \"crates/kanade-internal-tool\" }"));
3286 }
3287
3288 #[test]
3292 fn cargo_version_rewrite_bails_on_an_unrepresentable_inline_table() {
3293 let toml = "\
3294[workspace.package]\n\
3295version = \"0.1.0\"\n\
3296\n\
3297[workspace.dependencies]\n\
3298inner = { path = \"crates/inner\",\n\
3299 version = \"0.1.0\" }\n";
3300 assert!(rewrite_cargo_version(toml, "0.2.0").is_err());
3301 }
3302
3303 #[test]
3306 fn cargo_version_rewrite_recognises_a_commented_workspace_dependencies_header() {
3307 let toml = "\
3308[workspace.package]\n\
3309version = \"0.1.0\"\n\
3310\n\
3311[workspace.dependencies] # internal pins\n\
3312inner = { path = \"crates/inner\", version = \"0.1.0\" }\n";
3313 let out = rewrite_cargo_version(toml, "0.2.0").unwrap();
3314 assert!(out.contains("inner = { path = \"crates/inner\", version = \"0.2.0\" }"));
3315 }
3316
3317 #[test]
3320 fn cargo_version_rewrite_bumps_a_quoted_dependency_key() {
3321 let toml = "\
3322[workspace.package]\n\
3323version = \"0.1.0\"\n\
3324\n\
3325[workspace.dependencies]\n\
3326\"inner\" = { path = \"crates/inner\", version = \"0.1.0\" }\n";
3327 let out = rewrite_cargo_version(toml, "0.2.0").unwrap();
3328 assert!(out.contains("\"inner\" = { path = \"crates/inner\", version = \"0.2.0\" }"));
3329 }
3330
3331 #[test]
3335 fn cargo_version_rewrite_bumps_a_literal_string_version_pin() {
3336 let toml = "\
3337[workspace.package]\n\
3338version = \"0.1.0\"\n\
3339\n\
3340[workspace.dependencies]\n\
3341inner = { path = 'crates/inner', version = '0.1.0' }\n";
3342 let out = rewrite_cargo_version(toml, "0.2.0").unwrap();
3343 assert!(out.contains("inner = { path = 'crates/inner', version = '0.2.0' }"));
3344 }
3345
3346 #[test]
3352 fn cargo_version_rewrite_does_not_require_the_whole_file_to_parse() {
3353 let toml = "\
3354[workspace.package]\n\
3355version = \"0.1.0\"\n\
3356\n\
3357[workspace.dependencies]\n\
3358inner = { path = \"crates/inner\", version = \"0.1.0\" }\n\
3359\n\
3360[workspace.package]\n\
3361edition = \"2024\"\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 assert!(
3365 toml::from_str::<toml::Value>(toml).is_err(),
3366 "the fixture itself must be invalid as a whole file, or this test proves nothing"
3367 );
3368 }
3369
3370 #[test]
3371 fn current_version_prefers_the_package_table_when_both_exist() {
3372 let toml = "[workspace.package]\nversion = \"9.9.9\"\n\n[package]\nversion = \"0.8.0\"\n";
3373 assert_eq!(current_version(toml).unwrap(), "0.8.0");
3374 }
3375
3376 #[test]
3379 fn current_version_falls_back_to_workspace_package_without_a_package_table() {
3380 let toml = "\
3381[workspace]\n\
3382members = [\"crates/a\", \"crates/b\"]\n\
3383\n\
3384[workspace.package]\n\
3385version = \"0.45.18\"\n";
3386 assert_eq!(current_version(toml).unwrap(), "0.45.18");
3387 }
3388
3389 #[test]
3390 fn coalesce_proceeds_with_nothing_pending() {
3391 assert_eq!(coalesce(None, "0.8.0").unwrap(), Coalesce::Proceed);
3392 }
3393
3394 fn test_pending(target_version: &str, level: BumpLevel) -> PendingBump {
3397 PendingBump {
3398 target_version: target_version.to_owned(),
3399 level,
3400 branch: format!("chore/release-v{target_version}"),
3401 pr_url: "https://example.invalid/pull/9".to_owned(),
3402 }
3403 }
3404
3405 #[test]
3406 fn coalesce_skips_while_the_pending_target_is_still_ahead() {
3407 let pending = test_pending("0.9.0", BumpLevel::Minor);
3408 assert_eq!(
3409 coalesce(Some(&pending), "0.8.0").unwrap(),
3410 Coalesce::Skip {
3411 target_version: "0.9.0".to_owned()
3412 }
3413 );
3414 }
3415
3416 #[test]
3417 fn coalesce_treats_a_landed_or_superseded_pending_bump_as_stale() {
3418 let pending = test_pending("0.9.0", BumpLevel::Minor);
3419 assert_eq!(
3421 coalesce(Some(&pending), "0.9.0").unwrap(),
3422 Coalesce::Proceed
3423 );
3424 assert_eq!(
3426 coalesce(Some(&pending), "1.0.0").unwrap(),
3427 Coalesce::Proceed
3428 );
3429 }
3430
3431 #[test]
3432 fn pending_action_escalates_only_for_a_more_severe_decision() {
3433 assert_eq!(
3434 pending_action(BumpLevel::Patch, BumpLevel::Patch),
3435 PendingAction::AlreadyCovered
3436 );
3437 assert_eq!(
3438 pending_action(BumpLevel::Patch, BumpLevel::Minor),
3439 PendingAction::Escalate
3440 );
3441 assert_eq!(
3442 pending_action(BumpLevel::Patch, BumpLevel::Major),
3443 PendingAction::Escalate
3444 );
3445 assert_eq!(
3446 pending_action(BumpLevel::Minor, BumpLevel::Patch),
3447 PendingAction::AlreadyCovered
3448 );
3449 assert_eq!(
3450 pending_action(BumpLevel::Major, BumpLevel::Minor),
3451 PendingAction::AlreadyCovered
3452 );
3453 assert_eq!(
3454 pending_action(BumpLevel::Major, BumpLevel::Major),
3455 PendingAction::AlreadyCovered
3456 );
3457 }
3458
3459 #[test]
3460 fn pr_state_parsing_reads_open_and_not_open() {
3461 assert!(parse_pr_state(r#"{"state":"OPEN"}"#).unwrap());
3462 assert!(!parse_pr_state(r#"{"state":"CLOSED"}"#).unwrap());
3463 assert!(!parse_pr_state(r#"{"state":"MERGED"}"#).unwrap());
3464 }
3465
3466 #[test]
3467 fn a_lock_is_exclusive_until_dropped() {
3468 let dir = tempfile::tempdir().unwrap();
3469 let marker = dir.path().join("bump").join("deadbeefdeadbeef.json");
3470 let first = MarkerLock::acquire(&marker)
3471 .unwrap()
3472 .expect("first attempt takes the lock");
3473 assert!(
3474 MarkerLock::acquire(&marker).unwrap().is_none(),
3475 "a second attempt must be refused while the first holds it"
3476 );
3477 drop(first);
3478 assert!(
3479 MarkerLock::acquire(&marker).unwrap().is_some(),
3480 "dropping the guard releases the lock for the next attempt"
3481 );
3482 }
3483
3484 #[test]
3485 fn a_stale_lock_is_reclaimed() {
3486 let dir = tempfile::tempdir().unwrap();
3487 let marker = dir.path().join("bump").join("deadbeefdeadbeef.json");
3488 let lock_path = marker.with_extension("lock");
3489 std::fs::create_dir_all(lock_path.parent().unwrap()).unwrap();
3490 std::fs::write(&lock_path, b"").unwrap();
3491 let old = std::time::SystemTime::now() - LOCK_STALE_AFTER - Duration::from_secs(1);
3492 std::fs::OpenOptions::new()
3493 .write(true)
3494 .open(&lock_path)
3495 .unwrap()
3496 .set_modified(old)
3497 .unwrap();
3498 assert!(
3499 MarkerLock::acquire(&marker).unwrap().is_some(),
3500 "a lock older than the stale window must be reclaimed rather than block forever"
3501 );
3502 }
3503
3504 #[tokio::test]
3505 async fn a_contended_lock_is_retried_until_the_holder_releases_it() {
3506 let dir = tempfile::tempdir().unwrap();
3507 let marker = dir.path().join("bump").join("deadbeefdeadbeef.json");
3508 let held = MarkerLock::acquire(&marker)
3509 .unwrap()
3510 .expect("seed the contention");
3511 let releaser = tokio::spawn(async move {
3512 tokio::time::sleep(Duration::from_millis(20)).await;
3513 drop(held);
3514 });
3515 let waited =
3516 wait_for_marker_lock_with(&marker, Duration::from_millis(5), Duration::from_secs(5))
3517 .await
3518 .unwrap();
3519 assert!(
3520 waited.is_some(),
3521 "a merge landing behind another's still-running decision must not be dropped - it \
3522 must wait for that decision to finish and then judge against what it left behind"
3523 );
3524 releaser.await.unwrap();
3525 }
3526
3527 #[tokio::test]
3528 async fn a_lock_held_past_the_ceiling_gives_up() {
3529 let dir = tempfile::tempdir().unwrap();
3530 let marker = dir.path().join("bump").join("deadbeefdeadbeef.json");
3531 let _held = MarkerLock::acquire(&marker).unwrap().unwrap();
3532 let waited =
3533 wait_for_marker_lock_with(&marker, Duration::from_millis(2), Duration::from_millis(10))
3534 .await
3535 .unwrap();
3536 assert!(
3537 waited.is_none(),
3538 "a lock genuinely held past the ceiling must eventually give up rather than wait \
3539 forever"
3540 );
3541 }
3542
3543 #[test]
3544 fn level_between_reads_off_the_differing_digit() {
3545 assert_eq!(
3546 level_between(
3547 Version::parse("0.8.0").unwrap(),
3548 Version::parse("1.0.0").unwrap()
3549 ),
3550 Some(BumpLevel::Major)
3551 );
3552 assert_eq!(
3553 level_between(
3554 Version::parse("0.8.0").unwrap(),
3555 Version::parse("0.9.0").unwrap()
3556 ),
3557 Some(BumpLevel::Minor)
3558 );
3559 assert_eq!(
3560 level_between(
3561 Version::parse("0.8.0").unwrap(),
3562 Version::parse("0.8.1").unwrap()
3563 ),
3564 Some(BumpLevel::Patch)
3565 );
3566 assert_eq!(
3567 level_between(
3568 Version::parse("0.8.0").unwrap(),
3569 Version::parse("0.8.0").unwrap()
3570 ),
3571 None
3572 );
3573 }
3574
3575 #[test]
3576 fn open_release_pr_is_found_among_unrelated_pull_requests() {
3577 let json = r#"[
3578 {"url": "https://example.invalid/pull/1", "headRefName": "feat/something"},
3579 {"url": "https://example.invalid/pull/2", "headRefName": "chore/release-v0.9.0"}
3580 ]"#;
3581 let found = parse_open_release_pr(json).unwrap();
3582 assert_eq!(
3583 found,
3584 Some((
3585 "chore/release-v0.9.0".to_owned(),
3586 "https://example.invalid/pull/2".to_owned()
3587 ))
3588 );
3589 }
3590
3591 #[test]
3592 fn no_open_release_pr_reads_as_none_not_an_error() {
3593 let json =
3594 r#"[{"url": "https://example.invalid/pull/1", "headRefName": "feat/something"}]"#;
3595 assert_eq!(parse_open_release_pr(json).unwrap(), None);
3596 assert_eq!(parse_open_release_pr("[]").unwrap(), None);
3597 }
3598
3599 #[test]
3600 fn marker_round_trips_through_disk() {
3601 let dir = tempfile::tempdir().unwrap();
3602 let path = marker_path(dir.path(), Path::new("/repos/magi"));
3603 assert!(read_marker(&path).is_none());
3604
3605 let marker = test_pending("0.9.0", BumpLevel::Patch);
3606 write_marker(&path, &marker).unwrap();
3607 let read_back = read_marker(&path).unwrap();
3608 assert_eq!(read_back.target_version, "0.9.0");
3609 assert_eq!(read_back.level, BumpLevel::Patch);
3610 assert_eq!(read_back.pr_url, marker.pr_url);
3611
3612 clear_marker(&path);
3613 assert!(read_marker(&path).is_none());
3614 }
3615
3616 #[test]
3617 fn different_repos_get_different_marker_files() {
3618 let dir = tempfile::tempdir().unwrap();
3619 let a = marker_path(dir.path(), Path::new("/repos/a"));
3620 let b = marker_path(dir.path(), Path::new("/repos/b"));
3621 assert_ne!(a, b);
3622 }
3623
3624 #[test]
3628 fn a_bump_pull_requests_own_merge_does_not_retrigger() {
3629 let files = vec!["Cargo.toml".to_owned(), "Cargo.lock".to_owned()];
3630 assert!(
3631 is_release_only(&files),
3632 "the bump pull request's own diff must read as release-only"
3633 );
3634 }
3635
3636 #[test]
3637 fn should_release_bump_reads_only_a_merged_status() {
3638 assert!(should_release_bump(RunStatus::Merged));
3639 for other in [RunStatus::Blocked, RunStatus::Ready, RunStatus::Prep] {
3640 assert!(!should_release_bump(other));
3641 }
3642 }
3643
3644 #[test]
3648 fn all_three_merge_paths_report_pr_lifecycle_merged_case_done() {
3649 let pr = land::PrState {
3650 url: "https://github.com/o/r/pull/1".to_owned(),
3651 number: 1,
3652 state: PrLifecycle::Merged,
3653 checks: land::Checks::Green,
3654 failing: Vec::new(),
3655 review_comments: Vec::new(),
3656 blocking: land::Blocking::No,
3657 };
3658 assert_eq!(
3659 land::decide(&pr, 0, 4, Duration::ZERO),
3660 land::Step::Done { merged: true }
3661 );
3662 assert!(should_release_bump(RunStatus::Merged));
3663 }
3664
3665 #[test]
3670 fn all_three_merge_paths_report_pr_lifecycle_merged_case_direct_merge() {
3671 let pr = land::PrState {
3672 url: "https://github.com/o/r/pull/2".to_owned(),
3673 number: 2,
3674 state: PrLifecycle::Open,
3675 checks: land::Checks::Green,
3676 failing: Vec::new(),
3677 review_comments: Vec::new(),
3678 blocking: land::Blocking::No,
3679 };
3680 assert_eq!(land::decide(&pr, 0, 4, Duration::ZERO), land::Step::Merge);
3681 assert!(should_release_bump(RunStatus::Merged));
3684 }
3685
3686 #[test]
3689 fn all_three_merge_paths_report_pr_lifecycle_merged_case_merged_after_all() {
3690 let argv = land::merge_argv(3, "feat: something");
3691 let outcome = land::merged_after_all(
3692 &argv,
3693 "could not determine current branch: not on any branch",
3694 Some(PrLifecycle::Merged),
3695 );
3696 assert!(outcome.is_some(), "the forge's confirmation must win");
3697 assert!(should_release_bump(RunStatus::Merged));
3698
3699 assert!(land::merged_after_all(&argv, "network error", Some(PrLifecycle::Open)).is_none());
3702 assert!(land::merged_after_all(&argv, "network error", None).is_none());
3703 }
3704
3705 #[test]
3707 fn a_close_or_a_give_up_does_not_trigger_a_bump() {
3708 let pr = land::PrState {
3709 url: "https://github.com/o/r/pull/4".to_owned(),
3710 number: 4,
3711 state: PrLifecycle::Closed,
3712 checks: land::Checks::Green,
3713 failing: Vec::new(),
3714 review_comments: Vec::new(),
3715 blocking: land::Blocking::No,
3716 };
3717 assert_eq!(
3718 land::decide(&pr, 0, 4, Duration::ZERO),
3719 land::Step::Done { merged: false }
3720 );
3721 assert!(!should_release_bump(RunStatus::Blocked));
3722 }
3723}