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
80/// The only roots an upgrade may remove dropped managed files from.
81const PRUNABLE: &[&str] = &[".spec-driven-docs/", ".claude/skills/", ".agents/skills/"];
82
83fn prune(
84    target: &Utf8Path,
85    dropped: &[Utf8PathBuf],
86    outcome: &mut UpgradeOutcome,
87) -> Vec<Utf8PathBuf> {
88    let mut unremoved = Vec::new();
89    for destination in dropped {
90        let raw = destination.as_str();
91        if raw.starts_with('/')
92            || raw == ".."
93            || raw.starts_with("../")
94            || raw.ends_with("/..")
95            || raw.contains("/../")
96        {
97            outcome.lines.push(format!(
98                "refused to remove a destination that leaves the target: {raw}"
99            ));
100            outcome.failures += 1;
101            continue;
102        }
103        if !PRUNABLE.iter().any(|prefix| raw.starts_with(prefix)) {
104            continue;
105        }
106        let mut prefix = target.to_path_buf();
107        let parts: Vec<&str> = raw.split('/').collect();
108        let mut escapes = false;
109        for part in &parts[..parts.len() - 1] {
110            prefix.push(part);
111            if prefix.is_symlink() {
112                escapes = true;
113            }
114        }
115        let full = target.join(destination);
116        if escapes || full.is_symlink() {
117            outcome.lines.push(format!(
118                "refused to remove a destination reached through a symlink: {raw}"
119            ));
120            outcome.failures += 1;
121            continue;
122        }
123        if !full.is_file() {
124            continue;
125        }
126        if std::fs::remove_file(&full).is_ok() {
127            outcome
128                .lines
129                .push(format!("removed managed file no longer owned: {raw}"));
130        } else {
131            unremoved.push(destination.clone());
132        }
133    }
134    unremoved
135}
136
137/// Upgrade an installed instance to this binary's version.
138///
139/// # Errors
140///
141/// [`AppError::Violations`] when conflicts block the upgrade or removals
142/// remain unfinished, [`AppError::Refused`] when the binary is older than
143/// the instance or the reinstall refuses, and manifest errors when the
144/// record cannot be read.
145pub fn upgrade(options: &UpgradeOptions) -> Result<UpgradeOutcome, AppError> {
146    if !options.target.is_absolute() {
147        return Err(AppError::Usage("target must be absolute".to_string()));
148    }
149    if !options.target.is_dir() {
150        return Err(AppError::Usage(format!(
151            "unresolved target: {}",
152            options.target
153        )));
154    }
155    let target = Utf8PathBuf::from_path_buf(std::fs::canonicalize(&options.target)?)
156        .map_err(|p| AppError::Usage(format!("target is not UTF-8: {}", p.display())))?;
157
158    let installed = read_installed(&target)?;
159    let new = CanonVersion::current();
160    let old = installed.version;
161    let mut outcome = UpgradeOutcome::default();
162
163    if old == new {
164        outcome.lines.push(format!("OK already at {new}"));
165        return Ok(outcome);
166    }
167    if old > new {
168        return Err(AppError::Refused(format!(
169            "sdd {new} is older than the installed canon {old}; upgrade sdd"
170        )));
171    }
172
173    let mut conflicts = Vec::new();
174    for (destination, recorded) in &installed.managed {
175        let file = target.join(destination);
176        if !file.is_file() {
177            conflicts.push(format!("CONFLICT missing managed file: {destination}"));
178            continue;
179        }
180        if sha256_file(&file)? != *recorded {
181            conflicts.push(format!(
182                "CONFLICT locally edited managed file: {destination}"
183            ));
184        }
185    }
186    if !conflicts.is_empty() {
187        let count = conflicts.len();
188        outcome.lines.extend(conflicts);
189        outcome.failures += count;
190        return Ok(outcome);
191    }
192
193    if options.dry_run {
194        outcome
195            .lines
196            .push(format!("DRY RUN upgrade {old} to {new}"));
197        return Ok(outcome);
198    }
199
200    init(&InitOptions {
201        target: target.clone(),
202        profile: installed.profile,
203        apply: true,
204        dry_run: false,
205    })
206    .map_err(|error| {
207        AppError::Refused(format!(
208            "upgrade aborted during reinstall from {old} to {new}: {error}"
209        ))
210    })?;
211
212    finish(&target, &installed, old, new, &mut outcome)?;
213    Ok(outcome)
214}
215
216fn finish(
217    target: &Utf8Path,
218    installed: &Installed,
219    old: CanonVersion,
220    new: CanonVersion,
221    outcome: &mut UpgradeOutcome,
222) -> Result<(), AppError> {
223    let fresh = Manifest::parse(&std::fs::read_to_string(target.join(MANIFEST_PATH))?)
224        .map_err(|error| AppError::ManifestInvalid(error.to_string()))?;
225    let kept: std::collections::BTreeSet<&Utf8PathBuf> = fresh
226        .managed_files
227        .iter()
228        .map(|entry| &entry.destination)
229        .collect();
230    let dropped: Vec<Utf8PathBuf> = installed
231        .managed
232        .iter()
233        .map(|(destination, _)| destination.clone())
234        .filter(|destination| !kept.contains(destination))
235        .collect();
236    let unremoved = prune(target, &dropped, outcome);
237    if !unremoved.is_empty() {
238        outcome.lines.push(
239            "FAIL these files are no longer owned and could not be removed; delete them by hand:"
240                .to_string(),
241        );
242        for destination in &unremoved {
243            outcome.lines.push(format!("  {destination}"));
244        }
245        outcome.lines.push(format!(
246            "the payload and manifest are upgraded to {new}; only these removals remain, and"
247        ));
248        outcome.lines.push(format!(
249            "re-running this upgrade will report 'already at {new}' rather than retry them"
250        ));
251        outcome.failures += unremoved.len();
252    }
253
254    let mut local_ids = std::collections::BTreeSet::new();
255    let specs = target.join(&installed.docs_root).join("specs");
256    if let Ok(entries) = specs.read_dir_utf8() {
257        for entry in entries.filter_map(Result::ok) {
258            if let Ok(text) = std::fs::read_to_string(entry.path()) {
259                local_ids.extend(crate::embedded::rule_ids_in(&text));
260            }
261        }
262    }
263    let upstream_only: Vec<String> = crate::embedded::spec_rule_ids()
264        .difference(&local_ids)
265        .cloned()
266        .collect();
267    if !upstream_only.is_empty() {
268        outcome
269            .lines
270            .push("upstream rule IDs not present locally:".to_string());
271        for id in upstream_only {
272            outcome.lines.push(format!("  {id}"));
273        }
274    }
275
276    if outcome.failures > 0 {
277        outcome.lines.push(format!(
278            "FAIL upgraded {old} to {new} with unfinished removals above"
279        ));
280    } else {
281        outcome.lines.push(format!("OK upgraded {old} to {new}"));
282    }
283    Ok(())
284}