surjection-core 1.2.0

Core library of Surjection: MCP servers, skills and secret references for AI coding clients
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
//! Skills (SPEC 12): the store copy of each skill (`store/skills/<id>/`
//! plus `store/skill-meta/<id>.toml`), installs from git or local sources,
//! links and copies in client skill directories (table 7.6), the
//! classification of those directories, and the read-only scan of the
//! agents CLI's `~/.agents/skills`.
//!
//! Store changes are one commit each; links and copies follow right after
//! the commit ([`link::sync`], instant apply) under the store lock, owned
//! through the machine-local ledger.
//!
//! Links and archives need file system operations [`Fs`] does not have
//! (link creation, link metadata, renames). They use `std::fs` directly,
//! after [`confine`] checks the path against the view's root, so a test
//! with a rooted view still cannot reach outside its temp root.

pub mod adopt;
pub mod agents_cli;
pub mod classify;
pub mod frontmatter;
pub mod hash_cache;
pub mod install;
pub mod link;
#[cfg(test)]
mod read_only_tests;
#[cfg(test)]
mod replace_tests;
pub mod store;

use std::borrow::Cow;
use std::collections::BTreeMap;
use std::io;
use std::path::{Path, PathBuf};

use sha2::{Digest, Sha256};

use crate::adapters::detect::RegistryProbe;
use crate::env::Env;
use crate::error::{CoreError, ErrorCode};
use crate::fs::Fs;
use crate::paths::{SurjectionHome, normalize, plain};
use crate::remote::git::Runner;

pub use install::{
    Decisions, InstallRequest, Installed, Naming, Prepared, Source, UpdateCheck, UpdateStatus,
    Updated,
};
pub use link::{LinkKind, LinkResult, LinkStatus, SkillLedger, SkillLink, SyncReport};
pub use store::StoreSkill;

/// The skill's entry file.
pub const SKILL_FILE: &str = "SKILL.md";
/// Marker file in a copy Surjection made (SPEC 12.2); never part of a skill.
pub const MARKER_FILE: &str = ".surjection-managed";
/// The marker Loadout 1.0.x wrote in its copies; still recognized as one.
pub const LEGACY_MARKER_FILE: &str = ".loadout-managed";

/// Whether a file name at the top of a copy is a marker (current or legacy).
pub fn is_marker(name: &str) -> bool {
    name == MARKER_FILE || name == LEGACY_MARKER_FILE
}
/// Largest skill (SPEC 12.1).
pub const MAX_SKILL_BYTES: u64 = 100 * 1024 * 1024;
/// Total store skill size that raises a warning (SPEC 12.1).
pub const WARN_TOTAL_BYTES: u64 = 500 * 1024 * 1024;
/// Most files in a `.zip` or `.skill` archive (SPEC 17).
pub const MAX_ARCHIVE_FILES: usize = 500;
/// Largest file in an archive (SPEC 17).
pub const MAX_ARCHIVE_FILE_BYTES: u64 = 5 * 1024 * 1024;
/// Largest total of an archive's files (SPEC 17).
pub const MAX_ARCHIVE_TOTAL_BYTES: u64 = 20 * 1024 * 1024;

/// A skill's files: `/`-separated relative path to bytes.
pub type SkillFiles = BTreeMap<String, Vec<u8>>;

/// What skill operations run against.
#[derive(Clone, Copy)]
pub struct SkillsEnv<'a> {
    pub env: &'a Env,
    pub fs: &'a dyn Fs,
    pub home: &'a SurjectionHome,
    /// Detection for `all-detected` client selections.
    pub registry: &'a dyn RegistryProbe,
    /// Runs the system git (git sources) and the agents `skills` CLI.
    pub runner: &'a dyn Runner,
    /// How links are made on Windows: a junction (default) or a directory
    /// symbolic link (needs Developer Mode or admin rights). Ignored
    /// elsewhere, where links are symbolic links.
    pub link_kind: LinkKind,
}

