release-kit 0.8.7

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
//! The resolved target configuration.
//!
//! The project profile, the Git workflow, and the capability requests,
//! resolved by one precedence from an invocation's flags, the committed
//! configuration, a compatible record, the target's observation, and the
//! compiled defaults.
//!
//! Three representations live here and stay apart. The declared
//! configuration is `crate::config::Config`, exactly as authored. The
//! resolved configuration is [`Resolved`]: every effective value beside the
//! runtime [`Source`] that answered it, which `rk profile` reports and
//! nothing serializes. The wire form is [`Params`]: the same values with no
//! source, which the projection consumes, the configuration writes back,
//! and the record carries as [`ProfileSnapshot`], [`GitWorkflow`], and
//! [`CapabilityRequests`].
//!
//! SATISFIES project-profile:every-field-resolves-by-one-precedence
//! SATISFIES project-profile:a-record-is-source-free

pub mod catalog;

use std::collections::BTreeMap;

use camino::Utf8Path;
use serde::{Deserialize, Serialize};

use crate::diagnostic::{Diagnostic, Reason};
use crate::error::RkError;
use crate::landing::manifest::{self, CheckoutMode, Integration, Provider, Style};

/// The release intent's mode.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum ReleaseMode {
    /// release-kit drives the release: a bot maintains the request, and
    /// the landed automation tags and publishes.
    Automatic,
    /// The target releases through a process release-kit does not drive.
    /// No automation lands, and no bot-operate chapter applies.
    External,
    /// Nothing releases.
    None,
}

impl ReleaseMode {
    /// The flag, wire, and report form.
    #[must_use]
    pub const fn as_str(self) -> &'static str {
        match self {
            Self::Automatic => "automatic",
            Self::External => "external",
            Self::None => "none",
        }
    }

    /// Parse a `--release-mode` flag value.
    ///
    /// # Errors
    ///
    /// Returns [`RkError::Usage`] naming the three values.
    pub fn parse(raw: &str) -> Result<Self, RkError> {
        match raw {
            "automatic" => Ok(Self::Automatic),
            "external" => Ok(Self::External),
            "none" => Ok(Self::None),
            other => Err(RkError::Usage(format!(
                "unknown release mode '{other}'; the modes are: automatic, external, none"
            ))),
        }
    }
}

/// The release intent: the mode and, for an automatic release, its driver,
/// style, and line prefix.
///
/// SATISFIES project-profile:release-intent-has-three-modes
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct ReleaseIntent {
    /// The mode.
    pub mode: ReleaseMode,
    /// The technology that states the version and takes the bot; present
    /// for an automatic release alone.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub driver: Option<String>,
    /// The release style; present for an automatic release alone.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub style: Option<Style>,
    /// The release-line branch prefix; present for an automatic release
    /// alone.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub line_prefix: Option<String>,
}

/// What the project is, on the wire: values alone.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct ProfileSnapshot {
    /// The technologies present, sorted, zero or many.
    pub technologies: Vec<String>,
    /// The forge, where the project has one.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub forge: Option<String>,
    /// The release intent.
    pub release: ReleaseIntent,
}

/// The Git workflow parameters.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct GitWorkflow {
    /// The one permanent branch.
    pub trunk: String,
    /// Where a topic branch opens.
    pub checkout_mode: CheckoutMode,
    /// Which authority moves an implementation onto the trunk. A record
    /// predating the parameter carries no key and reads as `forge`.
    #[serde(default = "crate::landing::manifest::integration_forge")]
    pub integration: Integration,
}

/// The optional products the target requested.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct CapabilityRequests {
    /// The seeded package expression and the seed flake pair.
    #[serde(default)]
    pub nix_packaging: bool,
    /// The landed vulnerability reporting policy.
    #[serde(default)]
    pub reporting_policy: bool,
    /// The `OpenSSF` Scorecard workflow.
    #[serde(default)]
    pub scorecard: bool,
    /// The code scanning workflow, by provider.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub code_scanning: Option<Provider>,
}

/// Where a resolved value came from.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
#[serde(rename_all = "lowercase")]
pub enum Source {
    /// An invocation flag.
    Flag,
    /// The committed configuration.
    Config,
    /// A compatible landing record.
    Record,
    /// The target's observation: its version files and its origin remote.
    Observation,
    /// A compiled default.
    Default,
}

impl Source {
    /// Where this source sits in the one precedence, lowest first.
    ///
    /// The comparison a resolution needs when one field's answer has to be
    /// weighed against another's: a value only contradicts a decision that
    /// its own tier or a lower one made.
    #[must_use]
    pub const fn rank(self) -> u8 {
        match self {
            Self::Flag => 0,
            Self::Config => 1,
            Self::Record => 2,
            Self::Observation => 3,
            Self::Default => 4,
        }
    }

    /// The report form.
    #[must_use]
    pub const fn as_str(self) -> &'static str {
        match self {
            Self::Flag => "flag",
            Self::Config => "config",
            Self::Record => "record",
            Self::Observation => "observation",
            Self::Default => "default",
        }
    }
}

/// What the observation proposes for the release, where nothing else
/// answered it.
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
#[serde(rename_all = "kebab-case", tag = "state")]
pub enum Proposal {
    /// No release-bearing technology: nothing to automate.
    None,
    /// Exactly one release-bearing technology drives the release.
    Automatic {
        /// The driver.
        driver: String,
    },
    /// More than one release-bearing technology, so a flag must name the
    /// driver before an apply.
    Ambiguous {
        /// The candidates, sorted.
        drivers: Vec<String>,
    },
}

