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