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