surjection-core 1.2.0

Core library of Surjection: MCP servers, skills and secret references for AI coding clients
Documentation
//! `state/local-settings.toml` (SPEC 4.5): this machine's own settings,
//! never synced. Only the keys this build reads are typed; every other key
//! is kept as it is when the file is written.

use std::path::Path;

use serde::{Deserialize, Serialize};

use crate::error::{CoreError, ErrorCode};
use crate::fs::Fs;
use crate::model::SCHEMA_VERSION;

/// The file in `state/`.
pub const LOCAL_SETTINGS_FILE: &str = "local-settings.toml";

/// What the user answered to the first run's "Add a backup remote" step
/// (SPEC 15.2).
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "kebab-case")]
pub enum BackupRemoteOffer {
    /// "Not now": the store stays local-only; Settings still offers Add.
    NotNow,
    /// A remote was added from the step.
    Added,
}

/// What the user did with the app's first-run welcome (M58). Any value
/// means "answered": the welcome is not shown again on this machine.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(from = "String", into = "String")]
pub enum WelcomeAnswer {
    /// Skipped or closed before the end (`skipped`).
    Skipped,
    /// Reached Finish (`finished`).
    Finished,
    /// A value a newer build wrote, kept as written: still answered, the
    /// file stays readable, and saving it writes the value back unchanged.
    Other(String),
}

impl From<String> for WelcomeAnswer {
    fn from(text: String) -> Self {
        match text.as_str() {
            "skipped" => Self::Skipped,
            "finished" => Self::Finished,
            _ => Self::Other(text),
        }
    }
}

impl From<WelcomeAnswer> for String {
    fn from(answer: WelcomeAnswer) -> Self {
        match answer {
            WelcomeAnswer::Skipped => "skipped".to_owned(),
            WelcomeAnswer::Finished => "finished".to_owned(),
            WelcomeAnswer::Other(text) => text,
        }
    }
}

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct LocalSettings {
    pub schema: i64,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub backup_remote_offer: Option<BackupRemoteOffer>,
    /// The first-run welcome was answered (M58). Absent in files written
    /// before it existed: the app then decides from the store alone.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub welcome: Option<WelcomeAnswer>,
    /// Settings > Updates switch (SPEC 16.4). Absent means on; read only
    /// by builds that carry the updater.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub check_for_updates: Option<bool>,
    /// The bundled Surjection skill version this machine already reported as
    /// "customized, not updated" (#8), so the note is shown once per
    /// version.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub agent_skill_notice: Option<String>,
    /// The "Online catalogs" switch (#26). Absent means off: nothing
    /// contacts a catalog until the user turns it on (the first time they
    /// open Install > Browse, or `surject catalog online on`).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub online_catalogs: Option<bool>,
    /// The hosts the user approved for online catalogs: named when they
    /// turned them on (M53) or allowed since (M60). A file from before
    /// 0.9.0 has no list: its "on" approved `catalog::LEGACY_HOSTS`.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub online_catalog_hosts: Option<Vec<String>>,
    /// Hosts the user answered "Not now" (M60, #40): not contacted, and
    /// Browse does not ask about them again. Absent in older files.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub online_catalog_hosts_not_now: Option<Vec<String>>,
    /// SkillSpector, the optional external scanner (#30). Absent means
    /// off.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub skillspector: Option<SkillSpectorSettings>,
    /// `surject migrate loadout` finished on this machine (the Surjection
    /// version that ran it): the automatic run at start is not repeated.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub loadout_migration: Option<String>,
    /// "Check this address" answers per host (#47). Absent: none yet.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub address_check_hosts: Option<AddressCheckHosts>,
    /// Every other key, kept as it is (`[snyk_agent_scan]` of 0.7.0 among
    /// them: `scan::external::snyk_leftover` removes it).
    #[serde(flatten)]
    pub extra: toml::Table,
}

/// `[skillspector]`: SkillSpector on this machine (#30).
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
pub struct SkillSpectorSettings {
    /// Run it on skill installs and updates. Absent means off.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub enabled: Option<bool>,
    /// Seconds per scan (default 120, at most 3540: see
    /// `skillspector::MAX_TIMEOUT`).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub timeout_secs: Option<u64>,
}

/// `[address_check_hosts]`: the hosts the user answered for "Check this
/// address" (#47). A host in neither list was never asked about; the
/// check contacts only `allowed` hosts.
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
pub struct AddressCheckHosts {
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub allowed: Vec<String>,
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub denied: Vec<String>,
}

