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