blyte 0.87.0

The blyte coding-agent harness: headless runs with a sealed verification gate, and a REPL.
Documentation
use std::fmt::Write as _;
use std::path::{Path, PathBuf};
use std::time::UNIX_EPOCH;

use serde::{Deserialize, Serialize};

pub const CURRENT_VERSION: &str =
    concat!(env!("CARGO_PKG_VERSION"), " (", env!("BLYTE_BUILD"), ")");

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct BinaryFingerprint {
    pub path: PathBuf,
    pub size: u64,
    pub modified_secs: u64,
    pub modified_nanos: u32,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub inode: Option<u64>,
}

impl BinaryFingerprint {
    pub fn current() -> Result<Self, String> {
        let exe = std::env::current_exe()
            .map_err(|e| format!("cannot locate running blyte binary: {e}"))?;
        Self::from_path(&exe)
    }

    pub fn from_path(path: &Path) -> Result<Self, String> {
        let meta = std::fs::metadata(path)
            .map_err(|e| format!("cannot inspect blyte binary {}: {e}", path.display()))?;
        if !meta.is_file() {
            return Err(format!(
                "blyte binary {} is not a regular file",
                path.display()
            ));
        }
        let modified = meta
            .modified()
            .map_err(|e| format!("cannot read mtime of blyte binary {}: {e}", path.display()))?;
        let since_epoch = modified.duration_since(UNIX_EPOCH).map_err(|e| {
            format!(
                "mtime of blyte binary {} precedes Unix epoch: {e}",
                path.display()
            )
        })?;
        Ok(Self {
            path: path.to_path_buf(),
            size: meta.len(),
            modified_secs: since_epoch.as_secs(),
            modified_nanos: since_epoch.subsec_nanos(),
            inode: file_inode(&meta),
        })
    }

    pub fn is_stale(&self) -> Result<bool, String> {
        let on_disk = Self::from_path(&self.path)?;
        Ok(on_disk != *self)
    }
}

#[cfg(unix)]
fn file_inode(meta: &std::fs::Metadata) -> Option<u64> {
    use std::os::unix::fs::MetadataExt;
    Some(meta.ino())
}

#[cfg(not(unix))]
fn file_inode(_meta: &std::fs::Metadata) -> Option<u64> {
    None
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct SurfaceRuntimeInfo {
    pub version: String,
    pub binary_fingerprint: BinaryFingerprint,
    pub boot_id: String,
}

impl SurfaceRuntimeInfo {
    pub fn current() -> Result<Self, String> {
        Ok(Self {
            version: CURRENT_VERSION.to_string(),
            binary_fingerprint: BinaryFingerprint::current()?,
            boot_id: generate_boot_id()?,
        })
    }

    pub fn from_binary(
        version: impl Into<String>,
        binary_path: &Path,
        boot_id: impl Into<String>,
    ) -> Result<Self, String> {
        let version = version.into();
        let boot_id = boot_id.into();
        if version.trim().is_empty() {
            return Err("surface version cannot be empty".to_string());
        }
        if boot_id.trim().is_empty() {
            return Err("surface boot_id cannot be empty".to_string());
        }
        Ok(Self {
            version,
            binary_fingerprint: BinaryFingerprint::from_path(binary_path)?,
            boot_id,
        })
    }

    pub fn is_stale(&self) -> Result<bool, String> {
        self.binary_fingerprint.is_stale()
    }

    pub fn verify_executable(&self) -> Result<(), String> {
        verify_executable(&self.binary_fingerprint.path)
    }

    pub fn validate(&self) -> Result<(), String> {
        if self.version.trim().is_empty() {
            return Err("surface version cannot be empty".to_string());
        }
        if self.boot_id.trim().is_empty() {
            return Err("surface boot_id cannot be empty".to_string());
        }
        if self.binary_fingerprint.path.as_os_str().is_empty() {
            return Err("binary_fingerprint path cannot be empty".to_string());
        }
        Ok(())
    }
}

#[cfg(unix)]
pub fn generate_boot_id() -> Result<String, String> {
    use std::io::Read;
    let mut file = std::fs::File::open("/dev/urandom")
        .map_err(|e| format!("cannot open /dev/urandom to generate boot_id: {e}"))?;
    let mut bytes = [0u8; 16];
    file.read_exact(&mut bytes)
        .map_err(|e| format!("cannot read /dev/urandom to generate boot_id: {e}"))?;
    Ok(hex_encode(&bytes))
}

#[cfg(not(unix))]
pub fn generate_boot_id() -> Result<String, String> {
    use sha2::{Digest, Sha256};
    use std::sync::atomic::{AtomicU64, Ordering};
    static COUNTER: AtomicU64 = AtomicU64::new(0);
    let now = std::time::SystemTime::now()
        .duration_since(UNIX_EPOCH)
        .map_err(|e| format!("system clock error generating boot_id: {e}"))?;
    let mut hasher = Sha256::new();
    hasher.update(std::process::id().to_le_bytes());
    hasher.update(now.as_nanos().to_le_bytes());
    hasher.update(COUNTER.fetch_add(1, Ordering::Relaxed).to_le_bytes());
    let digest = hasher.finalize();
    Ok(hex_encode(&digest[..16]))
}

fn hex_encode(bytes: &[u8]) -> String {
    let mut out = String::with_capacity(bytes.len() * 2);
    for b in bytes {
        let _ = write!(out, "{b:02x}");
    }
    out
}

pub fn verify_executable(path: &Path) -> Result<(), String> {
    if path.as_os_str().is_empty() {
        return Err("blyte binary path is empty".to_string());
    }
    let meta = std::fs::metadata(path).map_err(|e| match e.kind() {
        std::io::ErrorKind::NotFound => format!("blyte binary not found at {}", path.display()),
        _ => format!("cannot inspect blyte binary at {}: {e}", path.display()),
    })?;
    if !meta.is_file() {
        return Err(format!(
            "blyte binary at {} is not a regular file",
            path.display()
        ));
    }
    #[cfg(unix)]
    {
        use std::ffi::CString;
        use std::os::unix::ffi::OsStrExt;
        use std::os::unix::fs::PermissionsExt;
        if meta.permissions().mode() & 0o111 == 0 {
            return Err(format!(
                "blyte binary at {} is not executable",
                path.display()
            ));
        }
        let cpath = CString::new(path.as_os_str().as_bytes())
            .map_err(|_| format!("blyte binary path {} contains a NUL byte", path.display()))?;
        if unsafe { libc::access(cpath.as_ptr(), libc::X_OK) } != 0 {
            let err = std::io::Error::last_os_error();
            return Err(format!(
                "blyte binary at {} is not executable: {err}",
                path.display()
            ));
        }
    }
    Ok(())
}