use std::process::Command;
use camino::{Utf8Path, Utf8PathBuf};
use serde::Serialize;
use crate::skills::record::{RECORD_PATH, Record};
use crate::skills::{AGENTS_ROOT, CLAUDE_ROOT, Digest, SHARED_ROOT};
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
#[serde(rename_all = "kebab-case")]
pub enum ProbeClass {
Hard,
Soft,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
#[serde(rename_all = "kebab-case")]
pub enum ProbeStatus {
Ok,
Failed,
}
#[derive(Debug, Serialize)]
pub struct ProbeResult {
pub id: &'static str,
pub class: ProbeClass,
pub status: ProbeStatus,
pub message: String,
#[serde(skip_serializing_if = "Option::is_none")]
pub remediation: Option<String>,
}
impl ProbeResult {
fn ok(id: &'static str, class: ProbeClass, message: impl Into<String>) -> Self {
Self {
id,
class,
status: ProbeStatus::Ok,
message: message.into(),
remediation: None,
}
}
fn failed(
id: &'static str,
class: ProbeClass,
message: impl Into<String>,
remediation: impl Into<String>,
) -> Self {
Self {
id,
class,
status: ProbeStatus::Failed,
message: message.into(),
remediation: Some(remediation.into()),
}
}
}
pub const SKILL_PROBES: [&str; 3] = ["skill-roots", "skill-gate", "skill-payload"];
#[must_use]
pub fn run_all() -> Vec<ProbeResult> {
vec![
shell(),
state_root(),
skill_roots(),
skill_gate(),
skill_payload(),
git_remote(),
forge_cli(
"gh-auth",
"RK_GH_BIN",
"gh",
"the GitHub CLI",
"gh auth login",
&[&["auth", "status", "--active"], &["auth", "status"]],
),
forge_cli(
"glab-auth",
"RK_GLAB_BIN",
"glab",
"the GitLab CLI",
"glab auth login",
&[&["auth", "status"]],
),
tool(
"openssl",
"RK_OPENSSL_BIN",
"openssl",
"OpenSSL; install-bot signs the App JWT with it",
&["version"],
),
tool(
"curl",
"RK_CURL_BIN",
"curl",
"curl; install-bot reads the installation and rk versions --check fetches with it",
&["--version"],
),
tool(
"cosign",
"RK_COSIGN_BIN",
"cosign",
"cosign; the release verify step checks a GitLab provenance bundle with it",
&["version"],
),
tool(
"pypi-attestations",
"RK_PYPI_ATTESTATIONS_BIN",
"pypi-attestations",
"pypi-attestations; the release verify step checks a PyPI distribution's attestations with it",
&["--help"],
),
]
}
fn tool(
id: &'static str,
env_override: &str,
default_bin: &str,
label: &str,
args: &[&str],
) -> ProbeResult {
let bin = std::env::var(env_override).unwrap_or_else(|_| default_bin.to_owned());
match Command::new(&bin).args(args).output() {
Ok(out) if out.status.success() => {
ProbeResult::ok(id, ProbeClass::Soft, format!("{default_bin} runs"))
}
Ok(_) => ProbeResult::failed(
id,
ProbeClass::Soft,
format!("{default_bin} does not answer {}", args.join(" ")),
format!("repair {label}"),
),
Err(_) => ProbeResult::failed(
id,
ProbeClass::Soft,
format!("{default_bin} is not on PATH"),
format!("install {label}"),
),
}
}
fn shell() -> ProbeResult {
let id = "sh";
match Command::new("sh").args(["-c", "exit 0"]).status() {
Ok(status) if status.success() => ProbeResult::ok(id, ProbeClass::Hard, "sh runs"),
Ok(status) => ProbeResult::failed(
id,
ProbeClass::Hard,
format!("sh exited {status}"),
"repair the POSIX shell on PATH",
),
Err(source) => ProbeResult::failed(
id,
ProbeClass::Hard,
format!("sh does not spawn: {source}"),
"install a POSIX shell on PATH",
),
}
}
fn state_root() -> ProbeResult {
let id = "state-root";
let Some(root) = crate::applog::state_root() else {
return ProbeResult::failed(
id,
ProbeClass::Hard,
"neither XDG_STATE_HOME nor HOME is set",
"export HOME, or XDG_STATE_HOME",
);
};
let display = root.display().to_string();
let probe = root.join(format!(".probe-{}", std::process::id()));
let written = std::fs::create_dir_all(&root).and_then(|()| std::fs::write(&probe, b"probe"));
let _ = std::fs::remove_file(&probe);
match written {
Ok(()) => ProbeResult::ok(id, ProbeClass::Hard, format!("{display} is writable")),
Err(source) => ProbeResult::failed(
id,
ProbeClass::Hard,
format!("{display} is not writable: {source}"),
format!("make {display} writable"),
),
}
}
fn skill_roots() -> ProbeResult {
let id = SKILL_PROBES[0];
let Ok(home) = crate::skills::home() else {
return ProbeResult::failed(
id,
ProbeClass::Soft,
"neither HOME nor USERPROFILE is set, so no skill root resolves",
"export HOME",
);
};
let mut refused = Vec::new();
for root in [CLAUDE_ROOT, AGENTS_ROOT, SHARED_ROOT] {
let root = home.join(root);
let Some(existing) = nearest_existing(&root) else {
refused.push(format!("no ancestor of {root} exists"));
continue;
};
if let Err(source) = accepts_a_write(&existing) {
refused.push(format!("{existing} is not writable: {source}"));
}
}
if refused.is_empty() {
ProbeResult::ok(
id,
ProbeClass::Soft,
format!("the skill roots under {home} accept writes"),
)
} else {
ProbeResult::failed(
id,
ProbeClass::Soft,
refused.join("; "),
format!("make the skill roots under {home} writable"),
)
}
}
fn skill_gate() -> ProbeResult {
let id = SKILL_PROBES[1];
let Ok(home) = crate::skills::home() else {
return ProbeResult::failed(
id,
ProbeClass::Soft,
"neither HOME nor USERPROFILE is set, so the shared root does not resolve",
"export HOME",
);
};
let root = home.join(SHARED_ROOT);
let record = Record::load(&home.join(RECORD_PATH));
let planned: Vec<(Utf8PathBuf, &'static [u8])> = crate::skills::shared()
.into_iter()
.map(|artifact| (root.join(&artifact.path), artifact.bytes))
.collect();
let found = judge(planned, &record);
if let Some(first) = found.missing.first() {
return ProbeResult::failed(
id,
ProbeClass::Soft,
format!("a shared artifact every skill reads before acting is not installed: {first}"),
"rk skill install --apply",
);
}
if !found.differing.is_empty() {
return ProbeResult::failed(
id,
ProbeClass::Soft,
format!(
"{} shared artifact(s) under {root} are not this binary's",
found.differing.len()
),
reinstall(found.all_recorded),
);
}
ProbeResult::ok(
id,
ProbeClass::Soft,
format!("{root} holds this binary's shared artifacts"),
)
}
fn skill_payload() -> ProbeResult {
let id = SKILL_PROBES[2];
let Ok(home) = crate::skills::home() else {
return ProbeResult::failed(
id,
ProbeClass::Soft,
"neither HOME nor USERPROFILE is set, so no agent root resolves",
"export HOME",
);
};
let Ok(skills) = crate::skills::all() else {
return ProbeResult::failed(
id,
ProbeClass::Soft,
"this binary's embedded skills do not read",
"reinstall rk; the payload it was built from is defective",
);
};
let record = Record::load(&home.join(RECORD_PATH));
let mut planned = Vec::new();
for root in [CLAUDE_ROOT, AGENTS_ROOT] {
let root = home.join(root);
if !root.is_dir() {
continue;
}
for skill in &skills {
planned.push((
root.join(&skill.name).join("SKILL.md"),
skill.text.as_bytes(),
));
}
}
if planned.is_empty() {
return ProbeResult::failed(
id,
ProbeClass::Soft,
format!("no agent skill root exists under {home}"),
"rk skill install --apply",
);
}
let found = judge(planned, &record);
if let Some(first) = found.missing.first() {
return ProbeResult::failed(
id,
ProbeClass::Soft,
format!(
"{} of this binary's skills are not installed, the first at {first}",
found.missing.len()
),
"rk skill install --apply",
);
}
if !found.differing.is_empty() {
return ProbeResult::failed(
id,
ProbeClass::Soft,
format!(
"{} installed skill(s) are not this binary's; rk is {}",
found.differing.len(),
env!("CARGO_PKG_VERSION")
),
reinstall(found.all_recorded),
);
}
ProbeResult::ok(
id,
ProbeClass::Soft,
format!(
"{} installed skill destination(s) are this binary's",
found.matching
),
)
}
struct Installed {
missing: Vec<Utf8PathBuf>,
differing: Vec<Utf8PathBuf>,
matching: usize,
all_recorded: bool,
}
fn judge(planned: Vec<(Utf8PathBuf, &'static [u8])>, record: &Record) -> Installed {
let mut found = Installed {
missing: Vec::new(),
differing: Vec::new(),
matching: 0,
all_recorded: true,
};
for (destination, bytes) in planned {
match std::fs::read(&destination) {
Ok(held) if held == bytes => found.matching += 1,
Ok(held) => {
if !record.wrote(&destination, &Digest::of(&held)) {
found.all_recorded = false;
}
found.differing.push(destination);
}
Err(_) => found.missing.push(destination),
}
}
found
}
const fn reinstall(all_recorded: bool) -> &'static str {
if all_recorded {
"rk skill install --apply"
} else {
"rk skill install --apply --force"
}
}
fn nearest_existing(path: &Utf8Path) -> Option<Utf8PathBuf> {
let mut current = Some(path);
while let Some(dir) = current {
if dir.is_dir() {
return Some(dir.to_owned());
}
current = dir.parent();
}
None
}
fn accepts_a_write(dir: &Utf8Path) -> std::io::Result<()> {
let probe = dir.join(format!(".rk-probe-{}", std::process::id()));
let written = std::fs::write(&probe, b"probe");
let _ = std::fs::remove_file(&probe);
written
}
fn git_remote() -> ProbeResult {
let id = "git-remote";
let out = Command::new("git")
.args(["remote", "get-url", "origin"])
.output();
let url = match out {
Ok(out) if out.status.success() => String::from_utf8_lossy(&out.stdout).trim().to_owned(),
_ => {
return ProbeResult::failed(
id,
ProbeClass::Soft,
"the working directory has no origin remote",
"pass --repo <owner/name> where a command needs the slug",
);
}
};
remote_host(&url).map_or_else(
|| {
ProbeResult::failed(
id,
ProbeClass::Soft,
"the origin remote does not parse to a host",
"pass --repo <owner/name> where a command needs the slug",
)
},
|host| ProbeResult::ok(id, ProbeClass::Soft, format!("origin resolves to {host}")),
)
}
fn remote_host(url: &str) -> Option<String> {
if let Some(rest) = url.split_once("://").map(|(_, rest)| rest) {
let authority = rest.split('/').next()?;
let host = authority
.rsplit_once('@')
.map_or(authority, |(_, host)| host);
let host = host.split(':').next()?;
return (!host.is_empty()).then(|| host.to_owned());
}
let (authority, path) = url.split_once(':')?;
let host = authority
.rsplit_once('@')
.map_or(authority, |(_, host)| host);
(!host.is_empty() && !path.is_empty()).then(|| host.to_owned())
}
fn forge_cli(
id: &'static str,
env_override: &str,
default_bin: &str,
label: &str,
login: &str,
attempts: &[&[&str]],
) -> ProbeResult {
let bin = std::env::var(env_override).unwrap_or_else(|_| default_bin.to_owned());
let mut spawned = false;
for args in attempts {
match Command::new(&bin).args(*args).output() {
Ok(out) if out.status.success() => {
return ProbeResult::ok(
id,
ProbeClass::Soft,
format!("{default_bin} is authenticated"),
);
}
Ok(_) => spawned = true,
Err(_) => {}
}
}
if spawned {
ProbeResult::failed(
id,
ProbeClass::Soft,
format!("{default_bin} is not authenticated"),
format!("run {login}"),
)
} else {
ProbeResult::failed(
id,
ProbeClass::Soft,
format!("{default_bin} is not on PATH"),
format!("install {label}"),
)
}
}
#[cfg(test)]
mod tests {
use super::remote_host;
#[test]
fn a_remote_host_parses_from_both_url_forms() {
assert_eq!(
remote_host("https://github.com/owner/name.git").as_deref(),
Some("github.com")
);
assert_eq!(
remote_host("git@gitlab.com:group/sub/name.git").as_deref(),
Some("gitlab.com")
);
assert_eq!(
remote_host("ssh://git@github.com:22/owner/name.git").as_deref(),
Some("github.com")
);
assert_eq!(remote_host("not a url"), None);
}
}