Skip to main content

release_kit/commands/
status.rs

1//! `rk status`: a target describes itself from its own disk.
2//!
3//! Read-only and offline: the receipt supplies what landed, this binary's
4//! projection supplies what an upgrade would offer, the embedded registry
5//! supplies the pin comparison, and no network is ever touched: a fetch
6//! is a way for a status command to hang, fail on a network it should not
7//! need, or leak a repository's existence. Status compares the current
8//! target with this binary's projection and the receipt and nothing else;
9//! it reads no stage and resolves no other release. Plain `rk status`
10//! reports and exits 0 for every reportable state, drift and no-landing
11//! included; `--check` computes the identical report and changes only
12//! the final judgment, the one sanctioned bare exit 1.
13//!
14//! SATISFIES landing:status-judges-only-under-check
15
16use 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/// Drift counts by owned kind; `state` files are never compared.
33#[derive(Debug, Serialize)]
34struct Drift {
35    /// Edits to files release-kit owns — the violation class.
36    rendered: usize,
37    /// Edits to files the target owns — expected and informational.
38    seeded: usize,
39}
40
41/// One recorded pin that is behind this binary's registry.
42#[derive(Debug, Serialize)]
43struct StalePin {
44    /// The tool's registry name.
45    tool: String,
46    /// The version the landing recorded.
47    landed: String,
48    /// The version this binary's registry pins.
49    available: String,
50}
51
52/// One reportable condition that is not a violation: the target is not
53/// broken and the decision behind it is the operator's.
54///
55/// The `code` is stable, so a machine reader branches on it rather than on
56/// the prose.
57#[derive(Debug, Serialize)]
58struct Warning {
59    /// The stable reason code.
60    code: &'static str,
61    /// What the condition is, in the target's own terms.
62    reason: String,
63}
64
65/// Where the committed setup proof stands against the contract the target
66/// states now, read offline.
67///
68/// SATISFIES setup-proof:the-status-check-holds-the-proof
69#[derive(Debug, Clone, Serialize)]
70struct SetupProof {
71    /// `compatible`, `stale`, `invalid`, or `absent`.
72    state: &'static str,
73    /// Each changed field of a stale proof.
74    #[serde(skip_serializing_if = "Vec::is_empty")]
75    changed: Vec<String>,
76    /// Why an invalid proof cannot be read.
77    #[serde(skip_serializing_if = "Option::is_none")]
78    reason: Option<&'static str>,
79    /// What an invalid proof held, one line.
80    #[serde(skip_serializing_if = "Option::is_none")]
81    detail: Option<String>,
82}
83
84/// What every setup proof code asks the operator to run, who holds the
85/// credentials the check reads.
86const 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    /// The violation a proof that is not compatible counts under
109    /// `--check`.
110    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
142/// The committed setup proof, for a target whose automatic release has a
143/// forge to set up; `None` for every other target, whose report is
144/// unchanged.
145fn 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
155/// The warning code of a nested hook configuration that no `.prekignore`
156/// line excludes.
157const NESTED_HOOK_CONFIGURATION: &str = "nested-hook-configuration";
158
159/// The code a lapsed code scanning licence reports under.
160const CODE_SCANNING_LICENCE: &str = "code-scanning-licence";
161
162/// Where a target stands for the setup skill's gate: one word computed by
163/// the CLI's own rule, so no reader branches on five fields by hand.
164///
165/// SATISFIES landing:a-landing-classifies-its-target-first
166#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
167#[serde(rename_all = "kebab-case")]
168pub enum Classification {
169    /// No record, no release mechanism, and no release history.
170    Setup,
171    /// No record and another release mechanism in place.
172    Migration,
173    /// No record and release activity no mechanism explains.
174    NeedsDecision,
175    /// No record, and release-kit's own landing is present.
176    Adopt,
177    /// A record older than this binary.
178    Upgrade,
179    /// A record at this binary's version that `--check` fails.
180    Drift,
181    /// A record at this binary's version that `--check` passes.
182    Current,
183}
184
185impl Classification {
186    /// The kebab-case word, as the JSON serializes it.
187    #[must_use]
188    pub const fn as_str(self) -> &'static str {
189        match self {
190            Self::Setup => "setup",
191            Self::Migration => "migration",
192            Self::NeedsDecision => "needs-decision",
193            Self::Adopt => "adopt",
194            Self::Upgrade => "upgrade",
195            Self::Drift => "drift",
196            Self::Current => "current",
197        }
198    }
199}
200
201/// The classification of a target with no record, from the assessment's
202/// rule and the adoption detector.
203const fn unrecorded(class: assess::Unrecorded) -> Classification {
204    match class {
205        assess::Unrecorded::Adopt => Classification::Adopt,
206        assess::Unrecorded::Assessed(assess::Classification::Greenfield) => Classification::Setup,
207        assess::Unrecorded::Assessed(assess::Classification::Brownfield) => {
208            Classification::Migration
209        }
210        assess::Unrecorded::Assessed(assess::Classification::NeedsDecision) => {
211            Classification::NeedsDecision
212        }
213    }
214}
215
216/// The classification of a recorded target. A record newer than this
217/// binary has none: that is an observation the setup skill routes to
218/// provisioning, not a state this binary can judge.
219const fn recorded(alignment: Alignment, clean: bool) -> Option<Classification> {
220    match alignment {
221        Alignment::TargetNewer => None,
222        Alignment::BinaryNewer => Some(Classification::Upgrade),
223        Alignment::Aligned if clean => Some(Classification::Current),
224        Alignment::Aligned => Some(Classification::Drift),
225    }
226}
227
228/// One unfilled judgment sentinel, located.
229#[derive(Debug, Clone, Serialize)]
230struct SentinelAt {
231    /// The landed file that carries it.
232    file: String,
233    /// Its line, counted from one.
234    line: usize,
235    /// The line's text, trimmed.
236    text: String,
237}
238
239/// One path a 0.4.x release left under the state root.
240#[derive(Debug, Serialize)]
241struct LegacyPath {
242    /// The absolute path.
243    path: String,
244    /// `plan` for a stored plan, `release-cache` for the release cache.
245    kind: &'static str,
246    /// Whether it holds an operation the old binary could still apply.
247    active: bool,
248}
249
250/// The state a 0.4.x release stored under the state root, each path with
251/// whether an operation is active. No later release writes `plans/` or
252/// `release/`, so what is there is the old binary's.
253///
254/// A stored plan reads as active while its own document says an apply
255/// may run it, and while it cannot be read at all, because only the
256/// operator can retire an operation the old binary owns. The release
257/// cache holds no operation.
258fn legacy_state() -> Vec<LegacyPath> {
259    let Some(root) = crate::applog::state_root() else {
260        return Vec::new();
261    };
262    let mut found = Vec::new();
263    if let Ok(entries) = std::fs::read_dir(root.join(LEGACY_PLANS)) {
264        let mut plans: Vec<std::path::PathBuf> = entries
265            .flatten()
266            .filter(|entry| !entry.file_name().to_string_lossy().starts_with('.'))
267            .map(|entry| entry.path())
268            .filter(|path| path.is_dir())
269            .collect();
270        plans.sort();
271        for plan in plans {
272            let active = std::fs::read(plan.join("plan.json"))
273                .ok()
274                .and_then(|bytes| serde_json::from_slice::<serde_json::Value>(&bytes).ok())
275                .is_none_or(|document| document["readiness"].as_str() == Some("ready"));
276            found.push(LegacyPath {
277                path: plan.display().to_string(),
278                kind: "plan",
279                active,
280            });
281        }
282    }
283    let cache = root.join(LEGACY_RELEASE_CACHE);
284    if cache.is_dir() {
285        found.push(LegacyPath {
286            path: cache.display().to_string(),
287            kind: "release-cache",
288            active: false,
289        });
290    }
291    found
292}
293
294/// Where a 0.4.x release stored its plans, under the state root.
295const LEGACY_PLANS: &str = "plans";
296
297/// Where a 0.4.x release cached fetched releases, under the state root.
298const LEGACY_RELEASE_CACHE: &str = "release";
299
300/// The status report's shape version.
301const SCHEMA: &str = "rk.status/16";
302
303/// Configuration is informational, independent of every drift comparison.
304#[derive(Debug, serde::Serialize)]
305struct ConfigState {
306    state: &'static str,
307    pending: Vec<String>,
308}
309
310fn config_state(config: Option<&crate::config::Config>, record: Option<&Manifest>) -> ConfigState {
311    let pending = config
312        .zip(record)
313        .map_or_else(Vec::new, |(config, record)| {
314            crate::config::pending(config, record)
315        });
316    ConfigState {
317        state: if config.is_none() {
318            "absent"
319        } else if pending.is_empty() {
320            "aligned"
321        } else {
322            "pending"
323        },
324        pending,
325    }
326}
327
328/// The machine form of a status report.
329#[derive(Debug, Serialize)]
330struct Report {
331    /// The shape version of this document.
332    schema: &'static str,
333    /// Whether a landing record exists; most other fields need one.
334    landed: bool,
335    /// Where the target stands for the setup skill's gate; null where the
336    /// record is newer than this binary.
337    classification: Option<Classification>,
338    /// Whether the target sits in a non-bare Git work tree.
339    git_work_tree: bool,
340    config: ConfigState,
341    /// What the record says the project is.
342    #[serde(skip_serializing_if = "Option::is_none")]
343    profile: Option<ProfileSnapshot>,
344    /// The recorded Git workflow.
345    #[serde(skip_serializing_if = "Option::is_none")]
346    git: Option<GitWorkflow>,
347    /// The recorded capability requests.
348    #[serde(skip_serializing_if = "Option::is_none")]
349    capabilities: Option<CapabilityRequests>,
350    /// Every capability the catalog answers for the recorded values, in
351    /// catalog order; absent where this binary cannot project the record.
352    #[serde(skip_serializing_if = "Option::is_none")]
353    selection: Option<Vec<CapabilityNote>>,
354    #[serde(skip_serializing_if = "Option::is_none")]
355    rk_version: Option<String>,
356    #[serde(skip_serializing_if = "Option::is_none")]
357    binary_version: Option<&'static str>,
358    #[serde(skip_serializing_if = "Option::is_none")]
359    alignment: Option<Alignment>,
360    /// The rk version the project pins against the latest release the
361    /// check cache knows; absent where no one manager pins rk.
362    #[serde(skip_serializing_if = "Option::is_none")]
363    pin: Option<PinState>,
364    #[serde(skip_serializing_if = "Option::is_none")]
365    drift: Option<Drift>,
366    /// Recorded destinations absent from the disk.
367    #[serde(skip_serializing_if = "Option::is_none")]
368    missing: Option<Vec<String>>,
369    #[serde(skip_serializing_if = "Option::is_none")]
370    stale_pins: Option<Vec<StalePin>>,
371    /// Unresolved judgment sentinels across the landed files.
372    #[serde(skip_serializing_if = "Option::is_none")]
373    sentinels: Option<usize>,
374    /// Each unresolved sentinel, by file and line.
375    #[serde(skip_serializing_if = "Option::is_none")]
376    sentinel_locations: Option<Vec<SentinelAt>>,
377    /// Record-set disagreements between the recorded parameters'
378    /// projection and the recorded destinations — its own count, because
379    /// no file was edited and the kind counts must stay honest.
380    #[serde(skip_serializing_if = "Option::is_none")]
381    record_drift: Option<usize>,
382    /// Invariants a landed file's effective configuration violates —
383    /// judged, never rewritten, because the file stays the target's.
384    #[serde(skip_serializing_if = "Option::is_none")]
385    invariant_failures: Option<Vec<InvariantFailure>>,
386    /// Conditions that are reportable and not violations: `--check` exits 0
387    /// on them, because the target is not broken and the decision is the
388    /// operator's.
389    #[serde(skip_serializing_if = "Option::is_none")]
390    warnings: Option<Vec<Warning>>,
391    /// Where the committed setup proof stands, on a target with an
392    /// automatic release and a forge; absent on every other target.
393    #[serde(skip_serializing_if = "Option::is_none")]
394    setup_proof: Option<SetupProof>,
395    /// How many destinations an upgrade would change: the count this
396    /// binary's sources project under the recorded parameters against
397    /// what the record names. Zero means nothing to take, whatever the two
398    /// versions say. Absent on a landed target means this binary carries
399    /// no files for the recorded pair and cannot answer.
400    #[serde(skip_serializing_if = "Option::is_none")]
401    pending: Option<usize>,
402    /// Rendered files edited on purpose, each under its accepted-drift
403    /// entry and reason: reported, never a violation.
404    #[serde(skip_serializing_if = "Option::is_none")]
405    accepted_drift: Option<Vec<AcceptedNote>>,
406    /// Accepted-drift entries whose file matches the receipt again: the
407    /// deviation is gone and the entry can go.
408    #[serde(skip_serializing_if = "Option::is_none")]
409    stale_accepted_drift: Option<Vec<String>>,
410    /// Present only under `--check`: what the judgment failed on.
411    #[serde(skip_serializing_if = "Option::is_none")]
412    violations: Option<Vec<String>>,
413    /// The state a 0.4.x release left under the state root.
414    legacy_state: Vec<LegacyPath>,
415    /// The open migration, where the configuration names one.
416    #[serde(skip_serializing_if = "Option::is_none")]
417    migration: Option<OpenMigration>,
418}
419
420/// The project's rk pin against the latest known release.
421///
422/// SATISFIES packaging:the-unattended-caller-never-fails-the-shell
423#[derive(Debug, Serialize)]
424struct PinState {
425    /// The pinned version, without a leading `v`.
426    version: String,
427    /// The latest release the check cache records, where it records one.
428    #[serde(skip_serializing_if = "Option::is_none")]
429    latest: Option<String>,
430    /// Whether a newer release is out.
431    behind: bool,
432}
433
434/// Read the pin and the check cache, offline, and print the warning on
435/// a pin that is behind.
436fn pin_state(out: Output, target: &camino::Utf8Path) -> Option<PinState> {
437    let version = crate::self_depend::pinned_version(target)?;
438    let key = crate::self_depend::observe(target).ok()?.key();
439    let latest = crate::self_depend::advice::cached_latest(&key)
440        .map(|latest| latest.trim_start_matches('v').to_owned());
441    let warning = crate::self_depend::advice::pending_from_cache(&key, &version);
442    if let Some(warning) = &warning {
443        out.result_line(warning.clone());
444    }
445    Some(PinState {
446        version,
447        latest,
448        behind: warning.is_some(),
449    })
450}
451
452/// An open migration, as the status reports it.
453#[derive(Debug, Serialize)]
454struct OpenMigration {
455    /// The identifier the configuration names.
456    id: String,
457    /// The workspace on this host, absent where this host holds none.
458    #[serde(skip_serializing_if = "Option::is_none")]
459    workspace: Option<String>,
460    /// How many sources are neither verified nor dropped, absent where
461    /// this host holds no registry.
462    #[serde(skip_serializing_if = "Option::is_none")]
463    unfinished: Option<usize>,
464}
465
466/// The open migration the configuration names, read from this host's
467/// workspace where it holds one.
468///
469/// SATISFIES migration:the-configuration-names-the-open-migration
470fn open_migration(
471    target: &camino::Utf8Path,
472    config: Option<&crate::config::Config>,
473) -> Option<OpenMigration> {
474    let id = config.and_then(|config| config.migration.clone())?;
475    let workspace = crate::migrate::open_workspace(target).ok().flatten();
476    let unfinished = workspace
477        .as_ref()
478        .filter(|workspace| workspace.join(crate::migrate::REGISTRY_FILE).is_file())
479        .and_then(|workspace| crate::migrate::registry::load(workspace).ok())
480        .map(|registry| {
481            registry
482                .sources
483                .iter()
484                .filter(|source| !source.status.finished())
485                .count()
486        });
487    Some(OpenMigration {
488        id,
489        workspace: workspace.map(|workspace| workspace.to_string()),
490        unfinished,
491    })
492}
493
494/// The line a human report carries for an open migration.
495fn render_migration(out: Output, migration: Option<&OpenMigration>) {
496    if let Some(migration) = migration {
497        out.result_line(format!(
498            "migration {} is open; rk migrate status reads it",
499            migration.id
500        ));
501    }
502}
503
504fn report_absent(
505    out: Output,
506    args: &StatusArgs,
507    config: Option<&crate::config::Config>,
508    git_work_tree: bool,
509) -> Result<(), RkError> {
510    let migration = open_migration(&args.target, config);
511    let classification = match assess::standing(&args.target, config)? {
512        assess::Standing::Migrating => Classification::Migration,
513        assess::Standing::Unrecorded(class) => unrecorded(class),
514    };
515    let legacy = legacy_state();
516    out.result_line(format!("config: {}", config_state(config, None).state));
517    out.result_line(format!("no landing at {}", args.target));
518    out.result_line(format!("classification: {}", classification.as_str()));
519    render_migration(out, migration.as_ref());
520    render_context(out, git_work_tree, &legacy);
521    let pin = pin_state(out, &args.target);
522    out.next(&[
523        format!(
524            "rk profile --target {} reports what a landing would select",
525            args.target
526        ),
527        format!("rk init --target {} lands the workflow", args.target),
528        format!(
529            "rk adopt --target {} records a landing made before the receipt existed",
530            args.target
531        ),
532        format!(
533            "rk stage --target {} stages this binary's candidate; the rk-setup skill carries the best-effort migration",
534            args.target
535        ),
536    ]);
537    out.emit(&Report {
538        schema: SCHEMA,
539        landed: false,
540        classification: Some(classification),
541        git_work_tree,
542        config: config_state(config, None),
543        profile: None,
544        git: None,
545        capabilities: None,
546        selection: None,
547        rk_version: None,
548        binary_version: None,
549        alignment: None,
550        pin,
551        drift: None,
552        missing: None,
553        stale_pins: None,
554        sentinels: None,
555        sentinel_locations: None,
556        record_drift: None,
557        invariant_failures: None,
558        warnings: None,
559        setup_proof: None,
560        pending: None,
561        accepted_drift: None,
562        stale_accepted_drift: None,
563        violations: args.check.then(|| vec!["no landing".to_owned()]),
564        legacy_state: legacy,
565        migration,
566    })?;
567    if args.check {
568        return Err(RkError::check_failed(
569            Diagnostic::new(
570                Reason::StateDrift,
571                format!("no landing at {}, and --check requires one", args.target),
572            )
573            .expected("a target carrying .release-kit/manifest.json")
574            .action("rk init lands the workflow; rk adopt records an existing landing; rk stage and the rk-setup skill carry the migration"),
575        ));
576    }
577    Ok(())
578}
579
580/// A rendered file under its accepted-drift entry.
581#[derive(Debug, Clone, Serialize)]
582struct AcceptedNote {
583    /// The destination.
584    destination: String,
585    /// Why the project deviates.
586    reason: String,
587}
588
589/// What one pass over the record and the disk observed.
590struct Observed {
591    drift_rendered: Vec<String>,
592    /// The current digest of each drifted rendered file, which the
593    /// remediation prints so an operator can accept it.
594    drift_digests: std::collections::BTreeMap<String, String>,
595    /// The reason of each drifted rendered file edited past its accepted
596    /// bytes, which the violation names.
597    drift_reasons: std::collections::BTreeMap<String, String>,
598    /// Rendered files whose bytes match their accepted-drift entry.
599    drift_accepted: Vec<AcceptedNote>,
600    /// Entries whose file matches the receipt again.
601    accepted_stale: Vec<String>,
602    drift_seeded: Vec<String>,
603    /// Recorded block destinations whose recorded digest the record's own
604    /// parameters do not reproduce: the record was edited, not the file.
605    parameter_drift: Vec<String>,
606    /// Set differences between what the recorded parameters project —
607    /// the withhold judgment applied — and the destinations the record
608    /// names: a record whose parameters and file list disagree, whichever
609    /// of the two was edited or outgrown.
610    record_drift: Vec<String>,
611    missing: Vec<String>,
612    stale: Vec<StalePin>,
613    sentinels: Vec<(String, usize, String)>,
614    invariants: Vec<InvariantFailure>,
615    /// Reportable conditions that are not violations.
616    warnings: Vec<Warning>,
617    setup_proof: Option<SetupProof>,
618    /// Recorded intents this target cannot honour, counted in
619    /// `record_drift` and kept separately because a plain upgrade cannot
620    /// repair them: it re-reads the same recorded answer and refuses. An
621    /// unavailable optional capability is not one of these; it is reported
622    /// in `selection` and omitted, and an upgrade runs over it unharmed.
623    incompatible: Vec<String>,
624    /// The destinations an upgrade would change, or `None` where this
625    /// binary carries no projection for the recorded pair and so cannot
626    /// say.
627    pending: Option<Vec<String>>,
628    /// Every capability the catalog answers for the recorded values.
629    selection: Option<Vec<CapabilityNote>>,
630}
631
632/// Report the target's landing.
633///
634/// # Errors
635///
636/// Returns [`RkError::Missing`] for a target that is not a directory, the
637/// record's own failure taxonomy for an unreadable or unknown record, and
638/// [`RkError::CheckFailed`] under `--check` when the report holds a
639/// violation.
640#[allow(
641    clippy::too_many_lines,
642    reason = "one pass reads the target, judges it, and emits the one report every reader takes"
643)]
644pub fn run(args: &StatusArgs) -> Result<(), RkError> {
645    crate::requirements::require("rk status", &[crate::requirements::Tool::Git])?;
646    let out = Output::new(args.json);
647    if !args.target.is_dir() {
648        return Err(RkError::missing(
649            Diagnostic::new(
650                Reason::TargetNotFound,
651                format!("target {} is not a directory", args.target),
652            )
653            .expected("an existing repository to report on"),
654        ));
655    }
656    let config = crate::config::load(args.target.as_std_path())?;
657    let git_work_tree = assess::git_work_tree(&args.target)?;
658    let Some(manifest) = manifest::load(&args.target)? else {
659        return report_absent(out, args, config.as_ref(), git_work_tree);
660    };
661    // SATISFIES project-profile:release-intent-has-three-modes
662    // A record that still carries the retired build command fails with the
663    // diagnostic the release actions refuse with, so the operator meets it
664    // here before CI does.
665    if manifest
666        .profile
667        .release
668        .build
669        .as_ref()
670        .is_some_and(|build| build.command.is_some())
671    {
672        return Err(crate::profile::retired_build_command());
673    }
674
675    let migration = open_migration(&args.target, config.as_ref());
676    let accepted = config
677        .as_ref()
678        .map(|config| config.landing.accepted_drift.clone())
679        .unwrap_or_default();
680    let stated = Stated::of(config.as_ref(), &manifest);
681    let config = config_state(config.as_ref(), Some(&manifest));
682    out.result_line(format!("config: {}", config.state));
683    for key in &config.pending {
684        out.result_line(format!(
685            "config pending: {key}; rk upgrade --apply takes it up"
686        ));
687    }
688    let mut observed = observe(args, &manifest, &stated)?;
689    accept(&mut observed, &manifest, &accepted)?;
690    observed.setup_proof = setup_proof_of(&args.target, &manifest)?;
691    let alignment = manifest::alignment(&manifest.rk_version, env!("CARGO_PKG_VERSION"));
692    render_human(out, args, &manifest, alignment, &observed);
693    let pin = pin_state(out, &args.target);
694
695    let violations = violations_of(&observed);
696    // A record newer than this binary is no state it can judge, an open
697    // migration included; below that, the open migration outranks the
698    // record until it closes.
699    let classification = if migration.is_some() && alignment != Alignment::TargetNewer {
700        Some(Classification::Migration)
701    } else {
702        recorded(alignment, violations.is_empty())
703    };
704    out.result_line(format!(
705        "classification: {}",
706        classification.map_or(
707            "none: the record is newer than this binary",
708            Classification::as_str
709        )
710    ));
711    render_migration(out, migration.as_ref());
712    let legacy = legacy_state();
713    render_context(out, git_work_tree, &legacy);
714    out.emit(&Report {
715        schema: SCHEMA,
716        landed: true,
717        classification,
718        git_work_tree,
719        config,
720        profile: Some(manifest.profile.clone()),
721        git: Some(manifest.git.clone()),
722        capabilities: Some(manifest.capabilities.clone()),
723        selection: observed.selection.clone(),
724        rk_version: Some(manifest.rk_version),
725        binary_version: Some(env!("CARGO_PKG_VERSION")),
726        alignment: Some(alignment),
727        pin,
728        drift: Some(Drift {
729            rendered: observed.drift_rendered.len() + observed.parameter_drift.len(),
730            seeded: observed.drift_seeded.len(),
731        }),
732        record_drift: Some(observed.record_drift.len()),
733        missing: Some(observed.missing.clone()),
734        stale_pins: Some(observed.stale),
735        sentinels: Some(observed.sentinels.len()),
736        sentinel_locations: Some(
737            observed
738                .sentinels
739                .iter()
740                .map(|(file, line, text)| SentinelAt {
741                    file: file.clone(),
742                    line: *line,
743                    text: text.clone(),
744                })
745                .collect(),
746        ),
747        invariant_failures: Some(observed.invariants),
748        warnings: Some(observed.warnings),
749        setup_proof: observed.setup_proof.clone(),
750        pending: observed.pending.as_ref().map(Vec::len),
751        accepted_drift: Some(observed.drift_accepted.clone()),
752        stale_accepted_drift: Some(observed.accepted_stale.clone()),
753        violations: args.check.then(|| violations.clone()),
754        legacy_state: legacy,
755        migration,
756    })?;
757
758    if args.check && !violations.is_empty() {
759        return Err(RkError::check_failed(
760            Diagnostic::new(
761                Reason::StateDrift,
762                format!(
763                    "the landing is not clean: {} violation{}",
764                    violations.len(),
765                    if violations.len() == 1 { "" } else { "s" }
766                ),
767            )
768            .expected(
769                "no rendered drift, no missing recorded file, no unresolved sentinel, no invariant failure",
770            ),
771        ));
772    }
773    Ok(())
774}
775
776/// The human lines every report carries, landed or not: whether the
777/// target is a work tree the method can land in, and each path a 0.4.x
778/// release left under the state root.
779fn render_context(out: Output, git_work_tree: bool, legacy: &[LegacyPath]) {
780    if !git_work_tree {
781        out.result_line("not a non-bare Git work tree: the method lands files a work tree commits");
782    }
783    for entry in legacy {
784        out.result_line(format!(
785            "LEGACY {} ({}, {})",
786            entry.path,
787            entry.kind,
788            if entry.active { "active" } else { "inactive" }
789        ));
790    }
791}
792
793/// Move each drifted rendered file whose bytes match its accepted-drift
794/// entry out of the violations, name the reason of one edited past it,
795/// and report an entry whose file matches the receipt again.
796///
797/// An entry must name a whole-file rendered destination the receipt
798/// records; any other refuses as configuration. Accepted drift exempts a
799/// file from the drift judgment alone: an invariant failure on it stays.
800///
801/// SATISFIES accepted-drift:an-accepted-drift-names-its-reason-and-its-bytes
802fn accept(
803    observed: &mut Observed,
804    manifest: &Manifest,
805    accepted: &std::collections::BTreeMap<String, crate::config::AcceptedDrift>,
806) -> Result<(), RkError> {
807    for (destination, entry) in accepted {
808        let Some(file) = manifest.file(destination) else {
809            return Err(crate::config::invalid(format!(
810                "landing.accepted_drift names {destination}, which the receipt does not record"
811            )));
812        };
813        if file.kind != Kind::Rendered || file.placement != manifest::Placement::Whole {
814            return Err(crate::config::invalid(format!(
815                "landing.accepted_drift names {destination}, which is not a whole rendered file: only such a file has bytes release-kit owns whole"
816            )));
817        }
818        if !observed.drift_rendered.contains(destination) {
819            if !observed.missing.contains(destination) {
820                observed.accepted_stale.push(destination.clone());
821            }
822            continue;
823        }
824        if observed.drift_digests.get(destination) == Some(&entry.sha256) {
825            observed.drift_rendered.retain(|path| path != destination);
826            observed.drift_accepted.push(AcceptedNote {
827                destination: destination.clone(),
828                reason: entry.reason.clone(),
829            });
830        } else {
831            observed
832                .drift_reasons
833                .insert(destination.clone(), entry.reason.clone());
834        }
835    }
836    Ok(())
837}
838
839/// The check-mode violation lines: rendered drift, missing recorded
840/// files, unresolved sentinels, and invariant failures — the closed set
841/// `landing:status-judges-only-under-check` names.
842fn violations_of(observed: &Observed) -> Vec<String> {
843    observed
844        .drift_rendered
845        .iter()
846        .map(|path| {
847            let digest = observed.drift_digests.get(path).map_or("", String::as_str);
848            observed.drift_reasons.get(path).map_or_else(
849                || format!("rendered drift: {path}; its sha256 is {digest}"),
850                |reason| {
851                    format!(
852                        "rendered drift: {path}, edited past its accepted drift ({reason}); its sha256 is now {digest}"
853                    )
854                },
855            )
856        })
857        .chain(
858            observed
859                .parameter_drift
860                .iter()
861                .map(|path| format!("parameter drift: {path}")),
862        )
863        .chain(
864            observed
865                .record_drift
866                .iter()
867                .map(|reason| format!("record drift: {reason}")),
868        )
869        .chain(
870            observed
871                .missing
872                .iter()
873                .map(|path| format!("missing: {path}")),
874        )
875        .chain(
876            observed
877                .sentinels
878                .iter()
879                .map(|(path, line, _)| format!("sentinel: {path}:{line}")),
880        )
881        .chain(
882            observed
883                .invariants
884                .iter()
885                .map(|failure| format!("invariant: {}: {}", failure.destination, failure.code)),
886        )
887        .chain(
888            observed
889                .setup_proof
890                .as_ref()
891                .and_then(SetupProof::failure)
892                .map(|failure| format!("setup proof: {}", failure.code)),
893        )
894        .collect()
895}
896
897/// The answers the target states now, for the judgments: a committed
898/// answer the landing verbs have yet to take up outranks the record.
899struct Stated {
900    /// Where the crate publishes.
901    registry: Option<RegistryAnswer>,
902    /// The check context of the gate.
903    required_check: String,
904}
905
906impl Stated {
907    fn of(config: Option<&crate::config::Config>, manifest: &Manifest) -> Self {
908        Self {
909            registry: config
910                .and_then(|config| config.profile.release.registry)
911                .or(manifest.profile.release.registry),
912            // The landing writes the check back as a class P answer, so a
913            // configuration that exists states it, an empty one included.
914            required_check: config.map_or_else(
915                || manifest.parameters.required_check.clone(),
916                |config| config.setup.required_check.clone(),
917            ),
918        }
919    }
920}
921
922/// One pass over the record and the disk: drift, missing files, stale
923/// pins, and sentinels.
924#[allow(
925    clippy::too_many_lines,
926    reason = "one pass over the record and the disk answers every comparison the report states"
927)]
928fn observe(args: &StatusArgs, manifest: &Manifest, stated: &Stated) -> Result<Observed, RkError> {
929    let mut observed = Observed {
930        drift_rendered: Vec::new(),
931        drift_digests: std::collections::BTreeMap::new(),
932        drift_reasons: std::collections::BTreeMap::new(),
933        drift_accepted: Vec::new(),
934        accepted_stale: Vec::new(),
935        drift_seeded: Vec::new(),
936        parameter_drift: Vec::new(),
937        record_drift: Vec::new(),
938        missing: Vec::new(),
939        stale: Vec::new(),
940        sentinels: Vec::new(),
941        invariants: Vec::new(),
942        warnings: Vec::new(),
943        setup_proof: None,
944        incompatible: Vec::new(),
945        pending: None,
946        selection: None,
947    };
948    // One projection serves every reader below, because each asks what
949    // this binary makes of the recorded parameters at this target. A pair
950    // this binary does not carry cannot be projected at all: under a
951    // receipt this binary wrote that is a defect and still fails, and
952    // under a landing from another rk it is a fact to report.
953    let aligned =
954        manifest::alignment(&manifest.rk_version, env!("CARGO_PKG_VERSION")) == Alignment::Aligned;
955    let projected = match project(args, manifest) {
956        Ok(projection) => Some(projection),
957        Err(err) if aligned => return Err(err),
958        Err(_) => None,
959    };
960    for file in &manifest.files {
961        let Some(bytes) = landing::read_recorded(&args.target, &file.destination)? else {
962            observed.missing.push(file.destination.clone());
963            continue;
964        };
965        if Digest::of(&bytes) != file.sha256 {
966            match file.kind {
967                Kind::Rendered => {
968                    observed.drift_rendered.push(file.destination.clone());
969                    observed
970                        .drift_digests
971                        .insert(file.destination.clone(), Digest::of(&bytes).to_string());
972                }
973                Kind::Seeded => observed.drift_seeded.push(file.destination.clone()),
974                Kind::State => {}
975            }
976        }
977        observed.invariants.extend(invariants::failures(
978            manifest.profile.release.driver.as_deref().unwrap_or(""),
979            manifest.profile.forge.as_deref().unwrap_or(""),
980            &file.destination,
981            &bytes,
982            stated.registry,
983        ));
984        let text = String::from_utf8_lossy(&bytes);
985        for (idx, line) in text.lines().enumerate() {
986            if line.contains(embedded::SENTINEL) {
987                observed.sentinels.push((
988                    file.destination.clone(),
989                    idx + 1,
990                    line.trim().to_owned(),
991                ));
992            }
993        }
994        // A marked document's markers must be well formed even when its
995        // first block matches the receipt: a duplicate hook block still
996        // executes, so an ill-formed document reads as rendered drift,
997        // never as clean.
998        let defective = projected.as_ref().is_some_and(|projection| {
999            projection
1000                .collisions
1001                .iter()
1002                .any(|collision| collision.destination == file.destination)
1003        });
1004        if defective && !observed.drift_rendered.contains(&file.destination) {
1005            observed.drift_rendered.push(file.destination.clone());
1006        }
1007    }
1008    // The cross-file step: a landed file can generate the artifact the
1009    // forge actually executes, and the seeds ship no copy of it, so no
1010    // recorded digest sees the two disagree. The pair's own rule reads
1011    // both off the target's disk.
1012    observed.invariants.extend(invariants::target_failures(
1013        manifest.profile.release.driver.as_deref().unwrap_or(""),
1014        manifest.profile.forge.as_deref().unwrap_or(""),
1015        &args.target,
1016    ));
1017    // The gate builds every dist target before a merge, or the build
1018    // fails only after the tag exists.
1019    if manifest.profile.release.driver.as_deref() == Some("rust")
1020        && manifest.profile.forge.as_deref() == Some("github")
1021    {
1022        let dev_run = manifest
1023            .parameters
1024            .dev_environment
1025            .as_ref()
1026            .map_or("", |answer| answer.run.as_str());
1027        let gate = invariants::dist_targets_built(&args.target, &stated.required_check, dev_run);
1028        observed.invariants.extend(gate.failures);
1029        observed.warnings.extend(
1030            gate.limitations
1031                .into_iter()
1032                .map(|(code, reason)| Warning { code, reason }),
1033        );
1034    }
1035    observed.selection = projected.as_ref().map(|projection| {
1036        projection
1037            .capabilities
1038            .iter()
1039            .map(|selection| CapabilityNote::of(selection, projection))
1040            .collect()
1041    });
1042    if let Some(reason) = projected
1043        .as_ref()
1044        .and_then(|projection| projection.licence_refusal.clone())
1045    {
1046        observed.warnings.push(Warning {
1047            code: CODE_SCANNING_LICENCE,
1048            reason,
1049        });
1050    }
1051    // A nested hook configuration that prek would run as a project of its
1052    // own: reported, never a violation, because the file is the project's.
1053    for path in crate::hooks::unexcluded_nested_configs(args.target.as_std_path()) {
1054        observed.warnings.push(Warning {
1055            code: NESTED_HOOK_CONFIGURATION,
1056            reason: format!(
1057                "{path} is a hook configuration below the root, which prek runs as a project of its own; where it is no hook configuration of this project, list its directory in a root .prekignore"
1058            ),
1059        });
1060    }
1061    // A receipt naming a release intent nothing can honour is judged at
1062    // every alignment rather than only where this binary wrote the record.
1063    // An unavailable optional capability is not one of these: it reports
1064    // through `selection` and lands nothing, and no verb refuses on it.
1065    if let Some(projection) = projected.as_ref() {
1066        observed.incompatible.clone_from(&projection.record_defects);
1067        observed
1068            .record_drift
1069            .extend(projection.record_defects.iter().cloned());
1070    }
1071    if aligned && let Some(projection) = projected.as_ref() {
1072        observe_parameter_drift(manifest, projection, &mut observed);
1073        observe_record_set(manifest, projection, &mut observed.record_drift);
1074    }
1075    // What an upgrade would change, which is the only honest ground for
1076    // telling an operator to run one. The recorded version says who wrote
1077    // the receipt, and two releases apart can carry identical bytes for
1078    // this pair, so it answers a different question and prompts nothing.
1079    observed.pending = projected
1080        .as_ref()
1081        .map(|projection| pending_of(manifest, &projection.candidates));
1082    // Stale means behind, not merely different: a landing from a newer rk
1083    // can carry pins ahead of this binary's registry, and that is the
1084    // alignment line's story, not a freshness complaint.
1085    for (tool, landed) in &manifest.pins {
1086        if let Some(available) = registry::version_of(tool)
1087            && manifest::version_is_newer(&available, landed)
1088        {
1089            observed.stale.push(StalePin {
1090                tool: tool.clone(),
1091                landed: landed.clone(),
1092                available,
1093            });
1094        }
1095    }
1096    Ok(observed)
1097}
1098
1099/// The receipt-consistency step over every rendered destination.
1100///
1101/// Recorded digests alone cannot see a receipt edited only at its
1102/// parameters, since every file still matches its own record, so every
1103/// rendered candidate, whole file or region, as this projection renders
1104/// it from the receipt's own parameters, is compared against the digest
1105/// the receipt stores for it. Called only where this binary wrote the
1106/// receipt: an older landing's files legitimately differ from this
1107/// projection, which is the alignment line's story and the upgrade's job,
1108/// not parameter drift. A destination already reported as rendered drift
1109/// is the file's own story, not the receipt's, and is skipped too.
1110fn observe_parameter_drift(manifest: &Manifest, projection: &Projection, observed: &mut Observed) {
1111    for candidate in &projection.candidates {
1112        if candidate.kind != Kind::Rendered {
1113            continue;
1114        }
1115        let Some(record) = manifest.file(&candidate.destination) else {
1116            continue;
1117        };
1118        if observed.drift_rendered.contains(&candidate.destination)
1119            || observed.missing.contains(&candidate.destination)
1120        {
1121            continue;
1122        }
1123        if Digest::of(recorded_form(candidate)) != record.sha256 {
1124            observed
1125                .parameter_drift
1126                .push(format!("{} (parameters)", candidate.destination));
1127        }
1128    }
1129}
1130
1131/// What this binary projects under the receipt's own parameters at this
1132/// target, with the same withhold judgment a landing applies, so the
1133/// comparison stands against what an upgrade would actually offer.
1134fn project(args: &StatusArgs, manifest: &Manifest) -> Result<Projection, RkError> {
1135    let evidence = TargetEvidence::gather(&args.target, Some(manifest))?;
1136    Projection::compute(&ProjectionInput {
1137        params: landing::Params::from_record(manifest),
1138        evidence,
1139    })
1140}
1141
1142/// The bytes the receipt digests for a candidate: the whole file, or the
1143/// marked region alone.
1144fn recorded_form(candidate: &Candidate) -> &[u8] {
1145    candidate.region.as_deref().unwrap_or(&candidate.bytes)
1146}
1147
1148/// The destinations an upgrade would change, read off the record alone.
1149///
1150/// A destination the projection adds or drops changes the record either
1151/// way, and a `rendered` one whose candidate digest differs from the
1152/// recorded digest is rewritten. A `seeded` or `state` destination the
1153/// record already names is never rewritten, so only a change of kind
1154/// counts for it. Disk drift is a separate story, told by its own lines:
1155/// an edited file is the target's doing, not a newer binary's.
1156fn pending_of(manifest: &Manifest, projected: &[Candidate]) -> Vec<String> {
1157    let mut pending = Vec::new();
1158    for entry in projected {
1159        let changed = manifest.file(&entry.destination).is_none_or(|record| {
1160            record.kind != entry.kind
1161                || (entry.kind == Kind::Rendered
1162                    && record.sha256 != Digest::of(recorded_form(entry)))
1163        });
1164        if changed {
1165            pending.push(entry.destination.clone());
1166        }
1167    }
1168    for file in &manifest.files {
1169        if !projected
1170            .iter()
1171            .any(|entry| entry.destination == file.destination)
1172        {
1173            pending.push(file.destination.clone());
1174        }
1175    }
1176    pending.sort();
1177    pending.dedup();
1178    pending
1179}
1180
1181/// The receipt-set consistency step: the recorded digests judge each
1182/// named file, and the region re-render judges the region records, but
1183/// neither can see a receipt whose parameters and file list disagree, a
1184/// nix flag flipped in the receipt with no file landed, or a
1185/// once-withheld capability whose target grew into the supported shape.
1186/// So the projection is computed from the receipt's own parameters, the
1187/// same withhold judgment applied, and the two destination sets compared
1188/// both ways. A destination the projection withholds at this target is
1189/// absent because withheld, which is not drift. Called only where this
1190/// binary wrote the receipt: an older landing's set legitimately differs,
1191/// and that is the alignment line's story.
1192fn observe_record_set(
1193    manifest: &Manifest,
1194    projection: &Projection,
1195    record_drift: &mut Vec<String>,
1196) {
1197    for entry in &projection.candidates {
1198        if manifest.file(&entry.destination).is_none() {
1199            record_drift.push(format!(
1200                "the recorded parameters project {}, which the receipt does not name",
1201                entry.destination
1202            ));
1203        }
1204    }
1205    for file in &manifest.files {
1206        let produced = projection
1207            .candidates
1208            .iter()
1209            .any(|entry| entry.destination == file.destination)
1210            || projection
1211                .omissions
1212                .iter()
1213                .any(|omission| omission.destination == file.destination);
1214        if !produced {
1215            record_drift.push(format!(
1216                "the receipt names {}, which the recorded parameters do not project",
1217                file.destination
1218            ));
1219        }
1220    }
1221}
1222
1223/// The human lines, identical with and without `--check`.
1224#[allow(
1225    clippy::too_many_lines,
1226    reason = "one pass prints every reportable condition in the order the report states them"
1227)]
1228fn render_human(
1229    out: Output,
1230    args: &StatusArgs,
1231    manifest: &Manifest,
1232    alignment: Alignment,
1233    observed: &Observed,
1234) {
1235    out.result_line(format!(
1236        "release-kit {} at {}: {}",
1237        manifest.rk_version,
1238        args.target,
1239        crate::commands::profile::describe(
1240            &manifest.profile,
1241            &manifest.git,
1242            &manifest.capabilities,
1243            &manifest.parameters.repo
1244        )
1245    ));
1246    // Every capability the record does not select is information, never
1247    // a violation: a product nobody asked for, or one this target's
1248    // dimensions cannot take.
1249    for note in observed.selection.iter().flatten() {
1250        if note.status != "selected" {
1251            out.result_line(format!(
1252                "capability {}: {}{}",
1253                note.id,
1254                note.status,
1255                note.reason
1256                    .as_deref()
1257                    .map_or_else(String::new, |reason| format!(" ({reason})"))
1258            ));
1259        }
1260    }
1261    if alignment == Alignment::TargetNewer {
1262        out.result_line(format!(
1263            "binary {} is older than this landing; run the rk of the project's own environment, or move its pin with rk self-depend sync --apply",
1264            env!("CARGO_PKG_VERSION")
1265        ));
1266    }
1267    match observed.pending.as_deref() {
1268        None => out.result_line(format!(
1269            "this binary carries no projection for the recorded {} release on {}, so what an upgrade would change is unknown",
1270            manifest
1271                .profile
1272                .release
1273                .driver
1274                .as_deref()
1275                .unwrap_or("release-less"),
1276            manifest.profile.forge.as_deref().unwrap_or("no forge")
1277        )),
1278        Some(paths) => {
1279            for path in paths {
1280                out.result_line(format!("PENDING {path} (this binary would change it)"));
1281            }
1282        }
1283    }
1284    for path in &observed.drift_rendered {
1285        let digest = observed.drift_digests.get(path).map_or("", String::as_str);
1286        out.result_line(observed.drift_reasons.get(path).map_or_else(
1287            || {
1288                format!(
1289                    "DRIFT {path} (rendered, release-kit-owned): sha256 {digest}; a deliberate edit is accepted under landing.accepted_drift with its reason and this digest"
1290                )
1291            },
1292            |reason| {
1293                format!(
1294                    "DRIFT {path} (rendered, edited past its accepted drift: {reason}; sha256 now {digest})"
1295                )
1296            },
1297        ));
1298    }
1299    for note in &observed.drift_accepted {
1300        out.result_line(format!(
1301            "ACCEPTED {} (rendered, accepted drift: {})",
1302            note.destination, note.reason
1303        ));
1304    }
1305    for path in &observed.accepted_stale {
1306        out.result_line(format!(
1307            "STALE landing.accepted_drift entry for {path}: the file matches the receipt, so the entry can go"
1308        ));
1309    }
1310    for path in &observed.parameter_drift {
1311        out.result_line(format!(
1312            "DRIFT {path}: the recorded parameters do not render the recorded bytes"
1313        ));
1314    }
1315    for reason in &observed.record_drift {
1316        out.result_line(format!("DRIFT record: {reason}"));
1317    }
1318    for path in &observed.drift_seeded {
1319        out.result_line(format!("DRIFT {path} (seeded, target-owned)"));
1320    }
1321    for path in &observed.missing {
1322        out.result_line(format!("MISSING {path}"));
1323    }
1324    for pin in &observed.stale {
1325        out.result_line(format!(
1326            "STALE {} {} landed, {} in this binary",
1327            pin.tool, pin.landed, pin.available
1328        ));
1329    }
1330    for (path, line, text) in &observed.sentinels {
1331        out.result_line(format!("SENTINEL {path}:{line}: {text}"));
1332    }
1333    for failure in &observed.invariants {
1334        out.result_line(format!(
1335            "INVARIANT {} ({}): {}",
1336            failure.destination, failure.code, failure.reason
1337        ));
1338    }
1339    for warning in &observed.warnings {
1340        out.result_line(format!("WARNING ({}): {}", warning.code, warning.reason));
1341    }
1342    let proof_failure = observed.setup_proof.as_ref().and_then(SetupProof::failure);
1343    if let Some(proof) = &observed.setup_proof {
1344        out.result_line(format!("setup proof: {}", proof.state));
1345    }
1346    if let Some(failure) = &proof_failure {
1347        out.result_line(format!(
1348            "SETUP-PROOF ({}): {}",
1349            failure.code, failure.reason
1350        ));
1351    }
1352    let mut next = Vec::new();
1353    for failure in observed.invariants.iter().chain(&proof_failure) {
1354        next.push(format!("{}: {}", failure.destination, failure.remediation));
1355    }
1356    // The incompatible ones first, and with the override: a plain upgrade
1357    // reads the same recorded intent and refuses, so advertising it alone
1358    // would send the operator into a loop.
1359    if !observed.incompatible.is_empty() {
1360        next.push(format!(
1361            "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",
1362            args.target
1363        ));
1364    }
1365    if observed.record_drift.len() > observed.incompatible.len() {
1366        next.push(format!(
1367            "rk upgrade --target {} rewrites the receipt from its parameters",
1368            args.target
1369        ));
1370    }
1371    if observed
1372        .pending
1373        .as_deref()
1374        .is_none_or(|paths| !paths.is_empty())
1375    {
1376        next.push(format!(
1377            "rk upgrade --target {} takes this landing to {}",
1378            args.target,
1379            env!("CARGO_PKG_VERSION")
1380        ));
1381    }
1382    next.push(format!(
1383        "rk status --check --target {} exits 1 on a violation",
1384        args.target
1385    ));
1386    if manifest.profile.release.mode != ReleaseMode::Automatic {
1387        next.retain(|line| !line.contains("rk method operate"));
1388    }
1389    out.next(&next);
1390}
1391
1392#[cfg(test)]
1393mod tests {
1394    use super::{
1395        Classification, Drift, InvariantFailure, LegacyPath, OpenMigration, Report, SentinelAt,
1396        StalePin,
1397    };
1398    use crate::assess::{self, Facts, OwnLanding, Unrecorded};
1399    use crate::landing::CheckoutMode;
1400    use crate::landing::Integration;
1401    use crate::landing::manifest::Alignment;
1402    use crate::profile::{
1403        CapabilityRequests, GitWorkflow, ProfileSnapshot, ReleaseIntent, ReleaseMode,
1404    };
1405
1406    /// Accepted drift exempts a file from the drift judgment alone: an
1407    /// invariant failure on the same file stays a violation.
1408    #[test]
1409    fn accepted_drift_does_not_silence_an_invariant() {
1410        let destination = ".gitlab-ci.yml".to_owned();
1411        let digest = "a".repeat(64);
1412        let mut observed = super::Observed {
1413            drift_rendered: vec![destination.clone()],
1414            drift_digests: std::iter::once((destination.clone(), digest.clone())).collect(),
1415            drift_reasons: std::collections::BTreeMap::new(),
1416            drift_accepted: Vec::new(),
1417            accepted_stale: Vec::new(),
1418            drift_seeded: Vec::new(),
1419            parameter_drift: Vec::new(),
1420            record_drift: Vec::new(),
1421            missing: Vec::new(),
1422            stale: Vec::new(),
1423            sentinels: Vec::new(),
1424            invariants: vec![crate::landing::invariants::InvariantFailure {
1425                code: "an-invariant",
1426                destination: destination.clone(),
1427                reason: "the accepted bytes break it".to_owned(),
1428                remediation: "restore it",
1429            }],
1430            warnings: Vec::new(),
1431            setup_proof: None,
1432            incompatible: Vec::new(),
1433            pending: None,
1434            selection: None,
1435        };
1436        let manifest: crate::landing::manifest::Manifest = serde_json::from_str(&format!(
1437            r#"{{"schema_version":12,"rk_version":"0.1.0","origin":"init","landed_at":"2026-08-29T00:00:00Z","profile":{{"technologies":["bash"],"forge":"gitlab","release":{{"mode":"automatic","driver":"bash","style":"trunk","line_prefix":"release/"}}}},"git":{{"trunk":"master","checkout_mode":"linked-worktree","integration":"local","merge_form":"squash"}},"capabilities":{{"nix_packaging":false,"reporting_policy":true,"scorecard":false,"workflow_guards":false}},"parameters":{{"repo":"acme/widget"}},"files":[{{"destination":".gitlab-ci.yml","kind":"rendered","sha256":"{}"}}],"pins":{{}}}}"#,
1438            crate::digest::Digest::of(b"candidate")
1439        ))
1440        .expect("the record parses");
1441        let accepted = std::iter::once((
1442            destination,
1443            crate::config::AcceptedDrift {
1444                reason: "deliberate".to_owned(),
1445                sha256: digest,
1446            },
1447        ))
1448        .collect();
1449        super::accept(&mut observed, &manifest, &accepted).expect("accepts");
1450        assert!(observed.drift_rendered.is_empty());
1451        let violations = super::violations_of(&observed);
1452        assert!(
1453            violations.iter().any(|line| line.contains("an-invariant")),
1454            "{violations:?}"
1455        );
1456    }
1457
1458    /// The complete `rk.status/16` shape, held by snapshot in both the
1459    /// landed and absent forms.
1460    #[test]
1461    #[allow(
1462        clippy::too_many_lines,
1463        reason = "the snapshot states every field of both forms in one place"
1464    )]
1465    fn the_status_report_schema_snapshot_holds() {
1466        let landed = Report {
1467            schema: super::SCHEMA,
1468            landed: true,
1469            classification: Some(Classification::Upgrade),
1470            git_work_tree: true,
1471            config: super::ConfigState {
1472                state: "pending",
1473                pending: vec!["profile.release.style".into()],
1474            },
1475            profile: Some(ProfileSnapshot {
1476                technologies: vec!["rust".into()],
1477                forge: Some("github".into()),
1478                release: ReleaseIntent {
1479                    mode: ReleaseMode::Automatic,
1480                    driver: Some("rust".into()),
1481                    style: Some(crate::landing::Style::Trunk),
1482                    line_prefix: Some("release/".into()),
1483                    registry: None,
1484                    build: None,
1485                },
1486            }),
1487            git: Some(GitWorkflow {
1488                trunk: "master".into(),
1489                checkout_mode: CheckoutMode::LinkedWorktree,
1490                integration: Integration::Local,
1491                merge_form: crate::landing::MergeForm::Squash,
1492            }),
1493            capabilities: Some(CapabilityRequests {
1494                nix_packaging: true,
1495                reporting_policy: true,
1496                scorecard: false,
1497                code_scanning: Some(crate::landing::Provider::Semgrep),
1498                workflow_guards: Some(false),
1499            }),
1500            selection: Some(vec![]),
1501            rk_version: Some("0.1.0".into()),
1502            binary_version: Some("0.2.0"),
1503            alignment: Some(crate::landing::manifest::Alignment::BinaryNewer),
1504            pin: Some(super::PinState {
1505                version: "0.1.0".to_owned(),
1506                latest: Some("0.2.0".to_owned()),
1507                behind: true,
1508            }),
1509            drift: Some(Drift {
1510                rendered: 0,
1511                seeded: 1,
1512            }),
1513            missing: Some(vec![]),
1514            stale_pins: Some(vec![StalePin {
1515                tool: "release-plz".into(),
1516                landed: "0.3.160".into(),
1517                available: "0.3.170".into(),
1518            }]),
1519            sentinels: Some(1),
1520            sentinel_locations: Some(vec![SentinelAt {
1521                file: "release-plz.toml".into(),
1522                line: 18,
1523                text: "# TODO(release-kit): keep false for a binary-only crate".into(),
1524            }]),
1525            record_drift: Some(0),
1526            invariant_failures: Some(vec![InvariantFailure {
1527                code: "attestations-disabled",
1528                destination: "dist-workspace.toml".into(),
1529                reason: "github-attestations is not effectively true".into(),
1530                remediation: "set github-attestations = true in [dist]",
1531            }]),
1532            warnings: Some(vec![super::Warning {
1533                code: super::CODE_SCANNING_LICENCE,
1534                reason: "the target's license, LicenseRef-proprietary, does not state a codebase this release recognizes as open source".into(),
1535            }]),
1536            setup_proof: Some(super::SetupProof {
1537                state: "stale",
1538                changed: vec!["target.required_check".into()],
1539                reason: None,
1540                detail: None,
1541            }),
1542            pending: Some(2),
1543            accepted_drift: Some(vec![super::AcceptedNote {
1544                destination: ".gitlab-ci.yml".into(),
1545                reason: "the image carries a tool".into(),
1546            }]),
1547            stale_accepted_drift: Some(vec![]),
1548            violations: None,
1549            legacy_state: vec![LegacyPath {
1550                path: "/state/release-kit/plans/0123456789abcdef".into(),
1551                kind: "plan",
1552                active: true,
1553            }],
1554            migration: Some(OpenMigration {
1555                id: "20261009T140205Z".into(),
1556                workspace: Some(
1557                    "/state/release-kit/migrations/widget-0123456789ab/20261009T140205Z".into(),
1558                ),
1559                unfinished: Some(2),
1560            }),
1561        };
1562        assert_eq!(
1563            serde_json::to_string(&landed).expect("a report serializes"),
1564            r##"{"schema":"rk.status/16","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","pin":{"version":"0.1.0","latest":"0.2.0","behind":true},"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,"accepted_drift":[{"destination":".gitlab-ci.yml","reason":"the image carries a tool"}],"stale_accepted_drift":[],"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}}"##
1565        );
1566        let absent = Report {
1567            landed: false,
1568            classification: Some(Classification::Setup),
1569            git_work_tree: false,
1570            config: super::ConfigState {
1571                state: "absent",
1572                pending: vec![],
1573            },
1574            profile: None,
1575            git: None,
1576            capabilities: None,
1577            selection: None,
1578            rk_version: None,
1579            binary_version: None,
1580            alignment: None,
1581            pin: None,
1582            drift: None,
1583            missing: None,
1584            stale_pins: None,
1585            sentinels: None,
1586            sentinel_locations: None,
1587            record_drift: None,
1588            invariant_failures: None,
1589            warnings: None,
1590            setup_proof: None,
1591            pending: None,
1592            accepted_drift: None,
1593            stale_accepted_drift: None,
1594            violations: None,
1595            legacy_state: vec![],
1596            migration: None,
1597            ..landed
1598        };
1599        assert_eq!(
1600            serde_json::to_string(&absent).expect("a report serializes"),
1601            r#"{"schema":"rk.status/16","landed":false,"classification":"setup","git_work_tree":false,"config":{"state":"absent","pending":[]},"legacy_state":[]}"#,
1602            "an absent landing reports the fields a caller can branch on"
1603        );
1604        let newer = Report {
1605            classification: None,
1606            ..absent
1607        };
1608        assert!(
1609            serde_json::to_string(&newer)
1610                .expect("a report serializes")
1611                .contains(r#""classification":null"#),
1612            "no classification is stated as null, never omitted"
1613        );
1614    }
1615
1616    fn facts() -> Facts {
1617        Facts {
1618            technologies: Vec::new(),
1619            forge: None,
1620            repo: None,
1621            release_markers: Vec::new(),
1622            collisions: Vec::new(),
1623            git: true,
1624            tags: 0,
1625            long_lived_branches: Vec::new(),
1626        }
1627    }
1628
1629    /// Each value the gate reads has one rule that earns it: the
1630    /// assessment's three for a target with no record, the adoption
1631    /// detector before them, and the alignment and the check for a
1632    /// recorded one.
1633    #[test]
1634    fn every_classification_has_its_rule() {
1635        let none = OwnLanding::default();
1636        let classify = |facts: &Facts, own: &OwnLanding| {
1637            super::unrecorded(assess::classify_unrecorded(facts, own))
1638        };
1639        assert_eq!(classify(&facts(), &none), Classification::Setup);
1640        let marked = Facts {
1641            release_markers: vec![".goreleaser.yaml".into()],
1642            ..facts()
1643        };
1644        assert_eq!(classify(&marked, &none), Classification::Migration);
1645        let tagged = Facts { tags: 3, ..facts() };
1646        assert_eq!(classify(&tagged, &none), Classification::NeedsDecision);
1647        // release-kit's own regions read as collisions to the assessment,
1648        // and the detector outranks them.
1649        let own = OwnLanding {
1650            regions: vec!["AGENTS.md".into()],
1651            rendered: Vec::new(),
1652        };
1653        let colliding = Facts {
1654            collisions: vec!["AGENTS.md".into()],
1655            release_markers: vec!["CHANGELOG.md".into()],
1656            ..facts()
1657        };
1658        assert_eq!(classify(&colliding, &own), Classification::Adopt);
1659        assert_eq!(
1660            assess::classify_unrecorded(&colliding, &own),
1661            Unrecorded::Adopt
1662        );
1663        assert_eq!(
1664            super::recorded(Alignment::BinaryNewer, false),
1665            Some(Classification::Upgrade)
1666        );
1667        assert_eq!(
1668            super::recorded(Alignment::Aligned, false),
1669            Some(Classification::Drift)
1670        );
1671        assert_eq!(
1672            super::recorded(Alignment::Aligned, true),
1673            Some(Classification::Current)
1674        );
1675        assert_eq!(super::recorded(Alignment::TargetNewer, true), None);
1676        for (class, word) in [
1677            (Classification::Setup, "setup"),
1678            (Classification::Migration, "migration"),
1679            (Classification::NeedsDecision, "needs-decision"),
1680            (Classification::Adopt, "adopt"),
1681            (Classification::Upgrade, "upgrade"),
1682            (Classification::Drift, "drift"),
1683            (Classification::Current, "current"),
1684        ] {
1685            assert_eq!(class.as_str(), word);
1686            assert_eq!(
1687                serde_json::to_string(&class).expect("serializes"),
1688                format!("\"{word}\"")
1689            );
1690        }
1691    }
1692}