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            StepState::ok(format!("installation {id} covers {}", ctx.repo))
802        }
803        AppApi::Missing => StepState::not(format!("the App is not installed on {}", ctx.repo)),
804        AppApi::Refused(detail) | AppApi::Failed(detail) => StepState::unknown(detail),
805    }
806}
807
808/// A plain ruleset: active, and carrying exactly the expected rule types —
809/// not one fewer, and not one more, because an extra rule here is a rule the
810/// setup cannot reproduce or explain and can block the very push the method
811/// depends on.
812fn github_ruleset(
813    ctx: &Ctx,
814    run: &mut Runner,
815    name: &str,
816    target: &str,
817    include: &str,
818    rules: &[&str],
819) -> Result<StepState, RkError> {
820    let detail = match github_ruleset_body(ctx, run, name)? {
821        RulesetLookup::Found(detail) => detail,
822        RulesetLookup::Absent => {
823            return Ok(StepState::not(format!("no ruleset named {name}")));
824        }
825        RulesetLookup::Unreadable(err) => return Ok(StepState::unknown(err)),
826    };
827    if detail["enforcement"] != "active" {
828        return Ok(StepState::not(format!("{name} is not active")));
829    }
830    // The name proves nothing: the ruleset must cover exactly the declared
831    // refs, or the protection it reports exists somewhere else.
832    if detail["target"] != target {
833        return Ok(StepState::not(format!(
834            "{name} does not target {target} refs"
835        )));
836    }
837    if detail["conditions"]["ref_name"]["include"] != serde_json::json!([include]) {
838        return Ok(StepState::not(format!(
839            "{name} does not cover {include} alone"
840        )));
841    }
842    if detail["conditions"]["ref_name"]["exclude"] != serde_json::json!([]) {
843        return Ok(StepState::not(format!(
844            "{name} excludes refs from its own coverage"
845        )));
846    }
847    let mut held: Vec<&str> = detail["rules"]
848        .as_array()
849        .map(|list| {
850            list.iter()
851                .filter_map(|rule| rule["type"].as_str())
852                .collect()
853        })
854        .unwrap_or_default();
855    held.sort_unstable();
856    let mut expected: Vec<&str> = rules.to_vec();
857    expected.sort_unstable();
858    if held == expected {
859        Ok(StepState::ok(format!(
860            "{name} is active with exactly its rules"
861        )))
862    } else {
863        Ok(StepState::not(format!(
864            "{name} carries the rules [{}] where the setup owns [{}]",
865            held.join(", "),
866            expected.join(", ")
867        )))
868    }
869}
870
871// The trunk ruleset is checked for the shape a release merge needs.
872// The rule kinds the setup writes and can reproduce come from
873// `protection.owned_trunk_rules`, floored to contain all four. The set
874// also drives the missing-rule fault, so a kind this convention refuses
875// must stay out of it: adding one would demand that rule on every target.
876// The floor is what stops a target dropping one it needs.
877
878/// A fault line for every rule on the trunk that the setup does not own.
879///
880/// The merge queue gets its own text, because this convention refuses one
881/// deliberately and the operator needs the consequence and the remedy. Every
882/// other unowned kind reads generically: an unowned rule is one the setup
883/// cannot reproduce or explain, and it can block the very merge the method
884/// depends on.
885fn unowned_rule_faults(rules: &[Value], owned: &[String]) -> Vec<String> {
886    rules
887        .iter()
888        .filter_map(|rule| rule["type"].as_str())
889        .filter(|kind| !owned.iter().any(|name| name == kind))
890        .map(|kind| {
891            if kind == "merge_queue" {
892                MERGE_QUEUE_FAULT.to_owned()
893            } else {
894                format!("an unowned rule is present: {kind}")
895            }
896        })
897        .collect()
898}
899
900fn github_trunk_ruleset(ctx: &Ctx, run: &mut Runner) -> Result<StepState, RkError> {
901    let trunk = ctx.trunk();
902    let name = ctx.trunk_ruleset().to_owned();
903    let detail = match github_ruleset_body(ctx, run, &name)? {
904        RulesetLookup::Found(detail) => detail,
905        RulesetLookup::Absent => {
906            return Ok(StepState::not(format!("no ruleset named {name}")));
907        }
908        RulesetLookup::Unreadable(err) => return Ok(StepState::unknown(err)),
909    };
910    let rules = detail["rules"].as_array().cloned().unwrap_or_default();
911    let has = |kind: &str| rules.iter().any(|rule| rule["type"] == kind);
912    let mut faults = Vec::new();
913    if detail["enforcement"] != "active" {
914        faults.push(format!("{name} is not active"));
915    }
916    // The name proves nothing: a ruleset applies only where its conditions
917    // say, so a right-named ruleset covering another ref would otherwise
918    // read as a protected trunk.
919    if detail["target"] != "branch" {
920        faults.push(format!("{name} does not target branches"));
921    }
922    let expected_ref = serde_json::json!([format!("refs/heads/{trunk}")]);
923    if detail["conditions"]["ref_name"]["include"] != expected_ref {
924        faults.push(format!("{name} does not cover refs/heads/{trunk} alone"));
925    }
926    // A matching exclusion negates the include, so the owned shape is an
927    // exclusion list that is exactly empty.
928    if detail["conditions"]["ref_name"]["exclude"] != serde_json::json!([]) {
929        faults.push(format!("{name} excludes refs from its own coverage"));
930    }
931    if !detail["bypass_actors"].as_array().is_none_or(Vec::is_empty) {
932        faults.push("a bypass actor is named".to_owned());
933    }
934    for required in &ctx.protection().owned_trunk_rules {
935        if !has(required) {
936            faults.push(format!("the {required} rule is missing"));
937        }
938    }
939    faults.extend(unowned_rule_faults(
940        &rules,
941        &ctx.protection().owned_trunk_rules,
942    ));
943    if let Some(request) = rules.iter().find(|rule| rule["type"] == "pull_request")
944        && request["parameters"]["allowed_merge_methods"]
945            != serde_json::json!(ctx.protection().allowed_merge_methods)
946    {
947        faults.push("the merge method is not exactly a squash merge".to_owned());
948    }
949    if let Some(checks) = rules
950        .iter()
951        .find(|rule| rule["type"] == "required_status_checks")
952    {
953        if checks["parameters"]["strict_required_status_checks_policy"]
954            != ctx.protection().strict_required_status_checks
955        {
956            faults.push(STALE_MERGE_FAULT.to_owned());
957        }
958        let contexts: Vec<&str> = checks["parameters"]["required_status_checks"]
959            .as_array()
960            .map(|list| {
961                list.iter()
962                    .filter_map(|check| check["context"].as_str())
963                    .collect()
964            })
965            .unwrap_or_default();
966        // Where the expected check is known, the context set must be exactly
967        // it plus the title check: an extra stale context does not fail a
968        // merge, it hangs one, and a missing title check lets an
969        // unconventional squash title land on the trunk.
970        if contexts.is_empty() {
971            faults.push("no status check is required".to_owned());
972        } else if let Some(expected) = &ctx.required_check {
973            let mut held = contexts.clone();
974            held.sort_unstable();
975            let title_check = ctx.title_check();
976            let mut owned_contexts = [expected.as_str(), title_check];
977            owned_contexts.sort_unstable();
978            if held != owned_contexts {
979                faults.push(format!(
980                    "the required checks are [{}] where the setup owns [{}]",
981                    contexts.join(", "),
982                    owned_contexts.join(", ")
983                ));
984            }
985        } else if !contexts.contains(&ctx.title_check()) {
986            faults.push(format!("the {} check is not required", ctx.title_check()));
987        }
988    }
989    match squash_merge_sources(ctx, run)? {
990        MergeSources::Owned => {}
991        MergeSources::Faults(proven) => faults.extend(proven),
992        // Proven drift wins over an outage: an unreadable settings read
993        // downgrades the answer to unknown only when nothing above it was
994        // proven wrong.
995        MergeSources::Unreadable(err) => {
996            if faults.is_empty() {
997                return Ok(StepState::unknown(err));
998            }
999        }
1000    }
1001    if let Some(shape) = gate_faults(ctx) {
1002        faults.push(shape);
1003    }
1004    if !faults.is_empty() {
1005        return Ok(StepState::not(faults.join("; ")));
1006    }
1007    Ok(StepState::ok(format!(
1008        "{name} holds the release-merge shape"
1009    )))
1010}
1011
1012/// The ways the named gate is shaped so that it cannot report a blocking
1013/// answer. A required check that never reports is a broken trunk
1014/// protection, not a weaker guarantee, so each of these is a fault rather
1015/// than a limitation. Read only where the check is named: without the flag
1016/// the observation knows no gate.
1017///
1018/// It judges the gate alone. Which other jobs a project means to block a
1019/// merge is intent, no file states it, and `forges/github.md` carries that
1020/// as a convention instead.
1021fn gate_faults(ctx: &Ctx) -> Option<String> {
1022    let check = ctx.required_check.as_deref()?;
1023    workflow_jobs::faults(
1024        &workflow_jobs::read_gate(&ctx.target, check, ctx.trunk()),
1025        check,
1026        ctx.trunk(),
1027    )
1028}
1029
1030/// What the repository's squash message settings hold.
1031enum MergeSources {
1032    /// The request's title and body, as the setup owns.
1033    Owned,
1034    /// Proven other values, one fault line each.
1035    Faults(Vec<String>),
1036    /// The settings could not be read.
1037    Unreadable(String),
1038}
1039
1040/// The squash message sources, repository settings beside the ruleset:
1041/// with the title source unset, a one-commit request offers that commit's
1042/// own subject as the trunk's message, which the bot then reads for the
1043/// version; with the message source on another value, the trunk's body is
1044/// not the request's description the content gates judged. One GET
1045/// answers for both, each faulted by name.
1046fn squash_merge_sources(ctx: &Ctx, run: &mut Runner) -> Result<MergeSources, RkError> {
1047    Ok(match api_get(ctx, run, &format!("repos/{}", ctx.repo))? {
1048        Api::Ok(body) => {
1049            let mut faults = Vec::new();
1050            let owned_title = ctx.protection().github.squash_title_source.as_str();
1051            let owned_body = ctx.protection().github.squash_body_source.as_str();
1052            if body["squash_merge_commit_title"] != owned_title {
1053                faults.push(format!(
1054                    "the squash title source is {} where the setup owns {owned_title}",
1055                    body["squash_merge_commit_title"]
1056                ));
1057            }
1058            if body["squash_merge_commit_message"] != owned_body {
1059                faults.push(format!(
1060                    "the squash message source is {} where the setup owns {owned_body}",
1061                    body["squash_merge_commit_message"]
1062                ));
1063            }
1064            if faults.is_empty() {
1065                MergeSources::Owned
1066            } else {
1067                MergeSources::Faults(faults)
1068            }
1069        }
1070        Api::Missing => MergeSources::Faults(vec![format!("the forge does not know {}", ctx.repo)]),
1071        Api::Failed(err) => MergeSources::Unreadable(err),
1072    })
1073}
1074
1075/// One ruleset lookup by name: found, provably absent, or unreadable —
1076/// an unreadable inventory must never read as an absent ruleset.
1077enum RulesetLookup {
1078    /// The ruleset exists; its detail body.
1079    Found(Value),
1080    /// The inventory was read successfully and no ruleset carries the
1081    /// name.
1082    Absent,
1083    /// The inventory or the detail could not be read.
1084    Unreadable(String),
1085}
1086
1087/// A ruleset's detail body by name.
1088fn github_ruleset_body(ctx: &Ctx, run: &mut Runner, name: &str) -> Result<RulesetLookup, RkError> {
1089    // A 404 on the collection is an unreachable inventory — a missing
1090    // repository or an unauthorized read — never an empty one: an empty
1091    // inventory answers 200 with an empty list.
1092    let list = match api_get(ctx, run, &format!("repos/{}/rulesets", ctx.repo))? {
1093        Api::Ok(body) => body,
1094        Api::Missing => {
1095            return Ok(RulesetLookup::Unreadable(
1096                "the ruleset inventory is not readable".into(),
1097            ));
1098        }
1099        Api::Failed(err) => return Ok(RulesetLookup::Unreadable(err)),
1100    };
1101    let id = list
1102        .as_array()
1103        .into_iter()
1104        .flatten()
1105        .find(|ruleset| ruleset["name"] == name)
1106        .and_then(|ruleset| ruleset["id"].as_i64());
1107    let Some(id) = id else {
1108        return Ok(RulesetLookup::Absent);
1109    };
1110    match api_get(ctx, run, &format!("repos/{}/rulesets/{id}", ctx.repo))? {
1111        Api::Ok(body) => Ok(RulesetLookup::Found(body)),
1112        // A listed id that answers 404 is not proof of absence either — the
1113        // forge also answers 404 for an unauthorized read — so a rerun
1114        // decides, rather than a false drift.
1115        Api::Missing => Ok(RulesetLookup::Unreadable(format!(
1116            "the {name} detail is not readable"
1117        ))),
1118        Api::Failed(err) => Ok(RulesetLookup::Unreadable(err)),
1119    }
1120}
1121
1122/// The GitLab limitation the `auto-merge` step reports: the forge has no
1123/// project-level switch, so the observation reads the pipeline requirement
1124/// the trunk protection asserts.
1125const 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";
1126
1127/// The GitLab limitation `protect-tags` and `protections-check` report.
1128const GITLAB_TAG_LIMITATION: &str =
1129    "an Owner or Maintainer can still delete a protected tag through the UI or API";
1130
1131/// The fault a merge queue on the trunk reads as: what is enabled, what it
1132/// costs, and how to undo it. This convention refuses a queue rather than
1133/// owning one, so the operator needs the consequence rather than a rule
1134/// type's bare name.
1135const 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";
1136
1137/// The freshness defect is independent of an absent required check.
1138const 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";
1139
1140/// The GitLab limitation `protect-trunk` and `protections-check` report:
1141/// the title gate rides the request's own pipeline on this forge.
1142const 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";
1143
1144#[allow(
1145    clippy::too_many_lines,
1146    reason = "one arm per setup step, so the match is what makes an unobserved step a compile error"
1147)]
1148fn gitlab(ctx: &Ctx, step: &str, run: &mut Runner) -> Result<StepState, RkError> {
1149    let trunk = ctx.trunk();
1150    let project = ctx.repo.replace('/', "%2F");
1151    match step {
1152        "private-vulnerability-reporting" => {
1153            let path = format!("projects/{project}");
1154            Ok(match api_get(ctx, run, &path)? {
1155                Api::Ok(body) => {
1156                    let access = body["issues_access_level"].as_str();
1157                    if !matches!(access, Some("enabled" | "private" | "disabled")) {
1158                        StepState::unknown("issue intake access is unreadable")
1159                    } else if body
1160                        .get("issues_enabled")
1161                        .is_some_and(|flag| !flag.is_boolean())
1162                    {
1163                        StepState::unknown("legacy issue intake flag is unreadable")
1164                    } else if body["issues_enabled"] == false || access == Some("disabled") {
1165                        StepState::not("issue intake is disabled; see setup guide step 3g")
1166                    } else if access == Some("private") {
1167                        StepState::not("issue intake is restricted; see setup guide step 3g")
1168                    } else {
1169                        StepState::ok_with_limitation(
1170                            "issue intake is enabled",
1171                            GITLAB_PRIVATE_REPORTING_LIMITATION,
1172                        )
1173                    }
1174                }
1175                Api::Missing => {
1176                    StepState::unknown(format!("{path}: issue intake is unreadable (404)"))
1177                }
1178                Api::Failed(err) => StepState::unknown(format!("{path}: {err}")),
1179            })
1180        }
1181
1182        "default-branch" => Ok(match api_get(ctx, run, &format!("projects/{project}"))? {
1183            Api::Ok(body) => {
1184                let found = body["default_branch"].as_str().unwrap_or("");
1185                if found == trunk {
1186                    StepState::ok(format!("{trunk} is the default branch"))
1187                } else {
1188                    StepState::not(format!("the default branch is {found}"))
1189                }
1190            }
1191            Api::Missing => StepState::not(format!("the forge does not know {}", ctx.repo)),
1192            Api::Failed(err) => StepState::unknown(err),
1193        }),
1194        "single-trunk" => {
1195            for candidate in ctx.retired_branches() {
1196                let candidate = candidate.as_str();
1197                if candidate == trunk {
1198                    continue;
1199                }
1200                match api_get(
1201                    ctx,
1202                    run,
1203                    &format!("projects/{project}/repository/branches/{candidate}"),
1204                )? {
1205                    Api::Missing => {}
1206                    Api::Ok(_) => {
1207                        return Ok(StepState::not(format!("a {candidate} branch still exists")));
1208                    }
1209                    Api::Failed(err) => return Ok(StepState::unknown(err)),
1210                }
1211            }
1212            Ok(StepState::ok(
1213                "no long-lived branch besides the trunk remains",
1214            ))
1215        }
1216        "merge-cleanup" => Ok(match api_get(ctx, run, &format!("projects/{project}"))? {
1217            Api::Ok(body) => {
1218                if body["remove_source_branch_after_merge"]
1219                    .as_bool()
1220                    .unwrap_or(false)
1221                {
1222                    StepState::ok("a merged branch is deleted by the forge")
1223                } else {
1224                    StepState::not("a merged branch outlives its merge")
1225                }
1226            }
1227            Api::Missing => StepState::not(format!("the forge does not know {}", ctx.repo)),
1228            Api::Failed(err) => StepState::unknown(err),
1229        }),
1230        "auto-merge" => Ok(match api_get(ctx, run, &format!("projects/{project}"))? {
1231            Api::Ok(body) => {
1232                if body["only_allow_merge_if_pipeline_succeeds"]
1233                    .as_bool()
1234                    .unwrap_or(false)
1235                {
1236                    StepState::ok_with_limitation(
1237                        "a request may merge itself once its pipeline passes",
1238                        GITLAB_AUTO_MERGE_LIMITATION,
1239                    )
1240                } else {
1241                    StepState::not(
1242                        "the pipeline requirement auto-merge rides on is off; protect-trunk asserts it",
1243                    )
1244                }
1245            }
1246            Api::Missing => StepState::not(format!("the forge does not know {}", ctx.repo)),
1247            Api::Failed(err) => StepState::unknown(err),
1248        }),
1249        "ci-permissions" => Ok(match api_get(ctx, run, &format!("projects/{project}"))? {
1250            Api::Ok(body) => {
1251                if body["jobs_enabled"] == true {
1252                    StepState::ok("pipelines are enabled")
1253                } else {
1254                    StepState::not("pipelines are disabled")
1255                }
1256            }
1257            Api::Missing => StepState::not(format!("the forge does not know {}", ctx.repo)),
1258            Api::Failed(err) => StepState::unknown(err),
1259        }),
1260        "install-bot" => {
1261            // The listing paginates, exactly as the script's does: an
1262            // active token past the first page must not read as absent, or
1263            // verification would contradict the apply it verifies. Absence
1264            // is only reported once a short page proves the listing was
1265            // exhausted; a bound reached on a full page is an unknown.
1266            let mut active = false;
1267            let mut exhausted = false;
1268            for page in 1..=10u32 {
1269                let path = format!(
1270                    "projects/{project}/access_tokens?state=active&per_page=100&page={page}"
1271                );
1272                let list = match api_get(ctx, run, &path)? {
1273                    Api::Ok(body) => body.as_array().cloned().unwrap_or_default(),
1274                    Api::Missing => Vec::new(),
1275                    Api::Failed(err) => return Ok(StepState::unknown(err)),
1276                };
1277                active = active
1278                    || list.iter().any(|token| {
1279                        token["name"] == "release-bot"
1280                            && token["revoked"] == false
1281                            && token["active"] != false
1282                    });
1283                if list.len() < 100 {
1284                    exhausted = true;
1285                }
1286                if active || exhausted {
1287                    break;
1288                }
1289            }
1290            if !active {
1291                return Ok(if exhausted {
1292                    StepState::not("no active release-bot token exists")
1293                } else {
1294                    StepState::unknown(
1295                        "the token listing did not exhaust within ten pages; nothing was decided",
1296                    )
1297                });
1298            }
1299            // A token whose stored variable has gone missing is a stranded
1300            // identity — its value is unrecoverable — so the step is only
1301            // satisfied when both halves hold, and a rerun rotates.
1302            Ok(
1303                match api_get(
1304                    ctx,
1305                    run,
1306                    &format!("projects/{project}/variables/RELEASE_BOT_TOKEN"),
1307                )? {
1308                    Api::Ok(_) => StepState::ok(
1309                        "an active release-bot token exists and its variable is stored",
1310                    ),
1311                    Api::Missing => StepState::not(
1312                        "an active release-bot token exists with no stored variable; a rerun revokes and replaces it",
1313                    ),
1314                    Api::Failed(err) => StepState::unknown(err),
1315                },
1316            )
1317        }
1318        "bot-secrets" => Ok(
1319            match api_get(
1320                ctx,
1321                run,
1322                &format!("projects/{project}/variables/RELEASE_BOT_TOKEN"),
1323            )? {
1324                Api::Ok(_) => StepState::ok("RELEASE_BOT_TOKEN is stored"),
1325                Api::Missing => StepState::not("RELEASE_BOT_TOKEN is not stored"),
1326                Api::Failed(err) => StepState::unknown(err),
1327            },
1328        ),
1329        "protect-trunk" => {
1330            let protection = match api_get(
1331                ctx,
1332                run,
1333                &format!("projects/{project}/protected_branches/{trunk}"),
1334            )? {
1335                Api::Ok(body) => body,
1336                Api::Missing => {
1337                    return Ok(StepState::not(format!("{trunk} is not protected")));
1338                }
1339                Api::Failed(err) => return Ok(StepState::unknown(err)),
1340            };
1341            // Exactly one push grant, and it is the no-access entry: the
1342            // forge honors the most permissive grant, so a second entry
1343            // beside access level 0 is a branch that still takes a push.
1344            let grants = protection["push_access_levels"]
1345                .as_array()
1346                .cloned()
1347                .unwrap_or_default();
1348            let policy = ctx.protection();
1349            let no_push =
1350                grants.len() == 1 && grants[0]["access_level"] == policy.gitlab.push_access_level;
1351            // The merge grant is owned exactly too: a merge level of 0 keeps
1352            // every release request unmergeable while the push shape reads
1353            // clean, so both halves are checked.
1354            let merges = protection["merge_access_levels"]
1355                .as_array()
1356                .cloned()
1357                .unwrap_or_default();
1358            let can_merge =
1359                merges.len() == 1 && merges[0]["access_level"] == policy.gitlab.merge_access_level;
1360            let settings = match api_get(ctx, run, &format!("projects/{project}"))? {
1361                Api::Ok(body) => body,
1362                Api::Missing | Api::Failed(_) => Value::Null,
1363            };
1364            let mut faults = Vec::new();
1365            if !no_push {
1366                faults.push(format!(
1367                    "{trunk} still takes a direct push: the forge honors the most permissive of {} push grants",
1368                    grants.len()
1369                ));
1370            }
1371            if !can_merge {
1372                faults.push(format!(
1373                    "{trunk} merge grants are not exactly the one owned maintainer level"
1374                ));
1375            }
1376            if protection["allow_force_push"] != false {
1377                faults.push(format!("{trunk} allows force pushes"));
1378            }
1379            if settings["only_allow_merge_if_pipeline_succeeds"] != true {
1380                faults.push("the pipeline requirement is off".to_owned());
1381            }
1382            if settings["merge_method"] != policy.gitlab.merge_method.as_str() {
1383                faults.push("the merge method is not fast-forward".to_owned());
1384            }
1385            if settings["squash_option"] != policy.gitlab.squash_option.as_str() {
1386                faults.push("merge requests do not always squash".to_owned());
1387            }
1388            if settings["squash_commit_template"] != policy.gitlab.squash_commit_template.as_str() {
1389                faults.push("the squash template is not the merge request's title".to_owned());
1390            }
1391            Ok(if faults.is_empty() {
1392                StepState::ok_with_limitation(
1393                    format!("{trunk} holds the release-merge shape"),
1394                    GITLAB_TITLE_LIMITATION,
1395                )
1396            } else {
1397                StepState::not(faults.join("; "))
1398            })
1399        }
1400        "protect-tags" => Ok(
1401            match api_get(ctx, run, &format!("projects/{project}/protected_tags/v%2A"))? {
1402                Api::Ok(_) => {
1403                    StepState::ok_with_limitation("v* is protected", GITLAB_TAG_LIMITATION)
1404                }
1405                Api::Missing => StepState::not("v* is not protected"),
1406                Api::Failed(err) => StepState::unknown(err),
1407            },
1408        ),
1409        "protect-release-lines" => Ok(
1410            match api_get(
1411                ctx,
1412                run,
1413                &format!("projects/{project}/protected_branches/release%2F%2A"),
1414            )? {
1415                Api::Ok(body) => {
1416                    let level_ok = |levels: &Value| {
1417                        levels
1418                            .as_array()
1419                            .is_some_and(|list| list.len() == 1 && list[0]["access_level"] == 40)
1420                    };
1421                    if body["allow_force_push"] != false {
1422                        StepState::not("release/* allows force pushes")
1423                    } else if !level_ok(&body["push_access_levels"])
1424                        || !level_ok(&body["merge_access_levels"])
1425                    {
1426                        // A push level of 0 blocks the documented
1427                        // cherry-pick-by-push path while force-push reads
1428                        // clean, so the grant shape is owned exactly.
1429                        StepState::not(
1430                            "release/* grants are not exactly the owned maintainer levels",
1431                        )
1432                    } else {
1433                        StepState::ok("release/* refuses force pushes and deletion by git clients")
1434                    }
1435                }
1436                Api::Missing => StepState::inapplicable(
1437                    "release/* is unprotected; optional — applied only where older lines exist",
1438                ),
1439                Api::Failed(err) => StepState::unknown(err),
1440            },
1441        ),
1442        "protections-check" => {
1443            // Same separation as the sibling forge: proven drift wins,
1444            // an outage with nothing proven wrong stays unknown.
1445            let mut failures = Vec::new();
1446            let mut unknowns = Vec::new();
1447            // Every satisfied step's limitation survives the aggregate: a
1448            // first limitation must not shadow a second.
1449            let mut limitations: Vec<String> = Vec::new();
1450            for owned in ["protect-trunk", "protect-tags", "protect-release-lines"] {
1451                match gitlab(ctx, owned, run)? {
1452                    StepState::Satisfied {
1453                        limitation: found, ..
1454                    } => limitations.extend(found),
1455                    StepState::Inapplicable { .. } => {}
1456                    StepState::Unsatisfied { detail } => {
1457                        failures.push(format!("{owned}: {detail}"));
1458                    }
1459                    StepState::Unknown { detail } => {
1460                        unknowns.push(format!("{owned}: {detail}"));
1461                    }
1462                }
1463            }
1464            Ok(if !failures.is_empty() {
1465                StepState::not(failures.join("; "))
1466            } else if !unknowns.is_empty() {
1467                StepState::unknown(unknowns.join("; "))
1468            } else {
1469                StepState::Satisfied {
1470                    detail: "the protections hold, as far as this forge enforces them".into(),
1471                    limitation: if limitations.is_empty() {
1472                        None
1473                    } else {
1474                        Some(limitations.join("; "))
1475                    },
1476                }
1477            })
1478        }
1479        _ => Ok(StepState::unknown(format!("no observation for {step}"))),
1480    }
1481}