release-kit 0.8.5

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
//! The pure half of `rk integrate`: the transaction's judgments and the
//! evidence a local integration leaves behind.
//!
//! This module spawns nothing. It decides what a branch name, a seat, a
//! pair of observed tips, and a stored ledger permit, and it renders and
//! parses the ledger. `crate::commands::integrate` is the half that runs
//! git and `pre-commit`.
//!
//! The evidence is clone-local, under the common git directory, because a
//! local integration is a fact about one checkout: the branch it names
//! exists in that clone alone, the prune verbs that read it act in that
//! clone alone, and a committed file would carry a per-checkout fact into
//! every other clone. The common git directory rather than a worktree's
//! own is what makes one ledger serve every linked seat.
//!
//! SATISFIES git:a-local-integration-is-a-transaction

use serde::{Deserialize, Serialize};

/// The ledger's path below the common git directory.
pub const LEDGER_PATH: &str = "rk/integrations.json";

/// The ledger's shape version.
const LEDGER_SCHEMA: &str = "rk.integrations/1";

/// One local integration, as the prune verbs read it.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct Entry {
    /// The branch that was integrated.
    pub branch: String,
    /// The branch's tip at the moment it was integrated. A prune reads
    /// this: a branch that took another commit afterwards no longer
    /// matches, and its work is not on the trunk.
    pub branch_tip: String,
    /// The squash commit this integration wrote onto the trunk.
    pub trunk_commit: String,
    /// When the integration completed, UTC.
    pub at: String,
}

/// Every local integration this clone recorded, newest last.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct Ledger {
    /// The shape version this document declares.
    #[serde(default = "ledger_schema")]
    pub schema: String,
    /// One entry per branch; a re-integration replaces its predecessor.
    #[serde(default)]
    pub entries: Vec<Entry>,
}

fn ledger_schema() -> String {
    LEDGER_SCHEMA.to_owned()
}

impl Default for Ledger {
    fn default() -> Self {
        Self {
            schema: ledger_schema(),
            entries: Vec::new(),
        }
    }
}

impl Ledger {
    /// Parse a stored ledger.
    ///
    /// An absent file is an empty ledger, because a clone that never
    /// integrated locally has recorded nothing. Malformed content refuses
    /// rather than reading as empty: an empty ledger authorizes no
    /// deletion, so a silent downgrade would be safe, but it would also
    /// hide a defect that loses real evidence.
    ///
    /// # Errors
    ///
    /// The detail of what could not be read: invalid JSON, or a schema
    /// this binary does not know.
    pub fn parse(text: &str) -> Result<Self, String> {
        if text.trim().is_empty() {
            return Ok(Self::default());
        }
        let ledger: Self = serde_json::from_str(text)
            .map_err(|source| format!("the integration ledger is not readable: {source}"))?;
        if ledger.schema != LEDGER_SCHEMA {
            return Err(format!(
                "the integration ledger declares schema {}, and this binary knows {LEDGER_SCHEMA}",
                ledger.schema
            ));
        }
        Ok(ledger)
    }

    /// The stored form, one trailing newline.
    ///
    /// # Errors
    ///
    /// A serialization defect in this binary.
    pub fn render(&self) -> Result<String, String> {
        let mut text = serde_json::to_string_pretty(self)
            .map_err(|source| format!("the integration ledger does not serialize: {source}"))?;
        text.push('\n');
        Ok(text)
    }

    /// Record one integration, replacing any earlier entry for the same
    /// branch: a branch name is reused, and the ledger answers for the
    /// branch standing now.
    pub fn record(&mut self, entry: Entry) {
        self.entries.retain(|held| held.branch != entry.branch);
        self.entries.push(entry);
    }

    /// The proof this ledger offers for one branch at one observed tip.
    ///
    /// The tip must match exactly, re-observed by the caller at the
    /// moment of action. A branch that advanced after its integration has
    /// work the trunk does not carry, so it is not a candidate at all.
    #[must_use]
    pub fn proof(&self, branch: &str, tip: &str) -> Option<&Entry> {
        self.entries
            .iter()
            .find(|entry| entry.branch == branch && entry.branch_tip == tip)
    }

    /// Whether this ledger holds any entry for one branch, at whatever
    /// tip. The prune reports use it to tell a branch that was never
    /// integrated from one that advanced after it was.
    #[must_use]
    pub fn names(&self, branch: &str) -> bool {
        self.entries.iter().any(|entry| entry.branch == branch)
    }

    /// Forget one branch's entry, after the branch itself is gone.
    pub fn forget(&mut self, branch: &str) {
        self.entries.retain(|entry| entry.branch != branch);
    }
}

