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        tool(
126            "git",
127            "SDD_GIT_BIN",
128            "git",
129            "git; retiring a migrated document is safe only where version control restores it",
130            &["--version"],
131        ),
132        tool(
133            "prek",
134            "SDD_PREK_BIN",
135            "prek",
136            "prek; the delivered gates run through it",
137            &["--version"],
138        ),
139    ]
140}
141
142/// A host tool answers its version call. `env_override` names the
143/// substitute, which is also what keeps tests hermetic; presence is the
144/// whole question, because the tools here take no configuration.
145///
146/// The probe only reports. No command reads its result to pick a tool or
147/// to skip a step: a command that needs the tool runs it, and fails where
148/// the host lacks it.
149fn tool(
150    id: &'static str,
151    env_override: &str,
152    default_bin: &str,
153    label: &str,
154    args: &[&str],
155) -> ProbeResult {
156    let bin = std::env::var(env_override).unwrap_or_else(|_| default_bin.to_owned());
157    match Command::new(&bin).args(args).output() {
158        Ok(out) if out.status.success() => {
159            ProbeResult::ok(id, ProbeClass::Soft, format!("{default_bin} runs"))
160        }
161        Ok(_) => ProbeResult::failed(
162            id,
163            ProbeClass::Soft,
164            format!("{default_bin} does not answer {}", args.join(" ")),
165            format!("repair {label}"),
166        ),
167        Err(_) => ProbeResult::failed(
168            id,
169            ProbeClass::Soft,
170            format!("{default_bin} is not on PATH"),
171            format!("install {label}"),
172        ),
173    }
174}
175
176/// The registry the release resolver reads is reachable.
177///
178/// Soft, because a host that cannot fetch is a constraint on a plan rather
179/// than a broken install: every default path reads the embedded release,
180/// and only a plan toward another release needs this. The probe reads the
181/// registry's own configuration, which is the smallest document the
182/// protocol defines, and writes nothing.
183fn registry() -> ProbeResult {
184    let id = "release-registry";
185    let url = format!("{}/config.json", crate::self_depend::registry::INDEX_ROOT);
186    // One variable turns the read off, for a host that is deliberately
187    // offline and for every test in this repository's own suite.
188    if crate::domain::paths::variable(OFFLINE_VAR).is_some() {
189        return ProbeResult::ok(
190            id,
191            ProbeClass::Soft,
192            "SDD_OFFLINE is set, so no release beyond the embedded one is planned",
193        );
194    }
195    // A probe's budget is not a fetch's budget: an unreachable registry
196    // must answer this question in seconds, not in the minute a bounded
197    // archive read is allowed.
198    let agent: ureq::Agent = ureq::Agent::config_builder()
199        .timeout_connect(Some(std::time::Duration::from_secs(3)))
200        .timeout_global(Some(std::time::Duration::from_secs(5)))
201        .user_agent(format!("sdd/{}", env!("CARGO_PKG_VERSION")))
202        .build()
203        .into();
204    match agent.get(&url).call() {
205        Ok(response) if response.status().as_u16() == 200 => {
206            ProbeResult::ok(id, ProbeClass::Soft, format!("{url} answers"))
207        }
208        Ok(response) => ProbeResult::failed(
209            id,
210            ProbeClass::Soft,
211            format!("{url} answered {}", response.status().as_u16()),
212            "plan toward the embedded release, or retry when the registry answers",
213        ),
214        Err(source) => ProbeResult::failed(
215            id,
216            ProbeClass::Soft,
217            format!("{url} could not be read: {source}"),
218            "plan toward the embedded release; only a plan toward another release needs the registry",
219        ),
220    }
221}
222
223/// The state root accepts writes; the receipt, the lock, and the journal
224/// live under it.
225fn state_root() -> ProbeResult {
226    let id = "state-root";
227    let Some(root) = resolved_state_root() else {
228        return ProbeResult::failed(
229            id,
230            ProbeClass::Hard,
231            "HOME is not set, so no state root resolves",
232            "export HOME",
233        );
234    };
235    let probe = root.join(format!(".probe-{}", std::process::id()));
236    let written = std::fs::create_dir_all(&root).and_then(|()| std::fs::write(&probe, b"probe"));
237    let _ = std::fs::remove_file(&probe);
238    match written {
239        Ok(()) => ProbeResult::ok(id, ProbeClass::Hard, format!("{root} is writable")),
240        Err(source) => ProbeResult::failed(
241            id,
242            ProbeClass::Hard,
243            format!("{root} is not writable: {source}"),
244            format!("make {root} writable"),
245        ),
246    }
247}
248
249/// No copy of a payload skill under a home agent root shadows the copy an
250/// instance pins.
251///
252/// An agent prefers a personal skill over a project skill of the same name,
253/// or shows both, so a `SKILL.md` an earlier release installed under the
254/// home hides the one the project landed. A folder holding only notes
255/// passes. A manual the receipt no longer vouches for is the operator's
256/// edit, which the uninstall keeps, so the probe asks for a hand removal.
257///
258/// SATISFIES distribution:the-doctor-names-a-shadowing-user-copy
259fn skill_shadow() -> ProbeResult {
260    let id = "skill-shadow";
261    let record = receipt();
262    let mut vouched = Vec::new();
263    let mut edited = Vec::new();
264    for root in agent_roots() {
265        for name in crate::embedded::skill_names() {
266            let manual = root.join(name).join(SKILL_FILE);
267            let Ok(bytes) = std::fs::read(&manual) else {
268                continue;
269            };
270            if record.wrote(&manual, &Sha256::of(&bytes)) {
271                vouched.push(manual);
272            } else {
273                edited.push(manual);
274            }
275        }
276    }
277    if vouched.is_empty() && edited.is_empty() {
278        return ProbeResult::ok(
279            id,
280            ProbeClass::Soft,
281            "no sdd skill under a home agent root shadows an instance copy",
282        );
283    }
284    let mut found: Vec<String> = vouched.iter().map(ToString::to_string).collect();
285    found.extend(edited.iter().map(|path| format!("{path} (edited)")));
286    let remediation = if edited.is_empty() {
287        "sdd skill uninstall --apply".to_string()
288    } else if vouched.is_empty() {
289        "read each edited manual, keep what you need elsewhere, and remove it by hand".to_string()
290    } else {
291        "sdd skill uninstall --apply, then read each edited manual it keeps and remove it by hand"
292            .to_string()
293    };
294    ProbeResult::failed(
295        id,
296        ProbeClass::Soft,
297        format!(
298            "a home copy shadows the skill each instance pins: {}",
299            found.join(", ")
300        ),
301        remediation,
302    )
303}
304
305#[cfg(test)]
306mod tests {
307    #![allow(
308        clippy::unwrap_used,
309        reason = "a test panics as its failure signal, not as control flow"
310    )]
311
312    use super::*;
313
314    #[test]
315    fn the_skill_probes_are_in_the_catalog() {
316        for id in SKILL_PROBES {
317            assert!(run_all().iter().any(|probe| probe.id == id), "{id}");
318        }
319    }
320}