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 code a lapsed code scanning licence reports under.
156const CODE_SCANNING_LICENCE: &str = "code-scanning-licence";
157
158/// Where a target stands for the setup skill's gate: one word computed by
159/// the CLI's own rule, so no reader branches on five fields by hand.
160///
161/// SATISFIES landing:a-landing-classifies-its-target-first
162#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
163#[serde(rename_all = "kebab-case")]
164pub enum Classification {
165    /// No record, no release mechanism, and no release history.
166    Setup,
167    /// No record and another release mechanism in place.
168    Migration,
169    /// No record and release activity no mechanism explains.
170    NeedsDecision,
171    /// No record, and release-kit's own landing is present.
172    Adopt,
173    /// A record older than this binary.
174    Upgrade,
175    /// A record at this binary's version that `--check` fails.
176    Drift,
177    /// A record at this binary's version that `--check` passes.
178    Current,
179}
180
181impl Classification {
182    /// The kebab-case word, as the JSON serializes it.
183    #[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
197/// The classification of a target with no record, from the assessment's
198/// rule and the adoption detector.
199const 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
212/// The classification of a recorded target. A record newer than this
213/// binary has none: that is an observation the setup skill routes to
214/// provisioning, not a state this binary can judge.
215const 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/// One unfilled judgment sentinel, located.
225#[derive(Debug, Clone, Serialize)]
226struct SentinelAt {
227    /// The landed file that carries it.
228    file: String,
229    /// Its line, counted from one.
230    line: usize,
231    /// The line's text, trimmed.
232    text: String,
233}
234
235/// One path a 0.4.x release left under the state root.
236#[derive(Debug, Serialize)]
237struct LegacyPath {
238    /// The absolute path.
239    path: String,
240    /// `plan` for a stored plan, `release-cache` for the release cache.
241    kind: &'static str,
242    /// Whether it holds an operation the old binary could still apply.
243    active: bool,
244}
245
246/// The state a 0.4.x release stored under the state root, each path with
247/// whether an operation is active. No later release writes `plans/` or
248/// `release/`, so what is there is the old binary's.
249///
250/// A stored plan reads as active while its own document says an apply
251/// may run it, and while it cannot be read at all, because only the
252/// operator can retire an operation the old binary owns. The release
253/// cache holds no operation.
254fn 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
290/// Where a 0.4.x release stored its plans, under the state root.
291const LEGACY_PLANS: &str = "plans";
292
293/// Where a 0.4.x release cached fetched releases, under the state root.
294const LEGACY_RELEASE_CACHE: &str = "release";
295
296/// The status report's shape version.
297const SCHEMA: &str = "rk.status/14";
298
299/// Configuration is informational, independent of every drift comparison.
300#[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/// The machine form of a status report.
325#[derive(Debug, Serialize)]
326struct Report {
327    /// The shape version of this document.
328    schema: &'static str,
329    /// Whether a landing record exists; most other fields need one.
330    landed: bool,
331    /// Where the target stands for the setup skill's gate; null where the
332    /// record is newer than this binary.
333    classification: Option<Classification>,
334    /// Whether the target sits in a non-bare Git work tree.
335    git_work_tree: bool,
336    config: ConfigState,
337    /// What the record says the project is.
338    #[serde(skip_serializing_if = "Option::is_none")]
339    profile: Option<ProfileSnapshot>,
340    /// The recorded Git workflow.
341    #[serde(skip_serializing_if = "Option::is_none")]
342    git: Option<GitWorkflow>,
343    /// The recorded capability requests.
344    #[serde(skip_serializing_if = "Option::is_none")]
345    capabilities: Option<CapabilityRequests>,
346    /// Every capability the catalog answers for the recorded values, in
347    /// catalog order; absent where this binary cannot project the record.
348    #[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    /// Recorded destinations absent from the disk.
359    #[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    /// Unresolved judgment sentinels across the landed files.
364    #[serde(skip_serializing_if = "Option::is_none")]
365    sentinels: Option<usize>,
366    /// Each unresolved sentinel, by file and line.
367    #[serde(skip_serializing_if = "Option::is_none")]
368    sentinel_locations: Option<Vec<SentinelAt>>,
369    /// Record-set disagreements between the recorded parameters'
370    /// projection and the recorded destinations — its own count, because
371    /// no file was edited and the kind counts must stay honest.
372    #[serde(skip_serializing_if = "Option::is_none")]
373    record_drift: Option<usize>,
374    /// Invariants a landed file's effective configuration violates —
375    /// judged, never rewritten, because the file stays the target's.
376    #[serde(skip_serializing_if = "Option::is_none")]
377    invariant_failures: Option<Vec<InvariantFailure>>,
378    /// Conditions that are reportable and not violations: `--check` exits 0
379    /// on them, because the target is not broken and the decision is the
380    /// operator's.
381    #[serde(skip_serializing_if = "Option::is_none")]
382    warnings: Option<Vec<Warning>>,
383    /// Where the committed setup proof stands, on a target with an
384    /// automatic release and a forge; absent on every other target.
385    #[serde(skip_serializing_if = "Option::is_none")]
386    setup_proof: Option<SetupProof>,
387    /// How many destinations an upgrade would change: the count this
388    /// binary's sources project under the recorded parameters against
389    /// what the record names. Zero means nothing to take, whatever the two
390    /// versions say. Absent on a landed target means this binary carries
391    /// no files for the recorded pair and cannot answer.
392    #[serde(skip_serializing_if = "Option::is_none")]
393    pending: Option<usize>,
394    /// Present only under `--check`: what the judgment failed on.
395    #[serde(skip_serializing_if = "Option::is_none")]
396    violations: Option<Vec<String>>,
397    /// The state a 0.4.x release left under the state root.
398    legacy_state: Vec<LegacyPath>,
399    /// The open migration, where the configuration names one.
400    #[serde(skip_serializing_if = "Option::is_none")]
401    migration: Option<OpenMigration>,
402}
403
404/// An open migration, as the status reports it.
405#[derive(Debug, Serialize)]
406struct OpenMigration {
407    /// The identifier the configuration names.
408    id: String,
409    /// The workspace on this host, absent where this host holds none.
410    #[serde(skip_serializing_if = "Option::is_none")]
411    workspace: Option<String>,
412    /// How many sources are neither verified nor dropped, absent where
413    /// this host holds no registry.
414    #[serde(skip_serializing_if = "Option::is_none")]
415    unfinished: Option<usize>,
416}
417
418/// The open migration the configuration names, read from this host's
419/// workspace where it holds one.
420///
421/// SATISFIES migration:the-configuration-names-the-open-migration
422fn 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
446/// The line a human report carries for an open migration.
447fn 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
528/// What one pass over the record and the disk observed.
529struct Observed {
530    drift_rendered: Vec<String>,
531    drift_seeded: Vec<String>,
532    /// Recorded block destinations whose recorded digest the record's own
533    /// parameters do not reproduce: the record was edited, not the file.
534    parameter_drift: Vec<String>,
535    /// Set differences between what the recorded parameters project —
536    /// the withhold judgment applied — and the destinations the record
537    /// names: a record whose parameters and file list disagree, whichever
538    /// of the two was edited or outgrown.
539    record_drift: Vec<String>,
540    missing: Vec<String>,
541    stale: Vec<StalePin>,
542    sentinels: Vec<(String, usize, String)>,
543    invariants: Vec<InvariantFailure>,
544    /// Reportable conditions that are not violations.
545    warnings: Vec<Warning>,
546    setup_proof: Option<SetupProof>,
547    /// Recorded intents this target cannot honour, counted in
548    /// `record_drift` and kept separately because a plain upgrade cannot
549    /// repair them: it re-reads the same recorded answer and refuses. An
550    /// unavailable optional capability is not one of these; it is reported
551    /// in `selection` and omitted, and an upgrade runs over it unharmed.
552    incompatible: Vec<String>,
553    /// The destinations an upgrade would change, or `None` where this
554    /// binary carries no projection for the recorded pair and so cannot
555    /// say.
556    pending: Option<Vec<String>>,
557    /// Every capability the catalog answers for the recorded values.
558    selection: Option<Vec<CapabilityNote>>,
559}
560
561/// Report the target's landing.
562///
563/// # Errors
564///
565/// Returns [`RkError::Missing`] for a target that is not a directory, the
566/// record's own failure taxonomy for an unreadable or unknown record, and
567/// [`RkError::CheckFailed`] under `--check` when the report holds a
568/// violation.
569pub 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    // A record newer than this binary is no state it can judge, an open
602    // migration included; below that, the open migration outranks the
603    // record until it closes.
604    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
678/// The human lines every report carries, landed or not: whether the
679/// target is a work tree the method can land in, and each path a 0.4.x
680/// release left under the state root.
681fn 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
695/// The check-mode violation lines: rendered drift, missing recorded
696/// files, unresolved sentinels, and invariant failures — the closed set
697/// `landing:status-judges-only-under-check` names.
698fn 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
743/// The answers the target states now, for the judgments: a committed
744/// answer the landing verbs have yet to take up outranks the record.
745struct Stated {
746    /// Where the crate publishes.
747    registry: Option<RegistryAnswer>,
748    /// The check context of the gate.
749    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            // The landing writes the check back as a class P answer, so a
759            // configuration that exists states it, an empty one included.
760            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/// One pass over the record and the disk: drift, missing files, stale
769/// pins, and sentinels.
770#[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    // One projection serves every reader below, because each asks what
791    // this binary makes of the recorded parameters at this target. A pair
792    // this binary does not carry cannot be projected at all: under a
793    // receipt this binary wrote that is a defect and still fails, and
794    // under a landing from another rk it is a fact to report.
795    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        // A marked document's markers must be well formed even when its
832        // first block matches the receipt: a duplicate hook block still
833        // executes, so an ill-formed document reads as rendered drift,
834        // never as clean.
835        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    // The cross-file step: a landed file can generate the artifact the
846    // forge actually executes, and the seeds ship no copy of it, so no
847    // recorded digest sees the two disagree. The pair's own rule reads
848    // both off the target's disk.
849    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    // The gate builds every dist target before a merge, or the build
855    // fails only after the tag exists.
856    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    // A receipt naming a release intent nothing can honour is judged at
884    // every alignment rather than only where this binary wrote the record.
885    // An unavailable optional capability is not one of these: it reports
886    // through `selection` and lands nothing, and no verb refuses on it.
887    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    // What an upgrade would change, which is the only honest ground for
898    // telling an operator to run one. The recorded version says who wrote
899    // the receipt, and two releases apart can carry identical bytes for
900    // this pair, so it answers a different question and prompts nothing.
901    observed.pending = projected
902        .as_ref()
903        .map(|projection| pending_of(manifest, &projection.candidates));
904    // Stale means behind, not merely different: a landing from a newer rk
905    // can carry pins ahead of this binary's registry, and that is the
906    // alignment line's story, not a freshness complaint.
907    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
921/// The receipt-consistency step over every rendered destination.
922///
923/// Recorded digests alone cannot see a receipt edited only at its
924/// parameters, since every file still matches its own record, so every
925/// rendered candidate, whole file or region, as this projection renders
926/// it from the receipt's own parameters, is compared against the digest
927/// the receipt stores for it. Called only where this binary wrote the
928/// receipt: an older landing's files legitimately differ from this
929/// projection, which is the alignment line's story and the upgrade's job,
930/// not parameter drift. A destination already reported as rendered drift
931/// is the file's own story, not the receipt's, and is skipped too.
932fn 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
953/// What this binary projects under the receipt's own parameters at this
954/// target, with the same withhold judgment a landing applies, so the
955/// comparison stands against what an upgrade would actually offer.
956fn 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
964/// The bytes the receipt digests for a candidate: the whole file, or the
965/// marked region alone.
966fn recorded_form(candidate: &Candidate) -> &[u8] {
967    candidate.region.as_deref().unwrap_or(&candidate.bytes)
968}
969
970/// The destinations an upgrade would change, read off the record alone.
971///
972/// A destination the projection adds or drops changes the record either
973/// way, and a `rendered` one whose candidate digest differs from the
974/// recorded digest is rewritten. A `seeded` or `state` destination the
975/// record already names is never rewritten, so only a change of kind
976/// counts for it. Disk drift is a separate story, told by its own lines:
977/// an edited file is the target's doing, not a newer binary's.
978fn 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
1003/// The receipt-set consistency step: the recorded digests judge each
1004/// named file, and the region re-render judges the region records, but
1005/// neither can see a receipt whose parameters and file list disagree, a
1006/// nix flag flipped in the receipt with no file landed, or a
1007/// once-withheld capability whose target grew into the supported shape.
1008/// So the projection is computed from the receipt's own parameters, the
1009/// same withhold judgment applied, and the two destination sets compared
1010/// both ways. A destination the projection withholds at this target is
1011/// absent because withheld, which is not drift. Called only where this
1012/// binary wrote the receipt: an older landing's set legitimately differs,
1013/// and that is the alignment line's story.
1014fn 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/// The human lines, identical with and without `--check`.
1046#[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    // Every capability the record does not select is information, never
1069    // a violation: a product nobody asked for, or one this target's
1070    // dimensions cannot take.
1071    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    // The incompatible ones first, and with the override: a plain upgrade
1156    // reads the same recorded intent and refuses, so advertising it alone
1157    // would send the operator into a loop.
1158    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    /// The complete `rk.status/14` shape, held by snapshot in both the
1206    /// landed and absent forms.
1207    #[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    /// Each value the gate reads has one rule that earns it: the
1363    /// assessment's three for a target with no record, the adoption
1364    /// detector before them, and the alignment and the check for a
1365    /// recorded one.
1366    #[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        // release-kit's own regions read as collisions to the assessment,
1381        // and the detector outranks them.
1382        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}