/// Why a branch name cannot be integrated, or `None` where it can.
///
/// The trunk is refused before the grammar, because the trunk is the
/// destination and naming it is a different mistake from naming something
/// off the grammar. The grammar is the one owner in
/// [`crate::projection::BRANCH_GRAMMAR`], through
/// [`crate::worktree::matches_grammar`], so the desk, the landed hook,
/// and this verb judge one language.
#[must_use]
pub fn refuse_branch_name(branch: &str, trunk: &str) -> Option<String> {
    if branch == trunk {
        return Some(format!(
            "{branch} is the trunk; integration moves a short-lived branch onto it"
        ));
    }
    if !crate::worktree::matches_grammar(branch) {
        return Some(format!(
            "{branch} is neither <type>/<slug> nor <issue-id>-<slug>, so no landed hook would admit its commits"
        ));
    }
    None
}

/// How the local trunk stands against its remote.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum TrunkState {
    /// No remote answered, or the two name one commit.
    Level,
    /// The remote is ahead: the local trunk fast-forwards onto it.
    Behind,
    /// The local trunk carries integrations nobody pushed yet, which is
    /// the ordinary state under local integration.
    Ahead,
    /// Neither reaches the other.
    Diverged,
}

/// Where the local trunk stands against the remote tip, if any.
#[must_use]
pub const fn trunk_state(
    level: bool,
    local_reaches_remote: bool,
    remote_reaches_local: bool,
) -> TrunkState {
    if level {
        TrunkState::Level
    } else if local_reaches_remote {
        TrunkState::Behind
    } else if remote_reaches_local {
        TrunkState::Ahead
    } else {
        TrunkState::Diverged
    }
}

/// Why a diverged trunk cannot be integrated onto.
///
/// Only divergence refuses. A trunk behind its remote fast-forwards, and
/// a trunk ahead of it is the ordinary state under local integration:
/// integrations accumulate and the operator pushes when they decide to.
/// A divergence is never merged here, because choosing between the fetch
/// and the push is the operator's and a merge would put a second parent
/// on a trunk this convention keeps linear.
#[must_use]
pub fn refuse_trunk_state(state: TrunkState) -> Option<String> {
    matches!(state, TrunkState::Diverged).then(|| {
        "the local trunk and its remote diverged; neither reaches the other, so this command \
         refuses rather than merging them"
            .to_owned()
    })
}

/// Why the gate's verdict blocks the integration, or `None`.
#[must_use]
pub fn refuse_moved_trunk(before: &str, now: &str) -> Option<String> {
    (before != now).then(|| {
        format!(
            "the trunk moved from {} to {} while the gate ran, so the gate judged a trunk that is gone",
            short(before),
            short(now)
        )
    })
}

/// The seven-character form a report shows.
#[must_use]
pub fn short(oid: &str) -> String {
    oid.chars().take(7).collect()
}

/// The release intent a Conventional Commit message states, as the phrase
/// a warning names it by, or `None` for a type that states none.
///
/// A breaking `!` on the subject's type or a `BREAKING CHANGE:` footer
/// states a breaking change whatever the type; otherwise `feat` and `fix`
/// are the two types a release bot bumps for.
#[must_use]
pub fn release_intent(message: &str) -> Option<&'static str> {
    let mut lines = message.lines();
    let subject = lines.next()?.trim();
    let (head, _) = subject.split_once(':')?;
    let footer = lines
        .any(|line| line.starts_with("BREAKING CHANGE:") || line.starts_with("BREAKING-CHANGE:"));
    if head.ends_with('!') || footer {
        return Some("a breaking change");
    }
    let kind = head.split_once('(').map_or(head, |(kind, _)| kind);
    match kind {
        "feat" => Some("a feat type"),
        "fix" => Some("a fix type"),
        _ => None,
    }
}

/// The warning for a release-intent message over a change the package's
/// listing does not reach: release-plz will neither list the commit nor
/// count it toward a release.
///
/// SATISFIES git:a-local-integration-warns-of-an-uncounted-release
#[must_use]
pub fn uncounted_release(intent: &str, previewed: bool) -> String {
    let changes = if previewed {
        "the squash would change"
    } else {
        "the squash changes"
    };
    format!(
        "the message states {intent} and release-plz drives this target's release, but {changes} no file cargo package --list prints for the crate, so release-plz will neither list the commit in the changelog nor count it toward a release: change a file the crate ships, or retype the message with a type that states no release intent, such as docs, chore, or ci"
    )
}

#[cfg(test)]
mod tests {
    use super::{
        Entry, Ledger, refuse_branch_name, refuse_moved_trunk, refuse_trunk_state, release_intent,
        uncounted_release,
    };

    #[test]
    fn release_intent_reads_the_type_the_bang_and_the_footer() {
        assert_eq!(release_intent("feat(cli): add it"), Some("a feat type"));
        assert_eq!(release_intent("fix(cli): mend it"), Some("a fix type"));
        assert_eq!(
            release_intent("docs(cli)!: rename it"),
            Some("a breaking change")
        );
        assert_eq!(
            release_intent("chore(cli): move it\n\nBREAKING CHANGE: the flag is gone"),
            Some("a breaking change")
        );
        assert_eq!(
            release_intent("chore(cli): move it\n\nBREAKING-CHANGE: the flag is gone"),
            Some("a breaking change")
        );
        assert_eq!(release_intent("docs(cli): explain it"), None);
        assert_eq!(release_intent("refactor(cli): tidy it"), None);
        assert_eq!(release_intent("no shape at all"), None);
    }

