release-kit 0.9.13

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
//! `rk stage`: write the candidate this binary would land into a
//! disposable stage, and `rk stage clean`: remove exactly one such stage.
//!
//! The create verb reads the target the way the landing verbs do, resolves
//! the same parameters, computes the one pure projection, and materializes
//! it under the resolved output. It writes nothing inside the target, and
//! nothing about it changes what a production landing does: `rk init`,
//! `rk upgrade`, `rk adopt`, and `rk status` never read a stage. The
//! clean verb removes one directory whose own receipt names it, through
//! held descriptors, and refuses everything else.

use std::fmt::Write as _;

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

use crate::cli::stage::{StageAction, StageArgs};
use crate::diagnostic::{Diagnostic, Reason};
use crate::error::RkError;
use crate::landing::manifest::{self, Provider};
use crate::landing::{self, Params};
use crate::output::Output;
use crate::projection::{Projection, ProjectionInput, TargetEvidence};
use crate::stage::{self, OutputSource, Receipt, clean};

/// The machine form of a staging: the receipt as written, plus where the
/// output path came from and what follows.
#[derive(Debug, Serialize)]
struct Report<'a> {
    /// The receipt, its `schema` first.
    #[serde(flatten)]
    receipt: &'a Receipt,
    /// `--output`, `RK_STAGE_ROOT`, or `state root`.
    output_source: &'static str,
    /// What plausibly follows.
    next: Vec<String>,
}

/// The machine form of a cleanup.
#[derive(Debug, Serialize)]
struct CleanReport {
    /// The shape version of this document.
    schema: &'static str,
    /// The stage that was removed.
    stage_root: String,
    /// The target its receipt named.
    target: String,
    /// Whether the directory is gone.
    removed: bool,
    /// The command that recreates it.
    recovery: String,
    /// What plausibly follows.
    next: Vec<String>,
}

/// Stage the candidate, or remove a stage.
///
/// # Errors
///
/// Returns [`RkError::Missing`] for a target that is not a directory, the
/// parameter resolution's own failures, a `destructive-refusal` for a
/// stage root inside the target, a `state-drift` refusal for an existing
/// nonempty output, and [`RkError::Io`] for a write that fails;
/// `clean` returns the refusals `crate::stage::clean::validate` names.
pub fn run(args: &StageArgs) -> Result<(), RkError> {
    match &args.action {
        Some(StageAction::Clean { path, json }) => remove(Output::new(*json), path),
        Some(StageAction::Compare { root, target, json }) => {
            compare(Output::new(*json), root, target)
        }
        None => create(args),
    }
}

/// Compare a stage with its target, row by row.
fn compare(out: Output, root: &Utf8Path, target: &Utf8Path) -> Result<(), RkError> {
    if !target.is_dir() {
        return Err(RkError::missing(
            Diagnostic::new(
                Reason::TargetNotFound,
                format!("target {target} is not a directory"),
            )
            .expected("the repository the stage was taken for"),
        ));
    }
    let report = stage::compare::compare(root, target)?;
    out.result_line(format!("stage: {}", report.stage_root));
    out.result_line(format!("target: {}", report.target));
    if let Some(reason) = &report.history.reason {
        out.result_line(format!("history: {reason}"));
    }
    for row in &report.rows {
        let mut line = format!("{} {} ({}, {})", row.state, row.path, row.kind, row.word);
        if let Some(provenance) = row.provenance {
            let _ = write!(line, ", provenance {provenance}");
        }
        if let Some(edited) = row.edited_after_added {
            line.push_str(if edited {
                ", edited after the commit that brought it"
            } else {
                ", untouched since the commit that brought it"
            });
        }
        out.result_line(line);
    }
    let next = if stage::compare::rendered_equal(&report) {
        vec!["every rendered destination is equal: the landing is proven".to_owned()]
    } else {
        vec![
            "a conflict reads collision: answer it, then name it with --replace <path> on the landing verb".to_owned(),
            format!(
                "rk init, rk upgrade, or rk adopt --stage {} --target {} previews the landing",
                report.stage_root, report.target
            ),
        ]
    };
    out.next(&next);
    out.emit(&report)
}

