1use std::ffi::{OsStr, OsString};
13use std::io::Read;
14use std::path::{Path, PathBuf};
15
16use crate::error::{CoreError, ErrorCode};
17use crate::fs::Fs;
18use crate::model::clients::ClientSelection;
19use crate::model::ids::{self, IdKind};
20use crate::model::settings::NewItemEnable;
21use crate::model::skill_meta::{SkillEnable, SkillMeta, SkillSource, SkillSourceKind};
22use crate::remote::git::{Invocation, RunOutput, git_not_found, locate};
23use crate::scan::external::{self, ExternalReport};
24use crate::scan::{self, ScanReport, Scanner};
25use crate::skills::content_hash;
26use crate::skills::link::{SyncReport, sync};
27use crate::skills::store::{self, content_dir, missing_skill_file, not_found};
28use crate::skills::{
29 Entry, MAX_ARCHIVE_FILE_BYTES, MAX_ARCHIVE_FILES, MAX_ARCHIVE_TOTAL_BYTES, SKILL_FILE,
30 SkillFiles, SkillsEnv, check_name, confine, entry, frontmatter, io_error, read_folder, slug,
31};
32use crate::sources::{
33 self, SourceChange, SourceChangeKind, SourceRef, TrustCheck, TrustGrant, TrustVia,
34};
35use crate::store::{CommitId, Operation, Store};
36
37pub const SOURCES_DIR: &str = "skill-sources";
39const SEARCH_DEPTH: usize = 4;
41
42#[derive(Debug, Clone, PartialEq, Eq)]
44pub enum Source {
45 Git {
47 url: String,
48 git_ref: Option<String>,
49 path: Option<String>,
50 },
51 Local(PathBuf),
53}
54
55impl Source {
56 pub fn parse(text: &str, fs: &dyn Fs) -> Self {
63 let text = text.trim();
64 let lower = text.to_ascii_lowercase();
65 let is_url = ["https://", "http://", "ssh://", "git://", "file://"]
66 .iter()
67 .any(|scheme| lower.starts_with(scheme))
68 || is_scp_like(text);
69 if is_url {
70 return github_tree(text).unwrap_or_else(|| Source::Git {
71 url: text.to_owned(),
72 git_ref: None,
73 path: None,
74 });
75 }
76 let path = PathBuf::from(text);
77 if path.is_absolute() && is_bare_repo(fs, &path) {
78 return Source::Git {
79 url: text.to_owned(),
80 git_ref: None,
81 path: None,
82 };
83 }
84 Source::Local(path)
85 }
86}
87
88fn is_scp_like(text: &str) -> bool {
90 let Some((user_host, rest)) = text.split_once(':') else {
91 return false;
92 };
93 user_host.contains('@') && !user_host.contains(['/', '\\']) && !rest.starts_with("//")
94}
95
96fn github_tree(url: &str) -> Option<Source> {
97 let rest = url
98 .strip_prefix("https://github.com/")
99 .or_else(|| url.strip_prefix("http://github.com/"))?;
100 let parts: Vec<&str> = rest.trim_end_matches('/').split('/').collect();
101 if parts.len() < 4 || !(parts[2] == "tree" || parts[2] == "blob") {
102 return None;
103 }
104 let repo = parts[1].trim_end_matches(".git");
105 let mut path: Vec<&str> = parts[4..].to_vec();
106 if parts[2] == "blob" && path.last() == Some(&SKILL_FILE) {
107 path.pop();
108 }
109 Some(Source::Git {
110 url: format!("https://github.com/{}/{repo}", parts[0]),
111 git_ref: Some(parts[3].to_owned()),
112 path: (!path.is_empty()).then(|| path.join("/")),
113 })
114}
115
116fn is_bare_repo(fs: &dyn Fs, path: &Path) -> bool {
117 fs.exists(&path.join("HEAD"))
118 && fs.is_dir(&path.join("objects"))
119 && fs.is_dir(&path.join("refs"))
120 && !fs.exists(&path.join(SKILL_FILE))
121}
122
123#[derive(Debug, Clone, Default)]
125pub struct Naming {
126 pub id: Option<String>,
128 pub rename_if_taken: bool,
131}
132
133#[derive(Debug, Clone, Default)]
137pub struct Decisions {
138 pub allow_dangerous: bool,
142 pub trust: Option<TrustGrant>,
147 pub moved_trust: Option<TrustGrant>,
153 pub via: TrustVia,
155 pub external: Option<ExternalReport>,
161}
162
163#[derive(Debug, Clone)]
165pub struct InstallRequest {
166 pub source: Source,
167 pub path: Option<String>,
169 pub git_ref: Option<String>,
172 pub skill: Option<String>,
176 pub catalog: Option<String>,
179 pub naming: Naming,
180 pub decisions: Decisions,
181}
182
183impl InstallRequest {
184 pub fn new(source: Source) -> Self {
185 Self {
186 source,
187 path: None,
188 git_ref: None,
189 skill: None,
190 catalog: None,
191 naming: Naming::default(),
192 decisions: Decisions::default(),
193 }
194 }
195}
196
197#[derive(Debug, Clone)]
199pub struct Installed {
200 pub id: String,
201 pub name: String,
203 pub commit: Option<CommitId>,
204 pub source_commit: Option<String>,
206 pub renamed_from: Option<String>,
208 pub report: Option<SyncReport>,
210 pub warnings: Vec<CoreError>,
211 pub scan: ScanReport,
213 pub external: Option<ExternalReport>,
215}
216
217#[derive(Debug)]
219struct Fetched {
220 files: SkillFiles,
221 base_name: String,
224 from: String,
225 source: SkillSource,
226 clone: Option<PathBuf>,
228 redirect: Option<String>,
231}
232
233#[derive(Debug)]
237pub struct Prepared {
238 fetched: Fetched,
239 name: String,
240 scan: ScanReport,
241 external: Option<ExternalReport>,
243 spent: bool,
245 trust_source: Option<SourceRef>,
248 moved_to: Option<SourceRef>,
251 source_change: Option<SourceChange>,
253}
254
255impl Prepared {
256 pub fn name(&self) -> &str {
258 &self.name
259 }
260
261 pub fn files(&self) -> &SkillFiles {
263 &self.fetched.files
264 }
265
266 pub fn source(&self) -> &SkillSource {
268 &self.fetched.source
269 }
270
271 pub fn scan(&self) -> &ScanReport {
273 &self.scan
274 }
275
276 pub fn set_external(&mut self, report: Option<ExternalReport>) {
279 self.external = report;
280 }
281
282 pub fn external(&self) -> Option<&ExternalReport> {
284 self.external.as_ref()
285 }
286
287 pub fn trust_source(&self) -> Option<&SourceRef> {
291 self.trust_source.as_ref()
292 }
293
294 pub fn moved_to(&self) -> Option<&SourceRef> {
297 self.moved_to.as_ref()
298 }
299
300 pub fn source_change(&self) -> Option<&SourceChange> {
302 self.source_change.as_ref()
303 }
304}
305
306impl Drop for Prepared {
307 fn drop(&mut self) {
308 if let Some(clone) = self.fetched.clone.take() {
309 let _ = std::fs::remove_dir_all(clone);
312 }
313 }
314}
315
316pub fn prepare(sx: &SkillsEnv<'_>, request: &InstallRequest) -> Result<Prepared, CoreError> {
321 let requested = match &request.source {
322 Source::Git { url, .. } => Some(SourceRef::from_git_url(url)?),
323 Source::Local(_) => None,
324 };
325 let fetched = match &request.source {
326 Source::Local(path) => fetch_local(sx.fs, path)?,
327 Source::Git { url, git_ref, path } => {
328 let git_ref = request.git_ref.clone().or_else(|| git_ref.clone());
329 let path = request.path.clone().or_else(|| path.clone());
330 let mut fetched = fetch_git(sx, url, git_ref, path, request.skill.as_deref())?;
331 fetched.source.catalog.clone_from(&request.catalog);
332 fetched
333 }
334 };
335 let moved_to = requested.as_ref().and_then(|requested| {
336 let redirect = fetched.redirect.as_deref()?;
337 sources::detect::target_of(requested, redirect)
338 });
339 let source_change = moved_to.as_ref().map(sources::detect::moved_to);
340 let scan = Scanner::new(sx.fs, sx.home).scan_files(&fetched.files);
341 let name = fetched
342 .files
343 .get(SKILL_FILE)
344 .and_then(|text| {
345 frontmatter::parse(&String::from_utf8_lossy(text))
346 .ok()
347 .flatten()
348 })
349 .and_then(|fm| fm.name().map(str::to_owned))
350 .unwrap_or_else(|| fetched.base_name.clone());
351 Ok(Prepared {
352 fetched,
353 name,
354 scan,
355 external: None,
356 spent: false,
357 trust_source: requested,
358 moved_to,
359 source_change,
360 })
361}
362
363pub fn install_prepared(
373 store: &Store<'_>,
374 sx: &SkillsEnv<'_>,
375 prepared: &mut Prepared,
376 naming: &Naming,
377 decisions: &Decisions,
378) -> Result<Installed, CoreError> {
379 if prepared.spent {
380 return Err(CoreError::new(
381 ErrorCode::InvalidValue,
382 "this reviewed content is already installed",
383 ));
384 }
385 admit_with_move(
386 store,
387 prepared.trust_source.as_ref(),
388 prepared.moved_to.as_ref(),
389 decisions,
390 )?;
391 scan::gate(&prepared.scan, decisions.allow_dangerous)?;
392 if let Some(report) = &prepared.external {
393 external::gate(report, decisions.allow_dangerous)?;
394 }
395 let mut installed =
396 commit_install(store, sx, naming, &prepared.fetched, prepared.scan.clone())?;
397 installed.external = prepared.external.clone();
398 prepared.spent = true;
401 if let Some(clone) = prepared.fetched.clone.take()
402 && let Err(err) = keep_clone(sx, &clone, &installed.id)
403 {
404 let _ = remove_dir(sx.fs, &clone);
405 installed.warnings.push(err);
406 }
407 Ok(installed)
408}
409
410fn admit_with_move(
413 store: &Store<'_>,
414 requested: Option<&SourceRef>,
415 moved_to: Option<&SourceRef>,
416 decisions: &Decisions,
417) -> Result<(), CoreError> {
418 let Some(requested) = requested else {
419 return Ok(());
420 };
421 sources::would_admit(store, requested, decisions.trust)?;
422 if let Some(target) = moved_to {
423 sources::would_admit(store, target, decisions.moved_trust)?;
424 }
425 sources::admit(store, requested, decisions.trust, decisions.via)?;
426 if let Some(target) = moved_to {
427 sources::admit(store, target, decisions.moved_trust, decisions.via)?;
428 }
429 Ok(())
430}
431
432pub fn install(
437 store: &Store<'_>,
438 sx: &SkillsEnv<'_>,
439 request: &InstallRequest,
440) -> Result<Installed, CoreError> {
441 if let Source::Git { url, .. } = &request.source {
442 sources::would_admit(
443 store,
444 &SourceRef::from_git_url(url)?,
445 request.decisions.trust,
446 )?;
447 }
448 let mut prepared = prepare(sx, request)?;
449 install_prepared(
450 store,
451 sx,
452 &mut prepared,
453 &request.naming,
454 &request.decisions,
455 )
456}
457
458pub(crate) fn install_files(
463 store: &Store<'_>,
464 sx: &SkillsEnv<'_>,
465 naming: &Naming,
466 files: SkillFiles,
467 base_name: String,
468 source: SkillSource,
469) -> Result<Installed, CoreError> {
470 let fetched = Fetched {
471 files,
472 from: base_name.clone(),
473 base_name,
474 source,
475 clone: None,
476 redirect: None,
477 };
478 let scan = Scanner::new(sx.fs, sx.home).scan_files(&fetched.files);
479 commit_install(store, sx, naming, &fetched, scan)
480}
481
482fn commit_install(
483 store: &Store<'_>,
484 sx: &SkillsEnv<'_>,
485 naming: &Naming,
486 fetched: &Fetched,
487 scan: ScanReport,
488) -> Result<Installed, CoreError> {
489 let Some(skill_md) = fetched.files.get(SKILL_FILE) else {
490 return Err(CoreError::new(
491 ErrorCode::NotFound,
492 format!("the source has no {SKILL_FILE}"),
493 ));
494 };
495 let mut warnings = Vec::new();
496 let parsed = match frontmatter::parse(&String::from_utf8_lossy(skill_md)) {
497 Ok(parsed) => parsed,
498 Err(err) => {
499 warnings.push(err);
500 None
501 }
502 };
503 let name = parsed
504 .as_ref()
505 .and_then(|fm| fm.name())
506 .map_or_else(|| fetched.base_name.clone(), str::to_owned);
507 let wanted = match &naming.id {
508 Some(id) => {
509 ids::check(IdKind::Skill, id)?;
510 id.clone()
511 }
512 None => slug(&name)
513 .or_else(|| slug(&fetched.base_name))
514 .ok_or_else(|| {
515 CoreError::new(
516 ErrorCode::InvalidId,
517 format!("no skill id can be made from {name:?}; choose one"),
518 )
519 })?,
520 };
521 let settings = store::settings(store);
522 let enable_new = settings.new_skill_enable == Some(NewItemEnable::AllDetected);
523 let operation = Operation::new("skill.add", format!("skill: add {wanted}"));
524 let committed = store.transaction(operation, |tx| {
525 let id = if store::exists(tx, &wanted)? {
526 let free = store::free_id(tx, &wanted)?;
527 if !naming.rename_if_taken {
528 return Err(CoreError::new(
529 ErrorCode::AlreadyExists,
530 format!(
531 "skill {wanted:?} already exists; confirm to install this one as {free:?}"
532 ),
533 ));
534 }
535 free
536 } else {
537 wanted.clone()
538 };
539 let from = match &fetched.source.commit {
540 Some(commit) => format!("{}@{}", fetched.from, &commit[..commit.len().min(7)]),
541 None => fetched.from.clone(),
542 };
543 tx.set_summary(format!("skill: add {id} from {from}"));
544 tx.add_entity(format!("skill/{id}"));
545 store::stage_content(tx, &id, &fetched.files)?;
546 let mut meta = SkillMeta::new(&id);
547 meta.name = Some(name.clone());
548 meta.source = Some(fetched.source.clone());
549 if enable_new {
550 meta.enable = Some(SkillEnable {
551 clients: Some(ClientSelection::AllDetected),
552 ..SkillEnable::default()
553 });
554 }
555 store::stage_meta(tx, &meta)?;
556 Ok(id)
557 })?;
558 let id = committed.value;
559 warnings.extend(store::total_size_warning(store));
560 let report = if enable_new {
563 match sync(store, sx) {
564 Ok(report) => Some(report),
565 Err(err) => {
566 warnings.push(err);
567 None
568 }
569 }
570 } else {
571 None
572 };
573 Ok(Installed {
574 renamed_from: (id != wanted).then_some(wanted),
575 id,
576 name,
577 commit: committed.commit,
578 source_commit: fetched.source.commit.clone(),
579 report,
580 warnings,
581 scan,
582 external: None,
583 })
584}
585
586fn fetch_local(fs: &dyn Fs, path: &Path) -> Result<Fetched, CoreError> {
587 confine(fs, path)?;
588 if !path.is_absolute() {
589 return Err(
590 CoreError::new(ErrorCode::InvalidPath, "a local source must be absolute")
591 .with_path(path),
592 );
593 }
594 let file_name = path
595 .file_name()
596 .and_then(OsStr::to_str)
597 .unwrap_or("skill")
598 .to_owned();
599 let lower = file_name.to_ascii_lowercase();
600 let (files, base_name) = if fs.is_dir(path) {
601 let files = if fs.exists(&path.join(SKILL_FILE)) {
602 read_folder(fs, path)?
603 } else {
604 match find_skill_dirs(fs, path)?.as_slice() {
605 [] => return Err(missing_skill_file(path)),
606 [one] => read_folder(fs, &path.join(one))?,
607 many => return Err(several(many)),
608 }
609 };
610 (files, file_name)
611 } else if lower.ends_with(".zip") || lower.ends_with(".skill") {
612 let stem = file_name
613 .rsplit_once('.')
614 .map_or(file_name.as_str(), |(stem, _)| stem)
615 .to_owned();
616 (pick_root(read_archive(fs, path)?)?, stem)
617 } else if fs.exists(path) {
618 return Err(CoreError::new(
619 ErrorCode::InvalidValue,
620 "a local source is a folder, a .zip or a .skill file",
621 )
622 .with_path(path));
623 } else {
624 return Err(
625 CoreError::new(ErrorCode::NotFound, "the source does not exist").with_path(path),
626 );
627 };
628 Ok(Fetched {
629 files,
630 from: base_name.clone(),
631 base_name,
632 source: SkillSource {
633 kind: SkillSourceKind::Local,
634 url: None,
635 path: None,
636 git_ref: None,
637 commit: None,
638 catalog: None,
639 extra: toml::Table::new(),
640 },
641 clone: None,
642 redirect: None,
643 })
644}
645
646fn several(dirs: &[String]) -> CoreError {
647 CoreError::new(
648 ErrorCode::InvalidValue,
649 format!(
650 "the source holds several skills ({}); choose one with a path",
651 dirs.join(", ")
652 ),
653 )
654}
655
656fn find_skill_dirs(fs: &dyn Fs, dir: &Path) -> Result<Vec<String>, CoreError> {
660 let mut found = Vec::new();
661 search(fs, dir, "", 0, &mut found)?;
662 Ok(found)
663}
664
665fn search(
666 fs: &dyn Fs,
667 dir: &Path,
668 prefix: &str,
669 depth: usize,
670 found: &mut Vec<String>,
671) -> Result<(), CoreError> {
672 if depth >= SEARCH_DEPTH {
673 return Ok(());
674 }
675 let entries = fs
676 .read_dir(dir)
677 .map_err(|err| io_error("cannot list directory", dir, &err))?;
678 for path in entries {
679 let Some(name) = path.file_name().and_then(OsStr::to_str) else {
680 continue;
681 };
682 if name.starts_with('.') || entry(fs, &path)? != Entry::Dir {
685 continue;
686 }
687 let relative = if prefix.is_empty() {
688 name.to_owned()
689 } else {
690 format!("{prefix}/{name}")
691 };
692 if fs.exists(&path.join(SKILL_FILE)) {
693 found.push(relative);
694 } else {
695 search(fs, &path, &relative, depth + 1, found)?;
696 }
697 }
698 Ok(())
699}
700
701pub fn read_archive(fs: &dyn Fs, path: &Path) -> Result<SkillFiles, CoreError> {
707 let bytes = fs
708 .read(path)
709 .map_err(|err| io_error("cannot read file", path, &err))?;
710 let zip_error = |err: zip::result::ZipError| {
711 CoreError::new(ErrorCode::ParseError, format!("not a readable zip: {err}")).with_path(path)
712 };
713 let refuse = |code: ErrorCode, message: String| CoreError::new(code, message).with_path(path);
714 let mut archive = zip::ZipArchive::new(std::io::Cursor::new(bytes)).map_err(zip_error)?;
715 if archive.len() > MAX_ARCHIVE_FILES * 4 {
716 return Err(refuse(
717 ErrorCode::InvalidValue,
718 format!("the archive holds more than {MAX_ARCHIVE_FILES} files"),
719 ));
720 }
721 let mut files = SkillFiles::new();
722 let mut total = 0u64;
723 for index in 0..archive.len() {
724 let entry = archive.by_index(index).map_err(zip_error)?;
725 let raw = entry.name().map_err(zip_error)?.replace('\\', "/");
726 let parts: Vec<&str> = raw.split('/').filter(|part| !part.is_empty()).collect();
727 let escapes = raw.starts_with('/')
728 || parts.iter().any(|part| *part == ".." || part.contains(':'))
729 || entry.enclosed_name().is_none();
730 if escapes {
731 return Err(refuse(
732 ErrorCode::InvalidPath,
733 format!("archive entry {raw:?} points outside the archive (zip-slip)"),
734 ));
735 }
736 if entry.is_symlink() {
737 return Err(refuse(
738 ErrorCode::InvalidPath,
739 format!("archive entry {raw:?} is a symbolic link"),
740 ));
741 }
742 if entry.is_dir()
743 || parts.first() == Some(&"__MACOSX")
744 || parts.iter().any(|part| part.eq_ignore_ascii_case(".git"))
745 {
746 continue;
747 }
748 for part in &parts {
749 check_name(part, path)?;
750 }
751 if files.len() >= MAX_ARCHIVE_FILES {
752 return Err(refuse(
753 ErrorCode::InvalidValue,
754 format!("the archive holds more than {MAX_ARCHIVE_FILES} files"),
755 ));
756 }
757 let too_big = |raw: &str| {
758 refuse(
759 ErrorCode::InvalidValue,
760 format!(
761 "archive entry {raw:?} is larger than {} MB",
762 MAX_ARCHIVE_FILE_BYTES / (1024 * 1024)
763 ),
764 )
765 };
766 if entry.size() > MAX_ARCHIVE_FILE_BYTES {
767 return Err(too_big(&raw));
768 }
769 let mut content = Vec::new();
770 entry
771 .take(MAX_ARCHIVE_FILE_BYTES + 1)
772 .read_to_end(&mut content)
773 .map_err(|err| io_error("cannot read the archive", path, &err))?;
774 if content.len() as u64 > MAX_ARCHIVE_FILE_BYTES {
775 return Err(too_big(&raw));
776 }
777 total += content.len() as u64;
778 if total > MAX_ARCHIVE_TOTAL_BYTES {
779 return Err(refuse(
780 ErrorCode::InvalidValue,
781 format!(
782 "the archive's files are larger than {} MB together",
783 MAX_ARCHIVE_TOTAL_BYTES / (1024 * 1024)
784 ),
785 ));
786 }
787 files.insert(parts.join("/"), content);
788 }
789 Ok(files)
790}
791
792fn pick_root(files: SkillFiles) -> Result<SkillFiles, CoreError> {
795 if files.contains_key(SKILL_FILE) {
796 return Ok(files);
797 }
798 let mut roots: Vec<String> = files
799 .keys()
800 .filter_map(|path| path.strip_suffix(&format!("/{SKILL_FILE}")))
801 .map(str::to_owned)
802 .collect();
803 roots.sort_by_key(|root| root.matches('/').count());
806 let Some(first) = roots.first().cloned() else {
807 return Err(CoreError::new(
808 ErrorCode::NotFound,
809 format!("the archive has no {SKILL_FILE}"),
810 ));
811 };
812 let depth = first.matches('/').count();
813 let top: Vec<String> = roots
814 .into_iter()
815 .filter(|root| root.matches('/').count() == depth)
816 .collect();
817 if top.len() > 1 {
818 return Err(several(&top));
819 }
820 let prefix = format!("{first}/");
821 Ok(files
822 .into_iter()
823 .filter_map(|(path, bytes)| {
824 path.strip_prefix(&prefix)
825 .map(|rest| (rest.to_owned(), bytes))
826 })
827 .collect())
828}
829
830fn sources_dir(sx: &SkillsEnv<'_>) -> PathBuf {
832 sx.home.cache_dir().join(SOURCES_DIR)
833}
834
835pub(crate) fn git_path(sx: &SkillsEnv<'_>) -> Result<PathBuf, CoreError> {
838 locate(sx.env, &crate::fs::RealFs)
839 .ok_or_else(|| git_not_found("Git skill sources, MCP servers from Git, and Git catalogs"))
840}
841
842const REPOSITORY_VARS: [&str; 9] = [
845 "GIT_DIR",
846 "GIT_WORK_TREE",
847 "GIT_INDEX_FILE",
848 "GIT_COMMON_DIR",
849 "GIT_OBJECT_DIRECTORY",
850 "GIT_ALTERNATE_OBJECT_DIRECTORIES",
851 "GIT_NAMESPACE",
852 "GIT_PREFIX",
853 "GIT_TERMINAL_PROMPT",
854];
855
856const LOCALE: [(&str, &str); 2] = [("LC_ALL", "C"), ("LANGUAGE", "C")];
859
860pub(crate) fn run_git(
861 sx: &SkillsEnv<'_>,
862 git: &Path,
863 cwd: &Path,
864 args: &[&OsStr],
865) -> Result<RunOutput, CoreError> {
866 let mut env: Vec<(OsString, OsString)> = sx
867 .env
868 .vars()
869 .filter(|(name, _)| {
870 !REPOSITORY_VARS
871 .iter()
872 .chain(LOCALE.iter().map(|(var, _)| var))
873 .any(|var| name.eq_ignore_ascii_case(var))
874 })
875 .map(|(name, value)| (OsString::from(name), value.to_owned()))
876 .collect();
877 env.push(("GIT_TERMINAL_PROMPT".into(), "0".into()));
878 env.extend(
879 LOCALE
880 .iter()
881 .map(|(var, value)| (OsString::from(var), OsString::from(value))),
882 );
883 let invocation = Invocation {
884 program: git.to_path_buf(),
885 args: args.iter().map(|arg| (*arg).to_owned()).collect(),
886 env,
887 cwd: cwd.to_path_buf(),
888 };
889 sx.runner
890 .run(&invocation, &mut |_| {})
891 .map_err(|err| CoreError::new(ErrorCode::ToolNotFound, format!("cannot run git: {err}")))
892}
893
894fn git_message(output: &RunOutput) -> String {
896 output
897 .stderr
898 .lines()
899 .rev()
900 .map(str::trim)
901 .find(|line| !line.is_empty())
902 .unwrap_or("git failed")
903 .to_owned()
904}
905
906pub(crate) fn unreachable(url: &str, output: &RunOutput) -> CoreError {
909 CoreError::new(
910 ErrorCode::SourceUnreachable,
911 SourceRef::redact_userinfo(&format!(
912 "the source {url} cannot be reached: {}",
913 git_message(output)
914 )),
915 )
916}
917
918pub(crate) fn git_failed(what: &str, output: &RunOutput) -> CoreError {
919 CoreError::new(
920 ErrorCode::GitError,
921 SourceRef::redact_userinfo(&format!("{what}: {}", git_message(output))),
922 )
923}
924
925pub(crate) fn check_repo_path(path: &str) -> Result<String, CoreError> {
927 let trimmed = path.trim_matches('/');
928 let valid = !trimmed.is_empty()
929 && trimmed.split('/').all(|part| {
930 !part.is_empty() && part != "." && part != ".." && !part.contains(['\\', ':'])
931 })
932 && !trimmed.starts_with('-');
933 if valid {
934 Ok(trimmed.to_owned())
935 } else {
936 Err(CoreError::new(
937 ErrorCode::InvalidPath,
938 format!("{path:?} is not a folder path inside the repository"),
939 ))
940 }
941}
942
943pub(crate) fn check_ref(git_ref: &str) -> Result<(), CoreError> {
946 let valid = !git_ref.is_empty()
947 && !git_ref.starts_with('-')
948 && !git_ref.contains("..")
949 && git_ref
950 .bytes()
951 .all(|b| b.is_ascii_alphanumeric() || b"._-/".contains(&b));
952 if !valid {
953 return Err(CoreError::new(
954 ErrorCode::InvalidValue,
955 format!("{git_ref:?} is not a branch or tag name"),
956 ));
957 }
958 if (7..40).contains(&git_ref.len()) && git_ref.bytes().all(|b| b.is_ascii_hexdigit()) {
959 return Err(CoreError::new(
960 ErrorCode::InvalidValue,
961 format!(
962 "{git_ref:?} looks like a short commit: pin the full 40-character commit \
963 (git rev-parse {git_ref})"
964 ),
965 ));
966 }
967 Ok(())
968}
969
970pub(crate) fn check_url(url: &str) -> Result<(), CoreError> {
971 if url.is_empty() || url.starts_with('-') || url.contains(['\n', '\r']) {
972 return Err(CoreError::new(
973 ErrorCode::InvalidValue,
974 format!("{url:?} is not a git URL"),
975 ));
976 }
977 Ok(())
978}
979
980pub(crate) fn is_remote_url(url: &str) -> bool {
981 let lower = url.to_ascii_lowercase();
982 ["https://", "http://", "ssh://", "git://"]
983 .iter()
984 .any(|scheme| lower.starts_with(scheme))
985 || is_scp_like(url)
986}
987
988pub(crate) struct Cloned {
990 pub(crate) commit: String,
991 pub(crate) branch: Option<String>,
993 pub(crate) redirect: Option<String>,
996}
997
998pub(crate) fn fetch_url(url: &str) -> Result<String, CoreError> {
1002 if !is_remote_url(url) {
1003 return Ok(url.to_owned());
1004 }
1005 Ok(SourceRef::from_git_url(url)?.fetch_url(url))
1006}
1007
1008pub(crate) fn clone(
1012 sx: &SkillsEnv<'_>,
1013 git: &Path,
1014 url: &str,
1015 git_ref: Option<&str>,
1016 path: Option<&str>,
1017 dir: &Path,
1018) -> Result<Cloned, CoreError> {
1019 check_url(url)?;
1020 if let Some(git_ref) = git_ref {
1021 check_ref(git_ref)?;
1022 }
1023 let fetch = fetch_url(url)?;
1024 let parent = dir.parent().expect("a clone folder has a parent");
1025 confine(sx.fs, dir)?;
1026 sx.fs
1027 .create_dir_all(parent)
1028 .map_err(|err| io_error("cannot create directory", parent, &err))?;
1029 let mut args: Vec<&OsStr> = vec![OsStr::new("clone"), OsStr::new("--no-progress")];
1030 if path.is_some() {
1031 args.push(OsStr::new("--no-checkout"));
1032 }
1033 if is_remote_url(url) {
1034 args.extend([OsStr::new("--depth"), OsStr::new("1")]);
1035 }
1036 let commit_ref = git_ref.filter(|r| is_commit_ref(r));
1039 if let Some(branch) = git_ref.filter(|r| !is_commit_ref(r)) {
1040 args.extend([OsStr::new("--branch"), OsStr::new(branch)]);
1041 }
1042 args.extend([OsStr::new("--"), OsStr::new(&fetch), dir.as_os_str()]);
1043 let output = run_git(sx, git, parent, &args)?;
1044 if !output.success {
1045 let _ = remove_dir(sx.fs, dir);
1046 return Err(unreachable(url, &output));
1047 }
1048 let redirect = sources::detect::redirect_target(&fetch, &output.stderr);
1049 if let Some(path) = path {
1050 let pattern = format!("/{path}/");
1051 let steps: [&[&str]; 2] = [
1052 &["sparse-checkout", "set", "--no-cone", &pattern],
1053 &["checkout", "--quiet"],
1054 ];
1055 for step in steps {
1056 let args: Vec<&OsStr> = step.iter().map(OsStr::new).collect();
1057 let output = run_git(sx, git, dir, &args)?;
1058 if !output.success {
1059 let _ = remove_dir(sx.fs, dir);
1060 return Err(git_failed("cannot check out the skill folder", &output));
1061 }
1062 }
1063 }
1064 if let Some(wanted) = commit_ref {
1065 let run = |args: &[&str]| {
1066 let args: Vec<&OsStr> = args.iter().map(OsStr::new).collect();
1067 run_git(sx, git, dir, &args)
1068 };
1069 let fail = |err: CoreError| {
1070 let _ = remove_dir(sx.fs, dir);
1071 err
1072 };
1073 let mut output = run(&["checkout", "--quiet", "--detach", wanted]).map_err(fail)?;
1074 if !output.success && is_remote_url(url) {
1075 let fetched =
1076 run(&["fetch", "--quiet", "--depth", "1", &fetch, wanted]).map_err(fail)?;
1077 if fetched.success {
1078 output = run(&["checkout", "--quiet", "--detach", "FETCH_HEAD"]).map_err(fail)?;
1079 }
1080 }
1081 if !output.success {
1082 return Err(fail(CoreError::new(
1083 ErrorCode::NotFound,
1084 format!("the repository has no commit {wanted}"),
1085 )));
1086 }
1087 }
1088 let commit = rev_parse(sx, git, dir, "HEAD")?;
1089 let branch = match git_ref {
1090 Some(_) if commit_ref.is_some() => None,
1091 Some(git_ref) => Some(git_ref.to_owned()),
1092 None => {
1093 let output = run_git(
1094 sx,
1095 git,
1096 dir,
1097 &[
1098 OsStr::new("symbolic-ref"),
1099 OsStr::new("--quiet"),
1100 OsStr::new("--short"),
1101 OsStr::new("HEAD"),
1102 ],
1103 )?;
1104 output
1105 .success
1106 .then(|| output.stdout.trim().to_owned())
1107 .filter(|branch| !branch.is_empty())
1108 }
1109 };
1110 Ok(Cloned {
1111 commit,
1112 branch,
1113 redirect,
1114 })
1115}
1116
1117pub(crate) fn is_commit_ref(git_ref: &str) -> bool {
1120 git_ref.len() == 40 && git_ref.bytes().all(|b| b.is_ascii_hexdigit())
1121}
1122
1123pub(crate) fn rev_parse(
1124 sx: &SkillsEnv<'_>,
1125 git: &Path,
1126 dir: &Path,
1127 rev: &str,
1128) -> Result<String, CoreError> {
1129 let output = run_git(
1130 sx,
1131 git,
1132 dir,
1133 &[
1134 OsStr::new("rev-parse"),
1135 OsStr::new("--verify"),
1136 OsStr::new(rev),
1137 ],
1138 )?;
1139 let commit = output.stdout.trim().to_owned();
1140 if !output.success || !ids::is_commit_id(&commit) {
1141 return Err(git_failed("cannot read the source commit", &output));
1142 }
1143 Ok(commit)
1144}
1145
1146fn fetch_git(
1147 sx: &SkillsEnv<'_>,
1148 url: &str,
1149 git_ref: Option<String>,
1150 path: Option<String>,
1151 skill: Option<&str>,
1152) -> Result<Fetched, CoreError> {
1153 let git = git_path(sx)?;
1154 let path = path.as_deref().map(check_repo_path).transpose()?;
1155 let temp = sources_dir(sx).join(format!(
1156 ".tmp-{}",
1157 ids::new_ulid(sx.env.now())?.to_ascii_lowercase()
1158 ));
1159 let Cloned {
1160 commit,
1161 branch,
1162 redirect,
1163 } = clone(sx, &git, url, git_ref.as_deref(), path.as_deref(), &temp)?;
1164 let read = || -> Result<(SkillFiles, Option<String>), CoreError> {
1165 match &path {
1166 Some(path) => {
1167 let dir = join_rel(&temp, path);
1168 if !sx.fs.is_dir(&dir) {
1169 return Err(CoreError::new(
1170 ErrorCode::NotFound,
1171 format!("the repository has no folder {path:?}"),
1172 ));
1173 }
1174 Ok((read_in_clone(sx.fs, &temp, &dir)?, Some(path.clone())))
1175 }
1176 None if sx.fs.exists(&temp.join(SKILL_FILE)) => {
1177 Ok((read_in_clone(sx.fs, &temp, &temp)?, None))
1178 }
1179 None => {
1180 let found = find_skill_dirs(sx.fs, &temp)?;
1181 let named = |dir: &&String| {
1182 skill.is_some_and(|skill| {
1183 dir.rsplit('/')
1184 .next()
1185 .is_some_and(|name| name.eq_ignore_ascii_case(skill))
1186 })
1187 };
1188 let picked: Vec<&String> = found.iter().filter(named).collect();
1189 let chosen = match picked.as_slice() {
1190 [one] => Some(*one),
1191 _ if found.len() == 1 => found.first(),
1192 _ => None,
1193 };
1194 match chosen {
1195 Some(one) => Ok((
1196 read_in_clone(sx.fs, &temp, &join_rel(&temp, one))?,
1197 Some(one.clone()),
1198 )),
1199 None if found.is_empty() => Err(missing_skill_file(&temp)),
1200 None => Err(several(&found)),
1201 }
1202 }
1203 }
1204 };
1205 let (files, path) = match read() {
1206 Ok(read) => read,
1207 Err(err) => {
1208 let _ = remove_dir(sx.fs, &temp);
1209 return Err(err);
1210 }
1211 };
1212 let repo_name = url
1213 .trim_end_matches(['/', '\\'])
1214 .rsplit(['/', '\\', ':'])
1215 .next()
1216 .unwrap_or("skill")
1217 .trim_end_matches(".git")
1218 .to_owned();
1219 let base_name = path
1220 .as_deref()
1221 .and_then(|path| path.rsplit('/').next())
1222 .map_or(repo_name, str::to_owned);
1223 Ok(Fetched {
1224 files,
1225 base_name,
1226 from: url.to_owned(),
1227 source: SkillSource {
1228 kind: SkillSourceKind::Git,
1229 url: Some(url.to_owned()),
1230 path,
1231 git_ref: branch.or_else(|| git_ref.filter(|r| is_commit_ref(r))),
1233 commit: Some(commit),
1234 catalog: None,
1235 extra: toml::Table::new(),
1236 },
1237 clone: Some(temp),
1238 redirect,
1239 })
1240}
1241
1242pub(crate) fn join_rel(base: &Path, relative: &str) -> PathBuf {
1243 relative
1244 .split('/')
1245 .fold(base.to_path_buf(), |path, part| path.join(part))
1246}
1247
1248fn keep_clone(sx: &SkillsEnv<'_>, clone: &Path, id: &str) -> Result<(), CoreError> {
1250 let target = sources_dir(sx).join(id);
1251 confine(sx.fs, clone)?;
1252 confine(sx.fs, &target)?;
1253 if sx.fs.exists(&target) {
1254 remove_dir(sx.fs, &target)?;
1255 }
1256 std::fs::rename(clone, &target).map_err(|err| io_error("cannot move the clone", &target, &err))
1257}
1258
1259pub(crate) fn remove_dir(fs: &dyn Fs, dir: &Path) -> Result<(), CoreError> {
1260 if fs.exists(dir) {
1261 fs.remove_dir_all(dir)
1262 .map_err(|err| io_error("cannot remove folder", dir, &err))?;
1263 }
1264 Ok(())
1265}
1266
1267pub fn forget_source(sx: &SkillsEnv<'_>, id: &str) -> Result<(), CoreError> {
1269 ids::check(IdKind::Skill, id)?;
1270 remove_dir(sx.fs, &sources_dir(sx).join(id))
1271}
1272
1273pub fn sweep_temp_clones(sx: &SkillsEnv<'_>, older_than: std::time::Duration) -> usize {
1279 let dir = sources_dir(sx);
1280 let Ok(entries) = std::fs::read_dir(&dir) else {
1281 return 0;
1282 };
1283 let now = sx.env.now();
1284 entries
1285 .flatten()
1286 .filter(|entry| entry.file_name().to_string_lossy().starts_with(".tmp-"))
1287 .filter(|entry| {
1288 entry
1289 .metadata()
1290 .and_then(|meta| meta.modified())
1291 .is_ok_and(|modified| {
1292 now.duration_since(modified).unwrap_or_default() >= older_than
1293 })
1294 })
1295 .filter(|entry| std::fs::remove_dir_all(entry.path()).is_ok())
1296 .count()
1297}
1298
1299#[derive(Debug, Clone, PartialEq, Eq)]
1301pub struct FileChange {
1302 pub path: String,
1303 pub kind: ChangeKind,
1304 pub script: bool,
1308}
1309
1310const SCRIPT_EXTENSIONS: [&str; 20] = [
1312 "sh", "bash", "zsh", "fish", "ps1", "psm1", "bat", "cmd", "py", "js", "mjs", "cjs", "ts", "rb",
1313 "pl", "php", "exe", "dll", "so", "dylib",
1314];
1315
1316pub fn looks_executable(path: &str, bytes: &[u8]) -> bool {
1318 let name = path.rsplit('/').next().unwrap_or(path);
1319 let by_extension = name.rsplit_once('.').is_some_and(|(stem, extension)| {
1320 !stem.is_empty() && SCRIPT_EXTENSIONS.contains(&extension.to_ascii_lowercase().as_str())
1321 });
1322 by_extension || bytes.starts_with(b"#!")
1323}
1324
1325#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1326pub enum ChangeKind {
1327 Added,
1328 Modified,
1329 Removed,
1330}
1331
1332impl ChangeKind {
1333 pub const fn as_str(self) -> &'static str {
1334 match self {
1335 ChangeKind::Added => "added",
1336 ChangeKind::Modified => "modified",
1337 ChangeKind::Removed => "removed",
1338 }
1339 }
1340}
1341
1342#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1344pub enum UpdateStatus {
1345 UpToDate,
1346 Available,
1347 NotTracked,
1349 Unreachable,
1352 Blocked,
1354}
1355
1356impl UpdateStatus {
1357 pub const fn as_str(self) -> &'static str {
1358 match self {
1359 UpdateStatus::UpToDate => "up_to_date",
1360 UpdateStatus::Available => "available",
1361 UpdateStatus::NotTracked => "not_tracked",
1362 UpdateStatus::Unreachable => "source_unreachable",
1363 UpdateStatus::Blocked => "source_blocked",
1364 }
1365 }
1366}
1367
1368#[derive(Debug, Clone)]
1370pub struct UpdateCheck {
1371 pub id: String,
1372 pub status: UpdateStatus,
1373 pub current: Option<String>,
1375 pub latest: Option<String>,
1377 pub changes: Vec<FileChange>,
1380 pub error: Option<CoreError>,
1381 pub scan: Option<ScanReport>,
1384 pub trust: Option<TrustCheck>,
1387 pub source_change: Option<SourceChange>,
1390 pub moved_trust: Option<TrustCheck>,
1394}
1395
1396struct Latest {
1398 commit: String,
1399 files: SkillFiles,
1400 change: Option<SourceChange>,
1401 moved_to: Option<SourceRef>,
1403}
1404
1405const MOVED_MARKER: &str = "surjection-moved-to";
1409
1410fn moved_marker(sx: &SkillsEnv<'_>, dir: &Path, url: &str) -> Option<SourceRef> {
1412 let requested = SourceRef::from_git_url(url).ok()?;
1413 let target = sx
1414 .fs
1415 .read_to_string(&dir.join(".git").join(MOVED_MARKER))
1416 .ok()?;
1417 sources::detect::target_of(&requested, target.trim())
1418}
1419
1420fn set_moved_marker(
1421 sx: &SkillsEnv<'_>,
1422 dir: &Path,
1423 target: Option<&SourceRef>,
1424) -> Result<(), CoreError> {
1425 let marker = dir.join(".git").join(MOVED_MARKER);
1426 let result = match target {
1427 Some(target) => sx.fs.write(&marker, target.url().as_bytes()),
1428 None if sx.fs.exists(&marker) => sx.fs.remove_file(&marker),
1429 None => Ok(()),
1430 };
1431 result.map_err(|err| io_error("cannot write", &marker, &err))
1432}
1433
1434fn latest(sx: &SkillsEnv<'_>, id: &str, source: &SkillSource) -> Result<Latest, CoreError> {
1440 let url = source
1441 .url
1442 .as_deref()
1443 .ok_or_else(|| CoreError::new(ErrorCode::MissingField, "the git source has no url"))?;
1444 let git = git_path(sx)?;
1445 let path = source.path.as_deref().map(check_repo_path).transpose()?;
1446 let dir = sources_dir(sx).join(id);
1447 let fetch = fetch_url(url)?;
1448 let (commit, redirect) = if sx.fs.exists(&dir.join(".git")) {
1449 let mut args: Vec<&OsStr> = vec![OsStr::new("fetch"), OsStr::new("--no-progress")];
1451 if is_remote_url(url) {
1452 args.extend([OsStr::new("--depth"), OsStr::new("1")]);
1453 }
1454 args.extend([OsStr::new("--"), OsStr::new(&fetch)]);
1455 if let Some(git_ref) = &source.git_ref {
1456 check_ref(git_ref)?;
1457 args.push(OsStr::new(git_ref));
1458 }
1459 let output = run_git(sx, &git, &dir, &args)?;
1460 if !output.success {
1461 return Err(unreachable(url, &output));
1462 }
1463 let redirect = sources::detect::redirect_target(&fetch, &output.stderr);
1464 let commit = rev_parse(sx, &git, &dir, "FETCH_HEAD")?;
1465 let output = run_git(
1466 sx,
1467 &git,
1468 &dir,
1469 &[
1470 OsStr::new("reset"),
1471 OsStr::new("--hard"),
1472 OsStr::new("--quiet"),
1473 OsStr::new(&commit),
1474 ],
1475 )?;
1476 if !output.success {
1477 return Err(git_failed(
1478 "cannot check out the new source commit",
1479 &output,
1480 ));
1481 }
1482 (commit, redirect)
1483 } else {
1484 remove_dir(sx.fs, &dir)?;
1485 let cloned = clone(
1486 sx,
1487 &git,
1488 url,
1489 source.git_ref.as_deref(),
1490 path.as_deref(),
1491 &dir,
1492 )?;
1493 (cloned.commit, cloned.redirect)
1494 };
1495 let moved_to = SourceRef::from_git_url(url)
1496 .ok()
1497 .and_then(|requested| sources::detect::target_of(&requested, redirect.as_deref()?));
1498 set_moved_marker(sx, &dir, moved_to.as_ref())?;
1499 let change = match &moved_to {
1500 Some(target) => Some(sources::detect::moved_to(target)),
1501 None => match &source.commit {
1502 Some(old) => {
1503 let in_clone = |args: &[&OsStr]| run_git(sx, &git, &dir, args);
1504 sources::detect::history_rewritten(
1505 &in_clone,
1506 &fetch,
1507 source.git_ref.as_deref(),
1508 old,
1509 &commit,
1510 )?
1511 .then_some(SourceChange {
1512 kind: SourceChangeKind::HistoryRewritten,
1513 detail: None,
1514 })
1515 }
1516 None => None,
1517 },
1518 };
1519 let skill_dir = match &path {
1520 Some(path) => join_rel(&dir, path),
1521 None => dir.clone(),
1522 };
1523 if !sx.fs.exists(&skill_dir.join(SKILL_FILE)) {
1524 return Err(CoreError::new(
1525 ErrorCode::SourceUnreachable,
1526 SourceRef::redact_userinfo(&format!("the source {url} no longer holds the skill")),
1527 ));
1528 }
1529 Ok(Latest {
1530 commit,
1531 files: read_in_clone(sx.fs, &dir, &skill_dir)?,
1532 change,
1533 moved_to,
1534 })
1535}
1536
1537fn read_in_clone(fs: &dyn Fs, clone: &Path, dir: &Path) -> Result<SkillFiles, CoreError> {
1542 let resolve = |path: &Path| {
1543 fs.canonicalize(path)
1544 .map_err(|err| io_error("cannot resolve folder", path, &err))
1545 };
1546 if !resolve(dir)?.starts_with(resolve(clone)?) {
1547 return Err(CoreError::new(
1548 ErrorCode::InvalidPath,
1549 "the skill folder is a link that points outside the repository",
1550 )
1551 .with_path(dir));
1552 }
1553 read_folder(fs, dir)
1554}
1555
1556fn changes(old: &SkillFiles, new: &SkillFiles) -> Vec<FileChange> {
1557 let mut out = Vec::new();
1558 for (path, bytes) in new {
1559 let kind = match old.get(path) {
1560 None => ChangeKind::Added,
1561 Some(before) if before != bytes => ChangeKind::Modified,
1562 Some(_) => continue,
1563 };
1564 out.push(FileChange {
1565 path: path.clone(),
1566 kind,
1567 script: looks_executable(path, bytes),
1568 });
1569 }
1570 for path in old.keys() {
1571 if !new.contains_key(path) {
1572 out.push(FileChange {
1573 path: path.clone(),
1574 kind: ChangeKind::Removed,
1575 script: false,
1576 });
1577 }
1578 }
1579 out.sort_by(|a, b| a.path.cmp(&b.path));
1580 out
1581}
1582
1583fn source_ref(source: &SkillSource) -> Option<SourceRef> {
1586 source
1587 .url
1588 .as_deref()
1589 .and_then(|url| SourceRef::from_git_url(url).ok())
1590}
1591
1592fn git_source(store: &Store<'_>, id: &str) -> Result<Option<SkillSource>, CoreError> {
1593 let meta = store::read_meta(store, id)?;
1594 if meta.is_none() && !store.fs().is_dir(&content_dir(store, id)?) {
1595 return Err(not_found(id));
1596 }
1597 Ok(meta
1598 .and_then(|meta| meta.source)
1599 .filter(|source| source.kind == SkillSourceKind::Git && source.url.is_some()))
1600}
1601
1602pub fn check_update(
1608 store: &Store<'_>,
1609 sx: &SkillsEnv<'_>,
1610 id: &str,
1611) -> Result<UpdateCheck, CoreError> {
1612 let Some(source) = git_source(store, id)? else {
1613 return Ok(UpdateCheck {
1614 id: id.to_owned(),
1615 status: UpdateStatus::NotTracked,
1616 current: None,
1617 latest: None,
1618 changes: Vec::new(),
1619 error: None,
1620 scan: None,
1621 trust: None,
1622 source_change: None,
1623 moved_trust: None,
1624 });
1625 };
1626 let current = source.commit.clone();
1627 let gated = source_ref(&source);
1628 let not_fetched = |status, err: CoreError| -> Result<UpdateCheck, CoreError> {
1629 Ok(UpdateCheck {
1630 id: id.to_owned(),
1631 status,
1632 current: current.clone(),
1633 latest: None,
1634 changes: Vec::new(),
1635 error: Some(err),
1636 scan: None,
1637 trust: gated
1638 .as_ref()
1639 .map(|source| sources::check(store, source))
1640 .transpose()?,
1641 source_change: None,
1642 moved_trust: None,
1643 })
1644 };
1645 if let Some(gated) = &gated
1646 && let Err(err) = sources::refuse_blocked(store, gated)
1647 {
1648 return not_fetched(UpdateStatus::Blocked, err);
1649 }
1650 let Latest {
1651 commit,
1652 files,
1653 change,
1654 moved_to,
1655 } = match latest(sx, id, &source) {
1656 Ok(latest) => latest,
1657 Err(err) if err.code() == ErrorCode::SourceUnreachable => {
1658 return not_fetched(UpdateStatus::Unreachable, err);
1659 }
1660 Err(err) => return Err(err),
1661 };
1662 if let (Some(gated), Some(change)) = (&gated, &change) {
1663 sources::lapse(store, gated, change)?;
1664 }
1665 let trust = gated
1666 .as_ref()
1667 .map(|source| sources::check(store, source))
1668 .transpose()?;
1669 let moved_trust = moved_to
1670 .as_ref()
1671 .map(|target| sources::check(store, target))
1672 .transpose()?;
1673 let stored = store::read_content(store, id)?;
1674 let changes = changes(&stored, &files);
1675 let status = if changes.is_empty() && current.as_deref() == Some(commit.as_str()) {
1676 UpdateStatus::UpToDate
1677 } else {
1678 UpdateStatus::Available
1679 };
1680 let scan = (status == UpdateStatus::Available)
1681 .then(|| Scanner::new(sx.fs, sx.home).scan_files(&files));
1682 Ok(UpdateCheck {
1683 id: id.to_owned(),
1684 status,
1685 current,
1686 latest: Some(commit),
1687 changes,
1688 error: None,
1689 scan,
1690 trust,
1691 source_change: change,
1692 moved_trust,
1693 })
1694}
1695
1696pub fn cached_latest(
1701 store: &Store<'_>,
1702 sx: &SkillsEnv<'_>,
1703 id: &str,
1704) -> Result<Option<SkillFiles>, CoreError> {
1705 let Some(source) = git_source(store, id)? else {
1706 return Ok(None);
1707 };
1708 let dir = sources_dir(sx).join(id);
1709 if !sx.fs.is_dir(&dir) {
1710 return Ok(None);
1711 }
1712 let path = source.path.as_deref().map(check_repo_path).transpose()?;
1713 let skill_dir = match &path {
1714 Some(path) => join_rel(&dir, path),
1715 None => dir.clone(),
1716 };
1717 if !sx.fs.exists(&skill_dir.join(SKILL_FILE)) {
1718 return Ok(None);
1719 }
1720 read_in_clone(sx.fs, &dir, &skill_dir).map(Some)
1721}
1722
1723#[derive(Debug, Clone)]
1725pub struct Updated {
1726 pub id: String,
1727 pub from: Option<String>,
1728 pub to: String,
1729 pub changes: Vec<FileChange>,
1730 pub commit: Option<CommitId>,
1732 pub report: SyncReport,
1734 pub scan: ScanReport,
1736 pub external: Option<ExternalReport>,
1738}
1739
1740pub fn update(
1747 store: &Store<'_>,
1748 sx: &SkillsEnv<'_>,
1749 id: &str,
1750 decisions: &Decisions,
1751) -> Result<Updated, CoreError> {
1752 let Some(source) = git_source(store, id)? else {
1753 return Err(CoreError::new(
1754 ErrorCode::InvalidValue,
1755 format!("skill {id:?} has no git source to update from; add it again to replace it"),
1756 ));
1757 };
1758 if let Some(gated) = source_ref(&source) {
1759 sources::refuse_blocked(store, &gated)?;
1760 }
1761 let Latest {
1762 commit,
1763 files,
1764 change,
1765 moved_to,
1766 } = latest(sx, id, &source)?;
1767 if let (Some(gated), Some(change)) = (source_ref(&source), &change) {
1768 sources::lapse(store, &gated, change)?;
1769 }
1770 commit_update(store, sx, id, source, commit, files, moved_to, decisions)
1771}
1772
1773pub fn update_reviewed(
1779 store: &Store<'_>,
1780 sx: &SkillsEnv<'_>,
1781 id: &str,
1782 expected: &str,
1783 decisions: &Decisions,
1784) -> Result<Updated, CoreError> {
1785 let Some(source) = git_source(store, id)? else {
1786 return Err(CoreError::new(
1787 ErrorCode::InvalidValue,
1788 format!("skill {id:?} has no git source to update from; add it again to replace it"),
1789 ));
1790 };
1791 let changed = || {
1792 CoreError::new(
1793 ErrorCode::EntryChanged,
1794 format!("the source of skill {id:?} changed since the check; check for updates again"),
1795 )
1796 };
1797 let dir = sources_dir(sx).join(id);
1798 if !sx.fs.exists(&dir.join(".git")) {
1799 return Err(changed());
1800 }
1801 let git = git_path(sx)?;
1802 let head = rev_parse(sx, &git, &dir, "HEAD")?;
1803 if !head.eq_ignore_ascii_case(expected.trim()) {
1804 return Err(changed());
1805 }
1806 let files = cached_latest(store, sx, id)?.ok_or_else(changed)?;
1807 let moved_to = source
1808 .url
1809 .as_deref()
1810 .and_then(|url| moved_marker(sx, &dir, url));
1811 commit_update(store, sx, id, source, head, files, moved_to, decisions)
1812}
1813
1814#[allow(clippy::too_many_arguments)]
1820fn commit_update(
1821 store: &Store<'_>,
1822 sx: &SkillsEnv<'_>,
1823 id: &str,
1824 source: SkillSource,
1825 commit: String,
1826 files: SkillFiles,
1827 moved_to: Option<SourceRef>,
1828 decisions: &Decisions,
1829) -> Result<Updated, CoreError> {
1830 if let Some(url) = source.url.as_deref() {
1832 let requested = SourceRef::from_git_url(url)?;
1833 admit_with_move(store, Some(&requested), moved_to.as_ref(), decisions)?;
1834 }
1835 let scan = Scanner::new(sx.fs, sx.home).scan_files(&files);
1836 scan::gate(&scan, decisions.allow_dangerous)?;
1837 if let Some(report) = &decisions.external {
1838 if report.content_hash.as_deref() != Some(content_hash(&files).as_str()) {
1839 return Err(CoreError::new(
1840 ErrorCode::EntryChanged,
1841 format!(
1842 "the source of skill {id:?} changed since the external scan; check for \
1843 updates again"
1844 ),
1845 ));
1846 }
1847 external::gate(report, decisions.allow_dangerous)?;
1848 }
1849 let stored = store::read_content(store, id)?;
1850 let changes = changes(&stored, &files);
1851 let short = &commit[..commit.len().min(7)];
1852 let operation = Operation::new("skill.update", format!("skill: update {id} to {short}"))
1853 .entity(format!("skill/{id}"));
1854 let committed = store.transaction(operation, |tx| {
1855 store::stage_content(tx, id, &files)?;
1856 let mut meta = store::read_meta(tx, id)?.unwrap_or_else(|| SkillMeta::new(id));
1857 if let Some(source) = meta.source.as_mut() {
1858 source.commit = Some(commit.clone());
1859 if let Some(target) = &moved_to {
1860 source.url = Some(target.url().to_owned());
1861 }
1862 }
1863 let skill_md = files
1864 .get(SKILL_FILE)
1865 .map(|bytes| String::from_utf8_lossy(bytes).into_owned());
1866 if let Some(name) = skill_md
1867 .and_then(|text| frontmatter::parse(&text).ok().flatten())
1868 .and_then(|fm| fm.name().map(str::to_owned))
1869 {
1870 meta.name = Some(name);
1871 }
1872 store::stage_meta(tx, &meta)
1873 })?;
1874 store::prune_empty_dirs(store, id)?;
1875 let report = sync(store, sx)?;
1876 Ok(Updated {
1877 id: id.to_owned(),
1878 from: source.commit,
1879 to: commit,
1880 changes,
1881 commit: committed.commit,
1882 report,
1883 scan,
1884 external: decisions.external.clone(),
1885 })
1886}