Skip to main content

release_kit/
stage.rs

1//! The candidate stage: this binary's projection for one target,
2//! materialized on disk beside the knowledge that explains it.
3//!
4//! A stage is evidence, never an installation transaction. `rk stage`
5//! gathers the target's evidence, computes the one pure [`Projection`],
6//! and writes the complete proposed bytes of every candidate under
7//! `artifacts/`, the installed binary's changelog, guidance, method,
8//! bindings, runbooks, forge notes, setup skill, and the shared resources
9//! that skill routes to under `reference/`, and one explanatory receipt,
10//! `stage.json`. It writes nothing inside the target. Production landing
11//! reads no byte of it, and only `rk stage clean` removes it.
12//!
13//! The stage is built whole under a fresh sibling of its resolved path and
14//! renamed into place after the receipt, so a stage that is visible is
15//! complete. The default root below the private state directory and the
16//! receipt are created owner-only.
17
18pub mod clean;
19
20use std::borrow::Cow;
21use std::fs::{self, File};
22use std::io::Write as _;
23use std::os::unix::fs::{DirBuilderExt as _, OpenOptionsExt as _, PermissionsExt as _};
24use std::path::{Path, PathBuf};
25
26use camino::Utf8Path;
27use serde::{Deserialize, Serialize};
28
29use crate::applog;
30use crate::diagnostic::{Diagnostic, Reason};
31use crate::digest::Digest;
32use crate::embedded;
33use crate::error::RkError;
34use crate::landing::manifest::Manifest;
35use crate::landing::{Kind, Params};
36use crate::profile::{CapabilityRequests, GitWorkflow, ProfileSnapshot};
37use crate::projection::{Placement, Projection};
38use crate::skills;
39
40/// The shape version of the stage receipt and of the `rk stage` report.
41pub const STAGE_SCHEMA: &str = "rk.stage/4";
42
43/// The receipt's name at the stage root.
44pub const RECEIPT_NAME: &str = "stage.json";
45
46/// The variable naming an alternative base for the default stage path.
47pub const OUTPUT_ROOT_VAR: &str = "RK_STAGE_ROOT";
48
49/// The directory below the state root that holds the default stages.
50pub const STAGES_DIR: &str = "stages";
51
52/// The directory below the stage root holding the candidate tree.
53pub const ARTIFACTS_DIR: &str = "artifacts";
54
55/// The directory below the stage root holding the installed knowledge.
56pub const REFERENCE_DIR: &str = "reference";
57
58/// The skill whose installed text and routed resources the reference
59/// tree carries.
60pub const SETUP_SKILL: &str = "rk-setup";
61
62/// The interruption proof's seam: the stage-relative path after which a
63/// materialization stops on purpose, as if the write after it had failed.
64pub const INTERRUPT_VAR: &str = "RK_STAGE_INTERRUPT_AT";
65
66/// Every reference root a stage writes, in the order the receipt lists
67/// them.
68pub const REFERENCE_ROOTS: [&str; 8] = [
69    "CHANGELOG.md",
70    "guidance",
71    "method",
72    "bindings",
73    "runbooks",
74    "forges",
75    "skills/rk-setup",
76    "skill-shared",
77];
78
79/// The explanatory receipt a stage carries, and the document `rk stage
80/// --json` reports. Metadata only: no later command reads it as input.
81#[derive(Debug, Clone, Serialize, Deserialize)]
82pub struct Receipt {
83    /// The shape version of this document.
84    pub schema: String,
85    /// The binary that staged.
86    pub rk_version: String,
87    /// The canonical absolute path of the target that was read.
88    pub target: String,
89    /// The canonical absolute path of the stage itself.
90    pub stage_root: String,
91    /// The resolved landing parameters the projection ran under.
92    pub parameters: Parameters,
93    /// Every capability the catalog answered, in catalog order.
94    pub capabilities: Vec<CapabilityNote>,
95    /// The `schema_version` the target's landing record declares, where
96    /// the record is present and readable as JSON.
97    pub receipt_schema_version: Option<u64>,
98    /// One entry per candidate destination under `artifacts/`.
99    pub candidates: Vec<CandidateEntry>,
100    /// The destinations the target's own state withholds.
101    pub omissions: Vec<Note>,
102    /// The block destinations whose document offers the block no place.
103    pub collisions: Vec<Note>,
104    /// The destinations the landing record names that this projection no
105    /// longer produces: target-owned from the next landing on.
106    pub retired: Vec<String>,
107    /// The recorded `seeded` destinations present on disk, which a
108    /// production landing preserves.
109    pub seeded_present: Vec<String>,
110    /// The recorded `state` destinations present on disk, which a
111    /// production landing preserves.
112    pub state_present: Vec<String>,
113    /// The reference roots written under `reference/`.
114    pub reference: Vec<String>,
115}
116
117/// The resolved landing parameters, stated whole.
118#[derive(Debug, Clone, Serialize, Deserialize)]
119pub struct Parameters {
120    /// What the project is.
121    pub profile: ProfileSnapshot,
122    /// How topic branches reach the trunk.
123    pub git: GitWorkflow,
124    /// Which optional products the target requested.
125    pub capabilities: CapabilityRequests,
126    /// The project path on the forge, empty where the project has none.
127    pub repo: String,
128    /// The security contact, empty for the forge's own wording.
129    pub security_contact: String,
130    /// The acknowledgment window.
131    pub security_response: String,
132}
133
134impl From<&Params> for Parameters {
135    fn from(params: &Params) -> Self {
136        Self {
137            profile: params.profile().clone(),
138            git: params.git().clone(),
139            capabilities: params.capabilities().clone(),
140            repo: params.repo().to_owned(),
141            security_contact: params.security_contact().to_owned(),
142            security_response: params.security_response().to_owned(),
143        }
144    }
145}
146
147/// One candidate under `artifacts/`.
148#[derive(Debug, Clone, Serialize, Deserialize)]
149pub struct CandidateEntry {
150    /// The destination, relative to the target root and to `artifacts/`.
151    pub destination: String,
152    /// Who owns the bytes after landing.
153    pub kind: Kind,
154    /// `whole` for a whole file, `region` for a marked region whose
155    /// artifact is the complete spliced document.
156    pub placement: String,
157    /// The digest of the complete artifact bytes.
158    pub sha256: Digest,
159    /// The digest of the rendered region alone, for a region destination.
160    #[serde(default, skip_serializing_if = "Option::is_none")]
161    pub region_sha256: Option<Digest>,
162    /// The embedded source paths the candidate was rendered from.
163    pub sources: Vec<String>,
164}
165
166/// One destination named with a reason.
167#[derive(Debug, Clone, Serialize, Deserialize)]
168pub struct Note {
169    /// The destination.
170    pub destination: String,
171    /// Why it is listed here.
172    pub reason: String,
173    /// The one edit the operator makes to activate what the landing
174    /// withheld, where the omission is an activation rather than a shape.
175    #[serde(default, skip_serializing_if = "Option::is_none")]
176    pub action: Option<String>,
177}
178
179/// One capability's answer, as the receipt carries it.
180#[derive(Debug, Clone, Serialize, Deserialize)]
181pub struct CapabilityNote {
182    /// The capability id.
183    pub id: String,
184    /// Its status: selected, not-requested, not-applicable, unavailable,
185    /// unknown, or withheld.
186    pub status: String,
187    /// Why, for every status but selected.
188    #[serde(default, skip_serializing_if = "Option::is_none")]
189    pub reason: Option<String>,
190    /// The operator's one edit, for a withheld capability.
191    #[serde(default, skip_serializing_if = "Option::is_none")]
192    pub action: Option<String>,
193    /// The destinations it lands, sorted.
194    pub destinations: Vec<String>,
195}
196
197impl CapabilityNote {
198    /// The note for one selection, with the destinations the projection
199    /// landed under it.
200    #[must_use]
201    pub fn of(selection: &crate::profile::catalog::Selection, projection: &Projection) -> Self {
202        Self {
203            id: selection.id.to_owned(),
204            status: selection.status.as_str().to_owned(),
205            reason: selection.reason.clone(),
206            action: selection.action.clone(),
207            destinations: projection
208                .candidates
209                .iter()
210                .filter(|candidate| candidate.capability == selection.id)
211                .map(|candidate| candidate.destination.clone())
212                .collect(),
213        }
214    }
215}
216
217/// Where the resolved output path came from.
218#[derive(Debug, Clone, Copy, PartialEq, Eq)]
219pub enum OutputSource {
220    /// `--output` named it.
221    Flag,
222    /// `RK_STAGE_ROOT` supplied the base.
223    Environment,
224    /// The private state root supplied the base.
225    StateRoot,
226}
227
228impl OutputSource {
229    /// The report form.
230    #[must_use]
231    pub const fn as_str(self) -> &'static str {
232        match self {
233            Self::Flag => "--output",
234            Self::Environment => "RK_STAGE_ROOT",
235            Self::StateRoot => "state root",
236        }
237    }
238}
239
240/// The filesystem-safe key naming one target below a stage base.
241///
242/// The digest of the canonical target path, the same derivation the
243/// target lock uses, so a path carrying a separator cannot name another
244/// target's stage.
245#[must_use]
246pub fn target_key(canonical_target: &Path) -> String {
247    Digest::of(canonical_target.display().to_string().as_bytes()).to_string()
248}
249
250/// Resolve the output directory: `--output` first, then a target and
251/// version directory below `RK_STAGE_ROOT`, then the same below the
252/// private state root.
253///
254/// # Errors
255///
256/// Returns a `prerequisite-unmet` refusal where neither a flag, the
257/// variable, nor a state root names a base.
258pub fn resolve_output(
259    flag: Option<&Utf8Path>,
260    canonical_target: &Path,
261) -> Result<(PathBuf, OutputSource), RkError> {
262    if let Some(flag) = flag {
263        let path = if flag.is_absolute() {
264            flag.as_std_path().to_path_buf()
265        } else {
266            std::env::current_dir()?.join(flag.as_std_path())
267        };
268        return Ok((path, OutputSource::Flag));
269    }
270    let leaf = Path::new(&target_key(canonical_target)).join(env!("CARGO_PKG_VERSION"));
271    if let Some(base) = std::env::var_os(OUTPUT_ROOT_VAR).filter(|value| !value.is_empty()) {
272        let base = PathBuf::from(base);
273        let base = if base.is_absolute() {
274            base
275        } else {
276            std::env::current_dir()?.join(base)
277        };
278        return Ok((base.join(leaf), OutputSource::Environment));
279    }
280    let Some(root) = applog::state_root() else {
281        return Err(RkError::refusal(
282            Diagnostic::new(
283                Reason::PrerequisiteUnmet,
284                "no state root resolves, so the stage has nowhere to go, and nothing was written",
285            )
286            .expected("--output <dir>, RK_STAGE_ROOT, or a state root under XDG_STATE_HOME or HOME")
287            .action("pass --output <dir>, or set XDG_STATE_HOME or HOME, and run it again")
288            .target_state("unchanged"),
289        ));
290    };
291    Ok((root.join(STAGES_DIR).join(leaf), OutputSource::StateRoot))
292}
293
294/// An output path checked and made ready: its parent exists and is
295/// canonical, the resolved stage root is known, and nothing nonempty
296/// stands there.
297#[derive(Debug)]
298pub struct Prepared {
299    parent: PathBuf,
300    name: std::ffi::OsString,
301    resolved: PathBuf,
302    owner_only: bool,
303}
304
305impl Prepared {
306    /// The canonical absolute path the stage will stand at.
307    #[must_use]
308    pub fn resolved(&self) -> &Path {
309        &self.resolved
310    }
311}
312
313/// The path `output` will stand at once created, computed without
314/// creating any component: the deepest existing ancestor canonicalized,
315/// the remaining components appended as named.
316///
317/// # Errors
318///
319/// A refusal for a remaining component that is `..`, which no stage path
320/// may carry, and [`RkError::Io`] where the existing ancestor cannot be
321/// canonicalized.
322fn eventual(output: &Path) -> Result<PathBuf, RkError> {
323    let mut existing = output;
324    let mut rest: Vec<&std::ffi::OsStr> = Vec::new();
325    loop {
326        match fs::symlink_metadata(existing) {
327            Ok(_) => break,
328            Err(error) if error.kind() == std::io::ErrorKind::NotFound => {}
329            Err(error) => return Err(error.into()),
330        }
331        let Some(name) = existing.file_name() else {
332            break;
333        };
334        rest.push(name);
335        existing = existing.parent().unwrap_or_else(|| Path::new("/"));
336    }
337    let mut path = fs::canonicalize(if existing.as_os_str().is_empty() {
338        Path::new(".")
339    } else {
340        existing
341    })?;
342    for name in rest.into_iter().rev() {
343        if name == ".." {
344            return Err(RkError::refusal(
345                Diagnostic::new(
346                    Reason::Usage,
347                    format!(
348                        "{} climbs through a directory that does not exist yet, and nothing was written",
349                        output.display()
350                    ),
351                )
352                .expected("an output path whose absent components are plain names")
353                .target_state("unchanged"),
354            ));
355        }
356        if name != "." {
357            path.push(name);
358        }
359    }
360    Ok(path)
361}
362
363/// Resolve where the stage will stand, refuse a stage inside the target,
364/// refuse an existing nonempty output, create the parent, and name the
365/// canonical stage root.
366///
367/// Nothing is created before the stage root is known and judged against
368/// the target: a stage below the target would be a write inside the
369/// repository this verb promises to leave alone, whichever of the flag,
370/// the variable, or the state root put it there. Below the state root
371/// every directory this creates is owner-only, and a base that turns out
372/// to be a link or another file type refuses, because a private stage
373/// under a directory somebody else controls is not private.
374///
375/// # Errors
376///
377/// Returns a `destructive-refusal` for a stage root at or below the
378/// target, a `state-drift` refusal for an existing nonempty output, a
379/// refusal for an output whose final component is no name, and
380/// [`RkError::Io`] for a parent that cannot be created or read.
381pub fn prepare(
382    output: &Path,
383    source: OutputSource,
384    canonical_target: &Path,
385) -> Result<Prepared, RkError> {
386    let name = output
387        .file_name()
388        .filter(|name| *name != "." && *name != "..")
389        .ok_or_else(|| {
390            RkError::refusal(
391                Diagnostic::new(
392                    Reason::Usage,
393                    format!("{} names no directory to stage into", output.display()),
394                )
395                .expected("an output path ending in a directory name")
396                .target_state("unchanged"),
397            )
398        })?
399        .to_owned();
400    let eventual = eventual(output)?;
401    if eventual.starts_with(canonical_target) {
402        return Err(RkError::refusal(
403            Diagnostic::new(
404                Reason::DestructiveRefusal,
405                format!(
406                    "the stage would stand at {}, inside the target {}, and nothing was written",
407                    eventual.display(),
408                    canonical_target.display()
409                ),
410            )
411            .expected("a stage root outside the target repository")
412            .action(match source {
413                OutputSource::Flag => "pass an --output outside the target".to_owned(),
414                OutputSource::Environment => {
415                    format!("point {OUTPUT_ROOT_VAR} outside the target, or pass --output")
416                }
417                OutputSource::StateRoot => {
418                    "move the state root outside the target, or pass --output".to_owned()
419                }
420            })
421            .target_state("unchanged"),
422        ));
423    }
424    let parent = output
425        .parent()
426        .filter(|parent| !parent.as_os_str().is_empty())
427        .map_or_else(|| PathBuf::from("/"), Path::to_path_buf);
428    let owner_only = source == OutputSource::StateRoot;
429    if owner_only {
430        create_owner_only(&parent)?;
431    } else {
432        fs::create_dir_all(&parent)?;
433    }
434    let parent = fs::canonicalize(&parent)?;
435    let resolved = parent.join(&name);
436    match fs::symlink_metadata(&resolved) {
437        Err(error) if error.kind() == std::io::ErrorKind::NotFound => {}
438        Err(error) => return Err(error.into()),
439        Ok(metadata) if metadata.is_dir() && fs::read_dir(&resolved)?.next().is_none() => {}
440        Ok(_) => {
441            return Err(RkError::refusal(
442                Diagnostic::new(
443                    Reason::StateDrift,
444                    format!(
445                        "{} already exists and is not empty, and nothing was written",
446                        resolved.display()
447                    ),
448                )
449                .expected("an absent or empty output directory")
450                .action(format!(
451                    "rk stage clean {} removes a stage that stands there; otherwise pass another --output",
452                    resolved.display()
453                ))
454                .target_state("unchanged"),
455            ));
456        }
457    }
458    Ok(Prepared {
459        parent,
460        name,
461        resolved,
462        owner_only,
463    })
464}
465
466/// Create the default base for a stage owner-only, component by
467/// component, and refuse a component that is a link or not a directory.
468fn create_owner_only(dir: &Path) -> std::io::Result<()> {
469    fs::DirBuilder::new()
470        .recursive(true)
471        .mode(0o700)
472        .create(dir)?;
473    // The state root itself belongs to every run-shaped artifact; the
474    // stage base below it and every component under that are private.
475    let Some(state_root) = applog::state_root() else {
476        return Ok(());
477    };
478    let base = state_root.join(STAGES_DIR);
479    let Ok(rest) = dir.strip_prefix(&base) else {
480        return Ok(());
481    };
482    let mut current = base;
483    restrict(&current)?;
484    for component in rest {
485        current.push(component);
486        restrict(&current)?;
487    }
488    Ok(())
489}
490
491/// Make one existing base component private, refusing a link or another
492/// file type.
493fn restrict(dir: &Path) -> std::io::Result<()> {
494    let metadata = fs::symlink_metadata(dir)?;
495    if metadata.file_type().is_symlink() || !metadata.is_dir() {
496        return Err(std::io::Error::new(
497            std::io::ErrorKind::InvalidData,
498            format!("stage base is not a directory: {}", dir.display()),
499        ));
500    }
501    fs::set_permissions(dir, fs::Permissions::from_mode(0o700))
502}
503
504/// A stage composed and ready to write: every file with its
505/// stage-relative path, and the receipt.
506#[derive(Debug)]
507pub struct Composed {
508    /// Every file under the stage root except the receipt, sorted by path.
509    pub files: Vec<(String, Cow<'static, [u8]>)>,
510    /// The receipt, written last.
511    pub receipt: Receipt,
512}
513
514/// Compose the stage for `projection`, rooted at `stage_root`, from the
515/// projection, the resolved parameters, the target's record, and this
516/// binary's embedded knowledge.
517#[must_use]
518pub fn compose(
519    projection: &Projection,
520    params: &Params,
521    canonical_target: &Path,
522    stage_root: &Path,
523    record: Option<&Manifest>,
524    receipt_schema_version: Option<u64>,
525) -> Composed {
526    let mut files: Vec<(String, Cow<'static, [u8]>)> = Vec::new();
527    let mut candidates = Vec::new();
528    for candidate in &projection.candidates {
529        files.push((
530            format!("{ARTIFACTS_DIR}/{}", candidate.destination),
531            Cow::Owned(candidate.bytes.clone()),
532        ));
533        candidates.push(CandidateEntry {
534            destination: candidate.destination.clone(),
535            kind: candidate.kind,
536            placement: match candidate.placement {
537                Placement::Whole => "whole",
538                Placement::Region { .. } => "region",
539            }
540            .to_owned(),
541            sha256: Digest::of(&candidate.bytes),
542            region_sha256: candidate.region.as_deref().map(Digest::of),
543            sources: candidate.sources.clone(),
544        });
545    }
546    for (path, bytes) in reference_files() {
547        files.push((format!("{REFERENCE_DIR}/{path}"), Cow::Borrowed(bytes)));
548    }
549    files.sort_by(|a, b| a.0.cmp(&b.0));
550    let produced = |destination: &str| {
551        projection
552            .candidates
553            .iter()
554            .any(|candidate| candidate.destination == destination)
555            || projection
556                .omissions
557                .iter()
558                .any(|omission| omission.destination == destination)
559    };
560    let mut retired = Vec::new();
561    let mut seeded_present = Vec::new();
562    let mut state_present = Vec::new();
563    if let Some(record) = record {
564        for file in &record.files {
565            if !produced(&file.destination) {
566                retired.push(file.destination.clone());
567            }
568            let present = fs::symlink_metadata(canonical_target.join(&file.destination)).is_ok();
569            match file.kind {
570                Kind::Seeded if present => seeded_present.push(file.destination.clone()),
571                Kind::State if present => state_present.push(file.destination.clone()),
572                Kind::Rendered | Kind::Seeded | Kind::State => {}
573            }
574        }
575    }
576    let receipt = Receipt {
577        schema: STAGE_SCHEMA.to_owned(),
578        rk_version: env!("CARGO_PKG_VERSION").to_owned(),
579        target: canonical_target.display().to_string(),
580        stage_root: stage_root.display().to_string(),
581        parameters: Parameters::from(params),
582        capabilities: projection
583            .capabilities
584            .iter()
585            .map(|selection| CapabilityNote::of(selection, projection))
586            .collect(),
587        receipt_schema_version,
588        candidates,
589        omissions: projection
590            .omissions
591            .iter()
592            .map(|omission| Note {
593                destination: omission.destination.clone(),
594                reason: omission.reason.clone(),
595                action: omission.action.clone(),
596            })
597            .collect(),
598        collisions: projection
599            .collisions
600            .iter()
601            .map(|collision| Note {
602                action: None,
603                destination: collision.destination.clone(),
604                reason: collision.reason.clone(),
605            })
606            .collect(),
607        retired,
608        seeded_present,
609        state_present,
610        reference: REFERENCE_ROOTS
611            .iter()
612            .map(|root| (*root).to_owned())
613            .collect(),
614    };
615    Composed { files, receipt }
616}
617
618/// Every file the reference tree carries, as `(path, bytes)` below
619/// `reference/`.
620///
621/// From the embedded sources and from nowhere else: the changelog, every
622/// guidance file, the method, the bindings, the runbooks, the forge
623/// documents, the setup skill as installed, and the shared resources that
624/// skill names.
625#[must_use]
626pub fn reference_files() -> Vec<(String, &'static [u8])> {
627    let mut out: Vec<(String, &'static [u8])> =
628        vec![("CHANGELOG.md".to_owned(), embedded::CHANGELOG.as_bytes())];
629    for (root, dir) in [
630        ("guidance", &embedded::GUIDANCE),
631        ("method", &embedded::METHOD),
632        ("bindings", &embedded::BINDINGS),
633        ("runbooks", &embedded::RUNBOOKS),
634        ("forges", &embedded::FORGES),
635    ] {
636        for (path, bytes) in embedded::walk(dir) {
637            out.push((format!("{root}/{path}"), bytes));
638        }
639    }
640    let prefix = format!("{SETUP_SKILL}/");
641    let mut skill_text = String::new();
642    for (path, bytes) in embedded::walk(&embedded::SKILLS) {
643        if path.starts_with(&prefix) {
644            if path == format!("{prefix}SKILL.md") {
645                skill_text = String::from_utf8_lossy(bytes).into_owned();
646            }
647            out.push((format!("skills/{path}"), bytes));
648        }
649    }
650    for artifact in skills::shared() {
651        if skill_text.contains(&artifact.path) {
652            out.push((format!("skill-shared/{}", artifact.path), artifact.bytes));
653        }
654    }
655    out
656}
657
658/// How many sibling names a write tries before it refuses.
659const TEMP_ATTEMPTS: u32 = 8;
660
661/// The proof's seam for the failure cleanup: a directory where a stopped
662/// write announces `stopped` before it quarantines its sibling and waits
663/// for `proceed`.
664pub const PAUSE_BEFORE_CLEANUP_VAR: &str = "RK_STAGE_PAUSE_BEFORE_CLEANUP";
665
666/// The prefix of a quarantined sibling's name.
667const QUARANTINE_PREFIX: &str = ".rk-stage-quarantine-";
668
669/// The prefix of a finished sibling's claim name, the unpredictable name
670/// it is judged under before it is published.
671const CLAIM_PREFIX: &str = ".rk-stage-claim-";
672
673/// The proof's seam before publication: a finished write announces
674/// `finished` under this directory before it claims its sibling and
675/// waits for `proceed`.
676pub const PAUSE_BEFORE_LAND_VAR: &str = "RK_STAGE_PAUSE_BEFORE_LAND";
677
678/// The proof's seam after publication.
679///
680/// A write announces `landed` under this directory after the rename and
681/// before it checks that the public parent pathname still names the held
682/// parent, then waits for `proceed`.
683pub const PAUSE_AFTER_LAND_VAR: &str = "RK_STAGE_PAUSE_AFTER_LAND";
684
685/// The sibling name for one attempt: the first names this process alone,
686/// and every retry adds a nonce, so an entry somebody else left under the
687/// first name is stepped around rather than reused.
688fn temp_name(name: &std::ffi::OsStr, attempt: u32) -> std::ffi::OsString {
689    let mut out = std::ffi::OsString::from(format!(".rk-stage-{}", std::process::id()));
690    if attempt > 0 {
691        out.push(format!("-{:08x}", crate::held::nonce() & 0xffff_ffff));
692    }
693    out.push(".");
694    out.push(name);
695    out
696}
697
698/// The sibling this write created and holds: its name under the held
699/// parent, the open directory, and the identity the directory had the
700/// moment it was opened, which every later act on it is judged against.
701struct Temp {
702    name: std::ffi::OsString,
703    dir: File,
704    identity: crate::held::Identity,
705}
706
707/// Create the fresh sibling this write owns, exclusively, and hold it
708/// open: a name that already exists is never entered or removed, and the
709/// next name is tried instead, a bounded number of times.
710fn create_temp(prepared: &Prepared, parent: &File) -> std::io::Result<Temp> {
711    let mut builder = fs::DirBuilder::new();
712    if prepared.owner_only {
713        builder.mode(0o700);
714    }
715    let base = crate::held::proc_path(parent);
716    for attempt in 0..TEMP_ATTEMPTS {
717        let name = temp_name(&prepared.name, attempt);
718        match builder.create(base.join(&name)) {
719            Ok(()) => {
720                let dir = crate::held::open_dir(&base.join(&name))?;
721                let identity = crate::held::Identity::of(&dir.metadata()?);
722                return Ok(Temp {
723                    name,
724                    dir,
725                    identity,
726                });
727            }
728            Err(error) if error.kind() == std::io::ErrorKind::AlreadyExists => {}
729            Err(error) => return Err(error),
730        }
731    }
732    Err(std::io::Error::new(
733        std::io::ErrorKind::AlreadyExists,
734        format!(
735            "every sibling name for the stage below {} is taken, and nothing was written or removed",
736            prepared.parent.display()
737        ),
738    ))
739}
740
741/// Write the composed stage whole, then rename it into place.
742///
743/// Every file goes into a fresh sibling of the resolved root that this
744/// write created exclusively and holds open, written through the held
745/// descriptor rather than by name; the receipt goes last and owner-only;
746/// then, once the entry under the sibling's name still carries the
747/// created identity, one rename lands it. A failure anywhere quarantines
748/// the entry under an unpredictable name in the same parent, judges it
749/// against the created identity, and removes it only on a match: an
750/// entry this write did not create is never removed.
751///
752/// # Errors
753///
754/// Any I/O failure, including the injected stop of the interruption
755/// proof, which reports as an I/O failure naming the path it stopped at.
756pub fn write(prepared: &Prepared, composed: &Composed) -> Result<(), RkError> {
757    let stop = std::env::var_os(INTERRUPT_VAR).map(PathBuf::from);
758    write_stopping_at(prepared, composed, stop.as_deref())
759}
760
761/// [`write`], stopped on purpose after the file at `stop`, as if the
762/// write after it had failed: the interruption proof's seam.
763///
764/// # Errors
765///
766/// As [`write`], plus the injected stop.
767pub fn write_stopping_at(
768    prepared: &Prepared,
769    composed: &Composed,
770    stop: Option<&Path>,
771) -> Result<(), RkError> {
772    let parent = crate::held::open_dir(&prepared.parent)?;
773    let temp = create_temp(prepared, &parent)?;
774    if let Err(error) = write_into(&temp, composed, stop) {
775        return Err(RkError::Io(cleanup(
776            &parent,
777            &temp.name,
778            temp.identity,
779            error,
780        )));
781    }
782    land(&parent, &temp, prepared).map_err(RkError::Io)
783}
784
785/// Publish the finished sibling, every operand resolved through the held
786/// parent descriptor.
787///
788/// The sibling is first claimed: renamed to an unpredictable name under
789/// the held parent, then judged there against the created identity, so
790/// nothing exchanged under the sibling's name can be published. The
791/// claimed entry is renamed to the stage's name under the same
792/// descriptor. Afterwards the public parent pathname is checked to still
793/// name the held parent; where it does not, the stage just published is
794/// quarantined, judged, removed through the descriptor, and the run
795/// fails, because a stage nobody can reach by the path it was promised
796/// at is not a stage, and one reachable through a replaced parent might
797/// be anywhere.
798fn land(parent: &File, temp: &Temp, prepared: &Prepared) -> std::io::Result<()> {
799    crate::held::pause(PAUSE_BEFORE_LAND_VAR, "finished", "proceed");
800    let base = crate::held::proc_path(parent);
801    let (claim, current) = crate::held::quarantine(parent, &temp.name, CLAIM_PREFIX)?;
802    if current.file_type().is_symlink() || crate::held::Identity::of(&current) != temp.identity {
803        return Err(std::io::Error::other(format!(
804            "the sibling under {} was exchanged before the stage could land; the entry that took its name was moved to {} beside it and left in place, and nothing was published",
805            prepared.parent.join(&temp.name).display(),
806            claim.display()
807        )));
808    }
809    if let Err(error) = fs::rename(base.join(&claim), base.join(&prepared.name)) {
810        return Err(cleanup(parent, &claim, temp.identity, error));
811    }
812    crate::held::pause(PAUSE_AFTER_LAND_VAR, "landed", "proceed");
813    let public = fs::metadata(&prepared.parent)
814        .ok()
815        .map(|metadata| crate::held::Identity::of(&metadata));
816    let held_parent = crate::held::Identity::of(&parent.metadata()?);
817    if public == Some(held_parent) {
818        return Ok(());
819    }
820    Err(cleanup(
821        parent,
822        &prepared.name,
823        temp.identity,
824        std::io::Error::other(format!(
825            "the parent {} was replaced after it was opened, so the stage published under it is not where it was promised; it was removed again through the held descriptor",
826            prepared.parent.display()
827        )),
828    ))
829}
830
831/// The failure cleanup: quarantine whatever stands under `name` in the
832/// held parent, judge it against `identity`, and remove it only on a
833/// match. Returns `error` annotated with what was left where.
834fn cleanup(
835    parent: &File,
836    name: &std::ffi::OsStr,
837    identity: crate::held::Identity,
838    error: std::io::Error,
839) -> std::io::Error {
840    crate::held::pause(PAUSE_BEFORE_CLEANUP_VAR, "stopped", "proceed");
841    let base = crate::held::proc_path(parent);
842    let (quarantined, current) = match crate::held::quarantine(parent, name, QUARANTINE_PREFIX) {
843        Ok(moved) => moved,
844        Err(quarantine) => {
845            return std::io::Error::new(
846                error.kind(),
847                format!(
848                    "{error}; the entry under {} could not be quarantined and was left in place: {quarantine}",
849                    name.display()
850                ),
851            );
852        }
853    };
854    if current.file_type().is_symlink() || crate::held::Identity::of(&current) != identity {
855        return std::io::Error::new(
856            error.kind(),
857            format!(
858                "{error}; the entry under {} was not the directory this run created, so it was moved to {} and left in place",
859                name.display(),
860                quarantined.display()
861            ),
862        );
863    }
864    match fs::remove_dir_all(base.join(&quarantined)) {
865        Ok(()) => error,
866        Err(removal) => std::io::Error::new(
867            error.kind(),
868            format!(
869                "{error}; the directory was moved to {} and could not be removed: {removal}",
870                quarantined.display()
871            ),
872        ),
873    }
874}
875
876/// The body of [`write`]: every file into the held sibling, then the
877/// receipt, each addressed through the descriptor.
878fn write_into(temp: &Temp, composed: &Composed, stop: Option<&Path>) -> std::io::Result<()> {
879    let base = crate::held::proc_path(&temp.dir);
880    for (path, bytes) in &composed.files {
881        let destination = base.join(path);
882        if let Some(parent) = destination.parent() {
883            fs::create_dir_all(parent)?;
884        }
885        fs::write(&destination, bytes)?;
886        if stop.is_some_and(|stop| Path::new(path) == stop) {
887            return Err(std::io::Error::other(format!(
888                "the stage was stopped after {path} for the proof"
889            )));
890        }
891    }
892    let text = serde_json::to_string_pretty(&composed.receipt).map_err(std::io::Error::other)?;
893    let mut receipt = fs::OpenOptions::new()
894        .write(true)
895        .create_new(true)
896        .mode(0o600)
897        .open(base.join(RECEIPT_NAME))?;
898    receipt.write_all(text.as_bytes())?;
899    receipt.write_all(b"\n")?;
900    receipt.sync_all()?;
901    Ok(())
902}
903
904/// The `schema_version` the target's landing record declares, read
905/// leniently: `None` where no record exists or it does not parse as a
906/// JSON object carrying an integer there. Explanatory, never a gate.
907#[must_use]
908pub fn recorded_schema_version(target: &Utf8Path) -> Option<u64> {
909    let bytes = fs::read(target.join(crate::landing::manifest::MANIFEST_PATH)).ok()?;
910    let value: serde_json::Value = serde_json::from_slice(&bytes).ok()?;
911    value.get("schema_version")?.as_u64()
912}
913
914#[cfg(test)]
915mod tests {
916    use super::{
917        CandidateEntry, Note, Parameters, REFERENCE_ROOTS, Receipt, STAGE_SCHEMA, reference_files,
918        target_key,
919    };
920    use crate::digest::Digest;
921    use crate::landing::Integration;
922    use crate::landing::Kind;
923    use crate::landing::manifest::{CheckoutMode, Style};
924    use crate::profile::{
925        CapabilityRequests, GitWorkflow, ProfileSnapshot, ReleaseIntent, ReleaseMode,
926    };
927
928    /// The parameters every stage test renders under: an automatic rust
929    /// release on GitHub, trunk style, in the linked-worktree mode.
930    fn test_parameters() -> Parameters {
931        Parameters {
932            profile: ProfileSnapshot {
933                technologies: vec!["rust".into()],
934                forge: Some("github".into()),
935                release: ReleaseIntent {
936                    mode: ReleaseMode::Automatic,
937                    driver: Some("rust".into()),
938                    style: Some(Style::Trunk),
939                    line_prefix: Some("release/".into()),
940                },
941            },
942            git: GitWorkflow {
943                trunk: "master".into(),
944                checkout_mode: CheckoutMode::LinkedWorktree,
945                integration: Integration::Local,
946            },
947            capabilities: CapabilityRequests {
948                nix_packaging: false,
949                reporting_policy: true,
950                scorecard: false,
951                code_scanning: None,
952            },
953            repo: "acme/widget".into(),
954            security_contact: String::new(),
955            security_response: "best-effort".into(),
956        }
957    }
958
959    /// The complete `rk.stage/4` receipt shape, held by snapshot: a field
960    /// rename or removal fails here and becomes a schema-version bump.
961    #[test]
962    fn the_stage_receipt_schema_snapshot_holds() {
963        let receipt = Receipt {
964            schema: STAGE_SCHEMA.to_owned(),
965            rk_version: "0.0.0".into(),
966            target: "/tmp/t".into(),
967            stage_root: "/tmp/s".into(),
968            parameters: test_parameters(),
969            capabilities: vec![],
970            receipt_schema_version: Some(6),
971            candidates: vec![
972                CandidateEntry {
973                    destination: "AGENTS.md".into(),
974                    kind: Kind::Rendered,
975                    placement: "region".into(),
976                    sha256: Digest::of(b"a"),
977                    region_sha256: Some(Digest::of(b"r")),
978                    sources: vec!["blocks/routing.md.in".into()],
979                },
980                CandidateEntry {
981                    destination: "release-plz.toml".into(),
982                    kind: Kind::Seeded,
983                    placement: "whole".into(),
984                    sha256: Digest::of(b"b"),
985                    region_sha256: None,
986                    sources: vec!["snippets/rust/github/release-plz.toml".into()],
987                },
988            ],
989            omissions: vec![Note {
990                destination: "flake.nix".into(),
991                reason: "the target already carries flake.nix".into(),
992                action: None,
993            }],
994            collisions: vec![],
995            retired: vec!["old.yml".into()],
996            seeded_present: vec!["release-plz.toml".into()],
997            state_present: vec![],
998            reference: REFERENCE_ROOTS
999                .iter()
1000                .map(|root| (*root).to_owned())
1001                .collect(),
1002        };
1003        assert_eq!(
1004            serde_json::to_string(&receipt).expect("a receipt serializes"),
1005            format!(
1006                r#"{{"schema":"rk.stage/4","rk_version":"0.0.0","target":"/tmp/t","stage_root":"/tmp/s","parameters":{{"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}},"repo":"acme/widget","security_contact":"","security_response":"best-effort"}},"capabilities":[],"receipt_schema_version":6,"candidates":[{{"destination":"AGENTS.md","kind":"rendered","placement":"region","sha256":"{}","region_sha256":"{}","sources":["blocks/routing.md.in"]}},{{"destination":"release-plz.toml","kind":"seeded","placement":"whole","sha256":"{}","sources":["snippets/rust/github/release-plz.toml"]}}],"omissions":[{{"destination":"flake.nix","reason":"the target already carries flake.nix"}}],"collisions":[],"retired":["old.yml"],"seeded_present":["release-plz.toml"],"state_present":[],"reference":["CHANGELOG.md","guidance","method","bindings","runbooks","forges","skills/rk-setup","skill-shared"]}}"#,
1007                Digest::of(b"a"),
1008                Digest::of(b"r"),
1009                Digest::of(b"b")
1010            )
1011        );
1012        let back: Receipt =
1013            serde_json::from_str(&serde_json::to_string(&receipt).expect("serializes"))
1014                .expect("a receipt reads back");
1015        assert_eq!(back.stage_root, "/tmp/s");
1016    }
1017
1018    /// Every declared reference root is served by at least one file, and
1019    /// no file reaches outside the declared roots.
1020    #[test]
1021    fn every_reference_root_serves_a_file_and_nothing_else_is_served() {
1022        let files = reference_files();
1023        for root in REFERENCE_ROOTS {
1024            assert!(
1025                files
1026                    .iter()
1027                    .any(|(path, _)| path == root || path.starts_with(&format!("{root}/"))),
1028                "{root}: the reference tree carries no file for it"
1029            );
1030        }
1031        for (path, _) in &files {
1032            assert!(
1033                REFERENCE_ROOTS
1034                    .iter()
1035                    .any(|root| path == root || path.starts_with(&format!("{root}/"))),
1036                "{path}: outside every declared reference root"
1037            );
1038            assert!(
1039                !path
1040                    .split('/')
1041                    .any(|part| part == "_docs" || part == "tests" || part == "src"),
1042                "{path}: an instance-owned or source path in the reference tree"
1043            );
1044        }
1045    }
1046
1047    /// A sibling somebody else left under the exact first candidate name
1048    /// is neither entered nor removed: the write steps to the next name,
1049    /// lands, and every byte of the stranger survives.
1050    #[test]
1051    fn a_pre_existing_temp_sibling_is_never_touched() {
1052        let scratch = tempfile::tempdir().expect("a scratch dir exists");
1053        let parent = std::fs::canonicalize(scratch.path()).expect("canonical");
1054        let output = parent.join("stage");
1055        let target = parent.join("target");
1056        std::fs::create_dir(&target).expect("creates");
1057        let prepared =
1058            super::prepare(&output, super::OutputSource::Flag, &target).expect("prepares");
1059        let stranger = parent.join(super::temp_name(std::ffi::OsStr::new("stage"), 0));
1060        std::fs::create_dir_all(stranger.join("deep")).expect("creates");
1061        std::fs::write(stranger.join("deep/canary"), b"not yours").expect("writes");
1062        std::fs::write(stranger.join("canary"), b"still not yours").expect("writes");
1063        let composed = super::Composed {
1064            files: vec![(
1065                "artifacts/a.txt".to_owned(),
1066                std::borrow::Cow::Borrowed(b"a"),
1067            )],
1068            receipt: sample_receipt(),
1069        };
1070        super::write(&prepared, &composed).expect("the write lands beside the stranger");
1071        assert_eq!(
1072            std::fs::read(output.join("artifacts/a.txt")).expect("reads"),
1073            b"a"
1074        );
1075        assert_eq!(
1076            std::fs::read(stranger.join("deep/canary")).expect("the stranger reads"),
1077            b"not yours"
1078        );
1079        assert_eq!(
1080            std::fs::read(stranger.join("canary")).expect("the stranger reads"),
1081            b"still not yours"
1082        );
1083        // The interrupted variant removes only what it created.
1084        let output_two = parent.join("stage-two");
1085        let prepared =
1086            super::prepare(&output_two, super::OutputSource::Flag, &target).expect("prepares");
1087        let stranger_two = parent.join(super::temp_name(std::ffi::OsStr::new("stage-two"), 0));
1088        std::fs::create_dir(&stranger_two).expect("creates");
1089        std::fs::write(stranger_two.join("canary"), b"kept").expect("writes");
1090        let stopped = super::write_stopping_at(
1091            &prepared,
1092            &composed,
1093            Some(std::path::Path::new("artifacts/a.txt")),
1094        );
1095        assert!(stopped.is_err());
1096        assert!(!output_two.exists());
1097        assert_eq!(
1098            std::fs::read(stranger_two.join("canary")).expect("the stranger reads"),
1099            b"kept"
1100        );
1101        let leftovers: Vec<String> = std::fs::read_dir(&parent)
1102            .expect("reads")
1103            .map(|entry| {
1104                entry
1105                    .expect("an entry")
1106                    .file_name()
1107                    .to_string_lossy()
1108                    .into_owned()
1109            })
1110            .filter(|name| name.starts_with(".rk-stage-"))
1111            .collect();
1112        assert_eq!(
1113            leftovers.len(),
1114            2,
1115            "only the two strangers remain: {leftovers:?}"
1116        );
1117    }
1118
1119    /// A stage root at or below the target refuses before any component
1120    /// is created, whichever source named it.
1121    #[test]
1122    fn a_stage_root_inside_the_target_refuses_before_anything_is_created() {
1123        let scratch = tempfile::tempdir().expect("a scratch dir exists");
1124        let target = std::fs::canonicalize(scratch.path())
1125            .expect("canonical")
1126            .join("t");
1127        std::fs::create_dir(&target).expect("creates");
1128        for (output, source) in [
1129            (target.join("stage"), super::OutputSource::Flag),
1130            (
1131                target.join("deep/er/stage"),
1132                super::OutputSource::Environment,
1133            ),
1134            (
1135                target.join("state/release-kit/stages/k/v"),
1136                super::OutputSource::StateRoot,
1137            ),
1138            (target.clone(), super::OutputSource::Flag),
1139        ] {
1140            let error = super::prepare(&output, source, &target).expect_err("refuses");
1141            assert_eq!(
1142                error.reason(),
1143                crate::diagnostic::Reason::DestructiveRefusal
1144            );
1145            assert_eq!(error.exit_code(), 73);
1146        }
1147        assert_eq!(
1148            std::fs::read_dir(&target).expect("reads").count(),
1149            0,
1150            "a refusal created a component inside the target"
1151        );
1152    }
1153
1154    fn sample_receipt() -> Receipt {
1155        Receipt {
1156            schema: STAGE_SCHEMA.to_owned(),
1157            rk_version: "0.0.0".into(),
1158            target: "/tmp/t".into(),
1159            stage_root: "/tmp/s".into(),
1160            parameters: test_parameters(),
1161            capabilities: vec![],
1162            receipt_schema_version: None,
1163            candidates: vec![],
1164            omissions: vec![],
1165            collisions: vec![],
1166            retired: vec![],
1167            seeded_present: vec![],
1168            state_present: vec![],
1169            reference: vec![],
1170        }
1171    }
1172
1173    /// The key is the lock's derivation: one digest per canonical path,
1174    /// and a separator in the path cannot escape the base.
1175    #[test]
1176    fn the_target_key_is_one_flat_digest() {
1177        let key = target_key(std::path::Path::new("/a/b"));
1178        assert_eq!(key.len(), 64);
1179        assert!(key.bytes().all(|b| b.is_ascii_hexdigit()));
1180        assert_ne!(key, target_key(std::path::Path::new("/a/c")));
1181    }
1182}