artifactize-core 0.33.0

The library behind artifactize: Artifacts, evals, reviews, the monitor and review models, and the shared operations every interface calls.
Documentation
//! The process environment, read in one place: variable lookup, which ignores the case of
//! names on Windows, snapshots handed to children, and lookups in such snapshots. Every child
//! gets a snapshot, never this process's environment by inheritance.

use std::{
    borrow::Cow,
    collections::BTreeMap,
    ffi::{OsStr, OsString},
};

/// One variable of this process's environment; `None` when it is unset.
pub fn var(name: &str) -> Option<OsString> {
    std::env::var_os(name)
}

/// One variable as text; `None` when it is unset or not Unicode.
pub fn var_text(name: &str) -> Option<String> {
    std::env::var(name).ok()
}

/// The whole environment of a child that runs as the person using artifactize: this
/// process's, without what an AppImage added to it ([`artifactize_tools::environment::user`]).
pub(crate) fn snapshot() -> BTreeMap<OsString, OsString> {
    artifactize_tools::environment::user()
}

/// The prefix of artifactize's own variables: its credentials, settings and the variables it
/// sets for one command.
const OWN_PREFIX: &str = "ARTIFACTIZE_";

/// The environment of a command an author declared: this process's whole environment, as in
/// the author's terminal, without artifactize's own variables. A caller adds the few that
/// the command is meant to see.
pub(crate) fn for_command() -> BTreeMap<OsString, OsString> {
    for_command_from(&snapshot())
}

/// The environment of the shared Verify engine daemon: [`snapshot`] without per-caller
/// credentials, test endpoints, Codex home, agent timeouts, or remote store overrides.
/// Each submitted Run carries its own `caller_env` snapshot instead of inheriting Caller 1's.
pub(crate) fn for_engine() -> BTreeMap<OsString, OsString> {
    const PER_CALLER_EXACT: [&str; 10] = [
        "OPENAI_API_KEY",
        "ANTHROPIC_API_KEY",
        "GEMINI_API_KEY",
        "CODEX_HOME",
        "ARTIFACTIZE_AGENT_TIMEOUT_MS",
        "ARTIFACTIZE_OPENAI_BASE_URL",
        "ARTIFACTIZE_ANTHROPIC_BASE_URL",
        "ARTIFACTIZE_GEMINI_BASE_URL",
        "ARTIFACTIZE_CODEX_BASE_URL",
        "ARTIFACTIZE_CODEX_AUTH_URL",
    ];
    const REMOTE_PREFIX: &str = "ARTIFACTIZE_REMOTE";
    let mut environment = snapshot();
    environment.retain(|name, _| {
        !PER_CALLER_EXACT
            .iter()
            .any(|var| same_name(name, OsStr::new(var)))
            && !starts_with_name_prefix(name, REMOTE_PREFIX)
    });
    environment
}

/// Filter a captured caller environment for an authored command, stripping artifactize's own
/// `ARTIFACTIZE_*` variables just as [`for_command`] does for the current process.
pub(crate) fn for_command_from(
    base: &BTreeMap<OsString, OsString>,
) -> BTreeMap<OsString, OsString> {
    let mut environment = base.clone();
    environment.retain(|name, _| {
        !name
            .to_str()
            .is_some_and(|name| name.to_ascii_uppercase().starts_with(OWN_PREFIX))
    });
    environment
}

/// Capture the Unicode subset of [`snapshot`] for IPC transfer from a submitter to the Verify
/// engine daemon, preserving the caller's environment without leaking across concurrent Runs.
pub(crate) fn snapshot_text() -> BTreeMap<String, String> {
    snapshot()
        .into_iter()
        .filter_map(|(k, v)| Some((k.into_string().ok()?, v.into_string().ok()?)))
        .collect()
}

/// Convert a wire text environment map back into an OS-string environment map.
pub(crate) fn from_text(map: &BTreeMap<String, String>) -> BTreeMap<OsString, OsString> {
    map.iter()
        .map(|(k, v)| (OsString::from(k), OsString::from(v)))
        .collect()
}

