Skip to main content

spec_driven_docs/services/
status.rs

1//! Report an instance's state as data.
2//!
3//! Status answers what the verifier's text answers, but as one typed
4//! record a machine can branch on, and it treats a missing instance as an
5//! answer rather than an error. A corrupt manifest still raises: absence
6//! and breakage are different findings, and reporting a broken instance as
7//! absent would invite a destructive re-init.
8
9use camino::{Utf8Path, Utf8PathBuf};
10use serde::Serialize;
11
12use crate::domain::manifest::DOCS_SCRATCH_VAR;
13use crate::domain::paths::{
14    self, ActivePaths, Paths, UserEnv, docs_scratch_location, recorded_paths, variable,
15};
16use crate::domain::profile::{DocsRoot, ProfileId};
17use crate::domain::version::CanonVersion;
18use crate::error::AppError;
19use crate::landing::classify::{Classification, Signals, classify};
20use crate::services::verifier;
21
22/// The machine schema this report declares.
23///
24/// Adding a field within a schema is additive. Removing one, renaming one,
25/// changing one's type, or giving a field a value a reader of the old shape
26/// would misread is the next schema, because a reader that branched on the
27/// old shape cannot tell the two apart otherwise. Schema 4 added
28/// `classification`, whose `needs-decision` no earlier reader knew. Schema
29/// 5 added `migration`, and `classification` reads `migration` over a
30/// landed instance while one is open, which no earlier reader expected.
31pub const SCHEMA: &str = "sdd.status/6";
32
33/// How an instance's canon version relates to this binary's.
34#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
35#[serde(rename_all = "kebab-case")]
36pub enum Alignment {
37    /// The versions are equal.
38    Aligned,
39    /// The binary is newer; `sdd upgrade` moves the instance.
40    BinaryNewer,
41    /// The instance is newer; a newer `sdd` is required.
42    InstanceNewer,
43}
44
45/// One instance's state, as `sdd status` reports it.
46#[derive(Debug, Serialize)]
47pub struct StatusReport {
48    /// The machine schema this object declares.
49    pub schema: &'static str,
50    /// What the target is, read from the target alone, or nothing where the
51    /// instance is newer than this binary: an older binary cannot judge a
52    /// record a newer release wrote, and `upgrade` would say it can.
53    ///
54    /// SATISFIES distribution:a-landing-classifies-its-target-first
55    pub classification: Option<Classification>,
56    /// Why the record or the declaration cannot be trusted, where the
57    /// classification is `invalid`.
58    pub invalid: Option<String>,
59    /// Whether the target carries an instance.
60    pub instance: bool,
61    /// The installed profile.
62    pub profile: Option<ProfileId>,
63    /// The instance's documentation root.
64    pub docs_root: Option<DocsRoot>,
65    /// The docs scratch the instance records.
66    pub docs_scratch: Option<Utf8PathBuf>,
67    /// What `SDD_DOCS_SCRATCH` carries here, when it is set. The variable
68    /// overrides the recorded value, so an audit needs both.
69    pub docs_scratch_env: Option<String>,
70    /// The canon version that produced the instance.
71    pub canon_version: Option<CanonVersion>,
72    /// The version this binary carries.
73    pub binary_version: CanonVersion,
74    /// How the two versions relate.
75    pub alignment: Option<Alignment>,
76    /// Managed files missing, symlinked, or byte-drifted.
77    pub managed_drift: usize,
78    /// Adopted files awaiting reconciliation.
79    pub adopted_drift: usize,
80    /// Verification failures in total.
81    pub failures: usize,
82    /// Whether verification passes.
83    pub ok: Option<bool>,
84    /// What an older release left under this user's state and cache roots.
85    ///
86    /// No verb of this release reads any of it, so each entry is a path an
87    /// operator removes by hand once nothing of the older release is still
88    /// running.
89    pub legacy_state: Vec<LegacyState>,
90    /// The migration the declaration holds open, by its id. While one is
91    /// open, `classification` reads `migration`.
92    ///
93    /// SATISFIES setup:an-open-migration-is-declared
94    pub migration: Option<String>,
95    /// Every path this binary can name for this target and this user.
96    ///
97    /// A skill reads this section rather than spelling a path of its own.
98    /// Every entry states what decided it, so a reader can tell a recorded
99    /// answer from a derived one.
100    pub paths: Paths,
101    /// A newer release than the pin, where the version-check cache records
102    /// one. Read offline, from the cache alone.
103    #[serde(skip_serializing_if = "Option::is_none")]
104    pub pending: Option<crate::self_depend::status::Pending>,
105}
106
107/// What this target offers for the docs scratch.
108fn proposals(target: &Utf8Path, env: &UserEnv) -> paths::Proposals {
109    paths::proposals(env, |relative| target.join(relative).is_dir())
110}
111
112/// Every path, with no instance recorded.
113fn derived_paths(target: &Utf8Path, env: &UserEnv) -> Paths {
114    Paths {
115        user: env.user_paths().map(|user| {
116            let legacy = env
117                .legacy_state_root()
118                .map(|root| root.join(crate::domain::paths::SKILL_RECEIPT_FILE));
119            user.with_skill_entries_while_a_receipt_exists(legacy.as_deref())
120        }),
121        active: None,
122        candidates: paths::candidates(),
123        proposals: proposals(target, env),
124    }
125}
126
127fn absent(target: &Utf8Path, classified: Classified) -> StatusReport {
128    let env = UserEnv::from_process();
129    StatusReport {
130        schema: SCHEMA,
131        classification: Some(classified.classification),
132        invalid: classified.invalid,
133        migration: classified.migration,
134        legacy_state: legacy_state(&env),
135        paths: derived_paths(target, &env),
136        instance: false,
137        profile: None,
138        docs_root: None,
139        docs_scratch: None,
140        docs_scratch_env: variable(DOCS_SCRATCH_VAR),
141        canon_version: None,
142        binary_version: CanonVersion::current(),
143        alignment: None,
144        managed_drift: 0,
145        adopted_drift: 0,
146        failures: 0,
147        ok: None,
148        pending: crate::self_depend::status::pending(target, &env),
149    }
150}
151
152/// Report the target's instance state.
153///
154/// # Errors
155///
156/// [`AppError::ManifestInvalid`] when a manifest exists but cannot be
157/// trusted, and I/O errors when the disk cannot be read. A missing
158/// manifest is a report, not an error.
159pub fn status(target: &Utf8Path) -> Result<StatusReport, AppError> {
160    let manifest = match verifier::read_manifest(target) {
161        Ok(manifest) => manifest,
162        Err(AppError::ManifestMissing(_)) => return Ok(absent(target, classify_target(target)?)),
163        Err(error) => return Err(error),
164    };
165    let classified = classify_target(target)?;
166    let report = verifier::verify(target)?;
167    let binary = CanonVersion::current();
168    let alignment = match manifest.canon_version.cmp(&binary) {
169        std::cmp::Ordering::Equal => Alignment::Aligned,
170        std::cmp::Ordering::Less => Alignment::BinaryNewer,
171        std::cmp::Ordering::Greater => Alignment::InstanceNewer,
172    };
173    let env = UserEnv::from_process();
174    let mut resolved = derived_paths(target, &env);
175    resolved.active = Some(ActivePaths {
176        profile: manifest.profile,
177        destinations: recorded_paths(manifest.docs_root),
178        docs_scratch: docs_scratch_location(manifest.docs_scratch.as_deref(), &env),
179    });
180    Ok(StatusReport {
181        schema: SCHEMA,
182        classification: (alignment != Alignment::InstanceNewer)
183            .then_some(classified.classification),
184        invalid: classified.invalid,
185        migration: classified.migration,
186        legacy_state: legacy_state(&env),
187        paths: resolved,
188        instance: true,
189        profile: Some(manifest.profile),
190        docs_root: Some(manifest.docs_root),
191        docs_scratch: manifest.docs_scratch,
192        docs_scratch_env: variable(DOCS_SCRATCH_VAR),
193        canon_version: Some(manifest.canon_version),
194        binary_version: binary,
195        alignment: Some(alignment),
196        managed_drift: report.managed_drift,
197        adopted_drift: report.adopted_drift,
198        failures: report.failures,
199        ok: Some(report.failures == 0),
200        pending: crate::self_depend::status::pending(target, &env),
201    })
202}
203
204/// One directory or file an older release kept, and what it held.
205#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
206pub struct LegacyState {
207    /// Where it is.
208    pub path: Utf8PathBuf,
209    /// What it held, as one word.
210    pub kind: &'static str,
211    /// Whether it still binds a run: a plan the older release has not
212    /// finished, or a journal of a run it did not finish. Only that release
213    /// can finish or abandon such a run.
214    pub active: bool,
215}
216
217/// What the releases that stored plans left under the user-scope roots.
218///
219/// The names are the ones those releases wrote, and this release writes
220/// none of them. The list is closed: a path this tool never wrote is not
221/// its to name.
222const LEGACY_STATE: [(&str, &str); 3] = [
223    ("plans", "plan-store"),
224    ("backups", "transaction-backups"),
225    ("skills.journal", "skill-journal"),
226];
227
228/// The bundle cache those releases kept under the cache root.
229const LEGACY_CACHE: (&str, &str) = ("bundles", "bundle-cache");
230
231/// Every legacy entry present on this host.
232///
233/// SATISFIES setup:status-reports-what-an-older-release-left
234fn legacy_state(env: &UserEnv) -> Vec<LegacyState> {
235    let mut found = Vec::new();
236    if let Some(state) = env.state_root() {
237        for (name, kind) in LEGACY_STATE {
238            let path = state.path.join(name);
239            if path.symlink_metadata().is_ok() {
240                let active = match kind {
241                    // A finished plan leaves the store with its result, so
242                    // a plan still there is one nobody finished.
243                    "plan-store" => std::fs::read_dir(path.join("plans"))
244                        .is_ok_and(|mut plans| plans.any(|plan| plan.is_ok())),
245                    // A run that finished removed its journal.
246                    "skill-journal" => true,
247                    _ => false,
248                };
249                found.push(LegacyState { path, kind, active });
250            }
251        }
252    }
253    if let Some(cache) = env.cache_root() {
254        let path = cache.path.join(LEGACY_CACHE.0);
255        if path.symlink_metadata().is_ok() {
256            found.push(LegacyState {
257                path,
258                kind: LEGACY_CACHE.1,
259                active: false,
260            });
261        }
262    }
263    found
264}
265
266/// One target's classification, and why it is `invalid` where it is.
267#[derive(Debug, Clone, PartialEq, Eq)]
268pub struct Classified {
269    /// What the target is.
270    pub classification: Classification,
271    /// Why the metadata cannot be trusted, where it cannot.
272    pub invalid: Option<String>,
273    /// The migration the declaration holds open, by its id.
274    pub migration: Option<String>,
275    /// What the target is beneath an open migration: the state its files
276    /// alone show, which a landing verb serves while the migration is open.
277    pub beneath: Classification,
278}
279
280/// Read what `target` is, from the target alone.
281///
282/// One rule serves every reader: the status report and each front verb.
283/// With no instance, documents decide, not directories: a target with no
284/// durable document beyond root metadata is a first landing, whatever
285/// layout it started. Documents in a recognized home, by the rule
286/// `sdd assess` applies, are a migration, and documents with no such home
287/// are a decision the operator owes. With an instance, the record decides,
288/// and a declaration that does not parse is metadata nobody can trust. A
289/// path that is not a directory has nothing written in it, so it reads as
290/// `setup`.
291///
292/// # Errors
293///
294/// [`AppError::Io`] when the walk cannot complete.
295pub fn classify_target(target: &Utf8Path) -> Result<Classified, AppError> {
296    if !target.is_dir() {
297        return Ok(Classified {
298            classification: Classification::Setup,
299            invalid: None,
300            migration: None,
301            beneath: Classification::Setup,
302        });
303    }
304    let observation = crate::landing::observe::observe(target)?;
305    let invalid = match (&observation.invalid, &observation.installation) {
306        (Some(reason), _) => Some(reason.clone()),
307        // A declaration an archive wrote stands before any instance, so it
308        // is judged whenever it exists: an id that is not a migration id is
309        // an invalid declaration, never a migration nobody can find.
310        (None, _) => crate::domain::instance_config::InstanceConfig::read(target)
311            .err()
312            .map(|error| error.to_string()),
313    };
314    let written =
315        observation.installation.is_none() && invalid.is_none() && observation.corpus.settled();
316    // Where the written documents belong is the assess rule's answer. A
317    // target whose only documents sit in the docs scratch has written none
318    // the convention keeps, so it reads as a first landing.
319    let verdict = if written {
320        Some(
321            crate::services::assess::corpus(target, crate::gates::paths::docs_scratch_variable())?
322                .verdict(),
323        )
324    } else {
325        None
326    };
327    let homed = verdict == Some(crate::services::assess::Classification::Brownfield);
328    let scattered = verdict == Some(crate::services::assess::Classification::NeedsDecision);
329    let classification = classify(Signals {
330        invalid: invalid.is_some(),
331        installed: observation.installation.is_some(),
332        // The destination is this binary's own release for every reader.
333        at_destination: observation
334            .installation
335            .as_ref()
336            .is_some_and(|installed| installed.canon_version == CanonVersion::current()),
337        drifted: observation
338            .installation
339            .as_ref()
340            .is_some_and(crate::landing::observe::Installation::drifted),
341        settled: homed,
342        scattered,
343    });
344    // An open migration is the state until it closes, whatever the files
345    // beneath it show: the corpus sits in the archive, and the instance a
346    // migration lands is the start of the rebuild, not its end.
347    let migration = if invalid.is_none() {
348        crate::domain::instance_config::InstanceConfig::read(target)
349            .ok()
350            .and_then(|declaration| declaration.migration)
351    } else {
352        None
353    };
354    Ok(Classified {
355        classification: if migration.is_some() {
356            Classification::Migration
357        } else {
358            classification
359        },
360        invalid,
361        migration,
362        beneath: classification,
363    })
364}