use std::ffi::{OsStr, OsString};
use std::path::{Path, PathBuf};
use std::sync::{Mutex, OnceLock};
use std::time::{SystemTime, UNIX_EPOCH};
mod test_env_lock;
pub use test_env_lock::{
EnvScopeMembership, EnvScopeTicket, TestEnvLock, current_env_scope_generation,
current_thread_holds_test_env_lock, env_scope_ticket, join_env_scope, lock_test_env,
with_test_env_lock, with_test_env_lock_if_uncontended,
};
pub fn isolated_test_state_root() -> &'static Path {
static ROOT: OnceLock<PathBuf> = OnceLock::new();
ROOT.get_or_init(|| {
let nonce = SystemTime::now()
.duration_since(UNIX_EPOCH)
.unwrap_or_default()
.as_nanos();
let root = std::env::temp_dir().join(format!(
"codewhale-tui-test-state-{}-{nonce}",
std::process::id()
));
std::fs::create_dir_all(&root).unwrap_or_else(|error| {
panic!(
"failed to create isolated unit-test state root {}: {error}",
root.display()
)
});
root.canonicalize().expect("canonical test state root")
})
}
pub fn unsealed_test_state_root() -> PathBuf {
let shared = isolated_test_state_root();
if !current_thread_holds_test_env_lock() {
return shared.to_path_buf();
}
HOLDER_ROOT.with(|cached| {
cached
.get_or_init(|| {
let root = shared.join(format!("env-holder-{:?}", std::thread::current().id()));
std::fs::create_dir_all(&root).unwrap_or_else(|error| {
panic!(
"failed to create per-holder test state root {}: {error}",
root.display()
)
});
root
})
.clone()
})
}
thread_local! {
static HOLDER_ROOT: OnceLock<PathBuf> = const { OnceLock::new() };
}
pub fn unsealed_state_dir(name: impl AsRef<Path>) -> Option<PathBuf> {
if home_is_sealed() {
return None;
}
let dir = isolated_test_state_root().join(name);
std::fs::create_dir_all(&dir).unwrap_or_else(|error| {
panic!(
"failed to create the unsealed test state dir {}: {error}",
dir.display()
)
});
Some(dir)
}
fn state_io_lock() -> &'static Mutex<()> {
static LOCK: OnceLock<Mutex<()>> = OnceLock::new();
LOCK.get_or_init(|| Mutex::new(()))
}
pub fn with_test_state_io_lock<T>(operation: impl FnOnce() -> T) -> T {
let _guard = match state_io_lock().lock() {
Ok(guard) => guard,
Err(poisoned) => poisoned.into_inner(),
};
operation()
}
pub fn boxed_phase<'a, T, M, F>(
make: M,
) -> std::pin::Pin<Box<dyn std::future::Future<Output = T> + 'a>>
where
M: FnOnce() -> F,
F: std::future::Future<Output = T> + 'a,
{
Box::pin(make())
}
pub fn block_on_default_test_stack<M, F, T>(make: M) -> T
where
M: FnOnce() -> F + Send + 'static,
F: std::future::Future<Output = T>,
T: Send + 'static,
{
const DEFAULT_TEST_THREAD_STACK: usize = 2 * 1024 * 1024;
std::thread::Builder::new()
.name("default-test-stack".into())
.stack_size(DEFAULT_TEST_THREAD_STACK)
.spawn(move || {
let runtime = tokio::runtime::Builder::new_current_thread()
.enable_all()
.build()
.expect("current-thread test runtime");
let future = make();
tokio::pin!(future);
runtime.block_on(future)
})
.expect("spawn the default-stack test thread")
.join()
.unwrap_or_else(|panic| std::panic::resume_unwind(panic))
}
pub struct EnvVarGuard {
key: &'static str,
previous: Option<OsString>,
}
fn guarded_env_keys() -> &'static Mutex<std::collections::HashMap<&'static str, usize>> {
static KEYS: OnceLock<Mutex<std::collections::HashMap<&'static str, usize>>> = OnceLock::new();
KEYS.get_or_init(|| Mutex::new(std::collections::HashMap::new()))
}
fn register_guarded_env_key(key: &'static str) {
let mut keys = match guarded_env_keys().lock() {
Ok(keys) => keys,
Err(poisoned) => poisoned.into_inner(),
};
*keys.entry(key).or_insert(0) += 1;
}
fn unregister_guarded_env_key(key: &'static str) {
let mut keys = match guarded_env_keys().lock() {
Ok(keys) => keys,
Err(poisoned) => poisoned.into_inner(),
};
if let Some(count) = keys.get_mut(key) {
*count -= 1;
if *count == 0 {
keys.remove(key);
}
}
}
pub fn env_var_currently_guarded(key: &str) -> bool {
match guarded_env_keys().lock() {
Ok(keys) => keys.contains_key(key),
Err(poisoned) => poisoned.into_inner().contains_key(key),
}
}
pub fn guarded_environment_provides_state_paths() -> bool {
if !current_thread_holds_test_env_lock() {
return false;
}
let guarded_path_is_present = |var: &str| {
env_var_currently_guarded(var)
&& std::env::var_os(var)
.is_some_and(|value| value.to_str().is_none_or(|text| !text.trim().is_empty()))
};
[
"CODEWHALE_HOME",
"CODEWHALE_CONFIG_PATH",
"DEEPSEEK_CONFIG_PATH",
"HOME",
"USERPROFILE",
]
.iter()
.any(|var| guarded_path_is_present(var))
}
pub fn home_is_sealed() -> bool {
if !current_thread_holds_test_env_lock() {
return false;
}
let present = |var: &str| {
std::env::var_os(var)
.is_some_and(|value| value.to_str().is_none_or(|text| !text.trim().is_empty()))
};
if present("CODEWHALE_HOME") {
return env_var_currently_guarded("CODEWHALE_HOME");
}
["HOME", "USERPROFILE"]
.iter()
.any(|var| env_var_currently_guarded(var) && present(var))
}
impl EnvVarGuard {
pub fn set(key: &'static str, value: impl AsRef<OsStr>) -> Self {
debug_assert!(
current_thread_holds_test_env_lock(),
"EnvVarGuard::set({key}) requires lock_test_env()"
);
let previous = std::env::var_os(key);
unsafe { std::env::set_var(key, value) };
register_guarded_env_key(key);
Self { key, previous }
}
pub fn remove(key: &'static str) -> Self {
debug_assert!(
current_thread_holds_test_env_lock(),
"EnvVarGuard::remove({key}) requires lock_test_env()"
);
let previous = std::env::var_os(key);
unsafe { std::env::remove_var(key) };
register_guarded_env_key(key);
Self { key, previous }
}
}
impl Drop for EnvVarGuard {
fn drop(&mut self) {
unregister_guarded_env_key(self.key);
unsafe {
if let Some(value) = self.previous.take() {
std::env::set_var(self.key, value);
} else {
std::env::remove_var(self.key);
}
}
}
}
pub struct SealedHome {
_vars: Vec<EnvVarGuard>,
_dir: Option<tempfile::TempDir>,
home: PathBuf,
codewhale_home: PathBuf,
_lock: TestEnvLock,
}
#[expect(clippy::new_without_default)]
impl SealedHome {
pub fn new() -> Self {
let lock = lock_test_env();
let dir = tempfile::TempDir::new().expect("sealed home tempdir");
let home = dir.path().join("home");
let codewhale_home = dir.path().join("codewhale-home");
std::fs::create_dir_all(&home).expect("sealed home dir");
std::fs::create_dir_all(&codewhale_home).expect("sealed codewhale home dir");
Self::pin(lock, Some(dir), home, codewhale_home)
}
pub fn at(home: &Path) -> Self {
let lock = lock_test_env();
let codewhale_home = home.join(".codewhale");
Self::pin(lock, None, home.to_path_buf(), codewhale_home)
}
fn pin(
lock: TestEnvLock,
dir: Option<tempfile::TempDir>,
home: PathBuf,
codewhale_home: PathBuf,
) -> Self {
let vars = vec![
EnvVarGuard::set("CODEWHALE_HOME", &codewhale_home),
EnvVarGuard::set("HOME", &home),
EnvVarGuard::set("USERPROFILE", &home),
EnvVarGuard::remove("HOMEDRIVE"),
EnvVarGuard::remove("HOMEPATH"),
EnvVarGuard::remove("CODEWHALE_CONFIG_PATH"),
EnvVarGuard::remove("DEEPSEEK_CONFIG_PATH"),
EnvVarGuard::remove("DEEPSEEK_HOME"),
];
Self {
_vars: vars,
_dir: dir,
home,
codewhale_home,
_lock: lock,
}
}
pub fn home(&self) -> &Path {
&self.home
}
pub fn codewhale_home(&self) -> &Path {
&self.codewhale_home
}
}
pub fn first_divergence(a: &str, b: &str) -> Option<(usize, String, String)> {
let a_bytes = a.as_bytes();
let b_bytes = b.as_bytes();
let max = a_bytes.len().min(b_bytes.len());
for i in 0..max {
if a_bytes[i] != b_bytes[i] {
let lo = i.saturating_sub(32);
let a_hi = (i + 32).min(a_bytes.len());
let b_hi = (i + 32).min(b_bytes.len());
let a_ctx = String::from_utf8_lossy(&a_bytes[lo..a_hi]).into_owned();
let b_ctx = String::from_utf8_lossy(&b_bytes[lo..b_hi]).into_owned();
return Some((i, a_ctx, b_ctx));
}
}
if a_bytes.len() != b_bytes.len() {
return Some((
max,
format!("(len={})", a_bytes.len()),
format!("(len={})", b_bytes.len()),
));
}
None
}
#[track_caller]
pub fn assert_byte_identical(label: &str, a: &str, b: &str) {
if let Some((pos, a_ctx, b_ctx)) = first_divergence(a, b) {
panic!(
"{label}: prompt construction is non-deterministic — first diff at byte {pos}\n\
── side A (±32B) ──\n{a_ctx:?}\n── side B (±32B) ──\n{b_ctx:?}",
);
}
}
pub fn read_shell_sentinel(path: &Path) -> String {
let bytes = std::fs::read(path).unwrap_or_default();
let text = if bytes.starts_with(&[0xFF, 0xFE]) {
let units: Vec<u16> = bytes[2..]
.as_chunks::<2>()
.0
.iter()
.map(|pair| u16::from_le_bytes(*pair))
.collect();
String::from_utf16_lossy(&units)
} else {
String::from_utf8_lossy(&bytes).into_owned()
};
text.trim_start_matches('\u{feff}')
.replace("\r\n", "\n")
.replace('"', "")
.trim()
.to_string()
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn ambient_codewhale_home_is_not_a_test_seal() {
let _lock = lock_test_env();
let _ambient = EnvVarGuard::set("CODEWHALE_HOME", "/tmp/ambient-codewhale-home");
unregister_guarded_env_key("CODEWHALE_HOME");
let sealed = guarded_environment_provides_state_paths();
register_guarded_env_key("CODEWHALE_HOME");
assert!(!sealed, "ambient developer state must remain confined");
}
#[test]
fn a_config_path_guard_or_a_home_shadowed_by_the_ambient_override_is_not_a_home_seal() {
let _lock = lock_test_env();
let dir = tempfile::tempdir().expect("tempdir");
{
let _config = EnvVarGuard::set("CODEWHALE_CONFIG_PATH", dir.path().join("config.toml"));
let _no_home_override = EnvVarGuard::remove("CODEWHALE_HOME");
assert!(guarded_environment_provides_state_paths());
assert!(!home_is_sealed());
}
{
let _ambient = EnvVarGuard::set("CODEWHALE_HOME", dir.path().join("ambient"));
unregister_guarded_env_key("CODEWHALE_HOME");
let _home = EnvVarGuard::set("HOME", dir.path());
let sealed = home_is_sealed();
register_guarded_env_key("CODEWHALE_HOME");
assert!(!sealed, "an ambient CODEWHALE_HOME shadows a guarded HOME");
}
{
let _no_home_override = EnvVarGuard::remove("CODEWHALE_HOME");
let _home = EnvVarGuard::set("HOME", dir.path());
assert!(home_is_sealed());
}
}
#[test]
fn removing_overrides_does_not_seal_the_ambient_home() {
let _lock = lock_test_env();
let _codewhale_home = EnvVarGuard::remove("CODEWHALE_HOME");
let _codewhale_config = EnvVarGuard::remove("CODEWHALE_CONFIG_PATH");
let _deepseek_config = EnvVarGuard::remove("DEEPSEEK_CONFIG_PATH");
assert!(
!guarded_environment_provides_state_paths(),
"removing an override must not expose the developer's HOME"
);
}
}