Skip to main content

surjection_core/
agent.rs

1//! The Surjection skill for agents (#8, SPEC 12.6): a read-only skill that
2//! teaches coding agents Surjection's read and plan commands. It ships inside
3//! this crate (so the CLI works on its own) and as a resource of the app,
4//! and is installed as a normal store skill: id [`SKILL_ID`], marked by its
5//! `[bundled]` table, enabled per client through the normal skill sync, so
6//! it is versioned, reversible and visible like any other skill.
7//!
8//! Bundled copies carry no `[source]`: 0.5.x reads any `[source] kind` it
9//! does not know as a parse error (and refuses a merge holding it), while it
10//! keeps an unknown `[bundled]` table as it is.
11//!
12//! Updates follow Surjection: when the bundled version is newer than the store
13//! copy, [`refresh`] replaces the store copy (one commit), unless the user
14//! edited it: content whose [`normalized_hash`] differs from `[bundled]
15//! hash` is customized and never touched (only [`install`] with `reset`
16//! replaces it, when the user asks).
17
18use std::cmp::Ordering;
19use std::path::{Path, PathBuf};
20
21use sha2::{Digest, Sha256};
22
23use crate::error::{CoreError, ErrorCode};
24use crate::fs::Fs;
25use crate::local_settings::LocalSettings;
26use crate::model::TomlDocument;
27use crate::model::clients::ClientSelection;
28use crate::model::skill_meta::{BundledCopy, SkillEnable, SkillMeta};
29use crate::paths::SurjectionHome;
30use crate::skills::link::{self, CLIENT_SKILLS, DetectedClients, client_skills};
31use crate::skills::{self, SkillFiles, SkillsEnv, SyncReport, read_folder, store};
32use crate::store::{CommitId, Operation, Store};
33
34/// Store id of the Surjection skill.
35pub const SKILL_ID: &str = "surjection";
36/// The Surjection version the bundled copy ships with.
37pub const BUNDLED_VERSION: &str = env!("CARGO_PKG_VERSION");
38/// The skill folder inside the app's resources (`tauri.conf.json`
39/// `bundle.resources`) and below `cache/` (`surject agent skill-path`).
40pub const RESOURCE_DIR: &str = "agent-skill/surjection";
41/// What `surject agent status` tells the user to run for an outdated copy.
42pub const UPDATE_COMMAND: &str = "surject agent install";
43/// What it tells the user to run to replace a customized copy.
44pub const RESET_COMMAND: &str = "surject agent install --reset";
45
46/// The bundled files, by relative path, as the repository holds them (LF
47/// line endings, `.gitattributes`).
48pub const FILES: [(&str, &str); 4] = [
49    (
50        "SKILL.md",
51        include_str!("../agent-skill/surjection/SKILL.md"),
52    ),
53    (
54        "references/commands.md",
55        include_str!("../agent-skill/surjection/references/commands.md"),
56    ),
57    (
58        "references/errors.md",
59        include_str!("../agent-skill/surjection/references/errors.md"),
60    ),
61    (
62        "references/playbooks.md",
63        include_str!("../agent-skill/surjection/references/playbooks.md"),
64    ),
65];
66
67/// The bundled skill's files.
68pub fn bundled_files() -> SkillFiles {
69    FILES
70        .iter()
71        .map(|(path, text)| ((*path).to_owned(), text.as_bytes().to_vec()))
72        .collect()
73}
74
75/// Files an OS or an editor drops next to the user's files: never part of
76/// what decides whether the copy was edited.
77fn is_junk(path: &str) -> bool {
78    let name = path.rsplit('/').next().unwrap_or(path);
79    let lower = name.to_ascii_lowercase();
80    matches!(
81        lower.as_str(),
82        ".ds_store" | "thumbs.db" | "ehthumbs.db" | "desktop.ini"
83    ) || lower.starts_with("._")
84        || lower.starts_with(".#")
85        || (lower.starts_with('#') && lower.ends_with('#'))
86        || lower.ends_with('~')
87        || [".swp", ".swo", ".swx", ".bak", ".orig", ".tmp"]
88            .iter()
89            .any(|suffix| lower.ends_with(suffix))
90}
91
92/// `bytes` without a leading UTF-8 byte order mark and with CRLF as LF.
93fn normalized_text(bytes: &[u8]) -> Vec<u8> {
94    let bytes = bytes.strip_prefix(b"\xef\xbb\xbf").unwrap_or(bytes);
95    let mut out = Vec::with_capacity(bytes.len());
96    let mut iter = bytes.iter().peekable();
97    while let Some(&byte) = iter.next() {
98        if byte == b'\r' && iter.peek() == Some(&&b'\n') {
99            continue;
100        }
101        out.push(byte);
102    }
103    out
104}
105
106/// `sha256:<hex>` over the skill's files as an edit would change them:
107/// OS and editor junk files left out ([`is_junk`]), a BOM and CRLF line
108/// endings normalized. Resaving a file or opening the folder in a file
109/// manager is not an edit.
110pub fn normalized_hash(files: &SkillFiles) -> String {
111    let mut hasher = Sha256::new();
112    for (path, bytes) in files.iter().filter(|(path, _)| !is_junk(path)) {
113        let bytes = normalized_text(bytes);
114        hasher.update(path.as_bytes());
115        hasher.update([0]);
116        hasher.update((bytes.len() as u64).to_le_bytes());
117        hasher.update(&bytes);
118    }
119    let digest = hasher.finalize();
120    let mut text = String::with_capacity(7 + digest.len() * 2);
121    text.push_str("sha256:");
122    for byte in digest {
123        text.push_str(&format!("{byte:02x}"));
124    }
125    text
126}
127
128/// [`normalized_hash`] of [`bundled_files`].
129pub fn bundled_hash() -> String {
130    normalized_hash(&bundled_files())
131}
132
133/// Whether `meta` describes a copy of the bundled skill (its `[bundled]`
134/// table): the origin shown as "Bundled with Surjection".
135pub fn is_bundled(meta: &SkillMeta) -> bool {
136    meta.bundled.is_some()
137}
138
139/// How the store copy compares with the bundled one.
140#[derive(Debug, Clone, Copy, PartialEq, Eq)]
141pub enum CopyState {
142    /// The bundled version, as Surjection wrote it.
143    Current,
144    /// Written by an older Surjection and unchanged since: the next store
145    /// change, `surject agent install` or app start updates it.
146    Outdated,
147    /// Edited since Surjection wrote it: never updated (`install --reset`
148    /// replaces it on request).
149    Customized,
150    /// Written by a newer Surjection (a store synced from another machine):
151    /// never replaced by an older copy.
152    Newer,
153}
154
155impl CopyState {
156    pub const fn as_str(self) -> &'static str {
157        match self {
158            CopyState::Current => "current",
159            CopyState::Outdated => "outdated",
160            CopyState::Customized => "customized",
161            CopyState::Newer => "newer",
162        }
163    }
164
165    /// The command that changes this state, for `surject agent status`.
166    pub const fn action(self) -> Option<&'static str> {
167        match self {
168            CopyState::Outdated => Some(UPDATE_COMMAND),
169            CopyState::Customized => Some(RESET_COMMAND),
170            CopyState::Current | CopyState::Newer => None,
171        }
172    }
173}
174
175/// The Surjection skill in the store, as read at one moment.
176#[derive(Debug, Clone, PartialEq, Eq)]
177pub struct StoreCopy {
178    /// The Surjection version whose copy was written (`[bundled] version`).
179    pub version: String,
180    pub state: CopyState,
181}
182
183/// One client with a skill folder.
184#[derive(Debug, Clone, PartialEq, Eq)]
185pub struct ClientStatus {
186    pub client: &'static str,
187    pub detected: bool,
188    /// The store copy is enabled for it at user scope.
189    pub enabled: bool,
190}
191
192/// What [`status`] found.
193#[derive(Debug, Clone, PartialEq, Eq)]
194pub struct AgentStatus {
195    pub bundled_version: &'static str,
196    /// The store copy; `None` when it is not installed.
197    pub copy: Option<StoreCopy>,
198    /// A store skill with id [`SKILL_ID`] that Surjection did not bundle (the
199    /// user's own): it is never installed over, updated or removed here.
200    pub taken: bool,
201    /// Every client with a skill folder (table 7.6), omp first.
202    pub clients: Vec<ClientStatus>,
203}
204
205/// What [`refresh`] did.
206#[derive(Debug, Clone)]
207pub enum Refresh {
208    /// The store copy was replaced by the bundled one (one commit); the
209    /// skill sync's report says which client folders need a decision.
210    Updated {
211        from: String,
212        to: String,
213        commit: Option<CommitId>,
214        report: SyncReport,
215    },
216    /// A newer copy is bundled, but the store copy was edited: it stays as
217    /// it is ("customized, not updated").
218    Customized { version: String, bundled: String },
219}
220
221/// What [`install`] or [`remove`] did.
222#[derive(Debug, Clone, Default)]
223pub struct Change {
224    /// The last store commit made; `None` when nothing changed.
225    pub commit: Option<CommitId>,
226    /// Links and copies made or removed.
227    pub report: SyncReport,
228    /// The update [`install`] made first, if any.
229    pub refreshed: Option<Refresh>,
230    /// A customized or outdated copy was replaced on request (`reset`).
231    pub reset: bool,
232    /// The skill was removed from the store.
233    pub removed: bool,
234}
235
236/// The store skill [`SKILL_ID`], split by origin.
237enum Found {
238    Missing,
239    /// Present, but not bundled (or its metadata is missing or invalid).
240    Taken,
241    Bundled(Box<SkillMeta>),
242}
243
244fn find(store: &Store<'_>) -> Result<Found, CoreError> {
245    let Some(skill) = store::get(store, SKILL_ID)? else {
246        return Ok(Found::Missing);
247    };
248    Ok(match skill.meta {
249        Some(meta) if is_bundled(&meta) => Found::Bundled(Box::new(meta)),
250        _ => Found::Taken,
251    })
252}
253
254/// How the store copy described by `meta` compares with the bundled one,
255/// reading its content through `store`.
256fn copy_of(store: &Store<'_>, meta: &SkillMeta) -> StoreCopy {
257    let written = meta.bundled.as_ref().expect("bundled metadata");
258    // Content that cannot be read is not Surjection's to rewrite either.
259    let unchanged = store::read_content(store, SKILL_ID)
260        .is_ok_and(|files| normalized_hash(&files) == written.hash);
261    let state = if !unchanged {
262        CopyState::Customized
263    } else {
264        match compare_versions(&written.version, BUNDLED_VERSION) {
265            Ordering::Less => CopyState::Outdated,
266            Ordering::Equal => CopyState::Current,
267            Ordering::Greater => CopyState::Newer,
268        }
269    };
270    StoreCopy {
271        version: written.version.clone(),
272        state,
273    }
274}
275
276/// The clients with skill folders, omp first (#2), then table order.
277fn skill_clients() -> impl Iterator<Item = &'static str> {
278    let omp = CLIENT_SKILLS
279        .iter()
280        .map(|entry| entry.client)
281        .filter(|client| *client == "omp");
282    let rest = CLIENT_SKILLS
283        .iter()
284        .map(|entry| entry.client)
285        .filter(|client| *client != "omp");
286    omp.chain(rest)
287}
288
289/// The Surjection skill's state: the store copy (none without a store) and
290/// every client with a skill folder. Reads only; takes no lock.
291pub fn status(store: Option<&Store<'_>>, sx: &SkillsEnv<'_>) -> Result<AgentStatus, CoreError> {
292    let found = match store {
293        Some(store) => find(store)?,
294        None => Found::Missing,
295    };
296    let detected = DetectedClients::new(sx);
297    let enabled: Vec<&'static str> = match &found {
298        Found::Bundled(meta) => meta
299            .enable
300            .as_ref()
301            .and_then(|enable| enable.clients.as_ref())
302            .map(|selection| detected.selected(selection))
303            .unwrap_or_default(),
304        _ => Vec::new(),
305    };
306    let clients = skill_clients()
307        .map(|client| ClientStatus {
308            client,
309            detected: detected.is_detected(client),
310            enabled: enabled.contains(&client),
311        })
312        .collect();
313    let (copy, taken) = match (&found, store) {
314        (Found::Bundled(meta), Some(store)) => (Some(copy_of(store, meta)), false),
315        (Found::Taken, _) => (None, true),
316        _ => (None, false),
317    };
318    Ok(AgentStatus {
319        bundled_version: BUNDLED_VERSION,
320        copy,
321        taken,
322        clients,
323    })
324}
325
326/// What to do about a store skill `surject` that is the user's own: Surjection
327/// has no rename, so the way out is removing it or adding it again under
328/// another id.
329fn taken_hint() -> String {
330    format!(
331        "the store skill {SKILL_ID:?} is your own, not the one bundled with Surjection, and is never changed here; to use the Surjection skill, remove yours (surject skills rm {SKILL_ID}) or add it again under another id (surject skills add <its folder> --id <other id>) first"
332    )
333}
334
335/// `clients` checked against table 7.6, or every detected client with a
336/// skill folder when empty (`invalid_value` when there is none).
337fn chosen_clients(sx: &SkillsEnv<'_>, clients: &[String]) -> Result<Vec<String>, CoreError> {
338    check_clients(clients)?;
339    if !clients.is_empty() {
340        return Ok(clients.to_vec());
341    }
342    let detected = DetectedClients::new(sx);
343    let chosen: Vec<String> = skill_clients()
344        .filter(|client| detected.is_detected(client))
345        .map(str::to_owned)
346        .collect();
347    if chosen.is_empty() {
348        return Err(CoreError::new(
349            ErrorCode::InvalidValue,
350            "no client with a skill folder was detected; name one with --client",
351        ));
352    }
353    Ok(chosen)
354}
355
356fn check_clients(clients: &[String]) -> Result<(), CoreError> {
357    for client in clients {
358        if client_skills(client).is_none() {
359            let code = if crate::model::clients::known_client(client).is_some() {
360                ErrorCode::ScopeNotSupported
361            } else {
362                ErrorCode::UnknownClient
363            };
364            return Err(CoreError::new(
365                code,
366                format!("{client:?} has no skill folder Surjection writes"),
367            ));
368        }
369    }
370    Ok(())
371}
372
373/// Installs the Surjection skill for `clients`: a missing copy is added and
374/// enabled for them (every detected client with a skill folder when empty)
375/// in one commit (`skill: add surjection ...`). An existing bundled copy is
376/// first brought up to date ([`refresh`]), or with `reset` replaced by the
377/// bundled one whatever its state (`skill: reset surjection ...`, its client
378/// selection kept), and then enabled for `clients` ([`link::set_enabled`];
379/// with `reset` and no clients the selection is left as it is). Links
380/// follow at once. A store skill with the same id that Surjection did not
381/// bundle is `already_exists`.
382pub fn install(
383    store: &Store<'_>,
384    sx: &SkillsEnv<'_>,
385    clients: &[String],
386    reset: bool,
387) -> Result<Change, CoreError> {
388    match find(store)? {
389        Found::Taken => Err(CoreError::new(ErrorCode::AlreadyExists, taken_hint())),
390        Found::Bundled(_) => {
391            check_clients(clients)?;
392            let mut change = Change::default();
393            if reset {
394                let (commit, report) = replace(store, sx, "reset", None)?;
395                change.reset = commit.is_some();
396                change.commit = commit;
397                change.report = report;
398            } else {
399                change.refreshed = refresh(store, sx)?;
400            }
401            if reset && clients.is_empty() {
402                return Ok(change);
403            }
404            let clients = chosen_clients(sx, clients)?;
405            let (commit, report) = link::set_enabled(store, sx, SKILL_ID, &clients, true, None)?;
406            change.commit = commit.or(change.commit);
407            change.report.results.extend(report.results);
408            change.report.warnings.extend(report.warnings);
409            Ok(change)
410        }
411        Found::Missing => {
412            let clients = chosen_clients(sx, clients)?;
413            let files = bundled_files();
414            let mut sorted = clients.clone();
415            sorted.sort();
416            sorted.dedup();
417            let summary = format!(
418                "skill: add {SKILL_ID} (bundled with Surjection {BUNDLED_VERSION}) for {}",
419                clients.join(", ")
420            );
421            let operation =
422                Operation::new("skill.add", summary).entity(format!("skill/{SKILL_ID}"));
423            let committed = store.transaction(operation, |tx| {
424                store::stage_content(tx, SKILL_ID, &files)?;
425                let mut meta = bundled_meta(SkillMeta::new(SKILL_ID), &files);
426                meta.enable = Some(SkillEnable {
427                    clients: Some(ClientSelection::List(sorted)),
428                    ..SkillEnable::default()
429                });
430                store::stage_meta(tx, &meta)
431            })?;
432            let report = link::sync(store, sx)?;
433            Ok(Change {
434                commit: committed.commit,
435                report,
436                ..Change::default()
437            })
438        }
439    }
440}
441
442/// `meta` as the bundled copy `files`: name and `[bundled]`, no
443/// `[source]` (see the module notes).
444fn bundled_meta(mut meta: SkillMeta, files: &SkillFiles) -> SkillMeta {
445    meta.name = Some(SKILL_ID.to_owned());
446    meta.source = None;
447    meta.bundled = Some(BundledCopy {
448        version: BUNDLED_VERSION.to_owned(),
449        hash: normalized_hash(files),
450        extra: toml::Table::new(),
451    });
452    meta
453}
454
455/// Replaces the store copy by the bundled one (one commit, `skill: <verb>
456/// surjection to the copy bundled with Surjection <v>`), keeping the rest of its
457/// metadata, then syncs client folders. With `seen`, the copy is checked
458/// again under the lock and left alone (no commit, `None`) unless it is
459/// still [`CopyState::Outdated`] with that version: another run may have
460/// updated it, to this version or a newer one, since `seen` was read.
461fn replace(
462    store: &Store<'_>,
463    sx: &SkillsEnv<'_>,
464    verb: &str,
465    seen: Option<&StoreCopy>,
466) -> Result<(Option<CommitId>, SyncReport), CoreError> {
467    let files = bundled_files();
468    let summary =
469        format!("skill: {verb} {SKILL_ID} to the copy bundled with Surjection {BUNDLED_VERSION}");
470    let operation =
471        Operation::new(format!("skill.{verb}"), summary).entity(format!("skill/{SKILL_ID}"));
472    let committed = store.transaction(operation, |tx| {
473        let Some(current) = store::read_meta(tx, SKILL_ID)?.filter(is_bundled) else {
474            return Ok(false);
475        };
476        if let Some(seen) = seen
477            && copy_of(tx.store(), &current) != *seen
478        {
479            return Ok(false);
480        }
481        store::stage_content(tx, SKILL_ID, &files)?;
482        store::stage_meta(tx, &bundled_meta(current, &files))?;
483        Ok(true)
484    })?;
485    if !committed.value {
486        return Ok((None, SyncReport::default()));
487    }
488    let report = link::sync(store, sx)?;
489    Ok((committed.commit, report))
490}
491
492/// Disables the Surjection skill for `clients`, or with none removes it from
493/// the store (one commit each; owned links and copies go with it). Nothing
494/// to do when it is not installed. A store skill with the same id that
495/// Surjection did not bundle is `invalid_value`.
496pub fn remove(
497    store: &Store<'_>,
498    sx: &SkillsEnv<'_>,
499    clients: &[String],
500) -> Result<Change, CoreError> {
501    match find(store)? {
502        Found::Missing => Ok(Change::default()),
503        Found::Taken => Err(CoreError::new(ErrorCode::InvalidValue, taken_hint())),
504        Found::Bundled(_) if clients.is_empty() => {
505            let (commit, report) = skills::remove(store, sx, SKILL_ID)?;
506            Ok(Change {
507                commit,
508                report,
509                removed: true,
510                ..Change::default()
511            })
512        }
513        Found::Bundled(_) => {
514            check_clients(clients)?;
515            let (commit, report) = link::set_enabled(store, sx, SKILL_ID, clients, false, None)?;
516            Ok(Change {
517                commit,
518                report,
519                ..Change::default()
520            })
521        }
522    }
523}
524
525/// Brings the store copy up to date: an [`CopyState::Outdated`] copy is
526/// replaced by the bundled one (one commit, `skill: update surjection ...`,
527/// then the skill sync rewrites copies); a [`CopyState::Customized`] copy
528/// older than the bundled version is reported and left alone. `None` when
529/// there is nothing to say (not installed, current, newer, or not
530/// Surjection's).
531pub fn refresh(store: &Store<'_>, sx: &SkillsEnv<'_>) -> Result<Option<Refresh>, CoreError> {
532    let Found::Bundled(meta) = find(store)? else {
533        return Ok(None);
534    };
535    refresh_seen(store, sx, copy_of(store, &meta))
536}
537
538/// [`refresh`] acting on a state read earlier, as a run that read it
539/// before another run took the store lock does: an update is made only if
540/// the copy is still the one `seen` describes, checked again under the
541/// lock, so a newer copy written meanwhile is never replaced by an older
542/// one and two runs never both report an update.
543pub fn refresh_seen(
544    store: &Store<'_>,
545    sx: &SkillsEnv<'_>,
546    seen: StoreCopy,
547) -> Result<Option<Refresh>, CoreError> {
548    match seen.state {
549        CopyState::Outdated => {
550            let (commit, report) = replace(store, sx, "update", Some(&seen))?;
551            Ok(commit.map(|commit| Refresh::Updated {
552                from: seen.version,
553                to: BUNDLED_VERSION.to_owned(),
554                commit: Some(commit),
555                report,
556            }))
557        }
558        CopyState::Customized
559            if compare_versions(&seen.version, BUNDLED_VERSION) == Ordering::Less =>
560        {
561            Ok(Some(Refresh::Customized {
562                version: seen.version,
563                bundled: BUNDLED_VERSION.to_owned(),
564            }))
565        }
566        _ => Ok(None),
567    }
568}
569
570/// [`refresh`] for a store change (the CLI's changing commands) and the app
571/// start: runs only when the store copy's metadata names an older version
572/// (a file read otherwise). A copy already found customized for this
573/// bundled version (`state/local-settings.toml` `agent_skill_notice`) is
574/// not hashed again: "customized, not updated" is said once per bundled
575/// version per machine, and `surject agent install` still checks it.
576pub fn startup_refresh(
577    store: &Store<'_>,
578    sx: &SkillsEnv<'_>,
579) -> Result<Option<Refresh>, CoreError> {
580    if !written_older(sx.fs, sx.home) {
581        return Ok(None);
582    }
583    let state_dir = sx.home.state_dir();
584    let mut settings = LocalSettings::load(sx.fs, &state_dir)?;
585    if settings.agent_skill_notice.as_deref() == Some(BUNDLED_VERSION) {
586        return Ok(None);
587    }
588    let refreshed = refresh(store, sx)?;
589    if let Some(Refresh::Customized { bundled, .. }) = &refreshed {
590        settings.agent_skill_notice = Some(bundled.clone());
591        settings.save(sx.fs, &state_dir)?;
592    }
593    Ok(refreshed)
594}
595
596/// Whether the store's `skill-meta/surjection.toml` describes a bundled copy
597/// of an older version, read straight from the working tree (no store
598/// open, no lock). Anything unreadable is `false`: [`status`] reports it.
599pub fn written_older(fs: &dyn Fs, home: &SurjectionHome) -> bool {
600    let path = home
601        .store_dir()
602        .join(store::META_DIR)
603        .join(format!("{SKILL_ID}.toml"));
604    let Ok(text) = fs.read_to_string(&path) else {
605        return false;
606    };
607    let Ok(doc) = TomlDocument::<SkillMeta>::parse(&text) else {
608        return false;
609    };
610    doc.value().bundled.as_ref().is_some_and(|bundled| {
611        compare_versions(&bundled.version, BUNDLED_VERSION) == Ordering::Less
612    })
613}
614
615/// A folder holding the bundled copy, for `surject agent skill-path`:
616/// `cache/agent-skill/surjection`, rewritten when its files differ from the
617/// bundled ones.
618pub fn materialize(fs: &dyn Fs, home: &SurjectionHome) -> Result<PathBuf, CoreError> {
619    let dir = RESOURCE_DIR
620        .split('/')
621        .fold(home.cache_dir(), |path, part| path.join(part));
622    let files = bundled_files();
623    if fs.is_dir(&dir) && read_folder(fs, &dir).is_ok_and(|found| found == files) {
624        return Ok(dir);
625    }
626    if fs.exists(&dir) {
627        fs.remove_dir_all(&dir).map_err(|err| {
628            CoreError::new(ErrorCode::IoError, format!("cannot remove folder: {err}"))
629                .with_path(&dir)
630        })?;
631    }
632    skills::write_files(fs, &dir, &files)?;
633    Ok(dir)
634}
635
636/// Whether `dir` holds the bundled files (the app's resource folder),
637/// compared as [`normalized_hash`] does.
638pub fn is_bundled_copy(fs: &dyn Fs, dir: &Path) -> bool {
639    read_folder(fs, dir).is_ok_and(|found| normalized_hash(&found) == bundled_hash())
640}
641
642/// Orders `major.minor.patch[-pre][+build]` versions as semver does:
643/// numbers compare as numbers (missing or unreadable ones as 0), a
644/// pre-release sorts before its release, pre-release identifiers compare
645/// one by one (numeric ones as numbers and before text ones, a shorter
646/// list first when all else is equal), build metadata is ignored.
647pub fn compare_versions(a: &str, b: &str) -> Ordering {
648    fn parts(version: &str) -> ([u64; 3], Option<&str>) {
649        let version = version.trim();
650        let version = version.split_once('+').map_or(version, |(core, _)| core);
651        let (core, pre) = match version.split_once('-') {
652            Some((core, pre)) => (core, Some(pre)),
653            None => (version, None),
654        };
655        let mut numbers = [0u64; 3];
656        for (slot, part) in numbers.iter_mut().zip(core.split('.')) {
657            *slot = part.parse().unwrap_or(0);
658        }
659        (numbers, pre)
660    }
661    fn identifier(a: &str, b: &str) -> Ordering {
662        match (a.parse::<u64>(), b.parse::<u64>()) {
663            (Ok(a), Ok(b)) => a.cmp(&b),
664            (Ok(_), Err(_)) => Ordering::Less,
665            (Err(_), Ok(_)) => Ordering::Greater,
666            (Err(_), Err(_)) => a.cmp(b),
667        }
668    }
669    let (a_numbers, a_pre) = parts(a);
670    let (b_numbers, b_pre) = parts(b);
671    a_numbers
672        .cmp(&b_numbers)
673        .then_with(|| match (a_pre, b_pre) {
674            (None, None) => Ordering::Equal,
675            (None, Some(_)) => Ordering::Greater,
676            (Some(_), None) => Ordering::Less,
677            (Some(a), Some(b)) => {
678                let mut a = a.split('.');
679                let mut b = b.split('.');
680                loop {
681                    match (a.next(), b.next()) {
682                        (None, None) => return Ordering::Equal,
683                        (None, Some(_)) => return Ordering::Less,
684                        (Some(_), None) => return Ordering::Greater,
685                        (Some(x), Some(y)) => match identifier(x, y) {
686                            Ordering::Equal => {}
687                            other => return other,
688                        },
689                    }
690                }
691            }
692        })
693}
694
695#[cfg(test)]
696mod tests {
697    use super::*;
698
699    #[test]
700    fn versions_order_like_semver() {
701        assert_eq!(compare_versions("0.5.0", "0.6.0"), Ordering::Less);
702        assert_eq!(compare_versions("0.10.0", "0.9.9"), Ordering::Greater);
703        assert_eq!(compare_versions("1.0.0", "1.0.0"), Ordering::Equal);
704        assert_eq!(compare_versions("1.0.0-rc.1", "1.0.0"), Ordering::Less);
705        assert_eq!(compare_versions("1.0.0+build", "1.0.0"), Ordering::Equal);
706        assert_eq!(compare_versions("garbage", "0.0.1"), Ordering::Less);
707        // Pre-release identifiers one by one (semver 11.4).
708        assert_eq!(
709            compare_versions("1.0.0-rc.10", "1.0.0-rc.9"),
710            Ordering::Greater
711        );
712        assert_eq!(
713            compare_versions("1.0.0-alpha", "1.0.0-alpha.1"),
714            Ordering::Less
715        );
716        assert_eq!(
717            compare_versions("1.0.0-alpha.1", "1.0.0-alpha.beta"),
718            Ordering::Less
719        );
720        assert_eq!(
721            compare_versions("1.0.0-beta.2", "1.0.0-beta.11"),
722            Ordering::Less
723        );
724        assert_eq!(
725            compare_versions("1.0.0-rc.1", "1.0.0-beta.11"),
726            Ordering::Greater
727        );
728    }
729
730    /// The raw embedded bytes, not the normalized ones: a CRLF checkout
731    /// would fail here.
732    #[test]
733    fn embedded_files_have_lf_endings_and_a_frontmatter_name() {
734        for (path, text) in FILES {
735            assert!(!text.contains('\r'), "{path} has CR characters");
736            assert!(!text.starts_with('\u{feff}'), "{path} starts with a BOM");
737        }
738        let fm = crate::skills::frontmatter::parse(FILES[0].1)
739            .unwrap()
740            .unwrap();
741        assert_eq!(fm.name(), Some(SKILL_ID));
742        assert!(fm.description().is_some_and(|text| !text.is_empty()));
743    }
744
745    #[test]
746    fn junk_files_line_endings_and_a_bom_are_not_edits() {
747        let files = bundled_files();
748        let hash = normalized_hash(&files);
749        let mut touched = files.clone();
750        for junk in [
751            ".DS_Store",
752            "Thumbs.db",
753            "references/desktop.ini",
754            ".SKILL.md.swp",
755            "SKILL.md~",
756            "._SKILL.md",
757        ] {
758            touched.insert(junk.to_owned(), b"junk".to_vec());
759        }
760        let skill = files["SKILL.md"].clone();
761        let mut resaved = b"\xef\xbb\xbf".to_vec();
762        resaved.extend(
763            String::from_utf8(skill)
764                .unwrap()
765                .replace('\n', "\r\n")
766                .into_bytes(),
767        );
768        touched.insert("SKILL.md".to_owned(), resaved);
769        assert_eq!(normalized_hash(&touched), hash);
770        // A real edit, or a new real file, is one.
771        let mut edited = files.clone();
772        edited.insert("SKILL.md".to_owned(), b"mine".to_vec());
773        assert_ne!(normalized_hash(&edited), hash);
774        let mut added = files;
775        added.insert("notes.md".to_owned(), b"mine".to_vec());
776        assert_ne!(normalized_hash(&added), hash);
777    }
778}
779
780/// What [`swap_legacy`] found or did with the `loadout` skill Loadout
781/// 1.0.x bundled.
782#[derive(Debug, Clone, PartialEq, Eq)]
783pub enum LegacySwap {
784    /// No store skill `loadout`.
785    Absent,
786    /// A store skill `loadout` that Loadout did not bundle: the user's own.
787    Foreign,
788    /// The bundled copy was edited: kept as it is.
789    Customized,
790    /// It would be replaced (dry run).
791    Planned,
792    /// Replaced by the Surjection skill for the same clients.
793    Swapped { commit: Option<CommitId> },
794}
795
796/// Replaces the `loadout` skill Loadout 1.0.x bundled, when it is unchanged
797/// since Loadout wrote it, by the Surjection skill enabled for the same
798/// clients: the Surjection skill is added with the old selection (unless it
799/// is in the store already), then the old skill is removed with its owned
800/// links and copies, and the skill sync places the new one. An edited copy
801/// or a skill of the user's own named `loadout` is left alone.
802pub fn swap_legacy(
803    store: &Store<'_>,
804    sx: &SkillsEnv<'_>,
805    dry_run: bool,
806) -> Result<LegacySwap, CoreError> {
807    let legacy = crate::brand::legacy::SKILL_ID;
808    let Some(skill) = store::get(store, legacy)? else {
809        return Ok(LegacySwap::Absent);
810    };
811    let Some(meta) = skill.meta.filter(is_bundled) else {
812        return Ok(LegacySwap::Foreign);
813    };
814    let written = meta.bundled.as_ref().expect("bundled metadata");
815    let unchanged = store::read_content(store, legacy)
816        .is_ok_and(|files| normalized_hash(&files) == written.hash);
817    if !unchanged {
818        return Ok(LegacySwap::Customized);
819    }
820    if dry_run {
821        return Ok(LegacySwap::Planned);
822    }
823    let mut commit = None;
824    if matches!(find(store)?, Found::Missing) {
825        let files = bundled_files();
826        let operation = Operation::new(
827            "skill.add",
828            format!(
829                "skill: add {SKILL_ID} (bundled with Surjection {BUNDLED_VERSION}) in place of {legacy}"
830            ),
831        )
832        .entity(format!("skill/{SKILL_ID}"));
833        let enable = meta.enable.clone();
834        let committed = store.transaction(operation, |tx| {
835            store::stage_content(tx, SKILL_ID, &files)?;
836            let mut new = bundled_meta(SkillMeta::new(SKILL_ID), &files);
837            new.enable = enable;
838            store::stage_meta(tx, &new)
839        })?;
840        commit = committed.commit;
841    }
842    let (removed, _) = skills::remove(store, sx, legacy)?;
843    link::sync(store, sx)?;
844    Ok(LegacySwap::Swapped {
845        commit: removed.or(commit),
846    })
847}