1use std::process::Command;
11
12use serde::Serialize;
13
14use crate::detect::Forge;
15use crate::skills::record::{RECORD_PATH, Record};
16use crate::skills::{AGENTS_ROOT, CLAUDE_ROOT, Digest};
17
18#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
20#[serde(rename_all = "kebab-case")]
21pub enum ProbeClass {
22 Hard,
24 Soft,
26}
27
28#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
30#[serde(rename_all = "kebab-case")]
31pub enum ProbeStatus {
32 Ok,
34 Failed,
36}
37
38#[derive(Debug, Serialize)]
40pub struct ProbeResult {
41 pub id: &'static str,
43 pub class: ProbeClass,
45 pub status: ProbeStatus,
47 pub message: String,
49 #[serde(skip_serializing_if = "Option::is_none")]
51 pub remediation: Option<String>,
52}
53
54impl ProbeResult {
55 fn ok(id: &'static str, class: ProbeClass, message: impl Into<String>) -> Self {
56 Self {
57 id,
58 class,
59 status: ProbeStatus::Ok,
60 message: message.into(),
61 remediation: None,
62 }
63 }
64
65 fn failed(
66 id: &'static str,
67 class: ProbeClass,
68 message: impl Into<String>,
69 remediation: impl Into<String>,
70 ) -> Self {
71 Self {
72 id,
73 class,
74 status: ProbeStatus::Failed,
75 message: message.into(),
76 remediation: Some(remediation.into()),
77 }
78 }
79}
80
81pub const SKILL_PROBES: [&str; 1] = ["skill-shadow"];
88
89pub const HARD_RUNTIME_TOOLS: [(&str, &str); 2] = [("git", "git"), ("sh", "bash")];
97
98#[must_use]
104pub fn git_bin() -> std::ffi::OsString {
105 crate::requirements::Tool::Git.program()
106}
107
108#[must_use]
111pub fn nix_bin() -> std::ffi::OsString {
112 crate::requirements::Tool::Nix.program()
113}
114
115#[must_use]
119pub fn direnv_bin() -> std::ffi::OsString {
120 std::env::var_os("RK_DIRENV_BIN")
121 .filter(|value| !value.is_empty())
122 .unwrap_or_else(|| "direnv".into())
123}
124
125#[must_use]
129pub fn nix() -> ProbeResult {
130 tool(
131 "nix",
132 "RK_NIX_BIN",
133 "nix",
134 "Nix; rk self-depend sync updates and builds the pinned devshell with it",
135 &["--version"],
136 )
137}
138
139#[must_use]
141pub fn direnv() -> ProbeResult {
142 tool(
143 "direnv",
144 "RK_DIRENV_BIN",
145 "direnv",
146 "direnv; it loads the devshell on directory entry",
147 &["version"],
148 )
149}
150
151#[must_use]
156pub fn sh_bin() -> std::ffi::OsString {
157 crate::requirements::Tool::Sh.program()
158}
159
160#[must_use]
166pub fn git_cliff_bin() -> std::ffi::OsString {
167 crate::requirements::Tool::GitCliff.program()
168}
169
170#[must_use]
175pub fn uv_bin() -> std::ffi::OsString {
176 crate::requirements::Tool::Uv.program()
177}
178
179#[must_use]
181pub fn run_all() -> Vec<ProbeResult> {
182 let mut probes = vec![
183 shell(),
184 git(),
185 state_root(),
186 skill_shadow(),
187 git_remote(),
188 pin_freshness(),
189 forge_cli(
190 "gh-auth",
191 "RK_GH_BIN",
192 "gh",
193 "the GitHub CLI",
194 "gh auth login",
195 &[&["auth", "status", "--active"]],
200 ),
201 forge_cli(
202 "glab-auth",
203 "RK_GLAB_BIN",
204 "glab",
205 "the GitLab CLI",
206 "glab auth login",
207 &[&["auth", "status"]],
208 ),
209 forge_cli_floor(Forge::Github),
210 forge_cli_floor(Forge::Gitlab),
211 registry(),
212 nix(),
213 direnv(),
214 tool(
215 "cosign",
216 "RK_COSIGN_BIN",
217 "cosign",
218 "cosign; the release verify step checks a GitLab provenance bundle with it",
219 &["version"],
220 ),
221 tool(
222 "pypi-attestations",
223 "RK_PYPI_ATTESTATIONS_BIN",
224 "pypi-attestations",
225 "pypi-attestations; the release verify step checks a PyPI distribution's attestations with it",
226 &["--help"],
227 ),
228 ];
229 probes.extend(hook_probes());
230 probes
231}
232
233fn hook_probes() -> Vec<ProbeResult> {
240 let Ok(cwd) = std::env::current_dir() else {
241 return Vec::new();
242 };
243 let Some(installed) = crate::hooks::installed(&cwd) else {
244 return Vec::new();
245 };
246 let names = |filter: &dyn Fn(crate::hooks::Writer) -> bool| -> Vec<&'static str> {
247 installed
248 .iter()
249 .filter(|hook| filter(hook.writer))
250 .map(|hook| hook.event)
251 .collect()
252 };
253 let mut probes = vec![if installed
254 .iter()
255 .any(|hook| hook.event == "pre-merge-commit")
256 {
257 ProbeResult::ok(
258 "pre-merge-commit-hook",
259 ProbeClass::Soft,
260 "a pre-merge-commit hook is installed, the gate rk integrate asks git to run",
261 )
262 } else {
263 ProbeResult::failed(
264 "pre-merge-commit-hook",
265 ProbeClass::Soft,
266 "no pre-merge-commit hook is installed, so rk integrate has no gate to run in this clone",
267 "install it with the project's hook manager, for example prek install --hook-type pre-merge-commit",
268 )
269 }];
270 for (id, writer) in [
271 ("prek", crate::hooks::Writer::Prek),
272 ("pre-commit", crate::hooks::Writer::PreCommit),
273 ] {
274 let hooks = names(&|found| found == writer);
275 if hooks.is_empty() {
276 continue;
277 }
278 let answers = Command::new(id)
279 .arg("--version")
280 .output()
281 .is_ok_and(|out| out.status.success());
282 let wrote = hooks.join(", ");
283 probes.push(if answers {
284 ProbeResult::ok(id, ProbeClass::Soft, format!("{id} runs; it wrote the {wrote} hooks"))
285 } else {
286 ProbeResult::failed(
287 id,
288 ProbeClass::Soft,
289 format!("{id} does not run, and the {wrote} hooks call it"),
290 format!("install {id} on the host, or reinstall the hooks with the project's hook manager"),
291 )
292 });
293 }
294 let configured = names(&|found| found == crate::hooks::Writer::Configured);
295 if !configured.is_empty() {
296 let mut events = configured.clone();
297 events.dedup();
298 probes.push(ProbeResult::ok(
299 "configured-hooks",
300 ProbeClass::Soft,
301 format!(
302 "git's configuration defines {} hooks for {}",
303 configured.len(),
304 events.join(", ")
305 ),
306 ));
307 }
308 let own = names(&|found| found == crate::hooks::Writer::Own);
309 if !own.is_empty() {
310 probes.push(ProbeResult::ok(
311 "own-hooks",
312 ProbeClass::Soft,
313 format!(
314 "the {} hooks are the project's own, written by no known hook manager",
315 own.join(", ")
316 ),
317 ));
318 }
319 probes
320}
321
322fn tool(
326 id: &'static str,
327 env_override: &str,
328 default_bin: &str,
329 label: &str,
330 args: &[&str],
331) -> ProbeResult {
332 let bin = std::env::var(env_override)
333 .ok()
334 .filter(|value| !value.is_empty())
335 .unwrap_or_else(|| default_bin.to_owned());
336 match Command::new(&bin).args(args).output() {
337 Ok(out) if out.status.success() => {
338 ProbeResult::ok(id, ProbeClass::Soft, format!("{default_bin} runs"))
339 }
340 Ok(_) => ProbeResult::failed(
341 id,
342 ProbeClass::Soft,
343 format!("{default_bin} does not answer {}", args.join(" ")),
344 format!("repair {label}"),
345 ),
346 Err(_) => ProbeResult::failed(
347 id,
348 ProbeClass::Soft,
349 format!("{default_bin} is not on PATH"),
350 format!("install {label}"),
351 ),
352 }
353}
354
355fn registry() -> ProbeResult {
360 let id = "registry";
361 let answered = crate::http::send(
362 &crate::http::Request::get(
363 "https://index.crates.io/config.json",
364 std::time::Duration::from_secs(5),
365 )
366 .following(),
367 )
368 .is_ok_and(|answer| answer.ok());
369 if answered {
370 ProbeResult::ok(id, ProbeClass::Soft, "the crates.io index answers")
371 } else {
372 ProbeResult::failed(
373 id,
374 ProbeClass::Soft,
375 "the crates.io index does not answer",
376 "reach the network before rk versions --check or rk self-depend sync; every offline verb runs without it",
377 )
378 }
379}
380
381fn shell() -> ProbeResult {
383 let id = "sh";
384 match Command::new(sh_bin()).args(["-c", "exit 0"]).status() {
385 Ok(status) if status.success() => ProbeResult::ok(id, ProbeClass::Hard, "sh runs"),
386 Ok(status) => ProbeResult::failed(
387 id,
388 ProbeClass::Hard,
389 format!("sh exited {status}"),
390 "repair the POSIX shell on PATH",
391 ),
392 Err(source) => ProbeResult::failed(
393 id,
394 ProbeClass::Hard,
395 format!("sh does not spawn: {source}"),
396 "install a POSIX shell on PATH",
397 ),
398 }
399}
400
401fn git() -> ProbeResult {
404 let id = "git";
405 match Command::new(git_bin()).arg("--version").output() {
406 Ok(out) if out.status.success() => ProbeResult::ok(id, ProbeClass::Hard, "git runs"),
407 Ok(_) => ProbeResult::failed(
408 id,
409 ProbeClass::Hard,
410 "git does not answer --version",
411 "repair the git on PATH, or point RK_GIT_BIN at a working one",
412 ),
413 Err(_) => ProbeResult::failed(id, ProbeClass::Hard, "git is not on PATH", "install git"),
414 }
415}
416
417fn state_root() -> ProbeResult {
420 let id = "state-root";
421 let Some(root) = crate::applog::state_root() else {
422 return ProbeResult::failed(
423 id,
424 ProbeClass::Hard,
425 "neither XDG_STATE_HOME nor HOME is set",
426 "export HOME, or XDG_STATE_HOME",
427 );
428 };
429 let display = root.display().to_string();
430 let probe = root.join(format!(".probe-{}", std::process::id()));
431 let written = std::fs::create_dir_all(&root).and_then(|()| std::fs::write(&probe, b"probe"));
432 let _ = std::fs::remove_file(&probe);
433 match written {
434 Ok(()) => ProbeResult::ok(id, ProbeClass::Hard, format!("{display} is writable")),
435 Err(source) => ProbeResult::failed(
436 id,
437 ProbeClass::Hard,
438 format!("{display} is not writable: {source}"),
439 format!("make {display} writable"),
440 ),
441 }
442}
443
444fn skill_shadow() -> ProbeResult {
455 let id = SKILL_PROBES[0];
456 let Ok(home) = crate::skills::home() else {
457 return ProbeResult::failed(
458 id,
459 ProbeClass::Soft,
460 "neither HOME nor USERPROFILE is set, so no user-scope skill root resolves",
461 "export HOME",
462 );
463 };
464 let Ok(skills) = crate::skills::all() else {
465 return ProbeResult::failed(
466 id,
467 ProbeClass::Soft,
468 "this binary's embedded skills do not read",
469 "reinstall rk; the sources it was built from are defective",
470 );
471 };
472 let record = Record::load(&home.join(RECORD_PATH));
473 let mut vouched = Vec::new();
474 let mut edited = Vec::new();
475 for root in [CLAUDE_ROOT, AGENTS_ROOT] {
476 for skill in &skills {
477 let manual = home.join(root).join(&skill.name).join("SKILL.md");
478 if std::fs::symlink_metadata(&manual).is_err() {
479 continue;
480 }
481 let ours = std::fs::read(&manual)
482 .is_ok_and(|bytes| record.wrote(&manual, &Digest::of(&bytes)));
483 if ours {
484 vouched.push(manual);
485 } else {
486 edited.push(manual);
487 }
488 }
489 }
490 if let Some(first) = edited.first() {
491 return ProbeResult::failed(
492 id,
493 ProbeClass::Soft,
494 format!(
495 "{} user-scope SKILL.md file(s) shadow the project's landed skills, and the uninstall kept them as your edits, the first at {first}",
496 edited.len()
497 ),
498 format!(
499 "read {first} and each other kept copy, keep what you need elsewhere, and remove them by hand"
500 ),
501 );
502 }
503 if let Some(first) = vouched.first() {
504 return ProbeResult::failed(
505 id,
506 ProbeClass::Soft,
507 format!(
508 "{} user-scope SKILL.md file(s) that an earlier release installed shadow the project's landed skills, the first at {first}",
509 vouched.len()
510 ),
511 "rk skill uninstall --apply",
512 );
513 }
514 ProbeResult::ok(
515 id,
516 ProbeClass::Soft,
517 format!("no user-scope copy of an rk skill under {home} shadows a project's landed one"),
518 )
519}
520
521fn pin_freshness() -> ProbeResult {
527 use crate::self_depend::{self, advice};
528 let id = "pin-freshness";
529 let Ok(observed) = self_depend::observe(camino::Utf8Path::new(".")) else {
530 return ProbeResult::ok(
531 id,
532 ProbeClass::Soft,
533 "the working directory does not read as a project",
534 );
535 };
536 let Some(pin) = observed
537 .wired
538 .and_then(|wired| observed.entry(wired))
539 .and_then(|entry| entry.read.version())
540 .map(|version| version.trim_start_matches('v').to_owned())
541 else {
542 return ProbeResult::ok(id, ProbeClass::Soft, "the working directory pins no rk");
543 };
544 let key = observed.key();
545 if let Some(warning) = advice::pending_from_cache(&key, &pin) {
546 return ProbeResult::failed(
547 id,
548 ProbeClass::Soft,
549 format!("this project pins rk {pin}, and a newer release is out"),
550 warning,
551 );
552 }
553 let message = advice::cached_latest(&key).map_or_else(
554 || format!("this project pins rk {pin}; no release check is cached yet"),
555 |latest| {
556 format!(
557 "this project pins rk {pin}, and the latest known release is {}",
558 latest.trim_start_matches('v')
559 )
560 },
561 );
562 ProbeResult::ok(id, ProbeClass::Soft, message)
563}
564
565fn git_remote() -> ProbeResult {
568 let id = "git-remote";
569 let out = Command::new(git_bin())
570 .args(["remote", "get-url", "origin"])
571 .output();
572 let url = match out {
573 Ok(out) if out.status.success() => String::from_utf8_lossy(&out.stdout).trim().to_owned(),
574 _ => {
575 return ProbeResult::failed(
576 id,
577 ProbeClass::Soft,
578 "the working directory has no origin remote",
579 "pass --repo <owner/name> where a command needs the slug",
580 );
581 }
582 };
583 remote_host(&url).map_or_else(
587 || {
588 ProbeResult::failed(
589 id,
590 ProbeClass::Soft,
591 "the origin remote does not parse to a host",
592 "pass --repo <owner/name> where a command needs the slug",
593 )
594 },
595 |host| ProbeResult::ok(id, ProbeClass::Soft, format!("origin resolves to {host}")),
596 )
597}
598
599fn remote_host(url: &str) -> Option<String> {
601 if let Some(rest) = url.split_once("://").map(|(_, rest)| rest) {
602 let authority = rest.split('/').next()?;
603 let host = authority
604 .rsplit_once('@')
605 .map_or(authority, |(_, host)| host);
606 let host = host.split(':').next()?;
607 return (!host.is_empty()).then(|| host.to_owned());
608 }
609 let (authority, path) = url.split_once(':')?;
610 let host = authority
611 .rsplit_once('@')
612 .map_or(authority, |(_, host)| host);
613 (!host.is_empty() && !path.is_empty()).then(|| host.to_owned())
614}
615
616fn forge_cli(
622 id: &'static str,
623 env_override: &str,
624 default_bin: &str,
625 label: &str,
626 login: &str,
627 attempts: &[&[&str]],
628) -> ProbeResult {
629 let bin = std::env::var(env_override)
630 .ok()
631 .filter(|value| !value.is_empty())
632 .unwrap_or_else(|| default_bin.to_owned());
633 let mut spawned = false;
634 for args in attempts {
635 match Command::new(&bin).args(*args).output() {
636 Ok(out) if out.status.success() => {
637 return ProbeResult::ok(
638 id,
639 ProbeClass::Soft,
640 format!("{default_bin} is authenticated"),
641 );
642 }
643 Ok(_) => spawned = true,
644 Err(_) => {}
645 }
646 }
647 if spawned {
648 ProbeResult::failed(
649 id,
650 ProbeClass::Soft,
651 format!("{default_bin} is not authenticated"),
652 format!("run {login}"),
653 )
654 } else {
655 ProbeResult::failed(
656 id,
657 ProbeClass::Soft,
658 format!("{default_bin} is not on PATH"),
659 format!("install {label}"),
660 )
661 }
662}
663
664#[must_use]
667pub fn forge_bin(forge: Forge) -> String {
668 crate::requirements::Tool::ForgeCli(forge)
669 .program()
670 .to_string_lossy()
671 .into_owned()
672}
673
674const fn version_probe_id(forge: Forge) -> &'static str {
676 match forge {
677 Forge::Github => "gh-version",
678 Forge::Gitlab => "glab-version",
679 }
680}
681
682#[must_use]
687pub fn parse_cli_version(text: &str) -> Option<(u32, u32, u32)> {
688 let bytes = text.as_bytes();
689 let mut start = 0;
690 while start < bytes.len() {
691 if !bytes[start].is_ascii_digit() {
692 start += 1;
693 continue;
694 }
695 let mut end = start;
696 while end < bytes.len() && (bytes[end].is_ascii_digit() || bytes[end] == b'.') {
697 end += 1;
698 }
699 let run = &text[start..end];
700 let mut parts = run.split('.');
701 let parsed = (|| {
702 let major = parts.next()?.parse().ok()?;
703 let minor = parts.next()?.parse().ok()?;
704 let patch = parts.next()?.parse().ok()?;
705 Some((major, minor, patch))
706 })();
707 if let Some(version) = parsed {
708 return Some(version);
709 }
710 start = end.max(start + 1);
711 }
712 None
713}
714
715#[must_use]
719pub fn forge_cli_version(bin: &str) -> Option<(u32, u32, u32)> {
720 let out = Command::new(bin).arg("--version").output().ok()?;
721 if !out.status.success() {
722 return None;
723 }
724 parse_cli_version(&String::from_utf8_lossy(&out.stdout))
725}
726
727fn forge_cli_floor(forge: Forge) -> ProbeResult {
731 let id = version_probe_id(forge);
732 let bin = forge_bin(forge);
733 let name = forge.cli();
734 let floor = forge.cli_floor();
735 match forge_cli_version(&bin) {
736 Some(found) if found >= floor => ProbeResult::ok(
737 id,
738 ProbeClass::Soft,
739 format!("{name} {} is at or above {}", show(found), show(floor)),
740 ),
741 Some(found) => ProbeResult::failed(
742 id,
743 ProbeClass::Soft,
744 format!(
745 "{name} {} is below the {} rk calls",
746 show(found),
747 show(floor)
748 ),
749 forge.cli_upgrade(),
750 ),
751 None => ProbeResult::failed(
752 id,
753 ProbeClass::Soft,
754 format!("{name} does not answer --version with a version"),
755 format!("install {name}"),
756 ),
757 }
758}
759
760fn show((major, minor, patch): (u32, u32, u32)) -> String {
762 format!("{major}.{minor}.{patch}")
763}
764
765#[cfg(test)]
766mod tests {
767 use super::{parse_cli_version, remote_host};
768
769 #[test]
773 fn a_version_line_parses_from_both_forge_clis() {
774 assert_eq!(
775 parse_cli_version("gh version 2.19.0 (2022-10-25)"),
776 Some((2, 19, 0))
777 );
778 assert_eq!(
779 parse_cli_version("glab 1.114.0 (4d7c6cd)\n"),
780 Some((1, 114, 0))
781 );
782 assert_eq!(parse_cli_version("gh version 2.99.0"), Some((2, 99, 0)));
783 assert_eq!(parse_cli_version("no version here"), None);
784 assert_eq!(parse_cli_version("gh version 2.19"), None);
785 }
786
787 #[test]
790 fn a_floor_comparison_orders_by_component() {
791 assert!((2, 100, 0) > (2, 99, 0));
792 assert!((2, 9, 0) < (2, 19, 0));
793 assert!((2, 19, 0) >= (2, 19, 0));
794 }
795
796 #[test]
797 fn a_remote_host_parses_from_both_url_forms() {
798 assert_eq!(
799 remote_host("https://github.com/owner/name.git").as_deref(),
800 Some("github.com")
801 );
802 assert_eq!(
803 remote_host("git@gitlab.com:group/sub/name.git").as_deref(),
804 Some("gitlab.com")
805 );
806 assert_eq!(
807 remote_host("ssh://git@github.com:22/owner/name.git").as_deref(),
808 Some("github.com")
809 );
810 assert_eq!(remote_host("not a url"), None);
811 }
812}