fn create(args: &StageArgs) -> Result<(), RkError> {
    let out = Output::new(args.json);
    if !args.target.is_dir() {
        return Err(RkError::missing(
            Diagnostic::new(
                Reason::TargetNotFound,
                format!("target {} is not a directory", args.target),
            )
            .expected("an existing repository to stage the candidate for"),
        ));
    }
    let target = canonical(&args.target)?;
    let config = crate::config::load(target.as_std_path())?;
    // The record explains the target to the projection; a record this
    // binary cannot read is reported and stands aside, because a stage is
    // evidence and refusing to explain would leave the agent with less.
    let record = match manifest::load(&target) {
        Ok(record) => record,
        Err(error) => {
            out.warn(format!(
                "the landing record was not read, so the candidate is computed as a first landing: {error}"
            ));
            None
        }
    };
    let receipt_schema_version = stage::recorded_schema_version(&target);
    let params = Params::resolve(
        &target,
        &landing::Inputs {
            nix: args.nix_packaging.then_some(true),
            reporting_policy: args.reporting_policy.then_some(true),
            scorecard: args.scorecard.then_some(true),
            workflow_guards: args.workflow_guards.then_some(true),
            code_scanning: args
                .code_scanning
                .as_deref()
                .map(Provider::parse)
                .transpose()?,
            ..args.profile.inputs()?
        },
        config.as_ref(),
        record.as_ref(),
        stage::purpose(&target, config.as_ref(), record.is_some())?,
    )?;
    let evidence = TargetEvidence::gather(&target, record.as_ref())?;
    let projection = Projection::compute(&ProjectionInput {
        params: params.clone(),
        evidence,
    })?;
    landing::accepted_drift_faults(&projection, record.as_ref(), config.as_ref())?;
    let (output, source) = stage::resolve_output(args.output.as_deref(), target.as_std_path())?;
    let prepared = stage::prepare(&output, source, target.as_std_path())?;
    let composed = stage::compose(
        &projection,
        &params,
        target.as_std_path(),
        prepared.resolved(),
        record.as_ref(),
        receipt_schema_version,
    );
    stage::write(&prepared, &composed)?;
    let receipt = &composed.receipt;
    let next = vec![
        format!(
            "read {}/{} for the candidate inventory and its reasons",
            receipt.stage_root,
            stage::RECEIPT_NAME
        ),
        format!(
            "compare {}/{} with {} before anything lands",
            receipt.stage_root,
            stage::ARTIFACTS_DIR,
            receipt.target
        ),
        format!(
            "rk stage clean {} removes the stage once the landing is verified",
            receipt.stage_root
        ),
    ];
    render(out, receipt, source);
    out.next(&next);
    out.emit(&Report {
        receipt,
        output_source: source.as_str(),
        next,
    })
}

/// The human report, one fact per line.
fn render(out: Output, receipt: &Receipt, source: OutputSource) {
    out.result_line(format!("stage: {}", receipt.stage_root));
    out.result_line(format!("output: from {}", source.as_str()));
    out.result_line(format!("target: {}", receipt.target));
    let parameters = &receipt.parameters;
    out.result_line(format!(
        "parameters: {}",
        crate::commands::profile::describe(
            &parameters.profile,
            &parameters.git,
            &parameters.capabilities,
            &parameters.repo
        )
    ));
    for note in &receipt.capabilities {
        out.result_line(format!(
            "capability {}: {}{}",
            note.id,
            note.status,
            note.reason
                .as_deref()
                .map_or_else(String::new, |reason| format!(" ({reason})"))
        ));
    }
    out.result_line(format!(
        "landing record: {}",
        receipt.receipt_schema_version.map_or_else(
            || "none".to_owned(),
            |version| format!("schema_version {version}")
        )
    ));
    out.result_line(format!("candidates: {}", receipt.candidates.len()));
    for candidate in &receipt.candidates {
        out.result_line(format!(
            "  {}/{} ({}, {})",
            stage::ARTIFACTS_DIR,
            candidate.destination,
            candidate.kind.as_str(),
            candidate.placement
        ));
    }
    for note in &receipt.omissions {
        out.result_line(format!("omitted {}: {}", note.destination, note.reason));
        if let Some(action) = &note.action {
            out.result_line(format!("  action: {action}"));
        }
    }
    for note in &receipt.collisions {
        out.result_line(format!("collision {}: {}", note.destination, note.reason));
    }
    for destination in &receipt.retired {
        out.result_line(format!(
            "retired {destination}: recorded, no longer produced; target-owned from the next landing"
        ));
    }
    for moved in &receipt.secrets_moved {
        out.result_line(moved.line());
    }
    for destination in &receipt.seeded_present {
        out.result_line(format!("seeded present {destination}: a landing keeps it"));
    }
    for destination in &receipt.state_present {
        out.result_line(format!("state present {destination}: a landing keeps it"));
    }
    out.result_line(format!(
        "reference: {}",
        receipt
            .reference
            .iter()
            .map(|root| format!("{}/{root}", stage::REFERENCE_DIR))
            .collect::<Vec<_>>()
            .join(", ")
    ));
}

