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    /// Every skill package folder the landing would refuse, as
126    /// `<root>/<name>/`, by the check the landing itself applies.
127    pub refused_packages: Vec<String>,
128}
129
130/// Compare the stage at `root` against `target`.
131///
132/// SATISFIES staging:compare-reports-every-destination-the-stage-carries
133///
134/// # Errors
135///
136/// Whatever [`super::read_choices`] refuses, and I/O errors reading a
137/// staged artifact.
138pub fn compare(root: &Utf8Path, target: &Utf8Path) -> Result<Report, AppError> {
139    let choices = super::read_choices(root, target)?;
140    let replaceable = crate::services::upgrader::replaceable(&choices)?;
141    let target = choices.target.clone();
142    let recorded = crate::services::installer::recorded(&target);
143    let refused_packages = crate::landing::apply::refused_skill_packages(&target, &recorded);
144    let (history, history_state) = match History::open(&target) {
145        Ok(history) => (
146            Some(history),
147            HistoryState {
148                available: true,
149                reason: None,
150            },
151        ),
152        Err(missing) => (
153            None,
154            HistoryState {
155                available: false,
156                reason: Some(missing.to_string()),
157            },
158        ),
159    };
160    let touches = |path: &Utf8Path| history.as_ref().is_some_and(|held| held.touches(path));
161    let provenance = |vouched: bool, path: &Utf8Path| match (vouched, touches(path)) {
162        (true, true) => Provenance::Attributed,
163        (false, false) => Provenance::Unknown,
164        _ => Provenance::Reduced,
165    };
166
167    let mut rows = Vec::new();
168    let mut staged_paths = Vec::new();
169    for artifact in &choices.artifacts {
170        let ownership = match artifact.ownership.as_str() {
171            "managed" => RowOwnership::Managed,
172            "integration" => RowOwnership::Integration,
173            "adopted" => RowOwnership::Adopted,
174            // The record itself is rewritten by every landing, so it is
175            // never compared.
176            _ => continue,
177        };
178        let path = Utf8PathBuf::from(&artifact.path);
179        staged_paths.push(artifact.path.clone());
180        let staged = std::fs::read(root.join(super::ARTIFACTS_DIR).join(&path))?;
181        let Ok(held) = std::fs::read(target.join(&path)) else {
182            rows.push(Row {
183                path: artifact.path.clone(),
184                state: State::Absent,
185                ownership,
186                provenance: None,
187                vouched: None,
188                replaceable: replaceable.contains(&artifact.path),
189            });
190            continue;
191        };
192        let vouched = crate::landing::apply::vouches(&recorded, &path, ownership.landing(), &held);
193        let equal = match ownership {
194            // A marked region is the canon's and the rest of its host is the
195            // project's, so only the region is compared.
196            RowOwnership::Integration => region(&path, &held) == region(&path, &staged),
197            RowOwnership::Managed | RowOwnership::Adopted => held == staged,
198        };
199        rows.push(Row {
200            path: artifact.path.clone(),
201            state: if equal { State::Equal } else { State::Differs },
202            ownership,
203            provenance: (!equal).then(|| provenance(vouched, &path)),
204            vouched: Some(vouched),
205            replaceable: replaceable.contains(&artifact.path),
206        });
207    }
208    for (destination, _) in &recorded.managed {
209        if staged_paths.contains(destination) {
210            continue;
211        }
212        let path = Utf8PathBuf::from(destination);
213        // Every recorded destination gets its row. One that is gone has no
214        // bytes to vouch for, so its provenance is the Git half alone, and
215        // one that cannot be read is vouched for by nobody, so the operator
216        // is asked rather than the row dropped.
217        let (provenance, vouched) = match std::fs::read(target.join(&path)) {
218            Ok(held) => {
219                let vouched = crate::landing::apply::vouches_retired(&recorded, destination, &held);
220                (Some(provenance(vouched, &path)), Some(vouched))
221            }
222            Err(error) if error.kind() == std::io::ErrorKind::NotFound => {
223                (Some(provenance(false, &path)), None)
224            }
225            Err(_) => (Some(Provenance::Unknown), None),
226        };
227        rows.push(Row {
228            path: destination.clone(),
229            state: State::Retired,
230            ownership: RowOwnership::Managed,
231            provenance,
232            vouched,
233            replaceable: replaceable.contains(destination),
234        });
235    }
236    Ok(Report {
237        schema: SCHEMA,
238        root: root.to_owned(),
239        target,
240        history: history_state,
241        rows,
242        refused_packages,
243    })
244}
245
246/// The hash of the marked region one host file carries.
247fn region(path: &Utf8Path, bytes: &[u8]) -> Option<crate::domain::ownership::Sha256> {
248    use crate::domain::marker;
249
250    let text = std::str::from_utf8(bytes).ok()?;
251    if path == crate::domain::paths::HOOKS_CONFIG_PATH {
252        marker::block_hash(text)
253    } else {
254        marker::block_hash_with(text, marker::AGENTS_BEGIN, marker::AGENTS_END)
255    }
256}