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