Skip to main content

release_kit/commands/
release.rs

1//! `rk release status`: where a landed target's release stands.
2//!
3//! The record answers the style, the integration authority, the checkout
4//! mode, and the trunk, offline. The forge answers the release request,
5//! the last release, and the runs, and a field the runtime cannot read
6//! reads `unknown`: the verb never asks for a credential so that a field
7//! can read. The registry answers whether a version is published. The
8//! judgments live in [`crate::release_state`]; this handler reads, joins,
9//! and renders.
10//!
11//! SATISFIES release-state:the-report-joins-the-record-and-the-forge
12
13use std::time::{Duration, Instant};
14
15use camino::Utf8Path;
16use serde::Serialize;
17use serde_json::Value;
18
19use crate::cli::release::{ReleaseAction, ReleaseArgs};
20use crate::commands::lines::{self, LineRow};
21use crate::detect::Forge;
22use crate::diagnostic::{Diagnostic, Reason};
23use crate::error::RkError;
24use crate::landing::manifest::{self, CheckoutMode, Integration, Manifest, Style};
25use crate::output::Output;
26use crate::profile::ReleaseMode;
27use crate::release_engine;
28use crate::release_state::{
29    self, Answer, Api, ForgeCli, LastRelease, Merged, Page, Pair, Request, Run, Symptom,
30};
31use crate::requirements::Tool;
32
33/// The tags one forge page holds.
34const TAG_PAGE: usize = 100;
35
36/// The most tag pages a read follows before it reports the list unread.
37const TAG_PAGES: usize = 50;
38
39/// The report's shape version.
40const SCHEMA: &str = "rk.release-status/1";
41
42/// How long `--wait` sleeps between two reads, unless the environment
43/// names another interval in milliseconds.
44const WAIT_INTERVAL_MS: u64 = 15_000;
45
46/// The variable that overrides the wait interval.
47const WAIT_INTERVAL_VAR: &str = "RK_RELEASE_WAIT_INTERVAL_MS";
48
49/// Whether the forge could be read, and why not.
50#[derive(Debug, Serialize)]
51struct ForgeState {
52    /// The recorded forge.
53    name: Option<String>,
54    /// The recorded project path.
55    repo: Option<String>,
56    /// `yes`, `unknown`, or `not-applicable`.
57    read: Answer,
58    /// Why the forge was not read, where it was not.
59    reason: Option<String>,
60}
61
62/// What `--wait` found on the commit.
63#[derive(Debug, Serialize)]
64struct Wait {
65    /// The commit waited on.
66    sha: String,
67    /// The run that tags and publishes.
68    publish: Option<Run>,
69    /// The run that builds the artifacts, where the pair builds any.
70    artifact: Option<Run>,
71    /// The release tag that names the commit, once one does.
72    tag: Option<String>,
73    /// Whether the timeout ended the wait before both runs concluded.
74    timed_out: bool,
75}
76
77/// The machine form of `rk release status`.
78#[derive(Debug, Serialize)]
79struct Report {
80    /// The shape version of this document.
81    schema: &'static str,
82    /// Whether a landing record exists; every other field needs one.
83    landed: bool,
84    /// The recorded release style.
85    #[serde(skip_serializing_if = "Option::is_none")]
86    style: Option<Style>,
87    /// The recorded integration authority.
88    #[serde(skip_serializing_if = "Option::is_none")]
89    integration: Option<Integration>,
90    /// The recorded checkout mode.
91    #[serde(skip_serializing_if = "Option::is_none")]
92    checkout_mode: Option<CheckoutMode>,
93    /// The recorded trunk.
94    #[serde(skip_serializing_if = "Option::is_none")]
95    trunk: Option<String>,
96    /// Whether the forge could be read.
97    #[serde(skip_serializing_if = "Option::is_none")]
98    forge: Option<ForgeState>,
99    /// The open release request.
100    #[serde(skip_serializing_if = "Option::is_none")]
101    request: Option<Request>,
102    /// The newest release.
103    #[serde(skip_serializing_if = "Option::is_none")]
104    last_release: Option<LastRelease>,
105    /// Every release line, as `rk lines list` reports it.
106    #[serde(skip_serializing_if = "Option::is_none")]
107    lines: Option<Vec<LineRow>>,
108    /// Every symptom the state shows.
109    #[serde(skip_serializing_if = "Option::is_none")]
110    symptoms: Option<Vec<Symptom>>,
111    /// What `--wait` found, where it ran.
112    #[serde(skip_serializing_if = "Option::is_none")]
113    wait: Option<Wait>,
114}
115
116/// Route one `rk release` invocation.
117///
118/// # Errors
119///
120/// Each verb's own failures; every failure is typed.
121pub fn run(args: &ReleaseArgs) -> Result<(), RkError> {
122    match &args.action {
123        ReleaseAction::Status {
124            target,
125            wait,
126            timeout,
127            json,
128        } => status(target, wait.as_deref(), *timeout, Output::new(*json)),
129        ReleaseAction::Merge {
130            target,
131            apply,
132            timeout,
133            json,
134        } => render_done(
135            &release_engine::merge::run(target, *apply, *timeout)?,
136            Output::new(*json),
137        ),
138        ReleaseAction::Request { target, json } => {
139            render_done(&release_engine::request::run(target)?, Output::new(*json))
140        }
141        ReleaseAction::Build { target, list, json } => {
142            let done = if *list {
143                release_engine::build::list(target)?
144            } else {
145                release_engine::build::run(target)?
146            };
147            render_done(&done, Output::new(*json))
148        }
149        ReleaseAction::Eligible { target, json } => {
150            render_done(&release_engine::eligible::run(target)?, Output::new(*json))
151        }
152        ReleaseAction::Publish { target, json } => {
153            render_done(&release_engine::publish::run(target)?, Output::new(*json))
154        }
155    }
156}
157
158/// Render one engine action's report: the human lines and the next steps,
159/// or the JSON document under `--json`.
160fn render_done<R: Serialize>(done: &release_engine::Done<R>, out: Output) -> Result<(), RkError> {
161    for line in &done.lines {
162        out.result_line(line);
163    }
164    if !done.next.is_empty() {
165        out.next(&done.next);
166    }
167    out.emit(&done.report)
168}
169
170/// Everything the forge answered, gathered once.
171struct Observed {
172    request: Request,
173    last: LastRelease,
174    symptoms: Vec<Symptom>,
175    wait: Option<Wait>,
176}
177
178#[allow(
179    clippy::too_many_lines,
180    reason = "one pass reads the record, the lines, and the forge, and renders the one report"
181)]
182fn status(target: &Utf8Path, wait: Option<&str>, timeout: u64, out: Output) -> Result<(), RkError> {
183    if !target.is_dir() {
184        return Err(RkError::missing(
185            Diagnostic::new(
186                Reason::TargetNotFound,
187                format!("target {target} is not a directory"),
188            )
189            .expected("an existing repository to report on"),
190        ));
191    }
192    let Some(manifest) = manifest::load(target)? else {
193        out.result_line(format!("no landing at {target}"));
194        out.next(&[format!(
195            "rk status --target {target} classifies the target; the rk-setup skill lands the convention"
196        )]);
197        return out.emit(&Report {
198            schema: SCHEMA,
199            landed: false,
200            style: None,
201            integration: None,
202            checkout_mode: None,
203            trunk: None,
204            forge: None,
205            request: None,
206            last_release: None,
207            lines: None,
208            symptoms: None,
209            wait: None,
210        });
211    };
212    let pair = pair_of(target, &manifest);
213    // The tools the report reads with, checked before the first read: git
214    // always, and for a pair this binary reads, its forge CLI at its floor.
215    // A missing tool is no observation boundary; a credential the runtime
216    // lacks, and a forge or a registry that does not answer, still read
217    // unknown. The registry is read in-process, through crate::http.
218    let mut tools = vec![Tool::Git];
219    if let Ok(pair) = &pair {
220        tools.push(Tool::ForgeCli(pair.forge));
221    }
222    crate::requirements::require("rk release status", &tools)?;
223    let lines = lines::rows(target)?;
224    let local = local_release_tags(target);
225    let (forge, observed) = match &pair {
226        Err(reason) => (
227            ForgeState {
228                name: manifest.profile.forge.clone(),
229                repo: (!manifest.parameters.repo.is_empty())
230                    .then(|| manifest.parameters.repo.clone()),
231                read: Answer::NotApplicable,
232                reason: Some(reason.clone()),
233            },
234            Observed {
235                request: Request::none(),
236                last: LastRelease {
237                    tag: newest_local(&local),
238                    published: Answer::NotApplicable,
239                    artifacts_verified: Answer::NotApplicable,
240                },
241                symptoms: Vec::new(),
242                wait: None,
243            },
244        ),
245        Ok(pair) => match ForgeCli::resolve(pair.forge, target) {
246            Err(error) => (
247                ForgeState {
248                    name: Some(pair.forge.as_str().to_owned()),
249                    repo: Some(pair.repo.clone()),
250                    read: Answer::Unknown,
251                    reason: Some(error.to_string()),
252                },
253                Observed {
254                    request: Request::unknown(),
255                    last: LastRelease {
256                        tag: newest_local(&local),
257                        published: Answer::Unknown,
258                        artifacts_verified: if pair.artifacts {
259                            Answer::Unknown
260                        } else {
261                            Answer::NotApplicable
262                        },
263                    },
264                    symptoms: Vec::new(),
265                    wait: None,
266                },
267            ),
268            Ok(cli) => {
269                let mut reader = Reader {
270                    cli: &cli,
271                    pair,
272                    read: Answer::Yes,
273                    failures: std::cell::RefCell::new(Vec::new()),
274                };
275                let line_names: Vec<&str> = lines.iter().map(|row| row.line.as_str()).collect();
276                let mut observed = reader.observe(&local, wait, timeout, &line_names);
277                observed.symptoms.extend(release_state::armed_request(
278                    &observed.request,
279                    pair.forge,
280                    &pair.repo,
281                ));
282                (
283                    ForgeState {
284                        name: Some(pair.forge.as_str().to_owned()),
285                        repo: Some(pair.repo.clone()),
286                        read: reader.read,
287                        reason: reader.reason(),
288                    },
289                    observed,
290                )
291            }
292        },
293    };
294    if wait.is_some() && observed.wait.is_none() {
295        return Err(RkError::refusal(
296            Diagnostic::new(
297                Reason::ObservationIncomplete,
298                format!(
299                    "--wait needs the forge's runs, and this runtime cannot read them: {}",
300                    forge
301                        .reason
302                        .as_deref()
303                        .unwrap_or("the forge did not answer")
304                ),
305            )
306            .expected("a forge CLI that can read this project's runs")
307            .action("rerun where the forge CLI is authenticated for this project")
308            .target_state("unchanged"),
309        ));
310    }
311    render(out, &manifest, &forge, &observed, &lines);
312    let failure = observed
313        .wait
314        .as_ref()
315        .and_then(wait_failure)
316        .or_else(|| armed_failure(&observed.symptoms));
317    out.emit(&Report {
318        schema: SCHEMA,
319        landed: true,
320        style: manifest.profile.release.style,
321        integration: Some(manifest.git.integration),
322        checkout_mode: Some(manifest.git.checkout_mode),
323        trunk: Some(manifest.git.trunk),
324        forge: Some(forge),
325        request: Some(observed.request),
326        last_release: Some(observed.last),
327        lines: Some(lines),
328        symptoms: Some(observed.symptoms),
329        wait: observed.wait,
330    })?;
331    failure.map_or(Ok(()), Err)
332}
333
334/// The pair the forge reads need, or why the forge is not read at all.
335fn pair_of(target: &Utf8Path, manifest: &Manifest) -> Result<Pair, String> {
336    if manifest.profile.release.mode != ReleaseMode::Automatic {
337        return Err("the record selects no automated release".to_owned());
338    }
339    let driver = manifest
340        .profile
341        .release
342        .driver
343        .clone()
344        .ok_or_else(|| "the record names no release driver".to_owned())?;
345    let forge = manifest
346        .profile
347        .forge
348        .as_deref()
349        .and_then(Forge::parse)
350        .ok_or_else(|| "the record names no forge this binary reads".to_owned())?;
351    if manifest.parameters.repo.is_empty() {
352        return Err("the record names no forge repository".to_owned());
353    }
354    let artifacts = match (forge, driver.as_str()) {
355        (Forge::Github, "rust") => manifest.file("dist-workspace.toml").is_some(),
356        (Forge::Github | Forge::Gitlab, "bash" | "python") => true,
357        _ => false,
358    };
359    Ok(Pair {
360        package: crate::release_engine::adapter::package_name(target.as_std_path(), &driver),
361        registry_answer: manifest.profile.release.registry,
362        driver,
363        forge,
364        repo: manifest.parameters.repo.clone(),
365        trunk: manifest.git.trunk.clone(),
366        line_prefix: manifest
367            .profile
368            .release
369            .line_prefix
370            .clone()
371            .unwrap_or_else(|| crate::config::LINE_PREFIX_DEFAULT.to_owned()),
372        artifacts,
373    })
374}
375
376/// Every release tag the clone holds, `v<version>` with a candidate
377/// included, with the commit it names, read offline. An annotated tag
378/// names the commit it points to, as the forge's tag list does. A clone
379/// whose tags cannot be read holds none here, so nothing is compared.
380fn local_release_tags(target: &Utf8Path) -> Vec<(String, String)> {
381    let mut command = std::process::Command::new(crate::probes::git_bin());
382    for var in crate::maintenance::GIT_HOOK_VARS {
383        command.env_remove(var);
384    }
385    let Ok(output) = command
386        .arg("-C")
387        .arg(target.as_std_path())
388        .args([
389            "for-each-ref",
390            "--format=%(refname:strip=2) %(objectname) %(*objectname)",
391            "refs/tags/v*",
392        ])
393        .output()
394    else {
395        return Vec::new();
396    };
397    if !output.status.success() {
398        return Vec::new();
399    }
400    String::from_utf8_lossy(&output.stdout)
401        .lines()
402        .filter_map(|line| {
403            let mut fields = line.split_whitespace();
404            let tag = fields.next()?;
405            let object = fields.next()?;
406            let commit = fields.next().unwrap_or(object);
407            tag.strip_prefix('v')
408                .is_some_and(release_state::is_version)
409                .then(|| (tag.to_owned(), commit.to_owned()))
410        })
411        .collect()
412}
413
414/// Each tag paired with its commit, borrowed.
415fn borrowed(tags: &[(String, String)]) -> Vec<(&str, &str)> {
416    tags.iter()
417        .map(|(tag, commit)| (tag.as_str(), commit.as_str()))
418        .collect()
419}
420
421/// The newest release among the clone's tags.
422fn newest_local(local: &[(String, String)]) -> Option<String> {
423    release_state::newest_release(local.iter().map(|(tag, _)| tag.as_str()))
424}
425
426/// The run that failed a wait, as the error the verb exits with after it
427/// rendered the report; a timeout refuses, because nothing was judged.
428fn wait_failure(wait: &Wait) -> Option<RkError> {
429    if wait.timed_out {
430        return Some(RkError::refusal(
431            Diagnostic::new(
432                Reason::ObservationIncomplete,
433                format!(
434                    "the runs on {} did not conclude before the timeout",
435                    wait.sha
436                ),
437            )
438            .expected("the publish run, and the artifact run where the pair builds one, concluded")
439            .action("rerun with a longer --timeout, or read the runs on the forge")
440            .target_state("unchanged"),
441        ));
442    }
443    let failed = [&wait.publish, &wait.artifact]
444        .into_iter()
445        .flatten()
446        .find(|run| run.concluded() && !run.succeeded())?;
447    Some(RkError::check_failed(
448        Diagnostic::new(
449            Reason::StateDrift,
450            format!(
451                "run {} on {} concluded {}",
452                failed.id,
453                wait.sha,
454                failed.conclusion.as_deref().unwrap_or("without success")
455            ),
456        )
457        .expected("every run on the release commit concluded success")
458        .action("rk method recovery names the path for the symptom this report shows"),
459    ))
460}
461
462/// An armed release request, as the error the verb exits with after it
463/// rendered the report: a release waits for the operator's order.
464fn armed_failure(symptoms: &[Symptom]) -> Option<RkError> {
465    let armed = symptoms
466        .iter()
467        .find(|symptom| symptom.code == release_state::REQUEST_ARMED)?;
468    Some(RkError::check_failed(
469        Diagnostic::new(Reason::StateDrift, armed.evidence.clone())
470            .expected("no release request stands armed to merge itself")
471            .action("rk setup step merge-on-order --apply disarms every open release request"),
472    ))
473}
474
475/// The forge reads for one pair, with what they could not read.
476struct Reader<'a> {
477    cli: &'a ForgeCli,
478    pair: &'a Pair,
479    read: Answer,
480    failures: std::cell::RefCell<Vec<String>>,
481}
482
483impl Reader<'_> {
484    fn reason(&self) -> Option<String> {
485        self.failures.borrow().first().cloned()
486    }
487
488    /// One call; a failure is remembered so the report says why a field
489    /// reads unknown.
490    fn api(&self, path: &str) -> Option<Value> {
491        match self.cli.api(path) {
492            Api::Ok(body) => Some(body),
493            Api::Missing => None,
494            Api::Failed(reason) => {
495                self.failures.borrow_mut().push(reason);
496                None
497            }
498        }
499    }
500
501    /// One call that tells a definite not-found apart from a failure.
502    fn api_answer(&self, path: &str) -> Api {
503        let answer = self.cli.api(path);
504        if let Api::Failed(reason) = &answer {
505            self.failures.borrow_mut().push(reason.clone());
506        }
507        answer
508    }
509
510    fn project(&self) -> String {
511        release_state::gitlab_project(&self.pair.repo)
512    }
513
514    fn observe(
515        &mut self,
516        local: &[(String, String)],
517        wait: Option<&str>,
518        timeout: u64,
519        lines: &[&str],
520    ) -> Observed {
521        let request = self.open_request();
522        let mut wait = wait.map(|sha| self.wait(sha, timeout));
523        // Read after the wait: a trunk run tags its own commit while it
524        // runs, so a list read before it cannot hold the tag it made.
525        let tags = self.tags();
526        if let Some(wait) = wait.as_mut().filter(|wait| wait.tag.is_none()) {
527            wait.tag = tags.as_ref().and_then(|tags| {
528                tags.iter()
529                    .find(|(name, commit)| *commit == wait.sha && name.starts_with('v'))
530                    .map(|(name, _)| name.clone())
531            });
532        }
533        // An unread tag list is no empty one: without it, the absence
534        // of a release is not observed either.
535        let unread = tags.is_none();
536        // A wait reports the release its commit made and no other: a
537        // commit that made none never borrows an older release's state.
538        let tag = wait.as_ref().map_or_else(
539            || {
540                tags.as_ref().map_or_else(
541                    || newest_local(local),
542                    |tags| {
543                        release_state::newest_release(tags.iter().map(|(name, _)| name.as_str()))
544                    },
545                )
546            },
547            |wait| wait.tag.clone(),
548        );
549        // A tag the clone supplies because the forge refused its list is
550        // no observed release: its fields stay unknown, as they do where
551        // the forge CLI is missing.
552        let from_clone = unread && wait.is_none();
553        let page = if from_clone {
554            None
555        } else {
556            tag.as_deref().and_then(|tag| self.page(tag))
557        };
558        let last = LastRelease {
559            published: if from_clone {
560                Answer::Unknown
561            } else {
562                tag.as_deref().map_or(
563                    if unread {
564                        Answer::Unknown
565                    } else {
566                        Answer::NotApplicable
567                    },
568                    |tag| self.published(tag, page.as_ref()),
569                )
570            },
571            artifacts_verified: if !self.pair.artifacts {
572                Answer::NotApplicable
573            } else if from_clone {
574                Answer::Unknown
575            } else if tag.is_none() {
576                if unread { Answer::Unknown } else { Answer::No }
577            } else {
578                page.as_ref().map_or(Answer::Unknown, Page::verified)
579            },
580            tag,
581        };
582        let merged = self.merged().map(|(number, version)| {
583            let name = format!("v{version}");
584            let tagged = tags.as_ref().map_or(Answer::Unknown, |tags| {
585                Answer::of(tags.iter().any(|(tag, _)| *tag == name))
586            });
587            let published = if last.tag.as_deref() == Some(name.as_str()) {
588                last.published
589            } else if tagged == Answer::No && self.pair.registry().is_none() {
590                Answer::No
591            } else {
592                self.published(&name, None)
593            };
594            Merged {
595                number,
596                version,
597                tagged,
598                published,
599            }
600        });
601        let mut symptoms =
602            release_state::symptoms(merged.as_ref(), &last, page.as_ref(), self.pair.artifacts);
603        if let Some(tags) = tags.as_ref() {
604            let names: Vec<&str> = tags.iter().map(|(name, _)| name.as_str()).collect();
605            symptoms.extend(release_state::orphan_tags(&names, lines, |tag| {
606                // The last release's page is already read; every other
607                // page is read once, newest first, until a complete one.
608                let read = if last.tag.as_deref() == Some(tag) {
609                    page.clone()
610                } else {
611                    self.page(tag)
612                };
613                read.map_or(Answer::Unknown, |page| self.complete(&page))
614            }));
615            symptoms.extend(release_state::local_tag_drift(
616                &borrowed(local),
617                &borrowed(tags),
618            ));
619        }
620        if !self.failures.borrow().is_empty() {
621            self.read = Answer::Unknown;
622        }
623        Observed {
624            request,
625            last,
626            symptoms,
627            wait,
628        }
629    }
630
631    /// Whether a release page is complete: one with artifacts for a pair
632    /// that builds them, one that exists for any other.
633    const fn complete(&self, page: &Page) -> Answer {
634        Answer::of(page.exists && (!self.pair.artifacts || !page.assets.is_empty()))
635    }
636
637    /// Whether the version a tag names is published: the registry's
638    /// answer where the pair has one, the release page's otherwise.
639    fn published(&self, tag: &str, page: Option<&Page>) -> Answer {
640        // The registry knows the version in the driver's own spelling: a
641        // python candidate tagged v1.4.3-rc.2 is 1.4.3rc2 on PyPI.
642        let version = crate::release_engine::adapter::Version::from_tag(tag).map_or_else(
643            || tag.strip_prefix('v').unwrap_or(tag).to_owned(),
644            |version| version.spelled(&self.pair.driver),
645        );
646        match (self.pair.registry(), self.pair.package.as_deref()) {
647            (Some(registry), Some(package)) => {
648                release_state::registry_serves(registry, package, Some(&version)).unwrap_or_else(
649                    |reason| {
650                        self.failures.borrow_mut().push(reason);
651                        Answer::Unknown
652                    },
653                )
654            }
655            (Some(_), None) => Answer::Unknown,
656            (None, _) => page
657                .cloned()
658                .or_else(|| self.page(tag))
659                .map_or(Answer::Unknown, |page| Answer::of(page.exists)),
660        }
661    }
662
663    fn open_request(&self) -> Request {
664        let Some(prefix) = self.pair.request_prefix() else {
665            return Request::none();
666        };
667        match self.pair.forge {
668            Forge::Github => self.github_request(prefix),
669            Forge::Gitlab => self.gitlab_request(prefix),
670        }
671    }
672
673    fn github_request(&self, prefix: &str) -> Request {
674        let repo = &self.pair.repo;
675        let Some(body) = self.api(&format!(
676            "repos/{repo}/pulls?state=open&base={}&per_page=100",
677            self.pair.trunk
678        )) else {
679            return Request::unknown();
680        };
681        let Some(request) = body.as_array().and_then(|requests| {
682            requests.iter().find(|request| {
683                request["head"]["ref"]
684                    .as_str()
685                    .is_some_and(|head| head.starts_with(prefix))
686            })
687        }) else {
688            return Request::none();
689        };
690        let sha = request["head"]["sha"].as_str().unwrap_or_default();
691        let checks = self
692            .api(&format!(
693                "repos/{repo}/commits/{sha}/check-runs?per_page=100"
694            ))
695            .map_or(release_state::Checks::Unknown, |body| {
696                release_state::github_checks(&body)
697            });
698        let behind_trunk = self
699            .api(&format!("repos/{repo}/compare/{}...{sha}", self.pair.trunk))
700            .and_then(|body| body["behind_by"].as_u64())
701            .map_or(Answer::Unknown, |behind| Answer::of(behind > 0));
702        Request {
703            state: "open",
704            number: request["number"].as_u64(),
705            proposed_version: request["title"]
706                .as_str()
707                .and_then(release_state::proposed_version),
708            armed: Answer::of(!request["auto_merge"].is_null()),
709            checks,
710            behind_trunk,
711        }
712    }
713
714    fn gitlab_request(&self, prefix: &str) -> Request {
715        let project = self.project();
716        let Some(body) = self.api(&format!(
717            "projects/{project}/merge_requests?state=opened&target_branch={}&per_page=100",
718            self.pair.trunk
719        )) else {
720            return Request::unknown();
721        };
722        let Some(request) = body.as_array().and_then(|requests| {
723            requests.iter().find(|request| {
724                request["source_branch"]
725                    .as_str()
726                    .is_some_and(|head| head.starts_with(prefix))
727            })
728        }) else {
729            return Request::none();
730        };
731        let iid = request["iid"].as_u64();
732        let detail = iid.and_then(|iid| {
733            self.api(&format!(
734                "projects/{project}/merge_requests/{iid}?include_diverged_commits_count=true"
735            ))
736        });
737        let armed = request["merge_when_pipeline_succeeds"]
738            .as_bool()
739            .or_else(|| request["auto_merge_enabled"].as_bool())
740            .map_or(Answer::Unknown, Answer::of);
741        Request {
742            state: "open",
743            number: iid,
744            proposed_version: request["title"]
745                .as_str()
746                .and_then(release_state::proposed_version),
747            armed,
748            checks: detail
749                .as_ref()
750                .map_or(release_state::Checks::Unknown, |detail| {
751                    release_state::gitlab_checks(detail["head_pipeline"]["status"].as_str())
752                }),
753            behind_trunk: detail
754                .as_ref()
755                .and_then(|detail| detail["diverged_commits_count"].as_u64())
756                .map_or(Answer::Unknown, |behind| Answer::of(behind > 0)),
757        }
758    }
759
760    /// The newest merged release request: its number and the version its
761    /// title proposed.
762    fn merged(&self) -> Option<(u64, String)> {
763        let prefix = self.pair.request_prefix()?;
764        let (path, head, merged_at, number) = match self.pair.forge {
765            Forge::Github => (
766                format!(
767                    "repos/{}/pulls?state=closed&base={}&sort=updated&direction=desc&per_page=30",
768                    self.pair.repo, self.pair.trunk
769                ),
770                "/head/ref",
771                "/merged_at",
772                "/number",
773            ),
774            Forge::Gitlab => (
775                format!(
776                    "projects/{}/merge_requests?state=merged&target_branch={}&order_by=updated_at&sort=desc&per_page=30",
777                    self.project(),
778                    self.pair.trunk
779                ),
780                "/source_branch",
781                "/merged_at",
782                "/iid",
783            ),
784        };
785        let body = self.api(&path)?;
786        body.as_array()?
787            .iter()
788            .filter(|request| {
789                request
790                    .pointer(head)
791                    .and_then(Value::as_str)
792                    .is_some_and(|head| head.starts_with(prefix))
793            })
794            .filter_map(|request| {
795                let at = request.pointer(merged_at)?.as_str()?.to_owned();
796                let version = release_state::proposed_version(request["title"].as_str()?)?;
797                Some((at, request.pointer(number)?.as_u64()?, version))
798            })
799            .max_by(|left, right| left.0.cmp(&right.0))
800            .map(|(_, number, version)| (number, version))
801    }
802
803    /// Every tag the forge holds, with the commit it names, read page by
804    /// page to the end. A page that cannot be read, or an inventory longer
805    /// than the bound, leaves the list unread, never silently truncated.
806    fn tags(&self) -> Option<Vec<(String, String)>> {
807        let (path, commit) = match self.pair.forge {
808            Forge::Github => (
809                format!("repos/{}/tags?per_page={TAG_PAGE}", self.pair.repo),
810                "/commit/sha",
811            ),
812            Forge::Gitlab => (
813                format!(
814                    "projects/{}/repository/tags?per_page={TAG_PAGE}",
815                    self.project()
816                ),
817                "/commit/id",
818            ),
819        };
820        let mut tags = Vec::new();
821        for page in 1..=TAG_PAGES {
822            let body = if page == 1 {
823                self.api(&path)?
824            } else {
825                self.api(&format!("{path}&page={page}"))?
826            };
827            let entries = body.as_array()?;
828            tags.extend(entries.iter().filter_map(|tag| {
829                Some((
830                    tag["name"].as_str()?.to_owned(),
831                    tag.pointer(commit)?.as_str()?.to_owned(),
832                ))
833            }));
834            if entries.len() < TAG_PAGE {
835                return Some(tags);
836            }
837        }
838        None
839    }
840
841    /// The release page for a tag, with each artifact's attestation.
842    fn page(&self, tag: &str) -> Option<Page> {
843        match self.pair.forge {
844            Forge::Github => {
845                let repo = &self.pair.repo;
846                let body = match self.api_answer(&format!("repos/{repo}/releases/tags/{tag}")) {
847                    Api::Ok(body) => body,
848                    Api::Missing => return Some(Page::default()),
849                    Api::Failed(_) => return None,
850                };
851                let mut page = Page {
852                    exists: true,
853                    ..Page::default()
854                };
855                for asset in body["assets"].as_array().into_iter().flatten() {
856                    let Some(name) = asset["name"].as_str() else {
857                        continue;
858                    };
859                    // The engine's checksum file lists the attested
860                    // artifacts and is no artifact itself, so it neither
861                    // counts as one nor needs an attestation.
862                    if release_state::is_support(name) {
863                        continue;
864                    }
865                    page.assets.push(name.to_owned());
866                    let Some(digest) = asset["digest"].as_str() else {
867                        page.attestation_unknown = true;
868                        continue;
869                    };
870                    match self.api_answer(&format!("repos/{repo}/attestations/{digest}")) {
871                        Api::Ok(body)
872                            if body["attestations"]
873                                .as_array()
874                                .is_some_and(|list| !list.is_empty()) => {}
875                        Api::Ok(_) | Api::Missing => page.unattested.push(name.to_owned()),
876                        Api::Failed(_) => page.attestation_unknown = true,
877                    }
878                }
879                Some(page)
880            }
881            Forge::Gitlab => {
882                let body =
883                    match self.api_answer(&format!("projects/{}/releases/{tag}", self.project())) {
884                        Api::Ok(body) => body,
885                        Api::Missing => return Some(Page::default()),
886                        Api::Failed(_) => return None,
887                    };
888                let names: Vec<String> = body["assets"]["links"]
889                    .as_array()
890                    .into_iter()
891                    .flatten()
892                    .filter_map(|link| link["name"].as_str().map(str::to_owned))
893                    .collect();
894                let bundles: Vec<&String> = names
895                    .iter()
896                    .filter(|name| name.ends_with(release_state::BUNDLE_SUFFIX))
897                    .collect();
898                // The checksum file and the bundles are support material,
899                // and no artifact the page must carry.
900                let assets: Vec<String> = names
901                    .iter()
902                    .filter(|name| !release_state::is_support(name))
903                    .cloned()
904                    .collect();
905                // The distributions the provenance job signs: the bash
906                // tarball, and the python sdist and wheel, each named in the
907                // lowercase the builds write.
908                let unattested = assets
909                    .iter()
910                    .filter(|name| {
911                        [".tar.gz", ".whl"]
912                            .iter()
913                            .any(|suffix| name.to_ascii_lowercase().ends_with(suffix))
914                    })
915                    .filter(|name| {
916                        !bundles.iter().any(|bundle| {
917                            **bundle == format!("{name}{}", release_state::BUNDLE_SUFFIX)
918                        })
919                    })
920                    .cloned()
921                    .collect();
922                Some(Page {
923                    exists: true,
924                    assets,
925                    unattested,
926                    attestation_unknown: false,
927                })
928            }
929        }
930    }
931
932    /// Read the runs on `sha` until the publish run, and the artifact run
933    /// where the pair builds one, concluded or the timeout passed.
934    fn wait(&self, sha: &str, timeout: u64) -> Wait {
935        let interval = std::env::var(WAIT_INTERVAL_VAR)
936            .ok()
937            .and_then(|value| value.parse().ok())
938            .unwrap_or(WAIT_INTERVAL_MS);
939        let deadline = Instant::now() + Duration::from_secs(timeout);
940        loop {
941            let (publish, artifact) = self.runs(sha);
942            let concluded = publish.as_ref().is_some_and(Run::concluded)
943                && (!self.pair.artifacts || artifact.as_ref().is_some_and(Run::concluded));
944            let failed = [&publish, &artifact]
945                .into_iter()
946                .flatten()
947                .any(|run| run.concluded() && !run.succeeded());
948            if concluded || failed || Instant::now() >= deadline {
949                let tag = artifact
950                    .as_ref()
951                    .and_then(|run| run.head_branch.clone())
952                    .filter(|branch| branch.starts_with('v'));
953                return Wait {
954                    sha: sha.to_owned(),
955                    timed_out: !concluded && !failed,
956                    publish,
957                    artifact,
958                    tag,
959                };
960            }
961            std::thread::sleep(Duration::from_millis(interval));
962        }
963    }
964
965    /// The publish run and the artifact run on `sha`.
966    fn runs(&self, sha: &str) -> (Option<Run>, Option<Run>) {
967        match self.pair.forge {
968            Forge::Github => {
969                let Some(body) = self.api(&format!(
970                    "repos/{}/actions/runs?head_sha={sha}&per_page=100",
971                    self.pair.repo
972                )) else {
973                    return (None, None);
974                };
975                let publish = self
976                    .pair
977                    .publish_workflow()
978                    .and_then(|workflow| release_state::github_run_on(&body, workflow, sha));
979                let artifact = self
980                    .pair
981                    .artifact_workflow()
982                    .and_then(|workflow| release_state::github_run_on(&body, workflow, sha));
983                (publish, artifact)
984            }
985            Forge::Gitlab => {
986                let Some(body) = self.api(&format!(
987                    "projects/{}/pipelines?sha={sha}&per_page=100",
988                    self.project()
989                )) else {
990                    return (None, None);
991                };
992                // The rk engine builds and publishes in the branch-push
993                // pipeline of the commit it released, on the trunk or on a
994                // release line. A rust pair publishes from the trunk and
995                // builds in the pipeline of the tag it pushed.
996                let engine =
997                    self.pair.request_prefix() == Some(crate::release_engine::REQUEST_PREFIX);
998                if engine {
999                    let run = release_state::gitlab_branch_push_on(&body, sha, |reference| {
1000                        self.pair.is_base(reference)
1001                    });
1002                    let artifact = self.pair.artifacts.then(|| run.clone()).flatten();
1003                    return (run, artifact);
1004                }
1005                let trunk = self.pair.trunk.clone();
1006                let publish =
1007                    release_state::gitlab_pipeline_on(&body, |reference| reference == trunk);
1008                let artifact = self.pair.artifacts.then(|| {
1009                    release_state::gitlab_pipeline_on(&body, |reference| reference.starts_with('v'))
1010                });
1011                (publish, artifact.flatten())
1012            }
1013        }
1014    }
1015}
1016
1017/// The human report, in the order the JSON states it.
1018fn render(
1019    out: Output,
1020    manifest: &Manifest,
1021    forge: &ForgeState,
1022    observed: &Observed,
1023    lines: &[LineRow],
1024) {
1025    out.result_line(format!(
1026        "release: {} style, {} integration, {} checkout, trunk {}",
1027        manifest
1028            .profile
1029            .release
1030            .style
1031            .map_or("no", |style| style.as_str()),
1032        manifest.git.integration.as_str(),
1033        manifest.git.checkout_mode.as_str(),
1034        manifest.git.trunk
1035    ));
1036    out.result_line(format!(
1037        "forge: {} {} ({}{})",
1038        forge.name.as_deref().unwrap_or("none"),
1039        forge.repo.as_deref().unwrap_or(""),
1040        forge.read.as_str(),
1041        forge
1042            .reason
1043            .as_deref()
1044            .map_or_else(String::new, |reason| format!(": {reason}"))
1045    ));
1046    let request = &observed.request;
1047    match request.state {
1048        "open" => out.result_line(format!(
1049            "request: #{} proposing {}, armed {}, checks {}, behind the trunk {}",
1050            request.number.unwrap_or_default(),
1051            request
1052                .proposed_version
1053                .as_deref()
1054                .unwrap_or("an unread version"),
1055            request.armed.as_str(),
1056            request.checks.as_str(),
1057            request.behind_trunk.as_str()
1058        )),
1059        state => out.result_line(format!("request: {state}")),
1060    }
1061    let last = &observed.last;
1062    out.result_line(format!(
1063        "last release: {}, published {}, artifacts verified {}",
1064        last.tag.as_deref().unwrap_or("none"),
1065        last.published.as_str(),
1066        last.artifacts_verified.as_str()
1067    ));
1068    for row in lines {
1069        out.result_line(format!(
1070            "line {}: newest release {}",
1071            row.branch,
1072            row.newest_release.as_deref().unwrap_or("none")
1073        ));
1074    }
1075    if let Some(wait) = &observed.wait {
1076        let describe = |run: &Option<Run>| {
1077            run.as_ref().map_or_else(
1078                || "not found".to_owned(),
1079                |run| {
1080                    format!(
1081                        "{} {}",
1082                        run.id,
1083                        run.conclusion.as_deref().unwrap_or(run.status.as_str())
1084                    )
1085                },
1086            )
1087        };
1088        out.result_line(format!(
1089            "wait {}: publish run {}, artifact run {}{}",
1090            wait.sha,
1091            describe(&wait.publish),
1092            describe(&wait.artifact),
1093            if wait.timed_out { ", timed out" } else { "" }
1094        ));
1095    }
1096    for symptom in &observed.symptoms {
1097        out.result_line(format!(
1098            "SYMPTOM {}: {} (rk method recovery: {})",
1099            symptom.code, symptom.evidence, symptom.recovery
1100        ));
1101    }
1102    let mut next = Vec::new();
1103    if !observed.symptoms.is_empty() {
1104        next.push("rk method recovery owns the path for each symptom".to_owned());
1105    }
1106    next.push("rk guide release orders the release".to_owned());
1107    out.next(&next);
1108}
1109
1110#[cfg(test)]
1111mod tests {
1112    use super::{ForgeState, Report, Wait};
1113    use crate::commands::lines::LineRow;
1114    use crate::landing::manifest::{CheckoutMode, Integration, Style};
1115    use crate::release_state::{
1116        Answer, Checks, LastRelease, MERGED_NOTHING_PUBLISHED, Request, Run, Symptom,
1117    };
1118
1119    /// The complete `rk.release-status/1` shape, held by snapshot in both
1120    /// the landed and the absent forms.
1121    #[test]
1122    fn the_release_status_schema_snapshot_holds() {
1123        let landed = Report {
1124            schema: super::SCHEMA,
1125            landed: true,
1126            style: Some(Style::Trunk),
1127            integration: Some(Integration::Local),
1128            checkout_mode: Some(CheckoutMode::LinkedWorktree),
1129            trunk: Some("master".into()),
1130            forge: Some(ForgeState {
1131                name: Some("github".into()),
1132                repo: Some("acme/widget".into()),
1133                read: Answer::Yes,
1134                reason: None,
1135            }),
1136            request: Some(Request {
1137                state: "open",
1138                number: Some(12),
1139                proposed_version: Some("1.2.3".into()),
1140                armed: Answer::Yes,
1141                checks: Checks::Passing,
1142                behind_trunk: Answer::No,
1143            }),
1144            last_release: Some(LastRelease {
1145                tag: Some("v1.2.2".into()),
1146                published: Answer::Yes,
1147                artifacts_verified: Answer::NotApplicable,
1148            }),
1149            lines: Some(vec![LineRow {
1150                line: "1.4".into(),
1151                branch: "release/1.4".into(),
1152                presence: "remote",
1153                newest_release: Some("v1.4.5".into()),
1154                newest_candidate: None,
1155                tag_covered: None,
1156                seat: None,
1157            }]),
1158            symptoms: Some(vec![Symptom {
1159                code: MERGED_NOTHING_PUBLISHED,
1160                evidence: "release request #11 proposing 1.2.2 merged, and no tag v1.2.2 exists"
1161                    .into(),
1162                recovery: "The release request merged and nothing published",
1163            }]),
1164            wait: Some(Wait {
1165                sha: "aaa".into(),
1166                publish: Some(Run {
1167                    id: 20,
1168                    status: "completed".into(),
1169                    conclusion: Some("success".into()),
1170                    head_branch: Some("master".into()),
1171                }),
1172                artifact: None,
1173                tag: Some("v1.2.2".into()),
1174                timed_out: false,
1175            }),
1176        };
1177        assert_eq!(
1178            serde_json::to_string(&landed).expect("a report serializes"),
1179            r#"{"schema":"rk.release-status/1","landed":true,"style":"trunk","integration":"local","checkout_mode":"linked-worktree","trunk":"master","forge":{"name":"github","repo":"acme/widget","read":"yes","reason":null},"request":{"state":"open","number":12,"proposed_version":"1.2.3","armed":"yes","checks":"passing","behind_trunk":"no"},"last_release":{"tag":"v1.2.2","published":"yes","artifacts_verified":"not-applicable"},"lines":[{"line":"1.4","branch":"release/1.4","presence":"remote","newest_release":"v1.4.5"}],"symptoms":[{"code":"request-merged-nothing-published","evidence":"release request #11 proposing 1.2.2 merged, and no tag v1.2.2 exists","recovery":"The release request merged and nothing published"}],"wait":{"sha":"aaa","publish":{"id":20,"status":"completed","conclusion":"success","head_branch":"master"},"artifact":null,"tag":"v1.2.2","timed_out":false}}"#
1180        );
1181        let absent = Report {
1182            landed: false,
1183            style: None,
1184            integration: None,
1185            checkout_mode: None,
1186            trunk: None,
1187            forge: None,
1188            request: None,
1189            last_release: None,
1190            lines: None,
1191            symptoms: None,
1192            wait: None,
1193            ..landed
1194        };
1195        assert_eq!(
1196            serde_json::to_string(&absent).expect("a report serializes"),
1197            r#"{"schema":"rk.release-status/1","landed":false}"#
1198        );
1199    }
1200}