Skip to main content

surjection_core/migrate/
skilldock.rs

1// Portions derived from SkillDock (https://github.com/DailenG/skilldock), MIT, Copyright (c) 2026 wanghuan
2
3//! SkillDock's data folder (`~/.skilldock`), read only: its MCP registry,
4//! settings, skill tags and skill library, and the mapping of one registry
5//! record to a store server (SPEC 15.1).
6//!
7//! Shapes follow SkillDock's `mcp_manager.rs` (`McpServerRecord`,
8//! `McpPersistence`), `state.rs` (`SettingsPersistence`,
9//! `SkillTagPersistence`), `models.rs` (`WorkspacePersistence`) and
10//! `workspace.rs` (the `config/`, `data/`, `credentials/` layout and the
11//! older top-level files). Every field is read leniently: SkillDock wrote
12//! some of them only in later versions.
13//!
14//! Records SkillDock synced with disabled tools were written to clients
15//! through a wrapper: `npx -y mcp-filter --include <tool>... -- <command>
16//! <args>...` for stdio servers and `npx -y mcp-remote@latest <url>
17//! [--transport http-only|sse-only] [--allow-http] [--header N:V]...
18//! [--ignore-tool <tool>]...` for remote ones. [`unwrap`] turns both back
19//! into the native server plus a tool filter.
20
21use std::collections::{BTreeMap, BTreeSet};
22use std::path::{Path, PathBuf};
23
24use serde_json::{Map, Value};
25
26use crate::adapters::adapter;
27use crate::adapters::caps::{Caps, FieldSet};
28use crate::apply::render::native_to_template;
29use crate::error::{CoreError, ErrorCode};
30use crate::fs::Fs;
31use crate::model::clients::{ClientSelection, NATIVE_NAME_KEY};
32use crate::model::ids::{self, IdKind};
33use crate::model::server::{Enable, Meta, Server, ToolFilter, Transport};
34use crate::secrets::classify::{classify_import, find_in_text};
35use crate::secrets::extract::{Aliases, Extraction, Extractor};
36
37/// SkillDock's data folder under the home folder.
38pub const DIR: &str = ".skilldock";
39/// The folder of SkillDock's first releases (`skillm`), read for its MCP
40/// registry only.
41pub const LEGACY_DIR: &str = ".skillm";
42/// `meta.origin` of a migrated server.
43pub const ORIGIN: &str = "migrated:skilldock";
44
45/// Where SkillDock kept its MCP registry, newest layout first.
46pub const MCP_FILES: [&str; 3] = [
47    "~/.skilldock/config/mcp-servers.json",
48    "~/.skilldock/mcp-servers.json",
49    "~/.skillm/mcp-servers.json",
50];
51/// Settings, newest layout first.
52pub const SETTINGS_FILES: [&str; 2] = [
53    "~/.skilldock/config/settings.json",
54    "~/.skilldock/settings.json",
55];
56/// Workspace state (installed skills and, in older versions, tags).
57pub const STATE_FILES: [&str; 2] = ["~/.skilldock/data/state.json", "~/.skilldock/state.json"];
58/// Skill tags, newest layout first.
59pub const TAG_FILES: [&str; 2] = [
60    "~/.skilldock/data/skill-tags.json",
61    "~/.skilldock/skill-tags.json",
62];
63/// The skill library.
64pub const SKILLS_DIR: &str = "~/.skilldock/skills";
65/// SkillDock's GitHub credential.
66pub const GITHUB_CREDENTIAL: &str = "~/.skilldock/credentials/github.json";
67/// SkillDock's backup repository (a working copy).
68pub const BACKUP_REPO: &str = "~/.skilldock/backup/repo";
69
70/// `~/...` display path as an absolute path under `home`.
71pub fn resolve(home: &Path, display: &str) -> PathBuf {
72    let rest = display.strip_prefix("~/").unwrap_or(display);
73    rest.split('/')
74        .fold(home.to_path_buf(), |path, part| path.join(part))
75}
76
77/// The first of `candidates` that exists, as `(display, path)`.
78pub fn first_existing(fs: &dyn Fs, home: &Path, candidates: &[&str]) -> Option<(String, PathBuf)> {
79    candidates.iter().find_map(|display| {
80        let path = resolve(home, display);
81        fs.exists(&path).then(|| ((*display).to_owned(), path))
82    })
83}
84
85/// Reads a JSON file; `parse_error` names the display path, never the
86/// content.
87pub fn read_json(fs: &dyn Fs, path: &Path, display: &str) -> Result<Value, CoreError> {
88    let text = fs.read_to_string(path).map_err(|err| {
89        CoreError::new(ErrorCode::IoError, format!("cannot read {display}: {err}"))
90    })?;
91    let text = text.strip_prefix('\u{feff}').unwrap_or(&text);
92    serde_json::from_str(text).map_err(|err| {
93        CoreError::new(
94            ErrorCode::ParseError,
95            format!("{display} is not valid JSON (line {})", err.line()),
96        )
97    })
98}
99
100/// One `McpServerRecord`.
101#[derive(Debug, Clone, PartialEq)]
102pub struct Record {
103    /// The key SkillDock wrote into client files.
104    pub id: String,
105    pub name: String,
106    /// The server definition as SkillDock kept it (client JSON shape).
107    pub server: Value,
108    pub description: String,
109    pub source_url: String,
110    pub enabled_app_ids: Vec<String>,
111    pub imported_from_app_ids: Vec<String>,
112    pub managed_app_ids: Vec<String>,
113    /// `(tool, is_enabled)`.
114    pub tools: Vec<(String, bool)>,
115    /// `plugin` for records a SkillDock plugin installed.
116    pub lifecycle_source: String,
117    pub owner_plugin_name: String,
118    /// SkillDock app ids that were renamed to Surjection client ids
119    /// ([`APP_RENAMES`]), as `(skilldock, surjection)`.
120    pub renamed: Vec<(String, String)>,
121}
122
123impl Record {
124    /// Whether a SkillDock plugin owns the record (plugins are not
125    /// migrated).
126    pub fn plugin_owned(&self) -> bool {
127        self.lifecycle_source == "plugin" || !self.owner_plugin_name.is_empty()
128    }
129}
130
131fn text(map: &Map<String, Value>, key: &str) -> String {
132    map.get(key)
133        .and_then(Value::as_str)
134        .map(str::trim)
135        .unwrap_or_default()
136        .to_owned()
137}
138
139fn texts(map: &Map<String, Value>, key: &str) -> Vec<String> {
140    let mut out: Vec<String> = Vec::new();
141    for item in map.get(key).and_then(Value::as_array).into_iter().flatten() {
142        if let Some(item) = item.as_str().map(str::trim).filter(|s| !s.is_empty())
143            && !out.iter().any(|known| known == item)
144        {
145            out.push(item.to_owned());
146        }
147    }
148    out
149}
150
151/// SkillDock app ids that name a Surjection client differently: SkillDock's
152/// `github-copilot` writes `~/.copilot/mcp-config.json`, Surjection's
153/// `copilot` user file (`mcp_manager.rs` `APP_GITHUB_COPILOT`).
154pub const APP_RENAMES: [(&str, &str); 1] = [("github-copilot", "copilot")];
155
156/// An app id list with [`APP_RENAMES`] applied (deduplicated, in order).
157fn app_ids(
158    map: &Map<String, Value>,
159    key: &str,
160    renamed: &mut Vec<(String, String)>,
161) -> Vec<String> {
162    let mut out: Vec<String> = Vec::new();
163    for id in texts(map, key) {
164        let id = match APP_RENAMES.iter().find(|(from, _)| *from == id) {
165            Some((from, to)) => {
166                if !renamed.iter().any(|(known, _)| known == from) {
167                    renamed.push(((*from).to_owned(), (*to).to_owned()));
168                }
169                (*to).to_owned()
170            }
171            None => id,
172        };
173        if !out.contains(&id) {
174            out.push(id);
175        }
176    }
177    out
178}
179
180/// The records of an MCP registry file (`{ "servers": [...] }`, or a bare
181/// array in the oldest files). A record that is not an object or has no
182/// id is an error of its own, so the others still migrate.
183pub fn parse_records(doc: &Value) -> Result<Vec<Result<Record, CoreError>>, CoreError> {
184    let items = match doc {
185        Value::Array(items) => items,
186        Value::Object(map) => match map.get("servers") {
187            Some(Value::Array(items)) => items,
188            None => return Ok(Vec::new()),
189            Some(_) => {
190                return Err(CoreError::new(
191                    ErrorCode::UnexpectedShape,
192                    "`servers` is not a list",
193                ));
194            }
195        },
196        _ => {
197            return Err(CoreError::new(
198                ErrorCode::UnexpectedShape,
199                "the MCP registry is not an object",
200            ));
201        }
202    };
203    Ok(items
204        .iter()
205        .enumerate()
206        .map(|(index, item)| {
207            let map = item.as_object().ok_or_else(|| {
208                CoreError::new(
209                    ErrorCode::UnexpectedShape,
210                    format!("record {} is not an object", index + 1),
211                )
212            })?;
213            let id = text(map, "id");
214            let name = text(map, "name");
215            let id = if id.is_empty() { name.clone() } else { id };
216            if id.is_empty() {
217                return Err(CoreError::new(
218                    ErrorCode::MissingField,
219                    format!("record {} has no id or name", index + 1),
220                ));
221            }
222            let tools = map
223                .get("tools")
224                .and_then(Value::as_array)
225                .into_iter()
226                .flatten()
227                .filter_map(|tool| {
228                    let tool = tool.as_object()?;
229                    let name = text(tool, "name");
230                    let enabled = tool
231                        .get("isEnabled")
232                        .and_then(Value::as_bool)
233                        .unwrap_or(true);
234                    (!name.is_empty()).then_some((name, enabled))
235                })
236                .collect();
237            let mut renamed = Vec::new();
238            Ok(Record {
239                name: if name.is_empty() { id.clone() } else { name },
240                id,
241                server: map.get("server").cloned().unwrap_or(Value::Null),
242                description: text(map, "description"),
243                source_url: text(map, "sourceUrl"),
244                enabled_app_ids: app_ids(map, "enabledAppIds", &mut renamed),
245                imported_from_app_ids: app_ids(map, "importedFromAppIds", &mut renamed),
246                managed_app_ids: app_ids(map, "managedAppIds", &mut renamed),
247                tools,
248                lifecycle_source: text(map, "lifecycleSource"),
249                owner_plugin_name: text(map, "ownerPluginName"),
250                renamed,
251            })
252        })
253        .collect())
254}
255
256/// The last component of a path SkillDock recorded (`/` or `\`
257/// separators): the skill folder it names.
258fn folder_of(path: &str) -> Option<String> {
259    path.trim()
260        .trim_end_matches(['/', '\\'])
261        .rsplit(['/', '\\'])
262        .next()
263        .map(str::trim)
264        .filter(|name| !name.is_empty())
265        .map(str::to_owned)
266}
267
268/// Whether a SkillDock skill reference (lower-cased `name`, optional skill
269/// `folder`) names the skill in `folder_name` whose names are `names`:
270/// by folder when SkillDock recorded a path, else by lower-cased name.
271fn names_skill(name: &str, folder: Option<&str>, folder_name: &str, names: &[&str]) -> bool {
272    match folder {
273        Some(folder) => folder.eq_ignore_ascii_case(folder_name),
274        None => names.iter().any(|n| n.trim().to_lowercase() == name),
275    }
276}
277
278/// One SkillDock skill tag. SkillDock allowed one tag per skill; its keys
279/// are `"<lower-cased name>\n<normalized skill path>"` (`state.rs`
280/// `skill_tag_key`), older ones the lower-cased name alone, and
281/// `installedSkills[].tag` repeats it.
282#[derive(Debug, Clone, PartialEq, Eq)]
283pub struct TagEntry {
284    /// The lower-cased skill name.
285    pub name: String,
286    /// The skill folder from the key's path, if the key has one.
287    pub folder: Option<String>,
288    pub tag: String,
289}
290
291impl TagEntry {
292    /// Whether the tag belongs to the skill in `folder_name` named `names`.
293    pub fn matches(&self, folder_name: &str, names: &[&str]) -> bool {
294        names_skill(&self.name, self.folder.as_deref(), folder_name, names)
295    }
296}
297
298/// The `skillTags` map of `skill-tags.json` or `state.json`.
299pub fn parse_tags(doc: &Value, into: &mut Vec<TagEntry>) {
300    let Some(tags) = doc.get("skillTags").and_then(Value::as_object) else {
301        return;
302    };
303    for (key, tag) in tags {
304        let Some(tag) = tag.as_str().map(str::trim).filter(|tag| !tag.is_empty()) else {
305            continue;
306        };
307        let (name, folder) = match key.split_once('\n') {
308            Some((name, path)) => (name, folder_of(path)),
309            None => (key.as_str(), None),
310        };
311        push_tag(
312            into,
313            TagEntry {
314                name: name.trim().to_lowercase(),
315                folder,
316                tag: tag.to_owned(),
317            },
318        );
319    }
320}
321
322fn push_tag(into: &mut Vec<TagEntry>, entry: TagEntry) {
323    if !into.contains(&entry) {
324        into.push(entry);
325    }
326}
327
328/// What `state.json` recorded about an installed skill.
329#[derive(Debug, Clone, Default, PartialEq, Eq)]
330pub struct InstalledSkill {
331    /// The lower-cased skill name.
332    pub name: String,
333    /// The skill folder (`canonicalPath`, else `localPath`).
334    pub folder: Option<String>,
335    pub source_type: String,
336    pub source_url: String,
337    pub branch: String,
338    /// `tag`, flattened from SkillDock's `SkillInstanceMetadata`.
339    pub tag: String,
340}
341
342impl InstalledSkill {
343    /// Whether this is the skill in `folder_name` named `names`.
344    pub fn matches(&self, folder_name: &str, names: &[&str]) -> bool {
345        names_skill(&self.name, self.folder.as_deref(), folder_name, names)
346    }
347}
348
349/// `installedSkills` of `state.json`; their embedded tags are added to
350/// `tags`.
351pub fn parse_installed(doc: &Value, tags: &mut Vec<TagEntry>) -> Vec<InstalledSkill> {
352    let mut out = Vec::new();
353    for item in doc
354        .get("installedSkills")
355        .and_then(Value::as_array)
356        .into_iter()
357        .flatten()
358    {
359        let Some(map) = item.as_object() else {
360            continue;
361        };
362        let name = text(map, "name").to_lowercase();
363        if name.is_empty() {
364            continue;
365        }
366        let canonical = text(map, "canonicalPath");
367        let path = if canonical.is_empty() {
368            text(map, "localPath")
369        } else {
370            canonical
371        };
372        let skill = InstalledSkill {
373            name,
374            folder: folder_of(&path),
375            source_type: text(map, "sourceType"),
376            source_url: text(map, "sourceUrl"),
377            branch: text(map, "branch"),
378            tag: text(map, "tag"),
379        };
380        if !skill.tag.is_empty() {
381            push_tag(
382                tags,
383                TagEntry {
384                    name: skill.name.clone(),
385                    folder: skill.folder.clone(),
386                    tag: skill.tag.clone(),
387                },
388            );
389        }
390        out.push(skill);
391    }
392    out
393}
394
395/// A record as a store server.
396#[derive(Debug, Clone)]
397pub struct Mapped {
398    pub server: Server,
399    /// The wrapper the definition was unwrapped from (`mcp-filter`,
400    /// `mcp-remote`).
401    pub unwrapped: Option<&'static str>,
402    pub extractions: Vec<Extraction>,
403    /// The command is an absolute path on this machine.
404    pub machine_path: bool,
405    /// Definition keys with no store field (dropped).
406    pub dropped: Vec<String>,
407    /// Client ids Surjection has no adapter for (kept in the enable list).
408    pub unknown_clients: Vec<String>,
409    /// Informational notes (renamed client ids).
410    pub notes: Vec<String>,
411    /// What needs a look (dropped wrapper env keys, a homepage left out).
412    pub review: Vec<String>,
413}
414
415/// The parts of a SkillDock server definition.
416#[derive(Debug, Clone, Default, PartialEq)]
417struct Raw {
418    transport: Option<Transport>,
419    command: Option<String>,
420    args: Vec<String>,
421    cwd: Option<String>,
422    url: Option<String>,
423    env: BTreeMap<String, String>,
424    headers: BTreeMap<String, String>,
425    /// From an `mcp-filter --include` list.
426    allow: Vec<String>,
427    /// From `mcp-remote --ignore-tool`.
428    deny: Vec<String>,
429    /// `env` keys of an `mcp-remote` wrapper its headers and URL did not
430    /// use (dropped: a remote server has no environment).
431    unused_env: Vec<String>,
432}
433
434/// `text` with each `${NAME}` that `env` defines replaced by its value;
435/// the names used go to `used`. The wrapper's shell expanded them inside
436/// its own process, so they are not variables of this machine.
437fn substitute(text: &str, env: &BTreeMap<String, String>, used: &mut BTreeSet<String>) -> String {
438    let mut out = String::new();
439    let mut rest = text;
440    while let Some(start) = rest.find("${") {
441        let after = &rest[start + 2..];
442        match after.find('}') {
443            Some(end) if env.contains_key(&after[..end]) => {
444                let name = &after[..end];
445                out.push_str(&rest[..start]);
446                out.push_str(&env[name]);
447                used.insert(name.to_owned());
448                rest = &after[end + 1..];
449            }
450            _ => {
451                out.push_str(&rest[..start + 2]);
452                rest = after;
453            }
454        }
455    }
456    out.push_str(rest);
457    out
458}
459
460fn is_filter(arg: &str) -> bool {
461    arg == "mcp-filter" || arg.ends_with("/mcp-filter") || arg.starts_with("mcp-filter@")
462}
463
464fn is_remote(arg: &str) -> bool {
465    arg == "mcp-remote" || arg.starts_with("mcp-remote@") || arg.ends_with("/mcp-remote")
466}
467
468/// The wrapper an entry's `command` and `args` use, if any: SkillDock's
469/// `mcp-filter` or `mcp-remote` in the first arguments of `npx`.
470pub fn wrapper_kind(command: Option<&str>, args: &[String]) -> Option<&'static str> {
471    let command = command?;
472    let program = command
473        .rsplit(['/', '\\'])
474        .next()
475        .unwrap_or(command)
476        .trim_end_matches(".cmd")
477        .trim_end_matches(".exe");
478    if program != "npx" {
479        return None;
480    }
481    let first = args.iter().take(3).find(|arg| !arg.starts_with('-'))?;
482    if is_filter(first) {
483        Some("mcp-filter")
484    } else if is_remote(first) {
485        Some("mcp-remote")
486    } else {
487        None
488    }
489}
490
491/// The definition inside a SkillDock wrapper, or `None` when `raw` is not
492/// one or cannot be read back.
493fn unwrap(raw: &Raw) -> Option<(Raw, &'static str)> {
494    let kind = wrapper_kind(raw.command.as_deref(), &raw.args)?;
495    let args = &raw.args;
496    let start = args.iter().position(|arg| !arg.starts_with('-'))? + 1;
497    match kind {
498        "mcp-filter" => {
499            let delimiter = args.iter().position(|arg| arg == "--")?;
500            let command = args.get(delimiter + 1)?.trim();
501            if command.is_empty() || delimiter < start {
502                return None;
503            }
504            let mut allow = Vec::new();
505            let mut index = start;
506            while index < delimiter {
507                if args[index] == "--include"
508                    && let Some(tool) = args.get(index + 1).map(|t| t.trim())
509                {
510                    if !tool.is_empty() && !allow.iter().any(|known| known == tool) {
511                        allow.push(tool.to_owned());
512                    }
513                    index += 2;
514                } else {
515                    index += 1;
516                }
517            }
518            Some((
519                Raw {
520                    transport: Some(Transport::Stdio),
521                    command: Some(command.to_owned()),
522                    args: args[delimiter + 2..].to_vec(),
523                    cwd: raw.cwd.clone(),
524                    env: raw.env.clone(),
525                    allow,
526                    ..Raw::default()
527                },
528                kind,
529            ))
530        }
531        _ => {
532            let url = args.get(start)?.trim();
533            if !(url.starts_with("http://") || url.starts_with("https://")) {
534                return None;
535            }
536            let mut inner = Raw {
537                transport: Some(Transport::Http),
538                url: Some(url.to_owned()),
539                ..Raw::default()
540            };
541            let mut index = start + 1;
542            while index < args.len() {
543                let value = args.get(index + 1);
544                match (args[index].as_str(), value) {
545                    ("--transport", Some(mode)) => {
546                        inner.transport = Some(match mode.as_str() {
547                            "sse-only" | "sse-first" => Transport::Sse,
548                            _ => Transport::Http,
549                        });
550                        index += 2;
551                    }
552                    ("--header", Some(header)) => {
553                        let (name, value) = header.split_once(':')?;
554                        inner
555                            .headers
556                            .insert(name.trim().to_owned(), value.trim().to_owned());
557                        index += 2;
558                    }
559                    ("--ignore-tool", Some(tool)) => {
560                        if !inner.deny.iter().any(|known| known == tool) {
561                            inner.deny.push(tool.clone());
562                        }
563                        index += 2;
564                    }
565                    ("--allow-http", _) => index += 1,
566                    _ => return None,
567                }
568            }
569            // The wrapper's `env` fed its own `${NAME}` expansion; a remote
570            // server has no environment.
571            let mut used = BTreeSet::new();
572            inner.url = inner.url.map(|url| substitute(&url, &raw.env, &mut used));
573            for value in inner.headers.values_mut() {
574                *value = substitute(value, &raw.env, &mut used);
575            }
576            inner.unused_env = raw
577                .env
578                .keys()
579                .filter(|k| !used.contains(*k))
580                .cloned()
581                .collect();
582            Some((inner, kind))
583        }
584    }
585}
586
587const KNOWN_KEYS: [&str; 7] = ["type", "command", "args", "env", "url", "headers", "cwd"];
588
589fn read_raw(server: &Value, dropped: &mut Vec<String>) -> Result<Raw, CoreError> {
590    let map = server.as_object().ok_or_else(|| {
591        CoreError::new(
592            ErrorCode::UnexpectedShape,
593            "the server definition is not an object",
594        )
595    })?;
596    let shape = |field: &str, expected: &str| {
597        CoreError::new(
598            ErrorCode::UnexpectedShape,
599            format!("`{field}` is not {expected}"),
600        )
601    };
602    let string = |key: &str| -> Result<Option<String>, CoreError> {
603        match map.get(key) {
604            None | Some(Value::Null) => Ok(None),
605            Some(Value::String(text)) if text.trim().is_empty() => Ok(None),
606            Some(Value::String(text)) => Ok(Some(text.clone())),
607            Some(_) => Err(shape(key, "a string")),
608        }
609    };
610    let string_map = |key: &str| -> Result<BTreeMap<String, String>, CoreError> {
611        match map.get(key) {
612            None | Some(Value::Null) => Ok(BTreeMap::new()),
613            Some(Value::Object(items)) => items
614                .iter()
615                .map(|(name, value)| match value {
616                    Value::String(text) => Ok((name.clone(), text.clone())),
617                    Value::Number(_) | Value::Bool(_) => Ok((name.clone(), value.to_string())),
618                    _ => Err(shape(&format!("{key}.{name}"), "a string")),
619                })
620                .collect(),
621            Some(_) => Err(shape(key, "an object")),
622        }
623    };
624    let args = match map.get("args") {
625        None | Some(Value::Null) => Vec::new(),
626        Some(Value::Array(items)) => items
627            .iter()
628            .map(|item| match item {
629                Value::String(text) => Ok(text.clone()),
630                Value::Number(_) | Value::Bool(_) => Ok(item.to_string()),
631                _ => Err(shape("args", "a list of strings")),
632            })
633            .collect::<Result<_, _>>()?,
634        Some(_) => return Err(shape("args", "a list")),
635    };
636    let command = string("command")?;
637    let url = string("url")?;
638    let transport = match string("type")?.as_deref() {
639        Some("stdio") => Some(Transport::Stdio),
640        Some("http" | "streamable-http" | "streamableHttp" | "streamable_http") => {
641            Some(Transport::Http)
642        }
643        Some("sse") => Some(Transport::Sse),
644        Some(other) => {
645            return Err(CoreError::new(
646                ErrorCode::UnsupportedTransport,
647                format!("transport {other:?} has no store equivalent"),
648            ));
649        }
650        None if command.is_some() => Some(Transport::Stdio),
651        None if url.is_some() => Some(Transport::Http),
652        None => None,
653    };
654    for key in map.keys() {
655        if !KNOWN_KEYS.contains(&key.as_str()) {
656            dropped.push(key.clone());
657        }
658    }
659    Ok(Raw {
660        transport,
661        command,
662        args,
663        cwd: string("cwd")?,
664        url,
665        env: string_map("env")?,
666        headers: string_map("headers")?,
667        allow: Vec::new(),
668        deny: Vec::new(),
669        unused_env: Vec::new(),
670    })
671}
672
673/// Whether `command` names a program by an absolute path (or `~`), which
674/// only holds on this machine (SkillDock rewrote `npx` and friends to
675/// `~/.local/bin/...` shims).
676pub fn is_machine_path(command: &str) -> bool {
677    let bytes = command.as_bytes();
678    command.starts_with('/')
679        || command.starts_with('~')
680        || command.starts_with("\\\\")
681        || (bytes.len() > 2
682            && bytes[0].is_ascii_alphabetic()
683            && bytes[1] == b':'
684            && matches!(bytes[2], b'\\' | b'/'))
685}
686
687/// Maps a record to store server `id`. Sensitive literals are replaced by
688/// `${secret:<alias>}` references and listed in [`Mapped::extractions`];
689/// the values are dropped.
690pub fn map_record(record: &Record, id: &str, aliases: &mut Aliases) -> Result<Mapped, CoreError> {
691    ids::check(IdKind::Server, id)?;
692    let mut dropped = Vec::new();
693    let raw = read_raw(&record.server, &mut dropped)?;
694    let (raw, unwrapped) = match unwrap(&raw) {
695        Some((inner, kind)) => (inner, Some(kind)),
696        None if wrapper_kind(raw.command.as_deref(), &raw.args).is_some() => {
697            return Err(CoreError::new(
698                ErrorCode::UnexpectedShape,
699                "a SkillDock wrapper whose arguments cannot be read back",
700            ));
701        }
702        None => (raw, None),
703    };
704    let Some(transport) = raw.transport else {
705        return Err(CoreError::new(
706            ErrorCode::MissingField,
707            "the definition has neither `command` nor `url`",
708        ));
709    };
710    let caps = &adapter(crate::adapters::claude_code::ID)
711        .and_then(|spec| spec.mcp.as_ref())
712        .expect("Claude Code has MCP")
713        .caps;
714    let mut extractor = Extractor::new(id, aliases);
715    let mut server = Server::new(id);
716    let body = &mut server.body;
717    body.transport = Some(transport);
718    if let Some(command) = &raw.command {
719        body.command = Some(convert(caps, command, FieldSet::COMMAND)?);
720    }
721    if !raw.args.is_empty() {
722        let args = raw
723            .args
724            .iter()
725            .map(|arg| convert(caps, arg, FieldSet::ARGS))
726            .collect::<Result<Vec<_>, _>>()?;
727        body.args = Some(extractor.args(args));
728    }
729    if let Some(cwd) = &raw.cwd {
730        body.cwd = Some(convert(caps, cwd, FieldSet::CWD)?);
731    }
732    if let Some(url) = &raw.url {
733        let url = convert(caps, url, FieldSet::URL)?;
734        body.url = Some(extractor.url(url)?);
735    }
736    for (field, source, label) in [
737        (FieldSet::ENV, &raw.env, "env"),
738        (FieldSet::HEADERS, &raw.headers, "headers"),
739    ] {
740        let mut map = BTreeMap::new();
741        for (name, value) in source {
742            map.insert(name.clone(), convert(caps, value, field)?);
743        }
744        let map = extractor.map(label, map);
745        let map = (!map.is_empty()).then_some(map);
746        match label {
747            "env" => body.env = map,
748            _ => body.headers = map,
749        }
750    }
751    // The migration keeps no value: the wizard asks for each one.
752    let extractions: Vec<Extraction> = extractor
753        .finish()
754        .into_iter()
755        .map(|extracted| extracted.extraction)
756        .collect();
757    let disabled: Vec<String> = record
758        .tools
759        .iter()
760        .filter(|(_, enabled)| !enabled)
761        .map(|(name, _)| name.clone())
762        .collect();
763    let mut deny = raw.deny.clone();
764    for tool in disabled {
765        if !deny.contains(&tool) {
766            deny.push(tool);
767        }
768    }
769    deny.sort();
770    let mut allow = raw.allow.clone();
771    allow.sort();
772    if !deny.is_empty() || !allow.is_empty() {
773        body.tools = Some(ToolFilter {
774            // A deny list says the same as the wrapper's include list.
775            allow: (deny.is_empty() && !allow.is_empty()).then_some(allow),
776            deny: (!deny.is_empty()).then_some(deny),
777            extra: toml::Table::new(),
778        });
779    }
780    if record.name != id {
781        body.display_name = Some(record.name.clone());
782    }
783    if !record.description.is_empty() {
784        body.description = Some(record.description.clone());
785    }
786    let mut notes = Vec::new();
787    let mut review = Vec::new();
788    for (from, to) in &record.renamed {
789        notes.push(format!("SkillDock's {from} is {to}"));
790    }
791    if !raw.unused_env.is_empty() {
792        review.push(format!(
793            "the wrapper's env keys its headers did not use were dropped: {}",
794            raw.unused_env.join(", ")
795        ));
796    }
797    // SkillDock kept `sourceUrl` as given; one with credentials would fail
798    // the store's leak scan and with it the whole migration.
799    let homepage = (!record.source_url.is_empty()).then(|| record.source_url.clone());
800    let homepage = match homepage {
801        Some(url) if classify_import(None, &url).is_some() || !find_in_text(&url).is_empty() => {
802            review.push(
803                "the source URL may hold a credential and was left out of meta.homepage".to_owned(),
804            );
805            None
806        }
807        other => other,
808    };
809    body.meta = Some(Meta {
810        homepage,
811        origin: Some(ORIGIN.to_owned()),
812        ..Meta::default()
813    });
814    let mut unknown_clients = Vec::new();
815    for client in &record.enabled_app_ids {
816        if adapter(client).is_none() {
817            unknown_clients.push(client.clone());
818        }
819    }
820    if record.id != id {
821        // The native key stays SkillDock's, so existing entries match.
822        let mut clients = BTreeMap::new();
823        for client in record
824            .enabled_app_ids
825            .iter()
826            .chain(&record.managed_app_ids)
827            .chain(&record.imported_from_app_ids)
828        {
829            if adapter(client).is_some() {
830                let mut table = toml::Table::new();
831                table.insert(
832                    NATIVE_NAME_KEY.to_owned(),
833                    toml::Value::String(record.id.clone()),
834                );
835                clients.insert(client.clone(), table);
836            }
837        }
838        body.client = (!clients.is_empty()).then_some(clients);
839    }
840    if !record.enabled_app_ids.is_empty() {
841        server.enable = Some(Enable {
842            clients: Some(ClientSelection::List(record.enabled_app_ids.clone())),
843            extra: toml::Table::new(),
844        });
845    }
846    if let Some(err) = server.validate(Some(id)).first_error(None) {
847        return Err(err);
848    }
849    let machine_path = server.body.command.as_deref().is_some_and(is_machine_path);
850    Ok(Mapped {
851        server,
852        unwrapped,
853        extractions,
854        machine_path,
855        dropped,
856        unknown_clients,
857        notes,
858        review,
859    })
860}
861
862fn convert(caps: &Caps, text: &str, field: FieldSet) -> Result<String, CoreError> {
863    native_to_template(text, caps, field).ok_or_else(|| {
864        CoreError::new(
865            ErrorCode::UnsupportedField,
866            "a value uses a variable form the store cannot express (`${NAME:-default}`)",
867        )
868    })
869}
870
871/// `settings.json` fields and how they map (SPEC 15.1): theme, agents CLI
872/// compatibility, install activation. The rest is listed as skipped.
873#[derive(Debug, Clone, Default, PartialEq)]
874pub struct SkillDockSettings {
875    pub fields: Map<String, Value>,
876}
877
878impl SkillDockSettings {
879    pub fn parse(doc: &Value) -> Result<Self, CoreError> {
880        match doc {
881            Value::Object(fields) => Ok(Self {
882                fields: fields.clone(),
883            }),
884            _ => Err(CoreError::new(
885                ErrorCode::UnexpectedShape,
886                "settings are not an object",
887            )),
888        }
889    }
890
891    pub fn text(&self, key: &str) -> Option<&str> {
892        self.fields
893            .get(key)
894            .and_then(Value::as_str)
895            .map(str::trim)
896            .filter(|value| !value.is_empty())
897    }
898
899    pub fn bool(&self, key: &str) -> Option<bool> {
900        self.fields.get(key).and_then(Value::as_bool)
901    }
902}