Skip to main content

surjection_core/mcp_source/
mod.rs

1//! MCP servers from a Git repository or a local folder (#5).
2//!
3//! [`resolve`] turns a source into **drafts**: proposed store servers read
4//! from the folder's files (`server.json` of the MCP Registry, an MCPB
5//! manifest, committed client configs, or the folder as a package). It
6//! runs nothing: the system git clones shallow at the ref (no submodules,
7//! no hooks from the repository) into `cache/mcp-sources/.tmp-<ulid>`, the
8//! files are read (dependency and build folders left out, [`SKIP_DIRS`])
9//! and scanned (M40), and the clone is removed when the [`Resolved`] is
10//! dropped ([`sweep_temp_clones`] removes what a crash left). [`save`]
11//! stores the drafts the user picked and edited in one commit, after the
12//! source trust gate (M39) and the scan gate; a draft that runs from the
13//! repository's files keeps the clone as the machine-local
14//! `<SURJECTION_HOME>/servers/<id>` (never synced), placed under the store
15//! lock and marked with the commit it holds.
16//!
17//! Only provenance goes into the synced server file (`[meta.source]`), so
18//! [`check_update`] can read the source again and show what changed. A
19//! server runs only where its code is what the file names ([`runnable`]):
20//! a checkout at another commit, or a folder of another machine, blocks its
21//! entries. Secrets: a declared secret becomes a `${secret:<alias>}`
22//! reference for the user to set; a literal the classifier flags is
23//! replaced by a reference and its value dropped: no value is kept or
24//! returned. Every check covers the base definition and each `[os.*]`
25//! override alike.
26
27mod convert;
28pub mod snippet;
29#[cfg(test)]
30mod tests;
31
32use std::collections::{BTreeMap, BTreeSet};
33use std::ffi::OsStr;
34use std::path::{Path, PathBuf};
35use std::time::Duration;
36
37use crate::apply::{ApplyEnv, ApplyReport, Touched, instant_apply};
38use crate::error::{CoreError, ErrorCode};
39use crate::fs::Fs;
40use crate::model::ids;
41use crate::model::server::{Meta, Server, ServerFields, ServerSource, ServerSourceKind};
42use crate::paths::STATE_DIR;
43use crate::scan::{self, ScanReport, Scanner};
44use crate::secrets::catalog::Catalog;
45use crate::secrets::extract::{Aliases, Extractor};
46use crate::skills::install::{
47    self, ChangeKind, Decisions, FileChange, Source, UpdateStatus, check_repo_path, git_path,
48    is_commit_ref, join_rel, looks_executable, remove_dir, run_git,
49};
50use crate::skills::{SkillFiles, SkillsEnv, confine, content_hash, io_error, read_folder_skipping};
51use crate::sources::{self, SourceChange, SourceChangeKind, SourceRef, TrustCheck, TrustGrant};
52use crate::store::{CommitId, Machine, Operation, Store, server_path};
53
54pub(crate) use convert::custom_registry_url;
55use convert::{CHECKOUT_TOKEN, Ctx, GitPin, ID_TOKEN, IMAGE_PREFIX, RawDraft};
56
57/// Machine-local clones servers run from: `<SURJECTION_HOME>/servers/<id>`.
58pub const CHECKOUTS_DIR: &str = "servers";
59/// Temporary clones of a resolve, below `<SURJECTION_HOME>/cache`.
60pub const TEMP_DIR: &str = "mcp-sources";
61/// `meta.origin` of a server drafted from a git source.
62pub const ORIGIN_GIT: &str = "source:git";
63/// `meta.origin` of a server drafted from a local folder.
64pub const ORIGIN_LOCAL: &str = "source:local";
65/// Dependency and build folders a source read leaves out (scan, size cap,
66/// diffs): installed or built on this machine, not part of the source.
67pub const SKIP_DIRS: [&str; 8] = [
68    "node_modules",
69    ".venv",
70    "venv",
71    "__pycache__",
72    ".git",
73    "target",
74    "dist",
75    "build",
76];
77/// The data folder template variable written into store files: Loadout
78/// 1.0.x's spelling, which both versions read (Appendix C.1).
79const HOME_VAR: &str = "loadout_home";
80/// The checkout's marker, inside its `.git`: the commit and URL it holds.
81const MARKER_FILE: &str = "surjection-checkout";
82/// The marker Loadout 1.0.x wrote; still read, so its checkouts stay current.
83const LEGACY_MARKER_FILE: &str = "loadout-checkout";
84/// A checkout moved aside while its replacement is committed.
85const ASIDE_PREFIX: &str = ".old-";
86
87/// A store id from a server or entry name: lower case, other characters
88/// become `-`, at most 64 characters.
89pub fn id_from_name(name: &str) -> String {
90    let mut id: String = name
91        .trim()
92        .chars()
93        .map(|c| {
94            let c = c.to_ascii_lowercase();
95            if c.is_ascii_alphanumeric() || matches!(c, '.' | '_' | '-') {
96                c
97            } else {
98                '-'
99            }
100        })
101        .collect();
102    id = id.trim_matches(|c| matches!(c, '-' | '.' | '_')).to_owned();
103    id.truncate(64);
104    if id.is_empty() {
105        "server".to_owned()
106    } else {
107        id
108    }
109}
110
111/// Which converter made a draft.
112#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
113pub enum DraftKind {
114    /// `server.json` (MCP Registry).
115    Registry,
116    /// An MCPB/DXT `manifest.json`.
117    Bundle,
118    /// A committed client config.
119    ClientConfig,
120    /// The folder is the server (`package.json`, `pyproject.toml`,
121    /// `Dockerfile`).
122    Package,
123}
124
125impl DraftKind {
126    pub const fn as_str(self) -> &'static str {
127        match self {
128            DraftKind::Registry => "registry",
129            DraftKind::Bundle => "bundle",
130            DraftKind::ClientConfig => "client_config",
131            DraftKind::Package => "package",
132        }
133    }
134}
135
136/// A value the user provides: a secret to set under `alias`, or a
137/// variable the draft reads from the environment.
138#[derive(Debug, Clone, PartialEq, Eq)]
139pub struct DraftInput {
140    /// `env.NAME`, `headers.NAME`, `args[N]` (1-based), `url`, `command`,
141    /// each also as `os.<name>.<field>` for an override, or
142    /// `client.<id>.<key>` for a native passthrough value.
143    pub field: String,
144    pub description: Option<String>,
145    /// The draft holds `${secret:<alias>}` (or, for a passthrough value,
146    /// the value was left out).
147    pub secret: bool,
148    pub required: bool,
149    pub alias: Option<String>,
150    /// The file held a literal value here; it was replaced by the
151    /// reference (or left out) and not kept.
152    pub value_dropped: bool,
153}
154
155/// One launch line: the base definition (`os` `None`) or an `[os.<name>]`
156/// override merged over it.
157#[derive(Debug, Clone, PartialEq, Eq)]
158pub struct LaunchLine {
159    pub os: Option<String>,
160    /// The command and arguments joined by spaces, or the URL.
161    pub line: String,
162}
163
164/// One proposed server.
165#[derive(Debug, Clone)]
166pub struct Draft {
167    /// Names the draft in [`Pick::key`]: `<file>#<entry>` or `<file>`.
168    pub key: String,
169    pub kind: DraftKind,
170    /// The proposed store server: `meta.origin` and `meta.source` set, no
171    /// enablement.
172    pub server: Server,
173    pub inputs: Vec<DraftInput>,
174    /// It runs code from the source (the folder's files, or the
175    /// repository as a package) every time a client starts it.
176    pub runs_repo_code: bool,
177    /// It runs from `<SURJECTION_HOME>/servers/<id>` (git sources).
178    pub checkout: bool,
179    /// The command names a version or commit; `false` for a registry
180    /// package without a concrete version (the scan flags it too).
181    pub pinned: bool,
182    /// Steps the user runs before it works (`docker build ...`); never run
183    /// by Surjection. They may hold `${home}` and `${surjection_home}`
184    /// ([`setup_text`]).
185    pub setup: Vec<String>,
186    /// Other files that held an identical definition.
187    pub also_in: Vec<String>,
188    /// The folder's files and every launch line of this draft.
189    pub scan: ScanReport,
190    /// What this draft runs, gated on its own (a registry entry's package
191    /// or remote host, #26); `None`: [`Resolved::trust_source`] gates it.
192    pub trust_source: Option<SourceRef>,
193}
194
195impl Draft {
196    /// The draft's provenance.
197    pub fn provenance(&self) -> &ServerSource {
198        self.server
199            .body
200            .meta
201            .as_ref()
202            .and_then(|meta| meta.source.as_ref())
203            .expect("a draft has its source")
204    }
205}
206
207/// A definition the folder holds that cannot be drafted.
208#[derive(Debug, Clone)]
209pub struct Skipped {
210    pub file: String,
211    /// The entry inside the file, when it holds several.
212    pub entry: Option<String>,
213    pub error: CoreError,
214}
215
216/// What to resolve.
217#[derive(Debug, Clone)]
218pub struct ResolveRequest {
219    pub source: Source,
220    /// Branch, tag or commit of a git source (overrides the URL's).
221    pub git_ref: Option<String>,
222    /// The folder inside a git source (overrides the URL's).
223    pub path: Option<String>,
224    /// The catalog entry the source comes from, `<catalog>/<entry id>`
225    /// (#26): recorded as `meta.source.catalog`.
226    pub catalog: Option<String>,
227    /// A Claude Code marketplace entry's `mcpServers` (#26), as JSON: an
228    /// object of server definitions, or a path to a config file in the
229    /// folder. Drafted with the folder's own configs.
230    pub mcp_servers: Option<String>,
231}
232
233impl ResolveRequest {
234    pub fn new(source: Source) -> Self {
235        Self {
236            source,
237            git_ref: None,
238            path: None,
239            catalog: None,
240            mcp_servers: None,
241        }
242    }
243}
244
245/// An MCP registry entry to draft from (#26): its `server.json` as the
246/// registry served it (the `server` object of the entry).
247#[derive(Debug, Clone)]
248pub struct RegistryRequest {
249    /// `<catalog>/<server name>`.
250    pub catalog: String,
251    /// The registry's base URL.
252    pub registry: String,
253    /// The server name (`io.github.acme/weather`).
254    pub name: String,
255    /// The entry's version.
256    pub version: String,
257    /// The version was asked for (`--ref`): updates do not follow the
258    /// latest one.
259    pub pinned: bool,
260    pub server_json: String,
261}
262
263/// A resolved source waiting for the user's picks ([`resolve`], then
264/// [`save`]). The temporary clone is removed when this is dropped without
265/// a save that keeps it.
266#[derive(Debug)]
267pub struct Resolved {
268    base: ServerSource,
269    drafts: Vec<Draft>,
270    skipped: Vec<Skipped>,
271    skipped_folders: Vec<String>,
272    files: SkillFiles,
273    files_scan: ScanReport,
274    trust_source: Option<SourceRef>,
275    moved_source: Option<SourceRef>,
276    source_change: Option<SourceChange>,
277    /// The temporary clone (git sources).
278    clone: Option<PathBuf>,
279    spent: bool,
280}
281
282impl Resolved {
283    pub fn drafts(&self) -> &[Draft] {
284        &self.drafts
285    }
286
287    pub fn skipped(&self) -> &[Skipped] {
288        &self.skipped
289    }
290
291    /// Dependency and build folders left out of the read and the scan
292    /// (relative paths, [`SKIP_DIRS`]).
293    pub fn skipped_folders(&self) -> &[String] {
294        &self.skipped_folders
295    }
296
297    /// Where the drafts come from (`file` and `converter` empty).
298    pub fn source(&self) -> &ServerSource {
299        &self.base
300    }
301
302    /// The scan of the folder's files.
303    pub fn files_scan(&self) -> &ScanReport {
304        &self.files_scan
305    }
306
307    /// The source the trust gate admits with [`Decisions::trust`]: the
308    /// repository the URL names, or the local folder. `None` for a
309    /// registry entry: each draft carries its own
310    /// ([`Draft::trust_source`]).
311    pub fn trust_source(&self) -> Option<&SourceRef> {
312        self.trust_source.as_ref()
313    }
314
315    /// Where the host redirected the repository (another key): gated too,
316    /// with [`Decisions::moved_trust`].
317    pub fn moved_source(&self) -> Option<&SourceRef> {
318        self.moved_source.as_ref()
319    }
320
321    /// The repository the URL names moved.
322    pub fn source_change(&self) -> Option<&SourceChange> {
323        self.source_change.as_ref()
324    }
325
326    /// The trust gate (#24): the requested source with the user's answer
327    /// for it, and a redirect target with the answer for that one. A
328    /// redirect only ever adds a question. Each of `drafts` that runs from
329    /// its own source (a registry entry) is gated on it, with the answer
330    /// given with it (a [`Pick::trust`]), or [`Decisions::trust`] when the
331    /// drafts run from one source.
332    fn admit(
333        &self,
334        store: &Store<'_>,
335        decisions: &Decisions,
336        drafts: &[(&Draft, Option<TrustGrant>)],
337    ) -> Result<(), CoreError> {
338        if let Some(source) = &self.trust_source {
339            sources::admit(store, source, decisions.trust, decisions.via)?;
340        }
341        if let Some(moved) = &self.moved_source {
342            sources::admit(store, moved, decisions.moved_trust, decisions.via)?;
343        }
344        let mut own: Vec<(&SourceRef, Option<TrustGrant>)> = Vec::new();
345        for (draft, grant) in drafts {
346            let Some(source) = draft.trust_source.as_ref() else {
347                continue;
348            };
349            match own
350                .iter_mut()
351                .find(|(known, _)| known.key() == source.key())
352            {
353                Some((_, known)) => *known = known.or(*grant),
354                None => own.push((source, *grant)),
355            }
356        }
357        // Blocks first: no "always trust" is recorded for a save that a
358        // block refuses anyway.
359        for (source, _) in &own {
360            sources::refuse_blocked(store, source)?;
361        }
362        let single = own.len() == 1 && self.trust_source.is_none();
363        for (source, grant) in own {
364            let grant = grant.or(if single { decisions.trust } else { None });
365            sources::admit(store, source, grant, decisions.via)?;
366        }
367        Ok(())
368    }
369}
370
371impl Drop for Resolved {
372    fn drop(&mut self) {
373        if let Some(clone) = self.clone.take() {
374            // Below `SURJECTION_HOME/cache`; a leftover is swept later.
375            let _ = std::fs::remove_dir_all(clone);
376        }
377    }
378}
379
380/// What [`fetch`] read.
381struct Fetched {
382    base: ServerSource,
383    files: SkillFiles,
384    skipped_folders: Vec<String>,
385    /// How commands name the folder.
386    root: String,
387    pin: Option<GitPin>,
388    name: String,
389    clone: Option<PathBuf>,
390    /// `None`: a registry entry (each draft is gated on what it runs).
391    trust_source: Option<SourceRef>,
392    moved_source: Option<SourceRef>,
393    source_change: Option<SourceChange>,
394    /// [`ResolveRequest::mcp_servers`].
395    plugin_servers: Option<String>,
396}
397
398/// `<SURJECTION_HOME>/servers/<id>`.
399pub fn checkout_dir(sx: &SkillsEnv<'_>, id: &str) -> PathBuf {
400    sx.home.path.join(CHECKOUTS_DIR).join(id)
401}
402
403/// The URL kept in the store (and in a checkout's `.git/config`): a
404/// password or token in an `http(s)` URL is removed; ssh users (`git@`)
405/// stay, the clone needs them.
406fn provenance_url(url: &str) -> String {
407    let url = url.trim();
408    let lower = url.to_ascii_lowercase();
409    for scheme in ["https://", "http://"] {
410        if lower.starts_with(scheme) {
411            let rest = &url[scheme.len()..];
412            let (authority, path) = rest.split_once('/').unwrap_or((rest, ""));
413            if let Some((_, host)) = authority.rsplit_once('@') {
414                return format!("{}{host}/{path}", &url[..scheme.len()]);
415            }
416        }
417    }
418    url.to_owned()
419}
420
421/// A folder as commands name it: `${home}/...` below the home folder, else
422/// the absolute path, `/`-separated.
423fn folder_template(sx: &SkillsEnv<'_>, folder: &Path) -> String {
424    let home = sx.env.home();
425    let text = match folder.strip_prefix(home) {
426        Ok(rest) if !rest.as_os_str().is_empty() => {
427            format!("${{home}}/{}", rest.to_string_lossy())
428        }
429        _ => folder.to_string_lossy().into_owned(),
430    };
431    convert::escape(&text.replace('\\', "/")).replace("$${home}", "${home}")
432}
433
434/// The folder a [`folder_template`] names.
435fn folder_of(sx: &SkillsEnv<'_>, template: &str) -> PathBuf {
436    let text = template.replace("$${", "${");
437    match text.strip_prefix("${home}/") {
438        Some(rest) => rest
439            .split('/')
440            .fold(sx.env.home().to_path_buf(), |path, part| path.join(part)),
441        None => PathBuf::from(text),
442    }
443}
444
445fn name_of(text: &str) -> String {
446    text.trim_end_matches(['/', '\\'])
447        .rsplit(['/', '\\', ':'])
448        .next()
449        .unwrap_or("server")
450        .trim_end_matches(".git")
451        .to_owned()
452}
453
454/// A setup step for a person to run: `${surjection_home}` and `${home}` (store
455/// templates, not shell variables) written as `surjection_home` and `home`.
456pub fn setup_text(step: &str, home: &str, surjection_home: &str) -> String {
457    step.replace("${surjection_home}", surjection_home)
458        .replace("${loadout_home}", surjection_home)
459        .replace("${home}", home)
460        .replace("$${", "${")
461}
462
463/// Reads a source folder ([`SKIP_DIRS`] left out).
464fn read_source(fs: &dyn Fs, dir: &Path) -> Result<(SkillFiles, Vec<String>), CoreError> {
465    read_folder_skipping(fs, dir, &SKIP_DIRS)
466}
467
468/// Reads a folder inside a clone, refused when it (or a link on its way)
469/// resolves outside the clone.
470fn read_in(
471    sx: &SkillsEnv<'_>,
472    clone: &Path,
473    dir: &Path,
474) -> Result<(SkillFiles, Vec<String>), CoreError> {
475    let resolve = |path: &Path| {
476        sx.fs
477            .canonicalize(path)
478            .map_err(|err| io_error("cannot resolve folder", path, &err))
479    };
480    if !resolve(dir)?.starts_with(resolve(clone)?) {
481        return Err(CoreError::new(
482            ErrorCode::InvalidPath,
483            "the folder points outside the repository",
484        )
485        .with_path(dir));
486    }
487    read_source(sx.fs, dir)
488}
489
490/// Clones `url` into a new temporary folder at `git_ref` (a branch, tag or
491/// commit), sparse to `path`, and points its `origin` at the URL without
492/// credentials. Returns the clone, the commit, the branch followed and
493/// where the host redirected the URL.
494fn clone_at(
495    sx: &SkillsEnv<'_>,
496    url: &str,
497    git_ref: Option<&str>,
498    path: Option<&str>,
499) -> Result<(PathBuf, String, Option<String>, Option<String>), CoreError> {
500    let git = git_path(sx)?;
501    let temp = sx.home.cache_dir().join(TEMP_DIR).join(format!(
502        ".tmp-{}",
503        ids::new_ulid(sx.env.now())?.to_ascii_lowercase()
504    ));
505    let cloned = install::clone(sx, &git, url, git_ref, path, &temp)?;
506    let fail = |err: CoreError| {
507        let _ = remove_dir(sx.fs, &temp);
508        err
509    };
510    // A token in the URL never stays in the clone's `.git/config`, which
511    // a checkout keeps for good.
512    let clean = provenance_url(url);
513    let args: Vec<&OsStr> = ["remote", "set-url", "origin", clean.as_str()]
514        .into_iter()
515        .map(OsStr::new)
516        .collect();
517    let output = run_git(sx, &git, &temp, &args).map_err(fail)?;
518    if !output.success {
519        return Err(fail(CoreError::new(
520            ErrorCode::GitError,
521            "cannot set the clone's remote URL",
522        )));
523    }
524    Ok((temp, cloned.commit, cloned.branch, cloned.redirect))
525}
526
527fn fetch(sx: &SkillsEnv<'_>, request: &ResolveRequest) -> Result<Fetched, CoreError> {
528    match &request.source {
529        Source::Local(folder) => {
530            if request.git_ref.is_some() || request.path.is_some() {
531                return Err(CoreError::new(
532                    ErrorCode::InvalidValue,
533                    "a ref and a path apply to git sources only",
534                ));
535            }
536            if !sx.fs.is_dir(folder) {
537                return Err(
538                    CoreError::new(ErrorCode::NotFound, "the folder does not exist")
539                        .with_path(folder),
540                );
541            }
542            let root = folder_template(sx, folder);
543            let (files, skipped_folders) = read_source(sx.fs, folder)?;
544            Ok(Fetched {
545                base: ServerSource {
546                    kind: ServerSourceKind::Local,
547                    url: None,
548                    folder: Some(root.clone()),
549                    path: None,
550                    git_ref: None,
551                    commit: None,
552                    file: String::new(),
553                    converter: String::new(),
554                    entry: None,
555                    checkout: None,
556                    machine: None,
557                    catalog: request.catalog.clone(),
558                    version: None,
559                    extra: toml::Table::new(),
560                },
561                files,
562                skipped_folders,
563                root,
564                pin: None,
565                name: name_of(&folder.to_string_lossy()),
566                clone: None,
567                trust_source: Some(SourceRef::from_local_path(folder)?),
568                moved_source: None,
569                source_change: None,
570                plugin_servers: request.mcp_servers.clone(),
571            })
572        }
573        Source::Git { url, git_ref, path } => {
574            let requested = SourceRef::from_git_url(url)?;
575            let git_ref = request.git_ref.clone().or_else(|| git_ref.clone());
576            let path = request
577                .path
578                .clone()
579                .or_else(|| path.clone())
580                .map(|path| check_repo_path(&path))
581                .transpose()?;
582            let (clone, commit, branch, redirect) =
583                clone_at(sx, url, git_ref.as_deref(), path.as_deref())?;
584            let read = || -> Result<(SkillFiles, Vec<String>), CoreError> {
585                let dir = match &path {
586                    Some(path) => join_rel(&clone, path),
587                    None => clone.clone(),
588                };
589                if !sx.fs.is_dir(&dir) {
590                    return Err(CoreError::new(
591                        ErrorCode::NotFound,
592                        format!(
593                            "the repository has no folder {:?}",
594                            path.as_deref().unwrap_or("")
595                        ),
596                    ));
597                }
598                read_in(sx, &clone, &dir)
599            };
600            let (files, skipped_folders) = match read() {
601                Ok(read) => read,
602                Err(err) => {
603                    let _ = remove_dir(sx.fs, &clone);
604                    return Err(err);
605                }
606            };
607            let moved_to = redirect
608                .as_deref()
609                .and_then(|target| SourceRef::from_git_url(target).ok())
610                .filter(|target| target.key() != requested.key());
611            let source_change = moved_to.as_ref().map(|target| SourceChange {
612                kind: SourceChangeKind::Moved,
613                detail: Some(target.key().to_owned()),
614            });
615            let url = provenance_url(url);
616            let followed = match git_ref.as_deref() {
617                Some(r) if is_commit_ref(r) => Some(r.to_owned()),
618                _ => branch,
619            };
620            let name = path
621                .as_deref()
622                .and_then(|path| path.rsplit('/').next())
623                .map_or_else(|| name_of(&url), str::to_owned);
624            Ok(Fetched {
625                base: ServerSource {
626                    kind: ServerSourceKind::Git,
627                    url: Some(url.clone()),
628                    folder: None,
629                    path: path.clone(),
630                    git_ref: followed,
631                    commit: Some(commit.clone()),
632                    file: String::new(),
633                    converter: String::new(),
634                    entry: None,
635                    checkout: None,
636                    machine: None,
637                    catalog: request.catalog.clone(),
638                    version: None,
639                    extra: toml::Table::new(),
640                },
641                files,
642                skipped_folders,
643                root: CHECKOUT_TOKEN.to_owned(),
644                pin: Some(GitPin { url, commit, path }),
645                name,
646                clone: Some(clone),
647                trust_source: Some(requested),
648                moved_source: moved_to,
649                source_change,
650                plugin_servers: request.mcp_servers.clone(),
651            })
652        }
653    }
654}
655
656/// `${loadout_home}/servers/<id>[/<path>]`: the data folder variable is
657/// written with the spelling Loadout 1.0.x reads (synced store files, like
658/// `store/loadout.toml`; Appendix C.1).
659fn checkout_root(id: &str, path: Option<&str>) -> String {
660    match path {
661        Some(path) => format!("${{{HOME_VAR}}}/{CHECKOUTS_DIR}/{id}/{path}"),
662        None => format!("${{{HOME_VAR}}}/{CHECKOUTS_DIR}/{id}"),
663    }
664}
665
666/// Every launch string of `fields` through `edit`.
667fn edit_fields(fields: &mut ServerFields, edit: &dyn Fn(&str) -> String) {
668    let apply = |value: &mut String| *value = edit(value);
669    fields.command.iter_mut().for_each(apply);
670    fields.cwd.iter_mut().for_each(apply);
671    fields.url.iter_mut().for_each(apply);
672    fields.args.iter_mut().flatten().for_each(apply);
673    fields
674        .env
675        .iter_mut()
676        .flatten()
677        .for_each(|(_, value)| apply(value));
678    fields
679        .headers
680        .iter_mut()
681        .flatten()
682        .for_each(|(_, value)| apply(value));
683}
684
685/// Every launch string of `server`, base and overrides, through `edit`.
686fn edit_server(server: &mut Server, edit: &dyn Fn(&str) -> String) {
687    let mut fields = server.body.fields();
688    edit_fields(&mut fields, edit);
689    set_launch(server, &fields);
690    for over in server.body.os.iter_mut().flatten().map(|(_, over)| over) {
691        edit_fields(&mut over.fields, edit);
692    }
693}
694
695/// Writes the launch fields of `fields` into `server`.
696fn set_launch(server: &mut Server, fields: &ServerFields) {
697    let body = &mut server.body;
698    body.transport = fields.transport;
699    body.command.clone_from(&fields.command);
700    body.args.clone_from(&fields.args);
701    body.cwd.clone_from(&fields.cwd);
702    body.url.clone_from(&fields.url);
703    body.headers.clone_from(&fields.headers);
704    body.env.clone_from(&fields.env);
705}
706
707/// `value` with each whole `from` (followed by the end, `/` or `:`)
708/// replaced by `to`.
709fn replace_whole(value: &str, from: &str, to: &str) -> String {
710    let mut out = String::new();
711    let mut rest = value;
712    while let Some(at) = rest.find(from) {
713        let after = &rest[at + from.len()..];
714        out.push_str(&rest[..at]);
715        if after.is_empty() || after.starts_with(['/', ':']) {
716            out.push_str(to);
717        } else {
718            out.push_str(from);
719        }
720        rest = after;
721    }
722    out.push_str(rest);
723    out
724}
725
726/// Points what a draft names by its id (its checkout folder, its local
727/// image tag) at `to` instead of `from`.
728fn rename_id(server: &mut Server, from: &str, to: &str) {
729    if from == to {
730        return;
731    }
732    let pairs = [
733        (
734            format!("${{surjection_home}}/{CHECKOUTS_DIR}/{from}"),
735            format!("${{surjection_home}}/{CHECKOUTS_DIR}/{to}"),
736        ),
737        (
738            format!("${{{HOME_VAR}}}/{CHECKOUTS_DIR}/{from}"),
739            format!("${{{HOME_VAR}}}/{CHECKOUTS_DIR}/{to}"),
740        ),
741        (
742            format!("{IMAGE_PREFIX}{from}"),
743            format!("{IMAGE_PREFIX}{to}"),
744        ),
745    ];
746    edit_server(server, &|value| {
747        pairs.iter().fold(value.to_owned(), |value, (old, new)| {
748            replace_whole(&value, old, new)
749        })
750    });
751}
752
753fn rename_steps(steps: &[String], from: &str, to: &str) -> Vec<String> {
754    let mut server = Server::new(to.to_owned());
755    server.body.args = Some(steps.to_vec());
756    rename_id(&mut server, from, to);
757    server.body.args.unwrap_or_default()
758}
759
760fn line_of(fields: &ServerFields) -> String {
761    match (&fields.url, &fields.command) {
762        (Some(url), _) => url.clone(),
763        (None, Some(command)) => std::iter::once(command)
764            .chain(fields.args.iter().flatten())
765            .cloned()
766            .collect::<Vec<_>>()
767            .join(" "),
768        (None, None) => String::new(),
769    }
770}
771
772/// The launch fields as each OS sees them: the base, then each
773/// `[os.<name>]` override merged over it.
774fn effective(server: &Server) -> Vec<(Option<String>, ServerFields)> {
775    let base = server.body.fields();
776    let mut out = vec![(None, base.clone())];
777    for (name, over) in server.body.os.iter().flatten() {
778        out.push((Some(name.clone()), base.merged(&over.fields)));
779    }
780    out
781}
782
783/// Every launch line of `server`: the base and each OS override.
784pub fn launch_lines(server: &Server) -> Vec<LaunchLine> {
785    effective(server)
786        .into_iter()
787        .map(|(os, fields)| LaunchLine {
788            os,
789            line: line_of(&fields),
790        })
791        .collect()
792}
793
794/// The scan of every command line `server` can run, base and overrides.
795fn scan_commands(scanner: &Scanner<'_>, server: &Server) -> ScanReport {
796    let mut lines = effective(server)
797        .into_iter()
798        .map(|(_, fields)| match &fields.command {
799            Some(command) => scanner.scan_command(command, &fields.args.unwrap_or_default()),
800            None => scanner.scan_command(&fields.url.unwrap_or_default(), &[]),
801        });
802    let mut report = lines.next().expect("the base definition");
803    for other in lines {
804        report.merge(other);
805    }
806    report
807}
808
809fn store_ids(store: Option<&Store<'_>>) -> Result<BTreeSet<String>, CoreError> {
810    Ok(match store {
811        Some(store) => store.servers()?.into_iter().map(|entry| entry.id).collect(),
812        None => BTreeSet::new(),
813    })
814}
815
816fn aliases(store: Option<&Store<'_>>, sx: &SkillsEnv<'_>) -> Result<Aliases, CoreError> {
817    let Some(store) = store else {
818        return Ok(Aliases::default());
819    };
820    let machine = Machine::load(sx.fs, &sx.home.state_dir())?;
821    let catalog = Catalog::load(store, machine.as_ref().map(|m| m.id.as_str()))?;
822    Ok(Aliases::new(
823        catalog.iter().map(|alias| alias.alias.clone()),
824    ))
825}
826
827/// `base`, or `base-2`, `base-3`, ... free of `taken`.
828fn free_id(base: &str, taken: &BTreeSet<String>) -> String {
829    if !taken.contains(base) {
830        return base.to_owned();
831    }
832    let stem: String = base.chars().take(60).collect();
833    (2..)
834        .map(|n| format!("{stem}-{n}"))
835        .find(|id| !taken.contains(id))
836        .expect("a free id")
837}
838
839/// Replaces the literals of `fields` the classifier flags by references
840/// (the values are dropped), listing each as an input named
841/// `<prefix><field>`.
842fn extract(
843    fields: &mut ServerFields,
844    prefix: &str,
845    id: &str,
846    aliases: &mut Aliases,
847    inputs: &mut Vec<DraftInput>,
848) -> Result<(), CoreError> {
849    let mut extractor = Extractor::new(id, aliases);
850    if let Some(args) = fields.args.take() {
851        fields.args = Some(extractor.args(args));
852    }
853    if let Some(url) = fields.url.take() {
854        fields.url = Some(extractor.url(url)?);
855    }
856    if let Some(env) = fields.env.take() {
857        fields.env = Some(extractor.map("env", env));
858    }
859    if let Some(headers) = fields.headers.take() {
860        fields.headers = Some(extractor.map("headers", headers));
861    }
862    for extracted in extractor.finish() {
863        let extraction = extracted.extraction;
864        // The value (`extracted.value`) is dropped here.
865        inputs.push(DraftInput {
866            field: format!("{prefix}{}", extraction.field),
867            description: None,
868            secret: true,
869            required: true,
870            alias: Some(extraction.alias),
871            value_dropped: true,
872        });
873    }
874    Ok(())
875}
876
877/// Renames the provisional secret references of `raw` to free aliases of
878/// server `id`, then replaces every other literal the classifier flags, in
879/// the base definition and in each override, by a reference.
880fn secure(raw: &mut RawDraft, id: &str, aliases: &mut Aliases) -> Result<(), CoreError> {
881    let mut renames = BTreeMap::new();
882    for input in raw.inputs.iter_mut().filter(|input| input.secret) {
883        if let Some(key) = input.alias.clone() {
884            let alias = renames
885                .entry(key)
886                .or_insert_with_key(|key| aliases.new_alias(id, key))
887                .clone();
888            input.alias = Some(alias);
889        }
890    }
891    if !renames.is_empty() {
892        let edit = |value: &str| {
893            let mut out = value.to_owned();
894            for (key, alias) in &renames {
895                out = out.replace(
896                    &format!("${{secret:{key}}}"),
897                    &format!("${{secret:{alias}}}"),
898                );
899            }
900            out
901        };
902        edit_fields(&mut raw.fields, &edit);
903        for over in raw.os.iter_mut().flatten().map(|(_, over)| over) {
904            edit_fields(&mut over.fields, &edit);
905        }
906    }
907    extract(&mut raw.fields, "", id, aliases, &mut raw.inputs)?;
908    for (name, over) in raw.os.iter_mut().flatten() {
909        let prefix = format!("os.{name}.");
910        extract(&mut over.fields, &prefix, id, aliases, &mut raw.inputs)?;
911    }
912    Ok(())
913}
914
915/// Resolves a source into drafts: fetches (a git source into a temporary
916/// clone), converts and scans, without touching the store. `store` (when
917/// there is one) keeps ids and secret aliases free of those in use, and a
918/// source it blocks is refused before it is contacted.
919pub fn resolve(
920    store: Option<&Store<'_>>,
921    sx: &SkillsEnv<'_>,
922    request: &ResolveRequest,
923) -> Result<Resolved, CoreError> {
924    if let Some(store) = store {
925        // A blocked source is never contacted (#24).
926        let requested = match &request.source {
927            Source::Git { url, .. } => SourceRef::from_git_url(url)?,
928            Source::Local(folder) => SourceRef::from_local_path(folder)?,
929        };
930        sources::refuse_blocked(store, &requested)?;
931    }
932    let fetched = fetch(sx, request)?;
933    build(store, sx, fetched)
934}
935
936/// The `meta.origin` of a catalog install: `catalog:<catalog id>`.
937pub fn catalog_origin(catalog: &str) -> String {
938    let id = catalog.split_once('/').map_or(catalog, |(id, _)| id);
939    format!("catalog:{id}")
940}
941
942/// Resolves an MCP registry entry (#26) into drafts: its `server.json`
943/// goes through the `registry` converter as a `registry` source. Nothing
944/// is fetched here (the catalog already read the entry); `store` keeps
945/// ids and aliases free. Each draft is gated on what it runs
946/// ([`crate::catalog::registry::trust_keys`]): a draft without a usable
947/// key is skipped, and an entry whose every draft is blocked is refused.
948pub fn resolve_registry(
949    store: Option<&Store<'_>>,
950    sx: &SkillsEnv<'_>,
951    request: &RegistryRequest,
952) -> Result<Resolved, CoreError> {
953    let keys = crate::catalog::registry::trust_keys(&request.server_json)?;
954    let files = SkillFiles::from([(
955        "server.json".to_owned(),
956        request.server_json.as_bytes().to_vec(),
957    )]);
958    let fetched = Fetched {
959        base: ServerSource {
960            kind: ServerSourceKind::Registry,
961            url: Some(request.registry.clone()),
962            folder: None,
963            path: None,
964            git_ref: request.pinned.then(|| request.version.clone()),
965            commit: None,
966            file: String::new(),
967            converter: String::new(),
968            entry: None,
969            checkout: None,
970            machine: None,
971            catalog: Some(request.catalog.clone()),
972            version: Some(request.version.clone()),
973            extra: toml::Table::new(),
974        },
975        files,
976        skipped_folders: Vec::new(),
977        root: String::new(),
978        pin: None,
979        name: name_of(&request.name),
980        clone: None,
981        trust_source: None,
982        moved_source: None,
983        source_change: None,
984        plugin_servers: None,
985    };
986    let mut resolved = build(store, sx, fetched)?;
987    let drafts = std::mem::take(&mut resolved.drafts);
988    for mut draft in drafts {
989        let entry = draft.provenance().entry.clone();
990        match keys
991            .iter()
992            .find(|(name, _)| Some(name) == entry.as_ref())
993            .map(|(_, key)| key.clone())
994        {
995            Some(Ok(source)) => {
996                draft.trust_source = Some(source);
997                resolved.drafts.push(draft);
998            }
999            Some(Err(error)) => resolved.skipped.push(Skipped {
1000                file: draft.provenance().file.clone(),
1001                entry,
1002                error,
1003            }),
1004            None => resolved.skipped.push(Skipped {
1005                file: draft.provenance().file.clone(),
1006                entry,
1007                error: CoreError::new(
1008                    ErrorCode::InvalidValue,
1009                    "Surjection cannot tell what this definition runs from",
1010                ),
1011            }),
1012        }
1013    }
1014    if let Some(store) = store {
1015        let mut blocked = None;
1016        for draft in &resolved.drafts {
1017            let source = draft.trust_source.as_ref().expect("set above");
1018            match sources::refuse_blocked(store, source) {
1019                Ok(_) => {
1020                    blocked = None;
1021                    break;
1022                }
1023                Err(err) => blocked = blocked.or(Some(err)),
1024            }
1025        }
1026        if let Some(err) = blocked {
1027            return Err(err);
1028        }
1029    }
1030    Ok(resolved)
1031}
1032
1033fn build(
1034    store: Option<&Store<'_>>,
1035    sx: &SkillsEnv<'_>,
1036    fetched: Fetched,
1037) -> Result<Resolved, CoreError> {
1038    let Fetched {
1039        base,
1040        files,
1041        skipped_folders,
1042        root,
1043        pin,
1044        name,
1045        clone,
1046        trust_source,
1047        moved_source,
1048        source_change,
1049        plugin_servers,
1050    } = fetched;
1051    let ctx = Ctx {
1052        files: &files,
1053        skipped: &skipped_folders,
1054        root: root.clone(),
1055        git: pin.as_ref(),
1056        os: sx.env.os(),
1057        name,
1058        content_hash: content_hash(&files),
1059        plugin_servers: plugin_servers.as_deref(),
1060    };
1061    let (raws, mut skipped) = convert::all(&ctx);
1062    // Identical definitions collapse into the first.
1063    let mut kept: Vec<(RawDraft, Vec<String>)> = Vec::new();
1064    for raw in raws {
1065        match kept
1066            .iter_mut()
1067            .find(|(first, _)| first.fields == raw.fields && first.os == raw.os)
1068        {
1069            Some((_, also_in)) => also_in.push(raw.file),
1070            None => kept.push((raw, Vec::new())),
1071        }
1072    }
1073    let mut taken = store_ids(store)?;
1074    let mut aliases = aliases(store, sx)?;
1075    let scanner = Scanner::new(sx.fs, sx.home);
1076    let files_scan = scanner.scan_files(&files);
1077    let mut drafts = Vec::new();
1078    for (mut raw, also_in) in kept {
1079        let id = free_id(&id_from_name(&raw.name), &taken);
1080        if let Err(error) = secure(&mut raw, &id, &mut aliases) {
1081            skipped.push(Skipped {
1082                file: raw.file,
1083                entry: raw.entry,
1084                error,
1085            });
1086            continue;
1087        }
1088        let checkout = pin.is_some() && convert::uses_root(&raw, CHECKOUT_TOKEN);
1089        let root_text = match &pin {
1090            Some(pin) => checkout_root(&id, pin.path.as_deref()),
1091            None => root.clone(),
1092        };
1093        let mut server = Server::new(id.clone());
1094        set_launch(&mut server, &raw.fields);
1095        let body = &mut server.body;
1096        body.display_name = raw.display_name.clone();
1097        body.description = raw.description.clone();
1098        body.os = raw.os.clone();
1099        body.tools = raw.tools.clone();
1100        body.client = raw
1101            .passthrough
1102            .clone()
1103            .map(|(client, table)| BTreeMap::from([(client, table)]));
1104        let mut source = base.clone();
1105        source.file.clone_from(&raw.file);
1106        source.converter.clone_from(&raw.converter);
1107        source.entry.clone_from(&raw.entry);
1108        source.checkout = checkout.then_some(true);
1109        body.meta = Some(Meta {
1110            homepage: raw.homepage.clone(),
1111            origin: Some(match (&base.catalog, base.kind) {
1112                (Some(catalog), _) => catalog_origin(catalog),
1113                (None, ServerSourceKind::Git) => ORIGIN_GIT.to_owned(),
1114                (None, ServerSourceKind::Local) => ORIGIN_LOCAL.to_owned(),
1115                (None, ServerSourceKind::Registry) => "catalog".to_owned(),
1116            }),
1117            source: Some(source),
1118            ..Meta::default()
1119        });
1120        let fill = |value: &str| {
1121            value
1122                .replace(CHECKOUT_TOKEN, &root_text)
1123                .replace(ID_TOKEN, &id)
1124        };
1125        edit_server(&mut server, &fill);
1126        let setup = raw.setup.iter().map(|step| fill(step)).collect();
1127        if let Some(error) = server.validate(Some(&id)).first_error(None) {
1128            skipped.push(Skipped {
1129                file: raw.file,
1130                entry: raw.entry,
1131                error,
1132            });
1133            continue;
1134        }
1135        taken.insert(id);
1136        let mut scan = files_scan.clone();
1137        scan.merge(scan_commands(&scanner, &server));
1138        let key = match &raw.entry {
1139            Some(entry) => format!("{}#{entry}", raw.file),
1140            None => raw.file.clone(),
1141        };
1142        drafts.push(Draft {
1143            key,
1144            kind: raw.kind,
1145            server,
1146            inputs: raw.inputs,
1147            runs_repo_code: raw.runs_repo_code || checkout,
1148            checkout,
1149            pinned: raw.pinned,
1150            setup,
1151            also_in,
1152            scan,
1153            trust_source: None,
1154        });
1155    }
1156    Ok(Resolved {
1157        base,
1158        drafts,
1159        skipped,
1160        skipped_folders,
1161        files,
1162        files_scan,
1163        trust_source,
1164        moved_source,
1165        source_change,
1166        clone,
1167        spent: false,
1168    })
1169}
1170
1171// --------------------------------------------------------------- checkouts
1172
1173/// `<checkout>/.git/surjection-checkout`.
1174fn marker_path(dir: &Path) -> PathBuf {
1175    dir.join(".git").join(MARKER_FILE)
1176}
1177
1178fn marker_text(commit: &str, url: &str) -> String {
1179    format!("{commit}\n{url}\n")
1180}
1181
1182/// Whether the checkout of server `id` below `surjection_home` holds what
1183/// `source` names (its marker: commit and URL).
1184fn checkout_current(fs: &dyn Fs, surjection_home: &Path, id: &str, source: &ServerSource) -> bool {
1185    let dir = surjection_home.join(CHECKOUTS_DIR).join(id);
1186    let Ok(bytes) = fs
1187        .read(&marker_path(&dir))
1188        .or_else(|_| fs.read(&dir.join(".git").join(LEGACY_MARKER_FILE)))
1189    else {
1190        return false;
1191    };
1192    let expected = marker_text(
1193        source.commit.as_deref().unwrap_or_default(),
1194        source.url.as_deref().unwrap_or_default(),
1195    );
1196    String::from_utf8_lossy(&bytes) == expected
1197}
1198
1199/// Whether `server` may run on this machine (checked when its entries are
1200/// rendered): a server from a Git repository that runs from a checkout
1201/// needs this machine's checkout at the commit and URL its file names
1202/// (`checkout_out_of_date` otherwise, so the old code never runs with the
1203/// new command); a server from a local folder runs only on the machine
1204/// that added it (`folder_on_other_machine`).
1205pub fn runnable(fs: &dyn Fs, surjection_home: &Path, server: &Server) -> Result<(), CoreError> {
1206    let Some(source) = server
1207        .body
1208        .meta
1209        .as_ref()
1210        .and_then(|meta| meta.source.as_ref())
1211    else {
1212        return Ok(());
1213    };
1214    match source.kind {
1215        ServerSourceKind::Git if source.uses_checkout() => {
1216            if checkout_current(fs, surjection_home, &server.id, source) {
1217                Ok(())
1218            } else {
1219                Err(CoreError::new(
1220                    ErrorCode::CheckoutOutOfDate,
1221                    format!(
1222                        "checkout out of date: run `surject server checkout {}`",
1223                        server.id
1224                    ),
1225                ))
1226            }
1227        }
1228        ServerSourceKind::Local => match &source.machine {
1229            Some(machine) => {
1230                let here = Machine::load(fs, &surjection_home.join(STATE_DIR))?;
1231                if here.as_ref().is_some_and(|here| &here.id == machine) {
1232                    Ok(())
1233                } else {
1234                    Err(CoreError::new(
1235                        ErrorCode::FolderOnOtherMachine,
1236                        "added from a folder on another machine; it does not run here",
1237                    ))
1238                }
1239            }
1240            None => Ok(()),
1241        },
1242        ServerSourceKind::Git | ServerSourceKind::Registry => Ok(()),
1243    }
1244}
1245
1246/// A checkout being put in place: the new folder placed (moved from a
1247/// clone, or copied), the folder it replaces moved aside. [`Swap::finish`]
1248/// keeps the new one (and deletes the old) or undoes it all.
1249#[derive(Debug)]
1250struct Swap {
1251    target: PathBuf,
1252    aside: Option<PathBuf>,
1253    /// Where the new folder was moved from, to move it back on undo.
1254    moved_from: Option<PathBuf>,
1255}
1256
1257impl Swap {
1258    fn finish(self, fs: &dyn Fs, keep: bool) {
1259        if keep {
1260            if let Some(aside) = &self.aside {
1261                let _ = remove_dir(fs, aside);
1262            }
1263            return;
1264        }
1265        match &self.moved_from {
1266            Some(from) => {
1267                let _ = std::fs::rename(&self.target, from);
1268            }
1269            None => {
1270                let _ = remove_dir(fs, &self.target);
1271            }
1272        }
1273        if let Some(aside) = &self.aside {
1274            let _ = std::fs::rename(aside, &self.target);
1275        }
1276    }
1277}
1278
1279/// `<SURJECTION_HOME>/servers/.old-<id>-<ulid>`.
1280fn aside_path(sx: &SkillsEnv<'_>, id: &str) -> Result<PathBuf, CoreError> {
1281    Ok(sx.home.path.join(CHECKOUTS_DIR).join(format!(
1282        "{ASIDE_PREFIX}{id}-{}",
1283        ids::new_ulid(sx.env.now())?.to_ascii_lowercase()
1284    )))
1285}
1286
1287/// Moves the checkout of `id` aside, if there is one.
1288fn set_aside(sx: &SkillsEnv<'_>, id: &str) -> Result<Option<(PathBuf, PathBuf)>, CoreError> {
1289    let target = checkout_dir(sx, id);
1290    confine(sx.fs, &target)?;
1291    if !sx.fs.exists(&target) {
1292        return Ok(None);
1293    }
1294    let aside = aside_path(sx, id)?;
1295    std::fs::rename(&target, &aside)
1296        .map_err(|err| io_error("cannot move the old checkout aside", &target, &err))?;
1297    Ok(Some((aside, target)))
1298}
1299
1300/// Copies the tree `from` into `to` (a second checkout of one clone).
1301fn copy_tree(fs: &dyn Fs, from: &Path, to: &Path) -> Result<(), CoreError> {
1302    confine(fs, from)?;
1303    confine(fs, to)?;
1304    std::fs::create_dir_all(to).map_err(|err| io_error("cannot create directory", to, &err))?;
1305    let entries =
1306        std::fs::read_dir(from).map_err(|err| io_error("cannot list directory", from, &err))?;
1307    for entry in entries {
1308        let entry = entry.map_err(|err| io_error("cannot list directory", from, &err))?;
1309        let kind = entry
1310            .file_type()
1311            .map_err(|err| io_error("cannot read file metadata", &entry.path(), &err))?;
1312        let target = to.join(entry.file_name());
1313        if kind.is_dir() {
1314            copy_tree(fs, &entry.path(), &target)?;
1315        } else if kind.is_file() {
1316            std::fs::copy(entry.path(), &target)
1317                .map_err(|err| io_error("cannot copy file", &target, &err))?;
1318        }
1319    }
1320    Ok(())
1321}
1322
1323/// Puts `clone` in place as the checkout of `id` (moved, or copied with
1324/// `copy`), marked with `commit` and `url`; an existing checkout is moved
1325/// aside. On an error nothing is left changed.
1326fn place_checkout(
1327    sx: &SkillsEnv<'_>,
1328    clone: &Path,
1329    id: &str,
1330    copy: bool,
1331    commit: &str,
1332    url: &str,
1333) -> Result<Swap, CoreError> {
1334    let target = checkout_dir(sx, id);
1335    confine(sx.fs, clone)?;
1336    confine(sx.fs, &target)?;
1337    let aside = set_aside(sx, id)?.map(|(aside, _)| aside);
1338    let mut swap = Swap {
1339        target: target.clone(),
1340        aside,
1341        moved_from: None,
1342    };
1343    let place = |swap: &mut Swap| -> Result<(), CoreError> {
1344        if let Some(parent) = target.parent() {
1345            sx.fs
1346                .create_dir_all(parent)
1347                .map_err(|err| io_error("cannot create directory", parent, &err))?;
1348        }
1349        if copy {
1350            copy_tree(sx.fs, clone, &target)?;
1351        } else {
1352            std::fs::rename(clone, &target)
1353                .map_err(|err| io_error("cannot move the clone", &target, &err))?;
1354            swap.moved_from = Some(clone.to_path_buf());
1355        }
1356        let marker = marker_path(&target);
1357        sx.fs
1358            .write(&marker, marker_text(commit, url).as_bytes())
1359            .map_err(|err| io_error("cannot mark the checkout", &marker, &err))
1360    };
1361    if let Err(err) = place(&mut swap) {
1362        swap.finish(sx.fs, false);
1363        return Err(err);
1364    }
1365    Ok(swap)
1366}
1367
1368/// Checkouts of removed servers, moved aside under the store lock until
1369/// the removal commits ([`CheckoutRemoval::finish`]).
1370#[derive(Debug, Default)]
1371pub struct CheckoutRemoval {
1372    moved: Vec<(PathBuf, PathBuf)>,
1373}
1374
1375impl CheckoutRemoval {
1376    /// Moves the checkouts of `ids` aside (call it inside the removal's
1377    /// transaction).
1378    pub fn begin(sx: &SkillsEnv<'_>, ids: &[String]) -> Result<Self, CoreError> {
1379        let mut removal = Self::default();
1380        for id in ids {
1381            ids::check(ids::IdKind::Server, id)?;
1382            match set_aside(sx, id) {
1383                Ok(Some(pair)) => removal.moved.push(pair),
1384                Ok(None) => {}
1385                Err(err) => {
1386                    removal.finish(sx.fs, false);
1387                    return Err(err);
1388                }
1389            }
1390        }
1391        Ok(removal)
1392    }
1393
1394    /// Deletes the checkouts (`committed`) or puts them back.
1395    pub fn finish(self, fs: &dyn Fs, committed: bool) {
1396        for (aside, target) in self.moved {
1397            if committed {
1398                let _ = remove_dir(fs, &aside);
1399            } else {
1400                let _ = std::fs::rename(&aside, &target);
1401            }
1402        }
1403    }
1404}
1405
1406/// Removes temporary clones of resolves and checkouts moved aside that are
1407/// older than `older_than` (left by a crash or an app that ended with
1408/// reviews open). Returns how many were removed.
1409pub fn sweep_temp_clones(sx: &SkillsEnv<'_>, older_than: Duration) -> usize {
1410    let now = sx.env.now();
1411    let sweep = |dir: PathBuf, prefix: &str| {
1412        let Ok(entries) = std::fs::read_dir(&dir) else {
1413            return 0;
1414        };
1415        entries
1416            .flatten()
1417            .filter(|entry| entry.file_name().to_string_lossy().starts_with(prefix))
1418            .filter(|entry| {
1419                entry
1420                    .metadata()
1421                    .and_then(|meta| meta.modified())
1422                    .is_ok_and(|modified| {
1423                        now.duration_since(modified).unwrap_or_default() >= older_than
1424                    })
1425            })
1426            .filter(|entry| std::fs::remove_dir_all(entry.path()).is_ok())
1427            .count()
1428    };
1429    sweep(sx.home.cache_dir().join(TEMP_DIR), ".tmp-")
1430        + sweep(sx.home.path.join(CHECKOUTS_DIR), ASIDE_PREFIX)
1431}
1432
1433// -------------------------------------------------------------------- save
1434
1435/// One draft to save, as the user edited it.
1436#[derive(Debug, Clone)]
1437pub struct Pick {
1438    /// [`Draft::key`].
1439    pub key: String,
1440    /// The server to store: its id, launch fields, enablement and names as
1441    /// edited; `meta.origin` and `meta.source` are set from the draft.
1442    pub server: Server,
1443    /// The user's answer for what this draft runs, when it is gated on
1444    /// its own source ([`Draft::trust_source`]: registry entries, which
1445    /// can name several). `None` leaves it to [`Decisions::trust`] when
1446    /// the picks run from one source.
1447    pub trust: Option<TrustGrant>,
1448}
1449
1450/// What [`save`] did.
1451#[derive(Debug, Clone)]
1452pub struct Saved {
1453    pub ids: Vec<String>,
1454    pub commit: Option<CommitId>,
1455    pub apply: Option<ApplyReport>,
1456    /// The scan the gate checked: the folder's files and every saved
1457    /// launch line.
1458    pub scan: ScanReport,
1459}
1460
1461/// The server `pick` stores for `draft`.
1462fn picked_server(draft: &Draft, pick: &Pick) -> Result<Server, CoreError> {
1463    let mut server = pick.server.clone();
1464    ids::check(ids::IdKind::Server, &server.id)?;
1465    rename_id(&mut server, &draft.server.id, &pick.server.id);
1466    let meta = server.body.meta.get_or_insert_with(Meta::default);
1467    let draft_meta = draft.server.body.meta.as_ref();
1468    meta.origin = draft_meta.and_then(|m| m.origin.clone());
1469    let mut source = draft.provenance().clone();
1470    if draft.checkout {
1471        source.checkout = Some(true);
1472    }
1473    meta.source = Some(source);
1474    if meta.homepage.is_none() {
1475        meta.homepage = draft_meta.and_then(|m| m.homepage.clone());
1476    }
1477    if let Some(error) = server.validate(Some(&server.id)).first_error(None) {
1478        return Err(error);
1479    }
1480    Ok(server)
1481}
1482
1483/// Where a commit message says the servers come from: the URL, or the
1484/// folder (`${home}/...`, or only its name when it is outside the home
1485/// folder: no absolute path goes into history).
1486fn from_text(source: &ServerSource) -> String {
1487    if source.kind == ServerSourceKind::Registry {
1488        let entry = source.catalog.as_deref().unwrap_or_default();
1489        return match &source.version {
1490            Some(version) => format!("catalog {entry}@{version}"),
1491            None => format!("catalog {entry}"),
1492        };
1493    }
1494    let place = match (&source.url, &source.folder) {
1495        (Some(url), _) => url.clone(),
1496        (None, Some(folder)) if folder.starts_with("${home}") => folder.clone(),
1497        (None, Some(folder)) => format!("folder {}", name_of(folder)),
1498        (None, None) => String::new(),
1499    };
1500    match &source.commit {
1501        Some(commit) => format!("{place}@{}", &commit[..commit.len().min(7)]),
1502        None => place,
1503    }
1504}
1505
1506/// Stores the picked drafts (one commit, with the instant apply) when the
1507/// decisions let them through: the source must be trusted or
1508/// [`Decisions::trust`] carries the user's answer (`source_trust_required`,
1509/// `source_blocked`); then a `dangerous` scan of the folder's files and
1510/// every saved launch line needs [`Decisions::allow_dangerous`]
1511/// (`scan_blocked`). A taken id is `already_exists`. Checkouts are placed
1512/// under the store lock and undone when the commit fails; a local folder's
1513/// servers are bound to this machine. On an error `resolved` stays usable;
1514/// once saved it is spent.
1515pub fn save(
1516    store: &Store<'_>,
1517    sx: &SkillsEnv<'_>,
1518    ax: &ApplyEnv<'_>,
1519    resolved: &mut Resolved,
1520    picks: &[Pick],
1521    decisions: &Decisions,
1522) -> Result<Saved, CoreError> {
1523    if resolved.spent {
1524        return Err(CoreError::new(
1525            ErrorCode::InvalidValue,
1526            "these drafts are already saved",
1527        ));
1528    }
1529    if picks.is_empty() {
1530        return Err(CoreError::new(
1531            ErrorCode::InvalidValue,
1532            "pick at least one draft to save",
1533        ));
1534    }
1535    let mut servers: Vec<(Server, bool)> = Vec::new();
1536    let mut gated: Vec<(&Draft, Option<TrustGrant>)> = Vec::new();
1537    for pick in picks {
1538        let draft = resolved
1539            .drafts
1540            .iter()
1541            .find(|draft| draft.key == pick.key)
1542            .ok_or_else(|| {
1543                CoreError::new(ErrorCode::NotFound, format!("no draft {:?}", pick.key))
1544            })?;
1545        let server = picked_server(draft, pick)?;
1546        if servers.iter().any(|(other, _)| other.id == server.id)
1547            || store.server(&server.id)?.is_some()
1548        {
1549            return Err(CoreError::new(
1550                ErrorCode::AlreadyExists,
1551                format!("server {:?} already exists", server.id),
1552            ));
1553        }
1554        servers.push((server, draft.checkout));
1555        gated.push((draft, pick.trust));
1556    }
1557    resolved.admit(store, decisions, &gated)?;
1558    drop(gated);
1559    let scanner = Scanner::new(sx.fs, sx.home);
1560    let mut report = resolved.files_scan.clone();
1561    for (server, _) in &servers {
1562        report.merge(scan_commands(&scanner, server));
1563    }
1564    scan::gate(&report, decisions.allow_dangerous)?;
1565
1566    let ids: Vec<String> = servers
1567        .iter()
1568        .map(|(server, _)| server.id.clone())
1569        .collect();
1570    let from = from_text(&resolved.base);
1571    let summary = match ids.as_slice() {
1572        [one] => format!("server: add {one} from {from}"),
1573        many => format!(
1574            "server: add {} servers ({}) from {from}",
1575            many.len(),
1576            many.join(", ")
1577        ),
1578    };
1579    let operation = ids
1580        .iter()
1581        .fold(Operation::new("server.add", summary), |operation, id| {
1582            operation.entity(format!("server/{id}"))
1583        });
1584    let clone = resolved.clone.clone();
1585    let commit = resolved.base.commit.clone().unwrap_or_default();
1586    let url = resolved.base.url.clone().unwrap_or_default();
1587    let mut swaps: Vec<Swap> = Vec::new();
1588    let result = store.transaction(operation, |tx| {
1589        // Under the store lock: no other save or removal of these ids
1590        // runs between placing the checkouts and the commit.
1591        let wanted: Vec<&str> = servers
1592            .iter()
1593            .filter(|(_, checkout)| *checkout)
1594            .map(|(server, _)| server.id.as_str())
1595            .collect();
1596        if !wanted.is_empty() {
1597            let clone = clone.as_deref().ok_or_else(|| {
1598                CoreError::new(
1599                    ErrorCode::InvalidValue,
1600                    "the clone of this source is gone; resolve it again",
1601                )
1602            })?;
1603            // Copies first, then the move of the clone itself.
1604            for (index, id) in wanted.iter().enumerate() {
1605                let last = index + 1 == wanted.len();
1606                swaps.push(place_checkout(sx, clone, id, !last, &commit, &url)?);
1607            }
1608        }
1609        let machine = tx.machine().id.clone();
1610        for (server, _) in &servers {
1611            let mut server = server.clone();
1612            if let Some(source) = server.body.meta.as_mut().and_then(|m| m.source.as_mut())
1613                && source.kind == ServerSourceKind::Local
1614            {
1615                source.machine = Some(machine.clone());
1616            }
1617            tx.add_server(server)?;
1618        }
1619        instant_apply(tx, ax, &Touched::Servers(ids.clone()))
1620    });
1621    let keep = result.is_ok();
1622    let moved = swaps.iter().any(|swap| swap.moved_from.is_some());
1623    for swap in swaps {
1624        swap.finish(sx.fs, keep);
1625    }
1626    let committed = result?;
1627    resolved.spent = true;
1628    if moved {
1629        resolved.clone = None;
1630    }
1631    Ok(Saved {
1632        ids,
1633        commit: committed.commit,
1634        apply: committed.value,
1635        scan: report,
1636    })
1637}
1638
1639// ------------------------------------------------------------------ update
1640
1641/// One launch field that differs.
1642#[derive(Debug, Clone, PartialEq, Eq)]
1643pub struct FieldChange {
1644    /// `transport`, `command`, `args`, `url`, `cwd`, `env.NAME`,
1645    /// `headers.NAME`, each also as `os.<name>.<field>`.
1646    pub field: String,
1647    pub old: Option<String>,
1648    pub new: Option<String>,
1649}
1650
1651/// What [`check_update`] found.
1652#[derive(Debug, Clone)]
1653pub struct UpdateCheck {
1654    pub id: String,
1655    pub status: UpdateStatus,
1656    /// The commit the server came from.
1657    pub current: Option<String>,
1658    /// The source's commit now; for a local folder, the content hash of
1659    /// what was read (pass it to [`update`] as `expected`).
1660    pub latest: Option<String>,
1661    /// A registry entry's version now (its `latest` is the content hash
1662    /// of its `server.json`, so other content under one version is seen).
1663    pub version: Option<String>,
1664    pub changes: Vec<FieldChange>,
1665    /// Changed files of a checkout ([`SKIP_DIRS`] left out).
1666    pub files: Vec<FileChange>,
1667    /// The server an update stores.
1668    pub server: Option<Server>,
1669    /// The folder's files and every new launch line, when an update is
1670    /// available.
1671    pub scan: Option<ScanReport>,
1672    pub trust: Option<TrustCheck>,
1673    /// The trust check of where the host redirected the repository, when
1674    /// that is another source; an update needs its answer too.
1675    pub moved_trust: Option<TrustCheck>,
1676    pub source_change: Option<SourceChange>,
1677    pub runs_repo_code: bool,
1678    /// The setup steps of the new version ([`setup_text`]).
1679    pub setup: Vec<String>,
1680    /// The update replaces the checkout: what its setup steps installed
1681    /// there (dependencies, a build) has to be done again.
1682    pub setup_again: bool,
1683    /// This machine's checkout is missing or not at the commit the server
1684    /// file names; its entries are blocked until [`restore_checkout`].
1685    pub checkout_out_of_date: bool,
1686    pub error: Option<CoreError>,
1687}
1688
1689impl UpdateCheck {
1690    fn new(id: &str, status: UpdateStatus, current: Option<String>) -> Self {
1691        Self {
1692            id: id.to_owned(),
1693            status,
1694            current,
1695            latest: None,
1696            version: None,
1697            changes: Vec::new(),
1698            files: Vec::new(),
1699            server: None,
1700            scan: None,
1701            trust: None,
1702            moved_trust: None,
1703            source_change: None,
1704            runs_repo_code: false,
1705            setup: Vec::new(),
1706            setup_again: false,
1707            checkout_out_of_date: false,
1708            error: None,
1709        }
1710    }
1711}
1712
1713fn stored(store: &Store<'_>, id: &str) -> Result<(Server, Option<ServerSource>), CoreError> {
1714    ids::check(ids::IdKind::Server, id)?;
1715    let doc = store.server(id)?.ok_or_else(|| {
1716        CoreError::new(ErrorCode::NotFound, format!("server {id:?} does not exist"))
1717    })?;
1718    let server = doc.into_value();
1719    let source = server
1720        .body
1721        .meta
1722        .as_ref()
1723        .and_then(|meta| meta.source.clone());
1724    Ok((server, source))
1725}
1726
1727/// The `mcpServers` of the marketplace entry a catalog install came from,
1728/// read again from the catalog's cached index (no network): an update
1729/// drafts what the install drafted.
1730fn catalog_servers(store: &Store<'_>, sx: &SkillsEnv<'_>, catalog: Option<&str>) -> Option<String> {
1731    let (catalog, entry) = catalog?.split_once('/')?;
1732    crate::catalog::cached_entry(sx, Some(store), catalog, entry)
1733        .ok()?
1734        .mcp_servers
1735}
1736
1737fn request_of(
1738    store: &Store<'_>,
1739    sx: &SkillsEnv<'_>,
1740    source: &ServerSource,
1741) -> Result<ResolveRequest, CoreError> {
1742    match source.kind {
1743        ServerSourceKind::Git => {
1744            let url = source.url.clone().ok_or_else(|| {
1745                CoreError::new(ErrorCode::MissingField, "the git source has no url")
1746            })?;
1747            Ok(ResolveRequest {
1748                source: Source::Git {
1749                    url,
1750                    git_ref: None,
1751                    path: None,
1752                },
1753                git_ref: source.git_ref.clone(),
1754                path: source.path.clone(),
1755                catalog: source.catalog.clone(),
1756                mcp_servers: catalog_servers(store, sx, source.catalog.as_deref()),
1757            })
1758        }
1759        ServerSourceKind::Local => {
1760            let folder = source.folder.as_deref().ok_or_else(|| {
1761                CoreError::new(ErrorCode::MissingField, "the local source has no folder")
1762            })?;
1763            Ok(ResolveRequest::new(Source::Local(folder_of(sx, folder))))
1764        }
1765        ServerSourceKind::Registry => Err(CoreError::new(
1766            ErrorCode::InvalidValue,
1767            "a registry source is read through its catalog",
1768        )),
1769    }
1770}
1771
1772/// The value at `field` (`command`, `url`, `cwd`, `env.X`, `headers.X`,
1773/// `args[N]`, each optionally `os.<name>.`-prefixed) of `server`.
1774fn field_value<'a>(server: &'a Server, field: &str) -> Option<&'a str> {
1775    let (fields_command, fields_args, fields_url, fields_cwd, fields_env, fields_headers, rest) =
1776        match field.strip_prefix("os.") {
1777            Some(rest) => {
1778                let (os, rest) = rest.split_once('.')?;
1779                let over = &server.body.os.as_ref()?.get(os)?.fields;
1780                (
1781                    &over.command,
1782                    &over.args,
1783                    &over.url,
1784                    &over.cwd,
1785                    &over.env,
1786                    &over.headers,
1787                    rest,
1788                )
1789            }
1790            None => {
1791                let body = &server.body;
1792                (
1793                    &body.command,
1794                    &body.args,
1795                    &body.url,
1796                    &body.cwd,
1797                    &body.env,
1798                    &body.headers,
1799                    field,
1800                )
1801            }
1802        };
1803    match rest {
1804        "command" => fields_command.as_deref(),
1805        "url" => fields_url.as_deref(),
1806        "cwd" => fields_cwd.as_deref(),
1807        _ => {
1808            if let Some(name) = rest.strip_prefix("env.") {
1809                return fields_env.as_ref()?.get(name).map(String::as_str);
1810            }
1811            if let Some(name) = rest.strip_prefix("headers.") {
1812                return fields_headers.as_ref()?.get(name).map(String::as_str);
1813            }
1814            let index: usize = rest
1815                .strip_prefix("args[")?
1816                .strip_suffix(']')?
1817                .parse()
1818                .ok()?;
1819            fields_args
1820                .as_ref()?
1821                .get(index.checked_sub(1)?)
1822                .map(String::as_str)
1823        }
1824    }
1825}
1826
1827/// The first `${secret:<alias>}` alias in `text`.
1828fn secret_alias(text: &str) -> Option<&str> {
1829    let start = text.find("${secret:")? + "${secret:".len();
1830    let end = text[start..].find('}')?;
1831    Some(&text[start..start + end])
1832}
1833
1834/// Keeps the secret aliases `stored` uses: a re-read draft names its
1835/// secrets after a fresh id, so each one whose field already held a
1836/// reference gets that reference's alias back.
1837fn keep_aliases(proposed: &mut Server, stored: &Server, inputs: &[DraftInput]) {
1838    let renames: Vec<(String, String)> = inputs
1839        .iter()
1840        .filter(|input| input.secret)
1841        .filter_map(|input| {
1842            let new = input.alias.clone()?;
1843            let old = secret_alias(field_value(stored, &input.field)?)?.to_owned();
1844            (old != new).then_some((new, old))
1845        })
1846        .collect();
1847    if renames.is_empty() {
1848        return;
1849    }
1850    edit_server(proposed, &|value| {
1851        renames.iter().fold(value.to_owned(), |value, (new, old)| {
1852            value.replace(&format!("${{secret:{new}}}"), &format!("${{secret:{old}}}"))
1853        })
1854    });
1855}
1856
1857/// The fields of `a` and `b` that differ, named with `prefix`.
1858fn diff_fields(prefix: &str, a: &ServerFields, b: &ServerFields, changes: &mut Vec<FieldChange>) {
1859    let mut push = |field: &str, old: Option<String>, new: Option<String>| {
1860        if old != new {
1861            changes.push(FieldChange {
1862                field: format!("{prefix}{field}"),
1863                old,
1864                new,
1865            });
1866        }
1867    };
1868    push(
1869        "transport",
1870        a.transport.map(|t| t.as_str().to_owned()),
1871        b.transport.map(|t| t.as_str().to_owned()),
1872    );
1873    push("command", a.command.clone(), b.command.clone());
1874    let join = |args: &Option<Vec<String>>| args.as_ref().map(|args| args.join(" "));
1875    push("args", join(&a.args), join(&b.args));
1876    push("url", a.url.clone(), b.url.clone());
1877    push("cwd", a.cwd.clone(), b.cwd.clone());
1878    for (label, old, new) in [("env", &a.env, &b.env), ("headers", &a.headers, &b.headers)] {
1879        let keys: BTreeSet<&String> = old
1880            .iter()
1881            .flatten()
1882            .chain(new.iter().flatten())
1883            .map(|(k, _)| k)
1884            .collect();
1885        for key in keys {
1886            let get = |map: &Option<BTreeMap<String, String>>| {
1887                map.as_ref().and_then(|m| m.get(key).cloned())
1888            };
1889            push(&format!("{label}.{key}"), get(old), get(new));
1890        }
1891    }
1892}
1893
1894/// The launch fields that differ between `old` and `new`, base and each
1895/// override.
1896fn field_changes(old: &Server, new: &Server) -> Vec<FieldChange> {
1897    let mut changes = Vec::new();
1898    diff_fields("", &old.body.fields(), &new.body.fields(), &mut changes);
1899    let names: BTreeSet<&String> = old
1900        .body
1901        .os
1902        .iter()
1903        .flatten()
1904        .chain(new.body.os.iter().flatten())
1905        .map(|(name, _)| name)
1906        .collect();
1907    let empty = ServerFields::default();
1908    for name in names {
1909        let get = |server: &Server| {
1910            server
1911                .body
1912                .os
1913                .as_ref()
1914                .and_then(|os| os.get(name.as_str()))
1915                .map_or(empty.clone(), |over| over.fields.clone())
1916        };
1917        diff_fields(&format!("os.{name}."), &get(old), &get(new), &mut changes);
1918    }
1919    changes
1920}
1921
1922/// `stored` with `draft`'s launch fields and provenance under the stored
1923/// id: `env` and `headers` keys present before and after keep the stored
1924/// value, secret references keep their aliases, the machine a local folder
1925/// is bound to stays.
1926fn updated_server(stored: &Server, draft: &Draft) -> Server {
1927    let mut server = stored.clone();
1928    let mut fields = draft.server.body.fields();
1929    let keep = |new: &mut Option<BTreeMap<String, String>>,
1930                old: &Option<BTreeMap<String, String>>| {
1931        if let (Some(new), Some(old)) = (new.as_mut(), old.as_ref()) {
1932            for (key, value) in new.iter_mut() {
1933                if let Some(kept) = old.get(key) {
1934                    value.clone_from(kept);
1935                }
1936            }
1937        }
1938    };
1939    keep(&mut fields.env, &stored.body.env);
1940    keep(&mut fields.headers, &stored.body.headers);
1941    set_launch(&mut server, &fields);
1942    server.body.os = draft.server.body.os.clone();
1943    rename_id(&mut server, &draft.server.id, &stored.id);
1944    keep_aliases(&mut server, stored, &draft.inputs);
1945    let machine = stored
1946        .body
1947        .meta
1948        .as_ref()
1949        .and_then(|meta| meta.source.as_ref())
1950        .and_then(|source| source.machine.clone());
1951    let meta = server.body.meta.get_or_insert_with(Meta::default);
1952    let mut source = draft.provenance().clone();
1953    source.machine = machine;
1954    meta.source = Some(source);
1955    server
1956}
1957
1958/// Files that differ between a checkout and the source now.
1959fn file_changes(old: &SkillFiles, new: &SkillFiles) -> Vec<FileChange> {
1960    let paths: BTreeSet<&String> = old.keys().chain(new.keys()).collect();
1961    paths
1962        .into_iter()
1963        .filter_map(|path| {
1964            let kind = match (old.get(path), new.get(path)) {
1965                (Some(a), Some(b)) if a == b => return None,
1966                (Some(_), Some(_)) => ChangeKind::Modified,
1967                (None, Some(_)) => ChangeKind::Added,
1968                (Some(_), None) => ChangeKind::Removed,
1969                (None, None) => return None,
1970            };
1971            let script = kind != ChangeKind::Removed
1972                && new
1973                    .get(path)
1974                    .is_some_and(|bytes| looks_executable(path, bytes));
1975            Some(FileChange {
1976                path: path.clone(),
1977                kind,
1978                script,
1979            })
1980        })
1981        .collect()
1982}
1983
1984/// The folder of `id`'s checkout that holds the server's files.
1985fn checkout_folder(sx: &SkillsEnv<'_>, id: &str, source: &ServerSource) -> PathBuf {
1986    let dir = checkout_dir(sx, id);
1987    match &source.path {
1988        Some(path) => join_rel(&dir, path),
1989        None => dir,
1990    }
1991}
1992
1993/// This machine's id, if it has one yet.
1994fn this_machine(sx: &SkillsEnv<'_>) -> Result<Option<String>, CoreError> {
1995    Ok(Machine::load(sx.fs, &sx.home.state_dir())?.map(|machine| machine.id))
1996}
1997
1998/// The check and what an update would store.
1999struct Latest {
2000    check: UpdateCheck,
2001    resolved: Option<Resolved>,
2002}
2003
2004fn latest(store: &Store<'_>, sx: &SkillsEnv<'_>, id: &str) -> Result<Latest, CoreError> {
2005    let (server, source) = stored(store, id)?;
2006    let Some(source) = source else {
2007        return Ok(Latest {
2008            check: UpdateCheck::new(id, UpdateStatus::NotTracked, None),
2009            resolved: None,
2010        });
2011    };
2012    let registry = source.kind == ServerSourceKind::Registry;
2013    let current = if registry {
2014        source.version.clone()
2015    } else {
2016        source.commit.clone()
2017    };
2018    let mut check = UpdateCheck::new(id, UpdateStatus::UpToDate, current.clone());
2019    check.checkout_out_of_date =
2020        source.uses_checkout() && !checkout_current(sx.fs, &sx.home.path, id, &source);
2021    let gated = match source.kind {
2022        ServerSourceKind::Git => source
2023            .url
2024            .as_deref()
2025            .and_then(|url| SourceRef::from_git_url(url).ok()),
2026        ServerSourceKind::Local => source
2027            .folder
2028            .as_deref()
2029            .map(|f| folder_of(sx, f))
2030            .and_then(|folder| SourceRef::from_local_path(&folder).ok()),
2031        // Its trust source is in the entry, read below.
2032        ServerSourceKind::Registry => None,
2033    };
2034    let not_fetched = |mut check: UpdateCheck,
2035                       status: UpdateStatus,
2036                       err: CoreError|
2037     -> Result<Latest, CoreError> {
2038        check.status = status;
2039        check.trust = gated
2040            .as_ref()
2041            .map(|source| sources::check(store, source))
2042            .transpose()?;
2043        check.error = Some(err);
2044        Ok(Latest {
2045            check,
2046            resolved: None,
2047        })
2048    };
2049    if source.kind == ServerSourceKind::Local
2050        && let Some(machine) = &source.machine
2051        && this_machine(sx)?.as_ref() != Some(machine)
2052    {
2053        let err = CoreError::new(
2054            ErrorCode::FolderOnOtherMachine,
2055            "added from a folder on another machine; check it there",
2056        );
2057        return not_fetched(check, UpdateStatus::Unreachable, err);
2058    }
2059    let pinned = match source.kind {
2060        ServerSourceKind::Git => source.git_ref.as_deref().is_some_and(is_commit_ref),
2061        ServerSourceKind::Registry => source.git_ref.is_some(),
2062        ServerSourceKind::Local => false,
2063    };
2064    if pinned {
2065        // Pinned to a commit or a registry version: nothing to follow.
2066        check.latest = current;
2067        return Ok(Latest {
2068            check,
2069            resolved: None,
2070        });
2071    }
2072    let resolved = if registry {
2073        crate::catalog::registry_latest(store, sx, &source)
2074            .and_then(|request| resolve_registry(Some(store), sx, &request))
2075    } else {
2076        request_of(store, sx, &source).and_then(|request| resolve(Some(store), sx, &request))
2077    };
2078    let resolved = match resolved {
2079        Ok(resolved) => resolved,
2080        Err(err) if err.code() == ErrorCode::SourceBlocked => {
2081            return not_fetched(check, UpdateStatus::Blocked, err);
2082        }
2083        // Whatever stops the read (unreachable, gone, too large) is this
2084        // server's result, not an error of the whole check.
2085        Err(err) => return not_fetched(check, UpdateStatus::Unreachable, err),
2086    };
2087    let latest_commit = match source.kind {
2088        ServerSourceKind::Git => resolved.base.commit.clone(),
2089        ServerSourceKind::Local => Some(content_hash(&resolved.files)),
2090        // The content, not the version string: a registry serving other
2091        // content under the same version is another update to review.
2092        ServerSourceKind::Registry => Some(content_hash(&resolved.files)),
2093    };
2094    let mut change = resolved.source_change.clone();
2095    if change.is_none()
2096        && let (Some(old), Some(new), Some(clone), Some(url)) = (
2097            source.commit.as_deref(),
2098            resolved.base.commit.as_deref(),
2099            resolved.clone.as_deref(),
2100            source.url.as_deref(),
2101        )
2102    {
2103        let git = git_path(sx)?;
2104        let in_clone = |args: &[&OsStr]| run_git(sx, &git, clone, args);
2105        if sources::detect::history_rewritten(&in_clone, url, source.git_ref.as_deref(), old, new)?
2106        {
2107            change = Some(SourceChange {
2108                kind: SourceChangeKind::HistoryRewritten,
2109                detail: None,
2110            });
2111        }
2112    }
2113    if let (Some(gated), Some(change)) = (resolved.trust_source(), &change) {
2114        sources::lapse(store, gated, change)?;
2115    }
2116    check.trust = resolved
2117        .trust_source()
2118        .map(|source| sources::check(store, source))
2119        .transpose()?;
2120    check.moved_trust = resolved
2121        .moved_source()
2122        .map(|source| sources::check(store, source))
2123        .transpose()?;
2124    check.source_change = change;
2125    check.latest.clone_from(&latest_commit);
2126    if registry {
2127        check.version.clone_from(&resolved.base.version);
2128    }
2129    let Some(draft) = resolved.drafts.iter().find(|draft| {
2130        let p = draft.provenance();
2131        p.file == source.file && p.converter == source.converter && p.entry == source.entry
2132    }) else {
2133        let err = CoreError::new(
2134            ErrorCode::SourceUnreachable,
2135            format!(
2136                "the source no longer holds this server ({}{})",
2137                source.file,
2138                source
2139                    .entry
2140                    .as_deref()
2141                    .map(|entry| format!(" {entry}"))
2142                    .unwrap_or_default()
2143            ),
2144        );
2145        return not_fetched(check, UpdateStatus::Unreachable, err);
2146    };
2147    if let Some(own) = &draft.trust_source {
2148        check.trust = Some(sources::check(store, own)?);
2149        if let Err(err) = sources::refuse_blocked(store, own) {
2150            check.status = UpdateStatus::Blocked;
2151            check.error = Some(err);
2152            return Ok(Latest {
2153                check,
2154                resolved: None,
2155            });
2156        }
2157    }
2158    let proposed = updated_server(&server, draft);
2159    check.changes = field_changes(&server, &proposed);
2160    check.setup = rename_steps(&draft.setup, &draft.server.id, id);
2161    if draft.checkout {
2162        let folder = checkout_folder(sx, id, &source);
2163        if sx.fs.is_dir(&folder) {
2164            match read_source(sx.fs, &folder) {
2165                Ok((files, _)) => check.files = file_changes(&files, &resolved.files),
2166                Err(err) => return not_fetched(check, UpdateStatus::Unreachable, err),
2167            }
2168        }
2169    }
2170    let moved_on = match source.kind {
2171        ServerSourceKind::Git => current.is_some() && resolved.base.commit != current,
2172        ServerSourceKind::Registry => current.is_some() && resolved.base.version != current,
2173        ServerSourceKind::Local => false,
2174    };
2175    if !check.changes.is_empty() || moved_on || !check.files.is_empty() {
2176        check.status = UpdateStatus::Available;
2177        check.setup_again = draft.checkout && !check.setup.is_empty();
2178        let scanner = Scanner::new(sx.fs, sx.home);
2179        let mut scan = resolved.files_scan.clone();
2180        scan.merge(scan_commands(&scanner, &proposed));
2181        check.scan = Some(scan);
2182    }
2183    check.runs_repo_code = draft.runs_repo_code;
2184    check.server = Some(proposed);
2185    Ok(Latest {
2186        check,
2187        resolved: Some(resolved),
2188    })
2189}
2190
2191/// Checks a source server for an update: reads its source again (a fresh
2192/// temporary clone, or the folder) and compares the definition it gives
2193/// now with the stored one. Whatever stops the read (unreachable, gone,
2194/// too large, a folder of another machine) is reported in the check, not
2195/// returned as an error. A force-push or a move of a trusted source makes
2196/// its trust lapse (one store commit).
2197pub fn check_update(
2198    store: &Store<'_>,
2199    sx: &SkillsEnv<'_>,
2200    id: &str,
2201) -> Result<UpdateCheck, CoreError> {
2202    Ok(latest(store, sx, id)?.check)
2203}
2204
2205/// What [`update`] did.
2206#[derive(Debug, Clone)]
2207pub struct Updated {
2208    pub id: String,
2209    pub from: Option<String>,
2210    pub to: Option<String>,
2211    pub changes: Vec<FieldChange>,
2212    pub commit: Option<CommitId>,
2213    pub apply: Option<ApplyReport>,
2214    /// `None` when nothing was updated (up to date).
2215    pub scan: Option<ScanReport>,
2216}
2217
2218/// Updates a source server to what its source gives now (one commit,
2219/// `server: update <id> to <sha7>`, with the instant apply): the launch
2220/// fields are replaced, `env` and `headers` values of keys kept keep the
2221/// stored value, secret references keep their aliases, a checkout is
2222/// replaced: the new one is built beside the old, committed, then swapped
2223/// (the old stays when anything fails). `expected` is what the user
2224/// reviewed (the commit, or a folder's content hash): another one is
2225/// `entry_changed`. The gates are those of [`save`]. Nothing is written
2226/// when it is up to date.
2227pub fn update(
2228    store: &Store<'_>,
2229    sx: &SkillsEnv<'_>,
2230    ax: &ApplyEnv<'_>,
2231    id: &str,
2232    expected: Option<&str>,
2233    decisions: &Decisions,
2234) -> Result<Updated, CoreError> {
2235    let Latest { check, resolved } = latest(store, sx, id)?;
2236    match check.status {
2237        UpdateStatus::NotTracked => {
2238            return Err(CoreError::new(
2239                ErrorCode::InvalidValue,
2240                format!("server {id:?} does not come from a git repository, folder or catalog"),
2241            ));
2242        }
2243        UpdateStatus::Unreachable | UpdateStatus::Blocked => {
2244            return Err(check.error.unwrap_or_else(|| {
2245                CoreError::new(ErrorCode::SourceUnreachable, "the source cannot be reached")
2246            }));
2247        }
2248        _ => {}
2249    }
2250    if let Some(expected) = expected
2251        && check.latest.as_deref() != Some(expected)
2252    {
2253        return Err(CoreError::new(
2254            ErrorCode::EntryChanged,
2255            "the source changed since it was checked; check again and review it",
2256        ));
2257    }
2258    let (Some(mut resolved), Some(server), UpdateStatus::Available) =
2259        (resolved, check.server.clone(), check.status)
2260    else {
2261        return Ok(Updated {
2262            id: id.to_owned(),
2263            from: check.current.clone(),
2264            to: check.version.clone().or_else(|| check.latest.clone()),
2265            changes: Vec::new(),
2266            commit: None,
2267            apply: None,
2268            scan: check.scan,
2269        });
2270    };
2271    let source = server
2272        .body
2273        .meta
2274        .as_ref()
2275        .and_then(|meta| meta.source.clone())
2276        .expect("a source server");
2277    let gated: Vec<(&Draft, Option<TrustGrant>)> = resolved
2278        .drafts
2279        .iter()
2280        .filter(|draft| {
2281            let p = draft.provenance();
2282            p.file == source.file && p.converter == source.converter && p.entry == source.entry
2283        })
2284        .map(|draft| (draft, None))
2285        .collect();
2286    resolved.admit(store, decisions, &gated)?;
2287    drop(gated);
2288    let scan = check.scan.clone().expect("an available update is scanned");
2289    scan::gate(&scan, decisions.allow_dangerous)?;
2290    let summary = match source.kind {
2291        ServerSourceKind::Git => {
2292            let commit = source.commit.as_deref().unwrap_or_default();
2293            format!("server: update {id} to {}", &commit[..commit.len().min(7)])
2294        }
2295        ServerSourceKind::Registry => format!(
2296            "server: update {id} to {}",
2297            source.version.as_deref().unwrap_or_default()
2298        ),
2299        ServerSourceKind::Local => format!("server: update {id} from its folder"),
2300    };
2301    let mut doc = store.server(id)?.ok_or_else(|| {
2302        CoreError::new(ErrorCode::NotFound, format!("server {id:?} does not exist"))
2303    })?;
2304    *doc.value_mut() = server;
2305    let text = doc.to_text()?;
2306    let operation = Operation::new("server.update", summary).entity(format!("server/{id}"));
2307    let clone = resolved.clone.clone();
2308    let mut swap: Option<Swap> = None;
2309    let result = store.transaction(operation, |tx| {
2310        if source.uses_checkout() {
2311            let clone = clone.as_deref().ok_or_else(|| {
2312                CoreError::new(ErrorCode::InvalidValue, "the clone of this source is gone")
2313            })?;
2314            swap = Some(place_checkout(
2315                sx,
2316                clone,
2317                id,
2318                false,
2319                source.commit.as_deref().unwrap_or_default(),
2320                source.url.as_deref().unwrap_or_default(),
2321            )?);
2322        }
2323        tx.write(&server_path(id)?, text)?;
2324        instant_apply(tx, ax, &Touched::Servers(vec![id.to_owned()]))
2325    });
2326    if let Some(swap) = swap {
2327        if result.is_ok() && swap.moved_from.is_some() {
2328            resolved.clone = None;
2329        }
2330        swap.finish(sx.fs, result.is_ok());
2331    }
2332    let committed = result?;
2333    Ok(Updated {
2334        id: id.to_owned(),
2335        from: check.current,
2336        to: check.version.or(check.latest),
2337        changes: check.changes,
2338        commit: committed.commit,
2339        apply: committed.value,
2340        scan: Some(scan),
2341    })
2342}
2343
2344// ----------------------------------------------------------------- restore
2345
2346/// A checkout fetched for [`restore_checkout`]: the repository at the
2347/// commit the server file names, scanned with the stored launch lines.
2348#[derive(Debug)]
2349pub struct PreparedCheckout {
2350    id: String,
2351    resolved: Resolved,
2352    scan: ScanReport,
2353    commit: String,
2354    url: String,
2355}
2356
2357impl PreparedCheckout {
2358    pub fn id(&self) -> &str {
2359        &self.id
2360    }
2361
2362    pub fn commit(&self) -> &str {
2363        &self.commit
2364    }
2365
2366    /// The repository's files and every launch line of the stored server.
2367    pub fn scan(&self) -> &ScanReport {
2368        &self.scan
2369    }
2370
2371    pub fn trust_source(&self) -> Option<&SourceRef> {
2372        self.resolved.trust_source()
2373    }
2374
2375    /// Where the host redirected the repository (asked about too).
2376    pub fn moved_source(&self) -> Option<&SourceRef> {
2377        self.resolved.moved_source()
2378    }
2379
2380    pub fn source_change(&self) -> Option<&SourceChange> {
2381        self.resolved.source_change()
2382    }
2383}
2384
2385/// Fetches what this machine's checkout of source server `id` should hold
2386/// (another machine saved or updated it, or it was removed): the
2387/// repository at the recorded commit, into a temporary clone. `None` when
2388/// the checkout is already current. A blocked source is not contacted.
2389pub fn prepare_checkout(
2390    store: &Store<'_>,
2391    sx: &SkillsEnv<'_>,
2392    id: &str,
2393) -> Result<Option<PreparedCheckout>, CoreError> {
2394    let (server, source) = stored(store, id)?;
2395    let source = source.filter(ServerSource::uses_checkout).ok_or_else(|| {
2396        CoreError::new(
2397            ErrorCode::InvalidValue,
2398            format!("server {id:?} does not run from a checkout"),
2399        )
2400    })?;
2401    if checkout_current(sx.fs, &sx.home.path, id, &source) {
2402        return Ok(None);
2403    }
2404    let (Some(url), Some(commit)) = (source.url.clone(), source.commit.clone()) else {
2405        return Err(CoreError::new(
2406            ErrorCode::MissingField,
2407            "the git source has no url or commit",
2408        ));
2409    };
2410    let request = ResolveRequest {
2411        source: Source::Git {
2412            url: url.clone(),
2413            git_ref: None,
2414            path: None,
2415        },
2416        git_ref: Some(commit.clone()),
2417        path: source.path.clone(),
2418        catalog: source.catalog.clone(),
2419        mcp_servers: catalog_servers(store, sx, source.catalog.as_deref()),
2420    };
2421    let resolved = resolve(Some(store), sx, &request)?;
2422    let scanner = Scanner::new(sx.fs, sx.home);
2423    let mut scan = resolved.files_scan.clone();
2424    scan.merge(scan_commands(&scanner, &server));
2425    Ok(Some(PreparedCheckout {
2426        id: id.to_owned(),
2427        resolved,
2428        scan,
2429        commit,
2430        url,
2431    }))
2432}
2433
2434/// Puts a prepared checkout in place under the store lock, after the same
2435/// gates as a save: trust in the source (and a redirect target), then the
2436/// scan of its files and the stored launch lines (`allow_dangerous`). A
2437/// stale checkout is replaced atomically; the server's entries are applied
2438/// again.
2439pub fn restore_checkout(
2440    store: &Store<'_>,
2441    sx: &SkillsEnv<'_>,
2442    ax: &ApplyEnv<'_>,
2443    mut prepared: PreparedCheckout,
2444    decisions: &Decisions,
2445) -> Result<Option<ApplyReport>, CoreError> {
2446    prepared.resolved.admit(store, decisions, &[])?;
2447    scan::gate(&prepared.scan, decisions.allow_dangerous)?;
2448    let clone = prepared.resolved.clone.clone().ok_or_else(|| {
2449        CoreError::new(ErrorCode::InvalidValue, "the clone of this source is gone")
2450    })?;
2451    let id = prepared.id.clone();
2452    let operation = Operation::new(
2453        "server.checkout",
2454        format!(
2455            "server: check out {id} at {}",
2456            &prepared.commit[..7.min(prepared.commit.len())]
2457        ),
2458    )
2459    .entity(format!("server/{id}"));
2460    let mut swap: Option<Swap> = None;
2461    let result = store.transaction(operation, |tx| {
2462        swap = Some(place_checkout(
2463            sx,
2464            &clone,
2465            &id,
2466            false,
2467            &prepared.commit,
2468            &prepared.url,
2469        )?);
2470        instant_apply(tx, ax, &Touched::Servers(vec![id.clone()]))
2471    });
2472    if let Some(swap) = swap {
2473        if result.is_ok() && swap.moved_from.is_some() {
2474            prepared.resolved.clone = None;
2475        }
2476        swap.finish(sx.fs, result.is_ok());
2477    }
2478    Ok(result?.value)
2479}
2480
2481/// Removes the machine-local checkout of `id`, if any.
2482pub fn remove_checkout(sx: &SkillsEnv<'_>, id: &str) -> Result<(), CoreError> {
2483    ids::check(ids::IdKind::Server, id)?;
2484    let dir = checkout_dir(sx, id);
2485    confine(sx.fs, &dir)?;
2486    remove_dir(sx.fs, &dir)
2487}