release-kit 0.9.14

A canonical release workflow: a technology-agnostic method, per-technology bindings, and the rk CLI that lands and serves them.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
//! `rk status`: a target describes itself from its own disk.
//!
//! Read-only and offline: the receipt supplies what landed, this binary's
//! projection supplies what an upgrade would offer, the embedded registry
//! supplies the pin comparison, and no network is ever touched: a fetch
//! is a way for a status command to hang, fail on a network it should not
//! need, or leak a repository's existence. Status compares the current
//! target with this binary's projection and the receipt and nothing else;
//! it reads no stage and resolves no other release. Plain `rk status`
//! reports and exits 0 for every reportable state, drift and no-landing
//! included; `--check` computes the identical report and changes only
//! the final judgment, the one sanctioned bare exit 1.
//!
//! SATISFIES landing:status-judges-only-under-check

use serde::Serialize;

use crate::cli::status::StatusArgs;
use crate::diagnostic::{Diagnostic, Reason};
use crate::digest::Digest;
use crate::error::RkError;
use crate::landing::invariants::{self, InvariantFailure};
use crate::landing::manifest::{self, Alignment, Manifest};
use crate::landing::{self, Kind};
use crate::output::Output;
use crate::profile::RegistryAnswer;
use crate::profile::{CapabilityRequests, GitWorkflow, ProfileSnapshot, ReleaseMode};
use crate::projection::{Candidate, Projection, ProjectionInput, TargetEvidence};
use crate::stage::CapabilityNote;
use crate::{assess, embedded, registry};

/// Drift counts by owned kind; `state` files are never compared.
#[derive(Debug, Serialize)]
struct Drift {
    /// Edits to files release-kit owns — the violation class.
    rendered: usize,
    /// Edits to files the target owns — expected and informational.
    seeded: usize,
}

/// One recorded pin that is behind this binary's registry.
#[derive(Debug, Serialize)]
struct StalePin {
    /// The tool's registry name.
    tool: String,
    /// The version the landing recorded.
    landed: String,
    /// The version this binary's registry pins.
    available: String,
}

/// One reportable condition that is not a violation: the target is not
/// broken and the decision behind it is the operator's.
///
/// The `code` is stable, so a machine reader branches on it rather than on
/// the prose.
#[derive(Debug, Serialize)]
struct Warning {
    /// The stable reason code.
    code: &'static str,
    /// What the condition is, in the target's own terms.
    reason: String,
}

/// Where the committed setup proof stands against the contract the target
/// states now, read offline.
///
/// SATISFIES setup-proof:the-status-check-holds-the-proof
#[derive(Debug, Clone, Serialize)]
struct SetupProof {
    /// `compatible`, `stale`, `invalid`, or `absent`.
    state: &'static str,
    /// Each changed field of a stale proof.
    #[serde(skip_serializing_if = "Vec::is_empty")]
    changed: Vec<String>,
    /// Why an invalid proof cannot be read.
    #[serde(skip_serializing_if = "Option::is_none")]
    reason: Option<&'static str>,
    /// What an invalid proof held, one line.
    #[serde(skip_serializing_if = "Option::is_none")]
    detail: Option<String>,
}

/// What every setup proof code asks the operator to run, who holds the
/// credentials the check reads.
const 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";

impl SetupProof {
    fn of(standing: &crate::setup::proof::Standing) -> Self {
        use crate::setup::proof::Standing;
        let mut proof = Self {
            state: standing.word(),
            changed: Vec::new(),
            reason: None,
            detail: None,
        };
        match standing {
            Standing::Stale { differences, .. } => proof.changed.clone_from(differences),
            Standing::Invalid { reason, detail } => {
                proof.reason = Some(reason);
                proof.detail = Some(detail.clone());
            }
            Standing::Absent | Standing::Compatible(_) => {}
        }
        proof
    }

    /// The violation a proof that is not compatible counts under
    /// `--check`.
    fn failure(&self) -> Option<InvariantFailure> {
        let (code, reason) = match self.state {
            "absent" => (
                "setup-proof-absent",
                "no .release-kit/setup-proof.json is committed, so nothing proves the forge, the registry, and the bot meet the setup contract".to_owned(),
            ),
            "stale" => (
                "setup-proof-stale",
                format!(
                    "the committed setup proof was written for another setup contract; changed: {}",
                    self.changed.join(", ")
                ),
            ),
            "invalid" => (
                "setup-proof-invalid",
                format!(
                    "the committed setup proof cannot be read: {}: {}",
                    self.reason.unwrap_or("invalid"),
                    self.detail.as_deref().unwrap_or("")
                ),
            ),
            _ => return None,
        };
        Some(InvariantFailure {
            code,
            destination: crate::setup::proof::PROOF_PATH.to_owned(),
            reason,
            remediation: SETUP_PROOF_REMEDIATION,
        })
    }
}

/// The committed setup proof, for a target whose automatic release has a
/// forge to set up; `None` for every other target, whose report is
/// unchanged.
fn setup_proof_of(
    target: &camino::Utf8PathBuf,
    manifest: &Manifest,
) -> Result<Option<SetupProof>, RkError> {
    if manifest.profile.release.mode != ReleaseMode::Automatic || manifest.profile.forge.is_none() {
        return Ok(None);
    }
    Ok(Some(SetupProof::of(&crate::setup::proof::offline(target)?)))
}

/// The code a lapsed code scanning licence reports under.
const CODE_SCANNING_LICENCE: &str = "code-scanning-licence";

/// Where a target stands for the setup skill's gate: one word computed by
/// the CLI's own rule, so no reader branches on five fields by hand.
///
/// SATISFIES landing:a-landing-classifies-its-target-first
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
#[serde(rename_all = "kebab-case")]
pub enum Classification {
    /// No record, no release mechanism, and no release history.
    Setup,
    /// No record and another release mechanism in place.
    Migration,
    /// No record and release activity no mechanism explains.
    NeedsDecision,
    /// No record, and release-kit's own landing is present.
    Adopt,
    /// A record older than this binary.
    Upgrade,
    /// A record at this binary's version that `--check` fails.
    Drift,
    /// A record at this binary's version that `--check` passes.
    Current,
}

impl Classification {
    /// The kebab-case word, as the JSON serializes it.
    #[must_use]
    pub const fn as_str(self) -> &'static str {
        match self {
            Self::Setup => "setup",
            Self::Migration => "migration",
            Self::NeedsDecision => "needs-decision",
            Self::Adopt => "adopt",
            Self::Upgrade => "upgrade",
            Self::Drift => "drift",
            Self::Current => "current",
        }
    }
}

/// The classification of a target with no record, from the assessment's
/// rule and the adoption detector.
const fn unrecorded(class: assess::Unrecorded) -> Classification {
    match class {
        assess::Unrecorded::Adopt => Classification::Adopt,
        assess::Unrecorded::Assessed(assess::Classification::Greenfield) => Classification::Setup,
        assess::Unrecorded::Assessed(assess::Classification::Brownfield) => {
            Classification::Migration
        }
        assess::Unrecorded::Assessed(assess::Classification::NeedsDecision) => {
            Classification::NeedsDecision
        }
    }
}

