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