surjection-core 1.2.0

Core library of Surjection: MCP servers, skills and secret references for AI coding clients
Documentation
//! `state/eject.json`: the record of every eject run on this machine (its
//! journal, what rollback needs) and the marker that keeps Surjection away from
//! what was ejected while a run is active.

use std::path::Path;

use serde::{Deserialize, Serialize};

use crate::apply::ledger::LedgerEntry;
use crate::apply::write_atomic;
use crate::error::{CoreError, ErrorCode};
use crate::fs::Fs;
use crate::skills::link::SkillLink;

/// The record file in `state/`.
pub const EJECT_FILE: &str = "eject.json";
pub(crate) const EJECT_SCHEMA: u32 = 1;
/// Runs kept; the oldest inactive ones go first.
const KEEP_RUNS: usize = 20;

/// `state/eject.json`.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct EjectFile {
    pub schema: u32,
    #[serde(default)]
    pub runs: Vec<EjectRun>,
    /// Keys a newer build wrote, kept on rewrite.
    #[serde(flatten)]
    pub extra: serde_json::Map<String, serde_json::Value>,
}

impl Default for EjectFile {
    fn default() -> Self {
        Self {
            schema: EJECT_SCHEMA,
            runs: Vec::new(),
            extra: serde_json::Map::new(),
        }
    }
}

/// One eject run.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct EjectRun {
    /// A ULID, like apply ids (its backups are `backups/files/<ts>-<id>/`).
    pub id: String,
    /// RFC 3339, UTC.
    pub time: String,
    /// The clients the run covered; `None` for every client.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub clients: Option<Vec<String>>,
    /// The project the run covered; `None` for user files and every project.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub project_id: Option<String>,
    /// The run got to its end (a crash leaves it `false`; it still counts as
    /// active).
    #[serde(default)]
    pub finished: bool,
    /// The user started managing again ([`super::resume`]).
    #[serde(default)]
    pub resumed: bool,
    #[serde(default)]
    pub rolled_back: bool,
    /// Client files written, with what was written.
    #[serde(default)]
    pub files: Vec<EjectedFile>,
    /// The ledger rows the run dropped, as they were.
    #[serde(default)]
    pub ledger: Vec<LedgerEntry>,
    /// The skill rows the run dropped, as they were.
    #[serde(default)]
    pub skill_links: Vec<SkillLink>,
    /// Links replaced by copies: the copy's content hash.
    #[serde(default)]
    pub copied: Vec<CopiedSkill>,
    /// Owned copies whose marker file was removed.
    #[serde(default)]
    pub unmarked: Vec<String>,
    #[serde(flatten)]
    pub extra: serde_json::Map<String, serde_json::Value>,
}

impl EjectRun {
    /// Whether the run still keeps Surjection away from what it ejected.
    pub fn active(&self) -> bool {
        !self.resumed && !self.rolled_back
    }
}

/// A client file an eject run wrote.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct EjectedFile {
    /// Absolute, as on this machine.
    pub file: String,
    /// The backup of the content before the run.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub backup: Option<String>,
    /// `sha256:<hex>` of the bytes the run wrote.
    pub written: String,
}

/// A skill link an eject run replaced by a copy.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct CopiedSkill {
    pub path: String,
    /// [`crate::skills::content_hash`] of the copy.
    pub hash: String,
}

impl EjectFile {
    /// Reads the record; an absent file is an empty record. A record that
    /// does not parse is an error (losing it would let Surjection manage what
    /// the user handed back).
    pub fn load(fs: &dyn Fs, state_dir: &Path) -> Result<Self, CoreError> {
        let path = state_dir.join(EJECT_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 the eject record: {err}"),
            )
            .with_path(&path)
        })?;
        let file: Self = serde_json::from_str(&text).map_err(|err| {
            CoreError::new(
                ErrorCode::ParseError,
                format!("the eject record does not parse: {err}"),
            )
            .with_path(&path)
        })?;
        if file.schema != EJECT_SCHEMA {
            return Err(CoreError::new(
                ErrorCode::UnsupportedSchema,
                format!(
                    "eject record schema {} is not supported; this build reads schema {EJECT_SCHEMA}",
                    file.schema
                ),
            )
            .with_path(&path));
        }
        Ok(file)
    }

    /// Writes the record atomically, keeping the newest [`KEEP_RUNS`] runs
    /// (active runs are never dropped).
    pub fn save(&mut self, fs: &dyn Fs, state_dir: &Path) -> Result<(), CoreError> {
        while self.runs.len() > KEEP_RUNS {
            match self.runs.iter().position(|run| !run.active()) {
                Some(index) => {
                    self.runs.remove(index);
                }
                None => break,
            }
        }
        let mut text = serde_json::to_string_pretty(self).map_err(|err| {
            CoreError::new(
                ErrorCode::InvalidValue,
                format!("cannot serialize the eject record: {err}"),
            )
        })?;
        text.push('\n');
        fs.create_dir_all(state_dir).map_err(|err| {
            CoreError::new(
                ErrorCode::IoError,
                format!("cannot create directory: {err}"),
            )
            .with_path(state_dir)
        })?;
        write_atomic(fs, &state_dir.join(EJECT_FILE), text.as_bytes())
    }
}

/// What the active eject runs cover.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Ejected {
    pub runs: Vec<ActiveRun>,
}

/// One active run ([`EjectRun::active`]).
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ActiveRun {
    pub id: String,
    pub time: String,
    pub clients: Option<Vec<String>>,
    pub project_id: Option<String>,
    /// `false` for a run that stopped partway (roll it back).
    pub finished: bool,
}

impl Ejected {
    /// Whether `client`'s entries in the target of `project_id` (`None` for
    /// user files) were handed back.
    pub fn covers(&self, client: &str, project_id: Option<&str>) -> bool {
        self.runs.iter().any(|run| {
            run.clients
                .as_ref()
                .is_none_or(|clients| clients.iter().any(|id| id == client))
                && run
                    .project_id
                    .as_deref()
                    .is_none_or(|id| Some(id) == project_id)
        })
    }

    /// Whether a run covered everything: this machine is not managed.
    pub fn all(&self) -> bool {
        self.runs
            .iter()
            .any(|run| run.clients.is_none() && run.project_id.is_none())
    }

    /// A run that stopped partway, if any: roll it back before ejecting
    /// again.
    pub fn unfinished(&self) -> Option<&ActiveRun> {
        self.runs.iter().find(|run| !run.finished)
    }
}

/// The active runs of the record in `state_dir`, `None` when there are
/// none (or no record).
pub fn status_at(fs: &dyn Fs, state_dir: &Path) -> Result<Option<Ejected>, CoreError> {
    if !fs.exists(&state_dir.join(EJECT_FILE)) {
        return Ok(None);
    }
    let runs: Vec<ActiveRun> = EjectFile::load(fs, state_dir)?
        .runs
        .into_iter()
        .filter(EjectRun::active)
        .map(|run| ActiveRun {
            id: run.id,
            time: run.time,
            clients: run.clients,
            project_id: run.project_id,
            finished: run.finished,
        })
        .collect();
    Ok((!runs.is_empty()).then_some(Ejected { runs }))
}