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 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
142fn 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
176fn registry() -> ProbeResult {
184 let id = "release-registry";
185 let url = format!("{}/config.json", crate::self_depend::registry::INDEX_ROOT);
186 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 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
223fn 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
249fn 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}