Skip to main content

spec_driven_docs/services/
installer.rs

1//! Instance installation: project the embedded payload into a target.
2//!
3//! The chezmoi vocabulary applies: the embedded payload and profile are the
4//! source state, the computed projection is the target state, the repository
5//! on disk is the destination state, and the manifest — written last — is
6//! the persistent entry state. The whole target state is computed before a
7//! byte lands; a non-empty target previews by default; every destination is
8//! guarded; and any failure mid-apply rolls the target back. What the
9//! payload contains is `embedded`'s and the profiles' business.
10
11use camino::{Utf8Path, Utf8PathBuf};
12
13use crate::domain::manifest::{MANIFEST_PATH, validate_docs_scratch_path};
14use crate::domain::paths::{AGENTS_DIGEST_PATH, HOOKS_CONFIG_PATH};
15use crate::domain::profile::{ProfileId, resolve_destination};
16use crate::domain::version::CanonVersion;
17use crate::error::AppError;
18
19/// What an installation was asked to do.
20#[derive(Debug, Clone)]
21pub struct InitOptions {
22    /// The absolute target repository.
23    pub target: Utf8PathBuf,
24    /// The profile to project.
25    pub profile: ProfileId,
26    /// Write even into a non-empty target with no instance.
27    pub apply: bool,
28    /// Preview only, regardless of the target's state.
29    pub dry_run: bool,
30    /// The docs scratch to record. `None` keeps whatever is recorded, and
31    /// `Some(None)` clears it.
32    pub docs_scratch: Option<Option<Utf8PathBuf>>,
33    /// Paths to record under `reserved:` in the instance's declaration. An
34    /// empty list keeps whatever is recorded.
35    pub reserve: Vec<String>,
36    /// The writing-style selection to record in the declaration. `None`
37    /// keeps whatever is recorded.
38    pub writing_style: Option<crate::domain::instance_config::WritingStyle>,
39    /// The acquisition decision to record in the declaration. `None` keeps
40    /// whatever is recorded.
41    pub acquisition: Option<crate::domain::instance_config::Acquisition>,
42    /// Destinations the operator named for replacement. The caller saves
43    /// each one's bytes before the landing runs.
44    pub replace: Vec<String>,
45}
46
47/// What an installation did.
48#[derive(Debug)]
49pub struct InitOutcome {
50    /// Every line to print: the proposed destinations, then any notices.
51    pub lines: Vec<String>,
52    /// Whether files were written.
53    pub applied: bool,
54    /// Every destination the landing took back, relative to the target.
55    pub removed: Vec<String>,
56}
57
58fn canonical_target(target: &Utf8Path) -> Result<Utf8PathBuf, AppError> {
59    if !target.is_absolute() {
60        return Err(AppError::Usage("target must be absolute".to_string()));
61    }
62    if !target.is_dir() {
63        return Err(AppError::Usage(format!("unresolved target: {target}")));
64    }
65    let canonical = std::fs::canonicalize(target)?;
66    let canonical = Utf8PathBuf::from_path_buf(canonical)
67        .map_err(|p| AppError::Usage(format!("target is not UTF-8: {}", p.display())))?;
68    if canonical.as_str().chars().all(|c| c == '/') {
69        return Err(AppError::Usage("refusing root target".to_string()));
70    }
71    let mut ancestor = Some(canonical.as_path());
72    while let Some(dir) = ancestor {
73        if let Ok(cargo) = std::fs::read_to_string(dir.join("Cargo.toml"))
74            && cargo.contains("name = \"spec-driven-docs\"")
75        {
76            return Err(AppError::Usage(
77                "target is inside the canon checkout".to_string(),
78            ));
79        }
80        ancestor = dir.parent();
81    }
82    Ok(canonical)
83}
84
85fn target_has_content(target: &Utf8Path) -> Result<bool, AppError> {
86    for entry in target.read_dir_utf8()? {
87        let entry = entry?;
88        if entry.file_name() != ".git" {
89            return Ok(true);
90        }
91    }
92    Ok(false)
93}
94
95/// One field of whatever manifest the target already carries.
96///
97/// Read as free JSON rather than through [`Manifest::parse`]: a reinstall
98/// over a record of another schema version must still carry the operator's
99/// declared values forward, and a typed parse would refuse to read it.
100pub(crate) fn recorded_field(target: &Utf8Path, key: &str) -> Option<serde_json::Value> {
101    std::fs::read_to_string(target.join(MANIFEST_PATH))
102        .ok()
103        .and_then(|text| serde_json::from_str::<serde_json::Value>(&text).ok())
104        .and_then(|value| value.get(key).cloned())
105        .filter(|value| !value.is_null())
106}
107
108fn installed_at(target: &Utf8Path) -> String {
109    recorded_field(target, "installed_at")
110        .and_then(|value| value.as_str().map(String::from))
111        .unwrap_or_else(|| {
112            jiff::Timestamp::now()
113                .strftime("%Y-%m-%dT%H:%M:%SZ")
114                .to_string()
115        })
116}
117
118/// The docs scratch to record: the flag, else the recorded value, else none.
119///
120/// An omitted flag never clears a declared value. `sdd upgrade` reinstalls
121/// with no flag at all, so "absent means the default" would erase the
122/// operator's declaration on every upgrade. The flag is two-level on
123/// purpose: absent keeps what is recorded, and `--docs-scratch none` clears
124/// it.
125///
126/// # Errors
127///
128/// [`AppError::ManifestInvalid`] when the recorded value is not a string.
129pub(crate) fn resolved_docs_scratch(
130    target: &Utf8Path,
131    flag: Option<&Option<Utf8PathBuf>>,
132) -> Result<Option<Utf8PathBuf>, AppError> {
133    if let Some(declared) = flag {
134        return Ok(declared.clone());
135    }
136    let Some(recorded) = recorded_field(target, "docs_scratch") else {
137        return Ok(None);
138    };
139    let path = recorded
140        .as_str()
141        .filter(|path| !path.is_empty())
142        .map(Utf8PathBuf::from)
143        .ok_or_else(|| {
144            AppError::ManifestInvalid(format!(
145                "the recorded docs_scratch is not a path ({recorded}); \
146                 re-declare it with --docs-scratch"
147            ))
148        })?;
149    if let Err(error) = validate_docs_scratch_path(&path) {
150        return Err(AppError::ManifestInvalid(format!(
151            "the recorded docs_scratch is not usable ({error}); \
152             re-declare it with --docs-scratch"
153        )));
154    }
155    Ok(Some(path))
156}
157
158/// Every byte one landing would put in a target, and what it would say.
159///
160/// The planner takes this rather than deriving it a second time: what a
161/// release lands into a target is one computation, and two of them would
162/// be two places for one rule to drift.
163#[derive(Debug, Clone)]
164pub struct TargetState {
165    /// Each destination and the bytes that would go there.
166    pub files: Vec<(Utf8PathBuf, Vec<u8>)>,
167    /// What the operator would be told.
168    pub lines: Vec<String>,
169}
170
171/// What this binary would put in a target, and what it would say.
172///
173/// Observation happens here and projection happens in [`crate::candidate`].
174/// Everything this function reads from the target is a value it hands over,
175/// so the bytes a stage renders and the bytes a landing writes come out of
176/// one pure pass over the same evidence.
177///
178/// # Errors
179///
180/// [`AppError::Refused`] when this release declares no such profile, when a
181/// marked region cannot be read, or when the root author-instructions file
182/// is a link, and I/O errors reading the target.
183pub fn compute_target_state(
184    target: &Utf8Path,
185    options: &InitOptions,
186) -> Result<TargetState, AppError> {
187    let candidate = candidate_for(target, options)?;
188    let mut lines: Vec<String> = Vec::new();
189    for destination in &candidate.destinations {
190        lines.push(destination.path.to_string());
191    }
192    lines.extend(candidate.notes.iter().cloned());
193    lines.push(MANIFEST_PATH.to_string());
194    Ok(TargetState {
195        files: candidate.files(),
196        lines,
197    })
198}
199
200/// The candidate this binary renders for one target.
201///
202/// # Errors
203///
204/// As [`compute_target_state`].
205pub fn candidate_for(
206    target: &Utf8Path,
207    options: &InitOptions,
208) -> Result<crate::candidate::Candidate, AppError> {
209    crate::candidate::project(&gather(target, options)?)
210}
211
212/// The target a landing or a stage will read, canonical and known-good.
213///
214/// # Errors
215///
216/// [`AppError::Usage`] for a path no verb can mean: relative, absent, the
217/// filesystem root, or inside the canon checkout.
218pub fn resolved_target(target: &Utf8Path) -> Result<Utf8PathBuf, AppError> {
219    canonical_target(target)
220}
221
222/// Which names of every yield set this release declares exist at the
223/// target root.
224///
225/// A seed that yields reads nothing from these files but their presence:
226/// the project's own configuration governs, whatever its grammar.
227#[must_use]
228pub fn present_at_root(target: &Utf8Path) -> Vec<String> {
229    let mut present: Vec<String> = Vec::new();
230    for projection in &crate::domain::profile::DECLARATION.adopted {
231        let Some(set) = projection.yield_set() else {
232            continue;
233        };
234        for name in set.names() {
235            if target.join(name).is_file() && !present.iter().any(|held| held == name) {
236                present.push(name.to_string());
237            }
238        }
239    }
240    present
241}
242
243/// Read the target once, so the projection never has to.
244fn gather(target: &Utf8Path, options: &InitOptions) -> Result<crate::candidate::Input, AppError> {
245    let docs_root = crate::candidate::docs_root_of(options.profile)?;
246
247    // What the target already records as adopted. A destination that holds
248    // project content and is recorded nowhere is preserved and noted: the
249    // seed does not land, and the project should know the specification it
250    // would have received.
251    let recorded_adopted: Vec<String> = recorded_field(target, "adopted_files")
252        .and_then(|value| {
253            value.as_array().map(|entries| {
254                entries
255                    .iter()
256                    .filter_map(|entry| entry.get("destination")?.as_str().map(String::from))
257                    .collect()
258            })
259        })
260        .unwrap_or_default();
261
262    let mut existing = std::collections::BTreeMap::new();
263    for projection in &crate::domain::profile::DECLARATION.adopted {
264        let destination = resolve_destination(&projection.destination, docs_root);
265        let path = target.join(&destination);
266        if path.is_file() {
267            existing.insert(destination, std::fs::read(&path)?);
268        }
269    }
270
271    let present_at_root = present_at_root(target);
272
273    let hooks_path = target.join(HOOKS_CONFIG_PATH);
274    let hooks_host = if hooks_path.is_file() {
275        std::fs::read_to_string(&hooks_path)?
276    } else {
277        String::new()
278    };
279
280    // The root AGENTS.md documentation block routes authors to the context they
281    // load before editing. A symlinked host is refused before it is read, so a
282    // link cannot redirect the read outside the target.
283    let agents_path = target.join(AGENTS_DIGEST_PATH);
284    if agents_path.is_symlink() {
285        return Err(AppError::Refused(
286            "AGENTS.md is a symlink; refusing to write the documentation block through it"
287                .to_string(),
288        ));
289    }
290    let agents_exists = agents_path.is_file();
291    let agents_host = if agents_exists {
292        std::fs::read_to_string(&agents_path)?
293    } else {
294        String::new()
295    };
296
297    Ok(crate::candidate::Input {
298        profile: options.profile,
299        version: CanonVersion::current(),
300        installed_at: installed_at(target),
301        docs_scratch: resolved_docs_scratch(target, options.docs_scratch.as_ref())?,
302        reserve: options.reserve.clone(),
303        writing_style: options.writing_style.clone(),
304        acquisition: options.acquisition.clone(),
305        evidence: crate::candidate::Evidence {
306            existing,
307            recorded_adopted,
308            hooks_host,
309            agents_host,
310            agents_exists,
311            present_at_root,
312        },
313    })
314}
315
316/// Install or reinstall an instance.
317///
318/// # Errors
319///
320/// [`AppError::Usage`] for a target the arguments cannot mean,
321/// [`AppError::Marker`] for a configuration whose markers cannot be
322/// trusted, and [`AppError::Refused`] when a destination escapes the
323/// target, holds bytes no record accounts for, or cannot be written.
324pub fn init(
325    options: &InitOptions,
326    intent: crate::landing::classify::Intent,
327) -> Result<InitOutcome, AppError> {
328    init_holding(None, options, intent)
329}
330
331/// Install or reinstall an instance under a lock the caller already holds.
332///
333/// A verb that observed the target before it decided to land must hold the
334/// target across both, so the tree it decided from is the tree it writes.
335///
336/// # Errors
337///
338/// As [`init`].
339pub fn init_holding(
340    held: Option<crate::transaction::lock::Lock>,
341    options: &InitOptions,
342    intent: crate::landing::classify::Intent,
343) -> Result<InitOutcome, AppError> {
344    let target = canonical_target(&options.target)?;
345    // The target is known-good before it is classified, so an argument
346    // this verb cannot mean is a usage answer rather than a walk of
347    // whatever the argument happened to name.
348    crate::commands::front::serves(intent, &target)?;
349    let forced_dry = !options.apply
350        && !options.dry_run
351        && target_has_content(&target)?
352        && !target.join(MANIFEST_PATH).is_file();
353    let dry = options.dry_run || forced_dry;
354
355    // A preview reads and writes nothing, so it needs no lock. An apply
356    // holds one across the observation as well as the writes: a candidate
357    // rendered before the lock would describe a target another run could
358    // still be changing. A caller that already holds it passes it in,
359    // because taking it twice from one process proves nothing.
360    let held = match (dry, held) {
361        (true, _) => None,
362        (false, Some(held)) => Some(held),
363        (false, None) => Some(crate::landing::lock::hold(&target)?),
364    };
365
366    // A profile carries the documentation root, so changing it moves every
367    // adopted document to a new home and leaves the old corpus where it
368    // is. That is a migration somebody asks for deliberately, never a
369    // consequence of running a landing verb with a different flag.
370    if let Some(recorded) = recorded_field(&target, "profile").and_then(|value| {
371        ProfileId::every().find(|profile| Some(profile.as_str()) == value.as_str())
372    }) && recorded != options.profile
373    {
374        return Err(AppError::Refused(format!(
375            "{target} records the {recorded} profile and this run asks for {}; \
376             moving a profile moves the documentation root, which is a migration to ask for deliberately",
377            options.profile
378        )));
379    }
380
381    let candidate = candidate_for(&target, options)?;
382    let mut lines: Vec<String> = candidate
383        .destinations
384        .iter()
385        .map(|destination| destination.path.to_string())
386        .collect();
387    lines.extend(candidate.notes.iter().cloned());
388    lines.push(MANIFEST_PATH.to_string());
389
390    if dry {
391        if forced_dry {
392            lines.push(
393                "DRY RUN: the target is a non-empty repository with no instance; re-run with --apply to write these files"
394                    .to_string(),
395            );
396        }
397        lines.push("DRY RUN: no files written".to_string());
398        return Ok(InitOutcome {
399            lines,
400            applied: false,
401            removed: Vec::new(),
402        });
403    }
404
405    let mut vouched = recorded(&target);
406    vouched.replace.clone_from(&options.replace);
407    let outcome = crate::landing::apply::land(&target, &candidate, &vouched)?;
408    drop(held);
409    Ok(InitOutcome {
410        lines,
411        applied: true,
412        removed: outcome.removed,
413    })
414}
415
416/// What the target's own record says this tool owns today.
417///
418/// Read as free JSON, so a record an older release wrote still says which
419/// files this tool may refresh, which regions it may re-splice, and which
420/// files it may take back.
421pub(crate) fn recorded(target: &Utf8Path) -> crate::landing::apply::Recorded {
422    crate::landing::apply::Recorded {
423        managed: digests(target, "managed_files", "destination", "sha256"),
424        integration: digests(target, "integration_blocks", "path", "marker_hash"),
425        replace: Vec::new(),
426    }
427}
428
429/// One recorded list, as pairs of destination and digest.
430fn digests(
431    target: &Utf8Path,
432    key: &str,
433    name: &str,
434    digest: &str,
435) -> Vec<(String, crate::domain::ownership::Sha256)> {
436    let Some(value) = recorded_field(target, key) else {
437        return Vec::new();
438    };
439    let Some(entries) = value.as_array() else {
440        return Vec::new();
441    };
442    entries
443        .iter()
444        .filter_map(|entry| {
445            let destination = entry.get(name)?.as_str()?.to_string();
446            let held = entry.get(digest)?.as_str()?;
447            let held = held.parse::<crate::domain::ownership::Sha256>().ok()?;
448            Some((destination, held))
449        })
450        .collect()
451}