Skip to main content

release_kit/commands/
setup.rs

1//! `rk setup`: execute the repository-side setup against the detected forge.
2//!
3//! Preview is the default and is an offline rendering — it materializes
4//! nothing and invokes no external command. Apply runs each step as the
5//! observe-compare-apply-verify lifecycle: observe the current state,
6//! report and skip when satisfied, otherwise materialize the embedded
7//! script into the run's private journal directory, verify its digest,
8//! spawn it as `sh <path>`, and read the state back. `check` calls the same
9//! observe functions with the mutating half unreachable from its code path.
10
11use std::ffi::OsString;
12use std::fs;
13use std::path::PathBuf;
14use std::time::Instant;
15
16use zeroize::Zeroizing;
17
18use crate::cli::setup::{SetupAction, SetupArgs};
19use crate::detect::Forge;
20use crate::diagnostic::{Diagnostic, Reason};
21use crate::digest::Digest;
22use crate::embedded;
23use crate::error::RkError;
24use crate::events::{ChildStream, Event, EventKind};
25use crate::output::Output;
26use crate::setup::app_jwt::{self, AppApi};
27use crate::setup::context::{Ctx, SECRET_VARS};
28use crate::setup::journal::Journal;
29use crate::setup::observe::{self, StepState};
30use crate::setup::process::{self, Exec, Outcome};
31use crate::setup::secrets;
32use crate::setup::steps::{Mutates, STEPS, StepSpec, spec};
33
34/// Dispatch the setup surface.
35///
36/// # Errors
37///
38/// Every failure classified through the matrix, each carrying its `reason`.
39pub fn run(args: &SetupArgs) -> Result<(), RkError> {
40    match &args.action {
41        Some(SetupAction::Script { name, forge }) => script(name, forge.as_deref()),
42        Some(SetupAction::Check {
43            target,
44            repo,
45            forge,
46            required_check,
47            json,
48        }) => {
49            let ctx = Ctx::resolve(
50                target,
51                repo.as_deref(),
52                forge.as_deref(),
53                required_check.as_deref(),
54            )?;
55            reject_check_flag_on_gitlab(&ctx)?;
56            check(Output::new(*json), ctx)
57        }
58        Some(SetupAction::Step {
59            name,
60            target,
61            repo,
62            forge,
63            required_check,
64            apply,
65            json,
66        }) => {
67            let selected = spec(name).ok_or_else(|| {
68                RkError::Usage(format!("unknown step '{name}'; rk setup --list names them"))
69            })?;
70            let ctx = Ctx::resolve(
71                target,
72                repo.as_deref(),
73                forge.as_deref(),
74                required_check.as_deref(),
75            )?;
76            reject_check_flag_on_gitlab(&ctx)?;
77            if *apply {
78                require_check_for(&ctx, &[selected])?;
79                execute(Output::new(*json), ctx, &[selected], "setup step")
80            } else {
81                preview(Output::new(*json), &ctx, &[selected])
82            }
83        }
84        None if args.list => list(args.forge.as_deref()),
85        None => {
86            let target = args.target.clone().ok_or_else(|| {
87                RkError::Usage("name a --target, or pass --list to see the steps".into())
88            })?;
89            let ctx = Ctx::resolve(
90                &target,
91                args.repo.as_deref(),
92                args.forge.as_deref(),
93                args.required_check.as_deref(),
94            )?;
95            reject_check_flag_on_gitlab(&ctx)?;
96            let all: Vec<&StepSpec> = STEPS.iter().collect();
97            if args.apply {
98                require_check_for(&ctx, &all)?;
99                execute(Output::new(args.json), ctx, &all, "setup")
100            } else {
101                preview(Output::new(args.json), &ctx, &all)
102            }
103        }
104    }
105}
106
107/// On GitLab `--required-check` is a usage error, per the forge document:
108/// the forge requires the whole pipeline and names no individual check, and
109/// a flag silently discarded would read as configured while nothing uses it.
110fn reject_check_flag_on_gitlab(ctx: &Ctx) -> Result<(), RkError> {
111    if ctx.forge == Forge::Gitlab && ctx.required_check.is_some() {
112        return Err(RkError::Usage(
113            "--required-check is refused on gitlab: the forge requires the whole pipeline and names no individual check".into(),
114        ));
115    }
116    Ok(())
117}
118
119/// On GitHub the trunk protection needs the check name before any step
120/// runs: a wrong or missing one does not fail, it hangs the merge button,
121/// so a full apply refuses up front rather than writing eight steps and
122/// stopping.
123fn require_check_for(ctx: &Ctx, steps: &[&StepSpec]) -> Result<(), RkError> {
124    let needs = ctx.forge == Forge::Github
125        && ctx.required_check.is_none()
126        && steps.iter().any(|step| step.name == "protect-trunk");
127    if needs {
128        return Err(RkError::refusal(
129            Diagnostic::new(
130                Reason::PrerequisiteUnmet,
131                "protect-trunk refuses without --required-check, and nothing was written",
132            )
133            .expected("the name of the CI check the release merge must pass")
134            .action(format!(
135                "pass --required-check <name>; gh api repos/{}/commits/HEAD/check-runs lists the project's check names",
136                ctx.repo
137            ))
138            .step("protect-trunk"),
139        ));
140    }
141    Ok(())
142}
143
144/// `rk setup --list`: the ordered steps, what each proves, and which needs
145/// input on which forge — visible before a first apply rather than
146/// discovered by one.
147fn list(forge: Option<&str>) -> Result<(), RkError> {
148    let forge = forge
149        .map(|name| {
150            Forge::parse(name).ok_or_else(|| {
151                RkError::Usage(format!(
152                    "unknown forge '{name}'; the forges are: github, gitlab"
153                ))
154            })
155        })
156        .transpose()?;
157    let out = Output::human();
158    for (idx, step) in STEPS.iter().enumerate() {
159        let mut line = format!(
160            "{:2}. {} [{}] proves: {}",
161            idx + 1,
162            step.name,
163            step.chapter,
164            step.proves
165        );
166        if step.name == "protect-trunk" && forge != Some(Forge::Gitlab) {
167            line.push_str(" (needs --required-check on github)");
168        }
169        if step.destructive {
170            line.push_str(" (destructive)");
171        }
172        if step.optional {
173            line.push_str(" (optional; a full apply skips it)");
174        }
175        out.result_line(line);
176    }
177    out.next(&[
178        "rk setup --target . previews every step".to_owned(),
179        "rk setup script <name> prints one embedded script".to_owned(),
180    ]);
181    Ok(())
182}
183
184/// `rk setup script <name>`: the audit escape hatch, printed byte-identical
185/// to the embedded file.
186fn script(name: &str, forge: Option<&str>) -> Result<(), RkError> {
187    if name == "package-check" {
188        return Err(RkError::Usage(
189            "package-check reads its command from the technology binding and has no script".into(),
190        ));
191    }
192    if name == "branch-reminder" {
193        return Err(RkError::Usage(
194            "branch-reminder writes an embedded hook body and has no script; rk setup step branch-reminder previews the write".into(),
195        ));
196    }
197    if name == "forge-version" {
198        return Err(RkError::Usage(
199            "forge-version reads the forge's own version and has no script; rk setup step forge-version previews the read".into(),
200        ));
201    }
202    let forge = match forge {
203        Some(value) => Forge::parse(value).ok_or_else(|| {
204            RkError::Usage(format!(
205                "unknown forge '{value}'; the forges are: github, gitlab"
206            ))
207        })?,
208        None => Forge::Github,
209    };
210    let path = format!("{}/{name}", forge.as_str());
211    let file = embedded::SETUP.get_file(&path).ok_or(RkError::NotFound {
212        kind: "setup step",
213        name: name.to_owned(),
214    })?;
215    Output::human().result_raw(&String::from_utf8_lossy(file.contents()));
216    Ok(())
217}
218
219/// The shared run state: the boundary, the resolved context, the journal,
220/// and the event stream.
221struct Engine {
222    out: Output,
223    ctx: Ctx,
224    journal: Option<Journal>,
225    secrets: Vec<Zeroizing<Vec<u8>>>,
226    /// The run's one read of the named key file; see [`key_file_for`].
227    key: Option<secrets::KeyFile>,
228    /// The run's App JWT, minted at most once; see [`app_jwt_for`].
229    app_jwt: Option<String>,
230    seq: u64,
231    command: &'static str,
232    run_id: String,
233}
234
235impl Engine {
236    /// Open the run: journal first, before any remote mutation. An apply
237    /// that cannot create its journal refuses; observability-only modes
238    /// warn and continue, because refusing them over observability is
239    /// self-defeating.
240    fn open(
241        out: Output,
242        ctx: Ctx,
243        command: &'static str,
244        journal_required: bool,
245    ) -> Result<Self, RkError> {
246        // A stale key export is refused wherever a run opens, so every
247        // mode catches it and not the one step that would have used it.
248        secrets::refuse_legacy_key()?;
249        let journal =
250            match Journal::create(command, ctx.target.as_str(), ctx.forge.as_str(), &ctx.repo) {
251                Ok(journal) => Some(journal),
252                Err(source) if journal_required => {
253                    return Err(RkError::refusal(
254                        Diagnostic::new(
255                            Reason::JournalUnavailable,
256                            format!("the run journal cannot be created: {source}"),
257                        )
258                        .expected("a writable state root for the journal")
259                        .target_state("nothing was run and nothing changed"),
260                    ));
261                }
262                Err(source) => {
263                    out.warn(format!("no run journal for this run: {source}"));
264                    None
265                }
266            };
267        let run_id = journal
268            .as_ref()
269            .map_or_else(|| "unjournaled".to_owned(), |j| j.run_id().to_owned());
270        let mut engine = Self {
271            out,
272            ctx,
273            journal,
274            secrets: Ctx::secret_values(),
275            key: None,
276            app_jwt: None,
277            seq: 0,
278            command,
279            run_id,
280        };
281        let opening = Event::opening(
282            engine.next_seq(),
283            crate::applog::now_utc(),
284            engine.run_id.clone(),
285            engine.command,
286        );
287        engine.emit(&opening);
288        if engine.ctx.self_hosted_gitlab() {
289            engine.out.warn(
290                "this remote is a self-hosted GitLab: registry trusted publishing covers GitLab.com only, so the OIDC invariant cannot be satisfied here",
291            );
292        }
293        Ok(engine)
294    }
295
296    const fn next_seq(&mut self) -> u64 {
297        let seq = self.seq;
298        self.seq += 1;
299        seq
300    }
301
302    fn event(&mut self, kind: EventKind, step: Option<&str>) -> Event {
303        let mut event = Event::opening(
304            self.next_seq(),
305            crate::applog::now_utc(),
306            self.run_id.clone(),
307            self.command,
308        );
309        event.kind = kind;
310        event.step = step.map(str::to_owned);
311        event
312    }
313
314    fn emit(&mut self, event: &Event) {
315        self.out.event(event);
316        if let Some(journal) = &mut self.journal {
317            if let Ok(line) = serde_json::to_string(event) {
318                journal.event_line(&line);
319            }
320        }
321    }
322
323    /// Run one external command: echo it, stream and redact its output,
324    /// journal everything, surface its exit.
325    fn exec(&mut self, exec: &Exec, passthrough: bool) -> Result<Outcome, RkError> {
326        let echo = exec.echo();
327        self.out.frame(&echo);
328        if let Some(journal) = &mut self.journal {
329            journal.transcript(echo.as_bytes());
330            journal.transcript(b"\n");
331        }
332        let secrets = std::mem::take(&mut self.secrets);
333        let step_name: Option<String> = None;
334        let mut chunks: Vec<(ChildStream, Vec<u8>)> = Vec::new();
335        let spawned = process::run(exec, |stream, chunk| {
336            chunks.push((stream, process::redact(chunk, &secrets)));
337        });
338        self.secrets = secrets;
339        for (stream, chunk) in chunks {
340            if passthrough {
341                self.out.child_passthrough(stream, &chunk);
342            }
343            let event = self.event(EventKind::ChildOutput, step_name.as_deref());
344            let event = event.child_output(stream, &chunk);
345            self.emit(&event);
346            if let Some(journal) = &mut self.journal {
347                journal.transcript(&chunk);
348            }
349        }
350        spawned.map_err(|source| {
351            RkError::refusal(
352                Diagnostic::new(
353                    Reason::SubprocessSpawn,
354                    format!("{} did not spawn: {source}", exec.program.to_string_lossy()),
355                )
356                .expected("a POSIX sh and the forge CLI on PATH")
357                .run(self.run_path()),
358            )
359        })
360    }
361
362    fn run_path(&self) -> String {
363        self.journal.as_ref().map_or_else(
364            || "no journal was written".to_owned(),
365            |j| j.dir.display().to_string(),
366        )
367    }
368
369    fn finish(&mut self, exit_code: i32, reason: Option<&str>) {
370        let mut event = self.event(EventKind::RunFinished, None);
371        event.exit_code = Some(exit_code);
372        event.status = Some(if exit_code == 0 {
373            "ok".into()
374        } else {
375            "failed".into()
376        });
377        self.emit(&event);
378        if let Some(journal) = &mut self.journal {
379            journal.finish(exit_code, reason);
380        }
381    }
382}
383
384/// Attach the failure to its run journal and close the run.
385fn fail(engine: &mut Engine, error: RkError) -> RkError {
386    let error = match error {
387        RkError::Refusal(mut diagnostic) => {
388            diagnostic.run.get_or_insert_with(|| engine.run_path());
389            RkError::Refusal(diagnostic)
390        }
391        RkError::Subprocess(mut diagnostic) => {
392            diagnostic.run.get_or_insert_with(|| engine.run_path());
393            RkError::Subprocess(diagnostic)
394        }
395        RkError::CheckFailed(mut diagnostic) => {
396            diagnostic.run.get_or_insert_with(|| engine.run_path());
397            RkError::CheckFailed(diagnostic)
398        }
399        other => other,
400    };
401    engine.finish(i32::from(error.exit_code()), Some(error.reason().as_str()));
402    error
403}
404
405/// Preview: walk the ordered steps and print, for each, the step name, what
406/// it proves, and the resolved invocation — without materializing anything
407/// and without invoking any external command. What preview shows is what
408/// apply would run, because both read the same step table and environment
409/// construction.
410fn preview(out: Output, ctx: &Ctx, steps: &[&StepSpec]) -> Result<(), RkError> {
411    let mut engine = Engine::open(out, clone_ctx(ctx), "setup preview", false)?;
412    out.result_line(format!(
413        "DRY RUN: rk setup would run these steps against {} on {}; re-run with --apply",
414        engine.ctx.repo,
415        engine.ctx.forge.as_str()
416    ));
417    for (idx, step) in steps.iter().enumerate() {
418        out.result_line(format!(
419            "step {}/{} {} — proves {}",
420            idx + 1,
421            steps.len(),
422            step.name,
423            step.proves
424        ));
425        // Preview is the rehearsal of apply, so a credential apply could
426        // not use is a preview failure: the operator learns it here rather
427        // than one flag later, and before an invocation is claimed.
428        if step.name == "bot-secrets" && engine.ctx.forge == Forge::Github {
429            secrets::resolve_key_file(&engine.ctx.target)?;
430        }
431        out.result_line(format!("  {}", render_invocation(&engine.ctx, step)));
432        if step.name == "protect-trunk"
433            && engine.ctx.forge == Forge::Github
434            && engine.ctx.required_check.is_none()
435        {
436            out.result_line("  needs: --required-check <name> before apply");
437        }
438        if step.optional && steps.len() > 1 {
439            out.result_line(format!(
440                "  optional: a full apply skips it; rk setup step {} --apply runs it",
441                step.name
442            ));
443        }
444        let mut event = engine.event(EventKind::StepFinished, Some(step.name));
445        event.status = Some("previewed".into());
446        engine.emit(&event);
447    }
448    let next = next_for_apply(&engine.ctx, steps);
449    out.next(&[
450        next,
451        "rk setup check --target . proves what is already true".to_owned(),
452    ]);
453    engine.finish(0, None);
454    Ok(())
455}
456
457/// The one line preview prints per step: the exact spawn shape, with every
458/// non-secret variable resolved.
459fn render_invocation(ctx: &Ctx, step: &StepSpec) -> String {
460    match step.name {
461        "branch-reminder" => {
462            "would write: the post-merge reminder hook at $(git rev-parse --git-path hooks)/post-merge".to_owned()
463        }
464        "package-check" => match ctx.tech {
465            Some("rust") => "would run: cargo publish --dry-run --allow-dirty".to_owned(),
466            Some("python") => "would run: python3 -m build".to_owned(),
467            Some("bash") => "nothing to run: no registry for this technology".to_owned(),
468            _ => "needs: a version file naming the technology".to_owned(),
469        },
470        "forge-version" => {
471            let (major, minor) = observe::GITLAB_VERSION_FLOOR;
472            match ctx.forge {
473                Forge::Github => {
474                    "nothing to read: github.com is a rolling service and declares no version floor"
475                        .to_owned()
476                }
477                Forge::Gitlab => format!(
478                    "would read: GET /version, and compare it against the {major}.{minor} floor; nothing is written"
479                ),
480            }
481        }
482        name => {
483            let check = ctx
484                .required_check
485                .as_ref()
486                .filter(|_| ctx.forge == Forge::Github && name == "protect-trunk")
487                .map(|value| format!(" RK_REQUIRED_CHECK={value}"))
488                .unwrap_or_default();
489            format!(
490                "would run: sh <embedded setup/{}/{name}> with RK_REPO={} RK_TRUNK_BRANCH={}{check}",
491                ctx.forge.as_str(),
492                ctx.repo,
493                ctx.trunk()
494            )
495        }
496    }
497}
498
499fn next_for_apply(ctx: &Ctx, steps: &[&StepSpec]) -> String {
500    let check = ctx
501        .required_check
502        .as_ref()
503        .map(|value| format!(" --required-check {value}"))
504        .unwrap_or_default();
505    if steps.len() == 1 {
506        format!(
507            "rk setup step {} --target {} --apply{check}",
508            steps[0].name, ctx.target
509        )
510    } else {
511        format!("rk setup --target {} --apply{check}", ctx.target)
512    }
513}
514
515/// A `Ctx` copy for engine ownership; the context is plain data.
516fn clone_ctx(ctx: &Ctx) -> Ctx {
517    ctx.clone()
518}
519
520/// Apply: run the selected steps in order, each through the full lifecycle.
521fn execute(
522    out: Output,
523    ctx: Ctx,
524    steps: &[&StepSpec],
525    command: &'static str,
526) -> Result<(), RkError> {
527    guard_sh()?;
528    let mut engine = Engine::open(out, ctx, command, true)?;
529    let mut done: Vec<(String, String)> = Vec::new();
530    for (idx, step) in steps.iter().enumerate() {
531        // An optional step applies only by name: a full run states the skip
532        // rather than acting on a condition the operator never asserted.
533        if step.optional && steps.len() > 1 {
534            engine.out.frame(format!(
535                "step {}/{} {} — skipped (optional; rk setup step {} --apply runs it)",
536                idx + 1,
537                steps.len(),
538                step.name,
539                step.name
540            ));
541            let mut finished = engine.event(EventKind::StepFinished, Some(step.name));
542            finished.status = Some("skipped".into());
543            engine.emit(&finished);
544            done.push((step.name.to_owned(), "skipped".to_owned()));
545            continue;
546        }
547        engine.out.frame(format!(
548            "step {}/{} {} — {}",
549            idx + 1,
550            steps.len(),
551            step.name,
552            step.proves
553        ));
554        let mut started = engine.event(EventKind::StepStarted, Some(step.name));
555        started.status = Some("running".into());
556        engine.emit(&started);
557        let clock = Instant::now();
558        let status = match apply_step(&mut engine, step) {
559            Ok(status) => status,
560            Err(error) => {
561                let error = attach_progress(error, &done, step, steps);
562                let mut finished = engine.event(EventKind::StepFinished, Some(step.name));
563                finished.status = Some("failed".into());
564                finished.reason = Some(error.reason());
565                finished.duration_ms = Some(elapsed_ms(clock));
566                engine.emit(&finished);
567                return Err(fail(&mut engine, error));
568            }
569        };
570        engine.out.frame(format!(
571            "{} {}: {}",
572            if matches!(status, Done::Skipped(_)) {
573                "skipped"
574            } else {
575                "ok"
576            },
577            step.name,
578            status.line()
579        ));
580        let mut finished = engine.event(EventKind::StepFinished, Some(step.name));
581        finished.status = Some(status.wire().into());
582        finished.exit_code = Some(0);
583        finished.duration_ms = Some(elapsed_ms(clock));
584        engine.emit(&finished);
585        done.push((step.name.to_owned(), status.wire().to_owned()));
586    }
587    engine.out.result_line(format!(
588        "setup: {} completed against {}",
589        step_count(done.len()),
590        engine.ctx.repo
591    ));
592    for (name, status) in &done {
593        engine.out.result_line(format!("  {status} {name}"));
594    }
595    engine.out.next(&[
596        format!("rk setup check --target {}", engine.ctx.target),
597        "rk guide setup orders what no command performs".to_owned(),
598    ]);
599    engine.finish(0, None);
600    Ok(())
601}
602
603/// A step count rendered with the noun that agrees with it, so no summary
604/// line can regrow a dangling plural.
605fn step_count(count: usize) -> String {
606    format!("{count} {}", if count == 1 { "step" } else { "steps" })
607}
608
609fn elapsed_ms(clock: Instant) -> u64 {
610    u64::try_from(clock.elapsed().as_millis()).unwrap_or(u64::MAX)
611}
612
613/// What one applied step reported.
614enum Done {
615    /// The desired state already held; nothing ran.
616    Satisfied(String),
617    /// The target is ineligible for this step.
618    Skipped(String),
619    /// The script ran and the postcondition was read back.
620    Changed(String, Option<String>),
621    /// A read-only step ran and passed.
622    Passed(String),
623}
624
625impl Done {
626    const fn wire(&self) -> &'static str {
627        match self {
628            Self::Satisfied(_) => "satisfied",
629            Self::Skipped(_) => "skipped",
630            Self::Changed(..) => "applied",
631            Self::Passed(_) => "passed",
632        }
633    }
634
635    fn line(&self) -> String {
636        match self {
637            Self::Satisfied(detail) | Self::Passed(detail) | Self::Skipped(detail) => {
638                detail.clone()
639            }
640            Self::Changed(detail, limitation) => limitation.as_ref().map_or_else(
641                || detail.clone(),
642                |limit| format!("{detail} (limitation: {limit})"),
643            ),
644        }
645    }
646}
647
648/// One step, full lifecycle.
649#[allow(clippy::too_many_lines)]
650fn apply_step(engine: &mut Engine, step: &StepSpec) -> Result<Done, RkError> {
651    // Prerequisites are observed, not remembered: the forge is the
652    // authority on whether an earlier step's state holds.
653    for prereq in step.prereqs {
654        let state = observe_with(engine, prereq)?;
655        if !state.satisfied() {
656            return Err(RkError::refusal(
657                Diagnostic::new(
658                    Reason::PrerequisiteUnmet,
659                    format!(
660                        "{} requires {prereq} first: {}",
661                        step.name,
662                        state_detail(&state)
663                    ),
664                )
665                .expected(format!("{prereq} satisfied before {}", step.name))
666                .action(format!(
667                    "rk setup step {prereq} --target {} --apply",
668                    engine.ctx.target
669                ))
670                .step(step.name),
671            ));
672        }
673    }
674    match step.name {
675        "package-check" => {
676            if engine.ctx.tech.is_none() {
677                return Err(RkError::Usage(
678                    "no version file names a technology; rk binding --list names the bindings"
679                        .into(),
680                ));
681            }
682            let state = observe_with(engine, "package-check")?;
683            match state {
684                StepState::Satisfied { detail, .. } => Ok(Done::Passed(detail)),
685                StepState::Unsatisfied { detail } | StepState::Inapplicable { detail } => {
686                    Err(RkError::subprocess(
687                        Diagnostic::new(
688                            Reason::SubprocessFailed,
689                            format!("package-check failed: {detail}"),
690                        )
691                        .expected(step.proves.to_owned())
692                        .step(step.name),
693                    ))
694                }
695                StepState::Unknown { detail } => Err(RkError::subprocess(
696                    Diagnostic::new(
697                        Reason::SubprocessFailed,
698                        format!("package-check could not run: {detail}"),
699                    )
700                    .step(step.name),
701                )),
702            }
703        }
704        // The step mutates nothing, so apply and check read the same answer
705        // and apply writes nothing at all. An unreadable version is a
706        // refusal, never a pass: the floor exists to stop a protection the
707        // forge cannot honor, and a floor nobody could read proves neither
708        // way.
709        "forge-version" => match observe_with(engine, "forge-version")? {
710            StepState::Satisfied { detail, .. } => Ok(Done::Satisfied(detail)),
711            StepState::Unsatisfied { detail } | StepState::Inapplicable { detail } => {
712                Err(RkError::refusal(
713                    Diagnostic::new(Reason::PrerequisiteUnmet, detail)
714                        .expected(step.proves.to_owned())
715                        .action("upgrade the instance, or host the project on gitlab.com")
716                        .target_state("unchanged")
717                        .step(step.name),
718                ))
719            }
720            StepState::Unknown { detail } => Err(RkError::refusal(
721                Diagnostic::new(Reason::ForgeTemporary, detail)
722                    .expected("a readable forge version")
723                    .action("glab auth login, then rerun")
724                    .target_state("unchanged")
725                    .step(step.name),
726            )),
727        },
728        "branch-reminder" => {
729            use crate::setup::branch_reminder::{HookState, hook_body, hook_path, observe_hook};
730            match observe_hook(&engine.ctx.target) {
731                HookState::Installed => Ok(Done::Satisfied(
732                    "the post-merge reminder hook is installed".into(),
733                )),
734                HookState::Foreign => Err(RkError::refusal(
735                    Diagnostic::new(
736                        Reason::StateDrift,
737                        "a foreign post-merge hook exists; the reminder is never written over it",
738                    )
739                    .expected("no post-merge hook, or one carrying the release-kit marker")
740                    .action(
741                        "merge by hand: guard each call behind its own capability probe inside the existing hook — `rk branches prune --help >/dev/null 2>&1` before `rk branches prune --quiet || :`, and the same pair for `rk worktree prune`",
742                    )
743                    .target_state("unchanged")
744                    .step(step.name),
745                )),
746                HookState::Unreadable(detail) => Err(RkError::refusal(
747                    Diagnostic::new(
748                        Reason::StateDrift,
749                        format!("the post-merge hook cannot be read: {detail}"),
750                    )
751                    .target_state("unchanged")
752                    .step(step.name),
753                )),
754                HookState::Absent | HookState::Drifted => {
755                    let path = hook_path(&engine.ctx.target).map_err(|detail| {
756                        RkError::refusal(
757                            Diagnostic::new(
758                                Reason::PrerequisiteUnmet,
759                                format!("the hooks directory cannot be resolved: {detail}"),
760                            )
761                            .expected("a git repository whose hooks directory git can name")
762                            .step(step.name),
763                        )
764                    })?;
765                    crate::atomic::write(&path, hook_body())?;
766                    #[cfg(unix)]
767                    {
768                        use std::os::unix::fs::PermissionsExt as _;
769                        std::fs::set_permissions(
770                            &path,
771                            std::fs::Permissions::from_mode(0o755),
772                        )?;
773                    }
774                    Ok(Done::Changed(
775                        "wrote the post-merge reminder hook".into(),
776                        None,
777                    ))
778                }
779            }
780        }
781        "single-trunk" => {
782            let guard = {
783                let ctx = clone_ctx(&engine.ctx);
784                let mut runner = |exec: &Exec| engine.exec(exec, false);
785                observe::single_trunk_guard(&ctx, &mut runner)?
786            };
787            // A destructive step fails closed: an ancestry the guard cannot
788            // establish is treated exactly like one it refuted.
789            match &guard {
790                StepState::Satisfied { .. } => {}
791                StepState::Unsatisfied { detail }
792                | StepState::Inapplicable { detail }
793                | StepState::Unknown { detail } => {
794                    return Err(RkError::refusal(
795                        Diagnostic::new(
796                            Reason::DestructiveRefusal,
797                            format!("single-trunk refuses: {detail}"),
798                        )
799                        .expected(
800                            "proof that every candidate branch is absent, or an ancestor of the trunk",
801                        )
802                        .step(step.name),
803                    ));
804                }
805            }
806            run_forge_step(engine, step)
807        }
808        "bot-secrets" => {
809            // Validate before observing: a wrong path or a wrong mode is
810            // the operator's answer either way, and the refusal costs no
811            // forge call. Only GitHub reads a key file; GitLab's credential
812            // is a token, and its step must not fail over a variable it
813            // never consumes.
814            let key = match engine.ctx.forge {
815                // The run's one read: an install-bot observation earlier in
816                // this run already holds the bytes, and this step stores
817                // those very bytes rather than reopening the path.
818                Forge::Github => key_file_for(engine)?.map(|key| key.bytes.clone()),
819                Forge::Gitlab => None,
820            };
821            let provided = match engine.ctx.forge {
822                // Both halves of an App identity, or neither: a run holding
823                // only one of them would store half a credential.
824                Forge::Github => secrets::value_of("RK_BOT_APP_ID").is_some() && key.is_some(),
825                Forge::Gitlab => secrets::value_of("RK_BOT_TOKEN").is_some(),
826            };
827            let state = observe_with(engine, step.name)?;
828            if !provided {
829                if state.satisfied() {
830                    return Ok(Done::Satisfied(state_detail(&state)));
831                }
832                let wanted = match engine.ctx.forge {
833                    Forge::Github => {
834                        "export RK_BOT_APP_ID and RK_BOT_PRIVATE_KEY_FILE, the second naming the .pem; rk forge github carries the walkthrough"
835                    }
836                    Forge::Gitlab => {
837                        "rk setup step install-bot --apply stores the token, or export RK_BOT_TOKEN to rotate one"
838                    }
839                };
840                return Err(RkError::refusal(
841                    Diagnostic::new(
842                        Reason::PrerequisiteUnmet,
843                        "bot-secrets has no credentials to store",
844                    )
845                    .expected("the bot credentials in the environment, the key as a path")
846                    .action(wanted.to_owned())
847                    .step(step.name),
848                ));
849            }
850            if let Some(journal) = &mut engine.journal {
851                for name in SECRET_VARS {
852                    if secrets::value_of(name).is_some() {
853                        journal.record_secret(name, true, "environment");
854                    }
855                }
856                if key.is_some() {
857                    journal.record_secret(secrets::PRIVATE_KEY_FILE, true, "file");
858                }
859            }
860            // The bytes rk validated are the bytes the child receives and
861            // the bytes the redactor holds: one read, one value, so nothing
862            // can be substituted between the check and the forge.
863            let stdin = key;
864            run_forge_step_with(engine, step, stdin, Vec::new())
865        }
866        "protections-check" => {
867            let (outcome, _) = run_script(engine, step)?;
868            if !outcome.success() {
869                return Err(classify_failure(engine, step, &outcome));
870            }
871            // The script is the operator-auditable mirror; the observation
872            // is the authoritative shape check, so the step passes only
873            // when both agree.
874            match observe_with(engine, step.name)? {
875                StepState::Satisfied { detail, limitation } => {
876                    Ok(Done::Passed(limitation.map_or_else(
877                        || detail.clone(),
878                        |limit| format!("{detail} (limitation: {limit})"),
879                    )))
880                }
881                StepState::Unsatisfied { detail } | StepState::Inapplicable { detail } => {
882                    Err(RkError::refusal(
883                        Diagnostic::new(
884                            Reason::StateDrift,
885                            format!("protections-check passed its script and the observation disagrees: {detail}"),
886                        )
887                        .expected(step.proves.to_owned())
888                        .step(step.name),
889                    ))
890                }
891                // An unreadable readback is a retryable outage, not drift,
892                // exactly as the postcondition lifecycle classifies it.
893                StepState::Unknown { detail } => Err(RkError::refusal(
894                    Diagnostic::new(
895                        Reason::ForgeTemporary,
896                        format!(
897                            "protections-check passed its script and the readback could not confirm it: {detail}"
898                        ),
899                    )
900                    .expected(step.proves.to_owned())
901                    .action("check authentication and connectivity, then rerun")
902                    .step(step.name),
903                )),
904            }
905        }
906        // GitHub's grant is the one write the forge offers a command, and
907        // it takes a user credential; everything else here — the pre- and
908        // post-observation, and the installation id the script is handed —
909        // happens as the App itself. GitLab's install-bot needs none of
910        // this and takes the generic lifecycle below.
911        "install-bot" if engine.ctx.forge == Forge::Github => {
912            match observe_with(engine, step.name)? {
913                StepState::Satisfied { detail, .. } => {
914                    return Ok(Done::Satisfied(detail));
915                }
916                StepState::Unsatisfied { .. } | StepState::Inapplicable { .. } => {}
917                StepState::Unknown { detail } => {
918                    return Err(RkError::refusal(
919                        Diagnostic::new(
920                            Reason::ForgeTemporary,
921                            format!("{} cannot observe the current state: {detail}", step.name),
922                        )
923                        .expected("a readable forge answer before anything mutates")
924                        .action("check the App credentials and connectivity, then rerun")
925                        .step(step.name),
926                    ));
927                }
928            }
929            let installation = github_installation_id(engine, step)?;
930            run_forge_step_with(
931                engine,
932                step,
933                None,
934                vec![("RK_BOT_INSTALLATION".into(), installation.into())],
935            )
936        }
937        _ => {
938            if step.mutates == Mutates::Forge {
939                // The lifecycle applies only on a state it has read: an
940                // observation that cannot decide fails closed here exactly
941                // as it does after the write, so no mutation ever rides on
942                // an unreadable forge answer.
943                match observe_with(engine, step.name)? {
944                    StepState::Satisfied { detail, limitation } => {
945                        let detail = if step.name == "private-vulnerability-reporting" {
946                            limitation.map_or_else(
947                                || detail.clone(),
948                                |limit| format!("{detail} (limitation: {limit})"),
949                            )
950                        } else {
951                            detail
952                        };
953                        return Ok(Done::Satisfied(detail));
954                    }
955                    StepState::Inapplicable { detail }
956                        if step.name == "private-vulnerability-reporting" =>
957                    {
958                        return Ok(Done::Skipped(detail));
959                    }
960                    StepState::Unsatisfied { .. } | StepState::Inapplicable { .. } => {}
961                    StepState::Unknown { detail } => {
962                        return Err(RkError::refusal(
963                            Diagnostic::new(
964                                Reason::ForgeTemporary,
965                                format!("{} cannot observe the current state: {detail}", step.name),
966                            )
967                            .expected("a readable forge answer before anything mutates")
968                            .action("check authentication and connectivity, then rerun")
969                            .step(step.name),
970                        ));
971                    }
972                }
973            }
974            run_forge_step(engine, step)
975        }
976    }
977}
978
979/// The id of the App's installation on this repository's owner, read as
980/// the App itself. The grant needs it, and no user credential can read
981/// it: the observation that just ran answered 404, so the repository
982/// endpoint that names the id directly has nothing to say yet. The
983/// account-level installation is a direct read for either account kind —
984/// the user endpoint answers for a person, the organization endpoint for
985/// an organization — so nothing here lists or paginates.
986fn github_installation_id(engine: &mut Engine, step: &StepSpec) -> Result<String, RkError> {
987    let refuse = |message: String, action: &str| {
988        RkError::refusal(
989            Diagnostic::new(Reason::PrerequisiteUnmet, message)
990                .expected("the App installed on the repository's owner")
991                .action(action.to_owned())
992                .step(step.name),
993        )
994    };
995    let jwt = match app_jwt_for(engine)? {
996        Ok(jwt) => jwt,
997        Err(detail) => {
998            return Err(refuse(
999                format!("install-bot has no App token: {detail}"),
1000                app_jwt::REMEDIATION,
1001            ));
1002        }
1003    };
1004    let owner = engine
1005        .ctx
1006        .repo
1007        .split('/')
1008        .next()
1009        .unwrap_or_default()
1010        .to_owned();
1011    let ctx = clone_ctx(&engine.ctx);
1012    for path in [
1013        format!("users/{owner}/installation"),
1014        format!("orgs/{owner}/installation"),
1015    ] {
1016        match app_jwt::api_get(&ctx, &jwt, &path) {
1017            AppApi::Ok(body) => {
1018                return body["id"].as_i64().map(|id| id.to_string()).ok_or_else(|| {
1019                    refuse(
1020                        format!("the forge answered {path} without an installation id"),
1021                        "check RK_BOT_APP_ID and the key file name the same App",
1022                    )
1023                });
1024            }
1025            AppApi::Missing => {}
1026            AppApi::Refused(detail) => {
1027                return Err(refuse(
1028                    detail,
1029                    "check RK_BOT_APP_ID and the key file name the same App",
1030                ));
1031            }
1032            AppApi::Failed(detail) => {
1033                return Err(RkError::refusal(
1034                    Diagnostic::new(
1035                        Reason::ForgeTemporary,
1036                        format!("install-bot cannot read the App's installation: {detail}"),
1037                    )
1038                    .action("check connectivity, then rerun")
1039                    .step(step.name),
1040                ));
1041            }
1042        }
1043    }
1044    Err(refuse(
1045        format!("the App has no installation on {owner}"),
1046        "install the App on the account first; the setup guide's step 5 walks it",
1047    ))
1048}
1049
1050/// Materialize, spawn, classify, and verify one forge-mutating step.
1051fn run_forge_step(engine: &mut Engine, step: &StepSpec) -> Result<Done, RkError> {
1052    run_forge_step_with(engine, step, None, Vec::new())
1053}
1054
1055/// The same, with bytes written to the step's standard input and values
1056/// `rk` derived added to its environment.
1057fn run_forge_step_with(
1058    engine: &mut Engine,
1059    step: &StepSpec,
1060    stdin: Option<Zeroizing<Vec<u8>>>,
1061    extra_env: Vec<(OsString, OsString)>,
1062) -> Result<Done, RkError> {
1063    let (outcome, _) = run_script_with(engine, step, stdin, extra_env)?;
1064    if !outcome.success() {
1065        return Err(classify_failure(engine, step, &outcome));
1066    }
1067    let state = observe_with(engine, step.name)?;
1068    match state {
1069        StepState::Satisfied { detail, limitation } => Ok(Done::Changed(detail, limitation)),
1070        StepState::Inapplicable { detail } if step.name == "private-vulnerability-reporting" => {
1071            Ok(Done::Skipped(detail))
1072        }
1073        StepState::Unsatisfied { detail } | StepState::Inapplicable { detail } => {
1074            Err(RkError::refusal(
1075                Diagnostic::new(
1076                    Reason::StateDrift,
1077                    format!(
1078                        "{} ran and its postcondition does not hold: {detail}",
1079                        step.name
1080                    ),
1081                )
1082                .expected(step.proves.to_owned())
1083                .step(step.name),
1084            ))
1085        }
1086        // The lifecycle ends with a proven postcondition; a readback that
1087        // cannot run leaves the step unproven, and an unproven apply is a
1088        // failure a retry can cure, never a success.
1089        StepState::Unknown { detail } => Err(RkError::refusal(
1090            Diagnostic::new(
1091                Reason::ForgeTemporary,
1092                format!(
1093                    "{} ran and the readback could not confirm it: {detail}",
1094                    step.name
1095                ),
1096            )
1097            .expected(step.proves.to_owned())
1098            .action(format!(
1099                "rk setup step {} --target {} --apply re-asserts and re-proves it",
1100                step.name, engine.ctx.target
1101            ))
1102            .step(step.name),
1103        )),
1104    }
1105}
1106
1107/// Observe one step through the engine's executor.
1108///
1109/// `install-bot` on GitHub is the one observation that authenticates as
1110/// the App itself, so it routes through [`app_jwt_for`] here — where the
1111/// engine can mint once and register the redaction needles — rather than
1112/// through the credential-free name dispatch in [`observe::observe`].
1113fn observe_with(engine: &mut Engine, step: &str) -> Result<StepState, RkError> {
1114    if step == "install-bot" && engine.ctx.forge == Forge::Github {
1115        let jwt = match app_jwt_for(engine)? {
1116            Ok(jwt) => jwt,
1117            Err(detail) => return Ok(StepState::Unknown { detail }),
1118        };
1119        return Ok(observe::github_install_bot(&engine.ctx, &jwt));
1120    }
1121    let ctx = clone_ctx(&engine.ctx);
1122    let mut runner = |exec: &Exec| engine.exec(exec, false);
1123    observe::observe(&ctx, step, &mut runner)
1124}
1125
1126/// The run's validated key file, read exactly once per run: the first
1127/// consumer resolves it and every later one reuses the same bytes, so the
1128/// file that authenticated the App is the file `bot-secrets` stores, and
1129/// no replacement between steps can split the two. The bytes become a
1130/// redaction needle the moment they are read.
1131fn key_file_for(engine: &mut Engine) -> Result<Option<&secrets::KeyFile>, RkError> {
1132    if engine.key.is_none() {
1133        engine.key = secrets::resolve_key_file(&engine.ctx.target)?;
1134        if let Some(key) = &engine.key {
1135            engine.secrets.push(key.bytes.clone());
1136        }
1137    }
1138    Ok(engine.key.as_ref())
1139}
1140
1141/// The run's App JWT, minted at most once: the key comes from the run's
1142/// one read, and the minted token and its signature segment become
1143/// redaction needles before anything else spawns. Every install-bot
1144/// observation and the grant's installation-id discovery reuse the one
1145/// token, whose nine-minute life covers a run's contiguous step easily.
1146///
1147/// The inner value is `Err` with a one-line detail where no token can
1148/// exist — absent exports, or a signer that failed — which an observation
1149/// reports as `unknown` and an apply turns into a refusal.
1150fn app_jwt_for(engine: &mut Engine) -> Result<Result<String, String>, RkError> {
1151    if let Some(jwt) = &engine.app_jwt {
1152        return Ok(Ok(jwt.clone()));
1153    }
1154    let app_id = app_jwt::app_id()?;
1155    let key_bytes = key_file_for(engine)?.map(|key| key.bytes.clone());
1156    let (Some(app_id), Some(key_bytes)) = (app_id, key_bytes) else {
1157        return Ok(Err(format!(
1158            "the installation is readable only to the App itself; {}",
1159            app_jwt::REMEDIATION
1160        )));
1161    };
1162    let credentials = app_jwt::AppCredentials { app_id, key_bytes };
1163    let ctx = clone_ctx(&engine.ctx);
1164    Ok(match app_jwt::mint(&ctx, &credentials) {
1165        Ok(jwt) => {
1166            engine
1167                .secrets
1168                .push(Zeroizing::new(jwt.clone().into_bytes()));
1169            if let Some(signature) = jwt.rsplit('.').next() {
1170                engine
1171                    .secrets
1172                    .push(Zeroizing::new(signature.as_bytes().to_vec()));
1173            }
1174            engine.app_jwt = Some(jwt.clone());
1175            Ok(jwt)
1176        }
1177        Err(detail) => Err(detail),
1178    })
1179}
1180
1181fn state_detail(state: &StepState) -> String {
1182    match state {
1183        StepState::Satisfied { detail, .. }
1184        | StepState::Unsatisfied { detail }
1185        | StepState::Inapplicable { detail }
1186        | StepState::Unknown { detail } => detail.clone(),
1187    }
1188}
1189
1190/// Materialize the step's script into the run's private directory, prove
1191/// the written bytes by digest, and spawn it through the interpreter.
1192fn run_script(engine: &mut Engine, step: &StepSpec) -> Result<(Outcome, PathBuf), RkError> {
1193    run_script_with(engine, step, None, Vec::new())
1194}
1195
1196/// The same, with bytes written to the script's standard input.
1197///
1198/// A credential travels this way and no other: `rk` reads it, validates it,
1199/// and hands the child the bytes it validated, so nothing between the check
1200/// and the forge can substitute a different file.
1201fn run_script_with(
1202    engine: &mut Engine,
1203    step: &StepSpec,
1204    stdin: Option<Zeroizing<Vec<u8>>>,
1205    extra_env: Vec<(OsString, OsString)>,
1206) -> Result<(Outcome, PathBuf), RkError> {
1207    let rel = format!("{}/{}", engine.ctx.forge.as_str(), step.name);
1208    let bytes = embedded::SETUP
1209        .get_file(&rel)
1210        .map(include_dir::File::contents)
1211        .ok_or_else(|| RkError::Other(anyhow::anyhow!("no embedded script at setup/{rel}")))?;
1212    let journal = engine
1213        .journal
1214        .as_mut()
1215        .ok_or_else(|| RkError::Other(anyhow::anyhow!("an apply always has a journal")))?;
1216    let dir = journal.scripts_dir().join(engine.ctx.forge.as_str());
1217    fs::create_dir_all(&dir)?;
1218    restrict(&dir, 0o700);
1219    let path = dir.join(step.name);
1220    fs::write(&path, bytes)?;
1221    restrict(&path, 0o600);
1222    let written = fs::read(&path)?;
1223    let digest = Digest::of(&written);
1224    if digest != Digest::of(bytes) {
1225        return Err(RkError::Other(anyhow::anyhow!(
1226            "the materialized script at {} differs from the embedded bytes",
1227            path.display()
1228        )));
1229    }
1230    journal.record_script(format!("scripts/{rel}"), digest.to_string());
1231    let mut env = engine.ctx.child_env(step.name);
1232    env.extend(extra_env);
1233    let exec = Exec {
1234        program: crate::probes::sh_bin(),
1235        args: vec![path.clone().into_os_string()],
1236        env,
1237        cwd: engine.ctx.target.as_std_path().to_path_buf(),
1238        stdin,
1239    };
1240    let outcome = engine.exec(&exec, true)?;
1241    Ok((outcome, path))
1242}
1243
1244/// Honest classification: `gh` documents exit 4 as authentication required;
1245/// beyond that only an HTTP status in the response says more, and a step
1246/// that fails for a reason nothing establishes stays `subprocess-failed`
1247/// with its own stderr surfaced verbatim.
1248fn classify_failure(engine: &Engine, step: &StepSpec, outcome: &Outcome) -> RkError {
1249    let stderr = String::from_utf8_lossy(&outcome.stderr);
1250    // A signalled child usually writes nothing before it dies, and
1251    // "no output" would blame the forge for a kill that came from
1252    // outside it. The adapter already resolved 128+N; say which.
1253    let last = if outcome.exit_code >= 128 {
1254        format!("killed by signal {}", outcome.exit_code - 128)
1255    } else {
1256        stderr
1257            .lines()
1258            .rev()
1259            .find(|line| !line.trim().is_empty())
1260            .unwrap_or("no output")
1261            .to_owned()
1262    };
1263    let reason = if (engine.ctx.forge == Forge::Github && outcome.exit_code == 4)
1264        || stderr.contains("HTTP 401")
1265    {
1266        Reason::ForgeAuthentication
1267    } else if stderr.contains("HTTP 403") {
1268        Reason::ForgePermission
1269    } else if stderr.contains("HTTP 429") || stderr.contains("rate limit") {
1270        Reason::ForgeRateLimit
1271    } else {
1272        Reason::SubprocessFailed
1273    };
1274    let diagnostic = Diagnostic::new(reason, format!("the forge refused '{}': {last}", step.name))
1275        .expected(step.proves.to_owned())
1276        .action(format!(
1277            "rk setup step {} --target {} --apply",
1278            step.name, engine.ctx.target
1279        ))
1280        .step(step.name);
1281    let diagnostic = match reason {
1282        Reason::ForgePermission => diagnostic.expected(format!(
1283            "repository administration write on {} for the authenticated account",
1284            engine.ctx.repo
1285        )),
1286        _ => diagnostic,
1287    };
1288    match reason {
1289        Reason::SubprocessFailed => RkError::subprocess(diagnostic),
1290        _ => RkError::refusal(diagnostic),
1291    }
1292}
1293
1294/// Fold the run's progress into the failure, so the diagnostic answers
1295/// what state the target is in.
1296fn attach_progress(
1297    error: RkError,
1298    done: &[(String, String)],
1299    failed: &StepSpec,
1300    steps: &[&StepSpec],
1301) -> RkError {
1302    let remaining = steps.len().saturating_sub(done.len() + 1);
1303    let state = format!(
1304        "{} completed; {} failed; {remaining} not attempted",
1305        step_count(done.len()),
1306        failed.name
1307    );
1308    match error {
1309        RkError::Refusal(mut diagnostic) => {
1310            diagnostic.target_state.get_or_insert(state);
1311            RkError::Refusal(diagnostic)
1312        }
1313        RkError::Subprocess(mut diagnostic) => {
1314            diagnostic.target_state.get_or_insert(state);
1315            RkError::Subprocess(diagnostic)
1316        }
1317        other => other,
1318    }
1319}
1320
1321/// `rk setup check`: observe and verify every step, report per step, and
1322/// judge at the end. The mutating half is unreachable from this path: it
1323/// calls only the observe functions.
1324fn check(out: Output, ctx: Ctx) -> Result<(), RkError> {
1325    let mut engine = Engine::open(out, ctx, "setup check", false)?;
1326    let mut unsatisfied = 0usize;
1327    let mut unverifiable = 0usize;
1328    for step in &STEPS {
1329        let clock = Instant::now();
1330        let state = observe_with(&mut engine, step.name)?;
1331        let (label, wire) = match &state {
1332            StepState::Satisfied { .. } => ("ok", "satisfied"),
1333            // An optional step whose condition does not hold is stated, not
1334            // judged: nothing is wrong and nothing was skipped silently.
1335            StepState::Inapplicable { .. } => ("skipped", "skipped"),
1336            StepState::Unsatisfied { .. } => {
1337                unsatisfied += 1;
1338                ("unsatisfied", "unsatisfied")
1339            }
1340            // A step the check cannot verify has not passed: an unreadable
1341            // forge answer must never read as a clean setup.
1342            StepState::Unknown { .. } => {
1343                unverifiable += 1;
1344                ("unknown", "unknown")
1345            }
1346        };
1347        let mut line = format!("{label} {} — {}", step.name, state_detail(&state));
1348        if let StepState::Satisfied {
1349            limitation: Some(limit),
1350            ..
1351        } = &state
1352        {
1353            use std::fmt::Write as _;
1354            let _ = write!(line, " (limitation: {limit})");
1355        }
1356        engine.out.result_line(line);
1357        let mut finished = engine.event(EventKind::StepFinished, Some(step.name));
1358        finished.status = Some(wire.into());
1359        finished.duration_ms = Some(elapsed_ms(clock));
1360        engine.emit(&finished);
1361    }
1362    if unsatisfied > 0 || unverifiable > 0 {
1363        let error = RkError::check_failed(
1364            Diagnostic::new(
1365                Reason::StateDrift,
1366                format!(
1367                    "{} {} not satisfied and {unverifiable} could not be verified",
1368                    step_count(unsatisfied),
1369                    if unsatisfied == 1 { "is" } else { "are" }
1370                ),
1371            )
1372            .expected("every step's proof column to hold and to be readable")
1373            .action(format!(
1374                "rk setup --target {} --apply re-asserts them",
1375                engine.ctx.target
1376            )),
1377        );
1378        return Err(fail(&mut engine, error));
1379    }
1380    engine
1381        .out
1382        .next(&["rk guide release orders the first release".to_owned()]);
1383    engine.finish(0, None);
1384    Ok(())
1385}
1386
1387/// Restrict a materialized path's mode: data, not an executable — nothing
1388/// ever executes a script directly, so no mode is load-bearing.
1389fn restrict(path: &std::path::Path, mode: u32) {
1390    #[cfg(unix)]
1391    {
1392        use std::os::unix::fs::PermissionsExt as _;
1393        let _ = fs::set_permissions(path, fs::Permissions::from_mode(mode));
1394    }
1395    #[cfg(not(unix))]
1396    let _ = (path, mode);
1397}
1398
1399/// A POSIX shell must spawn before anything else does; every step runs
1400/// through it.
1401fn guard_sh() -> Result<(), RkError> {
1402    let ok = std::process::Command::new(crate::probes::sh_bin())
1403        .args(["-c", "exit 0"])
1404        .status()
1405        .is_ok_and(|status| status.success());
1406    if ok {
1407        Ok(())
1408    } else {
1409        Err(RkError::refusal(
1410            Diagnostic::new(Reason::PrerequisiteUnmet, "no POSIX sh runs on this host")
1411                .expected("a working sh on PATH; every step spawns through it")
1412                .action("install a POSIX shell, then rerun")
1413                .target_state("nothing was run and nothing changed"),
1414        ))
1415    }
1416}
1417
1418#[cfg(test)]
1419mod tests {
1420    /// Every summary line reports its count through one helper, so none of
1421    /// them can regrow a dangling plural.
1422    #[test]
1423    fn a_step_count_carries_a_noun_that_agrees_with_it() {
1424        assert_eq!(super::step_count(0), "0 steps");
1425        assert_eq!(super::step_count(1), "1 step");
1426        assert_eq!(super::step_count(2), "2 steps");
1427    }
1428}