Skip to main content

spec_driven_docs/landing/
classify.rs

1//! What a target is, read from the target and never from the request.
2//!
3//! A front verb says what the operator meant to do. It does not get to say
4//! what the target is: `init` cannot turn a settled corpus into a
5//! greenfield landing by asking nicely, and `upgrade` cannot turn an
6//! absent instance into an upgrade. The classification comes from what was
7//! observed, and a front constrains which classifications it will serve.
8//!
9//! Findings stay orthogonal. A migration with no structural finding and a
10//! migration with five are the same classification and different plans.
11
12use serde::{Deserialize, Serialize};
13use thiserror::Error;
14
15/// What the planner found the target to be.
16#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
17#[serde(rename_all = "kebab-case")]
18pub enum Classification {
19    /// No instance and nothing durable written: land one.
20    Setup,
21    /// No instance and a settled corpus: land one and move the corpus.
22    Migration,
23    /// No instance, and documents outside any recognized home: the
24    /// operator names where they belong before anything lands.
25    NeedsDecision,
26    /// An instance older than the destination.
27    Upgrade,
28    /// An instance at the destination whose files have moved.
29    Drift,
30    /// An instance at the destination with nothing to do.
31    Current,
32    /// Metadata that exists and cannot be trusted.
33    Invalid,
34}
35
36impl Classification {
37    /// The kebab-case word, as the JSON spells it.
38    #[must_use]
39    pub const fn as_str(self) -> &'static str {
40        match self {
41            Self::Setup => "setup",
42            Self::Migration => "migration",
43            Self::NeedsDecision => "needs-decision",
44            Self::Upgrade => "upgrade",
45            Self::Drift => "drift",
46            Self::Current => "current",
47            Self::Invalid => "invalid",
48        }
49    }
50}
51
52impl std::fmt::Display for Classification {
53    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
54        f.write_str(self.as_str())
55    }
56}
57
58/// What a front verb is willing to serve.
59#[derive(Debug, Clone, Copy, PartialEq, Eq)]
60pub enum Intent {
61    /// Whatever the target is.
62    Reconcile,
63    /// A first landing.
64    Init,
65    /// A landing beside a corpus that stays, which the operator names.
66    Incremental,
67    /// A move to a newer release.
68    Upgrade,
69    /// A classification alone, writing nothing.
70    Assess,
71}
72
73/// A front verb asked for a target it does not serve.
74#[derive(Debug, Clone, PartialEq, Eq, Error)]
75#[error("{verb} does not serve a {found} target; run {next}")]
76pub struct IntentRefused {
77    /// The verb the operator ran.
78    pub verb: &'static str,
79    /// What the target turned out to be.
80    pub found: Classification,
81    /// What to run instead.
82    pub next: &'static str,
83}
84
85impl Intent {
86    /// Whether this front serves what the target turned out to be.
87    ///
88    /// # Errors
89    ///
90    /// [`IntentRefused`] naming the verb, the classification, and the next
91    /// command. A front that widened its own scope here would be the
92    /// classification lying about the target.
93    pub const fn accepts(self, found: Classification) -> Result<(), IntentRefused> {
94        match (self, found) {
95            (Self::Reconcile | Self::Assess, _)
96            // A landing verb still reinstalls over an instance it already
97            // owns, which is how a declared location changes. What it may
98            // not do is land seeds beside a convention that is already
99            // there, or over a record nobody can read. Moving the profile
100            // of an installed instance is refused separately, by the
101            // landing itself.
102            | (
103                Self::Init,
104                Classification::Setup
105                | Classification::Upgrade
106                | Classification::Drift
107                | Classification::Current,
108            )
109            | (
110                Self::Upgrade,
111                Classification::Upgrade | Classification::Drift | Classification::Current,
112            )
113            | (Self::Incremental, Classification::Migration) => Ok(()),
114            (Self::Init, _) => Err(IntentRefused {
115                verb: "sdd init",
116                found,
117                next: "sdd stage",
118            }),
119            (Self::Incremental, _) => Err(IntentRefused {
120                verb: "sdd init --incremental",
121                found,
122                next: "sdd init",
123            }),
124            (Self::Upgrade, _) => Err(IntentRefused {
125                verb: "sdd upgrade",
126                found,
127                next: "sdd stage",
128            }),
129        }
130    }
131}
132
133/// What the observation has to say before a classification can be read.
134///
135/// Six independent answers rather than one enumeration, because the
136/// classification is what combines them and a caller that had to pick a
137/// combined value would be classifying before the classifier does.
138#[expect(
139    clippy::struct_excessive_bools,
140    reason = "each field is one independent observation, and folding them would move the classification into the caller"
141)]
142#[derive(Debug, Clone, Copy, PartialEq, Eq)]
143pub struct Signals {
144    /// Metadata exists and cannot be trusted.
145    pub invalid: bool,
146    /// An instance is recorded.
147    pub installed: bool,
148    /// The recorded release is the destination.
149    pub at_destination: bool,
150    /// A recorded file has moved.
151    pub drifted: bool,
152    /// The target documents itself already.
153    pub settled: bool,
154    /// Documents sit outside any recognized home.
155    pub scattered: bool,
156}
157
158/// Read the classification from what was observed.
159#[must_use]
160pub const fn classify(signals: Signals) -> Classification {
161    if signals.invalid {
162        return Classification::Invalid;
163    }
164    if !signals.installed {
165        if signals.settled {
166            return Classification::Migration;
167        }
168        if signals.scattered {
169            return Classification::NeedsDecision;
170        }
171        return Classification::Setup;
172    }
173    if !signals.at_destination {
174        return Classification::Upgrade;
175    }
176    if signals.drifted {
177        return Classification::Drift;
178    }
179    Classification::Current
180}
181
182#[cfg(test)]
183mod tests {
184    use super::*;
185
186    const fn signals() -> Signals {
187        Signals {
188            invalid: false,
189            installed: false,
190            at_destination: false,
191            drifted: false,
192            settled: false,
193            scattered: false,
194        }
195    }
196
197    #[test]
198    fn documents_outside_any_home_need_a_decision_and_a_corpus_wins() {
199        let scattered = Signals {
200            scattered: true,
201            ..signals()
202        };
203        assert_eq!(classify(scattered), Classification::NeedsDecision);
204        let both = Signals {
205            settled: true,
206            ..scattered
207        };
208        assert_eq!(classify(both), Classification::Migration);
209        assert!(Intent::Init.accepts(Classification::NeedsDecision).is_err());
210        assert!(
211            Intent::Upgrade
212                .accepts(Classification::NeedsDecision)
213                .is_err()
214        );
215    }
216
217    #[test]
218    fn each_of_the_seven_target_states_classifies_correctly() {
219        // Empty.
220        assert_eq!(classify(signals()), Classification::Setup);
221        // Brownfield, whether or not it carries structural findings: the
222        // findings are a separate axis and do not move the classification.
223        let settled = Signals {
224            settled: true,
225            ..signals()
226        };
227        assert_eq!(classify(settled), Classification::Migration);
228        // Landed and older than the destination.
229        let old = Signals {
230            installed: true,
231            ..signals()
232        };
233        assert_eq!(classify(old), Classification::Upgrade);
234        // Landed, at the destination, and moved.
235        let drifted = Signals {
236            installed: true,
237            at_destination: true,
238            drifted: true,
239            ..signals()
240        };
241        assert_eq!(classify(drifted), Classification::Drift);
242        // Landed, at the destination, and untouched.
243        let current = Signals {
244            installed: true,
245            at_destination: true,
246            ..signals()
247        };
248        assert_eq!(classify(current), Classification::Current);
249        // Metadata that exists and cannot be trusted.
250        let invalid = Signals {
251            invalid: true,
252            installed: true,
253            ..signals()
254        };
255        assert_eq!(classify(invalid), Classification::Invalid);
256    }
257
258    #[test]
259    fn malformed_metadata_is_invalid_and_never_absence() {
260        // Absence and breakage are different findings, and reporting a
261        // broken instance as absent would invite a destructive landing.
262        let invalid = Signals {
263            invalid: true,
264            ..signals()
265        };
266        assert_eq!(classify(invalid), Classification::Invalid);
267        assert_ne!(classify(invalid), Classification::Setup);
268    }
269
270    #[test]
271    fn init_intent_cannot_force_a_settled_target_to_setup() {
272        let error = Intent::Init.accepts(Classification::Migration).unwrap_err();
273        assert_eq!(error.verb, "sdd init");
274        assert!(error.to_string().contains("sdd stage"));
275        assert!(Intent::Init.accepts(Classification::Setup).is_ok());
276        // A reinstall over an instance the verb already owns still works,
277        // which is how a declared location changes. Moving the profile is
278        // what the landing refuses, not the classification.
279        assert!(Intent::Init.accepts(Classification::Current).is_ok());
280        assert!(Intent::Init.accepts(Classification::Upgrade).is_ok());
281        assert!(Intent::Init.accepts(Classification::Invalid).is_err());
282    }
283
284    #[test]
285    fn upgrade_intent_cannot_turn_an_absent_instance_into_an_upgrade() {
286        assert!(Intent::Upgrade.accepts(Classification::Setup).is_err());
287        assert!(Intent::Upgrade.accepts(Classification::Migration).is_err());
288        assert!(Intent::Upgrade.accepts(Classification::Upgrade).is_ok());
289        assert!(Intent::Upgrade.accepts(Classification::Current).is_ok());
290    }
291
292    #[test]
293    fn reconcile_and_assess_serve_whatever_the_target_is() {
294        for found in [
295            Classification::Setup,
296            Classification::Migration,
297            Classification::NeedsDecision,
298            Classification::Upgrade,
299            Classification::Drift,
300            Classification::Current,
301            Classification::Invalid,
302        ] {
303            assert!(Intent::Reconcile.accepts(found).is_ok());
304            assert!(Intent::Assess.accepts(found).is_ok());
305        }
306    }
307}