ctb_io_environment/
environment.rs

1// SPDX-License-Identifier: AGPL-3.0-or-later
2/*
3This file is part of Collective Toolbox, a database and document workspace and utilities.
4Copyright (C) 2026 Collective Toolbox Developers
5Contact: info@collectivetoolbox.com
6
7This program is free software: you can redistribute it and/or modify it under
8the terms of the GNU Affero General Public License as published by the Free
9Software Foundation, either version 3 of the License, or (at your option) any
10later version.
11
12This program is distributed in the hope that it will be useful, but WITHOUT ANY
13WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
14A PARTICULAR PURPOSE.  See the GNU Affero General Public License for more details.
15
16You should have received a copy of the GNU Affero General Public License along
17with this program.  If not, see <https://www.gnu.org/licenses/>.
18*/
19
20//! Functions for detecting the environment the application is currently
21//! running in.
22//!
23//! TODO: A number of these are unimplemented.
24//! TODO: How will this interact with subprocesses? If things are checking the CLI directly, it won't work (a subprocess should still be considered to be running as GUI or CLI for instance even if it's not actually running those itself).
25
26#[allow(
27    unused_imports,
28    clippy::wildcard_imports,
29    reason = "Standard workspace crate prelude"
30)]
31pub(crate) use ctb_utilities::*;
32
33use std::cell::RefCell;
34use std::env;
35use std::net::{IpAddr, Ipv4Addr, Ipv6Addr, UdpSocket};
36use std::path::PathBuf;
37use std::sync::atomic::{AtomicU64, Ordering};
38use std::sync::{Arc, OnceLock, RwLock};
39use std::time::{Duration, SystemTime, UNIX_EPOCH};
40
41use ctb_utilities::pc_settings::{PcSettingU16Key, get_u16_setting};
42use serde::{Deserialize, Serialize};
43
44pub mod detection;
45pub use ctb_formats_utilities::format_id::FormatId;
46pub use detection::{
47    EnvironmentCapabilities, EnvironmentIdentity, detect_architecture,
48    detect_capabilities, detect_display_server, detect_identity,
49};
50
51pub use ctb_utilities::environment::{
52    ProcessRole, ctb_version, ctb_version_semver, get_process_role,
53    is_cargo_target_binary, is_debug_build, is_official_public_website,
54    is_official_signed_build, is_public_website,
55    reset_process_role_for_testing, set_process_role,
56    verify_official_signed_build,
57};
58
59/// Is a lightweight CLI command running (without workspace boot)?
60pub fn is_cli_lightweight() -> bool {
61    get_process_role() == ProcessRole::LightweightCli
62}
63
64/// Is the workspace running? True even if this is a subprocess, not the main
65/// workspace process.
66pub fn is_workspace() -> bool {
67    is_workspace_main_process() || is_service_subprocess()
68}
69
70/// Is this the main workspace process?
71pub fn is_workspace_main_process() -> bool {
72    get_process_role() == ProcessRole::WorkspaceMain
73}
74
75/// Is this a service subprocess?
76pub fn is_service_subprocess() -> bool {
77    get_process_role() == ProcessRole::ServiceSubprocess
78}
79
80/// Is this a workspace UI running in any VM instance in a browser? (v86, or
81/// potentially later other VMs.) Don't rely on these VM-related methods to
82/// check the bit width, the OS, or the display server. It is useful for telling
83/// what UI constraints (e.g. available keys - browsers capture some keys) we're
84/// working with. TODO STUB
85pub fn is_browser_vm() -> bool {
86    false
87}
88
89/// Is the workspace UI running in a VM in a browser in fullscreen mode? TODO STUB
90pub fn is_browser_vm_fullscreen() -> bool {
91    false
92}
93
94/// Is the workspace UI running in a VM in a mobile browser? TODO STUB
95pub fn is_browser_vm_mobile() -> bool {
96    false
97}
98
99/// Is the workspace UI running in v86 in the browser? TODO STUB
100pub fn is_v86() -> bool {
101    false
102}
103
104/// Is the workspace UI running as a PWA?
105pub fn is_pwa() -> bool {
106    // window.matchMedia('(display-mode: standalone)').matches
107    // TODO
108    #[expect(
109        clippy::overly_complex_bool_expr,
110        reason = "intentional stub logic"
111    )]
112    {
113        false && is_browser_vm()
114    }
115}
116
117/// Is the workspace UI running as a PWA on mobile?
118pub fn is_pwa_mobile() -> bool {
119    is_pwa() && is_browser_vm_mobile()
120}
121
122/// Return the width of usize
123pub fn usize() -> u8 {
124    // Intentionally not using anyhow here
125    #[expect(
126        clippy::expect_used,
127        reason = "size_of is constant so it cannot panic"
128    )]
129    u8::try_from(std::mem::size_of::<usize>().saturating_mul(8))
130        .expect("usize width exceeds u8")
131}
132
133/// Return the OS family
134pub fn os() -> String {
135    env::consts::OS.to_string()
136}
137static CACHED_TIME_RESOLUTION: OnceLock<u128> = OnceLock::new();
138static CACHED_LOCAL_IPV4: RwLock<Option<Ipv4Addr>> = RwLock::new(None);
139static CACHED_LOCAL_IPV6: RwLock<Option<Ipv6Addr>> = RwLock::new(None);
140static CACHED_PUBLIC_IPV4: RwLock<Option<Ipv4Addr>> = RwLock::new(None);
141static CACHED_PUBLIC_IPV6: RwLock<Option<Ipv6Addr>> = RwLock::new(None);
142static CACHED_SERVER_TIME_OFFSET_NANOS: RwLock<Option<i128>> =
143    RwLock::new(None);
144
145#[derive(Deserialize)]
146struct ServerIpResponse {
147    ip: String,
148    server_time_nanos: u128,
149}
150
151/// Return the current system time in nanoseconds since the Unix epoch.
152pub fn unix_system_time_now() -> u128 {
153    SystemTime::now()
154        .duration_since(UNIX_EPOCH)
155        // Reason for fallback: system clocks set before the Unix epoch clamp to zero elapsed duration
156        .unwrap_or(Duration::ZERO)
157        .as_nanos()
158}
159
160/// Detect the resolution of the system clock in nanoseconds.
161///
162/// On POSIX systems, this queries `clock_getres(CLOCK_REALTIME)`. On Windows,
163/// it assumes high-precision timer increments (100 ns). In fallback or
164/// virtualized environments, it computes the minimum non-zero delta across
165/// multiple bounded samples to avoid pegging the CPU.
166pub fn unix_system_time_resolution() -> Result<u128> {
167    if let Some(&res) = CACHED_TIME_RESOLUTION.get() {
168        return Ok(res);
169    }
170
171    let detected = detect_system_time_resolution()?;
172    let _ = CACHED_TIME_RESOLUTION.set(detected);
173    Ok(detected)
174}
175
176fn detect_system_time_resolution() -> Result<u128> {
177    #[cfg(unix)]
178    {
179        if let Ok(ts) =
180            nix::time::clock_getres(nix::time::ClockId::CLOCK_REALTIME)
181        {
182            let nanos = Duration::from(ts).as_nanos();
183            if nanos > 0 {
184                return Ok(nanos);
185            }
186        }
187    }
188
189    #[cfg(target_os = "windows")]
190    {
191        return Ok(100);
192    }
193
194    #[cfg(not(target_os = "windows"))]
195    sample_system_time_resolution()
196}
197
198fn sample_system_time_resolution() -> Result<u128> {
199    let mut min_delta = u128::MAX;
200    let mut samples = 0_usize;
201    let mut last = unix_system_time_now();
202    let mut iterations = 0_usize;
203
204    while samples < 10 && iterations < 1_000 {
205        iterations = iterations.saturating_add(1);
206        let now = unix_system_time_now();
207        if now > last {
208            let delta = now.saturating_sub(last);
209            if delta < min_delta {
210                min_delta = delta;
211            }
212            samples = samples.saturating_add(1);
213            last = now;
214        } else if now < last {
215            // Protect against NTP / backward clock steps
216            last = now;
217        }
218        std::hint::spin_loop();
219    }
220
221    if min_delta < u128::MAX && min_delta > 0 {
222        Ok(min_delta)
223    } else {
224        Ok(1_000)
225    }
226}
227
228/// Discover the local outbound IPv4 address by querying the routing table.
229pub fn local_ipv4() -> Result<Ipv4Addr> {
230    if is_in_test() {
231        return Ok(Ipv4Addr::LOCALHOST);
232    }
233    let socket = UdpSocket::bind((Ipv4Addr::UNSPECIFIED, 0))
234        .context("Failed to bind UDP socket for local IPv4 discovery")?;
235    socket
236        .connect(("8.8.8.8", 80))
237        .context("Failed to route to target for local IPv4 discovery")?;
238    match socket.local_addr()?.ip() {
239        IpAddr::V4(ip) => Ok(ip),
240        IpAddr::V6(_) => bail!("Expected IPv4 address, got IPv6"),
241    }
242}
243
244/// Discover the local outbound IPv6 address by querying the routing table.
245pub fn local_ipv6() -> Result<Ipv6Addr> {
246    if is_in_test() {
247        return Ok(Ipv6Addr::LOCALHOST);
248    }
249    let socket = UdpSocket::bind((Ipv6Addr::UNSPECIFIED, 0))
250        .context("Failed to bind UDP socket for local IPv6 discovery")?;
251    let target = "2001:4860:4860::8888"
252        .parse::<Ipv6Addr>()
253        .context("Invalid IPv6 target address")?;
254    socket
255        .connect((target, 80))
256        .context("Failed to route to target for local IPv6 discovery")?;
257    match socket.local_addr()?.ip() {
258        IpAddr::V6(ip) => Ok(ip),
259        IpAddr::V4(_) => bail!("Expected IPv6 address, got IPv4"),
260    }
261}
262
263/// Return cached local outbound IPv4 address, discovering if not cached.
264pub fn cached_local_ipv4() -> Result<Ipv4Addr> {
265    if let Ok(lock) = CACHED_LOCAL_IPV4.read() {
266        if let Some(ip) = *lock {
267            return Ok(ip);
268        }
269    }
270    let ip = local_ipv4()?;
271    if let Ok(mut lock) = CACHED_LOCAL_IPV4.write() {
272        *lock = Some(ip);
273    }
274    Ok(ip)
275}
276
277/// Return cached local outbound IPv6 address, discovering if not cached.
278pub fn cached_local_ipv6() -> Result<Ipv6Addr> {
279    if let Ok(lock) = CACHED_LOCAL_IPV6.read() {
280        if let Some(ip) = *lock {
281            return Ok(ip);
282        }
283    }
284    let ip = local_ipv6()?;
285    if let Ok(mut lock) = CACHED_LOCAL_IPV6.write() {
286        *lock = Some(ip);
287    }
288    Ok(ip)
289}
290
291/// Return cached local outbound IPv4 address as u32, or 0 if discovery fails.
292pub fn cached_local_ipv4_u32() -> u32 {
293    // Reason for fallback: numeric representation defaults to 0 (0.0.0.0) on network failure or offline
294    cached_local_ipv4().map(u32::from).unwrap_or(0)
295}
296
297/// Return cached local outbound IPv6 address as u128, or 0 if discovery fails.
298pub fn cached_local_ipv6_u128() -> u128 {
299    // Reason for fallback: numeric representation defaults to 0 (::) on network failure or offline
300    cached_local_ipv6().map(u128::from).unwrap_or(0)
301}
302
303fn compute_clock_offset_nanos(
304    server_nanos: u128,
305    t0: u128,
306    t1: u128,
307) -> Result<i128> {
308    let rtt = t1.saturating_sub(t0);
309    // Reason for fallback: dividing by non-zero constant 2 cannot fail, default to zero on overflow
310    let half_rtt = rtt.checked_div(2).unwrap_or(0);
311    let client_est = t0.saturating_add(half_rtt);
312
313    let client_i128 = i128::try_from(client_est)
314        .context("Client timestamp exceeds i128 range")?;
315    let server_i128 = i128::try_from(server_nanos)
316        .context("Server timestamp exceeds i128 range")?;
317
318    let diff = client_i128
319        .checked_sub(server_i128)
320        .context("Clock difference arithmetic overflow")?;
321
322    Ok(diff)
323}
324
325fn maybe_cache_clock_offset(server_nanos: u128, t0: u128, t1: u128) {
326    if let Ok(lock) = CACHED_SERVER_TIME_OFFSET_NANOS.read() {
327        if lock.is_some() {
328            return;
329        }
330    }
331    if let Ok(offset) = compute_clock_offset_nanos(server_nanos, t0, t1) {
332        if let Ok(mut lock) = CACHED_SERVER_TIME_OFFSET_NANOS.write() {
333            if lock.is_none() {
334                *lock = Some(offset);
335            }
336        }
337    }
338}
339
340fn query_ip_endpoint(url: &str) -> Result<(IpAddr, u128, u128, u128)> {
341    query_ip_endpoint_with_timeout(url, crate::https::STARTUP_REQUEST_TIMEOUT)
342}
343
344fn query_ip_endpoint_with_timeout(
345    url: &str,
346    timeout: Duration,
347) -> Result<(IpAddr, u128, u128, u128)> {
348    if !url.starts_with("http://") && !url.starts_with("https://") {
349        bail!("Invalid endpoint URL scheme: {url}");
350    }
351    let rest = if let Some(stripped) = url.strip_prefix("https://") {
352        stripped
353    } else if let Some(stripped) = url.strip_prefix("http://") {
354        stripped
355    } else {
356        bail!("Invalid endpoint URL scheme: {url}");
357    };
358    // Reason for fallback: absent host component defaults to empty string and is rejected immediately by the host validation check below
359    let host = rest.split(['/', ':', '?', '#']).next().unwrap_or("");
360    if host.is_empty() {
361        bail!("Invalid endpoint URL host: {url}");
362    }
363
364    if is_in_test()
365        && !ctb_utilities::https::crlite::has_test_download_override()
366    {
367        bail!("Remote IP discovery requires a download override in tests");
368    }
369
370    if timeout.is_zero() {
371        bail!(
372            "GET {url}: Request timed out after {:?}",
373            crate::https::STARTUP_REQUEST_TIMEOUT
374        );
375    }
376
377    let url_string = url.to_string();
378    let test_name = crate::testing::try_get_current_test_name();
379    let test_storage_dir = crate::testing::try_get_test_storage_dir();
380    let handle =
381        std::thread::spawn(move || -> Result<(IpAddr, u128, u128, u128)> {
382            let _test_scope = crate::testing::push_current_test_name(test_name);
383            crate::testing::TEST_STORAGE_DIR_SYNC.with(|storage| {
384                *storage.borrow_mut() = test_storage_dir;
385            });
386            let options = crate::https::ClientOptions {
387                connect_timeout: Some(timeout.min(Duration::from_secs(3))),
388                read_timeout: None,
389                timeout: Some(timeout),
390                user_agent: None,
391            };
392            let client = crate::https::blocking_client(options)?;
393            let t0 = unix_system_time_now();
394            let resp = client.get(&url_string)?;
395            let t1 = unix_system_time_now();
396            let body = resp.text()?;
397            let parsed: ServerIpResponse = serde_json::from_str(&body)
398                .context("Failed to parse server IP response")?;
399            let ip: IpAddr = parsed
400                .ip
401                .parse()
402                .context("Failed to parse IP address in server response")?;
403            Ok((ip, parsed.server_time_nanos, t0, t1))
404        });
405
406    handle
407        .join()
408        .map_err(|_| anyhow::anyhow!("IP query worker thread panicked"))?
409}
410
411/// Discover public IPv4 address by querying the default server IPv4 endpoint.
412pub fn public_ipv4() -> Result<Ipv4Addr> {
413    public_ipv4_with_timeout(crate::https::STARTUP_REQUEST_TIMEOUT)
414}
415
416fn public_ipv4_with_timeout(timeout: Duration) -> Result<Ipv4Addr> {
417    let domain = crate::branding::default_domain();
418    let url = format!("https://ipv4.{domain}/api/ip");
419    let (ip, server_nanos, t0, t1) =
420        query_ip_endpoint_with_timeout(&url, timeout)?;
421    maybe_cache_clock_offset(server_nanos, t0, t1);
422    match ip {
423        IpAddr::V4(ipv4) => Ok(ipv4),
424        IpAddr::V6(_) => bail!("Expected IPv4 address from server, got IPv6"),
425    }
426}
427
428/// Discover public IPv6 address by querying the default server IPv6 endpoint.
429pub fn public_ipv6() -> Result<Ipv6Addr> {
430    public_ipv6_with_timeout(crate::https::STARTUP_REQUEST_TIMEOUT)
431}
432
433fn public_ipv6_with_timeout(timeout: Duration) -> Result<Ipv6Addr> {
434    let domain = crate::branding::default_domain();
435    let url = format!("https://ipv6.{domain}/api/ip");
436    let (ip, server_nanos, t0, t1) =
437        query_ip_endpoint_with_timeout(&url, timeout)?;
438    maybe_cache_clock_offset(server_nanos, t0, t1);
439    match ip {
440        IpAddr::V6(ipv6) => Ok(ipv6),
441        IpAddr::V4(_) => bail!("Expected IPv6 address from server, got IPv4"),
442    }
443}
444
445/// Return cached public IPv4 address, discovering if not cached.
446pub fn cached_public_ipv4() -> Result<Ipv4Addr> {
447    cached_public_ipv4_with_timeout(crate::https::STARTUP_REQUEST_TIMEOUT)
448}
449
450fn cached_public_ipv4_with_timeout(timeout: Duration) -> Result<Ipv4Addr> {
451    if let Ok(lock) = CACHED_PUBLIC_IPV4.read() {
452        if let Some(ip) = *lock {
453            return Ok(ip);
454        }
455    }
456    let ip = public_ipv4_with_timeout(timeout)?;
457    if let Ok(mut lock) = CACHED_PUBLIC_IPV4.write() {
458        *lock = Some(ip);
459    }
460    Ok(ip)
461}
462
463/// Return cached public IPv6 address, discovering if not cached.
464pub fn cached_public_ipv6() -> Result<Ipv6Addr> {
465    cached_public_ipv6_with_timeout(crate::https::STARTUP_REQUEST_TIMEOUT)
466}
467
468fn cached_public_ipv6_with_timeout(timeout: Duration) -> Result<Ipv6Addr> {
469    if let Ok(lock) = CACHED_PUBLIC_IPV6.read() {
470        if let Some(ip) = *lock {
471            return Ok(ip);
472        }
473    }
474    let ip = public_ipv6_with_timeout(timeout)?;
475    if let Ok(mut lock) = CACHED_PUBLIC_IPV6.write() {
476        *lock = Some(ip);
477    }
478    Ok(ip)
479}
480
481/// Return cached public IPv4 address as u32, or 0 if discovery fails.
482pub fn cached_public_ipv4_u32() -> u32 {
483    // Reason for fallback: numeric representation defaults to 0 (0.0.0.0) on network failure or offline
484    cached_public_ipv4().map(u32::from).unwrap_or(0)
485}
486
487/// Return cached public IPv6 address as u128, or 0 if discovery fails.
488pub fn cached_public_ipv6_u128() -> u128 {
489    // Reason for fallback: numeric representation defaults to 0 (::) on network failure or offline
490    cached_public_ipv6().map(u128::from).unwrap_or(0)
491}
492
493/// Query the official server and return the estimated difference between
494/// the client's clock and the server's clock in nanoseconds.
495///
496/// Positive value indicates client's clock is ahead of server's clock;
497/// negative value indicates client's clock is behind server's clock.
498pub fn server_system_time_offset_nanos() -> Result<i128> {
499    server_system_time_offset_nanos_with_timeout(
500        crate::https::STARTUP_REQUEST_TIMEOUT,
501    )
502}
503
504fn server_system_time_offset_nanos_with_timeout(
505    timeout: Duration,
506) -> Result<i128> {
507    let domain = crate::branding::default_domain();
508    let url = format!("https://{domain}/api/ip");
509    let (_, server_nanos, t0, t1) =
510        query_ip_endpoint_with_timeout(&url, timeout)?;
511    compute_clock_offset_nanos(server_nanos, t0, t1)
512}
513
514/// Return cached server system time offset in nanoseconds, discovering if not
515/// already cached.
516pub fn cached_server_system_time_offset_nanos() -> Result<i128> {
517    cached_server_system_time_offset_nanos_with_timeout(
518        crate::https::STARTUP_REQUEST_TIMEOUT,
519    )
520}
521
522fn cached_server_system_time_offset_nanos_with_timeout(
523    timeout: Duration,
524) -> Result<i128> {
525    if let Ok(lock) = CACHED_SERVER_TIME_OFFSET_NANOS.read() {
526        if let Some(offset) = *lock {
527            return Ok(offset);
528        }
529    }
530    let offset = server_system_time_offset_nanos_with_timeout(timeout)?;
531    if let Ok(mut lock) = CACHED_SERVER_TIME_OFFSET_NANOS.write() {
532        *lock = Some(offset);
533    }
534    Ok(offset)
535}
536
537/// Clear cached IP addresses and server timestamp offset, and immediately
538/// refill them.
539pub fn env_cache_reset() {
540    if let Ok(mut lock) = CACHED_LOCAL_IPV4.write() {
541        *lock = None;
542    }
543    if let Ok(mut lock) = CACHED_LOCAL_IPV6.write() {
544        *lock = None;
545    }
546    if let Ok(mut lock) = CACHED_PUBLIC_IPV4.write() {
547        *lock = None;
548    }
549    if let Ok(mut lock) = CACHED_PUBLIC_IPV6.write() {
550        *lock = None;
551    }
552    if let Ok(mut lock) = CACHED_SERVER_TIME_OFFSET_NANOS.write() {
553        *lock = None;
554    }
555    reset_boot_cached_env();
556
557    init_boot_env();
558}
559
560/// Is running on Unix-ish OS?
561pub fn is_unix() -> bool {
562    capture_quick_arc().is_unix()
563}
564
565/// Is running on Linux?
566pub fn is_linux() -> bool {
567    capture_quick_arc().is_linux()
568}
569
570/// Is running on Windows?
571pub fn is_windows() -> bool {
572    capture_quick_arc().is_windows()
573}
574
575/// Is running under the Wine compatibility layer on Windows?
576///
577/// Honors active [`EnvironmentScope`] and [`GlobalEnvironmentScope`].
578pub fn is_wine() -> bool {
579    capture_quick_arc().is_wine()
580}
581
582/// Is running on macOS (not classic)?
583pub fn is_mac_os_10_or_newer() -> bool {
584    capture_quick_arc().is_mac_os_10_or_newer()
585}
586/// There does not seem to be a separate iPadOS value for `env::consts::OS`.
587pub fn is_apple_ios() -> bool {
588    capture_quick_arc().is_apple_ios()
589}
590pub fn is_watchos() -> bool {
591    capture_quick_arc().is_watchos()
592}
593pub fn is_tvos() -> bool {
594    capture_quick_arc().is_tvos()
595}
596pub fn is_visionos() -> bool {
597    capture_quick_arc().is_visionos()
598}
599
600/// Is running on Darwin family OS?
601pub fn is_darwin() -> bool {
602    capture_quick_arc().is_darwin()
603}
604
605/// Does it look like it's running in a GNUstep environment? A guess, not
606/// confirmed.
607pub fn looks_like_gnustep() -> bool {
608    // Using GNUstep Terminal -> probably GNUstep environment
609    if let Ok(term) = env::var("TERM_PROGRAM") {
610        if term == "GNUstep_Terminal" {
611            return true;
612        }
613    }
614    if let Ok(wmaker) = env::var("WMAKER_USER_ROOT") {
615        if !wmaker.is_empty() {
616            return true;
617        }
618    }
619    // Multiple LLMs suggest you can use these, but I couldn't confirm it and it
620    // doesn't appear to be the case on my system (though I haven't tried a
621    // dedicated WindowMaker session) - I suspect they may be present when
622    // compiling GNUstep, not when running it:
623    // env::var_os("GNUSTEP_SYSTEM_ROOT").is_some()
624    //     || env::var_os("GNUSTEP_USER_ROOT").is_some()
625    false
626}
627
628/// Does it look like it's running in a NeXTSTEP or OPENSTEP environment? A
629/// guess, not confirmed.
630pub fn looks_like_nextstep_or_openstep() -> bool {
631    if let Ok(path) = env::var("PATH") {
632        if path
633            .split(':')
634            .any(|entry| entry.trim_end_matches('/') == "/NextApps")
635        {
636            return true;
637        }
638    }
639    if env::var_os("NEXT_ROOT").is_some() || env::var_os("NEXTSTEP").is_some() {
640        return true;
641    }
642    std::path::Path::new("/NextApps").is_dir()
643}
644
645/// Is this a BSD of some sort, not including Darwin?
646pub fn is_bsd() -> bool {
647    capture_quick_arc().is_bsd()
648}
649
650/// Is running on OpenBSD?
651pub fn is_openbsd() -> bool {
652    capture_quick_arc().is_openbsd()
653}
654
655/// Is running on `DragonFly` BSD?
656pub fn is_dragonfly() -> bool {
657    capture_quick_arc().is_dragonfly()
658}
659
660/// Is running on FreeBSD?
661pub fn is_freebsd() -> bool {
662    capture_quick_arc().is_freebsd()
663}
664
665/// Is running on NetBSD?
666pub fn is_netbsd() -> bool {
667    capture_quick_arc().is_netbsd()
668}
669
670/// Is this a local client instance, as opposed to the public website server?
671pub fn is_local() -> bool {
672    !is_public_website()
673}
674
675/// Is the workspace running with the prototype web UI? (Page-oriented, not
676/// frame-oriented).
677pub fn is_webui() -> bool {
678    get_u16_setting(PcSettingU16Key::FixedHttpPort).is_some()
679        || get_u16_setting(PcSettingU16Key::FixedHttpsPort).is_some()
680}
681
682/// Is this a prototype web UI running in the system browser?
683pub fn is_webui_in_system_browser() -> bool {
684    false
685}
686
687/// Is this a prototype web UI running in the bundled browser (Linux) or a
688/// webview (Mac/Windows)?
689pub fn is_webui_in_webview() -> bool {
690    false
691}
692
693/// Is the workspace running with its main GUI, regardless of the output mode?
694/// Output mode may be browser VM, native window, HTML frames to a browser,
695/// headless, etc.
696pub fn is_gui() -> bool {
697    capture_quick_arc().is_gui()
698}
699
700/// Is the workspace running with its CLI interface (TTY or videoterminal)?
701pub fn is_cli() -> bool {
702    capture_quick_arc().is_cli()
703}
704
705/// Is the workspace running in a TTY (text-mode, but can't backspace or
706/// edit/clear previous lines)?
707pub fn is_cli_tty() -> bool {
708    capture_quick_arc().is_cli_tty()
709}
710
711/// Is the workspace running as a videoterminal/videoterminal emulator
712/// (text-mode, but able to edit past lines)?
713pub fn is_cli_videoterminal() -> bool {
714    capture_quick_arc().is_cli_videoterminal()
715}
716
717/// Check if the active execution environment has a specific [`FormatId`].
718pub fn has_format(format: FormatId) -> bool {
719    capture_quick_arc().has_format(format)
720}
721
722/// Return all [`FormatId`] elements representing the active environment.
723pub fn all_format_ids() -> Vec<FormatId> {
724    capture_quick_arc().all_format_ids()
725}
726
727/// Return the structured OS and platform identity for the active environment.
728pub fn identity() -> EnvironmentIdentity {
729    capture_quick_arc().identity().clone()
730}
731
732/// Return the display, terminal, and renderer capabilities for the active environment.
733pub fn capabilities() -> EnvironmentCapabilities {
734    capture_quick_arc().capabilities().clone()
735}
736
737/// Return a human-readable summary of the active environment.
738pub fn summary() -> String {
739    capture_quick_arc().summary()
740}
741
742pub fn is_release_build() -> bool {
743    cfg!(not(debug_assertions))
744}
745
746pub fn cwd() -> Result<String> {
747    Ok(std::env::current_dir()?.to_string_lossy().into_owned())
748}
749
750pub fn is_in_test() -> bool {
751    testing::is_in_test()
752}
753
754pub fn is_branded_build() -> bool {
755    branding::is_branded_build()
756}
757
758/// Detailed snapshot of the current application and platform environment.
759/// Operating system family for platform-specific file attributes, flags, and APIs.
760#[ipc_dto]
761#[derive(
762    Debug,
763    Clone,
764    Copy,
765    PartialEq,
766    Eq,
767    Hash,
768    Serialize,
769    Deserialize,
770    ctb_formats_dcstring::DcMixed,
771)]
772#[dc(names)]
773pub enum OsFamily {
774    /// Apple macOS / Darwin.
775    #[dc(name = "Darwin")]
776    Darwin,
777    /// FreeBSD.
778    #[dc(name = "FreeBSD")]
779    FreeBSD,
780    /// OpenBSD.
781    #[dc(name = "OpenBSD")]
782    OpenBSD,
783    /// NetBSD.
784    #[dc(name = "NetBSD")]
785    NetBSD,
786    /// `DragonFly` BSD.
787    #[dc(name = "DragonFly")]
788    DragonFly,
789    /// Linux kernel.
790    #[dc(name = "Linux")]
791    Linux,
792    /// Microsoft Windows.
793    #[dc(name = "Windows")]
794    Windows,
795    /// Unknown or other operating system.
796    #[dc(name = "Other")]
797    Other,
798}
799
800impl OsFamily {
801    /// Identifies the compile-target OS family.
802    pub const CURRENT: Self = {
803        #[cfg(target_vendor = "apple")]
804        {
805            Self::Darwin
806        }
807        #[cfg(target_os = "freebsd")]
808        {
809            Self::FreeBSD
810        }
811        #[cfg(target_os = "openbsd")]
812        {
813            Self::OpenBSD
814        }
815        #[cfg(target_os = "netbsd")]
816        {
817            Self::NetBSD
818        }
819        #[cfg(target_os = "dragonfly")]
820        {
821            Self::DragonFly
822        }
823        #[cfg(target_os = "linux")]
824        {
825            Self::Linux
826        }
827        #[cfg(target_os = "windows")]
828        {
829            Self::Windows
830        }
831        #[cfg(not(any(
832            target_vendor = "apple",
833            target_os = "freebsd",
834            target_os = "openbsd",
835            target_os = "netbsd",
836            target_os = "dragonfly",
837            target_os = "linux",
838            target_os = "windows"
839        )))]
840        {
841            Self::Other
842        }
843    };
844
845    /// String name of the OS family.
846    #[must_use]
847    pub const fn as_str(&self) -> &'static str {
848        match self {
849            Self::Darwin => "darwin",
850            Self::FreeBSD => "freebsd",
851            Self::OpenBSD => "openbsd",
852            Self::NetBSD => "netbsd",
853            Self::DragonFly => "dragonfly",
854            Self::Linux => "linux",
855            Self::Windows => "windows",
856            Self::Other => "other",
857        }
858    }
859
860    /// Primary [`FormatId`] representing this operating system family.
861    #[must_use]
862    pub const fn format_id(&self) -> Option<FormatId> {
863        match self {
864            Self::Darwin => Some(FormatId::Darwin),
865            Self::FreeBSD => Some(FormatId::FreeBsd),
866            Self::OpenBSD => Some(FormatId::OpenBsd),
867            Self::NetBSD => Some(FormatId::NetBsd),
868            Self::DragonFly => Some(FormatId::DragonFlyBsd),
869            Self::Linux => Some(FormatId::Linux),
870            Self::Windows => Some(FormatId::Windows),
871            Self::Other => None,
872        }
873    }
874
875    /// Converts an authoritative [`FormatId`] into an [`OsFamily`].
876    #[must_use]
877    pub const fn from_format_id(format: FormatId) -> Option<Self> {
878        match format {
879            FormatId::Darwin
880            | FormatId::MacOsDarwin
881            | FormatId::MacOs
882            | FormatId::AppleIos
883            | FormatId::WatchOs
884            | FormatId::TvOs
885            | FormatId::VisionOs => Some(Self::Darwin),
886            FormatId::FreeBsd => Some(Self::FreeBSD),
887            FormatId::OpenBsd => Some(Self::OpenBSD),
888            FormatId::NetBsd => Some(Self::NetBSD),
889            FormatId::DragonFlyBsd => Some(Self::DragonFly),
890            FormatId::Linux
891            | FormatId::GnuLinux
892            | FormatId::Wsl
893            | FormatId::Wsl2
894            | FormatId::Android => Some(Self::Linux),
895            FormatId::Windows | FormatId::WinNt | FormatId::WinClassic => {
896                Some(Self::Windows)
897            }
898            _ => None,
899        }
900    }
901}
902
903///
904/// Serializes to a format where omitted fields assume default values on
905/// JSON deserialization. Unknown JSON fields are rejected; JSON is a debugging
906/// representation, not a lossless document interchange format.
907#[ipc_dto]
908#[derive(
909    Debug,
910    Clone,
911    PartialEq,
912    Eq,
913    Default,
914    Serialize,
915    Deserialize,
916    ctb_formats_dcstring::DcMixed,
917)]
918#[serde(default, deny_unknown_fields)]
919#[dc(begin = 340, end = 341)]
920#[expect(
921    clippy::struct_excessive_bools,
922    reason = "Execution environment runtime flags are distinct individual attributes"
923)]
924pub struct EnvDescription {
925    #[dc(short = 342)]
926    pub os: String,
927    #[dc(short = 344)]
928    pub usize_width: u8,
929    #[dc(short = 343)]
930    pub ctb_version: String,
931    #[dc(short = 345)]
932    pub cwd: Option<std::path::PathBuf>,
933    #[dc(short = 346)]
934    pub local_ips: Vec<IpAddr>,
935    #[dc(short = 398)]
936    pub public_ips: Vec<IpAddr>,
937    #[dc(short = 347)]
938    pub system_time_resolution_nanos: Option<u128>,
939    #[dc(short = 519)]
940    pub server_system_time_offset_nanos: Option<i128>,
941    #[dc(short = 520)]
942    pub is_release_build: bool,
943    #[dc(short = 521)]
944    pub is_debug_build: bool,
945    #[dc(short = 522)]
946    pub is_cargo_target_binary: bool,
947    #[dc(short = 523)]
948    pub is_in_test: bool,
949    #[dc(short = 524)]
950    pub is_branded_build: bool,
951    #[dc(short = 525)]
952    pub is_official_signed_build: bool,
953    #[dc(short = 526)]
954    pub is_cli_lightweight: bool,
955    #[dc(short = 527)]
956    pub is_workspace: bool,
957    #[dc(short = 528)]
958    pub is_workspace_main_process: bool,
959    #[dc(short = 529)]
960    pub is_service_subprocess: bool,
961    #[dc(short = 530)]
962    pub is_official_public_website: bool,
963    #[dc(short = 531)]
964    pub is_public_website: bool,
965    #[dc(short = 532)]
966    pub is_local: bool,
967    #[dc(short = 533)]
968    pub kernel_version: Option<String>,
969    /// Authoritative format identifiers representing this environment.
970    ///
971    /// This flattened format list encapsulates all platform identity,
972    /// device capability, display server, and terminal protocol attributes.
973    /// Structured views corresponding to [`EnvironmentIdentity`] and
974    /// [`EnvironmentCapabilities`] are derived directly from this data and
975    /// can be retrieved via the [`Self::identity`] and [`Self::capabilities`]
976    /// accessors.
977    #[dc(flatten)]
978    #[serde(alias = "additional_support")]
979    pub supported_formats: Vec<FormatId>,
980}
981
982impl EnvDescription {
983    /// First local IPv4 address if present in `local_ips`.
984    #[must_use]
985    pub fn local_ipv4(&self) -> Option<Ipv4Addr> {
986        self.local_ips.iter().find_map(|ip| match ip {
987            IpAddr::V4(v4) => Some(*v4),
988            IpAddr::V6(_) => None,
989        })
990    }
991
992    /// First local IPv6 address if present in `local_ips`.
993    #[must_use]
994    pub fn local_ipv6(&self) -> Option<Ipv6Addr> {
995        self.local_ips.iter().find_map(|ip| match ip {
996            IpAddr::V6(v6) => Some(*v6),
997            IpAddr::V4(_) => None,
998        })
999    }
1000
1001    /// First public IPv4 address if present in `public_ips`.
1002    #[must_use]
1003    pub fn public_ipv4(&self) -> Option<Ipv4Addr> {
1004        self.public_ips.iter().find_map(|ip| match ip {
1005            IpAddr::V4(v4) => Some(*v4),
1006            IpAddr::V6(_) => None,
1007        })
1008    }
1009
1010    /// First public IPv6 address if present in `public_ips`.
1011    #[must_use]
1012    pub fn public_ipv6(&self) -> Option<Ipv6Addr> {
1013        self.public_ips.iter().find_map(|ip| match ip {
1014            IpAddr::V6(v6) => Some(*v6),
1015            IpAddr::V4(_) => None,
1016        })
1017    }
1018
1019    /// Capture a quick snapshot of the current execution environment, omitting
1020    /// slow or network-dependent queries unless already cached.
1021    ///
1022    /// NOTE: Direct use of `EnvDescription::capture_quick()` is discouraged;
1023    /// prefer [`crate::environment::capture_quick`].
1024    pub(crate) fn capture_quick() -> Self {
1025        let ident = detect_identity();
1026        let caps = detect_capabilities();
1027        let supported_formats =
1028            detection::collect_all_format_ids(&ident, &caps);
1029
1030        let mut local_ips = Vec::new();
1031        if let Some(v4) = CACHED_LOCAL_IPV4.read().ok().and_then(|l| *l) {
1032            local_ips.push(IpAddr::V4(v4));
1033        }
1034        if let Some(v6) = CACHED_LOCAL_IPV6.read().ok().and_then(|l| *l) {
1035            local_ips.push(IpAddr::V6(v6));
1036        }
1037
1038        let mut public_ips = Vec::new();
1039        if let Some(v4) = CACHED_PUBLIC_IPV4.read().ok().and_then(|l| *l) {
1040            public_ips.push(IpAddr::V4(v4));
1041        }
1042        if let Some(v6) = CACHED_PUBLIC_IPV6.read().ok().and_then(|l| *l) {
1043            public_ips.push(IpAddr::V6(v6));
1044        }
1045
1046        Self {
1047            os: os(),
1048            usize_width: usize(),
1049            ctb_version: ctb_version().to_string(),
1050            cwd: std::env::current_dir().ok(),
1051            local_ips,
1052            public_ips,
1053            system_time_resolution_nanos: unix_system_time_resolution().ok(),
1054            server_system_time_offset_nanos: CACHED_SERVER_TIME_OFFSET_NANOS
1055                .read()
1056                .ok()
1057                .and_then(|lock| *lock),
1058            is_release_build: is_release_build(),
1059            is_debug_build: is_debug_build(),
1060            is_cargo_target_binary: is_cargo_target_binary(),
1061            is_in_test: is_in_test(),
1062            is_branded_build: is_branded_build(),
1063            is_official_signed_build: is_official_signed_build(),
1064            is_cli_lightweight: is_cli_lightweight(),
1065            is_workspace: is_workspace(),
1066            is_workspace_main_process: is_workspace_main_process(),
1067            is_service_subprocess: is_service_subprocess(),
1068            is_official_public_website: is_official_public_website(),
1069            is_public_website: is_public_website(),
1070            is_local: is_local(),
1071            kernel_version: ident.kernel_version,
1072            supported_formats,
1073        }
1074    }
1075
1076    /// Return the structured OS, kernel, libc, and architecture identity.
1077    #[must_use]
1078    pub fn identity(&self) -> EnvironmentIdentity {
1079        let (ident, _) = detection::decode_environment_from_formats(
1080            &self.supported_formats,
1081            self.kernel_version.clone(),
1082        );
1083        ident
1084    }
1085
1086    /// Return the active display, terminal, and renderer capabilities.
1087    #[must_use]
1088    pub fn capabilities(&self) -> EnvironmentCapabilities {
1089        let (_, caps) = detection::decode_environment_from_formats(
1090            &self.supported_formats,
1091            self.kernel_version.clone(),
1092        );
1093        caps
1094    }
1095
1096    /// Returns the operating system family where this environment originated.
1097    #[must_use]
1098    pub fn os_family(&self) -> OsFamily {
1099        for format in &self.supported_formats {
1100            if let Some(family) = OsFamily::from_format_id(*format) {
1101                return family;
1102            }
1103            for &imp in format.implies() {
1104                if let Some(family) = OsFamily::from_format_id(imp) {
1105                    return family;
1106                }
1107            }
1108        }
1109        OsFamily::Other
1110    }
1111
1112    /// Return the execution role of the current process within the workspace architecture.
1113    #[must_use]
1114    pub fn process_role(&self) -> ProcessRole {
1115        if self.is_workspace_main_process {
1116            ProcessRole::WorkspaceMain
1117        } else if self.is_service_subprocess {
1118            ProcessRole::ServiceSubprocess
1119        } else if self.is_cli_lightweight {
1120            ProcessRole::LightweightCli
1121        } else {
1122            ProcessRole::Unknown
1123        }
1124    }
1125
1126    /// Returns all [`FormatId`] elements that apply to this environment
1127    /// (identity, capabilities, and families).
1128    #[must_use]
1129    pub fn all_format_ids(&self) -> Vec<FormatId> {
1130        self.supported_formats.clone()
1131    }
1132
1133    /// Check if this environment has a specific [`FormatId`] capability or identity.
1134    #[must_use]
1135    pub fn has_format(&self, format: FormatId) -> bool {
1136        self.supported_formats.contains(&format)
1137    }
1138
1139    /// Check if this environment is compatible with a given target OS format.
1140    #[must_use]
1141    pub fn is_os_compatible(&self, target_os: FormatId) -> bool {
1142        let ident = self.identity();
1143        if ident.os == Some(target_os)
1144            || ident.os_families.contains(&target_os)
1145            || ident.kernel == Some(target_os)
1146        {
1147            return true;
1148        }
1149        if let Some(os) = ident.os {
1150            ctb_formats_utilities::detection::is_os_match(os, target_os)
1151        } else {
1152            false
1153        }
1154    }
1155
1156    /// Produce a human-readable one-line summary string for this environment.
1157    #[must_use]
1158    pub fn summary(&self) -> String {
1159        let ident = self.identity();
1160        let caps = self.capabilities();
1161        detection::format_environment_summary(&ident, &caps)
1162    }
1163
1164    // --- Derivable boolean methods ---
1165
1166    #[must_use]
1167    pub fn is_unix(&self) -> bool {
1168        self.has_format(FormatId::Unix)
1169    }
1170
1171    #[must_use]
1172    pub fn is_linux(&self) -> bool {
1173        self.has_format(FormatId::Linux)
1174            || self.has_format(FormatId::Wsl)
1175            || self.has_format(FormatId::Wsl2)
1176    }
1177
1178    #[must_use]
1179    pub fn is_windows(&self) -> bool {
1180        self.has_format(FormatId::Windows) || self.has_format(FormatId::WinNt)
1181    }
1182
1183    #[must_use]
1184    pub fn is_wine(&self) -> bool {
1185        self.has_format(FormatId::Wine)
1186    }
1187
1188    #[must_use]
1189    pub fn is_mac_os_10_or_newer(&self) -> bool {
1190        self.has_format(FormatId::MacOsDarwin)
1191    }
1192
1193    #[must_use]
1194    pub fn is_apple_ios(&self) -> bool {
1195        self.has_format(FormatId::AppleIos)
1196    }
1197
1198    #[must_use]
1199    pub fn is_watchos(&self) -> bool {
1200        self.has_format(FormatId::WatchOs)
1201    }
1202
1203    #[must_use]
1204    pub fn is_tvos(&self) -> bool {
1205        self.has_format(FormatId::TvOs)
1206    }
1207
1208    #[must_use]
1209    pub fn is_visionos(&self) -> bool {
1210        self.has_format(FormatId::VisionOs)
1211    }
1212
1213    #[must_use]
1214    pub fn is_darwin(&self) -> bool {
1215        self.has_format(FormatId::Darwin) || self.has_format(FormatId::MacOs)
1216    }
1217
1218    #[must_use]
1219    pub fn looks_like_gnustep(&self) -> bool {
1220        self.has_format(FormatId::GnuStep)
1221    }
1222
1223    #[must_use]
1224    pub fn looks_like_nextstep_or_openstep(&self) -> bool {
1225        self.has_format(FormatId::NextStep)
1226    }
1227
1228    #[must_use]
1229    pub fn is_bsd(&self) -> bool {
1230        self.has_format(FormatId::BsdLibc)
1231            || self.has_format(FormatId::BsdKernel)
1232    }
1233
1234    #[must_use]
1235    pub fn is_openbsd(&self) -> bool {
1236        self.has_format(FormatId::OpenBsd)
1237    }
1238
1239    #[must_use]
1240    pub fn is_dragonfly(&self) -> bool {
1241        self.has_format(FormatId::DragonFlyBsd)
1242    }
1243
1244    #[must_use]
1245    pub fn is_freebsd(&self) -> bool {
1246        self.has_format(FormatId::FreeBsd)
1247    }
1248
1249    #[must_use]
1250    pub fn is_netbsd(&self) -> bool {
1251        self.has_format(FormatId::NetBsd)
1252    }
1253
1254    #[must_use]
1255    pub fn is_browser_vm(&self) -> bool {
1256        self.has_format(FormatId::BrowserVm)
1257    }
1258
1259    #[must_use]
1260    pub fn is_browser_vm_fullscreen(&self) -> bool {
1261        self.has_format(FormatId::BrowserVmFullscreen)
1262    }
1263
1264    #[must_use]
1265    pub fn is_browser_vm_mobile(&self) -> bool {
1266        self.has_format(FormatId::BrowserVmMobile)
1267    }
1268
1269    #[must_use]
1270    pub fn is_v86(&self) -> bool {
1271        self.has_format(FormatId::V86Vm)
1272    }
1273
1274    #[must_use]
1275    pub fn is_pwa(&self) -> bool {
1276        self.has_format(FormatId::Pwa)
1277    }
1278
1279    #[must_use]
1280    pub fn is_pwa_mobile(&self) -> bool {
1281        self.has_format(FormatId::PwaMobile)
1282    }
1283
1284    #[must_use]
1285    pub fn is_webui(&self) -> bool {
1286        self.has_format(FormatId::WebUi)
1287    }
1288
1289    #[must_use]
1290    pub fn is_webui_in_system_browser(&self) -> bool {
1291        self.has_format(FormatId::WebUiSystemBrowser)
1292    }
1293
1294    #[must_use]
1295    pub fn is_webui_in_webview(&self) -> bool {
1296        self.has_format(FormatId::WebView)
1297    }
1298
1299    #[must_use]
1300    pub fn is_gui(&self) -> bool {
1301        let caps = self.capabilities();
1302        caps.device_caps.contains(&FormatId::RasterDisplay)
1303            && !matches!(
1304                caps.display_server,
1305                None | Some(FormatId::HeadlessDisplay)
1306            )
1307    }
1308
1309    #[must_use]
1310    pub fn is_cli(&self) -> bool {
1311        self.has_format(FormatId::IsStdoutTerminal)
1312    }
1313
1314    #[must_use]
1315    pub fn is_cli_tty(&self) -> bool {
1316        self.has_format(FormatId::Teleprinter)
1317            || self.has_format(FormatId::LineModeTerminal)
1318    }
1319
1320    #[must_use]
1321    pub fn is_cli_videoterminal(&self) -> bool {
1322        self.has_format(FormatId::Videoterminal)
1323    }
1324
1325    /// Capture a full snapshot of the current execution environment, including
1326    /// network discovery for public IP and server time offset.
1327    ///
1328    /// NOTE: Direct use of `EnvDescription::capture()` is discouraged;
1329    /// prefer [`crate::environment::capture`].
1330    pub(crate) fn capture() -> Self {
1331        let mut desc = Self::capture_quick();
1332        desc.is_official_signed_build = verify_official_signed_build();
1333        let mut local_ips = Vec::new();
1334        match cached_local_ipv4() {
1335            Ok(v4) => local_ips.push(IpAddr::V4(v4)),
1336            Err(error) => warn_fmt!("Local IPv4 discovery failed: {error:#}"),
1337        }
1338        match cached_local_ipv6() {
1339            Ok(v6) => local_ips.push(IpAddr::V6(v6)),
1340            Err(error) => warn_fmt!("Local IPv6 discovery failed: {error:#}"),
1341        }
1342        desc.local_ips = local_ips;
1343
1344        let start = std::time::Instant::now();
1345        let budget = crate::https::STARTUP_REQUEST_TIMEOUT;
1346        let test_name = crate::testing::try_get_current_test_name();
1347        let test_storage_dir = crate::testing::try_get_test_storage_dir();
1348        let (v4_res, v6_res) = std::thread::scope(|s| {
1349            let v6_handle = s.spawn(move || {
1350                let _test_scope =
1351                    crate::testing::push_current_test_name(test_name);
1352                crate::testing::TEST_STORAGE_DIR_SYNC.with(|storage| {
1353                    *storage.borrow_mut() = test_storage_dir;
1354                });
1355                cached_public_ipv6_with_timeout(budget)
1356            });
1357            let v4 = cached_public_ipv4_with_timeout(budget);
1358            let v6 = v6_handle
1359                .join()
1360                .map_err(|_| anyhow::anyhow!("IPv6 discovery thread panicked"))
1361                .and_then(std::convert::identity);
1362            (v4, v6)
1363        });
1364
1365        let mut public_ips = Vec::new();
1366        match v4_res {
1367            Ok(v4) => public_ips.push(IpAddr::V4(v4)),
1368            Err(error) => warn_fmt!("Public IPv4 discovery failed: {error:#}"),
1369        }
1370        match v6_res {
1371            Ok(v6) => public_ips.push(IpAddr::V6(v6)),
1372            Err(error) => warn_fmt!("Public IPv6 discovery failed: {error:#}"),
1373        }
1374        desc.public_ips = public_ips;
1375        let remaining = budget.saturating_sub(start.elapsed());
1376        desc.server_system_time_offset_nanos =
1377            match cached_server_system_time_offset_nanos_with_timeout(remaining)
1378            {
1379                Ok(offset) => Some(offset),
1380                Err(error) => {
1381                    warn_fmt!(
1382                        "Server clock offset discovery failed: {error:#}"
1383                    );
1384                    None
1385                }
1386            };
1387        desc
1388    }
1389
1390    /// Alias for [`Self::capture`].
1391    pub fn current() -> Self {
1392        Self::capture()
1393    }
1394
1395    /// Parse `ctb_version` as a semver [`semver::Version`].
1396    pub fn ctb_version_semver(&self) -> semver::Version {
1397        // Reason for fallback: unparseable version string falls back to 0.0.0 semver
1398        semver::Version::parse(&self.ctb_version)
1399            .unwrap_or_else(|_| semver::Version::new(0, 0, 0))
1400    }
1401
1402    /// Serialize this environment description to a compact JSON string.
1403    pub fn to_json(&self) -> anyhow::Result<String> {
1404        serde_json::to_string(self).map_err(Into::into)
1405    }
1406
1407    /// Serialize this environment description to a pretty-printed JSON string.
1408    pub fn to_json_pretty(&self) -> anyhow::Result<String> {
1409        serde_json::to_string_pretty(self).map_err(Into::into)
1410    }
1411
1412    /// Deserialize an environment description from a JSON string.
1413    pub fn from_json(json: &str) -> anyhow::Result<Self> {
1414        serde_json::from_str(json).map_err(Into::into)
1415    }
1416}
1417
1418/// Capture a snapshot of the current execution environment as an
1419/// [`EnvDescription`].
1420pub fn capture() -> EnvDescription {
1421    EnvDescription::capture()
1422}
1423
1424static BOOT_CACHED_ENV: RwLock<Option<Arc<EnvDescription>>> = RwLock::new(None);
1425static BOOT_ENV_INIT_MUTEX: std::sync::Mutex<()> = std::sync::Mutex::new(());
1426
1427/// Initializes and caches the startup boot environment using a full (slow)
1428/// environment capture.
1429pub fn init_boot_env() -> Arc<EnvDescription> {
1430    if let Some(cached) = get_boot_cached_env() {
1431        return cached;
1432    }
1433    // Reason for fallback: poisoned lock error retains mutex guard so concurrent boot environment initializations still serialize
1434    let _init_guard = BOOT_ENV_INIT_MUTEX.lock().unwrap_or_else(|error| {
1435        warn!("Recovering poisoned boot environment init mutex");
1436        error.into_inner()
1437    });
1438    if let Some(cached) = get_boot_cached_env() {
1439        return cached;
1440    }
1441    let env = Arc::new(EnvDescription::capture());
1442    // Reason for fallback: poisoned lock error retains inner cache data so startup boot environment remains accessible across threads
1443    let mut lock = BOOT_CACHED_ENV.write().unwrap_or_else(|error| {
1444        warn!("Recovering poisoned boot environment cache");
1445        error.into_inner()
1446    });
1447    *lock = Some(Arc::clone(&env));
1448    env
1449}
1450
1451/// Returns the boot-cached environment recorded during workspace startup, if present.
1452pub fn get_boot_cached_env() -> Option<Arc<EnvDescription>> {
1453    // Reason for fallback: poisoned lock error retains inner cache data so startup boot environment remains readable
1454    let lock = BOOT_CACHED_ENV.read().unwrap_or_else(|error| {
1455        warn!("Recovering poisoned boot environment cache");
1456        error.into_inner()
1457    });
1458    lock.as_ref().map(Arc::clone)
1459}
1460
1461/// Reset the boot-cached environment (primarily used for test isolation).
1462pub fn reset_boot_cached_env() {
1463    // Reason for fallback: poisoned lock error retains inner cache data to permit resetting the boot cache for test isolation
1464    let mut lock = BOOT_CACHED_ENV.write().unwrap_or_else(|error| {
1465        warn!("Recovering poisoned boot environment cache");
1466        error.into_inner()
1467    });
1468    *lock = None;
1469}
1470
1471/// Capture a quick snapshot of the current execution environment as an
1472/// [`EnvDescription`], omitting slow or network-dependent queries unless
1473/// already cached.
1474///
1475/// If called after a full workspace boot, returns the cached value that was
1476/// recorded during startup.
1477pub fn capture_quick() -> EnvDescription {
1478    if let Some(cached) = get_boot_cached_env() {
1479        return (*cached).clone();
1480    }
1481    EnvDescription::capture_quick()
1482}
1483
1484#[derive(Clone, Debug)]
1485struct ScopeSlot {
1486    env: Arc<OnceLock<Arc<EnvDescription>>>,
1487    capture: fn() -> EnvDescription,
1488}
1489
1490impl ScopeSlot {
1491    fn concrete(env: Arc<EnvDescription>) -> Self {
1492        Self {
1493            env: Arc::new(OnceLock::from(env)),
1494            capture: capture_quick,
1495        }
1496    }
1497
1498    fn lazy(capture: fn() -> EnvDescription) -> Self {
1499        Self {
1500            env: Arc::new(OnceLock::new()),
1501            capture,
1502        }
1503    }
1504
1505    fn resolve(&self) -> Arc<EnvDescription> {
1506        Arc::clone(self.env.get_or_init(|| {
1507            if let Some(cached) = get_boot_cached_env() {
1508                cached
1509            } else {
1510                Arc::new((self.capture)())
1511            }
1512        }))
1513    }
1514}
1515
1516static GLOBAL_OPERATION_ENV: RwLock<Option<ScopeSlot>> = RwLock::new(None);
1517static OPERATION_EPOCH: AtomicU64 = AtomicU64::new(1);
1518
1519thread_local! {
1520    static ACTIVE_SCOPE: RefCell<Option<ScopeSlot>> =
1521        const { RefCell::new(None) };
1522    static EPOCH_CACHE: RefCell<(u64, Option<Arc<EnvDescription>>)> =
1523        const { RefCell::new((0, None)) };
1524}
1525
1526/// An RAII guard that establishes an active [`EnvDescription`] scope for the
1527/// current thread's operation.
1528///
1529/// While this scope is active, calls to [`capture_quick_arc()`] will return this
1530/// exact [`Arc<EnvDescription>`] without re-probing or allocating.
1531#[derive(Debug)]
1532pub struct EnvironmentScope {
1533    previous: Option<ScopeSlot>,
1534}
1535
1536impl EnvironmentScope {
1537    /// Enters a new thread-local environment scope with the given environment.
1538    pub fn enter(env: Arc<EnvDescription>) -> Self {
1539        Self::enter_slot(ScopeSlot::concrete(env))
1540    }
1541
1542    /// Enters a thread-local scope that lazily captures a quick environment
1543    /// snapshot only upon first access.
1544    pub fn enter_fresh() -> Self {
1545        Self::enter_slot(ScopeSlot::lazy(capture_quick))
1546    }
1547
1548    /// Enters a thread-local scope that lazily captures a full environment
1549    /// snapshot (including network queries) only upon first access, or reuses
1550    /// the workspace startup snapshot if available.
1551    pub fn enter_full() -> Self {
1552        Self::enter_slot(ScopeSlot::lazy(capture))
1553    }
1554
1555    fn enter_slot(slot: ScopeSlot) -> Self {
1556        let previous =
1557            ACTIVE_SCOPE.with(|scope| scope.borrow_mut().replace(slot));
1558        Self { previous }
1559    }
1560}
1561
1562impl Drop for EnvironmentScope {
1563    fn drop(&mut self) {
1564        ACTIVE_SCOPE.with(|scope| {
1565            *scope.borrow_mut() = self.previous.take();
1566        });
1567    }
1568}
1569
1570/// An RAII guard that establishes an active [`EnvDescription`] process-wide for
1571/// multi-threaded operations (such as parallel directory traversal).
1572#[derive(Debug)]
1573pub struct GlobalEnvironmentScope {
1574    previous: Option<ScopeSlot>,
1575}
1576
1577impl GlobalEnvironmentScope {
1578    /// Enters a process-wide environment scope with the given environment.
1579    pub fn enter(env: Arc<EnvDescription>) -> Self {
1580        Self::enter_slot(ScopeSlot::concrete(env))
1581    }
1582
1583    /// Enters a process-wide scope that lazily captures a quick environment
1584    /// snapshot only upon first access.
1585    pub fn enter_fresh() -> Self {
1586        Self::enter_slot(ScopeSlot::lazy(capture_quick))
1587    }
1588
1589    /// Enters a process-wide scope that lazily captures a full environment
1590    /// snapshot (including network queries) only upon first access, or reuses
1591    /// the workspace startup snapshot if available.
1592    pub fn enter_full() -> Self {
1593        Self::enter_slot(ScopeSlot::lazy(capture))
1594    }
1595
1596    fn enter_slot(slot: ScopeSlot) -> Self {
1597        // Reason for fallback: poisoned lock error retains previous operation scope state so new scope entry can still be registered
1598        let mut lock = GLOBAL_OPERATION_ENV.write().unwrap_or_else(|error| {
1599            warn!("Recovering poisoned operation environment scope");
1600            error.into_inner()
1601        });
1602        let previous = lock.replace(slot);
1603        Self { previous }
1604    }
1605}
1606
1607impl Drop for GlobalEnvironmentScope {
1608    fn drop(&mut self) {
1609        // Reason for fallback: poisoned lock error retains scope state so drop can restore the previous operation environment
1610        let mut lock = GLOBAL_OPERATION_ENV.write().unwrap_or_else(|error| {
1611            warn!("Recovering poisoned operation environment scope");
1612            error.into_inner()
1613        });
1614        *lock = self.previous.take();
1615    }
1616}
1617
1618/// Executes a closure within an active thread-local [`EnvironmentScope`].
1619pub fn with_environment_scope<F, R>(env: Arc<EnvDescription>, f: F) -> R
1620where
1621    F: FnOnce() -> R,
1622{
1623    let _guard = EnvironmentScope::enter(env);
1624    f()
1625}
1626
1627/// Executes a closure within an active process-wide [`GlobalEnvironmentScope`].
1628pub fn with_global_environment_scope<F, R>(env: Arc<EnvDescription>, f: F) -> R
1629where
1630    F: FnOnce() -> R,
1631{
1632    let _guard = GlobalEnvironmentScope::enter(env);
1633    f()
1634}
1635
1636/// Increments the operation epoch, causing any subsequent unscoped calls to
1637/// [`capture_quick_arc()`] to capture a fresh [`EnvDescription`] snapshot.
1638///
1639/// Note that this does NOT reset or clear global slow/network caches (such as
1640/// public/local IPv4 or server time offset), which remain cached across
1641/// operations.
1642pub fn advance_operation_epoch() -> u64 {
1643    OPERATION_EPOCH
1644        .fetch_add(1, Ordering::SeqCst)
1645        .wrapping_add(1)
1646}
1647
1648/// Invalidate the unscoped quick environment snapshot cache without resetting
1649/// slow network-sourced caches.
1650pub fn reset_quick_env_cache() {
1651    let _ = advance_operation_epoch();
1652}
1653
1654/// Returns a shared [`Arc<EnvDescription>`] snapshot of the current
1655/// environment.
1656///
1657/// Prioritizes:
1658/// 1. An active thread-local [`EnvironmentScope`].
1659/// 2. An active process-wide [`GlobalEnvironmentScope`].
1660/// 3. The boot-cached environment recorded during workspace startup, if present.
1661/// 4. An unscoped thread-local epoch cache (invalidated per-operation via
1662///    [`advance_operation_epoch()`] or [`reset_quick_env_cache()`]).
1663pub fn capture_quick_arc() -> Arc<EnvDescription> {
1664    if let Some(slot) = ACTIVE_SCOPE.with(|scope| scope.borrow().clone()) {
1665        return slot.resolve();
1666    }
1667
1668    // Reason for fallback: poisoned lock error retains active global scope slot so quick environment capture can resolve it
1669    let slot = GLOBAL_OPERATION_ENV
1670        .read()
1671        .unwrap_or_else(|error| {
1672            warn!("Recovering poisoned operation environment scope");
1673            error.into_inner()
1674        })
1675        .clone();
1676    if let Some(slot) = slot {
1677        return slot.resolve();
1678    }
1679
1680    if let Some(cached) = get_boot_cached_env() {
1681        return cached;
1682    }
1683
1684    let current_epoch = OPERATION_EPOCH.load(Ordering::Relaxed);
1685    if let Some(env) = EPOCH_CACHE.with(|cache| {
1686        let borrow = cache.borrow();
1687        if borrow.0 == current_epoch {
1688            borrow.1.as_ref().map(Arc::clone)
1689        } else {
1690            None
1691        }
1692    }) {
1693        return env;
1694    }
1695
1696    let fresh = Arc::new(capture_quick());
1697    EPOCH_CACHE.with(|cache| {
1698        *cache.borrow_mut() = (current_epoch, Some(Arc::clone(&fresh)));
1699    });
1700    fresh
1701}
1702
1703#[cfg(test)]
1704#[allow(
1705    clippy::panic,
1706    clippy::expect_used,
1707    clippy::unwrap_used,
1708    clippy::unwrap_in_result,
1709    clippy::panic_in_result_fn,
1710    clippy::indexing_slicing,
1711    clippy::arithmetic_side_effects,
1712    reason = "Standard repository test boilerplate"
1713)]
1714mod tests {
1715    use super::*;
1716
1717    static ENV_TEST_MUTEX: std::sync::Mutex<()> = std::sync::Mutex::new(());
1718
1719    #[crate::ctb_test]
1720    fn test_ip_endpoint_rejects_invalid_url() -> Result<()> {
1721        let error = query_ip_endpoint("not a URL")
1722            .expect_err("invalid endpoint must fail before making a request");
1723        anyhow::ensure!(
1724            !error.to_string().contains("Skipping remote IP endpoint"),
1725            "platform detection must not disable IP endpoint queries"
1726        );
1727        Ok(())
1728    }
1729
1730    #[crate::ctb_test]
1731    fn test_is_official_signed_build_defaults_to_false() {
1732        assert!(!is_official_signed_build());
1733    }
1734
1735    #[crate::ctb_test]
1736    fn test_os_and_environment_detection() {
1737        let _lock = ENV_TEST_MUTEX
1738            .lock()
1739            .unwrap_or_else(std::sync::PoisonError::into_inner);
1740        if is_linux() {
1741            assert!(!is_windows());
1742            assert!(!is_mac_os_10_or_newer());
1743            assert!(!is_darwin());
1744            assert!(!is_bsd());
1745            assert!(!is_openbsd());
1746            assert!(!is_dragonfly());
1747            assert!(!is_freebsd());
1748            assert!(!is_netbsd());
1749        }
1750
1751        assert_eq!(
1752            is_bsd(),
1753            is_openbsd() || is_dragonfly() || is_freebsd() || is_netbsd()
1754        );
1755
1756        let _ = is_darwin();
1757        let _ = looks_like_gnustep();
1758        let _ = looks_like_nextstep_or_openstep();
1759    }
1760
1761    #[crate::ctb_test]
1762    fn test_env_description_capture_and_serialization() {
1763        let _lock = ENV_TEST_MUTEX
1764            .lock()
1765            .unwrap_or_else(std::sync::PoisonError::into_inner);
1766        let desc = EnvDescription::capture();
1767        assert_eq!(desc.os, os());
1768        assert_eq!(desc.usize_width, usize());
1769        assert_eq!(desc.is_linux(), is_linux());
1770
1771        // Test capture_quick
1772        let quick = EnvDescription::capture_quick();
1773        assert_eq!(quick.os, os());
1774        assert_eq!(quick.usize_width, usize());
1775        assert_eq!(
1776            quick.server_system_time_offset_nanos,
1777            desc.server_system_time_offset_nanos
1778        );
1779        assert!(quick.system_time_resolution_nanos.is_some());
1780
1781        // Test JSON serialization
1782        let json = desc.to_json().expect("failed to serialize EnvDescription");
1783
1784        // Test roundtrip
1785        let deserialized = EnvDescription::from_json(&json)
1786            .expect("failed to deserialize EnvDescription");
1787        assert_eq!(desc, deserialized);
1788        assert_eq!(deserialized.is_linux(), desc.is_linux());
1789        assert_eq!(deserialized.is_windows(), desc.is_windows());
1790        assert_eq!(deserialized.is_wine(), desc.is_wine());
1791
1792        // Test semver parsing helper
1793        let semver = desc.ctb_version_semver();
1794        assert_eq!(semver, ctb_version_semver());
1795
1796        // Test empty JSON deserializes to default values
1797        let empty_desc = EnvDescription::from_json("{}")
1798            .expect("failed to deserialize empty JSON");
1799        assert_eq!(empty_desc, EnvDescription::default());
1800    }
1801
1802    #[crate::ctb_test]
1803    fn test_env_description_json_rejects_unknown_fields() -> Result<()> {
1804        for json in [
1805            r#"{"os":"linux","future_flag":true}"#,
1806            r#"{"future_num":42}"#,
1807            r#"{"extra":{"future_flag":true}}"#,
1808        ] {
1809            let error = EnvDescription::from_json(json)
1810                .expect_err("unknown JSON fields must be rejected");
1811            assert!(error.to_string().contains("unknown field"));
1812            serde_json::from_str::<EnvDescription>(json).unwrap_err();
1813        }
1814        Ok(())
1815    }
1816
1817    #[crate::ctb_test]
1818    fn test_is_wine_scope_and_format() {
1819        let mut desc = EnvDescription::default();
1820        assert!(!desc.is_wine());
1821
1822        desc.supported_formats.push(FormatId::Wine);
1823        assert!(desc.is_wine());
1824
1825        let env_arc = Arc::new(desc);
1826        with_environment_scope(env_arc, || {
1827            assert!(is_wine());
1828            assert!(capture_quick_arc().is_wine());
1829        });
1830    }
1831
1832    #[crate::ctb_test]
1833    fn test_system_time_resolution() {
1834        let now = unix_system_time_now();
1835        assert!(now > 0);
1836
1837        let resolution = unix_system_time_resolution()
1838            .expect("Failed to get system time resolution");
1839        assert!(resolution > 0);
1840
1841        // Subsequent calls should hit memoized cache
1842        let resolution_cached = unix_system_time_resolution()
1843            .expect("Failed to get cached system time resolution");
1844        assert_eq!(resolution, resolution_cached);
1845    }
1846
1847    #[crate::ctb_test]
1848    fn test_local_ip_discovery() {
1849        // Local IPv4 discovery succeeds when an outbound route is configured
1850        if let Ok(ip) = local_ipv4() {
1851            assert!(!ip.is_unspecified());
1852            let cached = cached_local_ipv4().expect("cached_local_ipv4 failed");
1853            assert_eq!(ip, cached);
1854            assert_ne!(cached_local_ipv4_u32(), 0);
1855        }
1856
1857        // Local IPv6 discovery succeeds when an outbound IPv6 route is configured
1858        if let Ok(ip) = local_ipv6() {
1859            assert!(!ip.is_unspecified());
1860            let cached = cached_local_ipv6().expect("cached_local_ipv6 failed");
1861            assert_eq!(ip, cached);
1862            assert_ne!(cached_local_ipv6_u128(), 0);
1863        }
1864    }
1865
1866    #[crate::ctb_test]
1867    fn test_process_role_tracking() {
1868        let _lock = ENV_TEST_MUTEX
1869            .lock()
1870            .unwrap_or_else(std::sync::PoisonError::into_inner);
1871        reset_process_role_for_testing();
1872        assert_eq!(get_process_role(), ProcessRole::Unknown);
1873        assert!(!is_cli_lightweight());
1874        assert!(!is_workspace());
1875        assert!(!is_workspace_main_process());
1876        assert!(!is_service_subprocess());
1877
1878        set_process_role(ProcessRole::LightweightCli);
1879        assert_eq!(get_process_role(), ProcessRole::LightweightCli);
1880        assert!(is_cli_lightweight());
1881        assert!(!is_workspace());
1882        assert!(!is_workspace_main_process());
1883        assert!(!is_service_subprocess());
1884
1885        set_process_role(ProcessRole::WorkspaceMain);
1886        assert_eq!(get_process_role(), ProcessRole::WorkspaceMain);
1887        assert!(!is_cli_lightweight());
1888        assert!(is_workspace());
1889        assert!(is_workspace_main_process());
1890        assert!(!is_service_subprocess());
1891
1892        set_process_role(ProcessRole::ServiceSubprocess);
1893        assert_eq!(get_process_role(), ProcessRole::ServiceSubprocess);
1894        assert!(!is_cli_lightweight());
1895        assert!(is_workspace());
1896        assert!(!is_workspace_main_process());
1897        assert!(is_service_subprocess());
1898
1899        reset_process_role_for_testing();
1900        assert_eq!(get_process_role(), ProcessRole::Unknown);
1901    }
1902
1903    #[crate::ctb_test]
1904    fn test_env_cache_reset() {
1905        let _lock = ENV_TEST_MUTEX
1906            .lock()
1907            .unwrap_or_else(std::sync::PoisonError::into_inner);
1908        // Calling env_cache_reset flushes and refills caches
1909        env_cache_reset();
1910
1911        // If local IPv4 is available, cached should be present
1912        if let Ok(ip) = local_ipv4() {
1913            let cached = CACHED_LOCAL_IPV4.read().unwrap();
1914            assert_eq!(*cached, Some(ip));
1915        }
1916
1917        // Quick capture should now reflect cached values if available
1918        let quick = capture_quick();
1919        assert_eq!(quick.os, os());
1920        assert!(quick.system_time_resolution_nanos.is_some());
1921    }
1922
1923    #[crate::ctb_test]
1924    fn test_capture_quick_arc() {
1925        let _lock = ENV_TEST_MUTEX
1926            .lock()
1927            .unwrap_or_else(std::sync::PoisonError::into_inner);
1928        reset_boot_cached_env();
1929        // Repeated calls within the same epoch share the exact same Arc
1930        let arc1 = capture_quick_arc();
1931        let arc2 = capture_quick_arc();
1932        assert!(Arc::ptr_eq(&arc1, &arc2));
1933        assert_eq!(arc1.os, os());
1934
1935        // Advancing the operation epoch forces a fresh Arc snapshot for subsequent operations
1936        let _ = advance_operation_epoch();
1937        let arc3 = capture_quick_arc();
1938        assert!(!Arc::ptr_eq(&arc1, &arc3));
1939        let arc4 = capture_quick_arc();
1940        assert!(Arc::ptr_eq(&arc3, &arc4));
1941
1942        // Thread-local EnvironmentScope overrides unscoped caching
1943        let custom_env = Arc::new(capture_quick());
1944        {
1945            let _scope = EnvironmentScope::enter(Arc::clone(&custom_env));
1946            let scoped = capture_quick_arc();
1947            assert!(Arc::ptr_eq(&scoped, &custom_env));
1948        }
1949        // Exiting the scope restores previous behavior
1950        let after_scope = capture_quick_arc();
1951        assert!(!Arc::ptr_eq(&after_scope, &custom_env));
1952
1953        // GlobalEnvironmentScope works across threads
1954        let global_custom = Arc::new(capture_quick());
1955        {
1956            let _global_scope =
1957                GlobalEnvironmentScope::enter(Arc::clone(&global_custom));
1958            let current = capture_quick_arc();
1959            assert!(Arc::ptr_eq(&current, &global_custom));
1960        }
1961
1962        // Verify that advancing the operation epoch does NOT clear slow network caches
1963        if let Ok(ip) = cached_local_ipv4() {
1964            let cached = CACHED_LOCAL_IPV4.read().unwrap();
1965            assert_eq!(*cached, Some(ip));
1966            let _ = advance_operation_epoch();
1967            let cached_after = CACHED_LOCAL_IPV4.read().unwrap();
1968            assert_eq!(*cached_after, Some(ip));
1969        }
1970    }
1971
1972    #[crate::ctb_test]
1973    fn test_boot_cached_env() {
1974        let _lock = ENV_TEST_MUTEX
1975            .lock()
1976            .unwrap_or_else(std::sync::PoisonError::into_inner);
1977        reset_boot_cached_env();
1978        assert!(get_boot_cached_env().is_none());
1979
1980        // Initializing boot env populates cache
1981        let boot_env = init_boot_env();
1982        assert!(get_boot_cached_env().is_some());
1983        let cached = get_boot_cached_env().unwrap();
1984        assert!(Arc::ptr_eq(&boot_env, &cached));
1985
1986        // capture_quick_arc returns the boot-cached env directly
1987        let quick_arc = capture_quick_arc();
1988        assert!(Arc::ptr_eq(&quick_arc, &boot_env));
1989
1990        // capture_quick returns a clone of the boot-cached env
1991        let quick = capture_quick();
1992        assert_eq!(quick, *boot_env);
1993
1994        for full in [false, true] {
1995            let _scope = if full {
1996                GlobalEnvironmentScope::enter_full()
1997            } else {
1998                GlobalEnvironmentScope::enter_fresh()
1999            };
2000            assert!(Arc::ptr_eq(&capture_quick_arc(), &boot_env));
2001        }
2002
2003        env_cache_reset();
2004        let refreshed = get_boot_cached_env().unwrap();
2005        assert!(!Arc::ptr_eq(&refreshed, &boot_env));
2006        assert!(Arc::ptr_eq(&capture_quick_arc(), &refreshed));
2007
2008        // Reset clears it
2009        reset_boot_cached_env();
2010        assert!(get_boot_cached_env().is_none());
2011    }
2012
2013    #[crate::ctb_test]
2014    fn test_lazy_scopes() {
2015        let _lock = ENV_TEST_MUTEX
2016            .lock()
2017            .unwrap_or_else(std::sync::PoisonError::into_inner);
2018        reset_boot_cached_env();
2019
2020        // 1. Thread-local lazy scope: enter_fresh lazily resolves on first capture_quick_arc
2021        {
2022            let _scope = EnvironmentScope::enter_fresh();
2023            ACTIVE_SCOPE.with(|scope| {
2024                assert!(scope.borrow().as_ref().unwrap().env.get().is_none());
2025            });
2026            let arc1 = capture_quick_arc();
2027            let arc2 = capture_quick_arc();
2028            assert!(Arc::ptr_eq(&arc1, &arc2));
2029        }
2030
2031        // 2. Process-wide lazy scope: successive enter_fresh scopes get distinct snapshots
2032        let arc_op1 = {
2033            let _scope1 = GlobalEnvironmentScope::enter_fresh();
2034            capture_quick_arc()
2035        };
2036        let arc_op2 = {
2037            let _scope2 = GlobalEnvironmentScope::enter_fresh();
2038            capture_quick_arc()
2039        };
2040        assert!(!Arc::ptr_eq(&arc_op1, &arc_op2));
2041
2042        // 3. enter_full lazily resolves full provenance
2043        {
2044            let _scope_full = GlobalEnvironmentScope::enter_full();
2045            assert!(
2046                GLOBAL_OPERATION_ENV
2047                    .read()
2048                    .unwrap()
2049                    .as_ref()
2050                    .unwrap()
2051                    .env
2052                    .get()
2053                    .is_none()
2054            );
2055            let arc_full = capture_quick_arc();
2056            assert_eq!(arc_full.os, os());
2057            assert!(Arc::ptr_eq(&capture_quick_arc(), &arc_full));
2058        }
2059    }
2060
2061    #[crate::ctb_test]
2062    fn test_lazy_slot_captures_once_across_threads() {
2063        static CAPTURES: std::sync::atomic::AtomicUsize =
2064            std::sync::atomic::AtomicUsize::new(0);
2065
2066        fn counted_capture() -> EnvDescription {
2067            CAPTURES.fetch_add(1, Ordering::SeqCst);
2068            EnvDescription::default()
2069        }
2070
2071        let _lock = ENV_TEST_MUTEX
2072            .lock()
2073            .unwrap_or_else(std::sync::PoisonError::into_inner);
2074        reset_boot_cached_env();
2075        CAPTURES.store(0, Ordering::SeqCst);
2076        let slot = ScopeSlot::lazy(counted_capture);
2077        assert_eq!(CAPTURES.load(Ordering::SeqCst), 0);
2078        let handles: Vec<_> = (0..8)
2079            .map(|_| {
2080                let slot = slot.clone();
2081                std::thread::spawn(move || slot.resolve())
2082            })
2083            .collect();
2084        let env = slot.resolve();
2085        for handle in handles {
2086            assert!(Arc::ptr_eq(&env, &handle.join().unwrap()));
2087        }
2088        assert_eq!(CAPTURES.load(Ordering::SeqCst), 1);
2089    }
2090
2091    #[crate::ctb_test]
2092    fn test_quick_capture_preserves_cached_network_metadata() {
2093        let _lock = ENV_TEST_MUTEX
2094            .lock()
2095            .unwrap_or_else(std::sync::PoisonError::into_inner);
2096        reset_boot_cached_env();
2097        let v4 = Ipv4Addr::new(192, 0, 2, 1);
2098        let v6 = Ipv6Addr::LOCALHOST;
2099        let previous_v4 = CACHED_PUBLIC_IPV4.write().unwrap().replace(v4);
2100        let previous_v6 = CACHED_PUBLIC_IPV6.write().unwrap().replace(v6);
2101        let previous_offset = CACHED_SERVER_TIME_OFFSET_NANOS
2102            .write()
2103            .unwrap()
2104            .replace(123);
2105
2106        let quick = capture_quick();
2107        *CACHED_PUBLIC_IPV4.write().unwrap() = previous_v4;
2108        *CACHED_PUBLIC_IPV6.write().unwrap() = previous_v6;
2109        *CACHED_SERVER_TIME_OFFSET_NANOS.write().unwrap() = previous_offset;
2110
2111        assert_eq!(quick.public_ipv4(), Some(v4));
2112        assert_eq!(quick.public_ipv6(), Some(v6));
2113        assert_eq!(quick.server_system_time_offset_nanos, Some(123));
2114    }
2115
2116    #[crate::ctb_test]
2117    fn test_unmocked_remote_discovery_fails_in_tests() {
2118        public_ipv4().unwrap_err();
2119        public_ipv6().unwrap_err();
2120        server_system_time_offset_nanos().unwrap_err();
2121    }
2122
2123    #[crate::ctb_test]
2124    #[allow(
2125        unsafe_code,
2126        reason = "Modifying environment variable is unsafe in Rust 2024"
2127    )]
2128    fn test_looks_like_gnustep() {
2129        let _lock = ENV_TEST_MUTEX
2130            .lock()
2131            .unwrap_or_else(std::sync::PoisonError::into_inner);
2132        // SAFETY: Test runs with mutex lock and restores variable
2133        unsafe {
2134            env::set_var("TERM_PROGRAM", "GNUstep_Terminal");
2135        }
2136        assert!(looks_like_gnustep());
2137        // SAFETY: Test restores environment variable
2138        unsafe {
2139            env::remove_var("TERM_PROGRAM");
2140        }
2141    }
2142
2143    #[crate::ctb_test]
2144    #[allow(
2145        unsafe_code,
2146        reason = "Modifying environment variable is unsafe in Rust 2024"
2147    )]
2148    fn test_looks_like_nextstep_or_openstep() {
2149        let _lock = ENV_TEST_MUTEX
2150            .lock()
2151            .unwrap_or_else(std::sync::PoisonError::into_inner);
2152        let original_path = env::var("PATH").ok();
2153        // SAFETY: Test runs with mutex lock and restores variable
2154        unsafe {
2155            env::set_var("PATH", "/usr/bin:/NextApps");
2156        }
2157        assert!(looks_like_nextstep_or_openstep());
2158        // SAFETY: Test restores environment variable
2159        unsafe {
2160            if let Some(orig) = original_path {
2161                env::set_var("PATH", orig);
2162            } else {
2163                env::remove_var("PATH");
2164            }
2165        }
2166    }
2167
2168    #[crate::ctb_test]
2169    #[allow(
2170        unsafe_code,
2171        reason = "Modifying environment variable is unsafe in Rust 2024"
2172    )]
2173    fn test_detect_identity_gnustep_and_nextstep() {
2174        let _lock = ENV_TEST_MUTEX
2175            .lock()
2176            .unwrap_or_else(std::sync::PoisonError::into_inner);
2177        let original_path = env::var("PATH").ok();
2178        let original_term = env::var("TERM_PROGRAM").ok();
2179        // SAFETY: Test runs with mutex lock and restores variables
2180        unsafe {
2181            env::set_var("PATH", "/usr/bin:/NextApps");
2182            env::set_var("TERM_PROGRAM", "GNUstep_Terminal");
2183        }
2184        let ident = detect_identity();
2185        assert!(ident.userspace.contains(&FormatId::GnuStep));
2186        // Nextstep/openstep is an OS, so it does not appear in userspace:
2187        assert!(!ident.userspace.contains(&FormatId::NextStep));
2188        assert!(looks_like_nextstep_or_openstep());
2189        // SAFETY: Test restores environment variables
2190        unsafe {
2191            if let Some(orig) = original_path {
2192                env::set_var("PATH", orig);
2193            } else {
2194                env::remove_var("PATH");
2195            }
2196            if let Some(orig) = original_term {
2197                env::set_var("TERM_PROGRAM", orig);
2198            } else {
2199                env::remove_var("TERM_PROGRAM");
2200            }
2201        }
2202    }
2203
2204    #[crate::ctb_test]
2205    fn test_environment_source_preserving_edit() -> Result<()> {
2206        use ctb_formats_dcstring::{DcChar, DcMixedFields, DcMstring};
2207        let original = EnvDescription {
2208            os: "original".to_owned(),
2209            ..EnvDescription::default()
2210        };
2211        let updated = EnvDescription {
2212            os: "revised".to_owned(),
2213            ..EnvDescription::default()
2214        };
2215        let mut source = DcMstring::new();
2216        source.push_char(DcChar::from_short(340));
2217        original.encode_dc_field("os", &mut source)?;
2218        let suffix_start = source.len();
2219        source.push_char(DcChar::from_short(600));
2220        source
2221            .push_binary_with_sha256(b"future environment field")
2222            .unwrap();
2223        source.push_char(DcChar::from_short(341));
2224        let view = source.inspect::<EnvDescription>();
2225        assert!(view.value().is_none());
2226        assert!(view.diagnostic().is_some());
2227        let revised = view.replace_field("os", &updated)?;
2228        let revised_view = revised.inspect::<EnvDescription>();
2229        let revised_field = revised_view
2230            .fields()
2231            .first()
2232            .context("Missing revised environment field")?;
2233        assert_eq!(
2234            revised.as_bytes().get(revised_field.range().end..),
2235            source.as_bytes().get(suffix_start..)
2236        );
2237        assert_eq!(view.source_bytes(), source.as_bytes());
2238        let text = source.to_dc_string()?;
2239        let revised = text
2240            .inspect::<EnvDescription>()
2241            .replace_field("os", &updated)?;
2242        assert!(revised.inspect::<EnvDescription>().diagnostic().is_some());
2243        Ok(())
2244    }
2245
2246    #[crate::ctb_test]
2247    fn test_env_description_roundtrip() -> Result<()> {
2248        let env = EnvDescription {
2249            os: "linux".to_string(),
2250            usize_width: 64,
2251            ctb_version: "0.1.49".to_string(),
2252            cwd: Some(PathBuf::from("/workspace")),
2253            local_ips: vec![
2254                IpAddr::V4(std::net::Ipv4Addr::LOCALHOST),
2255                IpAddr::V6(std::net::Ipv6Addr::LOCALHOST),
2256            ],
2257            public_ips: vec![
2258                IpAddr::V4(std::net::Ipv4Addr::new(8, 8, 8, 8)),
2259                IpAddr::V6(std::net::Ipv6Addr::new(
2260                    0x2001, 0x4860, 0x4860, 0, 0, 0, 0, 0x8888,
2261                )),
2262            ],
2263            system_time_resolution_nanos: Some(1),
2264            server_system_time_offset_nanos: Some(-1000),
2265            is_release_build: true,
2266            is_debug_build: false,
2267            is_cargo_target_binary: true,
2268            is_in_test: true,
2269            is_branded_build: true,
2270            is_official_signed_build: false,
2271            is_cli_lightweight: false,
2272            is_workspace: true,
2273            is_workspace_main_process: true,
2274            is_service_subprocess: false,
2275            is_official_public_website: false,
2276            is_public_website: false,
2277            is_local: true,
2278            kernel_version: Some("6.12.11-amd64".to_string()),
2279            supported_formats: vec![
2280                FormatId::GnuLinux,
2281                FormatId::Linux,
2282                FormatId::amd64,
2283                FormatId::Unix,
2284            ],
2285            ..Default::default()
2286        };
2287        ctb_formats_dcstring::assert_dc_roundtrip(&env)?;
2288        assert_eq!(env.os_family(), OsFamily::Linux);
2289        assert_eq!(env.identity().os, Some(FormatId::GnuLinux));
2290        Ok(())
2291    }
2292
2293    #[crate::ctb_test]
2294    fn test_environment_identity_and_capabilities() {
2295        let _lock = ENV_TEST_MUTEX
2296            .lock()
2297            .unwrap_or_else(std::sync::PoisonError::into_inner);
2298        let ident = identity();
2299        let caps = capabilities();
2300        let formats = all_format_ids();
2301
2302        assert!(!formats.is_empty());
2303        if let Some(os) = ident.os {
2304            assert!(formats.contains(&os));
2305        }
2306        if let Some(kernel) = ident.kernel {
2307            assert!(formats.contains(&kernel));
2308        }
2309        if let Some(arch) = ident.architecture {
2310            assert!(formats.contains(&arch));
2311        }
2312
2313        for family in &ident.os_families {
2314            assert!(formats.contains(family));
2315        }
2316        for u in &ident.userspace {
2317            assert!(formats.contains(u));
2318        }
2319        if let Some(libc) = ident.libc {
2320            assert!(formats.contains(&libc));
2321        }
2322
2323        if is_linux() {
2324            assert!(has_format(FormatId::Linux));
2325            assert!(has_format(FormatId::Unix));
2326            assert!(!has_format(FormatId::Windows));
2327            assert!(!has_format(FormatId::WinNtKernel));
2328            assert!(!has_format(FormatId::MacOsDarwin));
2329        }
2330
2331        if is_windows() {
2332            assert!(has_format(FormatId::Windows));
2333            assert!(has_format(FormatId::WinNtKernel));
2334            assert!(!has_format(FormatId::Linux));
2335            assert!(!has_format(FormatId::MacOsDarwin));
2336        }
2337
2338        if is_darwin() {
2339            assert!(has_format(FormatId::Darwin));
2340            assert!(has_format(FormatId::Unix));
2341            assert!(has_format(FormatId::MacOsDarwin));
2342            assert!(!has_format(FormatId::Linux));
2343            assert!(!has_format(FormatId::Windows));
2344        }
2345
2346        // Capabilities consistency
2347        if let Some(ds) = caps.display_server {
2348            assert!(formats.contains(&ds));
2349        }
2350        for cap in &caps.device_caps {
2351            assert!(formats.contains(cap));
2352        }
2353        for mode in &caps.render_modes {
2354            assert!(formats.contains(mode));
2355        }
2356        for term_cap in &caps.terminal_caps {
2357            assert!(formats.contains(term_cap));
2358        }
2359
2360        // Summary string format test
2361        let sum = summary();
2362        assert!(!sum.is_empty());
2363        assert!(sum.contains('[') && sum.contains(']'));
2364    }
2365
2366    #[crate::ctb_test]
2367    fn test_capture_quick_uses_detection() {
2368        let _lock = ENV_TEST_MUTEX
2369            .lock()
2370            .unwrap_or_else(std::sync::PoisonError::into_inner);
2371        reset_quick_env_cache();
2372        let desc = EnvDescription::capture_quick();
2373        let ident = desc.identity();
2374        let caps = desc.capabilities();
2375
2376        assert_eq!(desc.is_gui(), is_gui());
2377        assert_eq!(desc.is_linux(), is_linux());
2378        assert_eq!(desc.is_windows(), is_windows());
2379        assert_eq!(desc.is_unix(), is_unix());
2380        assert_eq!(desc.is_darwin(), is_darwin());
2381        assert_eq!(desc.is_bsd(), is_bsd());
2382        assert_eq!(
2383            desc.has_format(FormatId::RasterDisplay),
2384            caps.device_caps.contains(&FormatId::RasterDisplay)
2385        );
2386        assert_eq!(
2387            desc.has_format(FormatId::RenderModeInteractive),
2388            caps.render_modes.contains(&FormatId::RenderModeInteractive)
2389        );
2390        if let Some(os) = ident.os {
2391            assert!(desc.is_os_compatible(os));
2392        }
2393        if let Some(kernel) = ident.kernel {
2394            assert!(desc.is_os_compatible(kernel));
2395        }
2396    }
2397
2398    #[crate::ctb_test]
2399    fn test_decode_environment_unconfirmed() {
2400        let (ident, caps) =
2401            detection::decode_environment_from_formats(&[], None);
2402        assert_eq!(ident.os, None);
2403        assert_eq!(ident.kernel, None);
2404        assert_eq!(ident.libc, None);
2405        assert_eq!(ident.architecture, None);
2406        assert!(ident.userspace.is_empty());
2407        assert!(ident.os_families.is_empty());
2408        assert_eq!(caps.display_server, None);
2409        let summary = detection::format_environment_summary(&ident, &caps);
2410        assert_eq!(summary, "Unknown OS [Headless]");
2411    }
2412
2413    #[crate::ctb_test]
2414    fn test_maybe_cache_clock_offset_and_zero_timeout() {
2415        let _lock = ENV_TEST_MUTEX
2416            .lock()
2417            .unwrap_or_else(std::sync::PoisonError::into_inner);
2418        let prev = CACHED_SERVER_TIME_OFFSET_NANOS.write().unwrap().take();
2419
2420        maybe_cache_clock_offset(1_000_000_000, 1_000_000_100, 1_000_000_300);
2421        let cached = cached_server_system_time_offset_nanos().expect(
2422            "cached clock offset should be returned without network query",
2423        );
2424        assert_eq!(cached, 200);
2425
2426        *CACHED_SERVER_TIME_OFFSET_NANOS.write().unwrap() = None;
2427        let _override =
2428            ctb_utilities::https::crlite::set_test_download_override(|_url| {
2429                anyhow::bail!("simulated offline")
2430            });
2431        let err = query_ip_endpoint_with_timeout(
2432            "https://ipv4.collectivetoolbox.com/api/ip",
2433            Duration::ZERO,
2434        )
2435        .expect_err("zero timeout budget must fail immediately");
2436        assert!(
2437            err.to_string().contains("timed out"),
2438            "Expected timeout error, got: {err:#}"
2439        );
2440
2441        *CACHED_SERVER_TIME_OFFSET_NANOS.write().unwrap() = prev;
2442    }
2443}