aft-base 0.67.1

Shared foundation for Agent Foundational Toolkit
Documentation
//! Shared helpers for tests that need process-global environment isolation.
//!
//! `HOME`, `USERPROFILE`, `XDG_CONFIG_HOME`, `GIT_CONFIG_GLOBAL`, and
//! `GIT_CONFIG_SYSTEM` are process-global. The libtest runner executes unit tests
//! concurrently within one process, so any test that mutates or depends on these
//! variables must serialize on the SAME lock — module-local mutexes only protect
//! against siblings in the same file, not against an env-mutating test in another
//! module running in parallel.

use std::cell::{Cell, RefCell};
use std::ffi::{OsStr, OsString};
use std::process::Command;
use std::sync::{Mutex, MutexGuard, OnceLock};

/// Return inherited credential-shaped names so test child processes can omit them.
/// AFT's co-author setting is not a secret, but it is dropped too so a test
/// child never adds the operator's co-author trailer to fixture commits.
pub fn secret_named_environment_keys(is_secret_environment_key: fn(&str) -> bool) -> Vec<OsString> {
    std::env::vars_os()
        .map(|(key, _)| key)
        .filter(|key| {
            key.to_str()
                .is_some_and(|key| is_secret_environment_key(key) || key == "AFT_GIT_CO_AUTHOR")
        })
        .collect()
}

fn process_env_mutex() -> &'static Mutex<()> {
    static LOCK: OnceLock<Mutex<()>> = OnceLock::new();
    LOCK.get_or_init(|| Mutex::new(()))
}

/// Probe from a sibling test thread without waiting on the process-settings
/// guard. Used to verify that an environment fixture holds the shared mutex.
#[allow(dead_code)] // The integration helper copy uses this probe.
pub fn process_env_lock_is_available() -> bool {
    !matches!(
        process_env_mutex().try_lock(),
        Err(std::sync::TryLockError::WouldBlock)
    )
}

/// Acquire a test-only serialization mutex without cascading a prior test panic.
/// These locks serialize test setup rather than protect data invariants, so the
/// next test must proceed after a poisoned holder instead of manufacturing a
/// wall of unrelated failures.
pub fn lock_test_mutex<T>(mutex: &Mutex<T>) -> MutexGuard<'_, T> {
    mutex
        .lock()
        .unwrap_or_else(|poisoned| poisoned.into_inner())
}

thread_local! {
    static PROCESS_ENV_LOCK_DEPTH: Cell<usize> = const { Cell::new(0) };
    static PROCESS_ENV_LOCK_GUARD: RefCell<Option<MutexGuard<'static, ()>>> = const { RefCell::new(None) };
}

/// Reentrant guard for the process-wide env-mutation lock.
///
/// Some tests already hold the shared env lock for `HOME` / `XDG_*` isolation and
/// then need to install hermetic git-config vars inside the same thread. A plain
/// `MutexGuard` would deadlock on that nested acquisition, so this guard keeps the
/// underlying mutex in thread-local storage and only releases it when the outermost
/// acquisition drops.
pub struct ProcessEnvLockGuard;

impl Drop for ProcessEnvLockGuard {
    fn drop(&mut self) {
        PROCESS_ENV_LOCK_DEPTH.with(|depth| {
            let current = depth.get();
            debug_assert!(current > 0, "process env lock depth underflow");
            let next = current.saturating_sub(1);
            depth.set(next);
            if next == 0 {
                PROCESS_ENV_LOCK_GUARD.with(|slot| {
                    slot.borrow_mut().take();
                });
            }
        });
    }
}

/// Acquire the process-wide env-mutation lock. Poison is ignored: a panicking
/// test already restored (or failed to restore) the env; letting the next test
/// proceed keeps one failure from cascading into every env-dependent test.
pub fn process_env_lock() -> ProcessEnvLockGuard {
    PROCESS_ENV_LOCK_DEPTH.with(|depth| {
        if depth.get() == 0 {
            let guard = lock_test_mutex(process_env_mutex());
            PROCESS_ENV_LOCK_GUARD.with(|slot| {
                *slot.borrow_mut() = Some(guard);
            });
        }
        depth.set(depth.get() + 1);
    });
    ProcessEnvLockGuard
}

pub struct StorageOverrideGuard {
    previous: Option<OsString>,
    _lock: ProcessEnvLockGuard,
}
impl Drop for StorageOverrideGuard {
    fn drop(&mut self) {
        if let Some(value) = &self.previous {
            std::env::set_var("AFT_STORAGE_DIR", value);
        } else {
            std::env::remove_var("AFT_STORAGE_DIR");
        }
    }
}
/// Fixtures with explicit temporary namespaces must not inherit a worker's
/// process-wide override when testing their configured-path behavior.
pub fn without_storage_override() -> StorageOverrideGuard {
    let lock = process_env_lock();
    let previous = std::env::var_os("AFT_STORAGE_DIR");
    std::env::remove_var("AFT_STORAGE_DIR");
    StorageOverrideGuard {
        previous,
        _lock: lock,
    }
}

/// Keep transport fixtures from starting project watchers unrelated to their
/// protocol assertions. Restore the setting before releasing the shared env lock.
pub struct ProjectWatcherDisabledGuard {
    _setting: ScopedEnvVar,
    _lock: ProcessEnvLockGuard,
}

pub fn without_project_watcher() -> ProjectWatcherDisabledGuard {
    let lock = process_env_lock();
    ProjectWatcherDisabledGuard {
        _setting: ScopedEnvVar::set("AFT_TEST_DISABLE_FILE_WATCHER", "1"),
        _lock: lock,
    }
}

struct ScopedEnvVar {
    key: &'static str,
    previous: Option<OsString>,
}