/// The classification of a recorded target. A record newer than this
/// binary has none: that is an observation the setup skill routes to
/// provisioning, not a state this binary can judge.
const fn recorded(alignment: Alignment, clean: bool) -> Option<Classification> {
    match alignment {
        Alignment::TargetNewer => None,
        Alignment::BinaryNewer => Some(Classification::Upgrade),
        Alignment::Aligned if clean => Some(Classification::Current),
        Alignment::Aligned => Some(Classification::Drift),
    }
}

/// One unfilled judgment sentinel, located.
#[derive(Debug, Clone, Serialize)]
struct SentinelAt {
    /// The landed file that carries it.
    file: String,
    /// Its line, counted from one.
    line: usize,
    /// The line's text, trimmed.
    text: String,
}

/// One path a 0.4.x release left under the state root.
#[derive(Debug, Serialize)]
struct LegacyPath {
    /// The absolute path.
    path: String,
    /// `plan` for a stored plan, `release-cache` for the release cache.
    kind: &'static str,
    /// Whether it holds an operation the old binary could still apply.
    active: bool,
}

/// The state a 0.4.x release stored under the state root, each path with
/// whether an operation is active. No later release writes `plans/` or
/// `release/`, so what is there is the old binary's.
///
/// A stored plan reads as active while its own document says an apply
/// may run it, and while it cannot be read at all, because only the
/// operator can retire an operation the old binary owns. The release
/// cache holds no operation.
fn legacy_state() -> Vec<LegacyPath> {
    let Some(root) = crate::applog::state_root() else {
        return Vec::new();
    };
    let mut found = Vec::new();
    if let Ok(entries) = std::fs::read_dir(root.join(LEGACY_PLANS)) {
        let mut plans: Vec<std::path::PathBuf> = entries
            .flatten()
            .filter(|entry| !entry.file_name().to_string_lossy().starts_with('.'))
            .map(|entry| entry.path())
            .filter(|path| path.is_dir())
            .collect();
        plans.sort();
        for plan in plans {
            let active = std::fs::read(plan.join("plan.json"))
                .ok()
                .and_then(|bytes| serde_json::from_slice::<serde_json::Value>(&bytes).ok())
                .is_none_or(|document| document["readiness"].as_str() == Some("ready"));
            found.push(LegacyPath {
                path: plan.display().to_string(),
                kind: "plan",
                active,
            });
        }
    }
    let cache = root.join(LEGACY_RELEASE_CACHE);
    if cache.is_dir() {
        found.push(LegacyPath {
            path: cache.display().to_string(),
            kind: "release-cache",
            active: false,
        });
    }
    found
}

/// Where a 0.4.x release stored its plans, under the state root.
const LEGACY_PLANS: &str = "plans";

/// Where a 0.4.x release cached fetched releases, under the state root.
const LEGACY_RELEASE_CACHE: &str = "release";

/// The status report's shape version.
const SCHEMA: &str = "rk.status/15";

/// Configuration is informational, independent of every drift comparison.
#[derive(Debug, serde::Serialize)]
struct ConfigState {
    state: &'static str,
    pending: Vec<String>,
}

fn config_state(config: Option<&crate::config::Config>, record: Option<&Manifest>) -> ConfigState {
    let pending = config
        .zip(record)
        .map_or_else(Vec::new, |(config, record)| {
            crate::config::pending(config, record)
        });
    ConfigState {
        state: if config.is_none() {
            "absent"
        } else if pending.is_empty() {
            "aligned"
        } else {
            "pending"
        },
        pending,
    }
}

/// The machine form of a status report.
#[derive(Debug, Serialize)]
struct Report {
    /// The shape version of this document.
    schema: &'static str,
    /// Whether a landing record exists; most other fields need one.
    landed: bool,
    /// Where the target stands for the setup skill's gate; null where the
    /// record is newer than this binary.
    classification: Option<Classification>,
    /// Whether the target sits in a non-bare Git work tree.
    git_work_tree: bool,
    config: ConfigState,
    /// What the record says the project is.
    #[serde(skip_serializing_if = "Option::is_none")]
    profile: Option<ProfileSnapshot>,
    /// The recorded Git workflow.
    #[serde(skip_serializing_if = "Option::is_none")]
    git: Option<GitWorkflow>,
    /// The recorded capability requests.
    #[serde(skip_serializing_if = "Option::is_none")]
    capabilities: Option<CapabilityRequests>,
    /// Every capability the catalog answers for the recorded values, in
    /// catalog order; absent where this binary cannot project the record.
    #[serde(skip_serializing_if = "Option::is_none")]
    selection: Option<Vec<CapabilityNote>>,
    #[serde(skip_serializing_if = "Option::is_none")]
    rk_version: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    binary_version: Option<&'static str>,
    #[serde(skip_serializing_if = "Option::is_none")]
    alignment: Option<Alignment>,
    #[serde(skip_serializing_if = "Option::is_none")]
    drift: Option<Drift>,
    /// Recorded destinations absent from the disk.
    #[serde(skip_serializing_if = "Option::is_none")]
    missing: Option<Vec<String>>,
    #[serde(skip_serializing_if = "Option::is_none")]
    stale_pins: Option<Vec<StalePin>>,
    /// Unresolved judgment sentinels across the landed files.
    #[serde(skip_serializing_if = "Option::is_none")]
    sentinels: Option<usize>,
    /// Each unresolved sentinel, by file and line.
    #[serde(skip_serializing_if = "Option::is_none")]
    sentinel_locations: Option<Vec<SentinelAt>>,
    /// Record-set disagreements between the recorded parameters'
    /// projection and the recorded destinations — its own count, because
    /// no file was edited and the kind counts must stay honest.
    #[serde(skip_serializing_if = "Option::is_none")]
    record_drift: Option<usize>,
    /// Invariants a landed file's effective configuration violates —
    /// judged, never rewritten, because the file stays the target's.
    #[serde(skip_serializing_if = "Option::is_none")]
    invariant_failures: Option<Vec<InvariantFailure>>,
    /// Conditions that are reportable and not violations: `--check` exits 0
    /// on them, because the target is not broken and the decision is the
    /// operator's.
    #[serde(skip_serializing_if = "Option::is_none")]
    warnings: Option<Vec<Warning>>,
    /// Where the committed setup proof stands, on a target with an
    /// automatic release and a forge; absent on every other target.
    #[serde(skip_serializing_if = "Option::is_none")]
    setup_proof: Option<SetupProof>,
    /// How many destinations an upgrade would change: the count this
    /// binary's sources project under the recorded parameters against
    /// what the record names. Zero means nothing to take, whatever the two
    /// versions say. Absent on a landed target means this binary carries
    /// no files for the recorded pair and cannot answer.
    #[serde(skip_serializing_if = "Option::is_none")]
    pending: Option<usize>,
    /// Rendered files edited on purpose, each under its accepted-drift
    /// entry and reason: reported, never a violation.
    #[serde(skip_serializing_if = "Option::is_none")]
    accepted_drift: Option<Vec<AcceptedNote>>,
    /// Accepted-drift entries whose file matches the receipt again: the
    /// deviation is gone and the entry can go.
    #[serde(skip_serializing_if = "Option::is_none")]
    stale_accepted_drift: Option<Vec<String>>,
    /// Present only under `--check`: what the judgment failed on.
    #[serde(skip_serializing_if = "Option::is_none")]
    violations: Option<Vec<String>>,
    /// The state a 0.4.x release left under the state root.
    legacy_state: Vec<LegacyPath>,
    /// The open migration, where the configuration names one.
    #[serde(skip_serializing_if = "Option::is_none")]
    migration: Option<OpenMigration>,
}

