use std::fs;
use std::path::{Path, PathBuf};
use serde::Serialize;
use crate::error::{DaloError, DaloResult};
use crate::store::{self, StateFile, StorePaths, TargetState};
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
#[serde(rename_all = "snake_case")]
pub enum TargetSupport {
Supported,
Experimental,
}
impl TargetSupport {
#[must_use]
pub fn as_str(self) -> &'static str {
match self {
Self::Supported => "supported",
Self::Experimental => "experimental",
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct TargetRegistryEntry {
pub id: &'static str,
pub name: &'static str,
pub default_path: Option<&'static str>,
pub support: TargetSupport,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
pub struct TargetDetection {
pub id: String,
pub name: String,
pub support: TargetSupport,
pub path: Option<PathBuf>,
pub exists: bool,
pub linked: bool,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
pub struct TargetDetectReport {
pub targets: Vec<TargetDetection>,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
#[serde(rename_all = "snake_case")]
pub enum TargetLinkStatus {
Planned,
Linked,
Updated,
Existing,
}
impl TargetLinkStatus {
#[must_use]
pub fn as_str(self) -> &'static str {
match self {
Self::Planned => "planned",
Self::Linked => "linked",
Self::Updated => "updated",
Self::Existing => "existing",
}
}
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
pub struct TargetLinkReport {
pub target_id: String,
pub path: PathBuf,
pub canonical_path: PathBuf,
pub status: TargetLinkStatus,
pub created_dir: bool,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
#[serde(rename_all = "snake_case")]
pub enum TargetUnlinkStatus {
Planned,
Unlinked,
Missing,
}
impl TargetUnlinkStatus {
#[must_use]
pub fn as_str(self) -> &'static str {
match self {
Self::Planned => "planned",
Self::Unlinked => "unlinked",
Self::Missing => "missing",
}
}
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
pub struct TargetUnlinkReport {
pub target_id: String,
pub status: TargetUnlinkStatus,
}
#[must_use]
pub fn registry() -> &'static [TargetRegistryEntry] {
&[
TargetRegistryEntry {
id: "codex",
name: "Codex",
default_path: Some("~/.agents/skills"),
support: TargetSupport::Supported,
},
TargetRegistryEntry {
id: "claude",
name: "Claude Code",
default_path: Some("~/.claude/skills"),
support: TargetSupport::Supported,
},
TargetRegistryEntry {
id: "openclaw",
name: "OpenClaw",
default_path: Some("~/.agents/skills"),
support: TargetSupport::Supported,
},
TargetRegistryEntry {
id: "hermes",
name: "Hermes",
default_path: Some("~/.hermes/skills"),
support: TargetSupport::Supported,
},
TargetRegistryEntry {
id: "generic",
name: "Generic folder",
default_path: None,
support: TargetSupport::Supported,
},
TargetRegistryEntry {
id: "cursor",
name: "Cursor",
default_path: None,
support: TargetSupport::Experimental,
},
TargetRegistryEntry {
id: "opencode",
name: "OpenCode",
default_path: None,
support: TargetSupport::Experimental,
},
]
}
#[must_use = "the target detection report should be rendered or inspected"]
pub fn detect_targets(store_root: &Path) -> DaloResult<TargetDetectReport> {
let paths = StorePaths::new(store_root.to_path_buf());
let state = read_state_if_initialized(&paths)?;
let targets = registry()
.iter()
.map(|entry| detect_entry(entry, state.as_ref()))
.collect::<DaloResult<Vec<_>>>()?;
Ok(TargetDetectReport { targets })
}
pub fn link_target(
store_root: &Path,
target_id: &str,
path_override: Option<&Path>,
dry_run: bool,
) -> DaloResult<TargetLinkReport> {
let entry = registry_entry(target_id)?;
let path = target_path(entry, path_override)?;
let existed_before = path.exists();
let paths = StorePaths::new(store_root.to_path_buf());
let mut state = if dry_run {
None
} else {
Some(store::read_state(&paths)?)
};
let canonical_path = canonicalize_target_path(&path);
let status = if dry_run {
TargetLinkStatus::Planned
} else {
let state = state
.as_mut()
.expect("state is loaded before non-dry-run target link");
let status = upsert_target_state(state, entry.id, &path, &canonical_path)?;
if !existed_before {
fs::create_dir_all(&path)?;
}
if let Err(error) = store::write_state(&paths, state) {
if !existed_before {
let _ = fs::remove_dir(&path);
}
return Err(error);
}
status
};
Ok(TargetLinkReport {
target_id: entry.id.to_owned(),
path,
canonical_path,
status,
created_dir: !existed_before && !dry_run,
})
}
pub fn unlink_target(
store_root: &Path,
target_id: &str,
dry_run: bool,
) -> DaloResult<TargetUnlinkReport> {
registry_entry(target_id)?;
let paths = StorePaths::new(store_root.to_path_buf());
let mut state = store::read_state(&paths)?;
let original_len = state.targets.len();
let linked = state.targets.iter().any(|target| target.id == target_id);
let status = if dry_run {
if linked {
TargetUnlinkStatus::Planned
} else {
TargetUnlinkStatus::Missing
}
} else {
state.targets.retain(|target| target.id != target_id);
state.rebuild_materialization_dirs_for_removal()?;
store::write_state(&paths, &state)?;
if state.targets.len() == original_len {
TargetUnlinkStatus::Missing
} else {
TargetUnlinkStatus::Unlinked
}
};
Ok(TargetUnlinkReport {
target_id: target_id.to_owned(),
status,
})
}
fn detect_entry(
entry: &TargetRegistryEntry,
state: Option<&StateFile>,
) -> DaloResult<TargetDetection> {
let path = entry
.default_path
.map(PathBuf::from)
.map(|path| store::expand_user_path(&path))
.transpose()?;
let exists = path.as_ref().is_some_and(|path| path.exists());
let linked = state.is_some_and(|state| {
state
.targets
.iter()
.any(|target| target.id == entry.id && target.enabled)
});
Ok(TargetDetection {
id: entry.id.to_owned(),
name: entry.name.to_owned(),
support: entry.support,
path,
exists,
linked,
})
}
fn read_state_if_initialized(paths: &StorePaths) -> DaloResult<Option<StateFile>> {
if paths.state_file.exists() {
Ok(Some(store::read_state(paths)?))
} else {
Ok(None)
}
}
fn registry_entry(target_id: &str) -> DaloResult<&'static TargetRegistryEntry> {
registry()
.iter()
.find(|entry| entry.id == target_id)
.ok_or_else(|| DaloError::UnknownTarget {
target: target_id.to_owned(),
})
}
fn target_path(entry: &TargetRegistryEntry, path_override: Option<&Path>) -> DaloResult<PathBuf> {
if let Some(path) = path_override {
return store::expand_user_path(path);
}
let Some(default_path) = entry.default_path else {
return Err(DaloError::TargetPathRequired {
target: entry.id.to_owned(),
});
};
store::expand_user_path(Path::new(default_path))
}
fn canonicalize_target_path(path: &Path) -> PathBuf {
if let Ok(canonical) = path.canonicalize() {
return canonical;
}
match (path.parent(), path.file_name()) {
(Some(parent), Some(file_name)) => match parent.canonicalize() {
Ok(canonical_parent) => canonical_parent.join(file_name),
Err(_) => path.to_path_buf(),
},
_ => path.to_path_buf(),
}
}
fn upsert_target_state(
state: &mut StateFile,
target_id: &str,
path: &Path,
canonical_path: &Path,
) -> DaloResult<TargetLinkStatus> {
let existing = state
.targets
.iter_mut()
.find(|target| target.id == target_id);
let status = if let Some(target) = existing {
if target.path == path && target.canonical_path == canonical_path && target.enabled {
TargetLinkStatus::Existing
} else {
target.path = path.to_path_buf();
target.canonical_path = canonical_path.to_path_buf();
target.enabled = true;
TargetLinkStatus::Updated
}
} else {
state.targets.push(TargetState {
id: target_id.to_owned(),
path: path.to_path_buf(),
canonical_path: canonical_path.to_path_buf(),
enabled: true,
extra: Default::default(),
});
TargetLinkStatus::Linked
};
state.rebuild_materialization_dirs()?;
Ok(status)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn registry_should_include_v1_targets() {
let ids = registry().iter().map(|entry| entry.id).collect::<Vec<_>>();
assert_eq!(
ids,
[
"codex", "claude", "openclaw", "hermes", "generic", "cursor", "opencode",
]
);
}
#[test]
fn link_target_should_dedupe_shared_physical_directory() {
let temp_dir = tempfile::tempdir().expect("tempdir should be created");
let store_root = temp_dir.path().join("store");
let shared_target = temp_dir.path().join("skills");
store::init_store(store_root.clone(), false).expect("init should succeed");
link_target(&store_root, "codex", Some(&shared_target), false)
.expect("codex link should succeed");
link_target(&store_root, "openclaw", Some(&shared_target), false)
.expect("openclaw link should succeed");
let state =
store::read_state(&StorePaths::new(store_root)).expect("state should be readable");
assert_eq!(state.targets.len(), 2);
assert_eq!(state.materialization_dirs.len(), 1);
assert_eq!(
state.materialization_dirs[0].logical_targets,
["codex".to_owned(), "openclaw".to_owned()]
);
}
#[test]
fn link_target_should_report_stable_canonical_path_between_dry_run_and_real_run() {
use std::os::unix::fs as unix_fs;
let temp_dir = tempfile::tempdir().expect("tempdir should be created");
let store_root = temp_dir.path().join("store");
store::init_store(store_root.clone(), false).expect("init should succeed");
let real_parent = temp_dir.path().join("real");
std::fs::create_dir_all(&real_parent).expect("real parent should be created");
let linked_parent = temp_dir.path().join("linked");
unix_fs::symlink(&real_parent, &linked_parent).expect("symlink should be created");
let target = linked_parent.join("skills");
let planned = link_target(&store_root, "codex", Some(&target), true)
.expect("dry-run link should succeed");
let applied = link_target(&store_root, "codex", Some(&target), false)
.expect("real link should succeed");
assert_eq!(planned.canonical_path, applied.canonical_path);
}
#[test]
fn link_target_should_read_store_before_creating_target_dir() {
let temp_dir = tempfile::tempdir().expect("tempdir should be created");
let store_root = temp_dir.path().join("missing-store");
let target = temp_dir.path().join("skills");
let error = link_target(&store_root, "codex", Some(&target), false)
.expect_err("link should require an initialized store");
assert!(matches!(error, DaloError::StoreNotInitialized { .. }));
assert!(!target.exists());
}
#[test]
fn link_target_should_not_create_directory_when_metadata_merge_fails() {
let temp_dir = tempfile::tempdir().expect("tempdir should be created");
let store_root = temp_dir.path().join("store");
let shared_target = temp_dir.path().join("shared-skills");
store::init_store(store_root.clone(), false).expect("init should succeed");
let paths = StorePaths::new(store_root.clone());
let state = conflicting_future_directory_state(temp_dir.path(), &shared_target);
store::write_state(&paths, &state).expect("conflicting future state should be written");
let error = link_target(&store_root, "codex", Some(&shared_target), false)
.expect_err("lossy metadata merge should block link");
assert!(matches!(error, DaloError::StateMetadataConflict { .. }));
assert!(!shared_target.exists());
assert_eq!(
store::read_state(&paths).expect("state should remain readable"),
state
);
}
#[test]
fn unlink_target_should_drop_unrelated_conflicting_directory_metadata() {
let temp_dir = tempfile::tempdir().expect("tempdir should be created");
let store_root = temp_dir.path().join("store");
let shared_target = temp_dir.path().join("shared-skills");
store::init_store(store_root.clone(), false).expect("init should succeed");
let paths = StorePaths::new(store_root.clone());
let state = conflicting_future_directory_state(temp_dir.path(), &shared_target);
store::write_state(&paths, &state).expect("conflicting future state should be written");
let report = unlink_target(&store_root, "codex", false)
.expect("unrelated metadata must not wedge target removal");
let updated = store::read_state(&paths).expect("updated state should be readable");
assert_eq!(report.status, TargetUnlinkStatus::Unlinked);
assert!(updated.targets.iter().all(|target| target.id != "codex"));
assert_eq!(updated.materialization_dirs.len(), 1);
assert_eq!(updated.materialization_dirs[0].path, shared_target);
assert_eq!(
updated.materialization_dirs[0].logical_targets,
["claude".to_owned(), "openclaw".to_owned()]
);
assert!(
!updated.materialization_dirs[0]
.extra
.contains_key("future_directory_field")
);
}
#[test]
fn unlink_target_dry_run_should_report_missing_for_unlinked_target() {
let temp_dir = tempfile::tempdir().expect("tempdir should be created");
let store_root = temp_dir.path().join("store");
store::init_store(store_root.clone(), false).expect("init should succeed");
let report =
unlink_target(&store_root, "codex", true).expect("dry-run unlink should inspect state");
assert_eq!(report.status, TargetUnlinkStatus::Missing);
}
#[test]
fn link_generic_should_require_path() {
let temp_dir = tempfile::tempdir().expect("tempdir should be created");
let store_root = temp_dir.path().join("store");
store::init_store(store_root.clone(), false).expect("init should succeed");
let error = link_target(&store_root, "generic", None, false)
.expect_err("generic should require a path");
assert_eq!(
error.to_string(),
"target `generic` requires an explicit path"
);
}
fn conflicting_future_directory_state(root: &Path, shared_target: &Path) -> StateFile {
let mut state = StateFile::empty();
state.targets = vec![
TargetState {
id: "codex".to_owned(),
path: root.join("old-codex"),
canonical_path: root.join("old-codex"),
enabled: true,
extra: Default::default(),
},
TargetState {
id: "claude".to_owned(),
path: root.join("old-claude"),
canonical_path: root.join("old-claude"),
enabled: true,
extra: Default::default(),
},
TargetState {
id: "openclaw".to_owned(),
path: root.join("old-openclaw"),
canonical_path: root.join("old-openclaw"),
enabled: true,
extra: Default::default(),
},
];
state
.rebuild_materialization_dirs()
.expect("initial directories should rebuild");
for (target_id, value) in [("claude", "claude value"), ("openclaw", "openclaw value")] {
state
.materialization_dirs
.iter_mut()
.find(|directory| directory.logical_targets == [target_id.to_owned()])
.expect("target directory should exist")
.extra
.insert(
"future_directory_field".to_owned(),
toml::Value::String(value.to_owned()),
);
}
for target in state
.targets
.iter_mut()
.filter(|target| target.id != "codex")
{
target.path = shared_target.to_path_buf();
target.canonical_path = shared_target.to_path_buf();
}
state
}
}