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, bail};
27use serde::{Deserialize, Serialize};
28
29use crate::agent::{self, Invocation, SeatState};
30use crate::ask;
31use crate::config::AgentSpec;
32use crate::git;
33use crate::land;
34use crate::proc::Quiet as _;
35use crate::run::{self, RunState, RunStatus};
36use crate::verdict;
37
38/// How long the decision call may run.
39///
40/// It reads a diffstat, a subject line and a version string, and returns
41/// three words and a sentence - nowhere near the budget an implement wave
42/// gets, so a fixed, generous constant is simpler than a new config knob for
43/// a call this small.
44const DECISION_TIMEOUT: Duration = Duration::from_secs(600);
45
46/// Does this run's final status mean the merge this call is downstream of
47/// actually happened?
48///
49/// All three of `land`'s success paths converge on the same signal before
50/// [`crate::graph`] ever calls into this module: a pull request already
51/// merged underneath magi (`land::Step::Done { merged: true }`),
52/// `land::Step::Merge`'s own `gh pr merge` succeeding, and the
53/// [`land::merged_after_all`] recovery for a non-zero exit that merged
54/// anyway. Every one of them ends `land::land` with `pr.state ==
55/// PrLifecycle::Merged`, which is exactly what `graph::Runner::merge` reads
56/// to set `RunStatus::Merged` on the run - see the `all_three_merge_paths_*`
57/// tests below for each path's own evidence. Every path that does *not* land
58/// (a close, `Step::GiveUp`, an unanswered `land_approval`, or a `gh pr
59/// merge` failure the forge does not confirm) leaves the run `Blocked`
60/// instead, so this one check is the whole gate a caller needs.
61pub fn should_release_bump(status: RunStatus) -> bool {
62    status == RunStatus::Merged
63}
64
65/// Which digit of `major.minor.patch` a change earns.
66#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
67#[serde(rename_all = "lowercase")]
68pub enum BumpLevel {
69    /// A breaking change to a public surface.
70    Major,
71    /// A user-visible new capability, or - below `1.0.0` - a breaking change.
72    Minor,
73    /// A fix, internal refactor, or dependency update.
74    Patch,
75}
76
77impl BumpLevel {
78    /// Stable lower-case name, as the prompt and the events spell it.
79    pub fn as_str(self) -> &'static str {
80        match self {
81            Self::Major => "major",
82            Self::Minor => "minor",
83            Self::Patch => "patch",
84        }
85    }
86
87    /// Severity for comparing two independent decisions: `patch < minor <
88    /// major`, spelled out explicitly rather than derived from declaration
89    /// order, which exists here only for readability and must not silently
90    /// become load-bearing.
91    fn severity(self) -> u8 {
92        match self {
93            Self::Patch => 0,
94            Self::Minor => 1,
95            Self::Major => 2,
96        }
97    }
98}
99
100/// The agent's answer: which digit, and why.
101///
102/// Parsed with [`verdict::extract_json`], so a reply missing `reason`, or
103/// spelling `level` as anything but `major` / `minor` / `patch`, is a parse
104/// error rather than a value with a blank field - [`parse_decision`] never
105/// fabricates a bump out of a response it could not read.
106#[derive(Debug, Clone, Deserialize)]
107pub struct BumpDecision {
108    /// The chosen digit.
109    pub level: BumpLevel,
110    /// One line, carried into the pull request body so "why was this minor"
111    /// is answerable later without archaeology.
112    pub reason: String,
113}
114
115/// Parse the agent's reply. Never returns a default decision: an unparsable
116/// or incomplete reply is `Err`, and the caller must not open a bump pull
117/// request on the strength of a guess.
118pub fn parse_decision(text: &str) -> Result<BumpDecision> {
119    let decision: BumpDecision = verdict::extract_json(text)?;
120    if decision.reason.trim().is_empty() {
121        bail!("the bump decision carried no reason");
122    }
123    Ok(decision)
124}
125
126/// `major.minor.patch`, the only shape a `[package] version` in this
127/// ecosystem carries in practice.
128#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
129pub struct Version {
130    /// First component.
131    pub major: u64,
132    /// Second component.
133    pub minor: u64,
134    /// Third component.
135    pub patch: u64,
136}
137
138impl Version {
139    /// Parse `major.minor.patch`. A pre-release or build suffix on the patch
140    /// component (`0.8.0-rc1`) is tolerated by reading only its leading
141    /// digits - Cargo itself never writes one into `[package] version`, but a
142    /// human editing the file by hand might.
143    pub fn parse(s: &str) -> Result<Self> {
144        let s = s.trim();
145        let mut parts = s.splitn(3, '.');
146        let major = parts
147            .next()
148            .with_context(|| format!("`{s}` has no major component"))?;
149        let minor = parts
150            .next()
151            .with_context(|| format!("`{s}` has no minor component"))?;
152        let patch = parts
153            .next()
154            .with_context(|| format!("`{s}` has no patch component"))?;
155        let patch_digits: String = patch.chars().take_while(char::is_ascii_digit).collect();
156        Ok(Self {
157            major: major
158                .trim()
159                .parse()
160                .with_context(|| format!("`{major}` is not a number"))?,
161            minor: minor
162                .trim()
163                .parse()
164                .with_context(|| format!("`{minor}` is not a number"))?,
165            patch: patch_digits
166                .parse()
167                .with_context(|| format!("`{patch}` has no numeric patch component"))?,
168        })
169    }
170
171    /// The next version at `level`. A `major`/`minor` bump zeroes every digit
172    /// below it, matching what every tool that reads a semver range expects.
173    #[must_use]
174    pub fn bump(self, level: BumpLevel) -> Self {
175        match level {
176            BumpLevel::Major => Self {
177                major: self.major + 1,
178                minor: 0,
179                patch: 0,
180            },
181            BumpLevel::Minor => Self {
182                major: self.major,
183                minor: self.minor + 1,
184                patch: 0,
185            },
186            BumpLevel::Patch => Self {
187                major: self.major,
188                minor: self.minor,
189                patch: self.patch + 1,
190            },
191        }
192    }
193}
194
195impl std::fmt::Display for Version {
196    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
197        write!(f, "{}.{}.{}", self.major, self.minor, self.patch)
198    }
199}
200
201/// Did the merged change touch only the release manifest and its lockfile?
202///
203/// [`after_merge`] is reached from *every* qualifying merge, including a
204/// version-bump pull request's own - without this check a bump would trigger
205/// another bump forever. A human-authored version-only pull request is exempt
206/// from review for the same reason (`AGENTS.md`'s "version-bump-only pull
207/// requests"), so using its shape as the "do not treat this as a trigger"
208/// test is one rule doing both jobs instead of two.
209pub fn is_release_only(files: &[String]) -> bool {
210    !files.is_empty() && files.iter().all(|f| f == "Cargo.toml" || f == "Cargo.lock")
211}
212
213/// Rewrite `table`'s `version = "..."` line, leaving every other byte
214/// untouched.
215///
216/// Scoped to the named table specifically, rather than the first line
217/// anywhere in the file that looks like `version = "..."`: a dependency
218/// pinned as `foo = { version = "1.2.3" }` must never move, and neither must
219/// the *other* of `[package]` / `[workspace.package]` when only one of them
220/// is the one being bumped. That scoping is what lets a version-bump-only
221/// diff stay exactly that, which [`is_release_only`] and the "no reviewer
222/// needed" exemption in `AGENTS.md` both rest on.
223fn rewrite_table_version(toml: &str, table: &str, new_version: &str) -> Result<String> {
224    let mut out = String::with_capacity(toml.len() + 8);
225    let mut in_table = false;
226    let mut done = false;
227    for line in toml.split_inclusive('\n') {
228        let trimmed = line.trim();
229        if trimmed.starts_with('[') {
230            in_table = trimmed == table;
231        }
232        if !done && in_table && trimmed.split('=').next().map(str::trim) == Some("version") {
233            let newline = if line.ends_with("\r\n") { "\r\n" } else { "\n" };
234            let _ = write!(out, "version = \"{new_version}\"{newline}");
235            done = true;
236            continue;
237        }
238        out.push_str(line);
239    }
240    if !done {
241        bail!("no `version` field found under `{table}`");
242    }
243    Ok(out)
244}
245
246/// Rewrite the release version, wherever this manifest actually declares it.
247///
248/// A single crate carries its version under `[package]`. A workspace root
249/// with no crate of its own - `[workspace] members = [...]` and nothing
250/// else - carries it under `[workspace.package]` instead, and `[package]`
251/// does not exist there at all. `[package]` is tried first because it is the
252/// far more common shape and the one every existing bump so far has hit;
253/// `[workspace.package]` is the fallback for the shape that never worked
254/// before this. Either way exactly one table is ever touched, so the "one
255/// version line changes" property [`rewrite_table_version`] rests on holds
256/// regardless of which table it was.
257pub fn rewrite_cargo_version(toml: &str, new_version: &str) -> Result<String> {
258    rewrite_table_version(toml, "[package]", new_version)
259        .or_else(|_| rewrite_table_version(toml, "[workspace.package]", new_version))
260        .context("no `version` field found under `[package]` or `[workspace.package]`")
261}
262
263/// Find `table`'s `version` field, if it has one. No I/O.
264fn version_in_table(toml: &str, table: &str) -> Option<String> {
265    let mut in_table = false;
266    for line in toml.lines() {
267        let trimmed = line.trim();
268        if trimmed.starts_with('[') {
269            in_table = trimmed == table;
270            continue;
271        }
272        if !in_table {
273            continue;
274        }
275        let mut parts = trimmed.splitn(2, '=');
276        let key = parts.next().map(str::trim);
277        let Some(value) = parts.next() else {
278            continue;
279        };
280        if key == Some("version") {
281            return Some(value.trim().trim_matches('"').to_owned());
282        }
283    }
284    None
285}
286
287/// Read the version currently on the base branch, from `[package]` if it has
288/// one, else from `[workspace.package]` - see [`rewrite_cargo_version`] for
289/// why both exist and which wins. No I/O: the caller fetches the blob (`git
290/// show <remote>/<base>:Cargo.toml`).
291fn current_version(toml: &str) -> Result<String> {
292    version_in_table(toml, "[package]")
293        .or_else(|| version_in_table(toml, "[workspace.package]"))
294        .context("no `version` field found under `[package]` or `[workspace.package]`")
295}
296
297/// Build the prompt asking an agent which digit of `major.minor.patch` a
298/// merged change earns.
299///
300/// Pure: every input is already known once a merge lands, so the whole
301/// decision policy - the "`minor` is the breaking digit below `1.0.0`" rule,
302/// what counts as a breaking surface, and the tie-break toward the larger
303/// digit - is asserted directly on the returned string, the same way
304/// [`crate::land::fix_prompt`] doc-comments its own rules rather than leaving
305/// them for a human to spot missing from a live reply.
306pub fn decision_prompt(
307    subject: &str,
308    instruction: &str,
309    diffstat: &str,
310    files: &[String],
311    current_version: &str,
312) -> String {
313    let mut s = format!(
314        "A pull request just merged into the base branch. Decide which digit \
315         of this project's `major.minor.patch` version this change earns, so \
316         a release bump can be opened for exactly it.\n\n\
317         Current version: {current_version}\n\n\
318         # Merge subject\n\n{subject}\n\n\
319         # The task that produced it\n\n{instruction}\n\n\
320         # Files changed ({} total)\n\n",
321        files.len()
322    );
323    const MAX_FILES: usize = 50;
324    for f in files.iter().take(MAX_FILES) {
325        let _ = writeln!(s, "- {f}");
326    }
327    if files.len() > MAX_FILES {
328        let _ = writeln!(s, "- ... and {} more", files.len() - MAX_FILES);
329    }
330    let _ = write!(s, "\n# Diffstat\n\n```\n{}\n```\n", diffstat.trim());
331
332    s.push_str(
333        "\n# How to decide\n\n\
334         This project is below version `1.0.0`. At that stage **`minor` is \
335         the digit that carries a breaking change** - do not spend `major` \
336         below `1.0.0`.\n\n\
337         A change is breaking, and earns `minor`, when it changes any of: \
338         the public API reachable from `src/lib.rs`, a CLI subcommand or \
339         flag, an HTTP API route or response shape, a configuration key, or \
340         the on-disk shape of persisted state.\n\n\
341         A user-visible new capability that breaks none of the above also \
342         earns `minor`.\n\n\
343         A fix, an internal refactor, or a dependency update earns `patch`.\n\n\
344         **When it is not obvious which digit applies, choose the larger \
345         one.** An oversized bump costs nothing; a breaking change shipped as \
346         `patch` breaks every downstream update that pins a range.\n\n\
347         # Output\n\n\
348         Reply with exactly one fenced JSON object and nothing that matters \
349         outside it:\n\n\
350         ```json\n\
351         {\"level\": \"major\" | \"minor\" | \"patch\", \"reason\": \"one line\"}\n\
352         ```\n",
353    );
354    // The reason is pasted into the release pull request's body.
355    let _ = write!(
356        s,
357        "\n{}\n\nThe `reason` goes into a GitHub pull request body, so write it \
358         in English.\n",
359        crate::prompt::GITHUB_ENGLISH_HEADING
360    );
361    s
362}
363
364/// magi's own record of a bump pull request it currently has open, so a
365/// burst of merges in quick succession does not each open a competing
366/// release.
367///
368/// **Chosen policy: serialize, not coalesce two independent decisions into
369/// one.** A bump branch touches only `Cargo.toml` / `Cargo.lock`, so `gh pr
370/// merge --squash` applies it onto whatever the base branch has become by
371/// the time it lands - every commit merged while it was open rides along
372/// for free, at no extra cost, once it merges. But the *digit* a still-open
373/// pull request targets was judged from only the first change, and a more
374/// severe change landing while it waits must not ship at the smaller digit
375/// just because it arrived second - so the serialization is at the pull
376/// request, not at the judgement: a later, more severe decision escalates
377/// the same open pull request (see [`pending_action`]) rather than opening a
378/// second one or being silently absorbed at the wrong digit.
379#[derive(Debug, Clone, Serialize, Deserialize)]
380pub struct PendingBump {
381    /// The version the open pull request bumps to.
382    pub target_version: String,
383    /// The digit that version was judged to need, so a later, more severe
384    /// merge can tell it needs to escalate rather than assume it is covered.
385    pub level: BumpLevel,
386    /// The branch the open pull request is built from, so an escalation
387    /// knows what to check out and push to.
388    pub branch: String,
389    /// The pull request's URL, so a later merge can confirm it is still
390    /// open before trusting it to block a fresh decision.
391    pub pr_url: String,
392}
393
394/// Where [`PendingBump`] is recorded for `repo` - one file per repository, so
395/// a machine running magi against more than one checkout does not confuse
396/// their releases with each other.
397pub fn marker_path(home: &Path, repo: &Path) -> PathBuf {
398    let key = repo.to_string_lossy();
399    home.join("bump")
400        .join(format!("{:016x}.json", crate::rng::fnv1a(&key)))
401}
402
403/// Read a recorded [`PendingBump`], if any. Missing or unreadable both read
404/// as "nothing pending" - a marker is bookkeeping, not a source of truth
405/// worth failing a merge over.
406pub fn read_marker(path: &Path) -> Option<PendingBump> {
407    let body = std::fs::read_to_string(path).ok()?;
408    serde_json::from_str(&body).ok()
409}
410
411/// Persist `marker`, atomically - the same tmp-then-rename shape
412/// [`crate::updater::write_progress`] uses, since this file is read by a
413/// later, unrelated process invocation and must never be seen half-written.
414pub fn write_marker(path: &Path, marker: &PendingBump) -> Result<()> {
415    if let Some(parent) = path.parent() {
416        std::fs::create_dir_all(parent).with_context(|| format!("create {}", parent.display()))?;
417    }
418    let body = serde_json::to_string_pretty(marker).context("serialize pending bump")?;
419    let tmp = path.with_extension("json.tmp");
420    std::fs::write(&tmp, &body).with_context(|| format!("write {}", tmp.display()))?;
421    std::fs::rename(&tmp, path).with_context(|| format!("replace {}", path.display()))?;
422    Ok(())
423}
424
425/// Drop a recorded marker. Best-effort: a marker that is already gone is not
426/// an error.
427pub fn clear_marker(path: &Path) {
428    let _ = std::fs::remove_file(path);
429}
430
431/// What a recorded [`PendingBump`] means for a fresh decision, given what the
432/// base branch's `Cargo.toml` says right now. No I/O: the caller reads both
433/// the marker and the version.
434#[derive(Debug, Clone, PartialEq, Eq)]
435pub enum Coalesce {
436    /// Nothing is pending, or the pending bump already landed (or was
437    /// superseded by a manual one) - safe to open a fresh decision.
438    Proceed,
439    /// A bump to `target_version` is already open; do not open a second one.
440    Skip {
441        /// The version the pending pull request already targets.
442        target_version: String,
443    },
444}
445
446/// Decide what a pending marker means against `current_version`.
447pub fn coalesce(pending: Option<&PendingBump>, current_version: &str) -> Result<Coalesce> {
448    let Some(pending) = pending else {
449        return Ok(Coalesce::Proceed);
450    };
451    let current = Version::parse(current_version)?;
452    let target = Version::parse(&pending.target_version)?;
453    if current >= target {
454        return Ok(Coalesce::Proceed);
455    }
456    Ok(Coalesce::Skip {
457        target_version: pending.target_version.clone(),
458    })
459}
460
461/// What a still-open pending bump means once a fresh decision is in hand.
462#[derive(Debug, Clone, Copy, PartialEq, Eq)]
463pub enum PendingAction {
464    /// The new decision is no more severe than what is already queued; the
465    /// open pull request covers it once it lands.
466    AlreadyCovered,
467    /// The new decision outranks the pending target - escalate the open
468    /// pull request instead of opening a second one or dropping it.
469    Escalate,
470}
471
472/// Compare a fresh decision against what a still-open pull request already
473/// targets.
474///
475/// A patch bump left pending while a breaking change lands does not become a
476/// breaking release just because the pull request that carries both is
477/// squashed into one commit: the *version number* still comes from whichever
478/// digit was judged, and a pending `patch` never widens itself to `minor` on
479/// its own. This is the check that decides an escalation is owed.
480pub fn pending_action(pending_level: BumpLevel, decision_level: BumpLevel) -> PendingAction {
481    if decision_level.severity() > pending_level.severity() {
482        PendingAction::Escalate
483    } else {
484        PendingAction::AlreadyCovered
485    }
486}
487
488/// Parse `gh pr view --json state` output. No I/O.
489fn parse_pr_state(json: &str) -> Result<bool> {
490    #[derive(Deserialize)]
491    struct State {
492        state: String,
493    }
494    let parsed: State =
495        serde_json::from_str(json).context("parse `gh pr view --json state` output")?;
496    Ok(parsed.state.eq_ignore_ascii_case("OPEN"))
497}
498
499/// Is the pull request at `pr_url` still open?
500///
501/// Read fresh rather than trusted from the marker: a bump pull request can be
502/// closed without merging - CI that never goes green, an operator who
503/// decided against it - and nothing else in this module ever revisits a
504/// marker once it is written. Without this check, that close is invisible
505/// here forever: the marker still names a pending target, the base branch
506/// never reaches it because nothing ever merged the pull request, and every
507/// later merge skips in perpetuity. A `gh` failure (network, auth) answers
508/// `true` - the same "unreadable is not absent" rule `land::CHECKS_GRACE`
509/// uses - because guessing "closed" wrongly opens a second, competing pull
510/// request, while guessing "open" wrongly only costs one more merge's wait.
511async fn pr_is_open(repo: &Path, pr_url: &str) -> Result<bool> {
512    let out = tokio::process::Command::new("gh")
513        .args(["pr", "view", pr_url, "--json", "state"])
514        .current_dir(repo)
515        .quiet()
516        .stdin(std::process::Stdio::null())
517        .output()
518        .await
519        .context("spawn gh pr view")?;
520    if !out.status.success() {
521        bail!(
522            "gh pr view {pr_url}: {}",
523            String::from_utf8_lossy(&out.stderr).trim()
524        );
525    }
526    parse_pr_state(&String::from_utf8_lossy(&out.stdout))
527}
528
529/// How long a stale lock file is trusted to mean its owner is still working,
530/// before it is reclaimed.
531///
532/// Long enough to cover the slowest real step this module takes - the agent
533/// decision call ([`DECISION_TIMEOUT`]) plus `cargo build` and a `gh pr
534/// create` - so a lock is only ever stolen from a process that has actually
535/// gone (crashed, killed), never one still inside its own critical section.
536const LOCK_STALE_AFTER: Duration = Duration::from_secs(30 * 60);
537
538/// A host-local mutual exclusion for one repository's marker file.
539///
540/// Built on exclusive file creation rather than a locking crate: neither
541/// `flock` nor `fs2` is a dependency of this crate, and the constraints on
542/// this change forbid adding one. This is not a distributed lock and does
543/// not coordinate two machines racing the same repository - it exists to
544/// close the specific race two `after_merge` calls on the *same* host can
545/// hit landing within the same window (a human `magi run` alongside the
546/// daemon, or two review loops): both would otherwise read "nothing
547/// pending", judge independently, and open two competing pull requests, with
548/// whichever `write_marker` runs last silently erasing the other's record.
549struct MarkerLock {
550    path: PathBuf,
551}
552
553impl MarkerLock {
554    /// Try to take the lock for `marker`, stealing a stale one first if it is
555    /// old enough to mean its owner is gone rather than merely slow.
556    /// `Ok(None)` means someone else genuinely holds it right now.
557    fn acquire(marker: &Path) -> Result<Option<Self>> {
558        let path = marker.with_extension("lock");
559        if let Some(parent) = path.parent() {
560            std::fs::create_dir_all(parent)
561                .with_context(|| format!("create {}", parent.display()))?;
562        }
563        if Self::try_create(&path)? {
564            return Ok(Some(Self { path }));
565        }
566        if Self::is_stale(&path) {
567            let _ = std::fs::remove_file(&path);
568            if Self::try_create(&path)? {
569                return Ok(Some(Self { path }));
570            }
571        }
572        Ok(None)
573    }
574
575    fn try_create(path: &Path) -> Result<bool> {
576        match std::fs::OpenOptions::new()
577            .write(true)
578            .create_new(true)
579            .open(path)
580        {
581            Ok(_) => Ok(true),
582            Err(e) if e.kind() == std::io::ErrorKind::AlreadyExists => Ok(false),
583            Err(e) => Err(e).with_context(|| format!("create {}", path.display())),
584        }
585    }
586
587    fn is_stale(path: &Path) -> bool {
588        std::fs::metadata(path)
589            .and_then(|m| m.modified())
590            .ok()
591            .and_then(|m| m.elapsed().ok())
592            .is_some_and(|age| age >= LOCK_STALE_AFTER)
593    }
594}
595
596impl Drop for MarkerLock {
597    fn drop(&mut self) {
598        let _ = std::fs::remove_file(&self.path);
599    }
600}
601
602/// How often a blocked caller checks whether [`MarkerLock`] has freed up.
603const LOCK_POLL: Duration = Duration::from_secs(5);
604
605/// How long a caller waits for a contended lock before giving up on this
606/// merge's own judgement entirely.
607///
608/// A first version of this gate gave up the instant the lock was taken,
609/// which meant a change landing while another host's decision call was
610/// still running was never judged at all - not even recorded as pending,
611/// not escalated later, just dropped. The lock is only ever held for one
612/// `after_merge` call, so waiting past it is what lets that call's own
613/// decision reach [`pending_action`] against a marker the other side just
614/// finished writing, instead of finding nothing to check against. Set just
615/// under [`LOCK_STALE_AFTER`]: a lock still held this long after that point
616/// is reclaimed as abandoned rather than waited on further.
617const LOCK_WAIT_CEILING: Duration = Duration::from_secs(25 * 60);
618
619/// Wait for [`MarkerLock`] to free up, polling rather than blocking forever.
620/// `Ok(None)` means the ceiling passed with the lock still held.
621async fn wait_for_marker_lock(marker: &Path) -> Result<Option<MarkerLock>> {
622    wait_for_marker_lock_with(marker, LOCK_POLL, LOCK_WAIT_CEILING).await
623}
624
625/// [`wait_for_marker_lock`] with the poll interval and ceiling as parameters,
626/// so the retry behaviour is testable without a test actually waiting out
627/// [`LOCK_WAIT_CEILING`].
628async fn wait_for_marker_lock_with(
629    marker: &Path,
630    poll: Duration,
631    ceiling: Duration,
632) -> Result<Option<MarkerLock>> {
633    let mut waited = Duration::ZERO;
634    loop {
635        if let Some(lock) = MarkerLock::acquire(marker)? {
636            return Ok(Some(lock));
637        }
638        if waited >= ceiling {
639            return Ok(None);
640        }
641        tokio::time::sleep(poll).await;
642        waited += poll;
643    }
644}
645
646/// Which digit differs between `from` and `to`? `None` when they are equal.
647///
648/// Used to recover the level a pull request found by [`find_open_release_pr`]
649/// was judged at: the forge has the resulting version (in the branch name and
650/// the title) but not the digit an agent chose to get there, and this is the
651/// one other host-independent fact every host can compute the same way from
652/// it.
653fn level_between(from: Version, to: Version) -> Option<BumpLevel> {
654    if to.major != from.major {
655        Some(BumpLevel::Major)
656    } else if to.minor != from.minor {
657        Some(BumpLevel::Minor)
658    } else if to.patch != from.patch {
659        Some(BumpLevel::Patch)
660    } else {
661        None
662    }
663}
664
665/// Parse `gh pr list --state open --json url,headRefName` output, returning
666/// the first pull request whose branch is one of this module's own. No I/O.
667fn parse_open_release_pr(json: &str) -> Result<Option<(String, String)>> {
668    #[derive(Deserialize)]
669    struct Pr {
670        url: String,
671        #[serde(rename = "headRefName")]
672        head_ref_name: String,
673    }
674    let list: Vec<Pr> =
675        serde_json::from_str(json).context("parse `gh pr list --json url,headRefName` output")?;
676    Ok(list
677        .into_iter()
678        .find(|p| p.head_ref_name.starts_with("chore/release-v"))
679        .map(|p| (p.head_ref_name, p.url)))
680}
681
682/// Ask the forge directly whether a release bump is already open, for a host
683/// that has never seen it.
684///
685/// [`MarkerLock`] and the marker file only ever coordinate *this* host - a
686/// marker written on one machine is not visible to `run::home()` on another,
687/// so two hosts landing runs against the same repository at the same time
688/// can each read "nothing pending" and open a competing pull request no
689/// local lock can see. `gh pr list` is the one place every host actually
690/// shares a view, so it is consulted whenever this host's own marker says
691/// there is nothing pending, before a fresh decision is allowed to open a
692/// second pull request. This narrows the race to the gap between this call
693/// and whichever host's `gh pr create` lands first - it does not close it -
694/// because turning that into a real distributed lock would need coordination
695/// this crate has no dependency for.
696async fn find_open_release_pr(repo: &Path) -> Result<Option<(String, String)>> {
697    let out = tokio::process::Command::new("gh")
698        .args(["pr", "list", "--state", "open", "--json", "url,headRefName"])
699        .current_dir(repo)
700        .quiet()
701        .stdin(std::process::Stdio::null())
702        .output()
703        .await
704        .context("spawn gh pr list")?;
705    if !out.status.success() {
706        bail!(
707            "gh pr list: {}",
708            String::from_utf8_lossy(&out.stderr).trim()
709        );
710    }
711    parse_open_release_pr(&String::from_utf8_lossy(&out.stdout))
712}
713
714/// After a merge lands, ask an agent how big the change was and open a
715/// release bump sized to it.
716///
717/// Best-effort by construction, the same way `clean::fold_due` treats one
718/// run's fold failure: this runs after the merge the run exists to produce
719/// has already succeeded, so a failure here (the decision call, `gh`,
720/// `cargo`) must never turn a landed run into a failed one. The caller logs
721/// whatever this returns and moves on.
722pub async fn after_merge(state: &mut RunState, pr_url: &str) -> Result<()> {
723    after_merge_at(state, pr_url, None).await
724}
725
726/// Does the base branch carry a `Cargo.toml` at its root? Release bumps read
727/// and rewrite that file, so its absence means "not a Rust repository", which
728/// is not a fault. `ls-tree` rather than `cat-file -e`, so an unresolvable
729/// ref (a failed fetch, a misconfigured base) stays an error instead of being
730/// reported as a non-Rust repository.
731async fn base_has_cargo_toml(repo: &Path, remote: &str, base: &str) -> Result<bool> {
732    let out = git::git(
733        repo,
734        &[
735            "ls-tree",
736            "--name-only",
737            &format!("{remote}/{base}"),
738            "--",
739            "Cargo.toml",
740        ],
741    )
742    .await
743    .context("look for Cargo.toml on the base branch")?;
744    Ok(!out.trim().is_empty())
745}
746
747/// [`after_merge`] with an optional magi home, so tests can point the
748/// marker and its lock at a scratch directory.
749async fn after_merge_at(state: &mut RunState, pr_url: &str, home: Option<&Path>) -> Result<()> {
750    if !state.config.merge.release_bump {
751        return Ok(());
752    }
753    let Some(winner) = state.winner().cloned() else {
754        return Ok(());
755    };
756    let repo = state.repo.clone();
757    let base = state.base_branch.clone();
758    let remote = state.config.merge.remote.clone();
759
760    let files = git::changed_files(&winner.worktree, &base, &winner.branch)
761        .await
762        .unwrap_or_default();
763    if is_release_only(&files) {
764        state.event(
765            "bump",
766            "the merged change touches only the release manifest; not treating it as a trigger",
767        );
768        return Ok(());
769    }
770
771    // Outside the lock, and before anything that assumes a Rust manifest.
772    // Fetch first so a stale remote-tracking ref cannot misjudge the base.
773    git::fetch(&repo, &remote, &base).await.ok();
774    if !base_has_cargo_toml(&repo, &remote, &base).await? {
775        state.event(
776            "bump",
777            "release bump: no Cargo.toml on the base branch; release bumps are Rust-only, skipping",
778        );
779        return Ok(());
780    }
781
782    let marker = marker_path(&home.map_or_else(run::home, Path::to_path_buf), &repo);
783    // Held for the rest of this function: the whole read-decide-write
784    // sequence below is the critical section two `after_merge` calls landing
785    // within the same window must not both be inside at once. See
786    // `MarkerLock`'s own doc for why a second, unrelated bump PR is what
787    // that race produces without it, and `wait_for_marker_lock`'s for why
788    // this waits rather than giving up the instant it is contended.
789    let Some(_lock) = wait_for_marker_lock(&marker).await? else {
790        state.event(
791            "bump",
792            "another release bump decision held the lock past the wait ceiling; skipping this round",
793        );
794        return Ok(());
795    };
796
797    git::fetch(&repo, &remote, &base).await.ok();
798    let cargo_toml = git::git(&repo, &["show", &format!("{remote}/{base}:Cargo.toml")])
799        .await
800        .context("read Cargo.toml from the base branch")?;
801    let base_version = current_version(&cargo_toml)?;
802
803    let mut pending = read_marker(&marker);
804    if let Some(p) = &pending {
805        match coalesce(Some(p), &base_version)? {
806            Coalesce::Proceed => {
807                // Landed, or superseded by a manual bump: free for a fresh
808                // decision.
809                clear_marker(&marker);
810                pending = None;
811            }
812            Coalesce::Skip { target_version } => {
813                if !pr_is_open(&repo, &p.pr_url).await.unwrap_or(true) {
814                    state.event(
815                        "bump",
816                        format!(
817                            "the pending release bump to v{target_version} ({}) is no longer \
818                             open; treating it as abandoned",
819                            p.pr_url
820                        ),
821                    );
822                    clear_marker(&marker);
823                    pending = None;
824                }
825                // Otherwise still genuinely open: fall through and ask the
826                // same question this merge would get on a fresh path, so a
827                // more severe change landing while it waits can escalate it
828                // instead of being silently absorbed at the wrong digit.
829            }
830        }
831    }
832
833    if pending.is_none() {
834        // This host's own marker has nothing to say - check the forge itself
835        // before trusting that to mean a fresh pull request is safe to open.
836        // See `find_open_release_pr`'s own doc for what this does and does
837        // not close.
838        if let Ok(Some((branch, url))) = find_open_release_pr(&repo).await
839            && let Some(target) = branch
840                .strip_prefix("chore/release-v")
841                .and_then(|v| Version::parse(v).ok())
842        {
843            let base_parsed = Version::parse(&base_version)?;
844            if target > base_parsed
845                && let Some(level) = level_between(base_parsed, target)
846            {
847                let adopted = PendingBump {
848                    target_version: target.to_string(),
849                    level,
850                    branch,
851                    pr_url: url,
852                };
853                // Best-effort: worst case this host asks the forge again
854                // next time instead of finding its own record of it.
855                let _ = write_marker(&marker, &adopted);
856                pending = Some(adopted);
857            }
858        }
859    }
860
861    let title = pr_title(&repo, pr_url).await.unwrap_or_default();
862    let subject = land::merge_subject(&title, &state.instruction);
863    let stat = git::diff_stat(&winner.worktree, &base, &winner.branch)
864        .await
865        .unwrap_or_default();
866    let prompt = decision_prompt(&subject, &state.instruction, &stat, &files, &base_version);
867
868    // No dedicated role for this one-off decision. Borrows `[roles] chatter`
869    // - the nearest surviving single-agent-seat preference - rather than
870    // falling straight to `agent::pick`'s own default order, so an operator
871    // who has already named a preferred seat there is not silently
872    // overridden for this decision too.
873    let spec: AgentSpec = agent::pick(
874        &state.config.agents,
875        state.config.roles.chatter.as_deref(),
876        &agent::installed,
877    )
878    .context("choose an agent for the release-bump decision")?;
879    let mut seat = SeatState::new("bump", &spec.id, state.seed);
880    let artifacts = agent::artifacts_dir(&state.dir());
881    let out = agent::invoke(
882        &spec,
883        &mut seat,
884        &Invocation {
885            cwd: &repo,
886            prompt: &prompt,
887            timeout: DECISION_TIMEOUT,
888            // The decision reads a diffstat and writes a verdict; it must
889            // never touch a file.
890            allow_write: false,
891            sessions: false,
892            artifacts: &artifacts,
893            stem: "bump-decision",
894            run: &state.id,
895            node: "bump",
896            cache_dir: state.config.cache_dir().as_deref(),
897            attachments: &[],
898        },
899    )
900    .await
901    .context("ask an agent how big the merged change was")?;
902    if !out.usable() {
903        bail!(
904            "the release-bump decision produced nothing usable (exit {:?}, timed out: {})",
905            out.exit_code,
906            out.timed_out
907        );
908    }
909    let decision = parse_decision(&out.text).context("parse the release-bump decision")?;
910
911    if let Some(p) = pending {
912        return match pending_action(p.level, decision.level) {
913            PendingAction::AlreadyCovered => {
914                state.event(
915                    "bump",
916                    format!(
917                        "a release bump to v{} ({}) already covers at least a {} change; not \
918                         opening another",
919                        p.target_version,
920                        p.pr_url,
921                        decision.level.as_str()
922                    ),
923                );
924                Ok(())
925            }
926            PendingAction::Escalate => {
927                escalate_pending(state, &repo, &remote, &p, &decision, &base_version, &marker).await
928            }
929        };
930    }
931
932    let next = Version::parse(&base_version)?
933        .bump(decision.level)
934        .to_string();
935    let branch = format!("chore/release-v{next}");
936    let worktree = state.dir().join("bump");
937    git::worktree_remove(&repo, &worktree).await.ok();
938    git::worktree_add_branch(&repo, &worktree, &branch, &format!("{remote}/{base}"))
939        .await
940        .context("create the release-bump worktree")?;
941    let opened = open_bump_pr(state, &worktree, &branch, &next, &decision, pr_url).await;
942    // Throwaway either way: nothing downstream reads this worktree, and a
943    // release worktree left behind after a failed attempt would collide with
944    // the next one this same run tries.
945    git::worktree_remove(&repo, &worktree).await.ok();
946    let (pr_url_opened, automerge_warning) = opened?;
947
948    // The pull request exists on the forge the moment `open_bump_pr` returns
949    // its URL, regardless of what happens next - so the event that names it
950    // is unconditional, and a marker write failing (a full disk, a missing
951    // `home/bump` directory) is reported as its own warning rather than
952    // swallowing that URL entirely the way propagating it with `?` would.
953    // `find_open_release_pr` is the fallback if this leaves no local record:
954    // the next merge that finds no marker still finds this pull request on
955    // the forge before opening a second one.
956    let marker_write = write_marker(
957        &marker,
958        &PendingBump {
959            target_version: next.clone(),
960            level: decision.level,
961            branch,
962            pr_url: pr_url_opened.clone(),
963        },
964    );
965    state.event(
966        "bump",
967        format!(
968            "opened a {} release bump to v{next} ({}): {pr_url_opened}",
969            decision.level.as_str(),
970            decision.reason
971        ),
972    );
973    if let Err(e) = marker_write {
974        state.event(
975            "bump",
976            format!(
977                "could not record the pending release bump marker for v{next}: {e:#}; a later \
978                 merge may open a duplicate pull request if it cannot find {pr_url_opened} on \
979                 the forge either"
980            ),
981        );
982    }
983    state.release_bump = Some(run::ReleaseBump {
984        pr_url: Some(pr_url_opened.clone()),
985        version: Some(next.clone()),
986        automerge_enabled: automerge_warning.is_none(),
987        ..run::ReleaseBump::default()
988    });
989    if let Some(warning) = automerge_warning {
990        state.event(
991            "bump",
992            format!("could not enable automerge on {pr_url_opened}: {warning}; merge it by hand"),
993        );
994        report_problem(state, Some(&pr_url_opened), Some(&next), &warning).await;
995    }
996    Ok(())
997}
998
999/// The node name a post-merge notice is filed under. [`ask::Questions::settle_run`]
1000/// exempts it: the run it belongs to is `Merged` by definition, and abandoning
1001/// the notice on that ground would erase it the moment it is filed.
1002pub const NOTICE_NODE: &str = "release-bump";
1003/// Answer: the owner dealt with the release pull request themselves.
1004const NOTICE_DONE: &str = "merged by hand";
1005/// Answer: seen, nothing to do.
1006const NOTICE_DISMISS: &str = "dismiss";
1007
1008/// What to tell the operator to do about a refused `gh pr merge --auto`.
1009///
1010/// Keys on the wording GitHub is known to use when the base branch has no
1011/// required status checks (`enablePullRequestAutoMerge` / "protected branch
1012/// rules"); anything else falls back to the generic advice, with the reason
1013/// carried verbatim next to it.
1014fn automerge_hint(reason: &str) -> &'static str {
1015    let r = reason.to_lowercase();
1016    if r.contains("enablepullrequestautomerge") || r.contains("protected branch rules") {
1017        "merge the release pull request by hand, and enable branch protection with required \
1018         status checks on the base branch so automerge can work next time"
1019    } else {
1020        "merge the release pull request by hand"
1021    }
1022}
1023
1024/// The comment left on the release pull request itself.
1025fn automerge_failure_comment(reason: &str) -> String {
1026    format!(
1027        "magi could not enable automerge on this pull request: {reason}\n\n\
1028         Action required: {}. Until then the release does not happen.",
1029        automerge_hint(reason)
1030    )
1031}
1032
1033/// Record a post-merge problem on the run and file the operator-facing
1034/// notice, without touching the forge. Returns the comment body meant for the
1035/// release pull request when there is one.
1036///
1037/// Split from [`report_problem`] so the state, the question and the wording
1038/// can be asserted without a `gh`.
1039fn surface_problem(
1040    state: &mut RunState,
1041    store: &ask::Questions,
1042    pr_url: Option<&str>,
1043    version: Option<&str>,
1044    reason: &str,
1045) -> Result<(ask::Question, Option<String>)> {
1046    let action = if pr_url.is_some() {
1047        automerge_hint(reason).to_owned()
1048    } else {
1049        "the release bump did not run; open the release pull request by hand".to_owned()
1050    };
1051    let record = state.release_bump.get_or_insert_with(Default::default);
1052    record.pr_url = pr_url.map(str::to_owned).or(record.pr_url.take());
1053    record.version = version.map(str::to_owned).or(record.version.take());
1054    record.automerge_enabled = false;
1055    record.problem = Some(reason.to_owned());
1056    record.action_required = Some(action.clone());
1057
1058    let summary = match pr_url {
1059        Some(url) => format!("Release PR needs a human: {url}"),
1060        None => "Release bump did not run".to_owned(),
1061    };
1062    let detail = format!(
1063        "Run {} merged, but the release step after it failed.\n\n{reason}\n\n\
1064         Action required: {action}.",
1065        state.id
1066    );
1067    let mut q = ask::Question::new(
1068        state.id.clone(),
1069        NOTICE_NODE.to_owned(),
1070        "bump".to_owned(),
1071        summary,
1072        detail,
1073        vec![NOTICE_DONE.to_owned(), NOTICE_DISMISS.to_owned()],
1074    );
1075    store.put(&mut q).context("file the release-bump notice")?;
1076    state.event(
1077        "bump",
1078        format!("needs attention: notice {} filed - {action}", q.short()),
1079    );
1080    let comment = pr_url.map(|_| automerge_failure_comment(reason));
1081    Ok((q, comment))
1082}
1083
1084/// Make a post-merge problem visible: record it, comment on the release pull
1085/// request, and raise a notice through the question queue and the configured
1086/// notifier. Every step is best-effort - a failed comment or webhook is an
1087/// event, never a reason to lose the record or the run.
1088pub async fn report_problem(
1089    state: &mut RunState,
1090    pr_url: Option<&str>,
1091    version: Option<&str>,
1092    reason: &str,
1093) {
1094    match surface_problem(state, &ask::Questions::open(), pr_url, version, reason) {
1095        Ok((q, comment)) => {
1096            if let (Some(url), Some(body)) = (pr_url, comment)
1097                && let Err(e) = gh_pr_comment(
1098                    &state.repo,
1099                    url,
1100                    &crate::scrub::scrub(&body, &crate::scrub::Identity::current()),
1101                )
1102                .await
1103            {
1104                state.event("bump", format!("could not comment on {url}: {e:#}"));
1105            }
1106            if let Err(e) = ask::notify(&state.config.notify, &q).await {
1107                tracing::warn!(
1108                    "could not notify about release-bump notice {}: {e:#}",
1109                    q.short()
1110                );
1111            }
1112        }
1113        Err(e) => state.event("bump", format!("could not raise a notice: {e:#}")),
1114    }
1115}
1116
1117async fn gh_pr_comment(cwd: &Path, pr_url: &str, body: &str) -> Result<()> {
1118    let out = tokio::process::Command::new("gh")
1119        .args(["pr", "comment", pr_url, "--body", body])
1120        .current_dir(cwd)
1121        .quiet()
1122        .stdin(std::process::Stdio::null())
1123        .output()
1124        .await
1125        .context("spawn gh pr comment")?;
1126    if out.status.success() {
1127        Ok(())
1128    } else {
1129        bail!(
1130            "gh pr comment: {}",
1131            String::from_utf8_lossy(&out.stderr).trim()
1132        )
1133    }
1134}
1135
1136/// Bump an already-open release pull request further, because a change more
1137/// severe than what it already covers landed while it waited on CI or
1138/// automerge - see [`pending_action`].
1139///
1140/// Adds a second commit rather than rewriting the first: `gh pr merge
1141/// --squash` prefers a single commit's own message over the pull request's
1142/// title, and falls back to the title once there is more than one commit -
1143/// so the title is what is kept honest here, via `gh pr edit`.
1144async fn escalate_pending(
1145    state: &mut RunState,
1146    repo: &Path,
1147    remote: &str,
1148    pending: &PendingBump,
1149    decision: &BumpDecision,
1150    base_version: &str,
1151    marker: &Path,
1152) -> Result<()> {
1153    let next = Version::parse(base_version)?
1154        .bump(decision.level)
1155        .to_string();
1156    let worktree = state.dir().join("bump");
1157    git::worktree_remove(repo, &worktree).await.ok();
1158    let checked_out = git::git_raw(
1159        repo,
1160        &[
1161            "worktree",
1162            "add",
1163            "--force",
1164            &worktree.to_string_lossy(),
1165            &pending.branch,
1166        ],
1167    )
1168    .await?;
1169    if !checked_out.ok() {
1170        bail!(
1171            "checking out the pending release branch {} failed: {}",
1172            pending.branch,
1173            checked_out.stderr
1174        );
1175    }
1176
1177    // Only the substantive change - the commit landing on the remote branch
1178    // - has to succeed for the escalation to have happened at all. Anything
1179    // after the push is a follow-up, not a precondition: the branch already
1180    // carries the new version whether or not it succeeds.
1181    let pushed: Result<()> = async {
1182        let cargo_toml_path = worktree.join("Cargo.toml");
1183        let toml = tokio::fs::read_to_string(&cargo_toml_path)
1184            .await
1185            .with_context(|| format!("read {}", cargo_toml_path.display()))?;
1186        let rewritten = rewrite_cargo_version(&toml, &next)?;
1187        tokio::fs::write(&cargo_toml_path, rewritten)
1188            .await
1189            .with_context(|| format!("write {}", cargo_toml_path.display()))?;
1190        sync_lockfile(&worktree, state.config.cache_dir().as_deref()).await?;
1191        let committed = git::commit_all(
1192            &worktree,
1193            &format!(
1194                "chore: release v{next} (supersedes v{})",
1195                pending.target_version
1196            ),
1197        )
1198        .await
1199        .context("commit the escalated version bump")?;
1200        if !committed {
1201            bail!("escalating the version bump left nothing to commit");
1202        }
1203        let pushed = git::push(&worktree, remote, &pending.branch).await?;
1204        if !pushed.ok() {
1205            bail!("pushing {} failed: {}", pending.branch, pushed.stderr);
1206        }
1207        Ok(())
1208    }
1209    .await;
1210    if let Err(e) = pushed {
1211        git::worktree_remove(repo, &worktree).await.ok();
1212        return Err(e);
1213    }
1214
1215    // The commit is on the remote branch now regardless of what happens
1216    // below - the title edit is cosmetic, and the marker and the event must
1217    // both reflect the real, already-pushed state even if it fails.
1218    let title_warning = match gh_pr_edit_title(
1219        &worktree,
1220        &pending.pr_url,
1221        &crate::scrub::scrub(
1222            &format!("chore: release v{next} ({} bump)", decision.level.as_str()),
1223            &crate::scrub::Identity::current(),
1224        ),
1225    )
1226    .await
1227    {
1228        Ok(()) => None,
1229        Err(e) => Some(e.to_string()),
1230    };
1231    git::worktree_remove(repo, &worktree).await.ok();
1232
1233    let marker_write = write_marker(
1234        marker,
1235        &PendingBump {
1236            target_version: next.clone(),
1237            level: decision.level,
1238            branch: pending.branch.clone(),
1239            pr_url: pending.pr_url.clone(),
1240        },
1241    );
1242    state.event(
1243        "bump",
1244        format!(
1245            "escalated the pending release bump from v{} to v{next} to a {} change ({}): {}",
1246            pending.target_version,
1247            decision.level.as_str(),
1248            decision.reason,
1249            pending.pr_url
1250        ),
1251    );
1252    if let Err(e) = marker_write {
1253        state.event(
1254            "bump",
1255            format!(
1256                "could not update the pending release bump marker to v{next}: {e:#}; a later \
1257                 merge may misjudge whether it is already covered"
1258            ),
1259        );
1260    }
1261    if let Some(warning) = title_warning {
1262        state.event(
1263            "bump",
1264            format!(
1265                "pushed v{next} to {} but could not update its title: {warning}; the squashed \
1266                 subject may still read the superseded version",
1267                pending.pr_url
1268            ),
1269        );
1270    }
1271    Ok(())
1272}
1273
1274/// Edit the version, let the lockfile follow, commit, push, and open the pull
1275/// request with automerge enabled. Returns the opened pull request's URL and,
1276/// when enabling automerge itself failed, a note of why - the pull request
1277/// still exists on the forge either way, and the caller must not lose track
1278/// of its URL over that failure alone.
1279async fn open_bump_pr(
1280    state: &RunState,
1281    worktree: &Path,
1282    branch: &str,
1283    next_version: &str,
1284    decision: &BumpDecision,
1285    source_pr_url: &str,
1286) -> Result<(String, Option<String>)> {
1287    let cargo_toml_path = worktree.join("Cargo.toml");
1288    let toml = tokio::fs::read_to_string(&cargo_toml_path)
1289        .await
1290        .with_context(|| format!("read {}", cargo_toml_path.display()))?;
1291    let rewritten = rewrite_cargo_version(&toml, next_version)?;
1292    tokio::fs::write(&cargo_toml_path, rewritten)
1293        .await
1294        .with_context(|| format!("write {}", cargo_toml_path.display()))?;
1295
1296    sync_lockfile(worktree, state.config.cache_dir().as_deref()).await?;
1297
1298    let committed = git::commit_all(worktree, &format!("chore: release v{next_version}"))
1299        .await
1300        .context("commit the version bump")?;
1301    if !committed {
1302        bail!("the version bump left nothing to commit");
1303    }
1304
1305    let remote = state.config.merge.remote.clone();
1306    let pushed = git::push(worktree, &remote, branch).await?;
1307    if !pushed.ok() {
1308        bail!("pushing {branch} failed: {}", pushed.stderr);
1309    }
1310
1311    let (title, body) = release_pr(
1312        decision.level.as_str(),
1313        &decision.reason,
1314        next_version,
1315        &state.id,
1316        source_pr_url,
1317    );
1318    let who = crate::scrub::Identity::current();
1319    let (title, body) = (
1320        crate::scrub::scrub(&title, &who),
1321        crate::scrub::scrub(&body, &who),
1322    );
1323    let url = gh_pr_create(worktree, &state.base_branch, branch, &title, &body).await?;
1324    let automerge_warning = match gh_enable_automerge(worktree, &url).await {
1325        Ok(()) => None,
1326        Err(e) => Some(e.to_string()),
1327    };
1328    Ok((url, automerge_warning))
1329}
1330
1331/// Run `cargo build` so `Cargo.lock` follows the version bump, the same step
1332/// `AGENTS.md`'s hand-driven release recipe calls for.
1333///
1334/// Not exercised by a test: it is the one step in this module that runs the
1335/// real `cargo`, which the constraints on this change rule out doing from a
1336/// test (no network, no writing outside a throwaway worktree the test itself
1337/// does not have).
1338async fn sync_lockfile(worktree: &Path, cache_dir: Option<&Path>) -> Result<()> {
1339    let mut cmd = tokio::process::Command::new("cargo");
1340    cmd.arg("build").current_dir(worktree).quiet();
1341    if let Some(dir) = cache_dir {
1342        cmd.env("CARGO_TARGET_DIR", dir);
1343    }
1344    let out = cmd
1345        .stdin(std::process::Stdio::null())
1346        .output()
1347        .await
1348        .context("spawn cargo build")?;
1349    if !out.status.success() {
1350        bail!(
1351            "cargo build failed while syncing Cargo.lock: {}",
1352            String::from_utf8_lossy(&out.stderr).trim()
1353        );
1354    }
1355    Ok(())
1356}
1357
1358/// Title and body of a release bump pull request. Fixed English whatever
1359/// `[graph] language` says: it lands on GitHub. Pure so a test can hold it to
1360/// that. (`reason` comes from the decision seat, which the prompt tells to
1361/// write English.)
1362fn release_pr(
1363    level: &str,
1364    reason: &str,
1365    next_version: &str,
1366    run_id: &str,
1367    source_pr_url: &str,
1368) -> (String, String) {
1369    let title = format!("chore: release v{next_version} ({level} bump)");
1370    let body = format!(
1371        "## Background\n\n\
1372         A change that was just merged is a `{level}` change, so the crate needs a new \
1373         release: {reason}\n\n\
1374         Triggered by magi run `{run_id}`, which landed {source}.\n\n\
1375         ## Change\n\n\
1376         Raises the package version to `v{next_version}` in `Cargo.toml`, with \
1377         `Cargo.lock` following it. Nothing else changes.\n\n\
1378         ## Risk\n\n\
1379         Version-bump-only, so there is nothing here for a reviewer to find. Merging \
1380         it starts the release pipeline (auto-tag, then the release workflow).",
1381        source = source_pr_url,
1382    );
1383    (title, body)
1384}
1385
1386/// The merged pull request's title, for [`land::merge_subject`].
1387async fn pr_title(repo: &Path, pr_url: &str) -> Result<String> {
1388    let out = tokio::process::Command::new("gh")
1389        .args(["pr", "view", pr_url, "--json", "title"])
1390        .current_dir(repo)
1391        .quiet()
1392        .stdin(std::process::Stdio::null())
1393        .output()
1394        .await
1395        .context("spawn gh pr view")?;
1396    if !out.status.success() {
1397        bail!(
1398            "gh pr view {pr_url}: {}",
1399            String::from_utf8_lossy(&out.stderr).trim()
1400        );
1401    }
1402    #[derive(Deserialize)]
1403    struct Title {
1404        title: String,
1405    }
1406    let parsed: Title = serde_json::from_str(&String::from_utf8_lossy(&out.stdout))
1407        .context("parse `gh pr view --json title` output")?;
1408    Ok(parsed.title)
1409}
1410
1411async fn gh_pr_create(
1412    cwd: &Path,
1413    base: &str,
1414    head: &str,
1415    title: &str,
1416    body: &str,
1417) -> Result<String> {
1418    let out = tokio::process::Command::new("gh")
1419        .args([
1420            "pr", "create", "--base", base, "--head", head, "--title", title, "--body", body,
1421        ])
1422        .current_dir(cwd)
1423        .quiet()
1424        .stdin(std::process::Stdio::null())
1425        .output()
1426        .await
1427        .context("spawn gh pr create")?;
1428    if out.status.success() {
1429        Ok(String::from_utf8_lossy(&out.stdout).trim().to_owned())
1430    } else {
1431        bail!(
1432            "gh pr create: {}",
1433            String::from_utf8_lossy(&out.stderr).trim()
1434        )
1435    }
1436}
1437
1438/// Enable automerge, mirroring `AGENTS.md`'s `gh pr merge --auto --squash
1439/// --delete-branch`. Never `git tag`: `auto-tag.yml` mints the tag once this
1440/// merges, and a manual tag would collide with its push.
1441async fn gh_enable_automerge(cwd: &Path, pr_url: &str) -> Result<()> {
1442    let out = tokio::process::Command::new("gh")
1443        .args([
1444            "pr",
1445            "merge",
1446            pr_url,
1447            "--auto",
1448            "--squash",
1449            "--delete-branch",
1450        ])
1451        .current_dir(cwd)
1452        .quiet()
1453        .stdin(std::process::Stdio::null())
1454        .output()
1455        .await
1456        .context("spawn gh pr merge --auto")?;
1457    if out.status.success() {
1458        Ok(())
1459    } else {
1460        bail!(
1461            "gh pr merge --auto: {}",
1462            String::from_utf8_lossy(&out.stderr).trim()
1463        )
1464    }
1465}
1466
1467/// Rewrite a pull request's title, used when [`escalate_pending`] adds a
1468/// second commit: `gh pr merge --squash` only prefers a single commit's own
1469/// message over the title, so once there are two the title is what lands.
1470async fn gh_pr_edit_title(cwd: &Path, pr_url: &str, title: &str) -> Result<()> {
1471    let out = tokio::process::Command::new("gh")
1472        .args(["pr", "edit", pr_url, "--title", title])
1473        .current_dir(cwd)
1474        .quiet()
1475        .stdin(std::process::Stdio::null())
1476        .output()
1477        .await
1478        .context("spawn gh pr edit")?;
1479    if out.status.success() {
1480        Ok(())
1481    } else {
1482        bail!(
1483            "gh pr edit --title: {}",
1484            String::from_utf8_lossy(&out.stderr).trim()
1485        )
1486    }
1487}
1488
1489#[cfg(test)]
1490mod tests {
1491    use super::*;
1492
1493    #[test]
1494    fn github_facing_bump_text_is_english() {
1495        let (title, body) =
1496            release_pr("minor", "adds a flag", "0.37.0", "ab12", "https://x/pull/1");
1497        assert!(title.is_ascii() && body.is_ascii(), "{title}\n{body}");
1498        assert_eq!(title, "chore: release v0.37.0 (minor bump)");
1499        assert!(
1500            body.contains("## Background") && body.contains("## Change"),
1501            "{body}"
1502        );
1503        let p = decision_prompt("s", "i", "d", &[], "0.36.5");
1504        assert!(p.contains(crate::prompt::GITHUB_ENGLISH_HEADING), "{p}");
1505    }
1506    use crate::config::Config;
1507    use crate::land::PrLifecycle;
1508
1509    /// `[merge] release_bump = false` must short-circuit before any I/O -
1510    /// `after_merge` is reached from a live run with a real repo and a real
1511    /// `gh`, so the disabled case is asserted with a `RunState` that would
1512    /// fail loudly (an unresolvable `/no/such/repo`) the moment anything past
1513    /// the flag check tried to touch it.
1514    #[tokio::test]
1515    async fn a_disabled_config_does_nothing() {
1516        let config = Config {
1517            merge: crate::config::Merge {
1518                release_bump: false,
1519                ..crate::config::Merge::default()
1520            },
1521            ..Config::default()
1522        };
1523        let mut state = RunState::new(
1524            PathBuf::from("/no/such/repo"),
1525            "main".to_owned(),
1526            "0000000000000000000000000000000000000000".to_owned(),
1527            "irrelevant".to_owned(),
1528            config,
1529        );
1530        after_merge(&mut state, "https://example.invalid/pull/1")
1531            .await
1532            .expect("a disabled config must return Ok without touching anything");
1533        assert!(
1534            state.events.is_empty(),
1535            "nothing should happen at all, not even a logged event"
1536        );
1537    }
1538
1539    /// A bare `origin` plus a clone of it, `main` pushed with `files`.
1540    async fn origin_with(files: &[(&str, &str)]) -> (tempfile::TempDir, PathBuf) {
1541        let dir = tempfile::tempdir().unwrap();
1542        let origin = dir.path().join("origin.git");
1543        let repo = dir.path().join("repo");
1544        let o = origin.to_string_lossy().into_owned();
1545        git::git(dir.path(), &["init", "--bare", "-b", "main", &o])
1546            .await
1547            .unwrap();
1548        tokio::fs::create_dir_all(&repo).await.unwrap();
1549        git::git(&repo, &["init", "-b", "main"]).await.unwrap();
1550        git::git(&repo, &["config", "user.name", "test"])
1551            .await
1552            .unwrap();
1553        git::git(&repo, &["config", "user.email", "test@example.com"])
1554            .await
1555            .unwrap();
1556        for (name, body) in files {
1557            tokio::fs::write(repo.join(name), body).await.unwrap();
1558        }
1559        git::git(&repo, &["add", "-A"]).await.unwrap();
1560        git::git(&repo, &["commit", "-m", "init"]).await.unwrap();
1561        git::git(&repo, &["remote", "add", "origin", &o])
1562            .await
1563            .unwrap();
1564        git::git(&repo, &["push", "origin", "main"]).await.unwrap();
1565        (dir, repo)
1566    }
1567
1568    #[tokio::test]
1569    async fn base_has_cargo_toml_tells_rust_from_non_rust() {
1570        let (_d, rust) = origin_with(&[("Cargo.toml", "[package]\nversion = \"0.1.0\"\n")]).await;
1571        assert!(base_has_cargo_toml(&rust, "origin", "main").await.unwrap());
1572        let (_d2, other) = origin_with(&[("README.md", "hi\n")]).await;
1573        assert!(!base_has_cargo_toml(&other, "origin", "main").await.unwrap());
1574        // An unresolvable ref is a fault, not "not Rust".
1575        assert!(base_has_cargo_toml(&other, "origin", "nope").await.is_err());
1576    }
1577
1578    #[tokio::test]
1579    async fn a_repo_without_cargo_toml_skips_with_one_event_and_no_lock() {
1580        let (_d, repo) = origin_with(&[("README.md", "hi\n")]).await;
1581        let home = tempfile::tempdir().unwrap();
1582        let mut state = RunState::new(
1583            repo.clone(),
1584            "main".to_owned(),
1585            "0000000000000000000000000000000000000000".to_owned(),
1586            "task".to_owned(),
1587            Config::default(),
1588        );
1589        state.candidates.push(crate::run::Candidate {
1590            index: 0,
1591            label: 'A',
1592            agent: "x".to_owned(),
1593            branch: "main".to_owned(),
1594            worktree: repo.clone(),
1595            summary: String::new(),
1596            stat: String::new(),
1597            files: 1,
1598            commits: 1,
1599            empty: false,
1600            failed: None,
1601            verified_noop: None,
1602            duration_ms: 0,
1603            folded: false,
1604        });
1605        state.tally = Some(
1606            serde_json::from_value(serde_json::json!({
1607                "first_choice": {}, "borda": {}, "winner": "A",
1608                "unanimous_initial": true, "deliberated": false,
1609                "changed_votes": 0, "unanimous_final": true,
1610            }))
1611            .unwrap(),
1612        );
1613        after_merge_at(
1614            &mut state,
1615            "https://example.invalid/pull/1",
1616            Some(home.path()),
1617        )
1618        .await
1619        .expect("a non-Rust repository is not an error");
1620        let bumps: Vec<_> = state.events.iter().filter(|e| e.node == "bump").collect();
1621        assert_eq!(bumps.len(), 1, "{:?}", state.events);
1622        assert_eq!(
1623            bumps[0].message,
1624            "release bump: no Cargo.toml on the base branch; release bumps are Rust-only, skipping"
1625        );
1626        assert!(
1627            std::fs::read_dir(home.path()).unwrap().next().is_none(),
1628            "no marker and no lock may be created"
1629        );
1630    }
1631
1632    const NO_RULES: &str = "gh pr merge --auto: GraphQL: Pull request Branch does not have \
1633                            required protected branch rules (enablePullRequestAutoMerge)";
1634
1635    fn merged_state() -> RunState {
1636        // `report::run` prints `state.dir()`; pin the global home like the
1637        // report tests do so nothing reaches the operator's real one.
1638        run::set_home(std::env::temp_dir().join("magi-report-test-home"));
1639        let mut s = RunState::new(
1640            PathBuf::from("/no/such/repo"),
1641            "main".to_owned(),
1642            "0000000000000000000000000000000000000000".to_owned(),
1643            "task".to_owned(),
1644            Config::default(),
1645        );
1646        s.status = RunStatus::Merged;
1647        s
1648    }
1649
1650    #[test]
1651    fn the_known_automerge_refusal_names_branch_protection() {
1652        assert!(automerge_hint(NO_RULES).contains("branch protection with required"));
1653        let other = automerge_hint("gh: network unreachable");
1654        assert!(!other.contains("branch protection"), "{other}");
1655        let body = automerge_failure_comment(NO_RULES);
1656        assert!(body.contains("enablePullRequestAutoMerge"), "{body}");
1657        assert!(body.contains("Action required"), "{body}");
1658    }
1659
1660    #[test]
1661    fn an_automerge_failure_is_recorded_shown_and_filed_and_survives_settling() {
1662        let dir = tempfile::tempdir().unwrap();
1663        let store = ask::Questions::at(dir.path().join("questions"));
1664        let mut state = merged_state();
1665        let url = "https://github.com/o/r/pull/35";
1666
1667        let (q, comment) =
1668            surface_problem(&mut state, &store, Some(url), Some("0.8.0"), NO_RULES).unwrap();
1669
1670        // The comment goes on the release PR and carries reason and fix.
1671        let comment = comment.expect("a PR was opened, so it gets a comment");
1672        assert!(comment.contains("branch protection"), "{comment}");
1673
1674        // The run is still Merged, but no longer reads as plain green.
1675        assert_eq!(state.status, RunStatus::Merged);
1676        assert!(state.needs_attention());
1677        let text = crate::report::run(&state);
1678        assert!(text.contains("release bump"), "{text}");
1679        assert!(text.contains("FAILED"), "{text}");
1680        assert!(text.contains(url), "{text}");
1681        assert!(text.contains("action required"), "{text}");
1682        assert!(crate::report::line(&state).contains("release needs a human"));
1683
1684        // A notice is open, and settling the merged run does not erase it.
1685        assert_eq!(q.node, NOTICE_NODE);
1686        assert_eq!(store.open_for(&state.id).len(), 1);
1687        assert_eq!(store.settle_run(&state.id, RunStatus::Merged).unwrap(), 0);
1688        assert!(store.get(&q.id).unwrap().status.open());
1689    }
1690
1691    #[test]
1692    fn a_bump_that_never_ran_is_surfaced_without_a_pr_comment() {
1693        let dir = tempfile::tempdir().unwrap();
1694        let store = ask::Questions::at(dir.path().join("questions"));
1695        let mut state = merged_state();
1696        let (_, comment) = surface_problem(&mut state, &store, None, None, "no agent").unwrap();
1697        assert!(comment.is_none());
1698        assert!(state.needs_attention());
1699    }
1700
1701    #[test]
1702    fn version_parses_and_bumps_each_digit() {
1703        let v = Version::parse("0.4.0").unwrap();
1704        assert_eq!(
1705            v,
1706            Version {
1707                major: 0,
1708                minor: 4,
1709                patch: 0
1710            }
1711        );
1712
1713        assert_eq!(v.bump(BumpLevel::Major).to_string(), "1.0.0");
1714        assert_eq!(v.bump(BumpLevel::Minor).to_string(), "0.5.0");
1715        assert_eq!(v.bump(BumpLevel::Patch).to_string(), "0.4.1");
1716    }
1717
1718    #[test]
1719    fn version_tolerates_a_prerelease_suffix_on_patch() {
1720        let v = Version::parse("1.2.3-rc1").unwrap();
1721        assert_eq!(
1722            v,
1723            Version {
1724                major: 1,
1725                minor: 2,
1726                patch: 3
1727            }
1728        );
1729    }
1730
1731    #[test]
1732    fn version_rejects_garbage() {
1733        assert!(Version::parse("not-a-version").is_err());
1734        assert!(Version::parse("1.2").is_err());
1735    }
1736
1737    #[test]
1738    fn decision_parses_each_level() {
1739        for (json, level) in [
1740            (
1741                r#"{"level":"major","reason":"drops a config key"}"#,
1742                BumpLevel::Major,
1743            ),
1744            (
1745                r#"{"level":"minor","reason":"adds a new flag"}"#,
1746                BumpLevel::Minor,
1747            ),
1748            (
1749                r#"{"level":"patch","reason":"fixes a race"}"#,
1750                BumpLevel::Patch,
1751            ),
1752        ] {
1753            let decision = parse_decision(json).unwrap();
1754            assert_eq!(decision.level, level);
1755            assert!(!decision.reason.is_empty());
1756        }
1757    }
1758
1759    #[test]
1760    fn decision_wrapped_in_a_fence_and_prose_still_parses() {
1761        let text = "Here is my call.\n\n```json\n{\"level\":\"minor\",\"reason\":\"new HTTP route\"}\n```\n\nDone.";
1762        let decision = parse_decision(text).unwrap();
1763        assert_eq!(decision.level, BumpLevel::Minor);
1764        assert_eq!(decision.reason, "new HTTP route");
1765    }
1766
1767    #[test]
1768    fn a_broken_reply_is_an_error_not_a_default() {
1769        assert!(parse_decision("I decline to answer.").is_err());
1770        assert!(parse_decision(r#"{"level":"huge","reason":"go big"}"#).is_err());
1771        assert!(
1772            parse_decision(r#"{"level":"patch","reason":""}"#).is_err(),
1773            "an empty reason must not pass either"
1774        );
1775        assert!(
1776            parse_decision(r#"{"level":"patch"}"#).is_err(),
1777            "a reply with no reason at all must not pass"
1778        );
1779    }
1780
1781    #[test]
1782    fn prompt_states_the_zero_x_rule_and_the_tie_break() {
1783        let prompt = decision_prompt(
1784            "feat: add a phone endpoint",
1785            "add POST /api/widgets",
1786            "1 file changed, 10 insertions(+)",
1787            &["src/web.rs".to_owned()],
1788            "0.8.0",
1789        );
1790        assert!(prompt.contains("0.8.0"), "the current version is stated");
1791        assert!(
1792            prompt.contains("below `1.0.0`")
1793                && prompt.contains("`minor` is the digit that carries a breaking change"),
1794            "the 0.x rule must be explicit: {prompt}"
1795        );
1796        assert!(
1797            prompt.contains("choose the larger"),
1798            "the tie-break toward the bigger digit must be explicit: {prompt}"
1799        );
1800    }
1801
1802    #[test]
1803    fn release_only_diffs_are_recognised() {
1804        assert!(is_release_only(&["Cargo.toml".to_owned()]));
1805        assert!(is_release_only(&[
1806            "Cargo.toml".to_owned(),
1807            "Cargo.lock".to_owned()
1808        ]));
1809        assert!(!is_release_only(&[]));
1810        assert!(!is_release_only(&[
1811            "Cargo.toml".to_owned(),
1812            "src/main.rs".to_owned()
1813        ]));
1814    }
1815
1816    #[test]
1817    fn cargo_version_rewrite_touches_only_the_package_table() {
1818        let toml = "\
1819[package]\n\
1820# a comment mentioning version on purpose\n\
1821name = \"magi-cli\"\n\
1822version = \"0.8.0\"\n\
1823edition = \"2024\"\n\
1824\n\
1825[dependencies]\n\
1826foo = { version = \"1.2.3\" }\n";
1827        let out = rewrite_cargo_version(toml, "0.9.0").unwrap();
1828        assert!(out.contains("version = \"0.9.0\""));
1829        assert!(
1830            out.contains("foo = { version = \"1.2.3\" }"),
1831            "a dependency's own version pin must survive: {out}"
1832        );
1833        assert!(
1834            out.contains("# a comment mentioning version on purpose"),
1835            "unrelated lines, comments included, must be byte-for-byte preserved: {out}"
1836        );
1837        assert_eq!(
1838            out.lines().count(),
1839            toml.lines().count(),
1840            "the rewrite replaces one line, it does not add or remove any"
1841        );
1842    }
1843
1844    #[test]
1845    fn cargo_version_rewrite_fails_without_a_package_table() {
1846        let toml = "[dependencies]\nfoo = \"1\"\n";
1847        assert!(rewrite_cargo_version(toml, "1.0.0").is_err());
1848    }
1849
1850    /// The shape `kanadehq/kanade` has: a workspace root with member crates
1851    /// but no crate of its own, so `[package]` never exists and the version
1852    /// lives under `[workspace.package]` alone. Before this fell back,
1853    /// `rewrite_cargo_version` bailed on every such repository and no bump
1854    /// pull request was ever opened for it.
1855    #[test]
1856    fn cargo_version_rewrite_falls_back_to_workspace_package_without_a_package_table() {
1857        let toml = "\
1858[workspace]\n\
1859members = [\"crates/a\", \"crates/b\"]\n\
1860\n\
1861[workspace.package]\n\
1862version = \"0.45.18\"\n\
1863edition = \"2024\"\n\
1864\n\
1865[workspace.dependencies]\n\
1866foo = { version = \"1.2.3\" }\n";
1867        let out = rewrite_cargo_version(toml, "0.45.19").unwrap();
1868        assert!(out.contains("version = \"0.45.19\""));
1869        assert!(
1870            out.contains("foo = { version = \"1.2.3\" }"),
1871            "a workspace dependency's own version pin must survive: {out}"
1872        );
1873        assert_eq!(
1874            out.lines().count(),
1875            toml.lines().count(),
1876            "the rewrite replaces one line, it does not add or remove any"
1877        );
1878    }
1879
1880    #[test]
1881    fn current_version_prefers_the_package_table_when_both_exist() {
1882        let toml = "[workspace.package]\nversion = \"9.9.9\"\n\n[package]\nversion = \"0.8.0\"\n";
1883        assert_eq!(current_version(toml).unwrap(), "0.8.0");
1884    }
1885
1886    /// Same shape as `kanadehq/kanade`'s root `Cargo.toml`: no `[package]`
1887    /// at all, only `[workspace]` and `[workspace.package]`.
1888    #[test]
1889    fn current_version_falls_back_to_workspace_package_without_a_package_table() {
1890        let toml = "\
1891[workspace]\n\
1892members = [\"crates/a\", \"crates/b\"]\n\
1893\n\
1894[workspace.package]\n\
1895version = \"0.45.18\"\n";
1896        assert_eq!(current_version(toml).unwrap(), "0.45.18");
1897    }
1898
1899    #[test]
1900    fn coalesce_proceeds_with_nothing_pending() {
1901        assert_eq!(coalesce(None, "0.8.0").unwrap(), Coalesce::Proceed);
1902    }
1903
1904    /// A minimal, otherwise-plausible pending marker for tests that only
1905    /// care about one field.
1906    fn test_pending(target_version: &str, level: BumpLevel) -> PendingBump {
1907        PendingBump {
1908            target_version: target_version.to_owned(),
1909            level,
1910            branch: format!("chore/release-v{target_version}"),
1911            pr_url: "https://example.invalid/pull/9".to_owned(),
1912        }
1913    }
1914
1915    #[test]
1916    fn coalesce_skips_while_the_pending_target_is_still_ahead() {
1917        let pending = test_pending("0.9.0", BumpLevel::Minor);
1918        assert_eq!(
1919            coalesce(Some(&pending), "0.8.0").unwrap(),
1920            Coalesce::Skip {
1921                target_version: "0.9.0".to_owned()
1922            }
1923        );
1924    }
1925
1926    #[test]
1927    fn coalesce_treats_a_landed_or_superseded_pending_bump_as_stale() {
1928        let pending = test_pending("0.9.0", BumpLevel::Minor);
1929        // The pending bump landed exactly: proceed with a fresh decision.
1930        assert_eq!(
1931            coalesce(Some(&pending), "0.9.0").unwrap(),
1932            Coalesce::Proceed
1933        );
1934        // A human bumped further than what was pending: also proceed.
1935        assert_eq!(
1936            coalesce(Some(&pending), "1.0.0").unwrap(),
1937            Coalesce::Proceed
1938        );
1939    }
1940
1941    #[test]
1942    fn pending_action_escalates_only_for_a_more_severe_decision() {
1943        assert_eq!(
1944            pending_action(BumpLevel::Patch, BumpLevel::Patch),
1945            PendingAction::AlreadyCovered
1946        );
1947        assert_eq!(
1948            pending_action(BumpLevel::Patch, BumpLevel::Minor),
1949            PendingAction::Escalate
1950        );
1951        assert_eq!(
1952            pending_action(BumpLevel::Patch, BumpLevel::Major),
1953            PendingAction::Escalate
1954        );
1955        assert_eq!(
1956            pending_action(BumpLevel::Minor, BumpLevel::Patch),
1957            PendingAction::AlreadyCovered
1958        );
1959        assert_eq!(
1960            pending_action(BumpLevel::Major, BumpLevel::Minor),
1961            PendingAction::AlreadyCovered
1962        );
1963        assert_eq!(
1964            pending_action(BumpLevel::Major, BumpLevel::Major),
1965            PendingAction::AlreadyCovered
1966        );
1967    }
1968
1969    #[test]
1970    fn pr_state_parsing_reads_open_and_not_open() {
1971        assert!(parse_pr_state(r#"{"state":"OPEN"}"#).unwrap());
1972        assert!(!parse_pr_state(r#"{"state":"CLOSED"}"#).unwrap());
1973        assert!(!parse_pr_state(r#"{"state":"MERGED"}"#).unwrap());
1974    }
1975
1976    #[test]
1977    fn a_lock_is_exclusive_until_dropped() {
1978        let dir = tempfile::tempdir().unwrap();
1979        let marker = dir.path().join("bump").join("deadbeefdeadbeef.json");
1980        let first = MarkerLock::acquire(&marker)
1981            .unwrap()
1982            .expect("first attempt takes the lock");
1983        assert!(
1984            MarkerLock::acquire(&marker).unwrap().is_none(),
1985            "a second attempt must be refused while the first holds it"
1986        );
1987        drop(first);
1988        assert!(
1989            MarkerLock::acquire(&marker).unwrap().is_some(),
1990            "dropping the guard releases the lock for the next attempt"
1991        );
1992    }
1993
1994    #[test]
1995    fn a_stale_lock_is_reclaimed() {
1996        let dir = tempfile::tempdir().unwrap();
1997        let marker = dir.path().join("bump").join("deadbeefdeadbeef.json");
1998        let lock_path = marker.with_extension("lock");
1999        std::fs::create_dir_all(lock_path.parent().unwrap()).unwrap();
2000        std::fs::write(&lock_path, b"").unwrap();
2001        let old = std::time::SystemTime::now() - LOCK_STALE_AFTER - Duration::from_secs(1);
2002        std::fs::OpenOptions::new()
2003            .write(true)
2004            .open(&lock_path)
2005            .unwrap()
2006            .set_modified(old)
2007            .unwrap();
2008        assert!(
2009            MarkerLock::acquire(&marker).unwrap().is_some(),
2010            "a lock older than the stale window must be reclaimed rather than block forever"
2011        );
2012    }
2013
2014    #[tokio::test]
2015    async fn a_contended_lock_is_retried_until_the_holder_releases_it() {
2016        let dir = tempfile::tempdir().unwrap();
2017        let marker = dir.path().join("bump").join("deadbeefdeadbeef.json");
2018        let held = MarkerLock::acquire(&marker)
2019            .unwrap()
2020            .expect("seed the contention");
2021        let releaser = tokio::spawn(async move {
2022            tokio::time::sleep(Duration::from_millis(20)).await;
2023            drop(held);
2024        });
2025        let waited =
2026            wait_for_marker_lock_with(&marker, Duration::from_millis(5), Duration::from_secs(5))
2027                .await
2028                .unwrap();
2029        assert!(
2030            waited.is_some(),
2031            "a merge landing behind another's still-running decision must not be dropped - it \
2032             must wait for that decision to finish and then judge against what it left behind"
2033        );
2034        releaser.await.unwrap();
2035    }
2036
2037    #[tokio::test]
2038    async fn a_lock_held_past_the_ceiling_gives_up() {
2039        let dir = tempfile::tempdir().unwrap();
2040        let marker = dir.path().join("bump").join("deadbeefdeadbeef.json");
2041        let _held = MarkerLock::acquire(&marker).unwrap().unwrap();
2042        let waited =
2043            wait_for_marker_lock_with(&marker, Duration::from_millis(2), Duration::from_millis(10))
2044                .await
2045                .unwrap();
2046        assert!(
2047            waited.is_none(),
2048            "a lock genuinely held past the ceiling must eventually give up rather than wait \
2049             forever"
2050        );
2051    }
2052
2053    #[test]
2054    fn level_between_reads_off_the_differing_digit() {
2055        assert_eq!(
2056            level_between(
2057                Version::parse("0.8.0").unwrap(),
2058                Version::parse("1.0.0").unwrap()
2059            ),
2060            Some(BumpLevel::Major)
2061        );
2062        assert_eq!(
2063            level_between(
2064                Version::parse("0.8.0").unwrap(),
2065                Version::parse("0.9.0").unwrap()
2066            ),
2067            Some(BumpLevel::Minor)
2068        );
2069        assert_eq!(
2070            level_between(
2071                Version::parse("0.8.0").unwrap(),
2072                Version::parse("0.8.1").unwrap()
2073            ),
2074            Some(BumpLevel::Patch)
2075        );
2076        assert_eq!(
2077            level_between(
2078                Version::parse("0.8.0").unwrap(),
2079                Version::parse("0.8.0").unwrap()
2080            ),
2081            None
2082        );
2083    }
2084
2085    #[test]
2086    fn open_release_pr_is_found_among_unrelated_pull_requests() {
2087        let json = r#"[
2088            {"url": "https://example.invalid/pull/1", "headRefName": "feat/something"},
2089            {"url": "https://example.invalid/pull/2", "headRefName": "chore/release-v0.9.0"}
2090        ]"#;
2091        let found = parse_open_release_pr(json).unwrap();
2092        assert_eq!(
2093            found,
2094            Some((
2095                "chore/release-v0.9.0".to_owned(),
2096                "https://example.invalid/pull/2".to_owned()
2097            ))
2098        );
2099    }
2100
2101    #[test]
2102    fn no_open_release_pr_reads_as_none_not_an_error() {
2103        let json =
2104            r#"[{"url": "https://example.invalid/pull/1", "headRefName": "feat/something"}]"#;
2105        assert_eq!(parse_open_release_pr(json).unwrap(), None);
2106        assert_eq!(parse_open_release_pr("[]").unwrap(), None);
2107    }
2108
2109    #[test]
2110    fn marker_round_trips_through_disk() {
2111        let dir = tempfile::tempdir().unwrap();
2112        let path = marker_path(dir.path(), Path::new("/repos/magi"));
2113        assert!(read_marker(&path).is_none());
2114
2115        let marker = test_pending("0.9.0", BumpLevel::Patch);
2116        write_marker(&path, &marker).unwrap();
2117        let read_back = read_marker(&path).unwrap();
2118        assert_eq!(read_back.target_version, "0.9.0");
2119        assert_eq!(read_back.level, BumpLevel::Patch);
2120        assert_eq!(read_back.pr_url, marker.pr_url);
2121
2122        clear_marker(&path);
2123        assert!(read_marker(&path).is_none());
2124    }
2125
2126    #[test]
2127    fn different_repos_get_different_marker_files() {
2128        let dir = tempfile::tempdir().unwrap();
2129        let a = marker_path(dir.path(), Path::new("/repos/a"));
2130        let b = marker_path(dir.path(), Path::new("/repos/b"));
2131        assert_ne!(a, b);
2132    }
2133
2134    /// A version-bump-only pull request must never trigger the next bump - see
2135    /// [`is_release_only`]'s own doc for why that shape is the trigger for
2136    /// "do not treat this as a change to react to".
2137    #[test]
2138    fn a_bump_pull_requests_own_merge_does_not_retrigger() {
2139        let files = vec!["Cargo.toml".to_owned(), "Cargo.lock".to_owned()];
2140        assert!(
2141            is_release_only(&files),
2142            "the bump pull request's own diff must read as release-only"
2143        );
2144    }
2145
2146    #[test]
2147    fn should_release_bump_reads_only_a_merged_status() {
2148        assert!(should_release_bump(RunStatus::Merged));
2149        for other in [RunStatus::Blocked, RunStatus::Ready, RunStatus::Prep] {
2150            assert!(!should_release_bump(other));
2151        }
2152    }
2153
2154    /// `land::Step::Done { merged: true }` - a pull request already merged
2155    /// underneath magi. `land::decide` reads that straight off the pull
2156    /// request's own lifecycle before it looks at checks or comments at all.
2157    #[test]
2158    fn all_three_merge_paths_report_pr_lifecycle_merged_case_done() {
2159        let pr = land::PrState {
2160            url: "https://github.com/o/r/pull/1".to_owned(),
2161            number: 1,
2162            state: PrLifecycle::Merged,
2163            checks: land::Checks::Green,
2164            failing: Vec::new(),
2165            review_comments: Vec::new(),
2166            blocking: land::Blocking::No,
2167        };
2168        assert_eq!(
2169            land::decide(&pr, 0, 4, Duration::ZERO),
2170            land::Step::Done { merged: true }
2171        );
2172        assert!(should_release_bump(RunStatus::Merged));
2173    }
2174
2175    /// `land::Step::Merge`'s own `gh pr merge` succeeding: `land::land` then
2176    /// sets `pr.state = PrLifecycle::Merged` by hand before returning (see
2177    /// `land::land`'s `Step::Merge` arm), which is the same value the other
2178    /// two paths converge on.
2179    #[test]
2180    fn all_three_merge_paths_report_pr_lifecycle_merged_case_direct_merge() {
2181        let pr = land::PrState {
2182            url: "https://github.com/o/r/pull/2".to_owned(),
2183            number: 2,
2184            state: PrLifecycle::Open,
2185            checks: land::Checks::Green,
2186            failing: Vec::new(),
2187            review_comments: Vec::new(),
2188            blocking: land::Blocking::No,
2189        };
2190        assert_eq!(land::decide(&pr, 0, 4, Duration::ZERO), land::Step::Merge);
2191        // land::land's Step::Merge arm sets this by hand on success; asserted
2192        // here as the value that then makes should_release_bump fire.
2193        assert!(should_release_bump(RunStatus::Merged));
2194    }
2195
2196    /// [`land::merged_after_all`] - `gh pr merge` exited non-zero but the
2197    /// forge confirms the pull request merged anyway.
2198    #[test]
2199    fn all_three_merge_paths_report_pr_lifecycle_merged_case_merged_after_all() {
2200        let argv = land::merge_argv(3, "feat: something");
2201        let outcome = land::merged_after_all(
2202            &argv,
2203            "could not determine current branch: not on any branch",
2204            Some(PrLifecycle::Merged),
2205        );
2206        assert!(outcome.is_some(), "the forge's confirmation must win");
2207        assert!(should_release_bump(RunStatus::Merged));
2208
2209        // The same recovery must not fabricate a merge when the forge does
2210        // not confirm one.
2211        assert!(land::merged_after_all(&argv, "network error", Some(PrLifecycle::Open)).is_none());
2212        assert!(land::merged_after_all(&argv, "network error", None).is_none());
2213    }
2214
2215    /// The paths that do *not* land must not read as merged either.
2216    #[test]
2217    fn a_close_or_a_give_up_does_not_trigger_a_bump() {
2218        let pr = land::PrState {
2219            url: "https://github.com/o/r/pull/4".to_owned(),
2220            number: 4,
2221            state: PrLifecycle::Closed,
2222            checks: land::Checks::Green,
2223            failing: Vec::new(),
2224            review_comments: Vec::new(),
2225            blocking: land::Blocking::No,
2226        };
2227        assert_eq!(
2228            land::decide(&pr, 0, 4, Duration::ZERO),
2229            land::Step::Done { merged: false }
2230        );
2231        assert!(!should_release_bump(RunStatus::Blocked));
2232    }
2233}