/// An open migration, as the status reports it.
#[derive(Debug, Serialize)]
struct OpenMigration {
    /// The identifier the configuration names.
    id: String,
    /// The workspace on this host, absent where this host holds none.
    #[serde(skip_serializing_if = "Option::is_none")]
    workspace: Option<String>,
    /// How many sources are neither verified nor dropped, absent where
    /// this host holds no registry.
    #[serde(skip_serializing_if = "Option::is_none")]
    unfinished: Option<usize>,
}

/// The open migration the configuration names, read from this host's
/// workspace where it holds one.
///
/// SATISFIES migration:the-configuration-names-the-open-migration
fn open_migration(
    target: &camino::Utf8Path,
    config: Option<&crate::config::Config>,
) -> Option<OpenMigration> {
    let id = config.and_then(|config| config.migration.clone())?;
    let workspace = crate::migrate::open_workspace(target).ok().flatten();
    let unfinished = workspace
        .as_ref()
        .filter(|workspace| workspace.join(crate::migrate::REGISTRY_FILE).is_file())
        .and_then(|workspace| crate::migrate::registry::load(workspace).ok())
        .map(|registry| {
            registry
                .sources
                .iter()
                .filter(|source| !source.status.finished())
                .count()
        });
    Some(OpenMigration {
        id,
        workspace: workspace.map(|workspace| workspace.to_string()),
        unfinished,
    })
}

/// The line a human report carries for an open migration.
fn render_migration(out: Output, migration: Option<&OpenMigration>) {
    if let Some(migration) = migration {
        out.result_line(format!(
            "migration {} is open; rk migrate status reads it",
            migration.id
        ));
    }
}

fn report_absent(
    out: Output,
    args: &StatusArgs,
    config: Option<&crate::config::Config>,
    git_work_tree: bool,
) -> Result<(), RkError> {
    let migration = open_migration(&args.target, config);
    let classification = match assess::standing(&args.target, config)? {
        assess::Standing::Migrating => Classification::Migration,
        assess::Standing::Unrecorded(class) => unrecorded(class),
    };
    let legacy = legacy_state();
    out.result_line(format!("config: {}", config_state(config, None).state));
    out.result_line(format!("no landing at {}", args.target));
    out.result_line(format!("classification: {}", classification.as_str()));
    render_migration(out, migration.as_ref());
    render_context(out, git_work_tree, &legacy);
    out.next(&[
        format!(
            "rk profile --target {} reports what a landing would select",
            args.target
        ),
        format!("rk init --target {} lands the workflow", args.target),
        format!(
            "rk adopt --target {} records a landing made before the receipt existed",
            args.target
        ),
        format!(
            "rk stage --target {} stages this binary's candidate; the rk-setup skill carries the best-effort migration",
            args.target
        ),
    ]);
    out.emit(&Report {
        schema: SCHEMA,
        landed: false,
        classification: Some(classification),
        git_work_tree,
        config: config_state(config, None),
        profile: None,
        git: None,
        capabilities: None,
        selection: None,
        rk_version: None,
        binary_version: None,
        alignment: None,
        drift: None,
        missing: None,
        stale_pins: None,
        sentinels: None,
        sentinel_locations: None,
        record_drift: None,
        invariant_failures: None,
        warnings: None,
        setup_proof: None,
        pending: None,
        accepted_drift: None,
        stale_accepted_drift: None,
        violations: args.check.then(|| vec!["no landing".to_owned()]),
        legacy_state: legacy,
        migration,
    })?;
    if args.check {
        return Err(RkError::check_failed(
            Diagnostic::new(
                Reason::StateDrift,
                format!("no landing at {}, and --check requires one", args.target),
            )
            .expected("a target carrying .release-kit/manifest.json")
            .action("rk init lands the workflow; rk adopt records an existing landing; rk stage and the rk-setup skill carry the migration"),
        ));
    }
    Ok(())
}

/// A rendered file under its accepted-drift entry.
#[derive(Debug, Clone, Serialize)]
struct AcceptedNote {
    /// The destination.
    destination: String,
    /// Why the project deviates.
    reason: String,
}

/// What one pass over the record and the disk observed.
struct Observed {
    drift_rendered: Vec<String>,
    /// The current digest of each drifted rendered file, which the
    /// remediation prints so an operator can accept it.
    drift_digests: std::collections::BTreeMap<String, String>,
    /// The reason of each drifted rendered file edited past its accepted
    /// bytes, which the violation names.
    drift_reasons: std::collections::BTreeMap<String, String>,
    /// Rendered files whose bytes match their accepted-drift entry.
    drift_accepted: Vec<AcceptedNote>,
    /// Entries whose file matches the receipt again.
    accepted_stale: Vec<String>,
    drift_seeded: Vec<String>,
    /// Recorded block destinations whose recorded digest the record's own
    /// parameters do not reproduce: the record was edited, not the file.
    parameter_drift: Vec<String>,
    /// Set differences between what the recorded parameters project —
    /// the withhold judgment applied — and the destinations the record
    /// names: a record whose parameters and file list disagree, whichever
    /// of the two was edited or outgrown.
    record_drift: Vec<String>,
    missing: Vec<String>,
    stale: Vec<StalePin>,
    sentinels: Vec<(String, usize, String)>,
    invariants: Vec<InvariantFailure>,
    /// Reportable conditions that are not violations.
    warnings: Vec<Warning>,
    setup_proof: Option<SetupProof>,
    /// Recorded intents this target cannot honour, counted in
    /// `record_drift` and kept separately because a plain upgrade cannot
    /// repair them: it re-reads the same recorded answer and refuses. An
    /// unavailable optional capability is not one of these; it is reported
    /// in `selection` and omitted, and an upgrade runs over it unharmed.
    incompatible: Vec<String>,
    /// The destinations an upgrade would change, or `None` where this
    /// binary carries no projection for the recorded pair and so cannot
    /// say.
    pending: Option<Vec<String>>,
    /// Every capability the catalog answers for the recorded values.
    selection: Option<Vec<CapabilityNote>>,
}