/// The complete resolved input to a projection, on the wire.
///
/// The values the configuration writes back, the record carries, and the
/// projection renders from, with no precedence source.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Params {
    profile: ProfileSnapshot,
    git: GitWorkflow,
    capabilities: CapabilityRequests,
    repo: String,
    security_contact: String,
    security_response: String,
    required_check: String,
    required_workflow: String,
}

/// Explicit invocation answers; absence falls through to configuration.
#[derive(Default)]
pub struct Inputs<'a> {
    /// The technologies, replacing the declared list whole; empty is
    /// unsupplied.
    pub technologies: &'a [String],
    /// Forge override.
    pub forge: Option<&'a str>,
    /// Repository override.
    pub repo: Option<&'a str>,
    /// Release mode override.
    pub release_mode: Option<ReleaseMode>,
    /// Release driver override.
    pub release_driver: Option<&'a str>,
    /// Release style override.
    pub style: Option<Style>,
    /// Trunk override.
    pub trunk: Option<&'a str>,
    /// Checkout mode override.
    pub checkout_mode: Option<CheckoutMode>,
    /// Integration mode override.
    pub integration: Option<Integration>,
    /// The check the release gate believes, overriding the configuration.
    pub required_check: Option<&'a str>,
    /// The workflow whose completion wakes the release gate, overriding
    /// the configuration.
    pub required_workflow: Option<&'a str>,
    /// Nix packaging request override.
    pub nix: Option<bool>,
    /// Reporting policy request override.
    pub reporting_policy: Option<bool>,
    /// Scorecard request override.
    pub scorecard: Option<bool>,
    /// Code scanning override: `Some(None)` turns it off, and absence
    /// leaves the configuration and the record to answer.
    pub code_scanning: Option<Option<Provider>>,
}

/// Compatibility policy for a landing candidate.
#[derive(Clone, Copy, PartialEq, Eq)]
pub enum Purpose {
    /// A first landing.
    Init,
    /// A preview may leave the repository unresolved and reports an
    /// ambiguous release proposal rather than refusing it.
    Preview,
    /// An existing record supplies compatibility answers.
    Upgrade,
    /// A pre-record target requires an explicit release style.
    Adopt,
}

/// The resolved target configuration, with the source of every value.
#[derive(Debug, Clone)]
pub struct Resolved {
    /// The values.
    pub params: Params,
    /// The source of each value, keyed by its configuration path.
    pub sources: BTreeMap<&'static str, Source>,
    /// The category names the catalog does not know, preserved.
    pub unknown: Vec<String>,
    /// What the observation proposed for the release, where the mode was
    /// not answered above it.
    pub proposal: Option<Proposal>,
}

/// The canonical form of a category name, or why it is refused.
///
/// Lowercase, matching `[a-z0-9][a-z0-9-]*`. An unknown name is preserved, so the
/// shape is what keeps a record and a configuration readable.
///
/// SATISFIES project-profile:an-unknown-category-is-preserved
///
/// # Errors
/// The refusal text, naming the value and the shape.
pub fn canonical_category(raw: &str) -> Result<String, String> {
    let lowered = raw.trim().to_ascii_lowercase();
    let shaped = lowered
        .chars()
        .next()
        .is_some_and(|c| c.is_ascii_lowercase() || c.is_ascii_digit())
        && lowered
            .chars()
            .all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || c == '-');
    if shaped {
        Ok(lowered)
    } else {
        Err(format!(
            "{raw:?} is not a category name; one is lowercase letters and digits with hyphens inside, as [a-z0-9][a-z0-9-]*"
        ))
    }
}

/// A list of category names canonicalized, refused on a duplicate, and
/// sorted.
///
/// # Errors
/// The refusal text, naming the key.
pub fn canonical_list(key: &str, raw: &[String]) -> Result<Vec<String>, String> {
    let mut out = Vec::with_capacity(raw.len());
    for value in raw {
        let name = canonical_category(value).map_err(|reason| format!("{key}: {reason}"))?;
        if out.contains(&name) {
            return Err(format!("{key} names {name} twice; each technology once"));
        }
        out.push(name);
    }
    out.sort();
    Ok(out)
}

/// Append one POSIX-shell word, leaving the common inert alphabet readable
/// and single-quoting everything that could become syntax on replay.
fn push_shell_word(out: &mut String, value: &str) {
    let inert = !value.is_empty()
        && value.bytes().all(|byte| {
            byte.is_ascii_alphanumeric()
                || matches!(
                    byte,
                    b'_' | b'@' | b'%' | b'+' | b'=' | b':' | b',' | b'.' | b'/' | b'-'
                )
        });
    if inert {
        out.push_str(value);
        return;
    }
    out.push('\'');
    out.push_str(&value.replace('\'', "'\"'\"'"));
    out.push('\'');
}

impl Params {
    /// Reconstruct every projection parameter from the record alone,
    /// including the compatibility defaults applied when it was loaded.
    #[must_use]
    pub fn from_record(record: &manifest::Manifest) -> Self {
        Self {
            profile: record.profile.clone(),
            git: record.git.clone(),
            capabilities: record.capabilities.clone(),
            repo: record.parameters.repo.clone(),
            security_contact: record.parameters.security_contact.clone(),
            security_response: record.parameters.security_response.clone(),
            // A record predating the two answers carries neither, and
            // the compiled default is what such a landing renders now.
            required_check: gate_answer(
                record,
                |(check, _)| check,
                |parameters| &parameters.required_check,
            ),
            required_workflow: gate_answer(
                record,
                |(_, workflow)| workflow,
                |parameters| &parameters.required_workflow,
            ),
        }
    }

