Skip to main content

spec_driven_docs/services/
upgrader.rs

1//! Binary-driven instance upgrade.
2//!
3//! The newer binary carries the newer payload, so an upgrade is mechanical:
4//! refuse atomically while any managed file is locally edited, reinstall
5//! from the embedded payload, prune what the new version stopped managing —
6//! inside the vendored directory only, and never through a symlink — and
7//! report the rule-ID diff the operator reconciles by hand. Copier's model;
8//! what changed between versions is the changelog's business.
9
10use camino::{Utf8Path, Utf8PathBuf};
11
12use crate::adapters::fs::sha256_file;
13use crate::domain::manifest::{LegacyManifest, MANIFEST_PATH, Manifest, ManifestParseError};
14use crate::domain::ownership::Sha256;
15use crate::domain::profile::ProfileId;
16use crate::domain::version::CanonVersion;
17use crate::error::AppError;
18use crate::services::installer::{InitOptions, init};
19
20/// What an upgrade was asked to do.
21#[derive(Debug, Clone)]
22pub struct UpgradeOptions {
23    /// The absolute target instance.
24    pub target: Utf8PathBuf,
25    /// Report the plan and change nothing.
26    pub dry_run: bool,
27}
28
29/// What an upgrade did.
30#[derive(Debug, Default)]
31pub struct UpgradeOutcome {
32    /// Every line to print, in order.
33    pub lines: Vec<String>,
34    /// How many lines are conflicts or failures.
35    pub failures: usize,
36}
37
38struct Installed {
39    version: CanonVersion,
40    profile: ProfileId,
41    docs_root: String,
42    managed: Vec<(Utf8PathBuf, Sha256)>,
43}
44
45fn read_installed(target: &Utf8Path) -> Result<Installed, AppError> {
46    let path = target.join(MANIFEST_PATH);
47    if !path.is_file() {
48        return Err(AppError::ManifestMissing(path));
49    }
50    let text = std::fs::read_to_string(&path)?;
51    match Manifest::parse(&text) {
52        Ok(manifest) => Ok(Installed {
53            version: manifest.canon_version,
54            profile: manifest.profile,
55            docs_root: manifest.docs_root.as_str().to_string(),
56            managed: manifest
57                .managed_files
58                .into_iter()
59                .map(|entry| (entry.destination, entry.sha256))
60                .collect(),
61        }),
62        Err(ManifestParseError::Older(1)) => {
63            let legacy: LegacyManifest = serde_json::from_str(&text)
64                .map_err(|e| AppError::ManifestInvalid(e.to_string()))?;
65            Ok(Installed {
66                version: legacy.canon_version,
67                profile: legacy.profile,
68                docs_root: legacy.docs_root.as_str().to_string(),
69                managed: legacy
70                    .managed_files
71                    .into_iter()
72                    .map(|entry| (entry.destination, entry.sha256))
73                    .collect(),
74            })
75        }
76        Err(error) => Err(AppError::ManifestInvalid(error.to_string())),
77    }
78}
79
80fn prune(
81    target: &Utf8Path,
82    dropped: &[Utf8PathBuf],
83    outcome: &mut UpgradeOutcome,
84) -> Vec<Utf8PathBuf> {
85    let mut unremoved = Vec::new();
86    for destination in dropped {
87        let raw = destination.as_str();
88        if raw.starts_with('/')
89            || raw == ".."
90            || raw.starts_with("../")
91            || raw.ends_with("/..")
92            || raw.contains("/../")
93        {
94            outcome.lines.push(format!(
95                "refused to remove a destination that leaves the target: {raw}"
96            ));
97            outcome.failures += 1;
98            continue;
99        }
100        if !raw.starts_with(".spec-driven-docs/") {
101            continue;
102        }
103        let mut prefix = target.to_path_buf();
104        let parts: Vec<&str> = raw.split('/').collect();
105        let mut escapes = false;
106        for part in &parts[..parts.len() - 1] {
107            prefix.push(part);
108            if prefix.is_symlink() {
109                escapes = true;
110            }
111        }
112        let full = target.join(destination);
113        if escapes || full.is_symlink() {
114            outcome.lines.push(format!(
115                "refused to remove a destination reached through a symlink: {raw}"
116            ));
117            outcome.failures += 1;
118            continue;
119        }
120        if !full.is_file() {
121            continue;
122        }
123        if std::fs::remove_file(&full).is_ok() {
124            outcome
125                .lines
126                .push(format!("removed managed file no longer owned: {raw}"));
127        } else {
128            unremoved.push(destination.clone());
129        }
130    }
131    unremoved
132}
133
134/// Upgrade an installed instance to this binary's version.
135///
136/// # Errors
137///
138/// [`AppError::Violations`] when conflicts block the upgrade or removals
139/// remain unfinished, [`AppError::Refused`] when the binary is older than
140/// the instance or the reinstall refuses, and manifest errors when the
141/// record cannot be read.
142pub fn upgrade(options: &UpgradeOptions) -> Result<UpgradeOutcome, AppError> {
143    if !options.target.is_absolute() {
144        return Err(AppError::Usage("target must be absolute".to_string()));
145    }
146    if !options.target.is_dir() {
147        return Err(AppError::Usage(format!(
148            "unresolved target: {}",
149            options.target
150        )));
151    }
152    let target = Utf8PathBuf::from_path_buf(std::fs::canonicalize(&options.target)?)
153        .map_err(|p| AppError::Usage(format!("target is not UTF-8: {}", p.display())))?;
154
155    let installed = read_installed(&target)?;
156    let new = CanonVersion::current();
157    let old = installed.version;
158    let mut outcome = UpgradeOutcome::default();
159
160    if old == new {
161        outcome.lines.push(format!("OK already at {new}"));
162        return Ok(outcome);
163    }
164    if old > new {
165        return Err(AppError::Refused(format!(
166            "sdd {new} is older than the installed canon {old}; upgrade sdd"
167        )));
168    }
169
170    let mut conflicts = Vec::new();
171    for (destination, recorded) in &installed.managed {
172        let file = target.join(destination);
173        if !file.is_file() {
174            conflicts.push(format!("CONFLICT missing managed file: {destination}"));
175            continue;
176        }
177        if sha256_file(&file)? != *recorded {
178            conflicts.push(format!(
179                "CONFLICT locally edited managed file: {destination}"
180            ));
181        }
182    }
183    if !conflicts.is_empty() {
184        let count = conflicts.len();
185        outcome.lines.extend(conflicts);
186        outcome.failures += count;
187        return Ok(outcome);
188    }
189
190    if options.dry_run {
191        outcome
192            .lines
193            .push(format!("DRY RUN upgrade {old} to {new}"));
194        return Ok(outcome);
195    }
196
197    init(&InitOptions {
198        target: target.clone(),
199        profile: installed.profile,
200        apply: true,
201        dry_run: false,
202    })
203    .map_err(|error| {
204        AppError::Refused(format!(
205            "upgrade aborted during reinstall from {old} to {new}: {error}"
206        ))
207    })?;
208
209    finish(&target, &installed, old, new, &mut outcome)?;
210    Ok(outcome)
211}
212
213fn finish(
214    target: &Utf8Path,
215    installed: &Installed,
216    old: CanonVersion,
217    new: CanonVersion,
218    outcome: &mut UpgradeOutcome,
219) -> Result<(), AppError> {
220    let fresh = Manifest::parse(&std::fs::read_to_string(target.join(MANIFEST_PATH))?)
221        .map_err(|error| AppError::ManifestInvalid(error.to_string()))?;
222    let kept: std::collections::BTreeSet<&Utf8PathBuf> = fresh
223        .managed_files
224        .iter()
225        .map(|entry| &entry.destination)
226        .collect();
227    let dropped: Vec<Utf8PathBuf> = installed
228        .managed
229        .iter()
230        .map(|(destination, _)| destination.clone())
231        .filter(|destination| !kept.contains(destination))
232        .collect();
233    let unremoved = prune(target, &dropped, outcome);
234    if !unremoved.is_empty() {
235        outcome.lines.push(
236            "FAIL these files are no longer owned and could not be removed; delete them by hand:"
237                .to_string(),
238        );
239        for destination in &unremoved {
240            outcome.lines.push(format!("  {destination}"));
241        }
242        outcome.lines.push(format!(
243            "the payload and manifest are upgraded to {new}; only these removals remain, and"
244        ));
245        outcome.lines.push(format!(
246            "re-running this upgrade will report 'already at {new}' rather than retry them"
247        ));
248        outcome.failures += unremoved.len();
249    }
250
251    let mut local_ids = std::collections::BTreeSet::new();
252    let specs = target.join(&installed.docs_root).join("specs");
253    if let Ok(entries) = specs.read_dir_utf8() {
254        for entry in entries.filter_map(Result::ok) {
255            if let Ok(text) = std::fs::read_to_string(entry.path()) {
256                local_ids.extend(crate::embedded::rule_ids_in(&text));
257            }
258        }
259    }
260    let upstream_only: Vec<String> = crate::embedded::spec_rule_ids()
261        .difference(&local_ids)
262        .cloned()
263        .collect();
264    if !upstream_only.is_empty() {
265        outcome
266            .lines
267            .push("upstream rule IDs not present locally:".to_string());
268        for id in upstream_only {
269            outcome.lines.push(format!("  {id}"));
270        }
271    }
272
273    if outcome.failures > 0 {
274        outcome.lines.push(format!(
275            "FAIL upgraded {old} to {new} with unfinished removals above"
276        ));
277    } else {
278        outcome.lines.push(format!("OK upgraded {old} to {new}"));
279    }
280    Ok(())
281}