1use serde::Serialize;
17
18use crate::cli::status::StatusArgs;
19use crate::diagnostic::{Diagnostic, Reason};
20use crate::digest::Digest;
21use crate::error::RkError;
22use crate::landing::invariants::{self, InvariantFailure};
23use crate::landing::manifest::{self, Alignment, Manifest};
24use crate::landing::{self, Kind};
25use crate::output::Output;
26use crate::profile::RegistryAnswer;
27use crate::profile::{CapabilityRequests, GitWorkflow, ProfileSnapshot, ReleaseMode};
28use crate::projection::{Candidate, Projection, ProjectionInput, TargetEvidence};
29use crate::stage::CapabilityNote;
30use crate::{assess, embedded, registry};
31
32#[derive(Debug, Serialize)]
34struct Drift {
35 rendered: usize,
37 seeded: usize,
39}
40
41#[derive(Debug, Serialize)]
43struct StalePin {
44 tool: String,
46 landed: String,
48 available: String,
50}
51
52#[derive(Debug, Serialize)]
58struct Warning {
59 code: &'static str,
61 reason: String,
63}
64
65#[derive(Debug, Clone, Serialize)]
70struct SetupProof {
71 state: &'static str,
73 #[serde(skip_serializing_if = "Vec::is_empty")]
75 changed: Vec<String>,
76 #[serde(skip_serializing_if = "Option::is_none")]
78 reason: Option<&'static str>,
79 #[serde(skip_serializing_if = "Option::is_none")]
81 detail: Option<String>,
82}
83
84const SETUP_PROOF_REMEDIATION: &str = "run rk setup check --target ., then rk setup checkpoint --target ., and commit .release-kit/setup-proof.json; a step this forge cannot run goes in setup.excluded_steps with its reason, which keeps the proof complete";
87
88impl SetupProof {
89 fn of(standing: &crate::setup::proof::Standing) -> Self {
90 use crate::setup::proof::Standing;
91 let mut proof = Self {
92 state: standing.word(),
93 changed: Vec::new(),
94 reason: None,
95 detail: None,
96 };
97 match standing {
98 Standing::Stale { differences, .. } => proof.changed.clone_from(differences),
99 Standing::Invalid { reason, detail } => {
100 proof.reason = Some(reason);
101 proof.detail = Some(detail.clone());
102 }
103 Standing::Absent | Standing::Compatible(_) => {}
104 }
105 proof
106 }
107
108 fn failure(&self) -> Option<InvariantFailure> {
111 let (code, reason) = match self.state {
112 "absent" => (
113 "setup-proof-absent",
114 "no .release-kit/setup-proof.json is committed, so nothing proves the forge, the registry, and the bot meet the setup contract".to_owned(),
115 ),
116 "stale" => (
117 "setup-proof-stale",
118 format!(
119 "the committed setup proof was written for another setup contract; changed: {}",
120 self.changed.join(", ")
121 ),
122 ),
123 "invalid" => (
124 "setup-proof-invalid",
125 format!(
126 "the committed setup proof cannot be read: {}: {}",
127 self.reason.unwrap_or("invalid"),
128 self.detail.as_deref().unwrap_or("")
129 ),
130 ),
131 _ => return None,
132 };
133 Some(InvariantFailure {
134 code,
135 destination: crate::setup::proof::PROOF_PATH.to_owned(),
136 reason,
137 remediation: SETUP_PROOF_REMEDIATION,
138 })
139 }
140}
141
142fn setup_proof_of(
146 target: &camino::Utf8PathBuf,
147 manifest: &Manifest,
148) -> Result<Option<SetupProof>, RkError> {
149 if manifest.profile.release.mode != ReleaseMode::Automatic || manifest.profile.forge.is_none() {
150 return Ok(None);
151 }
152 Ok(Some(SetupProof::of(&crate::setup::proof::offline(target)?)))
153}
154
155const CODE_SCANNING_LICENCE: &str = "code-scanning-licence";
157
158#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
163#[serde(rename_all = "kebab-case")]
164pub enum Classification {
165 Setup,
167 Migration,
169 NeedsDecision,
171 Adopt,
173 Upgrade,
175 Drift,
177 Current,
179}
180
181impl Classification {
182 #[must_use]
184 pub const fn as_str(self) -> &'static str {
185 match self {
186 Self::Setup => "setup",
187 Self::Migration => "migration",
188 Self::NeedsDecision => "needs-decision",
189 Self::Adopt => "adopt",
190 Self::Upgrade => "upgrade",
191 Self::Drift => "drift",
192 Self::Current => "current",
193 }
194 }
195}
196
197const fn unrecorded(class: assess::Unrecorded) -> Classification {
200 match class {
201 assess::Unrecorded::Adopt => Classification::Adopt,
202 assess::Unrecorded::Assessed(assess::Classification::Greenfield) => Classification::Setup,
203 assess::Unrecorded::Assessed(assess::Classification::Brownfield) => {
204 Classification::Migration
205 }
206 assess::Unrecorded::Assessed(assess::Classification::NeedsDecision) => {
207 Classification::NeedsDecision
208 }
209 }
210}
211
212const fn recorded(alignment: Alignment, clean: bool) -> Option<Classification> {
216 match alignment {
217 Alignment::TargetNewer => None,
218 Alignment::BinaryNewer => Some(Classification::Upgrade),
219 Alignment::Aligned if clean => Some(Classification::Current),
220 Alignment::Aligned => Some(Classification::Drift),
221 }
222}
223
224#[derive(Debug, Clone, Serialize)]
226struct SentinelAt {
227 file: String,
229 line: usize,
231 text: String,
233}
234
235#[derive(Debug, Serialize)]
237struct LegacyPath {
238 path: String,
240 kind: &'static str,
242 active: bool,
244}
245
246fn legacy_state() -> Vec<LegacyPath> {
255 let Some(root) = crate::applog::state_root() else {
256 return Vec::new();
257 };
258 let mut found = Vec::new();
259 if let Ok(entries) = std::fs::read_dir(root.join(LEGACY_PLANS)) {
260 let mut plans: Vec<std::path::PathBuf> = entries
261 .flatten()
262 .filter(|entry| !entry.file_name().to_string_lossy().starts_with('.'))
263 .map(|entry| entry.path())
264 .filter(|path| path.is_dir())
265 .collect();
266 plans.sort();
267 for plan in plans {
268 let active = std::fs::read(plan.join("plan.json"))
269 .ok()
270 .and_then(|bytes| serde_json::from_slice::<serde_json::Value>(&bytes).ok())
271 .is_none_or(|document| document["readiness"].as_str() == Some("ready"));
272 found.push(LegacyPath {
273 path: plan.display().to_string(),
274 kind: "plan",
275 active,
276 });
277 }
278 }
279 let cache = root.join(LEGACY_RELEASE_CACHE);
280 if cache.is_dir() {
281 found.push(LegacyPath {
282 path: cache.display().to_string(),
283 kind: "release-cache",
284 active: false,
285 });
286 }
287 found
288}
289
290const LEGACY_PLANS: &str = "plans";
292
293const LEGACY_RELEASE_CACHE: &str = "release";
295
296const SCHEMA: &str = "rk.status/14";
298
299#[derive(Debug, serde::Serialize)]
301struct ConfigState {
302 state: &'static str,
303 pending: Vec<String>,
304}
305
306fn config_state(config: Option<&crate::config::Config>, record: Option<&Manifest>) -> ConfigState {
307 let pending = config
308 .zip(record)
309 .map_or_else(Vec::new, |(config, record)| {
310 crate::config::pending(config, record)
311 });
312 ConfigState {
313 state: if config.is_none() {
314 "absent"
315 } else if pending.is_empty() {
316 "aligned"
317 } else {
318 "pending"
319 },
320 pending,
321 }
322}
323
324#[derive(Debug, Serialize)]
326struct Report {
327 schema: &'static str,
329 landed: bool,
331 classification: Option<Classification>,
334 git_work_tree: bool,
336 config: ConfigState,
337 #[serde(skip_serializing_if = "Option::is_none")]
339 profile: Option<ProfileSnapshot>,
340 #[serde(skip_serializing_if = "Option::is_none")]
342 git: Option<GitWorkflow>,
343 #[serde(skip_serializing_if = "Option::is_none")]
345 capabilities: Option<CapabilityRequests>,
346 #[serde(skip_serializing_if = "Option::is_none")]
349 selection: Option<Vec<CapabilityNote>>,
350 #[serde(skip_serializing_if = "Option::is_none")]
351 rk_version: Option<String>,
352 #[serde(skip_serializing_if = "Option::is_none")]
353 binary_version: Option<&'static str>,
354 #[serde(skip_serializing_if = "Option::is_none")]
355 alignment: Option<Alignment>,
356 #[serde(skip_serializing_if = "Option::is_none")]
357 drift: Option<Drift>,
358 #[serde(skip_serializing_if = "Option::is_none")]
360 missing: Option<Vec<String>>,
361 #[serde(skip_serializing_if = "Option::is_none")]
362 stale_pins: Option<Vec<StalePin>>,
363 #[serde(skip_serializing_if = "Option::is_none")]
365 sentinels: Option<usize>,
366 #[serde(skip_serializing_if = "Option::is_none")]
368 sentinel_locations: Option<Vec<SentinelAt>>,
369 #[serde(skip_serializing_if = "Option::is_none")]
373 record_drift: Option<usize>,
374 #[serde(skip_serializing_if = "Option::is_none")]
377 invariant_failures: Option<Vec<InvariantFailure>>,
378 #[serde(skip_serializing_if = "Option::is_none")]
382 warnings: Option<Vec<Warning>>,
383 #[serde(skip_serializing_if = "Option::is_none")]
386 setup_proof: Option<SetupProof>,
387 #[serde(skip_serializing_if = "Option::is_none")]
393 pending: Option<usize>,
394 #[serde(skip_serializing_if = "Option::is_none")]
396 violations: Option<Vec<String>>,
397 legacy_state: Vec<LegacyPath>,
399 #[serde(skip_serializing_if = "Option::is_none")]
401 migration: Option<OpenMigration>,
402}
403
404#[derive(Debug, Serialize)]
406struct OpenMigration {
407 id: String,
409 #[serde(skip_serializing_if = "Option::is_none")]
411 workspace: Option<String>,
412 #[serde(skip_serializing_if = "Option::is_none")]
415 unfinished: Option<usize>,
416}
417
418fn open_migration(
423 target: &camino::Utf8Path,
424 config: Option<&crate::config::Config>,
425) -> Option<OpenMigration> {
426 let id = config.and_then(|config| config.migration.clone())?;
427 let workspace = crate::migrate::open_workspace(target).ok().flatten();
428 let unfinished = workspace
429 .as_ref()
430 .filter(|workspace| workspace.join(crate::migrate::REGISTRY_FILE).is_file())
431 .and_then(|workspace| crate::migrate::registry::load(workspace).ok())
432 .map(|registry| {
433 registry
434 .sources
435 .iter()
436 .filter(|source| !source.status.finished())
437 .count()
438 });
439 Some(OpenMigration {
440 id,
441 workspace: workspace.map(|workspace| workspace.to_string()),
442 unfinished,
443 })
444}
445
446fn render_migration(out: Output, migration: Option<&OpenMigration>) {
448 if let Some(migration) = migration {
449 out.result_line(format!(
450 "migration {} is open; rk migrate status reads it",
451 migration.id
452 ));
453 }
454}
455
456fn report_absent(
457 out: Output,
458 args: &StatusArgs,
459 config: Option<&crate::config::Config>,
460 git_work_tree: bool,
461) -> Result<(), RkError> {
462 let migration = open_migration(&args.target, config);
463 let classification = match assess::standing(&args.target, config)? {
464 assess::Standing::Migrating => Classification::Migration,
465 assess::Standing::Unrecorded(class) => unrecorded(class),
466 };
467 let legacy = legacy_state();
468 out.result_line(format!("config: {}", config_state(config, None).state));
469 out.result_line(format!("no landing at {}", args.target));
470 out.result_line(format!("classification: {}", classification.as_str()));
471 render_migration(out, migration.as_ref());
472 render_context(out, git_work_tree, &legacy);
473 out.next(&[
474 format!(
475 "rk profile --target {} reports what a landing would select",
476 args.target
477 ),
478 format!("rk init --target {} lands the workflow", args.target),
479 format!(
480 "rk adopt --target {} records a landing made before the receipt existed",
481 args.target
482 ),
483 format!(
484 "rk stage --target {} stages this binary's candidate; the rk-setup skill carries the best-effort migration",
485 args.target
486 ),
487 ]);
488 out.emit(&Report {
489 schema: SCHEMA,
490 landed: false,
491 classification: Some(classification),
492 git_work_tree,
493 config: config_state(config, None),
494 profile: None,
495 git: None,
496 capabilities: None,
497 selection: None,
498 rk_version: None,
499 binary_version: None,
500 alignment: None,
501 drift: None,
502 missing: None,
503 stale_pins: None,
504 sentinels: None,
505 sentinel_locations: None,
506 record_drift: None,
507 invariant_failures: None,
508 warnings: None,
509 setup_proof: None,
510 pending: None,
511 violations: args.check.then(|| vec!["no landing".to_owned()]),
512 legacy_state: legacy,
513 migration,
514 })?;
515 if args.check {
516 return Err(RkError::check_failed(
517 Diagnostic::new(
518 Reason::StateDrift,
519 format!("no landing at {}, and --check requires one", args.target),
520 )
521 .expected("a target carrying .release-kit/manifest.json")
522 .action("rk init lands the workflow; rk adopt records an existing landing; rk stage and the rk-setup skill carry the migration"),
523 ));
524 }
525 Ok(())
526}
527
528struct Observed {
530 drift_rendered: Vec<String>,
531 drift_seeded: Vec<String>,
532 parameter_drift: Vec<String>,
535 record_drift: Vec<String>,
540 missing: Vec<String>,
541 stale: Vec<StalePin>,
542 sentinels: Vec<(String, usize, String)>,
543 invariants: Vec<InvariantFailure>,
544 warnings: Vec<Warning>,
546 setup_proof: Option<SetupProof>,
547 incompatible: Vec<String>,
553 pending: Option<Vec<String>>,
557 selection: Option<Vec<CapabilityNote>>,
559}
560
561pub fn run(args: &StatusArgs) -> Result<(), RkError> {
570 let out = Output::new(args.json);
571 if !args.target.is_dir() {
572 return Err(RkError::missing(
573 Diagnostic::new(
574 Reason::TargetNotFound,
575 format!("target {} is not a directory", args.target),
576 )
577 .expected("an existing repository to report on"),
578 ));
579 }
580 let config = crate::config::load(args.target.as_std_path())?;
581 let git_work_tree = assess::git_work_tree(&args.target)?;
582 let Some(manifest) = manifest::load(&args.target)? else {
583 return report_absent(out, args, config.as_ref(), git_work_tree);
584 };
585
586 let migration = open_migration(&args.target, config.as_ref());
587 let stated = Stated::of(config.as_ref(), &manifest);
588 let config = config_state(config.as_ref(), Some(&manifest));
589 out.result_line(format!("config: {}", config.state));
590 for key in &config.pending {
591 out.result_line(format!(
592 "config pending: {key}; rk upgrade --apply takes it up"
593 ));
594 }
595 let mut observed = observe(args, &manifest, &stated)?;
596 observed.setup_proof = setup_proof_of(&args.target, &manifest)?;
597 let alignment = manifest::alignment(&manifest.rk_version, env!("CARGO_PKG_VERSION"));
598 render_human(out, args, &manifest, alignment, &observed);
599
600 let violations = violations_of(&observed);
601 let classification = if migration.is_some() && alignment != Alignment::TargetNewer {
605 Some(Classification::Migration)
606 } else {
607 recorded(alignment, violations.is_empty())
608 };
609 out.result_line(format!(
610 "classification: {}",
611 classification.map_or(
612 "none: the record is newer than this binary",
613 Classification::as_str
614 )
615 ));
616 render_migration(out, migration.as_ref());
617 let legacy = legacy_state();
618 render_context(out, git_work_tree, &legacy);
619 out.emit(&Report {
620 schema: SCHEMA,
621 landed: true,
622 classification,
623 git_work_tree,
624 config,
625 profile: Some(manifest.profile.clone()),
626 git: Some(manifest.git.clone()),
627 capabilities: Some(manifest.capabilities.clone()),
628 selection: observed.selection.clone(),
629 rk_version: Some(manifest.rk_version),
630 binary_version: Some(env!("CARGO_PKG_VERSION")),
631 alignment: Some(alignment),
632 drift: Some(Drift {
633 rendered: observed.drift_rendered.len() + observed.parameter_drift.len(),
634 seeded: observed.drift_seeded.len(),
635 }),
636 record_drift: Some(observed.record_drift.len()),
637 missing: Some(observed.missing.clone()),
638 stale_pins: Some(observed.stale),
639 sentinels: Some(observed.sentinels.len()),
640 sentinel_locations: Some(
641 observed
642 .sentinels
643 .iter()
644 .map(|(file, line, text)| SentinelAt {
645 file: file.clone(),
646 line: *line,
647 text: text.clone(),
648 })
649 .collect(),
650 ),
651 invariant_failures: Some(observed.invariants),
652 warnings: Some(observed.warnings),
653 setup_proof: observed.setup_proof.clone(),
654 pending: observed.pending.as_ref().map(Vec::len),
655 violations: args.check.then(|| violations.clone()),
656 legacy_state: legacy,
657 migration,
658 })?;
659
660 if args.check && !violations.is_empty() {
661 return Err(RkError::check_failed(
662 Diagnostic::new(
663 Reason::StateDrift,
664 format!(
665 "the landing is not clean: {} violation{}",
666 violations.len(),
667 if violations.len() == 1 { "" } else { "s" }
668 ),
669 )
670 .expected(
671 "no rendered drift, no missing recorded file, no unresolved sentinel, no invariant failure",
672 ),
673 ));
674 }
675 Ok(())
676}
677
678fn render_context(out: Output, git_work_tree: bool, legacy: &[LegacyPath]) {
682 if !git_work_tree {
683 out.result_line("not a non-bare Git work tree: the method lands files a work tree commits");
684 }
685 for entry in legacy {
686 out.result_line(format!(
687 "LEGACY {} ({}, {})",
688 entry.path,
689 entry.kind,
690 if entry.active { "active" } else { "inactive" }
691 ));
692 }
693}
694
695fn violations_of(observed: &Observed) -> Vec<String> {
699 observed
700 .drift_rendered
701 .iter()
702 .map(|path| format!("rendered drift: {path}"))
703 .chain(
704 observed
705 .parameter_drift
706 .iter()
707 .map(|path| format!("parameter drift: {path}")),
708 )
709 .chain(
710 observed
711 .record_drift
712 .iter()
713 .map(|reason| format!("record drift: {reason}")),
714 )
715 .chain(
716 observed
717 .missing
718 .iter()
719 .map(|path| format!("missing: {path}")),
720 )
721 .chain(
722 observed
723 .sentinels
724 .iter()
725 .map(|(path, line, _)| format!("sentinel: {path}:{line}")),
726 )
727 .chain(
728 observed
729 .invariants
730 .iter()
731 .map(|failure| format!("invariant: {}: {}", failure.destination, failure.code)),
732 )
733 .chain(
734 observed
735 .setup_proof
736 .as_ref()
737 .and_then(SetupProof::failure)
738 .map(|failure| format!("setup proof: {}", failure.code)),
739 )
740 .collect()
741}
742
743struct Stated {
746 registry: Option<RegistryAnswer>,
748 required_check: String,
750}
751
752impl Stated {
753 fn of(config: Option<&crate::config::Config>, manifest: &Manifest) -> Self {
754 Self {
755 registry: config
756 .and_then(|config| config.profile.release.registry)
757 .or(manifest.profile.release.registry),
758 required_check: config.map_or_else(
761 || manifest.parameters.required_check.clone(),
762 |config| config.setup.required_check.clone(),
763 ),
764 }
765 }
766}
767
768#[allow(
771 clippy::too_many_lines,
772 reason = "one pass over the record and the disk answers every comparison the report states"
773)]
774fn observe(args: &StatusArgs, manifest: &Manifest, stated: &Stated) -> Result<Observed, RkError> {
775 let mut observed = Observed {
776 drift_rendered: Vec::new(),
777 drift_seeded: Vec::new(),
778 parameter_drift: Vec::new(),
779 record_drift: Vec::new(),
780 missing: Vec::new(),
781 stale: Vec::new(),
782 sentinels: Vec::new(),
783 invariants: Vec::new(),
784 warnings: Vec::new(),
785 setup_proof: None,
786 incompatible: Vec::new(),
787 pending: None,
788 selection: None,
789 };
790 let aligned =
796 manifest::alignment(&manifest.rk_version, env!("CARGO_PKG_VERSION")) == Alignment::Aligned;
797 let projected = match project(args, manifest) {
798 Ok(projection) => Some(projection),
799 Err(err) if aligned => return Err(err),
800 Err(_) => None,
801 };
802 for file in &manifest.files {
803 let Some(bytes) = landing::read_recorded(&args.target, &file.destination)? else {
804 observed.missing.push(file.destination.clone());
805 continue;
806 };
807 if Digest::of(&bytes) != file.sha256 {
808 match file.kind {
809 Kind::Rendered => observed.drift_rendered.push(file.destination.clone()),
810 Kind::Seeded => observed.drift_seeded.push(file.destination.clone()),
811 Kind::State => {}
812 }
813 }
814 observed.invariants.extend(invariants::failures(
815 manifest.profile.release.driver.as_deref().unwrap_or(""),
816 manifest.profile.forge.as_deref().unwrap_or(""),
817 &file.destination,
818 &bytes,
819 stated.registry,
820 ));
821 let text = String::from_utf8_lossy(&bytes);
822 for (idx, line) in text.lines().enumerate() {
823 if line.contains(embedded::SENTINEL) {
824 observed.sentinels.push((
825 file.destination.clone(),
826 idx + 1,
827 line.trim().to_owned(),
828 ));
829 }
830 }
831 let defective = projected.as_ref().is_some_and(|projection| {
836 projection
837 .collisions
838 .iter()
839 .any(|collision| collision.destination == file.destination)
840 });
841 if defective && !observed.drift_rendered.contains(&file.destination) {
842 observed.drift_rendered.push(file.destination.clone());
843 }
844 }
845 observed.invariants.extend(invariants::target_failures(
850 manifest.profile.release.driver.as_deref().unwrap_or(""),
851 manifest.profile.forge.as_deref().unwrap_or(""),
852 &args.target,
853 ));
854 if manifest.profile.release.driver.as_deref() == Some("rust")
857 && manifest.profile.forge.as_deref() == Some("github")
858 {
859 let gate = invariants::dist_targets_built(&args.target, &stated.required_check);
860 observed.invariants.extend(gate.failures);
861 observed.warnings.extend(
862 gate.limitations
863 .into_iter()
864 .map(|(code, reason)| Warning { code, reason }),
865 );
866 }
867 observed.selection = projected.as_ref().map(|projection| {
868 projection
869 .capabilities
870 .iter()
871 .map(|selection| CapabilityNote::of(selection, projection))
872 .collect()
873 });
874 if let Some(reason) = projected
875 .as_ref()
876 .and_then(|projection| projection.licence_refusal.clone())
877 {
878 observed.warnings.push(Warning {
879 code: CODE_SCANNING_LICENCE,
880 reason,
881 });
882 }
883 if let Some(projection) = projected.as_ref() {
888 observed.incompatible.clone_from(&projection.record_defects);
889 observed
890 .record_drift
891 .extend(projection.record_defects.iter().cloned());
892 }
893 if aligned && let Some(projection) = projected.as_ref() {
894 observe_parameter_drift(manifest, projection, &mut observed);
895 observe_record_set(manifest, projection, &mut observed.record_drift);
896 }
897 observed.pending = projected
902 .as_ref()
903 .map(|projection| pending_of(manifest, &projection.candidates));
904 for (tool, landed) in &manifest.pins {
908 if let Some(available) = registry::version_of(tool)
909 && manifest::version_is_newer(&available, landed)
910 {
911 observed.stale.push(StalePin {
912 tool: tool.clone(),
913 landed: landed.clone(),
914 available,
915 });
916 }
917 }
918 Ok(observed)
919}
920
921fn observe_parameter_drift(manifest: &Manifest, projection: &Projection, observed: &mut Observed) {
933 for candidate in &projection.candidates {
934 if candidate.kind != Kind::Rendered {
935 continue;
936 }
937 let Some(record) = manifest.file(&candidate.destination) else {
938 continue;
939 };
940 if observed.drift_rendered.contains(&candidate.destination)
941 || observed.missing.contains(&candidate.destination)
942 {
943 continue;
944 }
945 if Digest::of(recorded_form(candidate)) != record.sha256 {
946 observed
947 .parameter_drift
948 .push(format!("{} (parameters)", candidate.destination));
949 }
950 }
951}
952
953fn project(args: &StatusArgs, manifest: &Manifest) -> Result<Projection, RkError> {
957 let evidence = TargetEvidence::gather(&args.target, Some(manifest))?;
958 Projection::compute(&ProjectionInput {
959 params: landing::Params::from_record(manifest),
960 evidence,
961 })
962}
963
964fn recorded_form(candidate: &Candidate) -> &[u8] {
967 candidate.region.as_deref().unwrap_or(&candidate.bytes)
968}
969
970fn pending_of(manifest: &Manifest, projected: &[Candidate]) -> Vec<String> {
979 let mut pending = Vec::new();
980 for entry in projected {
981 let changed = manifest.file(&entry.destination).is_none_or(|record| {
982 record.kind != entry.kind
983 || (entry.kind == Kind::Rendered
984 && record.sha256 != Digest::of(recorded_form(entry)))
985 });
986 if changed {
987 pending.push(entry.destination.clone());
988 }
989 }
990 for file in &manifest.files {
991 if !projected
992 .iter()
993 .any(|entry| entry.destination == file.destination)
994 {
995 pending.push(file.destination.clone());
996 }
997 }
998 pending.sort();
999 pending.dedup();
1000 pending
1001}
1002
1003fn observe_record_set(
1015 manifest: &Manifest,
1016 projection: &Projection,
1017 record_drift: &mut Vec<String>,
1018) {
1019 for entry in &projection.candidates {
1020 if manifest.file(&entry.destination).is_none() {
1021 record_drift.push(format!(
1022 "the recorded parameters project {}, which the receipt does not name",
1023 entry.destination
1024 ));
1025 }
1026 }
1027 for file in &manifest.files {
1028 let produced = projection
1029 .candidates
1030 .iter()
1031 .any(|entry| entry.destination == file.destination)
1032 || projection
1033 .omissions
1034 .iter()
1035 .any(|omission| omission.destination == file.destination);
1036 if !produced {
1037 record_drift.push(format!(
1038 "the receipt names {}, which the recorded parameters do not project",
1039 file.destination
1040 ));
1041 }
1042 }
1043}
1044
1045#[allow(
1047 clippy::too_many_lines,
1048 reason = "one pass prints every reportable condition in the order the report states them"
1049)]
1050fn render_human(
1051 out: Output,
1052 args: &StatusArgs,
1053 manifest: &Manifest,
1054 alignment: Alignment,
1055 observed: &Observed,
1056) {
1057 out.result_line(format!(
1058 "release-kit {} at {}: {}",
1059 manifest.rk_version,
1060 args.target,
1061 crate::commands::profile::describe(
1062 &manifest.profile,
1063 &manifest.git,
1064 &manifest.capabilities,
1065 &manifest.parameters.repo
1066 )
1067 ));
1068 for note in observed.selection.iter().flatten() {
1072 if note.status != "selected" {
1073 out.result_line(format!(
1074 "capability {}: {}{}",
1075 note.id,
1076 note.status,
1077 note.reason
1078 .as_deref()
1079 .map_or_else(String::new, |reason| format!(" ({reason})"))
1080 ));
1081 }
1082 }
1083 if alignment == Alignment::TargetNewer {
1084 out.result_line(format!(
1085 "binary {} is older than this landing; install the matching rk",
1086 env!("CARGO_PKG_VERSION")
1087 ));
1088 }
1089 match observed.pending.as_deref() {
1090 None => out.result_line(format!(
1091 "this binary carries no projection for the recorded {} release on {}, so what an upgrade would change is unknown",
1092 manifest
1093 .profile
1094 .release
1095 .driver
1096 .as_deref()
1097 .unwrap_or("release-less"),
1098 manifest.profile.forge.as_deref().unwrap_or("no forge")
1099 )),
1100 Some(paths) => {
1101 for path in paths {
1102 out.result_line(format!("PENDING {path} (this binary would change it)"));
1103 }
1104 }
1105 }
1106 for path in &observed.drift_rendered {
1107 out.result_line(format!("DRIFT {path} (rendered, release-kit-owned)"));
1108 }
1109 for path in &observed.parameter_drift {
1110 out.result_line(format!(
1111 "DRIFT {path}: the recorded parameters do not render the recorded bytes"
1112 ));
1113 }
1114 for reason in &observed.record_drift {
1115 out.result_line(format!("DRIFT record: {reason}"));
1116 }
1117 for path in &observed.drift_seeded {
1118 out.result_line(format!("DRIFT {path} (seeded, target-owned)"));
1119 }
1120 for path in &observed.missing {
1121 out.result_line(format!("MISSING {path}"));
1122 }
1123 for pin in &observed.stale {
1124 out.result_line(format!(
1125 "STALE {} {} landed, {} in this binary",
1126 pin.tool, pin.landed, pin.available
1127 ));
1128 }
1129 for (path, line, text) in &observed.sentinels {
1130 out.result_line(format!("SENTINEL {path}:{line}: {text}"));
1131 }
1132 for failure in &observed.invariants {
1133 out.result_line(format!(
1134 "INVARIANT {} ({}): {}",
1135 failure.destination, failure.code, failure.reason
1136 ));
1137 }
1138 for warning in &observed.warnings {
1139 out.result_line(format!("WARNING ({}): {}", warning.code, warning.reason));
1140 }
1141 let proof_failure = observed.setup_proof.as_ref().and_then(SetupProof::failure);
1142 if let Some(proof) = &observed.setup_proof {
1143 out.result_line(format!("setup proof: {}", proof.state));
1144 }
1145 if let Some(failure) = &proof_failure {
1146 out.result_line(format!(
1147 "SETUP-PROOF ({}): {}",
1148 failure.code, failure.reason
1149 ));
1150 }
1151 let mut next = Vec::new();
1152 for failure in observed.invariants.iter().chain(&proof_failure) {
1153 next.push(format!("{}: {}", failure.destination, failure.remediation));
1154 }
1155 if !observed.incompatible.is_empty() {
1159 next.push(format!(
1160 "rk upgrade --release-mode none --target {} retires the release intent this target cannot run; name a driver and forge this release carries to keep one",
1161 args.target
1162 ));
1163 }
1164 if observed.record_drift.len() > observed.incompatible.len() {
1165 next.push(format!(
1166 "rk upgrade --target {} rewrites the receipt from its parameters",
1167 args.target
1168 ));
1169 }
1170 if observed
1171 .pending
1172 .as_deref()
1173 .is_none_or(|paths| !paths.is_empty())
1174 {
1175 next.push(format!(
1176 "rk upgrade --target {} takes this landing to {}",
1177 args.target,
1178 env!("CARGO_PKG_VERSION")
1179 ));
1180 }
1181 next.push(format!(
1182 "rk status --check --target {} exits 1 on a violation",
1183 args.target
1184 ));
1185 if manifest.profile.release.mode != ReleaseMode::Automatic {
1186 next.retain(|line| !line.contains("rk method operate"));
1187 }
1188 out.next(&next);
1189}
1190
1191#[cfg(test)]
1192mod tests {
1193 use super::{
1194 Classification, Drift, InvariantFailure, LegacyPath, OpenMigration, Report, SentinelAt,
1195 StalePin,
1196 };
1197 use crate::assess::{self, Facts, OwnLanding, Unrecorded};
1198 use crate::landing::CheckoutMode;
1199 use crate::landing::Integration;
1200 use crate::landing::manifest::Alignment;
1201 use crate::profile::{
1202 CapabilityRequests, GitWorkflow, ProfileSnapshot, ReleaseIntent, ReleaseMode,
1203 };
1204
1205 #[test]
1208 #[allow(
1209 clippy::too_many_lines,
1210 reason = "the snapshot states every field of both forms in one place"
1211 )]
1212 fn the_status_report_schema_snapshot_holds() {
1213 let landed = Report {
1214 schema: super::SCHEMA,
1215 landed: true,
1216 classification: Some(Classification::Upgrade),
1217 git_work_tree: true,
1218 config: super::ConfigState {
1219 state: "pending",
1220 pending: vec!["profile.release.style".into()],
1221 },
1222 profile: Some(ProfileSnapshot {
1223 technologies: vec!["rust".into()],
1224 forge: Some("github".into()),
1225 release: ReleaseIntent {
1226 mode: ReleaseMode::Automatic,
1227 driver: Some("rust".into()),
1228 style: Some(crate::landing::Style::Trunk),
1229 line_prefix: Some("release/".into()),
1230 registry: None,
1231 },
1232 }),
1233 git: Some(GitWorkflow {
1234 trunk: "master".into(),
1235 checkout_mode: CheckoutMode::LinkedWorktree,
1236 integration: Integration::Local,
1237 merge_form: crate::landing::MergeForm::Squash,
1238 }),
1239 capabilities: Some(CapabilityRequests {
1240 nix_packaging: true,
1241 reporting_policy: true,
1242 scorecard: false,
1243 code_scanning: Some(crate::landing::Provider::Semgrep),
1244 workflow_guards: Some(false),
1245 }),
1246 selection: Some(vec![]),
1247 rk_version: Some("0.1.0".into()),
1248 binary_version: Some("0.2.0"),
1249 alignment: Some(crate::landing::manifest::Alignment::BinaryNewer),
1250 drift: Some(Drift {
1251 rendered: 0,
1252 seeded: 1,
1253 }),
1254 missing: Some(vec![]),
1255 stale_pins: Some(vec![StalePin {
1256 tool: "release-plz".into(),
1257 landed: "0.3.160".into(),
1258 available: "0.3.170".into(),
1259 }]),
1260 sentinels: Some(1),
1261 sentinel_locations: Some(vec![SentinelAt {
1262 file: "release-plz.toml".into(),
1263 line: 18,
1264 text: "# TODO(release-kit): keep false for a binary-only crate".into(),
1265 }]),
1266 record_drift: Some(0),
1267 invariant_failures: Some(vec![InvariantFailure {
1268 code: "attestations-disabled",
1269 destination: "dist-workspace.toml".into(),
1270 reason: "github-attestations is not effectively true".into(),
1271 remediation: "set github-attestations = true in [dist]",
1272 }]),
1273 warnings: Some(vec![super::Warning {
1274 code: super::CODE_SCANNING_LICENCE,
1275 reason: "the target's license, LicenseRef-proprietary, does not state a codebase this release recognizes as open source".into(),
1276 }]),
1277 setup_proof: Some(super::SetupProof {
1278 state: "stale",
1279 changed: vec!["target.required_check".into()],
1280 reason: None,
1281 detail: None,
1282 }),
1283 pending: Some(2),
1284 violations: None,
1285 legacy_state: vec![LegacyPath {
1286 path: "/state/release-kit/plans/0123456789abcdef".into(),
1287 kind: "plan",
1288 active: true,
1289 }],
1290 migration: Some(OpenMigration {
1291 id: "20261009T140205Z".into(),
1292 workspace: Some(
1293 "/state/release-kit/migrations/widget-0123456789ab/20261009T140205Z".into(),
1294 ),
1295 unfinished: Some(2),
1296 }),
1297 };
1298 assert_eq!(
1299 serde_json::to_string(&landed).expect("a report serializes"),
1300 r##"{"schema":"rk.status/14","landed":true,"classification":"upgrade","git_work_tree":true,"config":{"state":"pending","pending":["profile.release.style"]},"profile":{"technologies":["rust"],"forge":"github","release":{"mode":"automatic","driver":"rust","style":"trunk","line_prefix":"release/"}},"git":{"trunk":"master","checkout_mode":"linked-worktree","integration":"local","merge_form":"squash"},"capabilities":{"nix_packaging":true,"reporting_policy":true,"scorecard":false,"code_scanning":"semgrep","workflow_guards":false},"selection":[],"rk_version":"0.1.0","binary_version":"0.2.0","alignment":"binary-newer","drift":{"rendered":0,"seeded":1},"missing":[],"stale_pins":[{"tool":"release-plz","landed":"0.3.160","available":"0.3.170"}],"sentinels":1,"sentinel_locations":[{"file":"release-plz.toml","line":18,"text":"# TODO(release-kit): keep false for a binary-only crate"}],"record_drift":0,"invariant_failures":[{"code":"attestations-disabled","destination":"dist-workspace.toml","reason":"github-attestations is not effectively true","remediation":"set github-attestations = true in [dist]"}],"warnings":[{"code":"code-scanning-licence","reason":"the target's license, LicenseRef-proprietary, does not state a codebase this release recognizes as open source"}],"setup_proof":{"state":"stale","changed":["target.required_check"]},"pending":2,"legacy_state":[{"path":"/state/release-kit/plans/0123456789abcdef","kind":"plan","active":true}],"migration":{"id":"20261009T140205Z","workspace":"/state/release-kit/migrations/widget-0123456789ab/20261009T140205Z","unfinished":2}}"##
1301 );
1302 let absent = Report {
1303 landed: false,
1304 classification: Some(Classification::Setup),
1305 git_work_tree: false,
1306 config: super::ConfigState {
1307 state: "absent",
1308 pending: vec![],
1309 },
1310 profile: None,
1311 git: None,
1312 capabilities: None,
1313 selection: None,
1314 rk_version: None,
1315 binary_version: None,
1316 alignment: None,
1317 drift: None,
1318 missing: None,
1319 stale_pins: None,
1320 sentinels: None,
1321 sentinel_locations: None,
1322 record_drift: None,
1323 invariant_failures: None,
1324 warnings: None,
1325 setup_proof: None,
1326 pending: None,
1327 violations: None,
1328 legacy_state: vec![],
1329 migration: None,
1330 ..landed
1331 };
1332 assert_eq!(
1333 serde_json::to_string(&absent).expect("a report serializes"),
1334 r#"{"schema":"rk.status/14","landed":false,"classification":"setup","git_work_tree":false,"config":{"state":"absent","pending":[]},"legacy_state":[]}"#,
1335 "an absent landing reports the fields a caller can branch on"
1336 );
1337 let newer = Report {
1338 classification: None,
1339 ..absent
1340 };
1341 assert!(
1342 serde_json::to_string(&newer)
1343 .expect("a report serializes")
1344 .contains(r#""classification":null"#),
1345 "no classification is stated as null, never omitted"
1346 );
1347 }
1348
1349 fn facts() -> Facts {
1350 Facts {
1351 technologies: Vec::new(),
1352 forge: None,
1353 repo: None,
1354 release_markers: Vec::new(),
1355 collisions: Vec::new(),
1356 git: true,
1357 tags: 0,
1358 long_lived_branches: Vec::new(),
1359 }
1360 }
1361
1362 #[test]
1367 fn every_classification_has_its_rule() {
1368 let none = OwnLanding::default();
1369 let classify = |facts: &Facts, own: &OwnLanding| {
1370 super::unrecorded(assess::classify_unrecorded(facts, own))
1371 };
1372 assert_eq!(classify(&facts(), &none), Classification::Setup);
1373 let marked = Facts {
1374 release_markers: vec![".goreleaser.yaml".into()],
1375 ..facts()
1376 };
1377 assert_eq!(classify(&marked, &none), Classification::Migration);
1378 let tagged = Facts { tags: 3, ..facts() };
1379 assert_eq!(classify(&tagged, &none), Classification::NeedsDecision);
1380 let own = OwnLanding {
1383 regions: vec!["AGENTS.md".into()],
1384 rendered: Vec::new(),
1385 };
1386 let colliding = Facts {
1387 collisions: vec!["AGENTS.md".into()],
1388 release_markers: vec!["CHANGELOG.md".into()],
1389 ..facts()
1390 };
1391 assert_eq!(classify(&colliding, &own), Classification::Adopt);
1392 assert_eq!(
1393 assess::classify_unrecorded(&colliding, &own),
1394 Unrecorded::Adopt
1395 );
1396 assert_eq!(
1397 super::recorded(Alignment::BinaryNewer, false),
1398 Some(Classification::Upgrade)
1399 );
1400 assert_eq!(
1401 super::recorded(Alignment::Aligned, false),
1402 Some(Classification::Drift)
1403 );
1404 assert_eq!(
1405 super::recorded(Alignment::Aligned, true),
1406 Some(Classification::Current)
1407 );
1408 assert_eq!(super::recorded(Alignment::TargetNewer, true), None);
1409 for (class, word) in [
1410 (Classification::Setup, "setup"),
1411 (Classification::Migration, "migration"),
1412 (Classification::NeedsDecision, "needs-decision"),
1413 (Classification::Adopt, "adopt"),
1414 (Classification::Upgrade, "upgrade"),
1415 (Classification::Drift, "drift"),
1416 (Classification::Current, "current"),
1417 ] {
1418 assert_eq!(class.as_str(), word);
1419 assert_eq!(
1420 serde_json::to_string(&class).expect("serializes"),
1421 format!("\"{word}\"")
1422 );
1423 }
1424 }
1425}