use oxdock_diagnostics::DiagnosticResult;
use oxdock_fs::env as oxdock_env;
use std::collections::HashMap;
use crate::diagnostics as proc_diag;
pub fn has_var(envs: &HashMap<String, String>, name: &str) -> bool {
#[allow(clippy::disallowed_macros)]
if cfg!(windows) {
envs.keys().any(|k| k.eq_ignore_ascii_case(name))
} else {
envs.contains_key(name)
}
}
pub fn is_sanctioned_seed(name: &str) -> bool {
name.starts_with("CARGO_FEATURE_") || name.starts_with("CARGO_CFG_")
}
pub fn needs_path_lookup(program: &str) -> bool {
!program.contains('/') && !program.contains('\\')
}
pub fn check_spawn_anchors(
program: &str,
envs: &HashMap<String, String>,
require_path: bool,
) -> DiagnosticResult<()> {
if (require_path || needs_path_lookup(program)) && !has_var(envs, oxdock_env::os::PATH) {
return Err(proc_diag::spawn_requires_path(program));
}
#[allow(clippy::disallowed_macros)]
if cfg!(windows) && !has_var(envs, oxdock_env::os::windows::SYSTEM_ROOT) {
return Err(proc_diag::spawn_requires_system_root());
}
Ok(())
}
pub fn names_eq(a: &str, b: &str) -> bool {
#[allow(clippy::disallowed_macros)]
if cfg!(windows) {
a.eq_ignore_ascii_case(b)
} else {
a == b
}
}
#[allow(clippy::disallowed_methods)]
fn host_var(name: &str) -> Option<String> {
#[allow(clippy::disallowed_macros)]
if cfg!(miri) {
None
} else {
std::env::var(name).ok()
}
}
pub const CONTRACT_INTRO_MD: &str = indoc::indoc! {"
## Seeded environment
Session start copies host values for the declared names directly
into the script environment map. A host lacking a name leaves it
absent: nothing is synthesized, nothing is immutable. Explicit
script `ENV`/`INHERIT_ENV` overwrite entries uniformly; `ISOLATED`
resets the map to the same seed. A missing value surfaces at spawn
time, with the exact `INHERIT_ENV` declaration to add.
"};
pub const BASELINE_INTRO_MD: &str = indoc::indoc! {"
### Host-mirrored defaults
Declared names mirrored from the host at session start and on every
`ISOLATED` entry, wherever the host defines them. Absent stays
absent; explicit script values win.
"};
pub const ROUTING_MD: &str = indoc::indoc! {"
### Explicit routing
The defaults in the table above mirror the host. Everything else
enters scripts only when listed in `INHERIT_ENV` (inside `ISOLATED`,
only when listed in the block allowlist, which copies from the
enclosing scope). Absent stays absent.
"};
pub const PRECEDENCE_MD: &str = indoc::indoc! {"
### Precedence and enforcement
Uniform script-wins: the seed populates mirrors, and explicit
script `ENV`/`INHERIT_ENV` overwrite them like any other variable.
No name is immutable. `ISOLATED` resets to the identical seed, so
inner and outer scopes start from the same defaults.
`check_spawn_anchors` validates the final staged map with no
caller-specific flags: present anchors pass, absent ones bail with
the exact `INHERIT_ENV` declaration to add.
Source of truth: the `define_env_contract!` invocation in
`crates/sys/oxdock-process/src/env_policy.rs` (names live in
`crates/sys/oxdock-fs/src/env.rs`). This file is generated; do not
edit by hand.
"};
pub const HOST_READS_INTRO_MD: &str = indoc::indoc! {"
### Host reads
Variables the engine process itself touches.
"};
pub struct BaselineDefaultEntry {
pub name: &'static str,
pub platforms: &'static str,
}
pub struct HostRead {
pub name: &'static str,
pub reader: &'static str,
}
macro_rules! define_env_contract {
(
seeds { $($name:expr, [$($platform:ident),*];)* }
reads { $($rname:expr, $rreader:expr;)* }
) => {
fn platform_seed_names() -> Vec<&'static str> {
vec![ $($name),* ]
}
pub fn describe_baseline_defaults() -> Vec<BaselineDefaultEntry> {
vec![ $( define_env_contract!(@entry $name, $($platform),*), )* ]
}
pub fn current_platform_seed() -> Vec<BaselineDefaultEntry> {
describe_baseline_defaults()
}
pub fn engine_host_reads() -> Vec<HostRead> {
vec![ $( HostRead { name: $rname, reader: $rreader } ),* ]
}
};
(@entry $name:expr, unix, windows) => {
BaselineDefaultEntry { name: $name, platforms: "unix, windows" }
};
(@entry $name:expr, unix) => {
BaselineDefaultEntry { name: $name, platforms: "unix" }
};
(@entry $name:expr, windows) => {
BaselineDefaultEntry { name: $name, platforms: "windows" }
};
}
define_env_contract! {
seeds {
oxdock_env::os::PATH, [unix, windows];
oxdock_env::os::unix::HOME, [unix];
oxdock_env::os::unix::TMPDIR, [unix];
oxdock_env::os::unix::TERM, [unix];
oxdock_env::os::unix::LANG, [unix];
oxdock_env::os::unix::LC_ALL, [unix];
oxdock_env::os::unix::LOGNAME, [unix];
oxdock_env::os::unix::USER, [unix];
oxdock_env::os::windows::TEMP, [windows];
oxdock_env::os::windows::TMP, [windows];
oxdock_env::os::windows::USERPROFILE, [windows];
oxdock_env::os::windows::LOCALAPPDATA, [windows];
oxdock_env::os::windows::APPDATA, [windows];
oxdock_env::os::windows::SYSTEM_ROOT, [windows];
oxdock_env::os::windows::WINDIR, [windows];
oxdock_env::os::windows::PATHEXT, [windows];
oxdock_env::os::windows::PROGRAM_FILES, [windows];
oxdock_env::os::windows::PROGRAM_FILES_X86, [windows];
oxdock_env::os::windows::PROGRAM_W6432, [windows];
oxdock_env::os::windows::COMSPEC, [windows];
oxdock_env::os::windows::SYSTEM_DRIVE, [windows];
oxdock_env::os::windows::PROCESSOR_ARCHITECTURE, [windows];
}
reads {
oxdock_env::os::unix::SHELL, "oxdock_process::shell::shell_program";
oxdock_env::os::windows::COMSPEC, "oxdock_process::shell::shell_program";
oxdock_env::os::unix::TMPDIR, "LazyGuardedTempDir::new (via std::env::temp_dir)";
"CARGO_FEATURE_*", "BuiltinEnv::collect";
"CARGO_CFG_*", "BuiltinEnv::collect";
}
}
pub fn seeded_env_names() -> Vec<&'static str> {
let mut names: Vec<&'static str> = describe_baseline_defaults()
.iter()
.map(|entry| entry.name)
.collect();
names.push(crate::builtin_env::BuiltinEnv::WORKSPACE_GIT_COMMIT);
names
}
pub fn seed_defaults() -> HashMap<String, String> {
interpret_seed_table(&platform_seed_names(), &host_var)
}
fn interpret_seed_table(
names: &[&str],
host: &dyn Fn(&str) -> Option<String>,
) -> HashMap<String, String> {
let mut seed = HashMap::with_capacity(names.len());
for name in names {
if let Some(mirrored) = host(name) {
seed.insert((*name).to_string(), mirrored);
}
}
seed
}
pub fn seed_transport() -> HashMap<String, String> {
transport_seed(&host_var)
}
fn transport_seed(host: &dyn Fn(&str) -> Option<String>) -> HashMap<String, String> {
let mut seed = HashMap::new();
for name in transport_names() {
if let Some(value) = host(name) {
seed.insert(name.to_string(), value);
}
}
seed
}
fn transport_names() -> Vec<&'static str> {
use oxdock_env::os::{unix, windows};
#[allow(clippy::disallowed_macros)]
if cfg!(windows) {
vec![
oxdock_env::os::PATH,
windows::SYSTEM_ROOT,
windows::WINDIR,
windows::PATHEXT,
unix::HOME,
windows::USERPROFILE,
windows::LOCALAPPDATA,
windows::APPDATA,
]
} else {
vec![oxdock_env::os::PATH, unix::TERM, unix::HOME]
}
}
pub fn seed_differs(seed: &HashMap<String, String>, key: &str, value: &str) -> bool {
match seed.iter().find(|(k, _)| names_eq(k, key)) {
Some((_, seeded)) => seeded != value,
None => true,
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn pathed_programs_skip_path_lookup() {
assert!(!needs_path_lookup("/bin/prog"));
assert!(!needs_path_lookup("sub/dir/prog"));
assert!(!needs_path_lookup("sub\\dir\\prog.exe"));
assert!(needs_path_lookup("prog"));
assert!(needs_path_lookup("prog.exe"));
}
#[test]
fn sanctioned_seeds_are_cargo_namespaced_only() {
assert!(is_sanctioned_seed("CARGO_FEATURE_FOO"));
assert!(is_sanctioned_seed("CARGO_CFG_FOO"));
assert!(!is_sanctioned_seed(oxdock_env::os::PATH));
assert!(!is_sanctioned_seed("GITHUB_TOKEN"));
assert!(!is_sanctioned_seed(oxdock_env::oxdock::WORKSPACE_ROOT));
}
#[test]
fn anchors_reject_bare_spawn_without_path() {
let envs = HashMap::new();
let err = check_spawn_anchors("prog", &envs, false).expect_err("must bail");
assert!(
err.to_string().contains("INHERIT_ENV [PATH]"),
"unexpected error: {err}"
);
}
#[test]
fn anchors_require_path_for_shell_form() {
let envs = HashMap::new();
let err = check_spawn_anchors("/bin/sh", &envs, true).expect_err("must bail");
assert!(
err.to_string().contains("INHERIT_ENV [PATH]"),
"unexpected error: {err}"
);
}
#[test]
fn anchors_accept_pathed_spawn_without_path() {
let envs = HashMap::new();
#[allow(clippy::disallowed_macros)]
if cfg!(windows) {
let err = check_spawn_anchors("/bin/prog", &envs, false).expect_err("must bail");
assert!(
err.to_string().contains("SystemRoot"),
"unexpected error: {err}"
);
} else {
check_spawn_anchors("/bin/prog", &envs, false).expect("pathed spawn needs no PATH");
}
}
fn stub_host(pairs: &[(&str, &str)]) -> HashMap<String, String> {
pairs
.iter()
.map(|(key, value)| (key.to_string(), value.to_string()))
.collect()
}
#[test]
fn seed_mirrors_host_essentials() {
let stub: HashMap<String, String> = current_platform_seed()
.iter()
.map(|entry| (entry.name.to_string(), format!("host-{}", entry.name)))
.collect();
let lookup = |name: &str| stub.get(name).cloned();
let seed = interpret_seed_table(&platform_seed_names(), &lookup);
for entry in current_platform_seed() {
assert_eq!(
seed.get(entry.name).map(String::as_str),
stub.get(entry.name).map(String::as_str),
"{} must mirror the host",
entry.name
);
}
}
#[test]
fn seed_omits_all_without_host() {
let seed = interpret_seed_table(&platform_seed_names(), &|_: &str| None::<String>);
assert!(seed.is_empty(), "empty host must seed nothing: {seed:?}");
}
#[test]
fn seed_admits_only_declared_names() {
let stub = stub_host(&[
(oxdock_env::os::PATH, "/host/bin"),
("HOST_HOME_PROBE", "/nowhere"),
]);
let lookup = |name: &str| stub.get(name).cloned();
let seed = interpret_seed_table(&platform_seed_names(), &lookup);
assert!(
!seed.contains_key("HOST_HOME_PROBE"),
"unlisted names never seed: {seed:?}"
);
assert_eq!(
seed.get(oxdock_env::os::PATH).map(String::as_str),
Some("/host/bin")
);
for entry in current_platform_seed() {
if entry.name == oxdock_env::os::PATH {
continue;
}
assert!(
!seed.contains_key(entry.name),
"{} must stay absent when the host lacks it: {seed:?}",
entry.name
);
}
}
#[test]
fn seed_differs_spots_seed_equality() {
let stub = stub_host(&[(oxdock_env::os::PATH, "/host/bin")]);
let lookup = |name: &str| stub.get(name).cloned();
let seed = interpret_seed_table(&platform_seed_names(), &lookup);
assert!(!seed_differs(&seed, oxdock_env::os::PATH, "/host/bin"));
assert!(seed_differs(&seed, oxdock_env::os::PATH, "/custom/bin"));
assert!(seed_differs(&seed, "OXDOCK_CUSTOM_UNSEEDED", "1"));
}
#[test]
fn transport_seed_mirrors_or_omits() {
let stub = stub_host(&[(oxdock_env::os::PATH, "/host/bin")]);
let staged = transport_seed(&|name: &str| stub.get(name).cloned());
assert_eq!(
staged.get(oxdock_env::os::PATH).map(String::as_str),
Some("/host/bin")
);
let bare = transport_seed(&|_: &str| None::<String>);
assert!(bare.is_empty(), "empty host must stage nothing: {bare:?}");
}
#[test]
fn transport_seed_holds_no_target_dir() {
let stub: HashMap<String, String> = transport_names()
.iter()
.map(|name| (name.to_string(), format!("host-{name}")))
.collect();
let lookup = |name: &str| stub.get(name).cloned();
let staged = transport_seed(&lookup);
assert!(
!staged.contains_key(oxdock_env::cargo::TARGET_DIR),
"transports must not carry a target dir: {staged:?}"
);
for name in transport_names() {
assert_eq!(
staged.get(name).map(String::as_str),
stub.get(name).map(String::as_str),
"{name} must mirror the host"
);
}
}
#[test]
fn engine_host_reads_names_are_consts_or_patterns() {
let reads = engine_host_reads();
assert!(!reads.is_empty());
for read in &reads {
let known = [
oxdock_env::os::unix::SHELL,
oxdock_env::os::windows::COMSPEC,
oxdock_env::os::unix::TMPDIR,
];
assert!(
known.contains(&read.name) || read.name.ends_with("_*"),
"host read {} is neither const nor pattern",
read.name
);
assert!(
!read.reader.is_empty(),
"host read {} names no reader",
read.name
);
}
}
#[test]
fn seed_tables_are_consistent() {
let described = describe_baseline_defaults();
let mut seen = std::collections::HashSet::new();
for entry in &described {
assert!(
seen.insert(entry.name),
"declaration duplicates {}",
entry.name
);
assert!(
["unix", "windows", "unix, windows"].contains(&entry.platforms),
"{} declares platforms outside the closed set: {}",
entry.name,
entry.platforms
);
}
let defined: std::collections::HashSet<&str> = oxdock_env::os::unix::ALL
.iter()
.chain(oxdock_env::os::windows::ALL.iter())
.chain(oxdock_env::cargo::ALL.iter())
.copied()
.chain([oxdock_env::os::PATH])
.collect();
for entry in &described {
assert!(
defined.contains(entry.name),
"declared {} is not a defined env constant",
entry.name
);
}
let stub: HashMap<String, String> = described
.iter()
.map(|entry| (entry.name.to_string(), format!("host-{}", entry.name)))
.collect();
let lookup = |name: &str| stub.get(name).cloned();
let seed = interpret_seed_table(&platform_seed_names(), &lookup);
for name in platform_seed_names() {
assert!(seed.contains_key(name), "declared {name} never seeds");
}
let mut current: Vec<&str> = current_platform_seed()
.iter()
.map(|entry| entry.name)
.collect();
let mut names = platform_seed_names();
current.sort_unstable();
names.sort_unstable();
assert_eq!(
current, names,
"current-platform entries disagree with seed names"
);
for name in platform_seed_names() {
assert!(
described.iter().any(|entry| entry.name == name),
"platform name {name} missing from the contract table"
);
}
}
}