use std::fs;
use std::path::{Path, PathBuf};
use std::process;
use schemars::JsonSchema;
use serde::{Deserialize, Serialize};
use sha2::{Digest, Sha256};
use thiserror::Error;
const SKILL_NAME: &str = "apoc";
const SKILL_MD: &str = include_str!("../skills/apoc/SKILL.md");
const OPENAI_YAML: &str = include_str!("../skills/apoc/agents/openai.yaml");
const REFERENCES: &[(&str, &str)] = &[
(
"references/execution.md",
include_str!("../skills/apoc/references/execution.md"),
),
(
"references/workflows.md",
include_str!("../skills/apoc/references/workflows.md"),
),
(
"references/debugging.md",
include_str!("../skills/apoc/references/debugging.md"),
),
];
const MANIFEST_FILE: &str = ".apoc-skill.json";
const MANIFEST_VERSION: u32 = 1;
const RELATIVE_CANONICAL: &str = "../../.agents/skills/apoc";
#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema, PartialEq, Eq)]
#[serde(rename_all = "snake_case")]
pub struct SkillStatus {
pub state: String,
pub ready: bool,
pub canonical_state: String,
pub codex_state: String,
pub claude_state: String,
pub prefix: String,
pub canonical: String,
pub codex: String,
pub claude: String,
pub digest: String,
pub details: Vec<String>,
}
#[derive(Debug, Error)]
pub enum SkillError {
#[error("Could not determine the current user's home directory")]
MissingHome,
#[error("{action} \"{path}\": {source}")]
Io {
action: &'static str,
path: String,
#[source]
source: std::io::Error,
},
#[error("{0}")]
Conflict(String),
}
pub fn status() -> Result<SkillStatus, SkillError> {
let prefix = dirs::home_dir().ok_or(SkillError::MissingHome)?;
status_with_prefix(prefix)
}
pub fn install(force: bool) -> Result<SkillStatus, SkillError> {
let prefix = dirs::home_dir().ok_or(SkillError::MissingHome)?;
install_with_prefix(prefix, force)
}
pub fn status_with_prefix(prefix: impl AsRef<Path>) -> Result<SkillStatus, SkillError> {
let paths = SkillPaths::new(prefix.as_ref());
Ok(status_for(&paths))
}
pub fn install_with_prefix(
prefix: impl AsRef<Path>,
force: bool,
) -> Result<SkillStatus, SkillError> {
let paths = SkillPaths::new(prefix.as_ref());
let state = classify(&paths);
if !force {
let conflicts = state.conflicts();
if !conflicts.is_empty() {
return Err(SkillError::Conflict(conflicts.join("; ")));
}
}
match state.canonical {
RootState::Current | RootState::External => {}
RootState::Missing | RootState::ManagedOutdated => {
write_managed_skill(&paths)?;
}
RootState::Conflict if force => {
replace_exact_target(&paths.canonical)?;
write_managed_skill(&paths)?;
}
RootState::Conflict => unreachable!("non-force conflict returned earlier"),
}
ensure_consumer_link(&paths.codex, force)?;
ensure_consumer_link(&paths.claude, force)?;
for root in framework_consumer_roots(&paths) {
ensure_consumer_link(&root, force)?;
}
Ok(status_for(&paths))
}
fn framework_consumer_roots(paths: &SkillPaths) -> Vec<PathBuf> {
let Some(home) = dirs::home_dir() else {
return Vec::new();
};
let mut roots = Vec::new();
for agent in incurs::agents::detect() {
if agent.universal {
continue;
}
let Ok(relative) = agent.global_skills_dir.strip_prefix(&home) else {
continue;
};
if relative.components().count() != 2 {
continue;
}
let root = paths.prefix.join(relative).join(SKILL_NAME);
if root != paths.claude && root != paths.codex && !roots.contains(&root) {
roots.push(root);
}
}
roots
}
#[derive(Debug)]
struct SkillPaths {
prefix: PathBuf,
canonical: PathBuf,
codex: PathBuf,
claude: PathBuf,
}
impl SkillPaths {
fn new(prefix: &Path) -> Self {
let prefix = prefix.to_path_buf();
Self {
canonical: prefix.join(".agents/skills").join(SKILL_NAME),
codex: prefix.join(".codex/skills").join(SKILL_NAME),
claude: prefix.join(".claude/skills").join(SKILL_NAME),
prefix,
}
}
}
#[derive(Debug)]
struct Classified {
state: String,
ready: bool,
canonical: RootState,
codex: RootState,
claude: RootState,
details: Vec<String>,
}
impl Classified {
fn conflicts(&self) -> Vec<String> {
let mut details = Vec::new();
if self.canonical == RootState::Conflict {
details.extend(self.details_for_root("canonical"));
}
if self.codex == RootState::Conflict {
details.extend(self.details_for_root("codex"));
}
if self.claude == RootState::Conflict {
details.extend(self.details_for_root("claude"));
}
if details.is_empty()
&& self
.details
.iter()
.any(|detail| detail.contains("conflict"))
{
self.details.clone()
} else {
details
}
}
fn details_for_root(&self, root: &str) -> Vec<String> {
self.details
.iter()
.filter(|detail| detail.starts_with(root))
.cloned()
.collect()
}
}
#[derive(Debug, Serialize, Deserialize)]
struct Manifest {
product: String,
version: u32,
digest: String,
}
fn status_for(paths: &SkillPaths) -> SkillStatus {
let state = classify(paths);
SkillStatus {
state: state.state,
ready: state.ready,
canonical_state: state.canonical.public_state().to_string(),
codex_state: state.codex.public_state().to_string(),
claude_state: state.claude.public_state().to_string(),
prefix: display(&paths.prefix),
canonical: display(&paths.canonical),
codex: display(&paths.codex),
claude: display(&paths.claude),
digest: embedded_digest(),
details: state.details,
}
}
fn classify(paths: &SkillPaths) -> Classified {
let mut details = Vec::new();
let canonical = classify_canonical(paths, &mut details);
let codex = classify_consumer("codex", &paths.codex, &mut details);
let claude = classify_consumer("claude", &paths.claude, &mut details);
let roots = [canonical, codex, claude];
let state =
if roots.contains(&RootState::Conflict) || roots.contains(&RootState::ManagedOutdated) {
"conflict"
} else if canonical == RootState::External {
"external"
} else if roots.contains(&RootState::Missing) {
"missing"
} else {
"current"
};
Classified {
state: state.to_string(),
ready: matches!(state, "current" | "external") && !roots.contains(&RootState::Missing),
canonical,
codex,
claude,
details,
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum RootState {
Current,
Missing,
External,
ManagedOutdated,
Conflict,
}
impl RootState {
fn public_state(self) -> &'static str {
match self {
Self::Current => "current",
Self::Missing => "missing",
Self::External => "external",
Self::ManagedOutdated | Self::Conflict => "conflict",
}
}
}
fn classify_canonical(paths: &SkillPaths, details: &mut Vec<String>) -> RootState {
let Ok(meta) = fs::symlink_metadata(&paths.canonical) else {
details.push(format!(
"canonical {} is missing",
display(&paths.canonical)
));
return RootState::Missing;
};
if meta.file_type().is_symlink() {
return if valid_external_symlink(&paths.canonical) {
RootState::External
} else {
details.push(format!(
"canonical {} is a symlink but not a valid external apoc skill",
display(&paths.canonical)
));
RootState::Conflict
};
}
if !meta.is_dir() {
details.push(format!(
"canonical {} is not a directory",
display(&paths.canonical)
));
return RootState::Conflict;
}
if managed_current(&paths.canonical) {
RootState::Current
} else if managed_marker(&paths.canonical) {
details.push(format!(
"canonical {} is apoc-managed but not current",
display(&paths.canonical)
));
RootState::ManagedOutdated
} else {
details.push(format!(
"canonical {} exists but is not an apoc-managed skill",
display(&paths.canonical)
));
RootState::Conflict
}
}
fn valid_external_symlink(path: &Path) -> bool {
let Ok(target) = fs::canonicalize(path) else {
return false;
};
target.join("SKILL.md").is_file() && target.join("agents/openai.yaml").is_file()
}
fn classify_consumer(root: &str, path: &Path, details: &mut Vec<String>) -> RootState {
let Ok(meta) = fs::symlink_metadata(path) else {
details.push(format!("{root} {} is missing", display(path)));
return RootState::Missing;
};
if !meta.file_type().is_symlink() {
details.push(format!(
"{root} {} is not the managed apoc symlink",
display(path)
));
return RootState::Conflict;
}
match fs::read_link(path) {
Ok(target) if target.as_path() == Path::new(RELATIVE_CANONICAL) => RootState::Current,
Ok(target) => {
details.push(format!(
"{root} {} points to {}, expected {}",
display(path),
target.display(),
RELATIVE_CANONICAL
));
RootState::Conflict
}
Err(error) => {
details.push(format!("{root} could not read {}: {error}", display(path)));
RootState::Conflict
}
}
}
fn managed_current(path: &Path) -> bool {
let Ok(bytes) = fs::read(path.join(MANIFEST_FILE)) else {
return false;
};
let Ok(manifest) = serde_json::from_slice::<Manifest>(&bytes) else {
return false;
};
manifest.product == SKILL_NAME
&& manifest.version == MANIFEST_VERSION
&& manifest.digest == embedded_digest()
&& fs::read_to_string(path.join("SKILL.md")).is_ok_and(|text| text == SKILL_MD)
&& fs::read_to_string(path.join("agents/openai.yaml")).is_ok_and(|text| text == OPENAI_YAML)
&& REFERENCES.iter().all(|(relative, expected)| {
fs::read_to_string(path.join(relative)).is_ok_and(|text| text == *expected)
})
}
fn managed_marker(path: &Path) -> bool {
let Ok(bytes) = fs::read(path.join(MANIFEST_FILE)) else {
return false;
};
serde_json::from_slice::<Manifest>(&bytes).is_ok_and(|manifest| manifest.product == SKILL_NAME)
}
fn write_managed_skill(paths: &SkillPaths) -> Result<(), SkillError> {
create_dir_all(&paths.canonical)?;
create_dir_all(&paths.canonical.join("agents"))?;
write_atomic(&paths.canonical.join("SKILL.md"), SKILL_MD.as_bytes())?;
write_atomic(
&paths.canonical.join("agents/openai.yaml"),
OPENAI_YAML.as_bytes(),
)?;
for (relative, contents) in REFERENCES {
let path = paths.canonical.join(relative);
create_dir_all(path.parent().expect("reference path has a parent"))?;
write_atomic(&path, contents.as_bytes())?;
}
write_atomic(
&paths.canonical.join(MANIFEST_FILE),
serde_json::to_vec_pretty(&Manifest {
product: SKILL_NAME.to_string(),
version: MANIFEST_VERSION,
digest: embedded_digest(),
})
.expect("manifest serializes")
.as_slice(),
)
}
fn ensure_consumer_link(path: &Path, force: bool) -> Result<(), SkillError> {
create_dir_all(path.parent().expect("skill path has a parent"))?;
match classify_consumer("consumer", path, &mut Vec::new()) {
RootState::Current => return Ok(()),
RootState::Missing => {}
RootState::Conflict if force => {}
RootState::Conflict => {
return Err(SkillError::Conflict(format!(
"{} is not the managed apoc symlink",
display(path)
)));
}
RootState::External | RootState::ManagedOutdated => unreachable!("consumer state"),
}
symlink_atomic(Path::new(RELATIVE_CANONICAL), path, force)
}
fn replace_exact_target(path: &Path) -> Result<(), SkillError> {
let Ok(meta) = fs::symlink_metadata(path) else {
return Ok(());
};
if meta.is_dir() && !meta.file_type().is_symlink() {
fs::remove_dir_all(path).map_err(|source| SkillError::Io {
action: "Remove directory",
path: display(path),
source,
})
} else {
fs::remove_file(path).map_err(|source| SkillError::Io {
action: "Remove file",
path: display(path),
source,
})
}
}
fn create_dir_all(path: &Path) -> Result<(), SkillError> {
fs::create_dir_all(path).map_err(|source| SkillError::Io {
action: "Create directory",
path: display(path),
source,
})
}
fn write_atomic(path: &Path, bytes: &[u8]) -> Result<(), SkillError> {
let tmp = temp_sibling(path);
fs::write(&tmp, bytes).map_err(|source| SkillError::Io {
action: "Write",
path: display(&tmp),
source,
})?;
fs::rename(&tmp, path).map_err(|source| SkillError::Io {
action: "Rename",
path: display(path),
source,
})
}
#[cfg(unix)]
fn symlink_atomic(target: &Path, link: &Path, force: bool) -> Result<(), SkillError> {
let tmp = temp_sibling(link);
let result = std::os::unix::fs::symlink(target, &tmp).map_err(|source| SkillError::Io {
action: "Create symlink",
path: display(&tmp),
source,
});
if result.is_err() {
let _ = fs::remove_file(&tmp);
}
result?;
if force
&& let Ok(meta) = fs::symlink_metadata(link)
&& meta.is_dir()
&& !meta.file_type().is_symlink()
{
fs::remove_dir_all(link).map_err(|source| SkillError::Io {
action: "Remove directory",
path: display(link),
source,
})?;
}
match fs::rename(&tmp, link) {
Ok(()) => Ok(()),
Err(source) => {
let _ = fs::remove_file(&tmp);
Err(SkillError::Io {
action: "Rename",
path: display(link),
source,
})
}
}
}
fn embedded_digest() -> String {
let mut digest = Sha256::new();
digest.update(SKILL_MD.as_bytes());
digest.update([0]);
digest.update(OPENAI_YAML.as_bytes());
for (relative, contents) in REFERENCES {
digest.update([0]);
digest.update(relative.as_bytes());
digest.update([0]);
digest.update(contents.as_bytes());
}
format!("{:x}", digest.finalize())
}
fn display(path: &Path) -> String {
path.display().to_string()
}
fn temp_sibling(path: &Path) -> PathBuf {
let name = path
.file_name()
.map(|value| value.to_string_lossy())
.unwrap_or_else(|| "apoc".into());
path.with_file_name(format!(".{name}.apoc-tmp-{}", process::id()))
}