/// Report the target's landing.
///
/// # Errors
///
/// Returns [`RkError::Missing`] for a target that is not a directory, the
/// record's own failure taxonomy for an unreadable or unknown record, and
/// [`RkError::CheckFailed`] under `--check` when the report holds a
/// violation.
#[allow(
    clippy::too_many_lines,
    reason = "one pass reads the target, judges it, and emits the one report every reader takes"
)]
pub fn run(args: &StatusArgs) -> Result<(), RkError> {
    let out = Output::new(args.json);
    if !args.target.is_dir() {
        return Err(RkError::missing(
            Diagnostic::new(
                Reason::TargetNotFound,
                format!("target {} is not a directory", args.target),
            )
            .expected("an existing repository to report on"),
        ));
    }
    let config = crate::config::load(args.target.as_std_path())?;
    let git_work_tree = assess::git_work_tree(&args.target)?;
    let Some(manifest) = manifest::load(&args.target)? else {
        return report_absent(out, args, config.as_ref(), git_work_tree);
    };

    let migration = open_migration(&args.target, config.as_ref());
    let accepted = config
        .as_ref()
        .map(|config| config.landing.accepted_drift.clone())
        .unwrap_or_default();
    let stated = Stated::of(config.as_ref(), &manifest);
    let config = config_state(config.as_ref(), Some(&manifest));
    out.result_line(format!("config: {}", config.state));
    for key in &config.pending {
        out.result_line(format!(
            "config pending: {key}; rk upgrade --apply takes it up"
        ));
    }
    let mut observed = observe(args, &manifest, &stated)?;
    accept(&mut observed, &manifest, &accepted)?;
    observed.setup_proof = setup_proof_of(&args.target, &manifest)?;
    let alignment = manifest::alignment(&manifest.rk_version, env!("CARGO_PKG_VERSION"));
    render_human(out, args, &manifest, alignment, &observed);

    let violations = violations_of(&observed);
    // A record newer than this binary is no state it can judge, an open
    // migration included; below that, the open migration outranks the
    // record until it closes.
    let classification = if migration.is_some() && alignment != Alignment::TargetNewer {
        Some(Classification::Migration)
    } else {
        recorded(alignment, violations.is_empty())
    };
    out.result_line(format!(
        "classification: {}",
        classification.map_or(
            "none: the record is newer than this binary",
            Classification::as_str
        )
    ));
    render_migration(out, migration.as_ref());
    let legacy = legacy_state();
    render_context(out, git_work_tree, &legacy);
    out.emit(&Report {
        schema: SCHEMA,
        landed: true,
        classification,
        git_work_tree,
        config,
        profile: Some(manifest.profile.clone()),
        git: Some(manifest.git.clone()),
        capabilities: Some(manifest.capabilities.clone()),
        selection: observed.selection.clone(),
        rk_version: Some(manifest.rk_version),
        binary_version: Some(env!("CARGO_PKG_VERSION")),
        alignment: Some(alignment),
        drift: Some(Drift {
            rendered: observed.drift_rendered.len() + observed.parameter_drift.len(),
            seeded: observed.drift_seeded.len(),
        }),
        record_drift: Some(observed.record_drift.len()),
        missing: Some(observed.missing.clone()),
        stale_pins: Some(observed.stale),
        sentinels: Some(observed.sentinels.len()),
        sentinel_locations: Some(
            observed
                .sentinels
                .iter()
                .map(|(file, line, text)| SentinelAt {
                    file: file.clone(),
                    line: *line,
                    text: text.clone(),
                })
                .collect(),
        ),
        invariant_failures: Some(observed.invariants),
        warnings: Some(observed.warnings),
        setup_proof: observed.setup_proof.clone(),
        pending: observed.pending.as_ref().map(Vec::len),
        accepted_drift: Some(observed.drift_accepted.clone()),
        stale_accepted_drift: Some(observed.accepted_stale.clone()),
        violations: args.check.then(|| violations.clone()),
        legacy_state: legacy,
        migration,
    })?;

    if args.check && !violations.is_empty() {
        return Err(RkError::check_failed(
            Diagnostic::new(
                Reason::StateDrift,
                format!(
                    "the landing is not clean: {} violation{}",
                    violations.len(),
                    if violations.len() == 1 { "" } else { "s" }
                ),
            )
            .expected(
                "no rendered drift, no missing recorded file, no unresolved sentinel, no invariant failure",
            ),
        ));
    }
    Ok(())
}

/// The human lines every report carries, landed or not: whether the
/// target is a work tree the method can land in, and each path a 0.4.x
/// release left under the state root.
fn render_context(out: Output, git_work_tree: bool, legacy: &[LegacyPath]) {
    if !git_work_tree {
        out.result_line("not a non-bare Git work tree: the method lands files a work tree commits");
    }
    for entry in legacy {
        out.result_line(format!(
            "LEGACY {} ({}, {})",
            entry.path,
            entry.kind,
            if entry.active { "active" } else { "inactive" }
        ));
    }
}

/// Move each drifted rendered file whose bytes match its accepted-drift
/// entry out of the violations, name the reason of one edited past it,
/// and report an entry whose file matches the receipt again.
///
/// An entry must name a whole-file rendered destination the receipt
/// records; any other refuses as configuration. Accepted drift exempts a
/// file from the drift judgment alone: an invariant failure on it stays.
///
/// SATISFIES accepted-drift:an-accepted-drift-names-its-reason-and-its-bytes
fn accept(
    observed: &mut Observed,
    manifest: &Manifest,
    accepted: &std::collections::BTreeMap<String, crate::config::AcceptedDrift>,
) -> Result<(), RkError> {
    for (destination, entry) in accepted {
        let Some(file) = manifest.file(destination) else {
            return Err(crate::config::invalid(format!(
                "landing.accepted_drift names {destination}, which the receipt does not record"
            )));
        };
        if file.kind != Kind::Rendered || file.placement != manifest::Placement::Whole {
            return Err(crate::config::invalid(format!(
                "landing.accepted_drift names {destination}, which is not a whole rendered file: only such a file has bytes release-kit owns whole"
            )));
        }
        if !observed.drift_rendered.contains(destination) {
            if !observed.missing.contains(destination) {
                observed.accepted_stale.push(destination.clone());
            }
            continue;
        }
        if observed.drift_digests.get(destination) == Some(&entry.sha256) {
            observed.drift_rendered.retain(|path| path != destination);
            observed.drift_accepted.push(AcceptedNote {
                destination: destination.clone(),
                reason: entry.reason.clone(),
            });
        } else {
            observed
                .drift_reasons
                .insert(destination.clone(), entry.reason.clone());
        }
    }
    Ok(())
}

