Skip to main content

agent_hub_runtime/core/
skill_deployment.rs

1use std::path::{Path, PathBuf};
2
3use super::{
4    error::{AppError, TargetConflictDetail},
5    scenario_service::{deployment_target, is_skill_path_within_root, replace_policy},
6    skill_metadata,
7    skill_store::{SkillStore, SkillTargetRecord},
8    sync_engine, tool_adapters, tool_service,
9};
10
11/// Why a caller is writing to an agent's skills directory.
12///
13/// Adoption and stranded-target repair legitimately write over an existing
14/// real directory that has no `skill_targets` row — that directory is the very
15/// thing the user asked us to take over. Ordinary deployment must never do
16/// that, so the two intents cannot share a code path (#363).
17#[derive(Debug, Clone, Copy)]
18pub enum DeployIntent<'a> {
19    /// Ordinary deployment: replace only what our own records vouch for.
20    Managed,
21    /// The user explicitly asked us to take over this scanned skill path.
22    AdoptExisting(&'a Path),
23}
24
25/// Re-point every `source_ref` that names `target` at the referring skill's own
26/// central copy, ahead of an adoption that replaces `target` with a managed
27/// deployment (#425).
28///
29/// An adopted directory stops being an independent copy the moment the
30/// adoption runs: it becomes a link to (or copy of) central that can be
31/// removed at any time — by the agent's own skill management cleaning up what
32/// it does not recognize, or by a later undeploy. A skill whose `source_ref`
33/// still names that directory then fails its update check with
34/// `source_missing` forever, even though the central copy is intact.
35///
36/// The central copy always exists while the skill row does, so re-pointing
37/// keeps the source resolvable; the content-hash comparison against it keeps
38/// reporting `up_to_date`. Matching is by exact string or canonicalized path,
39/// because import records can spell the same directory with mixed separators
40/// than the deployment target computed from the adapter.
41pub(crate) fn detach_source_refs_from_adoption_target(
42    store: &SkillStore,
43    target: &Path,
44) -> Result<(), AppError> {
45    let target_str = target.to_string_lossy().into_owned();
46    // `canonicalize` resolves through symlinks, but a symlinked target is only
47    // unlinked by the replacement below (`remove_classified_target` treats
48    // LinkToSource/ForeignLink as `remove_link`) -- whatever it pointed at
49    // survives untouched. Resolving through the link would re-point the
50    // source_ref of a directory that is still on disk and still the user's
51    // source of truth, and the update check would then compare central to
52    // itself forever. An exact string match still applies: if the source_ref
53    // *is* the link path, that link really is going away.
54    let target_canonical = if std::fs::symlink_metadata(target)
55        .map(|meta| meta.file_type().is_symlink())
56        .unwrap_or(false)
57    {
58        None
59    } else {
60        std::fs::canonicalize(target).ok()
61    };
62    for skill in store.get_all_skills().map_err(AppError::db)? {
63        let Some(source_ref) = skill.source_ref.as_deref() else {
64            continue;
65        };
66        // Already re-pointed by a previous adoption — nothing to do.
67        if source_ref == skill.central_path {
68            continue;
69        }
70        let points_at_target = source_ref == target_str
71            || target_canonical.as_ref().is_some_and(|canonical| {
72                std::fs::canonicalize(source_ref).is_ok_and(|source| &source == canonical)
73            });
74        if points_at_target {
75            store
76                .update_skill_source_ref(&skill.id, &skill.central_path)
77                .map_err(AppError::db)?;
78            log::info!(
79                "adoption: re-pointed source_ref of skill '{}' at its central copy; \
80                 the adopted agent directory is now a deployment, not a source (#425)",
81                skill.name
82            );
83        }
84    }
85    Ok(())
86}
87
88/// Deploy one skill; `force` requires explicit confirmation of replacement.
89pub fn sync_single_skill_to_tool(
90    store: &SkillStore,
91    skill_id: &str,
92    tool: &str,
93    intent: DeployIntent<'_>,
94    force: bool,
95) -> Result<(), AppError> {
96    let adapter = tool_adapters::find_adapter_with_store(store, tool)
97        .ok_or_else(|| AppError::not_found(format!("Unknown tool: {}", tool)))?;
98
99    if !adapter.can_deploy() {
100        return Err(AppError::not_found(format!(
101            "{} is not installed",
102            adapter.display_name
103        )));
104    }
105
106    if tool_service::get_disabled_tools(store).contains(&tool.to_string()) {
107        return Err(AppError::invalid_input(format!(
108            "{} is disabled",
109            adapter.display_name
110        )));
111    }
112
113    let skill = store
114        .get_skill_by_id(skill_id)
115        .map_err(AppError::db)?
116        .ok_or_else(|| AppError::not_found("Skill not found"))?;
117
118    let source = PathBuf::from(&skill.central_path);
119    let existing_targets = store
120        .get_targets_for_skill(skill_id)
121        .map_err(AppError::db)?;
122    let target = match intent {
123        DeployIntent::AdoptExisting(path) => {
124            let root = adapter.skills_dir();
125            if !is_skill_path_within_root(path, &root) {
126                return Err(AppError::invalid_input(
127                    "Skill path is outside the agent skills directory",
128                ));
129            }
130            path.to_path_buf()
131        }
132        DeployIntent::Managed => deployment_target(
133            &adapter,
134            &sync_engine::target_dir_name(&source, &skill.name),
135            skill_id,
136            &existing_targets,
137        ),
138    };
139    let preference = crate::core::deployment_preferences::Preference::load(
140        store,
141        crate::core::deployment_preferences::Scope::Global,
142    )?;
143    let recorded_mode = match intent {
144        DeployIntent::AdoptExisting(_) => None,
145        DeployIntent::Managed => existing_targets
146            .iter()
147            .find(|existing| {
148                existing.tool == tool && std::path::Path::new(&existing.target_path) == target
149            })
150            .map(|existing| existing.mode.clone()),
151    };
152    let mode = preference.for_target(recorded_mode.as_deref());
153    let policy = match intent {
154        DeployIntent::AdoptExisting(_) => sync_engine::ReplacePolicy::UserConfirmed,
155        DeployIntent::Managed => replace_policy(recorded_mode.as_deref(), force),
156    };
157    if matches!(policy, sync_engine::ReplacePolicy::UserConfirmed) {
158        // The directory at `target` may still be the import source of the very
159        // skill being deployed (or of a sibling record): re-point those at
160        // central BEFORE the replacement, so a failure partway through the
161        // replacement can never leave a dangling source behind (#425).
162        detach_source_refs_from_adoption_target(store, &target)?;
163    }
164    let actual_mode = sync_engine::sync_skill(&source, &target, mode, policy).map_err(|e| {
165        if let Some(refused) = e.downcast_ref::<sync_engine::ReplaceRefused>() {
166            AppError::target_conflict(
167                refused.to_string(),
168                vec![TargetConflictDetail {
169                    path: refused.target.to_string_lossy().to_string(),
170                    reason: refused.reason.to_string(),
171                    is_skill: skill_metadata::is_valid_skill_dir(&refused.target),
172                }],
173            )
174        } else {
175            AppError::io(e)
176        }
177    })?;
178
179    let now = chrono::Utc::now().timestamp_millis();
180    let target_record = SkillTargetRecord {
181        id: uuid::Uuid::new_v4().to_string(),
182        skill_id: skill_id.to_string(),
183        tool: tool.to_string(),
184        target_path: target.to_string_lossy().to_string(),
185        mode: actual_mode.as_str().to_string(),
186        status: "ok".to_string(),
187        synced_at: Some(now),
188        last_error: None,
189        source_hash: skill.content_hash.clone(),
190    };
191
192    store.insert_target(&target_record).map_err(AppError::db)?;
193    Ok(())
194}
195
196#[cfg(test)]
197mod tests;