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;
pub const SKILL_FILE: &str = "SKILL.md";
pub const MARKER_FILE: &str = ".surjection-managed";
pub const LEGACY_MARKER_FILE: &str = ".loadout-managed";
pub fn is_marker(name: &str) -> bool {
name == MARKER_FILE || name == LEGACY_MARKER_FILE
}
pub const MAX_SKILL_BYTES: u64 = 100 * 1024 * 1024;
pub const WARN_TOTAL_BYTES: u64 = 500 * 1024 * 1024;
pub const MAX_ARCHIVE_FILES: usize = 500;
pub const MAX_ARCHIVE_FILE_BYTES: u64 = 5 * 1024 * 1024;
pub const MAX_ARCHIVE_TOTAL_BYTES: u64 = 20 * 1024 * 1024;
pub type SkillFiles = BTreeMap<String, Vec<u8>>;
#[derive(Clone, Copy)]
pub struct SkillsEnv<'a> {
pub env: &'a Env,
pub fs: &'a dyn Fs,
pub home: &'a SurjectionHome,
pub registry: &'a dyn RegistryProbe,
pub runner: &'a dyn Runner,
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()
}
}
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)
}
pub(crate) fn write_error(fs: &dyn Fs, what: &str, path: &Path, err: &io::Error) -> CoreError {
crate::access::write_error(fs, what, path, err)
}
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),
}
}
fn inside_new(folder: &Path) -> PathBuf {
folder.join(".surjection-new")
}
pub(crate) fn new_folder_access(fs: &dyn Fs, path: &Path) -> crate::access::WriteAccess {
crate::access::probe_path(fs, &inside_new(path))
}
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),
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) enum Entry {
Missing,
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)),
};
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
})
}
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
}
pub fn read_folder(fs: &dyn Fs, dir: &Path) -> Result<SkillFiles, CoreError> {
Ok(read_folder_skipping(fs, dir, &[])?.0)
}
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))
}
struct SkipDirs<'a> {
names: &'a [&'a str],
skipped: Vec<String>,
}
#[derive(Debug, Clone, Default)]
pub struct FolderSummary {
pub bytes: u64,
pub skill_file: Option<Vec<u8>>,
}
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 })
}
type OnFile<'a> = dyn FnMut(String, &Path, u64) -> Result<u64, CoreError> + 'a;
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)
}
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 {
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)
}
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(())
}
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
}
pub fn files_size(files: &SkillFiles) -> u64 {
files.values().map(|bytes| bytes.len() as u64).sum()
}
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(())
}
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)
}
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))
}