impl std::fmt::Debug for SkillsEnv<'_> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("SkillsEnv")
            .field("home", &self.home.path)
            .field("link_kind", &self.link_kind)
            .finish_non_exhaustive()
    }
}

/// `invalid_path` when `path` lies outside the view `fs` is confined to.
/// Every direct `std::fs` call in this module checks its paths here first.
pub(crate) fn confine(fs: &dyn Fs, path: &Path) -> Result<(), CoreError> {
    let Some(root) = fs.root() else {
        return Ok(());
    };
    if path.is_absolute() && normalize(path).starts_with(root) {
        Ok(())
    } else {
        Err(CoreError::new(
            ErrorCode::InvalidPath,
            "the path is outside the file system view",
        )
        .with_path(path))
    }
}

pub(crate) fn io_error(what: &str, path: &Path, err: &io::Error) -> CoreError {
    CoreError::new(ErrorCode::IoError, format!("{what}: {err}")).with_path(path)
}

/// A failed write into a client skill folder: `read_only_target` when the
/// OS refused it as read only (SPEC 8.2, 12.2), else [`io_error`].
pub(crate) fn write_error(fs: &dyn Fs, what: &str, path: &Path, err: &io::Error) -> CoreError {
    crate::access::write_error(fs, what, path, err)
}

/// A failed removal or rename of the entry at `path` (a link, a copy, a
/// folder moved aside): what decides is the folder holding it, so that
/// folder is probed, never `path` itself (a link leads into the store,
/// which is always writable). The error keeps `path`.
pub(crate) fn removal_error(fs: &dyn Fs, what: &str, path: &Path, err: &io::Error) -> CoreError {
    match path
        .parent()
        .and_then(|folder| crate::access::denied(fs, err, folder))
    {
        Some(kind) => crate::access::read_only_target(kind, path),
        None => io_error(what, path, err),
    }
}

/// A path inside `folder`, a folder that does not exist yet: probing it
/// asks the nearest existing folder for creating a subfolder
/// (`FILE_ADD_SUBDIRECTORY` on Windows), which is what making a junction,
/// a symbolic link to a folder or a copy needs, not creating a file.
fn inside_new(folder: &Path) -> PathBuf {
    folder.join(".surjection-new")
}

/// Whether this account can create the folder entry `path` (missing).
pub(crate) fn new_folder_access(fs: &dyn Fs, path: &Path) -> crate::access::WriteAccess {
    crate::access::probe_path(fs, &inside_new(path))
}

/// A failed creation of the folder entry `path` (a junction, a link, a
/// copy): `read_only_target` when its folder does not let this account
/// create a subfolder, else [`io_error`].
pub(crate) fn creation_error(fs: &dyn Fs, what: &str, path: &Path, err: &io::Error) -> CoreError {
    match crate::access::denied(fs, err, &inside_new(path)) {
        Some(kind) => crate::access::read_only_target(kind, path),
        None => io_error(what, path, err),
    }
}

/// What is at a path, without following a final link.
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) enum Entry {
    Missing,
    /// A symbolic link or junction, with its target as stored.
    Link(PathBuf),
    Dir,
    File,
}

pub(crate) fn entry(fs: &dyn Fs, path: &Path) -> Result<Entry, CoreError> {
    confine(fs, path)?;
    let meta = match std::fs::symlink_metadata(path) {
        Ok(meta) => meta,
        Err(err) if err.kind() == io::ErrorKind::NotFound => return Ok(Entry::Missing),
        Err(err) => return Err(io_error("cannot read file metadata", path, &err)),
    };
    // std counts junctions as links (name-surrogate reparse points), and
    // `read_link` reads their target.
    if meta.file_type().is_symlink() {
        let target = std::fs::read_link(path)
            .map_err(|err| io_error("cannot read the link target", path, &err))?;
        return Ok(Entry::Link(plain_target(path, target)));
    }
    Ok(if meta.is_dir() {
        Entry::Dir
    } else {
        Entry::File
    })
}