/// The check-mode violation lines: rendered drift, missing recorded
/// files, unresolved sentinels, and invariant failures — the closed set
/// `landing:status-judges-only-under-check` names.
fn violations_of(observed: &Observed) -> Vec<String> {
    observed
        .drift_rendered
        .iter()
        .map(|path| {
            let digest = observed.drift_digests.get(path).map_or("", String::as_str);
            observed.drift_reasons.get(path).map_or_else(
                || format!("rendered drift: {path}; its sha256 is {digest}"),
                |reason| {
                    format!(
                        "rendered drift: {path}, edited past its accepted drift ({reason}); its sha256 is now {digest}"
                    )
                },
            )
        })
        .chain(
            observed
                .parameter_drift
                .iter()
                .map(|path| format!("parameter drift: {path}")),
        )
        .chain(
            observed
                .record_drift
                .iter()
                .map(|reason| format!("record drift: {reason}")),
        )
        .chain(
            observed
                .missing
                .iter()
                .map(|path| format!("missing: {path}")),
        )
        .chain(
            observed
                .sentinels
                .iter()
                .map(|(path, line, _)| format!("sentinel: {path}:{line}")),
        )
        .chain(
            observed
                .invariants
                .iter()
                .map(|failure| format!("invariant: {}: {}", failure.destination, failure.code)),
        )
        .chain(
            observed
                .setup_proof
                .as_ref()
                .and_then(SetupProof::failure)
                .map(|failure| format!("setup proof: {}", failure.code)),
        )
        .collect()
}

/// The answers the target states now, for the judgments: a committed
/// answer the landing verbs have yet to take up outranks the record.
struct Stated {
    /// Where the crate publishes.
    registry: Option<RegistryAnswer>,
    /// The check context of the gate.
    required_check: String,
}

impl Stated {
    fn of(config: Option<&crate::config::Config>, manifest: &Manifest) -> Self {
        Self {
            registry: config
                .and_then(|config| config.profile.release.registry)
                .or(manifest.profile.release.registry),
            // The landing writes the check back as a class P answer, so a
            // configuration that exists states it, an empty one included.
            required_check: config.map_or_else(
                || manifest.parameters.required_check.clone(),
                |config| config.setup.required_check.clone(),
            ),
        }
    }
}

/// One pass over the record and the disk: drift, missing files, stale
/// pins, and sentinels.
#[allow(
    clippy::too_many_lines,
    reason = "one pass over the record and the disk answers every comparison the report states"
)]
fn observe(args: &StatusArgs, manifest: &Manifest, stated: &Stated) -> Result<Observed, RkError> {
    let mut observed = Observed {
        drift_rendered: Vec::new(),
        drift_digests: std::collections::BTreeMap::new(),
        drift_reasons: std::collections::BTreeMap::new(),
        drift_accepted: Vec::new(),
        accepted_stale: Vec::new(),
        drift_seeded: Vec::new(),
        parameter_drift: Vec::new(),
        record_drift: Vec::new(),
        missing: Vec::new(),
        stale: Vec::new(),
        sentinels: Vec::new(),
        invariants: Vec::new(),
        warnings: Vec::new(),
        setup_proof: None,
        incompatible: Vec::new(),
        pending: None,
        selection: None,
    };
    // One projection serves every reader below, because each asks what
    // this binary makes of the recorded parameters at this target. A pair
    // this binary does not carry cannot be projected at all: under a
    // receipt this binary wrote that is a defect and still fails, and
    // under a landing from another rk it is a fact to report.
    let aligned =
        manifest::alignment(&manifest.rk_version, env!("CARGO_PKG_VERSION")) == Alignment::Aligned;
    let projected = match project(args, manifest) {
        Ok(projection) => Some(projection),
        Err(err) if aligned => return Err(err),
        Err(_) => None,
    };
    for file in &manifest.files {
        let Some(bytes) = landing::read_recorded(&args.target, &file.destination)? else {
            observed.missing.push(file.destination.clone());
            continue;
        };
        if Digest::of(&bytes) != file.sha256 {
            match file.kind {
                Kind::Rendered => {
                    observed.drift_rendered.push(file.destination.clone());
                    observed
                        .drift_digests
                        .insert(file.destination.clone(), Digest::of(&bytes).to_string());
                }
                Kind::Seeded => observed.drift_seeded.push(file.destination.clone()),
                Kind::State => {}
            }
        }
        observed.invariants.extend(invariants::failures(
            manifest.profile.release.driver.as_deref().unwrap_or(""),
            manifest.profile.forge.as_deref().unwrap_or(""),
            &file.destination,
            &bytes,
            stated.registry,
        ));
        let text = String::from_utf8_lossy(&bytes);
        for (idx, line) in text.lines().enumerate() {
            if line.contains(embedded::SENTINEL) {
                observed.sentinels.push((
                    file.destination.clone(),
                    idx + 1,
                    line.trim().to_owned(),
                ));
            }
        }
        // A marked document's markers must be well formed even when its
        // first block matches the receipt: a duplicate hook block still
        // executes, so an ill-formed document reads as rendered drift,
        // never as clean.
        let defective = projected.as_ref().is_some_and(|projection| {
            projection
                .collisions
                .iter()
                .any(|collision| collision.destination == file.destination)
        });
        if defective && !observed.drift_rendered.contains(&file.destination) {
            observed.drift_rendered.push(file.destination.clone());
        }
    }
    // The cross-file step: a landed file can generate the artifact the
    // forge actually executes, and the seeds ship no copy of it, so no
    // recorded digest sees the two disagree. The pair's own rule reads
    // both off the target's disk.
    observed.invariants.extend(invariants::target_failures(
        manifest.profile.release.driver.as_deref().unwrap_or(""),
        manifest.profile.forge.as_deref().unwrap_or(""),
        &args.target,
    ));
    // The gate builds every dist target before a merge, or the build
    // fails only after the tag exists.
    if manifest.profile.release.driver.as_deref() == Some("rust")
        && manifest.profile.forge.as_deref() == Some("github")
    {
        let dev_run = manifest
            .parameters
            .dev_environment
            .as_ref()
            .map_or("", |answer| answer.run.as_str());
        let gate = invariants::dist_targets_built(&args.target, &stated.required_check, dev_run);
        observed.invariants.extend(gate.failures);
        observed.warnings.extend(
            gate.limitations
                .into_iter()
                .map(|(code, reason)| Warning { code, reason }),
        );
    }
    observed.selection = projected.as_ref().map(|projection| {
        projection
            .capabilities
            .iter()
            .map(|selection| CapabilityNote::of(selection, projection))
            .collect()
    });
    if let Some(reason) = projected
        .as_ref()
        .and_then(|projection| projection.licence_refusal.clone())
    {
        observed.warnings.push(Warning {
            code: CODE_SCANNING_LICENCE,
            reason,
        });
    }
    // A receipt naming a release intent nothing can honour is judged at
    // every alignment rather than only where this binary wrote the record.
    // An unavailable optional capability is not one of these: it reports
    // through `selection` and lands nothing, and no verb refuses on it.
    if let Some(projection) = projected.as_ref() {
        observed.incompatible.clone_from(&projection.record_defects);
        observed
            .record_drift
            .extend(projection.record_defects.iter().cloned());
    }
    if aligned && let Some(projection) = projected.as_ref() {
        observe_parameter_drift(manifest, projection, &mut observed);
        observe_record_set(manifest, projection, &mut observed.record_drift);
    }
    // What an upgrade would change, which is the only honest ground for
    // telling an operator to run one. The recorded version says who wrote
    // the receipt, and two releases apart can carry identical bytes for
    // this pair, so it answers a different question and prompts nothing.
    observed.pending = projected
        .as_ref()
        .map(|projection| pending_of(manifest, &projection.candidates));
    // Stale means behind, not merely different: a landing from a newer rk
    // can carry pins ahead of this binary's registry, and that is the
    // alignment line's story, not a freshness complaint.
    for (tool, landed) in &manifest.pins {
        if let Some(available) = registry::version_of(tool)
            && manifest::version_is_newer(&available, landed)
        {
            observed.stale.push(StalePin {
                tool: tool.clone(),
                landed: landed.clone(),
                available,
            });
        }
    }
    Ok(observed)
}