fn remove(out: Output, path: &Utf8Path) -> Result<(), RkError> {
    let validated = clean::validate(path.as_std_path())?;
    clean::remove(&validated)?;
    let stage_root = validated.resolved().display().to_string();
    let target = validated.target().to_owned();
    let recovery = format!("rk stage --target {target} --output {stage_root}");
    out.result_line(format!("removed {stage_root}"));
    out.result_line(format!("recovery: {recovery} stages the candidate again"));
    let next = vec![
        format!("rk status --target {target} reports what the target holds"),
        format!("rk stage --target {target} stages this binary's candidate again"),
    ];
    out.next(&next);
    out.emit(&CleanReport {
        schema: "rk.stage-clean/1",
        stage_root,
        target,
        removed: true,
        recovery,
        next,
    })
}

/// The canonical absolute target, as text.
fn canonical(target: &Utf8Path) -> Result<Utf8PathBuf, RkError> {
    let path = std::fs::canonicalize(target)?;
    Utf8PathBuf::from_path_buf(path)
        .map_err(|path| RkError::Usage(format!("the target path is not UTF-8: {}", path.display())))
}

#[cfg(test)]
mod tests {
    use super::{CleanReport, Report};
    use crate::landing::Integration;
    use crate::stage::{Parameters, Receipt, STAGE_SCHEMA};

    /// The `rk stage --json` report is the receipt with the output source
    /// and the next lines beside it, held by snapshot.
    #[test]
    fn the_stage_report_schema_snapshot_holds() {
        let receipt = Receipt {
            schema: STAGE_SCHEMA.to_owned(),
            rk_version: "0.0.0".into(),
            target: "/tmp/t".into(),
            stage_root: "/tmp/s".into(),
            parameters: Parameters {
                profile: crate::profile::ProfileSnapshot {
                    technologies: vec!["rust".into()],
                    forge: Some("github".into()),
                    release: crate::profile::ReleaseIntent {
                        mode: crate::profile::ReleaseMode::Automatic,
                        driver: Some("rust".into()),
                        style: None,
                        line_prefix: Some("release/".into()),
                        registry: None,
                        build: None,
                    },
                },
                git: crate::profile::GitWorkflow {
                    trunk: "main".into(),
                    checkout_mode: crate::landing::CheckoutMode::MainWorktree,
                    integration: Integration::Local,
                    merge_form: crate::landing::MergeForm::Squash,
                },
                capabilities: crate::profile::CapabilityRequests {
                    nix_packaging: true,
                    reporting_policy: true,
                    scorecard: false,
                    code_scanning: None,
                    workflow_guards: Some(false),
                },
                repo: "acme/widget".into(),
                security_contact: String::new(),
                required_check: String::new(),
                required_workflow: String::new(),
                dev_environment: None,
                security_response: "best-effort".into(),
                security_scope: String::new(),
            },
            capabilities: vec![],
            receipt_schema_version: None,
            candidates: vec![],
            omissions: vec![],
            collisions: vec![],
            retired: vec![],
            seeded_present: vec![],
            state_present: vec![],
            secrets_moved: Vec::new(),
            reference: vec!["CHANGELOG.md".into()],
        };
        let report = Report {
            receipt: &receipt,
            output_source: "--output",
            next: vec![
                "rk stage clean /tmp/s removes the stage once the landing is verified".into(),
            ],
        };
        assert_eq!(
            serde_json::to_string(&report).expect("a report serializes"),
            r#"{"schema":"rk.stage/7","rk_version":"0.0.0","target":"/tmp/t","stage_root":"/tmp/s","parameters":{"profile":{"technologies":["rust"],"forge":"github","release":{"mode":"automatic","driver":"rust","line_prefix":"release/"}},"git":{"trunk":"main","checkout_mode":"main-worktree","integration":"local","merge_form":"squash"},"capabilities":{"nix_packaging":true,"reporting_policy":true,"scorecard":false,"workflow_guards":false},"repo":"acme/widget","security_contact":"","security_response":"best-effort","required_check":"","required_workflow":""},"capabilities":[],"receipt_schema_version":null,"candidates":[],"omissions":[],"collisions":[],"retired":[],"seeded_present":[],"state_present":[],"secrets_moved":[],"reference":["CHANGELOG.md"],"output_source":"--output","next":["rk stage clean /tmp/s removes the stage once the landing is verified"]}"#
        );
    }

    /// The complete `rk.stage-clean/1` shape, held by snapshot.
    #[test]
    fn the_stage_clean_report_schema_snapshot_holds() {
        let report = CleanReport {
            schema: "rk.stage-clean/1",
            stage_root: "/tmp/s".into(),
            target: "/tmp/t".into(),
            removed: true,
            recovery: "rk stage --target /tmp/t --output /tmp/s".into(),
            next: vec!["rk status --target /tmp/t reports what the target holds".into()],
        };
        assert_eq!(
            serde_json::to_string(&report).expect("a report serializes"),
            r#"{"schema":"rk.stage-clean/1","stage_root":"/tmp/s","target":"/tmp/t","removed":true,"recovery":"rk stage --target /tmp/t --output /tmp/s","next":["rk status --target /tmp/t reports what the target holds"]}"#
        );
    }
}