/// Look up a Unicode variable in a captured environment using the platform's name comparison.
pub(crate) fn lookup_text(
    environment: &BTreeMap<OsString, OsString>,
    name: &str,
) -> Option<String> {
    lookup(environment, name).and_then(|value| value.to_str().map(str::to_owned))
}

/// Use the same environment for program lookup and launch. When a caller supplies aliases,
/// the last entry in map order wins, as when passing the ordered map to `Command::envs`.
pub(crate) fn for_child(
    environment: &BTreeMap<OsString, OsString>,
) -> Cow<'_, BTreeMap<OsString, OsString>> {
    if !super::ENV_NAMES_IGNORE_CASE {
        return Cow::Borrowed(environment);
    }
    let mut normalized = BTreeMap::new();
    for (name, value) in environment {
        insert(&mut normalized, name, value.clone());
    }
    Cow::Owned(normalized)
}

/// Set one variable of a built environment, replacing a variable of the same name as this
/// system compares names.
pub(crate) fn set(
    environment: &mut BTreeMap<OsString, OsString>,
    name: &str,
    value: impl Into<OsString>,
) {
    insert(environment, OsStr::new(name), value.into());
}

fn insert(environment: &mut BTreeMap<OsString, OsString>, name: &OsStr, value: OsString) {
    if super::ENV_NAMES_IGNORE_CASE {
        environment.retain(|key, _| !same_name(key, name));
    }
    environment.insert(name.into(), value);
}

/// One variable of an environment built for a child, matching names as this system does:
/// exactly on Unix, without regard to case on Windows.
pub(crate) fn lookup<'a>(
    environment: &'a BTreeMap<OsString, OsString>,
    name: &str,
) -> Option<&'a OsStr> {
    if super::ENV_NAMES_IGNORE_CASE {
        environment
            .iter()
            .find_map(|(key, value)| same_name(key, OsStr::new(name)).then_some(value.as_os_str()))
    } else {
        environment.get(OsStr::new(name)).map(OsString::as_os_str)
    }
}

#[cfg(unix)]
pub(crate) fn same_name(left: &OsStr, right: &OsStr) -> bool {
    left == right
}

#[cfg(windows)]
pub(crate) fn same_name(left: &OsStr, right: &OsStr) -> bool {
    use std::os::windows::ffi::OsStrExt;
    use windows_sys::Win32::Globalization::{CSTR_EQUAL, CompareStringOrdinal};
    let left: Vec<_> = left.encode_wide().collect();
    let right: Vec<_> = right.encode_wide().collect();
    let (Ok(left_len), Ok(right_len)) = (i32::try_from(left.len()), i32::try_from(right.len()))
    else {
        return false;
    };
    // SAFETY: both UTF-16 buffers remain live for their explicit lengths; no pointer is retained.
    unsafe {
        CompareStringOrdinal(left.as_ptr(), left_len, right.as_ptr(), right_len, 1) == CSTR_EQUAL
    }
}

#[cfg(unix)]
fn starts_with_name_prefix(name: &OsStr, prefix: &str) -> bool {
    use std::os::unix::ffi::OsStrExt;
    name.as_bytes().starts_with(prefix.as_bytes())
}

#[cfg(windows)]
fn starts_with_name_prefix(name: &OsStr, prefix: &str) -> bool {
    use std::os::windows::ffi::OsStrExt;
    use windows_sys::Win32::Globalization::{CSTR_EQUAL, CompareStringOrdinal};
    let name: Vec<_> = name.encode_wide().collect();
    let prefix: Vec<_> = OsStr::new(prefix).encode_wide().collect();
    if name.len() < prefix.len() {
        return false;
    }
    let Ok(len) = i32::try_from(prefix.len()) else {
        return false;
    };
    // SAFETY: both UTF-16 slices remain live for `len` code units; no pointer is retained.
    unsafe { CompareStringOrdinal(name.as_ptr(), len, prefix.as_ptr(), len, 1) == CSTR_EQUAL }
}

/// Have a child allocate its ordinary temporary files within its owned run directory.
pub(crate) fn set_temporary_directory(
    environment: &mut BTreeMap<OsString, OsString>,
    dir: &std::path::Path,
) {
    for key in super::TEMP_VARIABLES {
        set(environment, key, dir);
    }
}