1use std::ffi::OsString;
12use std::fs;
13use std::path::PathBuf;
14use std::time::Instant;
15
16use zeroize::Zeroizing;
17
18use crate::cli::setup::{SetupAction, SetupArgs};
19use crate::detect::Forge;
20use crate::diagnostic::{Diagnostic, Reason};
21use crate::digest::Digest;
22use crate::embedded;
23use crate::error::RkError;
24use crate::events::{ChildStream, Event, EventKind};
25use crate::output::Output;
26use crate::setup::app_jwt::{self, AppApi};
27use crate::setup::context::{Ctx, SECRET_VARS};
28use crate::setup::journal::Journal;
29use crate::setup::observe::{self, StepState};
30use crate::setup::process::{self, Exec, Outcome};
31use crate::setup::proof::{self, Standing};
32use crate::setup::report::{Report, Row, Stance, stance};
33use crate::setup::secrets;
34use crate::setup::steps::{Mutates, STEPS, StepSpec, spec};
35
36pub fn run(args: &SetupArgs) -> Result<(), RkError> {
42 match &args.action {
43 Some(SetupAction::Script { name, forge }) => script(name, forge.as_deref()),
44 Some(SetupAction::Check {
45 target,
46 repo,
47 forge,
48 required_check,
49 json,
50 }) => check(
51 Output::new(*json),
52 observing(
53 target,
54 repo.as_deref(),
55 forge.as_deref(),
56 required_check.as_deref(),
57 )?,
58 ),
59 Some(SetupAction::Checkpoint {
60 target,
61 repo,
62 forge,
63 required_check,
64 json,
65 }) => checkpoint(
66 Output::new(*json),
67 observing(
68 target,
69 repo.as_deref(),
70 forge.as_deref(),
71 required_check.as_deref(),
72 )?,
73 ),
74 Some(SetupAction::Status {
77 target,
78 repo,
79 forge,
80 required_check,
81 json,
82 }) => status(
83 Output::new(*json),
84 &Ctx::resolve(
85 target,
86 repo.as_deref(),
87 forge.as_deref(),
88 required_check.as_deref(),
89 )?,
90 ),
91 Some(action @ SetupAction::Step { .. }) => step(action),
92 None if args.list => list(args.forge.as_deref()),
93 None => {
94 let target = args.target.clone().ok_or_else(|| {
95 RkError::Usage("name a --target, or pass --list to see the steps".into())
96 })?;
97 let all: Vec<&StepSpec> = STEPS.iter().collect();
98 let mut ctx = Ctx::resolve(
99 &target,
100 args.repo.as_deref(),
101 args.forge.as_deref(),
102 args.required_check.as_deref(),
103 )?;
104 reject_check_flag_on_gitlab(&ctx)?;
105 if args.apply {
106 require_check_for(&ctx, &all)?;
107 let acted: Vec<&StepSpec> = all
110 .iter()
111 .copied()
112 .filter(|step| !skipped_by_a_full_run(&ctx, step, all.len()))
113 .collect();
114 ctx.require_cli(&acted)?;
115 execute(Output::new(args.json), ctx, &all, "setup")
116 } else {
117 let acted: Vec<&StepSpec> = all
118 .iter()
119 .copied()
120 .filter(|step| !skipped_by_a_full_run(&ctx, step, all.len()))
121 .collect();
122 ctx.require_cli(&acted)?;
123 preview(Output::new(args.json), &ctx, &all)
124 }
125 }
126 }
127}
128
129fn step(action: &SetupAction) -> Result<(), RkError> {
131 let SetupAction::Step {
132 name,
133 target,
134 repo,
135 forge,
136 required_check,
137 apply,
138 json,
139 } = action
140 else {
141 unreachable!("the dispatch routes only a step here");
142 };
143 let selected = spec(name).ok_or_else(|| {
144 RkError::Usage(format!("unknown step '{name}'; rk setup --list names them"))
145 })?;
146 let mut ctx = Ctx::resolve(
147 target,
148 repo.as_deref(),
149 forge.as_deref(),
150 required_check.as_deref(),
151 )?;
152 reject_check_flag_on_gitlab(&ctx)?;
153 if *apply {
154 refuse_an_excluded_step(&ctx, selected)?;
155 require_check_for(&ctx, &[selected])?;
156 ctx.require_cli(&[selected])?;
159 execute(Output::new(*json), ctx, &[selected], "setup step")
160 } else {
161 ctx.require_cli(&[selected])?;
165 preview(Output::new(*json), &ctx, &[selected])
166 }
167}
168
169fn observing(
173 target: &camino::Utf8PathBuf,
174 repo: Option<&str>,
175 forge: Option<&str>,
176 required_check: Option<&str>,
177) -> Result<Ctx, RkError> {
178 let mut ctx = Ctx::resolve(target, repo, forge, required_check)?;
179 reject_check_flag_on_gitlab(&ctx)?;
180 let all: Vec<&StepSpec> = STEPS.iter().collect();
181 ctx.require_cli(&all)?;
182 Ok(ctx)
183}
184
185fn skipped_by_a_full_run(ctx: &Ctx, step: &StepSpec, selected: usize) -> bool {
193 if !step.optional || selected <= 1 {
194 return false;
195 }
196 !(step.name == "protect-release-lines" && ctx.release_lines())
197}
198
199fn refuse_an_excluded_step(ctx: &Ctx, step: &StepSpec) -> Result<(), RkError> {
205 match stance(ctx, step) {
206 Stance::Applies => Ok(()),
207 Stance::Excluded(reason) | Stance::Redundant { reason, .. } => {
208 Err(RkError::Usage(format!(
209 "{} is excluded by {}: {reason}; remove it from setup.excluded_steps to run it",
210 step.name,
211 crate::config::CONFIG_PATH
212 )))
213 }
214 Stance::NotApplicable(reason) => Err(RkError::refusal(
218 Diagnostic::new(
219 Reason::PrerequisiteUnmet,
220 format!("{} does not apply to this target: {reason}", step.name),
221 )
222 .expected("a target configuration that selects this step")
223 .action("rk profile --target . reports what this target resolves to")
224 .target_state("unchanged")
225 .step(step.name),
226 )),
227 }
228}
229
230fn reject_check_flag_on_gitlab(ctx: &Ctx) -> Result<(), RkError> {
238 if ctx.forge == Some(Forge::Gitlab) && ctx.required_check.is_some() {
239 return Err(RkError::Usage(
240 "--required-check is refused on gitlab: the forge requires the whole pipeline and names no individual check".into(),
241 ));
242 }
243 Ok(())
244}
245
246fn require_check_for(ctx: &Ctx, steps: &[&StepSpec]) -> Result<(), RkError> {
256 let needs = ctx.forge == Some(Forge::Github)
257 && ctx.required_check.is_none()
258 && ctx
259 .protection()
260 .owned_trunk_rules
261 .iter()
262 .any(|rule| rule == "required_status_checks")
263 && steps
264 .iter()
265 .any(|step| step.name == "protect-trunk" && stance(ctx, step).acts());
266 if needs {
267 return Err(RkError::refusal(
268 Diagnostic::new(
269 Reason::PrerequisiteUnmet,
270 "protect-trunk refuses until the required check is named, and nothing was written",
271 )
272 .expected("the name of the CI check the release merge must pass")
273 .action(format!(
274 "set setup.required_check in {}, or pass --required-check <name>; gh api repos/{}/commits/HEAD/check-runs lists the project's check names",
275 crate::config::CONFIG_PATH,
276 ctx.repo
277 ))
278 .step("protect-trunk"),
279 ));
280 }
281 Ok(())
282}
283
284fn list(forge: Option<&str>) -> Result<(), RkError> {
288 let forge = forge
289 .map(|name| {
290 Forge::parse(name).ok_or_else(|| {
291 RkError::Usage(format!(
292 "unknown forge '{name}'; the forges are: github, gitlab"
293 ))
294 })
295 })
296 .transpose()?;
297 let out = Output::human();
298 for (idx, step) in STEPS.iter().enumerate() {
299 let mut line = format!(
300 "{:2}. {} [{}] proves: {}",
301 idx + 1,
302 step.name,
303 step.chapter,
304 step.proves
305 );
306 if step.name == "protect-trunk" && forge != Some(Forge::Gitlab) {
307 line.push_str(" (needs --required-check on github)");
308 }
309 if step.destructive {
310 line.push_str(" (destructive)");
311 }
312 if step.optional {
313 line.push_str(" (optional; a full apply skips it)");
314 }
315 out.result_line(line);
316 }
317 out.next(&[
318 "rk setup --target . previews every step".to_owned(),
319 "rk setup script <name> prints one embedded script".to_owned(),
320 ]);
321 Ok(())
322}
323
324fn script(name: &str, forge: Option<&str>) -> Result<(), RkError> {
327 if name == "package-check" {
328 return Err(RkError::Usage(
329 "package-check reads its command from the technology binding and has no script".into(),
330 ));
331 }
332 if name == "branch-reminder" {
333 return Err(RkError::Usage(
334 "branch-reminder writes an embedded hook body and has no script; rk setup step branch-reminder previews the write".into(),
335 ));
336 }
337 if name == "forge-version" {
338 return Err(RkError::Usage(
339 "forge-version reads the forge's own version and has no script; rk setup step forge-version previews the read".into(),
340 ));
341 }
342 let forge = match forge {
343 Some(value) => Forge::parse(value).ok_or_else(|| {
344 RkError::Usage(format!(
345 "unknown forge '{value}'; the forges are: github, gitlab"
346 ))
347 })?,
348 None => Forge::Github,
349 };
350 let path = format!("{}/{name}", forge.as_str());
351 let file = embedded::SETUP.get_file(&path).ok_or(RkError::NotFound {
352 kind: "setup step",
353 name: name.to_owned(),
354 })?;
355 Output::human().result_raw(&String::from_utf8_lossy(file.contents()));
356 Ok(())
357}
358
359struct Engine {
362 out: Output,
363 ctx: Ctx,
364 journal: Option<Journal>,
365 secrets: Vec<Zeroizing<Vec<u8>>>,
366 key: Option<secrets::KeyFile>,
368 app_jwt: Option<String>,
370 key_boundary: bool,
373 key_unavailable: Option<String>,
375 seq: u64,
376 command: &'static str,
377 run_id: String,
378 snapshot: Option<crate::snapshot::Snapshot>,
381}
382
383impl Engine {
384 fn open(
389 out: Output,
390 ctx: Ctx,
391 command: &'static str,
392 journal_required: bool,
393 ) -> Result<Self, RkError> {
394 secrets::refuse_legacy_key()?;
397 let journal = match Journal::create(
398 command,
399 ctx.target.as_str(),
400 ctx.forge.map_or("none", Forge::as_str),
401 &ctx.repo,
402 ) {
403 Ok(journal) => Some(journal),
404 Err(source) if journal_required => {
405 return Err(RkError::refusal(
406 Diagnostic::new(
407 Reason::JournalUnavailable,
408 format!("the run journal cannot be created: {source}"),
409 )
410 .expected("a writable state root for the journal")
411 .target_state("nothing was run and nothing changed"),
412 ));
413 }
414 Err(source) => {
415 out.warn(format!("no run journal for this run: {source}"));
416 None
417 }
418 };
419 let run_id = journal
420 .as_ref()
421 .map_or_else(|| "unjournaled".to_owned(), |j| j.run_id().to_owned());
422 let mut engine = Self {
423 out,
424 ctx,
425 journal,
426 secrets: Ctx::secret_values(),
427 key: None,
428 app_jwt: None,
429 key_boundary: false,
430 key_unavailable: None,
431 seq: 0,
432 command,
433 run_id,
434 snapshot: None,
435 };
436 let opening = Event::opening(
437 engine.next_seq(),
438 crate::applog::now_utc(),
439 engine.run_id.clone(),
440 engine.command,
441 );
442 engine.emit(&opening);
443 if engine.ctx.self_hosted_gitlab() {
444 engine.out.warn(
445 "this remote is a self-hosted GitLab: registry trusted publishing covers GitLab.com only, so the OIDC invariant cannot be satisfied here",
446 );
447 }
448 Ok(engine)
449 }
450
451 const fn next_seq(&mut self) -> u64 {
452 let seq = self.seq;
453 self.seq += 1;
454 seq
455 }
456
457 fn event(&mut self, kind: EventKind, step: Option<&str>) -> Event {
458 let mut event = Event::opening(
459 self.next_seq(),
460 crate::applog::now_utc(),
461 self.run_id.clone(),
462 self.command,
463 );
464 event.kind = kind;
465 event.step = step.map(str::to_owned);
466 event
467 }
468
469 fn emit(&mut self, event: &Event) {
470 self.out.event(event);
471 if let Some(journal) = &mut self.journal
472 && let Ok(line) = serde_json::to_string(event)
473 {
474 journal.event_line(&line);
475 }
476 }
477
478 fn exec(&mut self, exec: &Exec, passthrough: bool) -> Result<Outcome, RkError> {
481 let echo = exec.echo();
482 self.out.frame(&echo);
483 if let Some(journal) = &mut self.journal {
484 journal.transcript(echo.as_bytes());
485 journal.transcript(b"\n");
486 }
487 let secrets = std::mem::take(&mut self.secrets);
488 let step_name: Option<String> = None;
489 let mut chunks: Vec<(ChildStream, Vec<u8>)> = Vec::new();
490 let spawned = process::run(exec, |stream, chunk| {
491 chunks.push((stream, process::redact(chunk, &secrets)));
492 });
493 self.secrets = secrets;
494 for (stream, chunk) in chunks {
495 if passthrough {
496 self.out.child_passthrough(stream, &chunk);
497 }
498 let event = self.event(EventKind::ChildOutput, step_name.as_deref());
499 let event = event.child_output(stream, &chunk);
500 self.emit(&event);
501 if let Some(journal) = &mut self.journal {
502 journal.transcript(&chunk);
503 }
504 }
505 spawned.map_err(|source| {
506 RkError::refusal(
507 Diagnostic::new(
508 Reason::SubprocessSpawn,
509 format!("{} did not spawn: {source}", exec.program.to_string_lossy()),
510 )
511 .expected("a POSIX sh and the forge CLI on PATH")
512 .run(self.run_path()),
513 )
514 })
515 }
516
517 fn run_path(&self) -> String {
518 self.journal.as_ref().map_or_else(
519 || "no journal was written".to_owned(),
520 |j| j.dir.display().to_string(),
521 )
522 }
523
524 fn finish(&mut self, exit_code: i32, reason: Option<&str>) {
525 let mut event = self.event(EventKind::RunFinished, None);
526 event.exit_code = Some(exit_code);
527 event.status = Some(if exit_code == 0 {
528 "ok".into()
529 } else {
530 "failed".into()
531 });
532 self.emit(&event);
533 if let Some(journal) = &mut self.journal {
534 journal.finish(exit_code, reason);
535 }
536 }
537}
538
539fn fail(engine: &mut Engine, error: RkError) -> RkError {
541 let error = match error {
542 RkError::Refusal(mut diagnostic) => {
543 diagnostic.run.get_or_insert_with(|| engine.run_path());
544 RkError::Refusal(diagnostic)
545 }
546 RkError::Subprocess(mut diagnostic) => {
547 diagnostic.run.get_or_insert_with(|| engine.run_path());
548 RkError::Subprocess(diagnostic)
549 }
550 RkError::CheckFailed(mut diagnostic) => {
551 diagnostic.run.get_or_insert_with(|| engine.run_path());
552 RkError::CheckFailed(diagnostic)
553 }
554 other => other,
555 };
556 engine.finish(i32::from(error.exit_code()), Some(error.reason().as_str()));
557 error
558}
559
560fn preview(out: Output, ctx: &Ctx, steps: &[&StepSpec]) -> Result<(), RkError> {
566 let mut engine = Engine::open(out, clone_ctx(ctx), "setup preview", false)?;
567 out.result_line(format!(
568 "DRY RUN: rk setup would run these steps against {} on {}; re-run with --apply",
569 engine.ctx.repo,
570 engine.ctx.forge.map_or("no forge", Forge::as_str)
571 ));
572 for (idx, step) in steps.iter().enumerate() {
573 out.result_line(format!(
574 "step {}/{} {} — proves {}",
575 idx + 1,
576 steps.len(),
577 step.name,
578 step.proves
579 ));
580 let stance = stance(&engine.ctx, step);
581 if !stance.acts() {
582 out.result_line(format!(" {}", stance.framed()));
583 let mut event = engine.event(EventKind::StepFinished, Some(step.name));
584 event.status = Some(stance.word().into());
585 event.detail = Some(stance.detail());
586 engine.emit(&event);
587 continue;
588 }
589 if step.name == "bot-secrets" && engine.ctx.forge == Some(Forge::Github) {
593 secrets::resolve_key_file(&engine.ctx.target)?;
594 }
595 out.result_line(format!(" {}", render_invocation(&engine.ctx, step)));
596 if step.name == "protect-trunk"
602 && engine.ctx.forge == Some(Forge::Github)
603 && engine.ctx.required_check.is_none()
604 && engine
605 .ctx
606 .protection()
607 .owned_trunk_rules
608 .iter()
609 .any(|rule| rule == "required_status_checks")
610 {
611 out.result_line(" needs: --required-check <name> before apply");
612 }
613 if skipped_by_a_full_run(&engine.ctx, step, steps.len()) {
614 out.result_line(format!(
615 " optional: a full apply skips it; set setup.release_lines, or rk setup step {} --apply runs it",
616 step.name
617 ));
618 }
619 let mut event = engine.event(EventKind::StepFinished, Some(step.name));
620 event.status = Some("previewed".into());
621 engine.emit(&event);
622 }
623 let next = next_for_apply(&engine.ctx, steps);
624 out.next(&[
625 next,
626 "rk setup check --target . proves what is already true".to_owned(),
627 ]);
628 engine.finish(0, None);
629 Ok(())
630}
631
632fn render_invocation(ctx: &Ctx, step: &StepSpec) -> String {
635 match step.name {
636 "branch-reminder" => {
637 "would write: the post-merge reminder hook at $(git rev-parse --git-path hooks)/post-merge".to_owned()
638 }
639 "package-check" => match ctx.tech {
640 Some("rust") if ctx.reporting_policy() => "would run: cargo publish --dry-run --allow-dirty, then cargo metadata --no-deps --format-version 1, then cargo package --list --allow-dirty for a single default package rooted at the target, asserting it carries SECURITY.md and none of release-kit's own files; another workspace shape reports both as unproved".to_owned(),
641 Some("rust") => "would run: cargo publish --dry-run --allow-dirty, then cargo metadata --no-deps --format-version 1, then cargo package --list --allow-dirty for a single default package rooted at the target, asserting it ships none of release-kit's own files; another workspace shape reports that as unproved".to_owned(),
642 Some("python") if ctx.reporting_policy() => "would run: python3 -m build; sdist and wheel SECURITY.md inclusion stays unproved".to_owned(),
643 Some("python") => "would run: python3 -m build".to_owned(),
644 Some("bash") if ctx.reporting_policy() => "nothing to run: no registry for this technology; the make dist tarball is not inspected".to_owned(),
645 Some("bash") => "nothing to run: no registry for this technology".to_owned(),
646 _ => "needs: a version file naming the technology".to_owned(),
647 },
648 "forge-version" => {
649 let (major, minor) = observe::GITLAB_VERSION_FLOOR;
650 match ctx.forge {
651 Some(Forge::Github) => {
652 "nothing to read: github.com is a rolling service and declares no version floor"
653 .to_owned()
654 }
655 Some(Forge::Gitlab) => format!(
656 "would read: GET /version, and compare it against the {major}.{minor} floor; nothing is written"
657 ),
658 None => "nothing to read: the profile names no forge".to_owned(),
659 }
660 }
661 name => {
662 let check = ctx
663 .required_check
664 .as_ref()
665 .filter(|_| ctx.forge == Some(Forge::Github) && name == "protect-trunk")
666 .map(|value| format!(" RK_REQUIRED_CHECK={value}"))
667 .unwrap_or_default();
668 let ruleset = match name {
672 "protect-trunk" => format!(
673 " RK_TRUNK_RULESET={} RK_SAFETY_RULESET={} RK_TITLE_CHECK={}",
674 ctx.trunk_ruleset(),
675 ctx.safety_ruleset(),
676 ctx.title_check()
677 ),
678 "protect-tags" => format!(" RK_TAG_RULESET={}", ctx.tag_ruleset()),
679 "protect-release-lines" => format!(" RK_LINES_RULESET={}", ctx.lines_ruleset()),
680 _ => String::new(),
681 };
682 format!(
683 "would run: sh <embedded setup/{}/{name}> with RK_REPO={} RK_TRUNK_BRANCH={}{ruleset}{check}",
684 ctx.forge.map_or("<no forge>", Forge::as_str),
685 ctx.repo,
686 ctx.trunk()
687 )
688 }
689 }
690}
691
692fn next_for_apply(ctx: &Ctx, steps: &[&StepSpec]) -> String {
693 let check = ctx
694 .required_check
695 .as_ref()
696 .map(|value| format!(" --required-check {value}"))
697 .unwrap_or_default();
698 if steps.len() == 1 {
699 format!(
700 "rk setup step {} --target {} --apply{check}",
701 steps[0].name, ctx.target
702 )
703 } else {
704 format!("rk setup --target {} --apply{check}", ctx.target)
705 }
706}
707
708fn clone_ctx(ctx: &Ctx) -> Ctx {
710 ctx.clone()
711}
712
713fn execute(
715 out: Output,
716 ctx: Ctx,
717 steps: &[&StepSpec],
718 command: &'static str,
719) -> Result<(), RkError> {
720 guard_sh()?;
721 let mut engine = Engine::open(out, ctx, command, true)?;
722 let mut done: Vec<(String, String)> = Vec::new();
723 for (idx, step) in steps.iter().enumerate() {
724 let stance = stance(&engine.ctx, step);
728 if !stance.acts() {
729 engine.out.frame(format!(
730 "step {}/{} {} — {}",
731 idx + 1,
732 steps.len(),
733 step.name,
734 stance.framed()
735 ));
736 let mut finished = engine.event(EventKind::StepFinished, Some(step.name));
737 finished.status = Some(stance.word().into());
738 finished.detail = Some(stance.detail());
739 engine.emit(&finished);
740 done.push((step.name.to_owned(), stance.word().to_owned()));
741 continue;
742 }
743 if skipped_by_a_full_run(&engine.ctx, step, steps.len()) {
746 engine.out.frame(format!(
747 "step {}/{} {} — skipped (optional; set setup.release_lines, or rk setup step {} --apply runs it)",
748 idx + 1,
749 steps.len(),
750 step.name,
751 step.name
752 ));
753 let mut finished = engine.event(EventKind::StepFinished, Some(step.name));
754 finished.status = Some("skipped".into());
755 engine.emit(&finished);
756 done.push((step.name.to_owned(), "skipped".to_owned()));
757 continue;
758 }
759 engine.out.frame(format!(
760 "step {}/{} {} — {}",
761 idx + 1,
762 steps.len(),
763 step.name,
764 step.proves
765 ));
766 let mut started = engine.event(EventKind::StepStarted, Some(step.name));
767 started.status = Some("running".into());
768 engine.emit(&started);
769 let clock = Instant::now();
770 let status = match apply_step(&mut engine, step) {
771 Ok(status) => status,
772 Err(error) => {
773 let error = attach_progress(error, &done, step, steps);
774 let mut finished = engine.event(EventKind::StepFinished, Some(step.name));
775 finished.status = Some("failed".into());
776 finished.reason = Some(error.reason());
777 finished.duration_ms = Some(elapsed_ms(clock));
778 engine.emit(&finished);
779 return Err(fail(&mut engine, error));
780 }
781 };
782 engine.out.frame(format!(
783 "{} {}: {}",
784 if matches!(status, Done::Skipped(_)) {
785 "skipped"
786 } else {
787 "ok"
788 },
789 step.name,
790 status.line()
791 ));
792 let mut finished = engine.event(EventKind::StepFinished, Some(step.name));
793 finished.status = Some(status.wire().into());
794 finished.detail = Some(status.line());
795 finished.exit_code = Some(0);
796 finished.duration_ms = Some(elapsed_ms(clock));
797 engine.emit(&finished);
798 done.push((step.name.to_owned(), status.wire().to_owned()));
799 }
800 engine.out.result_line(format!(
801 "setup: {} completed against {}",
802 step_count(done.len()),
803 engine.ctx.repo
804 ));
805 for (name, status) in &done {
806 engine.out.result_line(format!(" {status} {name}"));
807 }
808 engine.out.next(&[
809 format!("rk setup check --target {}", engine.ctx.target),
810 "rk guide setup orders what no command performs".to_owned(),
811 ]);
812 engine.finish(0, None);
813 Ok(())
814}
815
816fn step_count(count: usize) -> String {
819 format!("{count} {}", if count == 1 { "step" } else { "steps" })
820}
821
822fn elapsed_ms(clock: Instant) -> u64 {
823 u64::try_from(clock.elapsed().as_millis()).unwrap_or(u64::MAX)
824}
825
826enum Done {
828 Satisfied(String),
830 Skipped(String),
832 Changed(String, Option<String>),
834 Passed(String),
836}
837
838impl Done {
839 const fn wire(&self) -> &'static str {
840 match self {
841 Self::Satisfied(_) => "satisfied",
842 Self::Skipped(_) => "skipped",
843 Self::Changed(..) => "applied",
844 Self::Passed(_) => "passed",
845 }
846 }
847
848 fn line(&self) -> String {
849 match self {
850 Self::Satisfied(detail) | Self::Passed(detail) | Self::Skipped(detail) => {
851 detail.clone()
852 }
853 Self::Changed(detail, limitation) => limitation.as_ref().map_or_else(
854 || detail.clone(),
855 |limit| format!("{detail} (limitation: {limit})"),
856 ),
857 }
858 }
859}
860
861#[allow(
863 clippy::too_many_lines,
864 reason = "one step is observe, compare, apply, and verify in one place, and splitting it would separate a verdict from the observation it rests on"
865)]
866fn apply_step(engine: &mut Engine, step: &StepSpec) -> Result<Done, RkError> {
867 for prereq in step.prereqs {
870 let state = observe_with(engine, prereq)?;
871 if !state.satisfied() {
872 return Err(RkError::refusal(
873 Diagnostic::new(
874 Reason::PrerequisiteUnmet,
875 format!(
876 "{} requires {prereq} first: {}",
877 step.name,
878 state_detail(&state)
879 ),
880 )
881 .expected(format!("{prereq} satisfied before {}", step.name))
882 .action(format!(
883 "rk setup step {prereq} --target {} --apply",
884 engine.ctx.target
885 ))
886 .step(step.name),
887 ));
888 }
889 }
890 match step.name {
891 "package-check" => {
892 if engine.ctx.tech.is_none() {
893 return Err(RkError::Usage(
894 "no version file names a technology; rk binding --list names the bindings"
895 .into(),
896 ));
897 }
898 let state = observe_with(engine, "package-check")?;
899 match state {
900 StepState::Satisfied { detail, .. } => Ok(Done::Passed(detail)),
901 StepState::Unsatisfied { detail } | StepState::Inapplicable { detail } => {
902 Err(RkError::subprocess(
903 Diagnostic::new(
904 Reason::SubprocessFailed,
905 format!("package-check failed: {detail}"),
906 )
907 .expected(step.proves.to_owned())
908 .step(step.name),
909 ))
910 }
911 StepState::Unknown { detail } => Err(RkError::subprocess(
912 Diagnostic::new(
913 Reason::SubprocessFailed,
914 format!("package-check could not run: {detail}"),
915 )
916 .step(step.name),
917 )),
918 }
919 }
920 "forge-version" => match observe_with(engine, "forge-version")? {
926 StepState::Satisfied { detail, .. } => Ok(Done::Satisfied(detail)),
927 StepState::Unsatisfied { detail } | StepState::Inapplicable { detail } => {
928 Err(RkError::refusal(
929 Diagnostic::new(Reason::PrerequisiteUnmet, detail)
930 .expected(step.proves.to_owned())
931 .action("upgrade the instance, or host the project on gitlab.com")
932 .target_state("unchanged")
933 .step(step.name),
934 ))
935 }
936 StepState::Unknown { detail } => Err(RkError::refusal(
937 Diagnostic::new(Reason::ForgeTemporary, detail)
938 .expected("a readable forge version")
939 .action("glab auth login, then rerun")
940 .target_state("unchanged")
941 .step(step.name),
942 )),
943 },
944 "branch-reminder" => {
945 use crate::setup::branch_reminder::{HookState, hook_body, hook_path, observe_hook};
946 match observe_hook(&engine.ctx.target) {
947 HookState::Installed => Ok(Done::Satisfied(
948 "the post-merge reminder hook is installed".into(),
949 )),
950 HookState::Foreign => Err(RkError::refusal(
951 Diagnostic::new(
952 Reason::StateDrift,
953 "a foreign post-merge hook exists; the reminder is never written over it",
954 )
955 .expected("no post-merge hook, or one carrying the release-kit marker")
956 .action(
957 "merge by hand: guard each call behind its own capability probe inside the existing hook — `rk branches prune --help >/dev/null 2>&1` before `rk branches prune --quiet || :`, and the same pair for `rk worktree prune`",
958 )
959 .target_state("unchanged")
960 .step(step.name),
961 )),
962 HookState::Unreadable(detail) => Err(RkError::refusal(
963 Diagnostic::new(
964 Reason::StateDrift,
965 format!("the post-merge hook cannot be read: {detail}"),
966 )
967 .target_state("unchanged")
968 .step(step.name),
969 )),
970 HookState::Absent | HookState::Drifted => {
971 let path = hook_path(&engine.ctx.target).map_err(|detail| {
972 RkError::refusal(
973 Diagnostic::new(
974 Reason::PrerequisiteUnmet,
975 format!("the hooks directory cannot be resolved: {detail}"),
976 )
977 .expected("a git repository whose hooks directory git can name")
978 .step(step.name),
979 )
980 })?;
981 crate::atomic::write(&path, hook_body())?;
982 #[cfg(unix)]
983 {
984 use std::os::unix::fs::PermissionsExt as _;
985 std::fs::set_permissions(
986 &path,
987 std::fs::Permissions::from_mode(0o755),
988 )?;
989 }
990 Ok(Done::Changed(
991 "wrote the post-merge reminder hook".into(),
992 None,
993 ))
994 }
995 }
996 }
997 "single-trunk" => {
998 let guard = {
999 let ctx = clone_ctx(&engine.ctx);
1000 let mut runner = |exec: &Exec| engine.exec(exec, false);
1001 observe::single_trunk_guard(&ctx, &mut runner)?
1002 };
1003 match &guard {
1006 StepState::Satisfied { .. } => {}
1007 StepState::Unsatisfied { detail }
1008 | StepState::Inapplicable { detail }
1009 | StepState::Unknown { detail } => {
1010 return Err(RkError::refusal(
1011 Diagnostic::new(
1012 Reason::DestructiveRefusal,
1013 format!("single-trunk refuses: {detail}"),
1014 )
1015 .expected(
1016 "proof that every candidate branch is absent, or an ancestor of the trunk",
1017 )
1018 .step(step.name),
1019 ));
1020 }
1021 }
1022 run_forge_step(engine, step)
1023 }
1024 "bot-secrets" => {
1025 let adapter = engine.ctx.adapter()?;
1031 let key = match adapter {
1032 Forge::Github => key_file_for(engine)?.map(|key| key.bytes.clone()),
1036 Forge::Gitlab => None,
1037 };
1038 let provided = match adapter {
1039 Forge::Github => secrets::value_of("RK_BOT_APP_ID").is_some() && key.is_some(),
1042 Forge::Gitlab => secrets::value_of("RK_BOT_TOKEN").is_some(),
1043 };
1044 let state = observe_with(engine, step.name)?;
1045 if !provided {
1046 if state.satisfied() {
1047 return Ok(Done::Satisfied(state_detail(&state)));
1048 }
1049 let wanted = match adapter {
1050 Forge::Github => {
1051 "export RK_BOT_APP_ID and RK_BOT_PRIVATE_KEY_FILE, the second naming the .pem; rk forge github carries the walkthrough"
1052 }
1053 Forge::Gitlab => {
1054 "rk setup step install-bot --apply stores the token, or export RK_BOT_TOKEN to rotate one"
1055 }
1056 };
1057 return Err(RkError::refusal(
1058 Diagnostic::new(
1059 Reason::PrerequisiteUnmet,
1060 "bot-secrets has no credentials to store",
1061 )
1062 .expected("the bot credentials in the environment, the key as a path")
1063 .action(wanted.to_owned())
1064 .step(step.name),
1065 ));
1066 }
1067 if let Some(journal) = &mut engine.journal {
1068 for name in SECRET_VARS {
1069 if secrets::value_of(name).is_some() {
1070 journal.record_secret(name, true, "environment");
1071 }
1072 }
1073 if key.is_some() {
1074 journal.record_secret(secrets::PRIVATE_KEY_FILE, true, "file");
1075 }
1076 }
1077 let stdin = key;
1081 run_forge_step_with(engine, step, stdin, Vec::new())
1082 }
1083 "protections-check" => {
1084 let (outcome, _) = run_script(engine, step)?;
1085 if !outcome.success() {
1086 return Err(classify_failure(engine, step, &outcome));
1087 }
1088 match observe_with(engine, step.name)? {
1092 StepState::Satisfied { detail, limitation } => {
1093 Ok(Done::Passed(limitation.map_or_else(
1094 || detail.clone(),
1095 |limit| format!("{detail} (limitation: {limit})"),
1096 )))
1097 }
1098 StepState::Unsatisfied { detail } | StepState::Inapplicable { detail } => {
1099 Err(RkError::refusal(
1100 Diagnostic::new(
1101 Reason::StateDrift,
1102 format!("protections-check passed its script and the observation disagrees: {detail}"),
1103 )
1104 .expected(step.proves.to_owned())
1105 .step(step.name),
1106 ))
1107 }
1108 StepState::Unknown { detail } => Err(RkError::refusal(
1111 Diagnostic::new(
1112 Reason::ForgeTemporary,
1113 format!(
1114 "protections-check passed its script and the readback could not confirm it: {detail}"
1115 ),
1116 )
1117 .expected(step.proves.to_owned())
1118 .action("check authentication and connectivity, then rerun")
1119 .step(step.name),
1120 )),
1121 }
1122 }
1123 "install-bot" if engine.ctx.forge == Some(Forge::Github) => {
1129 match observe_with(engine, step.name)? {
1130 StepState::Satisfied { detail, .. } => {
1131 return Ok(Done::Satisfied(detail));
1132 }
1133 StepState::Unsatisfied { .. } | StepState::Inapplicable { .. } => {}
1134 StepState::Unknown { detail } => {
1135 return Err(RkError::refusal(
1136 Diagnostic::new(
1137 Reason::ForgeTemporary,
1138 format!("{} cannot observe the current state: {detail}", step.name),
1139 )
1140 .expected("a readable forge answer before anything mutates")
1141 .action("check the App credentials and connectivity, then rerun")
1142 .step(step.name),
1143 ));
1144 }
1145 }
1146 let installation = github_installation_id(engine, step)?;
1147 run_forge_step_with(
1148 engine,
1149 step,
1150 None,
1151 vec![("RK_BOT_INSTALLATION".into(), installation.into())],
1152 )
1153 }
1154 _ => {
1155 if step.mutates == Mutates::Forge {
1156 match observe_with(engine, step.name)? {
1161 StepState::Satisfied { detail, limitation } => {
1162 let detail = if step.name == "private-vulnerability-reporting" {
1163 limitation.map_or_else(
1164 || detail.clone(),
1165 |limit| format!("{detail} (limitation: {limit})"),
1166 )
1167 } else {
1168 detail
1169 };
1170 return Ok(Done::Satisfied(detail));
1171 }
1172 StepState::Inapplicable { detail }
1173 if step.name == "private-vulnerability-reporting" =>
1174 {
1175 return Ok(Done::Skipped(detail));
1176 }
1177 StepState::Unsatisfied { .. } | StepState::Inapplicable { .. } => {}
1178 StepState::Unknown { detail } => {
1179 return Err(RkError::refusal(
1180 Diagnostic::new(
1181 Reason::ForgeTemporary,
1182 format!("{} cannot observe the current state: {detail}", step.name),
1183 )
1184 .expected("a readable forge answer before anything mutates")
1185 .action("check authentication and connectivity, then rerun")
1186 .step(step.name),
1187 ));
1188 }
1189 }
1190 }
1191 run_forge_step(engine, step)
1192 }
1193 }
1194}
1195
1196fn github_installation_id(engine: &mut Engine, step: &StepSpec) -> Result<String, RkError> {
1204 let refuse = |message: String, action: &str| {
1205 RkError::refusal(
1206 Diagnostic::new(Reason::PrerequisiteUnmet, message)
1207 .expected("the App installed on the repository's owner")
1208 .action(action.to_owned())
1209 .step(step.name),
1210 )
1211 };
1212 let jwt = match app_jwt_for(engine)? {
1213 Ok(jwt) => jwt,
1214 Err(detail) => {
1215 return Err(refuse(
1216 format!("install-bot has no App token: {detail}"),
1217 app_jwt::REMEDIATION,
1218 ));
1219 }
1220 };
1221 let owner = engine
1222 .ctx
1223 .repo
1224 .split('/')
1225 .next()
1226 .unwrap_or_default()
1227 .to_owned();
1228 let ctx = clone_ctx(&engine.ctx);
1229 for path in [
1230 format!("users/{owner}/installation"),
1231 format!("orgs/{owner}/installation"),
1232 ] {
1233 match app_jwt::api_get(&ctx, &jwt, &path) {
1234 AppApi::Ok(body) => {
1235 return body["id"].as_i64().map(|id| id.to_string()).ok_or_else(|| {
1236 refuse(
1237 format!("the forge answered {path} without an installation id"),
1238 "check RK_BOT_APP_ID and the key file name the same App",
1239 )
1240 });
1241 }
1242 AppApi::Missing => {}
1243 AppApi::Refused(detail) => {
1244 return Err(refuse(
1245 detail,
1246 "check RK_BOT_APP_ID and the key file name the same App",
1247 ));
1248 }
1249 AppApi::Failed(detail) => {
1250 return Err(RkError::refusal(
1251 Diagnostic::new(
1252 Reason::ForgeTemporary,
1253 format!("install-bot cannot read the App's installation: {detail}"),
1254 )
1255 .action("check connectivity, then rerun")
1256 .step(step.name),
1257 ));
1258 }
1259 }
1260 }
1261 Err(refuse(
1262 format!("the App has no installation on {owner}"),
1263 "install the App on the account first; the setup guide's step 5 walks it",
1264 ))
1265}
1266
1267fn run_forge_step(engine: &mut Engine, step: &StepSpec) -> Result<Done, RkError> {
1269 run_forge_step_with(engine, step, None, Vec::new())
1270}
1271
1272fn run_forge_step_with(
1275 engine: &mut Engine,
1276 step: &StepSpec,
1277 stdin: Option<Zeroizing<Vec<u8>>>,
1278 extra_env: Vec<(OsString, OsString)>,
1279) -> Result<Done, RkError> {
1280 if crate::setup::before_state::destructive(step.name) {
1281 save_before_state(engine, step)?;
1282 }
1283 let (outcome, _) = run_script_with(engine, step, stdin, extra_env)?;
1284 if !outcome.success() {
1285 return Err(classify_failure(engine, step, &outcome));
1286 }
1287 let state = observe_with(engine, step.name)?;
1288 match state {
1289 StepState::Satisfied { detail, limitation } => Ok(Done::Changed(detail, limitation)),
1290 StepState::Inapplicable { detail } if step.name == "private-vulnerability-reporting" => {
1291 Ok(Done::Skipped(detail))
1292 }
1293 StepState::Unsatisfied { detail } | StepState::Inapplicable { detail } => {
1294 Err(RkError::refusal(
1295 Diagnostic::new(
1296 Reason::StateDrift,
1297 format!(
1298 "{} ran and its postcondition does not hold: {detail}",
1299 step.name
1300 ),
1301 )
1302 .expected(step.proves.to_owned())
1303 .step(step.name),
1304 ))
1305 }
1306 StepState::Unknown { detail } => Err(RkError::refusal(
1310 Diagnostic::new(
1311 Reason::ForgeTemporary,
1312 format!(
1313 "{} ran and the readback could not confirm it: {detail}",
1314 step.name
1315 ),
1316 )
1317 .expected(step.proves.to_owned())
1318 .action(format!(
1319 "rk setup step {} --target {} --apply re-asserts and re-proves it",
1320 step.name, engine.ctx.target
1321 ))
1322 .step(step.name),
1323 )),
1324 }
1325}
1326
1327fn save_before_state(engine: &mut Engine, step: &StepSpec) -> Result<(), RkError> {
1332 if let Some(held) = migration_snapshot(&engine.ctx.target, step.name)? {
1337 engine.out.result_line(format!(
1338 "the migration holds the before-state of {} at {held}",
1339 step.name
1340 ));
1341 let mut event = engine.event(EventKind::Snapshot, Some(step.name));
1342 event.detail = Some(held);
1343 engine.emit(&event);
1344 return Ok(());
1345 }
1346 let snapshot = if let Some(snapshot) = &engine.snapshot {
1347 snapshot.clone()
1348 } else {
1349 let canonical = std::fs::canonicalize(engine.ctx.target.as_std_path())?;
1350 let snapshot = crate::snapshot::Snapshot::begin(&canonical)?;
1351 engine.snapshot = Some(snapshot.clone());
1352 snapshot
1353 };
1354 let ctx = clone_ctx(&engine.ctx);
1355 let mut runner = |exec: &Exec| engine.exec(exec, false);
1356 let path = crate::setup::before_state::save(&ctx, step.name, &snapshot, &mut runner)?;
1357 let path = path.display().to_string();
1358 engine
1359 .out
1360 .result_line(format!("saved the before-state of {} to {path}", step.name));
1361 let mut event = engine.event(EventKind::Snapshot, Some(step.name));
1362 event.detail = Some(path);
1363 engine.emit(&event);
1364 Ok(())
1365}
1366
1367#[must_use]
1369pub fn forge_snapshot_id(step: &str) -> String {
1370 format!("forge-{step}")
1371}
1372
1373fn migration_snapshot(target: &camino::Utf8Path, step: &str) -> Result<Option<String>, RkError> {
1382 let Some(id) = crate::migrate::open_id(target)? else {
1383 return Ok(None);
1384 };
1385 let Some(workspace) = crate::migrate::open_workspace(target)? else {
1386 return Err(crate::migrate::none_open());
1387 };
1388 if !workspace.join(crate::migrate::REGISTRY_FILE).is_file() {
1389 return Err(crate::migrate::workspace_missing(&id, &workspace));
1390 }
1391 let registry = crate::migrate::registry::load(&workspace)?;
1392 let wanted = forge_snapshot_id(step);
1393 let found = registry
1396 .snapshots
1397 .iter()
1398 .find(|snapshot| snapshot.id == wanted);
1399 let intact = match found {
1400 Some(snapshot) => {
1401 crate::migrate::registry::integrity(&workspace, snapshot)?
1402 == crate::migrate::registry::Integrity::Intact
1403 }
1404 None => false,
1405 };
1406 let Some(snapshot) = found.filter(|_| intact) else {
1407 return Err(RkError::refusal(
1408 Diagnostic::new(
1409 Reason::DestructiveRefusal,
1410 format!(
1411 "{step} changes forge state, and the migration {id} holds no intact snapshot of it (migration:a-destructive-step-waits-for-its-snapshot)"
1412 ),
1413 )
1414 .expected("the step's before-state in the migration registry")
1415 .action("rk migrate archive --apply --target . takes the missing forge snapshots on a host that holds the forge credentials")
1416 .target_state("unchanged")
1417 .step(step),
1418 ));
1419 };
1420 Ok(Some(workspace.join(&snapshot.file).to_string()))
1421}
1422
1423#[derive(Debug, Clone, PartialEq, Eq)]
1425pub enum ForgeSnapshot {
1426 Taken(PathBuf),
1428 Unknown(String),
1430}
1431
1432pub fn migration_snapshots(
1443 target: &camino::Utf8PathBuf,
1444 snapshot: &crate::snapshot::Snapshot,
1445 skip: &[String],
1446) -> Result<Vec<(&'static str, ForgeSnapshot)>, RkError> {
1447 let mut ctx = Ctx::resolve(target, None, None, None)?;
1448 let steps: Vec<&StepSpec> = STEPS
1449 .iter()
1450 .filter(|step| {
1451 crate::setup::before_state::destructive(step.name)
1452 && stance(&ctx, step).acts()
1453 && !skip.contains(&forge_snapshot_id(step.name))
1454 })
1455 .collect();
1456 if steps.is_empty() {
1457 return Ok(Vec::new());
1458 }
1459 if let Err(error) = ctx.require_cli(&steps) {
1460 return Ok(steps
1461 .iter()
1462 .map(|step| (step.name, ForgeSnapshot::Unknown(error.to_string())))
1463 .collect());
1464 }
1465 let mut engine = Engine::open(Output::new(false), ctx, "migrate", false)?;
1468 let mut out = Vec::new();
1469 for step in steps {
1470 let ctx = clone_ctx(&engine.ctx);
1471 let mut runner = |exec: &Exec| engine.exec(exec, false);
1472 let taken = match crate::setup::before_state::save(&ctx, step.name, snapshot, &mut runner) {
1473 Ok(path) => ForgeSnapshot::Taken(path),
1474 Err(error) => ForgeSnapshot::Unknown(error.to_string()),
1475 };
1476 out.push((step.name, taken));
1477 }
1478 Ok(out)
1479}
1480
1481pub fn destructive_steps(target: &camino::Utf8PathBuf) -> Result<Vec<&'static str>, RkError> {
1488 let ctx = Ctx::resolve(target, None, None, None)?;
1489 Ok(STEPS
1490 .iter()
1491 .filter(|step| {
1492 crate::setup::before_state::destructive(step.name) && stance(&ctx, step).acts()
1493 })
1494 .map(|step| step.name)
1495 .collect())
1496}
1497
1498pub fn proof_word(target: &camino::Utf8PathBuf) -> Result<&'static str, RkError> {
1505 let ctx = Ctx::resolve(target, None, None, None)?;
1506 Ok(proof::judge(&ctx.target, &proof::subject(&ctx)).word())
1507}
1508
1509fn observe_with(engine: &mut Engine, step: &str) -> Result<StepState, RkError> {
1516 if step == "install-bot" && engine.ctx.forge == Some(Forge::Github) {
1517 let jwt = match app_jwt_for(engine)? {
1518 Ok(jwt) => jwt,
1519 Err(detail) => return Ok(StepState::Unknown { detail }),
1520 };
1521 return Ok(observe::github_install_bot(&engine.ctx, &jwt));
1522 }
1523 let ctx = clone_ctx(&engine.ctx);
1524 let mut runner = |exec: &Exec| engine.exec(exec, false);
1525 observe::observe(&ctx, step, &mut runner)
1526}
1527
1528fn key_file_for(engine: &mut Engine) -> Result<Option<&secrets::KeyFile>, RkError> {
1534 if engine.key.is_none() && engine.key_unavailable.is_none() {
1535 match secrets::look_up_key_file(&engine.ctx.target)? {
1536 secrets::KeyLookup::Absent => {}
1537 secrets::KeyLookup::Found(key) => {
1538 engine.secrets.push(key.bytes.clone());
1539 engine.key = Some(key);
1540 }
1541 secrets::KeyLookup::Unavailable(unavailable) if engine.key_boundary => {
1546 engine.key_unavailable = Some(unavailable.message);
1547 }
1548 secrets::KeyLookup::Unavailable(unavailable) => return Err(unavailable.refusal()),
1549 }
1550 }
1551 Ok(engine.key.as_ref())
1552}
1553
1554fn app_jwt_for(engine: &mut Engine) -> Result<Result<String, String>, RkError> {
1564 if let Some(jwt) = &engine.app_jwt {
1565 return Ok(Ok(jwt.clone()));
1566 }
1567 let app_id = app_jwt::app_id(engine.ctx.bot_app_id())?;
1568 let key_bytes = key_file_for(engine)?.map(|key| key.bytes.clone());
1569 if let Some(unreachable) = &engine.key_unavailable {
1570 return Ok(Err(format!(
1571 "the installation is readable only to the App itself, and this runtime cannot reach the key {} names: {unreachable}; a host that holds the key re-verifies it",
1572 secrets::PRIVATE_KEY_FILE
1573 )));
1574 }
1575 let (Some(app_id), Some(key_bytes)) = (app_id, key_bytes) else {
1576 return Ok(Err(format!(
1577 "the installation is readable only to the App itself; {}",
1578 app_jwt::REMEDIATION
1579 )));
1580 };
1581 let credentials = app_jwt::AppCredentials { app_id, key_bytes };
1582 let ctx = clone_ctx(&engine.ctx);
1583 Ok(match app_jwt::mint(&ctx, &credentials) {
1584 Ok(jwt) => {
1585 engine
1586 .secrets
1587 .push(Zeroizing::new(jwt.clone().into_bytes()));
1588 if let Some(signature) = jwt.rsplit('.').next() {
1589 engine
1590 .secrets
1591 .push(Zeroizing::new(signature.as_bytes().to_vec()));
1592 }
1593 engine.app_jwt = Some(jwt.clone());
1594 Ok(jwt)
1595 }
1596 Err(detail) => Err(detail),
1597 })
1598}
1599
1600fn state_detail(state: &StepState) -> String {
1601 state.detail().to_owned()
1602}
1603
1604fn run_script(engine: &mut Engine, step: &StepSpec) -> Result<(Outcome, PathBuf), RkError> {
1607 run_script_with(engine, step, None, Vec::new())
1608}
1609
1610fn run_script_with(
1616 engine: &mut Engine,
1617 step: &StepSpec,
1618 stdin: Option<Zeroizing<Vec<u8>>>,
1619 extra_env: Vec<(OsString, OsString)>,
1620) -> Result<(Outcome, PathBuf), RkError> {
1621 let forge = engine.ctx.adapter()?;
1622 let rel = format!("{}/{}", forge.as_str(), step.name);
1623 let bytes = embedded::SETUP
1624 .get_file(&rel)
1625 .map(include_dir::File::contents)
1626 .ok_or_else(|| RkError::Other(anyhow::anyhow!("no embedded script at setup/{rel}")))?;
1627 let journal = engine
1628 .journal
1629 .as_mut()
1630 .ok_or_else(|| RkError::Other(anyhow::anyhow!("an apply always has a journal")))?;
1631 let dir = journal.scripts_dir().join(forge.as_str());
1632 fs::create_dir_all(&dir)?;
1633 restrict(&dir, 0o700);
1634 let path = dir.join(step.name);
1635 fs::write(&path, bytes)?;
1636 restrict(&path, 0o600);
1637 let written = fs::read(&path)?;
1638 let digest = Digest::of(&written);
1639 if digest != Digest::of(bytes) {
1640 return Err(RkError::Other(anyhow::anyhow!(
1641 "the materialized script at {} differs from the embedded bytes",
1642 path.display()
1643 )));
1644 }
1645 journal.record_script(format!("scripts/{rel}"), digest.to_string());
1646 let mut env = engine.ctx.child_env(step.name);
1647 env.extend(extra_env);
1648 let exec = Exec {
1649 program: crate::probes::sh_bin(),
1650 args: vec![path.clone().into_os_string()],
1651 env,
1652 cwd: engine.ctx.target.as_std_path().to_path_buf(),
1653 stdin,
1654 };
1655 let outcome = engine.exec(&exec, true)?;
1656 Ok((outcome, path))
1657}
1658
1659fn classify_failure(engine: &Engine, step: &StepSpec, outcome: &Outcome) -> RkError {
1664 let stderr = String::from_utf8_lossy(&outcome.stderr);
1665 let last = if outcome.exit_code >= 128 {
1669 format!("killed by signal {}", outcome.exit_code - 128)
1670 } else {
1671 stderr
1672 .lines()
1673 .rev()
1674 .find(|line| !line.trim().is_empty())
1675 .unwrap_or("no output")
1676 .to_owned()
1677 };
1678 let reason = if (engine.ctx.forge == Some(Forge::Github) && outcome.exit_code == 4)
1679 || stderr.contains("HTTP 401")
1680 {
1681 Reason::ForgeAuthentication
1682 } else if stderr.contains("HTTP 403") {
1683 Reason::ForgePermission
1684 } else if stderr.contains("HTTP 429") || stderr.contains("rate limit") {
1685 Reason::ForgeRateLimit
1686 } else {
1687 Reason::SubprocessFailed
1688 };
1689 let diagnostic = Diagnostic::new(reason, format!("the forge refused '{}': {last}", step.name))
1690 .expected(step.proves.to_owned())
1691 .action(format!(
1692 "rk setup step {} --target {} --apply",
1693 step.name, engine.ctx.target
1694 ))
1695 .step(step.name);
1696 let diagnostic = match reason {
1697 Reason::ForgePermission => diagnostic.expected(format!(
1698 "repository administration write on {} for the authenticated account",
1699 engine.ctx.repo
1700 )),
1701 _ => diagnostic,
1702 };
1703 match reason {
1704 Reason::SubprocessFailed => RkError::subprocess(diagnostic),
1705 _ => RkError::refusal(diagnostic),
1706 }
1707}
1708
1709fn attach_progress(
1712 error: RkError,
1713 done: &[(String, String)],
1714 failed: &StepSpec,
1715 steps: &[&StepSpec],
1716) -> RkError {
1717 let remaining = steps.len().saturating_sub(done.len() + 1);
1718 let state = format!(
1719 "{} completed; {} failed; {remaining} not attempted",
1720 step_count(done.len()),
1721 failed.name
1722 );
1723 match error {
1724 RkError::Refusal(mut diagnostic) => {
1725 diagnostic.target_state.get_or_insert(state);
1726 RkError::Refusal(diagnostic)
1727 }
1728 RkError::Subprocess(mut diagnostic) => {
1729 diagnostic.target_state.get_or_insert(state);
1730 RkError::Subprocess(diagnostic)
1731 }
1732 other => other,
1733 }
1734}
1735
1736fn observe_all(engine: &mut Engine) -> Result<Report, RkError> {
1742 let mut report = Report::default();
1743 for step in &STEPS {
1744 let clock = Instant::now();
1745 let stance = stance(&engine.ctx, step);
1750 let row = if stance.acts() {
1751 let state = observe_with(engine, step.name)?;
1752 Row::observed(step, stance, &state)
1753 } else {
1754 Row::stated(step, stance)
1755 };
1756 engine.out.result_line(row.line());
1757 let (status, detail) = row.event_fields();
1758 let mut finished = engine.event(EventKind::StepFinished, Some(step.name));
1759 finished.status = Some(status);
1760 finished.detail = Some(detail);
1761 finished.duration_ms = Some(elapsed_ms(clock));
1762 engine.emit(&finished);
1763 report.rows.push(row);
1764 }
1765 if report.judged() < STEPS.len() {
1766 engine.out.result_line(format!(
1767 "{} judged; the rest do not apply to this target or {} excludes them",
1768 step_count(report.judged()),
1769 crate::config::CONFIG_PATH
1770 ));
1771 }
1772 Ok(report)
1773}
1774
1775fn check(out: Output, ctx: Ctx) -> Result<(), RkError> {
1779 let mut engine = Engine::open(out, ctx, "setup check", false)?;
1780 engine.key_boundary = true;
1781 let report = observe_all(&mut engine)?;
1782 for milestone in crate::setup::milestones::observe(&engine.ctx) {
1785 engine.out.result_line(milestone.line());
1786 let mut event = engine.event(EventKind::Milestone, Some(milestone.id));
1787 event.status = Some(milestone.status.to_owned());
1788 event.detail = Some(milestone.detail);
1789 engine.emit(&event);
1790 }
1791 if !report.checkpointable() {
1792 let error = verdict(&engine.ctx, &report);
1793 return Err(fail(&mut engine, error));
1794 }
1795 engine
1796 .out
1797 .next(&["rk guide release orders the first release".to_owned()]);
1798 engine.finish(0, None);
1799 Ok(())
1800}
1801
1802fn verdict(ctx: &Ctx, report: &Report) -> RkError {
1812 let unsatisfied = report.unsatisfied();
1813 let unknown = report.unknown();
1814 let standing = proof::judge(&ctx.target, &proof::subject(ctx));
1815 let proven = match &standing {
1816 Standing::Compatible(proof) => Some(proof),
1817 _ => None,
1818 };
1819 if unsatisfied == 0 {
1820 let state = proven.map_or_else(
1821 || {
1822 format!(
1823 "no setup defect was inferred; no compatible {} is committed, so the current state is unverified",
1824 proof::PROOF_PATH
1825 )
1826 },
1827 |proof| {
1828 format!(
1829 "no setup defect was inferred; the committed setup proof from {} by rk {} still matches this target's setup contract",
1830 proof.verified_at, proof.rk_version
1831 )
1832 },
1833 );
1834 return RkError::check_failed(
1835 Diagnostic::new(
1836 Reason::ObservationIncomplete,
1837 format!(
1838 "{} could not be verified from this runtime, and none is unsatisfied",
1839 step_count(unknown)
1840 ),
1841 )
1842 .expected("every applicable step readable from where the check runs")
1843 .action("rerun rk setup check where each unknown step can be observed; its line names what it needs")
1844 .target_state(state),
1845 );
1846 }
1847 let mut message = format!(
1848 "{} {} not satisfied",
1849 step_count(unsatisfied),
1850 if unsatisfied == 1 { "is" } else { "are" }
1851 );
1852 let mut action = format!(
1853 "rk setup --target {} --apply re-asserts the unsatisfied ones",
1854 ctx.target
1855 );
1856 if unknown > 0 {
1857 use std::fmt::Write as _;
1858 let _ = write!(
1859 message,
1860 ", and {unknown} could not be verified from this runtime"
1861 );
1862 action.push_str("; the unknown ones need a runtime that can observe what each line names");
1863 }
1864 let mut diagnostic = Diagnostic::new(Reason::StateDrift, message)
1865 .expected("every step's proof column to hold")
1866 .action(action);
1867 if let Some(proof) = proven {
1868 diagnostic = diagnostic.target_state(format!(
1869 "this observation supersedes the committed setup proof from {} by rk {}",
1870 proof.verified_at, proof.rk_version
1871 ));
1872 }
1873 RkError::check_failed(diagnostic)
1874}
1875
1876fn checkpoint(out: Output, ctx: Ctx) -> Result<(), RkError> {
1882 let mut engine = Engine::open(out, ctx, "setup checkpoint", false)?;
1883 let report = observe_all(&mut engine)?;
1884 let Some(proof) = proof::of(&engine.ctx, &report, crate::applog::now_utc()) else {
1885 let error = RkError::check_failed(
1886 Diagnostic::new(
1887 Reason::StateDrift,
1888 format!(
1889 "the observation is incomplete: {} not satisfied and {} could not be verified",
1890 step_count(report.unsatisfied()),
1891 report.unknown()
1892 ),
1893 )
1894 .expected("every applicable step observed and holding")
1895 .action(format!(
1896 "rk setup check --target {} names each gap; checkpoint again once none remains",
1897 engine.ctx.target
1898 ))
1899 .target_state(format!("{} was not written", proof::PROOF_PATH)),
1900 );
1901 return Err(fail(&mut engine, error));
1902 };
1903 if let Err(source) = proof::write(&engine.ctx.target, &proof) {
1904 let error = RkError::refusal(
1905 Diagnostic::new(
1906 Reason::Io,
1907 format!("{} cannot be written: {source}", proof::PROOF_PATH),
1908 )
1909 .expected("a writable .release-kit directory in the target")
1910 .target_state("the earlier proof, where one exists, is unchanged"),
1911 );
1912 return Err(fail(&mut engine, error));
1913 }
1914 engine.out.result_line(format!(
1915 "wrote {}: {} proven at {} by rk {}",
1916 proof::PROOF_PATH,
1917 step_count(proof.steps.len()),
1918 proof.verified_at,
1919 proof.rk_version
1920 ));
1921 engine.out.next(&[
1922 format!("commit {} with the setup it proves", proof::PROOF_PATH),
1923 format!(
1924 "rk setup status --target {} reads it offline",
1925 engine.ctx.target
1926 ),
1927 ]);
1928 engine.finish(0, None);
1929 Ok(())
1930}
1931
1932fn status(out: Output, ctx: &Ctx) -> Result<(), RkError> {
1938 let standing = proof::judge(&ctx.target, &proof::subject(ctx));
1939 out.emit(&proof::StatusDocument::of(&standing))?;
1940 match &standing {
1941 Standing::Absent => out.result_line(format!(
1942 "setup proof: absent — {} does not exist, so no complete observation is on record",
1943 proof::PROOF_PATH
1944 )),
1945 Standing::Compatible(proof) => out.result_line(format!(
1946 "setup proof: compatible — proven {} by rk {}, and this target's setup contract has not changed since",
1947 proof.verified_at, proof.rk_version
1948 )),
1949 Standing::Stale { proof, differences } => out.result_line(format!(
1950 "setup proof: stale — proven {} by rk {}, and the setup contract changed since: {}",
1951 proof.verified_at,
1952 proof.rk_version,
1953 differences.join(", ")
1954 )),
1955 Standing::Invalid { detail, .. } => {
1956 out.result_line(format!("setup proof: invalid — {detail}"));
1957 }
1958 }
1959 if let Standing::Compatible(proof) | Standing::Stale { proof, .. } = &standing {
1960 for step in &proof.steps {
1961 let limitation = step
1962 .limitation
1963 .as_ref()
1964 .map_or_else(String::new, |limit| format!(" (limitation: {limit})"));
1965 out.result_line(format!(" {} {}{limitation}", step.state, step.name));
1966 }
1967 }
1968 let next = match standing {
1969 Standing::Compatible(_) => format!(
1970 "rk setup check --target {} observes the forge now, where this runtime can",
1971 ctx.target
1972 ),
1973 _ => format!(
1974 "rk setup checkpoint --target {}, from a host that can observe every step, records a proof",
1975 ctx.target
1976 ),
1977 };
1978 out.next(&[next]);
1979 Ok(())
1980}
1981
1982fn restrict(path: &std::path::Path, mode: u32) {
1985 #[cfg(unix)]
1986 {
1987 use std::os::unix::fs::PermissionsExt as _;
1988 let _ = fs::set_permissions(path, fs::Permissions::from_mode(mode));
1989 }
1990 #[cfg(not(unix))]
1991 let _ = (path, mode);
1992}
1993
1994fn guard_sh() -> Result<(), RkError> {
1997 let ok = std::process::Command::new(crate::probes::sh_bin())
1998 .args(["-c", "exit 0"])
1999 .status()
2000 .is_ok_and(|status| status.success());
2001 if ok {
2002 Ok(())
2003 } else {
2004 Err(RkError::refusal(
2005 Diagnostic::new(Reason::PrerequisiteUnmet, "no POSIX sh runs on this host")
2006 .expected("a working sh on PATH; every step spawns through it")
2007 .action("install a POSIX shell, then rerun")
2008 .target_state("nothing was run and nothing changed"),
2009 ))
2010 }
2011}
2012
2013#[cfg(test)]
2014mod tests {
2015 #[test]
2018 fn a_step_count_carries_a_noun_that_agrees_with_it() {
2019 assert_eq!(super::step_count(0), "0 steps");
2020 assert_eq!(super::step_count(1), "1 step");
2021 assert_eq!(super::step_count(2), "2 steps");
2022 }
2023}