/// The receipt-consistency step over every rendered destination.
///
/// Recorded digests alone cannot see a receipt edited only at its
/// parameters, since every file still matches its own record, so every
/// rendered candidate, whole file or region, as this projection renders
/// it from the receipt's own parameters, is compared against the digest
/// the receipt stores for it. Called only where this binary wrote the
/// receipt: an older landing's files legitimately differ from this
/// projection, which is the alignment line's story and the upgrade's job,
/// not parameter drift. A destination already reported as rendered drift
/// is the file's own story, not the receipt's, and is skipped too.
fn observe_parameter_drift(manifest: &Manifest, projection: &Projection, observed: &mut Observed) {
    for candidate in &projection.candidates {
        if candidate.kind != Kind::Rendered {
            continue;
        }
        let Some(record) = manifest.file(&candidate.destination) else {
            continue;
        };
        if observed.drift_rendered.contains(&candidate.destination)
            || observed.missing.contains(&candidate.destination)
        {
            continue;
        }
        if Digest::of(recorded_form(candidate)) != record.sha256 {
            observed
                .parameter_drift
                .push(format!("{} (parameters)", candidate.destination));
        }
    }
}

/// What this binary projects under the receipt's own parameters at this
/// target, with the same withhold judgment a landing applies, so the
/// comparison stands against what an upgrade would actually offer.
fn project(args: &StatusArgs, manifest: &Manifest) -> Result<Projection, RkError> {
    let evidence = TargetEvidence::gather(&args.target, Some(manifest))?;
    Projection::compute(&ProjectionInput {
        params: landing::Params::from_record(manifest),
        evidence,
    })
}

/// The bytes the receipt digests for a candidate: the whole file, or the
/// marked region alone.
fn recorded_form(candidate: &Candidate) -> &[u8] {
    candidate.region.as_deref().unwrap_or(&candidate.bytes)
}

/// The destinations an upgrade would change, read off the record alone.
///
/// A destination the projection adds or drops changes the record either
/// way, and a `rendered` one whose candidate digest differs from the
/// recorded digest is rewritten. A `seeded` or `state` destination the
/// record already names is never rewritten, so only a change of kind
/// counts for it. Disk drift is a separate story, told by its own lines:
/// an edited file is the target's doing, not a newer binary's.
fn pending_of(manifest: &Manifest, projected: &[Candidate]) -> Vec<String> {
    let mut pending = Vec::new();
    for entry in projected {
        let changed = manifest.file(&entry.destination).is_none_or(|record| {
            record.kind != entry.kind
                || (entry.kind == Kind::Rendered
                    && record.sha256 != Digest::of(recorded_form(entry)))
        });
        if changed {
            pending.push(entry.destination.clone());
        }
    }
    for file in &manifest.files {
        if !projected
            .iter()
            .any(|entry| entry.destination == file.destination)
        {
            pending.push(file.destination.clone());
        }
    }
    pending.sort();
    pending.dedup();
    pending
}

/// The receipt-set consistency step: the recorded digests judge each
/// named file, and the region re-render judges the region records, but
/// neither can see a receipt whose parameters and file list disagree, a
/// nix flag flipped in the receipt with no file landed, or a
/// once-withheld capability whose target grew into the supported shape.
/// So the projection is computed from the receipt's own parameters, the
/// same withhold judgment applied, and the two destination sets compared
/// both ways. A destination the projection withholds at this target is
/// absent because withheld, which is not drift. Called only where this
/// binary wrote the receipt: an older landing's set legitimately differs,
/// and that is the alignment line's story.
fn observe_record_set(
    manifest: &Manifest,
    projection: &Projection,
    record_drift: &mut Vec<String>,
) {
    for entry in &projection.candidates {
        if manifest.file(&entry.destination).is_none() {
            record_drift.push(format!(
                "the recorded parameters project {}, which the receipt does not name",
                entry.destination
            ));
        }
    }
    for file in &manifest.files {
        let produced = projection
            .candidates
            .iter()
            .any(|entry| entry.destination == file.destination)
            || projection
                .omissions
                .iter()
                .any(|omission| omission.destination == file.destination);
        if !produced {
            record_drift.push(format!(
                "the receipt names {}, which the recorded parameters do not project",
                file.destination
            ));
        }
    }
}

