Skip to main content

release_kit/setup/
observe.rs

1//! The observe-and-verify half of every step's lifecycle.
2//!
3//! One implementation per forge and step, called by preview never, by apply
4//! before and after the mutation, and by `check` as its whole job — so the
5//! three modes cannot drift apart, and the mutating half is unreachable from
6//! here by construction: nothing spawned from this module mutates anything —
7//! read-only forge-CLI calls, the technology's own dry-run check, and the
8//! App-credential read [`super::app_jwt`] carries for `install-bot`.
9
10use serde_json::Value;
11
12use crate::detect::Forge;
13use crate::error::RkError;
14use crate::setup::app_jwt::{self, AppApi};
15use crate::setup::context::Ctx;
16use crate::setup::process::{Exec, Outcome};
17use crate::setup::workflow_jobs;
18
19/// The executor observes run through: the command layer wraps echoing,
20/// journaling, and redaction around the process adapter.
21pub type Runner<'a> = dyn FnMut(&Exec) -> Result<Outcome, RkError> + 'a;
22
23// The long-lived branch names `single-trunk` retires when each is an
24// ancestor of the trunk come from the target's own configuration, read
25// through `Ctx::retired_branches`. The compiled default is the common
26// default branch and the retired second branch, so a target that names
27// none behaves exactly as it did.
28
29// The landed title check's context is the job in `pr-title.yml` that
30// holds the squash title to the commit convention. The target names it in
31// `protection.title_check`, read through `Ctx::title_check`; the landed
32// job keeps its own name as a source constant, so a target that renames
33// the key without renaming the job breaks its own trunk protection and
34// this observer reports it.
35
36const GITLAB_PRIVATE_REPORTING_LIMITATION: &str = "GitLab has no project-level private reporting switch; the reporter must enable confidentiality; this proves project feature access, not successful submission by every external reporter";
37
38/// What one observation found.
39#[derive(Debug)]
40pub enum StepState {
41    /// The desired state holds; a limitation names what the forge enforces
42    /// less strongly than the step's proof claims.
43    Satisfied {
44        /// What was found, one line.
45        detail: String,
46        /// The weaker guarantee, by name, where the forge enforces less.
47        limitation: Option<String>,
48    },
49    /// The desired state does not hold.
50    Unsatisfied {
51        /// What was found instead.
52        detail: String,
53    },
54    /// Eligibility or an optional step's condition does not hold: nothing
55    /// is proven, and `check` reports it as skipped.
56    Inapplicable {
57        /// Why the step does not apply here.
58        detail: String,
59    },
60    /// The observation could not decide.
61    Unknown {
62        /// Why not.
63        detail: String,
64    },
65}
66
67impl StepState {
68    /// Whether the desired state holds.
69    #[must_use]
70    pub const fn satisfied(&self) -> bool {
71        matches!(self, Self::Satisfied { .. })
72    }
73
74    fn ok(detail: impl Into<String>) -> Self {
75        Self::Satisfied {
76            detail: detail.into(),
77            limitation: None,
78        }
79    }
80
81    fn ok_with_limitation(detail: impl Into<String>, limitation: impl Into<String>) -> Self {
82        Self::Satisfied {
83            detail: detail.into(),
84            limitation: Some(limitation.into()),
85        }
86    }
87
88    fn not(detail: impl Into<String>) -> Self {
89        Self::Unsatisfied {
90            detail: detail.into(),
91        }
92    }
93
94    fn inapplicable(detail: impl Into<String>) -> Self {
95        Self::Inapplicable {
96            detail: detail.into(),
97        }
98    }
99
100    fn unknown(detail: impl Into<String>) -> Self {
101        Self::Unknown {
102            detail: detail.into(),
103        }
104    }
105}
106
107/// One read-only forge API answer.
108enum Api {
109    /// The call succeeded and parsed.
110    Ok(Value),
111    /// The forge answered 404: the thing is not there.
112    Missing,
113    /// The call failed for another reason, with the CLI's own words.
114    Failed(String),
115}
116
117/// Observe one step's desired state.
118///
119/// # Errors
120///
121/// Propagates executor failures; a forge answer that merely disagrees is a
122/// [`StepState`], not an error.
123pub fn observe(ctx: &Ctx, step: &str, run: &mut Runner) -> Result<StepState, RkError> {
124    if step == "package-check" {
125        return package_check(ctx, run);
126    }
127    if step == "branch-reminder" {
128        return Ok(branch_reminder_state(ctx));
129    }
130    if step == "forge-version" {
131        return forge_version(ctx, run);
132    }
133    match ctx.forge {
134        Some(Forge::Github) => github(ctx, step, run),
135        Some(Forge::Gitlab) => gitlab(ctx, step, run),
136        // A forge step at a target with no adapter proves nothing and
137        // reads nothing: the applicability gate states why, and this is
138        // the observation saying the same.
139        None => Ok(StepState::inapplicable(
140            "the profile names no forge this release drives",
141        )),
142    }
143}
144
145/// The policy a consumer must find in the artifact they downloaded. A
146/// reporting policy readable on the forge alone is a policy the consumer
147/// who has only the package cannot follow.
148const POLICY_DESTINATION: &str = "SECURITY.md";
149
150/// What Python's check cannot answer. PEP 517 lets a project choose its
151/// build backend, and an sdist and a wheel can carry different files, so
152/// one `python3 -m build` run supplies no listing contract across both
153/// outputs.
154const PYTHON_LIMITATION: &str = "sdist and wheel policy inclusion is unproved: PEP 517 leaves the file set to the build backend and the two outputs can differ; inspect both before publishing";
155
156/// What Bash's check cannot answer. Its binding builds the tarball with
157/// `git archive`, where an `export-ignore` attribute drops a tracked file.
158const BASH_LIMITATION: &str = "the make dist tarball is not inspected: git archive honours export-ignore, so SECURITY.md inclusion is unproved; inspect the generated tarball before publishing";
159
160/// §0: the technology's own no-credential packaging check; the one step that
161/// reads its command from the binding rather than from a forge tree.
162///
163/// Publishability is the whole of the check for every binding. Policy reach
164/// is asserted only where the binding has a deterministic listing command
165/// the step can run with no credentials, which today is a sole Cargo
166/// package rooted at the target; every other shape reports its successful
167/// packaging result with the unproved inclusion named.
168fn package_check(ctx: &Ctx, run: &mut Runner) -> Result<StepState, RkError> {
169    let (program, args): (&str, &[&str]) = match ctx.tech {
170        Some("rust") => ("cargo", &["publish", "--dry-run", "--allow-dirty"]),
171        Some("python") => ("python3", &["-m", "build"]),
172        Some("bash") => {
173            return Ok(StepState::ok_with_limitation(
174                "no registry for this technology; there is nothing to package",
175                BASH_LIMITATION,
176            ));
177        }
178        Some(other) => {
179            return Ok(StepState::unknown(format!(
180                "no packaging check is defined for {other}"
181            )));
182        }
183        None => {
184            return Ok(StepState::unknown(
185                "no version file names a technology; see rk binding --list",
186            ));
187        }
188    };
189    let outcome = run(&cargo_exec(ctx, program, args))?;
190    if !outcome.success() {
191        return Ok(StepState::not(format!(
192            "the packaging check failed: {}",
193            last_line(&outcome.stderr)
194        )));
195    }
196    let built = "the package builds and passes the registry's dry run";
197    Ok(match ctx.tech {
198        Some("rust") => policy_in_the_crate(ctx, run, built)?,
199        _ => StepState::ok_with_limitation(built, PYTHON_LIMITATION),
200    })
201}
202
203/// One no-credential Cargo invocation against the target.
204fn cargo_exec(ctx: &Ctx, program: &str, args: &[&str]) -> Exec {
205    Exec {
206        program: program.into(),
207        args: args.iter().map(Into::into).collect(),
208        env: ctx.child_env("package-check"),
209        cwd: ctx.target.as_std_path().to_path_buf(),
210        stdin: None,
211    }
212}
213
214/// Whether the published crate carries the root policy, for the one shape
215/// Cargo answers unambiguously.
216///
217/// `cargo package --list` prints one path per line for one package and
218/// emits no stable delimiter when it selects several, and a nested package
219/// cannot include a file above its own root. So the listing runs only for a
220/// sole selected default member whose manifest is the target's own
221/// `Cargo.toml`; a virtual workspace, several default members, and a sole
222/// nested member each keep the successful publishability result and name
223/// the limitation instead of claiming a reach they cannot prove.
224fn policy_in_the_crate(ctx: &Ctx, run: &mut Runner, built: &str) -> Result<StepState, RkError> {
225    let metadata = run(&cargo_exec(
226        ctx,
227        "cargo",
228        &["metadata", "--no-deps", "--format-version", "1"],
229    ))?;
230    if !metadata.success() {
231        return Ok(StepState::unknown(format!(
232            "{built}, and the policy check could not run: cargo metadata failed: {}",
233            last_line(&metadata.stderr)
234        )));
235    }
236    let root_manifest = ctx.target.as_std_path().join("Cargo.toml");
237    let selected = sole_root_package(&metadata.stdout, &root_manifest);
238    let Some(manifest) = selected else {
239        return Ok(StepState::ok_with_limitation(
240            built,
241            format!(
242                "{POLICY_DESTINATION} inclusion is unproved: the package check lists files only for a single default package rooted at the target, and this workspace selects a different shape; inspect the published archive before releasing"
243            ),
244        ));
245    };
246    let listing = run(&cargo_exec(
247        ctx,
248        "cargo",
249        &[
250            "package",
251            "--list",
252            "--allow-dirty",
253            "--manifest-path",
254            &manifest,
255        ],
256    ))?;
257    if !listing.success() {
258        return Ok(StepState::unknown(format!(
259            "{built}, and the policy check could not run: cargo package --list failed: {}",
260            last_line(&listing.stderr)
261        )));
262    }
263    // An exact line, never a substring: `docs/SECURITY.md` and
264    // `SECURITY.md.bak` are different files and neither is the policy.
265    let carried = String::from_utf8_lossy(&listing.stdout)
266        .lines()
267        .any(|line| line.trim() == POLICY_DESTINATION);
268    Ok(if carried {
269        StepState::ok(format!(
270            "{built}, and the published package carries {POLICY_DESTINATION}"
271        ))
272    } else {
273        StepState::not(format!(
274            "{built}, but the published package omits {POLICY_DESTINATION}: add /{POLICY_DESTINATION} to [package].include, remove the [package].exclude entry matching it, or stop ignoring the file"
275        ))
276    })
277}
278
279/// The manifest path of the one selected default package rooted at the
280/// target, or `None` for every other workspace shape.
281fn sole_root_package(metadata: &[u8], root_manifest: &std::path::Path) -> Option<String> {
282    let document: Value = serde_json::from_slice(metadata).ok()?;
283    let defaults: Vec<&str> = document
284        .get("workspace_default_members")?
285        .as_array()?
286        .iter()
287        .filter_map(Value::as_str)
288        .collect();
289    let [only] = defaults.as_slice() else {
290        return None;
291    };
292    let manifest = document
293        .get("packages")?
294        .as_array()?
295        .iter()
296        .find(|package| package.get("id").and_then(Value::as_str) == Some(*only))?
297        .get("manifest_path")?
298        .as_str()?;
299    // Compare what each path resolves to, so a symlinked or
300    // differently-spelled target directory still reads as the root.
301    let same =
302        std::fs::canonicalize(manifest).ok()? == std::fs::canonicalize(root_manifest).ok()?;
303    same.then(|| manifest.to_owned())
304}
305
306/// §1: the post-merge reminder hook, judged from the target's own files;
307/// the one step whose observation asks no forge and spawns no CLI.
308fn branch_reminder_state(ctx: &Ctx) -> StepState {
309    use crate::setup::branch_reminder::{HookState, observe_hook};
310    match observe_hook(&ctx.target) {
311        HookState::Installed => {
312            StepState::ok("the post-merge hook carries the release-kit reminder")
313        }
314        HookState::Absent => StepState::not("no post-merge hook is installed"),
315        HookState::Foreign => {
316            StepState::not("a post-merge hook exists without the release-kit marker")
317        }
318        HookState::Drifted => StepState::not("the reminder hook drifted from this binary's body"),
319        HookState::Unreadable(detail) => StepState::unknown(detail),
320    }
321}
322
323/// The GitLab version this convention needs, as major and minor.
324///
325/// `trigger: strategy: mirror` arrived in GitLab 18.2, and the merge-request
326/// pipeline's `project-jobs` bridge rests on it: below the floor the child
327/// pipeline's status never reaches the parent, so a failing project job
328/// merges.
329pub const GITLAB_VERSION_FLOOR: (u64, u64) = (18, 2);
330
331/// The two suffixes that name an edition rather than a pre-release. Every
332/// other suffix is a pre-release, and the step fails closed on one.
333const GITLAB_EDITIONS: [&str; 2] = ["ee", "ce"];
334
335/// The refusal an instance below the floor reads: the reading, the reason,
336/// and the fix.
337fn version_refusal(found: &str, prerelease: Option<&str>) -> String {
338    let (major, minor) = GITLAB_VERSION_FLOOR;
339    let mut said = vec![format!(
340        "this GitLab instance reports {found}; the convention needs {major}.{minor} or newer"
341    )];
342    if let Some(suffix) = prerelease {
343        said.push(format!(
344            "the -{suffix} suffix is a pre-release, and nothing proves the feature shipped in it, so this step fails closed"
345        ));
346    }
347    said.push(format!(
348        "the merge-request pipeline triggers a child pipeline with `strategy: mirror`, which GitLab added in {major}.{minor}"
349    ));
350    said.push(
351        "below it the child's status never reaches the parent pipeline, so a failing project job merges".to_owned(),
352    );
353    said.push(format!(
354        "upgrade the instance to {major}.{minor} or newer, or host the project on gitlab.com"
355    ));
356    said.join("; ")
357}
358
359/// §3: the forge's own version against the convention's floor.
360///
361/// GitHub is a rolling service and is answered without a call. GitLab is one
362/// read-only `GET /version`, and every failure to read is `Unknown`, which
363/// blocks the `protect-trunk` prerequisite exactly as `Unsatisfied` does.
364fn forge_version(ctx: &Ctx, run: &mut Runner) -> Result<StepState, RkError> {
365    if ctx.forge == Some(Forge::Github) {
366        return Ok(StepState::ok(
367            "github.com is a rolling service and declares no version floor",
368        ));
369    }
370    let body = match api_get(ctx, run, "version")? {
371        Api::Ok(body) => body,
372        Api::Missing => {
373            return Ok(StepState::unknown(
374                "this instance answers no GET /version; the floor cannot be read. Check that glab is authenticated against it: glab auth login",
375            ));
376        }
377        Api::Failed(err) => {
378            return Ok(StepState::unknown(format!(
379                "the version could not be read: {err}. Check that glab is authenticated against this instance: glab auth login"
380            )));
381        }
382    };
383    let Some(found) = body["version"].as_str() else {
384        return Ok(StepState::unknown(
385            "the forge answer carries no version field; the floor cannot be read. Check that glab is authenticated against this instance: glab auth login",
386        ));
387    };
388    let (number, suffix) = found
389        .split_once('-')
390        .map_or((found, None), |(n, s)| (n, Some(s)));
391    let mut parts = number.split('.');
392    let parsed = parts
393        .next()
394        .and_then(|major| major.parse::<u64>().ok())
395        .zip(parts.next().and_then(|minor| minor.parse::<u64>().ok()));
396    let Some(pair) = parsed else {
397        return Ok(StepState::unknown(format!(
398            "the forge reports the version as '{found}', which names no major and minor pair; the floor cannot be read"
399        )));
400    };
401    if let Some(suffix) = suffix.filter(|s| !GITLAB_EDITIONS.contains(s)) {
402        return Ok(StepState::not(version_refusal(found, Some(suffix))));
403    }
404    if pair < GITLAB_VERSION_FLOOR {
405        return Ok(StepState::not(version_refusal(found, None)));
406    }
407    let (major, minor) = GITLAB_VERSION_FLOOR;
408    Ok(StepState::ok(format!(
409        "this instance reports {found}, at or above the {major}.{minor} floor"
410    )))
411}
412
413/// The destructive step's own guard: whether deleting a candidate branch
414/// can lose work.
415///
416/// `Satisfied` means every candidate is already gone or is an ancestor of
417/// the trunk; `Unsatisfied` means the deletion must refuse.
418///
419/// # Errors
420///
421/// Propagates executor failures.
422pub fn single_trunk_guard(ctx: &Ctx, run: &mut Runner) -> Result<StepState, RkError> {
423    let trunk = ctx.trunk();
424    for candidate in ctx.retired_branches() {
425        let candidate = candidate.as_str();
426        if candidate == trunk {
427            continue;
428        }
429        let state = match ctx.forge {
430            Some(Forge::Github) => github_candidate_guard(ctx, run, candidate)?,
431            Some(Forge::Gitlab) => gitlab_candidate_guard(ctx, run, candidate)?,
432            // A destructive step fails closed, and an absent adapter is
433            // one more thing the guard cannot establish.
434            None => StepState::unknown("the profile names no forge this release drives"),
435        };
436        if !state.satisfied() {
437            return Ok(state);
438        }
439    }
440    Ok(StepState::ok(
441        "every candidate branch is absent, or an ancestor of the trunk",
442    ))
443}
444
445/// One candidate branch's ancestry, on GitHub.
446fn github_candidate_guard(
447    ctx: &Ctx,
448    run: &mut Runner,
449    candidate: &str,
450) -> Result<StepState, RkError> {
451    let trunk = ctx.trunk();
452    match api_get(
453        ctx,
454        run,
455        &format!("repos/{}/git/ref/heads/{candidate}", ctx.repo),
456    )? {
457        Api::Missing => return Ok(StepState::ok(format!("{candidate} is already gone"))),
458        Api::Failed(err) => return Ok(StepState::unknown(err)),
459        Api::Ok(_) => {}
460    }
461    match api_get(
462        ctx,
463        run,
464        &format!("repos/{}/compare/{candidate}...{trunk}", ctx.repo),
465    )? {
466        Api::Ok(body) => {
467            let status = body["status"].as_str().unwrap_or("");
468            Ok(if matches!(status, "ahead" | "identical") {
469                StepState::ok(format!("{candidate} is an ancestor of {trunk}"))
470            } else {
471                StepState::not(format!(
472                    "{candidate} is not an ancestor of {trunk} ({status}); deleting it would lose work"
473                ))
474            })
475        }
476        Api::Missing => Ok(StepState::unknown("the comparison is not readable")),
477        Api::Failed(err) => Ok(StepState::unknown(err)),
478    }
479}
480
481/// One candidate branch's ancestry, on GitLab.
482fn gitlab_candidate_guard(
483    ctx: &Ctx,
484    run: &mut Runner,
485    candidate: &str,
486) -> Result<StepState, RkError> {
487    let trunk = ctx.trunk();
488    let project = ctx.repo.replace('/', "%2F");
489    match api_get(
490        ctx,
491        run,
492        &format!("projects/{project}/repository/branches/{candidate}"),
493    )? {
494        Api::Missing => return Ok(StepState::ok(format!("{candidate} is already gone"))),
495        Api::Failed(err) => return Ok(StepState::unknown(err)),
496        Api::Ok(_) => {}
497    }
498    match api_get(
499        ctx,
500        run,
501        &format!("projects/{project}/repository/compare?from={trunk}&to={candidate}"),
502    )? {
503        Api::Ok(body) => {
504            let ahead = body["commits"]
505                .as_array()
506                .is_some_and(|list| !list.is_empty());
507            Ok(if ahead {
508                StepState::not(format!(
509                    "{candidate} carries commits {trunk} does not; deleting it would lose work"
510                ))
511            } else {
512                StepState::ok(format!("{candidate} is an ancestor of {trunk}"))
513            })
514        }
515        Api::Missing => Ok(StepState::unknown("the comparison is not readable")),
516        Api::Failed(err) => Ok(StepState::unknown(err)),
517    }
518}
519
520/// One captured, read-only forge API call.
521fn api_get(ctx: &Ctx, run: &mut Runner, path: &str) -> Result<Api, RkError> {
522    let exec = Exec {
523        program: ctx.cli.clone().into_os_string(),
524        args: vec!["api".into(), path.into()],
525        env: ctx.child_env("observe"),
526        cwd: ctx.target.as_std_path().to_path_buf(),
527        stdin: None,
528    };
529    let outcome = run(&exec)?;
530    if outcome.success() {
531        return Ok(
532            serde_json::from_slice::<Value>(&outcome.stdout).map_or_else(
533                |_| Api::Failed("the forge answer did not parse as JSON".into()),
534                Api::Ok,
535            ),
536        );
537    }
538    let stderr = String::from_utf8_lossy(&outcome.stderr).into_owned();
539    if stderr.contains("404") {
540        Ok(Api::Missing)
541    } else {
542        Ok(Api::Failed(last_line(&outcome.stderr)))
543    }
544}
545
546/// The last non-empty line of a byte stream, for one-line detail fields.
547fn last_line(bytes: &[u8]) -> String {
548    String::from_utf8_lossy(bytes)
549        .lines()
550        .rev()
551        .find(|line| !line.trim().is_empty())
552        .unwrap_or("no output")
553        .to_owned()
554}
555
556#[allow(
557    clippy::too_many_lines,
558    reason = "one arm per setup step, so the match is what makes an unobserved step a compile error"
559)]
560fn github(ctx: &Ctx, step: &str, run: &mut Runner) -> Result<StepState, RkError> {
561    let trunk = ctx.trunk();
562    let repo = &ctx.repo;
563    match step {
564        "private-vulnerability-reporting" => {
565            let visibility_path = format!("repos/{repo}");
566            match api_get(ctx, run, &visibility_path)? {
567                Api::Ok(body) => match body["private"].as_bool() {
568                    Some(true) => {
569                        return Ok(StepState::inapplicable(
570                            "private vulnerability reporting is available for public repositories",
571                        ));
572                    }
573                    Some(false) => {}
574                    None => {
575                        return Ok(StepState::unknown(format!(
576                            "{visibility_path}: repository visibility is unreadable"
577                        )));
578                    }
579                },
580                Api::Missing => {
581                    return Ok(StepState::unknown(format!(
582                        "{visibility_path}: repository visibility is unreadable (404)"
583                    )));
584                }
585                Api::Failed(err) => {
586                    return Ok(StepState::unknown(format!("{visibility_path}: {err}")));
587                }
588            }
589            let path = format!("repos/{repo}/private-vulnerability-reporting");
590            Ok(match api_get(ctx, run, &path)? {
591                Api::Ok(body) => match body["enabled"].as_bool() {
592                    Some(true) => StepState::ok("private vulnerability reporting is enabled"),
593                    Some(false) => StepState::not("private vulnerability reporting is disabled"),
594                    None => StepState::unknown(format!("{path}: enabled is unreadable")),
595                },
596                Api::Missing => {
597                    StepState::unknown(format!("{path}: reporting state is unreadable (404)"))
598                }
599                Api::Failed(err) => StepState::unknown(format!("{path}: {err}")),
600            })
601        }
602
603        "default-branch" => Ok(match api_get(ctx, run, &format!("repos/{repo}"))? {
604            Api::Ok(body) => {
605                let found = body["default_branch"].as_str().unwrap_or("");
606                if found == trunk {
607                    StepState::ok(format!("{trunk} is the default branch"))
608                } else {
609                    StepState::not(format!("the default branch is {found}"))
610                }
611            }
612            Api::Missing => StepState::not(format!("the forge does not know {repo}")),
613            Api::Failed(err) => StepState::unknown(err),
614        }),
615        "single-trunk" => {
616            for candidate in ctx.retired_branches() {
617                let candidate = candidate.as_str();
618                if candidate == trunk {
619                    continue;
620                }
621                match api_get(ctx, run, &format!("repos/{repo}/git/ref/heads/{candidate}"))? {
622                    Api::Missing => {}
623                    Api::Ok(_) => {
624                        return Ok(StepState::not(format!("a {candidate} branch still exists")));
625                    }
626                    Api::Failed(err) => return Ok(StepState::unknown(err)),
627                }
628            }
629            Ok(StepState::ok(
630                "no long-lived branch besides the trunk remains",
631            ))
632        }
633        "merge-cleanup" => Ok(match api_get(ctx, run, &format!("repos/{repo}"))? {
634            Api::Ok(body) => {
635                if body["delete_branch_on_merge"].as_bool().unwrap_or(false) {
636                    StepState::ok("a merged branch is deleted by the forge")
637                } else {
638                    StepState::not("a merged branch outlives its merge")
639                }
640            }
641            Api::Missing => StepState::not(format!("the forge does not know {repo}")),
642            Api::Failed(err) => StepState::unknown(err),
643        }),
644        "auto-merge" => Ok(match api_get(ctx, run, &format!("repos/{repo}"))? {
645            Api::Ok(body) => {
646                if body["allow_auto_merge"].as_bool().unwrap_or(false) {
647                    StepState::ok("a request may merge itself once its checks pass")
648                } else {
649                    StepState::not("a request cannot merge itself; the auto-merge switch is off")
650                }
651            }
652            Api::Missing => StepState::not(format!("the forge does not know {repo}")),
653            Api::Failed(err) => StepState::unknown(err),
654        }),
655        "ci-permissions" => Ok(
656            match api_get(
657                ctx,
658                run,
659                &format!("repos/{repo}/actions/permissions/workflow"),
660            )? {
661                Api::Ok(body) => {
662                    let write = body["default_workflow_permissions"] == "write";
663                    let approve = body["can_approve_pull_request_reviews"] == true;
664                    if write && approve {
665                        StepState::ok("CI may write and open requests")
666                    } else {
667                        StepState::not(format!(
668                            "workflow permissions are {} with request approval {}",
669                            body["default_workflow_permissions"],
670                            body["can_approve_pull_request_reviews"]
671                        ))
672                    }
673                }
674                Api::Missing => StepState::not("no workflow permissions are readable"),
675                Api::Failed(err) => StepState::unknown(err),
676            },
677        ),
678        "bot-secrets" => Ok(
679            match api_get(ctx, run, &format!("repos/{repo}/actions/secrets"))? {
680                Api::Ok(body) => {
681                    let names: Vec<&str> = body["secrets"]
682                        .as_array()
683                        .map(|list| {
684                            list.iter()
685                                .filter_map(|secret| secret["name"].as_str())
686                                .collect()
687                        })
688                        .unwrap_or_default();
689                    let wanted = ["RELEASE_BOT_APP_ID", "RELEASE_BOT_APP_PRIVATE_KEY"];
690                    if wanted.iter().all(|name| names.contains(name)) {
691                        StepState::ok("both bot secrets are stored")
692                    } else if names.is_empty() {
693                        StepState::not("no bot secrets are stored")
694                    } else {
695                        StepState::not(format!("stored secrets: {}", names.join(", ")))
696                    }
697                }
698                Api::Missing => StepState::not("no secrets are readable"),
699                Api::Failed(err) => StepState::unknown(err),
700            },
701        ),
702        "protect-trunk" => github_trunk_ruleset(ctx, run),
703        "protect-tags" => github_ruleset(
704            ctx,
705            run,
706            ctx.tag_ruleset(),
707            "tag",
708            "refs/tags/v*",
709            &["deletion", "update"],
710        ),
711        "protect-release-lines" => {
712            match github_ruleset_body(ctx, run, ctx.lines_ruleset())? {
713                RulesetLookup::Absent => {
714                    return Ok(StepState::inapplicable(
715                        "release/* is unprotected; optional — applied only where older lines exist",
716                    ));
717                }
718                RulesetLookup::Unreadable(err) => return Ok(StepState::unknown(err)),
719                RulesetLookup::Found(_) => {}
720            }
721            github_ruleset(
722                ctx,
723                run,
724                ctx.lines_ruleset(),
725                "branch",
726                "refs/heads/release/*",
727                &["deletion", "non_fast_forward"],
728            )
729        }
730        "protections-check" => {
731            // Confirmed drift and unreadable answers stay apart: a proven
732            // mismatch is drift even beside an outage, and an outage with
733            // nothing proven wrong stays unknown, never drift.
734            let mut failures = Vec::new();
735            let mut unknowns = Vec::new();
736            // Every satisfied step's limitation survives the aggregate.
737            let mut limitations: Vec<String> = Vec::new();
738            for owned in ["protect-trunk", "protect-tags", "protect-release-lines"] {
739                match github(ctx, owned, run)? {
740                    StepState::Satisfied {
741                        limitation: found, ..
742                    } => limitations.extend(found),
743                    StepState::Inapplicable { .. } => {}
744                    StepState::Unsatisfied { detail } => {
745                        failures.push(format!("{owned}: {detail}"));
746                    }
747                    StepState::Unknown { detail } => {
748                        unknowns.push(format!("{owned}: {detail}"));
749                    }
750                }
751            }
752            match api_get(ctx, run, &format!("repos/{repo}/rulesets"))? {
753                Api::Ok(body) => {
754                    let owned = [
755                        ctx.trunk_ruleset().to_owned(),
756                        ctx.tag_ruleset().to_owned(),
757                        ctx.lines_ruleset().to_owned(),
758                    ];
759                    for ruleset in body.as_array().into_iter().flatten() {
760                        let name = ruleset["name"].as_str().unwrap_or("");
761                        if !owned.iter().any(|expected| expected == name) {
762                            failures.push(format!("a ruleset no step owns: {name}"));
763                        }
764                    }
765                }
766                Api::Missing | Api::Failed(_) => {
767                    unknowns.push("the ruleset inventory is not readable".to_owned());
768                }
769            }
770            Ok(if !failures.is_empty() {
771                StepState::not(failures.join("; "))
772            } else if !unknowns.is_empty() {
773                StepState::unknown(unknowns.join("; "))
774            } else {
775                StepState::Satisfied {
776                    detail: "exactly the owned protections, with those rules".into(),
777                    limitation: if limitations.is_empty() {
778                        None
779                    } else {
780                        Some(limitations.join("; "))
781                    },
782                }
783            })
784        }
785        _ => Ok(StepState::unknown(format!("no observation for {step}"))),
786    }
787}
788
789/// The installation, observed as the App itself.
790///
791/// The forge serves `repos/{owner}/{repo}/installation` to an App JWT and
792/// to nothing a user can hold. The caller mints `jwt` — once per run, with
793/// the token and the key bytes already registered as redaction needles —
794/// which is why this lives outside the name dispatch above: an observation
795/// entered without that token has no honest answer.
796#[must_use]
797pub fn github_install_bot(ctx: &Ctx, jwt: &str) -> StepState {
798    match app_jwt::api_get(ctx, jwt, &format!("repos/{}/installation", ctx.repo)) {
799        AppApi::Ok(body) => {
800            let id = body["id"].as_i64().unwrap_or_default();
801            let held = &body["permissions"];
802            let short: Vec<String> = minimum_grant(ctx)
803                .into_iter()
804                .filter(|(key, level)| held[key] != *level)
805                .map(|(key, level)| format!("{key}: {level}"))
806                .collect();
807            if short.is_empty() {
808                StepState::ok(format!("installation {id} covers {}", ctx.repo))
809            } else {
810                // An installation predating a widened grant reads
811                // unsatisfied until its owner approves the new permission
812                // in the App's installation settings; no token this run
813                // can mint grants it.
814                StepState::not(format!(
815                    "installation {id} covers {} and does not hold [{}]; approve the App's updated permissions on the installation's own settings page",
816                    ctx.repo,
817                    short.join(", ")
818                ))
819            }
820        }
821        AppApi::Missing => StepState::not(format!("the App is not installed on {}", ctx.repo)),
822        AppApi::Refused(detail) | AppApi::Failed(detail) => StepState::unknown(detail),
823    }
824}
825
826/// The release App's minimum grant for this target, as the installation
827/// reports it.
828///
829/// Contents and pull requests carry the release itself: the tag, the bump
830/// branch, and the request. A rendered release gate reads a check run
831/// beside them, and that rendering is the one shape that needs the third
832/// permission, so a target that renders no gate is not asked for it.
833fn minimum_grant(ctx: &Ctx) -> Vec<(&'static str, &'static str)> {
834    let mut grant = vec![("contents", "write"), ("pull_requests", "write")];
835    if ctx.integration() == crate::landing::Integration::Local
836        && ctx.profile.release.style == Some(crate::landing::Style::Trunk)
837    {
838        grant.push(("checks", "read"));
839    }
840    grant
841}
842
843/// A plain ruleset: active, and carrying exactly the expected rule types —
844/// not one fewer, and not one more, because an extra rule here is a rule the
845/// setup cannot reproduce or explain and can block the very push the method
846/// depends on.
847fn github_ruleset(
848    ctx: &Ctx,
849    run: &mut Runner,
850    name: &str,
851    target: &str,
852    include: &str,
853    rules: &[&str],
854) -> Result<StepState, RkError> {
855    let detail = match github_ruleset_body(ctx, run, name)? {
856        RulesetLookup::Found(detail) => detail,
857        RulesetLookup::Absent => {
858            return Ok(StepState::not(format!("no ruleset named {name}")));
859        }
860        RulesetLookup::Unreadable(err) => return Ok(StepState::unknown(err)),
861    };
862    if detail["enforcement"] != "active" {
863        return Ok(StepState::not(format!("{name} is not active")));
864    }
865    // The name proves nothing: the ruleset must cover exactly the declared
866    // refs, or the protection it reports exists somewhere else.
867    if detail["target"] != target {
868        return Ok(StepState::not(format!(
869            "{name} does not target {target} refs"
870        )));
871    }
872    if detail["conditions"]["ref_name"]["include"] != serde_json::json!([include]) {
873        return Ok(StepState::not(format!(
874            "{name} does not cover {include} alone"
875        )));
876    }
877    if detail["conditions"]["ref_name"]["exclude"] != serde_json::json!([]) {
878        return Ok(StepState::not(format!(
879            "{name} excludes refs from its own coverage"
880        )));
881    }
882    let mut held: Vec<&str> = detail["rules"]
883        .as_array()
884        .map(|list| {
885            list.iter()
886                .filter_map(|rule| rule["type"].as_str())
887                .collect()
888        })
889        .unwrap_or_default();
890    held.sort_unstable();
891    let mut expected: Vec<&str> = rules.to_vec();
892    expected.sort_unstable();
893    if held == expected {
894        Ok(StepState::ok(format!(
895            "{name} is active with exactly its rules"
896        )))
897    } else {
898        Ok(StepState::not(format!(
899            "{name} carries the rules [{}] where the setup owns [{}]",
900            held.join(", "),
901            expected.join(", ")
902        )))
903    }
904}
905
906// The trunk ruleset is checked for the shape a release merge needs.
907// The rule kinds the setup writes and can reproduce come from
908// `protection.owned_trunk_rules`, floored to contain all four. The set
909// also drives the missing-rule fault, so a kind this convention refuses
910// must stay out of it: adding one would demand that rule on every target.
911// The floor is what stops a target dropping one it needs.
912
913/// A fault line for every rule on the trunk that the setup does not own.
914///
915/// The merge queue gets its own text, because this convention refuses one
916/// deliberately and the operator needs the consequence and the remedy. Every
917/// other unowned kind reads generically: an unowned rule is one the setup
918/// cannot reproduce or explain, and it can block the very merge the method
919/// depends on.
920fn unowned_rule_faults(rules: &[Value], owned: &[String]) -> Vec<String> {
921    rules
922        .iter()
923        .filter_map(|rule| rule["type"].as_str())
924        .filter(|kind| !owned.iter().any(|name| name == kind))
925        .map(|kind| {
926            if kind == "merge_queue" {
927                MERGE_QUEUE_FAULT.to_owned()
928            } else {
929                format!("an unowned rule is present: {kind}")
930            }
931        })
932        .collect()
933}
934
935fn github_trunk_ruleset(ctx: &Ctx, run: &mut Runner) -> Result<StepState, RkError> {
936    let trunk = ctx.trunk();
937    let name = ctx.trunk_ruleset().to_owned();
938    let detail = match github_ruleset_body(ctx, run, &name)? {
939        RulesetLookup::Found(detail) => detail,
940        RulesetLookup::Absent => {
941            return Ok(StepState::not(format!("no ruleset named {name}")));
942        }
943        RulesetLookup::Unreadable(err) => return Ok(StepState::unknown(err)),
944    };
945    let rules = detail["rules"].as_array().cloned().unwrap_or_default();
946    let has = |kind: &str| rules.iter().any(|rule| rule["type"] == kind);
947    let mut faults = Vec::new();
948    if detail["enforcement"] != "active" {
949        faults.push(format!("{name} is not active"));
950    }
951    // The name proves nothing: a ruleset applies only where its conditions
952    // say, so a right-named ruleset covering another ref would otherwise
953    // read as a protected trunk.
954    if detail["target"] != "branch" {
955        faults.push(format!("{name} does not target branches"));
956    }
957    let expected_ref = serde_json::json!([format!("refs/heads/{trunk}")]);
958    if detail["conditions"]["ref_name"]["include"] != expected_ref {
959        faults.push(format!("{name} does not cover refs/heads/{trunk} alone"));
960    }
961    // A matching exclusion negates the include, so the owned shape is an
962    // exclusion list that is exactly empty.
963    if detail["conditions"]["ref_name"]["exclude"] != serde_json::json!([]) {
964        faults.push(format!("{name} excludes refs from its own coverage"));
965    }
966    if !detail["bypass_actors"].as_array().is_none_or(Vec::is_empty) {
967        faults.push("a bypass actor is named".to_owned());
968    }
969    for required in &ctx.protection().owned_trunk_rules {
970        if !has(required) {
971            faults.push(format!("the {required} rule is missing"));
972        }
973    }
974    faults.extend(unowned_rule_faults(
975        &rules,
976        &ctx.protection().owned_trunk_rules,
977    ));
978    if let Some(request) = rules.iter().find(|rule| rule["type"] == "pull_request")
979        && request["parameters"]["allowed_merge_methods"]
980            != serde_json::json!(ctx.protection().allowed_merge_methods)
981    {
982        faults.push("the merge method is not exactly a squash merge".to_owned());
983    }
984    if let Some(checks) = rules
985        .iter()
986        .find(|rule| rule["type"] == "required_status_checks")
987    {
988        if checks["parameters"]["strict_required_status_checks_policy"]
989            != ctx.protection().strict_required_status_checks
990        {
991            faults.push(STALE_MERGE_FAULT.to_owned());
992        }
993        let contexts: Vec<&str> = checks["parameters"]["required_status_checks"]
994            .as_array()
995            .map(|list| {
996                list.iter()
997                    .filter_map(|check| check["context"].as_str())
998                    .collect()
999            })
1000            .unwrap_or_default();
1001        // Where the expected check is known, the context set must be exactly
1002        // it plus the title check: an extra stale context does not fail a
1003        // merge, it hangs one, and a missing title check lets an
1004        // unconventional squash title land on the trunk.
1005        if contexts.is_empty() {
1006            faults.push("no status check is required".to_owned());
1007        } else if let Some(expected) = &ctx.required_check {
1008            let mut held = contexts.clone();
1009            held.sort_unstable();
1010            let title_check = ctx.title_check();
1011            let mut owned_contexts = [expected.as_str(), title_check];
1012            owned_contexts.sort_unstable();
1013            if held != owned_contexts {
1014                faults.push(format!(
1015                    "the required checks are [{}] where the setup owns [{}]",
1016                    contexts.join(", "),
1017                    owned_contexts.join(", ")
1018                ));
1019            }
1020        } else if !contexts.contains(&ctx.title_check()) {
1021            faults.push(format!("the {} check is not required", ctx.title_check()));
1022        }
1023    }
1024    match squash_merge_sources(ctx, run)? {
1025        MergeSources::Owned => {}
1026        MergeSources::Faults(proven) => faults.extend(proven),
1027        // Proven drift wins over an outage: an unreadable settings read
1028        // downgrades the answer to unknown only when nothing above it was
1029        // proven wrong.
1030        MergeSources::Unreadable(err) => {
1031            if faults.is_empty() {
1032                return Ok(StepState::unknown(err));
1033            }
1034        }
1035    }
1036    if let Some(shape) = gate_faults(ctx) {
1037        faults.push(shape);
1038    }
1039    if !faults.is_empty() {
1040        return Ok(StepState::not(faults.join("; ")));
1041    }
1042    Ok(StepState::ok(format!(
1043        "{name} holds the release-merge shape"
1044    )))
1045}
1046
1047/// The ways the named gate is shaped so that it cannot report a blocking
1048/// answer. A required check that never reports is a broken trunk
1049/// protection, not a weaker guarantee, so each of these is a fault rather
1050/// than a limitation. Read only where the check is named: without the flag
1051/// the observation knows no gate.
1052///
1053/// It judges the gate alone. Which other jobs a project means to block a
1054/// merge is intent, no file states it, and `forges/github.md` carries that
1055/// as a convention instead.
1056fn gate_faults(ctx: &Ctx) -> Option<String> {
1057    let check = ctx.required_check.as_deref()?;
1058    let shape = workflow_jobs::faults(
1059        &workflow_jobs::read_gate(&ctx.target, check, ctx.trunk()),
1060        check,
1061        ctx.trunk(),
1062    );
1063    // Under local integration the release gate waits on a workflow
1064    // completing and then judges this check. A trigger cannot name a check
1065    // and a required context cannot name a workflow, so nothing but this
1066    // reader proves the two answers describe one file.
1067    let waking = (ctx.integration() == crate::landing::Integration::Local)
1068        .then_some(ctx.required_workflow.as_deref())
1069        .flatten()
1070        .and_then(|workflow| {
1071            workflow_jobs::waking_workflow_fault(&ctx.target, workflow, check, ctx.trunk())
1072        });
1073    match (shape, waking) {
1074        (None, None) => None,
1075        (Some(one), None) | (None, Some(one)) => Some(one),
1076        (Some(shape), Some(waking)) => Some(format!("{shape}; {waking}")),
1077    }
1078}
1079
1080/// What the repository's squash message settings hold.
1081enum MergeSources {
1082    /// The request's title and body, as the setup owns.
1083    Owned,
1084    /// Proven other values, one fault line each.
1085    Faults(Vec<String>),
1086    /// The settings could not be read.
1087    Unreadable(String),
1088}
1089
1090/// The squash message sources, repository settings beside the ruleset:
1091/// with the title source unset, a one-commit request offers that commit's
1092/// own subject as the trunk's message, which the bot then reads for the
1093/// version; with the message source on another value, the trunk's body is
1094/// not the request's description the content gates judged. One GET
1095/// answers for both, each faulted by name.
1096fn squash_merge_sources(ctx: &Ctx, run: &mut Runner) -> Result<MergeSources, RkError> {
1097    Ok(match api_get(ctx, run, &format!("repos/{}", ctx.repo))? {
1098        Api::Ok(body) => {
1099            let mut faults = Vec::new();
1100            let owned_title = ctx.protection().github.squash_title_source.as_str();
1101            let owned_body = ctx.protection().github.squash_body_source.as_str();
1102            if body["squash_merge_commit_title"] != owned_title {
1103                faults.push(format!(
1104                    "the squash title source is {} where the setup owns {owned_title}",
1105                    body["squash_merge_commit_title"]
1106                ));
1107            }
1108            if body["squash_merge_commit_message"] != owned_body {
1109                faults.push(format!(
1110                    "the squash message source is {} where the setup owns {owned_body}",
1111                    body["squash_merge_commit_message"]
1112                ));
1113            }
1114            if faults.is_empty() {
1115                MergeSources::Owned
1116            } else {
1117                MergeSources::Faults(faults)
1118            }
1119        }
1120        Api::Missing => MergeSources::Faults(vec![format!("the forge does not know {}", ctx.repo)]),
1121        Api::Failed(err) => MergeSources::Unreadable(err),
1122    })
1123}
1124
1125/// One ruleset lookup by name: found, provably absent, or unreadable —
1126/// an unreadable inventory must never read as an absent ruleset.
1127enum RulesetLookup {
1128    /// The ruleset exists; its detail body.
1129    Found(Value),
1130    /// The inventory was read successfully and no ruleset carries the
1131    /// name.
1132    Absent,
1133    /// The inventory or the detail could not be read.
1134    Unreadable(String),
1135}
1136
1137/// A ruleset's detail body by name.
1138fn github_ruleset_body(ctx: &Ctx, run: &mut Runner, name: &str) -> Result<RulesetLookup, RkError> {
1139    // A 404 on the collection is an unreachable inventory — a missing
1140    // repository or an unauthorized read — never an empty one: an empty
1141    // inventory answers 200 with an empty list.
1142    let list = match api_get(ctx, run, &format!("repos/{}/rulesets", ctx.repo))? {
1143        Api::Ok(body) => body,
1144        Api::Missing => {
1145            return Ok(RulesetLookup::Unreadable(
1146                "the ruleset inventory is not readable".into(),
1147            ));
1148        }
1149        Api::Failed(err) => return Ok(RulesetLookup::Unreadable(err)),
1150    };
1151    let id = list
1152        .as_array()
1153        .into_iter()
1154        .flatten()
1155        .find(|ruleset| ruleset["name"] == name)
1156        .and_then(|ruleset| ruleset["id"].as_i64());
1157    let Some(id) = id else {
1158        return Ok(RulesetLookup::Absent);
1159    };
1160    match api_get(ctx, run, &format!("repos/{}/rulesets/{id}", ctx.repo))? {
1161        Api::Ok(body) => Ok(RulesetLookup::Found(body)),
1162        // A listed id that answers 404 is not proof of absence either — the
1163        // forge also answers 404 for an unauthorized read — so a rerun
1164        // decides, rather than a false drift.
1165        Api::Missing => Ok(RulesetLookup::Unreadable(format!(
1166            "the {name} detail is not readable"
1167        ))),
1168        Api::Failed(err) => Ok(RulesetLookup::Unreadable(err)),
1169    }
1170}
1171
1172/// The GitLab limitation the `auto-merge` step reports: the forge has no
1173/// project-level switch, so the observation reads the pipeline requirement
1174/// the trunk protection asserts.
1175const GITLAB_AUTO_MERGE_LIMITATION: &str = "the forge offers no project-level auto-merge switch: availability follows the pipeline requirement protect-trunk asserts, and turning that requirement off removes auto-merge with nothing here reporting it";
1176
1177/// The GitLab limitation `protect-tags` and `protections-check` report.
1178const GITLAB_TAG_LIMITATION: &str =
1179    "an Owner or Maintainer can still delete a protected tag through the UI or API";
1180
1181/// The fault a merge queue on the trunk reads as: what is enabled, what it
1182/// costs, and how to undo it. This convention refuses a queue rather than
1183/// owning one, so the operator needs the consequence rather than a rule
1184/// type's bare name.
1185const MERGE_QUEUE_FAULT: &str = "a merge queue is enabled on the trunk; this convention lands no workflow that triggers on merge_group, so the queue waits on a required check that never reports and drops the request when its CI timeout expires. rk setup step protect-trunk --apply rewrites the ruleset without it";
1186
1187/// The freshness defect is independent of an absent required check.
1188const STALE_MERGE_FAULT: &str = "the trunk permits a merge from a branch that does not carry the trunk's tip; an armed release request can therefore ship a version computed against a trunk that moved. rk setup step protect-trunk --apply rewrites the ruleset with the freshness requirement";
1189
1190/// The GitLab limitation `protect-trunk` and `protections-check` report:
1191/// the title gate rides the request's own pipeline on this forge.
1192const GITLAB_TITLE_LIMITATION: &str = "the title gate stops accident, not authority: a merge request runs its own CI configuration, and a title edit starts no new pipeline";
1193
1194#[allow(
1195    clippy::too_many_lines,
1196    reason = "one arm per setup step, so the match is what makes an unobserved step a compile error"
1197)]
1198fn gitlab(ctx: &Ctx, step: &str, run: &mut Runner) -> Result<StepState, RkError> {
1199    let trunk = ctx.trunk();
1200    let project = ctx.repo.replace('/', "%2F");
1201    match step {
1202        "private-vulnerability-reporting" => {
1203            let path = format!("projects/{project}");
1204            Ok(match api_get(ctx, run, &path)? {
1205                Api::Ok(body) => {
1206                    let access = body["issues_access_level"].as_str();
1207                    if !matches!(access, Some("enabled" | "private" | "disabled")) {
1208                        StepState::unknown("issue intake access is unreadable")
1209                    } else if body
1210                        .get("issues_enabled")
1211                        .is_some_and(|flag| !flag.is_boolean())
1212                    {
1213                        StepState::unknown("legacy issue intake flag is unreadable")
1214                    } else if body["issues_enabled"] == false || access == Some("disabled") {
1215                        StepState::not("issue intake is disabled; see setup guide step 3g")
1216                    } else if access == Some("private") {
1217                        StepState::not("issue intake is restricted; see setup guide step 3g")
1218                    } else {
1219                        StepState::ok_with_limitation(
1220                            "issue intake is enabled",
1221                            GITLAB_PRIVATE_REPORTING_LIMITATION,
1222                        )
1223                    }
1224                }
1225                Api::Missing => {
1226                    StepState::unknown(format!("{path}: issue intake is unreadable (404)"))
1227                }
1228                Api::Failed(err) => StepState::unknown(format!("{path}: {err}")),
1229            })
1230        }
1231
1232        "default-branch" => Ok(match api_get(ctx, run, &format!("projects/{project}"))? {
1233            Api::Ok(body) => {
1234                let found = body["default_branch"].as_str().unwrap_or("");
1235                if found == trunk {
1236                    StepState::ok(format!("{trunk} is the default branch"))
1237                } else {
1238                    StepState::not(format!("the default branch is {found}"))
1239                }
1240            }
1241            Api::Missing => StepState::not(format!("the forge does not know {}", ctx.repo)),
1242            Api::Failed(err) => StepState::unknown(err),
1243        }),
1244        "single-trunk" => {
1245            for candidate in ctx.retired_branches() {
1246                let candidate = candidate.as_str();
1247                if candidate == trunk {
1248                    continue;
1249                }
1250                match api_get(
1251                    ctx,
1252                    run,
1253                    &format!("projects/{project}/repository/branches/{candidate}"),
1254                )? {
1255                    Api::Missing => {}
1256                    Api::Ok(_) => {
1257                        return Ok(StepState::not(format!("a {candidate} branch still exists")));
1258                    }
1259                    Api::Failed(err) => return Ok(StepState::unknown(err)),
1260                }
1261            }
1262            Ok(StepState::ok(
1263                "no long-lived branch besides the trunk remains",
1264            ))
1265        }
1266        "merge-cleanup" => Ok(match api_get(ctx, run, &format!("projects/{project}"))? {
1267            Api::Ok(body) => {
1268                if body["remove_source_branch_after_merge"]
1269                    .as_bool()
1270                    .unwrap_or(false)
1271                {
1272                    StepState::ok("a merged branch is deleted by the forge")
1273                } else {
1274                    StepState::not("a merged branch outlives its merge")
1275                }
1276            }
1277            Api::Missing => StepState::not(format!("the forge does not know {}", ctx.repo)),
1278            Api::Failed(err) => StepState::unknown(err),
1279        }),
1280        "auto-merge" => Ok(match api_get(ctx, run, &format!("projects/{project}"))? {
1281            Api::Ok(body) => {
1282                if body["only_allow_merge_if_pipeline_succeeds"]
1283                    .as_bool()
1284                    .unwrap_or(false)
1285                {
1286                    StepState::ok_with_limitation(
1287                        "a request may merge itself once its pipeline passes",
1288                        GITLAB_AUTO_MERGE_LIMITATION,
1289                    )
1290                } else {
1291                    StepState::not(
1292                        "the pipeline requirement auto-merge rides on is off; protect-trunk asserts it",
1293                    )
1294                }
1295            }
1296            Api::Missing => StepState::not(format!("the forge does not know {}", ctx.repo)),
1297            Api::Failed(err) => StepState::unknown(err),
1298        }),
1299        "ci-permissions" => Ok(match api_get(ctx, run, &format!("projects/{project}"))? {
1300            Api::Ok(body) => {
1301                if body["jobs_enabled"] == true {
1302                    StepState::ok("pipelines are enabled")
1303                } else {
1304                    StepState::not("pipelines are disabled")
1305                }
1306            }
1307            Api::Missing => StepState::not(format!("the forge does not know {}", ctx.repo)),
1308            Api::Failed(err) => StepState::unknown(err),
1309        }),
1310        "install-bot" => {
1311            // The listing paginates, exactly as the script's does: an
1312            // active token past the first page must not read as absent, or
1313            // verification would contradict the apply it verifies. Absence
1314            // is only reported once a short page proves the listing was
1315            // exhausted; a bound reached on a full page is an unknown.
1316            let mut active = false;
1317            let mut exhausted = false;
1318            for page in 1..=10u32 {
1319                let path = format!(
1320                    "projects/{project}/access_tokens?state=active&per_page=100&page={page}"
1321                );
1322                let list = match api_get(ctx, run, &path)? {
1323                    Api::Ok(body) => body.as_array().cloned().unwrap_or_default(),
1324                    Api::Missing => Vec::new(),
1325                    Api::Failed(err) => return Ok(StepState::unknown(err)),
1326                };
1327                active = active
1328                    || list.iter().any(|token| {
1329                        token["name"] == "release-bot"
1330                            && token["revoked"] == false
1331                            && token["active"] != false
1332                    });
1333                if list.len() < 100 {
1334                    exhausted = true;
1335                }
1336                if active || exhausted {
1337                    break;
1338                }
1339            }
1340            if !active {
1341                return Ok(if exhausted {
1342                    StepState::not("no active release-bot token exists")
1343                } else {
1344                    StepState::unknown(
1345                        "the token listing did not exhaust within ten pages; nothing was decided",
1346                    )
1347                });
1348            }
1349            // A token whose stored variable has gone missing is a stranded
1350            // identity — its value is unrecoverable — so the step is only
1351            // satisfied when both halves hold, and a rerun rotates.
1352            Ok(
1353                match api_get(
1354                    ctx,
1355                    run,
1356                    &format!("projects/{project}/variables/RELEASE_BOT_TOKEN"),
1357                )? {
1358                    Api::Ok(_) => StepState::ok(
1359                        "an active release-bot token exists and its variable is stored",
1360                    ),
1361                    Api::Missing => StepState::not(
1362                        "an active release-bot token exists with no stored variable; a rerun revokes and replaces it",
1363                    ),
1364                    Api::Failed(err) => StepState::unknown(err),
1365                },
1366            )
1367        }
1368        "bot-secrets" => Ok(
1369            match api_get(
1370                ctx,
1371                run,
1372                &format!("projects/{project}/variables/RELEASE_BOT_TOKEN"),
1373            )? {
1374                Api::Ok(_) => StepState::ok("RELEASE_BOT_TOKEN is stored"),
1375                Api::Missing => StepState::not("RELEASE_BOT_TOKEN is not stored"),
1376                Api::Failed(err) => StepState::unknown(err),
1377            },
1378        ),
1379        "protect-trunk" => {
1380            let protection = match api_get(
1381                ctx,
1382                run,
1383                &format!("projects/{project}/protected_branches/{trunk}"),
1384            )? {
1385                Api::Ok(body) => body,
1386                Api::Missing => {
1387                    return Ok(StepState::not(format!("{trunk} is not protected")));
1388                }
1389                Api::Failed(err) => return Ok(StepState::unknown(err)),
1390            };
1391            // Exactly one push grant, and it is the no-access entry: the
1392            // forge honors the most permissive grant, so a second entry
1393            // beside access level 0 is a branch that still takes a push.
1394            let grants = protection["push_access_levels"]
1395                .as_array()
1396                .cloned()
1397                .unwrap_or_default();
1398            let policy = ctx.protection();
1399            let no_push =
1400                grants.len() == 1 && grants[0]["access_level"] == policy.gitlab.push_access_level;
1401            // The merge grant is owned exactly too: a merge level of 0 keeps
1402            // every release request unmergeable while the push shape reads
1403            // clean, so both halves are checked.
1404            let merges = protection["merge_access_levels"]
1405                .as_array()
1406                .cloned()
1407                .unwrap_or_default();
1408            let can_merge =
1409                merges.len() == 1 && merges[0]["access_level"] == policy.gitlab.merge_access_level;
1410            let settings = match api_get(ctx, run, &format!("projects/{project}"))? {
1411                Api::Ok(body) => body,
1412                Api::Missing | Api::Failed(_) => Value::Null,
1413            };
1414            let mut faults = Vec::new();
1415            if !no_push {
1416                faults.push(format!(
1417                    "{trunk} still takes a direct push: the forge honors the most permissive of {} push grants",
1418                    grants.len()
1419                ));
1420            }
1421            if !can_merge {
1422                faults.push(format!(
1423                    "{trunk} merge grants are not exactly the one owned maintainer level"
1424                ));
1425            }
1426            if protection["allow_force_push"] != false {
1427                faults.push(format!("{trunk} allows force pushes"));
1428            }
1429            if settings["only_allow_merge_if_pipeline_succeeds"] != true {
1430                faults.push("the pipeline requirement is off".to_owned());
1431            }
1432            if settings["merge_method"] != policy.gitlab.merge_method.as_str() {
1433                faults.push("the merge method is not fast-forward".to_owned());
1434            }
1435            if settings["squash_option"] != policy.gitlab.squash_option.as_str() {
1436                faults.push("merge requests do not always squash".to_owned());
1437            }
1438            if settings["squash_commit_template"] != policy.gitlab.squash_commit_template.as_str() {
1439                faults.push("the squash template is not the merge request's title".to_owned());
1440            }
1441            Ok(if faults.is_empty() {
1442                StepState::ok_with_limitation(
1443                    format!("{trunk} holds the release-merge shape"),
1444                    GITLAB_TITLE_LIMITATION,
1445                )
1446            } else {
1447                StepState::not(faults.join("; "))
1448            })
1449        }
1450        "protect-tags" => Ok(
1451            match api_get(ctx, run, &format!("projects/{project}/protected_tags/v%2A"))? {
1452                Api::Ok(_) => {
1453                    StepState::ok_with_limitation("v* is protected", GITLAB_TAG_LIMITATION)
1454                }
1455                Api::Missing => StepState::not("v* is not protected"),
1456                Api::Failed(err) => StepState::unknown(err),
1457            },
1458        ),
1459        "protect-release-lines" => Ok(
1460            match api_get(
1461                ctx,
1462                run,
1463                &format!("projects/{project}/protected_branches/release%2F%2A"),
1464            )? {
1465                Api::Ok(body) => {
1466                    let level_ok = |levels: &Value| {
1467                        levels
1468                            .as_array()
1469                            .is_some_and(|list| list.len() == 1 && list[0]["access_level"] == 40)
1470                    };
1471                    if body["allow_force_push"] != false {
1472                        StepState::not("release/* allows force pushes")
1473                    } else if !level_ok(&body["push_access_levels"])
1474                        || !level_ok(&body["merge_access_levels"])
1475                    {
1476                        // A push level of 0 blocks the documented
1477                        // cherry-pick-by-push path while force-push reads
1478                        // clean, so the grant shape is owned exactly.
1479                        StepState::not(
1480                            "release/* grants are not exactly the owned maintainer levels",
1481                        )
1482                    } else {
1483                        StepState::ok("release/* refuses force pushes and deletion by git clients")
1484                    }
1485                }
1486                Api::Missing => StepState::inapplicable(
1487                    "release/* is unprotected; optional — applied only where older lines exist",
1488                ),
1489                Api::Failed(err) => StepState::unknown(err),
1490            },
1491        ),
1492        "protections-check" => {
1493            // Same separation as the sibling forge: proven drift wins,
1494            // an outage with nothing proven wrong stays unknown.
1495            let mut failures = Vec::new();
1496            let mut unknowns = Vec::new();
1497            // Every satisfied step's limitation survives the aggregate: a
1498            // first limitation must not shadow a second.
1499            let mut limitations: Vec<String> = Vec::new();
1500            for owned in ["protect-trunk", "protect-tags", "protect-release-lines"] {
1501                match gitlab(ctx, owned, run)? {
1502                    StepState::Satisfied {
1503                        limitation: found, ..
1504                    } => limitations.extend(found),
1505                    StepState::Inapplicable { .. } => {}
1506                    StepState::Unsatisfied { detail } => {
1507                        failures.push(format!("{owned}: {detail}"));
1508                    }
1509                    StepState::Unknown { detail } => {
1510                        unknowns.push(format!("{owned}: {detail}"));
1511                    }
1512                }
1513            }
1514            Ok(if !failures.is_empty() {
1515                StepState::not(failures.join("; "))
1516            } else if !unknowns.is_empty() {
1517                StepState::unknown(unknowns.join("; "))
1518            } else {
1519                StepState::Satisfied {
1520                    detail: "the protections hold, as far as this forge enforces them".into(),
1521                    limitation: if limitations.is_empty() {
1522                        None
1523                    } else {
1524                        Some(limitations.join("; "))
1525                    },
1526                }
1527            })
1528        }
1529        _ => Ok(StepState::unknown(format!("no observation for {step}"))),
1530    }
1531}