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