1use 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
18fn 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
31fn resolved_state_root() -> Option<Utf8PathBuf> {
33 UserEnv::from_process().state_root().map(|entry| entry.path)
34}
35
36fn 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#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
50#[serde(rename_all = "kebab-case")]
51pub enum ProbeClass {
52 Hard,
54 Soft,
56}
57
58#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
60#[serde(rename_all = "kebab-case")]
61pub enum ProbeStatus {
62 Ok,
64 Failed,
66}
67
68#[derive(Debug, Serialize)]
70pub struct ProbeResult {
71 pub id: &'static str,
73 pub class: ProbeClass,
75 pub status: ProbeStatus,
77 pub message: String,
79 #[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
111pub const SKILL_PROBES: [&str; 1] = ["skill-shadow"];
117
118#[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
143fn 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
177fn 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
221fn registry() -> ProbeResult {
229 let id = "release-registry";
230 let url = format!("{}/config.json", crate::self_depend::registry::INDEX_ROOT);
231 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 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
268fn 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
294fn 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}