1use std::collections::BTreeMap;
13
14use camino::Utf8Path;
15use serde::{Deserialize, Serialize};
16
17use crate::atomic;
18use crate::diagnostic::{Diagnostic, Reason};
19use crate::digest::Digest;
20use crate::error::RkError;
21use crate::landing::Kind;
22pub use crate::profile::{
23 CapabilityRequests, GitWorkflow, ProfileSnapshot, ReleaseIntent, ReleaseMode,
24};
25
26pub const MANIFEST_PATH: &str = ".release-kit/manifest.json";
28
29pub const SCHEMA_VERSION: u64 = 12;
61
62const OLDEST_READABLE_SCHEMA: u64 = 1;
64
65const PLACEMENT_SCHEMA: u64 = 7;
69
70#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
78#[serde(rename_all = "kebab-case")]
79pub enum CheckoutMode {
80 LinkedWorktree,
83 MainWorktree,
87}
88
89impl CheckoutMode {
90 #[must_use]
92 pub const fn as_str(self) -> &'static str {
93 match self {
94 Self::LinkedWorktree => "linked-worktree",
95 Self::MainWorktree => "main-worktree",
96 }
97 }
98
99 #[must_use]
101 pub const fn runbook_label(self) -> &'static str {
102 match self {
103 Self::LinkedWorktree => "worktree",
104 Self::MainWorktree => "branches",
105 }
106 }
107
108 pub fn parse(raw: &str) -> Result<Self, RkError> {
117 match raw {
118 "linked-worktree" | "worktree" => Ok(Self::LinkedWorktree),
119 "main-worktree" | "branches" => Ok(Self::MainWorktree),
120 other => Err(RkError::Usage(format!(
121 "unknown checkout mode '{other}'; the modes are: linked-worktree, main-worktree"
122 ))),
123 }
124 }
125}
126
127impl<'de> serde::Deserialize<'de> for CheckoutMode {
128 fn deserialize<D: serde::Deserializer<'de>>(reader: D) -> Result<Self, D::Error> {
129 let raw = String::deserialize(reader)?;
130 Self::parse(&raw).map_err(|error| serde::de::Error::custom(error.to_string()))
131 }
132}
133
134#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
143#[serde(rename_all = "lowercase")]
144pub enum Integration {
145 Local,
148 Forge,
151}
152
153impl Integration {
154 #[must_use]
156 pub const fn as_str(self) -> &'static str {
157 match self {
158 Self::Local => "local",
159 Self::Forge => "forge",
160 }
161 }
162
163 pub fn parse(raw: &str) -> Result<Self, RkError> {
169 match raw {
170 "local" => Ok(Self::Local),
171 "forge" => Ok(Self::Forge),
172 other => Err(RkError::Usage(format!(
173 "unknown integration mode '{other}'; the modes are: local, forge"
174 ))),
175 }
176 }
177}
178
179impl<'de> serde::Deserialize<'de> for Integration {
180 fn deserialize<D: serde::Deserializer<'de>>(reader: D) -> Result<Self, D::Error> {
181 let raw = String::deserialize(reader)?;
182 Self::parse(&raw).map_err(|error| serde::de::Error::custom(error.to_string()))
183 }
184}
185
186pub(crate) const fn integration_forge() -> Integration {
191 Integration::Forge
192}
193
194#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
204#[serde(rename_all = "lowercase")]
205pub enum MergeForm {
206 Squash,
209 Rebase,
212}
213
214impl MergeForm {
215 #[must_use]
217 pub const fn as_str(self) -> &'static str {
218 match self {
219 Self::Squash => "squash",
220 Self::Rebase => "rebase",
221 }
222 }
223
224 pub fn parse(raw: &str) -> Result<Self, RkError> {
230 match raw {
231 "squash" => Ok(Self::Squash),
232 "rebase" => Ok(Self::Rebase),
233 other => Err(RkError::Usage(format!(
234 "unknown merge form '{other}'; the forms are: squash, rebase"
235 ))),
236 }
237 }
238}
239
240impl<'de> serde::Deserialize<'de> for MergeForm {
241 fn deserialize<D: serde::Deserializer<'de>>(reader: D) -> Result<Self, D::Error> {
242 let raw = String::deserialize(reader)?;
243 Self::parse(&raw).map_err(|error| serde::de::Error::custom(error.to_string()))
244 }
245}
246
247#[must_use]
253pub const fn merge_form_squash() -> MergeForm {
254 MergeForm::Squash
255}
256
257#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
263#[serde(rename_all = "lowercase")]
264pub enum Style {
265 Trunk,
268 Lines,
271}
272
273impl Style {
274 #[must_use]
276 pub const fn as_str(self) -> &'static str {
277 match self {
278 Self::Trunk => "trunk",
279 Self::Lines => "lines",
280 }
281 }
282
283 pub fn parse(raw: &str) -> Result<Self, RkError> {
289 match raw {
290 "trunk" => Ok(Self::Trunk),
291 "lines" => Ok(Self::Lines),
292 other => Err(RkError::Usage(format!(
293 "unknown style '{other}'; the styles are: trunk, lines"
294 ))),
295 }
296 }
297}
298
299#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
304#[serde(rename_all = "lowercase")]
305pub enum Provider {
306 CodeQl,
310 Semgrep,
313}
314
315impl Provider {
316 #[must_use]
318 pub const fn as_str(self) -> &'static str {
319 match self {
320 Self::CodeQl => "codeql",
321 Self::Semgrep => "semgrep",
322 }
323 }
324
325 pub fn parse(raw: &str) -> Result<Option<Self>, RkError> {
332 match raw {
333 "codeql" => Ok(Some(Self::CodeQl)),
334 "semgrep" => Ok(Some(Self::Semgrep)),
335 "off" => Ok(None),
336 other => Err(RkError::Usage(format!(
337 "unknown code scanning provider '{other}'; the providers are: codeql, semgrep, and off turns the capability off"
338 ))),
339 }
340 }
341}
342
343#[derive(Debug, Serialize, Deserialize)]
349pub struct Manifest {
350 pub schema_version: u64,
352 pub rk_version: String,
354 pub origin: String,
356 pub landed_at: String,
358 pub profile: ProfileSnapshot,
361 pub git: GitWorkflow,
364 pub capabilities: CapabilityRequests,
366 pub parameters: Parameters,
369 pub files: Vec<FileRecord>,
371 pub pins: BTreeMap<String, String>,
374}
375
376#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
378pub struct Parameters {
379 #[serde(default)]
383 pub repo: String,
384 #[serde(default, deserialize_with = "read_contact")]
389 pub security_contact: String,
390 #[serde(default = "response_best_effort", deserialize_with = "read_response")]
394 pub security_response: String,
395 #[serde(default)]
399 pub required_check: String,
400 #[serde(default)]
403 pub required_workflow: String,
404}
405
406fn response_best_effort() -> String {
408 crate::config::RESPONSE_DEFAULT.to_owned()
409}
410
411fn read_contact<'de, D: serde::Deserializer<'de>>(reader: D) -> Result<String, D::Error> {
417 canonical(reader, "security_contact", crate::config::canonical_contact)
418}
419
420fn read_response<'de, D: serde::Deserializer<'de>>(reader: D) -> Result<String, D::Error> {
422 canonical(
423 reader,
424 "security_response",
425 crate::config::canonical_response,
426 )
427}
428
429fn canonical<'de, D: serde::Deserializer<'de>>(
431 reader: D,
432 field: &str,
433 judge: impl Fn(&str) -> Result<String, String>,
434) -> Result<String, D::Error> {
435 let raw = String::deserialize(reader)?;
436 let canonical = judge(&raw)
437 .map_err(|reason| serde::de::Error::custom(format!("parameters.{field}: {reason}")))?;
438 if canonical == raw {
439 Ok(canonical)
440 } else {
441 Err(serde::de::Error::custom(format!(
442 "parameters.{field} is not canonical: the record carries {raw:?} where a landing writes {canonical:?}"
443 )))
444 }
445}
446
447#[derive(Debug, Serialize, Deserialize)]
449pub struct FileRecord {
450 pub destination: String,
452 pub kind: Kind,
454 pub sha256: Digest,
457 #[serde(default, skip_serializing_if = "Placement::is_whole")]
461 pub placement: Placement,
462}
463
464#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
466#[serde(rename_all = "lowercase")]
467pub enum Placement {
468 #[default]
470 Whole,
471 Region,
474}
475
476impl Placement {
477 #[must_use]
479 pub const fn is_whole(&self) -> bool {
480 matches!(self, Self::Whole)
481 }
482
483 #[must_use]
485 pub const fn as_str(self) -> &'static str {
486 match self {
487 Self::Whole => "whole",
488 Self::Region => "region",
489 }
490 }
491}
492
493pub mod legacy {
503 use serde_json::{Map, Value, json};
504
505 fn take(object: &mut Map<String, Value>, key: &str) -> Option<Value> {
507 object.remove(key)
508 }
509
510 #[must_use]
521 pub fn convert(mut value: Value) -> Value {
522 let Some(record) = value.as_object_mut() else {
523 return value;
524 };
525 record.remove("payload_sha256");
526 if let Some(files) = record.get_mut("files").and_then(Value::as_array_mut) {
527 for file in files.iter_mut().filter_map(Value::as_object_mut) {
528 file.remove("baseline_sha256");
529 }
530 }
531 if record.contains_key("profile") {
532 return value;
533 }
534 let tech = take(record, "tech").and_then(|v| v.as_str().map(str::to_owned));
535 let forge = take(record, "forge").and_then(|v| v.as_str().map(str::to_owned));
536 let mut parameters = take(record, "parameters")
537 .and_then(|v| v.as_object().cloned())
538 .unwrap_or_default();
539 parameters.remove("scopes");
540 let checkout_mode = match parameters
541 .remove("workflow")
542 .and_then(|v| v.as_str().map(str::to_owned))
543 .as_deref()
544 {
545 Some("worktree") => "linked-worktree",
546 _ => "main-worktree",
549 };
550 let style = parameters.remove("style").unwrap_or(Value::Null);
551 let trunk = parameters
552 .remove("trunk")
553 .unwrap_or_else(|| json!(crate::config::TRUNK_DEFAULT));
554 let line_prefix = parameters
555 .remove("line_prefix")
556 .unwrap_or_else(|| json!(crate::config::LINE_PREFIX_DEFAULT));
557 let nix = parameters.remove("nix").unwrap_or(json!(false));
558 let scorecard = parameters.remove("scorecard").unwrap_or(json!(false));
559 let code_scanning = parameters.remove("code_scanning").unwrap_or(Value::Null);
560 let mut release = Map::new();
561 release.insert("mode".into(), json!("automatic"));
562 if let Some(tech) = &tech {
563 release.insert("driver".into(), json!(tech));
564 }
565 if !style.is_null() {
566 release.insert("style".into(), style);
567 }
568 release.insert("line_prefix".into(), line_prefix);
569 let technologies: Vec<Value> = tech.iter().map(|t| json!(t)).collect();
570 record.insert(
571 "profile".into(),
572 json!({
573 "technologies": technologies,
574 "forge": forge,
575 "release": Value::Object(release),
576 }),
577 );
578 record.insert(
579 "git".into(),
580 json!({ "trunk": trunk, "checkout_mode": checkout_mode }),
581 );
582 record.insert(
583 "capabilities".into(),
584 json!({
585 "nix_packaging": nix,
586 "reporting_policy": true,
587 "scorecard": scorecard,
588 "code_scanning": code_scanning,
589 }),
590 );
591 record.insert("parameters".into(), Value::Object(parameters));
592 value
593 }
594}
595
596impl Manifest {
597 #[must_use]
599 pub fn file(&self, destination: &str) -> Option<&FileRecord> {
600 self.files
601 .iter()
602 .find(|file| file.destination == destination)
603 }
604}
605
606pub fn load(target: &Utf8Path) -> Result<Option<Manifest>, RkError> {
615 let path = target.join(MANIFEST_PATH);
616 let bytes = match std::fs::read(&path) {
617 Ok(bytes) => bytes,
618 Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(None),
619 Err(e) => {
620 return Err(RkError::refusal(
621 Diagnostic::new(Reason::Io, format!("cannot read {path}: {e}"))
622 .expected("a readable landing record")
623 .target_state("unchanged"),
624 ));
625 }
626 };
627 let value: serde_json::Value = serde_json::from_slice(&bytes)
628 .map_err(|e| record_invalid(&path, &format!("{path} is not a landing record: {e}")))?;
629 let schema = value
634 .get("schema_version")
635 .and_then(serde_json::Value::as_u64);
636 if !schema.is_some_and(|version| (OLDEST_READABLE_SCHEMA..=SCHEMA_VERSION).contains(&version)) {
637 let found = schema.map_or_else(|| "none".to_owned(), |version| version.to_string());
638 return Err(RkError::refusal(
639 Diagnostic::new(
640 Reason::UnsupportedSchema,
641 format!(
642 "{path} declares schema_version {found}, and this binary knows only {OLDEST_READABLE_SCHEMA} through {SCHEMA_VERSION}"
643 ),
644 )
645 .expected("a landing record at a schema this binary knows")
646 .action("install the rk release that wrote this record, or a newer one")
647 .target_state("unchanged"),
648 ));
649 }
650 let declared = schema.unwrap_or(SCHEMA_VERSION);
651 let value = if declared < SCHEMA_VERSION {
652 legacy::convert(value)
653 } else {
654 value
655 };
656 let mut manifest: Manifest = serde_json::from_value(value).map_err(|e| {
657 record_invalid(
658 &path,
659 &format!("{path} does not parse at schema_version {declared}: {e}"),
660 )
661 })?;
662 for file in &mut manifest.files {
666 if declared < PLACEMENT_SCHEMA && crate::landing::block_markers(&file.destination).is_some()
667 {
668 file.placement = Placement::Region;
669 }
670 }
671 Ok(Some(manifest))
672}
673
674fn record_invalid(path: &Utf8Path, message: &str) -> RkError {
681 RkError::refusal(
682 Diagnostic::new(Reason::RecordInvalid, message)
683 .expected("a landing record this binary wrote, or one it can convert")
684 .action(format!(
685 "restore {path} from Git, or repair the file it names, and retry"
686 ))
687 .target_state("nothing was written"),
688 )
689}
690
691pub fn write(target: &Utf8Path, manifest: &Manifest) -> Result<(), RkError> {
697 let path = target.join(MANIFEST_PATH);
698 atomic::write(path.as_std_path(), &render(manifest)?)?;
699 Ok(())
700}
701
702pub fn render(manifest: &Manifest) -> Result<Vec<u8>, RkError> {
708 let text = serde_json::to_string_pretty(manifest).map_err(anyhow::Error::from)?;
709 Ok(format!("{text}\n").into_bytes())
710}
711
712#[must_use]
714pub fn now() -> String {
715 humantime::format_rfc3339_seconds(std::time::SystemTime::now()).to_string()
716}
717
718#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
720#[serde(rename_all = "kebab-case")]
721pub enum Alignment {
722 Aligned,
724 BinaryNewer,
726 TargetNewer,
729}
730
731impl Alignment {
732 #[must_use]
734 pub const fn as_str(self) -> &'static str {
735 match self {
736 Self::Aligned => "aligned",
737 Self::BinaryNewer => "binary-newer",
738 Self::TargetNewer => "target-newer",
739 }
740 }
741}
742
743#[must_use]
745pub fn alignment(recorded: &str, binary: &str) -> Alignment {
746 let recorded = recorded
748 .split_once('+')
749 .map_or(recorded, |(version, _)| version);
750 let binary = binary
751 .split_once('+')
752 .map_or(binary, |(version, _)| version);
753 let recorded_core = numeric_core(recorded);
754 let binary_core = numeric_core(binary);
755 match binary_core.cmp(&recorded_core) {
756 std::cmp::Ordering::Greater => Alignment::BinaryNewer,
757 std::cmp::Ordering::Less => Alignment::TargetNewer,
758 std::cmp::Ordering::Equal => {
759 let recorded_pre = recorded.split_once('-').map(|(_, pre)| pre);
764 let binary_pre = binary.split_once('-').map(|(_, pre)| pre);
765 match (recorded_pre, binary_pre) {
766 (Some(_), None) => Alignment::BinaryNewer,
767 (None, Some(_)) => Alignment::TargetNewer,
768 (None, None) => Alignment::Aligned,
769 (Some(r), Some(b)) => match prerelease_cmp(b, r) {
770 std::cmp::Ordering::Greater => Alignment::BinaryNewer,
771 std::cmp::Ordering::Less => Alignment::TargetNewer,
772 std::cmp::Ordering::Equal => Alignment::Aligned,
773 },
774 }
775 }
776 }
777}
778
779#[must_use]
782pub fn version_is_newer(candidate: &str, pinned: &str) -> bool {
783 alignment(pinned, candidate) == Alignment::BinaryNewer
784}
785
786fn prerelease_cmp(a: &str, b: &str) -> std::cmp::Ordering {
793 let numeric = |identifier: &str| identifier.bytes().all(|byte| byte.is_ascii_digit());
794 let mut left = a.split('.');
795 let mut right = b.split('.');
796 loop {
797 match (left.next(), right.next()) {
798 (None, None) => return std::cmp::Ordering::Equal,
799 (None, Some(_)) => return std::cmp::Ordering::Less,
800 (Some(_), None) => return std::cmp::Ordering::Greater,
801 (Some(x), Some(y)) => {
802 let ordering = match (numeric(x), numeric(y)) {
803 (true, true) => x.len().cmp(&y.len()).then_with(|| x.cmp(y)),
804 (true, false) => std::cmp::Ordering::Less,
805 (false, true) => std::cmp::Ordering::Greater,
806 (false, false) => x.cmp(y),
807 };
808 if ordering != std::cmp::Ordering::Equal {
809 return ordering;
810 }
811 }
812 }
813 }
814}
815
816fn numeric_core(version: &str) -> Vec<u64> {
818 let core = version.split_once('-').map_or(version, |(core, _)| core);
819 core.split('.')
820 .map(|part| part.parse::<u64>().unwrap_or(0))
821 .collect()
822}
823
824#[cfg(test)]
825mod tests {
826 use super::{
827 Alignment, CapabilityRequests, CheckoutMode, FileRecord, GitWorkflow, Manifest, Parameters,
828 Placement, ProfileSnapshot, Provider, ReleaseIntent, ReleaseMode, Style, alignment,
829 };
830 use crate::digest::Digest;
831 use crate::landing::Integration;
832 use crate::landing::Kind;
833
834 #[test]
838 fn the_manifest_schema_snapshot_holds() {
839 let manifest = Manifest {
840 schema_version: super::SCHEMA_VERSION,
841 rk_version: "0.1.0".into(),
842 origin: "init".into(),
843 landed_at: "2026-08-29T00:00:00Z".into(),
844 profile: ProfileSnapshot {
845 technologies: vec!["rust".into()],
846 forge: Some("github".into()),
847 release: ReleaseIntent {
848 mode: ReleaseMode::Automatic,
849 driver: Some("rust".into()),
850 style: Some(Style::Trunk),
851 line_prefix: Some(crate::config::LINE_PREFIX_DEFAULT.to_owned()),
852 },
853 },
854 git: GitWorkflow {
855 trunk: crate::config::TRUNK_DEFAULT.to_owned(),
856 checkout_mode: CheckoutMode::LinkedWorktree,
857 integration: Integration::Local,
858 merge_form: crate::landing::MergeForm::Squash,
859 },
860 capabilities: CapabilityRequests {
861 nix_packaging: true,
862 reporting_policy: true,
863 scorecard: true,
864 code_scanning: Some(Provider::Semgrep),
865 workflow_guards: Some(false),
866 },
867 parameters: Parameters {
868 repo: "acme/widget".into(),
869 security_contact: String::new(),
870 security_response: crate::config::RESPONSE_DEFAULT.to_owned(),
871 required_check: String::new(),
872 required_workflow: String::new(),
873 },
874 files: vec![
875 FileRecord {
876 destination: "release-plz.toml".into(),
877 kind: Kind::Seeded,
878 sha256: Digest::of(b""),
879 placement: Placement::Whole,
880 },
881 FileRecord {
882 destination: "AGENTS.md".into(),
883 kind: Kind::Rendered,
884 sha256: Digest::of(b""),
885 placement: Placement::Region,
886 },
887 ],
888 pins: std::iter::once(("release-plz".to_owned(), "0.3.160".to_owned())).collect(),
889 };
890 let empty = Digest::of(b"").to_string();
891 let text = serde_json::to_string(&manifest).expect("a manifest serializes");
892 assert_eq!(
893 text,
894 format!(
895 r#"{{"schema_version":12,"rk_version":"0.1.0","origin":"init","landed_at":"2026-08-29T00:00:00Z","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":true,"code_scanning":"semgrep","workflow_guards":false}},"parameters":{{"repo":"acme/widget","security_contact":"","security_response":"best-effort","required_check":"","required_workflow":""}},"files":[{{"destination":"release-plz.toml","kind":"seeded","sha256":"{empty}"}},{{"destination":"AGENTS.md","kind":"rendered","sha256":"{empty}","placement":"region"}}],"pins":{{"release-plz":"0.3.160"}}}}"#
896 ),
897 "a whole file omits its placement, and no retired digest field survives"
898 );
899 assert!(!text.contains("payload_sha256") && !text.contains("baseline_sha256"));
900 let release_less = Manifest {
902 profile: ProfileSnapshot {
903 technologies: vec![],
904 forge: None,
905 release: ReleaseIntent {
906 mode: ReleaseMode::None,
907 driver: None,
908 style: None,
909 line_prefix: None,
910 },
911 },
912 capabilities: CapabilityRequests {
913 nix_packaging: false,
914 reporting_policy: false,
915 scorecard: false,
916 code_scanning: None,
917 workflow_guards: Some(false),
918 },
919 parameters: Parameters {
920 repo: String::new(),
921 security_contact: String::new(),
922 security_response: crate::config::RESPONSE_DEFAULT.to_owned(),
923 required_check: String::new(),
924 required_workflow: String::new(),
925 },
926 files: vec![],
927 pins: std::collections::BTreeMap::new(),
928 ..manifest
929 };
930 assert_eq!(
931 serde_json::to_string(&release_less).expect("serializes"),
932 r#"{"schema_version":12,"rk_version":"0.1.0","origin":"init","landed_at":"2026-08-29T00:00:00Z","profile":{"technologies":[],"release":{"mode":"none"}},"git":{"trunk":"master","checkout_mode":"linked-worktree","integration":"local","merge_form":"squash"},"capabilities":{"nix_packaging":false,"reporting_policy":false,"scorecard":false,"workflow_guards":false},"parameters":{"repo":"","security_contact":"","security_response":"best-effort","required_check":"","required_workflow":""},"files":[],"pins":{}}"#
933 );
934 }
935
936 #[test]
944 fn a_schema_1_record_reads_as_branches_and_a_newer_schema_refuses() {
945 let dir = tempfile::tempdir().expect("a scratch target exists");
946 let target = camino::Utf8Path::from_path(dir.path()).expect("utf-8 path");
947 std::fs::create_dir_all(target.join(".release-kit")).expect("the record dir writes");
948 let record = |schema: u64| {
949 format!(
950 r#"{{"schema_version":{schema},"rk_version":"0.1.0","payload_sha256":"0000000000000000000000000000000000000000000000000000000000000000","origin":"init","tech":"rust","forge":"github","landed_at":"2026-08-29T00:00:00Z","parameters":{{"repo":"acme/widget","scopes":["api"]}},"files":[],"pins":{{}}}}"#
951 )
952 };
953 std::fs::write(target.join(super::MANIFEST_PATH), record(1)).expect("the record writes");
954 let manifest = super::load(target)
955 .expect("a schema-1 record loads")
956 .expect("the record exists");
957 assert_eq!(manifest.git.checkout_mode, CheckoutMode::MainWorktree);
958 assert_eq!(manifest.profile.technologies, vec!["rust".to_owned()]);
959 assert_eq!(manifest.profile.forge.as_deref(), Some("github"));
960 assert_eq!(manifest.profile.release.mode, ReleaseMode::Automatic);
961 assert_eq!(manifest.profile.release.driver.as_deref(), Some("rust"));
962 assert_eq!(
963 manifest.profile.release.style, None,
964 "a pre-style record carries no style; the upgrade demands one"
965 );
966 assert_eq!(
967 manifest.profile.release.line_prefix.as_deref(),
968 Some(crate::config::LINE_PREFIX_DEFAULT)
969 );
970 assert_eq!(manifest.git.trunk, crate::config::TRUNK_DEFAULT);
971 assert!(
972 !manifest.capabilities.nix_packaging,
973 "a pre-nix record reads as opt-out, so an upgrade adds nothing unrequested"
974 );
975 assert!(
976 manifest.capabilities.reporting_policy,
977 "an older landing carried the policy, so the record says so"
978 );
979 assert_eq!(
980 manifest.parameters.security_contact, "",
981 "a pre-policy record names no contact, which is what its policy landed"
982 );
983 assert_eq!(
984 manifest.parameters.security_response,
985 crate::config::RESPONSE_DEFAULT,
986 "a pre-policy record promises no window, which is what its policy landed"
987 );
988
989 for schema in 2..=8 {
990 std::fs::write(
991 target.join(super::MANIFEST_PATH),
992 format!(
993 r#"{{"schema_version":{schema},"rk_version":"0.1.0","payload_sha256":"0000000000000000000000000000000000000000000000000000000000000000","origin":"init","tech":"rust","forge":"github","landed_at":"2026-08-29T00:00:00Z","parameters":{{"repo":"acme/widget","workflow":"worktree","style":"lines","nix":true,"scorecard":true,"code_scanning":"semgrep","trunk":"main","line_prefix":"stable/"}},"files":[{{"destination":"AGENTS.md","kind":"rendered","sha256":"0000000000000000000000000000000000000000000000000000000000000000","baseline_sha256":"0000000000000000000000000000000000000000000000000000000000000000"}}],"pins":{{}}}}"#
994 ),
995 )
996 .expect("the record writes");
997 let manifest = super::load(target)
998 .expect("an earlier record loads")
999 .expect("the record exists");
1000 assert_eq!(manifest.schema_version, schema);
1001 assert_eq!(manifest.git.checkout_mode, CheckoutMode::LinkedWorktree);
1002 assert_eq!(manifest.git.trunk, "main");
1006 assert_eq!(manifest.profile.release.style, Some(Style::Lines));
1007 assert_eq!(
1008 manifest.profile.release.line_prefix.as_deref(),
1009 Some("stable/")
1010 );
1011 assert!(manifest.capabilities.nix_packaging && manifest.capabilities.scorecard);
1012 assert_eq!(manifest.capabilities.code_scanning, Some(Provider::Semgrep));
1013 assert_eq!(
1014 manifest.files[0].placement,
1015 if schema < super::PLACEMENT_SCHEMA {
1016 Placement::Region
1017 } else {
1018 Placement::Whole
1019 },
1020 "a block destination below the placement schema reads as a region"
1021 );
1022 let rewritten = super::render(&manifest).expect("renders");
1023 let text = String::from_utf8(rewritten).expect("text");
1024 assert!(!text.contains("baseline_sha256"), "{text}");
1025 assert!(
1026 !text.contains("\"tech\""),
1027 "the flat identity moved: {text}"
1028 );
1029 }
1030
1031 std::fs::write(target.join(super::MANIFEST_PATH), record(999)).expect("the record writes");
1032 let refused = super::load(target).expect_err("a schema-999 record refuses");
1033 assert_eq!(
1034 refused.reason(),
1035 crate::diagnostic::Reason::UnsupportedSchema
1036 );
1037 let message = refused.to_string();
1038 assert!(message.contains("999"), "{message}");
1039 assert!(message.contains(super::MANIFEST_PATH), "{message}");
1040 assert!(
1041 !message.to_lowercase().contains("bundle"),
1042 "the record schema stands alone: {message}"
1043 );
1044 }
1045
1046 #[test]
1054 fn merge_form_of_a_schema_11_record_reads_as_squash() {
1055 let dir = tempfile::tempdir().expect("a scratch target exists");
1056 let target = camino::Utf8Path::from_path(dir.path()).expect("utf-8 path");
1057 std::fs::create_dir_all(target.join(".release-kit")).expect("the record dir writes");
1058 let record = |schema: u64, git: &str| {
1059 format!(
1060 r#"{{"schema_version":{schema},"rk_version":"0.1.0","origin":"init","landed_at":"2026-08-29T00:00:00Z","profile":{{"technologies":[],"release":{{"mode":"none"}}}},"git":{{"trunk":"master","checkout_mode":"linked-worktree","integration":"local"{git}}},"capabilities":{{"nix_packaging":false,"reporting_policy":false,"scorecard":false,"workflow_guards":true}},"parameters":{{"repo":""}},"files":[],"pins":{{}}}}"#
1061 )
1062 };
1063 std::fs::write(target.join(super::MANIFEST_PATH), record(11, "")).expect("writes");
1064 let manifest = super::load(target)
1065 .expect("a schema-11 record loads")
1066 .expect("the record exists");
1067 assert_eq!(manifest.schema_version, 11);
1068 assert_eq!(manifest.git.merge_form, super::MergeForm::Squash);
1069 let text = String::from_utf8(super::render(&manifest).expect("renders")).expect("text");
1070 assert!(text.contains("\"merge_form\": \"squash\""), "{text}");
1071
1072 std::fs::write(
1073 target.join(super::MANIFEST_PATH),
1074 record(super::SCHEMA_VERSION, r#","merge_form":"rebase""#),
1075 )
1076 .expect("writes");
1077 let manifest = super::load(target)
1078 .expect("a current record loads")
1079 .expect("the record exists");
1080 assert_eq!(manifest.git.merge_form, super::MergeForm::Rebase);
1081
1082 std::fs::write(
1083 target.join(super::MANIFEST_PATH),
1084 record(super::SCHEMA_VERSION, r#","merge_form":"merge""#),
1085 )
1086 .expect("writes");
1087 let refused = super::load(target).expect_err("an unknown form refuses");
1088 assert_eq!(refused.reason(), crate::diagnostic::Reason::RecordInvalid);
1089 assert!(refused.to_string().contains("merge form"), "{refused}");
1090 }
1091
1092 #[test]
1097 fn a_record_carrying_an_uncanonical_security_parameter_refuses() {
1098 let dir = tempfile::tempdir().expect("a scratch target exists");
1099 let target = camino::Utf8Path::from_path(dir.path()).expect("utf-8 path");
1100 std::fs::create_dir_all(target.join(".release-kit")).expect("the record dir writes");
1101 for (field, value) in [
1102 ("security_contact", "team@acme.example\\nsecond line"),
1105 ("security_contact", " team@acme.example "),
1106 ("security_response", "90d"),
1107 ("security_response", "0 days"),
1108 ("security_response", "07 days"),
1109 ("security_response", "1 days"),
1110 ("security_response", ""),
1111 ] {
1112 let record = format!(
1113 r#"{{"schema_version":10,"rk_version":"0.1.0","origin":"init","landed_at":"2026-08-29T00:00:00Z","profile":{{"technologies":["rust"],"forge":"github","release":{{"mode":"automatic","driver":"rust","style":"trunk","line_prefix":"release/"}}}},"git":{{"trunk":"master","checkout_mode":"linked-worktree","integration":"local"}},"capabilities":{{"nix_packaging":false,"reporting_policy":true,"scorecard":false}},"parameters":{{"repo":"acme/widget","{field}":"{value}"}},"files":[],"pins":{{}}}}"#
1114 );
1115 std::fs::write(target.join(super::MANIFEST_PATH), record).expect("the record writes");
1116 let refused = super::load(target).expect_err("an uncanonical record refuses");
1117 assert!(refused.to_string().contains(field), "{field}: {refused}");
1118 }
1119 }
1120
1121 #[test]
1122 fn alignment_orders_versions_numerically() {
1123 assert_eq!(alignment("0.1.0", "0.1.0"), Alignment::Aligned);
1124 assert_eq!(alignment("0.1.0", "0.2.0"), Alignment::BinaryNewer);
1125 assert_eq!(alignment("0.10.0", "0.9.9"), Alignment::TargetNewer);
1126 assert_eq!(alignment("0.1.0-rc.1", "0.1.0"), Alignment::BinaryNewer);
1127 assert_eq!(alignment("0.1.0", "0.1.0-rc.1"), Alignment::TargetNewer);
1128 }
1129
1130 #[test]
1135 fn alignment_orders_numeric_prerelease_identifiers_numerically() {
1136 assert_eq!(
1137 alignment("0.1.0-rc.10", "0.1.0-rc.2"),
1138 Alignment::TargetNewer
1139 );
1140 assert_eq!(
1141 alignment("0.1.0-rc.2", "0.1.0-rc.10"),
1142 Alignment::BinaryNewer
1143 );
1144 assert_eq!(alignment("0.1.0-rc.1", "0.1.0-rc.1"), Alignment::Aligned);
1145 assert_eq!(
1146 alignment("0.1.0-alpha", "0.1.0-alpha.1"),
1147 Alignment::BinaryNewer
1148 );
1149 assert_eq!(alignment("0.1.0-1", "0.1.0-alpha"), Alignment::BinaryNewer);
1150 assert_eq!(
1151 alignment("1.0.0-100000000000000000000", "1.0.0-99999999999999999999"),
1152 Alignment::TargetNewer,
1153 "identifiers past the u64 range still compare numerically"
1154 );
1155 assert_eq!(
1156 alignment("1.0.0-99999999999999999999", "1.0.0-100000000000000000000"),
1157 Alignment::BinaryNewer
1158 );
1159 }
1160
1161 #[test]
1164 fn alignment_ignores_build_metadata() {
1165 assert_eq!(alignment("1.2.10+build", "1.2.9"), Alignment::TargetNewer);
1166 assert_eq!(alignment("1.2.9", "1.2.10+build"), Alignment::BinaryNewer);
1167 assert_eq!(alignment("1.0.0+alpha", "1.0.0+beta"), Alignment::Aligned);
1168 assert_eq!(
1169 alignment("1.2.10-rc.1+build", "1.2.10-rc.1"),
1170 Alignment::Aligned
1171 );
1172 assert_eq!(
1173 alignment("1.2.10-rc.1+build", "1.2.10"),
1174 Alignment::BinaryNewer
1175 );
1176 }
1177}