/// The human lines, identical with and without `--check`.
#[allow(
    clippy::too_many_lines,
    reason = "one pass prints every reportable condition in the order the report states them"
)]
fn render_human(
    out: Output,
    args: &StatusArgs,
    manifest: &Manifest,
    alignment: Alignment,
    observed: &Observed,
) {
    out.result_line(format!(
        "release-kit {} at {}: {}",
        manifest.rk_version,
        args.target,
        crate::commands::profile::describe(
            &manifest.profile,
            &manifest.git,
            &manifest.capabilities,
            &manifest.parameters.repo
        )
    ));
    // Every capability the record does not select is information, never
    // a violation: a product nobody asked for, or one this target's
    // dimensions cannot take.
    for note in observed.selection.iter().flatten() {
        if note.status != "selected" {
            out.result_line(format!(
                "capability {}: {}{}",
                note.id,
                note.status,
                note.reason
                    .as_deref()
                    .map_or_else(String::new, |reason| format!(" ({reason})"))
            ));
        }
    }
    if alignment == Alignment::TargetNewer {
        out.result_line(format!(
            "binary {} is older than this landing; install the matching rk",
            env!("CARGO_PKG_VERSION")
        ));
    }
    match observed.pending.as_deref() {
        None => out.result_line(format!(
            "this binary carries no projection for the recorded {} release on {}, so what an upgrade would change is unknown",
            manifest
                .profile
                .release
                .driver
                .as_deref()
                .unwrap_or("release-less"),
            manifest.profile.forge.as_deref().unwrap_or("no forge")
        )),
        Some(paths) => {
            for path in paths {
                out.result_line(format!("PENDING {path} (this binary would change it)"));
            }
        }
    }
    for path in &observed.drift_rendered {
        let digest = observed.drift_digests.get(path).map_or("", String::as_str);
        out.result_line(observed.drift_reasons.get(path).map_or_else(
            || {
                format!(
                    "DRIFT {path} (rendered, release-kit-owned): sha256 {digest}; a deliberate edit is accepted under landing.accepted_drift with its reason and this digest"
                )
            },
            |reason| {
                format!(
                    "DRIFT {path} (rendered, edited past its accepted drift: {reason}; sha256 now {digest})"
                )
            },
        ));
    }
    for note in &observed.drift_accepted {
        out.result_line(format!(
            "ACCEPTED {} (rendered, accepted drift: {})",
            note.destination, note.reason
        ));
    }
    for path in &observed.accepted_stale {
        out.result_line(format!(
            "STALE landing.accepted_drift entry for {path}: the file matches the receipt, so the entry can go"
        ));
    }
    for path in &observed.parameter_drift {
        out.result_line(format!(
            "DRIFT {path}: the recorded parameters do not render the recorded bytes"
        ));
    }
    for reason in &observed.record_drift {
        out.result_line(format!("DRIFT record: {reason}"));
    }
    for path in &observed.drift_seeded {
        out.result_line(format!("DRIFT {path} (seeded, target-owned)"));
    }
    for path in &observed.missing {
        out.result_line(format!("MISSING {path}"));
    }
    for pin in &observed.stale {
        out.result_line(format!(
            "STALE {} {} landed, {} in this binary",
            pin.tool, pin.landed, pin.available
        ));
    }
    for (path, line, text) in &observed.sentinels {
        out.result_line(format!("SENTINEL {path}:{line}: {text}"));
    }
    for failure in &observed.invariants {
        out.result_line(format!(
            "INVARIANT {} ({}): {}",
            failure.destination, failure.code, failure.reason
        ));
    }
    for warning in &observed.warnings {
        out.result_line(format!("WARNING ({}): {}", warning.code, warning.reason));
    }
    let proof_failure = observed.setup_proof.as_ref().and_then(SetupProof::failure);
    if let Some(proof) = &observed.setup_proof {
        out.result_line(format!("setup proof: {}", proof.state));
    }
    if let Some(failure) = &proof_failure {
        out.result_line(format!(
            "SETUP-PROOF ({}): {}",
            failure.code, failure.reason
        ));
    }
    let mut next = Vec::new();
    for failure in observed.invariants.iter().chain(&proof_failure) {
        next.push(format!("{}: {}", failure.destination, failure.remediation));
    }
    // The incompatible ones first, and with the override: a plain upgrade
    // reads the same recorded intent and refuses, so advertising it alone
    // would send the operator into a loop.
    if !observed.incompatible.is_empty() {
        next.push(format!(
            "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",
            args.target
        ));
    }
    if observed.record_drift.len() > observed.incompatible.len() {
        next.push(format!(
            "rk upgrade --target {} rewrites the receipt from its parameters",
            args.target
        ));
    }
    if observed
        .pending
        .as_deref()
        .is_none_or(|paths| !paths.is_empty())
    {
        next.push(format!(
            "rk upgrade --target {} takes this landing to {}",
            args.target,
            env!("CARGO_PKG_VERSION")
        ));
    }
    next.push(format!(
        "rk status --check --target {} exits 1 on a violation",
        args.target
    ));
    if manifest.profile.release.mode != ReleaseMode::Automatic {
        next.retain(|line| !line.contains("rk method operate"));
    }
    out.next(&next);
}

#[cfg(test)]
mod tests {
    use super::{
        Classification, Drift, InvariantFailure, LegacyPath, OpenMigration, Report, SentinelAt,
        StalePin,
    };
    use crate::assess::{self, Facts, OwnLanding, Unrecorded};
    use crate::landing::CheckoutMode;
    use crate::landing::Integration;
    use crate::landing::manifest::Alignment;
    use crate::profile::{
        CapabilityRequests, GitWorkflow, ProfileSnapshot, ReleaseIntent, ReleaseMode,
    };

    /// Accepted drift exempts a file from the drift judgment alone: an
    /// invariant failure on the same file stays a violation.
    #[test]
    fn accepted_drift_does_not_silence_an_invariant() {
        let destination = ".gitlab-ci.yml".to_owned();
        let digest = "a".repeat(64);
        let mut observed = super::Observed {
            drift_rendered: vec![destination.clone()],
            drift_digests: std::iter::once((destination.clone(), digest.clone())).collect(),
            drift_reasons: std::collections::BTreeMap::new(),
            drift_accepted: Vec::new(),
            accepted_stale: Vec::new(),
            drift_seeded: Vec::new(),
            parameter_drift: Vec::new(),
            record_drift: Vec::new(),
            missing: Vec::new(),
            stale: Vec::new(),
            sentinels: Vec::new(),
            invariants: vec![crate::landing::invariants::InvariantFailure {
                code: "an-invariant",
                destination: destination.clone(),
                reason: "the accepted bytes break it".to_owned(),
                remediation: "restore it",
            }],
            warnings: Vec::new(),
            setup_proof: None,
            incompatible: Vec::new(),
            pending: None,
            selection: None,
        };
        let manifest: crate::landing::manifest::Manifest = serde_json::from_str(&format!(
            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":{{}}}}"#,
            crate::digest::Digest::of(b"candidate")
        ))
        .expect("the record parses");
        let accepted = std::iter::once((
            destination,
            crate::config::AcceptedDrift {
                reason: "deliberate".to_owned(),
                sha256: digest,
            },
        ))
        .collect();
        super::accept(&mut observed, &manifest, &accepted).expect("accepts");
        assert!(observed.drift_rendered.is_empty());
        let violations = super::violations_of(&observed);
        assert!(
            violations.iter().any(|line| line.contains("an-invariant")),
            "{violations:?}"
        );
    }

