Skip to main content

agent_hub_runtime/core/
project_library.rs

1//! Portable project skills and team deployment, independent of a personal library.
2mod entries;
3mod git;
4mod installation;
5mod manifest;
6mod removal;
7mod transaction;
8mod update;
9pub use update::update;
10
11use anyhow::{bail, Context, Result};
12use serde::Serialize;
13use std::{
14    collections::{BTreeMap, BTreeSet},
15    fs,
16    path::{Path, PathBuf},
17};
18
19use super::{
20    error::AppError, installer, path_guard, skill_store::SkillRecord, tool_adapters::ToolAdapter,
21};
22pub use manifest::LIBRARY as SKILLS_DIRECTORY;
23use manifest::{fingerprint, ProjectEntry, ProjectManifest, ProjectSource, LIBRARY, MANIFEST};
24pub use removal::{remove_target, remove_target_with_adapter};
25use transaction::{ProjectLock, Publication};
26
27#[derive(Serialize)]
28pub struct ProjectLibraryStatus {
29    pub skills: Vec<ProjectLibrarySkill>,
30    pub files_to_commit: Vec<String>,
31    /// Optional for Agent consumption; shared only for AgentHub maintenance.
32    pub management_files: Vec<String>,
33    pub ignored_paths: Vec<String>,
34}
35
36#[derive(Serialize)]
37pub struct ProjectLibrarySkill {
38    pub name: String,
39    pub directory: String,
40    pub modified: bool,
41    pub disabled: bool,
42    pub targets: Vec<String>,
43    pub stale_targets: Vec<String>,
44    pub target_issues: Vec<ProjectTargetIssue>,
45}
46
47#[derive(Serialize)]
48pub struct ProjectTargetIssue {
49    pub agent: String,
50    pub agent_name: String,
51    pub path: String,
52    pub reason: &'static str,
53}
54
55/// Install actual content in the project and generate selected team targets.
56/// Reinstall adds targets but never upgrades an existing project version.
57pub fn install(
58    root: &Path,
59    skill: &SkillRecord,
60    targets: &[ToolAdapter],
61) -> Result<ProjectLibraryStatus, AppError> {
62    install_with_mode(root, skill, targets, false)
63}
64
65/// Import/adopt project central contents; copy mode supports teams without links.
66pub fn install_with_mode(
67    root: &Path,
68    skill: &SkillRecord,
69    targets: &[ToolAdapter],
70    copy: bool,
71) -> Result<ProjectLibraryStatus, AppError> {
72    mutate(root, |root, lock| {
73        let name = super::sync_engine::target_dir_name(Path::new(&skill.central_path), &skill.name);
74        safe_name(&name)?;
75        let mut manifest = manifest::read(root)?;
76        if manifest.skills.contains_key(&name) {
77            return deploy_unlocked(root, lock, &mut manifest, &name, targets, copy);
78        }
79        installation::install_unlocked(root, lock, skill, targets, &mut manifest, &name, copy)
80    })
81}
82
83/// Add team targets using project content, without reading a personal library.
84pub fn deploy(
85    root: &Path,
86    name: &str,
87    targets: &[ToolAdapter],
88) -> Result<ProjectLibraryStatus, AppError> {
89    deploy_with_mode(root, name, targets, false)
90}
91
92pub fn deploy_with_mode(
93    root: &Path,
94    name: &str,
95    targets: &[ToolAdapter],
96    copy: bool,
97) -> Result<ProjectLibraryStatus, AppError> {
98    mutate(root, |root, lock| {
99        safe_name(name)?;
100        let mut manifest = manifest::read(root)?;
101        deploy_unlocked(root, lock, &mut manifest, name, targets, copy)
102    })
103}
104
105fn deploy_unlocked(
106    root: &Path,
107    lock: &ProjectLock,
108    manifest: &mut ProjectManifest,
109    name: &str,
110    targets: &[ToolAdapter],
111    copy: bool,
112) -> Result<()> {
113    let canonical = format!("{LIBRARY}/{name}");
114    let content = safe_path(root, &canonical)?;
115    if !super::skill_metadata::is_valid_skill_dir(&content) {
116        bail!("Project library Skill not found");
117    }
118    let current = fingerprint(&content)?.context("Project library Skill not found")?;
119    let entry = manifest
120        .skills
121        .entry(name.into())
122        .or_insert_with(|| ProjectEntry {
123            id: uuid::Uuid::new_v4().to_string(),
124            name: name.into(),
125            content_hash: current.clone(),
126            targets: BTreeMap::new(),
127            source: None,
128            disabled: false,
129            disabled_targets: BTreeSet::new(),
130            linked_targets: BTreeSet::new(),
131            extra: BTreeMap::new(),
132        });
133    if entry.disabled {
134        bail!("Project Skill is disabled; enable it before adding targets");
135    }
136    let paths = target_paths(root, name, targets)?;
137    let snapshot = team_snapshot(&content, &current)?;
138    let content = snapshot.path().join("content");
139    let mut publication = Publication::new(root)?;
140    publication.observe(canonical.clone(), Some(current.clone()));
141    for path in unique_paths(paths.values()) {
142        if path == canonical {
143            continue;
144        }
145        let recorded = entry.targets.values().any(|existing| existing == &path);
146        let disabled = entry
147            .targets
148            .iter()
149            .any(|(key, existing)| existing == &path && entry.disabled_targets.contains(key));
150        for (key, added_path) in &paths {
151            if added_path == &path && disabled {
152                entry.disabled_targets.insert(key.clone());
153            }
154        }
155        let path = actual_target(&path, disabled);
156        let baseline = entries::fingerprint_entry(&entries::path(root, &path)?)?;
157        check_replace(
158            root,
159            &path,
160            recorded.then_some(entry.content_hash.as_str()),
161            Some(&current),
162        )?;
163        let linked = if recorded {
164            installation::linked_path(entry, &path) || entries::path(root, &path)?.is_symlink()
165        } else {
166            !copy
167        };
168        if linked {
169            let created = publication.add_link(
170                root,
171                path.clone(),
172                &canonical,
173                &content,
174                baseline.as_deref(),
175            )?;
176            for (agent, added_path) in &paths {
177                if actual_target(added_path, disabled) == path {
178                    if created {
179                        entry.linked_targets.insert(agent.clone());
180                    } else {
181                        entry.linked_targets.remove(agent);
182                    }
183                }
184            }
185        } else {
186            publication.add(root, path.clone(), Some(&content), baseline.as_deref())?;
187            for (agent, added_path) in &paths {
188                if actual_target(added_path, disabled) == path {
189                    entry.linked_targets.remove(agent);
190                }
191            }
192        }
193    }
194    entry.targets.extend(paths);
195    // Existing targets may still use the original baseline. Only repair of
196    // every team target can advance the baseline after editing canonical.
197    publish_manifest(root, lock, publication, manifest)
198}
199
200/// Refresh existing team entries from project content, without adding Agents.
201pub fn repair(root: &Path, name: &str) -> Result<ProjectLibraryStatus, AppError> {
202    mutate(root, |root, lock| {
203        let mut manifest = manifest::read(root)?;
204        let entry = manifest
205            .skills
206            .get_mut(name)
207            .context("Project Skill is not managed")?;
208        let canonical = canonical_path(name, entry.disabled);
209        let baseline = entry.content_hash.clone();
210        let content = safe_path(root, &canonical)?;
211        let current = fingerprint(&content)?
212            .context("Project library content missing; restore it from project Git")?;
213        let snapshot = team_snapshot(&content, &current)?;
214        let content = snapshot.path().join("content");
215        let mut publication = Publication::new(root)?;
216        publication.observe(canonical.clone(), Some(current.clone()));
217        for path in all_entry_paths(name, entry) {
218            if path == canonical || !entries::is_present(root, &path)? {
219                continue;
220            }
221            check_replace(root, &path, Some(&baseline), Some(&current))?;
222            installation::publish_target(
223                &mut publication,
224                root,
225                entry,
226                path,
227                &canonical,
228                &content,
229                Some(&baseline),
230            )?;
231        }
232        entry.content_hash = current;
233        publish_manifest(root, lock, publication, &manifest)
234    })
235}
236
237/// Shared project enable/disable, including every recorded team copy.
238pub fn set_enabled(
239    root: &Path,
240    name: &str,
241    enabled: bool,
242) -> Result<ProjectLibraryStatus, AppError> {
243    mutate(root, |root, lock| {
244        let mut manifest = manifest::read(root)?;
245        let entry = manifest
246            .skills
247            .get_mut(name)
248            .context("Project Skill is not managed")?;
249        if entry.disabled != enabled {
250            return Ok(());
251        }
252        let old_paths = all_entry_paths(name, entry);
253        let source = safe_path(root, &canonical_path(name, entry.disabled))?;
254        let current = fingerprint(&source)?.context("Project library content missing")?;
255        // Moves require all copies to agree; arbitrary local edits are never
256        // discarded merely because the user toggled a shared project Skill.
257        for path in &old_paths {
258            check_replace(root, path, Some(&current), None)?;
259        }
260        let snapshot = team_snapshot(&source, &current)?;
261        let source = snapshot.path().join("content");
262        entry.disabled = !enabled;
263        entry.disabled_targets.clear();
264        let new_paths = all_entry_paths(name, entry);
265        let mut publication = Publication::new(root)?;
266        let unchanged: Vec<_> = old_paths
267            .iter()
268            .filter(|path| new_paths.contains(path))
269            .cloned()
270            .collect();
271        for path in old_paths {
272            if !unchanged.contains(&path) {
273                publication.add(root, path, None, Some(&current))?;
274            }
275        }
276        for path in new_paths {
277            if unchanged.contains(&path) {
278                continue;
279            }
280            check_replace(root, &path, None, Some(&current))?;
281            installation::publish_target(
282                &mut publication,
283                root,
284                entry,
285                path,
286                &canonical_path(name, entry.disabled),
287                &source,
288                None,
289            )?;
290        }
291        entry.content_hash = current;
292        publish_manifest(root, lock, publication, &manifest)
293    })
294}
295
296/// Toggle a dedicated team entry without changing the canonical content.
297/// A native public-directory target is necessarily shared across readers.
298pub fn set_target_enabled(
299    root: &Path,
300    name: &str,
301    agent: &str,
302    enabled: bool,
303) -> Result<ProjectLibraryStatus, AppError> {
304    let manifest = manifest::read(root).map_err(AppError::io_with_context)?;
305    if manifest
306        .skills
307        .get(name)
308        .and_then(|entry| entry.targets.get(agent))
309        .is_some_and(|path| path == &format!("{LIBRARY}/{name}"))
310    {
311        return set_enabled(root, name, enabled);
312    }
313    mutate(root, |root, lock| {
314        let mut manifest = manifest::read(root)?;
315        let entry = manifest
316            .skills
317            .get_mut(name)
318            .context("Project Skill is not managed")?;
319        if entry.disabled {
320            if !enabled {
321                return Ok(());
322            }
323            bail!("Shared project Skill is disabled; enable the project Skill first");
324        }
325        let path = entry
326            .targets
327            .get(agent)
328            .context("Team target not found")?
329            .clone();
330        let disabled = entry.disabled_targets.contains(agent);
331        if disabled != enabled {
332            return Ok(());
333        }
334        let old = actual_target(&path, disabled);
335        let new = actual_target(&path, !enabled);
336        let source = entries::path(root, &old)?;
337        let current = entries::content_fingerprint(root, &old)?
338            .context("Team entry missing; repair it first")?;
339        check_replace(root, &new, None, Some(&current))?;
340        let mut publication = Publication::new(root)?;
341        publication.add(root, old, None, Some(&current))?;
342        publication.add(root, new, Some(&source), None)?;
343        let aliases: Vec<_> = entry
344            .targets
345            .iter()
346            .filter(|(_, other)| *other == &path)
347            .map(|(key, _)| key.clone())
348            .collect();
349        for key in aliases {
350            if enabled {
351                entry.disabled_targets.remove(&key);
352            } else {
353                entry.disabled_targets.insert(key);
354            }
355        }
356        publish_manifest(root, lock, publication, &manifest)
357    })
358}
359
360/// Remove the complete project Skill after the user selects project deletion.
361pub fn remove(root: &Path, name: &str) -> Result<ProjectLibraryStatus, AppError> {
362    mutate(root, |root, lock| {
363        let mut manifest = manifest::read(root)?;
364        let entry = manifest
365            .skills
366            .get(name)
367            .context("Project Skill is not managed")?;
368        let mut publication = Publication::new(root)?;
369        for path in all_entry_paths(name, entry) {
370            check_replace(root, &path, Some(&entry.content_hash), None)?;
371            publication.add(root, path, None, Some(&entry.content_hash))?;
372        }
373        manifest.skills.remove(name);
374        publish_manifest(root, lock, publication, &manifest)
375    })
376}
377
378pub fn is_managed(root: &Path, name: &str) -> Result<bool, AppError> {
379    manifest::read(root)
380        .map(|manifest| manifest.skills.contains_key(name))
381        .map_err(AppError::io_with_context)
382}
383
384/// Read portable state without creating directories or modifying project files.
385pub fn status(root: &Path) -> Result<ProjectLibraryStatus, AppError> {
386    let root = root.canonicalize().map_err(AppError::io)?;
387    status_inner(&root).map_err(AppError::io_with_context)
388}
389
390fn status_inner(root: &Path) -> Result<ProjectLibraryStatus> {
391    let manifest = manifest::read(root)?;
392    let mut files = Vec::new();
393    let mut management_files = Vec::new();
394    let mut skills = Vec::new();
395    if root.join(MANIFEST).is_file() {
396        files.push(MANIFEST.into());
397        management_files.push(MANIFEST.into());
398    }
399    for (directory, entry) in &manifest.skills {
400        let canonical = canonical_path(directory, entry.disabled);
401        let current = fingerprint(&safe_path(root, &canonical)?)?;
402        let mut stale = Vec::new();
403        let mut target_issues = Vec::new();
404        for (agent, path) in &entry.targets {
405            let path = actual_target(
406                path,
407                entry.disabled || entry.disabled_targets.contains(agent),
408            );
409            let target = entries::path(root, &path)?;
410            // The actual entry, not historical manifest membership, defines
411            // deployment. Grey/unassigned Agents are a normal state.
412            if !entries::is_present(root, &path)? {
413                continue;
414            }
415            let is_linked = entry.linked_targets.contains(agent);
416            let reason = if is_linked && !target.is_symlink() {
417                Some("link_replaced")
418            } else if (is_linked || target.is_symlink())
419                && !entries::points_to(root, &path, &canonical)
420            {
421                // Report link drift without reading another project's/personal content.
422                Some("link_mismatch")
423            } else if entries::content_fingerprint(root, &path)? != current {
424                Some("content_mismatch")
425            } else {
426                None
427            };
428            if let Some(reason) = reason {
429                stale.push(agent.clone());
430                target_issues.push(ProjectTargetIssue {
431                    agent: agent.clone(),
432                    agent_name: super::tool_adapters::find_adapter(agent)
433                        .map(|adapter| adapter.display_name)
434                        .unwrap_or_else(|| agent.clone()),
435                    path,
436                    reason,
437                });
438            }
439        }
440        files.extend(all_entry_paths(directory, entry));
441        skills.push(ProjectLibrarySkill {
442            name: entry.name.clone(),
443            directory: directory.clone(),
444            disabled: entry.disabled,
445            modified: current.as_deref() != Some(&entry.content_hash),
446            targets: entry.targets.keys().cloned().collect(),
447            stale_targets: stale,
448            target_issues,
449        });
450    }
451    if let Ok(repo) = git2::Repository::discover(root) {
452        if let (Some(workdir), Ok(changes)) = (repo.workdir(), repo.statuses(None)) {
453            for change in changes.iter().filter(|change| {
454                change
455                    .status()
456                    .intersects(git2::Status::WT_DELETED | git2::Status::INDEX_DELETED)
457            }) {
458                if let Some(path) = change.path().and_then(|path| {
459                    workdir
460                        .join(path)
461                        .strip_prefix(root)
462                        .ok()
463                        .map(Path::to_path_buf)
464                }) {
465                    let path = path
466                        .to_string_lossy()
467                        .replace(std::path::MAIN_SEPARATOR, "/");
468                    // Only report removed Skill files, not unrelated project changes.
469                    if path.ends_with("/SKILL.md") || path.ends_with("/skill.md") {
470                        files.push(path);
471                    }
472                }
473            }
474        }
475    }
476    files.sort();
477    files.dedup();
478    let ignored_paths = git::ignored_paths(root, &files);
479    Ok(ProjectLibraryStatus {
480        skills,
481        files_to_commit: files,
482        management_files,
483        ignored_paths,
484    })
485}
486
487fn mutate(
488    root: &Path,
489    action: impl FnOnce(&Path, &ProjectLock) -> Result<()>,
490) -> Result<ProjectLibraryStatus, AppError> {
491    let _guard = super::project_skill_mutation::lock_project_skill_mutation()?;
492    let root = root
493        .canonicalize()
494        .map_err(|err| AppError::io_with_context(err.into()))?;
495    let result = (|| {
496        let lock = ProjectLock::acquire(&root)?;
497        transaction::recover(&root, &lock)?;
498        action(&root, &lock)?;
499        status_inner(&root)
500    })();
501    result.map_err(|error| match error.downcast::<AppError>() {
502        Ok(error) => error,
503        Err(error) => AppError::io_with_context(error),
504    })
505}
506
507pub(crate) fn safe_name(name: &str) -> Result<()> {
508    path_guard::ensure_safe_skill_relative_path(name).map_err(|e| anyhow::anyhow!(e.message))?;
509    if name.contains(['/', '\\', ':']) || name.starts_with('.') {
510        bail!("Invalid project Skill directory name");
511    }
512    Ok(())
513}
514
515pub(crate) fn safe_path(root: &Path, relative: &str) -> Result<PathBuf> {
516    let target = entries::path(root, relative)?;
517    if !path_guard::is_path_safe(root, &target) {
518        bail!("Project path escapes its workspace");
519    }
520    if target.is_symlink() {
521        bail!("Project path contains a symbolic link; import or migrate explicitly");
522    }
523    Ok(target)
524}
525
526fn check_replace(
527    root: &Path,
528    path: &str,
529    baseline: Option<&str>,
530    desired: Option<&str>,
531) -> Result<()> {
532    let current = entries::content_fingerprint(root, path)?;
533    if current.is_none() || current.as_deref() == desired || current.as_deref() == baseline {
534        return Ok(());
535    }
536    bail!("Project content changed or is not managed: {path}. Existing files were preserved; review the differences first");
537}
538
539fn target_paths(
540    root: &Path,
541    name: &str,
542    targets: &[ToolAdapter],
543) -> Result<BTreeMap<String, String>> {
544    if targets.is_empty() {
545        bail!("Select at least one team Agent");
546    }
547    // Keep owned values explicit before safe_path borrows them as str.
548    let mut paths: BTreeMap<String, String> = BTreeMap::new();
549    for target in targets {
550        let directory = target.project_relative_skills_dir();
551        if directory.is_empty() {
552            bail!("Agent has no project Skills directory");
553        }
554        let path = entries::target_path(root, &format!("{directory}/{name}"))?;
555        validate_target(root, name, &path)?;
556        for existing in paths.values() {
557            if existing != &path {
558                path_guard::ensure_disjoint_paths(
559                    &entries::path(root, existing)?,
560                    &entries::path(root, &path)?,
561                )
562                .map_err(|err| anyhow::anyhow!(err.message))?;
563            }
564        }
565        paths.insert(target.key.clone(), path);
566    }
567    Ok(paths)
568}
569
570pub(crate) fn validate_target(root: &Path, name: &str, path: &str) -> Result<()> {
571    let target = entries::path(root, path)?;
572    for relative in [
573        canonical_path(name, false),
574        canonical_path(name, true),
575        MANIFEST.into(),
576    ] {
577        let reference = entries::path(root, &relative)?;
578        if reference != target {
579            path_guard::ensure_disjoint_paths(&reference, &target)
580                .map_err(|err| anyhow::anyhow!(err.message))?;
581        }
582    }
583    Ok(())
584}
585
586fn unique_paths<'a>(paths: impl Iterator<Item = &'a String>) -> Vec<String> {
587    let mut result: Vec<_> = paths.cloned().collect();
588    result.sort();
589    result.dedup();
590    result
591}
592
593fn canonical_path(name: &str, disabled: bool) -> String {
594    format!(
595        "{LIBRARY}{}/{name}",
596        if disabled { "-disabled" } else { "" }
597    )
598}
599
600fn actual_target(path: &str, disabled: bool) -> String {
601    if !disabled {
602        return path.into();
603    }
604    let (parent, name) = path.rsplit_once('/').expect("validated relative target");
605    format!("{parent}-disabled/{name}")
606}
607
608fn all_entry_paths(name: &str, entry: &ProjectEntry) -> Vec<String> {
609    let mut paths = vec![canonical_path(name, entry.disabled)];
610    paths.extend(entry.targets.iter().map(|(agent, path)| {
611        actual_target(
612            path,
613            entry.disabled || entry.disabled_targets.contains(agent),
614        )
615    }));
616    paths.sort();
617    paths.dedup();
618    paths
619}
620
621fn team_snapshot(source: &Path, expected: &str) -> Result<tempfile::TempDir> {
622    let snapshot = tempfile::tempdir()?;
623    let content = snapshot.path().join("content");
624    transaction::copy_project_content(source, &content)?;
625    if fingerprint(source)?.as_deref() != Some(expected)
626        || fingerprint(&content)?.as_deref() != Some(expected)
627    {
628        bail!("Project source changed while staging; no team files were replaced");
629    }
630    Ok(snapshot)
631}
632
633fn portable_source(skill: &SkillRecord) -> Option<ProjectSource> {
634    if !matches!(skill.source_type.as_str(), "git" | "skillssh") {
635        return None;
636    }
637    let url = skill.source_ref_resolved.as_ref()?;
638    // Never export embedded credentials, local clone paths or filesystem URLs.
639    let parsed = reqwest::Url::parse(url).ok()?;
640    if !matches!(parsed.scheme(), "https" | "http")
641        || !parsed.username().is_empty()
642        || parsed.password().is_some()
643        || parsed.query().is_some()
644        || parsed.fragment().is_some()
645    {
646        return None;
647    }
648    Some(ProjectSource {
649        source_type: skill.source_type.clone(),
650        url: url.clone(),
651        subpath: skill
652            .source_subpath
653            .clone()
654            .filter(|path| path_guard::ensure_safe_skill_relative_path(path).is_ok()),
655        branch: skill.source_branch.clone(),
656        revision: if super::content_hash::hash_directory(Path::new(&skill.central_path))
657            .ok()
658            .as_ref()
659            == skill.content_hash.as_ref()
660        {
661            skill.source_revision.clone()
662        } else {
663            None
664        },
665    })
666}
667
668fn publish_manifest(
669    root: &Path,
670    lock: &ProjectLock,
671    mut publication: Publication,
672    manifest: &ProjectManifest,
673) -> Result<()> {
674    let file = tempfile::NamedTempFile::new()?;
675    let mut bytes = serde_json::to_vec_pretty(manifest)?;
676    bytes.push(b'\n');
677    fs::write(file.path(), bytes)?;
678    publication.add(
679        root,
680        MANIFEST.into(),
681        Some(file.path()),
682        manifest.baseline.as_deref(),
683    )?;
684    publication.apply(root, lock)
685}
686
687#[cfg(test)]
688mod compatibility_tests;
689#[cfg(test)]
690mod tests;
691
692#[cfg(test)]
693mod deployment_tests;
694
695#[cfg(test)]
696mod removal_tests;
697
698#[cfg(test)]
699mod force_restore_tests;
700
701#[cfg(test)]
702mod directory_alias_tests;