Skip to main content

magi/
bump.rs

1//! Release version bumps, opened automatically once a merge lands.
2//!
3//! `magi`'s own "Update & restart" only ever looks at tagged GitHub Releases
4//! (`src/updater.rs`); it never builds or tags anything itself. The tag comes
5//! from `auto-tag.yml` noticing a `Cargo.toml` version change on `main`, and
6//! nothing in the graph used to touch that field - a merge that changed the
7//! phone-facing binary left `main` ahead of the last tagged release with
8//! nobody to notice, and the next "Update & restart" found nothing newer.
9//!
10//! This module is the fix. Once [`crate::land`] confirms a merge, the caller
11//! in [`crate::graph`] hands off here: an agent is asked which digit of
12//! `major.minor.patch` the change earns, and this module opens the same
13//! `chore/release-vX.Y.Z` pull request `AGENTS.md` already documents as the
14//! hand-driven recipe, with automerge enabled so CI green is the only thing
15//! standing between the merge and the tag.
16//!
17//! Everything that can be decided without touching a network or a `cargo`
18//! binary is a pure function - the version arithmetic, the `Cargo.toml`
19//! rewrite, the prompt, the coalescing policy - so the policy itself is
20//! asserted directly, the same split [`crate::land`] uses for [`land::decide`](crate::land::decide).
21
22use 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
39/// How long the decision call may run.
40///
41/// It reads a diffstat, a subject line and a version string, and returns
42/// three words and a sentence - nowhere near the budget an implement wave
43/// gets, so a fixed, generous constant is simpler than a new config knob for
44/// a call this small.
45const DECISION_TIMEOUT: Duration = Duration::from_secs(600);
46
47/// Does this run's final status mean the merge this call is downstream of
48/// actually happened?
49///
50/// All three of `land`'s success paths converge on the same signal before
51/// [`crate::graph`] ever calls into this module: a pull request already
52/// merged underneath magi (`land::Step::Done { merged: true }`),
53/// `land::Step::Merge`'s own `gh pr merge` succeeding, and the
54/// [`land::merged_after_all`] recovery for a non-zero exit that merged
55/// anyway. Every one of them ends `land::land` with `pr.state ==
56/// PrLifecycle::Merged`, which is exactly what `graph::Runner::merge` reads
57/// to set `RunStatus::Merged` on the run - see the `all_three_merge_paths_*`
58/// tests below for each path's own evidence. Every path that does *not* land
59/// (a close, `Step::GiveUp`, an unanswered `land_approval`, or a `gh pr
60/// merge` failure the forge does not confirm) leaves the run `Blocked`
61/// instead, so this one check is the whole gate a caller needs.
62pub fn should_release_bump(status: RunStatus) -> bool {
63    status == RunStatus::Merged
64}
65
66/// Which digit of `major.minor.patch` a change earns.
67#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
68#[serde(rename_all = "lowercase")]
69pub enum BumpLevel {
70    /// A breaking change to a public surface.
71    Major,
72    /// A user-visible new capability, or - below `1.0.0` - a breaking change.
73    Minor,
74    /// A fix, internal refactor, or dependency update.
75    Patch,
76}
77
78impl BumpLevel {
79    /// Stable lower-case name, as the prompt and the events spell it.
80    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    /// Severity for comparing two independent decisions: `patch < minor <
89    /// major`, spelled out explicitly rather than derived from declaration
90    /// order, which exists here only for readability and must not silently
91    /// become load-bearing.
92    fn severity(self) -> u8 {
93        match self {
94            Self::Patch => 0,
95            Self::Minor => 1,
96            Self::Major => 2,
97        }
98    }
99}
100
101/// The agent's answer: which digit, and why.
102///
103/// Parsed with [`verdict::extract_json`], so a reply missing `reason`, or
104/// spelling `level` as anything but `major` / `minor` / `patch`, is a parse
105/// error rather than a value with a blank field - [`parse_decision`] never
106/// fabricates a bump out of a response it could not read.
107#[derive(Debug, Clone, Deserialize)]
108pub struct BumpDecision {
109    /// The chosen digit.
110    pub level: BumpLevel,
111    /// One line, carried into the pull request body so "why was this minor"
112    /// is answerable later without archaeology.
113    pub reason: String,
114}
115
116/// Parse the agent's reply. Never returns a default decision: an unparsable
117/// or incomplete reply is `Err`, and the caller must not open a bump pull
118/// request on the strength of a guess.
119pub 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/// `major.minor.patch`, the only shape a `[package] version` in this
128/// ecosystem carries in practice.
129#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
130pub struct Version {
131    /// First component.
132    pub major: u64,
133    /// Second component.
134    pub minor: u64,
135    /// Third component.
136    pub patch: u64,
137}
138
139impl Version {
140    /// Parse `major.minor.patch`. A pre-release or build suffix on the patch
141    /// component (`0.8.0-rc1`) is tolerated by reading only its leading
142    /// digits - Cargo itself never writes one into `[package] version`, but a
143    /// human editing the file by hand might.
144    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    /// The next version at `level`. A `major`/`minor` bump zeroes every digit
173    /// below it, matching what every tool that reads a semver range expects.
174    #[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
202/// Did the merged change touch only the release manifest and its lockfile?
203///
204/// [`after_merge`] is reached from *every* qualifying merge, including a
205/// version-bump pull request's own - without this check a bump would trigger
206/// another bump forever. A human-authored version-only pull request is exempt
207/// from review for the same reason (`AGENTS.md`'s "version-bump-only pull
208/// requests"), so using its shape as the "do not treat this as a trigger"
209/// test is one rule doing both jobs instead of two.
210pub fn is_release_only(files: &[String]) -> bool {
211    !files.is_empty() && files.iter().all(|f| f == "Cargo.toml" || f == "Cargo.lock")
212}
213
214/// Rewrite `table`'s `version = "..."` line, leaving every other byte
215/// untouched.
216///
217/// Scoped to the named table specifically, rather than the first line
218/// anywhere in the file that looks like `version = "..."`: a dependency
219/// pinned as `foo = { version = "1.2.3" }` must never move, and neither must
220/// the *other* of `[package]` / `[workspace.package]` when only one of them
221/// is the one being bumped. That scoping is what lets a version-bump-only
222/// diff stay exactly that, which [`is_release_only`] and the "no reviewer
223/// needed" exemption in `AGENTS.md` both rest on.
224fn 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
247/// Truncate `s` at the first `#` that is not inside a quoted string, the
248/// same rule a TOML parser uses to tell a comment from a literal `#` inside
249/// a value. Used only on table-header lines here (`[workspace.dependencies]
250/// # internal pins` is valid TOML), so header comparisons don't miss a
251/// section just because it carries a trailing comment.
252fn 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
270/// Strip a single layer of matching quotes from a TOML key, so a
271/// `"name" = { .. }` or `'name' = { .. }` entry compares equal to the plain
272/// `name` the `toml` crate itself hands back for the same key - Cargo
273/// manifests almost never quote a dependency key (bare keys already allow
274/// `-`), but it is legal TOML and costs nothing extra to normalise.
275fn 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
284/// Pull just the `[workspace.dependencies]` table - flat entries and any
285/// `[workspace.dependencies.<name>]` sub-tables - out of a full manifest and
286/// rewrite its headers to `[dependencies]` / `[dependencies.<name>]`, so the
287/// fragment parses standalone as TOML.
288///
289/// This is what keeps [`internal_pin_names`] and [`verify_pins_rewritten`]
290/// from imposing a whole-file strict-TOML precondition on every workspace
291/// manifest this rewrite runs against: only the dependency table itself has
292/// to parse, not any other section a hand-edited `Cargo.toml` might carry in
293/// a shape this crate's pinned `toml` version does not accept. Returns an
294/// empty string when the manifest has no such table at all.
295fn 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
322/// Names of `[workspace.dependencies]` entries that name an internal member
323/// by *both* `path` and `version` - the shape `AGENTS.md`'s own "internal
324/// version pin" guidance recommends for a published member that another
325/// workspace member depends on. Parsed with the `toml` crate (already a
326/// dependency, used read-only here) rather than by scanning for the word
327/// `version`, so an ordinary `[dependencies]` entry in some other table, or a
328/// `[workspace.dependencies]` entry that carries only one of the two keys,
329/// never enters the candidate set:
330///
331/// - `path` only (no `version`): an unpublished, workspace-only member - not
332///   ours to touch.
333/// - `version` only (no `path`): an external crates.io dependency - not ours
334///   to touch either.
335///
336/// Returns an empty list, not an error, when the manifest has no
337/// `[workspace.dependencies]` table at all - the common single-crate shape -
338/// so [`rewrite_cargo_version`]'s existing `[package]` path is unaffected.
339fn 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
361/// Rewrite the quoted string value of `key = "..."` (or `key = '...'`, a
362/// literal string) on `line`, wherever it appears - once for an inline table
363/// (`name = { path = "..", version = ".." }`, either key order) and once for
364/// a dotted `[workspace.dependencies.name]` table's own `version = ".."`
365/// line. The replacement is written back between the *same* quote
366/// characters the line already used, so a literal-string pin stays a
367/// literal string. Returns `None` when `key` is not present on this line as
368/// a `key = "value"` pair, which the caller treats as "could not rewrite
369/// this one" rather than silently leaving it unbumped.
370fn 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
405/// Rewrite the `version` pin of each `[workspace.dependencies]` entry named
406/// in `names` to `new_version`, in every shape Cargo accepts: the inline
407/// table (`name = { path = "..", version = "old" }`), the dotted-key form
408/// under the flat table (`name.path = ".."` / `name.version = "old"` as two
409/// separate lines), and the dotted sub-table (`[workspace.dependencies.
410/// name]` followed by its own `version = "old"` line). Every other byte,
411/// including entries not in `names`, is untouched - same discipline as
412/// [`rewrite_table_version`].
413///
414/// Bails rather than silently leaving a pin unbumped when a named entry's
415/// `version` field cannot be located on a single line this way (for example
416/// an inline table split across lines): a bump pull request that leaves a
417/// stale internal pin behind is exactly the failure this exists to prevent,
418/// so an unrepresentable form must stop the bump, not ship it half-done.
419fn 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            // The inline-table form: `name = { path = "..", version = ".." }`.
449            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                // The dotted-key form: `name.path = ".."` / `name.version =
460                // ".."` as two separate lines directly under
461                // `[workspace.dependencies]`, with no inline table and no
462                // `[workspace.dependencies.name]` sub-header either.
463                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
494/// Confirm every entry in `names` now reads `new_version` under
495/// `[workspace.dependencies]`, by reparsing the rewritten manifest rather
496/// than trusting the line-based rewrite's own bookkeeping. The safety net
497/// this run-time failure on the pending release bump is guarding against
498/// happened once already: `kanadehq/kanade`'s pin was left stale and its own
499/// `internal_pins_match_the_workspace_version` regression test caught it in
500/// CI, after the bump pull request had already opened.
501fn 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
522/// Rewrite the release version, wherever this manifest actually declares it.
523///
524/// A single crate carries its version under `[package]`. A workspace root
525/// with no crate of its own - `[workspace] members = [...]` and nothing
526/// else - carries it under `[workspace.package]` instead, and `[package]`
527/// does not exist there at all. `[package]` is tried first because it is the
528/// far more common shape and the one every existing bump so far has hit;
529/// `[workspace.package]` is the fallback for the shape that never worked
530/// before this.
531///
532/// A workspace manifest can also carry a *second*, independent version
533/// literal per internal member: `[workspace.dependencies].<name>` entries
534/// that reference a published member by both `path` and `version`, exactly
535/// the shape `AGENTS.md` documents as the canonical place to centralize that
536/// pin. Cargo does not derive that literal from `[workspace.package]
537/// version` - nothing does - so once the table version is rewritten, every
538/// such pin is rewritten to match in the same edit, and the result is
539/// reparsed to confirm it before this function returns. An entry with only
540/// `path` (an unpublished workspace-only member) or only `version` (an
541/// external dependency) is left untouched, as is a plain single-crate
542/// manifest with no `[workspace.dependencies]` table at all.
543pub 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
558/// Find `table`'s `version` field, if it has one. No I/O.
559fn 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
582/// Read the version currently on the base branch, from `[package]` if it has
583/// one, else from `[workspace.package]` - see [`rewrite_cargo_version`] for
584/// why both exist and which wins. No I/O: the caller fetches the blob (`git
585/// show <remote>/<base>:Cargo.toml`).
586pub(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
592/// Build the prompt asking an agent which digit of `major.minor.patch` a
593/// merged change earns.
594///
595/// Pure: every input is already known once a merge lands, so the whole
596/// decision policy - the "`minor` is the breaking digit below `1.0.0`" rule,
597/// what counts as a breaking surface, and the tie-break toward the larger
598/// digit - is asserted directly on the returned string, the same way
599/// [`crate::land::fix_prompt`] doc-comments its own rules rather than leaving
600/// them for a human to spot missing from a live reply.
601pub 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    // The reason is pasted into the release pull request's body.
650    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/// magi's own record of a bump pull request it currently has open, so a
660/// burst of merges in quick succession does not each open a competing
661/// release.
662///
663/// **Chosen policy: serialize, not coalesce two independent decisions into
664/// one.** A bump branch touches only `Cargo.toml` / `Cargo.lock`, so `gh pr
665/// merge --squash` applies it onto whatever the base branch has become by
666/// the time it lands - every commit merged while it was open rides along
667/// for free, at no extra cost, once it merges. But the *digit* a still-open
668/// pull request targets was judged from only the first change, and a more
669/// severe change landing while it waits must not ship at the smaller digit
670/// just because it arrived second - so the serialization is at the pull
671/// request, not at the judgement: a later, more severe decision escalates
672/// the same open pull request (see [`pending_action`]) rather than opening a
673/// second one or being silently absorbed at the wrong digit.
674#[derive(Debug, Clone, Serialize, Deserialize)]
675pub struct PendingBump {
676    /// The version the open pull request bumps to.
677    pub target_version: String,
678    /// The digit that version was judged to need, so a later, more severe
679    /// merge can tell it needs to escalate rather than assume it is covered.
680    pub level: BumpLevel,
681    /// The branch the open pull request is built from, so an escalation
682    /// knows what to check out and push to.
683    pub branch: String,
684    /// The pull request's URL, so a later merge can confirm it is still
685    /// open before trusting it to block a fresh decision.
686    pub pr_url: String,
687}
688
689/// Where [`PendingBump`] is recorded for `repo` - one file per repository, so
690/// a machine running magi against more than one checkout does not confuse
691/// their releases with each other.
692pub 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
698/// Read a recorded [`PendingBump`], if any. Missing or unreadable both read
699/// as "nothing pending" - a marker is bookkeeping, not a source of truth
700/// worth failing a merge over.
701pub 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
706/// Persist `marker`, atomically - the same tmp-then-rename shape
707/// [`crate::updater::write_progress`] uses, since this file is read by a
708/// later, unrelated process invocation and must never be seen half-written.
709pub 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
720/// Drop a recorded marker. Best-effort: a marker that is already gone is not
721/// an error.
722pub fn clear_marker(path: &Path) {
723    let _ = std::fs::remove_file(path);
724}
725
726/// What a recorded [`PendingBump`] means for a fresh decision, given what the
727/// base branch's `Cargo.toml` says right now. No I/O: the caller reads both
728/// the marker and the version.
729#[derive(Debug, Clone, PartialEq, Eq)]
730pub enum Coalesce {
731    /// Nothing is pending, or the pending bump already landed (or was
732    /// superseded by a manual one) - safe to open a fresh decision.
733    Proceed,
734    /// A bump to `target_version` is already open; do not open a second one.
735    Skip {
736        /// The version the pending pull request already targets.
737        target_version: String,
738    },
739}
740
741/// Decide what a pending marker means against `current_version`.
742pub 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/// What a still-open pending bump means once a fresh decision is in hand.
757#[derive(Debug, Clone, Copy, PartialEq, Eq)]
758pub enum PendingAction {
759    /// The new decision is no more severe than what is already queued; the
760    /// open pull request covers it once it lands.
761    AlreadyCovered,
762    /// The new decision outranks the pending target - escalate the open
763    /// pull request instead of opening a second one or dropping it.
764    Escalate,
765}
766
767/// Compare a fresh decision against what a still-open pull request already
768/// targets.
769///
770/// A patch bump left pending while a breaking change lands does not become a
771/// breaking release just because the pull request that carries both is
772/// squashed into one commit: the *version number* still comes from whichever
773/// digit was judged, and a pending `patch` never widens itself to `minor` on
774/// its own. This is the check that decides an escalation is owed.
775pub 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
783/// Parse `gh pr view --json state` output. No I/O.
784fn 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
794/// Is the pull request at `pr_url` still open?
795///
796/// Read fresh rather than trusted from the marker: a bump pull request can be
797/// closed without merging - CI that never goes green, an operator who
798/// decided against it - and nothing else in this module ever revisits a
799/// marker once it is written. Without this check, that close is invisible
800/// here forever: the marker still names a pending target, the base branch
801/// never reaches it because nothing ever merged the pull request, and every
802/// later merge skips in perpetuity. A `gh` failure (network, auth) answers
803/// `true` - the same "unreadable is not absent" rule `land::CHECKS_GRACE`
804/// uses - because guessing "closed" wrongly opens a second, competing pull
805/// request, while guessing "open" wrongly only costs one more merge's wait.
806async 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
824/// How long a stale lock file is trusted to mean its owner is still working,
825/// before it is reclaimed.
826///
827/// Long enough to cover the slowest real step this module takes - the agent
828/// decision call ([`DECISION_TIMEOUT`]) plus `cargo build` and a `gh pr
829/// create` - so a lock is only ever stolen from a process that has actually
830/// gone (crashed, killed), never one still inside its own critical section.
831const LOCK_STALE_AFTER: Duration = Duration::from_secs(30 * 60);
832
833/// A host-local mutual exclusion for one repository's marker file.
834///
835/// Built on exclusive file creation rather than a locking crate: neither
836/// `flock` nor `fs2` is a dependency of this crate, and the constraints on
837/// this change forbid adding one. This is not a distributed lock and does
838/// not coordinate two machines racing the same repository - it exists to
839/// close the specific race two `after_merge` calls on the *same* host can
840/// hit landing within the same window (a human `magi run` alongside the
841/// daemon, or two review loops): both would otherwise read "nothing
842/// pending", judge independently, and open two competing pull requests, with
843/// whichever `write_marker` runs last silently erasing the other's record.
844struct MarkerLock {
845    path: PathBuf,
846}
847
848impl MarkerLock {
849    /// Try to take the lock for `marker`, stealing a stale one first if it is
850    /// old enough to mean its owner is gone rather than merely slow.
851    /// `Ok(None)` means someone else genuinely holds it right now.
852    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
897/// How often a blocked caller checks whether [`MarkerLock`] has freed up.
898const LOCK_POLL: Duration = Duration::from_secs(5);
899
900/// How long a caller waits for a contended lock before giving up on this
901/// merge's own judgement entirely.
902///
903/// A first version of this gate gave up the instant the lock was taken,
904/// which meant a change landing while another host's decision call was
905/// still running was never judged at all - not even recorded as pending,
906/// not escalated later, just dropped. The lock is only ever held for one
907/// `after_merge` call, so waiting past it is what lets that call's own
908/// decision reach [`pending_action`] against a marker the other side just
909/// finished writing, instead of finding nothing to check against. Set just
910/// under [`LOCK_STALE_AFTER`]: a lock still held this long after that point
911/// is reclaimed as abandoned rather than waited on further.
912const LOCK_WAIT_CEILING: Duration = Duration::from_secs(25 * 60);
913
914/// Wait for [`MarkerLock`] to free up, polling rather than blocking forever.
915/// `Ok(None)` means the ceiling passed with the lock still held.
916async 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
920/// [`wait_for_marker_lock`] with the poll interval and ceiling as parameters,
921/// so the retry behaviour is testable without a test actually waiting out
922/// [`LOCK_WAIT_CEILING`].
923async 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
941/// Which digit differs between `from` and `to`? `None` when they are equal.
942///
943/// Used to recover the level a pull request found by [`find_open_release_pr`]
944/// was judged at: the forge has the resulting version (in the branch name and
945/// the title) but not the digit an agent chose to get there, and this is the
946/// one other host-independent fact every host can compute the same way from
947/// it.
948fn 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
960/// Parse `gh pr list --state open --json url,headRefName` output, returning
961/// the first pull request whose branch is one of this module's own. No I/O.
962fn 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
977/// Every open pull request on one of this module's own branches, as
978/// `(branch, url)`. No I/O.
979pub(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
995/// [`find_open_release_pr`], but every match rather than the first.
996pub(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
1024/// Ask the forge directly whether a release bump is already open, for a host
1025/// that has never seen it.
1026///
1027/// [`MarkerLock`] and the marker file only ever coordinate *this* host - a
1028/// marker written on one machine is not visible to `run::home()` on another,
1029/// so two hosts landing runs against the same repository at the same time
1030/// can each read "nothing pending" and open a competing pull request no
1031/// local lock can see. `gh pr list` is the one place every host actually
1032/// shares a view, so it is consulted whenever this host's own marker says
1033/// there is nothing pending, before a fresh decision is allowed to open a
1034/// second pull request. This narrows the race to the gap between this call
1035/// and whichever host's `gh pr create` lands first - it does not close it -
1036/// because turning that into a real distributed lock would need coordination
1037/// this crate has no dependency for.
1038async 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
1056/// After a merge lands, ask an agent how big the change was and open a
1057/// release bump sized to it.
1058///
1059/// Best-effort by construction, the same way `clean::fold_due` treats one
1060/// run's fold failure: this runs after the merge the run exists to produce
1061/// has already succeeded, so a failure here (the decision call, `gh`,
1062/// `cargo`) must never turn a landed run into a failed one. The caller logs
1063/// whatever this returns and moves on.
1064///
1065/// An `Err` is a bump that was tried and failed, never one that was not
1066/// eligible (every such case returns `Ok` after an event). When it fails
1067/// before any release pull request exists, the operator is notified here, so
1068/// the caller only has to record the event: nobody would otherwise learn that
1069/// a release silently never happened. A failure with a pull request in hand
1070/// goes through [`report_problem`] with its URL instead, and is not repeated.
1071/// A failure while a pending release pull request is in play (the decision or
1072/// an escalation of it) is notified here too, naming that pull request: the
1073/// escalation path itself never raises one, so suppressing it would leave the
1074/// operator with nothing.
1075pub async fn after_merge(state: &mut RunState, pr_url: &str) -> Result<()> {
1076    after_merge_at(state, pr_url, None, None).await
1077}
1078
1079/// What one attempt had settled by the time it failed.
1080#[derive(Debug, Default)]
1081struct Progress {
1082    /// The target version, once the decision had been made.
1083    version: Option<String>,
1084    /// A release pull request already pending when this attempt started.
1085    pending_pr: Option<String>,
1086}
1087
1088/// The `(version, reason)` to notify with for a failed attempt. The reason is
1089/// the first line of the full error chain, so the operator can tell a stale
1090/// branch from a build failure. A pull request this attempt opened never reaches here: past
1091/// `gh pr create` nothing returns `Err`, and automerge trouble goes through
1092/// [`report_problem`] itself.
1093fn 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
1099/// Does the base branch carry a `Cargo.toml` at its root? Release bumps read
1100/// and rewrite that file, so its absence means "not a Rust repository", which
1101/// is not a fault. `ls-tree` rather than `cat-file -e`, so an unresolvable
1102/// ref (a failed fetch, a misconfigured base) stays an error instead of being
1103/// reported as a non-Rust repository.
1104async 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
1120/// [`after_merge`] with an optional magi home, so tests can point the
1121/// marker and its lock at a scratch directory.
1122/// `store` is where a notice is raised; `None` is the operator's own.
1123async 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    // Outside the lock, and before anything that assumes a Rust manifest.
1176    // Fetch first so a stale remote-tracking ref cannot misjudge the base.
1177    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    // Held for the rest of this function: the whole read-decide-write
1188    // sequence below is the critical section two `after_merge` calls landing
1189    // within the same window must not both be inside at once. See
1190    // `MarkerLock`'s own doc for why a second, unrelated bump PR is what
1191    // that race produces without it, and `wait_for_marker_lock`'s for why
1192    // this waits rather than giving up the instant it is contended.
1193    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                // Landed, or superseded by a manual bump: free for a fresh
1212                // decision.
1213                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                // Otherwise still genuinely open: fall through and ask the
1230                // same question this merge would get on a fresh path, so a
1231                // more severe change landing while it waits can escalate it
1232                // instead of being silently absorbed at the wrong digit.
1233            }
1234        }
1235    }
1236
1237    if pending.is_none() {
1238        // This host's own marker has nothing to say - check the forge itself
1239        // before trusting that to mean a fresh pull request is safe to open.
1240        // See `find_open_release_pr`'s own doc for what this does and does
1241        // not close.
1242        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                // Best-effort: worst case this host asks the forge again
1258                // next time instead of finding its own record of it.
1259                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    // No dedicated role for this one-off decision. Borrows `[roles] chatter`
1277    // - the nearest surviving single-agent-seat preference - rather than
1278    // falling straight to `agent::pick`'s own default order, so an operator
1279    // who has already named a preferred seat there is not silently
1280    // overridden for this decision too.
1281    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            // The decision reads a diffstat and writes a verdict; it must
1297            // never touch a file.
1298            allow_write: false,
1299            sessions: false,
1300            artifacts: &artifacts,
1301            stem: "bump-decision",
1302            run: &state.id,
1303            node: "bump",
1304            cache_dir: state.config.cache_dir().as_deref(),
1305            attachments: &[],
1306            writable: &[],
1307        },
1308    )
1309    .await
1310    .context("ask an agent how big the merged change was")?;
1311    if !out.usable() {
1312        bail!(
1313            "the release-bump decision produced nothing usable (exit {:?}, timed out: {})",
1314            out.exit_code,
1315            out.timed_out
1316        );
1317    }
1318    let decision = parse_decision(&out.text).context("parse the release-bump decision")?;
1319
1320    if let Some(p) = pending {
1321        return match pending_action(p.level, decision.level) {
1322            PendingAction::AlreadyCovered => {
1323                state.event(
1324                    "bump",
1325                    format!(
1326                        "a release bump to v{} ({}) already covers at least a {} change; not \
1327                         opening another",
1328                        p.target_version,
1329                        p.pr_url,
1330                        decision.level.as_str()
1331                    ),
1332                );
1333                Ok(())
1334            }
1335            PendingAction::Escalate => {
1336                progress.version = Some(
1337                    Version::parse(&base_version)?
1338                        .bump(decision.level)
1339                        .to_string(),
1340                );
1341                escalate_pending(state, &repo, &remote, &p, &decision, &base_version, &marker).await
1342            }
1343        };
1344    }
1345
1346    let next = Version::parse(&base_version)?
1347        .bump(decision.level)
1348        .to_string();
1349    progress.version = Some(next.clone());
1350    let branch = format!("chore/release-v{next}");
1351    let worktree = state.dir().join("bump");
1352    let (shared, branch_ref, next_ref, decision_ref) = (&*state, &branch, &next, &decision);
1353    let (pr_url_opened, outcome) =
1354        release_attempt(
1355            &repo,
1356            &remote,
1357            &base,
1358            &worktree,
1359            &branch,
1360            |head| {
1361                let repo = repo.clone();
1362                async move { gh_open_pr_for_head(&repo, &head).await }
1363            },
1364            |wt| async move {
1365                open_bump_pr(shared, &wt, branch_ref, next_ref, decision_ref, pr_url).await
1366            },
1367        )
1368        .await?;
1369    let local = outcome == AutomergeOutcome::LocalGate;
1370    let (automerge_warning, merged_detail) = match outcome {
1371        AutomergeOutcome::Enabled | AutomergeOutcome::LocalGate => (None, None),
1372        AutomergeOutcome::MergedDirectly { detail } => (None, Some(detail)),
1373        AutomergeOutcome::Failed { reason } => (Some(reason), None),
1374    };
1375
1376    // The pull request exists on the forge the moment `open_bump_pr` returns
1377    // its URL, regardless of what happens next - so the event that names it
1378    // is unconditional, and a marker write failing (a full disk, a missing
1379    // `home/bump` directory) is reported as its own warning rather than
1380    // swallowing that URL entirely the way propagating it with `?` would.
1381    // `find_open_release_pr` is the fallback if this leaves no local record:
1382    // the next merge that finds no marker still finds this pull request on
1383    // the forge before opening a second one.
1384    let marker_write = write_marker(
1385        &marker,
1386        &PendingBump {
1387            target_version: next.clone(),
1388            level: decision.level,
1389            branch,
1390            pr_url: pr_url_opened.clone(),
1391        },
1392    );
1393    state.event(
1394        "bump",
1395        format!(
1396            "opened a {} release bump to v{next} ({}): {pr_url_opened}",
1397            decision.level.as_str(),
1398            decision.reason
1399        ),
1400    );
1401    if let Err(e) = marker_write {
1402        state.event(
1403            "bump",
1404            format!(
1405                "could not record the pending release bump marker for v{next}: {e:#}; a later \
1406                 merge may open a duplicate pull request if it cannot find {pr_url_opened} on \
1407                 the forge either"
1408            ),
1409        );
1410    }
1411    state.release_bump = Some(run::ReleaseBump {
1412        pr_url: Some(pr_url_opened.clone()),
1413        version: Some(next.clone()),
1414        automerge_enabled: automerge_warning.is_none() && merged_detail.is_none() && !local,
1415        merged_directly: merged_detail.is_some(),
1416        local,
1417        ..run::ReleaseBump::default()
1418    });
1419    if let Some(detail) = merged_detail {
1420        // Merged already: a pending marker would make the next merge wait on
1421        // a pull request that is gone.
1422        clear_marker(&marker);
1423        state.event("bump", format!("merged v{next} directly: {detail}"));
1424    }
1425    if let Some(warning) = automerge_warning {
1426        state.event(
1427            "bump",
1428            format!("could not enable automerge on {pr_url_opened}: {warning}; merge it by hand"),
1429        );
1430        report_problem(state, Some(&pr_url_opened), Some(&next), &warning).await;
1431    }
1432    Ok(())
1433}
1434
1435/// The node name post-merge notices were filed under, back when they were
1436/// questions. Kept because [`ask::Questions::settle_run`] must go on exempting
1437/// any such question still open on disk; new problems go to
1438/// [`crate::notices`] instead - nothing here is something to answer.
1439pub const NOTICE_NODE: &str = "release-bump";
1440
1441/// What to tell the operator to do about a refused `gh pr merge --auto`.
1442///
1443/// Keys on the wording GitHub is known to use when the base branch has no
1444/// required status checks (`enablePullRequestAutoMerge` / "protected branch
1445/// rules"); anything else falls back to the generic advice, with the reason
1446/// carried verbatim next to it.
1447fn automerge_hint(reason: &str) -> &'static str {
1448    let r = reason.to_lowercase();
1449    if is_clean_status_refusal(reason) {
1450        "merge the release pull request by hand; CI is already green"
1451    } else if r.contains("enablepullrequestautomerge") || r.contains("protected branch rules") {
1452        "merge the release pull request by hand, and enable branch protection with required \
1453         status checks on the base branch so automerge can work next time"
1454    } else {
1455        "merge the release pull request by hand"
1456    }
1457}
1458
1459/// The comment left on the release pull request itself.
1460fn automerge_failure_comment(reason: &str) -> String {
1461    format!(
1462        "magi could not enable automerge on this pull request: {reason}\n\n\
1463         Action required: {}. Until then the release does not happen.",
1464        automerge_hint(reason)
1465    )
1466}
1467
1468/// Record a post-merge problem on the run and raise the operator-facing
1469/// notification, without touching the forge. Returns the notice and the
1470/// comment body meant for the release pull request when there is one.
1471///
1472/// Split from [`report_problem`] so the state, the notice and the wording
1473/// can be asserted without a `gh`. The notice is keyed on the run, so a retry
1474/// of the same failed bump folds into one entry instead of flooding the bell.
1475#[cfg(test)]
1476fn surface_problem(
1477    state: &mut RunState,
1478    store: &Notices,
1479    pr_url: Option<&str>,
1480    version: Option<&str>,
1481    reason: &str,
1482) -> Result<(Notice, Option<String>)> {
1483    surface_problem_in(state, store, pr_url, version, reason, false)
1484}
1485
1486/// [`surface_problem`], where `pending` says `pr_url` is a release pull
1487/// request that already existed and could not be raised to `version` - not one
1488/// whose automerge failed. It is linked and recorded, but gets no comment.
1489fn surface_problem_in(
1490    state: &mut RunState,
1491    store: &Notices,
1492    pr_url: Option<&str>,
1493    version: Option<&str>,
1494    reason: &str,
1495    pending: bool,
1496) -> Result<(Notice, Option<String>)> {
1497    let action = if let (true, Some(url)) = (pending, pr_url) {
1498        let ja = crate::lang::is_japanese(&state.config.graph.language);
1499        let first = reason.lines().next().filter(|l| !l.is_empty());
1500        let cause = first.map(|l| format!(" ({l})")).unwrap_or_default();
1501        if ja {
1502            let target = version.map(|v| format!(" v{v}")).unwrap_or_default();
1503            format!(
1504                "既存のリリース PR {url} を{target}へ更新できませんでした{cause}。PR を手で更新してください"
1505            )
1506        } else {
1507            let target = version.map(|v| format!(" to v{v}")).unwrap_or_default();
1508            format!(
1509                "the pending release pull request {url} could not be updated{target}{cause}; update it by hand"
1510            )
1511        }
1512    } else if pr_url.is_some() {
1513        automerge_hint(reason).to_owned()
1514    } else {
1515        let ja = crate::lang::is_japanese(&state.config.graph.language);
1516        let first = reason.lines().next().filter(|l| !l.is_empty());
1517        if ja {
1518            let target = version.map(|v| format!(" (v{v})")).unwrap_or_default();
1519            let cause = first.map(|l| format!(" ({l})")).unwrap_or_default();
1520            format!(
1521                "リリースバンプ{target}は実行されませんでした{cause}。リリース PR を手で開いてください"
1522            )
1523        } else {
1524            let target = version.map(|v| format!(" to v{v}")).unwrap_or_default();
1525            let cause = first.map(|l| format!(" ({l})")).unwrap_or_default();
1526            format!(
1527                "the release bump{target} did not run{cause}; open the release pull request by hand"
1528            )
1529        }
1530    };
1531    let record = state.release_bump.get_or_insert_with(Default::default);
1532    record.pr_url = pr_url.map(str::to_owned).or(record.pr_url.take());
1533    record.version = version.map(str::to_owned).or(record.version.take());
1534    record.automerge_enabled = false;
1535    record.problem = Some(reason.to_owned());
1536    record.action_required = Some(action.clone());
1537
1538    let mut notice = Notice::error(
1539        &format!("release-bump:{}", state.id),
1540        format!(
1541            "Run {} merged, but its release step failed: {action}.",
1542            state.id
1543        ),
1544    );
1545    notice = match pr_url {
1546        Some(url) => notice.link(Link::Url {
1547            url: url.to_owned(),
1548        }),
1549        None => notice.link(Link::Run {
1550            id: state.id.clone(),
1551        }),
1552    };
1553    let notice = store
1554        .raise(notice)
1555        .context("raise the release-bump notification")?;
1556    state.event("bump", format!("needs attention: {action}"));
1557    let comment = pr_url
1558        .filter(|_| !pending)
1559        .map(|_| automerge_failure_comment(reason));
1560    Ok((notice, comment))
1561}
1562
1563/// Make a post-merge problem visible: record it, comment on the release pull
1564/// request, raise a notification and run the configured notifier. Every step
1565/// is best-effort - a failed comment or webhook is an event, never a reason to
1566/// lose the record or the run.
1567pub async fn report_problem(
1568    state: &mut RunState,
1569    pr_url: Option<&str>,
1570    version: Option<&str>,
1571    reason: &str,
1572) {
1573    report_problem_in(state, &Notices::open(), pr_url, version, reason, false).await;
1574}
1575
1576/// [`report_problem`] against an explicit notice store.
1577async fn report_problem_in(
1578    state: &mut RunState,
1579    store: &Notices,
1580    pr_url: Option<&str>,
1581    version: Option<&str>,
1582    reason: &str,
1583    pending: bool,
1584) {
1585    match surface_problem_in(state, store, pr_url, version, reason, pending) {
1586        Ok((notice, comment)) => {
1587            if let (Some(url), Some(body)) = (pr_url, comment)
1588                && let Err(e) = gh_pr_comment(
1589                    &state.repo,
1590                    url,
1591                    &crate::scrub::scrub(&body, &crate::scrub::Identity::current()),
1592                )
1593                .await
1594            {
1595                state.event("bump", format!("could not comment on {url}: {e:#}"));
1596            }
1597            // The webhook still speaks in question terms; a transient,
1598            // never-stored one carries the text so it is not lost.
1599            let summary = match pr_url {
1600                Some(url) if pending => format!("Release PR could not be updated: {url}"),
1601                Some(url) => format!("Release PR needs a human: {url}"),
1602                None if crate::lang::is_japanese(&state.config.graph.language) => {
1603                    "リリースバンプが実行されませんでした".to_owned()
1604                }
1605                None => "Release bump did not run".to_owned(),
1606            };
1607            let q = ask::Question::new(
1608                state.id.clone(),
1609                NOTICE_NODE.to_owned(),
1610                "bump".to_owned(),
1611                summary,
1612                notice.message.clone(),
1613                Vec::new(),
1614            );
1615            if let Err(e) = ask::notify(&state.config.notify, &q).await {
1616                tracing::warn!(
1617                    "could not notify about the release bump of {}: {e:#}",
1618                    state.id
1619                );
1620            }
1621        }
1622        Err(e) => state.event("bump", format!("could not raise a notice: {e:#}")),
1623    }
1624}
1625
1626pub(crate) async fn gh_pr_comment(cwd: &Path, pr_url: &str, body: &str) -> Result<()> {
1627    let out = tokio::process::Command::new("gh")
1628        .args(["pr", "comment", pr_url, "--body", body])
1629        .current_dir(cwd)
1630        .quiet()
1631        .stdin(std::process::Stdio::null())
1632        .output()
1633        .await
1634        .context("spawn gh pr comment")?;
1635    if out.status.success() {
1636        Ok(())
1637    } else {
1638        bail!(
1639            "gh pr comment: {}",
1640            String::from_utf8_lossy(&out.stderr).trim()
1641        )
1642    }
1643}
1644
1645/// Bump an already-open release pull request further, because a change more
1646/// severe than what it already covers landed while it waited on CI or
1647/// automerge - see [`pending_action`].
1648///
1649/// Adds a second commit rather than rewriting the first: `gh pr merge
1650/// --squash` prefers a single commit's own message over the pull request's
1651/// title, and falls back to the title once there is more than one commit -
1652/// so the title is what is kept honest here, via `gh pr edit`.
1653async fn escalate_pending(
1654    state: &mut RunState,
1655    repo: &Path,
1656    remote: &str,
1657    pending: &PendingBump,
1658    decision: &BumpDecision,
1659    base_version: &str,
1660    marker: &Path,
1661) -> Result<()> {
1662    let next = Version::parse(base_version)?
1663        .bump(decision.level)
1664        .to_string();
1665    let worktree = state.dir().join("bump");
1666    git::worktree_remove(repo, &worktree).await.ok();
1667    let checked_out = git::git_raw(
1668        repo,
1669        &[
1670            "worktree",
1671            "add",
1672            "--force",
1673            &worktree.to_string_lossy(),
1674            &pending.branch,
1675        ],
1676    )
1677    .await?;
1678    if !checked_out.ok() {
1679        bail!(
1680            "checking out the pending release branch {} failed: {}",
1681            pending.branch,
1682            checked_out.stderr
1683        );
1684    }
1685
1686    // Only the substantive change - the commit landing on the remote branch
1687    // - has to succeed for the escalation to have happened at all. Anything
1688    // after the push is a follow-up, not a precondition: the branch already
1689    // carries the new version whether or not it succeeds.
1690    let pushed: Result<()> = async {
1691        let cargo_toml_path = worktree.join("Cargo.toml");
1692        let toml = tokio::fs::read_to_string(&cargo_toml_path)
1693            .await
1694            .with_context(|| format!("read {}", cargo_toml_path.display()))?;
1695        let rewritten = rewrite_cargo_version(&toml, &next)?;
1696        tokio::fs::write(&cargo_toml_path, rewritten)
1697            .await
1698            .with_context(|| format!("write {}", cargo_toml_path.display()))?;
1699        sync_lockfile(&worktree, state.config.cache_dir().as_deref()).await?;
1700        let committed = git::commit_all(
1701            &worktree,
1702            &format!(
1703                "chore: release v{next} (supersedes v{})",
1704                pending.target_version
1705            ),
1706        )
1707        .await
1708        .context("commit the escalated version bump")?;
1709        if !committed {
1710            bail!("escalating the version bump left nothing to commit");
1711        }
1712        let pushed = git::push(&worktree, remote, &pending.branch).await?;
1713        if !pushed.ok() {
1714            bail!("pushing {} failed: {}", pending.branch, pushed.stderr);
1715        }
1716        Ok(())
1717    }
1718    .await;
1719    if let Err(e) = pushed {
1720        git::worktree_remove(repo, &worktree).await.ok();
1721        return Err(e);
1722    }
1723
1724    // The commit is on the remote branch now regardless of what happens
1725    // below - the title edit is cosmetic, and the marker and the event must
1726    // both reflect the real, already-pushed state even if it fails.
1727    let title_warning = match gh_pr_edit_title(
1728        &worktree,
1729        &pending.pr_url,
1730        &crate::scrub::scrub(
1731            &format!("chore: release v{next} ({} bump)", decision.level.as_str()),
1732            &crate::scrub::Identity::current(),
1733        ),
1734    )
1735    .await
1736    {
1737        Ok(()) => None,
1738        Err(e) => Some(e.to_string()),
1739    };
1740    git::worktree_remove(repo, &worktree).await.ok();
1741
1742    let marker_write = write_marker(
1743        marker,
1744        &PendingBump {
1745            target_version: next.clone(),
1746            level: decision.level,
1747            branch: pending.branch.clone(),
1748            pr_url: pending.pr_url.clone(),
1749        },
1750    );
1751    state.event(
1752        "bump",
1753        format!(
1754            "escalated the pending release bump from v{} to v{next} to a {} change ({}): {}",
1755            pending.target_version,
1756            decision.level.as_str(),
1757            decision.reason,
1758            pending.pr_url
1759        ),
1760    );
1761    if let Err(e) = marker_write {
1762        state.event(
1763            "bump",
1764            format!(
1765                "could not update the pending release bump marker to v{next}: {e:#}; a later \
1766                 merge may misjudge whether it is already covered"
1767            ),
1768        );
1769    }
1770    if let Some(warning) = title_warning {
1771        state.event(
1772            "bump",
1773            format!(
1774                "pushed v{next} to {} but could not update its title: {warning}; the squashed \
1775                 subject may still read the superseded version",
1776                pending.pr_url
1777            ),
1778        );
1779    }
1780    Ok(())
1781}
1782
1783/// Does an open pull request have `branch` as its head? Any head repository
1784/// counts: the question is only whether the branch name is spoken for.
1785async fn gh_open_pr_for_head(repo: &Path, branch: &str) -> Result<bool> {
1786    let out = tokio::process::Command::new("gh")
1787        .args([
1788            "pr", "list", "--head", branch, "--state", "open", "--json", "url",
1789        ])
1790        .current_dir(repo)
1791        .quiet()
1792        .stdin(std::process::Stdio::null())
1793        .output()
1794        .await
1795        .context("spawn gh pr list")?;
1796    if !out.status.success() {
1797        bail!(
1798            "gh pr list --head {branch}: {}",
1799            String::from_utf8_lossy(&out.stderr).trim()
1800        );
1801    }
1802    let prs: Vec<serde_json::Value> = serde_json::from_slice(&out.stdout)
1803        .with_context(|| format!("parse the pull requests headed by {branch}"))?;
1804    Ok(!prs.is_empty())
1805}
1806
1807/// Create the release branch and worktree, run `fill` in it, and leave nothing
1808/// behind unless a pull request came out of it.
1809///
1810/// A leftover `chore/release-vX.Y.Z` from an earlier failed attempt is
1811/// inspected rather than fatal ([`reclaim_stale_branch`]), once per attempt. A
1812/// failure of `fill` - or of creating the worktree - removes the worktree and
1813/// the branch this attempt made, except a branch that reached the remote,
1814/// which is kept and said so in the returned error.
1815async fn release_attempt<T, F, Fut, P, PFut>(
1816    repo: &Path,
1817    remote: &str,
1818    base: &str,
1819    worktree: &Path,
1820    branch: &str,
1821    open_pr: P,
1822    fill: F,
1823) -> Result<T>
1824where
1825    F: FnOnce(PathBuf) -> Fut,
1826    Fut: std::future::Future<Output = Result<T>>,
1827    P: Fn(String) -> PFut,
1828    PFut: std::future::Future<Output = Result<bool>>,
1829{
1830    let start = format!("{remote}/{base}");
1831    git::worktree_remove(repo, worktree).await.ok();
1832    let mut retried = false;
1833    if git::branch_exists(repo, branch).await? {
1834        reclaim_stale_branch(repo, remote, &start, branch, &open_pr).await?;
1835        retried = true;
1836    }
1837    loop {
1838        // Two steps instead of `worktree add -b`, so that who made the branch
1839        // is known from which step failed rather than guessed from git's
1840        // wording or the branch's tip: `git branch` creates the ref atomically
1841        // or fails, and only a branch it created is this attempt's.
1842        if let Err(e) = git::git(repo, &["branch", branch, &start]).await {
1843            let e = e.context("create the release branch");
1844            if !git::branch_exists(repo, branch).await.unwrap_or(false) {
1845                return Err(e);
1846            }
1847            // It appeared since the check above: somebody else's.
1848            if retried {
1849                return Err(anyhow!(
1850                    "{e:#}; left {branch} in place: it is not one this attempt created"
1851                ));
1852            }
1853            retried = true;
1854            if let Err(r) = reclaim_stale_branch(repo, remote, &start, branch, &open_pr).await {
1855                return Err(anyhow!("{r:#} (after: {e:#})"));
1856            }
1857            continue;
1858        }
1859        if let Some(parent) = worktree.parent() {
1860            tokio::fs::create_dir_all(parent).await.ok();
1861        }
1862        let path = worktree.to_string_lossy();
1863        if let Err(e) = git::git(repo, &["worktree", "add", &path, branch]).await {
1864            let e = e.context("create the release-bump worktree");
1865            return Err(discard_attempt(repo, remote, worktree, branch, e).await);
1866        }
1867        break;
1868    }
1869    match fill(worktree.to_path_buf()).await {
1870        Ok(v) => {
1871            // The branch lives on in the pull request; the worktree is
1872            // throwaway and a stale one would collide with the next attempt.
1873            git::worktree_remove(repo, worktree).await.ok();
1874            Ok(v)
1875        }
1876        Err(e) => Err(discard_attempt(repo, remote, worktree, branch, e).await),
1877    }
1878}
1879
1880/// Undo what a failed attempt created and fold the outcome into its error.
1881async fn discard_attempt(
1882    repo: &Path,
1883    remote: &str,
1884    worktree: &Path,
1885    branch: &str,
1886    cause: anyhow::Error,
1887) -> anyhow::Error {
1888    git::worktree_remove(repo, worktree).await.ok();
1889    if !git::branch_exists(repo, branch).await.unwrap_or(false) {
1890        return cause;
1891    }
1892    // The remote's own answer decides, not whether a push was attempted: a
1893    // push that failed half way may still have landed the ref.
1894    let note = match git::remote_has_branch(repo, remote, branch).await {
1895        Ok(false) => match git::branch_delete(repo, branch).await {
1896            Ok(true) => return cause,
1897            _ => format!("could not delete the local branch {branch}"),
1898        },
1899        Ok(true) => format!("left {branch} in place: it was pushed to {remote}"),
1900        Err(e) => format!(
1901            "left {branch} in place: could not tell whether it was pushed to {remote} ({e:#})"
1902        ),
1903    };
1904    anyhow!("{cause:#}; {note}")
1905}
1906
1907/// A branch of the release's name already exists. Delete it so the attempt can
1908/// go on if and only if it holds nothing: not on the remote, no open pull
1909/// request, and no commit that `start` (`<remote>/<base>`) lacks. Anything
1910/// unproven fails closed with a reason that names the branch.
1911async fn reclaim_stale_branch<P, PFut>(
1912    repo: &Path,
1913    remote: &str,
1914    start: &str,
1915    branch: &str,
1916    open_pr: &P,
1917) -> Result<()>
1918where
1919    P: Fn(String) -> PFut,
1920    PFut: std::future::Future<Output = Result<bool>>,
1921{
1922    match git::remote_has_branch(repo, remote, branch).await {
1923        Ok(false) => {}
1924        Ok(true) => bail!("the branch {branch} already exists and is on {remote}; left alone"),
1925        Err(e) => bail!(
1926            "the branch {branch} already exists and could not check whether {remote} has it              ({e:#}); left alone"
1927        ),
1928    }
1929    match open_pr(branch.to_string()).await {
1930        Ok(false) => {}
1931        Ok(true) => {
1932            bail!("the branch {branch} already exists and has an open pull request; left alone")
1933        }
1934        Err(e) => bail!(
1935            "the branch {branch} already exists and could not check for an open pull request \
1936             ({e:#}); left alone"
1937        ),
1938    }
1939    match git::commits_ahead(repo, start, branch).await {
1940        Ok(0) => {}
1941        Ok(n) => bail!(
1942            "the branch {branch} already exists with {n} commit(s) not in {start}; left alone"
1943        ),
1944        Err(e) => bail!(
1945            "the branch {branch} already exists and could not compare it with {start} ({e:#}); \
1946             left alone"
1947        ),
1948    }
1949    if let Some(held) = git::worktree_holding(repo, branch).await? {
1950        let same = |a: &Path, b: &Path| match (a.canonicalize(), b.canonicalize()) {
1951            (Ok(a), Ok(b)) => a == b,
1952            _ => a == b,
1953        };
1954        if same(&held, repo) {
1955            bail!(
1956                "the branch {branch} already exists and is checked out in the main checkout; left alone"
1957            );
1958        }
1959        git::worktree_remove(repo, &held).await.ok();
1960    }
1961    if !git::branch_delete(repo, branch).await? {
1962        bail!("the branch {branch} already exists and could not be deleted; left alone");
1963    }
1964    Ok(())
1965}
1966
1967/// Edit the version, let the lockfile follow, commit, push, and open the pull
1968/// request with automerge enabled. Returns the opened pull request's URL and,
1969/// when enabling automerge itself failed, a note of why - the pull request
1970/// still exists on the forge either way, and the caller must not lose track
1971/// of its URL over that failure alone.
1972async fn open_bump_pr(
1973    state: &RunState,
1974    worktree: &Path,
1975    branch: &str,
1976    next_version: &str,
1977    decision: &BumpDecision,
1978    source_pr_url: &str,
1979) -> Result<(String, AutomergeOutcome)> {
1980    let cargo_toml_path = worktree.join("Cargo.toml");
1981    let toml = tokio::fs::read_to_string(&cargo_toml_path)
1982        .await
1983        .with_context(|| format!("read {}", cargo_toml_path.display()))?;
1984    let rewritten = rewrite_cargo_version(&toml, next_version)?;
1985    tokio::fs::write(&cargo_toml_path, rewritten)
1986        .await
1987        .with_context(|| format!("write {}", cargo_toml_path.display()))?;
1988
1989    sync_lockfile(worktree, state.config.cache_dir().as_deref()).await?;
1990
1991    let committed = git::commit_all(worktree, &format!("chore: release v{next_version}"))
1992        .await
1993        .context("commit the version bump")?;
1994    if !committed {
1995        bail!("the version bump left nothing to commit");
1996    }
1997
1998    let remote = state.config.merge.remote.clone();
1999    let pushed = git::push(worktree, &remote, branch).await?;
2000    if !pushed.ok() {
2001        bail!("pushing {branch} failed: {}", pushed.stderr);
2002    }
2003
2004    let (title, body) = release_pr(
2005        decision.level.as_str(),
2006        &decision.reason,
2007        next_version,
2008        &state.id,
2009        source_pr_url,
2010    );
2011    let who = crate::scrub::Identity::current();
2012    let (title, body) = (
2013        crate::scrub::scrub(&title, &who),
2014        crate::scrub::scrub(&body, &who),
2015    );
2016    let url = gh_pr_create(worktree, &state.base_branch, branch, &title, &body).await?;
2017    // Without Actions nothing would ever merge it on green, and a direct merge
2018    // here would skip the owner's approval: leave it open for the release
2019    // watcher, which asks and then releases.
2020    if state.config.release.is_local() {
2021        // Watched from now on, so a pull request merged before the watcher's
2022        // first lap still gets released.
2023        crate::release_watch::register(&crate::run::home(), &state.repo, &url, &state.id);
2024        return Ok((url, AutomergeOutcome::LocalGate));
2025    }
2026    let outcome = match gh_enable_automerge(worktree, &url).await {
2027        Ok(()) => AutomergeOutcome::Enabled,
2028        Err(e) => {
2029            let reason = e.to_string();
2030            if is_clean_status_refusal(&reason) {
2031                gh_merge_directly(worktree, &url, &title, reason).await
2032            } else {
2033                AutomergeOutcome::Failed { reason }
2034            }
2035        }
2036    };
2037    Ok((url, outcome))
2038}
2039
2040/// What became of the release pull request's path to `main`.
2041#[derive(Debug, Clone, PartialEq, Eq)]
2042enum AutomergeOutcome {
2043    /// Automerge is armed; CI green will merge it.
2044    Enabled,
2045    /// CI beat us to it, so magi merged the pull request itself.
2046    MergedDirectly { detail: String },
2047    /// `[release] mode = "local"`: automerge was deliberately not armed.
2048    LocalGate,
2049    /// Neither worked; a human has to merge it.
2050    Failed { reason: String },
2051}
2052
2053/// Is this GitHub's refusal to arm automerge on a pull request that is already
2054/// mergeable? Automerge can only be enabled while something is still pending,
2055/// so a fast CI that finishes first gets `Pull request is in clean status`.
2056/// Both fragments are required so an unrelated "clean status" wording or a
2057/// branch-protection refusal does not trigger a direct merge.
2058fn is_clean_status_refusal(reason: &str) -> bool {
2059    let r = reason.to_lowercase();
2060    r.contains("is in clean status") && r.contains("enablepullrequestautomerge")
2061}
2062
2063/// The direct merge, in the same shape [`land::merge_argv`] uses but addressed
2064/// by URL: squash under the pull request's own title, delete the branch.
2065pub(crate) fn bump_merge_argv(pr_url: &str, subject: &str) -> Vec<String> {
2066    [
2067        "pr",
2068        "merge",
2069        pr_url,
2070        "--squash",
2071        "--delete-branch",
2072        "--subject",
2073        subject,
2074    ]
2075    .map(str::to_owned)
2076    .to_vec()
2077}
2078
2079/// Decide what a direct merge amounted to. No I/O. A zero exit is a merge; a
2080/// non-zero one is judged by the forge (`after`), never by the exit code, and
2081/// an unreadable forge is not evidence of success.
2082fn resolve_direct_merge(
2083    refusal: &str,
2084    argv: &[String],
2085    merge_ok: bool,
2086    stderr: &str,
2087    after: Option<land::PrLifecycle>,
2088) -> AutomergeOutcome {
2089    if merge_ok {
2090        return AutomergeOutcome::MergedDirectly {
2091            detail: format!("automerge was refused ({refusal}); gh {}", argv.join(" ")),
2092        };
2093    }
2094    match land::merged_after_all(argv, stderr, after) {
2095        Some(m) => AutomergeOutcome::MergedDirectly { detail: m.detail },
2096        None => AutomergeOutcome::Failed {
2097            reason: format!("{refusal}; merging directly failed too: {}", stderr.trim()),
2098        },
2099    }
2100}
2101
2102/// Merge the pull request directly after automerge was refused as clean.
2103/// Every failure lands in [`AutomergeOutcome::Failed`] so the caller keeps the
2104/// warning-and-comment path.
2105async fn gh_merge_directly(
2106    cwd: &Path,
2107    pr_url: &str,
2108    subject: &str,
2109    refusal: String,
2110) -> AutomergeOutcome {
2111    let argv = bump_merge_argv(pr_url, subject);
2112    let out = match tokio::process::Command::new("gh")
2113        .args(&argv)
2114        .current_dir(cwd)
2115        .quiet()
2116        .stdin(std::process::Stdio::null())
2117        .output()
2118        .await
2119    {
2120        Ok(o) => o,
2121        Err(e) => {
2122            return AutomergeOutcome::Failed {
2123                reason: format!("{refusal}; could not spawn gh to merge directly: {e}"),
2124            };
2125        }
2126    };
2127    let stderr = String::from_utf8_lossy(&out.stderr).into_owned();
2128    // jj keeps HEAD detached, so `--delete-branch` exits non-zero after the
2129    // merge has happened; ask the forge.
2130    let after = if out.status.success() {
2131        None
2132    } else {
2133        land::lifecycle(cwd, pr_url).await.ok()
2134    };
2135    resolve_direct_merge(&refusal, &argv, out.status.success(), &stderr, after)
2136}
2137
2138/// Run `cargo build` so `Cargo.lock` follows the version bump, the same step
2139/// `AGENTS.md`'s hand-driven release recipe calls for.
2140///
2141/// Not exercised by a test: it is the one step in this module that runs the
2142/// real `cargo`, which the constraints on this change rule out doing from a
2143/// test (no network, no writing outside a throwaway worktree the test itself
2144/// does not have).
2145async fn sync_lockfile(worktree: &Path, cache_dir: Option<&Path>) -> Result<()> {
2146    let mut cmd = tokio::process::Command::new("cargo");
2147    cmd.arg("build").current_dir(worktree).quiet();
2148    if let Some(dir) = cache_dir {
2149        cmd.env("CARGO_TARGET_DIR", dir);
2150    }
2151    let out = cmd
2152        .stdin(std::process::Stdio::null())
2153        .output()
2154        .await
2155        .context("spawn cargo build")?;
2156    if !out.status.success() {
2157        bail!(
2158            "cargo build failed while syncing Cargo.lock: {}",
2159            String::from_utf8_lossy(&out.stderr).trim()
2160        );
2161    }
2162    Ok(())
2163}
2164
2165/// Title and body of a release bump pull request. Fixed English whatever
2166/// `[graph] language` says: it lands on GitHub. Pure so a test can hold it to
2167/// that. (`reason` comes from the decision seat, which the prompt tells to
2168/// write English.)
2169fn release_pr(
2170    level: &str,
2171    reason: &str,
2172    next_version: &str,
2173    run_id: &str,
2174    source_pr_url: &str,
2175) -> (String, String) {
2176    let title = format!("chore: release v{next_version} ({level} bump)");
2177    let body = format!(
2178        "## Background\n\n\
2179         A change that was just merged is a `{level}` change, so the crate needs a new \
2180         release: {reason}\n\n\
2181         Triggered by magi run `{run_id}`, which landed {source}.\n\n\
2182         ## Change\n\n\
2183         Raises the package version to `v{next_version}` in `Cargo.toml`, with \
2184         `Cargo.lock` following it. Nothing else changes.\n\n\
2185         ## Risk\n\n\
2186         Version-bump-only, so there is nothing here for a reviewer to find. Merging \
2187         it starts the release pipeline (auto-tag, then the release workflow).",
2188        source = source_pr_url,
2189    );
2190    (title, body)
2191}
2192
2193/// The merged pull request's title, for [`land::merge_subject`].
2194async fn pr_title(repo: &Path, pr_url: &str) -> Result<String> {
2195    let out = tokio::process::Command::new("gh")
2196        .args(["pr", "view", pr_url, "--json", "title"])
2197        .current_dir(repo)
2198        .quiet()
2199        .stdin(std::process::Stdio::null())
2200        .output()
2201        .await
2202        .context("spawn gh pr view")?;
2203    if !out.status.success() {
2204        bail!(
2205            "gh pr view {pr_url}: {}",
2206            String::from_utf8_lossy(&out.stderr).trim()
2207        );
2208    }
2209    #[derive(Deserialize)]
2210    struct Title {
2211        title: String,
2212    }
2213    let parsed: Title = serde_json::from_str(&String::from_utf8_lossy(&out.stdout))
2214        .context("parse `gh pr view --json title` output")?;
2215    Ok(parsed.title)
2216}
2217
2218async fn gh_pr_create(
2219    cwd: &Path,
2220    base: &str,
2221    head: &str,
2222    title: &str,
2223    body: &str,
2224) -> Result<String> {
2225    let out = tokio::process::Command::new("gh")
2226        .args([
2227            "pr", "create", "--base", base, "--head", head, "--title", title, "--body", body,
2228        ])
2229        .current_dir(cwd)
2230        .quiet()
2231        .stdin(std::process::Stdio::null())
2232        .output()
2233        .await
2234        .context("spawn gh pr create")?;
2235    if out.status.success() {
2236        Ok(String::from_utf8_lossy(&out.stdout).trim().to_owned())
2237    } else {
2238        bail!(
2239            "gh pr create: {}",
2240            String::from_utf8_lossy(&out.stderr).trim()
2241        )
2242    }
2243}
2244
2245/// Enable automerge, mirroring `AGENTS.md`'s `gh pr merge --auto --squash
2246/// --delete-branch`. Never `git tag`: `auto-tag.yml` mints the tag once this
2247/// merges, and a manual tag would collide with its push.
2248async fn gh_enable_automerge(cwd: &Path, pr_url: &str) -> Result<()> {
2249    let out = tokio::process::Command::new("gh")
2250        .args([
2251            "pr",
2252            "merge",
2253            pr_url,
2254            "--auto",
2255            "--squash",
2256            "--delete-branch",
2257        ])
2258        .current_dir(cwd)
2259        .quiet()
2260        .stdin(std::process::Stdio::null())
2261        .output()
2262        .await
2263        .context("spawn gh pr merge --auto")?;
2264    if out.status.success() {
2265        Ok(())
2266    } else {
2267        bail!(
2268            "gh pr merge --auto: {}",
2269            String::from_utf8_lossy(&out.stderr).trim()
2270        )
2271    }
2272}
2273
2274/// Rewrite a pull request's title, used when [`escalate_pending`] adds a
2275/// second commit: `gh pr merge --squash` only prefers a single commit's own
2276/// message over the title, so once there are two the title is what lands.
2277async fn gh_pr_edit_title(cwd: &Path, pr_url: &str, title: &str) -> Result<()> {
2278    let out = tokio::process::Command::new("gh")
2279        .args(["pr", "edit", pr_url, "--title", title])
2280        .current_dir(cwd)
2281        .quiet()
2282        .stdin(std::process::Stdio::null())
2283        .output()
2284        .await
2285        .context("spawn gh pr edit")?;
2286    if out.status.success() {
2287        Ok(())
2288    } else {
2289        bail!(
2290            "gh pr edit --title: {}",
2291            String::from_utf8_lossy(&out.stderr).trim()
2292        )
2293    }
2294}
2295
2296#[cfg(test)]
2297mod tests {
2298    use super::*;
2299    use crate::notices::Severity;
2300
2301    #[test]
2302    fn github_facing_bump_text_is_english() {
2303        let (title, body) =
2304            release_pr("minor", "adds a flag", "0.37.0", "ab12", "https://x/pull/1");
2305        assert!(title.is_ascii() && body.is_ascii(), "{title}\n{body}");
2306        assert_eq!(title, "chore: release v0.37.0 (minor bump)");
2307        assert!(
2308            body.contains("## Background") && body.contains("## Change"),
2309            "{body}"
2310        );
2311        let p = decision_prompt("s", "i", "d", &[], "0.36.5");
2312        assert!(p.contains(crate::prompt::GITHUB_ENGLISH_HEADING), "{p}");
2313    }
2314    use crate::config::Config;
2315    use crate::land::PrLifecycle;
2316
2317    /// `[merge] release_bump = false` must short-circuit before any I/O -
2318    /// `after_merge` is reached from a live run with a real repo and a real
2319    /// `gh`, so the disabled case is asserted with a `RunState` that would
2320    /// fail loudly (an unresolvable `/no/such/repo`) the moment anything past
2321    /// the flag check tried to touch it.
2322    #[tokio::test]
2323    async fn a_disabled_config_does_nothing() {
2324        let config = Config {
2325            merge: crate::config::Merge {
2326                release_bump: false,
2327                ..crate::config::Merge::default()
2328            },
2329            ..Config::default()
2330        };
2331        let mut state = RunState::new(
2332            PathBuf::from("/no/such/repo"),
2333            "main".to_owned(),
2334            "0000000000000000000000000000000000000000".to_owned(),
2335            "irrelevant".to_owned(),
2336            config,
2337        );
2338        after_merge(&mut state, "https://example.invalid/pull/1")
2339            .await
2340            .expect("a disabled config must return Ok without touching anything");
2341        assert!(
2342            state.events.is_empty(),
2343            "nothing should happen at all, not even a logged event"
2344        );
2345    }
2346
2347    /// A bare `origin` plus a clone of it, `main` pushed with `files`.
2348    async fn origin_with(files: &[(&str, &str)]) -> (tempfile::TempDir, PathBuf) {
2349        let dir = tempfile::tempdir().unwrap();
2350        let origin = dir.path().join("origin.git");
2351        let repo = dir.path().join("repo");
2352        let o = origin.to_string_lossy().into_owned();
2353        git::git(dir.path(), &["init", "--bare", "-b", "main", &o])
2354            .await
2355            .unwrap();
2356        tokio::fs::create_dir_all(&repo).await.unwrap();
2357        git::git(&repo, &["init", "-b", "main"]).await.unwrap();
2358        git::git(&repo, &["config", "user.name", "test"])
2359            .await
2360            .unwrap();
2361        git::git(&repo, &["config", "user.email", "test@example.com"])
2362            .await
2363            .unwrap();
2364        for (name, body) in files {
2365            tokio::fs::write(repo.join(name), body).await.unwrap();
2366        }
2367        git::git(&repo, &["add", "-A"]).await.unwrap();
2368        git::git(&repo, &["commit", "-m", "init"]).await.unwrap();
2369        git::git(&repo, &["remote", "add", "origin", &o])
2370            .await
2371            .unwrap();
2372        git::git(&repo, &["push", "origin", "main"]).await.unwrap();
2373        (dir, repo)
2374    }
2375
2376    async fn no_pr(_: String) -> Result<bool> {
2377        Ok(false)
2378    }
2379
2380    /// `origin_with` plus a branch `b` made from `main`, optionally one commit
2381    /// ahead of it.
2382    async fn with_branch(ahead: bool) -> (tempfile::TempDir, PathBuf) {
2383        let (d, repo) = origin_with(&[("f", "x\n")]).await;
2384        git::git(&repo, &["branch", "b"]).await.unwrap();
2385        if ahead {
2386            git::git(&repo, &["checkout", "-q", "b"]).await.unwrap();
2387            git::git(&repo, &["commit", "--allow-empty", "-m", "wip"])
2388                .await
2389                .unwrap();
2390            git::git(&repo, &["checkout", "-q", "main"]).await.unwrap();
2391        }
2392        (d, repo)
2393    }
2394
2395    async fn attempt(repo: &Path, open_pr: bool, fail_after_push: Option<bool>) -> Result<()> {
2396        let wt = repo.parent().unwrap().join("bump");
2397        release_attempt(
2398            repo,
2399            "origin",
2400            "main",
2401            &wt,
2402            "b",
2403            |_| async move { Ok(open_pr) },
2404            |w| async move {
2405                if fail_after_push == Some(true) {
2406                    git::push(&w, "origin", "b").await?;
2407                }
2408                if fail_after_push.is_some() {
2409                    bail!("cargo build failed");
2410                }
2411                Ok(())
2412            },
2413        )
2414        .await
2415    }
2416
2417    #[tokio::test]
2418    async fn a_stale_ancestor_branch_is_deleted_and_the_attempt_proceeds() {
2419        let (_d, repo) = with_branch(false).await;
2420        attempt(&repo, false, None).await.unwrap();
2421        // Success keeps the branch (it backs the pull request).
2422        assert!(git::branch_exists(&repo, "b").await.unwrap());
2423    }
2424
2425    #[tokio::test]
2426    async fn a_stale_branch_holding_a_leftover_worktree_is_reclaimed() {
2427        let (_d, repo) = with_branch(false).await;
2428        let old = repo.parent().unwrap().join("old");
2429        git::git(&repo, &["worktree", "add", &old.to_string_lossy(), "b"])
2430            .await
2431            .unwrap();
2432        attempt(&repo, false, None).await.unwrap();
2433        assert!(!old.exists());
2434    }
2435
2436    #[tokio::test]
2437    async fn a_stale_branch_with_an_unmerged_commit_is_kept_with_a_reason() {
2438        let (_d, repo) = with_branch(true).await;
2439        let e = attempt(&repo, false, None).await.unwrap_err().to_string();
2440        assert!(e.contains("`b`") || e.contains("branch b"), "{e}");
2441        assert!(e.contains("1 commit(s) not in origin/main"), "{e}");
2442        assert!(git::branch_exists(&repo, "b").await.unwrap());
2443    }
2444
2445    #[tokio::test]
2446    async fn a_stale_branch_on_the_remote_is_kept() {
2447        let (_d, repo) = with_branch(false).await;
2448        git::git(&repo, &["push", "origin", "b"]).await.unwrap();
2449        let e = attempt(&repo, false, None).await.unwrap_err().to_string();
2450        assert!(e.contains("branch b") && e.contains("is on origin"), "{e}");
2451        assert!(git::branch_exists(&repo, "b").await.unwrap());
2452    }
2453
2454    #[tokio::test]
2455    async fn a_stale_branch_with_an_open_pull_request_is_kept() {
2456        let (_d, repo) = with_branch(false).await;
2457        let e = attempt(&repo, true, None).await.unwrap_err().to_string();
2458        assert!(e.contains("open pull request"), "{e}");
2459        assert!(git::branch_exists(&repo, "b").await.unwrap());
2460    }
2461
2462    #[tokio::test]
2463    async fn an_unanswerable_pull_request_check_keeps_the_branch() {
2464        let (_d, repo) = with_branch(false).await;
2465        let wt = repo.parent().unwrap().join("bump");
2466        let e = release_attempt(
2467            &repo,
2468            "origin",
2469            "main",
2470            &wt,
2471            "b",
2472            |_| async { bail!("offline") },
2473            |_| async { Ok(()) },
2474        )
2475        .await
2476        .unwrap_err()
2477        .to_string();
2478        assert!(
2479            e.contains("could not check for an open pull request"),
2480            "{e}"
2481        );
2482        assert!(git::branch_exists(&repo, "b").await.unwrap());
2483    }
2484
2485    #[tokio::test]
2486    async fn a_failed_attempt_removes_its_own_worktree_and_branch() {
2487        let (_d, repo) = origin_with(&[("f", "x\n")]).await;
2488        let wt = repo.parent().unwrap().join("bump");
2489        let e = attempt(&repo, false, Some(false)).await.unwrap_err();
2490        assert!(format!("{e:#}").contains("cargo build failed"));
2491        assert!(!wt.exists());
2492        assert!(!git::branch_exists(&repo, "b").await.unwrap());
2493    }
2494
2495    #[tokio::test]
2496    async fn a_pushed_branch_survives_a_failed_attempt_and_the_reason_says_so() {
2497        let (_d, repo) = origin_with(&[("f", "x\n")]).await;
2498        let e = attempt(&repo, false, Some(true)).await.unwrap_err();
2499        let e = format!("{e:#}");
2500        assert!(
2501            e.contains("cargo build failed") && e.contains("pushed to origin"),
2502            "{e}"
2503        );
2504        assert!(git::branch_exists(&repo, "b").await.unwrap());
2505    }
2506
2507    #[tokio::test]
2508    async fn a_branch_left_by_a_half_done_worktree_add_is_removed() {
2509        // No pre-existing branch; the worktree path sits under a regular
2510        // file, so `worktree add -b` may create the branch and then fail.
2511        let (_d, repo) = origin_with(&[("f", "x\n")]).await;
2512        let blocker = repo.parent().unwrap().join("blocker");
2513        tokio::fs::write(&blocker, "file").await.unwrap();
2514        let wt = blocker.join("bump");
2515        let r = release_attempt(
2516            &repo,
2517            "origin",
2518            "main",
2519            &wt,
2520            "b",
2521            |_| async { bail!("offline") },
2522            |_| async { Ok(()) },
2523        )
2524        .await;
2525        assert!(r.is_err());
2526        assert!(!git::branch_exists(&repo, "b").await.unwrap());
2527    }
2528
2529    #[tokio::test]
2530    async fn the_retry_is_taken_at_most_once() {
2531        // The branch is reclaimed, but the worktree path cannot be created, so
2532        // the second creation fails too: no third try, and no loop.
2533        let (_d, repo) = with_branch(false).await;
2534        let blocker = repo.parent().unwrap().join("blocker");
2535        tokio::fs::write(&blocker, "file").await.unwrap();
2536        let wt = blocker.join("bump");
2537        let r = release_attempt(&repo, "origin", "main", &wt, "b", no_pr, |_| async {
2538            Ok(())
2539        })
2540        .await;
2541        assert!(r.is_err());
2542        assert!(!git::branch_exists(&repo, "b").await.unwrap());
2543    }
2544
2545    #[tokio::test]
2546    async fn base_has_cargo_toml_tells_rust_from_non_rust() {
2547        let (_d, rust) = origin_with(&[("Cargo.toml", "[package]\nversion = \"0.1.0\"\n")]).await;
2548        assert!(base_has_cargo_toml(&rust, "origin", "main").await.unwrap());
2549        let (_d2, other) = origin_with(&[("README.md", "hi\n")]).await;
2550        assert!(!base_has_cargo_toml(&other, "origin", "main").await.unwrap());
2551        // An unresolvable ref is a fault, not "not Rust".
2552        assert!(base_has_cargo_toml(&other, "origin", "nope").await.is_err());
2553    }
2554
2555    #[tokio::test]
2556    async fn a_repo_without_cargo_toml_skips_with_one_event_and_no_lock() {
2557        let (_d, repo) = origin_with(&[("README.md", "hi\n")]).await;
2558        let home = tempfile::tempdir().unwrap();
2559        let mut state = RunState::new(
2560            repo.clone(),
2561            "main".to_owned(),
2562            "0000000000000000000000000000000000000000".to_owned(),
2563            "task".to_owned(),
2564            Config::default(),
2565        );
2566        state.candidates.push(crate::run::Candidate {
2567            index: 0,
2568            label: 'A',
2569            agent: "x".to_owned(),
2570            branch: "main".to_owned(),
2571            worktree: repo.clone(),
2572            summary: String::new(),
2573            stat: String::new(),
2574            files: 1,
2575            commits: 1,
2576            empty: false,
2577            failed: None,
2578            verified_noop: None,
2579            duration_ms: 0,
2580            folded: false,
2581        });
2582        state.tally = Some(
2583            serde_json::from_value(serde_json::json!({
2584                "first_choice": {}, "borda": {}, "winner": "A",
2585                "unanimous_initial": true, "deliberated": false,
2586                "changed_votes": 0, "unanimous_final": true,
2587            }))
2588            .unwrap(),
2589        );
2590        after_merge_at(
2591            &mut state,
2592            "https://example.invalid/pull/1",
2593            Some(home.path()),
2594            None,
2595        )
2596        .await
2597        .expect("a non-Rust repository is not an error");
2598        let bumps: Vec<_> = state.events.iter().filter(|e| e.node == "bump").collect();
2599        assert_eq!(bumps.len(), 1, "{:?}", state.events);
2600        assert_eq!(
2601            bumps[0].message,
2602            "release bump: no Cargo.toml on the base branch; release bumps are Rust-only, skipping"
2603        );
2604        assert!(
2605            std::fs::read_dir(home.path()).unwrap().next().is_none(),
2606            "no marker and no lock may be created"
2607        );
2608    }
2609
2610    fn winner_state(repo: &Path, base: &str) -> RunState {
2611        let mut state = RunState::new(
2612            repo.to_path_buf(),
2613            base.to_owned(),
2614            "0000000000000000000000000000000000000000".to_owned(),
2615            "task".to_owned(),
2616            Config::default(),
2617        );
2618        state.candidates.push(crate::run::Candidate {
2619            index: 0,
2620            label: 'A',
2621            agent: "x".to_owned(),
2622            branch: "main".to_owned(),
2623            worktree: repo.to_path_buf(),
2624            summary: String::new(),
2625            stat: String::new(),
2626            files: 1,
2627            commits: 1,
2628            empty: false,
2629            failed: None,
2630            verified_noop: None,
2631            duration_ms: 0,
2632            folded: false,
2633        });
2634        state.tally = Some(
2635            serde_json::from_value(serde_json::json!({
2636                "first_choice": {}, "borda": {}, "winner": "A",
2637                "unanimous_initial": true, "deliberated": false,
2638                "changed_votes": 0, "unanimous_final": true,
2639            }))
2640            .unwrap(),
2641        );
2642        state
2643    }
2644
2645    #[tokio::test]
2646    async fn a_real_failure_without_a_pr_raises_one_notice_and_a_retry_folds_into_it() {
2647        let (_d, repo) =
2648            origin_with(&[("Cargo.toml", "[package]\nname=\"x\"\nversion=\"0.1.0\"\n")]).await;
2649        let home = tempfile::tempdir().unwrap();
2650        let store = Notices::at(home.path().join("notifications"));
2651        // An unresolvable base is a fault, not "not eligible".
2652        let mut state = winner_state(&repo, "nope");
2653        let url = "https://example.invalid/pull/1";
2654        after_merge_at(&mut state, url, Some(home.path()), Some(&store))
2655            .await
2656            .expect_err("an unresolvable base is a failure");
2657        let listed = store.list();
2658        assert_eq!(listed.len(), 1, "{listed:?}");
2659        assert!(
2660            listed[0].message.contains("did not run"),
2661            "{}",
2662            listed[0].message
2663        );
2664        assert!(
2665            listed[0].message.contains("Cargo.toml"),
2666            "{}",
2667            listed[0].message
2668        );
2669        assert!(state.events.iter().any(|e| e.node == "bump"));
2670        after_merge_at(&mut state, url, Some(home.path()), Some(&store))
2671            .await
2672            .expect_err("still failing");
2673        let listed = store.list();
2674        assert_eq!(listed.len(), 1, "{listed:?}");
2675        assert_eq!(listed[0].count, 2);
2676    }
2677
2678    #[tokio::test]
2679    async fn not_eligible_cases_raise_no_notice() {
2680        let home = tempfile::tempdir().unwrap();
2681        let store = Notices::at(home.path().join("notifications"));
2682        let url = "https://example.invalid/pull/1";
2683        // No Cargo.toml on the base branch.
2684        let (_d, repo) = origin_with(&[("README.md", "hi\n")]).await;
2685        let mut state = winner_state(&repo, "main");
2686        after_merge_at(&mut state, url, Some(home.path()), Some(&store))
2687            .await
2688            .unwrap();
2689        // Disabled.
2690        let mut state = winner_state(&repo, "nope");
2691        state.config.merge.release_bump = false;
2692        after_merge_at(&mut state, url, Some(home.path()), Some(&store))
2693            .await
2694            .unwrap();
2695        // No winner.
2696        let mut state = winner_state(&repo, "nope");
2697        state.tally = None;
2698        after_merge_at(&mut state, url, Some(home.path()), Some(&store))
2699            .await
2700            .unwrap();
2701        assert!(store.list().is_empty(), "{:?}", store.list());
2702    }
2703
2704    #[test]
2705    fn the_no_pr_notice_follows_the_configured_language() {
2706        let dir = tempfile::tempdir().unwrap();
2707        let store = Notices::at(dir.path().join("notifications"));
2708        let mut state = merged_state();
2709        state.config.graph.language = "ja".to_owned();
2710        let (n, _) = surface_problem(&mut state, &store, None, Some("0.2.0"), "boom").unwrap();
2711        assert!(n.message.contains("実行されませんでした"), "{}", n.message);
2712        assert!(n.message.contains("boom") && n.message.contains("v0.2.0"));
2713    }
2714
2715    #[test]
2716    fn a_failed_escalation_points_at_the_pending_pr_without_commenting() {
2717        let dir = tempfile::tempdir().unwrap();
2718        let store = Notices::at(dir.path().join("notifications"));
2719        let mut state = merged_state();
2720        let url = "https://example.invalid/pull/9";
2721        let (n, comment) = surface_problem_in(
2722            &mut state,
2723            &store,
2724            Some(url),
2725            Some("0.3.0"),
2726            "push failed",
2727            true,
2728        )
2729        .unwrap();
2730        assert!(comment.is_none());
2731        assert!(
2732            n.message.contains(url) && n.message.contains("v0.3.0"),
2733            "{}",
2734            n.message
2735        );
2736        assert!(!n.message.contains("open the release pull request by hand"));
2737        assert!(matches!(n.link, Some(Link::Url { .. })));
2738    }
2739
2740    #[test]
2741    fn a_failure_notice_names_the_pending_pr_and_the_first_line_of_the_cause() {
2742        let err = anyhow!("outer context").context("cargo build failed\nsecond line");
2743        let with_pr = Progress {
2744            version: Some("0.2.0".into()),
2745            pending_pr: Some("https://example.invalid/pull/9".into()),
2746        };
2747        let (v, reason) = notice_for_failure(&with_pr, &err);
2748        assert_eq!(v.as_deref(), Some("0.2.0"));
2749        assert_eq!(reason, "cargo build failed");
2750        let (v, reason) = notice_for_failure(&Progress::default(), &err);
2751        assert_eq!(v, None);
2752        assert_eq!(reason, "cargo build failed");
2753    }
2754
2755    const NO_RULES: &str = "gh pr merge --auto: GraphQL: Pull request Branch does not have \
2756                            required protected branch rules (enablePullRequestAutoMerge)";
2757
2758    fn merged_state() -> RunState {
2759        // `report::run` prints `state.dir()`; pin the global home like the
2760        // report tests do so nothing reaches the operator's real one.
2761        run::pin_test_home();
2762        let mut s = RunState::new(
2763            PathBuf::from("/no/such/repo"),
2764            "main".to_owned(),
2765            "0000000000000000000000000000000000000000".to_owned(),
2766            "task".to_owned(),
2767            Config::default(),
2768        );
2769        s.status = RunStatus::Merged;
2770        s
2771    }
2772
2773    #[test]
2774    fn the_known_automerge_refusal_names_branch_protection() {
2775        assert!(automerge_hint(NO_RULES).contains("branch protection with required"));
2776        let other = automerge_hint("gh: network unreachable");
2777        assert!(!other.contains("branch protection"), "{other}");
2778        let body = automerge_failure_comment(NO_RULES);
2779        assert!(body.contains("enablePullRequestAutoMerge"), "{body}");
2780        assert!(body.contains("Action required"), "{body}");
2781    }
2782
2783    const CLEAN: &str = "gh pr merge --auto: GraphQL: Pull request Pull request is in clean \
2784                         status (enablePullRequestAutoMerge)";
2785
2786    #[test]
2787    fn clean_status_refusal_is_matched_narrowly() {
2788        assert!(is_clean_status_refusal(CLEAN));
2789        assert!(!is_clean_status_refusal(NO_RULES));
2790        assert!(!is_clean_status_refusal("gh: network unreachable"));
2791        assert!(!is_clean_status_refusal("Pull request is in clean status"));
2792        assert!(automerge_hint(CLEAN).contains("already green"));
2793    }
2794
2795    #[test]
2796    fn the_direct_merge_argv_matches_the_land_flags() {
2797        let a = bump_merge_argv("https://github.com/o/r/pull/9", "chore: release v1.0.0");
2798        let l = land::merge_argv(9, "chore: release v1.0.0");
2799        assert_eq!(a[..2], l[..2]);
2800        assert_eq!(a[3..], l[3..]);
2801        assert_eq!(a[2], "https://github.com/o/r/pull/9");
2802    }
2803
2804    #[test]
2805    fn a_direct_merge_is_judged_by_the_forge_not_the_exit_code() {
2806        let argv = bump_merge_argv("u", "t");
2807        let merged = |o: &AutomergeOutcome| matches!(o, AutomergeOutcome::MergedDirectly { .. });
2808        assert!(merged(&resolve_direct_merge(CLEAN, &argv, true, "", None)));
2809        let detached = "not on any branch";
2810        assert!(merged(&resolve_direct_merge(
2811            CLEAN,
2812            &argv,
2813            false,
2814            detached,
2815            Some(PrLifecycle::Merged)
2816        )));
2817        for after in [Some(PrLifecycle::Open), None] {
2818            let o = resolve_direct_merge(CLEAN, &argv, false, "boom", after);
2819            match o {
2820                AutomergeOutcome::Failed { reason } => {
2821                    assert!(
2822                        reason.contains("clean status") && reason.contains("boom"),
2823                        "{reason}"
2824                    )
2825                }
2826                other => panic!("expected Failed, got {other:?}"),
2827            }
2828        }
2829    }
2830
2831    #[test]
2832    fn a_local_mode_bump_reads_back_and_old_records_are_not_local() {
2833        let old: run::ReleaseBump =
2834            serde_json::from_str(r#"{"pr_url":"u","automerge_enabled":true}"#).unwrap();
2835        assert!(!old.local);
2836        let mut state = merged_state();
2837        state.release_bump = Some(run::ReleaseBump {
2838            pr_url: Some("https://github.com/o/r/pull/9".to_owned()),
2839            version: Some("1.0.0".to_owned()),
2840            local: true,
2841            ..run::ReleaseBump::default()
2842        });
2843        // Not a failure: nothing was supposed to be armed.
2844        assert!(!state.needs_attention());
2845        let text = crate::report::run(&state);
2846        assert!(text.contains("release.mode = local"), "{text}");
2847        assert!(!text.contains("FAILED"), "{text}");
2848    }
2849
2850    #[test]
2851    fn a_directly_merged_bump_is_not_reported_as_pending_or_failed() {
2852        let mut state = merged_state();
2853        state.release_bump = Some(run::ReleaseBump {
2854            pr_url: Some("https://github.com/o/r/pull/9".to_owned()),
2855            version: Some("1.0.0".to_owned()),
2856            merged_directly: true,
2857            ..run::ReleaseBump::default()
2858        });
2859        assert!(!state.needs_attention());
2860        let text = crate::report::run(&state);
2861        assert!(text.contains("merged directly"), "{text}");
2862        assert!(!text.contains("FAILED"), "{text}");
2863    }
2864
2865    #[test]
2866    fn an_automerge_failure_is_recorded_shown_and_filed_and_survives_settling() {
2867        let dir = tempfile::tempdir().unwrap();
2868        let store = Notices::at(dir.path().join("notifications"));
2869        let questions = ask::Questions::at(dir.path().join("questions"));
2870        let mut state = merged_state();
2871        let url = "https://github.com/o/r/pull/35";
2872
2873        let (n, comment) =
2874            surface_problem(&mut state, &store, Some(url), Some("0.8.0"), NO_RULES).unwrap();
2875
2876        // The comment goes on the release PR and carries reason and fix.
2877        let comment = comment.expect("a PR was opened, so it gets a comment");
2878        assert!(comment.contains("branch protection"), "{comment}");
2879
2880        // The run is still Merged, but no longer reads as plain green.
2881        assert_eq!(state.status, RunStatus::Merged);
2882        assert!(state.needs_attention());
2883        let text = crate::report::run(&state);
2884        assert!(text.contains("release bump"), "{text}");
2885        assert!(text.contains("FAILED"), "{text}");
2886        assert!(text.contains(url), "{text}");
2887        assert!(text.contains("action required"), "{text}");
2888        assert!(crate::report::line(&state).contains("release needs a human"));
2889
2890        // Exactly one notification, linked to the PR, and no question.
2891        assert_eq!(n.severity, Severity::Error);
2892        assert_eq!(
2893            n.link,
2894            Some(Link::Url {
2895                url: url.to_owned()
2896            })
2897        );
2898        assert_eq!(store.list().len(), 1);
2899        assert!(questions.open_for(&state.id).is_empty());
2900
2901        // A retry of the same failure folds into the same entry.
2902        surface_problem(&mut state, &store, Some(url), Some("0.8.0"), NO_RULES).unwrap();
2903        let listed = store.list();
2904        assert_eq!(listed.len(), 1);
2905        assert_eq!(listed[0].count, 2);
2906    }
2907
2908    #[test]
2909    fn a_bump_that_never_ran_is_surfaced_without_a_pr_comment() {
2910        let dir = tempfile::tempdir().unwrap();
2911        let store = Notices::at(dir.path().join("notifications"));
2912        let mut state = merged_state();
2913        let (n, comment) = surface_problem(&mut state, &store, None, None, "no agent").unwrap();
2914        assert!(comment.is_none());
2915        assert!(matches!(n.link, Some(Link::Run { .. })));
2916        assert!(state.needs_attention());
2917    }
2918
2919    #[test]
2920    fn version_parses_and_bumps_each_digit() {
2921        let v = Version::parse("0.4.0").unwrap();
2922        assert_eq!(
2923            v,
2924            Version {
2925                major: 0,
2926                minor: 4,
2927                patch: 0
2928            }
2929        );
2930
2931        assert_eq!(v.bump(BumpLevel::Major).to_string(), "1.0.0");
2932        assert_eq!(v.bump(BumpLevel::Minor).to_string(), "0.5.0");
2933        assert_eq!(v.bump(BumpLevel::Patch).to_string(), "0.4.1");
2934    }
2935
2936    #[test]
2937    fn version_tolerates_a_prerelease_suffix_on_patch() {
2938        let v = Version::parse("1.2.3-rc1").unwrap();
2939        assert_eq!(
2940            v,
2941            Version {
2942                major: 1,
2943                minor: 2,
2944                patch: 3
2945            }
2946        );
2947    }
2948
2949    #[test]
2950    fn version_rejects_garbage() {
2951        assert!(Version::parse("not-a-version").is_err());
2952        assert!(Version::parse("1.2").is_err());
2953    }
2954
2955    #[test]
2956    fn decision_parses_each_level() {
2957        for (json, level) in [
2958            (
2959                r#"{"level":"major","reason":"drops a config key"}"#,
2960                BumpLevel::Major,
2961            ),
2962            (
2963                r#"{"level":"minor","reason":"adds a new flag"}"#,
2964                BumpLevel::Minor,
2965            ),
2966            (
2967                r#"{"level":"patch","reason":"fixes a race"}"#,
2968                BumpLevel::Patch,
2969            ),
2970        ] {
2971            let decision = parse_decision(json).unwrap();
2972            assert_eq!(decision.level, level);
2973            assert!(!decision.reason.is_empty());
2974        }
2975    }
2976
2977    #[test]
2978    fn decision_wrapped_in_a_fence_and_prose_still_parses() {
2979        let text = "Here is my call.\n\n```json\n{\"level\":\"minor\",\"reason\":\"new HTTP route\"}\n```\n\nDone.";
2980        let decision = parse_decision(text).unwrap();
2981        assert_eq!(decision.level, BumpLevel::Minor);
2982        assert_eq!(decision.reason, "new HTTP route");
2983    }
2984
2985    #[test]
2986    fn a_broken_reply_is_an_error_not_a_default() {
2987        assert!(parse_decision("I decline to answer.").is_err());
2988        assert!(parse_decision(r#"{"level":"huge","reason":"go big"}"#).is_err());
2989        assert!(
2990            parse_decision(r#"{"level":"patch","reason":""}"#).is_err(),
2991            "an empty reason must not pass either"
2992        );
2993        assert!(
2994            parse_decision(r#"{"level":"patch"}"#).is_err(),
2995            "a reply with no reason at all must not pass"
2996        );
2997    }
2998
2999    #[test]
3000    fn prompt_states_the_zero_x_rule_and_the_tie_break() {
3001        let prompt = decision_prompt(
3002            "feat: add a phone endpoint",
3003            "add POST /api/widgets",
3004            "1 file changed, 10 insertions(+)",
3005            &["src/web.rs".to_owned()],
3006            "0.8.0",
3007        );
3008        assert!(prompt.contains("0.8.0"), "the current version is stated");
3009        assert!(
3010            prompt.contains("below `1.0.0`")
3011                && prompt.contains("`minor` is the digit that carries a breaking change"),
3012            "the 0.x rule must be explicit: {prompt}"
3013        );
3014        assert!(
3015            prompt.contains("choose the larger"),
3016            "the tie-break toward the bigger digit must be explicit: {prompt}"
3017        );
3018    }
3019
3020    #[test]
3021    fn release_only_diffs_are_recognised() {
3022        assert!(is_release_only(&["Cargo.toml".to_owned()]));
3023        assert!(is_release_only(&[
3024            "Cargo.toml".to_owned(),
3025            "Cargo.lock".to_owned()
3026        ]));
3027        assert!(!is_release_only(&[]));
3028        assert!(!is_release_only(&[
3029            "Cargo.toml".to_owned(),
3030            "src/main.rs".to_owned()
3031        ]));
3032    }
3033
3034    #[test]
3035    fn cargo_version_rewrite_touches_only_the_package_table() {
3036        let toml = "\
3037[package]\n\
3038# a comment mentioning version on purpose\n\
3039name = \"magi-cli\"\n\
3040version = \"0.8.0\"\n\
3041edition = \"2024\"\n\
3042\n\
3043[dependencies]\n\
3044foo = { version = \"1.2.3\" }\n";
3045        let out = rewrite_cargo_version(toml, "0.9.0").unwrap();
3046        assert!(out.contains("version = \"0.9.0\""));
3047        assert!(
3048            out.contains("foo = { version = \"1.2.3\" }"),
3049            "a dependency's own version pin must survive: {out}"
3050        );
3051        assert!(
3052            out.contains("# a comment mentioning version on purpose"),
3053            "unrelated lines, comments included, must be byte-for-byte preserved: {out}"
3054        );
3055        assert_eq!(
3056            out.lines().count(),
3057            toml.lines().count(),
3058            "the rewrite replaces one line, it does not add or remove any"
3059        );
3060    }
3061
3062    #[test]
3063    fn cargo_version_rewrite_fails_without_a_package_table() {
3064        let toml = "[dependencies]\nfoo = \"1\"\n";
3065        assert!(rewrite_cargo_version(toml, "1.0.0").is_err());
3066    }
3067
3068    /// The shape `kanadehq/kanade` has: a workspace root with member crates
3069    /// but no crate of its own, so `[package]` never exists and the version
3070    /// lives under `[workspace.package]` alone. Before this fell back,
3071    /// `rewrite_cargo_version` bailed on every such repository and no bump
3072    /// pull request was ever opened for it.
3073    #[test]
3074    fn cargo_version_rewrite_falls_back_to_workspace_package_without_a_package_table() {
3075        let toml = "\
3076[workspace]\n\
3077members = [\"crates/a\", \"crates/b\"]\n\
3078\n\
3079[workspace.package]\n\
3080version = \"0.45.18\"\n\
3081edition = \"2024\"\n\
3082\n\
3083[workspace.dependencies]\n\
3084foo = { version = \"1.2.3\" }\n";
3085        let out = rewrite_cargo_version(toml, "0.45.19").unwrap();
3086        assert!(out.contains("version = \"0.45.19\""));
3087        assert!(
3088            out.contains("foo = { version = \"1.2.3\" }"),
3089            "a workspace dependency's own version pin must survive: {out}"
3090        );
3091        assert_eq!(
3092            out.lines().count(),
3093            toml.lines().count(),
3094            "the rewrite replaces one line, it does not add or remove any"
3095        );
3096    }
3097
3098    /// The exact failure that happened on `kanadehq/kanade`: an internal
3099    /// member referenced by both `path` and `version` must have its pin
3100    /// bumped alongside `[workspace.package]`, in the same edit.
3101    #[test]
3102    fn cargo_version_rewrite_bumps_an_internal_workspace_dependency_pin() {
3103        let toml = "\
3104[workspace]\n\
3105members = [\"crates/kanade-shared\"]\n\
3106\n\
3107[workspace.package]\n\
3108version = \"0.48.2\"\n\
3109\n\
3110[workspace.dependencies]\n\
3111kanade-shared = { path = \"crates/kanade-shared\", version = \"0.48.2\" }\n";
3112        let out = rewrite_cargo_version(toml, "0.48.3").unwrap();
3113        assert!(out.contains("[workspace.package]\nversion = \"0.48.3\"\n"));
3114        assert!(
3115            out.contains(
3116                "kanade-shared = { path = \"crates/kanade-shared\", version = \"0.48.3\" }"
3117            ),
3118            "the internal pin must move with the workspace version: {out}"
3119        );
3120    }
3121
3122    /// Key order inside the inline table must not matter.
3123    #[test]
3124    fn cargo_version_rewrite_bumps_an_internal_pin_with_version_before_path() {
3125        let toml = "\
3126[workspace.package]\n\
3127version = \"1.0.0\"\n\
3128\n\
3129[workspace.dependencies]\n\
3130inner = { version = \"1.0.0\", path = \"crates/inner\" }\n";
3131        let out = rewrite_cargo_version(toml, "1.0.1").unwrap();
3132        assert!(out.contains("inner = { version = \"1.0.1\", path = \"crates/inner\" }"));
3133    }
3134
3135    /// The dotted-table form (`[workspace.dependencies.name]`) must be
3136    /// rewritten too, not only the inline-table form.
3137    #[test]
3138    fn cargo_version_rewrite_bumps_an_internal_pin_in_dotted_table_form() {
3139        let toml = "\
3140[workspace.package]\n\
3141version = \"2.3.0\"\n\
3142\n\
3143[workspace.dependencies.inner]\n\
3144path = \"crates/inner\"\n\
3145version = \"2.3.0\"\n";
3146        let out = rewrite_cargo_version(toml, "2.4.0").unwrap();
3147        assert!(out.contains("[workspace.package]\nversion = \"2.4.0\"\n"));
3148        assert!(out.contains(
3149            "[workspace.dependencies.inner]\npath = \"crates/inner\"\nversion = \"2.4.0\"\n"
3150        ));
3151    }
3152
3153    /// The dotted-key form written as two separate lines directly under the
3154    /// flat `[workspace.dependencies]` table - no inline table, no
3155    /// `[workspace.dependencies.name]` sub-header - is also valid TOML and
3156    /// must have its `version` line rewritten.
3157    #[test]
3158    fn cargo_version_rewrite_bumps_an_internal_pin_in_dotted_key_form() {
3159        let toml = "\
3160[workspace.package]\n\
3161version = \"2.3.0\"\n\
3162\n\
3163[workspace.dependencies]\n\
3164inner.path = \"crates/inner\"\n\
3165inner.version = \"2.3.0\"\n";
3166        let out = rewrite_cargo_version(toml, "2.4.0").unwrap();
3167        assert!(out.contains("[workspace.package]\nversion = \"2.4.0\"\n"));
3168        assert!(out.contains("inner.path = \"crates/inner\"\ninner.version = \"2.4.0\"\n"));
3169    }
3170
3171    /// A workspace-only member with `path` but no `version` is unpublished
3172    /// and must be left exactly alone.
3173    #[test]
3174    fn cargo_version_rewrite_leaves_a_path_only_workspace_dependency_untouched() {
3175        let toml = "\
3176[workspace.package]\n\
3177version = \"0.1.0\"\n\
3178\n\
3179[workspace.dependencies]\n\
3180internal-only = { path = \"crates/internal-only\" }\n";
3181        let out = rewrite_cargo_version(toml, "0.2.0").unwrap();
3182        assert!(out.contains("internal-only = { path = \"crates/internal-only\" }"));
3183    }
3184
3185    /// An external crates.io dependency, `version` but no `path`, must never
3186    /// be touched by the internal-pin logic even when it sits in
3187    /// `[workspace.dependencies]` alongside a real internal pin.
3188    #[test]
3189    fn cargo_version_rewrite_leaves_an_external_dependency_untouched() {
3190        let toml = "\
3191[workspace.package]\n\
3192version = \"0.1.0\"\n\
3193\n\
3194[workspace.dependencies]\n\
3195serde = { version = \"1\", features = [\"derive\"] }\n\
3196inner = { path = \"crates/inner\", version = \"0.1.0\" }\n";
3197        let out = rewrite_cargo_version(toml, "0.2.0").unwrap();
3198        assert!(out.contains("serde = { version = \"1\", features = [\"derive\"] }"));
3199        assert!(out.contains("inner = { path = \"crates/inner\", version = \"0.2.0\" }"));
3200    }
3201
3202    /// A manifest with no `[workspace.dependencies]` table at all must keep
3203    /// bumping `[workspace.package]` exactly as before - regression guard
3204    /// for the pre-existing behaviour this change extends.
3205    #[test]
3206    fn cargo_version_rewrite_without_workspace_dependencies_table_still_bumps_package() {
3207        let toml = "[workspace.package]\nversion = \"0.9.0\"\nedition = \"2024\"\n";
3208        let out = rewrite_cargo_version(toml, "0.10.0").unwrap();
3209        assert_eq!(
3210            out,
3211            "[workspace.package]\nversion = \"0.10.0\"\nedition = \"2024\"\n"
3212        );
3213    }
3214
3215    /// The `kanadehq/kanade` shape itself: several internal-looking and
3216    /// external entries mixed in one `[workspace.dependencies]` table.
3217    #[test]
3218    fn cargo_version_rewrite_handles_a_kanade_shaped_workspace_dependencies_table() {
3219        let toml = "\
3220[workspace.package]\n\
3221version = \"0.48.2\"\n\
3222\n\
3223[workspace.dependencies]\n\
3224anyhow = { version = \"1\" }\n\
3225serde = { version = \"1\", features = [\"derive\"] }\n\
3226kanade-shared = { path = \"crates/kanade-shared\", version = \"0.48.2\" }\n\
3227kanade-core = { path = \"crates/kanade-core\", version = \"0.48.2\" }\n\
3228kanade-internal-tool = { path = \"crates/kanade-internal-tool\" }\n";
3229        let out = rewrite_cargo_version(toml, "0.48.3").unwrap();
3230        assert!(out.contains("anyhow = { version = \"1\" }"));
3231        assert!(out.contains("serde = { version = \"1\", features = [\"derive\"] }"));
3232        assert!(
3233            out.contains(
3234                "kanade-shared = { path = \"crates/kanade-shared\", version = \"0.48.3\" }"
3235            )
3236        );
3237        assert!(
3238            out.contains("kanade-core = { path = \"crates/kanade-core\", version = \"0.48.3\" }")
3239        );
3240        assert!(out.contains("kanade-internal-tool = { path = \"crates/kanade-internal-tool\" }"));
3241    }
3242
3243    /// A shape the line-based rewrite cannot express - an inline table split
3244    /// across lines - must fail the whole bump rather than silently leave
3245    /// the pin stale.
3246    #[test]
3247    fn cargo_version_rewrite_bails_on_an_unrepresentable_inline_table() {
3248        let toml = "\
3249[workspace.package]\n\
3250version = \"0.1.0\"\n\
3251\n\
3252[workspace.dependencies]\n\
3253inner = { path = \"crates/inner\",\n\
3254    version = \"0.1.0\" }\n";
3255        assert!(rewrite_cargo_version(toml, "0.2.0").is_err());
3256    }
3257
3258    /// A trailing comment on the `[workspace.dependencies]` header itself is
3259    /// valid TOML and must not stop the section from being recognised.
3260    #[test]
3261    fn cargo_version_rewrite_recognises_a_commented_workspace_dependencies_header() {
3262        let toml = "\
3263[workspace.package]\n\
3264version = \"0.1.0\"\n\
3265\n\
3266[workspace.dependencies] # internal pins\n\
3267inner = { path = \"crates/inner\", version = \"0.1.0\" }\n";
3268        let out = rewrite_cargo_version(toml, "0.2.0").unwrap();
3269        assert!(out.contains("inner = { path = \"crates/inner\", version = \"0.2.0\" }"));
3270    }
3271
3272    /// A quoted dependency key (`"inner" = { .. }`) is valid TOML and must
3273    /// compare equal to the plain name the `toml` crate itself reports.
3274    #[test]
3275    fn cargo_version_rewrite_bumps_a_quoted_dependency_key() {
3276        let toml = "\
3277[workspace.package]\n\
3278version = \"0.1.0\"\n\
3279\n\
3280[workspace.dependencies]\n\
3281\"inner\" = { path = \"crates/inner\", version = \"0.1.0\" }\n";
3282        let out = rewrite_cargo_version(toml, "0.2.0").unwrap();
3283        assert!(out.contains("\"inner\" = { path = \"crates/inner\", version = \"0.2.0\" }"));
3284    }
3285
3286    /// A literal (single-quoted) TOML string is a legal way to spell a
3287    /// version pin, and the rewrite must preserve that quoting style rather
3288    /// than failing to find it or silently switching it to a basic string.
3289    #[test]
3290    fn cargo_version_rewrite_bumps_a_literal_string_version_pin() {
3291        let toml = "\
3292[workspace.package]\n\
3293version = \"0.1.0\"\n\
3294\n\
3295[workspace.dependencies]\n\
3296inner = { path = 'crates/inner', version = '0.1.0' }\n";
3297        let out = rewrite_cargo_version(toml, "0.2.0").unwrap();
3298        assert!(out.contains("inner = { path = 'crates/inner', version = '0.2.0' }"));
3299    }
3300
3301    /// A manifest whose unrelated sections would not satisfy a strict
3302    /// whole-file TOML parse (here: a duplicate top-level table, which the
3303    /// `toml` crate rejects) must still have its `[workspace.dependencies]`
3304    /// pins rewritten - only that section's own syntax is a precondition,
3305    /// not the rest of the file.
3306    #[test]
3307    fn cargo_version_rewrite_does_not_require_the_whole_file_to_parse() {
3308        let toml = "\
3309[workspace.package]\n\
3310version = \"0.1.0\"\n\
3311\n\
3312[workspace.dependencies]\n\
3313inner = { path = \"crates/inner\", version = \"0.1.0\" }\n\
3314\n\
3315[workspace.package]\n\
3316edition = \"2024\"\n";
3317        let out = rewrite_cargo_version(toml, "0.2.0").unwrap();
3318        assert!(out.contains("inner = { path = \"crates/inner\", version = \"0.2.0\" }"));
3319        assert!(
3320            toml::from_str::<toml::Value>(toml).is_err(),
3321            "the fixture itself must be invalid as a whole file, or this test proves nothing"
3322        );
3323    }
3324
3325    #[test]
3326    fn current_version_prefers_the_package_table_when_both_exist() {
3327        let toml = "[workspace.package]\nversion = \"9.9.9\"\n\n[package]\nversion = \"0.8.0\"\n";
3328        assert_eq!(current_version(toml).unwrap(), "0.8.0");
3329    }
3330
3331    /// Same shape as `kanadehq/kanade`'s root `Cargo.toml`: no `[package]`
3332    /// at all, only `[workspace]` and `[workspace.package]`.
3333    #[test]
3334    fn current_version_falls_back_to_workspace_package_without_a_package_table() {
3335        let toml = "\
3336[workspace]\n\
3337members = [\"crates/a\", \"crates/b\"]\n\
3338\n\
3339[workspace.package]\n\
3340version = \"0.45.18\"\n";
3341        assert_eq!(current_version(toml).unwrap(), "0.45.18");
3342    }
3343
3344    #[test]
3345    fn coalesce_proceeds_with_nothing_pending() {
3346        assert_eq!(coalesce(None, "0.8.0").unwrap(), Coalesce::Proceed);
3347    }
3348
3349    /// A minimal, otherwise-plausible pending marker for tests that only
3350    /// care about one field.
3351    fn test_pending(target_version: &str, level: BumpLevel) -> PendingBump {
3352        PendingBump {
3353            target_version: target_version.to_owned(),
3354            level,
3355            branch: format!("chore/release-v{target_version}"),
3356            pr_url: "https://example.invalid/pull/9".to_owned(),
3357        }
3358    }
3359
3360    #[test]
3361    fn coalesce_skips_while_the_pending_target_is_still_ahead() {
3362        let pending = test_pending("0.9.0", BumpLevel::Minor);
3363        assert_eq!(
3364            coalesce(Some(&pending), "0.8.0").unwrap(),
3365            Coalesce::Skip {
3366                target_version: "0.9.0".to_owned()
3367            }
3368        );
3369    }
3370
3371    #[test]
3372    fn coalesce_treats_a_landed_or_superseded_pending_bump_as_stale() {
3373        let pending = test_pending("0.9.0", BumpLevel::Minor);
3374        // The pending bump landed exactly: proceed with a fresh decision.
3375        assert_eq!(
3376            coalesce(Some(&pending), "0.9.0").unwrap(),
3377            Coalesce::Proceed
3378        );
3379        // A human bumped further than what was pending: also proceed.
3380        assert_eq!(
3381            coalesce(Some(&pending), "1.0.0").unwrap(),
3382            Coalesce::Proceed
3383        );
3384    }
3385
3386    #[test]
3387    fn pending_action_escalates_only_for_a_more_severe_decision() {
3388        assert_eq!(
3389            pending_action(BumpLevel::Patch, BumpLevel::Patch),
3390            PendingAction::AlreadyCovered
3391        );
3392        assert_eq!(
3393            pending_action(BumpLevel::Patch, BumpLevel::Minor),
3394            PendingAction::Escalate
3395        );
3396        assert_eq!(
3397            pending_action(BumpLevel::Patch, BumpLevel::Major),
3398            PendingAction::Escalate
3399        );
3400        assert_eq!(
3401            pending_action(BumpLevel::Minor, BumpLevel::Patch),
3402            PendingAction::AlreadyCovered
3403        );
3404        assert_eq!(
3405            pending_action(BumpLevel::Major, BumpLevel::Minor),
3406            PendingAction::AlreadyCovered
3407        );
3408        assert_eq!(
3409            pending_action(BumpLevel::Major, BumpLevel::Major),
3410            PendingAction::AlreadyCovered
3411        );
3412    }
3413
3414    #[test]
3415    fn pr_state_parsing_reads_open_and_not_open() {
3416        assert!(parse_pr_state(r#"{"state":"OPEN"}"#).unwrap());
3417        assert!(!parse_pr_state(r#"{"state":"CLOSED"}"#).unwrap());
3418        assert!(!parse_pr_state(r#"{"state":"MERGED"}"#).unwrap());
3419    }
3420
3421    #[test]
3422    fn a_lock_is_exclusive_until_dropped() {
3423        let dir = tempfile::tempdir().unwrap();
3424        let marker = dir.path().join("bump").join("deadbeefdeadbeef.json");
3425        let first = MarkerLock::acquire(&marker)
3426            .unwrap()
3427            .expect("first attempt takes the lock");
3428        assert!(
3429            MarkerLock::acquire(&marker).unwrap().is_none(),
3430            "a second attempt must be refused while the first holds it"
3431        );
3432        drop(first);
3433        assert!(
3434            MarkerLock::acquire(&marker).unwrap().is_some(),
3435            "dropping the guard releases the lock for the next attempt"
3436        );
3437    }
3438
3439    #[test]
3440    fn a_stale_lock_is_reclaimed() {
3441        let dir = tempfile::tempdir().unwrap();
3442        let marker = dir.path().join("bump").join("deadbeefdeadbeef.json");
3443        let lock_path = marker.with_extension("lock");
3444        std::fs::create_dir_all(lock_path.parent().unwrap()).unwrap();
3445        std::fs::write(&lock_path, b"").unwrap();
3446        let old = std::time::SystemTime::now() - LOCK_STALE_AFTER - Duration::from_secs(1);
3447        std::fs::OpenOptions::new()
3448            .write(true)
3449            .open(&lock_path)
3450            .unwrap()
3451            .set_modified(old)
3452            .unwrap();
3453        assert!(
3454            MarkerLock::acquire(&marker).unwrap().is_some(),
3455            "a lock older than the stale window must be reclaimed rather than block forever"
3456        );
3457    }
3458
3459    #[tokio::test]
3460    async fn a_contended_lock_is_retried_until_the_holder_releases_it() {
3461        let dir = tempfile::tempdir().unwrap();
3462        let marker = dir.path().join("bump").join("deadbeefdeadbeef.json");
3463        let held = MarkerLock::acquire(&marker)
3464            .unwrap()
3465            .expect("seed the contention");
3466        let releaser = tokio::spawn(async move {
3467            tokio::time::sleep(Duration::from_millis(20)).await;
3468            drop(held);
3469        });
3470        let waited =
3471            wait_for_marker_lock_with(&marker, Duration::from_millis(5), Duration::from_secs(5))
3472                .await
3473                .unwrap();
3474        assert!(
3475            waited.is_some(),
3476            "a merge landing behind another's still-running decision must not be dropped - it \
3477             must wait for that decision to finish and then judge against what it left behind"
3478        );
3479        releaser.await.unwrap();
3480    }
3481
3482    #[tokio::test]
3483    async fn a_lock_held_past_the_ceiling_gives_up() {
3484        let dir = tempfile::tempdir().unwrap();
3485        let marker = dir.path().join("bump").join("deadbeefdeadbeef.json");
3486        let _held = MarkerLock::acquire(&marker).unwrap().unwrap();
3487        let waited =
3488            wait_for_marker_lock_with(&marker, Duration::from_millis(2), Duration::from_millis(10))
3489                .await
3490                .unwrap();
3491        assert!(
3492            waited.is_none(),
3493            "a lock genuinely held past the ceiling must eventually give up rather than wait \
3494             forever"
3495        );
3496    }
3497
3498    #[test]
3499    fn level_between_reads_off_the_differing_digit() {
3500        assert_eq!(
3501            level_between(
3502                Version::parse("0.8.0").unwrap(),
3503                Version::parse("1.0.0").unwrap()
3504            ),
3505            Some(BumpLevel::Major)
3506        );
3507        assert_eq!(
3508            level_between(
3509                Version::parse("0.8.0").unwrap(),
3510                Version::parse("0.9.0").unwrap()
3511            ),
3512            Some(BumpLevel::Minor)
3513        );
3514        assert_eq!(
3515            level_between(
3516                Version::parse("0.8.0").unwrap(),
3517                Version::parse("0.8.1").unwrap()
3518            ),
3519            Some(BumpLevel::Patch)
3520        );
3521        assert_eq!(
3522            level_between(
3523                Version::parse("0.8.0").unwrap(),
3524                Version::parse("0.8.0").unwrap()
3525            ),
3526            None
3527        );
3528    }
3529
3530    #[test]
3531    fn open_release_pr_is_found_among_unrelated_pull_requests() {
3532        let json = r#"[
3533            {"url": "https://example.invalid/pull/1", "headRefName": "feat/something"},
3534            {"url": "https://example.invalid/pull/2", "headRefName": "chore/release-v0.9.0"}
3535        ]"#;
3536        let found = parse_open_release_pr(json).unwrap();
3537        assert_eq!(
3538            found,
3539            Some((
3540                "chore/release-v0.9.0".to_owned(),
3541                "https://example.invalid/pull/2".to_owned()
3542            ))
3543        );
3544    }
3545
3546    #[test]
3547    fn no_open_release_pr_reads_as_none_not_an_error() {
3548        let json =
3549            r#"[{"url": "https://example.invalid/pull/1", "headRefName": "feat/something"}]"#;
3550        assert_eq!(parse_open_release_pr(json).unwrap(), None);
3551        assert_eq!(parse_open_release_pr("[]").unwrap(), None);
3552    }
3553
3554    #[test]
3555    fn marker_round_trips_through_disk() {
3556        let dir = tempfile::tempdir().unwrap();
3557        let path = marker_path(dir.path(), Path::new("/repos/magi"));
3558        assert!(read_marker(&path).is_none());
3559
3560        let marker = test_pending("0.9.0", BumpLevel::Patch);
3561        write_marker(&path, &marker).unwrap();
3562        let read_back = read_marker(&path).unwrap();
3563        assert_eq!(read_back.target_version, "0.9.0");
3564        assert_eq!(read_back.level, BumpLevel::Patch);
3565        assert_eq!(read_back.pr_url, marker.pr_url);
3566
3567        clear_marker(&path);
3568        assert!(read_marker(&path).is_none());
3569    }
3570
3571    #[test]
3572    fn different_repos_get_different_marker_files() {
3573        let dir = tempfile::tempdir().unwrap();
3574        let a = marker_path(dir.path(), Path::new("/repos/a"));
3575        let b = marker_path(dir.path(), Path::new("/repos/b"));
3576        assert_ne!(a, b);
3577    }
3578
3579    /// A version-bump-only pull request must never trigger the next bump - see
3580    /// [`is_release_only`]'s own doc for why that shape is the trigger for
3581    /// "do not treat this as a change to react to".
3582    #[test]
3583    fn a_bump_pull_requests_own_merge_does_not_retrigger() {
3584        let files = vec!["Cargo.toml".to_owned(), "Cargo.lock".to_owned()];
3585        assert!(
3586            is_release_only(&files),
3587            "the bump pull request's own diff must read as release-only"
3588        );
3589    }
3590
3591    #[test]
3592    fn should_release_bump_reads_only_a_merged_status() {
3593        assert!(should_release_bump(RunStatus::Merged));
3594        for other in [RunStatus::Blocked, RunStatus::Ready, RunStatus::Prep] {
3595            assert!(!should_release_bump(other));
3596        }
3597    }
3598
3599    /// `land::Step::Done { merged: true }` - a pull request already merged
3600    /// underneath magi. `land::decide` reads that straight off the pull
3601    /// request's own lifecycle before it looks at checks or comments at all.
3602    #[test]
3603    fn all_three_merge_paths_report_pr_lifecycle_merged_case_done() {
3604        let pr = land::PrState {
3605            url: "https://github.com/o/r/pull/1".to_owned(),
3606            number: 1,
3607            state: PrLifecycle::Merged,
3608            checks: land::Checks::Green,
3609            failing: Vec::new(),
3610            review_comments: Vec::new(),
3611            blocking: land::Blocking::No,
3612        };
3613        assert_eq!(
3614            land::decide(&pr, 0, 4, Duration::ZERO),
3615            land::Step::Done { merged: true }
3616        );
3617        assert!(should_release_bump(RunStatus::Merged));
3618    }
3619
3620    /// `land::Step::Merge`'s own `gh pr merge` succeeding: `land::land` then
3621    /// sets `pr.state = PrLifecycle::Merged` by hand before returning (see
3622    /// `land::land`'s `Step::Merge` arm), which is the same value the other
3623    /// two paths converge on.
3624    #[test]
3625    fn all_three_merge_paths_report_pr_lifecycle_merged_case_direct_merge() {
3626        let pr = land::PrState {
3627            url: "https://github.com/o/r/pull/2".to_owned(),
3628            number: 2,
3629            state: PrLifecycle::Open,
3630            checks: land::Checks::Green,
3631            failing: Vec::new(),
3632            review_comments: Vec::new(),
3633            blocking: land::Blocking::No,
3634        };
3635        assert_eq!(land::decide(&pr, 0, 4, Duration::ZERO), land::Step::Merge);
3636        // land::land's Step::Merge arm sets this by hand on success; asserted
3637        // here as the value that then makes should_release_bump fire.
3638        assert!(should_release_bump(RunStatus::Merged));
3639    }
3640
3641    /// [`land::merged_after_all`] - `gh pr merge` exited non-zero but the
3642    /// forge confirms the pull request merged anyway.
3643    #[test]
3644    fn all_three_merge_paths_report_pr_lifecycle_merged_case_merged_after_all() {
3645        let argv = land::merge_argv(3, "feat: something");
3646        let outcome = land::merged_after_all(
3647            &argv,
3648            "could not determine current branch: not on any branch",
3649            Some(PrLifecycle::Merged),
3650        );
3651        assert!(outcome.is_some(), "the forge's confirmation must win");
3652        assert!(should_release_bump(RunStatus::Merged));
3653
3654        // The same recovery must not fabricate a merge when the forge does
3655        // not confirm one.
3656        assert!(land::merged_after_all(&argv, "network error", Some(PrLifecycle::Open)).is_none());
3657        assert!(land::merged_after_all(&argv, "network error", None).is_none());
3658    }
3659
3660    /// The paths that do *not* land must not read as merged either.
3661    #[test]
3662    fn a_close_or_a_give_up_does_not_trigger_a_bump() {
3663        let pr = land::PrState {
3664            url: "https://github.com/o/r/pull/4".to_owned(),
3665            number: 4,
3666            state: PrLifecycle::Closed,
3667            checks: land::Checks::Green,
3668            failing: Vec::new(),
3669            review_comments: Vec::new(),
3670            blocking: land::Blocking::No,
3671        };
3672        assert_eq!(
3673            land::decide(&pr, 0, 4, Duration::ZERO),
3674            land::Step::Done { merged: false }
3675        );
3676        assert!(!should_release_bump(RunStatus::Blocked));
3677    }
3678}