    /// Resolve flags, configuration, recorded compatibility inputs or
    /// observation, and finally the compiled defaults. Comparisons use
    /// `from_record` alone.
    ///
    /// # Errors
    /// Refuses unresolved identity, an invalid release state, or a style
    /// an existing target has not answered.
    pub fn resolve(
        target: &Utf8Path,
        flags: &Inputs<'_>,
        config: Option<&crate::config::Config>,
        record: Option<&manifest::Manifest>,
        purpose: Purpose,
    ) -> Result<Self, RkError> {
        resolve(target, flags, config, record, purpose).map(|resolved| resolved.params)
    }

    /// What the project is.
    #[must_use]
    pub const fn profile(&self) -> &ProfileSnapshot {
        &self.profile
    }

    /// The Git workflow parameters.
    #[must_use]
    pub const fn git(&self) -> &GitWorkflow {
        &self.git
    }

    /// The capability requests.
    #[must_use]
    pub const fn capabilities(&self) -> &CapabilityRequests {
        &self.capabilities
    }

    /// The technologies present, sorted.
    #[must_use]
    pub fn technologies(&self) -> &[String] {
        &self.profile.technologies
    }

    /// The forge, where the project has one.
    #[must_use]
    pub fn forge(&self) -> Option<&str> {
        self.profile.forge.as_deref()
    }

    /// The release mode.
    #[must_use]
    pub const fn release_mode(&self) -> ReleaseMode {
        self.profile.release.mode
    }

    /// The release driver, for an automatic release.
    #[must_use]
    pub fn driver(&self) -> Option<&str> {
        self.profile.release.driver.as_deref()
    }

    /// The release style, for an automatic release that answered it.
    #[must_use]
    pub const fn style(&self) -> Option<Style> {
        self.profile.release.style
    }

    /// Whether this landing requested the Nix capability.
    #[must_use]
    pub const fn nix_packaging(&self) -> bool {
        self.capabilities.nix_packaging
    }

    /// Whether this landing requested the reporting policy.
    #[must_use]
    pub const fn reporting_policy(&self) -> bool {
        self.capabilities.reporting_policy
    }

    /// Whether this landing requested the Scorecard capability.
    #[must_use]
    pub const fn scorecard(&self) -> bool {
        self.capabilities.scorecard
    }

    /// The code scanning provider this landing requested, if any.
    #[must_use]
    pub const fn code_scanning(&self) -> Option<Provider> {
        self.capabilities.code_scanning
    }

    /// The project path used by parameter-bearing files, empty where the
    /// target has no forge repository.
    #[must_use]
    pub fn repo(&self) -> &str {
        &self.repo
    }

    /// Where a topic branch opens.
    #[must_use]
    pub const fn checkout_mode(&self) -> CheckoutMode {
        self.git.checkout_mode
    }

    /// Which authority moves an implementation onto the trunk.
    #[must_use]
    pub const fn integration(&self) -> Integration {
        self.git.integration
    }

    /// The one permanent branch this landing writes into its artifacts.
    #[must_use]
    pub fn trunk(&self) -> &str {
        &self.git.trunk
    }

    /// The release-line prefix this landing writes into its artifacts,
    /// the compiled default where the release intent carries none.
    #[must_use]
    pub fn line_prefix(&self) -> &str {
        self.profile
            .release
            .line_prefix
            .as_deref()
            .unwrap_or(crate::config::LINE_PREFIX_DEFAULT)
    }

    /// The contact the landed policy names, empty for the forge's own
    /// authored wording.
    #[must_use]
    pub fn security_contact(&self) -> &str {
        &self.security_contact
    }

    /// The acknowledgment window the landed policy promises.
    #[must_use]
    pub fn security_response(&self) -> &str {
        &self.security_response
    }

    /// The check the release gate believes, empty where this target
    /// renders no gate that reads one.
    #[must_use]
    pub fn required_check(&self) -> &str {
        &self.required_check
    }

    /// The workflow whose completion wakes the release gate, empty where
    /// this target renders no gate that waits on one.
    #[must_use]
    pub fn required_workflow(&self) -> &str {
        &self.required_workflow
    }

    /// The canonical identity and Git workflow flags, as `rk init` and
    /// `rk adopt` take them: every resolved answer stated, so a follow-up
    /// command a preview prints applies the decision that was previewed.
    #[must_use]
    pub fn canonical_flags(&self) -> String {
        let mut out = String::new();
        for technology in &self.profile.technologies {
            out.push_str(" --technology ");
            out.push_str(technology);
        }
        if let Some(forge) = &self.profile.forge {
            out.push_str(" --forge ");
            out.push_str(forge);
        }
        // A preview stands in for an unresolved repository with the
        // placeholder, and a replayed apply takes the operator's own path
        // rather than that stand-in, so the flag stays out of the command.
        if !self.repo.is_empty() && self.repo != crate::projection::REPO_PLACEHOLDER {
            out.push_str(" --repo ");
            out.push_str(&self.repo);
        }
        out.push_str(" --release-mode ");
        out.push_str(self.profile.release.mode.as_str());
        if let Some(driver) = &self.profile.release.driver {
            out.push_str(" --release-driver ");
            out.push_str(driver);
        }
        if let Some(style) = self.profile.release.style {
            out.push_str(" --release-style ");
            out.push_str(style.as_str());
        }
        out.push_str(" --trunk ");
        out.push_str(&self.git.trunk);
        out.push_str(" --checkout-mode ");
        out.push_str(self.git.checkout_mode.as_str());
        out.push_str(" --integration ");
        out.push_str(self.git.integration.as_str());
        // An unanswered gate has no flag form: the empty answer is the
        // compiled default, and a replayed command that stated it would
        // pass a name the resolution never produced.
        if !self.required_check.is_empty() {
            out.push_str(" --required-check ");
            push_shell_word(&mut out, &self.required_check);
        }
        if !self.required_workflow.is_empty() {
            out.push_str(" --required-workflow ");
            push_shell_word(&mut out, &self.required_workflow);
        }
        out
    }