    /// The complete `rk.status/15` shape, held by snapshot in both the
    /// landed and absent forms.
    #[test]
    #[allow(
        clippy::too_many_lines,
        reason = "the snapshot states every field of both forms in one place"
    )]
    fn the_status_report_schema_snapshot_holds() {
        let landed = Report {
            schema: super::SCHEMA,
            landed: true,
            classification: Some(Classification::Upgrade),
            git_work_tree: true,
            config: super::ConfigState {
                state: "pending",
                pending: vec!["profile.release.style".into()],
            },
            profile: Some(ProfileSnapshot {
                technologies: vec!["rust".into()],
                forge: Some("github".into()),
                release: ReleaseIntent {
                    mode: ReleaseMode::Automatic,
                    driver: Some("rust".into()),
                    style: Some(crate::landing::Style::Trunk),
                    line_prefix: Some("release/".into()),
                    registry: None,
                    build: None,
                },
            }),
            git: Some(GitWorkflow {
                trunk: "master".into(),
                checkout_mode: CheckoutMode::LinkedWorktree,
                integration: Integration::Local,
                merge_form: crate::landing::MergeForm::Squash,
            }),
            capabilities: Some(CapabilityRequests {
                nix_packaging: true,
                reporting_policy: true,
                scorecard: false,
                code_scanning: Some(crate::landing::Provider::Semgrep),
                workflow_guards: Some(false),
            }),
            selection: Some(vec![]),
            rk_version: Some("0.1.0".into()),
            binary_version: Some("0.2.0"),
            alignment: Some(crate::landing::manifest::Alignment::BinaryNewer),
            drift: Some(Drift {
                rendered: 0,
                seeded: 1,
            }),
            missing: Some(vec![]),
            stale_pins: Some(vec![StalePin {
                tool: "release-plz".into(),
                landed: "0.3.160".into(),
                available: "0.3.170".into(),
            }]),
            sentinels: Some(1),
            sentinel_locations: Some(vec![SentinelAt {
                file: "release-plz.toml".into(),
                line: 18,
                text: "# TODO(release-kit): keep false for a binary-only crate".into(),
            }]),
            record_drift: Some(0),
            invariant_failures: Some(vec![InvariantFailure {
                code: "attestations-disabled",
                destination: "dist-workspace.toml".into(),
                reason: "github-attestations is not effectively true".into(),
                remediation: "set github-attestations = true in [dist]",
            }]),
            warnings: Some(vec![super::Warning {
                code: super::CODE_SCANNING_LICENCE,
                reason: "the target's license, LicenseRef-proprietary, does not state a codebase this release recognizes as open source".into(),
            }]),
            setup_proof: Some(super::SetupProof {
                state: "stale",
                changed: vec!["target.required_check".into()],
                reason: None,
                detail: None,
            }),
            pending: Some(2),
            accepted_drift: Some(vec![super::AcceptedNote {
                destination: ".gitlab-ci.yml".into(),
                reason: "the image carries a tool".into(),
            }]),
            stale_accepted_drift: Some(vec![]),
            violations: None,
            legacy_state: vec![LegacyPath {
                path: "/state/release-kit/plans/0123456789abcdef".into(),
                kind: "plan",
                active: true,
            }],
            migration: Some(OpenMigration {
                id: "20261009T140205Z".into(),
                workspace: Some(
                    "/state/release-kit/migrations/widget-0123456789ab/20261009T140205Z".into(),
                ),
                unfinished: Some(2),
            }),
        };
        assert_eq!(
            serde_json::to_string(&landed).expect("a report serializes"),
            r##"{"schema":"rk.status/15","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,"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}}"##
        );
        let absent = Report {
            landed: false,
            classification: Some(Classification::Setup),
            git_work_tree: false,
            config: super::ConfigState {
                state: "absent",
                pending: vec![],
            },
            profile: None,
            git: None,
            capabilities: None,
            selection: None,
            rk_version: None,
            binary_version: None,
            alignment: None,
            drift: None,
            missing: None,
            stale_pins: None,
            sentinels: None,
            sentinel_locations: None,
            record_drift: None,
            invariant_failures: None,
            warnings: None,
            setup_proof: None,
            pending: None,
            accepted_drift: None,
            stale_accepted_drift: None,
            violations: None,
            legacy_state: vec![],
            migration: None,
            ..landed
        };
        assert_eq!(
            serde_json::to_string(&absent).expect("a report serializes"),
            r#"{"schema":"rk.status/15","landed":false,"classification":"setup","git_work_tree":false,"config":{"state":"absent","pending":[]},"legacy_state":[]}"#,
            "an absent landing reports the fields a caller can branch on"
        );
        let newer = Report {
            classification: None,
            ..absent
        };
        assert!(
            serde_json::to_string(&newer)
                .expect("a report serializes")
                .contains(r#""classification":null"#),
            "no classification is stated as null, never omitted"
        );
    }

    fn facts() -> Facts {
        Facts {
            technologies: Vec::new(),
            forge: None,
            repo: None,
            release_markers: Vec::new(),
            collisions: Vec::new(),
            git: true,
            tags: 0,
            long_lived_branches: Vec::new(),
        }
    }

    /// Each value the gate reads has one rule that earns it: the
    /// assessment's three for a target with no record, the adoption
    /// detector before them, and the alignment and the check for a
    /// recorded one.
    #[test]
    fn every_classification_has_its_rule() {
        let none = OwnLanding::default();
        let classify = |facts: &Facts, own: &OwnLanding| {
            super::unrecorded(assess::classify_unrecorded(facts, own))
        };
        assert_eq!(classify(&facts(), &none), Classification::Setup);
        let marked = Facts {
            release_markers: vec![".goreleaser.yaml".into()],
            ..facts()
        };
        assert_eq!(classify(&marked, &none), Classification::Migration);
        let tagged = Facts { tags: 3, ..facts() };
        assert_eq!(classify(&tagged, &none), Classification::NeedsDecision);
        // release-kit's own regions read as collisions to the assessment,
        // and the detector outranks them.
        let own = OwnLanding {
            regions: vec!["AGENTS.md".into()],
            rendered: Vec::new(),
        };
        let colliding = Facts {
            collisions: vec!["AGENTS.md".into()],
            release_markers: vec!["CHANGELOG.md".into()],
            ..facts()
        };
        assert_eq!(classify(&colliding, &own), Classification::Adopt);
        assert_eq!(
            assess::classify_unrecorded(&colliding, &own),
            Unrecorded::Adopt
        );
        assert_eq!(
            super::recorded(Alignment::BinaryNewer, false),
            Some(Classification::Upgrade)
        );
        assert_eq!(
            super::recorded(Alignment::Aligned, false),
            Some(Classification::Drift)
        );
        assert_eq!(
            super::recorded(Alignment::Aligned, true),
            Some(Classification::Current)
        );
        assert_eq!(super::recorded(Alignment::TargetNewer, true), None);
        for (class, word) in [
            (Classification::Setup, "setup"),
            (Classification::Migration, "migration"),
            (Classification::NeedsDecision, "needs-decision"),
            (Classification::Adopt, "adopt"),
            (Classification::Upgrade, "upgrade"),
            (Classification::Drift, "drift"),
            (Classification::Current, "current"),
        ] {
            assert_eq!(class.as_str(), word);
            assert_eq!(
                serde_json::to_string(&class).expect("serializes"),
                format!("\"{word}\"")
            );
        }
    }
}