Skip to main content

surjection_core/skills/
link.rs

1//! Distribution of store skills to client skill directories (SPEC 12.2,
2//! 12.3, table 7.6, Tier A and B rows).
3//!
4//! - `link`: a directory junction on Windows (no Developer Mode or admin
5//!   needed, made with the Win32 API through the `junction` crate), or a
6//!   directory symbolic link when chosen ([`LinkKind::Symlink`]); a
7//!   symbolic link elsewhere.
8//! - `copy`: the files plus a [`MARKER_FILE`], owned by content hash, so an
9//!   edit in place shows as `changed` and is never overwritten or removed.
10//!
11//! An existing link to something else is a `collision`, and a real folder
12//! or file of the same name is `foreign`: neither is ever touched. Only
13//! entries the ledger owns, and that are unchanged, are replaced or
14//! removed.
15//!
16//! Ownership lives in `state/ledger.json` under the top-level key
17//! `skill_links` (see [`SkillLedger`]), next to the MCP entries, so the
18//! ledger stays the one record of what Surjection owns on this machine.
19
20use std::cell::OnceCell;
21use std::collections::{BTreeMap, BTreeSet, HashSet};
22use std::io;
23use std::path::{Path, PathBuf};
24
25use serde::{Deserialize, Serialize};
26
27use crate::adapters::detect::detect;
28use crate::adapters::location::Location;
29use crate::apply::ledger::Ledger;
30use crate::env::Env;
31use crate::error::{CoreError, ErrorCode};
32use crate::fs::Fs;
33use crate::layering::git::ProjectRepo;
34use crate::layering::projects::{mirror, this_overlay};
35use crate::layering::{
36    Project, ProjectStatus, TrustStore, known_projects, path_key, same_folder, same_path,
37};
38use crate::model::applied::Scope;
39use crate::model::clients::ClientSelection;
40use crate::model::ids::{self, IdKind};
41use crate::model::project::ProjectManifest;
42use crate::model::skill_meta::{DistributionMethod, SkillEnable, SkillMeta};
43use crate::skills::store::{self, content_dir};
44use crate::skills::{
45    Entry, MARKER_FILE, SkillFiles, SkillsEnv, confine, content_hash, creation_error, entry,
46    has_nested_git, io_error, new_folder_access, read_folder, removal_error, write_error,
47    write_files,
48};
49use crate::store::{
50    self as store_mod, CommitId, LOCK_TIMEOUT, Operation, Store, StoreLock, utc_datetime,
51};
52
53/// Ledger key holding skill links.
54pub const LEDGER_KEY: &str = "skill_links";
55const RECORD_KIND: &str = "skill_link";
56
57/// How links are made on Windows.
58#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
59pub enum LinkKind {
60    /// A directory junction (default).
61    #[default]
62    Junction,
63    /// A directory symbolic link (needs Developer Mode or admin rights).
64    Symlink,
65}
66
67/// How one entry was made.
68#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
69#[serde(rename_all = "lowercase")]
70pub enum LinkMethod {
71    Junction,
72    Symlink,
73    Copy,
74}
75
76impl LinkMethod {
77    pub const fn as_str(self) -> &'static str {
78        match self {
79            LinkMethod::Junction => "junction",
80            LinkMethod::Symlink => "symlink",
81            LinkMethod::Copy => "copy",
82        }
83    }
84
85    pub(crate) fn is_link(self) -> bool {
86        self != LinkMethod::Copy
87    }
88}
89
90/// A client's skill directories (table 7.6).
91#[derive(Debug, Clone, Copy)]
92pub struct ClientSkills {
93    pub client: &'static str,
94    /// User scope folder.
95    pub user: Location,
96    /// Project scope folder, relative to the project root.
97    pub project: &'static str,
98}
99
100/// Tier A and B clients with skill folders (table 7.6). Claude Desktop has
101/// none. Codex user skills go to `$CODEX_HOME/skills` [verify: Codex may
102/// read `~/.agents/skills` instead]; the project folders other than Claude
103/// Code's are [verify] in the spec.
104pub static CLIENT_SKILLS: [ClientSkills; 6] = [
105    ClientSkills {
106        client: "claude-code",
107        user: Location::EnvDir {
108            var: "CLAUDE_CONFIG_DIR",
109            fallback: &Location::Home(".claude"),
110            rel: "skills",
111            tilde: false,
112        },
113        project: ".claude/skills",
114    },
115    ClientSkills {
116        client: "omp",
117        user: Location::EnvDir {
118            var: "PI_CODING_AGENT_DIR",
119            fallback: &Location::HomeNamedDir {
120                var: "PI_CONFIG_DIR",
121                default: ".omp",
122                rel: "agent",
123            },
124            rel: "skills",
125            tilde: false,
126        },
127        project: ".omp/skills",
128    },
129    ClientSkills {
130        client: "codex",
131        user: Location::EnvDir {
132            var: "CODEX_HOME",
133            fallback: &Location::Home(".codex"),
134            rel: "skills",
135            tilde: false,
136        },
137        project: ".agents/skills",
138    },
139    ClientSkills {
140        client: "pi",
141        user: Location::EnvDir {
142            var: "PI_CODING_AGENT_DIR",
143            fallback: &Location::Home(".pi/agent"),
144            rel: "skills",
145            tilde: true,
146        },
147        project: ".pi/skills",
148    },
149    ClientSkills {
150        client: "copilot",
151        user: Location::EnvDir {
152            var: "COPILOT_HOME",
153            fallback: &Location::Home(".copilot"),
154            rel: "skills",
155            tilde: false,
156        },
157        project: ".github/skills",
158    },
159    ClientSkills {
160        client: "cursor",
161        user: Location::Home(".cursor/skills"),
162        project: ".cursor/skills",
163    },
164];
165
166/// The skill folder entry of `client`, if it has one.
167pub fn client_skills(client: &str) -> Option<&'static ClientSkills> {
168    CLIENT_SKILLS.iter().find(|entry| entry.client == client)
169}
170
171/// The skill folder of `client` in `scope` (`project` for the project
172/// scope). `scope_not_supported` for a client without skill folders.
173pub fn skills_dir(
174    env: &Env,
175    client: &str,
176    scope: Scope,
177    project: Option<&Path>,
178) -> Result<PathBuf, CoreError> {
179    let entry = client_skills(client).ok_or_else(|| no_skills(client))?;
180    match scope {
181        Scope::User => entry
182            .user
183            .resolve(env, None)
184            .ok_or_else(|| no_skills(client)),
185        Scope::Project | Scope::ProjectLocal => {
186            let root = project.filter(|root| root.is_absolute()).ok_or_else(|| {
187                CoreError::new(
188                    ErrorCode::InvalidPath,
189                    "a project scope needs an absolute folder",
190                )
191            })?;
192            Ok(entry
193                .project
194                .split('/')
195                .fold(root.to_path_buf(), |path, part| path.join(part)))
196        }
197    }
198}
199
200fn no_skills(client: &str) -> CoreError {
201    let code = if crate::model::clients::known_client(client).is_some() {
202        ErrorCode::ScopeNotSupported
203    } else {
204        ErrorCode::UnknownClient
205    };
206    CoreError::new(
207        code,
208        format!("{client:?} has no skill folder Surjection writes"),
209    )
210}
211
212/// One owned skill entry (`state/ledger.json` `skill_links`).
213#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
214pub struct SkillLink {
215    /// Always `skill_link`.
216    pub kind: String,
217    pub client: String,
218    pub scope: Scope,
219    #[serde(default, skip_serializing_if = "Option::is_none")]
220    pub project_id: Option<String>,
221    pub skill_id: String,
222    /// The entry in the client's folder, absolute.
223    pub path: String,
224    pub method: LinkMethod,
225    /// The store folder it was made from, absolute.
226    pub target: String,
227    /// Content hash of a copy ([`content_hash`]); `None` for links.
228    #[serde(default, skip_serializing_if = "Option::is_none")]
229    pub written_hash: Option<String>,
230    /// RFC 3339, UTC.
231    #[serde(default, skip_serializing_if = "Option::is_none")]
232    pub written_at: Option<String>,
233    #[serde(flatten)]
234    pub extra: serde_json::Map<String, serde_json::Value>,
235}
236
237/// The skill part of the ledger. Loaded and saved with the rest of
238/// `state/ledger.json`, whose MCP entries are kept as they are.
239#[derive(Debug, Clone, Default)]
240pub struct SkillLedger {
241    ledger: Ledger,
242    pub links: Vec<SkillLink>,
243}
244
245impl SkillLedger {
246    pub fn load(fs: &dyn Fs, state_dir: &Path) -> Result<Self, CoreError> {
247        let ledger = Ledger::load(fs, state_dir)?;
248        let links = match ledger.extra.get(LEDGER_KEY) {
249            Some(value) => serde_json::from_value(value.clone()).map_err(|err| {
250                CoreError::new(
251                    ErrorCode::ParseError,
252                    format!("the ledger's {LEDGER_KEY} do not parse: {err}"),
253                )
254            })?,
255            None => Vec::new(),
256        };
257        Ok(Self { ledger, links })
258    }
259
260    pub fn save(&mut self, fs: &dyn Fs, state_dir: &Path) -> Result<(), CoreError> {
261        let value = serde_json::to_value(&self.links).map_err(|err| {
262            CoreError::new(
263                ErrorCode::InvalidValue,
264                format!("cannot serialize skill links: {err}"),
265            )
266        })?;
267        if self.links.is_empty() {
268            self.ledger.extra.remove(LEDGER_KEY);
269        } else {
270            self.ledger.extra.insert(LEDGER_KEY.to_owned(), value);
271        }
272        fs.create_dir_all(state_dir)
273            .map_err(|err| io_error("cannot create directory", state_dir, &err))?;
274        self.ledger.save(fs, state_dir)
275    }
276
277    /// The owned entry at `path`.
278    pub fn get(&self, path: &Path) -> Option<&SkillLink> {
279        self.links
280            .iter()
281            .find(|link| same_path(Path::new(&link.path), path))
282    }
283
284    pub(crate) fn upsert(&mut self, link: SkillLink) {
285        self.remove(Path::new(&link.path));
286        self.links.push(link);
287    }
288
289    pub(crate) fn remove(&mut self, path: &Path) -> bool {
290        let before = self.links.len();
291        self.links
292            .retain(|link| !same_path(Path::new(&link.path), path));
293        self.links.len() != before
294    }
295
296    /// Drops ownership of `path` (moved to the trash, imported).
297    pub fn forget(&mut self, path: &Path) -> bool {
298        self.remove(path)
299    }
300
301    /// The MCP part of the ledger, saved with the skill links.
302    pub(crate) fn mcp_mut(&mut self) -> &mut Ledger {
303        &mut self.ledger
304    }
305}
306
307/// `origin` of a record for a folder the user handed over (adopt, SPEC
308/// 8.1): the entry was there before Surjection owned it.
309pub const ORIGIN_ADOPTED: &str = "adopted";
310/// `origin` of a record Surjection made; records without `origin` are these.
311pub const ORIGIN_CREATED: &str = "created";
312
313impl SkillLink {
314    /// `adopted` or `created` (SPEC 8.1). Stored in the record's extra
315    /// fields, absent for entries Surjection created.
316    pub fn origin(&self) -> &str {
317        self.extra
318            .get("origin")
319            .and_then(serde_json::Value::as_str)
320            .unwrap_or(ORIGIN_CREATED)
321    }
322}
323
324/// What happened to one entry.
325#[derive(Debug, Clone, Copy, PartialEq, Eq)]
326pub enum LinkStatus {
327    /// Made now.
328    Created,
329    /// A link to the store skill was already there; now owned.
330    Adopted,
331    /// Owned and as desired.
332    Unchanged,
333    /// An owned copy was rewritten with new store content, or an owned
334    /// entry was remade with another method.
335    Updated,
336    /// An owned entry that is no longer desired was removed (or was gone).
337    Removed,
338    /// A real folder or file of that name: never overwritten (offer import).
339    Foreign,
340    /// A link to something else (ask).
341    Collision,
342    /// An owned entry was edited in place (a copy's files, a link's
343    /// target): left as it is and no longer owned.
344    Changed,
345    /// Not done; see the error (no skill content, untrusted project, a
346    /// failed write).
347    Blocked,
348}
349
350impl LinkStatus {
351    pub const fn as_str(self) -> &'static str {
352        match self {
353            LinkStatus::Created => "created",
354            LinkStatus::Adopted => "adopted",
355            LinkStatus::Unchanged => "unchanged",
356            LinkStatus::Updated => "updated",
357            LinkStatus::Removed => "removed",
358            LinkStatus::Foreign => "foreign",
359            LinkStatus::Collision => "collision",
360            LinkStatus::Changed => "changed",
361            LinkStatus::Blocked => "blocked",
362        }
363    }
364
365    /// Whether the entry needs the user (SPEC 14 exit code 4).
366    pub fn needs_decision(self) -> bool {
367        matches!(
368            self,
369            LinkStatus::Foreign | LinkStatus::Collision | LinkStatus::Changed
370        )
371    }
372}
373
374/// One entry of a [`SyncReport`].
375#[derive(Debug, Clone)]
376pub struct LinkResult {
377    pub client: String,
378    pub scope: Scope,
379    pub project_id: Option<String>,
380    pub skill_id: String,
381    pub path: PathBuf,
382    pub method: LinkMethod,
383    pub status: LinkStatus,
384    /// The link target found, for a collision.
385    pub found_target: Option<PathBuf>,
386    pub error: Option<CoreError>,
387}
388
389/// What [`sync`] did.
390#[derive(Debug, Clone, Default)]
391pub struct SyncReport {
392    pub results: Vec<LinkResult>,
393    /// Unknown clients, missing skills, untrusted projects.
394    pub warnings: Vec<CoreError>,
395}
396
397impl SyncReport {
398    /// Whether any entry needs the user or failed.
399    pub fn needs_attention(&self) -> bool {
400        self.results
401            .iter()
402            .any(|result| result.status.needs_decision() || result.status == LinkStatus::Blocked)
403    }
404
405    /// Entries that changed something or need attention.
406    pub fn notable(&self) -> impl Iterator<Item = &LinkResult> {
407        self.results
408            .iter()
409            .filter(|result| result.status != LinkStatus::Unchanged)
410    }
411}
412
413/// One desired entry.
414#[derive(Debug, Clone)]
415pub(crate) struct Desired {
416    client: &'static str,
417    scope: Scope,
418    project_id: Option<String>,
419    skill_id: String,
420    path: PathBuf,
421    source: PathBuf,
422    method: LinkMethod,
423    /// The project folder of a project entry. Its repository hides links
424    /// (`share = false`) through `info/exclude` and shows copies
425    /// (`share = true`, SPEC 12.3).
426    project_root: Option<PathBuf>,
427}
428
429fn link_method(sx: &SkillsEnv<'_>) -> LinkMethod {
430    if cfg!(windows) && sx.link_kind == LinkKind::Junction {
431        LinkMethod::Junction
432    } else {
433        LinkMethod::Symlink
434    }
435}
436
437/// Which clients with skill folders (table 7.6) are detected, probed once
438/// on first need and kept for one operation (a sync, a listing): a store
439/// of 300 skills enabled for `all-detected` would otherwise run every
440/// client's detection 300 times (#16). Make a new one per operation, so a
441/// client installed since is seen.
442pub struct DetectedClients<'a> {
443    sx: SkillsEnv<'a>,
444    detected: OnceCell<Vec<&'static str>>,
445}
446
447impl<'a> DetectedClients<'a> {
448    pub fn new(sx: &SkillsEnv<'a>) -> Self {
449        Self {
450            sx: *sx,
451            detected: OnceCell::new(),
452        }
453    }
454
455    /// The detected clients, in table order.
456    pub fn clients(&self) -> &[&'static str] {
457        self.detected.get_or_init(|| {
458            CLIENT_SKILLS
459                .iter()
460                .filter(|entry| {
461                    crate::adapters::adapter(entry.client).is_some_and(|spec| {
462                        detect(spec, self.sx.env, self.sx.fs, self.sx.registry).detected()
463                    })
464                })
465                .map(|entry| entry.client)
466                .collect()
467        })
468    }
469
470    /// Whether `client` (a client with a skill folder) is detected.
471    pub fn is_detected(&self, client: &str) -> bool {
472        self.clients().contains(&client)
473    }
474
475    /// The client ids of `selection` that have skill folders, `all-detected`
476    /// resolved with the detection probes (for listings; unknown clients
477    /// are left out).
478    pub fn selected(&self, selection: &ClientSelection) -> Vec<&'static str> {
479        let mut ignored = Vec::new();
480        self.resolve(selection, "", &mut ignored)
481    }
482
483    /// Client ids of a selection that have skill folders; others are
484    /// warnings.
485    fn resolve(
486        &self,
487        selection: &ClientSelection,
488        what: &str,
489        warnings: &mut Vec<CoreError>,
490    ) -> Vec<&'static str> {
491        match selection {
492            ClientSelection::AllDetected => self.clients().to_vec(),
493            ClientSelection::List(ids) => {
494                let mut out = Vec::new();
495                for id in ids {
496                    match client_skills(id) {
497                        Some(entry) => {
498                            if !out.contains(&entry.client) {
499                                out.push(entry.client);
500                            }
501                        }
502                        None => warnings.push(CoreError::new(
503                            no_skills(id).code(),
504                            format!(
505                                "{what}: {id:?} has no skill folder Surjection writes; skipped"
506                            ),
507                        )),
508                    }
509                }
510                out
511            }
512        }
513    }
514}
515
516/// The projects whose links were evaluated, and the desired entries.
517fn desired(
518    store: &Store<'_>,
519    sx: &SkillsEnv<'_>,
520    report: &mut SyncReport,
521) -> Result<(Vec<Desired>, Vec<String>), CoreError> {
522    let mut out: Vec<Desired> = Vec::new();
523    let skills = store::list(store)?;
524    let with_content: HashSet<&str> = skills
525        .iter()
526        .filter(|skill| skill.has_content)
527        .map(|skill| skill.id.as_str())
528        .collect();
529    let detected = DetectedClients::new(sx);
530    // The first desired entry for a path wins (user scope before projects).
531    let mut seen: HashSet<String> = HashSet::new();
532    let mut push = |out: &mut Vec<Desired>, desired: Desired| {
533        if seen.insert(path_key(&desired.path)) {
534            out.push(desired);
535        }
536    };
537
538    for skill in &skills {
539        let Some(selection) = skill
540            .meta
541            .as_ref()
542            .and_then(|meta| meta.enable.as_ref())
543            .and_then(|enable| enable.clients.as_ref())
544        else {
545            continue;
546        };
547        if !skill.has_content {
548            report.warnings.push(store::not_found(&skill.id));
549            continue;
550        }
551        let method = match skill
552            .meta
553            .as_ref()
554            .and_then(|meta| meta.enable.as_ref())
555            .and_then(|enable| enable.method)
556        {
557            Some(DistributionMethod::Copy) => LinkMethod::Copy,
558            _ => link_method(sx),
559        };
560        let what = format!("skill {:?}", skill.id);
561        for client in detected.resolve(selection, &what, &mut report.warnings) {
562            let dir = skills_dir(sx.env, client, Scope::User, None)?;
563            push(
564                &mut out,
565                Desired {
566                    client,
567                    scope: Scope::User,
568                    project_id: None,
569                    skill_id: skill.id.clone(),
570                    path: dir.join(&skill.id),
571                    source: content_dir(store, &skill.id)?,
572                    method,
573                    project_root: None,
574                },
575            );
576        }
577    }
578
579    let state = sx.home.state_dir();
580    let overlay = this_overlay(store, sx.fs, &state)?;
581    let trust = TrustStore::load(sx.fs, &state)?;
582    let mut evaluated = Vec::new();
583    for known in known_projects(sx.fs, sx.env, overlay.as_ref(), &trust) {
584        let ProjectStatus::Loaded { project, .. } = &known.status else {
585            continue;
586        };
587        let wanted = project_skills(project);
588        if let Some(err) = known.trust_error() {
589            if !wanted.enable.is_empty() {
590                report.warnings.push(err);
591            }
592            continue;
593        }
594        evaluated.push(known.id.clone());
595        let what = format!("project {:?}", known.id);
596        let clients = detected.resolve(&wanted.clients, &what, &mut report.warnings);
597        let method = if wanted.share {
598            LinkMethod::Copy
599        } else {
600            link_method(sx)
601        };
602        for id in &wanted.enable {
603            if !ids::is_valid(IdKind::Skill, id) || !with_content.contains(id.as_str()) {
604                report.warnings.push(CoreError::new(
605                    ErrorCode::NotFound,
606                    format!("{what} enables skill {id:?}, which is not in the store"),
607                ));
608                continue;
609            }
610            for client in &clients {
611                let dir = skills_dir(sx.env, client, Scope::Project, Some(&known.root))?;
612                push(
613                    &mut out,
614                    Desired {
615                        client,
616                        scope: Scope::Project,
617                        project_id: Some(known.id.clone()),
618                        skill_id: id.clone(),
619                        path: dir.join(id),
620                        source: content_dir(store, id)?,
621                        method,
622                        project_root: Some(known.root.clone()),
623                    },
624                );
625            }
626        }
627    }
628    Ok((out, evaluated))
629}
630
631/// `[skills]` of a project's manifests: `enable` from both files, `share`
632/// and `defaults.clients` from the private file over the shared one.
633#[derive(Debug, Clone, PartialEq)]
634pub struct ProjectSkills {
635    pub enable: Vec<String>,
636    pub share: bool,
637    pub clients: ClientSelection,
638}
639
640/// `[skills]` of `project` as links are made from it.
641pub fn project_skills(project: &Project) -> ProjectSkills {
642    let layers: Vec<&ProjectManifest> = [project.local.as_ref(), project.shared.as_ref()]
643        .into_iter()
644        .flatten()
645        .map(|file| &file.manifest)
646        .collect();
647    let mut enable: Vec<String> = Vec::new();
648    for manifest in layers.iter().rev() {
649        for id in manifest
650            .skills
651            .as_ref()
652            .and_then(|skills| skills.enable.as_ref())
653            .into_iter()
654            .flatten()
655        {
656            if !enable.contains(id) {
657                enable.push(id.clone());
658            }
659        }
660    }
661    let share = layers
662        .iter()
663        .find_map(|manifest| manifest.skills.as_ref().and_then(|skills| skills.share))
664        .unwrap_or(false);
665    let clients = layers
666        .iter()
667        .find_map(|manifest| {
668            manifest
669                .defaults
670                .as_ref()
671                .and_then(|defaults| defaults.clients.clone())
672        })
673        .unwrap_or(ClientSelection::AllDetected);
674    ProjectSkills {
675        enable,
676        share,
677        clients,
678    }
679}
680
681/// Makes client skill folders match the store (SPEC 12.2, 12.3): every
682/// skill's `enable.clients` at user scope, and `[skills] enable` of every
683/// trusted project this machine knows. Creates missing entries, rewrites
684/// owned unchanged copies whose store content changed, removes owned
685/// unchanged entries that are no longer desired, and reports foreign,
686/// colliding and changed entries without touching them. Projects that are
687/// not trusted, missing or invalid are left alone. Runs under the store
688/// lock; call it after a commit, never inside a transaction.
689pub fn sync(store: &Store<'_>, sx: &SkillsEnv<'_>) -> Result<SyncReport, CoreError> {
690    let state = sx.home.state_dir();
691    let _lock = StoreLock::acquire(sx.fs, &state, LOCK_TIMEOUT)?;
692    let mut ledger = SkillLedger::load(sx.fs, &state)?;
693    let mut report = SyncReport::default();
694    let (mut wanted, evaluated) = desired(store, sx, &mut report)?;
695    // Entries this machine stopped managing (`surject eject`) are left
696    // alone: not made, not replaced, not retired.
697    let ejected = crate::eject::status_at(sx.fs, &state)?;
698    let covered = |client: &str, project_id: Option<&str>| {
699        ejected
700            .as_ref()
701            .is_some_and(|ejected| ejected.covers(client, project_id))
702    };
703    wanted.retain(|desired| !covered(desired.client, desired.project_id.as_deref()));
704    let now = utc_datetime(sx.env.now()).to_string();
705
706    for desired in &wanted {
707        let result = ensure(sx, &mut ledger, desired, &now);
708        report.results.push(result);
709    }
710
711    let wanted_paths: HashSet<String> = wanted
712        .iter()
713        .map(|desired| path_key(&desired.path))
714        .collect();
715    let stale: Vec<SkillLink> = ledger
716        .links
717        .iter()
718        .filter(|link| !wanted_paths.contains(&path_key(Path::new(&link.path))))
719        .filter(|link| !covered(&link.client, link.project_id.as_deref()))
720        .filter(|link| match link.scope {
721            Scope::User => true,
722            Scope::Project | Scope::ProjectLocal => link
723                .project_id
724                .as_ref()
725                .is_some_and(|id| evaluated.contains(id)),
726        })
727        .cloned()
728        .collect();
729    for link in stale {
730        report.results.push(retire(sx, &mut ledger, &link));
731    }
732    ledger.save(sx.fs, &state)?;
733    Ok(report)
734}
735
736fn result(desired: &Desired, status: LinkStatus) -> LinkResult {
737    LinkResult {
738        client: desired.client.to_owned(),
739        scope: desired.scope,
740        project_id: desired.project_id.clone(),
741        skill_id: desired.skill_id.clone(),
742        path: desired.path.clone(),
743        method: desired.method,
744        status,
745        found_target: None,
746        error: None,
747    }
748}
749
750fn ensure(
751    sx: &SkillsEnv<'_>,
752    ledger: &mut SkillLedger,
753    desired: &Desired,
754    now: &str,
755) -> LinkResult {
756    match try_ensure(sx, ledger, desired, now) {
757        Ok(result) => result,
758        Err(err) => LinkResult {
759            error: Some(err),
760            ..result(desired, LinkStatus::Blocked)
761        },
762    }
763}
764
765fn try_ensure(
766    sx: &SkillsEnv<'_>,
767    ledger: &mut SkillLedger,
768    desired: &Desired,
769    now: &str,
770) -> Result<LinkResult, CoreError> {
771    let fs = sx.fs;
772    let owned = ledger.get(&desired.path).cloned();
773    let status = match entry(fs, &desired.path)? {
774        Entry::Missing => {
775            // A folder this account cannot write is reported, never tried
776            // (SPEC 8.2 `read_only_target`). Entries are folders (a
777            // junction, a link to a folder, a copy): the question is
778            // whether a subfolder can be created there.
779            if let Some(kind) = new_folder_access(fs, &desired.path).read_only() {
780                return Err(crate::access::read_only_target(kind, &desired.path));
781            }
782            // The exclude line first: a link that cannot be hidden is
783            // never made.
784            git_visibility(fs, desired)?;
785            let hash = create(fs, desired)?;
786            ledger.upsert(record(desired, hash, now));
787            LinkStatus::Created
788        }
789        Entry::Link(found) => {
790            let to_store = same_folder(fs, &found, &desired.source);
791            let owned_link = owned.as_ref().filter(|link| {
792                link.method.is_link() && same_folder(fs, &found, Path::new(&link.target))
793            });
794            // An owned link that reaches the store only through another
795            // path (the link `surject migrate loadout` left at Loadout's
796            // old data folder) is made again with the desired target, so
797            // it never depends on that path.
798            let retarget = owned_link.is_some() && !same_text(&found, &desired.source);
799            if to_store && desired.method.is_link() && !retarget {
800                git_visibility(fs, desired)?;
801                let status = if owned_link.is_some() {
802                    LinkStatus::Unchanged
803                } else {
804                    LinkStatus::Adopted
805                };
806                let mut link = record(desired, None, now);
807                if let Some(owned) = owned_link {
808                    // Keep how it was made (a junction stays a junction)
809                    // and what else the record says (`origin`).
810                    link.method = owned.method;
811                    link.written_at.clone_from(&owned.written_at);
812                    link.extra.clone_from(&owned.extra);
813                }
814                ledger.upsert(link);
815                status
816            } else if let Some(owned) = owned_link {
817                // Owned and unchanged, but another target or method is
818                // desired now.
819                git_visibility(fs, desired)?;
820                remove_link(fs, &desired.path)?;
821                let hash = create(fs, desired)?;
822                let mut link = record(desired, hash, now);
823                link.extra.clone_from(&owned.extra);
824                ledger.upsert(link);
825                LinkStatus::Updated
826            } else if owned.is_some() {
827                ledger.remove(&desired.path);
828                LinkStatus::Changed
829            } else {
830                return Ok(LinkResult {
831                    found_target: Some(found),
832                    ..result(desired, LinkStatus::Collision)
833                });
834            }
835        }
836        Entry::Dir => match owned.filter(|link| link.method == LinkMethod::Copy) {
837            Some(link) => match unchanged_copy(fs, &desired.path, &link)? {
838                None => {
839                    ledger.remove(&desired.path);
840                    LinkStatus::Changed
841                }
842                Some(current) => {
843                    git_visibility(fs, desired)?;
844                    if desired.method == LinkMethod::Copy
845                        && content_hash(&read_source(fs, desired)?) == current
846                    {
847                        LinkStatus::Unchanged
848                    } else {
849                        remove_copy(fs, &desired.path)?;
850                        let hash = create(fs, desired)?;
851                        let mut copy = record(desired, hash, now);
852                        copy.extra.clone_from(&link.extra);
853                        ledger.upsert(copy);
854                        LinkStatus::Updated
855                    }
856                }
857            },
858            None => LinkStatus::Foreign,
859        },
860        Entry::File => LinkStatus::Foreign,
861    };
862    Ok(result(desired, status))
863}
864
865/// The content hash of an owned copy at `path` when it is as written:
866/// same hash and no `.git` added inside (the hash leaves `.git` out, and a
867/// repository the user made there must never be deleted). `None` when it
868/// changed.
869pub(crate) fn unchanged_copy(
870    fs: &dyn Fs,
871    path: &Path,
872    link: &SkillLink,
873) -> Result<Option<String>, CoreError> {
874    let current = content_hash(&read_folder(fs, path)?);
875    if link.written_hash.as_deref() != Some(current.as_str()) || has_nested_git(fs, path)? {
876        return Ok(None);
877    }
878    Ok(Some(current))
879}
880
881/// Makes a project entry's visibility to the project's repository match
882/// its method before anything is written: a link (`share = false`) is
883/// listed in `info/exclude`; a copy (`share = true`, meant to be
884/// committed) is not, so an exclude line left from a link is dropped.
885/// Nothing for user scope or a folder without a repository.
886fn git_visibility(fs: &dyn Fs, desired: &Desired) -> Result<(), CoreError> {
887    let Some(root) = &desired.project_root else {
888        return Ok(());
889    };
890    let Some(repo) = ProjectRepo::discover(root)? else {
891        return Ok(());
892    };
893    if desired.method.is_link() {
894        repo.exclude(fs, &desired.path)?;
895        return Ok(());
896    }
897    let Some(relative) = repo.relative(&desired.path) else {
898        return Ok(());
899    };
900    let pattern = format!("/{relative}");
901    let file = repo.exclude_file();
902    if let Some(text) = crate::layering::projects::read_optional(fs, &file)?
903        && text
904            .lines()
905            .any(|line| line.trim() == pattern || line.trim() == relative)
906    {
907        let kept: String = text
908            .lines()
909            .filter(|line| line.trim() != pattern && line.trim() != relative)
910            .map(|line| format!("{line}\n"))
911            .collect();
912        crate::layering::projects::write_file(fs, &file, kept.as_bytes())?;
913    }
914    Ok(())
915}
916
917fn record(desired: &Desired, written_hash: Option<String>, now: &str) -> SkillLink {
918    SkillLink {
919        kind: RECORD_KIND.to_owned(),
920        client: desired.client.to_owned(),
921        scope: desired.scope,
922        project_id: desired.project_id.clone(),
923        skill_id: desired.skill_id.clone(),
924        path: desired.path.to_string_lossy().into_owned(),
925        method: desired.method,
926        target: desired.source.to_string_lossy().into_owned(),
927        written_hash,
928        written_at: Some(now.to_owned()),
929        extra: serde_json::Map::new(),
930    }
931}
932
933fn read_source(fs: &dyn Fs, desired: &Desired) -> Result<SkillFiles, CoreError> {
934    if !fs.is_dir(&desired.source) {
935        return Err(store::not_found(&desired.skill_id).with_path(&desired.source));
936    }
937    read_folder(fs, &desired.source)
938}
939
940/// Creates the entry; the content hash for a copy.
941fn create(fs: &dyn Fs, desired: &Desired) -> Result<Option<String>, CoreError> {
942    if !fs.is_dir(&desired.source) {
943        return Err(store::not_found(&desired.skill_id).with_path(&desired.source));
944    }
945    if let Some(parent) = desired.path.parent() {
946        confine(fs, parent)?;
947        fs.create_dir_all(parent)
948            .map_err(|err| write_error(fs, "cannot create directory", parent, &err))?;
949    }
950    confine(fs, &desired.path)?;
951    confine(fs, &desired.source)?;
952    match desired.method {
953        LinkMethod::Junction => {
954            make_junction(fs, &desired.source, &desired.path)?;
955            Ok(None)
956        }
957        LinkMethod::Symlink => {
958            make_symlink(fs, &desired.source, &desired.path)?;
959            Ok(None)
960        }
961        LinkMethod::Copy => {
962            let files = read_folder(fs, &desired.source)?;
963            write_files(fs, &desired.path, &files)?;
964            let marker = desired.path.join(MARKER_FILE);
965            let text = marker_text(&desired.skill_id);
966            fs.write(&marker, text.as_bytes())
967                .map_err(|err| write_error(fs, "cannot write file", &marker, &err))?;
968            Ok(Some(content_hash(&files)))
969        }
970    }
971}
972
973/// The text of [`MARKER_FILE`] in a copy of `skill_id`.
974pub(crate) fn marker_text(skill_id: &str) -> String {
975    format!(
976        "Managed by {}: a copy of skill {skill_id:?}. Edits here show as changes and are never \
977         overwritten.\n",
978        crate::brand::PRODUCT_NAME
979    )
980}
981
982#[cfg(windows)]
983fn make_junction(fs: &dyn Fs, target: &Path, link: &Path) -> Result<(), CoreError> {
984    junction::create(target, link)
985        .map_err(|err| creation_error(fs, "cannot create junction", link, &err))
986}
987
988#[cfg(not(windows))]
989fn make_junction(fs: &dyn Fs, target: &Path, link: &Path) -> Result<(), CoreError> {
990    make_symlink(fs, target, link)
991}
992
993#[cfg(windows)]
994fn make_symlink(fs: &dyn Fs, target: &Path, link: &Path) -> Result<(), CoreError> {
995    std::os::windows::fs::symlink_dir(target, link).map_err(|err| {
996        creation_error(
997            fs,
998            "cannot create symbolic link (Windows needs Developer Mode or admin rights; \
999             junctions need neither)",
1000            link,
1001            &err,
1002        )
1003    })
1004}
1005
1006#[cfg(unix)]
1007fn make_symlink(fs: &dyn Fs, target: &Path, link: &Path) -> Result<(), CoreError> {
1008    std::os::unix::fs::symlink(target, link)
1009        .map_err(|err| creation_error(fs, "cannot create symbolic link", link, &err))
1010}
1011
1012/// Whether two link targets name the same path as written (no `\\?\`
1013/// prefix, `/` and `\` alike and case-insensitive on Windows, no trailing
1014/// separator), without resolving links on the way.
1015fn same_text(a: &Path, b: &Path) -> bool {
1016    fn norm(path: &Path) -> String {
1017        let text = path.to_string_lossy();
1018        let text = text.strip_prefix(r"\\?\").unwrap_or(&text);
1019        if cfg!(windows) {
1020            text.replace('/', "\\")
1021                .trim_end_matches('\\')
1022                .to_lowercase()
1023        } else {
1024            text.trim_end_matches('/').to_owned()
1025        }
1026    }
1027    norm(a) == norm(b)
1028}
1029
1030/// Removes a link only, never what it points to.
1031pub(crate) fn remove_link(fs: &dyn Fs, path: &Path) -> Result<(), CoreError> {
1032    confine(fs, path)?;
1033    let removed = if cfg!(windows) {
1034        // Junctions and directory symlinks are directories to Windows;
1035        // removing one removes the link alone.
1036        std::fs::remove_dir(path).or_else(|_| std::fs::remove_file(path))
1037    } else {
1038        std::fs::remove_file(path)
1039    };
1040    removed.map_err(|err| removal_error(fs, "cannot remove link", path, &err))
1041}
1042
1043pub(crate) fn remove_copy(fs: &dyn Fs, path: &Path) -> Result<(), CoreError> {
1044    fs.remove_dir_all(path)
1045        .map_err(|err| removal_error(fs, "cannot remove folder", path, &err))
1046}
1047
1048/// Removes an owned entry that is no longer desired, when unchanged.
1049fn retire(sx: &SkillsEnv<'_>, ledger: &mut SkillLedger, link: &SkillLink) -> LinkResult {
1050    let path = PathBuf::from(&link.path);
1051    let fs = sx.fs;
1052    let outcome = (|| -> Result<LinkStatus, CoreError> {
1053        let status = match entry(fs, &path)? {
1054            Entry::Missing => LinkStatus::Removed,
1055            Entry::Link(found)
1056                if link.method.is_link() && same_folder(fs, &found, Path::new(&link.target)) =>
1057            {
1058                remove_link(fs, &path)?;
1059                LinkStatus::Removed
1060            }
1061            Entry::Dir if link.method == LinkMethod::Copy => {
1062                if unchanged_copy(fs, &path, link)?.is_some() {
1063                    remove_copy(fs, &path)?;
1064                    LinkStatus::Removed
1065                } else {
1066                    LinkStatus::Changed
1067                }
1068            }
1069            _ => LinkStatus::Changed,
1070        };
1071        ledger.remove(&path);
1072        Ok(status)
1073    })();
1074    let (status, error) = match outcome {
1075        Ok(status) => (status, None),
1076        Err(err) => (LinkStatus::Blocked, Some(err)),
1077    };
1078    LinkResult {
1079        client: link.client.clone(),
1080        scope: link.scope,
1081        project_id: link.project_id.clone(),
1082        skill_id: link.skill_id.clone(),
1083        path,
1084        method: link.method,
1085        status,
1086        found_target: None,
1087        error,
1088    }
1089}
1090
1091/// An unmanaged folder to hand over to Surjection (adopt, SPEC 8.6, 12.5).
1092#[derive(Debug, Clone)]
1093pub(crate) struct Replacement {
1094    pub client: &'static str,
1095    /// The unmanaged folder.
1096    pub folder: PathBuf,
1097    /// Where the store skill's entry goes: the folder's own path, or
1098    /// `<dir>/<id>` for a skill stored under another id (`name-<client>`).
1099    pub entry: PathBuf,
1100    pub skill_id: String,
1101}
1102
1103/// The file operations a replacement makes; tests swap them to fail one.
1104#[derive(Clone, Copy)]
1105pub(crate) struct ReplaceOps {
1106    /// Renames a folder (`std::fs::rename`).
1107    pub rename: fn(&Path, &Path) -> io::Result<()>,
1108    /// Copies a folder to a new path, for a trash on another drive.
1109    pub copy_tree: fn(&Path, &Path) -> io::Result<()>,
1110    /// Makes the managed entry ([`create`]).
1111    pub create: fn(&dyn Fs, &Desired) -> Result<Option<String>, CoreError>,
1112}
1113
1114pub(crate) const REAL_OPS: ReplaceOps = ReplaceOps {
1115    rename: rename_folder,
1116    copy_tree,
1117    create,
1118};
1119
1120fn rename_folder(from: &Path, to: &Path) -> io::Result<()> {
1121    std::fs::rename(from, to)
1122}
1123
1124/// Replaces each folder with the managed entry of its store skill (a link,
1125/// or a copy for `copy` distribution) and moves the folder to
1126/// `backups/trash/` (never deleted), when the skill is distributed there
1127/// and nothing of the folder would be lost: its files equal the store
1128/// copy, and it holds no `.git`, no empty folder and (on Unix) no
1129/// executable file; in a project, none of its files is tracked by the
1130/// project's repository. The entry is recorded with `origin = adopted`.
1131/// Otherwise the folder stays as it is and its result is the reason. Runs
1132/// under the store lock; call it after the commit that stored the skills.
1133/// The result per item is the trash path.
1134pub(crate) fn replace_folders(
1135    store: &Store<'_>,
1136    sx: &SkillsEnv<'_>,
1137    items: &[Replacement],
1138) -> Result<Vec<Result<PathBuf, CoreError>>, CoreError> {
1139    replace_folders_with(store, sx, items, &REAL_OPS)
1140}
1141
1142pub(crate) fn replace_folders_with(
1143    store: &Store<'_>,
1144    sx: &SkillsEnv<'_>,
1145    items: &[Replacement],
1146    ops: &ReplaceOps,
1147) -> Result<Vec<Result<PathBuf, CoreError>>, CoreError> {
1148    let state = sx.home.state_dir();
1149    let _lock = StoreLock::acquire(sx.fs, &state, LOCK_TIMEOUT)?;
1150    let mut ledger = SkillLedger::load(sx.fs, &state)?;
1151    let mut ignored = SyncReport::default();
1152    let (wanted, _) = desired(store, sx, &mut ignored)?;
1153    let now = utc_datetime(sx.env.now()).to_string();
1154    let results = items
1155        .iter()
1156        .map(|item| replace_one(sx, &mut ledger, &wanted, item, &now, ops))
1157        .collect();
1158    ledger.save(sx.fs, &state)?;
1159    Ok(results)
1160}
1161
1162/// Hands one folder over. The folder is first renamed aside in its own
1163/// folder (same drive, always possible), then the entry is made, then the
1164/// folder goes to the trash: renamed, or on another drive copied, checked
1165/// and removed. Any failure before the trash holds the folder puts
1166/// everything back: the entry made is removed, the folder renamed back,
1167/// the repository's `info/exclude` restored.
1168fn replace_one(
1169    sx: &SkillsEnv<'_>,
1170    ledger: &mut SkillLedger,
1171    wanted: &[Desired],
1172    item: &Replacement,
1173    now: &str,
1174    ops: &ReplaceOps,
1175) -> Result<PathBuf, CoreError> {
1176    let fs = sx.fs;
1177    let kept =
1178        |code: ErrorCode, why: String| Err(CoreError::new(code, why).with_path(&item.folder));
1179    let Some(desired) = wanted
1180        .iter()
1181        .find(|desired| same_path(&desired.path, &item.entry))
1182    else {
1183        return kept(
1184            ErrorCode::InvalidValue,
1185            format!(
1186                "skill {:?} is not distributed to {} here, so its folder is kept",
1187                item.skill_id, item.client
1188            ),
1189        );
1190    };
1191    if entry(fs, &item.folder)? != Entry::Dir || ledger.get(&item.folder).is_some() {
1192        return kept(
1193            ErrorCode::EntryChanged,
1194            "the folder changed since the scan; scan again".to_owned(),
1195        );
1196    }
1197    if !same_path(&item.folder, &item.entry) && entry(fs, &item.entry)? != Entry::Missing {
1198        return Err(CoreError::new(
1199            ErrorCode::AlreadyExists,
1200            format!(
1201                "an entry named {:?} is in the way, so the folder is kept",
1202                item.skill_id
1203            ),
1204        )
1205        .with_path(&item.entry));
1206    }
1207    if has_nested_git(fs, &item.folder)? {
1208        return kept(
1209            ErrorCode::InvalidValue,
1210            "the folder holds a git repository, which the store copy leaves out; it is kept"
1211                .to_owned(),
1212        );
1213    }
1214    if let Some(root) = &desired.project_root
1215        && let Some(repo) = ProjectRepo::discover(root)?
1216        && repo.tracks_any_under(&item.folder)?
1217    {
1218        return kept(
1219            ErrorCode::InvalidValue,
1220            "the project's repository tracks files in the folder (teammates get it from \
1221             there); it is kept"
1222                .to_owned(),
1223        );
1224    }
1225    if let Some(what) = lost_in_store(fs, &item.folder, &item.folder)? {
1226        return kept(
1227            ErrorCode::InvalidValue,
1228            format!("the store copy would lose {what}; the folder is kept"),
1229        );
1230    }
1231    if content_hash(&read_folder(fs, &item.folder)?) != content_hash(&read_source(fs, desired)?) {
1232        return kept(
1233            ErrorCode::EntryChanged,
1234            "the folder's content differs from the store copy; it is kept".to_owned(),
1235        );
1236    }
1237    let name = item
1238        .folder
1239        .file_name()
1240        .map(|name| name.to_string_lossy().into_owned())
1241        .unwrap_or_default();
1242    let aside = item
1243        .folder
1244        .with_file_name(format!(".{name}.surjection-adopt"));
1245    confine(fs, &item.folder)?;
1246    confine(fs, &aside)?;
1247    if entry(fs, &aside)? != Entry::Missing {
1248        return Err(CoreError::new(
1249            ErrorCode::AlreadyExists,
1250            "a folder left by an earlier adopt is in the way; move it away first",
1251        )
1252        .with_path(&aside));
1253    }
1254    let exclude = exclude_state(fs, desired)?;
1255    (ops.rename)(&item.folder, &aside)
1256        .map_err(|err| removal_error(fs, "cannot move the folder aside", &item.folder, &err))?;
1257    let done = (|| -> Result<(PathBuf, Option<String>), CoreError> {
1258        // The exclude line before the entry: a link that cannot be hidden
1259        // is never made.
1260        git_visibility(fs, desired)?;
1261        let hash = (ops.create)(fs, desired)?;
1262        let trash = crate::skills::classify::trash_target(sx, item.client, &name)?;
1263        move_to_trash(fs, ops, &aside, &trash)?;
1264        Ok((trash, hash))
1265    })();
1266    match done {
1267        Ok((trash, hash)) => {
1268            let mut link = record(desired, hash, now);
1269            link.extra.insert(
1270                "origin".to_owned(),
1271                serde_json::Value::String(ORIGIN_ADOPTED.to_owned()),
1272            );
1273            ledger.upsert(link);
1274            Ok(trash)
1275        }
1276        Err(err) => Err(put_back(fs, ops, item, desired, &aside, exclude, err)),
1277    }
1278}
1279
1280/// Undoes a replacement that failed before the trash held the folder;
1281/// `err` with what could not be undone added.
1282fn put_back(
1283    fs: &dyn Fs,
1284    ops: &ReplaceOps,
1285    item: &Replacement,
1286    desired: &Desired,
1287    aside: &Path,
1288    exclude: Option<Saved>,
1289    err: CoreError,
1290) -> CoreError {
1291    let mut notes = Vec::new();
1292    // The entry path was free (or the folder itself, now aside): what is
1293    // there was made by this replacement.
1294    let removed = match entry(fs, &desired.path) {
1295        Ok(Entry::Link(_)) => remove_link(fs, &desired.path),
1296        Ok(Entry::Dir) if desired.method == LinkMethod::Copy => remove_copy(fs, &desired.path),
1297        _ => Ok(()),
1298    };
1299    if let Err(failed) = removed {
1300        notes.push(failed.message().to_owned());
1301    }
1302    if let Err(back) = (ops.rename)(aside, &item.folder) {
1303        notes.push(format!(
1304            "the folder cannot be moved back from {}: {back}",
1305            aside.display()
1306        ));
1307    }
1308    if let Some((file, bytes)) = exclude {
1309        let restored = match bytes {
1310            Some(bytes) => fs.write(&file, &bytes),
1311            None if fs.exists(&file) => fs.remove_file(&file),
1312            None => Ok(()),
1313        };
1314        if let Err(failed) = restored {
1315            notes.push(format!("{} cannot be restored: {failed}", file.display()));
1316        }
1317    }
1318    if notes.is_empty() {
1319        return err;
1320    }
1321    let message = format!("{}; also, {}", err.message(), notes.join("; "));
1322    let kept = CoreError::new(err.code(), message).with_path(&item.folder);
1323    match err.read_only() {
1324        Some(kind) => kept.with_read_only(kind),
1325        None => kept,
1326    }
1327}
1328
1329/// A file and its bytes before a change (`None`: it did not exist).
1330type Saved = (PathBuf, Option<Vec<u8>>);
1331
1332/// The project repository's `info/exclude` as it is before a replacement,
1333/// when the entry is in a project with a repository.
1334fn exclude_state(fs: &dyn Fs, desired: &Desired) -> Result<Option<Saved>, CoreError> {
1335    let Some(root) = &desired.project_root else {
1336        return Ok(None);
1337    };
1338    let Some(repo) = ProjectRepo::discover(root)? else {
1339        return Ok(None);
1340    };
1341    let file = repo.exclude_file();
1342    let bytes = if fs.exists(&file) {
1343        Some(
1344            fs.read(&file)
1345                .map_err(|err| io_error("cannot read file", &file, &err))?,
1346        )
1347    } else {
1348        None
1349    };
1350    Ok(Some((file, bytes)))
1351}
1352
1353/// Moves the folder set `aside` to `trash`: a rename, or across drives
1354/// (`ERROR_NOT_SAME_DEVICE`, `EXDEV`) a copy that is compared with the
1355/// folder before the folder is removed. A failed copy is removed and the
1356/// folder stays aside (the caller puts it back).
1357fn move_to_trash(
1358    fs: &dyn Fs,
1359    ops: &ReplaceOps,
1360    aside: &Path,
1361    trash: &Path,
1362) -> Result<(), CoreError> {
1363    confine(fs, trash)?;
1364    match (ops.rename)(aside, trash) {
1365        Ok(()) => Ok(()),
1366        Err(err) if err.kind() == io::ErrorKind::CrossesDevices => {
1367            let copied = (ops.copy_tree)(aside, trash).and_then(|()| {
1368                if tree_snapshot(aside)? == tree_snapshot(trash)? {
1369                    Ok(())
1370                } else {
1371                    Err(io::Error::other(
1372                        "the copy in the trash differs from the folder",
1373                    ))
1374                }
1375            });
1376            if let Err(err) = copied {
1377                let _ = std::fs::remove_dir_all(trash);
1378                return Err(io_error(
1379                    "cannot copy the folder to the trash on another drive",
1380                    aside,
1381                    &err,
1382                ));
1383            }
1384            // The trash holds a checked copy; a folder that cannot be
1385            // removed now stays as a hidden `.<name>.surjection-adopt`.
1386            let _ = std::fs::remove_dir_all(aside);
1387            Ok(())
1388        }
1389        Err(err) => Err(io_error("cannot move the folder to the trash", aside, &err)),
1390    }
1391}
1392
1393/// Copies the folder `from` to the new path `to`: folders and files (with
1394/// their permissions); a link inside is refused.
1395fn copy_tree(from: &Path, to: &Path) -> io::Result<()> {
1396    std::fs::create_dir(to)?;
1397    for item in std::fs::read_dir(from)? {
1398        let item = item?;
1399        let kind = item.file_type()?;
1400        let target = to.join(item.file_name());
1401        if kind.is_symlink() {
1402            return Err(io::Error::other(format!(
1403                "{} is a link, which is not copied across drives",
1404                item.path().display()
1405            )));
1406        } else if kind.is_dir() {
1407            copy_tree(&item.path(), &target)?;
1408        } else {
1409            std::fs::copy(item.path(), &target)?;
1410        }
1411    }
1412    Ok(())
1413}
1414
1415/// Every folder (`None`) and file (its bytes) below `dir`, by relative path.
1416fn tree_snapshot(dir: &Path) -> io::Result<BTreeMap<String, Option<Vec<u8>>>> {
1417    fn walk(
1418        dir: &Path,
1419        prefix: &str,
1420        out: &mut BTreeMap<String, Option<Vec<u8>>>,
1421    ) -> io::Result<()> {
1422        for item in std::fs::read_dir(dir)? {
1423            let item = item?;
1424            let relative = format!("{prefix}/{}", item.file_name().to_string_lossy());
1425            if item.file_type()?.is_dir() {
1426                out.insert(relative.clone(), None);
1427                walk(&item.path(), &relative, out)?;
1428            } else {
1429                out.insert(relative, Some(std::fs::read(item.path())?));
1430            }
1431        }
1432        Ok(())
1433    }
1434    let mut out = BTreeMap::new();
1435    walk(dir, "", &mut out)?;
1436    Ok(out)
1437}
1438
1439/// What the store copy of `dir` would not keep, named for the user: an
1440/// empty folder (the store keeps files), or on Unix an executable file
1441/// (store files have no mode). `None` when nothing.
1442fn lost_in_store(fs: &dyn Fs, root: &Path, dir: &Path) -> Result<Option<String>, CoreError> {
1443    let shown = |path: &Path| {
1444        path.strip_prefix(root)
1445            .unwrap_or(path)
1446            .to_string_lossy()
1447            .replace('\\', "/")
1448    };
1449    for path in fs
1450        .read_dir(dir)
1451        .map_err(|err| io_error("cannot list directory", dir, &err))?
1452    {
1453        let Some(name) = path.file_name().and_then(|name| name.to_str()) else {
1454            continue;
1455        };
1456        if name == ".git" || crate::skills::is_marker(name) {
1457            continue;
1458        }
1459        match entry(fs, &path)? {
1460            Entry::Dir => {
1461                let empty = fs
1462                    .read_dir(&path)
1463                    .map_err(|err| io_error("cannot list directory", &path, &err))?
1464                    .is_empty();
1465                if empty {
1466                    return Ok(Some(format!("the empty folder {}", shown(&path))));
1467                }
1468                if let Some(what) = lost_in_store(fs, root, &path)? {
1469                    return Ok(Some(what));
1470                }
1471            }
1472            Entry::File => {
1473                #[cfg(unix)]
1474                {
1475                    use std::os::unix::fs::PermissionsExt;
1476                    let mode = std::fs::metadata(&path)
1477                        .map_err(|err| io_error("cannot read file metadata", &path, &err))?
1478                        .permissions()
1479                        .mode();
1480                    if mode & 0o111 != 0 {
1481                        return Ok(Some(format!("the executable mode of {}", shown(&path))));
1482                    }
1483                }
1484            }
1485            Entry::Link(_) | Entry::Missing => {}
1486        }
1487    }
1488    Ok(None)
1489}
1490
1491/// Enables (or disables) skill `id` for `clients` at user scope: one
1492/// commit of `skill-meta/<id>.toml`, then [`sync`]. Enabling with no
1493/// clients selects `all-detected`; disabling with none turns the skill off
1494/// everywhere. `method` changes how it is distributed.
1495pub fn set_enabled(
1496    store: &Store<'_>,
1497    sx: &SkillsEnv<'_>,
1498    id: &str,
1499    clients: &[String],
1500    enabled: bool,
1501    method: Option<DistributionMethod>,
1502) -> Result<(Option<CommitId>, SyncReport), CoreError> {
1503    ids::check(IdKind::Skill, id)?;
1504    for client in clients {
1505        if client_skills(client).is_none() {
1506            return Err(no_skills(client));
1507        }
1508    }
1509    let verb = if enabled { "enable" } else { "disable" };
1510    let target = if clients.is_empty() {
1511        if enabled {
1512            "all detected clients".to_owned()
1513        } else {
1514            "all clients".to_owned()
1515        }
1516    } else {
1517        clients.join(", ")
1518    };
1519    let operation = Operation::new(
1520        format!("skill.{verb}"),
1521        format!("skill: {verb} {id} for {target}"),
1522    )
1523    .entity(format!("skill/{id}"));
1524    let committed = store.transaction(operation, |tx| {
1525        if !store::exists(tx, id)? {
1526            return Err(store::not_found(id));
1527        }
1528        let mut meta = store::read_meta(tx, id)?.unwrap_or_else(|| SkillMeta::new(id));
1529        let enable = meta.enable.get_or_insert_with(SkillEnable::default);
1530        let current = enable.clients.take();
1531        enable.clients = next_selection(sx, current, clients, enabled);
1532        if let Some(method) = method {
1533            enable.method = Some(method);
1534        }
1535        if enable.clients.is_none() && enable.method.is_none() && enable.extra.is_empty() {
1536            meta.enable = None;
1537        }
1538        store::stage_meta(tx, &meta)
1539    })?;
1540    let report = sync(store, sx)?;
1541    Ok((committed.commit, report))
1542}
1543
1544/// Sets how skill `id` reaches client folders at user scope (SPEC 12.2:
1545/// link or copy), leaving its clients as they are: one commit of
1546/// `skill-meta/<id>.toml` (`skill: distribute <id> as <method>`), `None`
1547/// when unchanged, then [`sync`].
1548pub fn set_method(
1549    store: &Store<'_>,
1550    sx: &SkillsEnv<'_>,
1551    id: &str,
1552    method: DistributionMethod,
1553) -> Result<(Option<CommitId>, SyncReport), CoreError> {
1554    ids::check(IdKind::Skill, id)?;
1555    let name = match method {
1556        DistributionMethod::Link => "link",
1557        DistributionMethod::Copy => "copy",
1558    };
1559    let operation = Operation::new("skill.method", format!("skill: distribute {id} as {name}"))
1560        .entity(format!("skill/{id}"));
1561    let committed = store.transaction(operation, |tx| {
1562        if !store::exists(tx, id)? {
1563            return Err(store::not_found(id));
1564        }
1565        let mut meta = store::read_meta(tx, id)?.unwrap_or_else(|| SkillMeta::new(id));
1566        meta.enable.get_or_insert_with(SkillEnable::default).method = Some(method);
1567        store::stage_meta(tx, &meta)
1568    })?;
1569    let report = sync(store, sx)?;
1570    Ok((committed.commit, report))
1571}
1572
1573fn next_selection(
1574    sx: &SkillsEnv<'_>,
1575    current: Option<ClientSelection>,
1576    clients: &[String],
1577    enabled: bool,
1578) -> Option<ClientSelection> {
1579    if clients.is_empty() {
1580        return enabled.then_some(ClientSelection::AllDetected);
1581    }
1582    let mut list: BTreeSet<String> = match &current {
1583        Some(ClientSelection::List(ids)) => ids.iter().cloned().collect(),
1584        Some(ClientSelection::AllDetected) => {
1585            if enabled {
1586                return current;
1587            }
1588            DetectedClients::new(sx)
1589                .clients()
1590                .iter()
1591                .map(|client| (*client).to_owned())
1592                .collect()
1593        }
1594        None => BTreeSet::new(),
1595    };
1596    for client in clients {
1597        if enabled {
1598            list.insert(client.clone());
1599        } else {
1600            list.remove(client);
1601        }
1602    }
1603    (!list.is_empty()).then(|| ClientSelection::List(list.into_iter().collect()))
1604}
1605
1606/// Enables (or disables) skill `id` in a project (SPEC 12.3): edits
1607/// `[skills] enable` of the project's private manifest (the shared one when
1608/// there is no private one), commits the store mirror, trusts the edited
1609/// content (Surjection wrote it), then [`sync`]s. The project must be known on
1610/// this machine and trusted as it is. `expected` is the manifests' content
1611/// hash the caller showed (the app); the manifests are re-read right
1612/// before the write, and content other than what was trusted (and shown)
1613/// is `trust_required`, with nothing written. Disabling a skill the
1614/// shared `project.toml` enables, in a project with a private file, is
1615/// `invalid_value` naming that file.
1616pub fn set_project_enabled(
1617    store: &Store<'_>,
1618    sx: &SkillsEnv<'_>,
1619    folder: &Path,
1620    id: &str,
1621    enabled: bool,
1622    expected: Option<&str>,
1623) -> Result<(Option<CommitId>, SyncReport), CoreError> {
1624    ids::check(IdKind::Skill, id)?;
1625    let project = trusted_project(store, sx, folder)?;
1626    if enabled {
1627        let has_content = store::get(store, id)?.is_some_and(|skill| skill.has_content);
1628        if !has_content {
1629            return Err(store::not_found(id));
1630        }
1631    }
1632    // Disabling in the private file leaves a skill the shared file enables
1633    // on: say so instead of reporting a change that did not happen.
1634    if !enabled
1635        && project.local.is_some()
1636        && let Some(shared) = &project.shared
1637        && manifest_enables(&shared.manifest, id)
1638    {
1639        return Err(CoreError::new(
1640            ErrorCode::InvalidValue,
1641            format!(
1642                "skill {id:?} is enabled by the shared project.toml, which teammates use too; \
1643                 remove it from [skills] enable there"
1644            ),
1645        )
1646        .with_path(&shared.path));
1647    }
1648    let (text, path) = skills_file_text(&project)?;
1649    let Some(edited) = edit_manifest(&text, id, enabled, &path)? else {
1650        let report = sync(store, sx)?;
1651        return Ok((None, report));
1652    };
1653    let verb = if enabled { "enable" } else { "disable" };
1654    let operation = Operation::new(
1655        format!("skill.project-{verb}"),
1656        format!("skill: {verb} {id} in project {}", project.id),
1657    )
1658    .entity(format!("skill/{id}"))
1659    .entity(format!("project/{}", project.id))
1660    .scope(store_mod::Scope::Project(project.id.clone()));
1661    let committed =
1662        commit_project_edit(
1663            store,
1664            sx,
1665            &project,
1666            &edited,
1667            expected,
1668            operation,
1669            |_| Ok(()),
1670        )?;
1671    let report = sync(store, sx)?;
1672    Ok((committed.commit, report))
1673}
1674
1675/// The project known on this machine at `folder`, trusted as it is now;
1676/// `not_found` for an unknown or missing folder, `trust_required` when
1677/// not trusted.
1678pub(crate) fn trusted_project(
1679    store: &Store<'_>,
1680    sx: &SkillsEnv<'_>,
1681    folder: &Path,
1682) -> Result<Project, CoreError> {
1683    let fs = sx.fs;
1684    let state = sx.home.state_dir();
1685    let overlay = this_overlay(store, fs, &state)?;
1686    let trust = TrustStore::load(fs, &state)?;
1687    let known = known_projects(fs, sx.env, overlay.as_ref(), &trust)
1688        .into_iter()
1689        .find(|known| same_folder(fs, &known.root, folder))
1690        .ok_or_else(|| {
1691            CoreError::new(
1692                ErrorCode::NotFound,
1693                format!(
1694                    "the folder is not a project this machine knows; run `{} project add` first",
1695                    crate::brand::BIN_NAME
1696                ),
1697            )
1698            .with_path(folder)
1699        })?;
1700    match &known.status {
1701        ProjectStatus::Loaded { project, .. } => {
1702            if let Some(err) = known.trust_error() {
1703                return Err(err);
1704            }
1705            Ok(project.as_ref().clone())
1706        }
1707        ProjectStatus::Missing => Err(CoreError::new(
1708            ErrorCode::NotFound,
1709            "the project folder does not exist",
1710        )
1711        .with_path(&known.root)),
1712        ProjectStatus::Failed(err) => Err(err.clone()),
1713    }
1714}
1715
1716/// The text and path of the manifest `[skills]` edits go to: the private
1717/// file, else the shared one.
1718pub(crate) fn skills_file_text(project: &Project) -> Result<(String, PathBuf), CoreError> {
1719    let file = project
1720        .local
1721        .as_ref()
1722        .or(project.shared.as_ref())
1723        .expect("a loaded project has a manifest");
1724    let text = String::from_utf8(file.bytes.clone()).map_err(|_| {
1725        CoreError::new(ErrorCode::ParseError, "the manifest is not UTF-8").with_path(&file.path)
1726    })?;
1727    Ok((text, file.path.clone()))
1728}
1729
1730/// Writes `edited` over the file [`skills_file_text`] names, then commits
1731/// `operation`: the store mirror of the edited manifests, trusted (Surjection
1732/// wrote them), plus what `stage` stages. The manifests must still be what
1733/// was trusted and read (and `expected`, the hash the caller showed);
1734/// other content is `trust_required`, with nothing written. When the
1735/// commit fails, the file and the trust state are put back.
1736pub(crate) fn commit_project_edit<T>(
1737    store: &Store<'_>,
1738    sx: &SkillsEnv<'_>,
1739    project: &Project,
1740    edited: &str,
1741    expected: Option<&str>,
1742    operation: Operation,
1743    stage: impl FnOnce(&mut crate::store::Transaction<'_>) -> Result<T, CoreError>,
1744) -> Result<crate::store::Committed<T>, CoreError> {
1745    let fs = sx.fs;
1746    let state = sx.home.state_dir();
1747    // The edit is trusted below: both files must still be what was
1748    // trusted and read (a `git pull` in between needs a review first).
1749    let hash = project.hash();
1750    if manifests_hash(fs, &project.root)? != hash || expected.is_some_and(|shown| shown != hash) {
1751        return Err(CoreError::new(
1752            ErrorCode::TrustRequired,
1753            format!(
1754                "the manifests of project {:?} changed while being edited; review them, then \
1755                 run `{} project trust {}`",
1756                project.id,
1757                crate::brand::BIN_NAME,
1758                project.root.display()
1759            ),
1760        )
1761        .with_path(crate::layering::manifest::manifest_dir(fs, &project.root)));
1762    }
1763    let file = project
1764        .local
1765        .as_ref()
1766        .or(project.shared.as_ref())
1767        .expect("a loaded project has a manifest");
1768    let before = file.bytes.clone();
1769    let path = file.path.clone();
1770    let previous = TrustStore::load(fs, &state)?;
1771    crate::layering::projects::write_file(fs, &path, edited.as_bytes())?;
1772    let committed = (|| {
1773        let reloaded = crate::layering::projects::load_project(fs, &project.root)?;
1774        store.transaction(operation, |tx| {
1775            let value = stage(tx)?;
1776            mirror(tx, &reloaded)?;
1777            let mut trust = TrustStore::load(fs, &state)?;
1778            trust.trust(&reloaded);
1779            trust.save(fs, &state)?;
1780            Ok(value)
1781        })
1782    })();
1783    match committed {
1784        Ok(committed) => Ok(committed),
1785        Err(err) => {
1786            let _ = crate::layering::projects::write_file(fs, &path, &before);
1787            let _ = previous.save(fs, &state);
1788            Err(err)
1789        }
1790    }
1791}
1792
1793/// Whether `[skills] enable` of `manifest` lists `id`.
1794pub fn manifest_enables(manifest: &ProjectManifest, id: &str) -> bool {
1795    manifest
1796        .skills
1797        .as_ref()
1798        .and_then(|skills| skills.enable.as_ref())
1799        .is_some_and(|enable| enable.iter().any(|known| known == id))
1800}
1801
1802/// [`crate::layering::content_hash`] of the manifests in `root` as they are
1803/// on disk now.
1804fn manifests_hash(fs: &dyn Fs, root: &Path) -> Result<String, CoreError> {
1805    let dir = crate::layering::manifest::manifest_dir(fs, root);
1806    let read = |name: &str| -> Result<Option<Vec<u8>>, CoreError> {
1807        let path = dir.join(name);
1808        if !fs.exists(&path) {
1809            return Ok(None);
1810        }
1811        fs.read(&path)
1812            .map(Some)
1813            .map_err(|err| io_error("cannot read file", &path, &err))
1814    };
1815    let shared = read(crate::layering::SHARED_FILE)?;
1816    let local = read(crate::layering::LOCAL_FILE)?;
1817    Ok(crate::layering::content_hash(
1818        shared.as_deref(),
1819        local.as_deref(),
1820    ))
1821}
1822
1823/// `[skills] enable` with `id` added or removed, comments kept; `None`
1824/// when nothing changes.
1825pub(crate) fn edit_manifest(
1826    text: &str,
1827    id: &str,
1828    enabled: bool,
1829    path: &Path,
1830) -> Result<Option<String>, CoreError> {
1831    let mut doc: toml_edit::DocumentMut = text.parse().map_err(|err| {
1832        CoreError::new(
1833            ErrorCode::ParseError,
1834            format!("the manifest does not parse: {err}"),
1835        )
1836        .with_path(path)
1837    })?;
1838    let shape = || {
1839        CoreError::new(
1840            ErrorCode::UnexpectedShape,
1841            "`skills` must be a table with an `enable` array",
1842        )
1843        .with_path(path)
1844    };
1845    if !doc.contains_key("skills") {
1846        if !enabled {
1847            return Ok(None);
1848        }
1849        doc["skills"] = toml_edit::table();
1850    }
1851    let skills = doc["skills"].as_table_like_mut().ok_or_else(shape)?;
1852    if skills.get("enable").is_none() {
1853        if !enabled {
1854            return Ok(None);
1855        }
1856        skills.insert("enable", toml_edit::value(toml_edit::Array::new()));
1857    }
1858    let array = skills
1859        .get_mut("enable")
1860        .and_then(toml_edit::Item::as_array_mut)
1861        .ok_or_else(shape)?;
1862    let position = array.iter().position(|value| value.as_str() == Some(id));
1863    match (enabled, position) {
1864        (true, None) => array.push(id),
1865        (false, Some(index)) => {
1866            array.remove(index);
1867        }
1868        _ => return Ok(None),
1869    }
1870    Ok(Some(doc.to_string()))
1871}
1872
1873/// Every owned entry of skill `id` (for listings).
1874pub fn owned_entries<'a>(
1875    ledger: &'a SkillLedger,
1876    id: &'a str,
1877) -> impl Iterator<Item = &'a SkillLink> {
1878    ledger.links.iter().filter(move |link| link.skill_id == id)
1879}