    /// Every opt-in capability's flag, as `rk init` and `rk adopt` take it.
    ///
    /// The resolved answers, not the flags the caller typed: a follow-up
    /// command a preview prints must apply the decision that was previewed,
    /// and the preview's decision is what resolution produced.
    #[must_use]
    pub fn capability_flags(&self) -> String {
        let mut out = String::new();
        if self.capabilities.nix_packaging {
            out.push_str(" --nix-packaging");
        }
        if self.capabilities.reporting_policy {
            out.push_str(" --reporting-policy");
        }
        if self.capabilities.scorecard {
            out.push_str(" --scorecard");
        }
        // The provider flag takes a value, so `off` is a statable answer and
        // is stated: a committed `capabilities.code_scanning` would
        // otherwise re-enable on replay exactly what this preview turned
        // off. The boolean flags above have no off form, so absence is
        // their only honest rendering and no committed value can
        // contradict it.
        out.push_str(" --code-scanning ");
        out.push_str(
            self.capabilities
                .code_scanning
                .map_or("off", Provider::as_str),
        );
        out
    }

    /// The same answers as `rk upgrade` takes them, every one stated.
    ///
    /// An upgrade can turn a capability off as well as on, so absence is no
    /// answer there and each value is rendered explicitly. That is what makes
    /// a printed follow-up command reproduce the previewed decision rather
    /// than re-resolve the configured one.
    #[must_use]
    pub fn capability_toggles(&self) -> String {
        let word = |on: bool| if on { "on" } else { "off" };
        format!(
            " --nix-packaging {} --reporting-policy {} --scorecard {} --code-scanning {}",
            word(self.capabilities.nix_packaging),
            word(self.capabilities.reporting_policy),
            word(self.capabilities.scorecard),
            self.capabilities
                .code_scanning
                .map_or("off", Provider::as_str)
        )
    }
}

#[cfg(test)]
impl Params {
    /// A parameter set for tests alone: an automatic rust release on
    /// GitHub. Production code reaches `Params` through `from_record` and
    /// `resolve` and through nothing else, and this constructor is
    /// compiled out of the shipped binary.
    pub(crate) fn for_test(repo: &str, style: Option<Style>) -> Self {
        Self {
            profile: ProfileSnapshot {
                technologies: vec!["rust".to_owned()],
                forge: Some("github".to_owned()),
                release: ReleaseIntent {
                    mode: ReleaseMode::Automatic,
                    driver: Some("rust".to_owned()),
                    style,
                    line_prefix: Some(crate::config::LINE_PREFIX_DEFAULT.to_owned()),
                },
            },
            git: GitWorkflow {
                trunk: crate::config::TRUNK_DEFAULT.to_owned(),
                checkout_mode: CheckoutMode::LinkedWorktree,
                integration: Integration::Local,
            },
            capabilities: CapabilityRequests {
                nix_packaging: false,
                reporting_policy: true,
                scorecard: false,
                code_scanning: None,
            },
            repo: repo.to_owned(),
            security_contact: String::new(),
            security_response: crate::config::RESPONSE_DEFAULT.to_owned(),
            required_check: "gate".to_owned(),
            required_workflow: "ci".to_owned(),
        }
    }

    /// The same set with the two security parameters answered.
    pub(crate) fn for_test_security(contact: &str, response: &str) -> Self {
        Self {
            security_contact: contact.to_owned(),
            security_response: response.to_owned(),
            ..Self::for_test("acme/widget", Some(Style::Trunk))
        }
    }

    /// A release-less set for tests: the technologies and the forge as
    /// given, no driver, no style.
    pub(crate) fn for_test_release_less(
        technologies: &[&str],
        forge: Option<&str>,
        mode: ReleaseMode,
    ) -> Self {
        let mut params = Self::for_test("acme/widget", None);
        params.profile.technologies = technologies.iter().map(|t| (*t).to_owned()).collect();
        params.profile.forge = forge.map(str::to_owned);
        params.profile.release = ReleaseIntent {
            mode,
            driver: None,
            style: None,
            line_prefix: None,
        };
        params.capabilities.reporting_policy = false;
        if forge.is_none() {
            params.repo = String::new();
        }
        params
    }

    /// The same set with the forge and the driver changed.
    pub(crate) fn set_pair_for_test(&mut self, driver: &str, forge: &str) {
        self.profile.technologies = vec![driver.to_owned()];
        self.profile.release.driver = Some(driver.to_owned());
        self.profile.forge = Some(forge.to_owned());
    }

    /// The same set with the checkout mode answered.
    pub(crate) const fn set_checkout_mode_for_test(&mut self, mode: CheckoutMode) {
        self.git.checkout_mode = mode;
    }

    /// The same set with the integration mode answered.
    pub(crate) const fn set_integration_for_test(&mut self, mode: Integration) {
        self.git.integration = mode;
    }

    /// The same set with the Nix opt-in answered.
    pub(crate) const fn set_nix_for_test(&mut self, nix: bool) {
        self.capabilities.nix_packaging = nix;
    }

    /// The same set with the Scorecard opt-in answered.
    pub(crate) const fn set_scorecard_for_test(&mut self, scorecard: bool) {
        self.capabilities.scorecard = scorecard;
    }

    /// The same set with the code scanning provider answered.
    pub(crate) const fn set_code_scanning_for_test(&mut self, provider: Option<Provider>) {
        self.capabilities.code_scanning = provider;
    }
}