impl ScopedEnvVar {
    fn set(key: &'static str, value: impl AsRef<OsStr>) -> Self {
        let previous = std::env::var_os(key);
        unsafe { std::env::set_var(key, value) };
        Self { key, previous }
    }
}

impl Drop for ScopedEnvVar {
    fn drop(&mut self) {
        if let Some(previous) = self.previous.take() {
            unsafe { std::env::set_var(self.key, previous) };
        } else {
            unsafe { std::env::remove_var(self.key) };
        }
    }
}

/// An empty git config file. Git for Windows refuses the `NUL` device as a
/// config path ("unable to access 'NUL': Invalid argument"), so Windows uses
/// a real empty file; elsewhere `/dev/null` reads as empty.
fn hermetic_git_config_path() -> &'static OsStr {
    #[cfg(windows)]
    {
        static PATH: OnceLock<std::path::PathBuf> = OnceLock::new();
        PATH.get_or_init(|| {
            let path = std::env::temp_dir()
                .join(format!("aft-test-empty-gitconfig-{}", std::process::id()));
            std::fs::write(&path, b"").expect("write empty hermetic git config");
            path
        })
        .as_os_str()
    }
    #[cfg(not(windows))]
    {
        OsStr::new("/dev/null")
    }
}

/// Test-only git env overrides that suppress user/system config reads.
#[allow(dead_code)]
pub fn hermetic_git_env() -> [(&'static str, &'static OsStr); 2] {
    [
        ("GIT_CONFIG_GLOBAL", hermetic_git_config_path()),
        ("GIT_CONFIG_SYSTEM", hermetic_git_config_path()),
    ]
}

/// Apply hermetic git-config env vars to one child process, including removal
/// of command-scope config inherited through `GIT_CONFIG_COUNT`.
#[allow(dead_code)]
pub fn apply_hermetic_git_env(command: &mut Command) -> &mut Command {
    command
        .envs(hermetic_git_env())
        .env("GIT_CONFIG_COUNT", "0")
}

/// Hold hermetic git-config env vars for the current test thread.
///
/// Fields drop in declaration order, so `_lock` is last: the env vars must be
/// restored before another test can take the lock and observe them.
#[allow(dead_code)]
pub struct HermeticGitEnvGuard {
    _global: ScopedEnvVar,
    _system: ScopedEnvVar,
    _config_count: ScopedEnvVar,
    _lock: ProcessEnvLockGuard,
}

/// Install hermetic git-config env vars for in-process git executions during a
/// test. This is for code-under-test paths that shell `git` internally and
/// therefore cannot receive per-command env injection from the caller.
#[allow(dead_code)]
pub fn hermetic_git_env_guard() -> HermeticGitEnvGuard {
    let lock = process_env_lock();
    let [(global_key, global_value), (system_key, system_value)] = hermetic_git_env();
    HermeticGitEnvGuard {
        _lock: lock,
        _global: ScopedEnvVar::set(global_key, global_value),
        _system: ScopedEnvVar::set(system_key, system_value),
        // Agent children on hosts with git.co_author enabled carry
        // GIT_CONFIG_COUNT/KEY_0/VALUE_0 (core.hooksPath injection), and git's
        // env scope outranks a test repo's local config - zeroing the count
        // neutralizes the whole injected block for in-process git spawns.
        _config_count: ScopedEnvVar::set("GIT_CONFIG_COUNT", OsStr::new("0")),
    }
}

/// Keep in-process gh-shim tests away from the operator's state directory.
/// The shared lock is held for the complete lifetime of the override because
/// libtest runs these tests concurrently with other env-sensitive modules.
/// As above, `_lock` is declared last so the override is gone before the lock
/// is released.
pub struct GhShimStateGuard {
    _state: ScopedEnvVar,
    _temp: tempfile::TempDir,
    _lock: ProcessEnvLockGuard,
}

pub fn gh_shim_state_guard() -> GhShimStateGuard {
    let lock = process_env_lock();
    let temp = tempfile::tempdir().expect("create gh-shim test state directory");
    let state = ScopedEnvVar::set("AFT_GH_SHIM_STATE_DIR", temp.path());
    GhShimStateGuard {
        _lock: lock,
        _state: state,
        _temp: temp,
    }
}

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

    #[test]
    fn test_mutex_lock_recovers_after_a_panicking_holder() {
        let mutex = Mutex::new(());
        let panic = std::panic::catch_unwind(|| {
            let _guard = lock_test_mutex(&mutex);
            panic!("deliberately poison the test serialization mutex");
        });
        assert!(panic.is_err());
        assert!(mutex.is_poisoned());

        drop(lock_test_mutex(&mutex));
    }

    #[test]
    fn per_command_git_env_discards_inherited_command_scope_config() {
        let mut command = Command::new("git");
        command
            .env("GIT_CONFIG_COUNT", "1")
            .env("GIT_CONFIG_KEY_0", "core.fsyncMethod")
            .env("GIT_CONFIG_VALUE_0", "batch");
        let output = apply_hermetic_git_env(&mut command)
            .args(["config", "--get", "core.fsyncMethod"])
            .output()
            .expect("query hermetic git config");

        assert_eq!(output.status.code(), Some(1));
        assert!(output.stdout.is_empty());
    }

    #[test]
    fn gh_shim_state_guard_scopes_a_temp_override() {
        let previous = std::env::var_os("AFT_GH_SHIM_STATE_DIR");
        {
            let _guard = gh_shim_state_guard();
            let selected = std::env::var_os("AFT_GH_SHIM_STATE_DIR")
                .expect("gh-shim guard installs a state override");
            assert!(std::path::Path::new(&selected).is_absolute());
        }
        assert_eq!(std::env::var_os("AFT_GH_SHIM_STATE_DIR"), previous);
    }
}