Skip to main content

agent_hub_runtime/core/
scenario_service.rs

1pub(crate) use super::skill_deployment::detach_source_refs_from_adoption_target;
2pub use super::skill_deployment::{sync_single_skill_to_tool, DeployIntent};
3
4use serde::Serialize;
5use std::collections::{HashMap, HashSet};
6use std::fmt;
7use std::path::{Path, PathBuf};
8use std::time::Instant;
9
10use super::{
11    error::{AppError, TargetConflictDetail},
12    skill_metadata,
13    skill_store::{ScenarioRecord, SkillStore, SkillTargetRecord},
14    sync_engine, tool_adapters, tool_service,
15};
16
17#[derive(Debug, Clone)]
18pub struct ScenarioSyncTarget {
19    pub skill_id: String,
20    pub skill_name: String,
21    pub tool: String,
22    pub source: PathBuf,
23    pub target: PathBuf,
24    pub mode: sync_engine::SyncMode,
25    /// Current content hash of the central skill source, copied from
26    /// `SkillRecord.content_hash`. Compared against the previously
27    /// synced `SkillTargetRecord.source_hash` to skip redundant
28    /// Copy-mode resyncs at startup (issue #153).
29    pub source_hash: Option<String>,
30}
31
32#[derive(Debug, Clone, Serialize)]
33pub struct SyncPreviewTarget {
34    pub skill_id: String,
35    pub skill_name: String,
36    pub tool: String,
37    pub target_path: String,
38    pub mode: String,
39}
40
41pub fn ensure_scenario_exists(store: &SkillStore, scenario_id: &str) -> Result<(), AppError> {
42    let exists = store
43        .get_all_scenarios()
44        .map_err(AppError::db)?
45        .iter()
46        .any(|s| s.id == scenario_id);
47    if !exists {
48        return Err(AppError::not_found("Scenario not found"));
49    }
50    Ok(())
51}
52
53pub fn enabled_deployable_adapters_for_scenario_skill(
54    store: &SkillStore,
55    scenario_id: &str,
56    skill_id: &str,
57) -> Result<Vec<tool_adapters::ToolAdapter>, AppError> {
58    let adapters = tool_adapters::enabled_deployable_adapters(store);
59    let adapter_keys: Vec<String> = adapters.iter().map(|a| a.key.clone()).collect();
60
61    store
62        .ensure_scenario_skill_tool_defaults(scenario_id, skill_id, &adapter_keys)
63        .map_err(AppError::db)?;
64
65    let enabled = store
66        .get_enabled_tools_for_scenario_skill(scenario_id, skill_id)
67        .map_err(AppError::db)?;
68    let enabled_set: HashSet<String> = enabled.into_iter().collect();
69
70    Ok(adapters
71        .into_iter()
72        .filter(|adapter| enabled_set.contains(&adapter.key))
73        .collect())
74}
75
76pub fn collect_scenario_sync_targets(
77    store: &SkillStore,
78    scenario_id: &str,
79) -> Result<Vec<ScenarioSyncTarget>, AppError> {
80    let skills = store
81        .get_skills_for_scenario(scenario_id)
82        .map_err(AppError::db)?;
83    let preference = crate::core::deployment_preferences::Preference::load(
84        store,
85        crate::core::deployment_preferences::Scope::Global,
86    )?;
87    let existing_targets = store.get_all_targets().map_err(AppError::db)?;
88    let mut targets = Vec::new();
89
90    for skill in &skills {
91        let source = PathBuf::from(&skill.central_path);
92        let target_name = sync_engine::target_dir_name(&source, &skill.name);
93        let adapters =
94            enabled_deployable_adapters_for_scenario_skill(store, scenario_id, &skill.id)?;
95        for adapter in &adapters {
96            let target = deployment_target(adapter, &target_name, &skill.id, &existing_targets);
97            let recorded = existing_targets.iter().find(|existing| {
98                existing.skill_id == skill.id
99                    && existing.tool == adapter.key
100                    && Path::new(&existing.target_path) == target
101            });
102            let mode = preference.for_target(recorded.map(|existing| existing.mode.as_str()));
103            targets.push(ScenarioSyncTarget {
104                skill_id: skill.id.clone(),
105                skill_name: skill.name.clone(),
106                tool: adapter.key.clone(),
107                source: source.clone(),
108                target,
109                mode,
110                source_hash: skill.content_hash.clone(),
111            });
112        }
113    }
114
115    Ok(targets)
116}
117
118pub(crate) fn deployment_target(
119    adapter: &tool_adapters::ToolAdapter,
120    target_name: &str,
121    skill_id: &str,
122    existing_targets: &[SkillTargetRecord],
123) -> PathBuf {
124    let root = adapter.skills_dir();
125    existing_targets
126        .iter()
127        .find(|target| target.skill_id == skill_id && target.tool == adapter.key)
128        .map(|target| PathBuf::from(&target.target_path))
129        .filter(|path| is_skill_path_within_root(path, &root))
130        .unwrap_or_else(|| root.join(target_name))
131}
132
133pub(crate) fn is_skill_path_within_root(path: &Path, root: &Path) -> bool {
134    path.strip_prefix(root).is_ok_and(|relative| {
135        !relative.as_os_str().is_empty()
136            && relative
137                .components()
138                .all(|component| matches!(component, std::path::Component::Normal(_)))
139    })
140}
141
142pub fn preview_scenario_sync(
143    store: &SkillStore,
144    scenario_id: &str,
145) -> Result<Vec<SyncPreviewTarget>, AppError> {
146    collect_scenario_sync_targets(store, scenario_id).map(|targets| {
147        targets
148            .into_iter()
149            .map(|target| SyncPreviewTarget {
150                skill_id: target.skill_id,
151                skill_name: target.skill_name,
152                tool: target.tool,
153                target_path: target.target.to_string_lossy().to_string(),
154                mode: target.mode.as_str().to_string(),
155            })
156            .collect()
157    })
158}
159
160/// Decide which `SyncMode` `is_target_current` should compare against, or
161/// `None` if the existing target's mode is incompatible with the desired
162/// mode and the skip path must be refused.
163///
164/// Returns `Some(existing)` when both modes match exactly. Also returns
165/// `Some(Copy)` when the existing record is `"copy"` but the desired
166/// mode is `Symlink` — this is the Windows fallback case (issue #153):
167/// `symlink_dir()` failed on a prior run and we landed in copy mode, so
168/// every subsequent startup would re-attempt symlink, fail again, and
169/// trigger a full recursive copy. Treating the existing copy as
170/// compatible lets the hash gate skip when the source hasn't changed.
171///
172/// The reverse direction (existing `"symlink"`, desired `Copy`) returns
173/// `None` because the user actively changed the `sync_mode` setting and
174/// the on-disk symlink doesn't reflect that intent.
175fn skip_check_mode(
176    existing_mode: &str,
177    desired: sync_engine::SyncMode,
178) -> Option<sync_engine::SyncMode> {
179    match (existing_mode, desired) {
180        ("symlink", sync_engine::SyncMode::Symlink) => Some(sync_engine::SyncMode::Symlink),
181        ("copy", sync_engine::SyncMode::Copy) => Some(sync_engine::SyncMode::Copy),
182        ("copy", sync_engine::SyncMode::Symlink) => Some(sync_engine::SyncMode::Copy),
183        _ => None,
184    }
185}
186
187/// Remove a recorded deployment, keeping (and reporting) anything that no
188/// longer matches the record. Every row-driven removal in this module goes
189/// through here so none of them can fall back to "delete whatever is there".
190fn remove_recorded_or_warn(path: &Path, recorded_mode: &str) -> bool {
191    match sync_engine::remove_recorded_target(path, recorded_mode) {
192        Ok(removed) => {
193            if !removed {
194                log::warn!(
195                    "Preserving {}: no longer matches its recorded {recorded_mode} deployment; \
196                     removing the record only",
197                    path.display()
198                );
199            }
200            removed
201        }
202        Err(e) => {
203            log::warn!("Failed to remove sync target {}: {e}", path.display());
204            false
205        }
206    }
207}
208
209/// A key identifying the *directory entry* a target path names, used to spot
210/// two rows that claim one object under different spellings.
211///
212/// The parent is canonicalized (resolving `..` and symlinked ancestors) and the
213/// final component re-attached verbatim — deliberately NOT `canonicalize()` on
214/// the whole path, which follows the final symlink and would collapse every
215/// agent's link into the one library directory they all point at, making
216/// distinct deployments look like the same object.
217///
218/// Known gap: on a case-insensitive filesystem two spellings of the final
219/// component still key differently. That is the same lexical assumption the
220/// rest of this module makes about `target_path`, and erring here only costs a
221/// refusal, never a deletion.
222fn ownership_key(path: &Path, memo: &mut HashMap<PathBuf, PathBuf>) -> PathBuf {
223    let (Some(parent), Some(name)) = (path.parent(), path.file_name()) else {
224        return path.to_path_buf();
225    };
226    // Rows share a handful of skills directories, so memoizing the parent keeps
227    // this to a few syscalls no matter how large the library is.
228    let canonical_parent = match memo.get(parent) {
229        Some(cached) => cached.clone(),
230        None => {
231            let resolved = parent
232                .canonicalize()
233                .unwrap_or_else(|_| parent.to_path_buf());
234            memo.insert(parent.to_path_buf(), resolved.clone());
235            resolved
236        }
237    };
238    canonical_parent.join(name)
239}
240
241/// Authorization for a deployment write: a `skill_targets` row claiming this
242/// exact path lets us replace what it recorded, otherwise we may only write
243/// where nothing of the user's would be destroyed (#363).
244pub(crate) fn replace_policy(
245    recorded_mode: Option<&str>,
246    force: bool,
247) -> sync_engine::ReplacePolicy<'_> {
248    match recorded_mode {
249        Some(mode) => sync_engine::ReplacePolicy::Recorded { mode },
250        None if force => sync_engine::ReplacePolicy::UserConfirmed,
251        None => sync_engine::ReplacePolicy::NoClobber,
252    }
253}
254
255/// One target a sync refused to write because it is not ours to replace.
256///
257/// Kept structured all the way to the caller: an agent driving the CLI has to
258/// tell the user *which* path is in the way and what to do about it, and a
259/// pre-rendered English sentence cannot be branched on (#363).
260#[derive(Debug, Clone, Serialize)]
261pub struct TargetConflict {
262    pub target: PathBuf,
263    pub reason: String,
264}
265
266impl fmt::Display for TargetConflict {
267    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
268        f.write_str(&sync_engine::refusal_message(&self.target, &self.reason))
269    }
270}
271
272/// Sync every desired target, returning the ownership refusals rather than
273/// failing on them.
274///
275/// Refusals are *reported*, not thrown, because whether one should abort the
276/// operation depends entirely on the caller: a user typing `skills sync` needs
277/// an error, while app startup must not be prevented from launching by a
278/// name collision in an agent directory. Returning the list lets each caller
279/// state that policy; an early `Err` here made startup panic (#363).
280pub fn sync_desired_targets(
281    store: &SkillStore,
282    desired_targets: &[ScenarioSyncTarget],
283    force: bool,
284) -> Result<Vec<TargetConflict>, AppError> {
285    let batch_start = Instant::now();
286    let existing_targets: HashMap<(String, String), SkillTargetRecord> = store
287        .get_all_targets()
288        .map_err(AppError::db)?
289        .into_iter()
290        .map(|target| ((target.skill_id.clone(), target.tool.clone()), target))
291        .collect();
292
293    let mut synced_count = 0usize;
294    let mut skipped_count = 0usize;
295    let mut failed_count = 0usize;
296    let mut refusals: Vec<TargetConflict> = Vec::new();
297
298    for desired in desired_targets {
299        let target_start = Instant::now();
300        let key = (desired.skill_id.clone(), desired.tool.clone());
301        // A row claiming exactly this path is what lets us replace a copy-mode
302        // directory; anything else must be left alone (#363).
303        let recorded_mode = existing_targets
304            .get(&key)
305            .filter(|existing| std::path::Path::new(&existing.target_path) == desired.target)
306            .map(|existing| existing.mode.clone());
307        if let Some(existing) = existing_targets.get(&key) {
308            let target_path = PathBuf::from(&existing.target_path);
309            if target_path != desired.target {
310                // Adapters can share a skills directory: amp and replit both
311                // deploy to ~/.config/agents/skills, and kimi did too until it
312                // moved to ~/.kimi-code/skills (#270). When one of them is
313                // retargeted, the old path is not this tool's leftover — it is
314                // still another tool's live deployment. Drop the stale record,
315                // but leave the directory to whoever is still deployed there.
316                let claimed_by_another_tool = desired_targets.iter().any(|other| {
317                    other.tool != desired.tool
318                        && other.skill_id == desired.skill_id
319                        && other.target == target_path
320                });
321                if claimed_by_another_tool {
322                    log::info!(
323                        "Keeping {}: still the deployment target of another tool; \
324                         dropping {}'s stale record only",
325                        target_path.display(),
326                        desired.tool
327                    );
328                } else {
329                    match sync_engine::remove_recorded_target(&target_path, &existing.mode) {
330                        Ok(true) => {}
331                        Ok(false) => log::warn!(
332                            "Keeping {}: no longer matches its recorded {} deployment; \
333                             dropping the stale record only",
334                            target_path.display(),
335                            existing.mode
336                        ),
337                        Err(e) => log::warn!(
338                            "Failed to remove stale target {}: {e}",
339                            target_path.display()
340                        ),
341                    }
342                }
343                if let Err(e) = store.delete_target(&desired.skill_id, &desired.tool) {
344                    log::warn!(
345                        "Failed to delete stale target record for skill {}, tool {}: {e}",
346                        desired.skill_id,
347                        desired.tool
348                    );
349                }
350            } else if existing.status == "ok" {
351                if let Some(check_mode) = skip_check_mode(&existing.mode, desired.mode) {
352                    if sync_engine::is_target_current(
353                        &desired.source,
354                        &desired.target,
355                        check_mode,
356                        existing.source_hash.as_deref(),
357                        desired.source_hash.as_deref(),
358                    ) {
359                        // Surface the Windows fallback case in logs so operators
360                        // can tell when a target is permanently on Copy because
361                        // an earlier symlink_dir() failed (issue #153). Helpful
362                        // when a user later enables Developer Mode and wonders
363                        // why Symlink isn't being re-attempted.
364                        if existing.mode == "copy"
365                            && matches!(desired.mode, sync_engine::SyncMode::Symlink)
366                        {
367                            log::debug!(
368                                "sync_desired_targets: skill {} ({}) staying on copy fallback for {} (content unchanged); trigger a manual resync to retry symlink",
369                                desired.skill_id,
370                                desired.skill_name,
371                                desired.tool
372                            );
373                        }
374                        skipped_count += 1;
375                        continue;
376                    }
377                }
378            }
379        }
380
381        match sync_engine::sync_skill(
382            &desired.source,
383            &desired.target,
384            desired.mode,
385            replace_policy(recorded_mode.as_deref(), force),
386        ) {
387            Ok(actual_mode) => {
388                let now = chrono::Utc::now().timestamp_millis();
389                let target_record = SkillTargetRecord {
390                    id: uuid::Uuid::new_v4().to_string(),
391                    skill_id: desired.skill_id.clone(),
392                    tool: desired.tool.clone(),
393                    target_path: desired.target.to_string_lossy().to_string(),
394                    mode: actual_mode.as_str().to_string(),
395                    status: "ok".to_string(),
396                    synced_at: Some(now),
397                    last_error: None,
398                    // Record the hash that was just synced so the next
399                    // run of this loop can short-circuit when the central
400                    // skill content has not changed (issue #153).
401                    source_hash: desired.source_hash.clone(),
402                };
403                if let Err(e) = store.insert_target(&target_record) {
404                    log::warn!(
405                        "Failed to insert sync target for skill {}: {e}",
406                        desired.skill_id
407                    );
408                }
409                synced_count += 1;
410                let elapsed = target_start.elapsed().as_millis();
411                if elapsed >= 200 {
412                    log::warn!(
413                        "sync_desired_targets: slow sync ({elapsed} ms, mode={}) for skill {} ({}) -> {}",
414                        actual_mode.as_str(),
415                        desired.skill_id,
416                        desired.skill_name,
417                        desired.target.display()
418                    );
419                }
420            }
421            Err(e) => {
422                failed_count += 1;
423                // An ownership refusal is not a transient failure to log and
424                // move past: the user's content is intact but the skill they
425                // asked for is not deployed, and saying "ok" to that is the
426                // half of #363 that made the data loss invisible.
427                if let Some(refused) = e.downcast_ref::<sync_engine::ReplaceRefused>() {
428                    refusals.push(TargetConflict {
429                        target: refused.target.clone(),
430                        reason: refused.reason.to_string(),
431                    });
432                }
433                log::warn!(
434                    "Failed to sync skill {} ({}) to {} after {} ms: {e}",
435                    desired.skill_id,
436                    desired.skill_name,
437                    desired.target.display(),
438                    target_start.elapsed().as_millis()
439                );
440            }
441        }
442    }
443
444    log::info!(
445        "sync_desired_targets: {} targets in {} ms (synced={synced_count}, skipped={skipped_count}, failed={failed_count})",
446        desired_targets.len(),
447        batch_start.elapsed().as_millis()
448    );
449
450    // Everything that could be synced has been; hand back what was not.
451    // Ordinary IO failures stay logged-and-tolerated, as before.
452    Ok(refusals)
453}
454
455/// Preview the ownership decisions made by `sync_desired_targets` without changing targets.
456pub fn preflight_scenario_sync_targets(
457    store: &SkillStore,
458    desired_targets: &[ScenarioSyncTarget],
459    force: bool,
460) -> Result<(), AppError> {
461    let existing_targets = store.get_all_targets().map_err(AppError::db)?;
462    let mut conflicts = Vec::new();
463    for desired in desired_targets {
464        let recorded_mode = existing_targets
465            .iter()
466            .find(|existing| {
467                existing.skill_id == desired.skill_id
468                    && existing.tool == desired.tool
469                    && std::path::Path::new(&existing.target_path) == desired.target
470            })
471            .map(|existing| existing.mode.as_str());
472        if let Err(error) = sync_engine::preflight_replace(
473            &desired.source,
474            &desired.target,
475            desired.mode,
476            replace_policy(recorded_mode, force),
477        ) {
478            if let Some(refused) = error.downcast_ref::<sync_engine::ReplaceRefused>() {
479                conflicts.push(TargetConflictDetail {
480                    path: refused.target.display().to_string(),
481                    reason: refused.reason.to_string(),
482                    is_skill: skill_metadata::is_valid_skill_dir(&refused.target),
483                });
484            } else {
485                return Err(AppError::io(error));
486            }
487        }
488    }
489    if conflicts.is_empty() {
490        Ok(())
491    } else {
492        Err(AppError::target_conflict(
493            format!(
494                "拒绝同步:{} 个目标路径已有内容且不由 AgentHub 管理,未做任何修改。",
495                conflicts.len()
496            ),
497            conflicts,
498        ))
499    }
500}
501
502/// Turn reported refusals into the error a user-initiated command should show.
503/// Deliberately says only that these targets were skipped — everything else in
504/// the operation did apply, so claiming "nothing happened" would be false.
505pub fn refusals_to_error(refusals: Vec<TargetConflict>) -> Result<(), AppError> {
506    if refusals.is_empty() {
507        return Ok(());
508    }
509    let summary = format!(
510        "已跳过 {} 个技能——目标路径已有内容且不由 AgentHub 管理(这些路径未被删除,其余技能已正常部署)。{}",
511        refusals.len(),
512        refusals
513            .iter()
514            .map(|c| c.to_string())
515            .collect::<Vec<_>>()
516            .join(";")
517    );
518    Err(AppError::target_conflict(
519        summary,
520        refusals
521            .into_iter()
522            .map(|c| TargetConflictDetail {
523                path: c.target.display().to_string(),
524                reason: c.reason,
525                is_skill: skill_metadata::is_valid_skill_dir(&c.target),
526            })
527            .collect(),
528    ))
529}
530
531pub fn unsync_obsolete_scenario_targets(
532    store: &SkillStore,
533    old_scenario_id: &str,
534    desired_targets: &[ScenarioSyncTarget],
535) -> Result<(), AppError> {
536    let desired_paths: HashMap<(String, String), PathBuf> = desired_targets
537        .iter()
538        .map(|target| {
539            (
540                (target.skill_id.clone(), target.tool.clone()),
541                target.target.clone(),
542            )
543        })
544        .collect();
545
546    let old_skill_ids = store
547        .get_skill_ids_for_scenario(old_scenario_id)
548        .map_err(AppError::db)?;
549    for skill_id in &old_skill_ids {
550        let targets = store.get_targets_for_skill(skill_id).unwrap_or_default();
551        for target in &targets {
552            let path = PathBuf::from(&target.target_path);
553            let key = (skill_id.clone(), target.tool.clone());
554            if desired_paths.get(&key) == Some(&path) {
555                continue;
556            }
557
558            remove_recorded_or_warn(&path, &target.mode);
559            if let Err(e) = store.delete_target(skill_id, &target.tool) {
560                log::warn!(
561                    "Failed to delete target record for skill {skill_id}, tool {}: {e}",
562                    target.tool
563                );
564            }
565        }
566    }
567
568    Ok(())
569}
570
571pub fn unsync_scenario_skills(store: &SkillStore, scenario_id: &str) -> Result<(), AppError> {
572    let skill_ids = store
573        .get_skill_ids_for_scenario(scenario_id)
574        .map_err(AppError::db)?;
575
576    for skill_id in &skill_ids {
577        let targets = store.get_targets_for_skill(skill_id).unwrap_or_default();
578        for target in &targets {
579            let path = PathBuf::from(&target.target_path);
580            remove_recorded_or_warn(&path, &target.mode);
581            if let Err(e) = store.delete_target(skill_id, &target.tool) {
582                log::warn!(
583                    "Failed to delete target record for skill {skill_id}, tool {}: {e}",
584                    target.tool
585                );
586            }
587        }
588    }
589
590    Ok(())
591}
592
593pub fn sync_scenario_skills(
594    store: &SkillStore,
595    scenario_id: &str,
596    force: bool,
597) -> Result<Vec<TargetConflict>, AppError> {
598    let desired_targets = collect_scenario_sync_targets(store, scenario_id)?;
599    sync_desired_targets(store, &desired_targets, force)
600}
601
602pub fn apply_scenario_to_default(
603    store: &SkillStore,
604    scenario_id: &str,
605    force: bool,
606) -> Result<Vec<TargetConflict>, AppError> {
607    ensure_scenario_exists(store, scenario_id)?;
608    let desired_targets = collect_scenario_sync_targets(store, scenario_id)?;
609
610    if let Ok(Some(old_id)) = store.get_active_scenario_id() {
611        if old_id != scenario_id {
612            unsync_obsolete_scenario_targets(store, &old_id, &desired_targets)?;
613        }
614    }
615
616    store
617        .set_active_scenario(scenario_id)
618        .map_err(AppError::db)?;
619    sync_desired_targets(store, &desired_targets, force)
620}
621
622pub fn sync_skill_to_active_scenario(
623    store: &SkillStore,
624    scenario_id: &str,
625    skill_id: &str,
626) -> Result<(), AppError> {
627    if let Ok(Some(active_id)) = store.get_active_scenario_id() {
628        if active_id == scenario_id {
629            let adapters =
630                enabled_deployable_adapters_for_scenario_skill(store, scenario_id, skill_id)?;
631            let preference = crate::core::deployment_preferences::Preference::load(
632                store,
633                crate::core::deployment_preferences::Scope::Global,
634            )?;
635            let Ok(Some(skill)) = store.get_skill_by_id(skill_id) else {
636                return Ok(());
637            };
638            let source = PathBuf::from(&skill.central_path);
639            let target_name = sync_engine::target_dir_name(&source, &skill.name);
640            let old_targets = store.get_targets_for_skill(skill_id).unwrap_or_default();
641            for adapter in &adapters {
642                let target = deployment_target(adapter, &target_name, skill_id, &old_targets);
643                let mut recorded_mode: Option<String> = None;
644                if let Some(old) = old_targets.iter().find(|t| t.tool == adapter.key) {
645                    let old_path = PathBuf::from(&old.target_path);
646                    if old_path != target {
647                        match sync_engine::remove_recorded_target(&old_path, &old.mode) {
648                            Ok(true) => {}
649                            Ok(false) => log::warn!(
650                                "Keeping {}: no longer matches its recorded {} deployment; \
651                                 dropping the stale record only",
652                                old_path.display(),
653                                old.mode
654                            ),
655                            Err(e) => log::warn!(
656                                "Failed to remove stale target {}: {e}",
657                                old_path.display()
658                            ),
659                        }
660                        let _ = store.delete_target(skill_id, &adapter.key);
661                    } else {
662                        recorded_mode = Some(old.mode.clone());
663                    }
664                }
665
666                let mode = preference.for_target(recorded_mode.as_deref());
667                match sync_engine::sync_skill(
668                    &source,
669                    &target,
670                    mode,
671                    replace_policy(recorded_mode.as_deref(), false),
672                ) {
673                    Ok(actual_mode) => {
674                        let now = chrono::Utc::now().timestamp_millis();
675                        let target_record = super::skill_store::SkillTargetRecord {
676                            id: uuid::Uuid::new_v4().to_string(),
677                            skill_id: skill_id.to_string(),
678                            tool: adapter.key.clone(),
679                            target_path: target.to_string_lossy().to_string(),
680                            mode: actual_mode.as_str().to_string(),
681                            status: "ok".to_string(),
682                            synced_at: Some(now),
683                            last_error: None,
684                            source_hash: skill.content_hash.clone(),
685                        };
686                        if let Err(e) = store.insert_target(&target_record) {
687                            log::warn!("Failed to insert sync target for skill {skill_id}: {e}");
688                        }
689                    }
690                    Err(e) => {
691                        log::warn!(
692                            "Failed to sync skill {skill_id} to {}: {e}",
693                            target.display()
694                        );
695                    }
696                }
697            }
698        }
699    }
700    Ok(())
701}
702
703pub fn ensure_default_startup_scenario(store: &SkillStore) -> Result<(), AppError> {
704    let mut scenarios = store.get_all_scenarios().map_err(AppError::db)?;
705    if scenarios.is_empty() {
706        let now = chrono::Utc::now().timestamp_millis();
707        let default_scenario = ScenarioRecord {
708            id: uuid::Uuid::new_v4().to_string(),
709            name: "Default".to_string(),
710            description: Some("Default startup scenario".to_string()),
711            icon: None,
712            sort_order: 0,
713            created_at: now,
714            updated_at: now,
715        };
716        store
717            .insert_scenario(&default_scenario)
718            .map_err(AppError::db)?;
719        scenarios.push(default_scenario);
720    }
721
722    // Startup restores whatever skill group was last active; there is no separate
723    // "default startup skill group" setting to override it.
724    let current_active = store.get_active_scenario_id().map_err(AppError::db)?;
725
726    let desired_active = current_active
727        .clone()
728        .filter(|id| scenarios.iter().any(|scenario| scenario.id == *id))
729        .unwrap_or_else(|| scenarios[0].id.clone());
730
731    if current_active.as_deref() != Some(desired_active.as_str()) {
732        if let Some(old_active) = current_active.as_deref() {
733            unsync_scenario_skills(store, old_active)?;
734        }
735        store
736            .set_active_scenario(&desired_active)
737            .map_err(AppError::db)?;
738    }
739
740    // Startup policy: a collision must never stop the app from launching. The
741    // colliding skill simply is not deployed, its content is untouched, and the
742    // workspace view shows it as not synced.
743    let refusals = sync_scenario_skills(store, &desired_active, false)?;
744    for refusal in &refusals {
745        log::warn!("startup sync skipped a target: {refusal}");
746    }
747    Ok(())
748}
749
750pub fn ensure_cli_scenario_state(store: &SkillStore) -> Result<(), AppError> {
751    let mut scenarios = store.get_all_scenarios().map_err(AppError::db)?;
752    if scenarios.is_empty() {
753        let now = chrono::Utc::now().timestamp_millis();
754        let default_scenario = ScenarioRecord {
755            id: uuid::Uuid::new_v4().to_string(),
756            name: "Default".to_string(),
757            description: Some("Default startup scenario".to_string()),
758            icon: None,
759            sort_order: 0,
760            created_at: now,
761            updated_at: now,
762        };
763        store
764            .insert_scenario(&default_scenario)
765            .map_err(AppError::db)?;
766        scenarios.push(default_scenario);
767    }
768
769    let current_active = store.get_active_scenario_id().map_err(AppError::db)?;
770    if current_active
771        .as_deref()
772        .is_some_and(|id| scenarios.iter().any(|scenario| scenario.id == id))
773    {
774        return Ok(());
775    }
776
777    store
778        .set_active_scenario(&scenarios[0].id)
779        .map_err(AppError::db)
780}
781
782pub fn restore_all_skills_sync_included(store: &SkillStore) -> Result<bool, AppError> {
783    let mut changed = false;
784    for skill in store.get_all_skills().map_err(AppError::db)? {
785        if !skill.enabled {
786            store
787                .update_skill_enabled(&skill.id, true)
788                .map_err(AppError::db)?;
789            changed = true;
790        }
791    }
792    Ok(changed)
793}
794
795pub fn sync_active_scenario_to_tool(store: &SkillStore, tool_key: &str) {
796    if let Ok(Some(active_id)) = store.get_active_scenario_id() {
797        let Ok(skill_ids) = store.get_skill_ids_for_scenario(&active_id) else {
798            return;
799        };
800        for skill_id in skill_ids {
801            if let Ok(adapters) =
802                enabled_deployable_adapters_for_scenario_skill(store, &active_id, &skill_id)
803            {
804                if adapters.iter().any(|adapter| adapter.key == tool_key) {
805                    let _ = sync_skill_to_active_scenario(store, &active_id, &skill_id);
806                }
807            }
808        }
809    }
810}
811
812#[derive(Debug, Clone, Copy)]
813pub enum BatchApplyMode {
814    Add,
815    Remove,
816}
817
818/// Apply a batch of `(skill_id × tool_key)` pairs in either Add or Remove mode
819/// without touching `active_scenario_id` or `scenario_skill_tools` toggles.
820///
821/// This is the tray-side skill group apply primitive. Unlike [`sync_single_skill_to_tool`]
822/// (which is wrapped by the `sync_skill_to_tool` Tauri command and carries the
823/// implicit active-skill-group toggle side-effect), this batch is a pure
824/// "write/remove files + maintain `skill_targets` rows" operation.
825///
826/// Remove mode handles shared physical paths: a `target_path` may be referenced
827/// by multiple `(skill_id, tool)` records when several tools resolve to the same
828/// skills directory. The filesystem path is only removed when no remaining
829/// `skill_targets` row references it after the batch deletions, so removing one
830/// skill group's tools never wipes another tool's still-active files.
831pub fn apply_skills_to_tools(
832    store: &SkillStore,
833    skill_ids: &[String],
834    tool_keys: &[String],
835    mode: BatchApplyMode,
836    force: bool,
837) -> Result<(), AppError> {
838    if skill_ids.is_empty() || tool_keys.is_empty() {
839        return Ok(());
840    }
841
842    match mode {
843        BatchApplyMode::Add => apply_add(store, skill_ids, tool_keys, false, force),
844        BatchApplyMode::Remove => apply_remove(store, skill_ids, tool_keys),
845    }
846}
847
848/// Check the same targets and ownership rules as batch deployment without writing.
849pub fn preflight_add_skills_to_tools(
850    store: &SkillStore,
851    skill_ids: &[String],
852    tool_keys: &[String],
853) -> Result<(), AppError> {
854    if skill_ids.is_empty() || tool_keys.is_empty() {
855        return Ok(());
856    }
857    apply_add(store, skill_ids, tool_keys, true, false)
858}
859
860fn apply_add(
861    store: &SkillStore,
862    skill_ids: &[String],
863    tool_keys: &[String],
864    preflight_only: bool,
865    force: bool,
866) -> Result<(), AppError> {
867    let preference = crate::core::deployment_preferences::Preference::load(
868        store,
869        crate::core::deployment_preferences::Scope::Global,
870    )?;
871    let disabled = tool_service::get_disabled_tools(store);
872
873    let mut adapters: HashMap<String, tool_adapters::ToolAdapter> = HashMap::new();
874    for key in tool_keys {
875        if disabled.contains(key) {
876            log::debug!("apply_skills_to_tools: skipping disabled tool {key}");
877            continue;
878        }
879        let Some(adapter) = tool_adapters::find_adapter_with_store(store, key) else {
880            log::warn!("apply_skills_to_tools: unknown tool {key}");
881            continue;
882        };
883        if !adapter.can_deploy() {
884            log::debug!(
885                "apply_skills_to_tools: skipping uninstalled tool {} ({key})",
886                adapter.display_name
887            );
888            continue;
889        }
890        adapters.insert(key.clone(), adapter);
891    }
892
893    // Plan every pair up front, then refuse the whole batch if any one of them
894    // would destroy something (#363, expectation 4). Not a rollback — a
895    // finished copy cannot be undone — but nothing is written until every pair
896    // has been judged.
897    struct PlannedPair {
898        skill: crate::core::skill_store::SkillRecord,
899        tool_key: String,
900        source: PathBuf,
901        target: PathBuf,
902        mode: sync_engine::SyncMode,
903    }
904
905    let existing_targets = store.get_all_targets().map_err(AppError::db)?;
906    let mut plan: Vec<PlannedPair> = Vec::new();
907    for skill_id in skill_ids {
908        let Ok(Some(skill)) = store.get_skill_by_id(skill_id) else {
909            log::warn!("apply_skills_to_tools: skill {skill_id} not found");
910            continue;
911        };
912        let source = PathBuf::from(&skill.central_path);
913        let target_name = sync_engine::target_dir_name(&source, &skill.name);
914        for (tool_key, adapter) in &adapters {
915            plan.push(PlannedPair {
916                skill: skill.clone(),
917                tool_key: tool_key.clone(),
918                mode: preference.for_target(
919                    existing_targets
920                        .iter()
921                        .find(|existing| {
922                            existing.skill_id == *skill_id
923                                && existing.tool == *tool_key
924                                && Path::new(&existing.target_path)
925                                    == deployment_target(
926                                        adapter,
927                                        &target_name,
928                                        skill_id,
929                                        &existing_targets,
930                                    )
931                        })
932                        .map(|existing| existing.mode.as_str()),
933                ),
934                source: source.clone(),
935                target: deployment_target(adapter, &target_name, skill_id, &existing_targets),
936            });
937        }
938    }
939
940    // Two skills whose central directories share a basename resolve to the
941    // same deployment path (`target_dir_name` uses the basename only), so the
942    // second would silently overwrite the first. Neither is the user's data,
943    // but the result is a target whose contents don't match its record.
944    // Two library skills planning onto one path is a naming problem, not a
945    // user's directory being in the way — kept apart so the refusal that does
946    // mean the latter is the only thing tagged as a target conflict.
947    let mut duplicate_targets: Vec<String> = Vec::new();
948    let mut conflicts: Vec<TargetConflictDetail> = Vec::new();
949    let mut probe_errors: Vec<String> = Vec::new();
950    // Keyed on skill id, not name: names are not unique, and two distinct
951    // skills that happen to share one would otherwise slip through as "the
952    // same skill" and silently overwrite each other.
953    let mut planned_paths: HashMap<&Path, (&str, &str)> = HashMap::new();
954    for pair in &plan {
955        let entry = (pair.skill.id.as_str(), pair.skill.name.as_str());
956        if let Some((first_id, first_name)) = planned_paths.insert(pair.target.as_path(), entry) {
957            if first_id != pair.skill.id {
958                duplicate_targets.push(format!(
959                    "{} — skills \"{}\" and \"{}\" both deploy here",
960                    pair.target.display(),
961                    first_name,
962                    pair.skill.name
963                ));
964            }
965        }
966    }
967    if !duplicate_targets.is_empty() {
968        return Err(AppError::invalid_input(format!(
969            "拒绝部署:{} 个目标路径被多个技能同时占用,未做任何修改。{}",
970            duplicate_targets.len(),
971            duplicate_targets.join(";")
972        )));
973    }
974
975    // Ownership belongs to the path, not to the (skill, tool) pair. When two
976    // agents share a skills directory, a row for either one vouches for the
977    // object there, so evidence is pooled per path before judging — otherwise
978    // the pair without its own row would refuse a target we demonstrably own.
979    // Pool the distinct recorded modes per path, then keep the evidence only
980    // when they agree. Contradictory rows must refuse, exactly as in the
981    // removal path — taking whichever one came first would let a stale `copy`
982    // row authorize deleting a real directory, and HashMap order is not even
983    // deterministic about which one that is.
984    // Pooled from every existing row that lands on a planned path, not just
985    // from the pairs in this batch: `skill_targets` is unique on
986    // `(skill_id, tool)`, not on `target_path`, so a row we did not select can
987    // still be a claim on the same object — and a contradictory one.
988    // Keyed by directory entry rather than by path string, so a row spelled
989    // differently (symlinked ancestor, `..`) but naming the same object still
990    // counts as evidence about it.
991    let mut key_memo: HashMap<PathBuf, PathBuf> = HashMap::new();
992    let planned_keys: HashSet<PathBuf> = plan
993        .iter()
994        .map(|pair| ownership_key(&pair.target, &mut key_memo))
995        .collect();
996    let mut modes_by_key: HashMap<PathBuf, HashSet<&str>> = HashMap::new();
997    for row in &existing_targets {
998        let key = ownership_key(Path::new(row.target_path.as_str()), &mut key_memo);
999        if planned_keys.contains(&key) {
1000            modes_by_key
1001                .entry(key)
1002                .or_default()
1003                .insert(row.mode.as_str());
1004        }
1005    }
1006    let evidence_by_key: HashMap<&PathBuf, &str> = modes_by_key
1007        .iter()
1008        .filter_map(|(key, modes)| {
1009            let mut it = modes.iter();
1010            match (it.next(), it.next()) {
1011                (Some(only), None) => Some((key, *only)),
1012                _ => None,
1013            }
1014        })
1015        .collect();
1016    let evidence_for = |target: &Path, memo: &mut HashMap<PathBuf, PathBuf>| -> Option<&str> {
1017        let key = ownership_key(target, memo);
1018        evidence_by_key.get(&key).copied()
1019    };
1020    let mut preflighted: HashSet<&Path> = HashSet::new();
1021    for pair in &plan {
1022        if !preflighted.insert(pair.target.as_path()) {
1023            continue;
1024        }
1025        if let Err(e) = sync_engine::preflight_replace(
1026            &pair.source,
1027            &pair.target,
1028            pair.mode,
1029            replace_policy(evidence_for(&pair.target, &mut key_memo), force),
1030        ) {
1031            // Keep the refusal's own path and reason: the caller may be an
1032            // agent that has to name the directory in the way and offer the
1033            // way out, which a flattened sentence cannot support.
1034            match e.downcast_ref::<sync_engine::ReplaceRefused>() {
1035                Some(refused) => conflicts.push(TargetConflictDetail {
1036                    path: refused.target.display().to_string(),
1037                    reason: refused.reason.to_string(),
1038                    is_skill: skill_metadata::is_valid_skill_dir(&refused.target),
1039                }),
1040                // Failing to even inspect the target (permissions, a broken
1041                // mount) is an IO problem. Reporting it as a conflict would
1042                // tell the caller to adopt or move content that may not exist.
1043                None => probe_errors.push(format!("{}: {e}", pair.target.display())),
1044            }
1045        }
1046    }
1047    if !probe_errors.is_empty() {
1048        return Err(AppError::io(format!(
1049            "拒绝部署:{} 个目标路径无法检查,未做任何修改。{}",
1050            probe_errors.len(),
1051            probe_errors.join(";")
1052        )));
1053    }
1054    if !conflicts.is_empty() {
1055        let summary = format!(
1056            "拒绝部署:{}/{} 个目标路径已有内容且不由 AgentHub 管理,未做任何修改。{}",
1057            conflicts.len(),
1058            plan.len(),
1059            conflicts
1060                .iter()
1061                .map(|c| sync_engine::refusal_message(Path::new(&c.path), &c.reason))
1062                .collect::<Vec<_>>()
1063                .join(";")
1064        );
1065        return Err(AppError::target_conflict(summary, conflicts));
1066    }
1067    if preflight_only {
1068        return Ok(());
1069    }
1070
1071    let mut synced = 0usize;
1072    let mut failed = 0usize;
1073    // Several tools can resolve to one skills directory, so two pairs of this
1074    // batch may write the same path. The second one has no row of its own yet,
1075    // and without this it would refuse the directory the first one just created
1076    // (only visible in copy mode — a symlink already points at the source).
1077    let mut written_in_batch: HashMap<&Path, String> = HashMap::new();
1078    for pair in &plan {
1079        let PlannedPair {
1080            skill,
1081            tool_key,
1082            source,
1083            target,
1084            mode,
1085        } = pair;
1086        let skill_id = &skill.id;
1087        // What this batch just wrote outranks the row: the row describes the
1088        // previous deployment, the batch describes what is on disk right now.
1089        // Preferring the row would make the second pair on a shared path refuse
1090        // the directory the first pair created after a mode change.
1091        // Same precedence the preflight used, and deliberately NOT falling back
1092        // to this pair's own `recorded_mode`: that would reinstate a row the
1093        // conflict rule above just rejected as ambiguous.
1094        let effective_mode = written_in_batch
1095            .get(target.as_path())
1096            .map(String::as_str)
1097            .or_else(|| evidence_for(target, &mut key_memo));
1098        match sync_engine::sync_skill(source, target, *mode, replace_policy(effective_mode, force))
1099        {
1100            Ok(actual_mode) => {
1101                written_in_batch.insert(target.as_path(), actual_mode.as_str().to_string());
1102                let now = chrono::Utc::now().timestamp_millis();
1103                let target_record = SkillTargetRecord {
1104                    id: uuid::Uuid::new_v4().to_string(),
1105                    skill_id: skill_id.clone(),
1106                    tool: tool_key.clone(),
1107                    target_path: target.to_string_lossy().to_string(),
1108                    mode: actual_mode.as_str().to_string(),
1109                    status: "ok".to_string(),
1110                    synced_at: Some(now),
1111                    last_error: None,
1112                    source_hash: skill.content_hash.clone(),
1113                };
1114                if let Err(e) = store.insert_target(&target_record) {
1115                    log::warn!(
1116                        "apply_skills_to_tools: failed to insert target for skill {skill_id} / {tool_key}: {e}"
1117                    );
1118                    failed += 1;
1119                } else {
1120                    synced += 1;
1121                }
1122            }
1123            Err(e) => {
1124                failed += 1;
1125                log::warn!(
1126                    "apply_skills_to_tools: failed to sync skill {skill_id} ({}) to {}: {e}",
1127                    skill.name,
1128                    target.display()
1129                );
1130            }
1131        }
1132    }
1133
1134    log::info!(
1135        "apply_skills_to_tools(Add): skills={} tools={} synced={synced} failed={failed}",
1136        skill_ids.len(),
1137        adapters.len(),
1138    );
1139    Ok(())
1140}
1141
1142fn apply_remove(
1143    store: &SkillStore,
1144    skill_ids: &[String],
1145    tool_keys: &[String],
1146) -> Result<(), AppError> {
1147    let tool_set: HashSet<&String> = tool_keys.iter().collect();
1148
1149    // Keep each row's recorded mode: it is the only evidence of what we put at
1150    // that path, and it has to survive until after the filesystem is inspected
1151    // (#363, expectation 5).
1152    let mut to_delete: Vec<(String, String, PathBuf, String)> = Vec::new();
1153    for skill_id in skill_ids {
1154        let targets = store.get_targets_for_skill(skill_id).unwrap_or_default();
1155        for target in targets {
1156            if tool_set.contains(&target.tool) {
1157                to_delete.push((
1158                    skill_id.clone(),
1159                    target.tool.clone(),
1160                    PathBuf::from(&target.target_path),
1161                    target.mode.clone(),
1162                ));
1163            }
1164        }
1165    }
1166
1167    if to_delete.is_empty() {
1168        return Ok(());
1169    }
1170
1171    // Rows go first, exactly as before: the recorded modes this batch needs are
1172    // already captured above, so deleting now costs no evidence, and re-reading
1173    // afterwards keeps the survivor set honest if any delete failed. Reading
1174    // must not fail open — treating a DB error as "nothing survives" would
1175    // authorize removing a path another tool is still using.
1176    for (skill_id, tool, _, _) in &to_delete {
1177        if let Err(e) = store.delete_target(skill_id, tool) {
1178            log::warn!(
1179                "apply_skills_to_tools(Remove): failed to delete target record for skill {skill_id} / {tool}: {e}"
1180            );
1181        }
1182    }
1183
1184    // Must not fail open: treating a read error as "nothing survives" would
1185    // authorize deleting a path another tool still uses. It also must not fail
1186    // with an error, because the rows above are already gone — returning Err
1187    // here would leave callers thinking nothing happened. So on a read error,
1188    // keep every path and stop.
1189    let still_referenced: HashSet<PathBuf> = match store.get_all_targets() {
1190        Ok(rows) => rows
1191            .into_iter()
1192            .map(|t| PathBuf::from(&t.target_path))
1193            .collect(),
1194        Err(e) => {
1195            log::warn!(
1196                "apply_skills_to_tools(Remove): cannot verify remaining references ({e}); \
1197                 leaving every affected path on disk"
1198            );
1199            return Ok(());
1200        }
1201    };
1202
1203    // One path may be claimed by several doomed rows. Their modes must agree
1204    // before anything is deleted: disagreement means we do not actually know
1205    // what we put there, and for a fix whose whole purpose is preservation,
1206    // ambiguous evidence has to preserve. (Taking whichever mode happens to
1207    // match would let a stale `copy` row authorize deleting a user directory
1208    // that replaced our symlink.)
1209    let mut candidates: Vec<(&PathBuf, Vec<&String>)> = Vec::new();
1210    let mut seen: HashMap<&PathBuf, usize> = HashMap::new();
1211    for (_, _, path, mode) in &to_delete {
1212        match seen.get(path) {
1213            Some(index) => candidates[*index].1.push(mode),
1214            None => {
1215                seen.insert(path, candidates.len());
1216                candidates.push((path, vec![mode]));
1217            }
1218        }
1219    }
1220
1221    let mut removed = 0usize;
1222    let mut preserved = 0usize;
1223    for (path, recorded_modes) in candidates {
1224        if still_referenced.contains(path) {
1225            log::debug!(
1226                "apply_skills_to_tools(Remove): keeping {} (still referenced by another target)",
1227                path.display()
1228            );
1229            continue;
1230        }
1231        let mut modes: Vec<&str> = recorded_modes.iter().map(|m| m.as_str()).collect();
1232        modes.sort_unstable();
1233        modes.dedup();
1234        let outcome = match modes.as_slice() {
1235            [single] => sync_engine::remove_recorded_target(path, single),
1236            // Contradictory records: keep the object, drop the rows.
1237            _ => {
1238                log::warn!(
1239                    "apply_skills_to_tools(Remove): {} has conflicting records ({}); \
1240                     preserving it and removing the records only",
1241                    path.display(),
1242                    modes.join("/")
1243                );
1244                Ok(false)
1245            }
1246        };
1247        match outcome {
1248            Ok(true) => removed += 1,
1249            // Someone replaced our deployment with content of their own. The
1250            // record goes; the content stays.
1251            Ok(false) => {
1252                preserved += 1;
1253                log::warn!(
1254                    "apply_skills_to_tools(Remove): preserving {} — no longer matches its \
1255                     recorded deployment ({}); removing the record only",
1256                    path.display(),
1257                    recorded_modes
1258                        .iter()
1259                        .map(|m| m.as_str())
1260                        .collect::<Vec<_>>()
1261                        .join("/")
1262                );
1263            }
1264            Err(e) => {
1265                log::warn!(
1266                    "apply_skills_to_tools(Remove): failed to remove {}: {e}",
1267                    path.display()
1268                );
1269            }
1270        }
1271    }
1272
1273    log::info!(
1274        "apply_skills_to_tools(Remove): pairs={} fs_removed={removed} preserved={preserved}",
1275        to_delete.len(),
1276    );
1277    Ok(())
1278}
1279
1280#[cfg(test)]
1281mod sync_desired_targets_tests;
1282
1283#[cfg(test)]
1284mod skip_check_mode_tests;