/// The refusal for an invalid release state, naming the key and its
/// valid shape.
fn invalid_release(message: impl std::fmt::Display) -> RkError {
    RkError::Usage(format!(
        "{message}; an automatic release names a driver among profile.technologies and a style, and an external or none release names neither"
    ))
}

/// The canonical release gate answers, for the one shape that renders a
/// gate reading them, or `None` for every other shape.
///
/// One shape consumes them: GitHub, an automatic release, the trunk
/// style, and local integration. There the rendered release workflow
/// wakes on a workflow completing and judges a named check, so a landing
/// that left either empty would render a gate no event can ever satisfy.
/// The names are this convention's own: `runbooks/setup.md` writes the
/// gate job as `gate`, and `ci` is the workflow that carries it.
///
/// They are a compiled default and nothing more. A flag, the committed
/// configuration, and a compatible record each answer ahead of them, the
/// resolved answer is written back and recorded, and `rk setup check`
/// proves it against the target's own workflow files. A project whose
/// names differ states them and the default never applies.
///
/// Every other shape resolves to empty, because no rendered reader
/// consumes the answer there. Under forge integration the trunk ruleset
/// holds the release request and `setup.required_check` names the context
/// that ruleset requires, which is the project's own answer and not this
/// convention's, so `protect-trunk` keeps asking for it.
#[must_use]
pub fn gate_defaults(
    profile: &ProfileSnapshot,
    git: &GitWorkflow,
) -> Option<(&'static str, &'static str)> {
    let consuming = profile.forge.as_deref() == Some("github")
        && profile.release.mode == ReleaseMode::Automatic
        && profile.release.style == Some(Style::Trunk)
        && git.integration == Integration::Local;
    consuming.then_some(("gate", "ci"))
}

/// One gate answer read back from a record, falling to the compiled
/// default where the record predates the field.
fn gate_answer(
    record: &manifest::Manifest,
    pick: impl Fn((&'static str, &'static str)) -> &'static str,
    held: impl Fn(&manifest::Parameters) -> &String,
) -> String {
    let recorded = held(&record.parameters);
    if recorded.is_empty() {
        gate_defaults(&record.profile, &record.git)
            .map_or_else(String::new, |pair| pick(pair).to_owned())
    } else {
        recorded.clone()
    }
}

/// One field's answer and where it came from.
fn answered<T>(chain: [(Option<T>, Source); 5]) -> Option<(T, Source)> {
    chain
        .into_iter()
        .find_map(|(value, source)| value.map(|value| (value, source)))
}

