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::proof::{self, Standing};
32use crate::setup::report::{Report, Row, Stance, stance};
33use crate::setup::secrets;
34use crate::setup::steps::{Mutates, STEPS, StepSpec, spec};
35
36/// Dispatch the setup surface.
37///
38/// # Errors
39///
40/// Every failure classified through the matrix, each carrying its `reason`.
41pub fn run(args: &SetupArgs) -> Result<(), RkError> {
42    match &args.action {
43        Some(SetupAction::Script { name, forge }) => script(name, forge.as_deref()),
44        Some(SetupAction::Check {
45            target,
46            repo,
47            forge,
48            required_check,
49            json,
50        }) => check(
51            Output::new(*json),
52            observing(
53                target,
54                repo.as_deref(),
55                forge.as_deref(),
56                required_check.as_deref(),
57            )?,
58        ),
59        Some(SetupAction::Checkpoint {
60            target,
61            repo,
62            forge,
63            required_check,
64            json,
65        }) => checkpoint(
66            Output::new(*json),
67            observing(
68                target,
69                repo.as_deref(),
70                forge.as_deref(),
71                required_check.as_deref(),
72            )?,
73        ),
74        // No forge CLI is resolved and no run opens: the status reads a
75        // committed file and this target's own configuration alone.
76        Some(SetupAction::Status {
77            target,
78            repo,
79            forge,
80            required_check,
81            json,
82        }) => status(
83            Output::new(*json),
84            &Ctx::resolve(
85                target,
86                repo.as_deref(),
87                forge.as_deref(),
88                required_check.as_deref(),
89            )?,
90        ),
91        Some(action @ SetupAction::Step { .. }) => step(action),
92        None if args.list => list(args.forge.as_deref()),
93        None => {
94            let target = args.target.clone().ok_or_else(|| {
95                RkError::Usage("name a --target, or pass --list to see the steps".into())
96            })?;
97            let all: Vec<&StepSpec> = STEPS.iter().collect();
98            let mut ctx = Ctx::resolve(
99                &target,
100                args.repo.as_deref(),
101                args.forge.as_deref(),
102                args.required_check.as_deref(),
103            )?;
104            reject_check_flag_on_gitlab(&ctx)?;
105            if args.apply {
106                require_check_for(&ctx, &all)?;
107                // The full run skips its optional steps, so the callers
108                // are what the run will actually reach.
109                let acted: Vec<&StepSpec> = all
110                    .iter()
111                    .copied()
112                    .filter(|step| !skipped_by_a_full_run(&ctx, step, all.len()))
113                    .collect();
114                ctx.require_cli(&acted)?;
115                execute(Output::new(args.json), ctx, &all, "setup")
116            } else {
117                let acted: Vec<&StepSpec> = all
118                    .iter()
119                    .copied()
120                    .filter(|step| !skipped_by_a_full_run(&ctx, step, all.len()))
121                    .collect();
122                ctx.require_cli(&acted)?;
123                preview(Output::new(args.json), &ctx, &all)
124            }
125        }
126    }
127}
128
129/// `rk setup step`: preview one step, or run it under `--apply`.
130fn step(action: &SetupAction) -> Result<(), RkError> {
131    let SetupAction::Step {
132        name,
133        target,
134        repo,
135        forge,
136        required_check,
137        apply,
138        json,
139    } = action
140    else {
141        unreachable!("the dispatch routes only a step here");
142    };
143    let selected = spec(name).ok_or_else(|| {
144        RkError::Usage(format!("unknown step '{name}'; rk setup --list names them"))
145    })?;
146    let mut ctx = Ctx::resolve(
147        target,
148        repo.as_deref(),
149        forge.as_deref(),
150        required_check.as_deref(),
151    )?;
152    reject_check_flag_on_gitlab(&ctx)?;
153    if *apply {
154        refuse_an_excluded_step(&ctx, selected)?;
155        require_check_for(&ctx, &[selected])?;
156        // Every argument refusal has been given, so what remains
157        // is the call itself and its one prerequisite.
158        ctx.require_cli(&[selected])?;
159        execute(Output::new(*json), ctx, &[selected], "setup step")
160    } else {
161        // A preview writes nothing, but it names the command it
162        // would run, so a forge CLI it could never find is worth
163        // saying now rather than at the apply.
164        ctx.require_cli(&[selected])?;
165        preview(Output::new(*json), &ctx, &[selected])
166    }
167}
168
169/// The context of a run that observes every step: a check and a
170/// checkpoint. Each asks the forge for every step the target runs, so it
171/// needs the forge CLI for each one that asks a question.
172fn observing(
173    target: &camino::Utf8PathBuf,
174    repo: Option<&str>,
175    forge: Option<&str>,
176    required_check: Option<&str>,
177) -> Result<Ctx, RkError> {
178    let mut ctx = Ctx::resolve(target, repo, forge, required_check)?;
179    reject_check_flag_on_gitlab(&ctx)?;
180    let all: Vec<&StepSpec> = STEPS.iter().collect();
181    ctx.require_cli(&all)?;
182    Ok(ctx)
183}
184
185/// Whether a full run skips this step at this target.
186///
187/// `optional` is the setup declaration's claim that a step is not universal; the
188/// target's own configuration answers whether it wants this one. Today
189/// `protect-release-lines` is the single such step, and a project that
190/// sets `setup.release_lines` gets it run rather than skipped and
191/// remembered.
192fn skipped_by_a_full_run(ctx: &Ctx, step: &StepSpec, selected: usize) -> bool {
193    if !step.optional || selected <= 1 {
194        return false;
195    }
196    !(step.name == "protect-release-lines" && ctx.release_lines())
197}
198
199/// A step the target declared it does not run is refused by name rather
200/// than applied. The committed file is the one statement of which steps
201/// this target runs, so a run that installed what the file excludes would
202/// leave the forge and the declaration disagreeing with nobody to notice;
203/// changing the model is one edit, and that edit is the auditable act.
204fn refuse_an_excluded_step(ctx: &Ctx, step: &StepSpec) -> Result<(), RkError> {
205    match stance(ctx, step) {
206        Stance::Applies => Ok(()),
207        Stance::Excluded(reason) | Stance::Redundant { reason, .. } => {
208            Err(RkError::Usage(format!(
209                "{} is excluded by {}: {reason}; remove it from setup.excluded_steps to run it",
210                step.name,
211                crate::config::CONFIG_PATH
212            )))
213        }
214        // A step the target configuration does not select is refused
215        // rather than applied: the value that decided it is the answer,
216        // and changing the configuration is the auditable act.
217        Stance::NotApplicable(reason) => Err(RkError::refusal(
218            Diagnostic::new(
219                Reason::PrerequisiteUnmet,
220                format!("{} does not apply to this target: {reason}", step.name),
221            )
222            .expected("a target configuration that selects this step")
223            .action("rk profile --target . reports what this target resolves to")
224            .target_state("unchanged")
225            .step(step.name),
226        )),
227    }
228}
229
230/// On GitLab `--required-check` is a usage error, per the forge document:
231/// the forge requires the whole pipeline and names no individual check, and
232/// a flag silently discarded would read as configured while nothing uses it.
233///
234/// The same reason holds for the release gate's second answer, which the
235/// landing verbs refuse on GitLab for this one reason rather than a
236/// second of their own.
237fn reject_check_flag_on_gitlab(ctx: &Ctx) -> Result<(), RkError> {
238    if ctx.forge == Some(Forge::Gitlab) && ctx.required_check.is_some() {
239        return Err(RkError::Usage(
240            "--required-check is refused on gitlab: the forge requires the whole pipeline and names no individual check".into(),
241        ));
242    }
243    Ok(())
244}
245
246/// On GitHub the trunk protection needs the check name before any step
247/// runs: a wrong or missing one does not fail, it hangs the merge button,
248/// so a full apply refuses up front rather than writing eight steps and
249/// stopping. A target that excludes the protection is asked for nothing,
250/// because the value would answer a step this run never reaches, or one
251/// whose effective policy carries no required-check rule. Both integration
252/// modes normally carry that rule; local integration also renders the same
253/// name into its release gate. The landing verbs refuse an unanswered gate,
254/// while this prerequisite stays about the ruleset step.
255fn require_check_for(ctx: &Ctx, steps: &[&StepSpec]) -> Result<(), RkError> {
256    let needs = ctx.forge == Some(Forge::Github)
257        && ctx.required_check.is_none()
258        && ctx
259            .protection()
260            .owned_trunk_rules
261            .iter()
262            .any(|rule| rule == "required_status_checks")
263        && steps
264            .iter()
265            .any(|step| step.name == "protect-trunk" && stance(ctx, step).acts());
266    if needs {
267        return Err(RkError::refusal(
268            Diagnostic::new(
269                Reason::PrerequisiteUnmet,
270                "protect-trunk refuses until the required check is named, and nothing was written",
271            )
272            .expected("the name of the CI check the release merge must pass")
273            .action(format!(
274                "set setup.required_check in {}, or pass --required-check <name>; gh api repos/{}/commits/HEAD/check-runs lists the project's check names",
275                crate::config::CONFIG_PATH,
276                ctx.repo
277            ))
278            .step("protect-trunk"),
279        ));
280    }
281    Ok(())
282}
283
284/// `rk setup --list`: the ordered steps, what each proves, and which needs
285/// input on which forge — visible before a first apply rather than
286/// discovered by one.
287fn list(forge: Option<&str>) -> Result<(), RkError> {
288    let forge = forge
289        .map(|name| {
290            Forge::parse(name).ok_or_else(|| {
291                RkError::Usage(format!(
292                    "unknown forge '{name}'; the forges are: github, gitlab"
293                ))
294            })
295        })
296        .transpose()?;
297    let out = Output::human();
298    for (idx, step) in STEPS.iter().enumerate() {
299        let mut line = format!(
300            "{:2}. {} [{}] proves: {}",
301            idx + 1,
302            step.name,
303            step.chapter,
304            step.proves
305        );
306        if step.name == "protect-trunk" && forge != Some(Forge::Gitlab) {
307            line.push_str(" (needs --required-check on github)");
308        }
309        if step.destructive {
310            line.push_str(" (destructive)");
311        }
312        if step.optional {
313            line.push_str(" (optional; a full apply skips it)");
314        }
315        out.result_line(line);
316    }
317    out.next(&[
318        "rk setup --target . previews every step".to_owned(),
319        "rk setup script <name> prints one embedded script".to_owned(),
320    ]);
321    Ok(())
322}
323
324/// `rk setup script <name>`: the audit escape hatch, printed byte-identical
325/// to the embedded file.
326fn script(name: &str, forge: Option<&str>) -> Result<(), RkError> {
327    if name == "package-check" {
328        return Err(RkError::Usage(
329            "package-check reads its command from the technology binding and has no script".into(),
330        ));
331    }
332    if name == "branch-reminder" {
333        return Err(RkError::Usage(
334            "branch-reminder writes an embedded hook body and has no script; rk setup step branch-reminder previews the write".into(),
335        ));
336    }
337    if name == "forge-version" {
338        return Err(RkError::Usage(
339            "forge-version reads the forge's own version and has no script; rk setup step forge-version previews the read".into(),
340        ));
341    }
342    let forge = match forge {
343        Some(value) => Forge::parse(value).ok_or_else(|| {
344            RkError::Usage(format!(
345                "unknown forge '{value}'; the forges are: github, gitlab"
346            ))
347        })?,
348        None => Forge::Github,
349    };
350    let path = format!("{}/{name}", forge.as_str());
351    let file = embedded::SETUP.get_file(&path).ok_or(RkError::NotFound {
352        kind: "setup step",
353        name: name.to_owned(),
354    })?;
355    Output::human().result_raw(&String::from_utf8_lossy(file.contents()));
356    Ok(())
357}
358
359/// The shared run state: the boundary, the resolved context, the journal,
360/// and the event stream.
361struct Engine {
362    out: Output,
363    ctx: Ctx,
364    journal: Option<Journal>,
365    secrets: Vec<Zeroizing<Vec<u8>>>,
366    /// The run's one read of the named key file; see [`key_file_for`].
367    key: Option<secrets::KeyFile>,
368    /// The run's App JWT, minted at most once; see [`app_jwt_for`].
369    app_jwt: Option<String>,
370    /// Whether an unreachable key file is an observation boundary rather
371    /// than a refusal: true for a read-only check alone.
372    key_boundary: bool,
373    /// Why the named key file was unreachable, once a check found it so.
374    key_unavailable: Option<String>,
375    seq: u64,
376    command: &'static str,
377    run_id: String,
378    /// The run's snapshot directory, opened by the first step that saves
379    /// a before-state.
380    snapshot: Option<crate::snapshot::Snapshot>,
381}
382
383impl Engine {
384    /// Open the run: journal first, before any remote mutation. An apply
385    /// that cannot create its journal refuses; observability-only modes
386    /// warn and continue, because refusing them over observability is
387    /// self-defeating.
388    fn open(
389        out: Output,
390        ctx: Ctx,
391        command: &'static str,
392        journal_required: bool,
393    ) -> Result<Self, RkError> {
394        // A stale key export is refused wherever a run opens, so every
395        // mode catches it and not the one step that would have used it.
396        secrets::refuse_legacy_key()?;
397        let journal = match Journal::create(
398            command,
399            ctx.target.as_str(),
400            ctx.forge.map_or("none", Forge::as_str),
401            &ctx.repo,
402        ) {
403            Ok(journal) => Some(journal),
404            Err(source) if journal_required => {
405                return Err(RkError::refusal(
406                    Diagnostic::new(
407                        Reason::JournalUnavailable,
408                        format!("the run journal cannot be created: {source}"),
409                    )
410                    .expected("a writable state root for the journal")
411                    .target_state("nothing was run and nothing changed"),
412                ));
413            }
414            Err(source) => {
415                out.warn(format!("no run journal for this run: {source}"));
416                None
417            }
418        };
419        let run_id = journal
420            .as_ref()
421            .map_or_else(|| "unjournaled".to_owned(), |j| j.run_id().to_owned());
422        let mut engine = Self {
423            out,
424            ctx,
425            journal,
426            secrets: Ctx::secret_values(),
427            key: None,
428            app_jwt: None,
429            key_boundary: false,
430            key_unavailable: None,
431            seq: 0,
432            command,
433            run_id,
434            snapshot: None,
435        };
436        let opening = Event::opening(
437            engine.next_seq(),
438            crate::applog::now_utc(),
439            engine.run_id.clone(),
440            engine.command,
441        );
442        engine.emit(&opening);
443        if engine.ctx.self_hosted_gitlab() {
444            engine.out.warn(
445                "this remote is a self-hosted GitLab: registry trusted publishing covers GitLab.com only, so the OIDC invariant cannot be satisfied here",
446            );
447        }
448        Ok(engine)
449    }
450
451    const fn next_seq(&mut self) -> u64 {
452        let seq = self.seq;
453        self.seq += 1;
454        seq
455    }
456
457    fn event(&mut self, kind: EventKind, step: Option<&str>) -> Event {
458        let mut event = Event::opening(
459            self.next_seq(),
460            crate::applog::now_utc(),
461            self.run_id.clone(),
462            self.command,
463        );
464        event.kind = kind;
465        event.step = step.map(str::to_owned);
466        event
467    }
468
469    fn emit(&mut self, event: &Event) {
470        self.out.event(event);
471        if let Some(journal) = &mut self.journal
472            && let Ok(line) = serde_json::to_string(event)
473        {
474            journal.event_line(&line);
475        }
476    }
477
478    /// Run one external command: echo it, stream and redact its output,
479    /// journal everything, surface its exit.
480    fn exec(&mut self, exec: &Exec, passthrough: bool) -> Result<Outcome, RkError> {
481        let echo = exec.echo();
482        self.out.frame(&echo);
483        if let Some(journal) = &mut self.journal {
484            journal.transcript(echo.as_bytes());
485            journal.transcript(b"\n");
486        }
487        let secrets = std::mem::take(&mut self.secrets);
488        let step_name: Option<String> = None;
489        let mut chunks: Vec<(ChildStream, Vec<u8>)> = Vec::new();
490        let spawned = process::run(exec, |stream, chunk| {
491            chunks.push((stream, process::redact(chunk, &secrets)));
492        });
493        self.secrets = secrets;
494        for (stream, chunk) in chunks {
495            if passthrough {
496                self.out.child_passthrough(stream, &chunk);
497            }
498            let event = self.event(EventKind::ChildOutput, step_name.as_deref());
499            let event = event.child_output(stream, &chunk);
500            self.emit(&event);
501            if let Some(journal) = &mut self.journal {
502                journal.transcript(&chunk);
503            }
504        }
505        spawned.map_err(|source| {
506            RkError::refusal(
507                Diagnostic::new(
508                    Reason::SubprocessSpawn,
509                    format!("{} did not spawn: {source}", exec.program.to_string_lossy()),
510                )
511                .expected("a POSIX sh and the forge CLI on PATH")
512                .run(self.run_path()),
513            )
514        })
515    }
516
517    fn run_path(&self) -> String {
518        self.journal.as_ref().map_or_else(
519            || "no journal was written".to_owned(),
520            |j| j.dir.display().to_string(),
521        )
522    }
523
524    fn finish(&mut self, exit_code: i32, reason: Option<&str>) {
525        let mut event = self.event(EventKind::RunFinished, None);
526        event.exit_code = Some(exit_code);
527        event.status = Some(if exit_code == 0 {
528            "ok".into()
529        } else {
530            "failed".into()
531        });
532        self.emit(&event);
533        if let Some(journal) = &mut self.journal {
534            journal.finish(exit_code, reason);
535        }
536    }
537}
538
539/// Attach the failure to its run journal and close the run.
540fn fail(engine: &mut Engine, error: RkError) -> RkError {
541    let error = match error {
542        RkError::Refusal(mut diagnostic) => {
543            diagnostic.run.get_or_insert_with(|| engine.run_path());
544            RkError::Refusal(diagnostic)
545        }
546        RkError::Subprocess(mut diagnostic) => {
547            diagnostic.run.get_or_insert_with(|| engine.run_path());
548            RkError::Subprocess(diagnostic)
549        }
550        RkError::CheckFailed(mut diagnostic) => {
551            diagnostic.run.get_or_insert_with(|| engine.run_path());
552            RkError::CheckFailed(diagnostic)
553        }
554        other => other,
555    };
556    engine.finish(i32::from(error.exit_code()), Some(error.reason().as_str()));
557    error
558}
559
560/// Preview: walk the ordered steps and print, for each, the step name, what
561/// it proves, and the resolved invocation — without materializing anything
562/// and without invoking any external command. What preview shows is what
563/// apply would run, because both read the same step table and environment
564/// construction.
565fn preview(out: Output, ctx: &Ctx, steps: &[&StepSpec]) -> Result<(), RkError> {
566    let mut engine = Engine::open(out, clone_ctx(ctx), "setup preview", false)?;
567    out.result_line(format!(
568        "DRY RUN: rk setup would run these steps against {} on {}; re-run with --apply",
569        engine.ctx.repo,
570        engine.ctx.forge.map_or("no forge", Forge::as_str)
571    ));
572    for (idx, step) in steps.iter().enumerate() {
573        out.result_line(format!(
574            "step {}/{} {} — proves {}",
575            idx + 1,
576            steps.len(),
577            step.name,
578            step.proves
579        ));
580        let stance = stance(&engine.ctx, step);
581        if !stance.acts() {
582            out.result_line(format!("  {}", stance.framed()));
583            let mut event = engine.event(EventKind::StepFinished, Some(step.name));
584            event.status = Some(stance.word().into());
585            event.detail = Some(stance.detail());
586            engine.emit(&event);
587            continue;
588        }
589        // Preview is the rehearsal of apply, so a credential apply could
590        // not use is a preview failure: the operator learns it here rather
591        // than one flag later, and before an invocation is claimed.
592        if step.name == "bot-secrets" && engine.ctx.forge == Some(Forge::Github) {
593            secrets::resolve_key_file(&engine.ctx.target)?;
594        }
595        out.result_line(format!("  {}", render_invocation(&engine.ctx, step)));
596        // The name is asked for only where a rule consumes it. It feeds the
597        // required-status-checks rule alone, and local integration owns no
598        // such rule, because no forge can require a check before the push
599        // that starts it. Asking there would name a flag whose value reaches
600        // nothing the run installs.
601        if step.name == "protect-trunk"
602            && engine.ctx.forge == Some(Forge::Github)
603            && engine.ctx.required_check.is_none()
604            && engine
605                .ctx
606                .protection()
607                .owned_trunk_rules
608                .iter()
609                .any(|rule| rule == "required_status_checks")
610        {
611            out.result_line("  needs: --required-check <name> before apply");
612        }
613        if skipped_by_a_full_run(&engine.ctx, step, steps.len()) {
614            out.result_line(format!(
615                "  optional: a full apply skips it; set setup.release_lines, or rk setup step {} --apply runs it",
616                step.name
617            ));
618        }
619        let mut event = engine.event(EventKind::StepFinished, Some(step.name));
620        event.status = Some("previewed".into());
621        engine.emit(&event);
622    }
623    let next = next_for_apply(&engine.ctx, steps);
624    out.next(&[
625        next,
626        "rk setup check --target . proves what is already true".to_owned(),
627    ]);
628    engine.finish(0, None);
629    Ok(())
630}
631
632/// The one line preview prints per step: the exact spawn shape, with every
633/// non-secret variable resolved.
634fn render_invocation(ctx: &Ctx, step: &StepSpec) -> String {
635    match step.name {
636        "branch-reminder" => {
637            "would write: the post-merge reminder hook at $(git rev-parse --git-path hooks)/post-merge".to_owned()
638        }
639        "package-check" => match ctx.tech {
640            Some("rust") if ctx.reporting_policy() => "would run: cargo publish --dry-run --allow-dirty, then cargo metadata --no-deps --format-version 1, then cargo package --list --allow-dirty for a single default package rooted at the target, asserting it carries SECURITY.md and none of release-kit's own files; another workspace shape reports both as unproved".to_owned(),
641            Some("rust") => "would run: cargo publish --dry-run --allow-dirty, then cargo metadata --no-deps --format-version 1, then cargo package --list --allow-dirty for a single default package rooted at the target, asserting it ships none of release-kit's own files; another workspace shape reports that as unproved".to_owned(),
642            Some("python") if ctx.reporting_policy() => "would run: python3 -m build; sdist and wheel SECURITY.md inclusion stays unproved".to_owned(),
643            Some("python") => "would run: python3 -m build".to_owned(),
644            Some("bash") if ctx.reporting_policy() => "nothing to run: no registry for this technology; the make dist tarball is not inspected".to_owned(),
645            Some("bash") => "nothing to run: no registry for this technology".to_owned(),
646            _ => "needs: a version file naming the technology".to_owned(),
647        },
648        "forge-version" => {
649            let (major, minor) = observe::GITLAB_VERSION_FLOOR;
650            match ctx.forge {
651                Some(Forge::Github) => {
652                    "nothing to read: github.com is a rolling service and declares no version floor"
653                        .to_owned()
654                }
655                Some(Forge::Gitlab) => format!(
656                    "would read: GET /version, and compare it against the {major}.{minor} floor; nothing is written"
657                ),
658                None => "nothing to read: the profile names no forge".to_owned(),
659            }
660        }
661        name => {
662            let check = ctx
663                .required_check
664                .as_ref()
665                .filter(|_| ctx.forge == Some(Forge::Github) && name == "protect-trunk")
666                .map(|value| format!(" RK_REQUIRED_CHECK={value}"))
667                .unwrap_or_default();
668            // The ruleset a protection step installs is the one
669            // per-target fact the operator most needs to see before an
670            // apply, because a renamed ruleset leaves the old one standing.
671            let ruleset = match name {
672                "protect-trunk" => format!(
673                    " RK_TRUNK_RULESET={} RK_SAFETY_RULESET={} RK_TITLE_CHECK={}",
674                    ctx.trunk_ruleset(),
675                    ctx.safety_ruleset(),
676                    ctx.title_check()
677                ),
678                "protect-tags" => format!(" RK_TAG_RULESET={}", ctx.tag_ruleset()),
679                "protect-release-lines" => format!(" RK_LINES_RULESET={}", ctx.lines_ruleset()),
680                _ => String::new(),
681            };
682            format!(
683                "would run: sh <embedded setup/{}/{name}> with RK_REPO={} RK_TRUNK_BRANCH={}{ruleset}{check}",
684                ctx.forge.map_or("<no forge>", Forge::as_str),
685                ctx.repo,
686                ctx.trunk()
687            )
688        }
689    }
690}
691
692fn next_for_apply(ctx: &Ctx, steps: &[&StepSpec]) -> String {
693    let check = ctx
694        .required_check
695        .as_ref()
696        .map(|value| format!(" --required-check {value}"))
697        .unwrap_or_default();
698    if steps.len() == 1 {
699        format!(
700            "rk setup step {} --target {} --apply{check}",
701            steps[0].name, ctx.target
702        )
703    } else {
704        format!("rk setup --target {} --apply{check}", ctx.target)
705    }
706}
707
708/// A `Ctx` copy for engine ownership; the context is plain data.
709fn clone_ctx(ctx: &Ctx) -> Ctx {
710    ctx.clone()
711}
712
713/// Apply: run the selected steps in order, each through the full lifecycle.
714fn execute(
715    out: Output,
716    ctx: Ctx,
717    steps: &[&StepSpec],
718    command: &'static str,
719) -> Result<(), RkError> {
720    guard_sh()?;
721    let mut engine = Engine::open(out, ctx, command, true)?;
722    let mut done: Vec<(String, String)> = Vec::new();
723    for (idx, step) in steps.iter().enumerate() {
724        // A declared exclusion states the skip and runs nothing. A single
725        // step named on the command line never arrives here: that form
726        // refuses before the run opens.
727        let stance = stance(&engine.ctx, step);
728        if !stance.acts() {
729            engine.out.frame(format!(
730                "step {}/{} {} — {}",
731                idx + 1,
732                steps.len(),
733                step.name,
734                stance.framed()
735            ));
736            let mut finished = engine.event(EventKind::StepFinished, Some(step.name));
737            finished.status = Some(stance.word().into());
738            finished.detail = Some(stance.detail());
739            engine.emit(&finished);
740            done.push((step.name.to_owned(), stance.word().to_owned()));
741            continue;
742        }
743        // An optional step applies only by name: a full run states the skip
744        // rather than acting on a condition the operator never asserted.
745        if skipped_by_a_full_run(&engine.ctx, step, steps.len()) {
746            engine.out.frame(format!(
747                "step {}/{} {} — skipped (optional; set setup.release_lines, or rk setup step {} --apply runs it)",
748                idx + 1,
749                steps.len(),
750                step.name,
751                step.name
752            ));
753            let mut finished = engine.event(EventKind::StepFinished, Some(step.name));
754            finished.status = Some("skipped".into());
755            engine.emit(&finished);
756            done.push((step.name.to_owned(), "skipped".to_owned()));
757            continue;
758        }
759        engine.out.frame(format!(
760            "step {}/{} {} — {}",
761            idx + 1,
762            steps.len(),
763            step.name,
764            step.proves
765        ));
766        let mut started = engine.event(EventKind::StepStarted, Some(step.name));
767        started.status = Some("running".into());
768        engine.emit(&started);
769        let clock = Instant::now();
770        let status = match apply_step(&mut engine, step) {
771            Ok(status) => status,
772            Err(error) => {
773                let error = attach_progress(error, &done, step, steps);
774                let mut finished = engine.event(EventKind::StepFinished, Some(step.name));
775                finished.status = Some("failed".into());
776                finished.reason = Some(error.reason());
777                finished.duration_ms = Some(elapsed_ms(clock));
778                engine.emit(&finished);
779                return Err(fail(&mut engine, error));
780            }
781        };
782        engine.out.frame(format!(
783            "{} {}: {}",
784            if matches!(status, Done::Skipped(_)) {
785                "skipped"
786            } else {
787                "ok"
788            },
789            step.name,
790            status.line()
791        ));
792        let mut finished = engine.event(EventKind::StepFinished, Some(step.name));
793        finished.status = Some(status.wire().into());
794        finished.detail = Some(status.line());
795        finished.exit_code = Some(0);
796        finished.duration_ms = Some(elapsed_ms(clock));
797        engine.emit(&finished);
798        done.push((step.name.to_owned(), status.wire().to_owned()));
799    }
800    engine.out.result_line(format!(
801        "setup: {} completed against {}",
802        step_count(done.len()),
803        engine.ctx.repo
804    ));
805    for (name, status) in &done {
806        engine.out.result_line(format!("  {status} {name}"));
807    }
808    engine.out.next(&[
809        format!("rk setup check --target {}", engine.ctx.target),
810        "rk guide setup orders what no command performs".to_owned(),
811    ]);
812    engine.finish(0, None);
813    Ok(())
814}
815
816/// A step count rendered with the noun that agrees with it, so no summary
817/// line can regrow a dangling plural.
818fn step_count(count: usize) -> String {
819    format!("{count} {}", if count == 1 { "step" } else { "steps" })
820}
821
822fn elapsed_ms(clock: Instant) -> u64 {
823    u64::try_from(clock.elapsed().as_millis()).unwrap_or(u64::MAX)
824}
825
826/// What one applied step reported.
827enum Done {
828    /// The desired state already held; nothing ran.
829    Satisfied(String),
830    /// The target is ineligible for this step.
831    Skipped(String),
832    /// The script ran and the postcondition was read back.
833    Changed(String, Option<String>),
834    /// A read-only step ran and passed.
835    Passed(String),
836}
837
838impl Done {
839    const fn wire(&self) -> &'static str {
840        match self {
841            Self::Satisfied(_) => "satisfied",
842            Self::Skipped(_) => "skipped",
843            Self::Changed(..) => "applied",
844            Self::Passed(_) => "passed",
845        }
846    }
847
848    fn line(&self) -> String {
849        match self {
850            Self::Satisfied(detail) | Self::Passed(detail) | Self::Skipped(detail) => {
851                detail.clone()
852            }
853            Self::Changed(detail, limitation) => limitation.as_ref().map_or_else(
854                || detail.clone(),
855                |limit| format!("{detail} (limitation: {limit})"),
856            ),
857        }
858    }
859}
860
861/// One step, full lifecycle.
862#[allow(
863    clippy::too_many_lines,
864    reason = "one step is observe, compare, apply, and verify in one place, and splitting it would separate a verdict from the observation it rests on"
865)]
866fn apply_step(engine: &mut Engine, step: &StepSpec) -> Result<Done, RkError> {
867    // Prerequisites are observed, not remembered: the forge is the
868    // authority on whether an earlier step's state holds.
869    for prereq in step.prereqs {
870        let state = observe_with(engine, prereq)?;
871        if !state.satisfied() {
872            return Err(RkError::refusal(
873                Diagnostic::new(
874                    Reason::PrerequisiteUnmet,
875                    format!(
876                        "{} requires {prereq} first: {}",
877                        step.name,
878                        state_detail(&state)
879                    ),
880                )
881                .expected(format!("{prereq} satisfied before {}", step.name))
882                .action(format!(
883                    "rk setup step {prereq} --target {} --apply",
884                    engine.ctx.target
885                ))
886                .step(step.name),
887            ));
888        }
889    }
890    match step.name {
891        "package-check" => {
892            if engine.ctx.tech.is_none() {
893                return Err(RkError::Usage(
894                    "no version file names a technology; rk binding --list names the bindings"
895                        .into(),
896                ));
897            }
898            let state = observe_with(engine, "package-check")?;
899            match state {
900                StepState::Satisfied { detail, .. } => Ok(Done::Passed(detail)),
901                StepState::Unsatisfied { detail } | StepState::Inapplicable { detail } => {
902                    Err(RkError::subprocess(
903                        Diagnostic::new(
904                            Reason::SubprocessFailed,
905                            format!("package-check failed: {detail}"),
906                        )
907                        .expected(step.proves.to_owned())
908                        .step(step.name),
909                    ))
910                }
911                StepState::Unknown { detail } => Err(RkError::subprocess(
912                    Diagnostic::new(
913                        Reason::SubprocessFailed,
914                        format!("package-check could not run: {detail}"),
915                    )
916                    .step(step.name),
917                )),
918            }
919        }
920        // The step mutates nothing, so apply and check read the same answer
921        // and apply writes nothing at all. An unreadable version is a
922        // refusal, never a pass: the floor exists to stop a protection the
923        // forge cannot honor, and a floor nobody could read proves neither
924        // way.
925        "forge-version" => match observe_with(engine, "forge-version")? {
926            StepState::Satisfied { detail, .. } => Ok(Done::Satisfied(detail)),
927            StepState::Unsatisfied { detail } | StepState::Inapplicable { detail } => {
928                Err(RkError::refusal(
929                    Diagnostic::new(Reason::PrerequisiteUnmet, detail)
930                        .expected(step.proves.to_owned())
931                        .action("upgrade the instance, or host the project on gitlab.com")
932                        .target_state("unchanged")
933                        .step(step.name),
934                ))
935            }
936            StepState::Unknown { detail } => Err(RkError::refusal(
937                Diagnostic::new(Reason::ForgeTemporary, detail)
938                    .expected("a readable forge version")
939                    .action("glab auth login, then rerun")
940                    .target_state("unchanged")
941                    .step(step.name),
942            )),
943        },
944        "branch-reminder" => {
945            use crate::setup::branch_reminder::{HookState, hook_body, hook_path, observe_hook};
946            match observe_hook(&engine.ctx.target) {
947                HookState::Installed => Ok(Done::Satisfied(
948                    "the post-merge reminder hook is installed".into(),
949                )),
950                HookState::Foreign => Err(RkError::refusal(
951                    Diagnostic::new(
952                        Reason::StateDrift,
953                        "a foreign post-merge hook exists; the reminder is never written over it",
954                    )
955                    .expected("no post-merge hook, or one carrying the release-kit marker")
956                    .action(
957                        "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`",
958                    )
959                    .target_state("unchanged")
960                    .step(step.name),
961                )),
962                HookState::Unreadable(detail) => Err(RkError::refusal(
963                    Diagnostic::new(
964                        Reason::StateDrift,
965                        format!("the post-merge hook cannot be read: {detail}"),
966                    )
967                    .target_state("unchanged")
968                    .step(step.name),
969                )),
970                HookState::Absent | HookState::Drifted => {
971                    let path = hook_path(&engine.ctx.target).map_err(|detail| {
972                        RkError::refusal(
973                            Diagnostic::new(
974                                Reason::PrerequisiteUnmet,
975                                format!("the hooks directory cannot be resolved: {detail}"),
976                            )
977                            .expected("a git repository whose hooks directory git can name")
978                            .step(step.name),
979                        )
980                    })?;
981                    crate::atomic::write(&path, hook_body())?;
982                    #[cfg(unix)]
983                    {
984                        use std::os::unix::fs::PermissionsExt as _;
985                        std::fs::set_permissions(
986                            &path,
987                            std::fs::Permissions::from_mode(0o755),
988                        )?;
989                    }
990                    Ok(Done::Changed(
991                        "wrote the post-merge reminder hook".into(),
992                        None,
993                    ))
994                }
995            }
996        }
997        "single-trunk" => {
998            let guard = {
999                let ctx = clone_ctx(&engine.ctx);
1000                let mut runner = |exec: &Exec| engine.exec(exec, false);
1001                observe::single_trunk_guard(&ctx, &mut runner)?
1002            };
1003            // A destructive step fails closed: an ancestry the guard cannot
1004            // establish is treated exactly like one it refuted.
1005            match &guard {
1006                StepState::Satisfied { .. } => {}
1007                StepState::Unsatisfied { detail }
1008                | StepState::Inapplicable { detail }
1009                | StepState::Unknown { detail } => {
1010                    return Err(RkError::refusal(
1011                        Diagnostic::new(
1012                            Reason::DestructiveRefusal,
1013                            format!("single-trunk refuses: {detail}"),
1014                        )
1015                        .expected(
1016                            "proof that every candidate branch is absent, or an ancestor of the trunk",
1017                        )
1018                        .step(step.name),
1019                    ));
1020                }
1021            }
1022            run_forge_step(engine, step)
1023        }
1024        "bot-secrets" => {
1025            // Validate before observing: a wrong path or a wrong mode is
1026            // the operator's answer either way, and the refusal costs no
1027            // forge call. Only GitHub reads a key file; GitLab's credential
1028            // is a token, and its step must not fail over a variable it
1029            // never consumes.
1030            let adapter = engine.ctx.adapter()?;
1031            let key = match adapter {
1032                // The run's one read: an install-bot observation earlier in
1033                // this run already holds the bytes, and this step stores
1034                // those very bytes rather than reopening the path.
1035                Forge::Github => key_file_for(engine)?.map(|key| key.bytes.clone()),
1036                Forge::Gitlab => None,
1037            };
1038            let provided = match adapter {
1039                // Both halves of an App identity, or neither: a run holding
1040                // only one of them would store half a credential.
1041                Forge::Github => secrets::value_of("RK_BOT_APP_ID").is_some() && key.is_some(),
1042                Forge::Gitlab => secrets::value_of("RK_BOT_TOKEN").is_some(),
1043            };
1044            let state = observe_with(engine, step.name)?;
1045            if !provided {
1046                if state.satisfied() {
1047                    return Ok(Done::Satisfied(state_detail(&state)));
1048                }
1049                let wanted = match adapter {
1050                    Forge::Github => {
1051                        "export RK_BOT_APP_ID and RK_BOT_PRIVATE_KEY_FILE, the second naming the .pem; rk forge github carries the walkthrough"
1052                    }
1053                    Forge::Gitlab => {
1054                        "rk setup step install-bot --apply stores the token, or export RK_BOT_TOKEN to rotate one"
1055                    }
1056                };
1057                return Err(RkError::refusal(
1058                    Diagnostic::new(
1059                        Reason::PrerequisiteUnmet,
1060                        "bot-secrets has no credentials to store",
1061                    )
1062                    .expected("the bot credentials in the environment, the key as a path")
1063                    .action(wanted.to_owned())
1064                    .step(step.name),
1065                ));
1066            }
1067            if let Some(journal) = &mut engine.journal {
1068                for name in SECRET_VARS {
1069                    if secrets::value_of(name).is_some() {
1070                        journal.record_secret(name, true, "environment");
1071                    }
1072                }
1073                if key.is_some() {
1074                    journal.record_secret(secrets::PRIVATE_KEY_FILE, true, "file");
1075                }
1076            }
1077            // The bytes rk validated are the bytes the child receives and
1078            // the bytes the redactor holds: one read, one value, so nothing
1079            // can be substituted between the check and the forge.
1080            let stdin = key;
1081            run_forge_step_with(engine, step, stdin, Vec::new())
1082        }
1083        "protections-check" => {
1084            let (outcome, _) = run_script(engine, step)?;
1085            if !outcome.success() {
1086                return Err(classify_failure(engine, step, &outcome));
1087            }
1088            // The script is the operator-auditable mirror; the observation
1089            // is the authoritative shape check, so the step passes only
1090            // when both agree.
1091            match observe_with(engine, step.name)? {
1092                StepState::Satisfied { detail, limitation } => {
1093                    Ok(Done::Passed(limitation.map_or_else(
1094                        || detail.clone(),
1095                        |limit| format!("{detail} (limitation: {limit})"),
1096                    )))
1097                }
1098                StepState::Unsatisfied { detail } | StepState::Inapplicable { detail } => {
1099                    Err(RkError::refusal(
1100                        Diagnostic::new(
1101                            Reason::StateDrift,
1102                            format!("protections-check passed its script and the observation disagrees: {detail}"),
1103                        )
1104                        .expected(step.proves.to_owned())
1105                        .step(step.name),
1106                    ))
1107                }
1108                // An unreadable readback is a retryable outage, not drift,
1109                // exactly as the postcondition lifecycle classifies it.
1110                StepState::Unknown { detail } => Err(RkError::refusal(
1111                    Diagnostic::new(
1112                        Reason::ForgeTemporary,
1113                        format!(
1114                            "protections-check passed its script and the readback could not confirm it: {detail}"
1115                        ),
1116                    )
1117                    .expected(step.proves.to_owned())
1118                    .action("check authentication and connectivity, then rerun")
1119                    .step(step.name),
1120                )),
1121            }
1122        }
1123        // GitHub's grant is the one write the forge offers a command, and
1124        // it takes a user credential; everything else here — the pre- and
1125        // post-observation, and the installation id the script is handed —
1126        // happens as the App itself. GitLab's install-bot needs none of
1127        // this and takes the generic lifecycle below.
1128        "install-bot" if engine.ctx.forge == Some(Forge::Github) => {
1129            match observe_with(engine, step.name)? {
1130                StepState::Satisfied { detail, .. } => {
1131                    return Ok(Done::Satisfied(detail));
1132                }
1133                StepState::Unsatisfied { .. } | StepState::Inapplicable { .. } => {}
1134                StepState::Unknown { detail } => {
1135                    return Err(RkError::refusal(
1136                        Diagnostic::new(
1137                            Reason::ForgeTemporary,
1138                            format!("{} cannot observe the current state: {detail}", step.name),
1139                        )
1140                        .expected("a readable forge answer before anything mutates")
1141                        .action("check the App credentials and connectivity, then rerun")
1142                        .step(step.name),
1143                    ));
1144                }
1145            }
1146            let installation = github_installation_id(engine, step)?;
1147            run_forge_step_with(
1148                engine,
1149                step,
1150                None,
1151                vec![("RK_BOT_INSTALLATION".into(), installation.into())],
1152            )
1153        }
1154        _ => {
1155            if step.mutates == Mutates::Forge {
1156                // The lifecycle applies only on a state it has read: an
1157                // observation that cannot decide fails closed here exactly
1158                // as it does after the write, so no mutation ever rides on
1159                // an unreadable forge answer.
1160                match observe_with(engine, step.name)? {
1161                    StepState::Satisfied { detail, limitation } => {
1162                        let detail = if step.name == "private-vulnerability-reporting" {
1163                            limitation.map_or_else(
1164                                || detail.clone(),
1165                                |limit| format!("{detail} (limitation: {limit})"),
1166                            )
1167                        } else {
1168                            detail
1169                        };
1170                        return Ok(Done::Satisfied(detail));
1171                    }
1172                    StepState::Inapplicable { detail }
1173                        if step.name == "private-vulnerability-reporting" =>
1174                    {
1175                        return Ok(Done::Skipped(detail));
1176                    }
1177                    StepState::Unsatisfied { .. } | StepState::Inapplicable { .. } => {}
1178                    StepState::Unknown { detail } => {
1179                        return Err(RkError::refusal(
1180                            Diagnostic::new(
1181                                Reason::ForgeTemporary,
1182                                format!("{} cannot observe the current state: {detail}", step.name),
1183                            )
1184                            .expected("a readable forge answer before anything mutates")
1185                            .action("check authentication and connectivity, then rerun")
1186                            .step(step.name),
1187                        ));
1188                    }
1189                }
1190            }
1191            run_forge_step(engine, step)
1192        }
1193    }
1194}
1195
1196/// The id of the App's installation on this repository's owner, read as
1197/// the App itself. The grant needs it, and no user credential can read
1198/// it: the observation that just ran answered 404, so the repository
1199/// endpoint that names the id directly has nothing to say yet. The
1200/// account-level installation is a direct read for either account kind —
1201/// the user endpoint answers for a person, the organization endpoint for
1202/// an organization — so nothing here lists or paginates.
1203fn github_installation_id(engine: &mut Engine, step: &StepSpec) -> Result<String, RkError> {
1204    let refuse = |message: String, action: &str| {
1205        RkError::refusal(
1206            Diagnostic::new(Reason::PrerequisiteUnmet, message)
1207                .expected("the App installed on the repository's owner")
1208                .action(action.to_owned())
1209                .step(step.name),
1210        )
1211    };
1212    let jwt = match app_jwt_for(engine)? {
1213        Ok(jwt) => jwt,
1214        Err(detail) => {
1215            return Err(refuse(
1216                format!("install-bot has no App token: {detail}"),
1217                app_jwt::REMEDIATION,
1218            ));
1219        }
1220    };
1221    let owner = engine
1222        .ctx
1223        .repo
1224        .split('/')
1225        .next()
1226        .unwrap_or_default()
1227        .to_owned();
1228    let ctx = clone_ctx(&engine.ctx);
1229    for path in [
1230        format!("users/{owner}/installation"),
1231        format!("orgs/{owner}/installation"),
1232    ] {
1233        match app_jwt::api_get(&ctx, &jwt, &path) {
1234            AppApi::Ok(body) => {
1235                return body["id"].as_i64().map(|id| id.to_string()).ok_or_else(|| {
1236                    refuse(
1237                        format!("the forge answered {path} without an installation id"),
1238                        "check RK_BOT_APP_ID and the key file name the same App",
1239                    )
1240                });
1241            }
1242            AppApi::Missing => {}
1243            AppApi::Refused(detail) => {
1244                return Err(refuse(
1245                    detail,
1246                    "check RK_BOT_APP_ID and the key file name the same App",
1247                ));
1248            }
1249            AppApi::Failed(detail) => {
1250                return Err(RkError::refusal(
1251                    Diagnostic::new(
1252                        Reason::ForgeTemporary,
1253                        format!("install-bot cannot read the App's installation: {detail}"),
1254                    )
1255                    .action("check connectivity, then rerun")
1256                    .step(step.name),
1257                ));
1258            }
1259        }
1260    }
1261    Err(refuse(
1262        format!("the App has no installation on {owner}"),
1263        "install the App on the account first; the setup guide's step 5 walks it",
1264    ))
1265}
1266
1267/// Materialize, spawn, classify, and verify one forge-mutating step.
1268fn run_forge_step(engine: &mut Engine, step: &StepSpec) -> Result<Done, RkError> {
1269    run_forge_step_with(engine, step, None, Vec::new())
1270}
1271
1272/// The same, with bytes written to the step's standard input and values
1273/// `rk` derived added to its environment.
1274fn run_forge_step_with(
1275    engine: &mut Engine,
1276    step: &StepSpec,
1277    stdin: Option<Zeroizing<Vec<u8>>>,
1278    extra_env: Vec<(OsString, OsString)>,
1279) -> Result<Done, RkError> {
1280    if crate::setup::before_state::destructive(step.name) {
1281        save_before_state(engine, step)?;
1282    }
1283    let (outcome, _) = run_script_with(engine, step, stdin, extra_env)?;
1284    if !outcome.success() {
1285        return Err(classify_failure(engine, step, &outcome));
1286    }
1287    let state = observe_with(engine, step.name)?;
1288    match state {
1289        StepState::Satisfied { detail, limitation } => Ok(Done::Changed(detail, limitation)),
1290        StepState::Inapplicable { detail } if step.name == "private-vulnerability-reporting" => {
1291            Ok(Done::Skipped(detail))
1292        }
1293        StepState::Unsatisfied { detail } | StepState::Inapplicable { detail } => {
1294            Err(RkError::refusal(
1295                Diagnostic::new(
1296                    Reason::StateDrift,
1297                    format!(
1298                        "{} ran and its postcondition does not hold: {detail}",
1299                        step.name
1300                    ),
1301                )
1302                .expected(step.proves.to_owned())
1303                .step(step.name),
1304            ))
1305        }
1306        // The lifecycle ends with a proven postcondition; a readback that
1307        // cannot run leaves the step unproven, and an unproven apply is a
1308        // failure a retry can cure, never a success.
1309        StepState::Unknown { detail } => Err(RkError::refusal(
1310            Diagnostic::new(
1311                Reason::ForgeTemporary,
1312                format!(
1313                    "{} ran and the readback could not confirm it: {detail}",
1314                    step.name
1315                ),
1316            )
1317            .expected(step.proves.to_owned())
1318            .action(format!(
1319                "rk setup step {} --target {} --apply re-asserts and re-proves it",
1320                step.name, engine.ctx.target
1321            ))
1322            .step(step.name),
1323        )),
1324    }
1325}
1326
1327/// Save what `step` is about to change, before its script runs, and name
1328/// the path in the human report and the event stream.
1329///
1330/// SATISFIES forge-setup:a-step-is-idempotent
1331fn save_before_state(engine: &mut Engine, step: &StepSpec) -> Result<(), RkError> {
1332    // During a migration the archive took the before-state of every
1333    // destructive step, on a host that could read the forge. The step runs
1334    // only where the registry holds that snapshot, and the archive's copy
1335    // stays the record of what the forge held before the migration.
1336    if let Some(held) = migration_snapshot(&engine.ctx.target, step.name)? {
1337        engine.out.result_line(format!(
1338            "the migration holds the before-state of {} at {held}",
1339            step.name
1340        ));
1341        let mut event = engine.event(EventKind::Snapshot, Some(step.name));
1342        event.detail = Some(held);
1343        engine.emit(&event);
1344        return Ok(());
1345    }
1346    let snapshot = if let Some(snapshot) = &engine.snapshot {
1347        snapshot.clone()
1348    } else {
1349        let canonical = std::fs::canonicalize(engine.ctx.target.as_std_path())?;
1350        let snapshot = crate::snapshot::Snapshot::begin(&canonical)?;
1351        engine.snapshot = Some(snapshot.clone());
1352        snapshot
1353    };
1354    let ctx = clone_ctx(&engine.ctx);
1355    let mut runner = |exec: &Exec| engine.exec(exec, false);
1356    let path = crate::setup::before_state::save(&ctx, step.name, &snapshot, &mut runner)?;
1357    let path = path.display().to_string();
1358    engine
1359        .out
1360        .result_line(format!("saved the before-state of {} to {path}", step.name));
1361    let mut event = engine.event(EventKind::Snapshot, Some(step.name));
1362    event.detail = Some(path);
1363    engine.emit(&event);
1364    Ok(())
1365}
1366
1367/// The registry id of a destructive step's forge snapshot.
1368#[must_use]
1369pub fn forge_snapshot_id(step: &str) -> String {
1370    format!("forge-{step}")
1371}
1372
1373/// Where an open migration holds the before-state of `step`, or `None`
1374/// where no migration is open.
1375///
1376/// # Errors
1377///
1378/// A `destructive-refusal` while a migration is open and its registry
1379/// holds no intact snapshot of the step, and a refusal where the workspace is not
1380/// on this host.
1381fn migration_snapshot(target: &camino::Utf8Path, step: &str) -> Result<Option<String>, RkError> {
1382    let Some(id) = crate::migrate::open_id(target)? else {
1383        return Ok(None);
1384    };
1385    let Some(workspace) = crate::migrate::open_workspace(target)? else {
1386        return Err(crate::migrate::none_open());
1387    };
1388    if !workspace.join(crate::migrate::REGISTRY_FILE).is_file() {
1389        return Err(crate::migrate::workspace_missing(&id, &workspace));
1390    }
1391    let registry = crate::migrate::registry::load(&workspace)?;
1392    let wanted = forge_snapshot_id(step);
1393    // A snapshot whose file is gone or altered restores nothing, so it
1394    // licenses nothing either; one that cannot be read stops the step.
1395    let found = registry
1396        .snapshots
1397        .iter()
1398        .find(|snapshot| snapshot.id == wanted);
1399    let intact = match found {
1400        Some(snapshot) => {
1401            crate::migrate::registry::integrity(&workspace, snapshot)?
1402                == crate::migrate::registry::Integrity::Intact
1403        }
1404        None => false,
1405    };
1406    let Some(snapshot) = found.filter(|_| intact) else {
1407        return Err(RkError::refusal(
1408            Diagnostic::new(
1409                Reason::DestructiveRefusal,
1410                format!(
1411                    "{step} changes forge state, and the migration {id} holds no intact snapshot of it (migration:a-destructive-step-waits-for-its-snapshot)"
1412                ),
1413            )
1414            .expected("the step's before-state in the migration registry")
1415            .action("rk migrate archive --apply --target . takes the missing forge snapshots on a host that holds the forge credentials")
1416            .target_state("unchanged")
1417            .step(step),
1418        ));
1419    };
1420    Ok(Some(workspace.join(&snapshot.file).to_string()))
1421}
1422
1423/// One destructive step's forge snapshot, as the archive took it.
1424#[derive(Debug, Clone, PartialEq, Eq)]
1425pub enum ForgeSnapshot {
1426    /// The before-state is saved at this path.
1427    Taken(PathBuf),
1428    /// The before-state could not be read from where this ran.
1429    Unknown(String),
1430}
1431
1432/// Take the before-state of every destructive step this target runs into
1433/// `snapshot`, for a migration's archive.
1434///
1435/// A step whose state this host cannot read reads unknown and stays
1436/// refused until a host that can takes it; `skip` names the steps already
1437/// held.
1438///
1439/// # Errors
1440///
1441/// A target configuration that does not resolve.
1442pub fn migration_snapshots(
1443    target: &camino::Utf8PathBuf,
1444    snapshot: &crate::snapshot::Snapshot,
1445    skip: &[String],
1446) -> Result<Vec<(&'static str, ForgeSnapshot)>, RkError> {
1447    let mut ctx = Ctx::resolve(target, None, None, None)?;
1448    let steps: Vec<&StepSpec> = STEPS
1449        .iter()
1450        .filter(|step| {
1451            crate::setup::before_state::destructive(step.name)
1452                && stance(&ctx, step).acts()
1453                && !skip.contains(&forge_snapshot_id(step.name))
1454        })
1455        .collect();
1456    if steps.is_empty() {
1457        return Ok(Vec::new());
1458    }
1459    if let Err(error) = ctx.require_cli(&steps) {
1460        return Ok(steps
1461            .iter()
1462            .map(|step| (step.name, ForgeSnapshot::Unknown(error.to_string())))
1463            .collect());
1464    }
1465    // The archive's own report is the result; the engine's framing goes
1466    // to stderr and its events nowhere, so a JSON report stays one object.
1467    let mut engine = Engine::open(Output::new(false), ctx, "migrate", false)?;
1468    let mut out = Vec::new();
1469    for step in steps {
1470        let ctx = clone_ctx(&engine.ctx);
1471        let mut runner = |exec: &Exec| engine.exec(exec, false);
1472        let taken = match crate::setup::before_state::save(&ctx, step.name, snapshot, &mut runner) {
1473            Ok(path) => ForgeSnapshot::Taken(path),
1474            Err(error) => ForgeSnapshot::Unknown(error.to_string()),
1475        };
1476        out.push((step.name, taken));
1477    }
1478    Ok(out)
1479}
1480
1481/// The destructive steps this target runs, offline: the steps whose
1482/// before-state a migration must hold.
1483///
1484/// # Errors
1485///
1486/// A target configuration that does not resolve.
1487pub fn destructive_steps(target: &camino::Utf8PathBuf) -> Result<Vec<&'static str>, RkError> {
1488    let ctx = Ctx::resolve(target, None, None, None)?;
1489    Ok(STEPS
1490        .iter()
1491        .filter(|step| {
1492            crate::setup::before_state::destructive(step.name) && stance(&ctx, step).acts()
1493        })
1494        .map(|step| step.name)
1495        .collect())
1496}
1497
1498/// Where the committed setup proof stands against this target, offline:
1499/// `absent`, `compatible`, `stale`, or `invalid`.
1500///
1501/// # Errors
1502///
1503/// A target configuration that does not resolve.
1504pub fn proof_word(target: &camino::Utf8PathBuf) -> Result<&'static str, RkError> {
1505    let ctx = Ctx::resolve(target, None, None, None)?;
1506    Ok(proof::judge(&ctx.target, &proof::subject(&ctx)).word())
1507}
1508
1509/// Observe one step through the engine's executor.
1510///
1511/// `install-bot` on GitHub is the one observation that authenticates as
1512/// the App itself, so it routes through [`app_jwt_for`] here — where the
1513/// engine can mint once and register the redaction needles — rather than
1514/// through the credential-free name dispatch in [`observe::observe`].
1515fn observe_with(engine: &mut Engine, step: &str) -> Result<StepState, RkError> {
1516    if step == "install-bot" && engine.ctx.forge == Some(Forge::Github) {
1517        let jwt = match app_jwt_for(engine)? {
1518            Ok(jwt) => jwt,
1519            Err(detail) => return Ok(StepState::Unknown { detail }),
1520        };
1521        return Ok(observe::github_install_bot(&engine.ctx, &jwt));
1522    }
1523    let ctx = clone_ctx(&engine.ctx);
1524    let mut runner = |exec: &Exec| engine.exec(exec, false);
1525    observe::observe(&ctx, step, &mut runner)
1526}
1527
1528/// The run's validated key file, read exactly once per run: the first
1529/// consumer resolves it and every later one reuses the same bytes, so the
1530/// file that authenticated the App is the file `bot-secrets` stores, and
1531/// no replacement between steps can split the two. The bytes become a
1532/// redaction needle the moment they are read.
1533fn key_file_for(engine: &mut Engine) -> Result<Option<&secrets::KeyFile>, RkError> {
1534    if engine.key.is_none() && engine.key_unavailable.is_none() {
1535        match secrets::look_up_key_file(&engine.ctx.target)? {
1536            secrets::KeyLookup::Absent => {}
1537            secrets::KeyLookup::Found(key) => {
1538                engine.secrets.push(key.bytes.clone());
1539                engine.key = Some(key);
1540            }
1541            // A check reads the forge and changes nothing, so a key this
1542            // runtime cannot reach leaves the one step that needs it
1543            // undecided and lets every other step run. A run that would
1544            // mutate, or record a proof, still needs the key and refuses.
1545            secrets::KeyLookup::Unavailable(unavailable) if engine.key_boundary => {
1546                engine.key_unavailable = Some(unavailable.message);
1547            }
1548            secrets::KeyLookup::Unavailable(unavailable) => return Err(unavailable.refusal()),
1549        }
1550    }
1551    Ok(engine.key.as_ref())
1552}
1553
1554/// The run's App JWT, minted at most once: the key comes from the run's
1555/// one read, and the minted token and its signature segment become
1556/// redaction needles before anything else spawns. Every install-bot
1557/// observation and the grant's installation-id discovery reuse the one
1558/// token, whose nine-minute life covers a run's contiguous step easily.
1559///
1560/// The inner value is `Err` with a one-line detail where no token can
1561/// exist — absent exports, or a signer that failed — which an observation
1562/// reports as `unknown` and an apply turns into a refusal.
1563fn app_jwt_for(engine: &mut Engine) -> Result<Result<String, String>, RkError> {
1564    if let Some(jwt) = &engine.app_jwt {
1565        return Ok(Ok(jwt.clone()));
1566    }
1567    let app_id = app_jwt::app_id(engine.ctx.bot_app_id())?;
1568    let key_bytes = key_file_for(engine)?.map(|key| key.bytes.clone());
1569    if let Some(unreachable) = &engine.key_unavailable {
1570        return Ok(Err(format!(
1571            "the installation is readable only to the App itself, and this runtime cannot reach the key {} names: {unreachable}; a host that holds the key re-verifies it",
1572            secrets::PRIVATE_KEY_FILE
1573        )));
1574    }
1575    let (Some(app_id), Some(key_bytes)) = (app_id, key_bytes) else {
1576        return Ok(Err(format!(
1577            "the installation is readable only to the App itself; {}",
1578            app_jwt::REMEDIATION
1579        )));
1580    };
1581    let credentials = app_jwt::AppCredentials { app_id, key_bytes };
1582    let ctx = clone_ctx(&engine.ctx);
1583    Ok(match app_jwt::mint(&ctx, &credentials) {
1584        Ok(jwt) => {
1585            engine
1586                .secrets
1587                .push(Zeroizing::new(jwt.clone().into_bytes()));
1588            if let Some(signature) = jwt.rsplit('.').next() {
1589                engine
1590                    .secrets
1591                    .push(Zeroizing::new(signature.as_bytes().to_vec()));
1592            }
1593            engine.app_jwt = Some(jwt.clone());
1594            Ok(jwt)
1595        }
1596        Err(detail) => Err(detail),
1597    })
1598}
1599
1600fn state_detail(state: &StepState) -> String {
1601    state.detail().to_owned()
1602}
1603
1604/// Materialize the step's script into the run's private directory, prove
1605/// the written bytes by digest, and spawn it through the interpreter.
1606fn run_script(engine: &mut Engine, step: &StepSpec) -> Result<(Outcome, PathBuf), RkError> {
1607    run_script_with(engine, step, None, Vec::new())
1608}
1609
1610/// The same, with bytes written to the script's standard input.
1611///
1612/// A credential travels this way and no other: `rk` reads it, validates it,
1613/// and hands the child the bytes it validated, so nothing between the check
1614/// and the forge can substitute a different file.
1615fn run_script_with(
1616    engine: &mut Engine,
1617    step: &StepSpec,
1618    stdin: Option<Zeroizing<Vec<u8>>>,
1619    extra_env: Vec<(OsString, OsString)>,
1620) -> Result<(Outcome, PathBuf), RkError> {
1621    let forge = engine.ctx.adapter()?;
1622    let rel = format!("{}/{}", forge.as_str(), step.name);
1623    let bytes = embedded::SETUP
1624        .get_file(&rel)
1625        .map(include_dir::File::contents)
1626        .ok_or_else(|| RkError::Other(anyhow::anyhow!("no embedded script at setup/{rel}")))?;
1627    let journal = engine
1628        .journal
1629        .as_mut()
1630        .ok_or_else(|| RkError::Other(anyhow::anyhow!("an apply always has a journal")))?;
1631    let dir = journal.scripts_dir().join(forge.as_str());
1632    fs::create_dir_all(&dir)?;
1633    restrict(&dir, 0o700);
1634    let path = dir.join(step.name);
1635    fs::write(&path, bytes)?;
1636    restrict(&path, 0o600);
1637    let written = fs::read(&path)?;
1638    let digest = Digest::of(&written);
1639    if digest != Digest::of(bytes) {
1640        return Err(RkError::Other(anyhow::anyhow!(
1641            "the materialized script at {} differs from the embedded bytes",
1642            path.display()
1643        )));
1644    }
1645    journal.record_script(format!("scripts/{rel}"), digest.to_string());
1646    let mut env = engine.ctx.child_env(step.name);
1647    env.extend(extra_env);
1648    let exec = Exec {
1649        program: crate::probes::sh_bin(),
1650        args: vec![path.clone().into_os_string()],
1651        env,
1652        cwd: engine.ctx.target.as_std_path().to_path_buf(),
1653        stdin,
1654    };
1655    let outcome = engine.exec(&exec, true)?;
1656    Ok((outcome, path))
1657}
1658
1659/// Honest classification: `gh` documents exit 4 as authentication required;
1660/// beyond that only an HTTP status in the response says more, and a step
1661/// that fails for a reason nothing establishes stays `subprocess-failed`
1662/// with its own stderr surfaced verbatim.
1663fn classify_failure(engine: &Engine, step: &StepSpec, outcome: &Outcome) -> RkError {
1664    let stderr = String::from_utf8_lossy(&outcome.stderr);
1665    // A signalled child usually writes nothing before it dies, and
1666    // "no output" would blame the forge for a kill that came from
1667    // outside it. The adapter already resolved 128+N; say which.
1668    let last = if outcome.exit_code >= 128 {
1669        format!("killed by signal {}", outcome.exit_code - 128)
1670    } else {
1671        stderr
1672            .lines()
1673            .rev()
1674            .find(|line| !line.trim().is_empty())
1675            .unwrap_or("no output")
1676            .to_owned()
1677    };
1678    let reason = if (engine.ctx.forge == Some(Forge::Github) && outcome.exit_code == 4)
1679        || stderr.contains("HTTP 401")
1680    {
1681        Reason::ForgeAuthentication
1682    } else if stderr.contains("HTTP 403") {
1683        Reason::ForgePermission
1684    } else if stderr.contains("HTTP 429") || stderr.contains("rate limit") {
1685        Reason::ForgeRateLimit
1686    } else {
1687        Reason::SubprocessFailed
1688    };
1689    let diagnostic = Diagnostic::new(reason, format!("the forge refused '{}': {last}", step.name))
1690        .expected(step.proves.to_owned())
1691        .action(format!(
1692            "rk setup step {} --target {} --apply",
1693            step.name, engine.ctx.target
1694        ))
1695        .step(step.name);
1696    let diagnostic = match reason {
1697        Reason::ForgePermission => diagnostic.expected(format!(
1698            "repository administration write on {} for the authenticated account",
1699            engine.ctx.repo
1700        )),
1701        _ => diagnostic,
1702    };
1703    match reason {
1704        Reason::SubprocessFailed => RkError::subprocess(diagnostic),
1705        _ => RkError::refusal(diagnostic),
1706    }
1707}
1708
1709/// Fold the run's progress into the failure, so the diagnostic answers
1710/// what state the target is in.
1711fn attach_progress(
1712    error: RkError,
1713    done: &[(String, String)],
1714    failed: &StepSpec,
1715    steps: &[&StepSpec],
1716) -> RkError {
1717    let remaining = steps.len().saturating_sub(done.len() + 1);
1718    let state = format!(
1719        "{} completed; {} failed; {remaining} not attempted",
1720        step_count(done.len()),
1721        failed.name
1722    );
1723    match error {
1724        RkError::Refusal(mut diagnostic) => {
1725            diagnostic.target_state.get_or_insert(state);
1726            RkError::Refusal(diagnostic)
1727        }
1728        RkError::Subprocess(mut diagnostic) => {
1729            diagnostic.target_state.get_or_insert(state);
1730            RkError::Subprocess(diagnostic)
1731        }
1732        other => other,
1733    }
1734}
1735
1736/// Observe every step once, in table order, and render each row as it
1737/// lands, so a person reads the forge calls beside the step that made
1738/// them. The rows it returns are the only source of every later verdict.
1739///
1740/// SATISFIES setup-proof:one-report-owns-every-classification
1741fn observe_all(engine: &mut Engine) -> Result<Report, RkError> {
1742    let mut report = Report::default();
1743    for step in &STEPS {
1744        let clock = Instant::now();
1745        // A step the target declared it does not run is stated and judged
1746        // by nothing: no forge call, no verdict, and no weight in the exit
1747        // code. The reason travels with it, so a reader can tell a chosen
1748        // subset from an incomplete setup.
1749        let stance = stance(&engine.ctx, step);
1750        let row = if stance.acts() {
1751            let state = observe_with(engine, step.name)?;
1752            Row::observed(step, stance, &state)
1753        } else {
1754            Row::stated(step, stance)
1755        };
1756        engine.out.result_line(row.line());
1757        let (status, detail) = row.event_fields();
1758        let mut finished = engine.event(EventKind::StepFinished, Some(step.name));
1759        finished.status = Some(status);
1760        finished.detail = Some(detail);
1761        finished.duration_ms = Some(elapsed_ms(clock));
1762        engine.emit(&finished);
1763        report.rows.push(row);
1764    }
1765    if report.judged() < STEPS.len() {
1766        engine.out.result_line(format!(
1767            "{} judged; the rest do not apply to this target or {} excludes them",
1768            step_count(report.judged()),
1769            crate::config::CONFIG_PATH
1770        ));
1771    }
1772    Ok(report)
1773}
1774
1775/// `rk setup check`: observe and verify every step, report per step, and
1776/// judge at the end. The mutating half is unreachable from this path: it
1777/// calls only the observe functions.
1778fn check(out: Output, ctx: Ctx) -> Result<(), RkError> {
1779    let mut engine = Engine::open(out, ctx, "setup check", false)?;
1780    engine.key_boundary = true;
1781    let report = observe_all(&mut engine)?;
1782    // The milestones are information the publish task resumes from; none
1783    // weighs on the verdict below.
1784    for milestone in crate::setup::milestones::observe(&engine.ctx) {
1785        engine.out.result_line(milestone.line());
1786        let mut event = engine.event(EventKind::Milestone, Some(milestone.id));
1787        event.status = Some(milestone.status.to_owned());
1788        event.detail = Some(milestone.detail);
1789        engine.emit(&event);
1790    }
1791    if !report.checkpointable() {
1792        let error = verdict(&engine.ctx, &report);
1793        return Err(fail(&mut engine, error));
1794    }
1795    engine
1796        .out
1797        .next(&["rk guide release orders the first release".to_owned()]);
1798    engine.finish(0, None);
1799    Ok(())
1800}
1801
1802/// The check's failure, by what it found. An unsatisfied step is drift,
1803/// and applying the setup is its remedy. An unknown step is an
1804/// observation this runtime could not make, which proves nothing wrong,
1805/// so it prescribes no apply: it names where the observation can be
1806/// repeated, and what the committed proof says meanwhile. A proof never
1807/// masks a step found wrong now.
1808///
1809/// SATISFIES setup-proof:an-unavailable-credential-is-an-observation-boundary
1810/// SATISFIES setup-proof:current-evidence-overrides-the-proof
1811fn verdict(ctx: &Ctx, report: &Report) -> RkError {
1812    let unsatisfied = report.unsatisfied();
1813    let unknown = report.unknown();
1814    let standing = proof::judge(&ctx.target, &proof::subject(ctx));
1815    let proven = match &standing {
1816        Standing::Compatible(proof) => Some(proof),
1817        _ => None,
1818    };
1819    if unsatisfied == 0 {
1820        let state = proven.map_or_else(
1821            || {
1822                format!(
1823                    "no setup defect was inferred; no compatible {} is committed, so the current state is unverified",
1824                    proof::PROOF_PATH
1825                )
1826            },
1827            |proof| {
1828                format!(
1829                    "no setup defect was inferred; the committed setup proof from {} by rk {} still matches this target's setup contract",
1830                    proof.verified_at, proof.rk_version
1831                )
1832            },
1833        );
1834        return RkError::check_failed(
1835            Diagnostic::new(
1836                Reason::ObservationIncomplete,
1837                format!(
1838                    "{} could not be verified from this runtime, and none is unsatisfied",
1839                    step_count(unknown)
1840                ),
1841            )
1842            .expected("every applicable step readable from where the check runs")
1843            .action("rerun rk setup check where each unknown step can be observed; its line names what it needs")
1844            .target_state(state),
1845        );
1846    }
1847    let mut message = format!(
1848        "{} {} not satisfied",
1849        step_count(unsatisfied),
1850        if unsatisfied == 1 { "is" } else { "are" }
1851    );
1852    let mut action = format!(
1853        "rk setup --target {} --apply re-asserts the unsatisfied ones",
1854        ctx.target
1855    );
1856    if unknown > 0 {
1857        use std::fmt::Write as _;
1858        let _ = write!(
1859            message,
1860            ", and {unknown} could not be verified from this runtime"
1861        );
1862        action.push_str("; the unknown ones need a runtime that can observe what each line names");
1863    }
1864    let mut diagnostic = Diagnostic::new(Reason::StateDrift, message)
1865        .expected("every step's proof column to hold")
1866        .action(action);
1867    if let Some(proof) = proven {
1868        diagnostic = diagnostic.target_state(format!(
1869            "this observation supersedes the committed setup proof from {} by rk {}",
1870            proof.verified_at, proof.rk_version
1871        ));
1872    }
1873    RkError::check_failed(diagnostic)
1874}
1875
1876/// `rk setup checkpoint`: observe every step as `check` does, and commit
1877/// the result only where the observation is complete. An incomplete one
1878/// writes nothing, so an earlier proof stays byte for byte.
1879///
1880/// SATISFIES setup-proof:a-checkpoint-records-only-a-complete-observation
1881fn checkpoint(out: Output, ctx: Ctx) -> Result<(), RkError> {
1882    let mut engine = Engine::open(out, ctx, "setup checkpoint", false)?;
1883    let report = observe_all(&mut engine)?;
1884    let Some(proof) = proof::of(&engine.ctx, &report, crate::applog::now_utc()) else {
1885        let error = RkError::check_failed(
1886            Diagnostic::new(
1887                Reason::StateDrift,
1888                format!(
1889                    "the observation is incomplete: {} not satisfied and {} could not be verified",
1890                    step_count(report.unsatisfied()),
1891                    report.unknown()
1892                ),
1893            )
1894            .expected("every applicable step observed and holding")
1895            .action(format!(
1896                "rk setup check --target {} names each gap; checkpoint again once none remains",
1897                engine.ctx.target
1898            ))
1899            .target_state(format!("{} was not written", proof::PROOF_PATH)),
1900        );
1901        return Err(fail(&mut engine, error));
1902    };
1903    if let Err(source) = proof::write(&engine.ctx.target, &proof) {
1904        let error = RkError::refusal(
1905            Diagnostic::new(
1906                Reason::Io,
1907                format!("{} cannot be written: {source}", proof::PROOF_PATH),
1908            )
1909            .expected("a writable .release-kit directory in the target")
1910            .target_state("the earlier proof, where one exists, is unchanged"),
1911        );
1912        return Err(fail(&mut engine, error));
1913    }
1914    engine.out.result_line(format!(
1915        "wrote {}: {} proven at {} by rk {}",
1916        proof::PROOF_PATH,
1917        step_count(proof.steps.len()),
1918        proof.verified_at,
1919        proof.rk_version
1920    ));
1921    engine.out.next(&[
1922        format!("commit {} with the setup it proves", proof::PROOF_PATH),
1923        format!(
1924            "rk setup status --target {} reads it offline",
1925            engine.ctx.target
1926        ),
1927    ]);
1928    engine.finish(0, None);
1929    Ok(())
1930}
1931
1932/// `rk setup status`: where the committed proof stands against this
1933/// target's contract now. It reads a file and resolves configuration,
1934/// and nothing else: no forge, no key, no journal.
1935///
1936/// SATISFIES setup-proof:the-status-reads-the-proof-offline
1937fn status(out: Output, ctx: &Ctx) -> Result<(), RkError> {
1938    let standing = proof::judge(&ctx.target, &proof::subject(ctx));
1939    out.emit(&proof::StatusDocument::of(&standing))?;
1940    match &standing {
1941        Standing::Absent => out.result_line(format!(
1942            "setup proof: absent — {} does not exist, so no complete observation is on record",
1943            proof::PROOF_PATH
1944        )),
1945        Standing::Compatible(proof) => out.result_line(format!(
1946            "setup proof: compatible — proven {} by rk {}, and this target's setup contract has not changed since",
1947            proof.verified_at, proof.rk_version
1948        )),
1949        Standing::Stale { proof, differences } => out.result_line(format!(
1950            "setup proof: stale — proven {} by rk {}, and the setup contract changed since: {}",
1951            proof.verified_at,
1952            proof.rk_version,
1953            differences.join(", ")
1954        )),
1955        Standing::Invalid { detail, .. } => {
1956            out.result_line(format!("setup proof: invalid — {detail}"));
1957        }
1958    }
1959    if let Standing::Compatible(proof) | Standing::Stale { proof, .. } = &standing {
1960        for step in &proof.steps {
1961            let limitation = step
1962                .limitation
1963                .as_ref()
1964                .map_or_else(String::new, |limit| format!(" (limitation: {limit})"));
1965            out.result_line(format!("  {} {}{limitation}", step.state, step.name));
1966        }
1967    }
1968    let next = match standing {
1969        Standing::Compatible(_) => format!(
1970            "rk setup check --target {} observes the forge now, where this runtime can",
1971            ctx.target
1972        ),
1973        _ => format!(
1974            "rk setup checkpoint --target {}, from a host that can observe every step, records a proof",
1975            ctx.target
1976        ),
1977    };
1978    out.next(&[next]);
1979    Ok(())
1980}
1981
1982/// Restrict a materialized path's mode: data, not an executable — nothing
1983/// ever executes a script directly, so no mode is load-bearing.
1984fn restrict(path: &std::path::Path, mode: u32) {
1985    #[cfg(unix)]
1986    {
1987        use std::os::unix::fs::PermissionsExt as _;
1988        let _ = fs::set_permissions(path, fs::Permissions::from_mode(mode));
1989    }
1990    #[cfg(not(unix))]
1991    let _ = (path, mode);
1992}
1993
1994/// A POSIX shell must spawn before anything else does; every step runs
1995/// through it.
1996fn guard_sh() -> Result<(), RkError> {
1997    let ok = std::process::Command::new(crate::probes::sh_bin())
1998        .args(["-c", "exit 0"])
1999        .status()
2000        .is_ok_and(|status| status.success());
2001    if ok {
2002        Ok(())
2003    } else {
2004        Err(RkError::refusal(
2005            Diagnostic::new(Reason::PrerequisiteUnmet, "no POSIX sh runs on this host")
2006                .expected("a working sh on PATH; every step spawns through it")
2007                .action("install a POSIX shell, then rerun")
2008                .target_state("nothing was run and nothing changed"),
2009        ))
2010    }
2011}
2012
2013#[cfg(test)]
2014mod tests {
2015    /// Every summary line reports its count through one helper, so none of
2016    /// them can regrow a dangling plural.
2017    #[test]
2018    fn a_step_count_carries_a_noun_that_agrees_with_it() {
2019        assert_eq!(super::step_count(0), "0 steps");
2020        assert_eq!(super::step_count(1), "1 step");
2021        assert_eq!(super::step_count(2), "2 steps");
2022    }
2023}