Skip to main content

magi/
bump.rs

1//! Release version bumps, opened automatically once a merge lands.
2//!
3//! `magi`'s own "Update & restart" only ever looks at tagged GitHub Releases
4//! (`src/updater.rs`); it never builds or tags anything itself. The tag comes
5//! from `auto-tag.yml` noticing a `Cargo.toml` version change on `main`, and
6//! nothing in the graph used to touch that field - a merge that changed the
7//! phone-facing binary left `main` ahead of the last tagged release with
8//! nobody to notice, and the next "Update & restart" found nothing newer.
9//!
10//! This module is the fix. Once [`crate::land`] confirms a merge, the caller
11//! in [`crate::graph`] hands off here: an agent is asked which digit of
12//! `major.minor.patch` the change earns, and this module opens the same
13//! `chore/release-vX.Y.Z` pull request `AGENTS.md` already documents as the
14//! hand-driven recipe, with automerge enabled so CI green is the only thing
15//! standing between the merge and the tag.
16//!
17//! Everything that can be decided without touching a network or a `cargo`
18//! binary is a pure function - the version arithmetic, the `Cargo.toml`
19//! rewrite, the prompt, the coalescing policy - so the policy itself is
20//! asserted directly, the same split [`crate::land`] uses for [`land::decide`](crate::land::decide).
21
22use std::fmt::Write as _;
23use std::path::{Path, PathBuf};
24use std::time::Duration;
25
26use anyhow::{Context as _, Result, anyhow, bail};
27use serde::{Deserialize, Serialize};
28
29use crate::agent::{self, Invocation, SeatState};
30#[cfg(test)]
31use crate::ask;
32use crate::config::AgentSpec;
33use crate::git;
34use crate::land;
35use crate::notices::{Link, Notice, Notices};
36use crate::proc::Quiet as _;
37use crate::release_manifest;
38use crate::run::{self, RunState, RunStatus};
39use crate::verdict;
40
41/// One bounded release decision attempt, independent of a release PR outcome.
42#[derive(Debug, Clone, Serialize, Deserialize)]
43pub struct DecisionAttempt {
44    /// Configured agent id tried in this attempt.
45    pub agent: String,
46    /// Sanitized failure classification or successful decision.
47    pub outcome: String,
48}
49
50/// Consume the configured chain once. A parsed decision ends failover; reason
51/// rewriting happens afterwards and cannot change the selected level.
52async fn ask_decision(
53    state: &mut RunState,
54    repo: &Path,
55    prompt: &str,
56    timeout: Duration,
57) -> Result<(AgentSpec, SeatState, BumpDecision)> {
58    let chain = agent::pick_chain(
59        &state.config.agents,
60        state.config.roles.chatter.as_ref(),
61        &agent::installed,
62        "chatter (release-bump decision)",
63    )?;
64    // Keep the whole chain within the existing decision budget. In
65    // particular, failover must not outlive the marker lock's stale ceiling.
66    let attempt_timeout = timeout / u32::try_from(chain.len()).unwrap_or(u32::MAX);
67    let artifacts = agent::artifacts_dir(&state.dir());
68    let cache = state.config.cache_dir();
69    let mut failures = Vec::new();
70    for (n, spec) in chain.iter().enumerate() {
71        let mut seat = crate::graph::handover_seat("bump", &spec.id, state.next_seat_seed());
72        // Include the persisted attempt count so a resumed decision cannot
73        // overwrite earlier evidence, including the first attempt's output.
74        let attempt = state.bump_decision_attempts.len() + 1;
75        let stem = format!("bump-decision-{attempt}");
76        state.event(
77            "bump",
78            format!("decision attempt {attempt}: trying {} ({stem})", spec.id),
79        );
80        // The reason is posted in the release pull request.
81        let outcome = async {
82            let spec = agent::for_github_text(spec, &state.config.graph.github_language, repo)?;
83            agent::invoke(
84                &spec,
85                &mut seat,
86                &Invocation {
87                    coordination: state.config.coordination.as_ref(),
88                    fetched_base: None,
89                    cwd: repo,
90                    prompt,
91                    timeout: attempt_timeout,
92                    allow_write: false,
93                    sessions: false,
94                    artifacts: &artifacts,
95                    stem: &stem,
96                    run: &state.id,
97                    node: "bump",
98                    cache_dir: cache.as_deref(),
99                    attachments: &[],
100                    writable: &[],
101                },
102            )
103            .await
104        }
105        .await;
106        let parsed = if agent::chain_advances(&outcome) {
107            None
108        } else {
109            outcome
110                .as_ref()
111                .ok()
112                .and_then(|out| parse_decision(&out.text).ok())
113        };
114        // Fixed classifications avoid copying CLI output, secrets or local
115        // paths into events, reports, or the surfaced failure message.
116        let (class, reason) = match &outcome {
117            Ok(out) if out.quota_exhausted() => {
118                (run::FailClass::Quota, "rate/quota limit".to_owned())
119            }
120            Ok(out) if out.timed_out => (run::FailClass::Timeout, "timed out".to_owned()),
121            Ok(out) if out.exit_code != Some(0) => (
122                run::FailClass::Other("cli".into()),
123                format!(
124                    "CLI failed ({})",
125                    crate::notices::exit_status(out.exit_code)
126                ),
127            ),
128            Ok(out) if out.text.trim().is_empty() => (
129                run::FailClass::Other("empty".into()),
130                "empty output".to_owned(),
131            ),
132            Err(_) => (
133                run::FailClass::Other("cli".into()),
134                "CLI invocation failed; inspect attempt artifacts".to_owned(),
135            ),
136            _ => (
137                run::FailClass::Other("json".into()),
138                "invalid decision JSON or missing reason".to_owned(),
139            ),
140        };
141        let status = if parsed.is_some() {
142            "valid decision"
143        } else {
144            &reason
145        };
146        state.bump_decision_attempts.push(DecisionAttempt {
147            agent: spec.id.clone(),
148            outcome: status.to_owned(),
149        });
150        state.event(
151            "bump",
152            format!("decision attempt {attempt}: {}: {status}", spec.id),
153        );
154        if let Some(decision) = parsed {
155            return Ok((spec.clone(), seat, decision));
156        }
157        failures.push(format!("{}: {reason}", spec.id));
158        if let Some(next) = chain.get(n + 1) {
159            crate::graph::record_handover(
160                state, "bump", "bump", &spec.id, &next.id, &class, &reason,
161            );
162        }
163    }
164    bail!(
165        "release-bump decision exhausted {} eligible agent(s): {}. Check CLI subscription limits, availability and bump-decision attempt artifacts; adjust [roles] chatter or retry after recovery. No release PR was created by this decision",
166        chain.len(),
167        failures.join("; ")
168    )
169}
170
171/// Validate only the reason after a decision is settled; no retry can replace
172/// its level, even when a rewrite returns a different decision or fails.
173async fn guard_reason(
174    state: &mut RunState,
175    repo: &Path,
176    prompt: &str,
177    spec: &AgentSpec,
178    seat: &mut SeatState,
179    decision: &mut BumpDecision,
180) {
181    let artifacts = agent::artifacts_dir(&state.dir());
182    let mut violations =
183        crate::github_text::check_for(&state.config.graph, "", &decision.reason, None);
184    // Sensitive-only: span redaction is enough, no rewrite needed.
185    violations.retain(|v| *v != crate::github_text::Violation::SensitiveData);
186    if violations.is_empty() {
187        decision.reason = crate::scrub::scrub(&decision.reason, &crate::scrub::Identity::current());
188    }
189    if state.config.graph.github_text_guard && !violations.is_empty() {
190        state.event(
191            "github-text",
192            format!("release reason rejected: {violations:?}; requesting one rewrite"),
193        );
194        let rewrite = format!(
195            "{prompt}\n\nYour release reason failed the GitHub text gate: {violations:?}. Return the same decision JSON with an English reason containing no local identity or secrets. Previous reason: {}",
196            decision.reason
197        );
198        let retry = async {
199            let spec = agent::for_github_text(spec, &state.config.graph.github_language, repo)?;
200            agent::invoke(
201                &spec,
202                seat,
203                &Invocation {
204                    coordination: state.config.coordination.as_ref(),
205                    fetched_base: None,
206                    cwd: repo,
207                    prompt: &rewrite,
208                    timeout: crate::graph::retry_budget(DECISION_TIMEOUT, true),
209                    allow_write: false,
210                    sessions: false,
211                    artifacts: &artifacts,
212                    stem: "bump-rewrite",
213                    run: &state.id,
214                    node: "bump",
215                    cache_dir: state.config.cache_dir().as_deref(),
216                    attachments: &[],
217                    writable: &[],
218                },
219            )
220            .await
221        }
222        .await;
223        let reason = retry
224            .ok()
225            .filter(|o| o.usable())
226            .and_then(|o| parse_decision(&o.text).ok())
227            .filter(|d| {
228                d.level == decision.level
229                    && crate::github_text::check_for(&state.config.graph, "", &d.reason, None)
230                        .is_empty()
231            })
232            .map(|d| d.reason);
233        if let Some(reason) = reason {
234            decision.reason = reason;
235            state.event("github-text", "release reason rewrite passed");
236        } else {
237            decision.reason = "The merged change requires a release.".to_owned();
238            state.event(
239                "github-text",
240                "release reason rewrite unavailable or rejected; using neutral text",
241            );
242        }
243    }
244}
245
246/// How long the decision call may run.
247///
248/// It reads a diffstat, a subject line and a version string, and returns
249/// three words and a sentence - nowhere near the budget an implement wave
250/// gets, so a fixed, generous constant is simpler than a new config knob for
251/// a call this small. This is the total CLI budget, divided equally among
252/// eligible candidates so failover cannot extend the release critical section.
253const DECISION_TIMEOUT: Duration = Duration::from_secs(600);
254
255/// Does this run's final status mean the merge this call is downstream of
256/// actually happened?
257///
258/// All three of `land`'s success paths converge on the same signal before
259/// [`crate::graph`] ever calls into this module: a pull request already
260/// merged underneath magi (`land::Step::Done { merged: true }`),
261/// `land::Step::Merge`'s own `gh pr merge` succeeding, and the
262/// [`land::merged_after_all`] recovery for a non-zero exit that merged
263/// anyway. Every one of them ends `land::land` with `pr.state ==
264/// PrLifecycle::Merged`, which is exactly what `graph::Runner::merge` reads
265/// to set `RunStatus::Merged` on the run - see the `all_three_merge_paths_*`
266/// tests below for each path's own evidence. Every path that does *not* land
267/// (a close, `Step::GiveUp`, an unanswered `land_approval`, or a `gh pr
268/// merge` failure the forge does not confirm) leaves the run `Blocked`
269/// instead, so this one check is the whole gate a caller needs.
270pub fn should_release_bump(status: RunStatus) -> bool {
271    status == RunStatus::Merged
272}
273
274/// Which digit of `major.minor.patch` a change earns.
275#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
276#[serde(rename_all = "lowercase")]
277pub enum BumpLevel {
278    /// A breaking change to a public surface.
279    Major,
280    /// A user-visible new capability, or - below `1.0.0` - a breaking change.
281    Minor,
282    /// A fix, internal refactor, or dependency update.
283    Patch,
284}
285
286impl BumpLevel {
287    /// Stable lower-case name, as the prompt and the events spell it.
288    pub fn as_str(self) -> &'static str {
289        match self {
290            Self::Major => "major",
291            Self::Minor => "minor",
292            Self::Patch => "patch",
293        }
294    }
295
296    /// Severity for comparing two independent decisions: `patch < minor <
297    /// major`, spelled out explicitly rather than derived from declaration
298    /// order, which exists here only for readability and must not silently
299    /// become load-bearing.
300    fn severity(self) -> u8 {
301        match self {
302            Self::Patch => 0,
303            Self::Minor => 1,
304            Self::Major => 2,
305        }
306    }
307}
308
309/// The agent's answer: which digit, and why.
310///
311/// Parsed with [`verdict::extract_json`], so a reply missing `reason`, or
312/// spelling `level` as anything but `major` / `minor` / `patch`, is a parse
313/// error rather than a value with a blank field - [`parse_decision`] never
314/// fabricates a bump out of a response it could not read.
315#[derive(Debug, Clone, Deserialize)]
316pub struct BumpDecision {
317    /// The chosen digit.
318    pub level: BumpLevel,
319    /// One line, carried into the pull request body so "why was this minor"
320    /// is answerable later without archaeology.
321    pub reason: String,
322}
323
324/// Parse the agent's reply. Never returns a default decision: an unparsable
325/// or incomplete reply is `Err`, and the caller must not open a bump pull
326/// request on the strength of a guess.
327pub fn parse_decision(text: &str) -> Result<BumpDecision> {
328    let decision: BumpDecision = verdict::extract_json(text)?;
329    if decision.reason.trim().is_empty() {
330        bail!("the bump decision carried no reason");
331    }
332    Ok(decision)
333}
334
335/// `major.minor.patch`, the only shape a `[package] version` in this
336/// ecosystem carries in practice.
337#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
338pub struct Version {
339    /// First component.
340    pub major: u64,
341    /// Second component.
342    pub minor: u64,
343    /// Third component.
344    pub patch: u64,
345}
346
347impl Version {
348    /// Parse `major.minor.patch`. A pre-release or build suffix on the patch
349    /// component (`0.8.0-rc1`) is tolerated by reading only its leading
350    /// digits - Cargo itself never writes one into `[package] version`, but a
351    /// human editing the file by hand might.
352    pub fn parse(s: &str) -> Result<Self> {
353        let s = s.trim();
354        let mut parts = s.splitn(3, '.');
355        let major = parts
356            .next()
357            .with_context(|| format!("`{s}` has no major component"))?;
358        let minor = parts
359            .next()
360            .with_context(|| format!("`{s}` has no minor component"))?;
361        let patch = parts
362            .next()
363            .with_context(|| format!("`{s}` has no patch component"))?;
364        let patch_digits: String = patch.chars().take_while(char::is_ascii_digit).collect();
365        Ok(Self {
366            major: major
367                .trim()
368                .parse()
369                .with_context(|| format!("`{major}` is not a number"))?,
370            minor: minor
371                .trim()
372                .parse()
373                .with_context(|| format!("`{minor}` is not a number"))?,
374            patch: patch_digits
375                .parse()
376                .with_context(|| format!("`{patch}` has no numeric patch component"))?,
377        })
378    }
379
380    /// The next version at `level`. A `major`/`minor` bump zeroes every digit
381    /// below it, matching what every tool that reads a semver range expects.
382    #[must_use]
383    pub fn bump(self, level: BumpLevel) -> Self {
384        match level {
385            BumpLevel::Major => Self {
386                major: self.major + 1,
387                minor: 0,
388                patch: 0,
389            },
390            BumpLevel::Minor => Self {
391                major: self.major,
392                minor: self.minor + 1,
393                patch: 0,
394            },
395            BumpLevel::Patch => Self {
396                major: self.major,
397                minor: self.minor,
398                patch: self.patch + 1,
399            },
400        }
401    }
402}
403
404impl std::fmt::Display for Version {
405    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
406        write!(f, "{}.{}.{}", self.major, self.minor, self.patch)
407    }
408}
409
410/// Did the merged change touch only the release manifest and its lockfile?
411///
412/// [`after_merge`] is reached from *every* qualifying merge, including a
413/// version-bump pull request's own - without this check a bump would trigger
414/// another bump forever. A human-authored version-only pull request is exempt
415/// from review for the same reason (`AGENTS.md`'s "version-bump-only pull
416/// requests"), so using its shape as the "do not treat this as a trigger"
417/// test is one rule doing both jobs instead of two.
418pub fn is_release_only(files: &[String]) -> bool {
419    !files.is_empty() && files.iter().all(|f| f == "Cargo.toml" || f == "Cargo.lock")
420}
421
422/// Rewrite `table`'s `version = "..."` line, leaving every other byte
423/// untouched.
424///
425/// Scoped to the named table specifically, rather than the first line
426/// anywhere in the file that looks like `version = "..."`: a dependency
427/// pinned as `foo = { version = "1.2.3" }` must never move, and neither must
428/// the *other* of `[package]` / `[workspace.package]` when only one of them
429/// is the one being bumped. That scoping is what lets a version-bump-only
430/// diff stay exactly that, which [`is_release_only`] and the "no reviewer
431/// needed" exemption in `AGENTS.md` both rest on.
432fn rewrite_table_version(toml: &str, table: &str, new_version: &str) -> Result<String> {
433    let mut out = String::with_capacity(toml.len() + 8);
434    let mut in_table = false;
435    let mut done = false;
436    for line in toml.split_inclusive('\n') {
437        let trimmed = line.trim();
438        if trimmed.starts_with('[') {
439            in_table = trimmed == table;
440        }
441        if !done && in_table && trimmed.split('=').next().map(str::trim) == Some("version") {
442            let newline = if line.ends_with("\r\n") { "\r\n" } else { "\n" };
443            let _ = write!(out, "version = \"{new_version}\"{newline}");
444            done = true;
445            continue;
446        }
447        out.push_str(line);
448    }
449    if !done {
450        bail!("no `version` field found under `{table}`");
451    }
452    Ok(out)
453}
454
455/// Truncate `s` at the first `#` that is not inside a quoted string, the
456/// same rule a TOML parser uses to tell a comment from a literal `#` inside
457/// a value. Used only on table-header lines here (`[workspace.dependencies]
458/// # internal pins` is valid TOML), so header comparisons don't miss a
459/// section just because it carries a trailing comment.
460fn strip_trailing_comment(s: &str) -> &str {
461    let mut in_string = false;
462    let mut quote = '"';
463    for (i, c) in s.char_indices() {
464        if in_string {
465            if c == quote {
466                in_string = false;
467            }
468        } else if c == '"' || c == '\'' {
469            in_string = true;
470            quote = c;
471        } else if c == '#' {
472            return s[..i].trim_end();
473        }
474    }
475    s
476}
477
478/// Strip a single layer of matching quotes from a TOML key, so a
479/// `"name" = { .. }` or `'name' = { .. }` entry compares equal to the plain
480/// `name` the `toml` crate itself hands back for the same key - Cargo
481/// manifests almost never quote a dependency key (bare keys already allow
482/// `-`), but it is legal TOML and costs nothing extra to normalise.
483fn unquote_key(key: &str) -> &str {
484    for quote in ['"', '\''] {
485        if let Some(inner) = key.strip_prefix(quote).and_then(|k| k.strip_suffix(quote)) {
486            return inner;
487        }
488    }
489    key
490}
491
492/// Pull just the `[workspace.dependencies]` table - flat entries and any
493/// `[workspace.dependencies.<name>]` sub-tables - out of a full manifest and
494/// rewrite its headers to `[dependencies]` / `[dependencies.<name>]`, so the
495/// fragment parses standalone as TOML.
496///
497/// This is what keeps [`internal_pin_names`] and [`verify_pins_rewritten`]
498/// from imposing a whole-file strict-TOML precondition on every workspace
499/// manifest this rewrite runs against: only the dependency table itself has
500/// to parse, not any other section a hand-edited `Cargo.toml` might carry in
501/// a shape this crate's pinned `toml` version does not accept. Returns an
502/// empty string when the manifest has no such table at all.
503fn extract_workspace_dependencies_fragment(toml: &str) -> String {
504    let mut fragment = String::new();
505    let mut capturing = false;
506    for line in toml.split_inclusive('\n') {
507        let header = strip_trailing_comment(line.trim());
508        if header.starts_with('[') {
509            if header == "[workspace.dependencies]" {
510                capturing = true;
511                fragment.push_str("[dependencies]\n");
512            } else if let Some(name) = header
513                .strip_prefix("[workspace.dependencies.")
514                .and_then(|rest| rest.strip_suffix(']'))
515            {
516                capturing = true;
517                let _ = writeln!(fragment, "[dependencies.{name}]");
518            } else {
519                capturing = false;
520            }
521            continue;
522        }
523        if capturing {
524            fragment.push_str(line);
525        }
526    }
527    fragment
528}
529
530/// Names of `[workspace.dependencies]` entries that name an internal member
531/// by *both* `path` and `version` - the shape `AGENTS.md`'s own "internal
532/// version pin" guidance recommends for a published member that another
533/// workspace member depends on. Parsed with the `toml` crate (already a
534/// dependency, used read-only here) rather than by scanning for the word
535/// `version`, so an ordinary `[dependencies]` entry in some other table, or a
536/// `[workspace.dependencies]` entry that carries only one of the two keys,
537/// never enters the candidate set:
538///
539/// - `path` only (no `version`): an unpublished, workspace-only member - not
540///   ours to touch.
541/// - `version` only (no `path`): an external crates.io dependency - not ours
542///   to touch either.
543///
544/// Returns an empty list, not an error, when the manifest has no
545/// `[workspace.dependencies]` table at all - the common single-crate shape -
546/// so [`rewrite_cargo_version`]'s existing `[package]` path is unaffected.
547fn internal_pin_names(toml: &str) -> Result<Vec<String>> {
548    let fragment = extract_workspace_dependencies_fragment(toml);
549    if fragment.trim().is_empty() {
550        return Ok(Vec::new());
551    }
552    let value: toml::Value =
553        toml::from_str(&fragment).context("failed to parse `[workspace.dependencies]` as TOML")?;
554    let mut names: Vec<String> = value
555        .get("dependencies")
556        .and_then(|d| d.as_table())
557        .into_iter()
558        .flatten()
559        .filter(|(_, dep)| {
560            dep.as_table()
561                .is_some_and(|t| t.contains_key("path") && t.contains_key("version"))
562        })
563        .map(|(name, _)| name.clone())
564        .collect();
565    names.sort();
566    Ok(names)
567}
568
569/// Rewrite the quoted string value of `key = "..."` (or `key = '...'`, a
570/// literal string) on `line`, wherever it appears - once for an inline table
571/// (`name = { path = "..", version = ".." }`, either key order) and once for
572/// a dotted `[workspace.dependencies.name]` table's own `version = ".."`
573/// line. The replacement is written back between the *same* quote
574/// characters the line already used, so a literal-string pin stays a
575/// literal string. Returns `None` when `key` is not present on this line as
576/// a `key = "value"` pair, which the caller treats as "could not rewrite
577/// this one" rather than silently leaving it unbumped.
578fn rewrite_quoted_field(line: &str, key: &str, new_value: &str) -> Option<String> {
579    let is_ident = |c: char| c.is_ascii_alphanumeric() || c == '_' || c == '-';
580    let mut search_from = 0;
581    while let Some(rel) = line[search_from..].find(key) {
582        let key_start = search_from + rel;
583        let before_ok = key_start == 0 || !is_ident(line[..key_start].chars().next_back().unwrap());
584        let eq_pos = key_start
585            + key.len()
586            + (line[key_start + key.len()..].len()
587                - line[key_start + key.len()..].trim_start().len());
588        if before_ok && line[eq_pos..].starts_with('=') {
589            let after_eq = &line[eq_pos + 1..];
590            let ws_len = after_eq.len() - after_eq.trim_start().len();
591            let quote_pos = eq_pos + 1 + ws_len;
592            if let Some(quote_char) = line[quote_pos..]
593                .chars()
594                .next()
595                .filter(|c| *c == '"' || *c == '\'')
596            {
597                let value_begin = quote_pos + quote_char.len_utf8();
598                if let Some(end_rel) = line[value_begin..].find(quote_char) {
599                    let value_end = value_begin + end_rel;
600                    let mut out = String::with_capacity(line.len());
601                    out.push_str(&line[..value_begin]);
602                    out.push_str(new_value);
603                    out.push_str(&line[value_end..]);
604                    return Some(out);
605                }
606            }
607        }
608        search_from = key_start + key.len();
609    }
610    None
611}
612
613/// Rewrite the `version` pin of each `[workspace.dependencies]` entry named
614/// in `names` to `new_version`, in every shape Cargo accepts: the inline
615/// table (`name = { path = "..", version = "old" }`), the dotted-key form
616/// under the flat table (`name.path = ".."` / `name.version = "old"` as two
617/// separate lines), and the dotted sub-table (`[workspace.dependencies.
618/// name]` followed by its own `version = "old"` line). Every other byte,
619/// including entries not in `names`, is untouched - same discipline as
620/// [`rewrite_table_version`].
621///
622/// Bails rather than silently leaving a pin unbumped when a named entry's
623/// `version` field cannot be located on a single line this way (for example
624/// an inline table split across lines): a bump pull request that leaves a
625/// stale internal pin behind is exactly the failure this exists to prevent,
626/// so an unrepresentable form must stop the bump, not ship it half-done.
627fn rewrite_workspace_dependency_pins(
628    toml: &str,
629    names: &[String],
630    new_version: &str,
631) -> Result<String> {
632    if names.is_empty() {
633        return Ok(toml.to_owned());
634    }
635    let mut out = String::with_capacity(toml.len() + names.len() * 8);
636    let mut in_flat_table = false;
637    let mut in_named_table: Option<String> = None;
638    let mut rewritten: std::collections::HashSet<String> = std::collections::HashSet::new();
639
640    for line in toml.split_inclusive('\n') {
641        let trimmed = line.trim();
642        if trimmed.starts_with('[') {
643            let header = strip_trailing_comment(trimmed);
644            in_flat_table = header == "[workspace.dependencies]";
645            in_named_table = header
646                .strip_prefix("[workspace.dependencies.")
647                .and_then(|rest| rest.strip_suffix(']'))
648                .map(str::to_owned);
649            out.push_str(line);
650            continue;
651        }
652
653        let key = trimmed.split('=').next().map(str::trim).map(unquote_key);
654
655        if in_flat_table {
656            // The inline-table form: `name = { path = "..", version = ".." }`.
657            if let Some(name) = key.and_then(|k| names.iter().find(|n| n.as_str() == k)) {
658                if let Some(rewritten_line) = rewrite_quoted_field(line, "version", new_version) {
659                    rewritten.insert(name.clone());
660                    out.push_str(&rewritten_line);
661                    continue;
662                }
663            } else if let Some(name) = key.and_then(|k| {
664                k.strip_suffix(".version")
665                    .and_then(|prefix| names.iter().find(|n| n.as_str() == prefix))
666            }) {
667                // The dotted-key form: `name.path = ".."` / `name.version =
668                // ".."` as two separate lines directly under
669                // `[workspace.dependencies]`, with no inline table and no
670                // `[workspace.dependencies.name]` sub-header either.
671                if let Some(rewritten_line) = rewrite_quoted_field(line, "version", new_version) {
672                    rewritten.insert(name.clone());
673                    out.push_str(&rewritten_line);
674                    continue;
675                }
676            }
677        } else if let Some(table_name) = &in_named_table {
678            if key == Some("version") && names.iter().any(|n| n == table_name) {
679                if let Some(rewritten_line) = rewrite_quoted_field(line, "version", new_version) {
680                    rewritten.insert(table_name.clone());
681                    out.push_str(&rewritten_line);
682                    continue;
683                }
684            }
685        }
686
687        out.push_str(line);
688    }
689
690    for name in names {
691        if !rewritten.contains(name) {
692            bail!(
693                "could not rewrite the `[workspace.dependencies]` version pin \
694                 for `{name}` - its `version` field was not found in a shape \
695                 this rewrite understands"
696            );
697        }
698    }
699    Ok(out)
700}
701
702/// Confirm every entry in `names` now reads `new_version` under
703/// `[workspace.dependencies]`, by reparsing the rewritten manifest rather
704/// than trusting the line-based rewrite's own bookkeeping. The safety net
705/// this run-time failure on the pending release bump is guarding against
706/// happened once already: `kanadehq/kanade`'s pin was left stale and its own
707/// `internal_pins_match_the_workspace_version` regression test caught it in
708/// CI, after the bump pull request had already opened.
709fn verify_pins_rewritten(toml: &str, names: &[String], new_version: &str) -> Result<()> {
710    let fragment = extract_workspace_dependencies_fragment(toml);
711    let value: toml::Value = toml::from_str(&fragment)
712        .context("rewritten `[workspace.dependencies]` failed to parse")?;
713    let deps = value.get("dependencies").and_then(|d| d.as_table());
714    for name in names {
715        let actual = deps
716            .and_then(|d| d.get(name))
717            .and_then(|dep| dep.as_table())
718            .and_then(|t| t.get("version"))
719            .and_then(|v| v.as_str());
720        if actual != Some(new_version) {
721            bail!(
722                "the `[workspace.dependencies]` version pin for `{name}` did \
723                 not end up at `{new_version}` after the rewrite"
724            );
725        }
726    }
727    Ok(())
728}
729
730/// Rewrite the release version, wherever this manifest actually declares it.
731///
732/// A single crate carries its version under `[package]`. A workspace root
733/// with no crate of its own - `[workspace] members = [...]` and nothing
734/// else - carries it under `[workspace.package]` instead, and `[package]`
735/// does not exist there at all. `[package]` is tried first because it is the
736/// far more common shape and the one every existing bump so far has hit;
737/// `[workspace.package]` is the fallback for the shape that never worked
738/// before this.
739///
740/// A workspace manifest can also carry a *second*, independent version
741/// literal per internal member: `[workspace.dependencies].<name>` entries
742/// that reference a published member by both `path` and `version`, exactly
743/// the shape `AGENTS.md` documents as the canonical place to centralize that
744/// pin. Cargo does not derive that literal from `[workspace.package]
745/// version` - nothing does - so once the table version is rewritten, every
746/// such pin is rewritten to match in the same edit, and the result is
747/// reparsed to confirm it before this function returns. An entry with only
748/// `path` (an unpublished workspace-only member) or only `version` (an
749/// external dependency) is left untouched, as is a plain single-crate
750/// manifest with no `[workspace.dependencies]` table at all.
751pub fn rewrite_cargo_version(toml: &str, new_version: &str) -> Result<String> {
752    let rewritten = rewrite_table_version(toml, "[package]", new_version)
753        .or_else(|_| rewrite_table_version(toml, "[workspace.package]", new_version))
754        .context("no `version` field found under `[package]` or `[workspace.package]`")?;
755
756    let pin_names = internal_pin_names(&rewritten)?;
757    if pin_names.is_empty() {
758        return Ok(rewritten);
759    }
760
761    let rewritten = rewrite_workspace_dependency_pins(&rewritten, &pin_names, new_version)?;
762    verify_pins_rewritten(&rewritten, &pin_names, new_version)?;
763    Ok(rewritten)
764}
765
766/// Find `table`'s `version` field, if it has one. No I/O.
767fn version_in_table(toml: &str, table: &str) -> Option<String> {
768    let mut in_table = false;
769    for line in toml.lines() {
770        let trimmed = line.trim();
771        if trimmed.starts_with('[') {
772            in_table = trimmed == table;
773            continue;
774        }
775        if !in_table {
776            continue;
777        }
778        let mut parts = trimmed.splitn(2, '=');
779        let key = parts.next().map(str::trim);
780        let Some(value) = parts.next() else {
781            continue;
782        };
783        if key == Some("version") {
784            return Some(value.trim().trim_matches('"').to_owned());
785        }
786    }
787    None
788}
789
790/// Read the version currently on the base branch, from `[package]` if it has
791/// one, else from `[workspace.package]` - see [`rewrite_cargo_version`] for
792/// why both exist and which wins. No I/O: the caller fetches the blob (`git
793/// show <remote>/<base>:Cargo.toml`).
794pub(crate) fn current_version(toml: &str) -> Result<String> {
795    version_in_table(toml, "[package]")
796        .or_else(|| version_in_table(toml, "[workspace.package]"))
797        .context("no `version` field found under `[package]` or `[workspace.package]`")
798}
799
800/// The version a release pull request really carries: the manifest on its head
801/// branch (an escalation rewrites it but keeps the branch name), falling back
802/// to the branch name only when the manifest cannot be read.
803async fn branch_version(repo: &Path, remote: &str, branch: &str, primary: &str) -> Option<String> {
804    let from_name = branch.strip_prefix("chore/release-v").map(str::to_owned);
805    // A tracking ref of its own: FETCH_HEAD is shared with every other fetch in
806    // this repository (the release watcher runs them concurrently).
807    let tracking = format!("refs/remotes/{remote}/{branch}");
808    let spec = format!("+refs/heads/{branch}:{tracking}");
809    let fetched = git::git_raw(repo, &["fetch", "--quiet", remote, &spec]).await;
810    if fetched.is_ok_and(|o| o.code == Some(0))
811        && let Ok(out) = git::git_raw(repo, &["show", &format!("{tracking}:{primary}")]).await
812        && out.code == Some(0)
813        && let Ok(v) = current_version(&out.stdout)
814    {
815        return Some(v);
816    }
817    from_name
818}
819
820/// Build the prompt asking an agent which digit of `major.minor.patch` a
821/// merged change earns.
822///
823/// Pure: every input is already known once a merge lands, so the whole
824/// decision policy - the "`minor` is the breaking digit below `1.0.0`" rule,
825/// what counts as a breaking surface, and the tie-break toward the larger
826/// digit - is asserted directly on the returned string, the same way
827/// [`crate::land::fix_prompt`] doc-comments its own rules rather than leaving
828/// them for a human to spot missing from a live reply.
829pub fn decision_prompt(
830    subject: &str,
831    instruction: &str,
832    diffstat: &str,
833    files: &[String],
834    current_version: &str,
835) -> String {
836    let mut s = format!(
837        "A pull request just merged into the base branch. Decide which digit \
838         of this project's `major.minor.patch` version this change earns, so \
839         a release bump can be opened for exactly it.\n\n\
840         Current version: {current_version}\n\n\
841         # Merge subject\n\n{subject}\n\n\
842         # The task that produced it\n\n{instruction}\n\n\
843         # Files changed ({} total)\n\n",
844        files.len()
845    );
846    const MAX_FILES: usize = 50;
847    for f in files.iter().take(MAX_FILES) {
848        let _ = writeln!(s, "- {f}");
849    }
850    if files.len() > MAX_FILES {
851        let _ = writeln!(s, "- ... and {} more", files.len() - MAX_FILES);
852    }
853    let _ = write!(s, "\n# Diffstat\n\n```\n{}\n```\n", diffstat.trim());
854
855    s.push_str(
856        "\n# How to decide\n\n\
857         This project is below version `1.0.0`. At that stage **`minor` is \
858         the digit that carries a breaking change** - do not spend `major` \
859         below `1.0.0`.\n\n\
860         A change is breaking, and earns `minor`, when it changes any of: \
861         the public API reachable from `src/lib.rs`, a CLI subcommand or \
862         flag, an HTTP API route or response shape, a configuration key, or \
863         the on-disk shape of persisted state.\n\n\
864         A user-visible new capability that breaks none of the above also \
865         earns `minor`.\n\n\
866         A fix, an internal refactor, or a dependency update earns `patch`.\n\n\
867         **When it is not obvious which digit applies, choose the larger \
868         one.** An oversized bump costs nothing; a breaking change shipped as \
869         `patch` breaks every downstream update that pins a range.\n\n\
870         # Output\n\n\
871         Reply with exactly one fenced JSON object and nothing that matters \
872         outside it:\n\n\
873         ```json\n\
874         {\"level\": \"major\" | \"minor\" | \"patch\", \"reason\": \"one line\"}\n\
875         ```\n",
876    );
877    // The reason is pasted into the release pull request's body.
878    let _ = write!(
879        s,
880        "\n{}\n\nThe `reason` goes into a GitHub pull request body, so write it \
881         in English.\n",
882        crate::prompt::GITHUB_ENGLISH_HEADING
883    );
884    s
885}
886
887/// magi's own record of a bump pull request it currently has open, so a
888/// burst of merges in quick succession does not each open a competing
889/// release.
890///
891/// **Chosen policy: serialize, not coalesce two independent decisions into
892/// one.** A bump branch touches only `Cargo.toml` / `Cargo.lock`, so `gh pr
893/// merge --squash` applies it onto whatever the base branch has become by
894/// the time it lands - every commit merged while it was open rides along
895/// for free, at no extra cost, once it merges. But the *digit* a still-open
896/// pull request targets was judged from only the first change, and a more
897/// severe change landing while it waits must not ship at the smaller digit
898/// just because it arrived second - so the serialization is at the pull
899/// request, not at the judgement: a later, more severe decision escalates
900/// the same open pull request (see [`pending_action`]) rather than opening a
901/// second one or being silently absorbed at the wrong digit.
902#[derive(Debug, Clone, Serialize, Deserialize)]
903pub struct PendingBump {
904    /// The version the open pull request bumps to.
905    pub target_version: String,
906    /// The digit that version was judged to need, so a later, more severe
907    /// merge can tell it needs to escalate rather than assume it is covered.
908    pub level: BumpLevel,
909    /// The branch the open pull request is built from, so an escalation
910    /// knows what to check out and push to.
911    pub branch: String,
912    /// The pull request's URL, so a later merge can confirm it is still
913    /// open before trusting it to block a fresh decision.
914    pub pr_url: String,
915}
916
917/// Where [`PendingBump`] is recorded for `repo` - one file per repository, so
918/// a machine running magi against more than one checkout does not confuse
919/// their releases with each other.
920pub fn marker_path(home: &Path, repo: &Path) -> PathBuf {
921    let key = repo.to_string_lossy();
922    home.join("bump")
923        .join(format!("{:016x}.json", crate::rng::fnv1a(&key)))
924}
925
926/// Read a recorded [`PendingBump`], if any. Missing or unreadable both read
927/// as "nothing pending" - a marker is bookkeeping, not a source of truth
928/// worth failing a merge over.
929pub fn read_marker(path: &Path) -> Option<PendingBump> {
930    let body = std::fs::read_to_string(path).ok()?;
931    serde_json::from_str(&body).ok()
932}
933
934/// Persist `marker`, atomically - the same tmp-then-rename shape
935/// [`crate::updater::write_progress`] uses, since this file is read by a
936/// later, unrelated process invocation and must never be seen half-written.
937pub fn write_marker(path: &Path, marker: &PendingBump) -> Result<()> {
938    if let Some(parent) = path.parent() {
939        std::fs::create_dir_all(parent).with_context(|| format!("create {}", parent.display()))?;
940    }
941    let body = serde_json::to_string_pretty(marker).context("serialize pending bump")?;
942    let tmp = path.with_extension("json.tmp");
943    std::fs::write(&tmp, &body).with_context(|| format!("write {}", tmp.display()))?;
944    std::fs::rename(&tmp, path).with_context(|| format!("replace {}", path.display()))?;
945    Ok(())
946}
947
948/// Drop a recorded marker. Best-effort: a marker that is already gone is not
949/// an error.
950pub fn clear_marker(path: &Path) {
951    let _ = std::fs::remove_file(path);
952}
953
954/// What a recorded [`PendingBump`] means for a fresh decision, given what the
955/// base branch's `Cargo.toml` says right now. No I/O: the caller reads both
956/// the marker and the version.
957#[derive(Debug, Clone, PartialEq, Eq)]
958pub enum Coalesce {
959    /// Nothing is pending, or the pending bump already landed (or was
960    /// superseded by a manual one) - safe to open a fresh decision.
961    Proceed,
962    /// A bump to `target_version` is already open; do not open a second one.
963    Skip {
964        /// The version the pending pull request already targets.
965        target_version: String,
966    },
967}
968
969/// Decide what a pending marker means against `current_version`.
970pub fn coalesce(pending: Option<&PendingBump>, current_version: &str) -> Result<Coalesce> {
971    let Some(pending) = pending else {
972        return Ok(Coalesce::Proceed);
973    };
974    let current = Version::parse(current_version)?;
975    let target = Version::parse(&pending.target_version)?;
976    if current >= target {
977        return Ok(Coalesce::Proceed);
978    }
979    Ok(Coalesce::Skip {
980        target_version: pending.target_version.clone(),
981    })
982}
983
984/// What a still-open pending bump means once a fresh decision is in hand.
985#[derive(Debug, Clone, Copy, PartialEq, Eq)]
986pub enum PendingAction {
987    /// The new decision is no more severe than what is already queued; the
988    /// open pull request covers it once it lands.
989    AlreadyCovered,
990    /// The new decision outranks the pending target - escalate the open
991    /// pull request instead of opening a second one or dropping it.
992    Escalate,
993}
994
995/// Compare a fresh decision against what a still-open pull request already
996/// targets.
997///
998/// A patch bump left pending while a breaking change lands does not become a
999/// breaking release just because the pull request that carries both is
1000/// squashed into one commit: the *version number* still comes from whichever
1001/// digit was judged, and a pending `patch` never widens itself to `minor` on
1002/// its own. This is the check that decides an escalation is owed.
1003pub fn pending_action(pending_level: BumpLevel, decision_level: BumpLevel) -> PendingAction {
1004    if decision_level.severity() > pending_level.severity() {
1005        PendingAction::Escalate
1006    } else {
1007        PendingAction::AlreadyCovered
1008    }
1009}
1010
1011/// Parse `gh pr view --json state` output. No I/O.
1012fn parse_pr_state(json: &str) -> Result<bool> {
1013    #[derive(Deserialize)]
1014    struct State {
1015        state: String,
1016    }
1017    let parsed: State =
1018        serde_json::from_str(json).context("parse `gh pr view --json state` output")?;
1019    Ok(parsed.state.eq_ignore_ascii_case("OPEN"))
1020}
1021
1022/// Is the pull request at `pr_url` still open?
1023///
1024/// Read fresh rather than trusted from the marker: a bump pull request can be
1025/// closed without merging - CI that never goes green, an operator who
1026/// decided against it - and nothing else in this module ever revisits a
1027/// marker once it is written. Without this check, that close is invisible
1028/// here forever: the marker still names a pending target, the base branch
1029/// never reaches it because nothing ever merged the pull request, and every
1030/// later merge skips in perpetuity. A `gh` failure (network, auth) answers
1031/// `true` - the same "unreadable is not absent" rule `land::CHECKS_GRACE`
1032/// uses - because guessing "closed" wrongly opens a second, competing pull
1033/// request, while guessing "open" wrongly only costs one more merge's wait.
1034async fn pr_is_open(repo: &Path, pr_url: &str) -> Result<bool> {
1035    let out = tokio::process::Command::new("gh")
1036        .args(["pr", "view", pr_url, "--json", "state"])
1037        .current_dir(repo)
1038        .quiet()
1039        .stdin(std::process::Stdio::null())
1040        .output()
1041        .await
1042        .context("spawn gh pr view")?;
1043    if !out.status.success() {
1044        bail!(
1045            "gh pr view {pr_url}: {}",
1046            String::from_utf8_lossy(&out.stderr).trim()
1047        );
1048    }
1049    parse_pr_state(&String::from_utf8_lossy(&out.stdout))
1050}
1051
1052/// How long a stale lock file is trusted to mean its owner is still working,
1053/// before it is reclaimed.
1054///
1055/// Long enough to cover the slowest real step this module takes - the agent
1056/// decision call ([`DECISION_TIMEOUT`]) plus `cargo build` and a `gh pr
1057/// create` - so a lock is only ever stolen from a process that has actually
1058/// gone (crashed, killed), never one still inside its own critical section.
1059const LOCK_STALE_AFTER: Duration = Duration::from_secs(30 * 60);
1060
1061/// A host-local mutual exclusion for one repository's marker file.
1062///
1063/// Built on exclusive file creation rather than a locking crate: neither
1064/// `flock` nor `fs2` is a dependency of this crate, and the constraints on
1065/// this change forbid adding one. This is not a distributed lock and does
1066/// not coordinate two machines racing the same repository - it exists to
1067/// close the specific race two `after_merge` calls on the *same* host can
1068/// hit landing within the same window (a human `magi run` alongside the
1069/// daemon, or two review loops): both would otherwise read "nothing
1070/// pending", judge independently, and open two competing pull requests, with
1071/// whichever `write_marker` runs last silently erasing the other's record.
1072struct MarkerLock {
1073    path: PathBuf,
1074}
1075
1076impl MarkerLock {
1077    /// Try to take the lock for `marker`, stealing a stale one first if it is
1078    /// old enough to mean its owner is gone rather than merely slow.
1079    /// `Ok(None)` means someone else genuinely holds it right now.
1080    #[cfg(test)]
1081    fn acquire(marker: &Path) -> Result<Option<Self>> {
1082        Self::acquire_with(marker, crate::lock_file::Retry::new(None))
1083    }
1084
1085    fn acquire_with(marker: &Path, retry: crate::lock_file::Retry) -> Result<Option<Self>> {
1086        let path = marker.with_extension("lock");
1087        if let Some(parent) = path.parent() {
1088            std::fs::create_dir_all(parent)
1089                .with_context(|| format!("create {}", parent.display()))?;
1090        }
1091        if Self::try_create(&path, retry)? {
1092            return Ok(Some(Self { path }));
1093        }
1094        if Self::is_stale(&path) {
1095            let _ = std::fs::remove_file(&path);
1096            if Self::try_create(&path, retry)? {
1097                return Ok(Some(Self { path }));
1098            }
1099        }
1100        Ok(None)
1101    }
1102
1103    fn try_create(path: &Path, retry: crate::lock_file::Retry) -> Result<bool> {
1104        match retry.create(path) {
1105            Ok(_) => Ok(true),
1106            Err(e) if e.kind() == std::io::ErrorKind::AlreadyExists => Ok(false),
1107            Err(e) => Err(e).with_context(|| format!("create {}", path.display())),
1108        }
1109    }
1110
1111    fn is_stale(path: &Path) -> bool {
1112        std::fs::metadata(path)
1113            .and_then(|m| m.modified())
1114            .ok()
1115            .and_then(|m| m.elapsed().ok())
1116            .is_some_and(|age| age >= LOCK_STALE_AFTER)
1117    }
1118}
1119
1120impl Drop for MarkerLock {
1121    fn drop(&mut self) {
1122        let _ = std::fs::remove_file(&self.path);
1123    }
1124}
1125
1126/// How often a blocked caller checks whether [`MarkerLock`] has freed up.
1127const LOCK_POLL: Duration = Duration::from_secs(5);
1128
1129/// How long a caller waits for a contended lock before giving up on this
1130/// merge's own judgement entirely.
1131///
1132/// A first version of this gate gave up the instant the lock was taken,
1133/// which meant a change landing while another host's decision call was
1134/// still running was never judged at all - not even recorded as pending,
1135/// not escalated later, just dropped. The lock is only ever held for one
1136/// `after_merge` call, so waiting past it is what lets that call's own
1137/// decision reach [`pending_action`] against a marker the other side just
1138/// finished writing, instead of finding nothing to check against. Set just
1139/// under [`LOCK_STALE_AFTER`]: a lock still held this long after that point
1140/// is reclaimed as abandoned rather than waited on further.
1141const LOCK_WAIT_CEILING: Duration = Duration::from_secs(25 * 60);
1142
1143/// Wait for [`MarkerLock`] to free up, polling rather than blocking forever.
1144/// `Ok(None)` means the ceiling passed with the lock still held.
1145async fn wait_for_marker_lock(marker: &Path) -> Result<Option<MarkerLock>> {
1146    wait_for_marker_lock_with(marker, LOCK_POLL, LOCK_WAIT_CEILING).await
1147}
1148
1149/// [`wait_for_marker_lock`] with the poll interval and ceiling as parameters,
1150/// so the retry behaviour is testable without a test actually waiting out
1151/// [`LOCK_WAIT_CEILING`].
1152async fn wait_for_marker_lock_with(
1153    marker: &Path,
1154    poll: Duration,
1155    ceiling: Duration,
1156) -> Result<Option<MarkerLock>> {
1157    let deadline = std::time::Instant::now() + ceiling;
1158    let retry = crate::lock_file::Retry::new(Some(deadline));
1159    loop {
1160        // Delete-pending retries must not block the async executor.
1161        let marker = marker.to_owned();
1162        let acquired =
1163            tokio::task::spawn_blocking(move || MarkerLock::acquire_with(&marker, retry))
1164                .await
1165                .context("join marker lock acquisition")??;
1166        if let Some(lock) = acquired {
1167            return Ok(Some(lock));
1168        }
1169        let remaining = deadline.saturating_duration_since(std::time::Instant::now());
1170        if remaining.is_zero() {
1171            return Ok(None);
1172        }
1173        tokio::time::sleep(poll.min(remaining)).await;
1174    }
1175}
1176
1177/// Which digit differs between `from` and `to`? `None` when they are equal.
1178///
1179/// Used to recover the level a pull request found by [`find_open_release_pr`]
1180/// was judged at: the forge has the resulting version (in the branch name and
1181/// the title) but not the digit an agent chose to get there, and this is the
1182/// one other host-independent fact every host can compute the same way from
1183/// it.
1184fn level_between(from: Version, to: Version) -> Option<BumpLevel> {
1185    if to.major != from.major {
1186        Some(BumpLevel::Major)
1187    } else if to.minor != from.minor {
1188        Some(BumpLevel::Minor)
1189    } else if to.patch != from.patch {
1190        Some(BumpLevel::Patch)
1191    } else {
1192        None
1193    }
1194}
1195
1196/// Parse `gh pr list --state open --json url,headRefName` output, returning
1197/// the first pull request whose branch is one of this module's own. No I/O.
1198fn parse_open_release_pr(json: &str) -> Result<Option<(String, String)>> {
1199    #[derive(Deserialize)]
1200    struct Pr {
1201        url: String,
1202        #[serde(rename = "headRefName")]
1203        head_ref_name: String,
1204    }
1205    let list: Vec<Pr> =
1206        serde_json::from_str(json).context("parse `gh pr list --json url,headRefName` output")?;
1207    Ok(list
1208        .into_iter()
1209        .find(|p| p.head_ref_name.starts_with("chore/release-v"))
1210        .map(|p| (p.head_ref_name, p.url)))
1211}
1212
1213/// Every open pull request on one of this module's own branches, as
1214/// `(branch, url)`. No I/O.
1215pub(crate) fn parse_open_release_prs(json: &str) -> Result<Vec<(String, String)>> {
1216    #[derive(Deserialize)]
1217    struct Pr {
1218        url: String,
1219        #[serde(rename = "headRefName")]
1220        head_ref_name: String,
1221    }
1222    let list: Vec<Pr> =
1223        serde_json::from_str(json).context("parse `gh pr list --json url,headRefName` output")?;
1224    Ok(list
1225        .into_iter()
1226        .filter(|p| p.head_ref_name.starts_with("chore/release-v"))
1227        .map(|p| (p.head_ref_name, p.url))
1228        .collect())
1229}
1230
1231/// [`find_open_release_pr`], but every match rather than the first.
1232pub(crate) async fn list_open_release_prs(repo: &Path) -> Result<Vec<(String, String)>> {
1233    let out = tokio::process::Command::new("gh")
1234        .args([
1235            "pr",
1236            "list",
1237            "--state",
1238            "open",
1239            "--limit",
1240            "100",
1241            "--json",
1242            "url,headRefName",
1243        ])
1244        .current_dir(repo)
1245        .env_remove("GH_REPO")
1246        .quiet()
1247        .stdin(std::process::Stdio::null())
1248        .output()
1249        .await
1250        .context("spawn gh pr list")?;
1251    if !out.status.success() {
1252        bail!(
1253            "gh pr list: {}",
1254            String::from_utf8_lossy(&out.stderr).trim()
1255        );
1256    }
1257    parse_open_release_prs(&String::from_utf8_lossy(&out.stdout))
1258}
1259
1260/// Ask the forge directly whether a release bump is already open, for a host
1261/// that has never seen it.
1262///
1263/// [`MarkerLock`] and the marker file only ever coordinate *this* host - a
1264/// marker written on one machine is not visible to `run::home()` on another,
1265/// so two hosts landing runs against the same repository at the same time
1266/// can each read "nothing pending" and open a competing pull request no
1267/// local lock can see. `gh pr list` is the one place every host actually
1268/// shares a view, so it is consulted whenever this host's own marker says
1269/// there is nothing pending, before a fresh decision is allowed to open a
1270/// second pull request. This narrows the race to the gap between this call
1271/// and whichever host's `gh pr create` lands first - it does not close it -
1272/// because turning that into a real distributed lock would need coordination
1273/// this crate has no dependency for.
1274async fn find_open_release_pr(repo: &Path) -> Result<Option<(String, String)>> {
1275    let out = tokio::process::Command::new("gh")
1276        .args(["pr", "list", "--state", "open", "--json", "url,headRefName"])
1277        .current_dir(repo)
1278        .quiet()
1279        .stdin(std::process::Stdio::null())
1280        .output()
1281        .await
1282        .context("spawn gh pr list")?;
1283    if !out.status.success() {
1284        bail!(
1285            "gh pr list: {}",
1286            String::from_utf8_lossy(&out.stderr).trim()
1287        );
1288    }
1289    parse_open_release_pr(&String::from_utf8_lossy(&out.stdout))
1290}
1291
1292/// After a merge lands, ask an agent how big the change was and open a
1293/// release bump sized to it.
1294///
1295/// Best-effort by construction, the same way `clean::fold_due` treats one
1296/// run's fold failure: this runs after the merge the run exists to produce
1297/// has already succeeded, so a failure here (the decision call, `gh`,
1298/// `cargo`) must never turn a landed run into a failed one. The caller logs
1299/// whatever this returns and moves on.
1300///
1301/// An `Err` is a bump that was tried and failed, never one that was not
1302/// eligible (every such case returns `Ok` after an event). When it fails
1303/// before any release pull request exists, the operator is notified here, so
1304/// the caller only has to record the event: nobody would otherwise learn that
1305/// a release silently never happened. A failure with a pull request in hand
1306/// goes through [`report_problem`] with its URL instead, and is not repeated.
1307/// A failure while a pending release pull request is in play (the decision or
1308/// an escalation of it) is notified here too, naming that pull request: the
1309/// escalation path itself never raises one, so suppressing it would leave the
1310/// operator with nothing.
1311pub async fn after_merge(state: &mut RunState, pr_url: &str) -> Result<()> {
1312    after_merge_at(state, pr_url, None, None).await
1313}
1314
1315/// What one attempt had settled by the time it failed.
1316#[derive(Debug, Default)]
1317struct Progress {
1318    /// The target version, once the decision had been made.
1319    version: Option<String>,
1320    /// A release pull request already pending when this attempt started.
1321    pending_pr: Option<String>,
1322    /// Why the bump was deliberately not made.
1323    skip: Option<Skip>,
1324}
1325
1326/// A bump that was deliberately not made. Recorded on the run so it can never
1327/// read as a completed release.
1328#[derive(Debug)]
1329struct Skip {
1330    /// Why, in one line.
1331    reason: String,
1332    /// What the owner has to do, when the skip needs them (this also raises a
1333    /// notice).
1334    action: Option<String>,
1335}
1336
1337/// Record a skip on the run, and page the owner when it needs them.
1338fn record_skip(state: &mut RunState, store: Option<&Notices>, skip: &Skip) {
1339    let record = state.release_bump.get_or_insert_with(Default::default);
1340    record.skipped = Some(skip.reason.clone());
1341    let Some(action) = &skip.action else {
1342        return;
1343    };
1344    record.action_required = Some(action.clone());
1345    let notice = Notice::error(
1346        &format!("release-bump:{}", state.id),
1347        format!(
1348            "Run {} merged, but its release bump was skipped: {action}.",
1349            state.id
1350        ),
1351    )
1352    .link(Link::Run {
1353        id: state.id.clone(),
1354    });
1355    let store = store.cloned().unwrap_or_else(Notices::open);
1356    if let Err(e) = store.raise_with(notice, &state.config.notify) {
1357        state.event("bump", format!("could not raise a notice: {e:#}"));
1358    }
1359    state.event("bump", format!("needs attention: {action}"));
1360}
1361
1362/// The `(version, reason)` to notify with for a failed attempt. Preserve the
1363/// complete error chain, including Git's full stderr, in the run record.
1364/// A pull request this attempt opened never reaches here: past
1365/// `gh pr create` nothing returns `Err`, and automerge trouble goes through
1366/// [`report_problem`] itself.
1367fn notice_for_failure(progress: &Progress, err: &anyhow::Error) -> (Option<String>, String) {
1368    (progress.version.clone(), format!("{err:#}"))
1369}
1370
1371/// Prefer Git's actual failure over a preceding progress line for short notices.
1372fn failure_headline(reason: &str) -> Option<&str> {
1373    let lines = || {
1374        reason
1375            .lines()
1376            .map(str::trim)
1377            .filter(|line| !line.is_empty())
1378    };
1379    lines()
1380        .find(|line| line.starts_with("fatal:") || line.starts_with("error:"))
1381        .or_else(|| lines().next())
1382}
1383
1384/// Does the base branch carry a `Cargo.toml` at its root? Release bumps read
1385/// and rewrite that file, so its absence means "not a Rust repository", which
1386/// is not a fault. `ls-tree` rather than `cat-file -e`, so an unresolvable
1387/// ref (a failed fetch, a misconfigured base) stays an error instead of being
1388/// reported as a non-Rust repository.
1389#[cfg(test)]
1390async fn base_has_cargo_toml(repo: &Path, remote: &str, base: &str) -> Result<bool> {
1391    base_has_file(repo, remote, base, release_manifest::DEFAULT_PRIMARY).await
1392}
1393
1394/// [`base_has_cargo_toml`] for any repository-relative path.
1395async fn base_has_file(repo: &Path, remote: &str, base: &str, path: &str) -> Result<bool> {
1396    let out = git::git(
1397        repo,
1398        &[
1399            "ls-tree",
1400            "--name-only",
1401            &format!("{remote}/{base}"),
1402            "--",
1403            path,
1404        ],
1405    )
1406    .await
1407    .with_context(|| format!("look for {path} on the base branch"))?;
1408    Ok(!out.trim().is_empty())
1409}
1410
1411/// Immutable evidence for one merged PR. File/stat evidence comes from the
1412/// complete PR file listing, not a local or remote branch that can move.
1413#[derive(Debug)]
1414struct MergedChange {
1415    files: Vec<String>,
1416    stat: String,
1417    merge: String,
1418    numstat: Vec<(String, Option<String>, u64, u64)>,
1419}
1420
1421#[derive(Deserialize)]
1422struct PrFile {
1423    filename: String,
1424    previous_filename: Option<String>,
1425    additions: u64,
1426    deletions: u64,
1427}
1428
1429/// GitHub may truncate a PR file listing at this boundary.
1430const PR_FILES_CEILING: usize = 3000;
1431
1432fn merged_change_from_pages(
1433    merge: String,
1434    expected: usize,
1435    pages: Vec<Vec<PrFile>>,
1436) -> Result<MergedChange> {
1437    anyhow::ensure!(
1438        merge.len() == 40 && merge.bytes().all(|b| b.is_ascii_hexdigit()),
1439        "merged PR has no valid merge commit"
1440    );
1441    let entries: Vec<_> = pages.into_iter().flatten().collect();
1442    anyhow::ensure!(
1443        expected < PR_FILES_CEILING && entries.len() < PR_FILES_CEILING,
1444        "merged PR file listing reached the 3000-file limit and may be truncated"
1445    );
1446    let mut seen = std::collections::HashSet::new();
1447    anyhow::ensure!(
1448        expected > 0
1449            && entries.len() == expected
1450            && entries.iter().all(|f| seen.insert(&f.filename)),
1451        "merged PR file listing is empty, incomplete or duplicated"
1452    );
1453    let mut files = Vec::new();
1454    let mut stat = String::new();
1455    let (mut added, mut removed) = (0_u64, 0_u64);
1456    let mut numstat: Vec<_> = entries
1457        .iter()
1458        .map(|f| {
1459            (
1460                f.filename.clone(),
1461                f.previous_filename.clone(),
1462                f.additions,
1463                f.deletions,
1464            )
1465        })
1466        .collect();
1467    numstat.sort();
1468    for file in entries {
1469        added = added
1470            .checked_add(file.additions)
1471            .context("PR additions overflow")?;
1472        removed = removed
1473            .checked_add(file.deletions)
1474            .context("PR deletions overflow")?;
1475        writeln!(
1476            stat,
1477            " {} | +{} -{}",
1478            file.filename, file.additions, file.deletions
1479        )?;
1480        // A rename out of a source path is not a release-only change.
1481        if let Some(previous) = file.previous_filename
1482            && !files.contains(&previous)
1483        {
1484            files.push(previous);
1485        }
1486        if !files.contains(&file.filename) {
1487            files.push(file.filename);
1488        }
1489    }
1490    writeln!(
1491        stat,
1492        " {expected} files changed, {added} insertions(+), {removed} deletions(-)"
1493    )?;
1494    Ok(MergedChange {
1495        files,
1496        stat,
1497        merge,
1498        numstat,
1499    })
1500}
1501
1502async fn merged_change(repo: &Path, pr_url: &str) -> Result<MergedChange> {
1503    let out = merged_pr_json(
1504        repo,
1505        &[
1506            "pr",
1507            "view",
1508            pr_url,
1509            "--json",
1510            "state,mergeCommit,changedFiles,number,url",
1511        ],
1512    )
1513    .await?;
1514    let (merge, expected, endpoint) = merged_pr_metadata(&out)?;
1515    let out = merged_pr_json(repo, &["api", "--paginate", "--slurp", &endpoint]).await?;
1516    parse_merged_pr_files(merge, expected, &out)
1517}
1518
1519async fn merged_pr_json(repo: &Path, args: &[&str]) -> Result<String> {
1520    let out = tokio::process::Command::new("gh")
1521        .args(args)
1522        .current_dir(repo)
1523        .env_remove("GH_REPO")
1524        .quiet()
1525        .stdin(std::process::Stdio::null())
1526        .output()
1527        .await
1528        .context("read merged PR evidence")?;
1529    anyhow::ensure!(
1530        out.status.success(),
1531        "read merged PR evidence: {}",
1532        String::from_utf8_lossy(&out.stderr).trim()
1533    );
1534    String::from_utf8(out.stdout).context("merged PR evidence is not UTF-8")
1535}
1536
1537/// Decode forge metadata and build the canonical file endpoint. No I/O.
1538fn merged_pr_metadata(json: &str) -> Result<(String, usize, String)> {
1539    let metadata: serde_json::Value = serde_json::from_str(json)?;
1540    anyhow::ensure!(metadata["state"] == "MERGED", "PR is not confirmed merged");
1541    let merge = metadata["mergeCommit"]["oid"]
1542        .as_str()
1543        .context("merged PR has no merge commit")?
1544        .to_owned();
1545    let expected = metadata["changedFiles"]
1546        .as_u64()
1547        .and_then(|n| usize::try_from(n).ok())
1548        .context("PR has no file count")?;
1549    // Use the forge's canonical URL, including the repository for fork PRs.
1550    let url = metadata["url"]
1551        .as_str()
1552        .context("PR has no canonical URL")?;
1553    let parts: Vec<_> = url.split('/').collect();
1554    anyhow::ensure!(
1555        parts.len() == 7
1556            && parts[5] == "pull"
1557            && parts[6].parse::<u64>().ok() == metadata["number"].as_u64(),
1558        "unrecognized PR URL"
1559    );
1560    let endpoint = format!(
1561        "repos/{}/{}/pulls/{}/files?per_page=100",
1562        parts[3], parts[4], parts[6]
1563    );
1564    Ok((merge, expected, endpoint))
1565}
1566
1567/// Decode `gh api --paginate --slurp` output. No I/O.
1568fn parse_merged_pr_files(merge: String, expected: usize, json: &str) -> Result<MergedChange> {
1569    merged_change_from_pages(merge, expected, serde_json::from_str(json)?)
1570}
1571
1572/// Compare versions only across the forge-confirmed merge and its first
1573/// parent. Neither the winner's ancestry nor a current merge-base proves
1574/// which upstream version the PR actually changed.
1575async fn merged_versions(
1576    repo: &Path,
1577    change: &MergedChange,
1578    primary: &str,
1579) -> Result<(String, String)> {
1580    let before = git::rev_parse(repo, &format!("{}^1", change.merge))
1581        .await
1582        .context("read merged PR's first parent")?;
1583    // In particular, the final commit of a multi-commit rebase merge may not
1584    // represent the whole PR. Refuse a mismatched range rather than guessing.
1585    let raw = git::git(
1586        repo,
1587        &[
1588            "diff",
1589            "--numstat",
1590            "-z",
1591            "--find-renames=50%",
1592            &before,
1593            &change.merge,
1594        ],
1595    )
1596    .await?;
1597    let mut actual = Vec::new();
1598    let mut entries = raw.split_terminator('\0');
1599    while let Some(entry) = entries.next() {
1600        let mut fields = entry.splitn(3, '\t');
1601        let count = |field: Option<&str>| -> Result<u64> {
1602            let field = field.context("missing merged diff count")?;
1603            if field == "-" {
1604                Ok(0)
1605            } else {
1606                Ok(field.parse()?)
1607            }
1608        };
1609        let additions = count(fields.next())?;
1610        let deletions = count(fields.next())?;
1611        let path = fields.next().context("missing merged diff path")?;
1612        let (path, previous) = if path.is_empty() {
1613            // With -z, rename records carry two separate NUL-delimited paths.
1614            let previous = entries.next().context("missing rename source")?;
1615            let path = entries.next().context("missing rename destination")?;
1616            anyhow::ensure!(
1617                !previous.is_empty() && !path.is_empty(),
1618                "empty rename path"
1619            );
1620            (path, Some(previous.to_owned()))
1621        } else {
1622            (path, None)
1623        };
1624        actual.push((path.to_owned(), previous, additions, deletions));
1625    }
1626    actual.sort();
1627    anyhow::ensure!(
1628        actual == change.numstat,
1629        "merge first-parent diff does not match the complete PR; version comparison is unknown"
1630    );
1631    let before = primary_version_at(repo, &before, primary)
1632        .await
1633        .context("read version before merged PR")?;
1634    let after = primary_version_at(repo, &change.merge, primary)
1635        .await
1636        .context("read version after merged PR")?;
1637    Ok((before, after))
1638}
1639
1640/// The version of record's version at `rev`, read in `dir`. `None` when it
1641/// cannot be read (unknown, never "unchanged").
1642async fn primary_version_at(dir: &Path, rev: &str, path: &str) -> Option<String> {
1643    let out = git::git_raw(dir, &["show", &format!("{rev}:{path}")])
1644        .await
1645        .ok()?;
1646    if out.code != Some(0) {
1647        return None;
1648    }
1649    current_version(&out.stdout).ok()
1650}
1651
1652/// [`after_merge`] with an optional magi home, so tests can point the
1653/// marker and its lock at a scratch directory.
1654/// `store` is where a notice is raised; `None` is the operator's own.
1655async fn after_merge_at(
1656    state: &mut RunState,
1657    pr_url: &str,
1658    home: Option<&Path>,
1659    store: Option<&Notices>,
1660) -> Result<()> {
1661    let repo = state.repo.clone();
1662    after_merge_using(state, pr_url, home, store, merged_change(&repo, pr_url)).await
1663}
1664
1665async fn after_merge_using(
1666    state: &mut RunState,
1667    pr_url: &str,
1668    home: Option<&Path>,
1669    store: Option<&Notices>,
1670    change: impl Future<Output = Result<MergedChange>>,
1671) -> Result<()> {
1672    let mut progress = Progress::default();
1673    let result = after_merge_inner(state, pr_url, home, &mut progress, change).await;
1674    if let Some(skip) = &progress.skip {
1675        record_skip(state, store, skip);
1676    }
1677    if let Err(e) = &result {
1678        let (version, reason) = notice_for_failure(&progress, e);
1679        let pending = progress.pending_pr.as_deref();
1680        let store = store.cloned().unwrap_or_else(Notices::open);
1681        report_problem_in(
1682            state,
1683            &store,
1684            pending,
1685            version.as_deref(),
1686            &reason,
1687            pending.is_some(),
1688        )
1689        .await;
1690    }
1691    result
1692}
1693
1694async fn after_merge_inner(
1695    state: &mut RunState,
1696    pr_url: &str,
1697    home: Option<&Path>,
1698    progress: &mut Progress,
1699    change: impl Future<Output = Result<MergedChange>>,
1700) -> Result<()> {
1701    if !state.config.merge.release_bump {
1702        return Ok(());
1703    }
1704    if state.winner().is_none() {
1705        return Ok(());
1706    }
1707    let repo = state.repo.clone();
1708    let base = state.base_branch.clone();
1709    let remote = state.config.merge.remote.clone();
1710
1711    let declared = state.config.release.version_files.clone();
1712    let custom = release_manifest::is_custom(&declared);
1713    let primary = release_manifest::primary_path(&declared).to_owned();
1714
1715    // Outside the lock, and before anything that assumes a Rust manifest.
1716    // Fetch first so a stale remote-tracking ref cannot misjudge the base.
1717    git::fetch(&repo, &remote, &base).await.ok();
1718    if !base_has_file(&repo, &remote, &base, &primary).await? {
1719        state.event(
1720            "bump",
1721            if custom {
1722                format!(
1723                    "release bump: no {primary} on the base branch (from [release] version_files); skipping"
1724                )
1725            } else {
1726                "release bump: no Cargo.toml on the base branch; release bumps are Rust-only, skipping"
1727                    .to_owned()
1728            },
1729        );
1730        // A repository that releases from a workflow but has no manifest magi
1731        // can read is one whose release silently never happens: say so.
1732        let releases_by_workflow =
1733            base_has_file(&repo, &remote, &base, ".github/workflows/auto-tag.yml")
1734                .await
1735                .unwrap_or(false);
1736        let ja = crate::lang::is_japanese(&state.config.graph.language);
1737        let action = releases_by_workflow.then(|| {
1738            if ja {
1739                format!(
1740                    "base ブランチに {primary} がありません。auto-tag.yml があるリポジトリです。magi.toml の [release] version_files に版の正本 (auto-tag.yml が読む Cargo.toml) を指定するか、リリースを手で行ってください"
1741                )
1742            } else {
1743                format!(
1744                    "the base branch has no {primary} but does have .github/workflows/auto-tag.yml; set [release] version_files in magi.toml to the version of record auto-tag.yml reads, or release by hand"
1745                )
1746            }
1747        });
1748        progress.skip = Some(Skip {
1749            reason: format!("no {primary} on the base branch; no release bump was made"),
1750            action,
1751        });
1752        return Ok(());
1753    }
1754
1755    let marker = marker_path(&home.map_or_else(run::home, Path::to_path_buf), &repo);
1756    // Held for the rest of this function: the whole read-decide-write
1757    // sequence below is the critical section two `after_merge` calls landing
1758    // within the same window must not both be inside at once. See
1759    // `MarkerLock`'s own doc for why a second, unrelated bump PR is what
1760    // that race produces without it, and `wait_for_marker_lock`'s for why
1761    // this waits rather than giving up the instant it is contended.
1762    let Some(_lock) = wait_for_marker_lock(&marker).await? else {
1763        state.event(
1764            "bump",
1765            "another release bump decision held the lock past the wait ceiling; skipping this round",
1766        );
1767        return Ok(());
1768    };
1769
1770    git::fetch(&repo, &remote, &base).await.ok();
1771    let mut versions = Vec::new();
1772    for f in release_manifest::effective(&declared) {
1773        let text = git::git(&repo, &["show", &format!("{remote}/{base}:{}", f.path)])
1774            .await
1775            .with_context(|| format!("read {} from the base branch", f.path))?;
1776        let v = release_manifest::read_version(f.kind, &text)
1777            .with_context(|| format!("read the version of {}", f.path))?;
1778        versions.push((f.path, v));
1779    }
1780    let base_version = match release_manifest::agree(&versions) {
1781        Ok(v) => v,
1782        Err(e) => {
1783            let reason = format!("{e:#}");
1784            state.event("bump", format!("release bump skipped: {reason}"));
1785            progress.skip = Some(Skip {
1786                action: Some(format!("{reason}; align them by hand, then release")),
1787                reason,
1788            });
1789            return Ok(());
1790        }
1791    };
1792    let change = change.await.context("read the merged PR's own change")?;
1793    let files = &change.files;
1794    let versions = if custom {
1795        Some(merged_versions(&repo, &change, &primary).await?)
1796    } else {
1797        None
1798    };
1799    if release_manifest::release_only(files, &declared)
1800        && !versions
1801            .as_ref()
1802            .is_some_and(|(before, after)| before == after)
1803    {
1804        state.event(
1805            "bump",
1806            "the merged change touches only the release files; not treating it as a trigger",
1807        );
1808        progress.skip = Some(Skip {
1809            reason: "the merged change touches only the release files; not a trigger".to_owned(),
1810            action: None,
1811        });
1812        return Ok(());
1813    }
1814    // Local mode has no auto-tag to hand the release to: the bump PR and the
1815    // watcher's approval are the release path, so it always proceeds.
1816    if custom
1817        && !state.config.release.is_local()
1818        && let Some((before, after)) = versions
1819        && before != after
1820    {
1821        state.event(
1822            "bump",
1823            format!(
1824                "the merged change already moved {primary} from v{before} to v{after}; leaving the release to the repository's auto-tag"
1825            ),
1826        );
1827        progress.skip = Some(Skip {
1828            reason: format!(
1829                "the change itself raised {primary} from v{before} to v{after}; the repository's auto-tag releases it"
1830            ),
1831            action: None,
1832        });
1833        return Ok(());
1834    }
1835
1836    let mut pending = read_marker(&marker);
1837    if let Some(p) = &pending {
1838        match coalesce(Some(p), &base_version)? {
1839            Coalesce::Proceed => {
1840                // Landed, or superseded by a manual bump: free for a fresh
1841                // decision.
1842                clear_marker(&marker);
1843                pending = None;
1844            }
1845            Coalesce::Skip { target_version } => {
1846                if !pr_is_open(&repo, &p.pr_url).await.unwrap_or(true) {
1847                    state.event(
1848                        "bump",
1849                        format!(
1850                            "the pending release bump to v{target_version} ({}) is no longer \
1851                             open; treating it as abandoned",
1852                            p.pr_url
1853                        ),
1854                    );
1855                    clear_marker(&marker);
1856                    pending = None;
1857                }
1858                // Otherwise still genuinely open: fall through and ask the
1859                // same question this merge would get on a fresh path, so a
1860                // more severe change landing while it waits can escalate it
1861                // instead of being silently absorbed at the wrong digit.
1862            }
1863        }
1864    }
1865
1866    if pending.is_none() {
1867        // This host's own marker has nothing to say - check the forge itself
1868        // before trusting that to mean a fresh pull request is safe to open.
1869        // See `find_open_release_pr`'s own doc for what this does and does
1870        // not close.
1871        if let Ok(Some((branch, url))) = find_open_release_pr(&repo).await
1872            && let Some(target) = branch_version(&repo, &remote, &branch, &primary)
1873                .await
1874                .and_then(|v| Version::parse(&v).ok())
1875        {
1876            let base_parsed = Version::parse(&base_version)?;
1877            if target > base_parsed
1878                && let Some(level) = level_between(base_parsed, target)
1879            {
1880                let adopted = PendingBump {
1881                    target_version: target.to_string(),
1882                    level,
1883                    branch,
1884                    pr_url: url,
1885                };
1886                // Best-effort: worst case this host asks the forge again
1887                // next time instead of finding its own record of it.
1888                let _ = write_marker(&marker, &adopted);
1889                pending = Some(adopted);
1890            }
1891        }
1892    }
1893
1894    progress.pending_pr = pending.as_ref().map(|p| p.pr_url.clone());
1895    let title = pr_title(&repo, pr_url).await.unwrap_or_default();
1896    let subject = land::merge_subject(
1897        crate::graph::landing_title(state, &title),
1898        &crate::graph::landing_subject_source(state),
1899    );
1900    let prompt = decision_prompt(
1901        &subject,
1902        &state.instruction,
1903        &change.stat,
1904        files,
1905        &base_version,
1906    );
1907
1908    let (spec, mut seat, mut decision) =
1909        ask_decision(state, &repo, &prompt, DECISION_TIMEOUT).await?;
1910    guard_reason(state, &repo, &prompt, &spec, &mut seat, &mut decision).await;
1911
1912    if let Some(p) = pending {
1913        return match pending_action(p.level, decision.level) {
1914            PendingAction::AlreadyCovered => {
1915                state.event(
1916                    "bump",
1917                    format!(
1918                        "a release bump to v{} ({}) already covers at least a {} change; not \
1919                         opening another",
1920                        p.target_version,
1921                        p.pr_url,
1922                        decision.level.as_str()
1923                    ),
1924                );
1925                Ok(())
1926            }
1927            PendingAction::Escalate => {
1928                progress.version = Some(
1929                    Version::parse(&base_version)?
1930                        .bump(decision.level)
1931                        .to_string(),
1932                );
1933                escalate_pending(state, &repo, &remote, &p, &decision, &base_version, &marker).await
1934            }
1935        };
1936    }
1937
1938    let next = Version::parse(&base_version)?
1939        .bump(decision.level)
1940        .to_string();
1941    progress.version = Some(next.clone());
1942    let branch = format!("chore/release-v{next}");
1943    let worktree = state.dir().join("bump");
1944    let (shared, branch_ref, next_ref, decision_ref) = (&mut *state, &branch, &next, &decision);
1945    let (pr_url_opened, outcome) =
1946        release_attempt(
1947            &repo,
1948            &remote,
1949            &base,
1950            &worktree,
1951            &branch,
1952            |head| {
1953                let repo = repo.clone();
1954                async move { gh_open_pr_for_head(&repo, &head).await }
1955            },
1956            |wt| async move {
1957                open_bump_pr(shared, &wt, branch_ref, next_ref, decision_ref, pr_url).await
1958            },
1959        )
1960        .await?;
1961    let local = outcome == AutomergeOutcome::LocalGate;
1962    let (automerge_warning, merged_detail) = match outcome {
1963        AutomergeOutcome::Enabled | AutomergeOutcome::LocalGate => (None, None),
1964        AutomergeOutcome::MergedDirectly { detail } => (None, Some(detail)),
1965        AutomergeOutcome::Failed { reason } => (Some(reason), None),
1966    };
1967
1968    // The pull request exists on the forge the moment `open_bump_pr` returns
1969    // its URL, regardless of what happens next - so the event that names it
1970    // is unconditional, and a marker write failing (a full disk, a missing
1971    // `home/bump` directory) is reported as its own warning rather than
1972    // swallowing that URL entirely the way propagating it with `?` would.
1973    // `find_open_release_pr` is the fallback if this leaves no local record:
1974    // the next merge that finds no marker still finds this pull request on
1975    // the forge before opening a second one.
1976    let marker_write = write_marker(
1977        &marker,
1978        &PendingBump {
1979            target_version: next.clone(),
1980            level: decision.level,
1981            branch,
1982            pr_url: pr_url_opened.clone(),
1983        },
1984    );
1985    state.event(
1986        "bump",
1987        format!(
1988            "opened a {} release bump to v{next} ({}): {pr_url_opened}",
1989            decision.level.as_str(),
1990            decision.reason
1991        ),
1992    );
1993    if let Err(e) = marker_write {
1994        state.event(
1995            "bump",
1996            format!(
1997                "could not record the pending release bump marker for v{next}: {e:#}; a later \
1998                 merge may open a duplicate pull request if it cannot find {pr_url_opened} on \
1999                 the forge either"
2000            ),
2001        );
2002    }
2003    state.release_bump = Some(run::ReleaseBump {
2004        pr_url: Some(pr_url_opened.clone()),
2005        version: Some(next.clone()),
2006        automerge_enabled: automerge_warning.is_none() && merged_detail.is_none() && !local,
2007        merged_directly: merged_detail.is_some(),
2008        local,
2009        ..run::ReleaseBump::default()
2010    });
2011    if let Some(detail) = merged_detail {
2012        // Merged already: a pending marker would make the next merge wait on
2013        // a pull request that is gone.
2014        clear_marker(&marker);
2015        state.event("bump", format!("merged v{next} directly: {detail}"));
2016    }
2017    if let Some(warning) = automerge_warning {
2018        state.event(
2019            "bump",
2020            format!("could not enable automerge on {pr_url_opened}: {warning}; merge it by hand"),
2021        );
2022        report_problem(state, Some(&pr_url_opened), Some(&next), &warning).await;
2023    }
2024    Ok(())
2025}
2026
2027/// The node name post-merge notices were filed under, back when they were
2028/// questions. Kept because [`ask::Questions::settle_run`] must go on exempting
2029/// any such question still open on disk; new problems go to
2030/// [`crate::notices`] instead - nothing here is something to answer.
2031pub const NOTICE_NODE: &str = "release-bump";
2032
2033/// What to tell the operator to do about a refused `gh pr merge --auto`.
2034///
2035/// Keys on the wording GitHub is known to use when the base branch has no
2036/// required status checks (`enablePullRequestAutoMerge` / "protected branch
2037/// rules"); anything else falls back to the generic advice, with the reason
2038/// carried verbatim next to it.
2039fn automerge_hint(reason: &str) -> &'static str {
2040    let r = reason.to_lowercase();
2041    if is_clean_status_refusal(reason) {
2042        "merge the release pull request by hand; CI is already green"
2043    } else if r.contains("enablepullrequestautomerge") || r.contains("protected branch rules") {
2044        "merge the release pull request by hand, and enable branch protection with required \
2045         status checks on the base branch so automerge can work next time"
2046    } else {
2047        "merge the release pull request by hand"
2048    }
2049}
2050
2051/// The comment left on the release pull request itself.
2052fn automerge_failure_comment(reason: &str) -> String {
2053    format!(
2054        "magi could not enable automerge on this pull request: {reason}\n\n\
2055         Action required: {}. Until then the release does not happen.",
2056        automerge_hint(reason)
2057    )
2058}
2059
2060/// Record a post-merge problem on the run and raise the operator-facing
2061/// notification, without touching the forge. Returns the notice and the
2062/// comment body meant for the release pull request when there is one.
2063///
2064/// Split from [`report_problem`] so the state, the notice and the wording
2065/// can be asserted without a `gh`. The notice is keyed on the run, so a retry
2066/// of the same failed bump folds into one entry instead of flooding the bell.
2067#[cfg(test)]
2068fn surface_problem(
2069    state: &mut RunState,
2070    store: &Notices,
2071    pr_url: Option<&str>,
2072    version: Option<&str>,
2073    reason: &str,
2074) -> Result<(Notice, Option<String>)> {
2075    surface_problem_in(state, store, pr_url, version, reason, false)
2076}
2077
2078/// [`surface_problem`], where `pending` says `pr_url` is a release pull
2079/// request that already existed and could not be raised to `version` - not one
2080/// whose automerge failed. It is linked and recorded, but gets no comment.
2081fn surface_problem_in(
2082    state: &mut RunState,
2083    store: &Notices,
2084    pr_url: Option<&str>,
2085    version: Option<&str>,
2086    reason: &str,
2087    pending: bool,
2088) -> Result<(Notice, Option<String>)> {
2089    let reason = crate::scrub::scrub(reason, &crate::scrub::Identity::current());
2090    let reason = reason.as_str();
2091    let action = if let (true, Some(url)) = (pending, pr_url) {
2092        let ja = crate::lang::is_japanese(&state.config.graph.language);
2093        let first = failure_headline(reason);
2094        let cause = first.map(|l| format!(" ({l})")).unwrap_or_default();
2095        if ja {
2096            let target = version.map(|v| format!(" v{v}")).unwrap_or_default();
2097            format!(
2098                "既存のリリース PR {url} を{target}へ更新できませんでした{cause}。PR を手で更新してください"
2099            )
2100        } else {
2101            let target = version.map(|v| format!(" to v{v}")).unwrap_or_default();
2102            format!(
2103                "the pending release pull request {url} could not be updated{target}{cause}; update it by hand"
2104            )
2105        }
2106    } else if pr_url.is_some() {
2107        automerge_hint(reason).to_owned()
2108    } else {
2109        let ja = crate::lang::is_japanese(&state.config.graph.language);
2110        let first = failure_headline(reason);
2111        if ja {
2112            let target = version.map(|v| format!(" (v{v})")).unwrap_or_default();
2113            let cause = first.map(|l| format!(" ({l})")).unwrap_or_default();
2114            format!(
2115                "リリースバンプ{target}は実行されませんでした{cause}。リリース PR を手で開いてください"
2116            )
2117        } else {
2118            let target = version.map(|v| format!(" to v{v}")).unwrap_or_default();
2119            let cause = first.map(|l| format!(" ({l})")).unwrap_or_default();
2120            format!(
2121                "the release bump{target} did not run{cause}; open the release pull request by hand"
2122            )
2123        }
2124    };
2125    let record = state.release_bump.get_or_insert_with(Default::default);
2126    record.pr_url = pr_url.map(str::to_owned).or(record.pr_url.take());
2127    record.version = version.map(str::to_owned).or(record.version.take());
2128    record.automerge_enabled = false;
2129    record.problem = Some(reason.to_owned());
2130    record.action_required = Some(action.clone());
2131
2132    let mut notice = Notice::error(
2133        &format!("release-bump:{}", state.id),
2134        format!(
2135            "Run {} merged, but its release step failed: {action}.",
2136            state.id
2137        ),
2138    );
2139    notice = match pr_url {
2140        Some(url) => notice.link(Link::Url {
2141            url: url.to_owned(),
2142        }),
2143        None => notice.link(Link::Run {
2144            id: state.id.clone(),
2145        }),
2146    };
2147    let notice = store
2148        .raise_with(
2149            notice
2150                .about([state.id.clone()])
2151                .for_run(Some(state.id.clone())),
2152            &state.config.notify,
2153        )
2154        .context("raise the release-bump notification")?;
2155    state.event("bump", format!("needs attention: {action}"));
2156    let comment = pr_url
2157        .filter(|_| !pending)
2158        .map(|_| automerge_failure_comment(reason));
2159    Ok((notice, comment))
2160}
2161
2162/// Make a post-merge problem visible: record it, comment on the release pull
2163/// request, raise a notification and run the configured notifier. Every step
2164/// is best-effort - a failed comment or webhook is an event, never a reason to
2165/// lose the record or the run.
2166pub async fn report_problem(
2167    state: &mut RunState,
2168    pr_url: Option<&str>,
2169    version: Option<&str>,
2170    reason: &str,
2171) {
2172    report_problem_in(state, &Notices::open(), pr_url, version, reason, false).await;
2173}
2174
2175/// [`report_problem`] against an explicit notice store.
2176async fn report_problem_in(
2177    state: &mut RunState,
2178    store: &Notices,
2179    pr_url: Option<&str>,
2180    version: Option<&str>,
2181    reason: &str,
2182    pending: bool,
2183) {
2184    match surface_problem_in(state, store, pr_url, version, reason, pending) {
2185        Ok((_notice, comment)) => {
2186            if let (Some(url), Some(body)) = (pr_url, comment)
2187                && let Err(e) = gh_pr_comment(state, url, &body).await
2188            {
2189                state.event("bump", format!("could not comment on {url}: {e:#}"));
2190            }
2191        }
2192        Err(e) => state.event("bump", format!("could not raise a notice: {e:#}")),
2193    }
2194}
2195
2196pub(crate) async fn gh_pr_comment(state: &mut RunState, pr_url: &str, body: &str) -> Result<()> {
2197    let (_, body) = crate::github_text::prepare(state, "", body);
2198    let cwd = &state.repo;
2199    let out = tokio::process::Command::new("gh")
2200        .args(["pr", "comment", pr_url, "--body", &body])
2201        .current_dir(cwd)
2202        .quiet()
2203        .stdin(std::process::Stdio::null())
2204        .output()
2205        .await
2206        .context("spawn gh pr comment")?;
2207    if out.status.success() {
2208        Ok(())
2209    } else {
2210        bail!(
2211            "gh pr comment: {}",
2212            String::from_utf8_lossy(&out.stderr).trim()
2213        )
2214    }
2215}
2216
2217/// Bump an already-open release pull request further, because a change more
2218/// severe than what it already covers landed while it waited on CI or
2219/// automerge - see [`pending_action`].
2220///
2221/// Adds a second commit rather than rewriting the first: `gh pr merge
2222/// --squash` prefers a single commit's own message over the pull request's
2223/// title, and falls back to the title once there is more than one commit -
2224/// so the title is what is kept honest here, via `gh pr edit`.
2225async fn escalate_pending(
2226    state: &mut RunState,
2227    repo: &Path,
2228    remote: &str,
2229    pending: &PendingBump,
2230    decision: &BumpDecision,
2231    base_version: &str,
2232    marker: &Path,
2233) -> Result<()> {
2234    let next = Version::parse(base_version)?
2235        .bump(decision.level)
2236        .to_string();
2237    let worktree = state.dir().join("bump");
2238    git::worktree_remove(repo, &worktree).await.ok();
2239    git::worktree_add_existing(repo, &worktree, &pending.branch, true)
2240        .await
2241        .with_context(|| format!("checking out the pending release branch {}", pending.branch))?;
2242
2243    // Only the substantive change - the commit landing on the remote branch
2244    // - has to succeed for the escalation to have happened at all. Anything
2245    // after the push is a follow-up, not a precondition: the branch already
2246    // carries the new version whether or not it succeeds.
2247    let pushed: Result<()> = async {
2248        write_release_files(state, &worktree, &next).await?;
2249        let committed = git::commit_all(
2250            &worktree,
2251            &format!(
2252                "chore: release v{next} (supersedes v{})",
2253                pending.target_version
2254            ),
2255        )
2256        .await
2257        .context("commit the escalated version bump")?;
2258        if !committed {
2259            bail!("escalating the version bump left nothing to commit");
2260        }
2261        let pushed = git::push(&worktree, remote, &pending.branch).await?;
2262        if !pushed.ok() {
2263            bail!("pushing {} failed: {}", pending.branch, pushed.stderr);
2264        }
2265        Ok(())
2266    }
2267    .await;
2268    if let Err(e) = pushed {
2269        git::worktree_remove(repo, &worktree).await.ok();
2270        return Err(e);
2271    }
2272
2273    // The commit is on the remote branch now regardless of what happens
2274    // below - the title edit is cosmetic, and the marker and the event must
2275    // both reflect the real, already-pushed state even if it fails.
2276    let (title, _) = crate::github_text::prepare(
2277        state,
2278        &format!("chore: release v{next} ({} bump)", decision.level.as_str()),
2279        "",
2280    );
2281    let title_warning = match gh_pr_edit_title(&worktree, &pending.pr_url, &title).await {
2282        Ok(()) => None,
2283        Err(e) => Some(e.to_string()),
2284    };
2285    git::worktree_remove(repo, &worktree).await.ok();
2286
2287    let marker_write = write_marker(
2288        marker,
2289        &PendingBump {
2290            target_version: next.clone(),
2291            level: decision.level,
2292            branch: pending.branch.clone(),
2293            pr_url: pending.pr_url.clone(),
2294        },
2295    );
2296    state.event(
2297        "bump",
2298        format!(
2299            "escalated the pending release bump from v{} to v{next} to a {} change ({}): {}",
2300            pending.target_version,
2301            decision.level.as_str(),
2302            decision.reason,
2303            pending.pr_url
2304        ),
2305    );
2306    if let Err(e) = marker_write {
2307        state.event(
2308            "bump",
2309            format!(
2310                "could not update the pending release bump marker to v{next}: {e:#}; a later \
2311                 merge may misjudge whether it is already covered"
2312            ),
2313        );
2314    }
2315    if let Some(warning) = title_warning {
2316        state.event(
2317            "bump",
2318            format!(
2319                "pushed v{next} to {} but could not update its title: {warning}; the squashed \
2320                 subject may still read the superseded version",
2321                pending.pr_url
2322            ),
2323        );
2324    }
2325    Ok(())
2326}
2327
2328/// Does an open pull request have `branch` as its head? Any head repository
2329/// counts: the question is only whether the branch name is spoken for.
2330async fn gh_open_pr_for_head(repo: &Path, branch: &str) -> Result<bool> {
2331    let out = tokio::process::Command::new("gh")
2332        .args([
2333            "pr", "list", "--head", branch, "--state", "open", "--json", "url",
2334        ])
2335        .current_dir(repo)
2336        .quiet()
2337        .stdin(std::process::Stdio::null())
2338        .output()
2339        .await
2340        .context("spawn gh pr list")?;
2341    if !out.status.success() {
2342        bail!(
2343            "gh pr list --head {branch}: {}",
2344            String::from_utf8_lossy(&out.stderr).trim()
2345        );
2346    }
2347    let prs: Vec<serde_json::Value> = serde_json::from_slice(&out.stdout)
2348        .with_context(|| format!("parse the pull requests headed by {branch}"))?;
2349    Ok(!prs.is_empty())
2350}
2351
2352/// Create the release branch and worktree, run `fill` in it, and leave nothing
2353/// behind unless a pull request came out of it.
2354///
2355/// A leftover `chore/release-vX.Y.Z` from an earlier failed attempt is
2356/// inspected rather than fatal ([`reclaim_stale_branch`]), once per attempt. A
2357/// failure of `fill` - or of creating the worktree - removes the worktree and
2358/// the branch this attempt made, except a branch that reached the remote,
2359/// which is kept and said so in the returned error.
2360async fn release_attempt<T, F, Fut, P, PFut>(
2361    repo: &Path,
2362    remote: &str,
2363    base: &str,
2364    worktree: &Path,
2365    branch: &str,
2366    open_pr: P,
2367    fill: F,
2368) -> Result<T>
2369where
2370    F: FnOnce(PathBuf) -> Fut,
2371    Fut: std::future::Future<Output = Result<T>>,
2372    P: Fn(String) -> PFut,
2373    PFut: std::future::Future<Output = Result<bool>>,
2374{
2375    let start = format!("{remote}/{base}");
2376    git::worktree_remove(repo, worktree).await.ok();
2377    let mut retried = false;
2378    if git::branch_exists(repo, branch).await? {
2379        reclaim_stale_branch(repo, remote, &start, branch, &open_pr).await?;
2380        retried = true;
2381    }
2382    loop {
2383        // Two steps instead of `worktree add -b`, so that who made the branch
2384        // is known from which step failed rather than guessed from git's
2385        // wording or the branch's tip: `git branch` creates the ref atomically
2386        // or fails, and only a branch it created is this attempt's.
2387        if let Err(e) = git::git(repo, &["branch", branch, &start]).await {
2388            let e = e.context("create the release branch");
2389            if !git::branch_exists(repo, branch).await.unwrap_or(false) {
2390                return Err(e);
2391            }
2392            // It appeared since the check above: somebody else's.
2393            if retried {
2394                return Err(anyhow!(
2395                    "{e:#}; left {branch} in place: it is not one this attempt created"
2396                ));
2397            }
2398            retried = true;
2399            if let Err(r) = reclaim_stale_branch(repo, remote, &start, branch, &open_pr).await {
2400                return Err(anyhow!("{r:#} (after: {e:#})"));
2401            }
2402            continue;
2403        }
2404        if let Err(e) = git::worktree_add_existing(repo, worktree, branch, false).await {
2405            let e = e.context("create the release-bump worktree");
2406            return Err(discard_attempt(repo, remote, worktree, branch, e).await);
2407        }
2408        break;
2409    }
2410    match fill(worktree.to_path_buf()).await {
2411        Ok(v) => {
2412            // The branch lives on in the pull request; the worktree is
2413            // throwaway and a stale one would collide with the next attempt.
2414            git::worktree_remove(repo, worktree).await.ok();
2415            Ok(v)
2416        }
2417        Err(e) => Err(discard_attempt(repo, remote, worktree, branch, e).await),
2418    }
2419}
2420
2421/// Undo what a failed attempt created and fold the outcome into its error.
2422async fn discard_attempt(
2423    repo: &Path,
2424    remote: &str,
2425    worktree: &Path,
2426    branch: &str,
2427    cause: anyhow::Error,
2428) -> anyhow::Error {
2429    git::worktree_remove(repo, worktree).await.ok();
2430    if !git::branch_exists(repo, branch).await.unwrap_or(false) {
2431        return cause;
2432    }
2433    // The remote's own answer decides, not whether a push was attempted: a
2434    // push that failed half way may still have landed the ref.
2435    let note = match git::remote_has_branch(repo, remote, branch).await {
2436        Ok(false) => match git::branch_delete(repo, branch).await {
2437            Ok(true) => return cause,
2438            _ => format!("could not delete the local branch {branch}"),
2439        },
2440        Ok(true) => format!("left {branch} in place: it was pushed to {remote}"),
2441        Err(e) => format!(
2442            "left {branch} in place: could not tell whether it was pushed to {remote} ({e:#})"
2443        ),
2444    };
2445    anyhow!("{cause:#}; {note}")
2446}
2447
2448/// A branch of the release's name already exists. Delete it so the attempt can
2449/// go on if and only if it holds nothing: not on the remote, no open pull
2450/// request, and no commit that `start` (`<remote>/<base>`) lacks. Anything
2451/// unproven fails closed with a reason that names the branch.
2452async fn reclaim_stale_branch<P, PFut>(
2453    repo: &Path,
2454    remote: &str,
2455    start: &str,
2456    branch: &str,
2457    open_pr: &P,
2458) -> Result<()>
2459where
2460    P: Fn(String) -> PFut,
2461    PFut: std::future::Future<Output = Result<bool>>,
2462{
2463    match git::remote_has_branch(repo, remote, branch).await {
2464        Ok(false) => {}
2465        Ok(true) => bail!("the branch {branch} already exists and is on {remote}; left alone"),
2466        Err(e) => bail!(
2467            "the branch {branch} already exists and could not check whether {remote} has it              ({e:#}); left alone"
2468        ),
2469    }
2470    match open_pr(branch.to_string()).await {
2471        Ok(false) => {}
2472        Ok(true) => {
2473            bail!("the branch {branch} already exists and has an open pull request; left alone")
2474        }
2475        Err(e) => bail!(
2476            "the branch {branch} already exists and could not check for an open pull request \
2477             ({e:#}); left alone"
2478        ),
2479    }
2480    match git::commits_ahead(repo, start, branch).await {
2481        Ok(0) => {}
2482        Ok(n) => bail!(
2483            "the branch {branch} already exists with {n} commit(s) not in {start}; left alone"
2484        ),
2485        Err(e) => bail!(
2486            "the branch {branch} already exists and could not compare it with {start} ({e:#}); \
2487             left alone"
2488        ),
2489    }
2490    if let Some(held) = git::worktree_holding(repo, branch).await? {
2491        let same = |a: &Path, b: &Path| match (a.canonicalize(), b.canonicalize()) {
2492            (Ok(a), Ok(b)) => a == b,
2493            _ => a == b,
2494        };
2495        if same(&held, repo) {
2496            bail!(
2497                "the branch {branch} already exists and is checked out in the main checkout; left alone"
2498            );
2499        }
2500        git::worktree_remove(repo, &held).await.ok();
2501    }
2502    if !git::branch_delete(repo, branch).await? {
2503        bail!("the branch {branch} already exists and could not be deleted; left alone");
2504    }
2505    Ok(())
2506}
2507
2508/// Edit the version, let the lockfile follow, commit, push, and open the pull
2509/// request with automerge enabled. Returns the opened pull request's URL and,
2510/// when enabling automerge itself failed, a note of why - the pull request
2511/// still exists on the forge either way, and the caller must not lose track
2512/// of its URL over that failure alone.
2513async fn open_bump_pr(
2514    state: &mut RunState,
2515    worktree: &Path,
2516    branch: &str,
2517    next_version: &str,
2518    decision: &BumpDecision,
2519    source_pr_url: &str,
2520) -> Result<(String, AutomergeOutcome)> {
2521    write_release_files(state, worktree, next_version).await?;
2522
2523    let committed = git::commit_all(worktree, &format!("chore: release v{next_version}"))
2524        .await
2525        .context("commit the version bump")?;
2526    if !committed {
2527        bail!("the version bump left nothing to commit");
2528    }
2529
2530    let remote = state.config.merge.remote.clone();
2531    let pushed = git::push(worktree, &remote, branch).await?;
2532    if !pushed.ok() {
2533        bail!("pushing {branch} failed: {}", pushed.stderr);
2534    }
2535
2536    let (title, body) = release_pr(
2537        decision.level.as_str(),
2538        &decision.reason,
2539        next_version,
2540        &state.id,
2541        source_pr_url,
2542    );
2543    let (title, body) = crate::github_text::prepare(state, &title, &body);
2544    let url = gh_pr_create(worktree, &state.base_branch, branch, &title, &body).await?;
2545    // Without Actions nothing would ever merge it on green, and a direct merge
2546    // here would skip the owner's approval: leave it open for the release
2547    // watcher, which asks and then releases.
2548    if state.config.release.is_local() {
2549        // Watched from now on, so a pull request merged before the watcher's
2550        // first lap still gets released.
2551        crate::release_watch::register(&crate::run::home(), &state.repo, &url, &state.id);
2552        return Ok((url, AutomergeOutcome::LocalGate));
2553    }
2554    let outcome = match gh_enable_automerge(worktree, &url).await {
2555        Ok(()) => AutomergeOutcome::Enabled,
2556        Err(e) => {
2557            let reason = e.to_string();
2558            if is_clean_status_refusal(&reason) {
2559                gh_merge_directly(worktree, &url, &title, reason).await
2560            } else {
2561                AutomergeOutcome::Failed { reason }
2562            }
2563        }
2564    };
2565    Ok((url, outcome))
2566}
2567
2568/// What became of the release pull request's path to `main`.
2569#[derive(Debug, Clone, PartialEq, Eq)]
2570enum AutomergeOutcome {
2571    /// Automerge is armed; CI green will merge it.
2572    Enabled,
2573    /// CI beat us to it, so magi merged the pull request itself.
2574    MergedDirectly { detail: String },
2575    /// `[release] mode = "local"`: automerge was deliberately not armed.
2576    LocalGate,
2577    /// Neither worked; a human has to merge it.
2578    Failed { reason: String },
2579}
2580
2581/// Is this GitHub's refusal to arm automerge on a pull request that is already
2582/// mergeable? Automerge can only be enabled while something is still pending,
2583/// so a fast CI that finishes first gets `Pull request is in clean status`.
2584/// Both fragments are required so an unrelated "clean status" wording or a
2585/// branch-protection refusal does not trigger a direct merge.
2586fn is_clean_status_refusal(reason: &str) -> bool {
2587    let r = reason.to_lowercase();
2588    r.contains("is in clean status") && r.contains("enablepullrequestautomerge")
2589}
2590
2591/// The direct merge, in the same shape [`land::merge_argv`] uses but addressed
2592/// by URL: squash under the pull request's own title, delete the branch.
2593pub(crate) fn bump_merge_argv(pr_url: &str, subject: &str) -> Vec<String> {
2594    [
2595        "pr",
2596        "merge",
2597        pr_url,
2598        "--squash",
2599        "--delete-branch",
2600        "--subject",
2601        subject,
2602    ]
2603    .map(str::to_owned)
2604    .to_vec()
2605}
2606
2607/// Decide what a direct merge amounted to. No I/O. A zero exit is a merge; a
2608/// non-zero one is judged by the forge (`after`), never by the exit code, and
2609/// an unreadable forge is not evidence of success.
2610fn resolve_direct_merge(
2611    refusal: &str,
2612    argv: &[String],
2613    merge_ok: bool,
2614    stderr: &str,
2615    after: Option<land::PrLifecycle>,
2616) -> AutomergeOutcome {
2617    if merge_ok {
2618        return AutomergeOutcome::MergedDirectly {
2619            detail: format!("automerge was refused ({refusal}); gh {}", argv.join(" ")),
2620        };
2621    }
2622    match land::merged_after_all(argv, stderr, after) {
2623        Some(m) => AutomergeOutcome::MergedDirectly { detail: m.detail },
2624        None => AutomergeOutcome::Failed {
2625            reason: format!("{refusal}; merging directly failed too: {}", stderr.trim()),
2626        },
2627    }
2628}
2629
2630/// Merge the pull request directly after automerge was refused as clean.
2631/// Every failure lands in [`AutomergeOutcome::Failed`] so the caller keeps the
2632/// warning-and-comment path.
2633async fn gh_merge_directly(
2634    cwd: &Path,
2635    pr_url: &str,
2636    subject: &str,
2637    refusal: String,
2638) -> AutomergeOutcome {
2639    let argv = bump_merge_argv(pr_url, subject);
2640    let out = match tokio::process::Command::new("gh")
2641        .args(&argv)
2642        .current_dir(cwd)
2643        .quiet()
2644        .stdin(std::process::Stdio::null())
2645        .output()
2646        .await
2647    {
2648        Ok(o) => o,
2649        Err(e) => {
2650            return AutomergeOutcome::Failed {
2651                reason: format!("{refusal}; could not spawn gh to merge directly: {e}"),
2652            };
2653        }
2654    };
2655    let stderr = String::from_utf8_lossy(&out.stderr).into_owned();
2656    // jj keeps HEAD detached, so `--delete-branch` exits non-zero after the
2657    // merge has happened; ask the forge.
2658    let after = if out.status.success() {
2659        None
2660    } else {
2661        land::lifecycle(cwd, pr_url).await.ok()
2662    };
2663    resolve_direct_merge(&refusal, &argv, out.status.success(), &stderr, after)
2664}
2665
2666/// Put `version` into the repository's release files in `worktree`: the
2667/// configured `version_files` (the lock beside the first one is edited as text),
2668/// else the root `Cargo.toml` with `cargo build` moving `Cargo.lock`.
2669async fn write_release_files(state: &RunState, worktree: &Path, version: &str) -> Result<()> {
2670    let declared = &state.config.release.version_files;
2671    if release_manifest::is_custom(declared) {
2672        return release_manifest::apply(worktree, declared, version);
2673    }
2674    let cargo_toml_path = worktree.join("Cargo.toml");
2675    let toml = tokio::fs::read_to_string(&cargo_toml_path)
2676        .await
2677        .with_context(|| format!("read {}", cargo_toml_path.display()))?;
2678    let rewritten = rewrite_cargo_version(&toml, version)?;
2679    tokio::fs::write(&cargo_toml_path, rewritten)
2680        .await
2681        .with_context(|| format!("write {}", cargo_toml_path.display()))?;
2682    if crate::build_target::isolated(&state.config) {
2683        let shell = state.config.shell();
2684        crate::build_target::command::check_shell(&shell)?;
2685        let mut build = crate::build_target::Operation::admit(
2686            &state.config,
2687            worktree,
2688            &state.id,
2689            "bump-lockfile",
2690            crate::build_target::Coordination::Acquire,
2691        )
2692        .await?;
2693        if let Some(output) = crate::retention::OutputLease::borrow(worktree)? {
2694            build.outputs.push(output);
2695        }
2696        return crate::worktree_setup::run_command(
2697            &shell,
2698            "cargo build",
2699            worktree,
2700            Duration::from_secs(state.config.graph.verify_timeout()),
2701            build.lease.take(),
2702            std::mem::take(&mut build.outputs),
2703            false,
2704            Some((&build.target, state.config.disk.min_free_bytes)),
2705        )
2706        .await;
2707    }
2708    sync_lockfile(worktree, state.config.cache_dir().as_deref()).await
2709}
2710
2711/// Run `cargo build` so `Cargo.lock` follows the version bump, the same step
2712/// `AGENTS.md`'s hand-driven release recipe calls for.
2713///
2714/// Not exercised by a test: it is the one step in this module that runs the
2715/// real `cargo`, which the constraints on this change rule out doing from a
2716/// test (no network, no writing outside a throwaway worktree the test itself
2717/// does not have).
2718async fn sync_lockfile(worktree: &Path, cache_dir: Option<&Path>) -> Result<()> {
2719    let mut cmd = tokio::process::Command::new("cargo");
2720    cmd.arg("build").current_dir(worktree).quiet();
2721    crate::incremental::configure(&mut cmd, worktree)?;
2722    if let Some(dir) = cache_dir {
2723        cmd.env("CARGO_TARGET_DIR", dir);
2724    }
2725    let out = cmd
2726        .stdin(std::process::Stdio::null())
2727        .output()
2728        .await
2729        .context("spawn cargo build")?;
2730    if !out.status.success() {
2731        bail!(
2732            "cargo build failed while syncing Cargo.lock: {}",
2733            String::from_utf8_lossy(&out.stderr).trim()
2734        );
2735    }
2736    Ok(())
2737}
2738
2739/// Title and body of a release bump pull request. Fixed English whatever
2740/// `[graph] language` says: it lands on GitHub. Pure so a test can hold it to
2741/// that. (`reason` comes from the decision seat, which the prompt tells to
2742/// write English.)
2743fn release_pr(
2744    level: &str,
2745    reason: &str,
2746    next_version: &str,
2747    run_id: &str,
2748    source_pr_url: &str,
2749) -> (String, String) {
2750    let title = format!("chore: release v{next_version} ({level} bump)");
2751    let body = format!(
2752        "## Background\n\n\
2753         A change that was just merged is a `{level}` change, so the crate needs a new \
2754         release: {reason}\n\n\
2755         Triggered by magi run `{run_id}`, which landed {source}.\n\n\
2756         ## Change\n\n\
2757         Raises the package version to `v{next_version}` in `Cargo.toml`, with \
2758         `Cargo.lock` following it. Nothing else changes.\n\n\
2759         ## Risk\n\n\
2760         Version-bump-only, so there is nothing here for a reviewer to find. Merging \
2761         it starts the release pipeline (auto-tag, then the release workflow).",
2762        source = source_pr_url,
2763    );
2764    (title, body)
2765}
2766
2767/// The merged pull request's title, for [`land::merge_subject`].
2768async fn pr_title(repo: &Path, pr_url: &str) -> Result<String> {
2769    let out = tokio::process::Command::new("gh")
2770        .args(["pr", "view", pr_url, "--json", "title"])
2771        .current_dir(repo)
2772        .quiet()
2773        .stdin(std::process::Stdio::null())
2774        .output()
2775        .await
2776        .context("spawn gh pr view")?;
2777    if !out.status.success() {
2778        bail!(
2779            "gh pr view {pr_url}: {}",
2780            String::from_utf8_lossy(&out.stderr).trim()
2781        );
2782    }
2783    #[derive(Deserialize)]
2784    struct Title {
2785        title: String,
2786    }
2787    let parsed: Title = serde_json::from_str(&String::from_utf8_lossy(&out.stdout))
2788        .context("parse `gh pr view --json title` output")?;
2789    Ok(parsed.title)
2790}
2791
2792async fn gh_pr_create(
2793    cwd: &Path,
2794    base: &str,
2795    head: &str,
2796    title: &str,
2797    body: &str,
2798) -> Result<String> {
2799    let out = tokio::process::Command::new("gh")
2800        .args([
2801            "pr", "create", "--base", base, "--head", head, "--title", title, "--body", body,
2802        ])
2803        .current_dir(cwd)
2804        .quiet()
2805        .stdin(std::process::Stdio::null())
2806        .output()
2807        .await
2808        .context("spawn gh pr create")?;
2809    if out.status.success() {
2810        Ok(String::from_utf8_lossy(&out.stdout).trim().to_owned())
2811    } else {
2812        bail!(
2813            "gh pr create: {}",
2814            String::from_utf8_lossy(&out.stderr).trim()
2815        )
2816    }
2817}
2818
2819/// Enable automerge, mirroring `AGENTS.md`'s `gh pr merge --auto --squash
2820/// --delete-branch`. Never `git tag`: `auto-tag.yml` mints the tag once this
2821/// merges, and a manual tag would collide with its push.
2822async fn gh_enable_automerge(cwd: &Path, pr_url: &str) -> Result<()> {
2823    let out = tokio::process::Command::new("gh")
2824        .args([
2825            "pr",
2826            "merge",
2827            pr_url,
2828            "--auto",
2829            "--squash",
2830            "--delete-branch",
2831        ])
2832        .current_dir(cwd)
2833        .quiet()
2834        .stdin(std::process::Stdio::null())
2835        .output()
2836        .await
2837        .context("spawn gh pr merge --auto")?;
2838    if out.status.success() {
2839        Ok(())
2840    } else {
2841        bail!(
2842            "gh pr merge --auto: {}",
2843            String::from_utf8_lossy(&out.stderr).trim()
2844        )
2845    }
2846}
2847
2848/// Rewrite a pull request's title, used when [`escalate_pending`] adds a
2849/// second commit: `gh pr merge --squash` only prefers a single commit's own
2850/// message over the title, so once there are two the title is what lands.
2851async fn gh_pr_edit_title(cwd: &Path, pr_url: &str, title: &str) -> Result<()> {
2852    let out = tokio::process::Command::new("gh")
2853        .args(["pr", "edit", pr_url, "--title", title])
2854        .current_dir(cwd)
2855        .quiet()
2856        .stdin(std::process::Stdio::null())
2857        .output()
2858        .await
2859        .context("spawn gh pr edit")?;
2860    if out.status.success() {
2861        Ok(())
2862    } else {
2863        bail!(
2864            "gh pr edit --title: {}",
2865            String::from_utf8_lossy(&out.stderr).trim()
2866        )
2867    }
2868}
2869
2870#[cfg(test)]
2871mod tests {
2872    use super::*;
2873    use crate::notices::Severity;
2874
2875    // Inject forge evidence without changing PATH or contacting a real forge.
2876    // Existing fixtures represent a single merged commit at HEAD.
2877    async fn after_merge_at(
2878        state: &mut RunState,
2879        pr_url: &str,
2880        home: Option<&Path>,
2881        store: Option<&Notices>,
2882    ) -> Result<()> {
2883        let repo = state.repo.clone();
2884        after_merge_using(state, pr_url, home, store, fixture_change(&repo)).await
2885    }
2886
2887    async fn fixture_change(repo: &Path) -> Result<MergedChange> {
2888        let merge = git::rev_parse(repo, "HEAD").await?;
2889        let raw = git::git(
2890            repo,
2891            &["diff", "--numstat", "--no-renames", "HEAD^1", "HEAD"],
2892        )
2893        .await?;
2894        let entries: Vec<PrFile> = raw
2895            .lines()
2896            .map(|line| {
2897                let mut parts = line.splitn(3, '\t');
2898                PrFile {
2899                    additions: parts.next().unwrap().parse().unwrap(),
2900                    deletions: parts.next().unwrap().parse().unwrap(),
2901                    filename: parts.next().unwrap().to_owned(),
2902                    previous_filename: None,
2903                }
2904            })
2905            .collect();
2906        merged_change_from_pages(merge, entries.len(), vec![entries])
2907    }
2908
2909    #[tokio::test]
2910    async fn merged_release_pr_does_not_trigger_from_a_stale_local_base() {
2911        for squash in [true, false] {
2912            let (_dir, repo) = origin_with(&[
2913                ("Cargo.toml", "[package]\nname=\"x\"\nversion=\"0.1.0\"\n"),
2914                ("Cargo.lock", "old\n"),
2915            ])
2916            .await;
2917            let stale = git::rev_parse(&repo, "HEAD").await.unwrap();
2918            git::git(&repo, &["checkout", "-b", "landing"])
2919                .await
2920                .unwrap();
2921            tokio::fs::write(repo.join("feature.rs"), "upstream feature\n")
2922                .await
2923                .unwrap();
2924            git::git(&repo, &["add", "-A"]).await.unwrap();
2925            git::git(&repo, &["commit", "-m", "upstream feature"])
2926                .await
2927                .unwrap();
2928            git::git(&repo, &["push", "origin", "HEAD:main"])
2929                .await
2930                .unwrap();
2931            git::git(&repo, &["checkout", "-b", "release"])
2932                .await
2933                .unwrap();
2934            tokio::fs::write(
2935                repo.join("Cargo.toml"),
2936                "[package]\nname=\"x\"\nversion=\"0.1.1\"\n",
2937            )
2938            .await
2939            .unwrap();
2940            tokio::fs::write(repo.join("Cargo.lock"), "new\n")
2941                .await
2942                .unwrap();
2943            git::git(&repo, &["commit", "-am", "release"])
2944                .await
2945                .unwrap();
2946            git::git(&repo, &["checkout", "landing"]).await.unwrap();
2947            if squash {
2948                git::git(&repo, &["merge", "--squash", "release"])
2949                    .await
2950                    .unwrap();
2951                git::git(&repo, &["commit", "-m", "merged release"])
2952                    .await
2953                    .unwrap();
2954            } else {
2955                git::git(
2956                    &repo,
2957                    &["merge", "--no-ff", "release", "-m", "merged release"],
2958                )
2959                .await
2960                .unwrap();
2961            }
2962            git::git(&repo, &["push", "origin", "HEAD:main"])
2963                .await
2964                .unwrap();
2965            assert_eq!(git::rev_parse(&repo, "main").await.unwrap(), stale);
2966            assert!(!is_release_only(
2967                &git::changed_files(&repo, "main", "release").await.unwrap()
2968            ));
2969            let evidence = fixture_change(&repo).await.unwrap();
2970            assert_eq!(
2971                merged_versions(&repo, &evidence, "Cargo.toml")
2972                    .await
2973                    .unwrap(),
2974                ("0.1.0".to_owned(), "0.1.1".to_owned())
2975            );
2976            let mut mismatched = fixture_change(&repo).await.unwrap();
2977            mismatched.numstat.pop();
2978            assert!(
2979                merged_versions(&repo, &mismatched, "Cargo.toml")
2980                    .await
2981                    .is_err()
2982            );
2983            for custom in [false, true] {
2984                let mut state = winner_state(&repo, "main");
2985                state.candidates[0].branch = "release".to_owned();
2986                if custom {
2987                    state.config.release.version_files = release_manifest::effective(&[]);
2988                }
2989                let home = tempfile::tempdir().unwrap();
2990                let store = Notices::at(home.path().join("notifications"));
2991                after_merge_at(
2992                    &mut state,
2993                    "https://example.invalid/pull/1",
2994                    Some(home.path()),
2995                    Some(&store),
2996                )
2997                .await
2998                .unwrap();
2999                assert!(
3000                    state
3001                        .events
3002                        .iter()
3003                        .any(|e| e.node == "bump" && e.message.contains("only the release files")),
3004                    "{:?}",
3005                    state.events
3006                );
3007                assert!(
3008                    state
3009                        .release_bump
3010                        .as_ref()
3011                        .unwrap()
3012                        .skipped
3013                        .as_ref()
3014                        .unwrap()
3015                        .contains("only the release files")
3016                );
3017                assert!(state.bump_decision_attempts.is_empty());
3018                assert!(read_marker(&marker_path(home.path(), &repo)).is_none());
3019                assert!(store.list().is_empty());
3020            }
3021        }
3022    }
3023
3024    #[tokio::test]
3025    async fn merged_versions_accepts_rename_and_checks_both_paths() {
3026        let (_dir, repo) = origin_with(&[
3027            ("Cargo.toml", "[package]\nname=\"x\"\nversion=\"0.1.0\"\n"),
3028            ("old.rs", "fn main() {}\n"),
3029        ])
3030        .await;
3031        git::git(&repo, &["mv", "old.rs", "new.rs"]).await.unwrap();
3032        git::git(&repo, &["commit", "-m", "Rename source"])
3033            .await
3034            .unwrap();
3035        let merge = git::rev_parse(&repo, "HEAD").await.unwrap();
3036        let mut evidence = parse_merged_pr_files(
3037            merge,
3038            1,
3039            r#"[[{"filename":"new.rs","previous_filename":"old.rs","additions":0,"deletions":0}]]"#,
3040        )
3041        .unwrap();
3042        assert_eq!(
3043            merged_versions(&repo, &evidence, "Cargo.toml")
3044                .await
3045                .unwrap(),
3046            ("0.1.0".to_owned(), "0.1.0".to_owned())
3047        );
3048        evidence.numstat[0].1 = Some("unrelated.rs".to_owned());
3049        assert!(
3050            merged_versions(&repo, &evidence, "Cargo.toml")
3051                .await
3052                .is_err()
3053        );
3054    }
3055
3056    #[test]
3057    fn merged_pr_files_reject_the_forge_ceiling() {
3058        for count in [PR_FILES_CEILING - 1, PR_FILES_CEILING, PR_FILES_CEILING + 1] {
3059            let entries = (0..count)
3060                .map(|n| PrFile {
3061                    filename: format!("file-{n}"),
3062                    previous_filename: None,
3063                    additions: 1,
3064                    deletions: 0,
3065                })
3066                .collect();
3067            let result = merged_change_from_pages("a".repeat(40), count, vec![entries]);
3068            assert_eq!(result.is_ok(), count < PR_FILES_CEILING);
3069        }
3070    }
3071
3072    #[test]
3073    fn merged_pr_files_deduplicate_rename_paths_without_losing_source_evidence() {
3074        let change = parse_merged_pr_files(
3075            "a".repeat(40),
3076            2,
3077            r#"[
3078                [{"filename":"Cargo.toml","previous_filename":"src/old.rs","additions":1,"deletions":2}],
3079                [{"filename":"Cargo.lock","previous_filename":"Cargo.toml","additions":3,"deletions":4}]
3080            ]"#,
3081        )
3082        .unwrap();
3083        assert_eq!(change.files, ["src/old.rs", "Cargo.toml", "Cargo.lock"]);
3084        assert!(!is_release_only(&change.files));
3085        assert!(
3086            change
3087                .stat
3088                .contains("2 files changed, 4 insertions(+), 6 deletions(-)")
3089        );
3090        assert_eq!(change.numstat.len(), 2);
3091        assert!(parse_merged_pr_files("a".repeat(40), 2, "invalid").is_err());
3092        assert!(parse_merged_pr_files("a".repeat(40), 2, "[[]]").is_err());
3093    }
3094
3095    #[test]
3096    fn merged_pr_metadata_builds_the_canonical_repository_endpoint() {
3097        let mut metadata = serde_json::json!({
3098            "state": "MERGED",
3099            "mergeCommit": {"oid": "a".repeat(40)},
3100            "changedFiles": 2,
3101            "number": 380,
3102            "url": "https://github.com/owner/repo/pull/380"
3103        });
3104        let (merge, expected, endpoint) = merged_pr_metadata(&metadata.to_string()).unwrap();
3105        assert_eq!(merge, "a".repeat(40));
3106        assert_eq!(expected, 2);
3107        assert_eq!(endpoint, "repos/owner/repo/pulls/380/files?per_page=100");
3108        metadata["number"] = serde_json::json!(381);
3109        assert!(merged_pr_metadata(&metadata.to_string()).is_err());
3110        metadata["number"] = serde_json::json!(380);
3111        metadata["state"] = serde_json::json!("OPEN");
3112        assert!(merged_pr_metadata(&metadata.to_string()).is_err());
3113        assert!(merged_pr_metadata("invalid").is_err());
3114    }
3115
3116    #[test]
3117    fn merged_pr_pages_share_complete_guard_and_prompt_evidence() {
3118        let pages = serde_json::from_value(serde_json::json!([
3119            [{"filename":"Cargo.toml","additions":1,"deletions":1}],
3120            [{"filename":"src/fix.rs","additions":7,"deletions":2}]
3121        ]))
3122        .unwrap();
3123        let change = merged_change_from_pages("a".repeat(40), 2, pages).unwrap();
3124        assert!(!is_release_only(&change.files));
3125        let prompt = decision_prompt("fix", "task", &change.stat, &change.files, "1.0.0");
3126        assert!(prompt.contains("src/fix.rs"));
3127        assert!(prompt.contains("2 files changed, 8 insertions(+), 3 deletions(-)"));
3128        let partial = serde_json::from_value(serde_json::json!([
3129            [{"filename":"Cargo.toml","additions":1,"deletions":1}]
3130        ]))
3131        .unwrap();
3132        assert!(merged_change_from_pages("a".repeat(40), 2, partial).is_err());
3133        assert!(merged_change_from_pages("a".repeat(40), 0, vec![]).is_err());
3134    }
3135
3136    #[tokio::test]
3137    async fn unavailable_merged_pr_evidence_notifies_without_a_decision() {
3138        let (_dir, repo) =
3139            origin_with(&[("Cargo.toml", "[package]\nname=\"x\"\nversion=\"0.1.0\"\n")]).await;
3140        let home = tempfile::tempdir().unwrap();
3141        let store = Notices::at(home.path().join("notifications"));
3142        let mut state = winner_state(&repo, "main");
3143        after_merge_using(
3144            &mut state,
3145            "https://example.invalid/pull/1",
3146            Some(home.path()),
3147            Some(&store),
3148            async { bail!("incomplete PR file listing") },
3149        )
3150        .await
3151        .unwrap_err();
3152        assert!(state.bump_decision_attempts.is_empty());
3153        assert_eq!(store.list().len(), 1);
3154        assert!(
3155            state
3156                .release_bump
3157                .as_ref()
3158                .unwrap()
3159                .problem
3160                .as_ref()
3161                .unwrap()
3162                .contains("merged PR")
3163        );
3164    }
3165    #[test]
3166    fn github_facing_bump_text_is_english() {
3167        let (title, body) =
3168            release_pr("minor", "adds a flag", "0.37.0", "ab12", "https://x/pull/1");
3169        assert!(crate::github_text::check(&title, &body).is_empty());
3170        assert!(title.is_ascii() && body.is_ascii(), "{title}\n{body}");
3171        assert_eq!(title, "chore: release v0.37.0 (minor bump)");
3172        assert!(
3173            body.contains("## Background") && body.contains("## Change"),
3174            "{body}"
3175        );
3176        let p = decision_prompt("s", "i", "d", &[], "0.36.5");
3177        assert!(p.contains(crate::prompt::GITHUB_ENGLISH_HEADING), "{p}");
3178    }
3179    use crate::config::Config;
3180    use crate::land::PrLifecycle;
3181
3182    /// `[merge] release_bump = false` must short-circuit before any I/O -
3183    /// `after_merge` is reached from a live run with a real repo and a real
3184    /// `gh`, so the disabled case is asserted with a `RunState` that would
3185    /// fail loudly (an unresolvable `/no/such/repo`) the moment anything past
3186    /// the flag check tried to touch it.
3187    #[tokio::test]
3188    async fn a_disabled_config_does_nothing() {
3189        let config = Config {
3190            merge: crate::config::Merge {
3191                release_bump: false,
3192                ..crate::config::Merge::default()
3193            },
3194            ..Config::default()
3195        };
3196        let mut state = RunState::new(
3197            PathBuf::from("/no/such/repo"),
3198            "main".to_owned(),
3199            "0000000000000000000000000000000000000000".to_owned(),
3200            "irrelevant".to_owned(),
3201            config,
3202        );
3203        after_merge(&mut state, "https://example.invalid/pull/1")
3204            .await
3205            .expect("a disabled config must return Ok without touching anything");
3206        assert!(
3207            state.events.is_empty(),
3208            "nothing should happen at all, not even a logged event"
3209        );
3210    }
3211
3212    /// A bare `origin` plus a clone of it, `main` pushed with `files`.
3213    async fn origin_with(files: &[(&str, &str)]) -> (tempfile::TempDir, PathBuf) {
3214        let dir = tempfile::tempdir().unwrap();
3215        let origin = dir.path().join("origin.git");
3216        let repo = dir.path().join("repo");
3217        let o = origin.to_string_lossy().into_owned();
3218        git::git(dir.path(), &["init", "--bare", "-b", "main", &o])
3219            .await
3220            .unwrap();
3221        tokio::fs::create_dir_all(&repo).await.unwrap();
3222        git::git(&repo, &["init", "-b", "main"]).await.unwrap();
3223        git::git(&repo, &["config", "user.name", "test"])
3224            .await
3225            .unwrap();
3226        git::git(&repo, &["config", "user.email", "test@example.com"])
3227            .await
3228            .unwrap();
3229        for (name, body) in files {
3230            tokio::fs::write(repo.join(name), body).await.unwrap();
3231        }
3232        git::git(&repo, &["add", "-A"]).await.unwrap();
3233        git::git(&repo, &["commit", "-m", "init"]).await.unwrap();
3234        git::git(&repo, &["remote", "add", "origin", &o])
3235            .await
3236            .unwrap();
3237        git::git(&repo, &["push", "origin", "main"]).await.unwrap();
3238        (dir, repo)
3239    }
3240
3241    async fn no_pr(_: String) -> Result<bool> {
3242        Ok(false)
3243    }
3244
3245    /// `origin_with` plus a branch `b` made from `main`, optionally one commit
3246    /// ahead of it.
3247    async fn with_branch(ahead: bool) -> (tempfile::TempDir, PathBuf) {
3248        let (d, repo) = origin_with(&[("f", "x\n")]).await;
3249        git::git(&repo, &["branch", "b"]).await.unwrap();
3250        if ahead {
3251            git::git(&repo, &["checkout", "-q", "b"]).await.unwrap();
3252            git::git(&repo, &["commit", "--allow-empty", "-m", "wip"])
3253                .await
3254                .unwrap();
3255            git::git(&repo, &["checkout", "-q", "main"]).await.unwrap();
3256        }
3257        (d, repo)
3258    }
3259
3260    async fn attempt(repo: &Path, open_pr: bool, fail_after_push: Option<bool>) -> Result<()> {
3261        let wt = repo.parent().unwrap().join("bump");
3262        release_attempt(
3263            repo,
3264            "origin",
3265            "main",
3266            &wt,
3267            "b",
3268            |_| async move { Ok(open_pr) },
3269            |w| async move {
3270                if fail_after_push == Some(true) {
3271                    git::push(&w, "origin", "b").await?;
3272                }
3273                if fail_after_push.is_some() {
3274                    bail!("cargo build failed");
3275                }
3276                Ok(())
3277            },
3278        )
3279        .await
3280    }
3281
3282    #[tokio::test]
3283    async fn a_stale_ancestor_branch_is_deleted_and_the_attempt_proceeds() {
3284        let (_d, repo) = with_branch(false).await;
3285        attempt(&repo, false, None).await.unwrap();
3286        // Success keeps the branch (it backs the pull request).
3287        assert!(git::branch_exists(&repo, "b").await.unwrap());
3288    }
3289
3290    #[tokio::test]
3291    async fn a_stale_branch_holding_a_leftover_worktree_is_reclaimed() {
3292        let (_d, repo) = with_branch(false).await;
3293        let old = repo.parent().unwrap().join("old");
3294        git::git(&repo, &["worktree", "add", &old.to_string_lossy(), "b"])
3295            .await
3296            .unwrap();
3297        attempt(&repo, false, None).await.unwrap();
3298        assert!(!old.exists());
3299    }
3300
3301    #[tokio::test]
3302    async fn a_stale_branch_with_an_unmerged_commit_is_kept_with_a_reason() {
3303        let (_d, repo) = with_branch(true).await;
3304        let e = attempt(&repo, false, None).await.unwrap_err().to_string();
3305        assert!(e.contains("`b`") || e.contains("branch b"), "{e}");
3306        assert!(e.contains("1 commit(s) not in origin/main"), "{e}");
3307        assert!(git::branch_exists(&repo, "b").await.unwrap());
3308    }
3309
3310    #[tokio::test]
3311    async fn a_stale_branch_on_the_remote_is_kept() {
3312        let (_d, repo) = with_branch(false).await;
3313        git::git(&repo, &["push", "origin", "b"]).await.unwrap();
3314        let e = attempt(&repo, false, None).await.unwrap_err().to_string();
3315        assert!(e.contains("branch b") && e.contains("is on origin"), "{e}");
3316        assert!(git::branch_exists(&repo, "b").await.unwrap());
3317    }
3318
3319    #[tokio::test]
3320    async fn a_stale_branch_with_an_open_pull_request_is_kept() {
3321        let (_d, repo) = with_branch(false).await;
3322        let e = attempt(&repo, true, None).await.unwrap_err().to_string();
3323        assert!(e.contains("open pull request"), "{e}");
3324        assert!(git::branch_exists(&repo, "b").await.unwrap());
3325    }
3326
3327    #[tokio::test]
3328    async fn an_unanswerable_pull_request_check_keeps_the_branch() {
3329        let (_d, repo) = with_branch(false).await;
3330        let wt = repo.parent().unwrap().join("bump");
3331        let e = release_attempt(
3332            &repo,
3333            "origin",
3334            "main",
3335            &wt,
3336            "b",
3337            |_| async { bail!("offline") },
3338            |_| async { Ok(()) },
3339        )
3340        .await
3341        .unwrap_err()
3342        .to_string();
3343        assert!(
3344            e.contains("could not check for an open pull request"),
3345            "{e}"
3346        );
3347        assert!(git::branch_exists(&repo, "b").await.unwrap());
3348    }
3349
3350    #[tokio::test]
3351    async fn a_failed_attempt_removes_its_own_worktree_and_branch() {
3352        let (_d, repo) = origin_with(&[("f", "x\n")]).await;
3353        let wt = repo.parent().unwrap().join("bump");
3354        let e = attempt(&repo, false, Some(false)).await.unwrap_err();
3355        assert!(format!("{e:#}").contains("cargo build failed"));
3356        assert!(!wt.exists());
3357        assert!(!git::branch_exists(&repo, "b").await.unwrap());
3358    }
3359
3360    #[tokio::test]
3361    async fn release_worktrees_accept_canonical_paths_from_a_detached_checkout() {
3362        let (dir, repo) = origin_with(&[("f", "remote base\n")]).await;
3363        let base = git::rev_parse(&repo, "origin/main").await.unwrap();
3364        // A detached primary checkout can be newer than the fetched base.
3365        tokio::fs::write(repo.join("f"), "local only\n")
3366            .await
3367            .unwrap();
3368        git::git(&repo, &["commit", "-am", "local only"])
3369            .await
3370            .unwrap();
3371        git::git(&repo, &["checkout", "--detach"]).await.unwrap();
3372        // On Windows canonicalize supplies the verbatim namespace that Git
3373        // cannot use as a checkout destination without path_arg conversion.
3374        let root = std::fs::canonicalize(dir.path()).unwrap();
3375        let worktree = root.join("release bump");
3376        let head = release_attempt(
3377            &repo,
3378            "origin",
3379            "main",
3380            &worktree,
3381            "release-test",
3382            no_pr,
3383            |path| async move {
3384                // Git may check the file out with CRLF (core.autocrlf); the
3385                // contract is the remote base's content, not its line endings.
3386                assert_eq!(
3387                    tokio::fs::read_to_string(path.join("f"))
3388                        .await
3389                        .unwrap()
3390                        .replace("\r\n", "\n"),
3391                    "remote base\n"
3392                );
3393                git::rev_parse(&path, "HEAD").await
3394            },
3395        )
3396        .await
3397        .unwrap();
3398        assert_eq!(head, base);
3399        assert!(!worktree.exists());
3400
3401        // Pending bump escalation uses the forced existing-branch path.
3402        git::worktree_add_existing(&repo, &worktree, "release-test", true)
3403            .await
3404            .unwrap();
3405        assert_eq!(git::rev_parse(&worktree, "HEAD").await.unwrap(), base);
3406        assert_eq!(
3407            tokio::fs::read_to_string(worktree.join("f"))
3408                .await
3409                .unwrap()
3410                .replace("\r\n", "\n"),
3411            "remote base\n"
3412        );
3413        git::worktree_remove(&repo, &worktree).await.unwrap();
3414        git::branch_delete(&repo, "release-test").await.unwrap();
3415
3416        git::worktree_add_branch(&repo, &worktree, "fresh-test", "origin/main")
3417            .await
3418            .unwrap();
3419        assert_eq!(git::rev_parse(&worktree, "HEAD").await.unwrap(), base);
3420        git::worktree_remove(&repo, &worktree).await.unwrap();
3421        git::branch_delete(&repo, "fresh-test").await.unwrap();
3422        assert!(!worktree.exists());
3423    }
3424
3425    #[tokio::test]
3426    async fn a_pushed_branch_survives_a_failed_attempt_and_the_reason_says_so() {
3427        let (_d, repo) = origin_with(&[("f", "x\n")]).await;
3428        let e = attempt(&repo, false, Some(true)).await.unwrap_err();
3429        let e = format!("{e:#}");
3430        assert!(
3431            e.contains("cargo build failed") && e.contains("pushed to origin"),
3432            "{e}"
3433        );
3434        assert!(git::branch_exists(&repo, "b").await.unwrap());
3435    }
3436
3437    #[tokio::test]
3438    async fn a_branch_left_by_a_half_done_worktree_add_is_removed() {
3439        // The branch is created first, but a worktree beneath a regular file
3440        // cannot be checked out. Only this attempt's branch may be removed.
3441        let (_d, repo) = origin_with(&[("f", "x\n")]).await;
3442        let blocker = repo.parent().unwrap().join("blocker");
3443        tokio::fs::write(&blocker, "file").await.unwrap();
3444        let wt = blocker.join("bump");
3445        let r = release_attempt(
3446            &repo,
3447            "origin",
3448            "main",
3449            &wt,
3450            "b",
3451            |_| async { bail!("offline") },
3452            |_| async { Ok(()) },
3453        )
3454        .await;
3455        assert!(r.is_err());
3456        assert!(!git::branch_exists(&repo, "b").await.unwrap());
3457    }
3458
3459    #[tokio::test]
3460    async fn the_retry_is_taken_at_most_once() {
3461        // The branch is reclaimed, but the worktree path cannot be created, so
3462        // the second creation fails too: no third try, and no loop.
3463        let (_d, repo) = with_branch(false).await;
3464        let blocker = repo.parent().unwrap().join("blocker");
3465        tokio::fs::write(&blocker, "file").await.unwrap();
3466        let wt = blocker.join("bump");
3467        let r = release_attempt(&repo, "origin", "main", &wt, "b", no_pr, |_| async {
3468            Ok(())
3469        })
3470        .await;
3471        assert!(r.is_err());
3472        assert!(!git::branch_exists(&repo, "b").await.unwrap());
3473    }
3474
3475    #[tokio::test]
3476    async fn release_worktree_failure_preserves_full_diagnostics_and_operator_data() {
3477        let (dir, repo) = origin_with(&[("f", "x\n")]).await;
3478        let worktree = dir.path().join("occupied");
3479        tokio::fs::create_dir(&worktree).await.unwrap();
3480        let existing = worktree.join("keep");
3481        tokio::fs::write(&existing, "operator data").await.unwrap();
3482        let err = release_attempt::<(), _, _, _, _>(
3483            &repo,
3484            "origin",
3485            "main",
3486            &worktree,
3487            "release-test",
3488            no_pr,
3489            |_| async { panic!("worktree creation must fail before release edits") },
3490        )
3491        .await
3492        .unwrap_err();
3493        let (version, reason) = notice_for_failure(&Progress::default(), &err);
3494        assert!(
3495            reason.contains("create the release-bump worktree"),
3496            "{reason}"
3497        );
3498        assert!(reason.contains("exit code 128"), "{reason}");
3499        assert!(reason.contains("Preparing worktree"), "{reason}");
3500        assert!(reason.contains("\nfatal:"), "{reason}");
3501        let store = Notices::at(dir.path().join("notifications"));
3502        let mut state = winner_state(&repo, "main");
3503        state.status = RunStatus::Merged;
3504        report_problem_in(&mut state, &store, None, version.as_deref(), &reason, false).await;
3505        let notices = store.list();
3506        assert_eq!(notices.len(), 1);
3507        let notice = &notices[0];
3508        assert!(notice.message.contains("fatal:"), "{}", notice.message);
3509        assert!(!notice.message.contains("Some(") && !notice.message.contains("None"));
3510        assert_eq!(notice.severity, Severity::Error);
3511        assert_eq!(state.status, RunStatus::Merged);
3512        assert!(state.needs_attention());
3513        let problem = state
3514            .release_bump
3515            .as_ref()
3516            .unwrap()
3517            .problem
3518            .as_ref()
3519            .unwrap();
3520        assert_eq!(
3521            problem,
3522            &crate::scrub::scrub(&reason, &crate::scrub::Identity::current())
3523        );
3524        let saved = serde_json::to_string(&state).unwrap();
3525        let restored: RunState = serde_json::from_str(&saved).unwrap();
3526        assert_eq!(
3527            restored.release_bump.as_ref().unwrap().problem.as_ref(),
3528            Some(problem)
3529        );
3530        assert!(crate::report::run(&restored).contains("fatal:"));
3531        assert!(!git::branch_exists(&repo, "release-test").await.unwrap());
3532        assert_eq!(
3533            tokio::fs::read_to_string(existing).await.unwrap(),
3534            "operator data"
3535        );
3536    }
3537
3538    #[tokio::test]
3539    async fn base_has_cargo_toml_tells_rust_from_non_rust() {
3540        let (_d, rust) = origin_with(&[("Cargo.toml", "[package]\nversion = \"0.1.0\"\n")]).await;
3541        assert!(base_has_cargo_toml(&rust, "origin", "main").await.unwrap());
3542        let (_d2, other) = origin_with(&[("README.md", "hi\n")]).await;
3543        assert!(!base_has_cargo_toml(&other, "origin", "main").await.unwrap());
3544        // An unresolvable ref is a fault, not "not Rust".
3545        assert!(base_has_cargo_toml(&other, "origin", "nope").await.is_err());
3546    }
3547
3548    #[tokio::test]
3549    async fn a_repo_without_cargo_toml_skips_with_one_event_and_no_lock() {
3550        let (_d, repo) = origin_with(&[("README.md", "hi\n")]).await;
3551        let home = tempfile::tempdir().unwrap();
3552        let mut state = RunState::new(
3553            repo.clone(),
3554            "main".to_owned(),
3555            "0000000000000000000000000000000000000000".to_owned(),
3556            "task".to_owned(),
3557            Config::default(),
3558        );
3559        state.candidates.push(crate::run::Candidate {
3560            index: 0,
3561            label: 'A',
3562            agent: "x".to_owned(),
3563            branch: "main".to_owned(),
3564            worktree: repo.clone(),
3565            summary: String::new(),
3566            stat: String::new(),
3567            files: 1,
3568            commits: 1,
3569            empty: false,
3570            failed: None,
3571            verified_noop: None,
3572            duration_ms: 0,
3573            folded: false,
3574        });
3575        state.tally = Some(
3576            serde_json::from_value(serde_json::json!({
3577                "first_choice": {}, "borda": {}, "winner": "A",
3578                "unanimous_initial": true, "deliberated": false,
3579                "changed_votes": 0, "unanimous_final": true,
3580            }))
3581            .unwrap(),
3582        );
3583        after_merge_at(
3584            &mut state,
3585            "https://example.invalid/pull/1",
3586            Some(home.path()),
3587            None,
3588        )
3589        .await
3590        .expect("a non-Rust repository is not an error");
3591        let bumps: Vec<_> = state.events.iter().filter(|e| e.node == "bump").collect();
3592        assert_eq!(bumps.len(), 1, "{:?}", state.events);
3593        assert_eq!(
3594            bumps[0].message,
3595            "release bump: no Cargo.toml on the base branch; release bumps are Rust-only, skipping"
3596        );
3597        assert!(
3598            std::fs::read_dir(home.path()).unwrap().next().is_none(),
3599            "no marker and no lock may be created"
3600        );
3601    }
3602
3603    fn winner_state(repo: &Path, base: &str) -> RunState {
3604        let mut state = RunState::new(
3605            repo.to_path_buf(),
3606            base.to_owned(),
3607            "0000000000000000000000000000000000000000".to_owned(),
3608            "task".to_owned(),
3609            Config::default(),
3610        );
3611        state.candidates.push(crate::run::Candidate {
3612            index: 0,
3613            label: 'A',
3614            agent: "x".to_owned(),
3615            branch: "main".to_owned(),
3616            worktree: repo.to_path_buf(),
3617            summary: String::new(),
3618            stat: String::new(),
3619            files: 1,
3620            commits: 1,
3621            empty: false,
3622            failed: None,
3623            verified_noop: None,
3624            duration_ms: 0,
3625            folded: false,
3626        });
3627        state.tally = Some(
3628            serde_json::from_value(serde_json::json!({
3629                "first_choice": {}, "borda": {}, "winner": "A",
3630                "unanimous_initial": true, "deliberated": false,
3631                "changed_votes": 0, "unanimous_final": true,
3632            }))
3633            .unwrap(),
3634        );
3635        state
3636    }
3637
3638    #[tokio::test]
3639    async fn a_real_failure_without_a_pr_raises_one_notice_and_a_retry_folds_into_it() {
3640        let (_d, repo) =
3641            origin_with(&[("Cargo.toml", "[package]\nname=\"x\"\nversion=\"0.1.0\"\n")]).await;
3642        let home = tempfile::tempdir().unwrap();
3643        let store = Notices::at(home.path().join("notifications"));
3644        // An unresolvable base is a fault, not "not eligible".
3645        let mut state = winner_state(&repo, "nope");
3646        let url = "https://example.invalid/pull/1";
3647        after_merge_at(&mut state, url, Some(home.path()), Some(&store))
3648            .await
3649            .expect_err("an unresolvable base is a failure");
3650        let listed = store.list();
3651        assert_eq!(listed.len(), 1, "{listed:?}");
3652        assert!(state.events.iter().any(|e| e.node == "bump"));
3653        after_merge_at(&mut state, url, Some(home.path()), Some(&store))
3654            .await
3655            .expect_err("still failing");
3656        let listed = store.list();
3657        assert_eq!(listed.len(), 1, "{listed:?}");
3658        assert_eq!(listed[0].count, 2);
3659    }
3660
3661    #[tokio::test]
3662    async fn not_eligible_cases_raise_no_notice() {
3663        let home = tempfile::tempdir().unwrap();
3664        let store = Notices::at(home.path().join("notifications"));
3665        let url = "https://example.invalid/pull/1";
3666        // No Cargo.toml on the base branch.
3667        let (_d, repo) = origin_with(&[("README.md", "hi\n")]).await;
3668        let mut state = winner_state(&repo, "main");
3669        after_merge_at(&mut state, url, Some(home.path()), Some(&store))
3670            .await
3671            .unwrap();
3672        // Disabled.
3673        let mut state = winner_state(&repo, "nope");
3674        state.config.merge.release_bump = false;
3675        after_merge_at(&mut state, url, Some(home.path()), Some(&store))
3676            .await
3677            .unwrap();
3678        // No winner.
3679        let mut state = winner_state(&repo, "nope");
3680        state.tally = None;
3681        after_merge_at(&mut state, url, Some(home.path()), Some(&store))
3682            .await
3683            .unwrap();
3684        assert!(store.list().is_empty(), "{:?}", store.list());
3685    }
3686
3687    #[test]
3688    fn the_no_pr_notice_follows_the_configured_language() {
3689        let dir = tempfile::tempdir().unwrap();
3690        let store = Notices::at(dir.path().join("notifications"));
3691        let mut state = merged_state();
3692        state.config.graph.language = "ja".to_owned();
3693        let (n, _) = surface_problem(&mut state, &store, None, Some("0.2.0"), "boom").unwrap();
3694        assert!(n.message.contains("実行されませんでした"), "{}", n.message);
3695        assert!(n.message.contains("boom") && n.message.contains("v0.2.0"));
3696    }
3697
3698    #[test]
3699    fn a_failed_escalation_points_at_the_pending_pr_without_commenting() {
3700        let dir = tempfile::tempdir().unwrap();
3701        let store = Notices::at(dir.path().join("notifications"));
3702        let mut state = merged_state();
3703        let url = "https://example.invalid/pull/9";
3704        let (n, comment) = surface_problem_in(
3705            &mut state,
3706            &store,
3707            Some(url),
3708            Some("0.3.0"),
3709            "push failed",
3710            true,
3711        )
3712        .unwrap();
3713        assert!(comment.is_none());
3714        assert!(
3715            n.message.contains(url) && n.message.contains("v0.3.0"),
3716            "{}",
3717            n.message
3718        );
3719        assert!(!n.message.contains("open the release pull request by hand"));
3720        assert!(matches!(n.link, Some(Link::Url { .. })));
3721    }
3722
3723    #[test]
3724    fn a_failure_notice_preserves_the_full_error_chain() {
3725        let err = anyhow!("outer context").context("cargo build failed\nsecond line");
3726        let with_pr = Progress {
3727            version: Some("0.2.0".into()),
3728            pending_pr: Some("https://example.invalid/pull/9".into()),
3729            skip: None,
3730        };
3731        let (v, reason) = notice_for_failure(&with_pr, &err);
3732        assert_eq!(v.as_deref(), Some("0.2.0"));
3733        assert_eq!(reason, "cargo build failed\nsecond line: outer context");
3734        let (v, reason) = notice_for_failure(&Progress::default(), &err);
3735        assert_eq!(v, None);
3736        assert_eq!(reason, "cargo build failed\nsecond line: outer context");
3737    }
3738
3739    #[test]
3740    fn failure_headline_prefers_git_errors_and_skips_blank_lines() {
3741        assert_eq!(
3742            failure_headline("checkout failed\nPreparing worktree\n  fatal: invalid path\n"),
3743            Some("fatal: invalid path")
3744        );
3745        assert_eq!(
3746            failure_headline("Preparing worktree\n error: checkout failed\n"),
3747            Some("error: checkout failed")
3748        );
3749        assert_eq!(
3750            failure_headline("\n  \n first cause \nsecond"),
3751            Some("first cause")
3752        );
3753        assert_eq!(failure_headline(" \n\t"), None);
3754    }
3755
3756    const NO_RULES: &str = "gh pr merge --auto: GraphQL: Pull request Branch does not have \
3757                            required protected branch rules (enablePullRequestAutoMerge)";
3758
3759    fn merged_state() -> RunState {
3760        // `report::run` prints `state.dir()`; pin the global home like the
3761        // report tests do so nothing reaches the operator's real one.
3762        run::pin_test_home();
3763        let mut s = RunState::new(
3764            PathBuf::from("/no/such/repo"),
3765            "main".to_owned(),
3766            "0000000000000000000000000000000000000000".to_owned(),
3767            "task".to_owned(),
3768            Config::default(),
3769        );
3770        s.status = RunStatus::Merged;
3771        s
3772    }
3773
3774    #[cfg(unix)]
3775    fn decision_cli(id: &str, reply: &str, exit: &str) -> AgentSpec {
3776        AgentSpec {
3777            id: id.into(),
3778            kind: crate::config::AgentKind::Command,
3779            model: None,
3780            command: vec![
3781                "sh".into(),
3782                "-c".into(),
3783                concat!(
3784                    "if [ \"$STATUS\" = timeout ]; then exec sleep 5; fi; ",
3785                    "printf '%s' \"$REPLY\"; exit \"$STATUS\""
3786                )
3787                .into(),
3788            ],
3789            extra_args: Vec::new(),
3790            env: std::collections::BTreeMap::from([
3791                ("REPLY".into(), reply.into()),
3792                ("STATUS".into(), exit.into()),
3793            ]),
3794            prompt_delivery: None,
3795            max_turn_secs: None,
3796        }
3797    }
3798
3799    #[cfg(unix)]
3800    fn decision_state(agents: Vec<AgentSpec>, preferences: &[&str]) -> RunState {
3801        let mut state = merged_state();
3802        state.config.agents = agents;
3803        state.config.roles.chatter = Some(crate::config::AgentChoice::Chain(
3804            preferences.iter().map(|s| (*s).to_owned()).collect(),
3805        ));
3806        state
3807    }
3808
3809    #[cfg(unix)]
3810    const VALID_DECISION: &str = r#"{"level":"minor","reason":"Adds a feature."}"#;
3811
3812    #[cfg(unix)]
3813    #[tokio::test]
3814    async fn decision_failover_handles_each_unusable_cli_outcome() {
3815        for (reply, exit, expected) in [
3816            (
3817                r#"{"is_error":true,"api_error_status":429,"api_error":"usage_limit_reached"}"#,
3818                "1",
3819                "rate/quota limit",
3820            ),
3821            (
3822                r#"{"is_error":true,"api_error_status":429,"api_error":"usage_limit_reached","level":"minor","reason":"Looks valid."}"#,
3823                "0",
3824                "rate/quota limit",
3825            ),
3826            (
3827                r#"{"is_error":true,"api_error_status":"429","api_error":"usage_limit_reached","level":"minor","reason":"Looks valid."}"#,
3828                "0",
3829                "rate/quota limit",
3830            ),
3831            ("", "0", "empty output"),
3832            (
3833                "",
3834                "spawn",
3835                "CLI invocation failed; inspect attempt artifacts",
3836            ),
3837            ("not JSON", "0", "invalid decision JSON or missing reason"),
3838            (VALID_DECISION, "1", "CLI failed (exit code 1)"),
3839            ("", "timeout", "timed out"),
3840        ] {
3841            let dir = tempfile::tempdir().unwrap();
3842            let mut state = decision_state(
3843                vec![
3844                    decision_cli("first", reply, exit),
3845                    decision_cli("second", VALID_DECISION, "0"),
3846                ],
3847                &["first", "second"],
3848            );
3849            if exit == "spawn" {
3850                state.config.agents[0].command = vec!["magi-test-no-such-decision-cli".into()];
3851            }
3852            let (spec, seat, decision) =
3853                ask_decision(&mut state, dir.path(), "decide", Duration::from_millis(200))
3854                    .await
3855                    .unwrap();
3856            assert_eq!(spec.id, "second");
3857            assert_eq!(decision.level, BumpLevel::Minor);
3858            assert_eq!(state.bump_decision_attempts.len(), 2);
3859            assert_eq!(state.bump_decision_attempts[0].outcome, expected);
3860            assert_eq!(state.handovers.len(), 1);
3861            assert_eq!(state.handovers[0].to, "second");
3862            assert_ne!(
3863                seat.claude_session,
3864                SeatState::new("bump", "first", state.seed).claude_session
3865            );
3866            let report = crate::report::run(&state);
3867            assert!(report.contains(expected), "{report}");
3868            assert!(report.contains("second: valid decision"), "{report}");
3869            assert!(state.release_bump.is_none());
3870            let artifacts = agent::artifacts_dir(&state.dir());
3871            if exit != "spawn" {
3872                assert!(artifacts.join("bump-decision-1.out").exists());
3873            }
3874            assert!(artifacts.join("bump-decision-2.out").exists());
3875        }
3876    }
3877
3878    #[cfg(unix)]
3879    #[tokio::test]
3880    async fn decision_chain_respects_preferences_and_stops_on_first_success() {
3881        let dir = tempfile::tempdir().unwrap();
3882        let mut state = decision_state(
3883            vec![
3884                decision_cli("first", "bad", "1"),
3885                decision_cli("second", VALID_DECISION, "0"),
3886            ],
3887            &["missing", "second", "second", "first"],
3888        );
3889        let (spec, _, _) = ask_decision(&mut state, dir.path(), "decide", Duration::from_secs(1))
3890            .await
3891            .unwrap();
3892        assert_eq!(spec.id, "second");
3893        assert_eq!(state.bump_decision_attempts.len(), 1);
3894        assert!(state.handovers.is_empty());
3895    }
3896
3897    #[cfg(unix)]
3898    #[tokio::test]
3899    async fn decision_chain_consumes_same_failure_classes_and_preserves_unset_policy() {
3900        let dir = tempfile::tempdir().unwrap();
3901        let mut state = decision_state(
3902            vec![
3903                decision_cli("first", "bad", "0"),
3904                decision_cli("second", "bad", "0"),
3905                decision_cli("third", VALID_DECISION, "0"),
3906            ],
3907            &["first", "second", "third"],
3908        );
3909        let (spec, _, _) = ask_decision(&mut state, dir.path(), "decide", Duration::from_secs(2))
3910            .await
3911            .unwrap();
3912        assert_eq!(spec.id, "third");
3913        assert_eq!(state.bump_decision_attempts.len(), 3);
3914        assert_eq!(state.handovers.len(), 2);
3915        // No configured fallback list means the existing single default pick.
3916        state.config.roles.chatter = None;
3917        let err = ask_decision(&mut state, dir.path(), "decide", Duration::from_secs(2))
3918            .await
3919            .unwrap_err();
3920        assert!(err.to_string().contains("exhausted 1 eligible agent(s)"));
3921        assert_eq!(state.bump_decision_attempts.len(), 4);
3922    }
3923
3924    #[cfg(unix)]
3925    #[tokio::test]
3926    async fn decision_reason_rewrite_failure_preserves_the_selected_level() {
3927        let dir = tempfile::tempdir().unwrap();
3928        for reply in ["invalid", r#"{"level":"patch","reason":"Fixes a defect."}"#] {
3929            let mut state = merged_state();
3930            state.config.graph.github_text_guard = true;
3931            state.config.graph.github_language = "en".into();
3932            let spec = decision_cli("chosen", reply, "0");
3933            let mut seat = SeatState::new("bump", &spec.id, state.seed);
3934            let mut decision =
3935                parse_decision(r#"{"level":"minor","reason":"新しい機能を追加しました。"}"#)
3936                    .unwrap();
3937            guard_reason(
3938                &mut state,
3939                dir.path(),
3940                "decide",
3941                &spec,
3942                &mut seat,
3943                &mut decision,
3944            )
3945            .await;
3946            assert_eq!(decision.level, BumpLevel::Minor);
3947            assert_eq!(decision.reason, "The merged change requires a release.");
3948            assert!(state.handovers.is_empty());
3949            assert!(state.bump_decision_attempts.is_empty());
3950        }
3951    }
3952
3953    #[cfg(unix)]
3954    #[tokio::test]
3955    async fn decision_exhaustion_is_bounded_reported_and_leaves_no_release_outcome() {
3956        let dir = tempfile::tempdir().unwrap();
3957        let mut state = decision_state(
3958            vec![
3959                decision_cli("first", "bad", "0"),
3960                decision_cli("second", "", "0"),
3961            ],
3962            &["first", "first", "second", "second"],
3963        );
3964        let err = ask_decision(&mut state, dir.path(), "decide", Duration::from_secs(1))
3965            .await
3966            .unwrap_err()
3967            .to_string();
3968        assert!(err.contains("exhausted 2 eligible agent(s)"), "{err}");
3969        assert!(err.contains("first: invalid decision JSON"), "{err}");
3970        assert!(err.contains("second: empty output"), "{err}");
3971        assert!(err.contains("[roles] chatter"), "{err}");
3972        assert_eq!(state.bump_decision_attempts.len(), 2);
3973        assert_eq!(state.handovers.len(), 1);
3974        assert!(state.release_bump.is_none());
3975        let report = crate::report::run(&state);
3976        assert!(report.contains("first: invalid decision JSON"));
3977        assert!(report.contains("second: empty output"));
3978        let restored: RunState =
3979            serde_json::from_slice(&serde_json::to_vec(&state).unwrap()).unwrap();
3980        assert_eq!(restored.bump_decision_attempts.len(), 2);
3981    }
3982
3983    #[test]
3984    fn the_known_automerge_refusal_names_branch_protection() {
3985        assert!(automerge_hint(NO_RULES).contains("branch protection with required"));
3986        let other = automerge_hint("gh: network unreachable");
3987        assert!(!other.contains("branch protection"), "{other}");
3988        let body = automerge_failure_comment(NO_RULES);
3989        assert!(body.contains("enablePullRequestAutoMerge"), "{body}");
3990        assert!(body.contains("Action required"), "{body}");
3991    }
3992
3993    const CLEAN: &str = "gh pr merge --auto: GraphQL: Pull request Pull request is in clean \
3994                         status (enablePullRequestAutoMerge)";
3995
3996    #[test]
3997    fn clean_status_refusal_is_matched_narrowly() {
3998        assert!(is_clean_status_refusal(CLEAN));
3999        assert!(!is_clean_status_refusal(NO_RULES));
4000        assert!(!is_clean_status_refusal("gh: network unreachable"));
4001        assert!(!is_clean_status_refusal("Pull request is in clean status"));
4002        assert!(automerge_hint(CLEAN).contains("already green"));
4003    }
4004
4005    #[test]
4006    fn the_direct_merge_argv_matches_the_land_flags() {
4007        let a = bump_merge_argv("https://github.com/o/r/pull/9", "chore: release v1.0.0");
4008        let l = land::merge_argv(9, "chore: release v1.0.0");
4009        assert_eq!(a[..2], l[..2]);
4010        assert_eq!(a[3..], l[3..]);
4011        assert_eq!(a[2], "https://github.com/o/r/pull/9");
4012    }
4013
4014    #[test]
4015    fn a_direct_merge_is_judged_by_the_forge_not_the_exit_code() {
4016        let argv = bump_merge_argv("u", "t");
4017        let merged = |o: &AutomergeOutcome| matches!(o, AutomergeOutcome::MergedDirectly { .. });
4018        assert!(merged(&resolve_direct_merge(CLEAN, &argv, true, "", None)));
4019        let detached = "not on any branch";
4020        assert!(merged(&resolve_direct_merge(
4021            CLEAN,
4022            &argv,
4023            false,
4024            detached,
4025            Some(PrLifecycle::Merged)
4026        )));
4027        for after in [Some(PrLifecycle::Open), None] {
4028            let o = resolve_direct_merge(CLEAN, &argv, false, "boom", after);
4029            match o {
4030                AutomergeOutcome::Failed { reason } => {
4031                    assert!(
4032                        reason.contains("clean status") && reason.contains("boom"),
4033                        "{reason}"
4034                    )
4035                }
4036                other => panic!("expected Failed, got {other:?}"),
4037            }
4038        }
4039    }
4040
4041    #[test]
4042    fn a_local_mode_bump_reads_back_and_old_records_are_not_local() {
4043        let old: run::ReleaseBump =
4044            serde_json::from_str(r#"{"pr_url":"u","automerge_enabled":true}"#).unwrap();
4045        assert!(!old.local);
4046        let mut state = merged_state();
4047        state.release_bump = Some(run::ReleaseBump {
4048            pr_url: Some("https://github.com/o/r/pull/9".to_owned()),
4049            version: Some("1.0.0".to_owned()),
4050            local: true,
4051            ..run::ReleaseBump::default()
4052        });
4053        // Not a failure: nothing was supposed to be armed.
4054        assert!(!state.needs_attention());
4055        let text = crate::report::run(&state);
4056        assert!(text.contains("release.mode = local"), "{text}");
4057        assert!(!text.contains("FAILED"), "{text}");
4058    }
4059
4060    #[test]
4061    fn a_directly_merged_bump_is_not_reported_as_pending_or_failed() {
4062        let mut state = merged_state();
4063        state.release_bump = Some(run::ReleaseBump {
4064            pr_url: Some("https://github.com/o/r/pull/9".to_owned()),
4065            version: Some("1.0.0".to_owned()),
4066            merged_directly: true,
4067            ..run::ReleaseBump::default()
4068        });
4069        assert!(!state.needs_attention());
4070        let text = crate::report::run(&state);
4071        assert!(text.contains("merged directly"), "{text}");
4072        assert!(!text.contains("FAILED"), "{text}");
4073    }
4074
4075    #[test]
4076    fn an_automerge_failure_is_recorded_shown_and_filed_and_survives_settling() {
4077        let dir = tempfile::tempdir().unwrap();
4078        let store = Notices::at(dir.path().join("notifications"));
4079        let questions = ask::Questions::at(dir.path().join("questions"));
4080        let mut state = merged_state();
4081        let url = "https://github.com/o/r/pull/35";
4082
4083        let (n, comment) =
4084            surface_problem(&mut state, &store, Some(url), Some("0.8.0"), NO_RULES).unwrap();
4085
4086        // The comment goes on the release PR and carries reason and fix.
4087        let comment = comment.expect("a PR was opened, so it gets a comment");
4088        assert!(comment.contains("branch protection"), "{comment}");
4089
4090        // The run is still Merged, but no longer reads as plain green.
4091        assert_eq!(state.status, RunStatus::Merged);
4092        assert!(state.needs_attention());
4093        let text = crate::report::run(&state);
4094        assert!(text.contains("release bump"), "{text}");
4095        assert!(text.contains("FAILED"), "{text}");
4096        assert!(text.contains(url), "{text}");
4097        assert!(text.contains("action required"), "{text}");
4098        assert!(crate::report::line(&state).contains("release needs a human"));
4099
4100        // Exactly one notification, linked to the PR, and no question.
4101        assert_eq!(n.severity, Severity::Error);
4102        assert_eq!(
4103            n.link,
4104            Some(Link::Url {
4105                url: url.to_owned()
4106            })
4107        );
4108        assert_eq!(store.list().len(), 1);
4109        assert!(questions.open_for(&state.id).is_empty());
4110
4111        // A retry of the same failure folds into the same entry.
4112        surface_problem(&mut state, &store, Some(url), Some("0.8.0"), NO_RULES).unwrap();
4113        let listed = store.list();
4114        assert_eq!(listed.len(), 1);
4115        assert_eq!(listed[0].count, 2);
4116    }
4117
4118    #[test]
4119    fn a_bump_that_never_ran_is_surfaced_without_a_pr_comment() {
4120        let dir = tempfile::tempdir().unwrap();
4121        let store = Notices::at(dir.path().join("notifications"));
4122        let mut state = merged_state();
4123        let (n, comment) = surface_problem(&mut state, &store, None, None, "no agent").unwrap();
4124        assert!(comment.is_none());
4125        assert!(matches!(n.link, Some(Link::Run { .. })));
4126        assert!(state.needs_attention());
4127    }
4128
4129    #[test]
4130    fn version_parses_and_bumps_each_digit() {
4131        let v = Version::parse("0.4.0").unwrap();
4132        assert_eq!(
4133            v,
4134            Version {
4135                major: 0,
4136                minor: 4,
4137                patch: 0
4138            }
4139        );
4140
4141        assert_eq!(v.bump(BumpLevel::Major).to_string(), "1.0.0");
4142        assert_eq!(v.bump(BumpLevel::Minor).to_string(), "0.5.0");
4143        assert_eq!(v.bump(BumpLevel::Patch).to_string(), "0.4.1");
4144    }
4145
4146    #[test]
4147    fn version_tolerates_a_prerelease_suffix_on_patch() {
4148        let v = Version::parse("1.2.3-rc1").unwrap();
4149        assert_eq!(
4150            v,
4151            Version {
4152                major: 1,
4153                minor: 2,
4154                patch: 3
4155            }
4156        );
4157    }
4158
4159    #[test]
4160    fn version_rejects_garbage() {
4161        assert!(Version::parse("not-a-version").is_err());
4162        assert!(Version::parse("1.2").is_err());
4163    }
4164
4165    #[test]
4166    fn decision_parses_each_level() {
4167        for (json, level) in [
4168            (
4169                r#"{"level":"major","reason":"drops a config key"}"#,
4170                BumpLevel::Major,
4171            ),
4172            (
4173                r#"{"level":"minor","reason":"adds a new flag"}"#,
4174                BumpLevel::Minor,
4175            ),
4176            (
4177                r#"{"level":"patch","reason":"fixes a race"}"#,
4178                BumpLevel::Patch,
4179            ),
4180        ] {
4181            let decision = parse_decision(json).unwrap();
4182            assert_eq!(decision.level, level);
4183            assert!(!decision.reason.is_empty());
4184        }
4185    }
4186
4187    #[test]
4188    fn decision_wrapped_in_a_fence_and_prose_still_parses() {
4189        let text = "Here is my call.\n\n```json\n{\"level\":\"minor\",\"reason\":\"new HTTP route\"}\n```\n\nDone.";
4190        let decision = parse_decision(text).unwrap();
4191        assert_eq!(decision.level, BumpLevel::Minor);
4192        assert_eq!(decision.reason, "new HTTP route");
4193    }
4194
4195    #[test]
4196    fn a_broken_reply_is_an_error_not_a_default() {
4197        assert!(parse_decision("I decline to answer.").is_err());
4198        assert!(parse_decision(r#"{"level":"huge","reason":"go big"}"#).is_err());
4199        assert!(
4200            parse_decision(r#"{"level":"patch","reason":""}"#).is_err(),
4201            "an empty reason must not pass either"
4202        );
4203        assert!(
4204            parse_decision(r#"{"level":"patch"}"#).is_err(),
4205            "a reply with no reason at all must not pass"
4206        );
4207    }
4208
4209    #[test]
4210    fn prompt_states_the_zero_x_rule_and_the_tie_break() {
4211        let prompt = decision_prompt(
4212            "feat: add a phone endpoint",
4213            "add POST /api/widgets",
4214            "1 file changed, 10 insertions(+)",
4215            &["src/web.rs".to_owned()],
4216            "0.8.0",
4217        );
4218        assert!(prompt.contains("0.8.0"), "the current version is stated");
4219        assert!(
4220            prompt.contains("below `1.0.0`")
4221                && prompt.contains("`minor` is the digit that carries a breaking change"),
4222            "the 0.x rule must be explicit: {prompt}"
4223        );
4224        assert!(
4225            prompt.contains("choose the larger"),
4226            "the tie-break toward the bigger digit must be explicit: {prompt}"
4227        );
4228    }
4229
4230    #[test]
4231    fn release_only_diffs_are_recognised() {
4232        assert!(is_release_only(&["Cargo.toml".to_owned()]));
4233        assert!(is_release_only(&[
4234            "Cargo.toml".to_owned(),
4235            "Cargo.lock".to_owned()
4236        ]));
4237        assert!(!is_release_only(&[]));
4238        assert!(!is_release_only(&[
4239            "Cargo.toml".to_owned(),
4240            "src/main.rs".to_owned()
4241        ]));
4242    }
4243
4244    #[test]
4245    fn cargo_version_rewrite_touches_only_the_package_table() {
4246        let toml = "\
4247[package]\n\
4248# a comment mentioning version on purpose\n\
4249name = \"magi-cli\"\n\
4250version = \"0.8.0\"\n\
4251edition = \"2024\"\n\
4252\n\
4253[dependencies]\n\
4254foo = { version = \"1.2.3\" }\n";
4255        let out = rewrite_cargo_version(toml, "0.9.0").unwrap();
4256        assert!(out.contains("version = \"0.9.0\""));
4257        assert!(
4258            out.contains("foo = { version = \"1.2.3\" }"),
4259            "a dependency's own version pin must survive: {out}"
4260        );
4261        assert!(
4262            out.contains("# a comment mentioning version on purpose"),
4263            "unrelated lines, comments included, must be byte-for-byte preserved: {out}"
4264        );
4265        assert_eq!(
4266            out.lines().count(),
4267            toml.lines().count(),
4268            "the rewrite replaces one line, it does not add or remove any"
4269        );
4270    }
4271
4272    #[test]
4273    fn cargo_version_rewrite_fails_without_a_package_table() {
4274        let toml = "[dependencies]\nfoo = \"1\"\n";
4275        assert!(rewrite_cargo_version(toml, "1.0.0").is_err());
4276    }
4277
4278    /// The shape `kanadehq/kanade` has: a workspace root with member crates
4279    /// but no crate of its own, so `[package]` never exists and the version
4280    /// lives under `[workspace.package]` alone. Before this fell back,
4281    /// `rewrite_cargo_version` bailed on every such repository and no bump
4282    /// pull request was ever opened for it.
4283    #[test]
4284    fn cargo_version_rewrite_falls_back_to_workspace_package_without_a_package_table() {
4285        let toml = "\
4286[workspace]\n\
4287members = [\"crates/a\", \"crates/b\"]\n\
4288\n\
4289[workspace.package]\n\
4290version = \"0.45.18\"\n\
4291edition = \"2024\"\n\
4292\n\
4293[workspace.dependencies]\n\
4294foo = { version = \"1.2.3\" }\n";
4295        let out = rewrite_cargo_version(toml, "0.45.19").unwrap();
4296        assert!(out.contains("version = \"0.45.19\""));
4297        assert!(
4298            out.contains("foo = { version = \"1.2.3\" }"),
4299            "a workspace dependency's own version pin must survive: {out}"
4300        );
4301        assert_eq!(
4302            out.lines().count(),
4303            toml.lines().count(),
4304            "the rewrite replaces one line, it does not add or remove any"
4305        );
4306    }
4307
4308    /// The exact failure that happened on `kanadehq/kanade`: an internal
4309    /// member referenced by both `path` and `version` must have its pin
4310    /// bumped alongside `[workspace.package]`, in the same edit.
4311    #[test]
4312    fn cargo_version_rewrite_bumps_an_internal_workspace_dependency_pin() {
4313        let toml = "\
4314[workspace]\n\
4315members = [\"crates/kanade-shared\"]\n\
4316\n\
4317[workspace.package]\n\
4318version = \"0.48.2\"\n\
4319\n\
4320[workspace.dependencies]\n\
4321kanade-shared = { path = \"crates/kanade-shared\", version = \"0.48.2\" }\n";
4322        let out = rewrite_cargo_version(toml, "0.48.3").unwrap();
4323        assert!(out.contains("[workspace.package]\nversion = \"0.48.3\"\n"));
4324        assert!(
4325            out.contains(
4326                "kanade-shared = { path = \"crates/kanade-shared\", version = \"0.48.3\" }"
4327            ),
4328            "the internal pin must move with the workspace version: {out}"
4329        );
4330    }
4331
4332    /// Key order inside the inline table must not matter.
4333    #[test]
4334    fn cargo_version_rewrite_bumps_an_internal_pin_with_version_before_path() {
4335        let toml = "\
4336[workspace.package]\n\
4337version = \"1.0.0\"\n\
4338\n\
4339[workspace.dependencies]\n\
4340inner = { version = \"1.0.0\", path = \"crates/inner\" }\n";
4341        let out = rewrite_cargo_version(toml, "1.0.1").unwrap();
4342        assert!(out.contains("inner = { version = \"1.0.1\", path = \"crates/inner\" }"));
4343    }
4344
4345    /// The dotted-table form (`[workspace.dependencies.name]`) must be
4346    /// rewritten too, not only the inline-table form.
4347    #[test]
4348    fn cargo_version_rewrite_bumps_an_internal_pin_in_dotted_table_form() {
4349        let toml = "\
4350[workspace.package]\n\
4351version = \"2.3.0\"\n\
4352\n\
4353[workspace.dependencies.inner]\n\
4354path = \"crates/inner\"\n\
4355version = \"2.3.0\"\n";
4356        let out = rewrite_cargo_version(toml, "2.4.0").unwrap();
4357        assert!(out.contains("[workspace.package]\nversion = \"2.4.0\"\n"));
4358        assert!(out.contains(
4359            "[workspace.dependencies.inner]\npath = \"crates/inner\"\nversion = \"2.4.0\"\n"
4360        ));
4361    }
4362
4363    /// The dotted-key form written as two separate lines directly under the
4364    /// flat `[workspace.dependencies]` table - no inline table, no
4365    /// `[workspace.dependencies.name]` sub-header - is also valid TOML and
4366    /// must have its `version` line rewritten.
4367    #[test]
4368    fn cargo_version_rewrite_bumps_an_internal_pin_in_dotted_key_form() {
4369        let toml = "\
4370[workspace.package]\n\
4371version = \"2.3.0\"\n\
4372\n\
4373[workspace.dependencies]\n\
4374inner.path = \"crates/inner\"\n\
4375inner.version = \"2.3.0\"\n";
4376        let out = rewrite_cargo_version(toml, "2.4.0").unwrap();
4377        assert!(out.contains("[workspace.package]\nversion = \"2.4.0\"\n"));
4378        assert!(out.contains("inner.path = \"crates/inner\"\ninner.version = \"2.4.0\"\n"));
4379    }
4380
4381    /// A workspace-only member with `path` but no `version` is unpublished
4382    /// and must be left exactly alone.
4383    #[test]
4384    fn cargo_version_rewrite_leaves_a_path_only_workspace_dependency_untouched() {
4385        let toml = "\
4386[workspace.package]\n\
4387version = \"0.1.0\"\n\
4388\n\
4389[workspace.dependencies]\n\
4390internal-only = { path = \"crates/internal-only\" }\n";
4391        let out = rewrite_cargo_version(toml, "0.2.0").unwrap();
4392        assert!(out.contains("internal-only = { path = \"crates/internal-only\" }"));
4393    }
4394
4395    /// An external crates.io dependency, `version` but no `path`, must never
4396    /// be touched by the internal-pin logic even when it sits in
4397    /// `[workspace.dependencies]` alongside a real internal pin.
4398    #[test]
4399    fn cargo_version_rewrite_leaves_an_external_dependency_untouched() {
4400        let toml = "\
4401[workspace.package]\n\
4402version = \"0.1.0\"\n\
4403\n\
4404[workspace.dependencies]\n\
4405serde = { version = \"1\", features = [\"derive\"] }\n\
4406inner = { path = \"crates/inner\", version = \"0.1.0\" }\n";
4407        let out = rewrite_cargo_version(toml, "0.2.0").unwrap();
4408        assert!(out.contains("serde = { version = \"1\", features = [\"derive\"] }"));
4409        assert!(out.contains("inner = { path = \"crates/inner\", version = \"0.2.0\" }"));
4410    }
4411
4412    /// A manifest with no `[workspace.dependencies]` table at all must keep
4413    /// bumping `[workspace.package]` exactly as before - regression guard
4414    /// for the pre-existing behaviour this change extends.
4415    #[test]
4416    fn cargo_version_rewrite_without_workspace_dependencies_table_still_bumps_package() {
4417        let toml = "[workspace.package]\nversion = \"0.9.0\"\nedition = \"2024\"\n";
4418        let out = rewrite_cargo_version(toml, "0.10.0").unwrap();
4419        assert_eq!(
4420            out,
4421            "[workspace.package]\nversion = \"0.10.0\"\nedition = \"2024\"\n"
4422        );
4423    }
4424
4425    /// The `kanadehq/kanade` shape itself: several internal-looking and
4426    /// external entries mixed in one `[workspace.dependencies]` table.
4427    #[test]
4428    fn cargo_version_rewrite_handles_a_kanade_shaped_workspace_dependencies_table() {
4429        let toml = "\
4430[workspace.package]\n\
4431version = \"0.48.2\"\n\
4432\n\
4433[workspace.dependencies]\n\
4434anyhow = { version = \"1\" }\n\
4435serde = { version = \"1\", features = [\"derive\"] }\n\
4436kanade-shared = { path = \"crates/kanade-shared\", version = \"0.48.2\" }\n\
4437kanade-core = { path = \"crates/kanade-core\", version = \"0.48.2\" }\n\
4438kanade-internal-tool = { path = \"crates/kanade-internal-tool\" }\n";
4439        let out = rewrite_cargo_version(toml, "0.48.3").unwrap();
4440        assert!(out.contains("anyhow = { version = \"1\" }"));
4441        assert!(out.contains("serde = { version = \"1\", features = [\"derive\"] }"));
4442        assert!(
4443            out.contains(
4444                "kanade-shared = { path = \"crates/kanade-shared\", version = \"0.48.3\" }"
4445            )
4446        );
4447        assert!(
4448            out.contains("kanade-core = { path = \"crates/kanade-core\", version = \"0.48.3\" }")
4449        );
4450        assert!(out.contains("kanade-internal-tool = { path = \"crates/kanade-internal-tool\" }"));
4451    }
4452
4453    /// A shape the line-based rewrite cannot express - an inline table split
4454    /// across lines - must fail the whole bump rather than silently leave
4455    /// the pin stale.
4456    #[test]
4457    fn cargo_version_rewrite_bails_on_an_unrepresentable_inline_table() {
4458        let toml = "\
4459[workspace.package]\n\
4460version = \"0.1.0\"\n\
4461\n\
4462[workspace.dependencies]\n\
4463inner = { path = \"crates/inner\",\n\
4464    version = \"0.1.0\" }\n";
4465        assert!(rewrite_cargo_version(toml, "0.2.0").is_err());
4466    }
4467
4468    /// A trailing comment on the `[workspace.dependencies]` header itself is
4469    /// valid TOML and must not stop the section from being recognised.
4470    #[test]
4471    fn cargo_version_rewrite_recognises_a_commented_workspace_dependencies_header() {
4472        let toml = "\
4473[workspace.package]\n\
4474version = \"0.1.0\"\n\
4475\n\
4476[workspace.dependencies] # internal pins\n\
4477inner = { path = \"crates/inner\", version = \"0.1.0\" }\n";
4478        let out = rewrite_cargo_version(toml, "0.2.0").unwrap();
4479        assert!(out.contains("inner = { path = \"crates/inner\", version = \"0.2.0\" }"));
4480    }
4481
4482    /// A quoted dependency key (`"inner" = { .. }`) is valid TOML and must
4483    /// compare equal to the plain name the `toml` crate itself reports.
4484    #[test]
4485    fn cargo_version_rewrite_bumps_a_quoted_dependency_key() {
4486        let toml = "\
4487[workspace.package]\n\
4488version = \"0.1.0\"\n\
4489\n\
4490[workspace.dependencies]\n\
4491\"inner\" = { path = \"crates/inner\", version = \"0.1.0\" }\n";
4492        let out = rewrite_cargo_version(toml, "0.2.0").unwrap();
4493        assert!(out.contains("\"inner\" = { path = \"crates/inner\", version = \"0.2.0\" }"));
4494    }
4495
4496    /// A literal (single-quoted) TOML string is a legal way to spell a
4497    /// version pin, and the rewrite must preserve that quoting style rather
4498    /// than failing to find it or silently switching it to a basic string.
4499    #[test]
4500    fn cargo_version_rewrite_bumps_a_literal_string_version_pin() {
4501        let toml = "\
4502[workspace.package]\n\
4503version = \"0.1.0\"\n\
4504\n\
4505[workspace.dependencies]\n\
4506inner = { path = 'crates/inner', version = '0.1.0' }\n";
4507        let out = rewrite_cargo_version(toml, "0.2.0").unwrap();
4508        assert!(out.contains("inner = { path = 'crates/inner', version = '0.2.0' }"));
4509    }
4510
4511    /// A manifest whose unrelated sections would not satisfy a strict
4512    /// whole-file TOML parse (here: a duplicate top-level table, which the
4513    /// `toml` crate rejects) must still have its `[workspace.dependencies]`
4514    /// pins rewritten - only that section's own syntax is a precondition,
4515    /// not the rest of the file.
4516    #[test]
4517    fn cargo_version_rewrite_does_not_require_the_whole_file_to_parse() {
4518        let toml = "\
4519[workspace.package]\n\
4520version = \"0.1.0\"\n\
4521\n\
4522[workspace.dependencies]\n\
4523inner = { path = \"crates/inner\", version = \"0.1.0\" }\n\
4524\n\
4525[workspace.package]\n\
4526edition = \"2024\"\n";
4527        let out = rewrite_cargo_version(toml, "0.2.0").unwrap();
4528        assert!(out.contains("inner = { path = \"crates/inner\", version = \"0.2.0\" }"));
4529        assert!(
4530            toml::from_str::<toml::Value>(toml).is_err(),
4531            "the fixture itself must be invalid as a whole file, or this test proves nothing"
4532        );
4533    }
4534
4535    #[test]
4536    fn current_version_prefers_the_package_table_when_both_exist() {
4537        let toml = "[workspace.package]\nversion = \"9.9.9\"\n\n[package]\nversion = \"0.8.0\"\n";
4538        assert_eq!(current_version(toml).unwrap(), "0.8.0");
4539    }
4540
4541    /// Same shape as `kanadehq/kanade`'s root `Cargo.toml`: no `[package]`
4542    /// at all, only `[workspace]` and `[workspace.package]`.
4543    #[test]
4544    fn current_version_falls_back_to_workspace_package_without_a_package_table() {
4545        let toml = "\
4546[workspace]\n\
4547members = [\"crates/a\", \"crates/b\"]\n\
4548\n\
4549[workspace.package]\n\
4550version = \"0.45.18\"\n";
4551        assert_eq!(current_version(toml).unwrap(), "0.45.18");
4552    }
4553
4554    #[test]
4555    fn coalesce_proceeds_with_nothing_pending() {
4556        assert_eq!(coalesce(None, "0.8.0").unwrap(), Coalesce::Proceed);
4557    }
4558
4559    /// A minimal, otherwise-plausible pending marker for tests that only
4560    /// care about one field.
4561    fn test_pending(target_version: &str, level: BumpLevel) -> PendingBump {
4562        PendingBump {
4563            target_version: target_version.to_owned(),
4564            level,
4565            branch: format!("chore/release-v{target_version}"),
4566            pr_url: "https://example.invalid/pull/9".to_owned(),
4567        }
4568    }
4569
4570    #[test]
4571    fn coalesce_skips_while_the_pending_target_is_still_ahead() {
4572        let pending = test_pending("0.9.0", BumpLevel::Minor);
4573        assert_eq!(
4574            coalesce(Some(&pending), "0.8.0").unwrap(),
4575            Coalesce::Skip {
4576                target_version: "0.9.0".to_owned()
4577            }
4578        );
4579    }
4580
4581    #[test]
4582    fn coalesce_treats_a_landed_or_superseded_pending_bump_as_stale() {
4583        let pending = test_pending("0.9.0", BumpLevel::Minor);
4584        // The pending bump landed exactly: proceed with a fresh decision.
4585        assert_eq!(
4586            coalesce(Some(&pending), "0.9.0").unwrap(),
4587            Coalesce::Proceed
4588        );
4589        // A human bumped further than what was pending: also proceed.
4590        assert_eq!(
4591            coalesce(Some(&pending), "1.0.0").unwrap(),
4592            Coalesce::Proceed
4593        );
4594    }
4595
4596    #[test]
4597    fn pending_action_escalates_only_for_a_more_severe_decision() {
4598        assert_eq!(
4599            pending_action(BumpLevel::Patch, BumpLevel::Patch),
4600            PendingAction::AlreadyCovered
4601        );
4602        assert_eq!(
4603            pending_action(BumpLevel::Patch, BumpLevel::Minor),
4604            PendingAction::Escalate
4605        );
4606        assert_eq!(
4607            pending_action(BumpLevel::Patch, BumpLevel::Major),
4608            PendingAction::Escalate
4609        );
4610        assert_eq!(
4611            pending_action(BumpLevel::Minor, BumpLevel::Patch),
4612            PendingAction::AlreadyCovered
4613        );
4614        assert_eq!(
4615            pending_action(BumpLevel::Major, BumpLevel::Minor),
4616            PendingAction::AlreadyCovered
4617        );
4618        assert_eq!(
4619            pending_action(BumpLevel::Major, BumpLevel::Major),
4620            PendingAction::AlreadyCovered
4621        );
4622    }
4623
4624    #[test]
4625    fn pr_state_parsing_reads_open_and_not_open() {
4626        assert!(parse_pr_state(r#"{"state":"OPEN"}"#).unwrap());
4627        assert!(!parse_pr_state(r#"{"state":"CLOSED"}"#).unwrap());
4628        assert!(!parse_pr_state(r#"{"state":"MERGED"}"#).unwrap());
4629    }
4630
4631    #[test]
4632    fn a_lock_is_exclusive_until_dropped() {
4633        let dir = tempfile::tempdir().unwrap();
4634        let marker = dir.path().join("bump").join("deadbeefdeadbeef.json");
4635        let first = MarkerLock::acquire(&marker)
4636            .unwrap()
4637            .expect("first attempt takes the lock");
4638        assert!(
4639            MarkerLock::acquire(&marker).unwrap().is_none(),
4640            "a second attempt must be refused while the first holds it"
4641        );
4642        drop(first);
4643        assert!(
4644            MarkerLock::acquire(&marker).unwrap().is_some(),
4645            "dropping the guard releases the lock for the next attempt"
4646        );
4647    }
4648
4649    #[test]
4650    fn a_stale_lock_is_reclaimed() {
4651        let dir = tempfile::tempdir().unwrap();
4652        let marker = dir.path().join("bump").join("deadbeefdeadbeef.json");
4653        let lock_path = marker.with_extension("lock");
4654        std::fs::create_dir_all(lock_path.parent().unwrap()).unwrap();
4655        std::fs::write(&lock_path, b"").unwrap();
4656        let old = std::time::SystemTime::now() - LOCK_STALE_AFTER - Duration::from_secs(1);
4657        std::fs::OpenOptions::new()
4658            .write(true)
4659            .open(&lock_path)
4660            .unwrap()
4661            .set_modified(old)
4662            .unwrap();
4663        assert!(
4664            MarkerLock::acquire(&marker).unwrap().is_some(),
4665            "a lock older than the stale window must be reclaimed rather than block forever"
4666        );
4667    }
4668
4669    #[tokio::test]
4670    async fn a_contended_lock_is_retried_until_the_holder_releases_it() {
4671        let dir = tempfile::tempdir().unwrap();
4672        let marker = dir.path().join("bump").join("deadbeefdeadbeef.json");
4673        let held = MarkerLock::acquire(&marker)
4674            .unwrap()
4675            .expect("seed the contention");
4676        let releaser = tokio::spawn(async move {
4677            tokio::time::sleep(Duration::from_millis(20)).await;
4678            drop(held);
4679        });
4680        let waited =
4681            wait_for_marker_lock_with(&marker, Duration::from_millis(5), Duration::from_secs(5))
4682                .await
4683                .unwrap();
4684        assert!(
4685            waited.is_some(),
4686            "a merge landing behind another's still-running decision must not be dropped - it \
4687             must wait for that decision to finish and then judge against what it left behind"
4688        );
4689        releaser.await.unwrap();
4690    }
4691
4692    #[tokio::test]
4693    async fn a_lock_held_past_the_ceiling_gives_up() {
4694        let dir = tempfile::tempdir().unwrap();
4695        let marker = dir.path().join("bump").join("deadbeefdeadbeef.json");
4696        let _held = MarkerLock::acquire(&marker).unwrap().unwrap();
4697        let waited =
4698            wait_for_marker_lock_with(&marker, Duration::from_millis(2), Duration::from_millis(10))
4699                .await
4700                .unwrap();
4701        assert!(
4702            waited.is_none(),
4703            "a lock genuinely held past the ceiling must eventually give up rather than wait \
4704             forever"
4705        );
4706    }
4707
4708    #[test]
4709    fn level_between_reads_off_the_differing_digit() {
4710        assert_eq!(
4711            level_between(
4712                Version::parse("0.8.0").unwrap(),
4713                Version::parse("1.0.0").unwrap()
4714            ),
4715            Some(BumpLevel::Major)
4716        );
4717        assert_eq!(
4718            level_between(
4719                Version::parse("0.8.0").unwrap(),
4720                Version::parse("0.9.0").unwrap()
4721            ),
4722            Some(BumpLevel::Minor)
4723        );
4724        assert_eq!(
4725            level_between(
4726                Version::parse("0.8.0").unwrap(),
4727                Version::parse("0.8.1").unwrap()
4728            ),
4729            Some(BumpLevel::Patch)
4730        );
4731        assert_eq!(
4732            level_between(
4733                Version::parse("0.8.0").unwrap(),
4734                Version::parse("0.8.0").unwrap()
4735            ),
4736            None
4737        );
4738    }
4739
4740    #[test]
4741    fn open_release_pr_is_found_among_unrelated_pull_requests() {
4742        let json = r#"[
4743            {"url": "https://example.invalid/pull/1", "headRefName": "feat/something"},
4744            {"url": "https://example.invalid/pull/2", "headRefName": "chore/release-v0.9.0"}
4745        ]"#;
4746        let found = parse_open_release_pr(json).unwrap();
4747        assert_eq!(
4748            found,
4749            Some((
4750                "chore/release-v0.9.0".to_owned(),
4751                "https://example.invalid/pull/2".to_owned()
4752            ))
4753        );
4754    }
4755
4756    #[test]
4757    fn no_open_release_pr_reads_as_none_not_an_error() {
4758        let json =
4759            r#"[{"url": "https://example.invalid/pull/1", "headRefName": "feat/something"}]"#;
4760        assert_eq!(parse_open_release_pr(json).unwrap(), None);
4761        assert_eq!(parse_open_release_pr("[]").unwrap(), None);
4762    }
4763
4764    #[test]
4765    fn marker_round_trips_through_disk() {
4766        let dir = tempfile::tempdir().unwrap();
4767        let path = marker_path(dir.path(), Path::new("/repos/magi"));
4768        assert!(read_marker(&path).is_none());
4769
4770        let marker = test_pending("0.9.0", BumpLevel::Patch);
4771        write_marker(&path, &marker).unwrap();
4772        let read_back = read_marker(&path).unwrap();
4773        assert_eq!(read_back.target_version, "0.9.0");
4774        assert_eq!(read_back.level, BumpLevel::Patch);
4775        assert_eq!(read_back.pr_url, marker.pr_url);
4776
4777        clear_marker(&path);
4778        assert!(read_marker(&path).is_none());
4779    }
4780
4781    #[test]
4782    fn different_repos_get_different_marker_files() {
4783        let dir = tempfile::tempdir().unwrap();
4784        let a = marker_path(dir.path(), Path::new("/repos/a"));
4785        let b = marker_path(dir.path(), Path::new("/repos/b"));
4786        assert_ne!(a, b);
4787    }
4788
4789    /// A version-bump-only pull request must never trigger the next bump - see
4790    /// [`is_release_only`]'s own doc for why that shape is the trigger for
4791    /// "do not treat this as a change to react to".
4792    #[test]
4793    fn a_bump_pull_requests_own_merge_does_not_retrigger() {
4794        let files = vec!["Cargo.toml".to_owned(), "Cargo.lock".to_owned()];
4795        assert!(
4796            is_release_only(&files),
4797            "the bump pull request's own diff must read as release-only"
4798        );
4799    }
4800
4801    #[test]
4802    fn should_release_bump_reads_only_a_merged_status() {
4803        assert!(should_release_bump(RunStatus::Merged));
4804        for other in [RunStatus::Blocked, RunStatus::Ready, RunStatus::Prep] {
4805            assert!(!should_release_bump(other));
4806        }
4807    }
4808
4809    /// `land::Step::Done { merged: true }` - a pull request already merged
4810    /// underneath magi. `land::decide` reads that straight off the pull
4811    /// request's own lifecycle before it looks at checks or comments at all.
4812    #[test]
4813    fn all_three_merge_paths_report_pr_lifecycle_merged_case_done() {
4814        let pr = land::PrState {
4815            url: "https://github.com/o/r/pull/1".to_owned(),
4816            number: 1,
4817            state: PrLifecycle::Merged,
4818            checks: land::Checks::Green,
4819            failing: Vec::new(),
4820            review_comments: Vec::new(),
4821            blocking: land::Blocking::No,
4822        };
4823        assert_eq!(
4824            land::decide(&pr, 0, 4, Duration::ZERO),
4825            land::Step::Done { merged: true }
4826        );
4827        assert!(should_release_bump(RunStatus::Merged));
4828    }
4829
4830    /// `land::Step::Merge`'s own `gh pr merge` succeeding: `land::land` then
4831    /// sets `pr.state = PrLifecycle::Merged` by hand before returning (see
4832    /// `land::land`'s `Step::Merge` arm), which is the same value the other
4833    /// two paths converge on.
4834    #[test]
4835    fn all_three_merge_paths_report_pr_lifecycle_merged_case_direct_merge() {
4836        let pr = land::PrState {
4837            url: "https://github.com/o/r/pull/2".to_owned(),
4838            number: 2,
4839            state: PrLifecycle::Open,
4840            checks: land::Checks::Green,
4841            failing: Vec::new(),
4842            review_comments: Vec::new(),
4843            blocking: land::Blocking::No,
4844        };
4845        assert_eq!(land::decide(&pr, 0, 4, Duration::ZERO), land::Step::Merge);
4846        // land::land's Step::Merge arm sets this by hand on success; asserted
4847        // here as the value that then makes should_release_bump fire.
4848        assert!(should_release_bump(RunStatus::Merged));
4849    }
4850
4851    /// [`land::merged_after_all`] - `gh pr merge` exited non-zero but the
4852    /// forge confirms the pull request merged anyway.
4853    #[test]
4854    fn all_three_merge_paths_report_pr_lifecycle_merged_case_merged_after_all() {
4855        let argv = land::merge_argv(3, "feat: something");
4856        let outcome = land::merged_after_all(
4857            &argv,
4858            "could not determine current branch: not on any branch",
4859            Some(PrLifecycle::Merged),
4860        );
4861        assert!(outcome.is_some(), "the forge's confirmation must win");
4862        assert!(should_release_bump(RunStatus::Merged));
4863
4864        // The same recovery must not fabricate a merge when the forge does
4865        // not confirm one.
4866        assert!(land::merged_after_all(&argv, "network error", Some(PrLifecycle::Open)).is_none());
4867        assert!(land::merged_after_all(&argv, "network error", None).is_none());
4868    }
4869
4870    /// The paths that do *not* land must not read as merged either.
4871    #[test]
4872    fn a_close_or_a_give_up_does_not_trigger_a_bump() {
4873        let pr = land::PrState {
4874            url: "https://github.com/o/r/pull/4".to_owned(),
4875            number: 4,
4876            state: PrLifecycle::Closed,
4877            checks: land::Checks::Green,
4878            failing: Vec::new(),
4879            review_comments: Vec::new(),
4880            blocking: land::Blocking::No,
4881        };
4882        assert_eq!(
4883            land::decide(&pr, 0, 4, Duration::ZERO),
4884            land::Step::Done { merged: false }
4885        );
4886        assert!(!should_release_bump(RunStatus::Blocked));
4887    }
4888
4889    fn shun_files() -> Vec<crate::config::VersionFile> {
4890        use crate::config::{VersionFile, VersionKind};
4891        vec![
4892            VersionFile {
4893                path: "src-tauri/Cargo.toml".to_owned(),
4894                kind: VersionKind::Cargo,
4895            },
4896            VersionFile {
4897                path: "package.json".to_owned(),
4898                kind: VersionKind::Json,
4899            },
4900            VersionFile {
4901                path: "src-tauri/tauri.conf.json".to_owned(),
4902                kind: VersionKind::Json,
4903            },
4904        ]
4905    }
4906
4907    const SHUN_TOML: &str = "[package]\nname = \"shun\"\nversion = \"1.0.0\"\n";
4908    const SHUN_LOCK: &str = "[[package]]\nname = \"shun\"\nversion = \"1.0.0\"\n";
4909
4910    async fn shun_origin(package_version: &str) -> (tempfile::TempDir, PathBuf) {
4911        let pkg = format!("{{\n  \"version\": \"{package_version}\"\n}}\n");
4912        let origin = origin_with(&[("README.md", "x\n")]).await;
4913        for (name, body) in [
4914            ("src-tauri/Cargo.toml", SHUN_TOML),
4915            ("src-tauri/Cargo.lock", SHUN_LOCK),
4916            ("package.json", pkg.as_str()),
4917            ("src-tauri/tauri.conf.json", "{ \"version\": \"1.0.0\" }\n"),
4918        ] {
4919            let path = origin.1.join(name);
4920            tokio::fs::create_dir_all(path.parent().unwrap())
4921                .await
4922                .unwrap();
4923            tokio::fs::write(path, body).await.unwrap();
4924        }
4925        git::git(&origin.1, &["add", "-A"]).await.unwrap();
4926        git::git(&origin.1, &["commit", "-m", "shun"])
4927            .await
4928            .unwrap();
4929        git::git(&origin.1, &["push", "origin", "main"])
4930            .await
4931            .unwrap();
4932        origin
4933    }
4934
4935    #[tokio::test]
4936    async fn a_shun_layout_bump_changes_only_the_declared_files_and_the_adjacent_lock() {
4937        let (_d, repo) = shun_origin("1.0.0").await;
4938        let mut state = winner_state(&repo, "main");
4939        state.config.release.version_files = shun_files();
4940        write_release_files(&state, &repo, "1.1.0").await.unwrap();
4941        let status = git::git(&repo, &["status", "--porcelain"]).await.unwrap();
4942        let mut paths: Vec<_> = status.lines().map(|l| l[3..].to_owned()).collect();
4943        paths.sort();
4944        assert_eq!(
4945            paths,
4946            [
4947                "package.json",
4948                "src-tauri/Cargo.lock",
4949                "src-tauri/Cargo.toml",
4950                "src-tauri/tauri.conf.json"
4951            ]
4952        );
4953        let lock = std::fs::read_to_string(repo.join("src-tauri/Cargo.lock")).unwrap();
4954        assert!(lock.contains("version = \"1.1.0\""));
4955    }
4956
4957    #[tokio::test]
4958    async fn an_unconfigured_repo_with_auto_tag_but_no_root_manifest_is_skipped_visibly() {
4959        let (_d, repo) = origin_with(&[("README.md", "x\n")]).await;
4960        let wf = repo.join(".github/workflows");
4961        tokio::fs::create_dir_all(&wf).await.unwrap();
4962        tokio::fs::write(wf.join("auto-tag.yml"), "name: t\n")
4963            .await
4964            .unwrap();
4965        git::git(&repo, &["add", "-A"]).await.unwrap();
4966        git::git(&repo, &["commit", "-m", "wf"]).await.unwrap();
4967        git::git(&repo, &["push", "origin", "main"]).await.unwrap();
4968        let home = tempfile::tempdir().unwrap();
4969        let store = Notices::at(home.path().join("notifications"));
4970        let mut state = winner_state(&repo, "main");
4971        after_merge_at(
4972            &mut state,
4973            "https://example.invalid/pull/1",
4974            Some(home.path()),
4975            Some(&store),
4976        )
4977        .await
4978        .unwrap();
4979        let rec = state.release_bump.clone().expect("a skip is recorded");
4980        assert!(rec.skipped.is_some_and(|s| s.contains("Cargo.toml")));
4981        assert!(
4982            rec.action_required
4983                .is_some_and(|a| a.contains("version_files"))
4984        );
4985        assert!(rec.pr_url.is_none() && !rec.automerge_enabled);
4986        assert_eq!(store.list().len(), 1);
4987        assert!(crate::report::run(&state).contains("SKIPPED"));
4988    }
4989
4990    #[tokio::test]
4991    async fn a_non_rust_repo_without_auto_tag_records_a_skip_without_paging() {
4992        let (_d, repo) = origin_with(&[("README.md", "hi\n")]).await;
4993        let home = tempfile::tempdir().unwrap();
4994        let store = Notices::at(home.path().join("notifications"));
4995        let mut state = winner_state(&repo, "main");
4996        after_merge_at(
4997            &mut state,
4998            "https://example.invalid/pull/1",
4999            Some(home.path()),
5000            Some(&store),
5001        )
5002        .await
5003        .unwrap();
5004        let rec = state.release_bump.clone().unwrap();
5005        assert!(rec.skipped.is_some());
5006        assert!(rec.action_required.is_none());
5007        assert!(store.list().is_empty());
5008    }
5009
5010    #[tokio::test]
5011    async fn disagreeing_version_files_stop_the_bump_and_ask_the_owner() {
5012        let (_d, repo) = shun_origin("0.9.0").await;
5013        let home = tempfile::tempdir().unwrap();
5014        let store = Notices::at(home.path().join("notifications"));
5015        let mut state = winner_state(&repo, "main");
5016        state.config.release.version_files = shun_files();
5017        after_merge_at(
5018            &mut state,
5019            "https://example.invalid/pull/1",
5020            Some(home.path()),
5021            Some(&store),
5022        )
5023        .await
5024        .unwrap();
5025        let rec = state.release_bump.clone().unwrap();
5026        assert!(rec.skipped.is_some_and(|s| s.contains("disagree")));
5027        assert!(rec.action_required.is_some());
5028        assert_eq!(store.list().len(), 1);
5029        assert!(rec.pr_url.is_none());
5030    }
5031
5032    #[tokio::test]
5033    async fn a_change_that_already_raised_the_version_is_left_to_the_repos_auto_tag() {
5034        let (_d, repo) = shun_origin("1.0.0").await;
5035        git::git(&repo, &["checkout", "-b", "feat"]).await.unwrap();
5036        let toml = SHUN_TOML.replace("1.0.0", "1.0.1");
5037        tokio::fs::write(repo.join("src-tauri/Cargo.toml"), toml)
5038            .await
5039            .unwrap();
5040        tokio::fs::write(repo.join("app.ts"), "x\n").await.unwrap();
5041        git::git(&repo, &["add", "-A"]).await.unwrap();
5042        git::git(&repo, &["commit", "-m", "fix and bump"])
5043            .await
5044            .unwrap();
5045        let home = tempfile::tempdir().unwrap();
5046        let store = Notices::at(home.path().join("notifications"));
5047        let mut state = winner_state(&repo, "main");
5048        state.candidates[0].branch = "feat".to_owned();
5049        state.config.release.version_files = shun_files();
5050        after_merge_at(
5051            &mut state,
5052            "https://example.invalid/pull/1",
5053            Some(home.path()),
5054            Some(&store),
5055        )
5056        .await
5057        .unwrap();
5058        let rec = state.release_bump.clone().unwrap();
5059        assert!(
5060            rec.skipped
5061                .is_some_and(|s| s.contains("already") || s.contains("raised"))
5062        );
5063        assert!(rec.pr_url.is_none() && rec.action_required.is_none());
5064        assert!(store.list().is_empty());
5065    }
5066
5067    #[tokio::test]
5068    async fn a_stale_local_base_does_not_make_an_inherited_version_look_like_this_changes() {
5069        let (_d, repo) = shun_origin("1.0.0").await;
5070        let old = git::rev_parse(&repo, "HEAD").await.unwrap();
5071        tokio::fs::write(
5072            repo.join("src-tauri/Cargo.toml"),
5073            SHUN_TOML.replace("1.0.0", "1.0.1"),
5074        )
5075        .await
5076        .unwrap();
5077        git::git(&repo, &["commit", "-am", "bump upstream"])
5078            .await
5079            .unwrap();
5080        git::git(&repo, &["push", "origin", "main"]).await.unwrap();
5081        git::git(&repo, &["checkout", "-b", "feat"]).await.unwrap();
5082        tokio::fs::write(repo.join("app.ts"), "x\n").await.unwrap();
5083        git::git(&repo, &["add", "-A"]).await.unwrap();
5084        git::git(&repo, &["commit", "-m", "fix"]).await.unwrap();
5085        // The local main lags origin/main, which already carries 1.0.1.
5086        git::git(&repo, &["update-ref", "refs/heads/main", &old])
5087            .await
5088            .unwrap();
5089        let home = tempfile::tempdir().unwrap();
5090        let store = Notices::at(home.path().join("notifications"));
5091        let mut state = winner_state(&repo, "main");
5092        state.candidates[0].branch = "feat".to_owned();
5093        state.config.release.version_files = shun_files();
5094        let _ = after_merge_at(
5095            &mut state,
5096            "https://example.invalid/pull/1",
5097            Some(home.path()),
5098            Some(&store),
5099        )
5100        .await;
5101        assert!(
5102            !state
5103                .events
5104                .iter()
5105                .any(|e| e.message.contains("already moved")),
5106            "{:?}",
5107            state.events
5108        );
5109    }
5110
5111    #[tokio::test]
5112    async fn a_dependency_only_change_on_a_stale_local_base_is_not_release_only() {
5113        let (_d, repo) = shun_origin("1.0.0").await;
5114        let old = git::rev_parse(&repo, "HEAD").await.unwrap();
5115        for (p, from) in [
5116            ("src-tauri/Cargo.toml", SHUN_TOML),
5117            ("package.json", "{\n  \"version\": \"1.0.0\"\n}\n"),
5118            ("src-tauri/tauri.conf.json", "{ \"version\": \"1.0.0\" }\n"),
5119        ] {
5120            tokio::fs::write(repo.join(p), from.replace("1.0.0", "1.0.1"))
5121                .await
5122                .unwrap();
5123        }
5124        tokio::fs::write(
5125            repo.join("src-tauri/Cargo.lock"),
5126            SHUN_LOCK.replace("1.0.0", "1.0.1"),
5127        )
5128        .await
5129        .unwrap();
5130        git::git(&repo, &["commit", "-am", "bump upstream"])
5131            .await
5132            .unwrap();
5133        git::git(&repo, &["push", "origin", "main"]).await.unwrap();
5134        git::git(&repo, &["checkout", "-b", "feat"]).await.unwrap();
5135        tokio::fs::write(
5136            repo.join("package.json"),
5137            "{\n  \"version\": \"1.0.1\",\n  \"dependencies\": {}\n}\n",
5138        )
5139        .await
5140        .unwrap();
5141        git::git(&repo, &["commit", "-am", "deps"]).await.unwrap();
5142        git::git(&repo, &["update-ref", "refs/heads/main", &old])
5143            .await
5144            .unwrap();
5145        let home = tempfile::tempdir().unwrap();
5146        let store = Notices::at(home.path().join("notifications"));
5147        let mut state = winner_state(&repo, "main");
5148        state.candidates[0].branch = "feat".to_owned();
5149        state.config.release.version_files = shun_files();
5150        let _ = after_merge_at(
5151            &mut state,
5152            "https://example.invalid/pull/1",
5153            Some(home.path()),
5154            Some(&store),
5155        )
5156        .await;
5157        assert!(
5158            !state
5159                .events
5160                .iter()
5161                .any(|e| e.message.contains("only the release files")),
5162            "{:?}",
5163            state.events
5164        );
5165        assert!(
5166            state
5167                .release_bump
5168                .as_ref()
5169                .is_none_or(|b| b.skipped.is_none())
5170        );
5171    }
5172}