/// Resolve every domain value by one precedence, keeping the source of
/// each.
///
/// # Errors
/// Refuses unresolved identity, an invalid release state, a duplicate or
/// malformed category name, and a style an existing target has not
/// answered.
#[allow(
    clippy::too_many_lines,
    reason = "the resolution is one precedence walk per field, and splitting it would hide that every field walks the same chain"
)]
pub fn resolve(
    target: &Utf8Path,
    flags: &Inputs<'_>,
    config: Option<&crate::config::Config>,
    record: Option<&manifest::Manifest>,
    purpose: Purpose,
) -> Result<Resolved, RkError> {
    let mut sources: BTreeMap<&'static str, Source> = BTreeMap::new();
    let observed = crate::detect::observe(target.as_std_path());
    let known_drivers = catalog::known_drivers();

    // Technologies: a supplied list replaces the declared one whole.
    let (technologies, source) = answered([
        (
            (!flags.technologies.is_empty()).then(|| flags.technologies.to_vec()),
            Source::Flag,
        ),
        (
            config.and_then(|c| c.profile.technologies.clone()),
            Source::Config,
        ),
        (
            record.map(|r| r.profile.technologies.clone()),
            Source::Record,
        ),
        (
            Some(
                observed
                    .technologies
                    .iter()
                    .map(|t| (*t).to_owned())
                    .collect(),
            ),
            Source::Observation,
        ),
        (None, Source::Default),
    ])
    .unwrap_or_else(|| (Vec::new(), Source::Default));
    let technologies =
        canonical_list("profile.technologies", &technologies).map_err(RkError::Usage)?;
    sources.insert("profile.technologies", source);

    // The forge: an explicit empty configuration value states no forge.
    let forge_flag = flags
        .forge
        .map(|name| canonical_category(name).map_err(RkError::Usage))
        .transpose()?;
    let (forge, source) = answered([
        (forge_flag.map(Some), Source::Flag),
        (
            config
                .and_then(|c| c.profile.forge.clone())
                .map(|value| if value.is_empty() { None } else { Some(value) }),
            Source::Config,
        ),
        (record.map(|r| r.profile.forge.clone()), Source::Record),
        (
            observed.forge.map(|forge| Some(forge.as_str().to_owned())),
            Source::Observation,
        ),
        (Some(None), Source::Default),
    ])
    .unwrap_or((None, Source::Default));
    let forge = forge
        .map(|name| canonical_category(&name).map_err(RkError::Usage))
        .transpose()?;
    sources.insert("profile.forge", source);

    // The repository identity, needed only where a forge is present.
    let (repo, source) = answered([
        (flags.repo.map(str::to_owned), Source::Flag),
        (
            config
                .map(|c| c.project.repo.clone())
                .filter(|value| !value.is_empty()),
            Source::Config,
        ),
        (
            record
                .map(|r| r.parameters.repo.clone())
                .filter(|value| !value.is_empty()),
            Source::Record,
        ),
        (observed.repo.clone(), Source::Observation),
        (None, Source::Default),
    ])
    .map_or((None, Source::Default), |(value, source)| {
        (Some(value), source)
    });
    sources.insert("project.repo", source);

    // The release mode: the observation proposes where nothing above
    // answers.
    let release_bearing: Vec<String> = technologies
        .iter()
        .filter(|name| known_drivers.contains(name))
        .cloned()
        .collect();
    let proposal = match release_bearing.as_slice() {
        [] => Proposal::None,
        [one] => Proposal::Automatic {
            driver: one.clone(),
        },
        many => Proposal::Ambiguous {
            drivers: many.to_vec(),
        },
    };
    // The proposal reads the version files alone. A missing forge is not
    // an answer about the release intent: it is a separate refusal the
    // automatic branch below raises, naming the remote it did not find and
    // the two ways out. Folding it in here would silently land a
    // release-less target for a crate whose author simply has no remote
    // yet, and the record would then claim a release intent nobody stated.
    let proposed_mode = match &proposal {
        Proposal::Automatic { .. } | Proposal::Ambiguous { .. } => ReleaseMode::Automatic,
        Proposal::None => ReleaseMode::None,
    };
    let (mode, source) = answered([
        (flags.release_mode, Source::Flag),
        (config.and_then(|c| c.profile.release.mode), Source::Config),
        (record.map(|r| r.profile.release.mode), Source::Record),
        (Some(proposed_mode), Source::Observation),
        (None, Source::Default),
    ])
    .unwrap_or((ReleaseMode::None, Source::Default));
    let mode_source = source;
    sources.insert("profile.release.mode", mode_source);
    let mode_answered_above = mode_source != Source::Observation;
    let proposal = (!mode_answered_above).then_some(proposal);

    // The driver, style, and line prefix belong to an automatic release
    // alone, and a value from a flag or the configuration under another
    // mode is a malformed intent rather than an ignored one.
    let driver_flag = flags
        .release_driver
        .map(|name| canonical_category(name).map_err(RkError::Usage))
        .transpose()?;
    let (driver, driver_source) = answered([
        (driver_flag, Source::Flag),
        (
            config.and_then(|c| c.profile.release.driver.clone()),
            Source::Config,
        ),
        (
            record.and_then(|r| r.profile.release.driver.clone()),
            Source::Record,
        ),
        (
            match &proposal {
                Some(Proposal::Automatic { driver }) if mode == ReleaseMode::Automatic => {
                    Some(driver.clone())
                }
                _ => None,
            },
            Source::Observation,
        ),
        (None, Source::Default),
    ])
    .map_or((None, Source::Default), |(value, source)| {
        (Some(value), source)
    });
    let (style, style_source) = answered([
        (flags.style, Source::Flag),
        (config.and_then(|c| c.profile.release.style), Source::Config),
        (record.and_then(|r| r.profile.release.style), Source::Record),
        (None, Source::Observation),
        (
            (mode == ReleaseMode::Automatic && matches!(purpose, Purpose::Init | Purpose::Preview))
                .then_some(Style::Trunk),
            Source::Default,
        ),
    ])
    .map_or((None, Source::Default), |(value, source)| {
        (Some(value), source)
    });
    let (line_prefix, prefix_source) = answered([
        (None, Source::Flag),
        (
            config.and_then(|c| c.profile.release.line_prefix.clone()),
            Source::Config,
        ),
        (
            record.and_then(|r| r.profile.release.line_prefix.clone()),
            Source::Record,
        ),
        (None, Source::Observation),
        (
            (mode == ReleaseMode::Automatic).then(|| crate::config::LINE_PREFIX_DEFAULT.to_owned()),
            Source::Default,
        ),
    ])
    .map_or((None, Source::Default), |(value, source)| {
        (Some(value), source)
    });

    // A reporting purpose never refuses what it can state: `rk profile`
    // and every preview report an intent the target cannot yet take, and
    // the capability catalog says why. A purpose that writes refuses,
    // because a record must not claim a release nothing can land.
    let reporting = purpose == Purpose::Preview;
    let release = match mode {
        ReleaseMode::Automatic => {
            if let Some(Proposal::Ambiguous { drivers }) = &proposal
                && driver.is_none()
                && !reporting
            {
                return Err(RkError::Usage(format!(
                    "the target carries more than one release-bearing technology, {}, and nothing names the driver; pass --release-driver <name>, or set profile.release.driver in {}",
                    drivers.join(" and "),
                    crate::config::CONFIG_PATH
                )));
            }
            if forge.is_none() && !reporting {
                let message = observed.host.map_or_else(
                    || "no forge detected: the target has no origin remote, and an automatic release needs one".to_owned(),
                    |host| format!("no forge detected: the host {host} is not recognized, and an automatic release needs one"),
                );
                return Err(RkError::refusal(
                    Diagnostic::new(Reason::ForgeUndetected, message)
                        .expected("a github.com or gitlab remote, or --forge")
                        .action("pass --forge <github|gitlab>, or --release-mode none for a project that releases nothing"),
                ));
            }
            if driver.is_none() && !reporting {
                return Err(invalid_release(format!(
                    "profile.release.mode is automatic and no driver is named; pass --release-driver <{}>",
                    known_drivers.join("|")
                )));
            }
            if let Some(driver) = &driver
                && !technologies.contains(driver)
                && !reporting
            {
                return Err(invalid_release(format!(
                    "profile.release.driver names {driver}, which profile.technologies does not carry ({})",
                    if technologies.is_empty() {
                        "empty".to_owned()
                    } else {
                        technologies.join(", ")
                    }
                )));
            }
            let style = match (style, purpose) {
                (None, Purpose::Upgrade | Purpose::Adopt) => {
                    return Err(RkError::Usage(
                        "the target carries no style parameter; set profile.release.style in .release-kit/config.toml or pass --release-style <trunk|lines>".into(),
                    ));
                }
                (None, _) => Style::Trunk,
                (Some(style), _) => style,
            };
            sources.insert("profile.release.driver", driver_source);
            sources.insert("profile.release.style", style_source);
            sources.insert("profile.release.line_prefix", prefix_source);
            ReleaseIntent {
                mode,
                driver,
                style: Some(style),
                line_prefix: Some(
                    line_prefix.unwrap_or_else(|| crate::config::LINE_PREFIX_DEFAULT.to_owned()),
                ),
            }
        }
        ReleaseMode::External | ReleaseMode::None => {
            // A stated value under a mode that has no room for it is a
            // malformed intent. A value the mode outranks is not: that is
            // ordinary precedence, and `--release-mode none` over a
            // configured automatic release is the one command that retires
            // it. So the refusal fires only where the subordinate value
            // speaks at or above the tier that chose the mode.
            for (key, present, value_source) in [
                ("profile.release.driver", driver.is_some(), driver_source),
                ("profile.release.style", style.is_some(), style_source),
                (
                    "profile.release.line_prefix",
                    line_prefix.is_some(),
                    prefix_source,
                ),
            ] {
                if present
                    && matches!(value_source, Source::Flag | Source::Config)
                    && value_source.rank() <= mode_source.rank()
                {
                    return Err(invalid_release(format!(
                        "{key} is set while profile.release.mode is {}",
                        mode.as_str()
                    )));
                }
            }
            ReleaseIntent {
                mode,
                driver: None,
                style: None,
                line_prefix: None,
            }
        }
    };

    // Every capability this binary ships for a forge renders the project
    // path, so the identity is required exactly where the forge has an
    // adapter. An unknown forge selects no such capability and needs none.
    let adapter_known = forge
        .as_deref()
        .is_some_and(|name| crate::detect::Forge::parse(name).is_some());
    let repo = match (forge.is_some(), adapter_known, repo) {
        // No forge at all: the identity has nowhere to point, so a lower
        // tier's remote or record must not survive into `[project]`.
        (false, _, _) => String::new(),
        (true, false, repo) => repo.unwrap_or_default(),
        (true, true, Some(repo)) => repo,
        (true, true, None) if purpose == Purpose::Preview => {
            crate::projection::REPO_PLACEHOLDER.to_owned()
        }
        (true, true, None) => return Err(crate::landing::repo_unresolved()),
    };

    // The Git workflow.
    let (trunk, source) = answered([
        (flags.trunk.map(str::to_owned), Source::Flag),
        (config.and_then(|c| c.git.trunk.clone()), Source::Config),
        (record.map(|r| r.git.trunk.clone()), Source::Record),
        (None, Source::Observation),
        (
            Some(crate::config::TRUNK_DEFAULT.to_owned()),
            Source::Default,
        ),
    ])
    .unwrap_or_else(|| (crate::config::TRUNK_DEFAULT.to_owned(), Source::Default));
    sources.insert("git.trunk", source);
    let (checkout_mode, source) = answered([
        (flags.checkout_mode, Source::Flag),
        (config.and_then(|c| c.git.checkout_mode), Source::Config),
        (record.map(|r| r.git.checkout_mode), Source::Record),
        (None, Source::Observation),
        (
            Some(if purpose == Purpose::Adopt {
                CheckoutMode::MainWorktree
            } else {
                CheckoutMode::LinkedWorktree
            }),
            Source::Default,
        ),
    ])
    .unwrap_or((CheckoutMode::LinkedWorktree, Source::Default));
    sources.insert("git.checkout_mode", source);
    // The compiled default is `local` and the record's absence answers
    // `forge`. The two differ deliberately: a fresh landing takes the
    // cheaper authority, and a target that landed before this axis
    // existed keeps the one whose blocks and protections it carries.
    let (integration, source) = answered([
        (flags.integration, Source::Flag),
        (config.and_then(|c| c.git.integration), Source::Config),
        (record.map(|r| r.git.integration), Source::Record),
        (None, Source::Observation),
        // An adoption defaults to `forge`, the way it defaults to the
        // main worktree: it is describing a target that already exists,
        // and every target that landed before this axis carries the
        // forge blocks. A fresh landing takes `local`.
        (
            Some(if purpose == Purpose::Adopt {
                Integration::Forge
            } else {
                Integration::Local
            }),
            Source::Default,
        ),
    ])
    .unwrap_or((Integration::Local, Source::Default));
    sources.insert("git.integration", source);

    // The capability requests.
    let (nix_packaging, source) = answered([
        (flags.nix, Source::Flag),
        (
            config.and_then(|c| c.capabilities.nix_packaging),
            Source::Config,
        ),
        (record.map(|r| r.capabilities.nix_packaging), Source::Record),
        (None, Source::Observation),
        (Some(false), Source::Default),
    ])
    .unwrap_or((false, Source::Default));
    sources.insert("capabilities.nix_packaging", source);
    let (reporting_policy, source) = answered([
        (flags.reporting_policy, Source::Flag),
        (
            config.and_then(|c| c.capabilities.reporting_policy),
            Source::Config,
        ),
        (
            record.map(|r| r.capabilities.reporting_policy),
            Source::Record,
        ),
        (None, Source::Observation),
        // A project that automates its release carries the policy by
        // default; a release-less profile asks for it explicitly.
        (
            Some(release.mode == ReleaseMode::Automatic),
            Source::Default,
        ),
    ])
    .unwrap_or((false, Source::Default));
    sources.insert("capabilities.reporting_policy", source);
    let (scorecard, source) = answered([
        (flags.scorecard, Source::Flag),
        (
            config.and_then(|c| c.capabilities.scorecard),
            Source::Config,
        ),
        (record.map(|r| r.capabilities.scorecard), Source::Record),
        (None, Source::Observation),
        (Some(false), Source::Default),
    ])
    .unwrap_or((false, Source::Default));
    sources.insert("capabilities.scorecard", source);
    let configured_scanning = config
        .and_then(|c| c.capabilities.code_scanning.as_deref())
        .map(Provider::parse)
        .transpose()?;
    let (code_scanning, source) = answered([
        (flags.code_scanning, Source::Flag),
        (configured_scanning, Source::Config),
        (record.map(|r| r.capabilities.code_scanning), Source::Record),
        (None, Source::Observation),
        (Some(None), Source::Default),
    ])
    .unwrap_or((None, Source::Default));
    sources.insert("capabilities.code_scanning", source);
    // A requested scanner this release cannot land at these dimensions is
    // an unavailable optional capability, not a malformed request. The
    // catalog reports it and the landing omits it, which is what
    // `project-profile:an-operation-refuses-only-what-it-requires` says
    // must happen: only the selected release automation blocks an apply.

    // The security policy's two answers.
    let (security_contact, source) = answered([
        (None, Source::Flag),
        (
            config.and_then(|c| c.security.contact.clone()),
            Source::Config,
        ),
        (
            record.map(|r| r.parameters.security_contact.clone()),
            Source::Record,
        ),
        (None, Source::Observation),
        (Some(String::new()), Source::Default),
    ])
    .unwrap_or((String::new(), Source::Default));
    let security_contact =
        crate::config::canonical_contact(&security_contact).map_err(crate::config::invalid)?;
    sources.insert("security.contact", source);
    let (security_response, source) = answered([
        (None, Source::Flag),
        (
            config.and_then(|c| c.security.response.clone()),
            Source::Config,
        ),
        (
            record.map(|r| r.parameters.security_response.clone()),
            Source::Record,
        ),
        (None, Source::Observation),
        (
            Some(crate::config::RESPONSE_DEFAULT.to_owned()),
            Source::Default,
        ),
    ])
    .unwrap_or_else(|| (crate::config::RESPONSE_DEFAULT.to_owned(), Source::Default));
    let security_response =
        crate::config::canonical_response(&security_response).map_err(crate::config::invalid)?;
    sources.insert("security.response", source);

    // The release gate's two answers. Neither has an observation: nothing
    // in the target proposes a name. The compiled default is the
    // convention's own pair, and it applies to the one shape that renders
    // a gate reading them.
    let gate_default = gate_defaults(
        &ProfileSnapshot {
            technologies: technologies.clone(),
            forge: forge.clone(),
            release: release.clone(),
        },
        &GitWorkflow {
            trunk: trunk.clone(),
            checkout_mode,
            integration,
        },
    );
    let (required_check, source) = answered([
        (flags.required_check.map(str::to_owned), Source::Flag),
        (
            config
                .map(|c| c.setup.required_check.clone())
                .filter(|name| !name.is_empty()),
            Source::Config,
        ),
        (
            record
                .map(|r| r.parameters.required_check.clone())
                .filter(|name| !name.is_empty()),
            Source::Record,
        ),
        (None, Source::Observation),
        (
            Some(gate_default.map_or_else(String::new, |(check, _)| check.to_owned())),
            Source::Default,
        ),
    ])
    .unwrap_or((String::new(), Source::Default));
    sources.insert("setup.required_check", source);
    let (required_workflow, source) = answered([
        (flags.required_workflow.map(str::to_owned), Source::Flag),
        (
            config
                .map(|c| c.setup.required_workflow.clone())
                .filter(|name| !name.is_empty()),
            Source::Config,
        ),
        (
            record
                .map(|r| r.parameters.required_workflow.clone())
                .filter(|name| !name.is_empty()),
            Source::Record,
        ),
        (None, Source::Observation),
        (
            Some(gate_default.map_or_else(String::new, |(_, workflow)| workflow.to_owned())),
            Source::Default,
        ),
    ])
    .unwrap_or((String::new(), Source::Default));
    sources.insert("setup.required_workflow", source);
    // GitLab requires the whole pipeline through one project setting and
    // names no individual check, so neither answer has a reader there.
    // Refusing the flag says that; discarding it silently would let an
    // operator believe a gate was configured.
    if forge.as_deref() == Some("gitlab") {
        for (flag, supplied) in [
            ("--required-check", flags.required_check),
            ("--required-workflow", flags.required_workflow),
        ] {
            if supplied.is_some() {
                return Err(RkError::Usage(format!(
                    "{flag} is not a GitLab answer: the forge requires the whole pipeline through one project setting and names no individual check"
                )));
            }
        }
    }

    let mut unknown: Vec<String> = technologies
        .iter()
        .filter(|name| !known_drivers.contains(name))
        .map(|name| format!("technology {name}"))
        .collect();
    if let Some(name) = &forge
        && crate::detect::Forge::parse(name).is_none()
    {
        unknown.push(format!("forge {name}"));
    }

    Ok(Resolved {
        params: Params {
            profile: ProfileSnapshot {
                technologies,
                forge,
                release,
            },
            git: GitWorkflow {
                trunk,
                checkout_mode,
                integration,
            },
            capabilities: CapabilityRequests {
                nix_packaging,
                reporting_policy,
                scorecard,
                code_scanning,
            },
            repo,
            security_contact,
            security_response,
            required_check,
            required_workflow,
        },
        sources,
        unknown,
        proposal,
    })
}