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/5";
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}
102
103/// What this target offers for the docs scratch.
104fn proposals(target: &Utf8Path, env: &UserEnv) -> paths::Proposals {
105 paths::proposals(env, |relative| target.join(relative).is_dir())
106}
107
108/// Every path, with no instance recorded.
109fn derived_paths(target: &Utf8Path, env: &UserEnv) -> Paths {
110 Paths {
111 user: env.user_paths(),
112 active: None,
113 candidates: paths::candidates(),
114 proposals: proposals(target, env),
115 }
116}
117
118fn absent(target: &Utf8Path, classified: Classified) -> StatusReport {
119 let env = UserEnv::from_process();
120 StatusReport {
121 schema: SCHEMA,
122 classification: Some(classified.classification),
123 invalid: classified.invalid,
124 migration: classified.migration,
125 legacy_state: legacy_state(&env),
126 paths: derived_paths(target, &env),
127 instance: false,
128 profile: None,
129 docs_root: None,
130 docs_scratch: None,
131 docs_scratch_env: variable(DOCS_SCRATCH_VAR),
132 canon_version: None,
133 binary_version: CanonVersion::current(),
134 alignment: None,
135 managed_drift: 0,
136 adopted_drift: 0,
137 failures: 0,
138 ok: None,
139 }
140}
141
142/// Report the target's instance state.
143///
144/// # Errors
145///
146/// [`AppError::ManifestInvalid`] when a manifest exists but cannot be
147/// trusted, and I/O errors when the disk cannot be read. A missing
148/// manifest is a report, not an error.
149pub fn status(target: &Utf8Path) -> Result<StatusReport, AppError> {
150 let manifest = match verifier::read_manifest(target) {
151 Ok(manifest) => manifest,
152 Err(AppError::ManifestMissing(_)) => return Ok(absent(target, classify_target(target)?)),
153 Err(error) => return Err(error),
154 };
155 let classified = classify_target(target)?;
156 let report = verifier::verify(target)?;
157 let binary = CanonVersion::current();
158 let alignment = match manifest.canon_version.cmp(&binary) {
159 std::cmp::Ordering::Equal => Alignment::Aligned,
160 std::cmp::Ordering::Less => Alignment::BinaryNewer,
161 std::cmp::Ordering::Greater => Alignment::InstanceNewer,
162 };
163 let env = UserEnv::from_process();
164 let mut resolved = derived_paths(target, &env);
165 resolved.active = Some(ActivePaths {
166 profile: manifest.profile,
167 destinations: recorded_paths(manifest.docs_root),
168 docs_scratch: docs_scratch_location(manifest.docs_scratch.as_deref(), &env),
169 });
170 Ok(StatusReport {
171 schema: SCHEMA,
172 classification: (alignment != Alignment::InstanceNewer)
173 .then_some(classified.classification),
174 invalid: classified.invalid,
175 migration: classified.migration,
176 legacy_state: legacy_state(&env),
177 paths: resolved,
178 instance: true,
179 profile: Some(manifest.profile),
180 docs_root: Some(manifest.docs_root),
181 docs_scratch: manifest.docs_scratch,
182 docs_scratch_env: variable(DOCS_SCRATCH_VAR),
183 canon_version: Some(manifest.canon_version),
184 binary_version: binary,
185 alignment: Some(alignment),
186 managed_drift: report.managed_drift,
187 adopted_drift: report.adopted_drift,
188 failures: report.failures,
189 ok: Some(report.failures == 0),
190 })
191}
192
193/// One directory or file an older release kept, and what it held.
194#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
195pub struct LegacyState {
196 /// Where it is.
197 pub path: Utf8PathBuf,
198 /// What it held, as one word.
199 pub kind: &'static str,
200 /// Whether it still binds a run: a plan the older release has not
201 /// finished, or a journal of a run it did not finish. Only that release
202 /// can finish or abandon such a run.
203 pub active: bool,
204}
205
206/// What the releases that stored plans left under the user-scope roots.
207///
208/// The names are the ones those releases wrote, and this release writes
209/// none of them. The list is closed: a path this tool never wrote is not
210/// its to name.
211const LEGACY_STATE: [(&str, &str); 3] = [
212 ("plans", "plan-store"),
213 ("backups", "transaction-backups"),
214 ("skills.journal", "skill-journal"),
215];
216
217/// The bundle cache those releases kept under the cache root.
218const LEGACY_CACHE: (&str, &str) = ("bundles", "bundle-cache");
219
220/// Every legacy entry present on this host.
221///
222/// SATISFIES setup:status-reports-what-an-older-release-left
223fn legacy_state(env: &UserEnv) -> Vec<LegacyState> {
224 let mut found = Vec::new();
225 if let Some(state) = env.state_root() {
226 for (name, kind) in LEGACY_STATE {
227 let path = state.path.join(name);
228 if path.symlink_metadata().is_ok() {
229 let active = match kind {
230 // A finished plan leaves the store with its result, so
231 // a plan still there is one nobody finished.
232 "plan-store" => std::fs::read_dir(path.join("plans"))
233 .is_ok_and(|mut plans| plans.any(|plan| plan.is_ok())),
234 // A run that finished removed its journal.
235 "skill-journal" => true,
236 _ => false,
237 };
238 found.push(LegacyState { path, kind, active });
239 }
240 }
241 }
242 if let Some(cache) = env.cache_root() {
243 let path = cache.path.join(LEGACY_CACHE.0);
244 if path.symlink_metadata().is_ok() {
245 found.push(LegacyState {
246 path,
247 kind: LEGACY_CACHE.1,
248 active: false,
249 });
250 }
251 }
252 found
253}
254
255/// One target's classification, and why it is `invalid` where it is.
256#[derive(Debug, Clone, PartialEq, Eq)]
257pub struct Classified {
258 /// What the target is.
259 pub classification: Classification,
260 /// Why the metadata cannot be trusted, where it cannot.
261 pub invalid: Option<String>,
262 /// The migration the declaration holds open, by its id.
263 pub migration: Option<String>,
264 /// What the target is beneath an open migration: the state its files
265 /// alone show, which a landing verb serves while the migration is open.
266 pub beneath: Classification,
267}
268
269/// Read what `target` is, from the target alone.
270///
271/// One rule serves every reader: the status report and each front verb.
272/// With no instance, documents decide, not directories: a target with no
273/// durable document beyond root metadata is a first landing, whatever
274/// layout it started. Documents in a recognized home, by the rule
275/// `sdd assess` applies, are a migration, and documents with no such home
276/// are a decision the operator owes. With an instance, the record decides,
277/// and a declaration that does not parse is metadata nobody can trust. A
278/// path that is not a directory has nothing written in it, so it reads as
279/// `setup`.
280///
281/// # Errors
282///
283/// [`AppError::Io`] when the walk cannot complete.
284pub fn classify_target(target: &Utf8Path) -> Result<Classified, AppError> {
285 if !target.is_dir() {
286 return Ok(Classified {
287 classification: Classification::Setup,
288 invalid: None,
289 migration: None,
290 beneath: Classification::Setup,
291 });
292 }
293 let observation = crate::landing::observe::observe(target)?;
294 let invalid = match (&observation.invalid, &observation.installation) {
295 (Some(reason), _) => Some(reason.clone()),
296 // A declaration an archive wrote stands before any instance, so it
297 // is judged whenever it exists: an id that is not a migration id is
298 // an invalid declaration, never a migration nobody can find.
299 (None, _) => crate::domain::instance_config::InstanceConfig::read(target)
300 .err()
301 .map(|error| error.to_string()),
302 };
303 let written =
304 observation.installation.is_none() && invalid.is_none() && observation.corpus.settled();
305 // Where the written documents belong is the assess rule's answer. A
306 // target whose only documents sit in the docs scratch has written none
307 // the convention keeps, so it reads as a first landing.
308 let verdict = if written {
309 Some(
310 crate::services::assess::corpus(target, crate::gates::paths::docs_scratch_variable())?
311 .verdict(),
312 )
313 } else {
314 None
315 };
316 let homed = verdict == Some(crate::services::assess::Classification::Brownfield);
317 let scattered = verdict == Some(crate::services::assess::Classification::NeedsDecision);
318 let classification = classify(Signals {
319 invalid: invalid.is_some(),
320 installed: observation.installation.is_some(),
321 // The destination is this binary's own release for every reader.
322 at_destination: observation
323 .installation
324 .as_ref()
325 .is_some_and(|installed| installed.canon_version == CanonVersion::current()),
326 drifted: observation
327 .installation
328 .as_ref()
329 .is_some_and(crate::landing::observe::Installation::drifted),
330 settled: homed,
331 scattered,
332 });
333 // An open migration is the state until it closes, whatever the files
334 // beneath it show: the corpus sits in the archive, and the instance a
335 // migration lands is the start of the rebuild, not its end.
336 let migration = if invalid.is_none() {
337 crate::domain::instance_config::InstanceConfig::read(target)
338 .ok()
339 .and_then(|declaration| declaration.migration)
340 } else {
341 None
342 };
343 Ok(Classified {
344 classification: if migration.is_some() {
345 Classification::Migration
346 } else {
347 classification
348 },
349 invalid,
350 migration,
351 beneath: classification,
352 })
353}