Skip to main content

spec_driven_docs/
probes.rs

1//! The environment probe catalog.
2//!
3//! One catalog, read by every caller that needs to know whether this host
4//! is ready: `sdd doctor` runs it whole and reports by class. Each probe
5//! answers with a status, a message, and — on failure — the remediation
6//! printed verbatim wherever the probe is consulted. A probe failure is a
7//! result, not an error, so nothing here returns `Err`.
8
9use std::process::Command;
10
11use camino::Utf8PathBuf;
12use serde::Serialize;
13
14use crate::domain::ownership::Sha256;
15use crate::domain::paths::{AgentId, OFFLINE_VAR, SKILL_FILE, SKILL_RECEIPT_FILE, UserEnv};
16use crate::domain::skill_record::SkillRecord;
17
18/// Every agent skill root under this home, resolved through the table.
19///
20/// The table is the one place that knows a variable moved a root, so a
21/// probe that joined the defaults instead would report a directory the
22/// install never writes.
23fn agent_roots() -> Vec<Utf8PathBuf> {
24    UserEnv::from_process()
25        .agent_roots(&[AgentId::Claude, AgentId::Agents])
26        .into_iter()
27        .map(|entry| entry.path)
28        .collect()
29}
30
31/// The state root this host resolves.
32fn resolved_state_root() -> Option<Utf8PathBuf> {
33    UserEnv::from_process().state_root().map(|entry| entry.path)
34}
35
36/// The receipt, read from the resolved path or the home-relative one.
37fn receipt() -> SkillRecord {
38    let env = UserEnv::from_process();
39    let Some(state) = env.state_root() else {
40        return SkillRecord::new();
41    };
42    let legacy = env
43        .legacy_state_root()
44        .map_or_else(|| state.path.clone(), |root| root.join(SKILL_RECEIPT_FILE));
45    SkillRecord::load_with_fallback(&state.path.join(SKILL_RECEIPT_FILE), &legacy)
46}
47
48/// How a failure weighs at the doctor level.
49#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
50#[serde(rename_all = "kebab-case")]
51pub enum ProbeClass {
52    /// No install under the user's home can work without this.
53    Hard,
54    /// Needed only by some commands or some tasks.
55    Soft,
56}
57
58/// What a probe found.
59#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
60#[serde(rename_all = "kebab-case")]
61pub enum ProbeStatus {
62    /// The probe passed.
63    Ok,
64    /// The probe failed; the remediation says what fixes it.
65    Failed,
66}
67
68/// One probe's answer.
69#[derive(Debug, Serialize)]
70pub struct ProbeResult {
71    /// The probe's stable name.
72    pub id: &'static str,
73    /// How the failure weighs.
74    pub class: ProbeClass,
75    /// What was found.
76    pub status: ProbeStatus,
77    /// What was found, one line.
78    pub message: String,
79    /// The exact fix, when the probe failed.
80    #[serde(skip_serializing_if = "Option::is_none")]
81    pub remediation: Option<String>,
82}
83
84impl ProbeResult {
85    fn ok(id: &'static str, class: ProbeClass, message: impl Into<String>) -> Self {
86        Self {
87            id,
88            class,
89            status: ProbeStatus::Ok,
90            message: message.into(),
91            remediation: None,
92        }
93    }
94
95    fn failed(
96        id: &'static str,
97        class: ProbeClass,
98        message: impl Into<String>,
99        remediation: impl Into<String>,
100    ) -> Self {
101        Self {
102            id,
103            class,
104            status: ProbeStatus::Failed,
105            message: message.into(),
106            remediation: Some(remediation.into()),
107        }
108    }
109}
110
111/// The probes judging the skill installation itself, in catalog order.
112///
113/// Declared here rather than derived by running the catalog: the shared
114/// pre-flight gate must name each of these, and the test holding it to that
115/// must not have to write into the operator's home to learn what they are.
116pub const SKILL_PROBES: [&str; 1] = ["skill-shadow"];
117
118/// Run the whole catalog, in its stable order.
119#[must_use]
120pub fn run_all() -> Vec<ProbeResult> {
121    vec![
122        state_root(),
123        skill_shadow(),
124        registry(),
125        pin_fresh(),
126        tool(
127            "git",
128            "SDD_GIT_BIN",
129            "git",
130            "git; retiring a migrated document is safe only where version control restores it",
131            &["--version"],
132        ),
133        tool(
134            "prek",
135            "SDD_PREK_BIN",
136            "prek",
137            "prek; the delivered gates run through it",
138            &["--version"],
139        ),
140    ]
141}
142
143/// A host tool answers its version call. `env_override` names the
144/// substitute, which is also what keeps tests hermetic; presence is the
145/// whole question, because the tools here take no configuration.
146///
147/// The probe only reports. No command reads its result to pick a tool or
148/// to skip a step: a command that needs the tool runs it, and fails where
149/// the host lacks it.
150fn tool(
151    id: &'static str,
152    env_override: &str,
153    default_bin: &str,
154    label: &str,
155    args: &[&str],
156) -> ProbeResult {
157    let bin = std::env::var(env_override).unwrap_or_else(|_| default_bin.to_owned());
158    match Command::new(&bin).args(args).output() {
159        Ok(out) if out.status.success() => {
160            ProbeResult::ok(id, ProbeClass::Soft, format!("{default_bin} runs"))
161        }
162        Ok(_) => ProbeResult::failed(
163            id,
164            ProbeClass::Soft,
165            format!("{default_bin} does not answer {}", args.join(" ")),
166            format!("repair {label}"),
167        ),
168        Err(_) => ProbeResult::failed(
169            id,
170            ProbeClass::Soft,
171            format!("{default_bin} is not on PATH"),
172            format!("install {label}"),
173        ),
174    }
175}
176
177/// The pin of the current folder against the newest release the
178/// version-check cache records, offline.
179///
180/// Soft, because a pin that is behind is the operator's to move, and
181/// unknown where the folder pins nothing or no check has run yet. A pin
182/// that is behind fails with the pending text as its remediation.
183///
184/// SATISFIES acquisition:every-report-names-a-pending-move
185fn pin_fresh() -> ProbeResult {
186    use crate::self_depend::status::{PinFreshness, freshness};
187    let id = "pin-fresh";
188    let Some(folder) = std::env::current_dir()
189        .ok()
190        .and_then(|dir| Utf8PathBuf::from_path_buf(dir).ok())
191    else {
192        return ProbeResult::ok(
193            id,
194            ProbeClass::Soft,
195            "unknown: the current folder is unreadable",
196        );
197    };
198    match freshness(&folder, &UserEnv::from_process()) {
199        PinFreshness::Unknown => ProbeResult::ok(
200            id,
201            ProbeClass::Soft,
202            "unknown: no pin or no version check recorded here",
203        ),
204        PinFreshness::Current { pin } => ProbeResult::ok(
205            id,
206            ProbeClass::Soft,
207            format!("ok: the pin {pin} names the newest recorded release"),
208        ),
209        PinFreshness::Behind(pending) => ProbeResult::failed(
210            id,
211            ProbeClass::Soft,
212            format!(
213                "behind: sdd {} is out, the pin names {}",
214                pending.latest, pending.pin
215            ),
216            pending.text,
217        ),
218    }
219}
220
221/// The registry the release resolver reads is reachable.
222///
223/// Soft, because a host that cannot fetch is a constraint on a plan rather
224/// than a broken install: every default path reads the embedded release,
225/// and only a plan toward another release needs this. The probe reads the
226/// registry's own configuration, which is the smallest document the
227/// protocol defines, and writes nothing.
228fn registry() -> ProbeResult {
229    let id = "release-registry";
230    let url = format!("{}/config.json", crate::self_depend::registry::INDEX_ROOT);
231    // One variable turns the read off, for a host that is deliberately
232    // offline and for every test in this repository's own suite.
233    if crate::domain::paths::variable(OFFLINE_VAR).is_some() {
234        return ProbeResult::ok(
235            id,
236            ProbeClass::Soft,
237            "SDD_OFFLINE is set, so no release beyond the embedded one is planned",
238        );
239    }
240    // A probe's budget is not a fetch's budget: an unreachable registry
241    // must answer this question in seconds, not in the minute a bounded
242    // archive read is allowed.
243    let agent: ureq::Agent = ureq::Agent::config_builder()
244        .timeout_connect(Some(std::time::Duration::from_secs(3)))
245        .timeout_global(Some(std::time::Duration::from_secs(5)))
246        .user_agent(format!("sdd/{}", env!("CARGO_PKG_VERSION")))
247        .build()
248        .into();
249    match agent.get(&url).call() {
250        Ok(response) if response.status().as_u16() == 200 => {
251            ProbeResult::ok(id, ProbeClass::Soft, format!("{url} answers"))
252        }
253        Ok(response) => ProbeResult::failed(
254            id,
255            ProbeClass::Soft,
256            format!("{url} answered {}", response.status().as_u16()),
257            "plan toward the embedded release, or retry when the registry answers",
258        ),
259        Err(source) => ProbeResult::failed(
260            id,
261            ProbeClass::Soft,
262            format!("{url} could not be read: {source}"),
263            "plan toward the embedded release; only a plan toward another release needs the registry",
264        ),
265    }
266}
267
268/// The state root accepts writes; the receipt, the lock, and the journal
269/// live under it.
270fn state_root() -> ProbeResult {
271    let id = "state-root";
272    let Some(root) = resolved_state_root() else {
273        return ProbeResult::failed(
274            id,
275            ProbeClass::Hard,
276            "HOME is not set, so no state root resolves",
277            "export HOME",
278        );
279    };
280    let probe = root.join(format!(".probe-{}", std::process::id()));
281    let written = std::fs::create_dir_all(&root).and_then(|()| std::fs::write(&probe, b"probe"));
282    let _ = std::fs::remove_file(&probe);
283    match written {
284        Ok(()) => ProbeResult::ok(id, ProbeClass::Hard, format!("{root} is writable")),
285        Err(source) => ProbeResult::failed(
286            id,
287            ProbeClass::Hard,
288            format!("{root} is not writable: {source}"),
289            format!("make {root} writable"),
290        ),
291    }
292}
293
294/// No copy of a payload skill under a home agent root shadows the copy an
295/// instance pins.
296///
297/// An agent prefers a personal skill over a project skill of the same name,
298/// or shows both, so a `SKILL.md` an earlier release installed under the
299/// home hides the one the project landed. A folder holding only notes
300/// passes. A manual the receipt no longer vouches for is the operator's
301/// edit, which the uninstall keeps, so the probe asks for a hand removal.
302///
303/// SATISFIES distribution:the-doctor-names-a-shadowing-user-copy
304fn skill_shadow() -> ProbeResult {
305    let id = "skill-shadow";
306    let record = receipt();
307    let mut vouched = Vec::new();
308    let mut edited = Vec::new();
309    for root in agent_roots() {
310        for name in crate::embedded::skill_names() {
311            let manual = root.join(name).join(SKILL_FILE);
312            let Ok(bytes) = std::fs::read(&manual) else {
313                continue;
314            };
315            if record.wrote(&manual, &Sha256::of(&bytes)) {
316                vouched.push(manual);
317            } else {
318                edited.push(manual);
319            }
320        }
321    }
322    if vouched.is_empty() && edited.is_empty() {
323        return ProbeResult::ok(
324            id,
325            ProbeClass::Soft,
326            "no sdd skill under a home agent root shadows an instance copy",
327        );
328    }
329    let mut found: Vec<String> = vouched.iter().map(ToString::to_string).collect();
330    found.extend(edited.iter().map(|path| format!("{path} (edited)")));
331    let remediation = if edited.is_empty() {
332        "sdd skill uninstall --apply".to_string()
333    } else if vouched.is_empty() {
334        "read each edited manual, keep what you need elsewhere, and remove it by hand".to_string()
335    } else {
336        "sdd skill uninstall --apply, then read each edited manual it keeps and remove it by hand"
337            .to_string()
338    };
339    ProbeResult::failed(
340        id,
341        ProbeClass::Soft,
342        format!(
343            "a home copy shadows the skill each instance pins: {}",
344            found.join(", ")
345        ),
346        remediation,
347    )
348}
349
350#[cfg(test)]
351mod tests {
352    #![allow(
353        clippy::unwrap_used,
354        reason = "a test panics as its failure signal, not as control flow"
355    )]
356
357    use super::*;
358
359    #[test]
360    fn the_skill_probes_are_in_the_catalog() {
361        for id in SKILL_PROBES {
362            assert!(run_all().iter().any(|probe| probe.id == id), "{id}");
363        }
364    }
365}