Skip to main content

release_kit/landing/
manifest.rs

1//! The landing record: `.release-kit/manifest.json`.
2//!
3//! The record is a manifest, not a stamp: `rk status` and `rk upgrade`
4//! make decisions from it, so it earns a parser that can fail and a
5//! stated schema version — an unknown shape refuses naming the record,
6//! never a best-effort read. It is written last, after every file has
7//! landed, through the temp-plus-rename writer, and it is committed:
8//! every reader it exists for sees only committed files, and it carries
9//! digests of committed files, nothing secret and nothing
10//! machine-specific.
11
12use 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;
22
23/// Where the record lives, relative to the target root.
24pub const MANIFEST_PATH: &str = ".release-kit/manifest.json";
25
26/// The schema this binary writes.
27///
28/// It also reads schema 1 — the pre-mode record, whose absent `workflow`
29/// parameter reads as `branches` — schema 2 — the pre-style record,
30/// whose absent `style` parameter reads as none and holds an upgrade
31/// until `--style` names one — and schema 3 — the pre-nix record, whose
32/// absent `nix` parameter reads as opt-out, so an existing target's
33/// upgrade never sprouts files nobody requested — and refuses anything
34/// else by name.
35pub const SCHEMA_VERSION: u64 = 4;
36
37/// The oldest schema this binary still reads.
38const OLDEST_READABLE_SCHEMA: u64 = 1;
39
40/// The working-copy mode a landing records: a project decision, rendered
41/// into the landed blocks and changed only through the landing verbs.
42#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
43#[serde(rename_all = "lowercase")]
44pub enum Workflow {
45    /// Every code-changing branch lives in a linked worktree and the main
46    /// checkout commits nothing.
47    Worktree,
48    /// Branches are worked in the main checkout; worktrees stay available
49    /// beside them and nothing refuses either form.
50    Branches,
51}
52
53impl Workflow {
54    /// The flag, wire, and report form.
55    #[must_use]
56    pub const fn as_str(self) -> &'static str {
57        match self {
58            Self::Worktree => "worktree",
59            Self::Branches => "branches",
60        }
61    }
62
63    /// Parse a `--workflow` flag value.
64    ///
65    /// # Errors
66    ///
67    /// Returns [`RkError::Usage`] naming the two values.
68    pub fn parse(raw: &str) -> Result<Self, RkError> {
69        match raw {
70            "worktree" => Ok(Self::Worktree),
71            "branches" => Ok(Self::Branches),
72            other => Err(RkError::Usage(format!(
73                "unknown workflow '{other}'; the modes are: worktree, branches"
74            ))),
75        }
76    }
77}
78
79/// The serde default for a record from before the parameter existed.
80const fn workflow_branches() -> Workflow {
81    Workflow::Branches
82}
83
84/// The release style a landing records.
85///
86/// Whether the bot's release request stands armed to merge itself: a
87/// project decision, rendered into the landed release workflow and
88/// changed only through the landing verbs.
89#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
90#[serde(rename_all = "lowercase")]
91pub enum Style {
92    /// The trunk style: the release request carries auto-merge from
93    /// creation, so a green trunk ships itself.
94    Trunk,
95    /// The lines style: every request waits for a human's merge, because
96    /// a line's candidate is validated by hand.
97    Lines,
98}
99
100impl Style {
101    /// The flag, wire, and report form.
102    #[must_use]
103    pub const fn as_str(self) -> &'static str {
104        match self {
105            Self::Trunk => "trunk",
106            Self::Lines => "lines",
107        }
108    }
109
110    /// Parse a `--style` flag value.
111    ///
112    /// # Errors
113    ///
114    /// Returns [`RkError::Usage`] naming the two values.
115    pub fn parse(raw: &str) -> Result<Self, RkError> {
116        match raw {
117            "trunk" => Ok(Self::Trunk),
118            "lines" => Ok(Self::Lines),
119            other => Err(RkError::Usage(format!(
120                "unknown style '{other}'; the styles are: trunk, lines"
121            ))),
122        }
123    }
124}
125
126/// The record a landing writes and every target-side verb reads.
127#[derive(Debug, Serialize, Deserialize)]
128pub struct Manifest {
129    /// An integer this binary either knows or refuses on.
130    pub schema_version: u64,
131    /// The binary that produced the landing.
132    pub rk_version: String,
133    /// The aggregate payload digest from `rk payload`: which payload
134    /// actually landed, where the version alone is ambiguous.
135    pub payload_sha256: Digest,
136    /// `init` or `adopt` — how the record came to exist.
137    pub origin: String,
138    /// The technology that selected the payload.
139    pub tech: String,
140    /// The forge that selected the payload.
141    pub forge: String,
142    /// When the first landing happened; an upgrade preserves it.
143    pub landed_at: String,
144    /// Every value substituted into a `rendered` file, so a re-render is
145    /// reproducible without asking again.
146    pub parameters: Parameters,
147    /// Every landed destination with its kind and digests.
148    pub files: Vec<FileRecord>,
149    /// The registry pins the landed technology uses, copied at landing
150    /// time; `rk status` compares them offline.
151    pub pins: BTreeMap<String, String>,
152}
153
154/// The landing parameters, recorded whole.
155#[derive(Debug, Serialize, Deserialize)]
156pub struct Parameters {
157    /// The project path on the forge, recorded whole because a GitLab
158    /// project may nest below its group.
159    pub repo: String,
160    /// The Conventional Commit scopes the project accepts, rendered into
161    /// the title checks, the commit hook, and the routing block. Defaults
162    /// empty for a record from before the parameter existed; an upgrade of
163    /// such a record asks for `--scopes` once and records the answer.
164    #[serde(default)]
165    pub scopes: Vec<String>,
166    /// The working-copy mode the project chose: every code-changing branch
167    /// in a linked worktree (`worktree`), or branches worked in the main
168    /// checkout with worktrees optional beside them (`branches`). A record
169    /// predating the field reads as `branches`, so an upgrade never imposes
170    /// a guard the project did not choose.
171    #[serde(default = "workflow_branches")]
172    pub workflow: Workflow,
173    /// The release style the project chose: the bot's request armed to
174    /// merge itself (`trunk`), or every merge a human's (`lines`). A
175    /// record predating the field carries none, and an upgrade refuses
176    /// until `--style` names one: neither value is a compatibility-safe
177    /// reading of a target nobody asked.
178    #[serde(default, skip_serializing_if = "Option::is_none")]
179    pub style: Option<Style>,
180    /// Whether the landing carries the Nix capability: the seeded package
181    /// expression, the flake pair where the target had none, and the
182    /// workflow that proves the build. A record predating the field reads
183    /// as opt-out, so an upgrade adds nothing unrequested; the projection
184    /// stays reproducible from the record because this field is part of
185    /// it.
186    #[serde(default)]
187    pub nix: bool,
188}
189
190/// One landed destination.
191#[derive(Debug, Serialize, Deserialize)]
192pub struct FileRecord {
193    /// The destination, relative to the target root.
194    pub destination: String,
195    /// The declared ownership kind.
196    pub kind: Kind,
197    /// The digest of what was written — after substitution for a
198    /// `rendered` file, of the marked block for `AGENTS.md`.
199    pub sha256: Digest,
200    /// The digest of the bytes this file's comparisons start from — what
201    /// makes the three-way comparison at upgrade possible. For a
202    /// `rendered` file, the payload as it stood at landing, before
203    /// substitution; for a `seeded` file, the starting point the target
204    /// tunes away from — the seeding payload, or, where a later payload
205    /// reclassified the file from `rendered`, the rendered bytes
206    /// release-kit last wrote. Absent for `state` files, which are never
207    /// compared.
208    #[serde(skip_serializing_if = "Option::is_none")]
209    pub baseline_sha256: Option<Digest>,
210}
211
212impl Manifest {
213    /// The recorded entry for one destination, where the record names it.
214    #[must_use]
215    pub fn file(&self, destination: &str) -> Option<&FileRecord> {
216        self.files
217            .iter()
218            .find(|file| file.destination == destination)
219    }
220}
221
222/// Read the record at `target`, or `None` where no landing exists.
223///
224/// # Errors
225///
226/// The record's stated failure taxonomy: an unreadable record is a
227/// refusal naming it, a record at an unknown `schema_version` is a
228/// refusal naming the record, and one that does not parse at a known
229/// schema is a defect-class failure.
230pub fn load(target: &Utf8Path) -> Result<Option<Manifest>, RkError> {
231    let path = target.join(MANIFEST_PATH);
232    let bytes = match std::fs::read(&path) {
233        Ok(bytes) => bytes,
234        Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(None),
235        Err(e) => {
236            return Err(RkError::refusal(
237                Diagnostic::new(Reason::Io, format!("cannot read {path}: {e}"))
238                    .expected("a readable landing record")
239                    .target_state("unchanged"),
240            ));
241        }
242    };
243    let value: serde_json::Value = serde_json::from_slice(&bytes)
244        .map_err(|e| anyhow::anyhow!("{path} is not a landing record: {e}"))?;
245    // Schema 1 is the pre-mode record: it parses through the same
246    // `Parameters`, whose serde default reads the absent `workflow` as
247    // `branches`. Anything past this binary's schema refuses by name —
248    // the record decides whether a guard is landed, and an older binary
249    // must never silently ignore that.
250    let schema = value
251        .get("schema_version")
252        .and_then(serde_json::Value::as_u64);
253    if !schema.is_some_and(|version| (OLDEST_READABLE_SCHEMA..=SCHEMA_VERSION).contains(&version)) {
254        let found = schema.map_or_else(|| "none".to_owned(), |version| version.to_string());
255        return Err(RkError::refusal(
256            Diagnostic::new(
257                Reason::UnsupportedSchema,
258                format!(
259                    "{path} declares schema_version {found}, and this binary knows only {OLDEST_READABLE_SCHEMA} through {SCHEMA_VERSION}"
260                ),
261            )
262            .expected("a record this binary can read")
263            .action("run the rk release that wrote this record, or a newer one")
264            .target_state("unchanged"),
265        ));
266    }
267    let declared = schema.unwrap_or(SCHEMA_VERSION);
268    let manifest: Manifest = serde_json::from_value(value)
269        .map_err(|e| anyhow::anyhow!("{path} does not parse at schema_version {declared}: {e}"))?;
270    Ok(Some(manifest))
271}
272
273/// Write the record, last, through the temp-plus-rename writer.
274///
275/// # Errors
276///
277/// Any write failure; the destination then holds what it held.
278pub fn write(target: &Utf8Path, manifest: &Manifest) -> Result<(), RkError> {
279    let text = serde_json::to_string_pretty(manifest).map_err(anyhow::Error::from)?;
280    let path = target.join(MANIFEST_PATH);
281    atomic::write(path.as_std_path(), format!("{text}\n").as_bytes())?;
282    Ok(())
283}
284
285/// The current instant in the record's RFC 3339 form.
286#[must_use]
287pub fn now() -> String {
288    humantime::format_rfc3339_seconds(std::time::SystemTime::now()).to_string()
289}
290
291/// How a record's `rk_version` stands against this binary's.
292#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
293#[serde(rename_all = "kebab-case")]
294pub enum Alignment {
295    /// The landing came from this binary's version.
296    Aligned,
297    /// The binary is newer; `rk upgrade` takes the target forward.
298    BinaryNewer,
299    /// The landing came from a newer `rk` than this one, which an upgrade
300    /// refuses rather than downgrading.
301    TargetNewer,
302}
303
304impl Alignment {
305    /// The wire form, identical to the serde rendering.
306    #[must_use]
307    pub const fn as_str(self) -> &'static str {
308        match self {
309            Self::Aligned => "aligned",
310            Self::BinaryNewer => "binary-newer",
311            Self::TargetNewer => "target-newer",
312        }
313    }
314}
315
316/// Compare a record's version against this binary's.
317#[must_use]
318pub fn alignment(recorded: &str, binary: &str) -> Alignment {
319    // Build metadata after `+` carries no precedence.
320    let recorded = recorded
321        .split_once('+')
322        .map_or(recorded, |(version, _)| version);
323    let binary = binary
324        .split_once('+')
325        .map_or(binary, |(version, _)| version);
326    let recorded_core = numeric_core(recorded);
327    let binary_core = numeric_core(binary);
328    match binary_core.cmp(&recorded_core) {
329        std::cmp::Ordering::Greater => Alignment::BinaryNewer,
330        std::cmp::Ordering::Less => Alignment::TargetNewer,
331        std::cmp::Ordering::Equal => {
332            // Equal numeric cores: a pre-release is older than the plain
333            // release it precedes, and two pre-releases compare by semver
334            // precedence — dot-separated identifiers, numeric ones
335            // numerically and below alphanumeric ones.
336            let recorded_pre = recorded.split_once('-').map(|(_, pre)| pre);
337            let binary_pre = binary.split_once('-').map(|(_, pre)| pre);
338            match (recorded_pre, binary_pre) {
339                (Some(_), None) => Alignment::BinaryNewer,
340                (None, Some(_)) => Alignment::TargetNewer,
341                (None, None) => Alignment::Aligned,
342                (Some(r), Some(b)) => match prerelease_cmp(b, r) {
343                    std::cmp::Ordering::Greater => Alignment::BinaryNewer,
344                    std::cmp::Ordering::Less => Alignment::TargetNewer,
345                    std::cmp::Ordering::Equal => Alignment::Aligned,
346                },
347            }
348        }
349    }
350}
351
352/// Whether `candidate` is ahead of `pinned`, by the same ordering the
353/// alignment uses.
354#[must_use]
355pub fn version_is_newer(candidate: &str, pinned: &str) -> bool {
356    alignment(pinned, candidate) == Alignment::BinaryNewer
357}
358
359/// Semver pre-release precedence: identifier by identifier, numeric ones
360/// numerically and below any alphanumeric one, and — all preceding
361/// identifiers equal — the longer list wins. An all-digit identifier
362/// compares by digit count and then lexically, which is numeric order at
363/// any length — semver forbids leading zeroes — so no integer parse can
364/// overflow into a wrong answer.
365fn prerelease_cmp(a: &str, b: &str) -> std::cmp::Ordering {
366    let numeric = |identifier: &str| identifier.bytes().all(|byte| byte.is_ascii_digit());
367    let mut left = a.split('.');
368    let mut right = b.split('.');
369    loop {
370        match (left.next(), right.next()) {
371            (None, None) => return std::cmp::Ordering::Equal,
372            (None, Some(_)) => return std::cmp::Ordering::Less,
373            (Some(_), None) => return std::cmp::Ordering::Greater,
374            (Some(x), Some(y)) => {
375                let ordering = match (numeric(x), numeric(y)) {
376                    (true, true) => x.len().cmp(&y.len()).then_with(|| x.cmp(y)),
377                    (true, false) => std::cmp::Ordering::Less,
378                    (false, true) => std::cmp::Ordering::Greater,
379                    (false, false) => x.cmp(y),
380                };
381                if ordering != std::cmp::Ordering::Equal {
382                    return ordering;
383                }
384            }
385        }
386    }
387}
388
389/// The dotted numeric components before any pre-release suffix.
390fn numeric_core(version: &str) -> Vec<u64> {
391    let core = version.split_once('-').map_or(version, |(core, _)| core);
392    core.split('.')
393        .map(|part| part.parse::<u64>().unwrap_or(0))
394        .collect()
395}
396
397#[cfg(test)]
398mod tests {
399    #![allow(clippy::expect_used)]
400
401    use super::{Alignment, FileRecord, Manifest, Parameters, Style, Workflow, alignment};
402    use crate::digest::Digest;
403    use crate::landing::Kind;
404
405    /// The complete record shape at schema 4, held by snapshot: a field
406    /// rename or removal fails here and becomes a schema-version bump
407    /// instead of a silent break at every reader.
408    #[test]
409    fn the_manifest_schema_snapshot_holds() {
410        let manifest = Manifest {
411            schema_version: 4,
412            rk_version: "0.1.0".into(),
413            payload_sha256: Digest::of(b""),
414            origin: "init".into(),
415            tech: "rust".into(),
416            forge: "github".into(),
417            landed_at: "2026-08-29T00:00:00Z".into(),
418            parameters: Parameters {
419                repo: "acme/widget".into(),
420                scopes: vec!["api".into(), "cli".into()],
421                workflow: Workflow::Worktree,
422                style: Some(Style::Trunk),
423                nix: true,
424            },
425            files: vec![
426                FileRecord {
427                    destination: "release-plz.toml".into(),
428                    kind: Kind::Seeded,
429                    sha256: Digest::of(b""),
430                    baseline_sha256: Some(Digest::of(b"")),
431                },
432                FileRecord {
433                    destination: "VERSION".into(),
434                    kind: Kind::State,
435                    sha256: Digest::of(b""),
436                    baseline_sha256: None,
437                },
438            ],
439            pins: std::iter::once(("release-plz".to_owned(), "0.3.160".to_owned())).collect(),
440        };
441        let empty = Digest::of(b"").to_string();
442        assert_eq!(
443            serde_json::to_string(&manifest).expect("a manifest serializes"),
444            format!(
445                r#"{{"schema_version":4,"rk_version":"0.1.0","payload_sha256":"{empty}","origin":"init","tech":"rust","forge":"github","landed_at":"2026-08-29T00:00:00Z","parameters":{{"repo":"acme/widget","scopes":["api","cli"],"workflow":"worktree","style":"trunk","nix":true}},"files":[{{"destination":"release-plz.toml","kind":"seeded","sha256":"{empty}","baseline_sha256":"{empty}"}},{{"destination":"VERSION","kind":"state","sha256":"{empty}"}}],"pins":{{"release-plz":"0.3.160"}}}}"#
446            ),
447            "a state file must omit baseline_sha256 rather than serializing null"
448        );
449    }
450
451    /// A record written before the mode existed reads as `branches`; a
452    /// record past this binary's schema refuses by name, because the field
453    /// it cannot see decides whether a guard is landed.
454    #[test]
455    fn a_schema_1_record_reads_as_branches_and_a_newer_schema_refuses() {
456        let dir = tempfile::tempdir().expect("a scratch target exists");
457        let target = camino::Utf8Path::from_path(dir.path()).expect("utf-8 path");
458        std::fs::create_dir_all(target.join(".release-kit")).expect("the record dir writes");
459        let record = |schema: u64| {
460            format!(
461                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":{{}}}}"#
462            )
463        };
464        std::fs::write(target.join(super::MANIFEST_PATH), record(1)).expect("the record writes");
465        let manifest = super::load(target)
466            .expect("a schema-1 record loads")
467            .expect("the record exists");
468        assert_eq!(manifest.parameters.workflow, Workflow::Branches);
469        assert_eq!(
470            manifest.parameters.style, None,
471            "a pre-style record carries no style; the upgrade demands one"
472        );
473        assert!(
474            !manifest.parameters.nix,
475            "a pre-nix record reads as opt-out, so an upgrade adds nothing unrequested"
476        );
477
478        std::fs::write(target.join(super::MANIFEST_PATH), record(5)).expect("the record writes");
479        let refused = super::load(target).expect_err("a schema-5 record refuses");
480        let message = refused.to_string();
481        assert!(message.contains('5'), "{message}");
482    }
483
484    #[test]
485    fn alignment_orders_versions_numerically() {
486        assert_eq!(alignment("0.1.0", "0.1.0"), Alignment::Aligned);
487        assert_eq!(alignment("0.1.0", "0.2.0"), Alignment::BinaryNewer);
488        assert_eq!(alignment("0.10.0", "0.9.9"), Alignment::TargetNewer);
489        assert_eq!(alignment("0.1.0-rc.1", "0.1.0"), Alignment::BinaryNewer);
490        assert_eq!(alignment("0.1.0", "0.1.0-rc.1"), Alignment::TargetNewer);
491    }
492
493    /// Pre-release identifiers order by semver precedence, not by text:
494    /// `rc.10` is newer than `rc.2`, so a binary at `rc.2` must refuse a
495    /// landing from `rc.10` rather than downgrade it — at any identifier
496    /// length, so no integer width bounds the protection.
497    #[test]
498    fn alignment_orders_numeric_prerelease_identifiers_numerically() {
499        assert_eq!(
500            alignment("0.1.0-rc.10", "0.1.0-rc.2"),
501            Alignment::TargetNewer
502        );
503        assert_eq!(
504            alignment("0.1.0-rc.2", "0.1.0-rc.10"),
505            Alignment::BinaryNewer
506        );
507        assert_eq!(alignment("0.1.0-rc.1", "0.1.0-rc.1"), Alignment::Aligned);
508        assert_eq!(
509            alignment("0.1.0-alpha", "0.1.0-alpha.1"),
510            Alignment::BinaryNewer
511        );
512        assert_eq!(alignment("0.1.0-1", "0.1.0-alpha"), Alignment::BinaryNewer);
513        assert_eq!(
514            alignment("1.0.0-100000000000000000000", "1.0.0-99999999999999999999"),
515            Alignment::TargetNewer,
516            "identifiers past the u64 range still compare numerically"
517        );
518        assert_eq!(
519            alignment("1.0.0-99999999999999999999", "1.0.0-100000000000000000000"),
520            Alignment::BinaryNewer
521        );
522    }
523
524    /// Build metadata carries no precedence: it never corrupts a numeric
525    /// component and never separates two otherwise-equal versions.
526    #[test]
527    fn alignment_ignores_build_metadata() {
528        assert_eq!(alignment("1.2.10+build", "1.2.9"), Alignment::TargetNewer);
529        assert_eq!(alignment("1.2.9", "1.2.10+build"), Alignment::BinaryNewer);
530        assert_eq!(alignment("1.0.0+alpha", "1.0.0+beta"), Alignment::Aligned);
531        assert_eq!(
532            alignment("1.2.10-rc.1+build", "1.2.10-rc.1"),
533            Alignment::Aligned
534        );
535        assert_eq!(
536            alignment("1.2.10-rc.1+build", "1.2.10"),
537            Alignment::BinaryNewer
538        );
539    }
540}