/// A link target as a plain absolute path: Windows junction targets come
/// back verbatim (`\\?\C:\...`, `\\?\UNC\server\...`), and relative
/// symbolic link targets are relative to the link's folder.
fn plain_target(link: &Path, target: PathBuf) -> PathBuf {
    if let Cow::Owned(target) = plain(&target) {
        return target;
    }
    if target.is_relative()
        && let Some(parent) = link.parent()
    {
        return normalize(&parent.join(&target));
    }
    target
}

/// Reads a skill folder: every file below `dir`, except nested `.git`
/// folders and files (SPEC 12.1) and [`MARKER_FILE`]. A link (file or
/// folder) is followed only when it resolves inside `dir`; one that
/// escapes is `invalid_path` (SPEC 17). More than [`MAX_SKILL_BYTES`] is
/// `invalid_value`.
pub fn read_folder(fs: &dyn Fs, dir: &Path) -> Result<SkillFiles, CoreError> {
    Ok(read_folder_skipping(fs, dir, &[])?.0)
}

/// [`read_folder`] leaving out the folders named `skip` (at any depth,
/// case-insensitive; links named so too): their contents are neither read
/// nor counted. Returns the files and the relative paths of the folders
/// left out. MCP sources skip dependency and build folders (#5).
pub(crate) fn read_folder_skipping(
    fs: &dyn Fs,
    dir: &Path,
    skip: &[&str],
) -> Result<(SkillFiles, Vec<String>), CoreError> {
    let mut files = SkillFiles::new();
    let mut skip = SkipDirs {
        names: skip,
        skipped: Vec::new(),
    };
    walk_folder(fs, dir, &mut skip, &mut |relative, path, _| {
        let bytes = fs
            .read(path)
            .map_err(|err| io_error("cannot read file", path, &err))?;
        let read = bytes.len() as u64;
        files.insert(relative, bytes);
        Ok(read)
    })?;
    Ok((files, skip.skipped))
}

/// Folders a walk leaves out by name, and the ones it left out.
struct SkipDirs<'a> {
    names: &'a [&'a str],
    skipped: Vec<String>,
}

/// What [`summarize_folder`] found in a skill folder.
#[derive(Debug, Clone, Default)]
pub struct FolderSummary {
    /// Total size of the files, from their metadata.
    pub bytes: u64,
    /// The bytes of the top-level [`SKILL_FILE`], when there is one.
    pub skill_file: Option<Vec<u8>>,
}

/// A skill folder as [`read_folder`] sees it (the same files, checks and
/// errors), without reading the contents: sizes come from file metadata,
/// every other file is opened for reading (so one this account cannot
/// read, or one another process holds without read sharing, is the same
/// `cannot read file` error) but not read, and only [`SKILL_FILE`] is
/// read. Listings use it (#16); anything that copies, hashes or compares
/// content uses [`read_folder`].
pub fn summarize_folder(fs: &dyn Fs, dir: &Path) -> Result<FolderSummary, CoreError> {
    let mut skill_file = None;
    let mut skip = SkipDirs {
        names: &[],
        skipped: Vec::new(),
    };
    let bytes = walk_folder(fs, dir, &mut skip, &mut |relative, path, len| {
        if relative != SKILL_FILE {
            std::fs::File::open(path).map_err(|err| io_error("cannot read file", path, &err))?;
            return Ok(len);
        }
        let bytes = fs
            .read(path)
            .map_err(|err| io_error("cannot read file", path, &err))?;
        let read = bytes.len() as u64;
        skill_file = Some(bytes);
        Ok(read)
    })?;
    Ok(FolderSummary { bytes, skill_file })
}

/// Called by [`walk`] for each file: its relative path, its path and its
/// size from metadata; returns the bytes it counts towards the total.
type OnFile<'a> = dyn FnMut(String, &Path, u64) -> Result<u64, CoreError> + 'a;

