Skip to main content

spec_driven_docs/stage/
compare.rs

1//! Compare one stage against the target it was rendered for.
2//!
3//! One row per destination the stage carries, plus one per recorded
4//! managed file the candidate no longer lands. Each row says whether the
5//! target holds the staged bytes, who owns the destination, and, where the
6//! two differ, how much this tool can say about who wrote what is there.
7//!
8//! The record half of that answer is the attribution check the landing
9//! runs before it refuses unvouched bytes, so a row this reports as
10//! unvouched is exactly a destination the landing would refuse. The
11//! history half asks the target's own Git history whether any commit
12//! touched the path. Nothing here writes.
13
14use camino::{Utf8Path, Utf8PathBuf};
15use serde::Serialize;
16
17use crate::adapters::history::History;
18use crate::candidate::Ownership;
19use crate::error::AppError;
20
21/// The machine schema `sdd stage compare --json` declares.
22pub const SCHEMA: &str = "sdd.stage-compare/1";
23
24/// What the target holds at one destination, against the stage.
25#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
26#[serde(rename_all = "kebab-case")]
27pub enum State {
28    /// The target holds the staged bytes.
29    Equal,
30    /// The target holds nothing there.
31    Absent,
32    /// The target holds other bytes.
33    Differs,
34    /// The record names a managed file the candidate no longer lands.
35    Retired,
36}
37
38/// How much this tool can say about the bytes that differ.
39#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
40#[serde(rename_all = "kebab-case")]
41pub enum Provenance {
42    /// The record vouches for the bytes and the history touches the path.
43    Attributed,
44    /// One of the two holds.
45    Reduced,
46    /// Neither holds.
47    Unknown,
48}
49
50/// Who owns one destination after a landing.
51#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
52#[serde(rename_all = "kebab-case")]
53pub enum RowOwnership {
54    /// The canon owns the whole file.
55    Managed,
56    /// The canon owns one marked region of a file the project owns.
57    Integration,
58    /// The project owns the file from the moment it lands.
59    Adopted,
60}
61
62impl RowOwnership {
63    const fn landing(self) -> Ownership {
64        match self {
65            Self::Managed => Ownership::Managed,
66            Self::Integration => Ownership::Integration,
67            Self::Adopted => Ownership::Adopted,
68        }
69    }
70
71    /// The word the JSON spells.
72    #[must_use]
73    pub const fn as_str(self) -> &'static str {
74        match self {
75            Self::Managed => "managed",
76            Self::Integration => "integration",
77            Self::Adopted => "adopted",
78        }
79    }
80}
81
82/// One destination's comparison.
83#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
84pub struct Row {
85    /// The destination, relative to the target.
86    pub path: String,
87    /// What the target holds against the stage.
88    pub state: State,
89    /// Who owns it.
90    pub ownership: RowOwnership,
91    /// For a destination that differs or retires, what vouches for it.
92    pub provenance: Option<Provenance>,
93    /// Whether the record vouches for the bytes the target holds, where
94    /// the target holds any. The landing refuses exactly the managed and
95    /// integration rows that differ with this false.
96    pub vouched: Option<bool>,
97    /// Whether the verb that lands this stage accepts the path in
98    /// `--replace`: true only for a conflict `sdd upgrade` would take a
99    /// name for, false on every other row.
100    pub replaceable: bool,
101}
102
103/// Whether the history half could be read.
104#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
105pub struct HistoryState {
106    /// Whether the target's Git history was read.
107    pub available: bool,
108    /// Why not, where it was not.
109    pub reason: Option<String>,
110}
111
112/// The whole comparison.
113#[derive(Debug, Clone, Serialize)]
114pub struct Report {
115    /// The machine schema of this object.
116    pub schema: &'static str,
117    /// The stage compared.
118    pub root: Utf8PathBuf,
119    /// The target compared against.
120    pub target: Utf8PathBuf,
121    /// Whether the history half was read.
122    pub history: HistoryState,
123    /// One row per destination, in the stage's order, then the retired.
124    pub rows: Vec<Row>,
125}
126
127/// Compare the stage at `root` against `target`.
128///
129/// SATISFIES staging:compare-reports-every-destination-the-stage-carries
130///
131/// # Errors
132///
133/// Whatever [`super::read_choices`] refuses, and I/O errors reading a
134/// staged artifact.
135pub fn compare(root: &Utf8Path, target: &Utf8Path) -> Result<Report, AppError> {
136    let choices = super::read_choices(root, target)?;
137    let replaceable = crate::services::upgrader::replaceable(&choices)?;
138    let target = choices.target.clone();
139    let recorded = crate::services::installer::recorded(&target);
140    let (history, history_state) = match History::open(&target) {
141        Ok(history) => (
142            Some(history),
143            HistoryState {
144                available: true,
145                reason: None,
146            },
147        ),
148        Err(missing) => (
149            None,
150            HistoryState {
151                available: false,
152                reason: Some(missing.to_string()),
153            },
154        ),
155    };
156    let touches = |path: &Utf8Path| history.as_ref().is_some_and(|held| held.touches(path));
157    let provenance = |vouched: bool, path: &Utf8Path| match (vouched, touches(path)) {
158        (true, true) => Provenance::Attributed,
159        (false, false) => Provenance::Unknown,
160        _ => Provenance::Reduced,
161    };
162
163    let mut rows = Vec::new();
164    let mut staged_paths = Vec::new();
165    for artifact in &choices.artifacts {
166        let ownership = match artifact.ownership.as_str() {
167            "managed" => RowOwnership::Managed,
168            "integration" => RowOwnership::Integration,
169            "adopted" => RowOwnership::Adopted,
170            // The record itself is rewritten by every landing, so it is
171            // never compared.
172            _ => continue,
173        };
174        let path = Utf8PathBuf::from(&artifact.path);
175        staged_paths.push(artifact.path.clone());
176        let staged = std::fs::read(root.join(super::ARTIFACTS_DIR).join(&path))?;
177        let Ok(held) = std::fs::read(target.join(&path)) else {
178            rows.push(Row {
179                path: artifact.path.clone(),
180                state: State::Absent,
181                ownership,
182                provenance: None,
183                vouched: None,
184                replaceable: replaceable.contains(&artifact.path),
185            });
186            continue;
187        };
188        let vouched = crate::landing::apply::vouches(&recorded, &path, ownership.landing(), &held);
189        let equal = match ownership {
190            // A marked region is the canon's and the rest of its host is the
191            // project's, so only the region is compared.
192            RowOwnership::Integration => region(&path, &held) == region(&path, &staged),
193            RowOwnership::Managed | RowOwnership::Adopted => held == staged,
194        };
195        rows.push(Row {
196            path: artifact.path.clone(),
197            state: if equal { State::Equal } else { State::Differs },
198            ownership,
199            provenance: (!equal).then(|| provenance(vouched, &path)),
200            vouched: Some(vouched),
201            replaceable: replaceable.contains(&artifact.path),
202        });
203    }
204    for (destination, _) in &recorded.managed {
205        if staged_paths.contains(destination) {
206            continue;
207        }
208        let path = Utf8PathBuf::from(destination);
209        // Every recorded destination gets its row. One that is gone has no
210        // bytes to vouch for, so its provenance is the Git half alone, and
211        // one that cannot be read is vouched for by nobody, so the operator
212        // is asked rather than the row dropped.
213        let (provenance, vouched) = match std::fs::read(target.join(&path)) {
214            Ok(held) => {
215                let vouched = crate::landing::apply::vouches_retired(&recorded, destination, &held);
216                (Some(provenance(vouched, &path)), Some(vouched))
217            }
218            Err(error) if error.kind() == std::io::ErrorKind::NotFound => {
219                (Some(provenance(false, &path)), None)
220            }
221            Err(_) => (Some(Provenance::Unknown), None),
222        };
223        rows.push(Row {
224            path: destination.clone(),
225            state: State::Retired,
226            ownership: RowOwnership::Managed,
227            provenance,
228            vouched,
229            replaceable: replaceable.contains(destination),
230        });
231    }
232    Ok(Report {
233        schema: SCHEMA,
234        root: root.to_owned(),
235        target,
236        history: history_state,
237        rows,
238    })
239}
240
241/// The hash of the marked region one host file carries.
242fn region(path: &Utf8Path, bytes: &[u8]) -> Option<crate::domain::ownership::Sha256> {
243    use crate::domain::marker;
244
245    let text = std::str::from_utf8(bytes).ok()?;
246    if path == crate::domain::paths::HOOKS_CONFIG_PATH {
247        marker::block_hash(text)
248    } else {
249        marker::block_hash_with(text, marker::AGENTS_BEGIN, marker::AGENTS_END)
250    }
251}