Skip to main content

surjection_core/skills/
install.rs

1//! Installs and updates (SPEC 12.4).
2//!
3//! - Git: the system git clones into `cache/skill-sources/<id>` (sparse
4//!   checkout of the skill folder when a path is known, from a
5//!   `/tree/<ref>/<path>` URL or `--path`), the skill folder is copied into
6//!   the store and committed as `skill: add <id> from <url>@<sha>`.
7//! - Local: a folder, or a `.zip`/`.skill` archive, with zip-slip,
8//!   symbolic link and size checks (SPEC 17).
9//! - Update: `git fetch` in the cache clone; an unreachable source is
10//!   `source_unreachable` and the store copy stays as it is.
11
12use 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
37/// Cache folder of git sources, below `<SURJECTION_HOME>/cache`.
38pub const SOURCES_DIR: &str = "skill-sources";
39/// Deepest folder searched for `SKILL.md` in a repository without a path.
40const SEARCH_DEPTH: usize = 4;
41
42/// Where a skill comes from.
43#[derive(Debug, Clone, PartialEq, Eq)]
44pub enum Source {
45    /// A git repository; `path` is the skill folder inside it.
46    Git {
47        url: String,
48        git_ref: Option<String>,
49        path: Option<String>,
50    },
51    /// A folder, or a `.zip`/`.skill` archive (absolute).
52    Local(PathBuf),
53}
54
55impl Source {
56    /// Reads a source argument: a URL (`https://`, `http://`, `ssh://`,
57    /// `git://`, `file://`, `user@host:path`) is git, and a GitHub
58    /// `/tree/<ref>/<path>` or `/blob/<ref>/<path>/SKILL.md` URL carries
59    /// the ref and the path; a bare git repository folder is git too;
60    /// anything else is a local folder or archive (made absolute by the
61    /// caller).
62    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
88/// `user@host:path` (not a Windows drive path).
89fn 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/// The id a new store skill gets.
124#[derive(Debug, Clone, Default)]
125pub struct Naming {
126    /// The id to use instead of one from the skill's name.
127    pub id: Option<String>,
128    /// When the id is taken: install as `<id>-2` (the user confirmed),
129    /// instead of failing with `already_exists`.
130    pub rename_if_taken: bool,
131}
132
133/// The user's choices for an install or update (SPEC 12.4, 17): what the
134/// gates before the store commit may let through. The default lets
135/// nothing through that needs a decision.
136#[derive(Debug, Clone, Default)]
137pub struct Decisions {
138    /// Install or update even when the built-in scan's verdict is
139    /// `dangerous` ("Install anyway", `--allow-dangerous`); without it,
140    /// such content is refused with `scan_blocked`.
141    pub allow_dangerous: bool,
142    /// The user's answer to the source trust prompt (#24) for the source
143    /// asked for; `None` lets only a trusted git source through
144    /// (`source_trust_required` otherwise). A block is never let through
145    /// (`source_blocked`).
146    pub trust: Option<TrustGrant>,
147    /// The user's separate answer for the repository the host redirected
148    /// to, when it moved to another key ([`Prepared::moved_to`],
149    /// [`UpdateCheck::moved_trust`]): [`Decisions::trust`] never carries
150    /// over to a location the user did not see. `None` lets only a
151    /// trusted target through.
152    pub moved_trust: Option<TrustGrant>,
153    /// Where those answers were given; recorded with "always trust".
154    pub via: TrustVia,
155    /// The external scanner's report (#27) on the content an update
156    /// writes, from the update review: a `dangerous` verdict needs
157    /// [`Decisions::allow_dangerous`] like a built-in one. It must be of
158    /// exactly the content written (`entry_changed` otherwise). Installs
159    /// carry theirs on the [`Prepared`] ([`Prepared::set_external`]).
160    pub external: Option<ExternalReport>,
161}
162
163/// An install.
164#[derive(Debug, Clone)]
165pub struct InstallRequest {
166    pub source: Source,
167    /// The skill folder inside a git source (overrides the URL's).
168    pub path: Option<String>,
169    /// Branch, tag or commit of a git source (overrides the URL's); a
170    /// commit pins the skill.
171    pub git_ref: Option<String>,
172    /// The skill to pick when a git source without a path holds several:
173    /// the folder with this name (a skills.sh link names the skill, not
174    /// its folder).
175    pub skill: Option<String>,
176    /// The catalog entry this install comes from, `<catalog>/<entry id>`
177    /// (#26): recorded as `source.catalog`.
178    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/// What an install did.
198#[derive(Debug, Clone)]
199pub struct Installed {
200    pub id: String,
201    /// Frontmatter `name`, else the folder name.
202    pub name: String,
203    pub commit: Option<CommitId>,
204    /// The git commit the content came from.
205    pub source_commit: Option<String>,
206    /// The id the name asked for, when it was taken and `-N` was used.
207    pub renamed_from: Option<String>,
208    /// Links made for a new skill enabled by `new_skill_enable`.
209    pub report: Option<SyncReport>,
210    pub warnings: Vec<CoreError>,
211    /// The built-in scan of the installed content (SPEC 17).
212    pub scan: ScanReport,
213    /// The external scanner's report the install was gated on (#27).
214    pub external: Option<ExternalReport>,
215}
216
217/// The content to commit and where it came from.
218#[derive(Debug)]
219struct Fetched {
220    files: SkillFiles,
221    /// Folder or archive name, repository name: the name when the
222    /// frontmatter has none, and the commit message's `from`.
223    base_name: String,
224    from: String,
225    source: SkillSource,
226    /// The clone to keep as `cache/skill-sources/<id>`.
227    clone: Option<PathBuf>,
228    /// Where the host redirected a git URL (a renamed or transferred
229    /// repository).
230    redirect: Option<String>,
231}
232
233/// A fetched and scanned source waiting for the user's decisions
234/// ([`prepare`], then [`install_prepared`]). A git source's temporary
235/// clone is removed when this is dropped without being installed.
236#[derive(Debug)]
237pub struct Prepared {
238    fetched: Fetched,
239    name: String,
240    scan: ScanReport,
241    /// The external scanner's report on the same files (#27).
242    external: Option<ExternalReport>,
243    /// Installed: another [`install_prepared`] is refused.
244    spent: bool,
245    /// The source the user asked for, which the trust gate admits (git
246    /// sources).
247    trust_source: Option<SourceRef>,
248    /// Where the host redirected it, when that is another repository: the
249    /// gate admits it too, with its own answer.
250    moved_to: Option<SourceRef>,
251    /// The host moved the repository the URL names.
252    source_change: Option<SourceChange>,
253}
254
255impl Prepared {
256    /// Frontmatter `name`, else the folder, archive or repository name.
257    pub fn name(&self) -> &str {
258        &self.name
259    }
260
261    /// The files that would be installed, by relative path.
262    pub fn files(&self) -> &SkillFiles {
263        &self.fetched.files
264    }
265
266    /// Where the content comes from (the git commit for a git source).
267    pub fn source(&self) -> &SkillSource {
268        &self.fetched.source
269    }
270
271    /// The built-in scan of [`Prepared::files`].
272    pub fn scan(&self) -> &ScanReport {
273        &self.scan
274    }
275
276    /// Attaches the external scanner's report on [`Prepared::files`] (#27):
277    /// [`install_prepared`] then gates on it too.
278    pub fn set_external(&mut self, report: Option<ExternalReport>) {
279        self.external = report;
280    }
281
282    /// The attached external report.
283    pub fn external(&self) -> Option<&ExternalReport> {
284        self.external.as_ref()
285    }
286
287    /// The source the trust gate admits (#24): a git source's repository
288    /// as the user named it; `None` for a local folder or archive (picked
289    /// on this machine, not gated). A redirect never replaces it.
290    pub fn trust_source(&self) -> Option<&SourceRef> {
291        self.trust_source.as_ref()
292    }
293
294    /// The repository the host redirected the URL to, when it has another
295    /// key: the gate admits it too, on [`Decisions::moved_trust`].
296    pub fn moved_to(&self) -> Option<&SourceRef> {
297        self.moved_to.as_ref()
298    }
299
300    /// The repository the URL names moved ([`SourceChangeKind::Moved`]).
301    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            // The clone lives below `SURJECTION_HOME/cache`; a leftover is
310            // re-creatable and replaced by the next install of that id.
311            let _ = std::fs::remove_dir_all(clone);
312        }
313    }
314}
315
316/// Fetches a source (a git source into a temporary clone) and scans it,
317/// without touching the store: what the install review shows. Callers
318/// refuse a blocked git source first ([`sources::refuse_blocked`]), so a
319/// blocked source is never contacted.
320pub 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
363/// Installs prepared content into the store (one commit) when the
364/// decisions let it through: a git source must be trusted, or
365/// [`Decisions::trust`] carries the user's answer (`source_trust_required`
366/// or `source_blocked` otherwise, #24), and so must the repository it
367/// moved to, on [`Decisions::moved_trust`]; then a `dangerous` scan
368/// verdict needs [`Decisions::allow_dangerous`] (`scan_blocked`
369/// otherwise). On an error `prepared` stays usable, so the review can ask
370/// the user and try again with other decisions; once installed it is
371/// spent (`invalid_value` on another try).
372pub 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    // Committed: the review is spent even if what follows fails, so a
399    // retry never installs a second copy.
400    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
410/// The trust gate of a git source and the repository it moved to: both
411/// are checked before either "always" is recorded.
412fn 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
432/// Installs a skill into the store (one commit): [`prepare`], then
433/// [`install_prepared`] with the request's decisions. A git source the
434/// gate would refuse is refused before anything is fetched; a repository
435/// it moved to needs [`Decisions::moved_trust`] or its own trust.
436pub 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
458/// Installs already-read content (agents CLI vendoring, tool folder
459/// imports). `source.kind` says where it came from. The content is
460/// already on this machine, in a folder a client reads, so the scan is
461/// reported and never blocks.
462pub(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    // The store commit is done: a sync that fails now (lock timeout,
561    // ledger I/O) is a warning, and the next apply or sync makes the links.
562    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
656/// Folders below `dir` (relative, `/`-separated) holding a `SKILL.md`,
657/// up to [`SEARCH_DEPTH`] levels, without descending into a skill or a
658/// `.git` folder.
659fn 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        // Linked folders are never candidates: a repository can link to
683        // any folder on this machine (SPEC 17).
684        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
701/// The files of an archive, checked per SPEC 17: no entry outside the
702/// archive root (zip-slip: absolute names, drive names, `..`), no
703/// symbolic links, at most [`MAX_ARCHIVE_FILES`] files of at most
704/// [`MAX_ARCHIVE_FILE_BYTES`] each and [`MAX_ARCHIVE_TOTAL_BYTES`] in all.
705/// Nested `.git` folders and `__MACOSX` are left out.
706pub 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
792/// The files of the one skill in `files`: the whole map when `SKILL.md` is
793/// at its root, else the folder holding the only `SKILL.md`.
794fn 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    // A skill's own subfolders may hold other SKILL.md files: keep the
804    // shallowest.
805    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
830/// `<SURJECTION_HOME>/cache/skill-sources`.
831fn sources_dir(sx: &SkillsEnv<'_>) -> PathBuf {
832    sx.home.cache_dir().join(SOURCES_DIR)
833}
834
835/// Git on `PATH`. Program lookup reads the real file system, as the
836/// programs live outside any confined view (a test's temp root).
837pub(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
842/// Git's repository-local variables, dropped so an inherited `GIT_DIR`
843/// never points a clone or fetch elsewhere.
844const 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
856/// Git's messages in English whatever the user's locale: the redirect
857/// warning is read from them (#24).
858const 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
894/// The last non-empty line git printed to stderr.
895fn 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
906/// `source_unreachable`, without the credentials a URL (or git's message
907/// about it) can carry.
908pub(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
925/// A relative `/`-separated path inside a repository.
926pub(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
943/// A branch, tag or full commit. A short commit (7 to 39 hex characters)
944/// is refused: a shallow clone cannot fetch one by an abbreviated name.
945pub(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
988/// A fresh clone.
989pub(crate) struct Cloned {
990    pub(crate) commit: String,
991    /// The branch followed.
992    pub(crate) branch: Option<String>,
993    /// Where the host redirected the URL (a renamed or transferred
994    /// repository).
995    pub(crate) redirect: Option<String>,
996}
997
998/// The URL git contacts for `url`: a remote URL rebuilt from its parsed
999/// parts ([`SourceRef::fetch_url`]), so what git contacts is exactly what
1000/// the trust gate checked; a local path or `file://` URL as it is.
1001pub(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
1008/// Clones `url` (from its [`fetch_url`]) into `dir` (which must not
1009/// exist): sparse to `path` when given. Without `--quiet`, so git reports
1010/// an HTTP redirect.
1011pub(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    // `--branch` takes a branch or tag; a commit is checked out after the
1037    // clone (fetched when the shallow clone does not hold it).
1038    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
1117/// A ref that names a commit (40 hex characters; [`check_ref`] refuses a
1118/// short one).
1119pub(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            // A commit pins the skill: its updates fetch that commit.
1232            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
1248/// Moves a fresh clone to `cache/skill-sources/<id>`, replacing an old one.
1249fn 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
1267/// Removes the cache clone of `id`, if any.
1268pub 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
1273/// Removes temporary clones (`cache/skill-sources/.tmp-*`) not changed
1274/// for `older_than`: left by an install review the app never finished (it
1275/// ends without dropping its state) or by a process that crashed. A clone
1276/// still in use by another process is younger than that. Returns how many
1277/// were removed; failures are skipped (the next sweep tries again).
1278pub 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/// One file that differs between the store copy and the source.
1300#[derive(Debug, Clone, PartialEq, Eq)]
1301pub struct FileChange {
1302    pub path: String,
1303    pub kind: ChangeKind,
1304    /// An added or modified file that looks executable (a script or
1305    /// binary by extension, or text starting with `#!`): highlighted in
1306    /// the update review (#24).
1307    pub script: bool,
1308}
1309
1310/// File extensions of scripts and binaries an agent or a hook could run.
1311const 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
1316/// Whether `path` (with content `bytes`) looks executable.
1317pub 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/// What an update check found.
1343#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1344pub enum UpdateStatus {
1345    UpToDate,
1346    Available,
1347    /// Not a git source (local, authored, agents CLI): nothing to check.
1348    NotTracked,
1349    /// The source cannot be reached or no longer holds the skill
1350    /// (`source_unreachable`); the store copy is intact.
1351    Unreachable,
1352    /// A block covers the source (`source_blocked`): it was not contacted.
1353    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/// Result of [`check_update`].
1369#[derive(Debug, Clone)]
1370pub struct UpdateCheck {
1371    pub id: String,
1372    pub status: UpdateStatus,
1373    /// The commit the store copy came from.
1374    pub current: Option<String>,
1375    /// The source's commit now.
1376    pub latest: Option<String>,
1377    /// Files that differ from the store copy (a store copy edited locally
1378    /// shows here too).
1379    pub changes: Vec<FileChange>,
1380    pub error: Option<CoreError>,
1381    /// The built-in scan of the source's content now, when an update is
1382    /// available (SPEC 17): what the update review shows.
1383    pub scan: Option<ScanReport>,
1384    /// The trust check of the skill's git source (#24): an update needs
1385    /// trust (or the user's answer) like an install.
1386    pub trust: Option<TrustCheck>,
1387    /// What changed about the source since the last fetch (force-push,
1388    /// moved); trust in it lapsed when it was trusted.
1389    pub source_change: Option<SourceChange>,
1390    /// The trust check of the repository the source moved to, when the
1391    /// host redirected it to another key: the update needs its trust too
1392    /// ([`Decisions::moved_trust`]), and moves the skill's URL there.
1393    pub moved_trust: Option<TrustCheck>,
1394}
1395
1396/// The latest content of a git skill, and what changed about its source.
1397struct Latest {
1398    commit: String,
1399    files: SkillFiles,
1400    change: Option<SourceChange>,
1401    /// The repository the host redirected the source to (another key).
1402    moved_to: Option<SourceRef>,
1403}
1404
1405/// In a cache clone's `.git`: the URL of the repository the last fetch
1406/// was redirected to, so a reviewed update knows where the content it
1407/// writes came from without fetching again.
1408const MOVED_MARKER: &str = "surjection-moved-to";
1409
1410/// The redirect target the last fetch into the cache clone `dir` saw.
1411fn 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
1434/// The latest content of a git skill: the cache clone fetched (re-cloned
1435/// when missing) and checked out at the source's head. A redirect to
1436/// another repository is [`SourceChangeKind::Moved`]; a head that no
1437/// longer contains the commit installed last is
1438/// [`SourceChangeKind::HistoryRewritten`] (#24).
1439fn 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        // Without `--quiet`, so git reports an HTTP redirect.
1450        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
1537/// [`read_folder`] of a skill folder inside a clone, refused with
1538/// `invalid_path` when the folder (or a link on its way) resolves outside
1539/// the clone: a repository can hold a link to any folder on this machine
1540/// (SPEC 17).
1541fn 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
1583/// The trust gate's view of a git skill source; `None` for a URL that
1584/// names no source (a hand-edited one).
1585fn 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
1602/// Checks a git skill for an update (SPEC 12.4). Touches only the cache
1603/// clone; an unreachable source is reported, not an error, and a blocked
1604/// one is reported without contacting it. A force-push or a move of a
1605/// trusted source makes its trust lapse (one store commit,
1606/// [`sources::lapse`]); that is the only store change a check makes.
1607pub 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
1696/// The source's files as the last [`check_update`] (or install, or
1697/// [`update`]) left them in the cache clone, without contacting the
1698/// source: what the update preview compares with the store copy. `None`
1699/// for a skill without a git source or without a cache clone.
1700pub 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/// What [`update`] did.
1724#[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    /// `None` when the store copy was already current.
1731    pub commit: Option<CommitId>,
1732    /// Copies rewritten with the new content.
1733    pub report: SyncReport,
1734    /// The built-in scan of the new content (SPEC 17).
1735    pub scan: ScanReport,
1736    /// The external scanner's report the update was gated on (#27).
1737    pub external: Option<ExternalReport>,
1738}
1739
1740/// Updates a git skill: the source's latest content replaces the store
1741/// copy in one commit (`skill: update <id> to <sha>`), then owned copies
1742/// follow ([`sync`]). A blocked source is refused (`source_blocked`)
1743/// before it is contacted; `source_unreachable` leaves everything as it
1744/// is; `not_found`/`invalid_value` for skills that are not git skills;
1745/// `scan_blocked` for content the decisions do not let through.
1746pub 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
1773/// Updates a git skill to `expected`, the source commit the user reviewed
1774/// (the app's update preview): the cache clone is used as the last check
1775/// left it, without fetching. When the clone is at another commit (a later
1776/// check saw a newer push), nothing is written and the error is
1777/// `entry_changed`: check again and review the new content.
1778pub 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/// Writes `files` (the source at `commit`) as the store copy of `id` in one
1815/// commit, then lets owned copies follow; nothing is written when the
1816/// decisions do not let the content through. The source and the
1817/// repository it moved to (`moved_to`) both pass the trust gate; then the
1818/// skill's URL follows the move, so the next check fetches from there.
1819#[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    // Source trust first (#24), then the scan's gate.
1831    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}