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