impl Default for LocalSettings {
    fn default() -> Self {
        Self {
            schema: SCHEMA_VERSION,
            backup_remote_offer: None,
            welcome: None,
            check_for_updates: None,
            agent_skill_notice: None,
            online_catalogs: None,
            online_catalog_hosts: None,
            online_catalog_hosts_not_now: None,
            skillspector: None,
            loadout_migration: None,
            address_check_hosts: None,
            extra: toml::Table::new(),
        }
    }
}

impl LocalSettings {
    /// The settings of this machine; defaults when the file is absent.
    pub fn load(fs: &dyn Fs, state_dir: &Path) -> Result<Self, CoreError> {
        let path = state_dir.join(LOCAL_SETTINGS_FILE);
        if !fs.exists(&path) {
            return Ok(Self::default());
        }
        let text = fs.read_to_string(&path).map_err(|err| {
            CoreError::new(ErrorCode::IoError, format!("cannot read file: {err}")).with_path(&path)
        })?;
        let settings: Self = toml::from_str(&text).map_err(|err| {
            CoreError::new(ErrorCode::ParseError, err.message().to_owned()).with_path(&path)
        })?;
        if settings.schema != SCHEMA_VERSION {
            return Err(CoreError::new(
                ErrorCode::UnsupportedSchema,
                format!("schema {} is not read by this build", settings.schema),
            )
            .with_path(&path));
        }
        Ok(settings)
    }

    pub fn save(&self, fs: &dyn Fs, state_dir: &Path) -> Result<(), CoreError> {
        let text = toml::to_string_pretty(self).map_err(|err| {
            CoreError::new(
                ErrorCode::InvalidValue,
                format!("cannot write local settings: {err}"),
            )
        })?;
        fs.create_dir_all(state_dir).map_err(|err| {
            CoreError::new(
                ErrorCode::IoError,
                format!("cannot create directory: {err}"),
            )
            .with_path(state_dir)
        })?;
        crate::apply::write_atomic(fs, &state_dir.join(LOCAL_SETTINGS_FILE), text.as_bytes())
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn welcome_answers_round_trip_and_older_files_parse() {
        let older: LocalSettings =
            toml::from_str("schema = 1\nbackup_remote_offer = \"not-now\"\n").unwrap();
        assert_eq!(older.welcome, None);
        assert_eq!(older.backup_remote_offer, Some(BackupRemoteOffer::NotNow));

        for answer in [WelcomeAnswer::Skipped, WelcomeAnswer::Finished] {
            let settings = LocalSettings {
                welcome: Some(answer.clone()),
                ..LocalSettings::default()
            };
            let text = toml::to_string_pretty(&settings).unwrap();
            let back: LocalSettings = toml::from_str(&text).unwrap();
            assert_eq!(back.welcome, Some(answer));
        }
    }

    #[test]
    fn a_welcome_value_from_a_newer_build_counts_as_answered_and_round_trips() {
        let newer: LocalSettings =
            toml::from_str("schema = 1\nwelcome = \"replayed\"\nfuture = 3\n").unwrap();
        assert_eq!(
            newer.welcome,
            Some(WelcomeAnswer::Other("replayed".to_owned()))
        );
        assert!(newer.extra.contains_key("future"), "other keys are kept");
        let text = toml::to_string_pretty(&newer).unwrap();
        assert!(text.contains("welcome = \"replayed\""), "{text}");
        let back: LocalSettings = toml::from_str(&text).unwrap();
        assert_eq!(back, newer);
    }

    #[test]
    fn catalog_host_answers_parse_from_every_release() {
        // 0.6 to 0.8: on, no hosts.
        let pre: LocalSettings = toml::from_str("schema = 1\nonline_catalogs = true\n").unwrap();
        assert_eq!(pre.online_catalog_hosts, None);
        assert_eq!(pre.online_catalog_hosts_not_now, None);
        // 0.9 to 1.0.0: hosts, no "Not now".
        let text = "schema = 1\nonline_catalogs = true\nonline_catalog_hosts = [\"github.com\"]\n";
        let hosts: LocalSettings = toml::from_str(text).unwrap();
        assert_eq!(
            hosts.online_catalog_hosts,
            Some(vec!["github.com".to_owned()])
        );
        // 1.0.1: "Not now" round-trips.
        let settings = LocalSettings {
            online_catalog_hosts_not_now: Some(vec!["skills.sh".to_owned()]),
            ..hosts
        };
        let back: LocalSettings =
            toml::from_str(&toml::to_string_pretty(&settings).unwrap()).unwrap();
        assert_eq!(back, settings);
        assert!(back.extra.is_empty(), "a known key, not an extra one");
    }
}