Skip to main content

surjection_core/migrate/
mod.rs

1//! Migration from SkillDock (SPEC 15.1): `~/.skilldock` into the store.
2//!
3//! `~/.skilldock` is read only; nothing in it is modified or deleted.
4//! [`plan`] is the dry run: it reads SkillDock's data, maps it, runs the
5//! post-migration scan ([`scan`]) and returns the [`Report`] without
6//! creating or writing anything. [`apply`] tags the store
7//! (`auto/pre-migrate/<ts>`), maps again inside one transaction and commits
8//! everything as one commit (`migrate: skilldock (...)`, tagged
9//! `auto/post-migrate/<ts>`), then records the
10//! skill links found pointing into SkillDock's library in the ledger (the
11//! next skills sync re-points them to the store copy) and bare-clones
12//! SkillDock's backup repository to `<SURJECTION_HOME>/imports`. No client
13//! file is written: the first apply is a separate, previewed step.
14//!
15//! What maps where:
16//!
17//! - MCP registry records: one `servers/<id>.toml` each; `enabledAppIds`
18//!   to `enable.clients`; disabled tools to `[tools] deny`; SkillDock's
19//!   `mcp-filter` / `mcp-remote` wrappers unwrapped; plaintext values that
20//!   may be secrets replaced by `${secret:<alias>}` and listed in
21//!   [`Report::extractions`] for the extraction wizard (the values are
22//!   never kept); absolute commands kept and flagged. Plugin-owned records
23//!   are skipped.
24//! - Skills in `~/.skilldock/skills/<name>`: content without `.git` into
25//!   `skills/<id>/`, metadata (tags, git remote and HEAD as `[source]`,
26//!   clients from the links on disk) into `skill-meta/<id>.toml`.
27//! - Settings: theme, agents CLI compatibility and install activation into
28//!   `settings.toml`; the rest listed as skipped.
29//! - Credentials, the backup repository, plugins and SkillHub data: listed
30//!   with what to do; secrets are never copied.
31
32pub mod loadout;
33pub mod scan;
34pub mod skilldock;
35
36use std::collections::{BTreeMap, BTreeSet};
37use std::path::{Path, PathBuf};
38use std::sync::Arc;
39
40use serde::Serialize;
41
42use crate::apply::ApplyEnv;
43use crate::apply::ledger::{Ledger, LedgerKey};
44use crate::apply::render::DesiredState;
45use crate::brand;
46use crate::error::{CoreError, ErrorCode};
47use crate::fs::Fs;
48use crate::model::TomlDocument;
49use crate::model::clients::ClientSelection;
50use crate::model::server::Server;
51use crate::model::settings::{NewItemEnable, Settings, Theme};
52use crate::model::skill_meta::{
53    DistributionMethod, SkillEnable, SkillMeta, SkillSource, SkillSourceKind,
54};
55use crate::secrets::classify::{classify_import, find_in_text};
56use crate::secrets::extract::{self, Aliases, Extraction, ExtractionChoice};
57use crate::secrets::scanner::{ALLOWLIST_FILE, Allowlist, SecretMemory, scan_text};
58use crate::skills::install::Source;
59use crate::skills::link::{SkillLedger, SkillLink};
60use crate::skills::store::{SKILLS_DIR, meta_path, read_meta};
61use crate::skills::{SKILL_FILE, frontmatter, read_folder, slug};
62use crate::store::{
63    CommitId, LOCK_TIMEOUT, Machine, Operation, Store, StoreLock, StoreRead, server_path,
64    utc_datetime,
65};
66
67use scan::{FoundLink, MigratedServer};
68use skilldock::{InstalledSkill, Record, SkillDockSettings, TagEntry};
69
70/// `auto/<kind>/<ts>` tag made before a migration.
71pub const TAG_KIND: &str = "pre-migrate";
72/// `auto/<kind>/<ts>` tag on the migration commit.
73pub const POST_TAG_KIND: &str = "post-migrate";
74/// Where SkillDock's backup repository is bare-cloned, under
75/// `<SURJECTION_HOME>/imports`.
76pub const BACKUP_IMPORT: &str = "skilldock-backup.git";
77const SETTINGS_FILE: &str = "settings.toml";
78
79/// What a report item is about.
80#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize)]
81#[serde(rename_all = "snake_case")]
82pub enum ItemKind {
83    /// An MCP registry record.
84    Server,
85    /// A skill folder in SkillDock's library.
86    Skill,
87    /// A `settings.json` field.
88    Setting,
89    /// A client entry of a migrated server (`<client>/<name>`).
90    ClientEntry,
91    /// A link in a client skill folder into SkillDock's library.
92    SkillLink,
93    Credential,
94    Backup,
95    Plugin,
96    Skillhub,
97    /// Any other file or folder of `~/.skilldock`.
98    File,
99}
100
101impl ItemKind {
102    pub const fn as_str(self) -> &'static str {
103        match self {
104            ItemKind::Server => "server",
105            ItemKind::Skill => "skill",
106            ItemKind::Setting => "setting",
107            ItemKind::ClientEntry => "client_entry",
108            ItemKind::SkillLink => "skill_link",
109            ItemKind::Credential => "credential",
110            ItemKind::Backup => "backup",
111            ItemKind::Plugin => "plugin",
112            ItemKind::Skillhub => "skillhub",
113            ItemKind::File => "file",
114        }
115    }
116}
117
118/// What happened to an item (SPEC 15.1: migrated, needs review, skipped
119/// with a reason).
120#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize)]
121#[serde(rename_all = "snake_case")]
122pub enum ItemStatus {
123    Migrated,
124    NeedsReview,
125    Skipped,
126}
127
128impl ItemStatus {
129    pub const fn as_str(self) -> &'static str {
130        match self {
131            ItemStatus::Migrated => "migrated",
132            ItemStatus::NeedsReview => "needs_review",
133            ItemStatus::Skipped => "skipped",
134        }
135    }
136}
137
138/// A follow-up the wizard offers for an item. Commands name ids and
139/// entries, never paths.
140#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
141#[serde(tag = "kind", rename_all = "snake_case")]
142pub enum Offer {
143    /// "Replace SkillDock wrapper": overwrite the client's wrapped entry
144    /// with the native definition (adopting it).
145    ReplaceWrapper {
146        client: String,
147        name: String,
148        command: String,
149    },
150    /// A different native entry: overwrite it, or keep the client's version.
151    ReviewEntry {
152        client: String,
153        name: String,
154        command: String,
155    },
156    /// A value replaced by a reference: store it (extraction wizard).
157    SetSecret { alias: String, command: String },
158    /// An absolute command: move it into `[os.*]` or the machine overlay.
159    MachinePath { server: String },
160    /// SkillDock's GitHub token: move it into the OS keyring for a `token`
161    /// remote. Never copied into the store.
162    KeyringToken { command: String },
163    /// SkillDock's GitHub backup repository: add it as a git remote.
164    AddRemote { url: String },
165}
166
167/// One line of the report.
168#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
169pub struct Item {
170    pub kind: ItemKind,
171    /// Record id, skill folder, setting key, `<client>/<name>`, or a
172    /// `~/.skilldock/...` path.
173    pub name: String,
174    pub status: ItemStatus,
175    pub detail: String,
176    /// The error code behind a review or skip, if any.
177    pub code: Option<&'static str>,
178    /// The store id it became (server or skill), if any.
179    pub id: Option<String>,
180    pub offers: Vec<Offer>,
181}
182
183impl Item {
184    pub fn new(
185        kind: ItemKind,
186        name: impl Into<String>,
187        status: ItemStatus,
188        detail: impl Into<String>,
189        code: Option<&'static str>,
190    ) -> Self {
191        Self {
192            kind,
193            name: name.into(),
194            status,
195            detail: detail.into(),
196            code,
197            id: None,
198            offers: Vec::new(),
199        }
200    }
201
202    fn skipped(kind: ItemKind, name: impl Into<String>, detail: impl Into<String>) -> Self {
203        Self::new(kind, name, ItemStatus::Skipped, detail, None)
204    }
205
206    fn error(kind: ItemKind, name: impl Into<String>, status: ItemStatus, err: &CoreError) -> Self {
207        Self::new(kind, name, status, err.message(), Some(err.code().as_str()))
208    }
209}
210
211/// The migration report: every item found, with its outcome.
212#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize)]
213pub struct Report {
214    /// `~/.skilldock`.
215    pub source: String,
216    pub items: Vec<Item>,
217    /// Plaintext values routed to the extraction wizard.
218    pub extractions: Vec<Extraction>,
219    /// Store server ids created.
220    pub servers: Vec<String>,
221    /// Store skill ids created.
222    pub skills: Vec<String>,
223}
224
225impl Report {
226    /// `(migrated, needs review, skipped)`.
227    pub fn counts(&self) -> (usize, usize, usize) {
228        let count = |status| self.items.iter().filter(|i| i.status == status).count();
229        (
230            count(ItemStatus::Migrated),
231            count(ItemStatus::NeedsReview),
232            count(ItemStatus::Skipped),
233        )
234    }
235}
236
237/// A computed migration: the report and what [`apply`] writes.
238#[derive(Debug, Clone)]
239pub struct Migration {
240    pub report: Report,
241    /// Store-relative path to content.
242    files: BTreeMap<String, Vec<u8>>,
243    links: Vec<SkillLink>,
244    backup: Option<PathBuf>,
245}
246
247impl Migration {
248    /// Store-relative paths the migration writes, sorted.
249    pub fn files(&self) -> impl Iterator<Item = &str> {
250        self.files.keys().map(String::as_str)
251    }
252}
253
254/// What [`apply`] did.
255#[derive(Debug, Clone)]
256pub struct Applied {
257    pub report: Report,
258    /// `auto/pre-migrate/<ts>`, on the store as it was.
259    pub tag: String,
260    /// `None` when nothing was left to migrate.
261    pub commit: Option<CommitId>,
262    /// `auto/post-migrate/<ts>` on the migration commit (SPEC 9.4).
263    pub post_tag: Option<String>,
264    /// `imports/skilldock-backup.git`, when the backup was cloned now.
265    pub backup_import: Option<String>,
266}
267
268/// `~/.skilldock`.
269pub fn source_dir(ax: &ApplyEnv<'_>) -> PathBuf {
270    ax.env.home().join(skilldock::DIR)
271}
272
273/// Whether there is SkillDock data to migrate (`~/.skilldock`, or the
274/// registry of `~/.skillm`).
275pub fn source_exists(ax: &ApplyEnv<'_>) -> bool {
276    ax.fs.is_dir(&source_dir(ax))
277        || ax
278            .fs
279            .exists(&skilldock::resolve(ax.env.home(), skilldock::MCP_FILES[2]))
280}
281
282fn require_source(ax: &ApplyEnv<'_>) -> Result<(), CoreError> {
283    if source_exists(ax) {
284        Ok(())
285    } else {
286        Err(CoreError::new(
287            ErrorCode::NotFound,
288            "no SkillDock data at ~/.skilldock",
289        ))
290    }
291}
292
293/// The dry run: the migration as [`apply`] would make it now. Creates and
294/// writes nothing (no store, ledger key, lock or file).
295pub fn plan(store: Option<&Store<'_>>, ax: &ApplyEnv<'_>) -> Result<Migration, CoreError> {
296    require_source(ax)?;
297    let memory = match store {
298        Some(store) => store.secret_memory().clone(),
299        None => Arc::new(SecretMemory::new()?),
300    };
301    build(ax, store.map(|s| s as &dyn StoreRead), memory)
302}
303
304/// [`apply_with_choices`] without extraction choices (the CLI: values are
305/// set afterwards with `surject secrets set`).
306pub fn apply(store: &Store<'_>, ax: &ApplyEnv<'_>) -> Result<Applied, CoreError> {
307    apply_with_choices(store, ax, &[])
308}
309
310/// Migrates: tags the store `auto/pre-migrate/<ts>`, commits the mapped
311/// files as one commit (tagged `auto/post-migrate/<ts>`), records the skill
312/// links into SkillDock's library
313/// as owned (re-pointed by the next skills sync) and bare-clones the
314/// backup repository. Confirmation is the caller's (CLI `--yes`, wizard).
315///
316/// `choices` (the wizard's extraction step) become `secrets.toml` aliases
317/// in the same commit ([`extract::stage_choices`]); keyring values are
318/// written right before the commit. Each alias must be one of this
319/// migration's extractions. No client file is written (no apply).
320pub fn apply_with_choices(
321    store: &Store<'_>,
322    ax: &ApplyEnv<'_>,
323    choices: &[ExtractionChoice],
324) -> Result<Applied, CoreError> {
325    require_source(ax)?;
326    let tag = store.create_auto_tag(TAG_KIND)?;
327    let operation = Operation::new("migrate.skilldock", "migrate: skilldock");
328    let committed = store.transaction(operation, |tx| {
329        let migration = build(ax, Some(&*tx), store.secret_memory().clone())?;
330        for choice in choices {
331            if !migration
332                .report
333                .extractions
334                .iter()
335                .any(|extraction| extraction.alias == choice.alias)
336            {
337                return Err(CoreError::new(
338                    ErrorCode::InvalidValue,
339                    format!("{:?} is not a value this migration extracts", choice.alias),
340                ));
341            }
342        }
343        for (relative, bytes) in &migration.files {
344            tx.write(relative, bytes.clone())?;
345        }
346        for id in &migration.report.servers {
347            tx.add_entity(format!("server/{id}"));
348        }
349        for id in &migration.report.skills {
350            tx.add_entity(format!("skill/{id}"));
351        }
352        extract::stage_choices(tx, ax, choices)?;
353        let plural = |n: usize| if n == 1 { "" } else { "s" };
354        let (servers, skills) = (
355            migration.report.servers.len(),
356            migration.report.skills.len(),
357        );
358        tx.set_summary(format!(
359            "migrate: skilldock ({servers} server{}, {skills} skill{})",
360            plural(servers),
361            plural(skills)
362        ));
363        Ok(migration)
364    })?;
365    let mut migration = committed.value;
366    let post_tag = match &committed.commit {
367        Some(commit) => Some(store.create_auto_tag_at(POST_TAG_KIND, commit)?),
368        None => None,
369    };
370    if !migration.links.is_empty() {
371        let state = ax.home.state_dir();
372        let _lock = StoreLock::acquire(ax.fs, &state, LOCK_TIMEOUT)?;
373        let mut ledger = SkillLedger::load(ax.fs, &state)?;
374        for link in &migration.links {
375            if ledger.get(Path::new(&link.path)).is_none() {
376                ledger.links.push(link.clone());
377            }
378        }
379        ledger.save(ax.fs, &state)?;
380    }
381    let mut backup_import = None;
382    if let Some(source) = &migration.backup {
383        let item = migration
384            .report
385            .items
386            .iter_mut()
387            .find(|item| item.kind == ItemKind::Backup && item.status == ItemStatus::Migrated);
388        match clone_backup(ax, source) {
389            Ok(()) => backup_import = Some(format!("imports/{BACKUP_IMPORT}")),
390            Err(err) => {
391                if let Some(item) = item {
392                    item.status = ItemStatus::NeedsReview;
393                    item.detail = format!("the bare clone failed: {}", err.message());
394                    item.code = Some(err.code().as_str());
395                }
396            }
397        }
398    }
399    Ok(Applied {
400        report: migration.report,
401        tag,
402        commit: committed.commit,
403        post_tag,
404        backup_import,
405    })
406}
407
408/// `source` bare-cloned (history kept, objects copied, no hard links) to
409/// `<SURJECTION_HOME>/imports/skilldock-backup.git`.
410fn clone_backup(ax: &ApplyEnv<'_>, source: &Path) -> Result<(), CoreError> {
411    let imports = ax.home.imports_dir();
412    let dest = imports.join(BACKUP_IMPORT);
413    crate::skills::confine(ax.fs, source)?;
414    crate::skills::confine(ax.fs, &dest)?;
415    ax.fs.create_dir_all(&imports).map_err(|err| {
416        CoreError::new(
417            ErrorCode::IoError,
418            format!("cannot create directory: {err}"),
419        )
420        .with_path(&imports)
421    })?;
422    let git = |err: git2::Error| CoreError::new(ErrorCode::GitError, err.message().to_owned());
423    let url = source.to_string_lossy().into_owned();
424    git2::build::RepoBuilder::new()
425        .bare(true)
426        .clone_local(git2::build::CloneLocal::NoLinks)
427        .clone(&url, &dest)
428        .map(|_| ())
429        .map_err(git)
430}
431
432/// Store files as the base plus the migration's staged ones.
433struct Overlay<'a> {
434    base: Option<&'a dyn StoreRead>,
435    files: &'a BTreeMap<String, Vec<u8>>,
436}
437
438impl StoreRead for Overlay<'_> {
439    fn read_file(&self, relative: &str) -> Result<Option<String>, CoreError> {
440        match self.files.get(relative) {
441            Some(bytes) => Ok(Some(String::from_utf8_lossy(bytes).into_owned())),
442            None => match self.base {
443                Some(base) => base.read_file(relative),
444                None => Ok(None),
445            },
446        }
447    }
448
449    fn list_files(&self, dir: &str) -> Result<Vec<String>, CoreError> {
450        let mut names = match self.base {
451            Some(base) => base.list_files(dir)?,
452            None => Vec::new(),
453        };
454        let prefix = format!("{dir}/");
455        for relative in self.files.keys() {
456            if let Some(name) = relative.strip_prefix(&prefix)
457                && !name.contains('/')
458                && !names.iter().any(|known| known == name)
459            {
460                names.push(name.to_owned());
461            }
462        }
463        names.sort();
464        Ok(names)
465    }
466}
467
468fn read_base(base: Option<&dyn StoreRead>, relative: &str) -> Result<Option<String>, CoreError> {
469    match base {
470        Some(base) => base.read_file(relative),
471        None => Ok(None),
472    }
473}
474
475/// Maps everything; `base` is the store as it is (or the transaction).
476fn build(
477    ax: &ApplyEnv<'_>,
478    base: Option<&dyn StoreRead>,
479    memory: Arc<SecretMemory>,
480) -> Result<Migration, CoreError> {
481    let fs: &dyn Fs = ax.fs;
482    let home = ax.env.home();
483    let root = source_dir(ax);
484    let mut report = Report {
485        source: format!("~/{}", skilldock::DIR),
486        ..Report::default()
487    };
488    let mut files: BTreeMap<String, Vec<u8>> = BTreeMap::new();
489    // Paths (`~/...`) the mapping consumed; everything else is listed.
490    let mut consumed: BTreeSet<String> = BTreeSet::new();
491
492    let machine = Machine::load(fs, &ax.home.state_dir())?.map(|m| m.id);
493    let base_desired = match base {
494        Some(base) => DesiredState::load(base, machine.as_deref())?,
495        None => DesiredState::empty(),
496    };
497    let mut aliases = Aliases::new(base_desired.catalog.iter().map(|alias| alias.alias.clone()));
498
499    // MCP registry.
500    let mut migrated: BTreeMap<String, MigratedServer> = BTreeMap::new();
501    let mut servers: Vec<Server> = Vec::new();
502    let mcp = skilldock::first_existing(fs, home, &skilldock::MCP_FILES);
503    for display in skilldock::MCP_FILES {
504        if mcp.as_ref().is_some_and(|(used, _)| used != display)
505            && fs.exists(&skilldock::resolve(home, display))
506        {
507            consumed.insert(display.to_owned());
508            report.items.push(Item::skipped(
509                ItemKind::File,
510                display,
511                format!(
512                    "an older copy of the MCP registry; {} is used",
513                    mcp.as_ref().expect("some").0
514                ),
515            ));
516        }
517    }
518    if let Some((display, path)) = &mcp {
519        consumed.insert(display.clone());
520        let records =
521            skilldock::read_json(fs, path, display).and_then(|doc| skilldock::parse_records(&doc));
522        match records {
523            Err(err) => report.items.push(Item::error(
524                ItemKind::File,
525                display.clone(),
526                ItemStatus::NeedsReview,
527                &err,
528            )),
529            Ok(records) => {
530                report.items.push(Item::new(
531                    ItemKind::File,
532                    display.clone(),
533                    ItemStatus::Migrated,
534                    format!(
535                        "the MCP registry: {} record{}",
536                        records.len(),
537                        if records.len() == 1 { "" } else { "s" }
538                    ),
539                    None,
540                ));
541                for record in records {
542                    map_server(
543                        record,
544                        base,
545                        &mut aliases,
546                        &mut report,
547                        &mut migrated,
548                        &mut servers,
549                    )?;
550                }
551            }
552        }
553    }
554
555    // Skills.
556    let mut tags: Vec<TagEntry> = Vec::new();
557    let mut installed: Vec<InstalledSkill> = Vec::new();
558    for (list, is_state) in [
559        (&skilldock::TAG_FILES[..], false),
560        (&skilldock::STATE_FILES[..], true),
561    ] {
562        let used = skilldock::first_existing(fs, home, list);
563        for display in list {
564            if !fs.exists(&skilldock::resolve(home, display)) {
565                continue;
566            }
567            consumed.insert((*display).to_owned());
568            if used.as_ref().is_some_and(|(first, _)| first != display) {
569                report.items.push(Item::skipped(
570                    ItemKind::File,
571                    *display,
572                    "an older copy; the newer file is used",
573                ));
574            }
575        }
576        if let Some((display, path)) = used {
577            match skilldock::read_json(fs, &path, &display) {
578                Ok(doc) => {
579                    report.items.push(Item::new(
580                        ItemKind::File,
581                        display.clone(),
582                        ItemStatus::Migrated,
583                        if is_state {
584                            "installed skills (sources) and skill tags"
585                        } else {
586                            "skill tags"
587                        },
588                        None,
589                    ));
590                    skilldock::parse_tags(&doc, &mut tags);
591                    if is_state {
592                        installed = skilldock::parse_installed(&doc, &mut tags);
593                    }
594                }
595                Err(err) => report.items.push(Item::error(
596                    ItemKind::File,
597                    display,
598                    ItemStatus::NeedsReview,
599                    &err,
600                )),
601            }
602        }
603    }
604    let library = skilldock::resolve(home, skilldock::SKILLS_DIR);
605    let mut links: Vec<SkillLink> = Vec::new();
606    let mut skill_ids: Vec<String> = Vec::new();
607    let mut tag_used = vec![false; tags.len()];
608    if fs.is_dir(&library) {
609        consumed.insert(skilldock::SKILLS_DIR.to_owned());
610        let found = scan::library_links(ax, &library)?;
611        let mut dirs = fs.read_dir(&library).map_err(|err| {
612            CoreError::new(
613                ErrorCode::IoError,
614                format!("cannot list ~/.skilldock/skills: {err}"),
615            )
616        })?;
617        dirs.sort();
618        let cx = SkillCx {
619            ax,
620            base,
621            now: utc_datetime(ax.env.now()).to_string(),
622            memory: &memory,
623            allow: Allowlist::parse(&read_base(base, ALLOWLIST_FILE)?.unwrap_or_default()),
624            ledger: SkillLedger::load(fs, &ax.home.state_dir())?,
625            tags: &tags,
626            installed: &installed,
627        };
628        let mut out = SkillOut {
629            report: &mut report,
630            files: &mut files,
631            links: &mut links,
632            skill_ids: &mut skill_ids,
633            tag_used: &mut tag_used,
634        };
635        for dir in dirs {
636            let name = file_name(&dir);
637            if name.is_empty() {
638                continue;
639            }
640            let found = found.get(&name).map(Vec::as_slice).unwrap_or_default();
641            map_skill(&cx, &name, &dir, found, &mut out)?;
642        }
643    }
644    // Tags of skills that are not in the library (the item names the
645    // skill, never SkillDock's key, which holds an absolute path).
646    let mut unmatched: BTreeMap<String, Vec<String>> = BTreeMap::new();
647    for (entry, used) in tags.iter().zip(&tag_used) {
648        if !used {
649            let list = unmatched.entry(entry.name.clone()).or_default();
650            if !list.contains(&entry.tag) {
651                list.push(entry.tag.clone());
652            }
653        }
654    }
655    for (name, list) in &unmatched {
656        report.items.push(Item::skipped(
657            ItemKind::Skill,
658            name.clone(),
659            format!(
660                "tag{} {} for a skill that is not in ~/.skilldock/skills",
661                if list.len() == 1 { "" } else { "s" },
662                list.join(", ")
663            ),
664        ));
665    }
666
667    // Settings.
668    let settings = skilldock::first_existing(fs, home, &skilldock::SETTINGS_FILES);
669    for display in skilldock::SETTINGS_FILES {
670        if fs.exists(&skilldock::resolve(home, display)) {
671            consumed.insert(display.to_owned());
672            if settings.as_ref().is_some_and(|(used, _)| used != display) {
673                report.items.push(Item::skipped(
674                    ItemKind::File,
675                    display,
676                    "an older copy of the settings; the newer file is used",
677                ));
678            }
679        }
680    }
681    if let Some((display, path)) = &settings {
682        match skilldock::read_json(fs, path, display).and_then(|doc| SkillDockSettings::parse(&doc))
683        {
684            Ok(parsed) => {
685                report.items.push(Item::new(
686                    ItemKind::File,
687                    display.clone(),
688                    ItemStatus::Migrated,
689                    "settings; one item per field below",
690                    None,
691                ));
692                map_settings(&parsed, base, &mut report, &mut files)?;
693            }
694            Err(err) => report.items.push(Item::error(
695                ItemKind::File,
696                display.clone(),
697                ItemStatus::NeedsReview,
698                &err,
699            )),
700        }
701    }
702
703    // Credentials, backup and the rest of `~/.skilldock`.
704    let backup = list_rest(ax, &root, &consumed, &mut report)?;
705
706    // The post-migration scan.
707    for server in &servers {
708        let text = TomlDocument::new(server.clone()).to_text()?;
709        files.insert(server_path(&server.id)?, text.into_bytes());
710    }
711    let mut desired = DesiredState::load(
712        &Overlay {
713            base,
714            files: &files,
715        },
716        machine.as_deref(),
717    )?;
718    let ledger = Ledger::load(fs, &ax.home.state_dir())?;
719    let key = LedgerKey::load(fs, &ax.home.state_dir())?.unwrap_or(LedgerKey::from_bytes([0; 32]));
720    let (candidates, warnings) = scan::candidates(ax, &desired, &ledger)?;
721    for warning in &warnings {
722        report.items.push(Item::error(
723            ItemKind::ClientEntry,
724            warning
725                .path()
726                .map(|path| crate::apply::placeholder_path(ax.env, path, None))
727                .unwrap_or_default(),
728            ItemStatus::NeedsReview,
729            warning,
730        ));
731    }
732    let adopted = scan::adopt_identical(ax, memory.clone(), &mut desired, &migrated, &candidates);
733    for (id, client) in &adopted {
734        let server = desired.servers[id].clone();
735        let text = TomlDocument::new(server).to_text()?;
736        files.insert(server_path(id)?, text.into_bytes());
737        if let Some(item) = report
738            .items
739            .iter_mut()
740            .find(|item| item.kind == ItemKind::Server && item.id.as_deref() == Some(id))
741        {
742            item.detail
743                .push_str(&format!("; enabled for {client} (identical entry found)"));
744        }
745    }
746    let entries = scan::mcp_entries(
747        ax,
748        memory,
749        &desired,
750        &ledger,
751        &key,
752        &migrated,
753        &candidates,
754        &adopted,
755    )?;
756    report.items.extend(entries);
757    for link in &links {
758        report.items.push(Item {
759            id: Some(link.skill_id.clone()),
760            ..Item::new(
761                ItemKind::SkillLink,
762                format!("{}/{}", link.client, link_name(link)),
763                ItemStatus::Migrated,
764                format!(
765                    "{} points into ~/.skilldock/skills; re-pointed to the store copy by the next \
766                     skills sync (planned as an update)",
767                    crate::apply::placeholder_path(ax.env, Path::new(&link.path), None)
768                ),
769                None,
770            )
771        });
772    }
773    report.servers = servers.iter().map(|s| s.id.clone()).collect();
774    report.skills = skill_ids;
775    Ok(Migration {
776        report,
777        files,
778        links,
779        backup,
780    })
781}
782
783fn link_name(link: &SkillLink) -> String {
784    Path::new(&link.path)
785        .file_name()
786        .map(|name| name.to_string_lossy().into_owned())
787        .unwrap_or_default()
788}
789
790fn map_server(
791    record: Result<Record, CoreError>,
792    base: Option<&dyn StoreRead>,
793    aliases: &mut Aliases,
794    report: &mut Report,
795    migrated: &mut BTreeMap<String, MigratedServer>,
796    servers: &mut Vec<Server>,
797) -> Result<(), CoreError> {
798    let record = match record {
799        Ok(record) => record,
800        Err(err) => {
801            report.items.push(Item::error(
802                ItemKind::Server,
803                "?",
804                ItemStatus::NeedsReview,
805                &err,
806            ));
807            return Ok(());
808        }
809    };
810    let name = record.id.clone();
811    if record.plugin_owned() {
812        report.items.push(Item::skipped(
813            ItemKind::Server,
814            name,
815            "installed by a SkillDock plugin; plugins are not migrated",
816        ));
817        return Ok(());
818    }
819    let Some(id) = slug(&record.id) else {
820        report.items.push(Item::new(
821            ItemKind::Server,
822            name,
823            ItemStatus::NeedsReview,
824            "no server id can be made from the record id; add it by hand",
825            Some(ErrorCode::InvalidId.as_str()),
826        ));
827        return Ok(());
828    };
829    if migrated.contains_key(&id) || read_base(base, &server_path(&id)?)?.is_some() {
830        report.items.push(Item::new(
831            ItemKind::Server,
832            name,
833            ItemStatus::Skipped,
834            format!("the store already has server {id:?}; left as it is"),
835            Some(ErrorCode::AlreadyExists.as_str()),
836        ));
837        return Ok(());
838    }
839    let mapped = match skilldock::map_record(&record, &id, aliases) {
840        Ok(mapped) => mapped,
841        Err(err) => {
842            report.items.push(Item::error(
843                ItemKind::Server,
844                name,
845                ItemStatus::NeedsReview,
846                &err,
847            ));
848            return Ok(());
849        }
850    };
851    let mut notes = Vec::new();
852    let mut offers = Vec::new();
853    let mut review = false;
854    if let Some(kind) = mapped.unwrapped {
855        notes.push(format!("unwrapped from SkillDock's {kind} wrapper"));
856    }
857    if let Some(tools) = &mapped.server.body.tools {
858        if let Some(deny) = &tools.deny {
859            notes.push(format!("tools denied: {}", deny.join(", ")));
860        }
861        if let Some(allow) = &tools.allow {
862            notes.push(format!("tools allowed: {}", allow.join(", ")));
863        }
864    }
865    match mapped
866        .server
867        .enable
868        .as_ref()
869        .and_then(|e| e.clients.as_ref())
870    {
871        Some(ClientSelection::List(ids)) => notes.push(format!("enabled for {}", ids.join(", "))),
872        _ => notes.push("SkillDock enabled it for no client".to_owned()),
873    }
874    if !mapped.unknown_clients.is_empty() {
875        review = true;
876        notes.push(format!(
877            "no {} adapter for {}",
878            brand::PRODUCT_NAME,
879            mapped.unknown_clients.join(", ")
880        ));
881    }
882    if mapped.machine_path {
883        review = true;
884        notes.push(
885            "machine-specific path: the command is absolute; consider moving it into [os.*] or \
886             the machine overlay"
887                .to_owned(),
888        );
889        offers.push(Offer::MachinePath { server: id.clone() });
890    }
891    for extraction in &mapped.extractions {
892        review = true;
893        notes.push(format!(
894            "{} may be a secret; replaced by ${{secret:{}}}",
895            extraction.field, extraction.alias
896        ));
897        offers.push(Offer::SetSecret {
898            alias: extraction.alias.clone(),
899            command: format!(
900                "{} secrets set {} --keyring",
901                brand::BIN_NAME,
902                extraction.alias
903            ),
904        });
905    }
906    if !mapped.dropped.is_empty() {
907        review = true;
908        notes.push(format!(
909            "fields with no store equivalent dropped: {}",
910            mapped.dropped.join(", ")
911        ));
912    }
913    notes.extend(mapped.notes.iter().cloned());
914    if !mapped.review.is_empty() {
915        review = true;
916        notes.extend(mapped.review.iter().cloned());
917    }
918    let mut item = Item::new(
919        ItemKind::Server,
920        name,
921        if review {
922            ItemStatus::NeedsReview
923        } else {
924            ItemStatus::Migrated
925        },
926        notes.join("; "),
927        None,
928    );
929    item.id = Some(id.clone());
930    item.offers = offers;
931    report.items.push(item);
932    report.extractions.extend(mapped.extractions);
933    migrated.insert(
934        id,
935        MigratedServer {
936            managed: record.managed_app_ids.clone(),
937            imported_from: record.imported_from_app_ids.clone(),
938        },
939    );
940    servers.push(mapped.server);
941    Ok(())
942}
943
944/// What every skill folder is mapped against.
945struct SkillCx<'a> {
946    ax: &'a ApplyEnv<'a>,
947    base: Option<&'a dyn StoreRead>,
948    now: String,
949    /// The store's secret memory and allowlist: skill files get the same
950    /// leak scan as the commit (SPEC 11.8), so one file cannot fail the
951    /// whole migration.
952    memory: &'a SecretMemory,
953    allow: Allowlist,
954    /// Skill links this machine owns already.
955    ledger: SkillLedger,
956    tags: &'a [TagEntry],
957    installed: &'a [InstalledSkill],
958}
959
960/// What the skill mapping adds to.
961struct SkillOut<'a> {
962    report: &'a mut Report,
963    files: &'a mut BTreeMap<String, Vec<u8>>,
964    links: &'a mut Vec<SkillLink>,
965    skill_ids: &'a mut Vec<String>,
966    /// Per [`SkillCx::tags`] entry: matched a skill folder.
967    tag_used: &'a mut Vec<bool>,
968}
969
970fn skill_link(cx: &SkillCx<'_>, link: &FoundLink, id: &str) -> SkillLink {
971    SkillLink {
972        kind: "skill_link".to_owned(),
973        client: link.client.to_owned(),
974        scope: crate::model::applied::Scope::User,
975        project_id: None,
976        skill_id: id.to_owned(),
977        path: link.path.to_string_lossy().into_owned(),
978        method: link.method,
979        target: link.target.to_string_lossy().into_owned(),
980        written_hash: None,
981        written_at: Some(cx.now.clone()),
982        extra: serde_json::Map::new(),
983    }
984}
985
986/// A link the sync could not re-point: its name is not the skill id, so
987/// the sync would add a second link at `<id>` and remove this one.
988fn misnamed_link(link: &FoundLink, id: &str) -> Item {
989    Item {
990        id: Some(id.to_owned()),
991        ..Item::new(
992            ItemKind::SkillLink,
993            format!("{}/{}", link.client, file_name(&link.path)),
994            ItemStatus::NeedsReview,
995            format!(
996                "{} points into ~/.skilldock/skills but is not named {id:?}, the skill's id; left \
997                 as it is and not enabled for {} (rename it to {id:?} or remove it, then enable \
998                 the skill)",
999                link.display, link.client
1000            ),
1001            None,
1002        )
1003    }
1004}
1005
1006fn map_skill(
1007    cx: &SkillCx<'_>,
1008    name: &str,
1009    dir: &Path,
1010    found: &[FoundLink],
1011    out: &mut SkillOut<'_>,
1012) -> Result<(), CoreError> {
1013    let fs = cx.ax.fs;
1014    let report = &mut *out.report;
1015    let display = format!("{}/{name}", skilldock::SKILLS_DIR);
1016    match crate::skills::entry(fs, dir)? {
1017        crate::skills::Entry::Dir => {}
1018        crate::skills::Entry::Link(_) => {
1019            report.items.push(Item::new(
1020                ItemKind::Skill,
1021                name,
1022                ItemStatus::NeedsReview,
1023                format!("{display} is a link; install the folder it points to with `skills add`"),
1024                Some(ErrorCode::InvalidPath.as_str()),
1025            ));
1026            return Ok(());
1027        }
1028        _ => {
1029            report
1030                .items
1031                .push(Item::skipped(ItemKind::File, display, "not a skill folder"));
1032            return Ok(());
1033        }
1034    }
1035    let content = match read_folder(fs, dir) {
1036        Ok(content) => content,
1037        Err(err) => {
1038            report.items.push(Item::error(
1039                ItemKind::Skill,
1040                name,
1041                ItemStatus::NeedsReview,
1042                &err,
1043            ));
1044            return Ok(());
1045        }
1046    };
1047    let Some(skill_md) = content.get(SKILL_FILE) else {
1048        report.items.push(Item::new(
1049            ItemKind::Skill,
1050            name,
1051            ItemStatus::Skipped,
1052            format!("no {SKILL_FILE}"),
1053            Some(ErrorCode::NotFound.as_str()),
1054        ));
1055        return Ok(());
1056    };
1057    let mut notes = Vec::new();
1058    let parsed = match frontmatter::parse(&String::from_utf8_lossy(skill_md)) {
1059        Ok(parsed) => parsed,
1060        Err(err) => {
1061            notes.push(format!("frontmatter: {}", err.message()));
1062            None
1063        }
1064    };
1065    let skill_name = parsed
1066        .as_ref()
1067        .and_then(|fm| fm.name())
1068        .unwrap_or(name)
1069        .to_owned();
1070    // SkillDock's tags and install records name the skill by folder (its
1071    // path) or by name.
1072    let names = [name, skill_name.as_str()];
1073    let mut tags: Vec<String> = Vec::new();
1074    for (index, entry) in cx.tags.iter().enumerate() {
1075        if entry.matches(name, &names) {
1076            out.tag_used[index] = true;
1077            if !tags.contains(&entry.tag) {
1078                tags.push(entry.tag.clone());
1079            }
1080        }
1081    }
1082    let installed = cx.installed.iter().find(|s| s.matches(name, &names));
1083    if let Some(file) = content.iter().find_map(|(relative, bytes)| {
1084        let findings = scan_text(
1085            relative,
1086            bytes,
1087            relative.ends_with(".toml"),
1088            cx.memory,
1089            &cx.allow,
1090        );
1091        (!findings.is_empty()).then_some(relative)
1092    }) {
1093        report.items.push(Item::new(
1094            ItemKind::Skill,
1095            name,
1096            ItemStatus::NeedsReview,
1097            format!(
1098                "{file} looks like it holds a secret, which the store refuses; remove it, then \
1099                 install the folder with `skills add`"
1100            ),
1101            Some(ErrorCode::LeakDetected.as_str()),
1102        ));
1103        return Ok(());
1104    }
1105    let Some(id) = slug(&skill_name).or_else(|| slug(name)) else {
1106        report.items.push(Item::new(
1107            ItemKind::Skill,
1108            name,
1109            ItemStatus::NeedsReview,
1110            "no skill id can be made from the name; install it by hand",
1111            Some(ErrorCode::InvalidId.as_str()),
1112        ));
1113        return Ok(());
1114    };
1115    // Only a link named like the id is the entry the sync re-points.
1116    let (named, misnamed): (Vec<&FoundLink>, Vec<&FoundLink>) =
1117        found.iter().partition(|link| file_name(&link.path) == id);
1118    for link in &misnamed {
1119        report.items.push(misnamed_link(link, &id));
1120    }
1121    if out.skill_ids.contains(&id) {
1122        report.items.push(Item::new(
1123            ItemKind::Skill,
1124            name,
1125            ItemStatus::NeedsReview,
1126            format!("another SkillDock skill already became {id:?}; install this one by hand"),
1127            Some(ErrorCode::AlreadyExists.as_str()),
1128        ));
1129        for link in &named {
1130            report.items.push(misnamed_link(link, &id));
1131        }
1132        return Ok(());
1133    }
1134    let existing = match cx.base {
1135        Some(base) => read_meta(base, &id)?
1136            .map(|meta| meta.enable.and_then(|e| e.clients))
1137            .or_else(|| {
1138                read_base(Some(base), &format!("{SKILLS_DIR}/{id}/{SKILL_FILE}"))
1139                    .ok()
1140                    .flatten()
1141                    .map(|_| None)
1142            }),
1143        None => None,
1144    };
1145    if let Some(enabled) = existing {
1146        // Already in the store (an earlier run, or the user's own skill):
1147        // its links are still owned now, so a run after a failed
1148        // post-commit step repairs them. A client the store copy is not
1149        // enabled for is left to the user (the sync would remove it).
1150        let mut recorded = 0;
1151        for link in &named {
1152            if cx.ledger.get(&link.path).is_some() {
1153                continue;
1154            }
1155            let wanted = match &enabled {
1156                Some(ClientSelection::AllDetected) => true,
1157                Some(ClientSelection::List(ids)) => ids.iter().any(|c| c == link.client),
1158                None => false,
1159            };
1160            if wanted {
1161                out.links.push(skill_link(cx, link, &id));
1162                recorded += 1;
1163            } else {
1164                report.items.push(Item {
1165                    id: Some(id.clone()),
1166                    ..Item::new(
1167                        ItemKind::SkillLink,
1168                        format!("{}/{}", link.client, file_name(&link.path)),
1169                        ItemStatus::NeedsReview,
1170                        format!(
1171                            "{} points into ~/.skilldock/skills; the store's skill {id:?} is not \
1172                             enabled for {}, so it is left as it is",
1173                            link.display, link.client
1174                        ),
1175                        None,
1176                    )
1177                });
1178            }
1179        }
1180        report.items.push(Item {
1181            id: Some(id.clone()),
1182            ..Item::new(
1183                ItemKind::Skill,
1184                name,
1185                ItemStatus::Skipped,
1186                if recorded == 0 {
1187                    format!("the store already has skill {id:?}; left as it is")
1188                } else {
1189                    format!(
1190                        "the store already has skill {id:?}; left as it is, its {recorded} \
1191                         link{} recorded",
1192                        if recorded == 1 { "" } else { "s" }
1193                    )
1194                },
1195                Some(ErrorCode::AlreadyExists.as_str()),
1196            )
1197        });
1198        return Ok(());
1199    }
1200    let mut review = false;
1201    let mut meta = SkillMeta::new(&id);
1202    meta.name = Some(skill_name);
1203    if !tags.is_empty() {
1204        notes.push(format!("tags: {}", tags.join(", ")));
1205        meta.tags = Some(tags);
1206    }
1207    let (source, source_note) = skill_source(fs, dir, installed);
1208    if let Some(note) = source_note {
1209        review = true;
1210        notes.push(note);
1211    }
1212    match &source {
1213        SkillSource {
1214            kind: SkillSourceKind::Git,
1215            url: Some(url),
1216            ..
1217        } => notes.push(format!("source: {url}")),
1218        _ => notes.push("source: local".to_owned()),
1219    }
1220    meta.source = Some(source);
1221    let mut clients: Vec<String> = Vec::new();
1222    let mut new_links = Vec::new();
1223    for link in &named {
1224        if !clients.iter().any(|known| known == link.client) {
1225            clients.push(link.client.to_owned());
1226        }
1227        new_links.push(skill_link(cx, link, &id));
1228    }
1229    if clients.is_empty() {
1230        notes.push("not linked into any client".to_owned());
1231    } else {
1232        notes.push(format!(
1233            "enabled for {} (links on disk)",
1234            clients.join(", ")
1235        ));
1236        meta.enable = Some(SkillEnable {
1237            clients: Some(ClientSelection::List(clients)),
1238            method: Some(DistributionMethod::Link),
1239            extra: toml::Table::new(),
1240        });
1241    }
1242    if !misnamed.is_empty() {
1243        review = true;
1244    }
1245    if let Some(err) = meta.validate(Some(&id)).first_error(None) {
1246        report.items.push(Item::error(
1247            ItemKind::Skill,
1248            name,
1249            ItemStatus::NeedsReview,
1250            &err,
1251        ));
1252        return Ok(());
1253    }
1254    for (relative, bytes) in &content {
1255        out.files
1256            .insert(format!("{SKILLS_DIR}/{id}/{relative}"), bytes.clone());
1257    }
1258    out.files.insert(
1259        meta_path(&id)?,
1260        TomlDocument::new(meta).to_text()?.into_bytes(),
1261    );
1262    out.links.extend(new_links);
1263    let mut item = Item::new(
1264        ItemKind::Skill,
1265        name,
1266        if review {
1267            ItemStatus::NeedsReview
1268        } else {
1269            ItemStatus::Migrated
1270        },
1271        notes.join("; "),
1272        None,
1273    );
1274    item.id = Some(id.clone());
1275    report.items.push(item);
1276    out.skill_ids.push(id);
1277    Ok(())
1278}
1279
1280/// `[source]` from the skill folder's git repository (remote `origin` and
1281/// HEAD, read only), else from `state.json` (`git`, and `github` with a
1282/// `/tree/<ref>/<path>` URL split into repository, ref and path), else
1283/// `local`. Other SkillDock sources (`marketplace`, `well-known`) have no
1284/// update path here and stay local, with a note. A URL that may hold a
1285/// credential is left out (with a note).
1286fn skill_source(
1287    fs: &dyn Fs,
1288    dir: &Path,
1289    installed: Option<&InstalledSkill>,
1290) -> (SkillSource, Option<String>) {
1291    let mut source = SkillSource {
1292        kind: SkillSourceKind::Local,
1293        url: None,
1294        path: None,
1295        git_ref: None,
1296        commit: None,
1297        catalog: None,
1298        extra: toml::Table::new(),
1299    };
1300    let mut url = None;
1301    if dir.join(".git").exists()
1302        && let Ok(repo) = git2::Repository::open_ext(
1303            dir,
1304            git2::RepositoryOpenFlags::NO_SEARCH,
1305            std::iter::empty::<&std::ffi::OsStr>(),
1306        )
1307    {
1308        url = repo
1309            .find_remote("origin")
1310            .ok()
1311            .and_then(|remote| remote.url().ok().map(str::to_owned));
1312        if let Ok(head) = repo.head() {
1313            source.commit = head.peel_to_commit().ok().map(|c| c.id().to_string());
1314            if head.is_branch() {
1315                source.git_ref = head.shorthand().ok().map(str::to_owned);
1316            }
1317        }
1318    }
1319    let mut note = None;
1320    if url.is_none()
1321        && let Some(installed) = installed
1322        && !installed.source_url.is_empty()
1323    {
1324        match installed.source_type.as_str() {
1325            "" | "local" => {}
1326            "git" | "github" => {
1327                if let Source::Git {
1328                    url: repo,
1329                    git_ref,
1330                    path,
1331                } = Source::parse(&installed.source_url, fs)
1332                {
1333                    url = Some(repo);
1334                    source.path = path;
1335                    source.git_ref = git_ref.filter(|r| r != "HEAD").or_else(|| {
1336                        (!installed.branch.is_empty()).then(|| installed.branch.clone())
1337                    });
1338                } else {
1339                    note = Some(
1340                        "SkillDock's git source is not a repository URL; kept as a local skill"
1341                            .to_owned(),
1342                    );
1343                }
1344            }
1345            other => {
1346                note = Some(format!(
1347                    "SkillDock's {other} source has no update path in Surjection; kept as a local \
1348                     skill (reinstall it from its repository for updates)"
1349                ));
1350            }
1351        }
1352    }
1353    match url {
1354        Some(url) if classify_import(None, &url).is_some() || !find_in_text(&url).is_empty() => {
1355            note = Some(
1356                "the source URL may hold a credential and was left out; reinstall from a clean URL \
1357                 for updates"
1358                    .to_owned(),
1359            );
1360            source.git_ref = None;
1361            source.commit = None;
1362            source.path = None;
1363        }
1364        Some(url) => {
1365            source.kind = SkillSourceKind::Git;
1366            source.url = Some(url);
1367        }
1368        None => {
1369            source.git_ref = None;
1370            source.commit = None;
1371            source.path = None;
1372        }
1373    }
1374    (source, note)
1375}
1376
1377/// Maps `settings.json` onto `settings.toml`. A field the store already
1378/// sets differently is kept and listed as skipped.
1379fn map_settings(
1380    parsed: &SkillDockSettings,
1381    base: Option<&dyn StoreRead>,
1382    report: &mut Report,
1383    files: &mut BTreeMap<String, Vec<u8>>,
1384) -> Result<(), CoreError> {
1385    let mut doc = match read_base(base, SETTINGS_FILE)? {
1386        Some(text) => TomlDocument::<Settings>::parse(&text).map_err(|d| d.to_core_error(None))?,
1387        None => TomlDocument::new(Settings::new()),
1388    };
1389    let before = doc.value().clone();
1390    let settings = doc.value_mut();
1391    for (key, value) in &parsed.fields {
1392        let item = |status, detail: String| {
1393            Item::new(ItemKind::Setting, key.clone(), status, detail, None)
1394        };
1395        match key.as_str() {
1396            "theme" => {
1397                let theme = match parsed.text(key) {
1398                    Some("light") => Some(Theme::Light),
1399                    Some("dark") => Some(Theme::Dark),
1400                    Some("system") => Some(Theme::System),
1401                    _ => None,
1402                };
1403                report.items.push(match theme {
1404                    None => item(ItemStatus::Skipped, "not a theme Surjection knows".to_owned()),
1405                    Some(theme) => set(key, &mut settings.theme, theme, "theme", |t| format!("{t:?}").to_lowercase()),
1406                });
1407            }
1408            "agentSkillsCompatibilityEnabled" => {
1409                let Some(on) = parsed.bool(key) else {
1410                    report.items.push(item(ItemStatus::Skipped, "not a true/false value".to_owned()));
1411                    continue;
1412                };
1413                // The agents CLI library as SkillDock's library also means compatibility.
1414                let on = on || parsed.text("skillLibraryProvider") == Some("agent-skills");
1415                report.items.push(set(key, &mut settings.agents_cli_compat, on, "agents_cli_compat", |v| v.to_string()));
1416            }
1417            "skillInstallActivation" | "mcpInstallActivation" => {
1418                let target = if key == "skillInstallActivation" {
1419                    (&mut settings.new_skill_enable, "new_skill_enable")
1420                } else {
1421                    (&mut settings.new_server_enable, "new_server_enable")
1422                };
1423                let value = match parsed.text(key) {
1424                    Some("apply-all-tools") => Some(NewItemEnable::AllDetected),
1425                    Some("disable-all-tools") => Some(NewItemEnable::None),
1426                    _ => None,
1427                };
1428                report.items.push(match value {
1429                    None => item(ItemStatus::Skipped, "not an activation mode Surjection knows".to_owned()),
1430                    Some(value) => set(key, target.0, value, target.1, |v| match v {
1431                        NewItemEnable::AllDetected => "all-detected".to_owned(),
1432                        NewItemEnable::None => "none".to_owned(),
1433                    }),
1434                });
1435            }
1436            "skillLibraryProvider" => match parsed.text(key) {
1437                // SkillDock computes compatibility as the field or this
1438                // provider (`state.rs` `load_app_settings`) and omits the
1439                // field when unset.
1440                Some("agent-skills")
1441                    if !parsed.fields.contains_key("agentSkillsCompatibilityEnabled") =>
1442                {
1443                    report.items.push(set(
1444                        key,
1445                        &mut settings.agents_cli_compat,
1446                        true,
1447                        "agents_cli_compat",
1448                        |v| v.to_string(),
1449                    ));
1450                }
1451                Some("agent-skills") => report.items.push(item(
1452                    ItemStatus::Skipped,
1453                    "the library was the agents CLI folder; it is scanned read-only with agents CLI compatibility".to_owned(),
1454                )),
1455                _ => report.items.push(item(
1456                    ItemStatus::Skipped,
1457                    "SkillDock's own library is migrated from ~/.skilldock/skills".to_owned(),
1458                )),
1459            },
1460            "defaultOpenToolId" => report.items.push(item(
1461                ItemStatus::Skipped,
1462                "no portable setting; the default editor is chosen per machine".to_owned(),
1463            )),
1464            "language" | "languageSource" => report.items.push(item(
1465                ItemStatus::Skipped,
1466                "Surjection is English only".to_owned(),
1467            )),
1468            "skillSourceViewStyle" | "skillTagFilterLayout" => report.items.push(item(
1469                ItemStatus::Skipped,
1470                "a SkillDock layout preference".to_owned(),
1471            )),
1472            "githubToken" => {
1473                if parsed.text(key).is_some() {
1474                    let mut review = item(
1475                        ItemStatus::NeedsReview,
1476                        "a GitHub token; never copied into the store. Move it into the OS keyring \
1477                         for a git remote with token auth"
1478                            .to_owned(),
1479                    );
1480                    review.kind = ItemKind::Credential;
1481                    review.offers.push(token_offer());
1482                    report.items.push(review);
1483                }
1484            }
1485            "githubConnection" => report.items.push(item(
1486                ItemStatus::Skipped,
1487                "GitHub account details; remotes are added in Surjection".to_owned(),
1488            )),
1489            "githubBackup" => {
1490                let url = value
1491                    .get("repositoryUrl")
1492                    .and_then(serde_json::Value::as_str)
1493                    .map(str::trim)
1494                    .filter(|url| !url.is_empty() && classify_import(None, url).is_none());
1495                let enabled = value.get("enabled").and_then(serde_json::Value::as_bool) == Some(true);
1496                report.items.push(match url {
1497                    Some(url) if enabled => {
1498                        let mut review = item(
1499                            ItemStatus::NeedsReview,
1500                            format!("SkillDock backed up to {url}; add it as a backup remote if wanted"),
1501                        );
1502                        review.offers.push(Offer::AddRemote { url: url.to_owned() });
1503                        review
1504                    }
1505                    _ => item(ItemStatus::Skipped, "GitHub backup was not enabled".to_owned()),
1506                });
1507            }
1508            _ => report.items.push(item(ItemStatus::Skipped, "a setting with no Surjection equivalent".to_owned())),
1509        }
1510    }
1511    if *doc.value() != before {
1512        files.insert(SETTINGS_FILE.to_owned(), doc.to_text()?.into_bytes());
1513    }
1514    Ok(())
1515}
1516
1517/// Sets `slot` to `value` unless the store already holds another value;
1518/// the item is named after SkillDock's `key`.
1519fn set<T: PartialEq + Copy>(
1520    key: &str,
1521    slot: &mut Option<T>,
1522    value: T,
1523    field: &str,
1524    show: impl Fn(T) -> String,
1525) -> Item {
1526    let item = |status, detail| Item::new(ItemKind::Setting, key, status, detail, None);
1527    match *slot {
1528        Some(current) if current != value => item(
1529            ItemStatus::Skipped,
1530            format!("the store already sets {field} = {}; kept", show(current)),
1531        ),
1532        Some(_) => item(
1533            ItemStatus::Migrated,
1534            format!("{field} = {} (already set)", show(value)),
1535        ),
1536        None => {
1537            *slot = Some(value);
1538            item(ItemStatus::Migrated, format!("{field} = {}", show(value)))
1539        }
1540    }
1541}
1542
1543fn token_offer() -> Offer {
1544    Offer::KeyringToken {
1545        command: format!(
1546            "{bin} remote add git <NAME> <URL> --auth token, then pipe the token to `{bin} remote \
1547             token <NAME>`",
1548            bin = brand::BIN_NAME
1549        ),
1550    }
1551}
1552
1553/// Lists every entry of `~/.skilldock` the mapping did not consume; returns
1554/// the backup repository to clone, if there is one to clone.
1555fn list_rest(
1556    ax: &ApplyEnv<'_>,
1557    root: &Path,
1558    consumed: &BTreeSet<String>,
1559    report: &mut Report,
1560) -> Result<Option<PathBuf>, CoreError> {
1561    let fs = ax.fs;
1562    let mut backup = None;
1563    if !fs.is_dir(root) {
1564        return Ok(None);
1565    }
1566    let list = |dir: &Path| -> Vec<PathBuf> {
1567        let mut paths = fs.read_dir(dir).unwrap_or_default();
1568        paths.sort();
1569        paths
1570    };
1571    for path in list(root) {
1572        let top = file_name(&path);
1573        let display = format!("~/{}/{top}", skilldock::DIR);
1574        if consumed.contains(&display) {
1575            continue;
1576        }
1577        match top.as_str() {
1578            "config" | "data" | "credentials" | "backup" if fs.is_dir(&path) => {
1579                for child in list(&path) {
1580                    let child_display = format!("{display}/{}", file_name(&child));
1581                    if consumed.contains(&child_display) {
1582                        continue;
1583                    }
1584                    if child_display == skilldock::BACKUP_REPO {
1585                        backup = backup_item(ax, &child, report);
1586                        continue;
1587                    }
1588                    report
1589                        .items
1590                        .push(rest_item(fs, &child, &child_display, top.as_str()));
1591                }
1592            }
1593            _ => report.items.push(rest_item(fs, &path, &display, "")),
1594        }
1595    }
1596    Ok(backup)
1597}
1598
1599fn file_name(path: &Path) -> String {
1600    path.file_name()
1601        .map(|name| name.to_string_lossy().into_owned())
1602        .unwrap_or_default()
1603}
1604
1605fn rest_item(fs: &dyn Fs, path: &Path, display: &str, parent: &str) -> Item {
1606    let name = file_name(path);
1607    match (parent, name.as_str()) {
1608        ("credentials", "github.json") | ("", "github-credentials.json") => {
1609            let has_token = fs
1610                .read_to_string(path)
1611                .ok()
1612                .and_then(|text| serde_json::from_str::<serde_json::Value>(&text).ok())
1613                .and_then(|doc| {
1614                    doc.get("token")
1615                        .and_then(serde_json::Value::as_str)
1616                        .map(|token| !token.trim().is_empty())
1617                })
1618                .unwrap_or(false);
1619            if has_token {
1620                let mut item = Item::new(
1621                    ItemKind::Credential,
1622                    display,
1623                    ItemStatus::NeedsReview,
1624                    "SkillDock's GitHub token; never copied into the store. Move it into the OS \
1625                     keyring for a git remote with token auth",
1626                    None,
1627                );
1628                item.offers.push(token_offer());
1629                item
1630            } else {
1631                Item::skipped(ItemKind::Credential, display, "holds no token")
1632            }
1633        }
1634        ("credentials", "skillhub.json") | ("", "skillhub-auth.json") => Item::skipped(
1635            ItemKind::Skillhub,
1636            display,
1637            "SkillHub sign-in; SkillHub is not migrated",
1638        ),
1639        ("credentials", _) => Item::skipped(
1640            ItemKind::Credential,
1641            display,
1642            "a SkillDock credential with no Surjection use; never copied",
1643        ),
1644        ("data", "publishing") => Item::skipped(
1645            ItemKind::Skillhub,
1646            display,
1647            "SkillHub publishing state; SkillHub is not migrated",
1648        ),
1649        ("", "plugins") => Item::skipped(
1650            ItemKind::Plugin,
1651            display,
1652            "SkillDock plugins are not migrated",
1653        ),
1654        ("", "repositories" | "repo-cache" | "cache" | "logs" | "imports") => Item::skipped(
1655            ItemKind::File,
1656            display,
1657            "SkillDock caches and logs; nothing to migrate",
1658        ),
1659        ("backup", _) => Item::skipped(
1660            ItemKind::Backup,
1661            display,
1662            "SkillDock backup bookkeeping; the repository itself is imported",
1663        ),
1664        _ => Item::skipped(ItemKind::File, display, "not used by the migration"),
1665    }
1666}
1667
1668/// The backup repository's item; the path to clone when it is a git
1669/// repository not imported yet.
1670fn backup_item(ax: &ApplyEnv<'_>, repo: &Path, report: &mut Report) -> Option<PathBuf> {
1671    let dest = ax.home.imports_dir().join(BACKUP_IMPORT);
1672    let display = skilldock::BACKUP_REPO;
1673    let is_repo = ax.fs.exists(&repo.join(".git")) || ax.fs.exists(&repo.join("HEAD"));
1674    if !is_repo {
1675        report.items.push(Item::skipped(
1676            ItemKind::Backup,
1677            display,
1678            "not a git repository",
1679        ));
1680        return None;
1681    }
1682    if ax.fs.exists(&dest) {
1683        report.items.push(Item::new(
1684            ItemKind::Backup,
1685            display,
1686            ItemStatus::Skipped,
1687            format!("already imported as imports/{BACKUP_IMPORT}"),
1688            Some(ErrorCode::AlreadyExists.as_str()),
1689        ));
1690        return None;
1691    }
1692    report.items.push(Item::new(
1693        ItemKind::Backup,
1694        display,
1695        ItemStatus::Migrated,
1696        format!(
1697            "bare-cloned to imports/{BACKUP_IMPORT} (history kept, read-only); one backup's \
1698             servers and skills can be imported from there"
1699        ),
1700        None,
1701    ));
1702    Some(repo.to_path_buf())
1703}