Skip to main content

surjection_core/skills/
classify.rs

1//! Client skill folders as they are (SPEC 12.5): each entry is `managed`
2//! (a link or copy the ledger owns), `unmanaged` (a real folder or file)
3//! or `mismatch` (a link the ledger does not own). Actions: import an
4//! unmanaged folder into the store, and move an entry to
5//! `backups/trash/` (never a hard delete).
6//!
7//! Operations take a client, a scope, a project folder and an entry name,
8//! never a free path, so they only reach client skill folders.
9
10use std::path::{Path, PathBuf};
11
12use crate::apply::backup::timestamp;
13use crate::error::{CoreError, ErrorCode};
14use crate::model::applied::Scope;
15use crate::model::skill_meta::{SkillSource, SkillSourceKind};
16use crate::skills::install::{Installed, Naming, install_files};
17use crate::skills::link::{CLIENT_SKILLS, SkillLedger, skills_dir};
18use crate::skills::{
19    Entry, SKILL_FILE, SkillsEnv, confine, entry, frontmatter, io_error, read_folder,
20};
21use crate::store::{LOCK_TIMEOUT, Store, StoreLock};
22
23/// Trash folder below `<SURJECTION_HOME>/backups`.
24pub const TRASH_DIR: &str = "trash";
25
26#[derive(Debug, Clone, Copy, PartialEq, Eq)]
27pub enum EntryClass {
28    /// A link or copy the ledger owns.
29    Managed,
30    /// A real folder or file.
31    Unmanaged,
32    /// A link the ledger does not own (to another folder, or to the store
33    /// without being recorded).
34    Mismatch,
35}
36
37impl EntryClass {
38    pub const fn as_str(self) -> &'static str {
39        match self {
40            EntryClass::Managed => "managed",
41            EntryClass::Unmanaged => "unmanaged",
42            EntryClass::Mismatch => "mismatch",
43        }
44    }
45}
46
47/// One entry of a client skill folder.
48#[derive(Debug, Clone)]
49pub struct ToolEntry {
50    pub name: String,
51    pub path: PathBuf,
52    pub class: EntryClass,
53    /// Where a link points.
54    pub link_target: Option<PathBuf>,
55    /// The store skill of a managed entry.
56    pub skill_id: Option<String>,
57    /// `description` from the entry's `SKILL.md`, when readable.
58    pub description: Option<String>,
59}
60
61/// One client's skill folder in one scope.
62#[derive(Debug, Clone)]
63pub struct ClientDir {
64    pub client: &'static str,
65    pub scope: Scope,
66    pub dir: PathBuf,
67    pub exists: bool,
68    pub entries: Vec<ToolEntry>,
69}
70
71/// Every Tier A and B client's skill folder in `scope` (`project` for the
72/// project scope), classified. Reads only.
73pub fn scan(
74    sx: &SkillsEnv<'_>,
75    scope: Scope,
76    project: Option<&Path>,
77) -> Result<Vec<ClientDir>, CoreError> {
78    let ledger = SkillLedger::load(sx.fs, &sx.home.state_dir())?;
79    let mut out: Vec<ClientDir> = Vec::new();
80    for client in &CLIENT_SKILLS {
81        let dir = skills_dir(sx.env, client.client, scope, project)?;
82        let exists = sx.fs.is_dir(&dir);
83        let entries = if exists {
84            classify_dir(sx, &ledger, &dir)?
85        } else {
86            Vec::new()
87        };
88        out.push(ClientDir {
89            client: client.client,
90            scope,
91            dir,
92            exists,
93            entries,
94        });
95    }
96    Ok(out)
97}
98
99/// The entries of one folder, sorted by name; names starting with `.` are
100/// left out.
101pub fn classify_dir(
102    sx: &SkillsEnv<'_>,
103    ledger: &SkillLedger,
104    dir: &Path,
105) -> Result<Vec<ToolEntry>, CoreError> {
106    let mut out = Vec::new();
107    for path in sx
108        .fs
109        .read_dir(dir)
110        .map_err(|err| io_error("cannot list directory", dir, &err))?
111    {
112        let Some(name) = path.file_name().and_then(|name| name.to_str()) else {
113            continue;
114        };
115        if name.starts_with('.') {
116            continue;
117        }
118        out.push(classify(sx, ledger, &path, name.to_owned())?);
119    }
120    Ok(out)
121}
122
123fn classify(
124    sx: &SkillsEnv<'_>,
125    ledger: &SkillLedger,
126    path: &Path,
127    name: String,
128) -> Result<ToolEntry, CoreError> {
129    let found = entry(sx.fs, path)?;
130    let owned = ledger.get(path);
131    let link_target = match &found {
132        Entry::Link(target) => Some(target.clone()),
133        _ => None,
134    };
135    let class = match (&found, owned) {
136        (_, Some(_)) => EntryClass::Managed,
137        (Entry::Link(_), None) => EntryClass::Mismatch,
138        _ => EntryClass::Unmanaged,
139    };
140    let description = sx
141        .fs
142        .read_to_string(&path.join(SKILL_FILE))
143        .ok()
144        .and_then(|text| frontmatter::parse(&text).ok().flatten())
145        .and_then(|fm| fm.description().map(str::to_owned));
146    Ok(ToolEntry {
147        name,
148        path: path.to_path_buf(),
149        class,
150        link_target,
151        skill_id: owned.map(|link| link.skill_id.clone()),
152        description,
153    })
154}
155
156/// The entry `name` of `client`'s folder; `not_found` when absent.
157fn locate(
158    sx: &SkillsEnv<'_>,
159    client: &str,
160    scope: Scope,
161    project: Option<&Path>,
162    name: &str,
163) -> Result<(PathBuf, Entry), CoreError> {
164    if name.is_empty() || name.starts_with('.') || name.contains(['/', '\\', ':']) {
165        return Err(CoreError::new(
166            ErrorCode::InvalidValue,
167            format!("{name:?} is not an entry name"),
168        ));
169    }
170    let path = skills_dir(sx.env, client, scope, project)?.join(name);
171    match entry(sx.fs, &path)? {
172        Entry::Missing => Err(CoreError::new(
173            ErrorCode::NotFound,
174            format!("{client} has no skill entry {name:?}"),
175        )
176        .with_path(&path)),
177        found => Ok((path, found)),
178    }
179}
180
181/// Imports an unmanaged folder of a client into the store (one commit).
182/// The folder itself stays as it is.
183pub fn import(
184    store: &Store<'_>,
185    sx: &SkillsEnv<'_>,
186    client: &str,
187    scope: Scope,
188    project: Option<&Path>,
189    name: &str,
190    naming: &Naming,
191) -> Result<Installed, CoreError> {
192    let (path, found) = locate(sx, client, scope, project, name)?;
193    let ledger = SkillLedger::load(sx.fs, &sx.home.state_dir())?;
194    if found != Entry::Dir || ledger.get(&path).is_some() {
195        return Err(CoreError::new(
196            ErrorCode::InvalidValue,
197            format!("{name:?} is not an unmanaged folder; only those can be imported"),
198        )
199        .with_path(&path));
200    }
201    let files = read_folder(sx.fs, &path)?;
202    let source = SkillSource {
203        kind: SkillSourceKind::Local,
204        url: None,
205        path: None,
206        git_ref: None,
207        commit: None,
208        catalog: None,
209        extra: toml::Table::new(),
210    };
211    install_files(store, sx, naming, files, name.to_owned(), source)
212}
213
214/// Moves an entry that is not managed to `backups/trash/<time>-<client>-<name>`
215/// (a link moves as a link; what it points to is untouched). Managed
216/// entries are disabled instead. Returns the trash path.
217pub fn trash(
218    sx: &SkillsEnv<'_>,
219    client: &str,
220    scope: Scope,
221    project: Option<&Path>,
222    name: &str,
223) -> Result<PathBuf, CoreError> {
224    let state = sx.home.state_dir();
225    let _lock = StoreLock::acquire(sx.fs, &state, LOCK_TIMEOUT)?;
226    let (path, _) = locate(sx, client, scope, project, name)?;
227    let ledger = SkillLedger::load(sx.fs, &state)?;
228    if ledger.get(&path).is_some() {
229        return Err(CoreError::new(
230            ErrorCode::InvalidValue,
231            format!("{name:?} is managed by Surjection; disable the skill instead"),
232        )
233        .with_path(&path));
234    }
235    let target = trash_target(sx, client, name)?;
236    confine(sx.fs, &path)?;
237    std::fs::rename(&path, &target)
238        .map_err(|err| io_error("cannot move the entry to the trash", &path, &err))?;
239    Ok(target)
240}
241
242/// A free `backups/trash/<time>-<client>-<name>` for an entry, its folder
243/// created; `already_exists` when that name is taken this second.
244pub(crate) fn trash_target(
245    sx: &SkillsEnv<'_>,
246    client: &str,
247    name: &str,
248) -> Result<PathBuf, CoreError> {
249    let dir = sx.home.backups_dir().join(TRASH_DIR);
250    let target = dir.join(format!("{}-{client}-{name}", timestamp(sx.env.now())));
251    confine(sx.fs, &target)?;
252    if sx.fs.exists(&target) {
253        return Err(
254            CoreError::new(ErrorCode::AlreadyExists, "the trash entry exists already")
255                .with_path(&target),
256        );
257    }
258    sx.fs
259        .create_dir_all(&dir)
260        .map_err(|err| io_error("cannot create directory", &dir, &err))?;
261    Ok(target)
262}