neosian 3.0.0

The state layer for LLM agents, as one static binary: the record, memory and the state process
//! One planned replacement of a client file (A1d, review finding 5): the
//! bytes it was computed from and the bytes to write. It is written only over
//! those same bytes, so a client that changed the file while setup ran keeps
//! its change and the install refuses; and two spellings of one file (a
//! project file that links to the user file) are one target.

use super::{
    context::{Context, absolute},
    files::{self, Failure},
};
use std::path::{Path, PathBuf};

pub struct Edit {
    pub path: PathBuf,
    /// The file's text when the edit was computed; `None` when absent.
    pub read: Option<String>,
    pub text: String,
}

impl Edit {
    pub fn changes(&self) -> bool {
        self.read.as_deref() != Some(self.text.as_str())
    }

    /// Writes the edit when it changes the file and the file still holds
    /// what it was computed from.
    pub fn write(&self) -> Result<(), Failure> {
        if !self.changes() {
            return Ok(());
        }
        let now = match std::fs::read_to_string(&self.path) {
            Ok(text) => Some(text),
            Err(e) if e.kind() == std::io::ErrorKind::NotFound => None,
            Err(e) => return Err(Failure::new(e.to_string(), files::FIX)),
        };
        if now != self.read {
            let message = format!(
                "{} changed while setup ran, so it was not written",
                self.path.display()
            );
            return Err(Failure::new(message, "run setup again"));
        }
        files::write_text(&self.path, &self.text)
    }
}

/// Whether two paths name one file once links are resolved.
pub fn same(context: &Context, one: &Path, other: &Path) -> bool {
    absolute(&context.cwd, one) == absolute(&context.cwd, other)
}

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

    #[test]
    fn an_edit_is_written_only_over_the_bytes_it_was_computed_from() {
        let scratch = Scratch::new("client-edit");
        scratch.plant("a.json", "before\n");
        let path = scratch.path().join("a.json");
        let edit = Edit {
            path: path.clone(),
            read: Some("before\n".into()),
            text: "after\n".into(),
        };
        scratch.plant("a.json", "the client's own\n");
        assert!(
            edit.write()
                .unwrap_err()
                .message
                .contains("changed while setup ran")
        );
        assert_eq!(
            std::fs::read_to_string(&path).unwrap(),
            "the client's own\n"
        );
        scratch.plant("a.json", "before\n");
        assert!(edit.write().is_ok());
        assert_eq!(std::fs::read_to_string(&path).unwrap(), "after\n");
    }
}