//! Filesystem effects supporting immutable project snapshots and atomic updates. use super::types::{ArtifactIdentity, Manifest, RunInfo, WorkflowError}; use serde::{Serialize, de::DeserializeOwned}; use sha2::{Digest, Sha256}; use std::fs::{self, File, OpenOptions}; use std::io::Write; use std::path::{Path, PathBuf}; /// Compute a stable identity of exact serialized bytes. pub(super) fn digest(bytes: &[u8]) -> String { format!("{:x}", Sha256::digest(bytes)) } /// Read one file and bind its current bytes. pub(super) fn file_digest(path: &Path) -> Result { Ok(digest(&fs::read(path)?)) } /// Decode strict metadata through the receiving type's schema. pub(super) fn read_json(path: &Path) -> Result { Ok(serde_json::from_slice(&fs::read(path)?)?) } /// Atomically replace a single file while its project lock is held. pub(super) fn atomic_bytes(path: &Path, bytes: &[u8]) -> Result<(), WorkflowError> { let parent = path .parent() .ok_or(WorkflowError::Invalid("file needs a parent directory"))?; let mut temporary = tempfile::NamedTempFile::new_in(parent)?; temporary.write_all(bytes)?; temporary.as_file().sync_all()?; temporary.persist(path).map_err(|error| error.error)?; File::open(parent)?.sync_all()?; Ok(()) } /// Serialize a complete state before publishing one atomic replacement. pub(super) fn atomic_json(path: &Path, value: &impl Serialize) -> Result<(), WorkflowError> { let mut bytes = serde_json::to_vec_pretty(value)?; bytes.push(b'\n'); atomic_bytes(path, &bytes) } /// A short-lived cross-process update lock; a crashed lock needs explicit removal. pub(super) struct ProjectLock { /// Exclusive lockfile claimed by this guard. path: PathBuf, } impl ProjectLock { /// Claim a new lock without blocking the native worker or losing updates. pub(super) fn acquire(project: &Path) -> Result { let path = project.join(".workflow.lock"); match OpenOptions::new().create_new(true).write(true).open(&path) { Ok(mut file) => { let guard = Self { path }; writeln!(file, "{}", std::process::id())?; Ok(guard) } Err(error) if error.kind() == std::io::ErrorKind::AlreadyExists => { Err(WorkflowError::Busy) } Err(error) => Err(error.into()), } } } impl Drop for ProjectLock { /// Release only the path owned by this successful exclusive claim. fn drop(&mut self) { let _ = fs::remove_file(&self.path); } } /// Resolve a local existing project to an absolute stable path. pub(super) fn canonical(project: &Path) -> Result { Ok(fs::canonicalize(project)?) } /// Read the two prediction-defining artifact files. pub(super) fn identity(model: &Path) -> Result { Ok(ArtifactIdentity { config_sha256: file_digest(&model.join("config.json"))?, weights_sha256: file_digest(&model.join("model.safetensors"))?, }) } /// Reject silent artifact replacement before trusting any associated evidence. pub(super) fn verify_identity( model: &Path, expected: &ArtifactIdentity, ) -> Result<(), WorkflowError> { if identity(model)? != *expected { return Err(WorkflowError::Changed(model.to_path_buf())); } Ok(()) } /// Validate all immutable project source identities on every public operation. pub(super) fn manifest(project: &Path) -> Result { let manifest: Manifest = read_json(&project.join("project.json"))?; if !matches!(manifest.format_version, 1 | 2) || (manifest.format_version == 1 && manifest.task_suite.is_some()) || (manifest.format_version == 2 && manifest.task_suite.is_none()) { return Err(WorkflowError::Invalid("unsupported project version")); } verify_identity(&project.join("baseline"), &manifest.baseline)?; for (name, expected) in [ ("training.json", &manifest.training_sha256), ("evaluation.json", &manifest.evaluation_sha256), ] { let path = project.join("frozen").join(name); if file_digest(&path)? != *expected { return Err(WorkflowError::Changed(path)); } } if let Some(tasks) = &manifest.task_suite { for (name, expected) in [ ("emacs-tasks.json", &tasks.tasks_sha256), ("emacs-task-runner.el", &tasks.runner_sha256), ] { let path = project.join("frozen").join(name); if file_digest(&path)? != *expected { return Err(WorkflowError::Changed(path)); } } if !tasks.emacs.is_absolute() || tasks.timeout_seconds == 0 { return Err(WorkflowError::Invalid("invalid frozen task runtime")); } } Ok(manifest) } /// Reject path components masquerading as generated run identifiers. pub(super) fn run_directory(project: &Path, id: &str) -> Result { if !id.starts_with("run-") || !id .bytes() .all(|byte| byte.is_ascii_alphanumeric() || byte == b'-') { return Err(WorkflowError::Invalid("invalid run identifier")); } Ok(project.join("runs").join(id)) } /// Load a run record whose embedded paths cannot escape its project. pub(super) fn read_run(project: &Path, id: &str) -> Result { let directory = run_directory(project, id)?; let run: RunInfo = read_json(&directory.join("run.json"))?; if run.id != id || run.model != directory.join("model") || run .finalized_model .as_ref() .is_some_and(|path| path != &project.join("finalized").join(id)) { return Err(WorkflowError::Invalid("run identity or path mismatch")); } if file_digest(&directory.join("training.json"))? != run.training_data_sha256 { return Err(WorkflowError::Changed(directory.join("training.json"))); } if file_digest(&directory.join("examples.json"))? != run.generation { return Err(WorkflowError::Changed(directory.join("examples.json"))); } Ok(run) } /// Copy only prediction artifacts into a newly claimed immutable directory. pub(super) fn copy_model( source: &Path, destination: &Path, ) -> Result { let before = identity(source)?; fs::create_dir(destination)?; for name in ["config.json", "model.safetensors"] { fs::copy(source.join(name), destination.join(name))?; } if source.join("catalog.json").is_file() { fs::copy(source.join("catalog.json"), destination.join("catalog.json"))?; } verify_identity(source, &before)?; verify_identity(destination, &before)?; Ok(before) } /// Resolve the active open `ActionCatalog` if `project/baseline` is a bi-encoder artifact. pub(super) fn project_catalog( project: &Path, ) -> Result, WorkflowError> { let baseline = project.join("baseline"); if !crate::engine::is_biencoder_artifact(&baseline)? { return Ok(None); } let root_cat = project.join("catalog.json"); if root_cat.is_file() { return Ok(Some(crate::catalog::ActionCatalog::load_or_builtin(&root_cat)?)); } Ok(Some(crate::catalog::ActionCatalog::load_or_builtin( &baseline.join("catalog.json"), )?)) } #[cfg(test)] mod tests { use super::*; #[test] fn a_copy_of_a_newer_source_cannot_satisfy_the_frozen_artifact_identity() -> Result<(), WorkflowError> { let directory = tempfile::tempdir()?; let source = directory.path().join("source"); fs::create_dir(&source)?; fs::write(source.join("config.json"), "configuration")?; fs::write(source.join("model.safetensors"), "original weights")?; let frozen = identity(&source)?; fs::write(source.join("model.safetensors"), "replacement weights")?; let staged = directory.path().join("staged"); copy_model(&source, &staged)?; assert!(matches!( verify_identity(&staged, &frozen), Err(WorkflowError::Changed(_)) )); Ok(()) } }