/// Walks `dir` as [`read_folder`] describes; the total counted.
fn walk_folder(
    fs: &dyn Fs,
    dir: &Path,
    skip: &mut SkipDirs<'_>,
    on_file: &mut OnFile<'_>,
) -> Result<u64, CoreError> {
    confine(fs, dir)?;
    let root = fs
        .canonicalize(dir)
        .map_err(|err| io_error("cannot resolve folder", dir, &err))?;
    let mut total = 0u64;
    let mut visited = vec![root.clone()];
    walk(fs, &root, dir, "", skip, on_file, &mut total, &mut visited)?;
    Ok(total)
}

/// Whether a `.git` folder or file is anywhere below `dir` (links are not
/// followed). [`content_hash`] leaves `.git` out, so a copy the user turned
/// into a repository would otherwise look unchanged.
pub(crate) fn has_nested_git(fs: &dyn Fs, dir: &Path) -> Result<bool, CoreError> {
    let entries = fs
        .read_dir(dir)
        .map_err(|err| io_error("cannot list directory", dir, &err))?;
    for path in entries {
        if path
            .file_name()
            .is_some_and(|name| name.eq_ignore_ascii_case(".git"))
        {
            return Ok(true);
        }
        if entry(fs, &path)? == Entry::Dir && has_nested_git(fs, &path)? {
            return Ok(true);
        }
    }
    Ok(false)
}

#[allow(clippy::too_many_arguments)]
fn walk(
    fs: &dyn Fs,
    root: &Path,
    dir: &Path,
    prefix: &str,
    skip: &mut SkipDirs<'_>,
    on_file: &mut OnFile<'_>,
    total: &mut u64,
    visited: &mut Vec<PathBuf>,
) -> Result<(), CoreError> {
    let entries = fs
        .read_dir(dir)
        .map_err(|err| io_error("cannot list directory", dir, &err))?;
    for path in entries {
        let Some(name) = path.file_name().and_then(|name| name.to_str()) else {
            return Err(CoreError::new(
                ErrorCode::InvalidPath,
                "a file name in the skill is not valid Unicode",
            )
            .with_path(&path));
        };
        if name.eq_ignore_ascii_case(".git") || (prefix.is_empty() && is_marker(name)) {
            continue;
        }
        check_name(name, &path)?;
        let relative = if prefix.is_empty() {
            name.to_owned()
        } else {
            format!("{prefix}/{name}")
        };
        if skip
            .names
            .iter()
            .any(|skipped| name.eq_ignore_ascii_case(skipped))
            && fs.is_dir(&path)
        {
            skip.skipped.push(relative);
            continue;
        }
        let is_dir = match entry(fs, &path)? {
            Entry::Missing => continue,
            Entry::Link(_) => {
                let resolved = fs.canonicalize(&path).map_err(|err| {
                    CoreError::new(
                        ErrorCode::InvalidPath,
                        format!("a link in the skill cannot be resolved: {err}"),
                    )
                    .with_path(&path)
                })?;
                if !resolved.starts_with(root) {
                    return Err(CoreError::new(
                        ErrorCode::InvalidPath,
                        "a link in the skill points outside the skill folder",
                    )
                    .with_path(&path));
                }
                let is_dir = fs.is_dir(&path);
                if is_dir {
                    if visited.contains(&resolved) {
                        continue;
                    }
                    visited.push(resolved);
                }
                is_dir
            }
            Entry::Dir => true,
            Entry::File => false,
        };
        if is_dir {
            walk(fs, root, &path, &relative, skip, on_file, total, visited)?;
        } else {
            // The size first: a huge file is refused before it is read.
            let len = std::fs::metadata(&path)
                .map_err(|err| io_error("cannot read file metadata", &path, &err))?
                .len();
            if *total + len > MAX_SKILL_BYTES {
                return Err(too_large(&path));
            }
            *total += on_file(relative, &path, len)?;
            if *total > MAX_SKILL_BYTES {
                return Err(too_large(&path));
            }
        }
    }
    Ok(())
}