    #[test]
    fn the_uncounted_release_warning_names_both_fixes() {
        let preview = uncounted_release("a feat type", true);
        assert!(preview.contains("the squash would change"), "{preview}");
        let applied = uncounted_release("a fix type", false);
        assert!(applied.contains("the squash changes no file"), "{applied}");
        for needle in [
            "neither list the commit in the changelog nor count it toward a release",
            "change a file the crate ships",
            "retype the message",
        ] {
            assert!(applied.contains(needle), "{applied}");
        }
    }

    fn entry(branch: &str, tip: &str) -> Entry {
        Entry {
            branch: branch.to_owned(),
            branch_tip: tip.to_owned(),
            trunk_commit: "c".repeat(40),
            at: "2026-09-15T00:00:00Z".to_owned(),
        }
    }

    #[test]
    fn an_absent_ledger_reads_as_empty_and_proves_nothing() {
        let ledger = Ledger::parse("").expect("absence is empty");
        assert!(ledger.entries.is_empty());
        assert_eq!(ledger.proof("feat/x", &"a".repeat(40)), None);
        assert!(!ledger.names("feat/x"));
    }

    #[test]
    fn a_ledger_round_trips_and_refuses_an_unknown_schema() {
        let mut ledger = Ledger::default();
        ledger.record(entry("feat/x", &"a".repeat(40)));
        let text = ledger.render().expect("it serializes");
        assert_eq!(Ledger::parse(&text).expect("it reads back"), ledger);
        let error = Ledger::parse(r#"{"schema":"rk.integrations/99","entries":[]}"#)
            .expect_err("a newer schema refuses");
        assert!(error.contains("rk.integrations/1"), "{error}");
        let error = Ledger::parse("{").expect_err("malformed content refuses");
        assert!(error.contains("not readable"), "{error}");
    }

    #[test]
    fn a_proof_needs_the_tip_the_integration_recorded() {
        let mut ledger = Ledger::default();
        let tip = "a".repeat(40);
        ledger.record(entry("feat/x", &tip));
        assert!(ledger.proof("feat/x", &tip).is_some());
        // One more commit after the integration: the work is not on the
        // trunk, so the branch is not a candidate at all.
        assert_eq!(ledger.proof("feat/x", &"b".repeat(40)), None);
        assert!(ledger.names("feat/x"));
        // Evidence for one branch never confirms another.
        assert_eq!(ledger.proof("feat/y", &tip), None);
    }

    #[test]
    fn a_re_integration_replaces_its_predecessor() {
        let mut ledger = Ledger::default();
        ledger.record(entry("feat/x", &"a".repeat(40)));
        ledger.record(entry("feat/x", &"b".repeat(40)));
        assert_eq!(ledger.entries.len(), 1);
        assert!(ledger.proof("feat/x", &"b".repeat(40)).is_some());
        ledger.forget("feat/x");
        assert!(ledger.entries.is_empty());
    }

    #[test]
    fn the_trunk_and_a_misshapen_branch_each_refuse_by_name() {
        assert!(
            refuse_branch_name("master", "master")
                .expect("the trunk refuses")
                .contains("trunk")
        );
        let error = refuse_branch_name("wip", "master").expect("the grammar refuses");
        assert!(error.contains("<type>/<slug>"), "{error}");
        assert_eq!(refuse_branch_name("feat/x", "master"), None);
        assert_eq!(refuse_branch_name("123-slug", "master"), None);
    }

    #[test]
    fn only_a_diverged_trunk_refuses() {
        use super::{TrunkState, trunk_state};
        // level, behind, and ahead all proceed; a trunk ahead of its
        // remote is the ordinary state under local integration.
        assert_eq!(trunk_state(true, false, false), TrunkState::Level);
        assert_eq!(trunk_state(false, true, false), TrunkState::Behind);
        assert_eq!(trunk_state(false, false, true), TrunkState::Ahead);
        assert_eq!(trunk_state(false, false, false), TrunkState::Diverged);
        for state in [TrunkState::Level, TrunkState::Behind, TrunkState::Ahead] {
            assert_eq!(refuse_trunk_state(state), None, "{state:?}");
        }
        let error = refuse_trunk_state(TrunkState::Diverged).expect("divergence refuses");
        assert!(error.contains("refuses rather than merging"), "{error}");
    }

    #[test]
    fn a_trunk_that_moved_under_the_gate_refuses() {
        assert_eq!(refuse_moved_trunk("a", "a"), None);
        let error =
            refuse_moved_trunk(&"a".repeat(40), &"b".repeat(40)).expect("a moved trunk refuses");
        assert!(error.contains("aaaaaaa"), "{error}");
        assert!(error.contains("bbbbbbb"), "{error}");
    }
}