pub(crate) fn too_large(path: &Path) -> CoreError {
    CoreError::new(
        ErrorCode::InvalidValue,
        format!(
            "the skill is larger than {} MB",
            MAX_SKILL_BYTES / (1024 * 1024)
        ),
    )
    .with_path(path)
}

/// A file name the store can hold on every OS (no `\`, `:`, `.` or `..`).
pub(crate) fn check_name(name: &str, path: &Path) -> Result<(), CoreError> {
    if name.is_empty() || name == "." || name == ".." || name.contains(['\\', ':', '/']) {
        return Err(CoreError::new(
            ErrorCode::InvalidPath,
            format!("{name:?} cannot be stored as a skill file name"),
        )
        .with_path(path));
    }
    Ok(())
}

/// `sha256:<hex>` over a skill's files (paths and bytes, sorted), the
/// content hash of copies in the ledger.
pub fn content_hash(files: &SkillFiles) -> String {
    let mut hasher = Sha256::new();
    for (path, bytes) in files {
        hasher.update(path.as_bytes());
        hasher.update([0]);
        hasher.update((bytes.len() as u64).to_le_bytes());
        hasher.update(bytes);
    }
    let digest = hasher.finalize();
    let mut text = String::with_capacity(7 + digest.len() * 2);
    text.push_str("sha256:");
    for byte in digest {
        text.push_str(&format!("{byte:02x}"));
    }
    text
}

/// Total size of a skill's files.
pub fn files_size(files: &SkillFiles) -> u64 {
    files.values().map(|bytes| bytes.len() as u64).sum()
}

/// Writes `files` below `dir`, creating folders.
pub(crate) fn write_files(fs: &dyn Fs, dir: &Path, files: &SkillFiles) -> Result<(), CoreError> {
    for (relative, bytes) in files {
        let path = relative
            .split('/')
            .fold(dir.to_path_buf(), |path, part| path.join(part));
        if let Some(parent) = path.parent() {
            fs.create_dir_all(parent)
                .map_err(|err| write_error(fs, "cannot create directory", parent, &err))?;
        }
        fs.write(&path, bytes)
            .map_err(|err| write_error(fs, "cannot write file", &path, &err))?;
    }
    Ok(())
}

/// A lower-case id from a skill name: runs of other characters become
/// `-`; `None` when nothing is left.
pub fn slug(name: &str) -> Option<String> {
    let mut slug = String::new();
    for ch in name.chars().flat_map(char::to_lowercase) {
        if ch.is_ascii_lowercase() || ch.is_ascii_digit() || ch == '.' || ch == '_' {
            slug.push(ch);
        } else if !slug.is_empty() && !slug.ends_with('-') {
            slug.push('-');
        }
    }
    let mut slug = slug
        .trim_start_matches(['.', '_', '-'])
        .trim_end_matches('-')
        .to_owned();
    slug.truncate(crate::model::ids::MAX_ID_LEN - 4);
    let slug = slug.trim_end_matches('-').to_owned();
    (!slug.is_empty()).then_some(slug)
}

/// Removes skill `id` from the store (one commit: `skill: remove <id>`),
/// its cache clone, then its owned unchanged links and copies
/// ([`link::sync`]). Changed copies stay in place, no longer owned.
/// Project manifests that still enable it get a warning on sync.
pub fn remove(
    store: &crate::store::Store<'_>,
    sx: &SkillsEnv<'_>,
    id: &str,
) -> Result<(Option<crate::store::CommitId>, SyncReport), CoreError> {
    crate::model::ids::check(crate::model::ids::IdKind::Skill, id)?;
    let operation = crate::store::Operation::new("skill.remove", format!("skill: remove {id}"))
        .entity(format!("skill/{id}"));
    let committed = store.transaction(operation, |tx| {
        if !store::exists(tx, id)? {
            return Err(store::not_found(id));
        }
        store::stage_remove(tx, id)
    })?;
    store::prune_empty_dirs(store, id)?;
    install::forget_source(sx, id)?;
    let report = link::sync(store, sx)?;
    Ok((committed.commit, report))
}