Skip to main content

subc_daemon/
bootstrap.rs

1use std::{
2    collections::BTreeMap,
3    env,
4    error::Error,
5    ffi::OsString,
6    fmt, fs, io,
7    net::{IpAddr, Ipv4Addr, Ipv6Addr, SocketAddr},
8    path::{Path, PathBuf},
9    process,
10    time::Duration,
11};
12
13use fs4::{FileExt, TryLockError};
14use subc_protocol::PROTOCOL_VERSION;
15pub use subc_transport::user_connection_token;
16use subc_transport::{
17    authenticate_client, connection_file, generate_daemon_id, generate_key,
18    write_atomic_with_local_endpoint, AuthError, ConnectionFileError, ConnectionInfo, Endpoint,
19    LocalEndpoint, SCHEMA_VERSION,
20};
21use tokio::{
22    net::{TcpListener, TcpStream},
23    task::{JoinError, JoinHandle},
24    time::{sleep, timeout},
25};
26use tracing::{error, info, warn};
27
28use crate::{
29    daemon_config::{self, ConfiguredModule, DaemonConfigError},
30    local_listener::{self, BoundLocalListener, LocalListenerConfig},
31    server::{serve_local_listener, serve_shared_listeners, ServerAuth, ServerError},
32    supervise::HealthConfig,
33    ConnectedClients, ControlHandler, DaemonSelfWatchdog, DaemonSelfWatchdogConfig,
34    ForwardingTable, Registry, RestartPolicy, Router, Supervisor, SupervisorHandle,
35    SupervisorProcessLiveness,
36};
37use std::sync::Arc;
38
39#[cfg(any(target_os = "linux", target_os = "macos"))]
40use crate::control::upgrade_in_place::UpgradeStartup;
41
42#[cfg(any(target_os = "linux", target_os = "macos"))]
43mod resume;
44#[cfg(windows)]
45mod windows_connection_copy;
46#[cfg(any(target_os = "linux", target_os = "macos"))]
47pub use resume::{ResumeBootstrap, HANDOVER_VERSIONS};
48#[cfg(not(any(target_os = "linux", target_os = "macos")))]
49pub const HANDOVER_VERSIONS: &[u32] = &[];
50
51pub const DEFAULT_SUBC_PORT: u16 = 8757;
52pub const SUBC_PORT_ENV: &str = "SUBC_PORT";
53use subc_transport::CONNECTION_FILE_NAME;
54const DAEMON_VERSION: &str = env!("CARGO_PKG_VERSION");
55const CONNECT_TIMEOUT: Duration = Duration::from_secs(2);
56const PROBE_AUTH_DEADLINE: Duration = Duration::from_secs(2);
57const START_LOCK_RETRIES: usize = 40;
58const START_LOCK_RETRY_DELAY: Duration = Duration::from_millis(25);
59
60#[derive(Debug, Clone, Copy, PartialEq, Eq)]
61pub enum ConnectionFileSource {
62    XdgRuntimeDir,
63    DaemonRunDir,
64    TempDirFallback,
65    Explicit,
66}
67
68impl ConnectionFileSource {
69    fn reason(self) -> &'static str {
70        match self {
71            Self::XdgRuntimeDir => "XDG_RUNTIME_DIR set and non-empty",
72            Self::DaemonRunDir => "XDG_RUNTIME_DIR unset or empty",
73            Self::TempDirFallback if cfg!(unix) => {
74                "XDG_RUNTIME_DIR unset or empty and daemon run directory could not be resolved"
75            }
76            Self::TempDirFallback => "XDG_RUNTIME_DIR unset or empty",
77            Self::Explicit => "configured path",
78        }
79    }
80}
81
82impl fmt::Display for ConnectionFileSource {
83    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
84        formatter.write_str(match self {
85            Self::XdgRuntimeDir => "xdg_runtime_dir",
86            Self::DaemonRunDir => "daemon_run_dir",
87            Self::TempDirFallback => "temp_dir_fallback",
88            Self::Explicit => "explicit",
89        })
90    }
91}
92
93/// Runtime bootstrap configuration. Production uses the default fixed port and
94/// optional daemon-config override; tests pass port 0 to let the OS assign a free
95/// loopback port and discover it from the connection file.
96#[derive(Debug, Clone, Default)]
97struct AdmissionFactsConfig {
98    carrier_module_id: Option<String>,
99    targets: Option<Vec<String>>,
100}
101
102/// Controls where module cgroups are prepared.
103///
104/// In-process daemons default to [`Self::Disabled`] so they never derive a
105/// production location from the host process. The shipped daemon explicitly uses
106/// [`Self::Current`]. The `ck-subc` binary accepts
107/// `SUBC_CGROUP_PLACEMENT=disabled` for isolated test processes; an unset
108/// variable retains `Current`, and every other value is rejected at startup.
109/// Tests that exercise placement can own a [`Self::Root`].
110#[derive(Debug, Clone, Default, PartialEq, Eq)]
111pub enum CgroupPlacementConfig {
112    #[default]
113    Disabled,
114    Current,
115    Root(PathBuf),
116}
117
118#[derive(Debug, Clone)]
119pub struct BootstrapConfig {
120    #[cfg(feature = "test-support")]
121    shutdown_intent_window: Duration,
122    pub operator_queue_wait: Duration,
123    pub operator_timeout: Duration,
124    pub operator_stuck_grace: Duration,
125    #[cfg(feature = "test-support")]
126    pub operator_script: Option<PathBuf>,
127    #[cfg(feature = "test-support")]
128    pub operator_events: Option<PathBuf>,
129    pub connection_file_path: PathBuf,
130    pub port: u16,
131    pub daemon_ver: String,
132    configured_modules: Vec<ConfiguredModule>,
133    storage_config: Option<daemon_config::StorageConfig>,
134    admission_facts: AdmissionFactsConfig,
135    /// Module ids whose scopes may carry the attributes that grant authority.
136    scope_authority_owners: Vec<String>,
137    flow_scope_authority_owners: Vec<String>,
138    federated_scope_owner: String,
139    privileged_operator_prompt: daemon_config::PrivilegedOperatorPrompt,
140    activity_config: daemon_config::ActivityConfig,
141    daemon_config_path: Option<PathBuf>,
142    /// Only a service-definition argument may name this authority store. An
143    /// embedded daemon with no explicit root never opens an installation store.
144    config_store_root: Option<PathBuf>,
145    defer_file_load: bool,
146    // Test-only stand-in for an additional field supplied by the file loader.
147    // Authority selection must carry it without knowing its name.
148    #[cfg(test)]
149    file_derived_test_probe: Option<Vec<String>>,
150    #[cfg(all(test, feature = "test-support"))]
151    test_store_factory:
152        Option<fn(crate::config_store::StoreRoot) -> crate::config_store::ConfigStore>,
153    #[cfg(all(test, feature = "test-support"))]
154    test_control: Option<fn(ControlHandler) -> ControlHandler>,
155    #[cfg(all(test, feature = "test-support"))]
156    test_listener_bind: Option<fn(&mut BootstrapConfig)>,
157    configured_port: Option<u16>,
158    /// Daemon-wide route.bind relay budget in milliseconds (the fallback for
159    /// any module without a per-module override). `None` = built-in default
160    /// (12s — see `control::DEFAULT_ROUTE_BIND_RELAY_TIMEOUT`).
161    route_bind_relay_default_ms: Option<u64>,
162    reserved_capabilities: BTreeMap<String, String>,
163    watchdog_config: DaemonSelfWatchdogConfig,
164    connection_file_source: ConnectionFileSource,
165    #[cfg(all(test, windows))]
166    profile_override: Option<PathBuf>,
167    /// Where module cgroups are prepared. Disabled unless a caller explicitly
168    /// opts in, because `Current` derives a host location from `/proc/self/cgroup`.
169    cgroup_placement: CgroupPlacementConfig,
170    /// Directory the supervisor writes per-module stdout/stderr capture files
171    /// into. `None` disables capture; the shipped binary supplies its real run
172    /// directory explicitly.
173    capture_logs_dir: Option<PathBuf>,
174    /// File the supervisor appends every module's terminal exits to, so exit
175    /// history survives a daemon restart. `None` keeps terminal history in
176    /// memory only (each module's ring). Absent by default for the same reason
177    /// as `capture_logs_dir`: an in-process daemon booted by a test must not
178    /// append its exits to the operator's real `terminals.jsonl`, where they
179    /// would show up in `ck module terminals`. The shipped binary supplies
180    /// `<run dir>/terminals.jsonl` explicitly.
181    terminal_journal_path: Option<PathBuf>,
182    /// Where the machine id is read from, or minted into when absent. `None`
183    /// serves no machine id. Absent by default for the same reason as
184    /// `capture_logs_dir`: an in-process daemon booted by a test must never
185    /// derive the operator's real data home and mint into it. The shipped binary
186    /// supplies `<data home>/cortexkit/machine-id` explicitly.
187    machine_id_path: Option<PathBuf>,
188
189    /// Where this daemon's same-user local listener lives (a Unix-domain socket
190    /// on macOS and Linux; nothing on Windows, where the pipe name is minted per
191    /// start). The default serves no local endpoint, so an in-process daemon
192    /// never touches the operator's run directory. The shipped binary names its
193    /// run directory; [`BootstrapConfig::with_local_listener_socket_dir`] names
194    /// any other, and an in-process daemon that wants the endpoint names one.
195    local_listener: LocalListenerConfig,
196    /// The live-children record: every supervised process this daemon has
197    /// running, kept so the next daemon can end the ones a crash left behind.
198    /// At startup, before any module is spawned, the previous daemon's record
199    /// here is swept. `None` keeps no record and sweeps nothing, for the same
200    /// reason as `capture_logs_dir`: an in-process daemon booted by a test
201    /// must never signal processes listed in the operator's real run
202    /// directory. The shipped binary supplies `<run dir>/live-children.json`.
203    live_children_path: Option<PathBuf>,
204    privacy_trampoline: Option<PathBuf>,
205    #[cfg(any(target_os = "linux", target_os = "macos"))]
206    upgrade_binary: Option<UpgradeBinary>,
207}
208
209#[cfg(any(target_os = "linux", target_os = "macos"))]
210#[derive(Debug, Clone)]
211struct UpgradeBinary {
212    image: Result<Arc<fs::File>, Arc<io::Error>>,
213    core_version: String,
214    build_git_sha: Option<String>,
215    #[cfg(feature = "test-support")]
216    test_hooks: bool,
217}
218
219impl BootstrapConfig {
220    /// Register the service executable's build identity and an image handle
221    /// opened at process entry, before an upgrade can replace its pathname.
222    #[cfg(any(target_os = "linux", target_os = "macos"))]
223    pub fn with_upgrade_binary(
224        mut self,
225        image: io::Result<fs::File>,
226        core_version: &str,
227        build_git_sha: Option<&str>,
228    ) -> Self {
229        self.upgrade_binary = Some(UpgradeBinary {
230            image: image.map(Arc::new).map_err(Arc::new),
231            core_version: core_version.into(),
232            build_git_sha: build_git_sha.map(str::to_owned),
233            #[cfg(feature = "test-support")]
234            test_hooks: false,
235        });
236        self
237    }
238
239    #[doc(hidden)]
240    #[cfg(all(
241        feature = "test-support",
242        any(target_os = "linux", target_os = "macos")
243    ))]
244    pub fn with_upgrade_test_hooks(mut self) -> Self {
245        if let Some(binary) = &mut self.upgrade_binary {
246            binary.test_hooks = true;
247        }
248        self
249    }
250    /// The service-configured store root, if any.
251    #[cfg(any(target_os = "linux", target_os = "macos"))]
252    pub(crate) fn config_store_root(&self) -> Option<&Path> {
253        self.config_store_root.as_deref()
254    }
255
256    pub fn with_config_store_root(mut self, root: PathBuf) -> Result<Self, BootstrapError> {
257        crate::config_store::StoreRoot::from_service_definition(root.clone())
258            .map_err(|e| BootstrapError::ConfigStore(e.to_string()))?;
259        let parent = root.parent().ok_or_else(|| {
260            BootstrapError::ConfigStore("config store root needs a parent directory".into())
261        })?;
262        std::fs::read_dir(parent).map_err(|e| {
263            BootstrapError::ConfigStore(format!("config store parent is unreadable: {e}"))
264        })?;
265        self.config_store_root = Some(root);
266        Ok(self)
267    }
268    /// Shorten restart intent validity in daemon integration fixtures.
269    #[cfg(feature = "test-support")]
270    pub fn with_shutdown_intent_window(mut self, window: Duration) -> Self {
271        self.shutdown_intent_window = window;
272        self
273    }
274
275    pub fn new(connection_file_path: impl Into<PathBuf>, port: u16) -> Self {
276        Self {
277            #[cfg(feature = "test-support")]
278            shutdown_intent_window: Duration::from_secs(120),
279            connection_file_path: connection_file_path.into(),
280            operator_queue_wait: Duration::from_secs(150),
281            operator_timeout: Duration::from_secs(120),
282            operator_stuck_grace: Duration::from_secs(10),
283            #[cfg(feature = "test-support")]
284            operator_script: None,
285            #[cfg(feature = "test-support")]
286            operator_events: None,
287            port,
288            daemon_ver: DAEMON_VERSION.to_owned(),
289            configured_modules: Vec::new(),
290            storage_config: None,
291            admission_facts: AdmissionFactsConfig::default(),
292            scope_authority_owners: daemon_config::default_scope_authority_owners(),
293            flow_scope_authority_owners: Vec::new(),
294            federated_scope_owner: daemon_config::default_federated_scope_owner(),
295            privileged_operator_prompt: daemon_config::PrivilegedOperatorPrompt::default(),
296            activity_config: daemon_config::ActivityConfig::default(),
297            daemon_config_path: None,
298            config_store_root: None,
299            defer_file_load: false,
300            #[cfg(test)]
301            file_derived_test_probe: None,
302            #[cfg(all(test, feature = "test-support"))]
303            test_store_factory: None,
304            #[cfg(all(test, feature = "test-support"))]
305            test_control: None,
306            #[cfg(all(test, feature = "test-support"))]
307            test_listener_bind: None,
308            configured_port: None,
309            route_bind_relay_default_ms: None,
310            reserved_capabilities: BTreeMap::new(),
311            watchdog_config: DaemonSelfWatchdogConfig::default(),
312            connection_file_source: ConnectionFileSource::Explicit,
313            #[cfg(all(test, windows))]
314            profile_override: None,
315            cgroup_placement: CgroupPlacementConfig::default(),
316            capture_logs_dir: None,
317            terminal_journal_path: None,
318            machine_id_path: None,
319            local_listener: LocalListenerConfig { socket_dir: None },
320            live_children_path: None,
321            privacy_trampoline: None,
322            #[cfg(any(target_os = "linux", target_os = "macos"))]
323            upgrade_binary: None,
324        }
325    }
326
327    /// Keep the local listener's socket in `dir`. Embedding daemons and tests
328    /// pass a path inside their own fixture tree.
329    pub fn with_local_listener_socket_dir(mut self, dir: impl Into<PathBuf>) -> Self {
330        self.local_listener = LocalListenerConfig::in_socket_dir(dir);
331        self
332    }
333
334    /// Set where the local listener lives, as [`LocalListenerConfig`] describes.
335    pub fn with_local_listener(mut self, config: LocalListenerConfig) -> Self {
336        self.local_listener = config;
337        self
338    }
339
340    /// Keep the live-children record at `path`, and at startup end the
341    /// processes a previous daemon recorded there that are still running.
342    /// Embedding daemons and tests pass a path inside their own fixture tree.
343    pub fn with_live_children_record(mut self, path: impl Into<PathBuf>) -> Self {
344        self.live_children_path = Some(path.into());
345        self
346    }
347
348    /// macOS module launches require an explicit executable implementing the
349    /// subc-os trampoline entry point. Other systems ignore this setting.
350    pub fn with_privacy_trampoline(mut self, path: impl Into<PathBuf>) -> Self {
351        self.privacy_trampoline = Some(path.into());
352        self
353    }
354
355    /// Serve the machine id stored at `path`, minting it there at startup when
356    /// the file is absent. Embedding daemons and tests pass a path inside their
357    /// own fixture tree.
358    pub fn with_machine_id_path(mut self, path: impl Into<PathBuf>) -> Self {
359        self.machine_id_path = Some(path.into());
360        self
361    }
362
363    /// Selects module cgroup placement. The default is disabled.
364    pub fn with_cgroup_placement(mut self, placement: CgroupPlacementConfig) -> Self {
365        self.cgroup_placement = placement;
366        self
367    }
368
369    /// Redirects per-module stdout/stderr capture files out of the real run
370    /// directory. Tests that start an in-process daemon must call this with a
371    /// path inside their fixture tree.
372    pub fn with_capture_logs_dir(mut self, dir: impl Into<PathBuf>) -> Self {
373        self.capture_logs_dir = Some(dir.into());
374        self
375    }
376
377    /// Redirects the daemon-private journal, allowing embedded daemons and tests
378    /// to keep their observations out of the operator's live run directory.
379    pub fn with_terminal_journal_path(mut self, path: impl Into<PathBuf>) -> Self {
380        self.terminal_journal_path = Some(path.into());
381        self
382    }
383
384    pub fn from_env() -> Result<Self, BootstrapError> {
385        Self::from_env_with_daemon_config_path(daemon_config::default_config_path())
386    }
387
388    /// The SHIPPED BINARY's config, which is the only caller that should capture
389    /// child output into the operator's real run directory.
390    ///
391    /// Kept separate from `from_env` deliberately: see `capture_logs_dir` and
392    /// `terminal_journal_path` on this struct for why an absent value must mean
393    /// NO CAPTURE and NO JOURNAL rather than the operator's real run directory.
394    /// A run directory that cannot be resolved (a relative data home) refuses
395    /// startup instead of landing under the working directory.
396    pub fn from_env_for_daemon_binary() -> Result<Self, BootstrapError> {
397        let run_dir = daemon_config::daemon_run_dir().map_err(BootstrapError::RunDir)?;
398        let machine_id_path =
399            crate::machine_id::default_machine_id_path().map_err(BootstrapError::MachineId)?;
400        // The service supplies its store root after constructing this value.
401        // Do not parse live files until that store has selected recovery mode.
402        let (connection_file, source) = connection_file_path_with_source(
403            env::var_os("XDG_RUNTIME_DIR"),
404            || Ok(run_dir.clone()),
405        );
406        let mut config = Self::new(connection_file, DEFAULT_SUBC_PORT)
407            .with_connection_file_source(source)
408            .with_daemon_config_source(daemon_config::default_config_path(), None)
409            .with_local_listener(LocalListenerConfig::in_socket_dir(&run_dir))
410            .with_capture_logs_dir(run_dir.join("logs"))
411            .with_terminal_journal_path(run_dir.join("terminals.jsonl"))
412            .with_live_children_record(crate::live_children::record_path(&run_dir))
413            .with_machine_id_path(machine_id_path);
414        config.defer_file_load = true;
415        #[cfg(feature = "test-support")]
416        let config = {
417            let mut config = config;
418            config.operator_script =
419                std::env::var_os("SUBC_TEST_OPERATOR_SCRIPT").map(PathBuf::from);
420            config.operator_events =
421                std::env::var_os("SUBC_TEST_OPERATOR_EVENTS").map(PathBuf::from);
422            for (name, value) in [
423                (
424                    "SUBC_TEST_OPERATOR_QUEUE_WAIT_MS",
425                    &mut config.operator_queue_wait,
426                ),
427                (
428                    "SUBC_TEST_OPERATOR_TIMEOUT_MS",
429                    &mut config.operator_timeout,
430                ),
431                (
432                    "SUBC_TEST_OPERATOR_STUCK_MS",
433                    &mut config.operator_stuck_grace,
434                ),
435            ] {
436                if let Ok(ms) = std::env::var(name) {
437                    if let Ok(ms) = ms.parse::<u64>() {
438                        *value = Duration::from_millis(ms);
439                    }
440                }
441            }
442            config
443        };
444        Ok(config)
445    }
446
447    /// Load live-file values for an unstamped embedder. If a store root is
448    /// attached later, these values are provisional and replaced at run time.
449    /// An invalid live file can still fail this eager constructor; the binary
450    /// defers loading until store authority has been selected instead.
451    pub fn from_env_with_daemon_config_path(
452        daemon_config_path: impl AsRef<Path>,
453    ) -> Result<Self, BootstrapError> {
454        let daemon_config_path = daemon_config_path.as_ref().to_path_buf();
455        let (daemon_config, activity_config) =
456            daemon_config::load_with_activity(&daemon_config_path)
457                .map_err(BootstrapError::DaemonConfig)?
458                .map(|(config, activity)| (Some(config), activity))
459                .unwrap_or_default();
460        let config_port = daemon_config.as_ref().and_then(|config| config.port);
461        let storage_config = daemon_config
462            .as_ref()
463            .and_then(|config| config.storage.clone());
464        let admission_facts_carrier_module_id = daemon_config
465            .as_ref()
466            .and_then(|config| config.admission_facts_carrier_module_id.clone());
467        let admission_facts_targets = daemon_config
468            .as_ref()
469            .and_then(|config| config.admission_facts_targets.clone());
470        let scope_authority_owners = daemon_config
471            .as_ref()
472            .map(|config| config.scope_authority_owners.clone())
473            .unwrap_or_else(daemon_config::default_scope_authority_owners);
474        let flow_scope_authority_owners = daemon_config
475            .as_ref()
476            .map(|config| config.flow_scope_authority_owners.clone())
477            .unwrap_or_default();
478        let federated_scope_owner = daemon_config
479            .as_ref()
480            .map(|config| config.federated_scope_owner.clone())
481            .unwrap_or_else(daemon_config::default_federated_scope_owner);
482        let privileged_operator_prompt = daemon_config
483            .as_ref()
484            .map(|config| config.privileged_operator_prompt)
485            .unwrap_or_default();
486        let route_bind_relay_default_ms = daemon_config
487            .as_ref()
488            .and_then(|config| config.route_bind_relay_timeout_ms);
489        let reserved_capabilities = daemon_config
490            .as_ref()
491            .map(|config| config.reserved_capabilities.clone())
492            .unwrap_or_default();
493        let configured_modules = daemon_config
494            .map(|config| config.modules)
495            .unwrap_or_default();
496
497        let port = match env::var(SUBC_PORT_ENV) {
498            Ok(raw) if !raw.trim().is_empty() => {
499                let port = raw
500                    .parse::<u16>()
501                    .map_err(|source| BootstrapError::InvalidPort { raw, source })?;
502                if let Some(config_port) = config_port {
503                    info!(
504                        env = SUBC_PORT_ENV,
505                        env_port = port,
506                        config_port,
507                        "SUBC_PORT overrides daemon config port"
508                    );
509                }
510                port
511            }
512            Ok(_) | Err(_) => config_port.unwrap_or(DEFAULT_SUBC_PORT),
513        };
514
515        let (connection_file_path, connection_file_source) = default_connection_file();
516        let config = Self::new(connection_file_path, port)
517            .with_configured_modules(configured_modules)
518            .with_storage_config(storage_config)
519            .with_admission_facts_config(admission_facts_carrier_module_id, admission_facts_targets)
520            .with_scope_authority_owners(scope_authority_owners)
521            .with_flow_scope_authority_owners(flow_scope_authority_owners)
522            .with_federated_scope_owner(federated_scope_owner)
523            .with_privileged_operator_prompt(privileged_operator_prompt)
524            .with_activity_config(activity_config)
525            .with_route_bind_relay_default_ms(route_bind_relay_default_ms)
526            .with_reserved_capabilities(reserved_capabilities)
527            .with_daemon_config_source(daemon_config_path, config_port)
528            .with_connection_file_source(connection_file_source);
529        #[cfg(test)]
530        let config = {
531            let mut config = config;
532            config.file_derived_test_probe = Some(config.scope_authority_owners.clone());
533            config
534        };
535        Ok(config)
536    }
537
538    /// Load live-file values unless a store root is already attached. Attaching
539    /// a root later makes eager values provisional: run time replaces them with
540    /// approved authority. An invalid live file can fail the eager constructor;
541    /// the binary's deferred path does not parse it before selecting authority.
542    pub fn with_daemon_config_path(
543        mut self,
544        daemon_config_path: impl AsRef<Path>,
545    ) -> Result<Self, BootstrapError> {
546        let daemon_config_path = daemon_config_path.as_ref().to_path_buf();
547        if self.config_store_root.is_some() {
548            self.defer_file_load = true;
549            return Ok(self.with_daemon_config_source(daemon_config_path, None));
550        }
551        let (daemon_config, activity_config) =
552            daemon_config::load_with_activity(&daemon_config_path)
553                .map_err(BootstrapError::DaemonConfig)?
554                .map(|(config, activity)| (Some(config), activity))
555                .unwrap_or_default();
556        let configured_port = daemon_config.as_ref().and_then(|config| config.port);
557        Ok(self
558            .with_parsed_daemon_config(daemon_config, activity_config)
559            .with_daemon_config_source(daemon_config_path, configured_port))
560    }
561
562    fn with_parsed_daemon_config(
563        self,
564        daemon_config: Option<daemon_config::DaemonConfig>,
565        activity_config: daemon_config::ActivityConfig,
566    ) -> Self {
567        let storage_config = daemon_config
568            .as_ref()
569            .and_then(|config| config.storage.clone());
570        let admission_facts_carrier_module_id = daemon_config
571            .as_ref()
572            .and_then(|config| config.admission_facts_carrier_module_id.clone());
573        let admission_facts_targets = daemon_config
574            .as_ref()
575            .and_then(|config| config.admission_facts_targets.clone());
576        let scope_authority_owners = daemon_config
577            .as_ref()
578            .map(|config| config.scope_authority_owners.clone())
579            .unwrap_or_else(daemon_config::default_scope_authority_owners);
580        let flow_scope_authority_owners = daemon_config
581            .as_ref()
582            .map(|config| config.flow_scope_authority_owners.clone())
583            .unwrap_or_default();
584        let federated_scope_owner = daemon_config
585            .as_ref()
586            .map(|config| config.federated_scope_owner.clone())
587            .unwrap_or_else(daemon_config::default_federated_scope_owner);
588        let privileged_operator_prompt = daemon_config
589            .as_ref()
590            .map(|config| config.privileged_operator_prompt)
591            .unwrap_or_default();
592        let route_bind_relay_default_ms = daemon_config
593            .as_ref()
594            .and_then(|config| config.route_bind_relay_timeout_ms);
595        let reserved_capabilities = daemon_config
596            .as_ref()
597            .map(|config| config.reserved_capabilities.clone())
598            .unwrap_or_default();
599        let configured_modules = daemon_config
600            .map(|config| config.modules)
601            .unwrap_or_default();
602        self.with_configured_modules(configured_modules)
603            .with_storage_config(storage_config)
604            .with_admission_facts_config(admission_facts_carrier_module_id, admission_facts_targets)
605            .with_scope_authority_owners(scope_authority_owners)
606            .with_flow_scope_authority_owners(flow_scope_authority_owners)
607            .with_federated_scope_owner(federated_scope_owner)
608            .with_privileged_operator_prompt(privileged_operator_prompt)
609            .with_activity_config(activity_config)
610            .with_route_bind_relay_default_ms(route_bind_relay_default_ms)
611            .with_reserved_capabilities(reserved_capabilities)
612    }
613
614    pub fn with_configured_modules(
615        mut self,
616        modules: impl IntoIterator<Item = ConfiguredModule>,
617    ) -> Self {
618        self.configured_modules = modules.into_iter().collect();
619        self.configured_modules
620            .sort_by(|left, right| left.module_id.cmp(&right.module_id));
621        self
622    }
623
624    pub fn with_storage_config(
625        mut self,
626        storage_config: Option<daemon_config::StorageConfig>,
627    ) -> Self {
628        self.storage_config = storage_config;
629        self
630    }
631
632    pub fn with_admission_facts_config(
633        mut self,
634        carrier_module_id: Option<String>,
635        targets: Option<Vec<String>>,
636    ) -> Self {
637        self.admission_facts = AdmissionFactsConfig {
638            carrier_module_id,
639            targets,
640        };
641        self
642    }
643
644    /// Set the module ids whose scopes may carry `agent_id` and `delegates`.
645    /// Absent from a config, this is `daemon_config::default_scope_authority_owners`.
646    pub fn with_scope_authority_owners(mut self, owners: Vec<String>) -> Self {
647        self.scope_authority_owners = owners;
648        self
649    }
650
651    /// Set the module ids whose head and ephemeral flow scopes may carry the
652    /// flow identity and its optional author agent id and delegation.
653    pub fn with_flow_scope_authority_owners(mut self, owners: Vec<String>) -> Self {
654        self.flow_scope_authority_owners = owners;
655        self
656    }
657
658    pub fn with_federated_scope_owner(mut self, owner: String) -> Self {
659        self.federated_scope_owner = owner;
660        self
661    }
662
663    /// Choose the privileged-operation policy for the daemon's entire lifetime.
664    pub fn with_privileged_operator_prompt(
665        mut self,
666        mode: daemon_config::PrivilegedOperatorPrompt,
667    ) -> Self {
668        self.privileged_operator_prompt = mode;
669        self
670    }
671
672    pub fn with_activity_config(mut self, config: daemon_config::ActivityConfig) -> Self {
673        self.activity_config = config;
674        self
675    }
676
677    /// Set the daemon-wide route.bind relay default (the fallback for any
678    /// module without a per-module override). `None` preserves the built-in
679    /// default (12s). `serve_bound_daemon` reads this at startup and threads
680    /// it into the control handler's daemon-wide field.
681    pub fn with_route_bind_relay_default_ms(mut self, ms: Option<u64>) -> Self {
682        self.route_bind_relay_default_ms = ms;
683        self
684    }
685
686    pub fn with_reserved_capabilities(
687        mut self,
688        reserved_capabilities: BTreeMap<String, String>,
689    ) -> Self {
690        self.reserved_capabilities = reserved_capabilities;
691        self
692    }
693
694    fn with_daemon_config_source(
695        mut self,
696        daemon_config_path: PathBuf,
697        configured_port: Option<u16>,
698    ) -> Self {
699        self.daemon_config_path = Some(daemon_config_path);
700        self.configured_port = configured_port;
701        self
702    }
703
704    fn with_connection_file_source(mut self, source: ConnectionFileSource) -> Self {
705        self.connection_file_source = source;
706        self
707    }
708
709    pub fn with_watchdog_config(mut self, watchdog_config: DaemonSelfWatchdogConfig) -> Self {
710        self.watchdog_config = watchdog_config;
711        self
712    }
713}
714
715/// Result of singleton discovery.
716// Built once per daemon start and immediately matched, so the size gap between
717// the variants costs nothing worth a box on the public shape.
718#[allow(clippy::large_enum_variant)]
719#[derive(Debug)]
720pub enum Outcome {
721    /// A live daemon authenticated from the connection file; this invocation should exit 0.
722    AlreadyRunning,
723    /// This process won the singleton race, owns bound loopback listener(s), and
724    /// has published a fresh connection file.
725    Bound(BoundDaemon),
726}
727
728#[derive(Debug)]
729pub struct BoundDaemon {
730    pub listeners: Vec<TcpListener>,
731    /// The same-user local listener, bound and not yet served. `None` when
732    /// binding it failed, in which case `local_endpoint` is `None` and
733    /// `local_endpoint_unavailable` says why.
734    pub local_listener: Option<BoundLocalListener>,
735    /// Why the daemon serves no local endpoint, when binding it failed. Reported
736    /// by `server.describe` so an operator can see it.
737    pub local_endpoint_unavailable: Option<String>,
738    /// What the connection file publishes under `local_endpoint`, so a client can
739    /// find the local listener without knowing how it was bound.
740    pub local_endpoint: Option<LocalEndpoint>,
741    pub connection_info: ConnectionInfo,
742    pub connection_file_path: PathBuf,
743    pub connection_file_source: ConnectionFileSource,
744    #[cfg(windows)]
745    connection_file_copy: Option<PathBuf>,
746    /// The machine id this daemon serves, established before any connection is
747    /// accepted. `None` when the config named no machine id path.
748    pub machine_id: Option<crate::machine_id::MachineId>,
749    /// Ownership of the run directory, held until the daemon exits so no other
750    /// daemon sweeps or writes this one's run state. `None` when the config
751    /// keeps no live-children record, and so has no run directory to own.
752    run_dir_lock: Option<crate::run_dir_lock::RunDirLock>,
753    /// The singleton start lock, kept when binding deferred publishing the
754    /// connection file. The service keeps this advisory lock until it exits or
755    /// passes the same locked descriptor to a replacement image. `None` when
756    /// the low-level binding API already wrote the connection file.
757    publication_lock: Option<StartLock>,
758}
759
760/// Resolve subc's per-user TCP connection-file path.
761///
762/// `$XDG_RUNTIME_DIR/subc-connection.json` is preferred because the runtime
763/// directory is already per-user on Unix desktops. Without it, Unix uses the
764/// daemon run directory so system temporary-file cleanup cannot remove the
765/// connection file. If that directory cannot be resolved, or on Windows with
766/// no runtime directory, the fallback is a per-user file in the system temp dir.
767pub fn connection_file_path() -> PathBuf {
768    default_connection_file().0
769}
770
771fn default_connection_file() -> (PathBuf, ConnectionFileSource) {
772    connection_file_path_with_source(
773        env::var_os("XDG_RUNTIME_DIR"),
774        daemon_config::daemon_run_dir,
775    )
776}
777
778fn connection_file_path_with_source(
779    runtime_dir: Option<OsString>,
780    resolve_run_dir: impl FnOnce() -> Result<PathBuf, daemon_config::DaemonRunDirError>,
781) -> (PathBuf, ConnectionFileSource) {
782    if let Some(runtime_dir) = runtime_dir.filter(|value| !value.is_empty()) {
783        return (
784            PathBuf::from(runtime_dir).join(CONNECTION_FILE_NAME),
785            ConnectionFileSource::XdgRuntimeDir,
786        );
787    }
788
789    #[cfg(unix)]
790    if let Ok(run_dir) = resolve_run_dir() {
791        return (
792            run_dir.join(CONNECTION_FILE_NAME),
793            ConnectionFileSource::DaemonRunDir,
794        );
795    }
796    #[cfg(not(unix))]
797    let _ = resolve_run_dir;
798
799    (
800        env::temp_dir().join(format!("subc-{}.connection.json", user_connection_token())),
801        ConnectionFileSource::TempDirFallback,
802    )
803}
804
805/// Resolve, claim, and serve the per-user daemon singleton.
806///
807/// A second invocation is successful: if a live daemon authenticates from the
808/// existing connection file, this returns `Ok(())` after logging and the caller
809/// exits with status 0.
810pub async fn run() -> Result<(), BootstrapError> {
811    // `run` is a binary entry point, so it opts into the production cgroup and
812    // child-log locations. In-process callers keep both features disabled by default.
813    run_with_config(
814        BootstrapConfig::from_env_for_daemon_binary()?
815            .with_cgroup_placement(CgroupPlacementConfig::Current),
816    )
817    .await
818}
819
820#[cfg(feature = "test-support")]
821mod config_test_seam {
822    #[cfg(not(test))]
823    use super::BootstrapError;
824
825    pub(super) fn enabled() -> bool {
826        std::env::var_os("SUBC_TEST_CONFIG_GATE").as_deref() == Some(std::ffi::OsStr::new("1"))
827            && std::env::current_exe().ok().is_some_and(|path| {
828                path.file_name()
829                    .is_some_and(|name| name.to_string_lossy().starts_with("ckdev-"))
830            })
831    }
832
833    #[cfg(not(test))]
834    pub(super) fn open(
835        root: crate::config_store::StoreRoot,
836    ) -> Result<crate::config_store::ConfigStore, BootstrapError> {
837        if !enabled() {
838            return Ok(crate::config_store::ConfigStore::open(root));
839        }
840        // The service's isolated store root contains every seam artifact, so a
841        // test cannot accidentally open the operator's keychain or anchor.
842        crate::config_store::testing::TestSupport::new(
843            root.path().to_path_buf(),
844            Some(root.path().join("test-key")),
845        )
846        .and_then(|hooks| {
847            hooks
848                .with_anchor_failure_file(root.path().join("fail-anchor"))
849                .open()
850        })
851        .map_err(|error| BootstrapError::ConfigStore(error.to_string()))
852    }
853}
854
855/// Serve a daemon from an explicit config. This is the entry point the twelve
856/// sibling repos use to boot an in-process daemon in their integration tests.
857///
858/// # THIS INSTALLS NO TRACING SUBSCRIBER, SO THE DAEMON IS SILENT BY DEFAULT
859///
860/// The daemon's own diagnostics go through `tracing`, and `tracing` DISCARDS
861/// every event when no subscriber is installed. The shipped binary installs one
862/// in `main` (`init_tracing`); this function deliberately does not, because a
863/// library that installs a global subscriber fights with whatever the host
864/// process already set up.
865///
866/// The consequence for a test harness is not "less verbose": it is that the
867/// daemon has NOTHING TO SAY about any failure, and a missing instrument reads
868/// exactly like a clean one. PLEX found this on 2026-09-18 while trying to
869/// capture daemon logs beside an intermittent bind failure, and discovered the
870/// daemon had been silent in every conformance run that repo had ever done --
871/// so the one client-side error string was all the evidence that could exist,
872/// and they had spent a real investigation on a failure whose second source was
873/// never being recorded.
874///
875/// Install one in the harness before calling this, and assert it did something
876/// (they measured 236 daemon lines with the subscriber installed, 0 with the
877/// call commented out) -- otherwise the fix is itself unverified.
878pub async fn run_with_config(config: BootstrapConfig) -> Result<(), BootstrapError> {
879    run_with_config_inner(
880        config,
881        #[cfg(any(target_os = "linux", target_os = "macos"))]
882        None,
883    )
884    .await
885}
886
887async fn run_with_config_inner(
888    config: BootstrapConfig,
889    #[cfg(any(target_os = "linux", target_os = "macos"))] inherited: Option<resume::Inherited>,
890) -> Result<(), BootstrapError> {
891    // A resumed upgrade starts a new daemon image, even though exec keeps the pid.
892    let daemon_start_clock = crate::clock::StartClock::capture();
893    #[cfg(any(target_os = "linux", target_os = "macos"))]
894    let (inherited_start, inherited_run, inherited_store, inherited_tcp, resume) = inherited
895        .map(|boot| {
896            (
897                Some(boot.start),
898                Some(boot.run),
899                boot.store,
900                boot.tcp_listeners,
901                Some(boot.resume),
902            )
903        })
904        .unwrap_or_default();
905    #[cfg(not(any(target_os = "linux", target_os = "macos")))]
906    let (inherited_start, inherited_run, inherited_store) = (None, None, None);
907    let start_lock = match inherited_start {
908        Some(lock) => lock,
909        None => {
910            let Some(lock) = singleton_start_lock(&config).await? else {
911                info!("subc daemon already running");
912                return Ok(());
913            };
914            lock
915        }
916    };
917    let (config, opened_store, start_lock) = tokio::task::spawn_blocking(move || {
918        let mut opened_store = config
919            .config_store_root
920            .as_ref()
921            .map(|root| {
922                let (root, lock) = match inherited_store {
923                    Some(inherited) => inherited,
924                    None => crate::config_store::StoreWriterLock::acquire(root)
925                        .map_err(|e| BootstrapError::ConfigStore(e.to_string()))?,
926                };
927                #[cfg(all(test, feature = "test-support"))]
928                let store = if let Some(factory) = config.test_store_factory {
929                    crate::config_store::testing::TestSupport::new(root.path().to_path_buf(), None)
930                        .map_err(|e| BootstrapError::ConfigStore(e.to_string()))?;
931                    factory(root)
932                } else {
933                    crate::config_store::ConfigStore::open(root)
934                };
935                #[cfg(all(feature = "test-support", not(test)))]
936                let store = config_test_seam::open(root)?;
937                #[cfg(not(feature = "test-support"))]
938                let store = crate::config_store::ConfigStore::open(root);
939                Ok::<_, BootstrapError>((store, lock))
940            })
941            .transpose()?;
942        let config =
943            load_bootstrap_authority(config, opened_store.as_mut().map(|(store, _)| store))?;
944        #[cfg(all(test, feature = "test-support"))]
945        let config = {
946            let mut config = config;
947            if let Some(bind) = config.test_listener_bind {
948                // Tests observe authority's port selection but change only the
949                // bind, so they never take a running daemon's production port.
950                bind(&mut config);
951            }
952            config
953        };
954        Ok::<_, BootstrapError>((config, opened_store, start_lock))
955    })
956    .await
957    .map_err(|e| BootstrapError::ConfigStore(e.to_string()))??;
958    #[cfg(feature = "test-support")]
959    let shutdown_intent_window = config.shutdown_intent_window;
960    let forwarding = Arc::new(ForwardingTable::default());
961    forwarding.operator_confirms().configure_bootstrap(&config);
962    let configured_modules = config.configured_modules.clone();
963    let storage_config = config.storage_config.clone();
964    let admission_facts = config.admission_facts.clone();
965    let scope_authority_owners = config.scope_authority_owners.clone();
966    let flow_scope_authority_owners = config.flow_scope_authority_owners.clone();
967    let federated_scope_owner = config.federated_scope_owner.clone();
968    let privileged_operator_prompt = config.privileged_operator_prompt;
969    let activity_config = config.activity_config;
970    let daemon_config_path = config.daemon_config_path.clone();
971    let configured_port = config.configured_port;
972    let route_bind_relay_default_ms = config.route_bind_relay_default_ms;
973    let reserved_capabilities = config.reserved_capabilities.clone();
974    let watchdog_config = config.watchdog_config.clone();
975    let cgroup_placement_config = config.cgroup_placement.clone();
976    let capture_logs_dir = config.capture_logs_dir.clone();
977    let terminal_journal_path = config.terminal_journal_path.clone();
978    let privacy_trampoline = config.privacy_trampoline.clone();
979    #[cfg(any(target_os = "linux", target_os = "macos"))]
980    let upgrade =
981        if let (Some(binary), Some(executable)) = (&config.upgrade_binary, &privacy_trampoline) {
982            match &binary.image {
983                Ok(image) => {
984                    #[cfg(feature = "test-support")]
985                    let hooks = if binary.test_hooks {
986                        crate::control::upgrade_in_place::Hooks::for_test_binary()
987                    } else {
988                        Default::default()
989                    };
990                    #[cfg(not(feature = "test-support"))]
991                    let hooks = Default::default();
992                    let boot = crate::control::upgrade_in_place::BootImage::capture(
993                        executable.clone(),
994                        image.clone(),
995                        binary.core_version.clone(),
996                        binary.build_git_sha.clone(),
997                        resume.as_ref().map(resume::Resume::verified_digest),
998                        &hooks,
999                    )
1000                    .await;
1001                    Some(UpgradeStartup {
1002                        boot,
1003                        required: crate::supervise::handover::required_lock_roles(&config),
1004                        hooks,
1005                    })
1006                }
1007                Err(error) => {
1008                    warn!(%error, "in-place upgrade disabled: could not open running executable");
1009                    None
1010                }
1011            }
1012        } else {
1013            None
1014        };
1015    #[cfg(all(test, feature = "test-support"))]
1016    let test_control = config.test_control;
1017    #[cfg(all(
1018        feature = "test-support",
1019        any(target_os = "linux", target_os = "macos")
1020    ))]
1021    if let Some(gate) = upgrade.as_ref().and_then(|startup| {
1022        inherited_run.as_ref()?;
1023        startup.hooks.resume_bind_gate.as_deref()
1024    }) {
1025        crate::control::upgrade_in_place::wait_at_gate(gate, 1)
1026            .await
1027            .map_err(BootstrapError::Resume)?;
1028    }
1029    let outcome = match inherited_run {
1030        Some(run_dir) => {
1031            bind_under_locks(
1032                config,
1033                false,
1034                start_lock,
1035                Some(run_dir),
1036                #[cfg(any(target_os = "linux", target_os = "macos"))]
1037                inherited_tcp,
1038            )
1039            .await?
1040        }
1041        None => ensure_singleton_with_start_lock(config, false, start_lock).await?,
1042    };
1043    match outcome {
1044        Outcome::AlreadyRunning => {
1045            info!("subc daemon already running");
1046            Ok(())
1047        }
1048        Outcome::Bound(bound) => {
1049            #[cfg(target_os = "linux")]
1050            let cgroup_placement = prepare_cgroup_placement(&cgroup_placement_config);
1051            #[cfg(not(target_os = "linux"))]
1052            let _ = cgroup_placement_config;
1053            serve_bound_daemon(
1054                bound,
1055                daemon_start_clock,
1056                forwarding,
1057                configured_modules,
1058                storage_config,
1059                admission_facts,
1060                scope_authority_owners,
1061                flow_scope_authority_owners,
1062                federated_scope_owner,
1063                privileged_operator_prompt,
1064                activity_config,
1065                daemon_config_path,
1066                opened_store,
1067                configured_port,
1068                route_bind_relay_default_ms,
1069                reserved_capabilities,
1070                watchdog_config,
1071                capture_logs_dir,
1072                terminal_journal_path,
1073                privacy_trampoline,
1074                #[cfg(any(target_os = "linux", target_os = "macos"))]
1075                upgrade,
1076                #[cfg(any(target_os = "linux", target_os = "macos"))]
1077                resume,
1078                #[cfg(all(test, feature = "test-support"))]
1079                test_control,
1080                #[cfg(feature = "test-support")]
1081                shutdown_intent_window,
1082                #[cfg(target_os = "linux")]
1083                cgroup_placement,
1084            )
1085            .await
1086        }
1087    }
1088}
1089
1090// Keep authority selection before binding listeners or constructing control
1091// authorization. Recovery must remain reachable even with invalid live files.
1092fn load_bootstrap_authority(
1093    config: BootstrapConfig,
1094    mut store: Option<&mut crate::config_store::ConfigStore>,
1095) -> Result<BootstrapConfig, BootstrapError> {
1096    let store_state = store.as_mut().map(|store| store.status().state);
1097    let recovery = matches!(
1098        store_state,
1099        Some(
1100            crate::config_store::StoreState::StoreUnverified
1101                | crate::config_store::StoreState::StoreMissing
1102        )
1103    );
1104    let authority = if recovery {
1105        BootstrapConfig::new(&config.connection_file_path, DEFAULT_SUBC_PORT)
1106    } else if store_state == Some(crate::config_store::StoreState::Stamped) {
1107        let store = store.expect("stamped store was just checked");
1108        match stamped_authority(&config.connection_file_path, store) {
1109            Ok(authority) => authority,
1110            Err(reason) => {
1111                // A stamped daemon never falls back to files, and exiting would
1112                // leave the operator no way to reach recovery.
1113                tracing::error!(%reason, "approved configuration unusable; starting in recovery");
1114                store.enter_recovery(&reason);
1115                BootstrapConfig::new(&config.connection_file_path, DEFAULT_SUBC_PORT)
1116            }
1117        }
1118    } else if config.defer_file_load {
1119        BootstrapConfig::from_env_with_daemon_config_path(
1120            config
1121                .daemon_config_path
1122                .as_ref()
1123                .expect("binary config path"),
1124        )?
1125    } else {
1126        return Ok(config);
1127    };
1128    // Only installation paths and explicit binary arguments override authority.
1129    // New file-derived fields are inherited whole from the selected authority.
1130    Ok(BootstrapConfig {
1131        connection_file_path: config.connection_file_path,
1132        connection_file_source: config.connection_file_source,
1133        daemon_ver: config.daemon_ver,
1134        daemon_config_path: config.daemon_config_path,
1135        config_store_root: config.config_store_root,
1136        defer_file_load: config.defer_file_load,
1137        operator_queue_wait: config.operator_queue_wait,
1138        operator_timeout: config.operator_timeout,
1139        operator_stuck_grace: config.operator_stuck_grace,
1140        watchdog_config: config.watchdog_config,
1141        cgroup_placement: config.cgroup_placement,
1142        capture_logs_dir: config.capture_logs_dir,
1143        terminal_journal_path: config.terminal_journal_path,
1144        machine_id_path: config.machine_id_path,
1145        local_listener: config.local_listener,
1146        live_children_path: config.live_children_path,
1147        privacy_trampoline: config.privacy_trampoline,
1148        #[cfg(any(target_os = "linux", target_os = "macos"))]
1149        upgrade_binary: config.upgrade_binary,
1150        #[cfg(feature = "test-support")]
1151        shutdown_intent_window: config.shutdown_intent_window,
1152        #[cfg(feature = "test-support")]
1153        operator_script: config.operator_script,
1154        #[cfg(feature = "test-support")]
1155        operator_events: config.operator_events,
1156        #[cfg(all(test, windows))]
1157        profile_override: config.profile_override,
1158        #[cfg(all(test, feature = "test-support"))]
1159        test_store_factory: config.test_store_factory,
1160        #[cfg(all(test, feature = "test-support"))]
1161        test_control: config.test_control,
1162        #[cfg(all(test, feature = "test-support"))]
1163        test_listener_bind: config.test_listener_bind,
1164        ..authority
1165    })
1166}
1167
1168/// Authority from the approved daemon generation the store selects for this
1169/// start. Every failure is a reason to enter recovery, never to exit.
1170fn stamped_authority(
1171    connection_file_path: &Path,
1172    store: &mut crate::config_store::ConfigStore,
1173) -> Result<BootstrapConfig, String> {
1174    let generation = store
1175        .select_boot_generation()
1176        .map_err(|error| error.to_string())?;
1177    let body = store.body().map_err(|error| error.to_string())?;
1178    let layer = body
1179        .generations
1180        .get(&generation)
1181        .and_then(|entry| entry.delivery.as_ref())
1182        .and_then(|delivery| delivery.daemon.as_ref())
1183        .ok_or("approved daemon snapshot is absent")?;
1184    let bytes = layer
1185        .bytes
1186        .as_deref()
1187        .ok_or("approved daemon bytes are absent")?;
1188    let path = layer
1189        .path
1190        .as_deref()
1191        .ok_or("approved daemon path is absent")?;
1192    let doc = std::str::from_utf8(bytes).map_err(|error| error.to_string())?;
1193    let (daemon, activity) = daemon_config::parse_with_activity(doc, Path::new(path))
1194        .map_err(|error| format!("approved daemon configuration is invalid: {error}"))?;
1195    let port = daemon.port;
1196    Ok(
1197        BootstrapConfig::new(connection_file_path, port.unwrap_or(DEFAULT_SUBC_PORT))
1198            .with_parsed_daemon_config(Some(daemon), activity)
1199            .with_daemon_config_source(PathBuf::from(path), port),
1200    )
1201}
1202
1203#[cfg(target_os = "linux")]
1204fn prepare_cgroup_placement(config: &CgroupPlacementConfig) -> Option<subc_cgroup::Placement> {
1205    let result = match config {
1206        CgroupPlacementConfig::Disabled => return None,
1207        CgroupPlacementConfig::Current => subc_cgroup::prepare_current(),
1208        CgroupPlacementConfig::Root(root) => subc_cgroup::prepare_at(root),
1209    };
1210
1211    match result {
1212        Ok(Some(placement)) => Some(placement),
1213        Ok(None) => {
1214            warn!(
1215                placement = ?config,
1216                "module cgroup placement is disabled: configured cgroup root is not delegated"
1217            );
1218            None
1219        }
1220        Err(error) => {
1221            warn!(
1222                placement = ?config,
1223                error = %error,
1224                "module cgroup placement is disabled by an unexpected cgroup probe error"
1225            );
1226            None
1227        }
1228    }
1229}
1230
1231/// Target soft limit for open file descriptors, applied to the daemon before any
1232/// module is spawned so children inherit it. Multi-root modules (one process
1233/// aggregating every project root's sqlite stores, index caches, watchers, and
1234/// LSP pipes) trivially exceed the macOS default soft limit of 256; a launchd
1235/// user agent does not pass login-shell ulimits through, so the raise must
1236/// happen in-process.
1237#[cfg(unix)]
1238const NOFILE_TARGET: u64 = 65536;
1239
1240/// Raise RLIMIT_NOFILE to `NOFILE_TARGET` (clamped to the hard limit).
1241/// Best-effort: failure is logged and never fatal, since the daemon can run
1242/// under the inherited limit — modules with few roots just have less headroom.
1243#[cfg(unix)]
1244fn raise_nofile_limit() {
1245    #[cfg(target_os = "macos")]
1246    let ceiling = subc_os::child_spawn::output(
1247        std::process::Command::new("/usr/sbin/sysctl").args(["-n", "kern.maxfilesperproc"]),
1248    )
1249    .ok()
1250    .filter(|output| output.status.success())
1251    .and_then(|output| String::from_utf8(output.stdout).ok())
1252    .and_then(|value| value.trim().parse::<u64>().ok())
1253    .filter(|value| *value > 0);
1254    #[cfg(not(target_os = "macos"))]
1255    let ceiling = None;
1256    raise_nofile_limit_with_ceiling(ceiling);
1257}
1258
1259#[cfg(unix)]
1260fn raise_nofile_limit_with_ceiling(kernel_ceiling: Option<u64>) {
1261    match rlimit::Resource::NOFILE.get() {
1262        Ok((soft, hard)) => {
1263            // On XNU an infinite hard limit does not remove the separate
1264            // per-process kernel ceiling. Exceeding it makes setrlimit fail
1265            // without raising the inherited (often 256) soft limit at all.
1266            let target = NOFILE_TARGET
1267                .min(hard)
1268                .min(kernel_ceiling.unwrap_or(u64::MAX));
1269            if soft >= target {
1270                return;
1271            }
1272            match rlimit::Resource::NOFILE.set(target, hard) {
1273                Ok(()) => info!(
1274                    previous_soft = soft,
1275                    new_soft = target,
1276                    hard,
1277                    "raised open-file soft limit for daemon and module children"
1278                ),
1279                Err(err) => warn!(
1280                    soft,
1281                    hard,
1282                    error = %err,
1283                    "could not raise open-file soft limit; multi-root modules may exhaust descriptors"
1284                ),
1285            }
1286        }
1287        Err(err) => warn!(error = %err, "could not read open-file limit"),
1288    }
1289}
1290
1291/// CRT stdio-stream target on Windows (the `_setmaxstdio` maximum). Win32
1292/// HANDLEs — what Rust `File`, tokio sockets, and SQLite's Win32 VFS actually
1293/// consume — have a per-process quota in the millions and need no raise; the
1294/// C-runtime stream table (default 512) is the only low ceiling, and it is
1295/// per-process rather than inherited, so supervised modules linking the CRT
1296/// must raise their own. Raising it here covers the daemon itself.
1297#[cfg(windows)]
1298fn raise_nofile_limit() {
1299    const MAXSTDIO_TARGET: u32 = 8192;
1300    let current = rlimit::getmaxstdio();
1301    if current >= MAXSTDIO_TARGET {
1302        return;
1303    }
1304    match rlimit::setmaxstdio(MAXSTDIO_TARGET) {
1305        Ok(new_max) => info!(
1306            previous = current,
1307            new_max, "raised CRT stdio-stream limit for daemon"
1308        ),
1309        Err(err) => warn!(
1310            current,
1311            error = %err,
1312            "could not raise CRT stdio-stream limit"
1313        ),
1314    }
1315}
1316
1317#[cfg(not(any(unix, windows)))]
1318fn raise_nofile_limit() {}
1319
1320pub async fn run_with_daemon_config_path(
1321    config: BootstrapConfig,
1322    daemon_config_path: impl AsRef<Path>,
1323) -> Result<(), BootstrapError> {
1324    run_with_config(config.with_daemon_config_path(daemon_config_path)?).await
1325}
1326
1327#[allow(clippy::too_many_arguments)]
1328async fn serve_bound_daemon(
1329    mut bound: BoundDaemon,
1330    daemon_start_clock: crate::clock::StartClock,
1331    forwarding: Arc<ForwardingTable>,
1332    configured_modules: Vec<ConfiguredModule>,
1333    storage_config: Option<daemon_config::StorageConfig>,
1334    admission_facts: AdmissionFactsConfig,
1335    scope_authority_owners: Vec<String>,
1336    flow_scope_authority_owners: Vec<String>,
1337    federated_scope_owner: String,
1338    privileged_operator_prompt: daemon_config::PrivilegedOperatorPrompt,
1339    activity_config: daemon_config::ActivityConfig,
1340    daemon_config_path: Option<PathBuf>,
1341    opened_store: Option<(
1342        crate::config_store::ConfigStore,
1343        crate::config_store::StoreWriterLock,
1344    )>,
1345    configured_port: Option<u16>,
1346    route_bind_relay_default_ms: Option<u64>,
1347    reserved_capabilities: BTreeMap<String, String>,
1348    watchdog_config: DaemonSelfWatchdogConfig,
1349    capture_logs_dir: Option<PathBuf>,
1350    terminal_journal_path: Option<PathBuf>,
1351    privacy_trampoline: Option<PathBuf>,
1352    #[cfg(any(target_os = "linux", target_os = "macos"))] upgrade: Option<UpgradeStartup>,
1353    #[cfg(any(target_os = "linux", target_os = "macos"))] resume: Option<resume::Resume>,
1354    #[cfg(all(test, feature = "test-support"))] test_control: Option<
1355        fn(ControlHandler) -> ControlHandler,
1356    >,
1357    #[cfg(feature = "test-support")] shutdown_intent_window: Duration,
1358    #[cfg(target_os = "linux")] cgroup_placement: Option<subc_cgroup::Placement>,
1359) -> Result<(), BootstrapError> {
1360    let _stall_witness = crate::stall_witness::Witness::start_if_daemon_logging();
1361    #[cfg(unix)]
1362    let mut terminate = tokio::signal::unix::signal(tokio::signal::unix::SignalKind::terminate())
1363        .map_err(BootstrapError::Signal)?;
1364    // Windows has no SIGTERM. Ctrl-C is a different event, not an equivalent
1365    // service-stop contract, so this shutdown handler is intentionally Unix-only.
1366    raise_nofile_limit();
1367    #[cfg(windows)]
1368    if let Err(error) = subc_jobobject::ensure_root_job() {
1369        // Keep the control plane available. The root-job API caches setup
1370        // failures, so later module spawns refuse instead of running unprotected.
1371        warn!(%error, "module launches disabled: Windows root job setup failed");
1372    }
1373
1374    #[cfg(any(target_os = "linux", target_os = "macos"))]
1375    let resuming = resume.is_some();
1376    #[cfg(not(any(target_os = "linux", target_os = "macos")))]
1377    let resuming = false;
1378    #[cfg(all(
1379        feature = "test-support",
1380        any(target_os = "linux", target_os = "macos")
1381    ))]
1382    let local_listener_gate = upgrade
1383        .as_ref()
1384        .filter(|startup| resuming && startup.hooks.pause_local_listener)
1385        .map(|_| {
1386            bound
1387                .connection_file_path
1388                .with_file_name("resume-local-listener.test.sock")
1389        });
1390    info!(
1391        connection_file = %bound.connection_file_path.display(),
1392        connection_file_source = %bound.connection_file_source,
1393        connection_file_source_reason = bound.connection_file_source.reason(),
1394        endpoints = ?bound.connection_info.endpoints,
1395        configured_modules = configured_modules.len(),
1396        machine_id = bound.machine_id.as_ref().map(|id| id.as_str()).unwrap_or("none"),
1397        "{}",
1398        if resuming { "subc daemon resuming" } else { "subc daemon starting" }
1399    );
1400
1401    // Before anything can spawn a module (the configured modules below, or a
1402    // client's start request once the listeners are served): a previous daemon
1403    // that died without its shutdown stop may have left children running, and
1404    // a fresh copy beside one would fight it for its port and stores. The
1405    // record is not a running daemon's because this daemon holds the lock on
1406    // the run directory the record lives in, and a running daemon holds that
1407    // lock for its whole life. (Claiming the singleton is not enough: it is
1408    // keyed on the connection file, which can live in a different runtime
1409    // directory from the run directory.) An in-flight record write keeps the
1410    // lock even if shutdown reaches its deadline and this function returns.
1411    let run_dir_lock = bound.run_dir_lock.take();
1412    let mut publication_lock = bound.publication_lock.take();
1413    #[cfg(any(target_os = "linux", target_os = "macos"))]
1414    let adoption = resume
1415        .map(|resume| {
1416            if bound.local_listener.is_none() {
1417                return Err(BootstrapError::Resume(io::Error::other(
1418                    "resume requires a local listener",
1419                )));
1420            }
1421            resume.reconcile(run_dir_lock.as_ref().expect("resume holds the run lock"))
1422        })
1423        .transpose()?;
1424    let no_protected = crate::live_children::AdoptedPids::none();
1425    #[cfg(any(target_os = "linux", target_os = "macos"))]
1426    let protected = adoption
1427        .as_ref()
1428        .map_or(&no_protected, |adoption| &adoption.protected);
1429    #[cfg(not(any(target_os = "linux", target_os = "macos")))]
1430    let protected = &no_protected;
1431    if let Some(owner) = &run_dir_lock {
1432        #[cfg(target_os = "linux")]
1433        crate::live_children::sweep_orphans_with_placement(
1434            owner,
1435            protected,
1436            crate::live_children::SweepBounds::default(),
1437            cgroup_placement.as_ref(),
1438        )
1439        .await;
1440        #[cfg(not(target_os = "linux"))]
1441        crate::live_children::sweep_orphans(
1442            owner,
1443            protected,
1444            crate::live_children::SweepBounds::default(),
1445        )
1446        .await;
1447    }
1448
1449    let registry = Arc::new(Registry::default());
1450    let process_liveness = Arc::new(SupervisorProcessLiveness::new());
1451    let supervisor_handle = SupervisorHandle::new();
1452    #[cfg(any(target_os = "linux", target_os = "macos"))]
1453    if let Some(adoption) = &adoption {
1454        adoption.begin_report(&supervisor_handle);
1455    }
1456    let _host_health_task = AbortOnDrop::new(supervisor_handle.spawn_host_health_monitor());
1457    #[cfg(feature = "test-support")]
1458    supervisor_handle.set_shutdown_intent_window(shutdown_intent_window);
1459    let connected_clients = ConnectedClients::new();
1460    #[cfg(any(target_os = "linux", target_os = "macos"))]
1461    let store_writer = opened_store.as_ref().and_then(|(_, lock)| {
1462        crate::control::upgrade_in_place::witness(
1463            crate::supervise::handover::LockRole::StoreWriter,
1464            lock.file(),
1465        )
1466        .ok()
1467    });
1468    let daemon_incarnation = format!(
1469        "{:032x}",
1470        u128::from_be_bytes(bound.connection_info.daemon_id)
1471    );
1472    let config_runtime = if let Some((store, writer_lock)) = opened_store {
1473        let path = daemon_config_path.clone().ok_or_else(|| {
1474            BootstrapError::ConfigStore(
1475                "an explicit daemon config path is required with a config store".into(),
1476            )
1477        })?;
1478        let config_home = daemon_config::default_config_home();
1479        let incarnation = daemon_incarnation.clone();
1480        let projects = Arc::new(
1481            crate::config_gate::project_registry::EntorhinalProjectRegistry::new(
1482                registry.clone(),
1483                forwarding.clone(),
1484            ),
1485        );
1486        Some(Arc::new(
1487            tokio::task::spawn_blocking(move || {
1488                crate::config_gate::runtime::RuntimeOwner::new(
1489                    incarnation,
1490                    store,
1491                    crate::config_gate::capture::ConfigCapturer {
1492                        daemon_path: path,
1493                        config_home,
1494                        projects,
1495                    },
1496                )
1497                .with_policy_root_data(daemon_config::default_data_home().join("cortexkit"))
1498                .with_settings_recovery_data(daemon_config::default_data_home().join("cortexkit"))
1499                .enable_project_settings()
1500                .retain_writer_lock(writer_lock)
1501                .map_err(io::Error::other)
1502            })
1503            .await
1504            .map_err(|e| BootstrapError::ConfigStore(e.to_string()))?
1505            .map_err(|e| BootstrapError::ConfigStore(e.to_string()))?,
1506        ))
1507    } else {
1508        None
1509    };
1510    let _config_plan_sweep = config_runtime.as_ref().map(|runtime| {
1511        let runtime = Arc::downgrade(runtime);
1512        AbortOnDrop::new(tokio::spawn(async move {
1513            let mut interval =
1514                tokio::time::interval(crate::config_gate::runtime::PLAN_SWEEP_INTERVAL);
1515            loop {
1516                interval.tick().await;
1517                let Some(runtime) = runtime.upgrade() else {
1518                    break;
1519                };
1520                match tokio::task::spawn_blocking(move || runtime.sweep_expired()).await {
1521                    Ok(Ok(())) => {}
1522                    result => tracing::warn!(?result, "configuration plan expiry sweep failed"),
1523                }
1524            }
1525        }))
1526    });
1527    let supervisor = Supervisor::new(Arc::clone(&registry), RestartPolicy::default())
1528        .with_process_liveness(process_liveness.clone())
1529        .with_forwarding(Arc::clone(&forwarding))
1530        .with_handle(supervisor_handle.clone())
1531        .with_connection_file_path(bound.connection_file_path.clone())
1532        .with_daemon_incarnation(daemon_incarnation.clone());
1533    let supervisor = match &config_runtime {
1534        Some(owner) => supervisor.with_config_runtime(owner.clone()),
1535        None => supervisor,
1536    };
1537    let supervisor = match privacy_trampoline {
1538        Some(path) => supervisor.with_privacy_trampoline(path),
1539        None => supervisor,
1540    };
1541    // ABSENT MEANS NO CAPTURE AND NO JOURNAL, NOT "THE REAL RUN DIRECTORY", and
1542    // the difference is a production-corruption hazard rather than a preference.
1543    // Both fields below follow the same rule: `None` for `capture_logs_dir`
1544    // means supervised output is not captured, and `None` for
1545    // `terminal_journal_path` means terminal history lives only in each
1546    // module's in-memory ring (`supervisor.terminals` still answers, with the
1547    // journal counters at zero).
1548    //
1549    // The terminal journal used to fall back to
1550    // `daemon_run_dir().join("terminals.jsonl")`, so an in-process test daemon
1551    // appended its fixture exits to the operator's journal, where they then
1552    // appeared in `ck module terminals`.
1553    //
1554    // The capture line used to be `unwrap_or_else(|| daemon_run_dir().join("logs"))`,
1555    // so ANY caller that did not set the field captured supervised children into
1556    // the operator's live `~/.local/share/cortexkit/run/logs/`. That is twelve
1557    // sibling repos whose integration tests boot an in-process daemon through
1558    // `run_with_config` -- none of which asked for it, and none of which can see
1559    // it from their side.
1560    //
1561    // Harmless while fixture module ids are fixture-shaped: this host carries 20
1562    // zero-byte files from subc's own tests (good-aft, missing-aft,
1563    // preview-consumer...). THE HAZARD IS A COLLISION. A fixture named "broca"
1564    // or "aft" appends to a PRODUCTION capture file that operators read
1565    // forensically and that placement gates count lines in -- with no residue to
1566    // notice, because the file legitimately exists and legitimately grows.
1567    //
1568    // Found by BROCA (2026-09-19) from the other side: their rigs spawn the
1569    // SHIPPED ck-subc and set XDG_CONFIG_HOME + XDG_RUNTIME_DIR but not
1570    // XDG_DATA_HOME, so every local rig run supervised a module named "broca"
1571    // and captured it into production's broca.stderr.log -- the same file I
1572    // count seal lines in before and after placing their binaries.
1573    //
1574    // The supervisor already treats `None` as no-capture and no-journal, so
1575    // this only removes invented defaults. The binary keeps capturing and
1576    // journaling via `BootstrapConfig::from_env_for_daemon_binary`.
1577
1578    // Keep both ledgers in the explicitly selected run directory. An embedded
1579    // daemon without a journal path must not write to the operator's live ledger.
1580    let activity_run_dir = terminal_journal_path
1581        .as_ref()
1582        .and_then(|path| path.parent())
1583        .map(Path::to_path_buf);
1584    let supervisor = match terminal_journal_path {
1585        Some(path) => supervisor.with_terminal_journal(path, daemon_incarnation.clone()),
1586        None => supervisor,
1587    };
1588    let supervisor = match capture_logs_dir {
1589        Some(dir) => supervisor.with_capture_logs_dir(dir),
1590        None => supervisor,
1591    };
1592    let supervisor = match &run_dir_lock {
1593        Some(owner) => supervisor.with_owned_live_children_record(owner, protected),
1594        None => supervisor,
1595    };
1596    #[cfg(target_os = "linux")]
1597    let supervisor = supervisor.with_cgroup_placement(cgroup_placement);
1598    // Collect per-module route.bind relay overrides BEFORE handing the
1599    // `configured_modules` vector to the supervisor (which only needs each
1600    // module's `drain_timeout_ms`). Each entry was filled in by parse-time
1601    // resolution (per-module > daemon-wide > absent), so modules with no
1602    // override are absent from this map and the daemon-wide default applies.
1603    let route_bind_relay_timeouts = configured_modules
1604        .iter()
1605        .filter_map(|module| {
1606            module
1607                .route_bind_relay_timeout_ms
1608                .map(|ms| (module.module_id.clone(), Duration::from_millis(ms)))
1609        })
1610        .collect::<std::collections::BTreeMap<_, _>>();
1611    let mut control = ControlHandler::with_forwarding(Arc::clone(&registry), forwarding)
1612        .with_daemon_version(bound.connection_info.daemon_ver.clone())
1613        .with_process_liveness(process_liveness)
1614        .with_supervisor(supervisor_handle.clone())
1615        // The same flag `begin_daemon_shutdown` sets below, so requirement
1616        // changes while modules exit during the shutdown log at INFO.
1617        .with_daemon_shutdown_flag(supervisor.daemon_shutdown_flag())
1618        .with_connected_clients(connected_clients.clone())
1619        .with_local_endpoint_unavailable(bound.local_endpoint_unavailable.clone())
1620        .with_storage_config(storage_config)
1621        .with_machine_id(bound.machine_id.clone())
1622        .with_admission_facts_config(admission_facts.carrier_module_id, admission_facts.targets)
1623        .with_scope_authority_owners(scope_authority_owners)
1624        .with_flow_scope_authority_owners(flow_scope_authority_owners)
1625        .with_federated_scope_owner(federated_scope_owner)
1626        .with_privileged_operator_prompt(privileged_operator_prompt)
1627        .with_route_bind_relay_timeouts(route_bind_relay_timeouts)
1628        .with_daemon_provenance(
1629            bound.connection_info.pid,
1630            daemon_start_clock.started_at_ms(),
1631            std::env::current_exe().ok(),
1632            normalized_build_provenance(env!("SUBC_BUILD_GIT_SHA")),
1633            normalized_build_provenance(env!("SUBC_BUILD_LOCK_DIGEST")),
1634        )
1635        .with_daemon_start_clock(daemon_start_clock)
1636        .with_capability_config(
1637            configured_modules
1638                .iter()
1639                .map(|module| (module.module_id.clone(), module.enabled)),
1640            reserved_capabilities,
1641        );
1642    if let Some(run_dir) = activity_run_dir {
1643        control =
1644            control.with_activity_ledger_config(&run_dir, daemon_incarnation, activity_config);
1645    }
1646    let daemon_ready_runtime = config_runtime.clone();
1647    if let Some(runtime) = config_runtime {
1648        control = control.with_explicit_config_store(runtime);
1649    }
1650    #[cfg(feature = "test-support")]
1651    if config_test_seam::enabled() {
1652        control = control.with_config_os_prompt_policy_for_tests();
1653    }
1654    if let Some(ms) = route_bind_relay_default_ms {
1655        // A daemon-wide config value overrides the built-in default; a
1656        // `None` here leaves the ControlHandler's 12s default in place.
1657        control = control.with_route_bind_relay_timeout(Duration::from_millis(ms));
1658    }
1659    if let Some(config_path) = daemon_config_path {
1660        control = control.with_supervisor_rescan(supervisor.clone(), config_path, configured_port);
1661        control = control.with_supervisor_rescan_entries(&configured_modules);
1662    }
1663    #[cfg(all(test, feature = "test-support"))]
1664    let control = if let Some(adapt) = test_control {
1665        // A test hook is not a substitute for the executable-name guard.
1666        let executable =
1667            std::env::current_exe().map_err(|e| BootstrapError::ConfigStore(e.to_string()))?;
1668        if !executable
1669            .file_name()
1670            .is_some_and(|name| name.to_string_lossy().starts_with("ckdev-"))
1671        {
1672            return Err(BootstrapError::ConfigStore(
1673                "test control requires a ckdev executable".into(),
1674            ));
1675        }
1676        adapt(control)
1677    } else {
1678        control
1679    };
1680    let tcp_listeners: Vec<_> = bound.listeners.into_iter().map(Arc::new).collect();
1681    #[cfg(any(target_os = "linux", target_os = "macos"))]
1682    let (control, upgrade_runtime, _run_dir_lock) = match (upgrade, run_dir_lock) {
1683        (Some(startup), Some(run_dir)) if bound.local_listener.is_some() => {
1684            let mut control = control;
1685            let runtime = Arc::new(
1686                crate::control::upgrade_in_place::Runtime::new(
1687                    startup.boot,
1688                    startup.required,
1689                    run_dir,
1690                    store_writer,
1691                    supervisor.retained_children(),
1692                    startup.hooks,
1693                )
1694                .with_listeners(&tcp_listeners),
1695            );
1696            control.upgrade = Some(runtime.clone());
1697            (control, Some(runtime), None)
1698        }
1699        (_, run_dir_lock) => (control, None, run_dir_lock),
1700    };
1701    let control = Arc::new(control);
1702    let router = Arc::new(Router::with_control_handler(Arc::clone(&control)));
1703    let auth = ServerAuth::new(
1704        bound.connection_info.key.clone(),
1705        bound.connection_info.daemon_id,
1706        bound.connection_info.daemon_ver.clone(),
1707    )
1708    .with_connected_clients(connected_clients);
1709
1710    // Discovery must expose every accepted configured module, including disabled
1711    // ones. Registration creates status handles but neither starts monitors
1712    // nor launches processes: children need the published file for `--subc`.
1713    let mut registered_modules = Vec::with_capacity(configured_modules.len());
1714    #[cfg(any(target_os = "linux", target_os = "macos"))]
1715    let mut registered_cohort = BTreeMap::new();
1716    for configured in configured_modules {
1717        let enabled = configured.enabled;
1718        let health = configured.health.clone();
1719        let module_id = configured.module_id.clone();
1720        #[cfg(any(target_os = "linux", target_os = "macos"))]
1721        let cohort_enabled = adoption
1722            .as_ref()
1723            .and_then(|plan| plan.enabled(&module_id, enabled));
1724        let registered = match supervisor.register_configured_with_health(
1725            configured.module_spec(),
1726            enabled,
1727            health.clone(),
1728            configured.drain_timeout_ms,
1729            configured.restart,
1730            configured.register_timeout,
1731        ) {
1732            Ok(registered) => registered,
1733            Err(err) => {
1734                error!(module_id = %module_id, error = %err, "failed to supervise configured module; continuing daemon startup");
1735                continue;
1736            }
1737        };
1738        // A relaxed threshold can silently outlive the temporary allowance
1739        // that required it, so report the extra tolerance on every boot.
1740        let default_threshold = HealthConfig::default().failure_threshold;
1741        if enabled && health.failure_threshold > default_threshold {
1742            warn!(
1743                module_id = %module_id,
1744                failure_threshold = health.failure_threshold,
1745                default_threshold,
1746                tolerance_secs = health.cadence.as_secs() * u64::from(health.failure_threshold),
1747                "health failure threshold is relaxed above the default; a wedged module stays unflagged for longer"
1748            );
1749        }
1750        info!(module_id = %module_id, enabled, "configured module registered");
1751        #[cfg(any(target_os = "linux", target_os = "macos"))]
1752        if let Some(effective) = cohort_enabled {
1753            registered_cohort.insert(module_id, (registered, effective));
1754            continue;
1755        }
1756        registered_modules.push(registered);
1757    }
1758    control.refresh_capability_requirements();
1759
1760    let publish = |lock| {
1761        publish_connection_file(
1762            &bound.connection_file_path,
1763            #[cfg(windows)]
1764            bound.connection_file_copy.as_deref(),
1765            &bound.connection_info,
1766            bound.local_endpoint.as_ref(),
1767            lock,
1768        )
1769    };
1770    #[cfg(any(target_os = "linux", target_os = "macos"))]
1771    let preparations = adoption
1772        .as_ref()
1773        .map(|plan| plan.stage_preparations(&supervisor_handle, &registered_cohort))
1774        .transpose()?
1775        .unwrap_or_default();
1776    #[cfg(any(target_os = "linux", target_os = "macos"))]
1777    let (resumed_listener, local_ready) = adoption
1778        .as_ref()
1779        .map(|plan| {
1780            let (ready, wait) = tokio::sync::oneshot::channel();
1781            (Some((plan.monotonic_ns, ready)), Some(wait))
1782        })
1783        .unwrap_or_default();
1784
1785    // The local endpoint is served beside TCP and answers the same handshake.
1786    // Only a carried child with a valid resume HELLO can register on it.
1787    let local_serve_task = bound.local_listener.map(|listener| {
1788        let router = router.clone();
1789        let auth = auth.clone();
1790        AbortOnDrop::new(tokio::spawn(async move {
1791            #[cfg(any(target_os = "linux", target_os = "macos"))]
1792            if let Some((sample, ready)) = resumed_listener {
1793                #[cfg(feature = "test-support")]
1794                if let Some(path) = local_listener_gate {
1795                    if let Err(error) =
1796                        crate::control::upgrade_in_place::wait_at_gate(&path, 1).await
1797                    {
1798                        warn!(%error, "could not wait at the resume local listener test gate");
1799                    }
1800                }
1801                return crate::server::serve_resumed_local_listener(
1802                    listener,
1803                    router,
1804                    auth,
1805                    move || {
1806                        resume::log_accept(sample);
1807                        let _ = ready.send(());
1808                    },
1809                )
1810                .await;
1811            }
1812            serve_local_listener(listener, router, auth).await
1813        }))
1814    });
1815    let mut serve_task = AbortOnDrop::new(tokio::spawn(serve_shared_listeners(
1816        tcp_listeners,
1817        router,
1818        auth,
1819    )));
1820    // On Unix the task is dropped below to stop accepting at shutdown. Windows
1821    // leaves it to the process exit; naming it keeps the binding uniform.
1822    #[cfg(windows)]
1823    let _local_serve_task = local_serve_task;
1824    // The connection file promises clients can authenticate immediately, even
1825    // while individual modules are still preparing to resume.
1826    verify_serving(&bound.connection_info).await?;
1827    #[cfg(any(target_os = "linux", target_os = "macos"))]
1828    if let Some(ready) = local_ready {
1829        timeout(PROBE_AUTH_DEADLINE, ready)
1830            .await
1831            .map_err(|_| BootstrapError::StartupNotServing)?
1832            .map_err(|_| BootstrapError::StartupNotServing)?;
1833    }
1834    let (published, lock) = publish(publication_lock.take()).await;
1835    published?;
1836    publication_lock = lock.flatten();
1837    #[cfg(any(target_os = "linux", target_os = "macos"))]
1838    let planned = if let Some(adoption) = adoption {
1839        if let Some(runtime) = &upgrade_runtime {
1840            if let Some(lock) = publication_lock.take() {
1841                runtime.retain_publication(lock);
1842            }
1843        }
1844        // A child being adopted may exit during installation and need a
1845        // replacement. Do not start these preparations before publishing.
1846        adoption
1847            .install(&supervisor, registered_cohort, preparations)
1848            .await?
1849    } else {
1850        Vec::new()
1851    };
1852    // Serving and discoverable: a daemon booted from a restart intent records
1853    // readiness, which makes that generation the daemon's active one. Without
1854    // this record the next start treats the warm-up as failed.
1855    if let Some(owner) = daemon_ready_runtime {
1856        if let Err(error) = owner.on_blocking(|owner| owner.record_daemon_ready()).await {
1857            warn!(%error, "daemon readiness was not recorded in the approved store");
1858        }
1859    }
1860    #[cfg(test)]
1861    startup_publication_hook::run(&bound.connection_file_path).await;
1862    #[cfg(not(any(target_os = "linux", target_os = "macos")))]
1863    drop(publication_lock);
1864    let _clock_step_task = AbortOnDrop::new(crate::watchdog::spawn_clock_step_monitor());
1865    let _stalled_cancel_task =
1866        AbortOnDrop::new(control.forwarding().spawn_stalled_cancel_monitor());
1867    // Off the startup path: it runs `systemctl`, and only ever logs.
1868    #[cfg(target_os = "linux")]
1869    let _kill_mode_check = AbortOnDrop::new(tokio::spawn(
1870        crate::systemd_kill_mode::warn_if_kill_mode_defeats_ordered_shutdown(),
1871    ));
1872    let _watchdog_task = AbortOnDrop::new(
1873        DaemonSelfWatchdog::new(
1874            bound.connection_info.clone(),
1875            bound.connection_file_path.clone(),
1876        )
1877        .with_config(watchdog_config)
1878        .spawn(),
1879    );
1880
1881    #[cfg(any(target_os = "linux", target_os = "macos"))]
1882    for (module, registered, enabled) in planned {
1883        if let Err(error) = supervisor
1884            .start_planned_after_upgrade(&module, registered, enabled)
1885            .await
1886        {
1887            error!(module_id = %module, %error, "failed to start a planned upgrade replacement");
1888        }
1889    }
1890    for registered in registered_modules {
1891        match supervisor
1892            .start_registered_configured_async(registered, None, true)
1893            .await
1894        {
1895            Ok(module) => {
1896                info!(module_id = %module.module_id(), "configured module supervised");
1897            }
1898            Err(err) => {
1899                error!(error = %err, "failed to start configured module; continuing daemon startup");
1900            }
1901        }
1902    }
1903
1904    control.refresh_capability_requirements();
1905    Arc::clone(&control).spawn_capability_deadline_loop();
1906    Arc::clone(&control).spawn_scope_expiry_loop();
1907    let _config_delivery_task = control.spawn_config_delivery_worker().map(AbortOnDrop::new);
1908    let _pending_settings_task = control
1909        .spawn_pending_settings_worker()
1910        .map(AbortOnDrop::new);
1911    control.spawn_resource_sampler();
1912    #[cfg(any(target_os = "linux", target_os = "macos"))]
1913    if let Some(runtime) = &upgrade_runtime {
1914        if let Some(lock) = publication_lock.take() {
1915            runtime.retain_publication(lock);
1916        }
1917    }
1918
1919    #[cfg(unix)]
1920    {
1921        tokio::select! {
1922            result = serve_task.join() => {
1923                return result.map_err(BootstrapError::ServeJoin)?.map_err(BootstrapError::Serve);
1924            }
1925            _ = terminate.recv() => {}
1926        }
1927        #[cfg(any(target_os = "linux", target_os = "macos"))]
1928        if let Some(runtime) = &upgrade_runtime {
1929            runtime.shutdown().await;
1930        }
1931        // First, before the notice, the drain, or any connection close: from
1932        // here on a module exit is recorded as `daemon_shutdown` and never
1933        // respawned. Also before allowing a second signal to cut the bounded
1934        // wait short, so the journal marker is queued first.
1935        supervisor.begin_daemon_shutdown();
1936        // Stop the self-watchdog before closing the listener. Its next tick would
1937        // connect to that listener, fail, and log an ERROR indistinguishable from
1938        // a wedged daemon, once for every interval a planned stop lasts.
1939        drop(_watchdog_task);
1940        // Dropping the listener stops new accepts, not established connections:
1941        // their detached tasks must remain live throughout notice and drain. The
1942        // local endpoint stops accepting the same way.
1943        drop(serve_task);
1944        drop(local_serve_task);
1945        let second_sigterm = async {
1946            terminate.recv().await;
1947            std::time::Instant::now()
1948        };
1949        tokio::pin!(second_sigterm);
1950        let mut escalation_started = tokio::select! {
1951            biased;
1952            at = second_sigterm.as_mut() => {
1953                info!("second SIGTERM: abandoning daemon shutdown wait");
1954                Some(at)
1955            }
1956            result = supervisor.drain_for_daemon_shutdown() => {
1957                if let Err(error) = result {
1958                    warn!(%error, "daemon shutdown drain failed; exiting anyway");
1959                }
1960                None
1961            }
1962        };
1963        // Supervised modules lead their own process groups, so a service
1964        // manager's kill of this process's group does not reach them. (A
1965        // systemd unit with KillMode=control-group kills by cgroup instead and
1966        // does reach them; see `systemd_kill_mode`.) The daemon ends them
1967        // itself: EOF (or SIGTERM for a protocol none child) first, then
1968        // signals at each child's own drain deadline.
1969        let already_escalated = escalation_started.is_some();
1970        supervisor
1971            .end_children_for_daemon_shutdown(already_escalated, async {
1972                if already_escalated {
1973                    std::future::pending::<()>().await;
1974                } else {
1975                    escalation_started = Some(second_sigterm.await);
1976                }
1977            })
1978            .await;
1979        if let Some(at) = escalation_started {
1980            info!(
1981                second_sigterm_elapsed_ms = at.elapsed().as_millis() as u64,
1982                "daemon shutdown wait ended after second SIGTERM"
1983            );
1984        }
1985        info!("daemon exiting: SIGTERM shutdown complete");
1986        Ok(())
1987    }
1988    #[cfg(not(unix))]
1989    serve_task
1990        .join()
1991        .await
1992        .map_err(BootstrapError::ServeJoin)?
1993        .map_err(BootstrapError::Serve)
1994}
1995
1996fn normalized_build_provenance(value: &str) -> Option<String> {
1997    match value.trim() {
1998        "" | "unavailable" => None,
1999        value => Some(value.to_string()),
2000    }
2001}
2002
2003/// Find an existing daemon or atomically bind loopback TCP for this daemon.
2004///
2005/// The algorithm is intentionally connect-first: an endpoint from the connection
2006/// file is treated as live only after the TCP+key server-proof authenticates for
2007/// that file's key and daemon_id. Stale or foreign connection files are reclaimed
2008/// only while holding the per-user start lock; the TCP port is never the
2009/// singleton primitive.
2010pub async fn ensure_singleton(
2011    connection_file_path: impl AsRef<Path>,
2012    port: u16,
2013) -> Result<Outcome, BootstrapError> {
2014    ensure_singleton_with_config(BootstrapConfig::new(connection_file_path.as_ref(), port)).await
2015}
2016
2017pub async fn ensure_singleton_with_config(
2018    config: BootstrapConfig,
2019) -> Result<Outcome, BootstrapError> {
2020    ensure_singleton_inner(config, true).await
2021}
2022
2023async fn ensure_singleton_inner(
2024    config: BootstrapConfig,
2025    publish: bool,
2026) -> Result<Outcome, BootstrapError> {
2027    let Some(lock) = singleton_start_lock(&config).await? else {
2028        return Ok(Outcome::AlreadyRunning);
2029    };
2030    ensure_singleton_with_start_lock(config, publish, lock).await
2031}
2032
2033async fn singleton_start_lock(
2034    config: &BootstrapConfig,
2035) -> Result<Option<StartLock>, BootstrapError> {
2036    let path = &config.connection_file_path;
2037    if stable_peer(path).await? {
2038        return Ok(None);
2039    }
2040
2041    #[cfg(unix)]
2042    if config.connection_file_source == ConnectionFileSource::DaemonRunDir {
2043        // The binary prepares the run directory for logging first. Embedded
2044        // daemons can reach the start lock before anything creates its parent.
2045        if let Some(parent) = path
2046            .parent()
2047            .filter(|p| !p.as_os_str().is_empty() && !p.exists())
2048        {
2049            daemon_config::ensure_directory_private(parent).map_err(|source| {
2050                BootstrapError::StartLockCreate {
2051                    path: start_lock_path(path),
2052                    source,
2053                }
2054            })?;
2055        }
2056    }
2057    let lock = match StartLock::acquire(path).await {
2058        Err(BootstrapError::StartLockBusy { .. }) if stable_peer(path).await? => return Ok(None),
2059        result => result?,
2060    };
2061
2062    // Re-probe after acquiring the start lock so a peer that won the race between
2063    // our first failed probe and the lock acquisition is observed instead of
2064    // overwritten.
2065    if stable_peer(path).await? {
2066        return Ok(None);
2067    }
2068    Ok(Some(lock))
2069}
2070
2071async fn ensure_singleton_with_start_lock(
2072    config: BootstrapConfig,
2073    publish: bool,
2074    lock: StartLock,
2075) -> Result<Outcome, BootstrapError> {
2076    // The held start lock and its peer check only rule out a daemon using this
2077    // connection file. A daemon started with another runtime directory but
2078    // the same data home shares the run directory while passing both, so the
2079    // run directory needs its own owner: refuse at once if a live daemon holds
2080    // it, before anything below reads or writes run or data-home state.
2081    let run_dir_lock = config
2082        .live_children_path
2083        .as_deref()
2084        .map(crate::run_dir_lock::RunDirLock::acquire)
2085        .transpose()?;
2086    #[cfg(any(target_os = "linux", target_os = "macos"))]
2087    if let Some(owner) = &run_dir_lock {
2088        resume::discard_leftover(owner);
2089    }
2090    bind_under_locks(
2091        config,
2092        publish,
2093        lock,
2094        run_dir_lock,
2095        #[cfg(any(target_os = "linux", target_os = "macos"))]
2096        None,
2097    )
2098    .await
2099}
2100
2101async fn bind_under_locks(
2102    config: BootstrapConfig,
2103    publish: bool,
2104    lock: StartLock,
2105    run_dir_lock: Option<crate::run_dir_lock::RunDirLock>,
2106    #[cfg(any(target_os = "linux", target_os = "macos"))] inherited_tcp: Option<
2107        Vec<std::net::TcpListener>,
2108    >,
2109) -> Result<Outcome, BootstrapError> {
2110    #[cfg(windows)]
2111    let copy_path = windows_connection_copy::resolve(&config);
2112    let path = config.connection_file_path;
2113    #[cfg(unix)]
2114    if config.connection_file_source == ConnectionFileSource::TempDirFallback {
2115        warn!(
2116            connection_file = %path.display(),
2117            reason = config.connection_file_source.reason(),
2118            "using the system temporary directory for the daemon connection file"
2119        );
2120    }
2121    remove_stale_connection_file_if_present(&path)?;
2122    #[cfg(windows)]
2123    let copy_path = windows_connection_copy::reclaim(&path, copy_path).await;
2124
2125    // Established under the start lock, and under the run-directory lock when
2126    // there is one, and before binding: a corrupt file stops boot before
2127    // anything is published, and two daemons racing to start cannot both mint.
2128    //
2129    // Minting a new machine id fsyncs its file, so loading or minting runs on
2130    // tokio's blocking pool. Both locks travel with that work, so neither is
2131    // released while a mint is in flight.
2132    let (machine_id, lock, run_dir_lock) = match config.machine_id_path {
2133        None => (None, lock, run_dir_lock),
2134        Some(machine_id_path) => {
2135            let task_path = machine_id_path.clone();
2136            match run_blocking_holding((lock, run_dir_lock), move || {
2137                crate::machine_id::load_or_mint(&task_path)
2138            })
2139            .await
2140            {
2141                Ok((Ok(id), (lock, run_dir_lock))) => (Some(id), lock, run_dir_lock),
2142                Ok((Err(error), _locks)) => return Err(BootstrapError::MachineId(error)),
2143                Err(join_error) => {
2144                    return Err(BootstrapError::MachineId(
2145                        crate::machine_id::MachineIdFileError::Write {
2146                            path: machine_id_path,
2147                            source: io::Error::other(describe_blocking_task_failure(
2148                                "loading or minting the machine id",
2149                                &join_error,
2150                            )),
2151                        },
2152                    ))
2153                }
2154            }
2155        }
2156    };
2157
2158    #[cfg(not(any(target_os = "linux", target_os = "macos")))]
2159    let (listeners, endpoints) = bind_loopback(config.port).await?;
2160    #[cfg(any(target_os = "linux", target_os = "macos"))]
2161    let (listeners, endpoints) = match inherited_tcp {
2162        None => bind_loopback(config.port).await?,
2163        Some(inherited) => {
2164            let mut listeners = Vec::with_capacity(inherited.len());
2165            let mut endpoints = Vec::with_capacity(inherited.len());
2166            for listener in inherited {
2167                let address = listener.local_addr().map_err(BootstrapError::Resume)?;
2168                listeners.push(TcpListener::from_std(listener).map_err(BootstrapError::Resume)?);
2169                endpoints.push(Endpoint {
2170                    host: address.ip().to_string(),
2171                    port: address.port(),
2172                });
2173            }
2174            (listeners, endpoints)
2175        }
2176    };
2177    // The local endpoint is an addition to the daemon, not a condition for it:
2178    // a bind failure leaves clients on TCP only, with the connection file naming
2179    // no local endpoint, and the reason reported by `server.describe`. A daemon
2180    // that refused to start would take every module down for a feature nothing
2181    // has to use yet.
2182    let (local_listener, local_endpoint, local_endpoint_unavailable) =
2183        if config.local_listener.configured_dir().is_some() {
2184            match local_listener::bind(&config.local_listener, &path) {
2185                Ok(local_listener) => {
2186                    let endpoint = local_listener.endpoint();
2187                    (Some(local_listener), Some(endpoint), None)
2188                }
2189                Err(error) => {
2190                    let reason = error.to_string();
2191                    warn!(
2192                        error = %reason,
2193                        "the local endpoint is unavailable; serving loopback TCP only"
2194                    );
2195                    (None, None, Some(reason))
2196                }
2197            }
2198        } else {
2199            (None, None, None)
2200        };
2201    let connection_info = ConnectionInfo {
2202        schema: SCHEMA_VERSION,
2203        wire_version: Some(PROTOCOL_VERSION),
2204        endpoints,
2205        key: generate_key().map_err(BootstrapError::GenerateConnectionFile)?,
2206        daemon_id: generate_daemon_id().map_err(BootstrapError::GenerateConnectionFile)?,
2207        pid: process::id(),
2208        daemon_ver: config.daemon_ver,
2209    };
2210
2211    // The low-level binding API historically publishes for callers that serve
2212    // these listeners themselves. The daemon entry point defers publication
2213    // until its own authentication server is running.
2214    let publication_lock = if publish {
2215        let (published, lock) = publish_connection_file(
2216            &path,
2217            #[cfg(windows)]
2218            copy_path.as_deref(),
2219            &connection_info,
2220            local_endpoint.as_ref(),
2221            lock,
2222        )
2223        .await;
2224        if let Err(error) = published {
2225            if let Some(local_listener) = local_listener.as_ref() {
2226                local_listener::release(local_listener);
2227            }
2228            drop(listeners);
2229            return Err(error);
2230        }
2231        drop(lock);
2232        None
2233    } else {
2234        Some(lock)
2235    };
2236
2237    Ok(Outcome::Bound(BoundDaemon {
2238        listeners,
2239        local_listener,
2240        local_endpoint,
2241        local_endpoint_unavailable,
2242        connection_info,
2243        connection_file_path: path,
2244        connection_file_source: config.connection_file_source,
2245        #[cfg(windows)]
2246        connection_file_copy: copy_path,
2247        machine_id,
2248        run_dir_lock,
2249        publication_lock,
2250    }))
2251}
2252
2253#[derive(Debug, Clone, Copy, PartialEq, Eq)]
2254enum Probe {
2255    Live,
2256    StaleOrAbsent,
2257}
2258
2259async fn stable_peer(path: &Path) -> Result<bool, BootstrapError> {
2260    if !matches!(probe_existing(path).await?, Probe::Live) {
2261        return Ok(false);
2262    }
2263    // A terminating peer can still authenticate while its listeners drain.
2264    // Require another proof after a short settling interval before reporting
2265    // a successful duplicate start. If the peer left, proceed with startup;
2266    // any remaining bind/ownership conflict is an error, not exit 0 (which
2267    // would suppress launchd's restart-on-failure policy).
2268    tokio::time::sleep(Duration::from_millis(1500)).await;
2269    Ok(matches!(probe_existing(path).await?, Probe::Live))
2270}
2271
2272async fn probe_existing(path: &Path) -> Result<Probe, BootstrapError> {
2273    let info = match connection_file::read(path) {
2274        Ok(info) => info,
2275        Err(source) if is_absent_or_stale_connection_file(&source) => {
2276            return Ok(Probe::StaleOrAbsent)
2277        }
2278        Err(source) => {
2279            return Err(BootstrapError::ConnectionFileRead {
2280                path: path.to_path_buf(),
2281                source,
2282            })
2283        }
2284    };
2285
2286    for endpoint in &info.endpoints {
2287        if matches!(probe_endpoint(&info, endpoint).await, Probe::Live) {
2288            return Ok(Probe::Live);
2289        }
2290    }
2291
2292    Ok(Probe::StaleOrAbsent)
2293}
2294
2295async fn probe_endpoint(info: &ConnectionInfo, endpoint: &Endpoint) -> Probe {
2296    let Ok(ip) = endpoint.host.parse::<IpAddr>() else {
2297        return Probe::StaleOrAbsent;
2298    };
2299    if !ip.is_loopback() {
2300        return Probe::StaleOrAbsent;
2301    }
2302    let addr = SocketAddr::new(ip, endpoint.port);
2303
2304    let mut stream = match timeout(CONNECT_TIMEOUT, TcpStream::connect(addr)).await {
2305        Ok(Ok(stream)) => stream,
2306        Ok(Err(_)) | Err(_) => return Probe::StaleOrAbsent,
2307    };
2308
2309    match authenticate_client(&mut stream, info, PROBE_AUTH_DEADLINE).await {
2310        Ok(()) => Probe::Live,
2311        Err(AuthError::DaemonIdMismatch)
2312        | Err(AuthError::InvalidServerProof)
2313        | Err(AuthError::UnexpectedEof { .. })
2314        | Err(AuthError::Timeout { .. })
2315        | Err(AuthError::JsonEncode { .. })
2316        | Err(AuthError::JsonDecode { .. })
2317        | Err(AuthError::Io { .. })
2318        | Err(AuthError::MessageTooLarge { .. })
2319        | Err(AuthError::KeyTooShort { .. })
2320        | Err(AuthError::Random(_))
2321        | Err(AuthError::InvalidClientAuth) => Probe::StaleOrAbsent,
2322    }
2323}
2324
2325async fn verify_serving(info: &ConnectionInfo) -> Result<(), BootstrapError> {
2326    // Scheduling a server task is not a readiness barrier. Authenticate once
2327    // against the mandatory IPv4 listener before exposing discovery to peers.
2328    // This uses the normal probe deadline, with no retries or widened budget.
2329    if let Some(endpoint) = info.endpoints.first() {
2330        if matches!(probe_endpoint(info, endpoint).await, Probe::Live) {
2331            return Ok(());
2332        }
2333    }
2334    Err(BootstrapError::StartupNotServing)
2335}
2336
2337/// Run blocking filesystem work (an fsync, a rename) on tokio's blocking-thread
2338/// pool rather than on the async worker thread that awaits it. On a slow or
2339/// busy disk an fsync can take seconds, and a runtime has few worker threads
2340/// (an in-process test daemon may share two with everything else), so doing it
2341/// inline stalls unrelated tasks for that long.
2342///
2343/// `guards` (lock handles) move into the blocking task and are handed back
2344/// with the work's result. If the awaiting future is dropped first, the work
2345/// still runs to completion on its thread and the guards are released only
2346/// after it ends, so a lock is never given up while the work it protects is
2347/// still writing.
2348///
2349/// `Err` means the task panicked, or was cancelled before it started because
2350/// the runtime is shutting down; the guards have then been released already.
2351async fn run_blocking_holding<G, T>(
2352    guards: G,
2353    work: impl FnOnce() -> T + Send + 'static,
2354) -> Result<(T, G), JoinError>
2355where
2356    G: Send + 'static,
2357    T: Send + 'static,
2358{
2359    tokio::task::spawn_blocking(move || {
2360        let output = work();
2361        (output, guards)
2362    })
2363    .await
2364}
2365
2366/// Explain, for a startup error, why blocking work produced no result.
2367fn describe_blocking_task_failure(work: &str, join_error: &JoinError) -> String {
2368    if join_error.is_panic() {
2369        format!("the background thread {work} panicked before finishing: {join_error}")
2370    } else {
2371        format!(
2372            "the background thread {work} was cancelled before finishing, because the async runtime is shutting down: {join_error}"
2373        )
2374    }
2375}
2376
2377/// Publish the connection file: owner-only permissions, written to a temporary
2378/// file, fsynced and renamed over `path` (all done by `write_atomic`). The
2379/// write runs on tokio's blocking pool through [`run_blocking_holding`], so the
2380/// fsync never holds an async worker thread.
2381///
2382/// `guard` is the singleton start lock (or whatever the caller must keep held
2383/// across publication); it is returned with the result. It comes back `None`
2384/// only when the write task panicked or was cancelled, in which case the
2385/// result is an error and the file must be treated as not published.
2386///
2387/// On Windows, `copy_path` asks for the profile copy as well. Its start lock is
2388/// taken before the primary write. Once `path` is written, an error returned
2389/// while preparing or writing the copy only logs a warning, and the result is
2390/// still success. The two writes share one blocking task but aren't one atomic
2391/// step, and a panic or cancellation of that task is still a publication
2392/// error.
2393async fn publish_connection_file<G: Send + 'static>(
2394    path: &Path,
2395    #[cfg(windows)] copy_path: Option<&Path>,
2396    info: &ConnectionInfo,
2397    local_endpoint: Option<&LocalEndpoint>,
2398    guard: G,
2399) -> (Result<(), BootstrapError>, Option<G>) {
2400    let task_path = path.to_path_buf();
2401    let task_info = info.clone();
2402    let task_endpoint = local_endpoint.cloned();
2403    #[cfg(windows)]
2404    let copy = windows_connection_copy::claim_for_publication(path, copy_path, info).await;
2405    let outcome = run_blocking_holding(guard, move || {
2406        write_connection_file(&task_path, &task_info, task_endpoint.as_ref())?;
2407        #[cfg(windows)]
2408        if let Some((copy_path, _lock)) = copy {
2409            if let Err(error) =
2410                write_connection_file(&copy_path, &task_info, task_endpoint.as_ref())
2411            {
2412                windows_connection_copy::warn_unavailable(&task_path, Some(&copy_path), &error);
2413            }
2414        }
2415        Ok(())
2416    })
2417    .await;
2418    match outcome {
2419        Ok((Ok(()), guard)) => (Ok(()), Some(guard)),
2420        Ok((Err(source), guard)) => (
2421            Err(BootstrapError::ConnectionFileWrite {
2422                path: path.to_path_buf(),
2423                source,
2424            }),
2425            Some(guard),
2426        ),
2427        Err(join_error) => (
2428            Err(BootstrapError::ConnectionFileWrite {
2429                path: path.to_path_buf(),
2430                source: ConnectionFileError::Io {
2431                    op: "write",
2432                    path: path.to_path_buf(),
2433                    source: io::Error::other(describe_blocking_task_failure(
2434                        "writing the connection file",
2435                        &join_error,
2436                    )),
2437                },
2438            }),
2439            None,
2440        ),
2441    }
2442}
2443
2444/// The synchronous connection-file write, including its fsync. Call it only
2445/// through [`publish_connection_file`], which keeps it off the async workers.
2446///
2447/// `local_endpoint` is written through subc-transport's endpoint-aware writer,
2448/// so the file carries `local_endpoint` when there is a local listener and is
2449/// byte-identical to before when there is none.
2450fn write_connection_file(
2451    path: &Path,
2452    info: &ConnectionInfo,
2453    local_endpoint: Option<&LocalEndpoint>,
2454) -> Result<(), ConnectionFileError> {
2455    #[cfg(test)]
2456    connection_file_write_hook::run(path);
2457    write_atomic_with_local_endpoint(path, info, local_endpoint)
2458}
2459
2460/// Lets a test run code inside the connection-file write, on whichever thread
2461/// performs it, for example to block there and check what else can still run.
2462#[cfg(test)]
2463mod connection_file_write_hook {
2464    use std::{
2465        path::{Path, PathBuf},
2466        sync::{Mutex, PoisonError},
2467    };
2468
2469    type Hook = Box<dyn FnOnce() + Send>;
2470
2471    /// Keyed by connection-file path, so a hook fires only for the test that
2472    /// installed it while other tests publish their own files in parallel.
2473    static HOOKS: Mutex<Vec<(PathBuf, Hook)>> = Mutex::new(Vec::new());
2474
2475    /// Run `hook` once, at the start of the next write of `path`.
2476    pub(super) fn install(path: &Path, hook: impl FnOnce() + Send + 'static) {
2477        HOOKS
2478            .lock()
2479            .unwrap_or_else(PoisonError::into_inner)
2480            .push((path.to_path_buf(), Box::new(hook)));
2481    }
2482
2483    pub(super) fn run(path: &Path) {
2484        let hook = {
2485            let mut hooks = HOOKS.lock().unwrap_or_else(PoisonError::into_inner);
2486            hooks
2487                .iter()
2488                .position(|(hooked, _)| hooked == path)
2489                .map(|index| hooks.swap_remove(index).1)
2490        };
2491        if let Some(hook) = hook {
2492            hook();
2493        }
2494    }
2495}
2496
2497/// A path-scoped barrier after publication and before any configured activation.
2498/// The async wait leaves the listeners free to answer discovery-time requests.
2499#[cfg(test)]
2500mod startup_publication_hook {
2501    use std::{
2502        path::{Path, PathBuf},
2503        sync::{Mutex, PoisonError},
2504    };
2505    use tokio::sync::oneshot;
2506
2507    type Barrier = (oneshot::Sender<()>, oneshot::Receiver<()>);
2508    static BARRIERS: Mutex<Vec<(PathBuf, Barrier)>> = Mutex::new(Vec::new());
2509
2510    pub(super) fn install(path: &Path) -> (oneshot::Receiver<()>, oneshot::Sender<()>) {
2511        let (entered_tx, entered_rx) = oneshot::channel();
2512        let (release_tx, release_rx) = oneshot::channel();
2513        BARRIERS
2514            .lock()
2515            .unwrap_or_else(PoisonError::into_inner)
2516            .push((path.to_path_buf(), (entered_tx, release_rx)));
2517        (entered_rx, release_tx)
2518    }
2519
2520    pub(super) async fn run(path: &Path) {
2521        let barrier = {
2522            let mut barriers = BARRIERS.lock().unwrap_or_else(PoisonError::into_inner);
2523            barriers
2524                .iter()
2525                .position(|(hooked, _)| hooked == path)
2526                .map(|index| barriers.swap_remove(index).1)
2527        };
2528        if let Some((entered, release)) = barrier {
2529            let _ = entered.send(());
2530            let _ = release.await;
2531        }
2532    }
2533}
2534
2535fn is_absent_or_stale_connection_file(err: &ConnectionFileError) -> bool {
2536    match err {
2537        ConnectionFileError::Io { source, .. } if source.kind() == io::ErrorKind::NotFound => true,
2538        ConnectionFileError::JsonRead { .. }
2539        | ConnectionFileError::UnsupportedSchema { .. }
2540        | ConnectionFileError::Invalid { .. }
2541        | ConnectionFileError::KeyTooShort { .. }
2542        // A live daemon always publishes the file owner-only (0600), so a file
2543        // with insecure permissions is never a daemon we should defer to: treat it
2544        // as stale and take over (which republishes a correct 0600 file).
2545        | ConnectionFileError::InsecurePermissions { .. } => true,
2546        ConnectionFileError::MissingParent { .. }
2547        | ConnectionFileError::MissingFileName { .. }
2548        // A writable ancestor is an operator misconfiguration, never evidence
2549        // about whether a daemon is live. Reclaiming the file would republish key
2550        // material into the same directory the refusal is about.
2551        | ConnectionFileError::InsecureParentDirectory { .. }
2552        | ConnectionFileError::Io { .. }
2553        | ConnectionFileError::JsonWrite { .. }
2554        | ConnectionFileError::Random(_)
2555        // A wire mismatch may identify a newer live daemon, so never reclaim its
2556        // connection file merely because this binary cannot speak its envelope.
2557        | ConnectionFileError::WireVersionMismatch { .. } => false,
2558    }
2559}
2560
2561fn remove_stale_connection_file_if_present(path: &Path) -> Result<(), BootstrapError> {
2562    match fs::remove_file(path) {
2563        Ok(()) => Ok(()),
2564        Err(err) if err.kind() == io::ErrorKind::NotFound => Ok(()),
2565        Err(source) => Err(BootstrapError::RemoveStale {
2566            path: path.to_path_buf(),
2567            source,
2568        }),
2569    }
2570}
2571
2572async fn bind_loopback(port: u16) -> Result<(Vec<TcpListener>, Vec<Endpoint>), BootstrapError> {
2573    bind_loopback_with(port, |port| TcpListener::bind((Ipv6Addr::LOCALHOST, port))).await
2574}
2575
2576async fn bind_loopback_with<F, Fut>(
2577    port: u16,
2578    mut bind_v6: F,
2579) -> Result<(Vec<TcpListener>, Vec<Endpoint>), BootstrapError>
2580where
2581    F: FnMut(u16) -> Fut,
2582    Fut: std::future::Future<Output = io::Result<TcpListener>>,
2583{
2584    let v4_host = Ipv4Addr::LOCALHOST;
2585    let v4 = TcpListener::bind((v4_host, port))
2586        .await
2587        .map_err(|source| BootstrapError::Bind {
2588            host: v4_host.to_string(),
2589            port,
2590            source,
2591        })?;
2592    let actual_port = v4
2593        .local_addr()
2594        .map_err(|source| BootstrapError::LocalAddr {
2595            host: v4_host.to_string(),
2596            source,
2597        })?
2598        .port();
2599
2600    let mut listeners = vec![v4];
2601    let mut endpoints = vec![Endpoint {
2602        host: v4_host.to_string(),
2603        port: actual_port,
2604    }];
2605
2606    let v6_host = Ipv6Addr::LOCALHOST;
2607    match bind_v6(actual_port).await {
2608        Ok(v6) => {
2609            listeners.push(v6);
2610            endpoints.push(Endpoint {
2611                host: v6_host.to_string(),
2612                port: actual_port,
2613            });
2614        }
2615        Err(err)
2616            if ipv6_loopback_unavailable(&err)
2617                || (port == 0 && err.kind() == io::ErrorKind::AddrInUse) =>
2618        {
2619            warn!(
2620                port = actual_port,
2621                error = %err,
2622                "IPv6 loopback unavailable; serving only IPv4 loopback"
2623            );
2624        }
2625        Err(source) => {
2626            drop(listeners);
2627            return Err(BootstrapError::Bind {
2628                host: v6_host.to_string(),
2629                port: actual_port,
2630                source,
2631            });
2632        }
2633    }
2634
2635    Ok((listeners, endpoints))
2636}
2637
2638fn ipv6_loopback_unavailable(err: &io::Error) -> bool {
2639    matches!(
2640        err.kind(),
2641        io::ErrorKind::AddrNotAvailable | io::ErrorKind::Unsupported
2642    ) || matches!(err.raw_os_error(), Some(47) | Some(49) | Some(97))
2643}
2644
2645struct AbortOnDrop<T> {
2646    handle: JoinHandle<T>,
2647}
2648
2649impl<T> AbortOnDrop<T> {
2650    fn new(handle: JoinHandle<T>) -> Self {
2651        Self { handle }
2652    }
2653
2654    async fn join(&mut self) -> Result<T, JoinError> {
2655        (&mut self.handle).await
2656    }
2657}
2658
2659impl<T> Drop for AbortOnDrop<T> {
2660    fn drop(&mut self) {
2661        if !self.handle.is_finished() {
2662            self.handle.abort();
2663        }
2664    }
2665}
2666
2667#[derive(Debug)]
2668pub(crate) struct StartLock {
2669    // Service boots keep the file holding the startup lock open for handover.
2670    _file: fs::File,
2671}
2672
2673impl Drop for StartLock {
2674    fn drop(&mut self) {
2675        // Closing alone leaves the lock held if a concurrent fork inherited
2676        // the open file description and has not exec'd yet. Unlock explicitly
2677        // so another daemon can start as soon as this owner releases the lock.
2678        if let Err(error) = FileExt::unlock(&self._file) {
2679            tracing::warn!(%error, "failed to release the singleton start lock");
2680        }
2681    }
2682}
2683
2684impl StartLock {
2685    #[cfg(any(target_os = "linux", target_os = "macos"))]
2686    pub(crate) fn file(&self) -> &fs::File {
2687        &self._file
2688    }
2689    async fn acquire(connection_file_path: &Path) -> Result<Self, BootstrapError> {
2690        let path = start_lock_path(connection_file_path);
2691        for _ in 0..START_LOCK_RETRIES {
2692            let file = match open_owner_only_lock(&path) {
2693                Ok(file) => file,
2694                Err(source) => return Err(BootstrapError::StartLockCreate { path, source }),
2695            };
2696            match FileExt::try_lock(&file) {
2697                Ok(()) => return Ok(Self { _file: file }),
2698                Err(TryLockError::WouldBlock) => sleep(START_LOCK_RETRY_DELAY).await,
2699                Err(TryLockError::Error(source)) => {
2700                    return Err(BootstrapError::StartLockCreate { path, source });
2701                }
2702            }
2703        }
2704
2705        Err(BootstrapError::StartLockBusy {
2706            path,
2707            attempts: START_LOCK_RETRIES,
2708        })
2709    }
2710}
2711
2712#[cfg(all(test, any(target_os = "linux", target_os = "macos")))]
2713pub(crate) async fn upgrade_runtime_for_test(
2714    root: &Path,
2715    supervisor: &Supervisor,
2716    executable: PathBuf,
2717) -> Arc<crate::control::upgrade_in_place::Runtime> {
2718    use crate::control::upgrade_in_place::{BootImage, Runtime};
2719
2720    let config = BootstrapConfig::new(root.join("connection.json"), 0);
2721    let run = crate::run_dir_lock::RunDirLock::acquire(&root.join("live-children.json")).unwrap();
2722    let publication = StartLock::acquire(&config.connection_file_path)
2723        .await
2724        .unwrap();
2725    #[cfg(target_os = "linux")]
2726    let image = fs::File::open("/proc/self/exe").unwrap();
2727    #[cfg(target_os = "macos")]
2728    let image = fs::File::open(&executable).unwrap();
2729    let boot = BootImage::capture(
2730        executable,
2731        Arc::new(image),
2732        "test".into(),
2733        None,
2734        None,
2735        &Default::default(),
2736    )
2737    .await
2738    .with_fixture_probe(root.join("must-not-exec"));
2739    boot.wait_for_digest().await.expect("fixture image hash");
2740    let runtime = Arc::new(Runtime::for_settings_cutover_test(
2741        boot,
2742        crate::supervise::handover::required_lock_roles(&config),
2743        run,
2744        supervisor.retained_children(),
2745    ));
2746    runtime.retain_publication(publication);
2747    runtime
2748}
2749
2750pub(crate) fn open_owner_only_lock(path: &Path) -> io::Result<fs::File> {
2751    let mut options = fs::OpenOptions::new();
2752    options.read(true).write(true).create(true);
2753    #[cfg(unix)]
2754    {
2755        use std::os::unix::fs::OpenOptionsExt;
2756        options.mode(0o600);
2757    }
2758    options.open(path)
2759}
2760
2761fn start_lock_path(connection_file_path: &Path) -> PathBuf {
2762    let file_name = connection_file_path
2763        .file_name()
2764        .map(|name| name.to_string_lossy())
2765        .unwrap_or_else(|| CONNECTION_FILE_NAME.into());
2766    let lock_name = format!("{file_name}.start-lock");
2767    connection_file_path
2768        .parent()
2769        .filter(|parent| !parent.as_os_str().is_empty())
2770        .unwrap_or_else(|| Path::new("."))
2771        .join(lock_name)
2772}
2773
2774/// Bootstrap-layer errors are deliberately typed so startup never panics for
2775/// ordinary daemon-discovery races or stale filesystem state.
2776#[derive(Debug)]
2777#[non_exhaustive]
2778pub enum BootstrapError {
2779    ConfigStore(String),
2780    #[cfg(any(target_os = "linux", target_os = "macos"))]
2781    Resume(io::Error),
2782    /// The bound server could not authenticate its own readiness probe.
2783    StartupNotServing,
2784    #[cfg(unix)]
2785    Signal(io::Error),
2786    InvalidPort {
2787        raw: String,
2788        source: std::num::ParseIntError,
2789    },
2790    ConnectionFileRead {
2791        path: PathBuf,
2792        source: ConnectionFileError,
2793    },
2794    ConnectionFileWrite {
2795        path: PathBuf,
2796        source: ConnectionFileError,
2797    },
2798    GenerateConnectionFile(ConnectionFileError),
2799    StartLockCreate {
2800        path: PathBuf,
2801        source: io::Error,
2802    },
2803    StartLockBusy {
2804        path: PathBuf,
2805        attempts: usize,
2806    },
2807    /// The run-directory lock file could not be created, opened or locked.
2808    RunDirLockCreate {
2809        path: PathBuf,
2810        source: io::Error,
2811    },
2812    /// Another live process, almost certainly a daemon started with a
2813    /// different runtime directory over the same data home, owns the run
2814    /// directory. The daemon does not start. `holder_pid` is read from the
2815    /// lock file when possible and is informational only.
2816    RunDirBusy {
2817        path: PathBuf,
2818        holder_pid: Option<u32>,
2819    },
2820    RemoveStale {
2821        path: PathBuf,
2822        source: io::Error,
2823    },
2824    Bind {
2825        host: String,
2826        port: u16,
2827        source: io::Error,
2828    },
2829    LocalAddr {
2830        host: String,
2831        source: io::Error,
2832    },
2833    DaemonConfig(DaemonConfigError),
2834    /// The machine id could not be established: its file is corrupt, unreadable
2835    /// or unwritable, or the data home is relative. The daemon does not start.
2836    MachineId(crate::machine_id::MachineIdFileError),
2837    /// The daemon run directory could not be resolved because the data home is
2838    /// relative. The daemon does not start.
2839    RunDir(daemon_config::DaemonRunDirError),
2840    Serve(ServerError),
2841    ServeJoin(tokio::task::JoinError),
2842}
2843
2844impl From<ServerError> for BootstrapError {
2845    fn from(error: ServerError) -> Self {
2846        Self::Serve(error)
2847    }
2848}
2849
2850impl fmt::Display for BootstrapError {
2851    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2852        match self {
2853            Self::ConfigStore(error) => write!(f, "configuration store startup refused: {error}"),
2854            #[cfg(any(target_os = "linux", target_os = "macos"))]
2855            Self::Resume(error) => write!(f, "daemon handover refused: {error}"),
2856            Self::StartupNotServing => write!(f, "bound daemon did not authenticate its readiness probe; connection file was not published"),
2857            #[cfg(unix)]
2858            Self::Signal(error) => write!(f, "failed to register SIGTERM handler: {error}"),
2859            Self::InvalidPort { raw, source } => {
2860                write!(f, "invalid {SUBC_PORT_ENV} value '{raw}': {source}")
2861            }
2862            Self::ConnectionFileRead { path, source } => write!(
2863                f,
2864                "failed to read connection file {}: {source}",
2865                path.display()
2866            ),
2867            Self::ConnectionFileWrite { path, source } => write!(
2868                f,
2869                "failed to publish connection file {}: {source}",
2870                path.display()
2871            ),
2872            Self::GenerateConnectionFile(err) => {
2873                write!(f, "failed to generate connection-file auth material: {err}")
2874            }
2875            Self::StartLockCreate { path, source } => {
2876                write!(
2877                    f,
2878                    "failed to create start lock {}: {source}",
2879                    path.display()
2880                )
2881            }
2882            Self::StartLockBusy { path, attempts } => write!(
2883                f,
2884                "start lock {} remained busy after {attempts} attempts",
2885                path.display()
2886            ),
2887            Self::RunDirLockCreate { path, source } => write!(
2888                f,
2889                "refusing to start: failed to lock run directory via {}: {source}",
2890                path.display()
2891            ),
2892            Self::RunDirBusy { path, holder_pid } => {
2893                write!(
2894                    f,
2895                    "refusing to start: run directory lock {} is held by another daemon",
2896                    path.display()
2897                )?;
2898                if let Some(pid) = holder_pid {
2899                    write!(f, " (pid {pid})")?;
2900                }
2901                write!(
2902                    f,
2903                    "; a live daemon owns this data home's run state (typically one started with a different XDG_RUNTIME_DIR)"
2904                )
2905            }
2906            Self::RemoveStale { path, source } => write!(
2907                f,
2908                "failed to remove stale connection file {}: {source}",
2909                path.display()
2910            ),
2911            Self::Bind { host, port, source } if source.kind() == io::ErrorKind::AddrInUse => {
2912                write!(
2913                    f,
2914                    "port {port} in use on loopback {host}: {source}; set the port in config"
2915                )
2916            }
2917            Self::Bind { host, port, source } => {
2918                write!(f, "failed to bind loopback TCP {host}:{port}: {source}")
2919            }
2920            Self::LocalAddr { host, source } => {
2921                write!(f, "failed to read local address for {host}: {source}")
2922            }
2923            Self::DaemonConfig(err) => write!(f, "failed to load daemon config: {err}"),
2924            Self::MachineId(err) => write!(f, "refusing to start: {err}"),
2925            Self::RunDir(err) => write!(f, "refusing to start: {err}"),
2926            Self::Serve(err) => write!(f, "daemon server failed: {err}"),
2927            Self::ServeJoin(err) => write!(f, "daemon server task failed: {err}"),
2928        }
2929    }
2930}
2931
2932impl Error for BootstrapError {
2933    fn source(&self) -> Option<&(dyn Error + 'static)> {
2934        match self {
2935            Self::ConfigStore(_) => None,
2936            #[cfg(any(target_os = "linux", target_os = "macos"))]
2937            Self::Resume(source) => Some(source),
2938            Self::StartupNotServing => None,
2939            #[cfg(unix)]
2940            Self::Signal(source) => Some(source),
2941            Self::InvalidPort { source, .. } => Some(source),
2942            Self::ConnectionFileRead { source, .. }
2943            | Self::ConnectionFileWrite { source, .. }
2944            | Self::GenerateConnectionFile(source) => Some(source),
2945            Self::StartLockCreate { source, .. }
2946            | Self::RunDirLockCreate { source, .. }
2947            | Self::RemoveStale { source, .. }
2948            | Self::Bind { source, .. }
2949            | Self::LocalAddr { source, .. } => Some(source),
2950            Self::DaemonConfig(err) => Some(err),
2951            Self::MachineId(err) => Some(err),
2952            Self::RunDir(err) => Some(err),
2953            Self::Serve(err) => Some(err),
2954            Self::ServeJoin(err) => Some(err),
2955            Self::StartLockBusy { .. } | Self::RunDirBusy { .. } => None,
2956        }
2957    }
2958}
2959
2960#[cfg(all(test, feature = "test-support", unix))]
2961#[path = "bootstrap_recovery_tests.rs"]
2962mod recovery_tests;
2963
2964#[cfg(test)]
2965mod tests {
2966    mod activity {
2967        include!("activity_bootstrap_tests.rs");
2968    }
2969    mod startup_order {
2970        include!("startup_order_tests.rs");
2971    }
2972    use super::*;
2973    use crate::server::ServerAuth;
2974    use cortexkit_test_support::ScratchDir;
2975    #[cfg(target_os = "linux")]
2976    use std::collections::BTreeSet;
2977    use std::sync::Mutex;
2978    #[cfg(target_os = "linux")]
2979    use subc_control::ModuleProtocol;
2980    use subc_transport::{write_atomic, MIN_KEY_LEN};
2981    use tokio::io::AsyncReadExt;
2982    use tokio::task::JoinHandle;
2983
2984    #[cfg(unix)]
2985    use std::os::unix::fs::PermissionsExt;
2986
2987    static ENV_LOCK: Mutex<()> = Mutex::new(());
2988
2989    #[test]
2990    fn normalized_build_provenance_preserves_real_values() {
2991        assert_eq!(normalized_build_provenance("abc"), Some("abc".to_string()));
2992    }
2993
2994    #[test]
2995    fn config_recovery_bootstrap_preserves_all_loaded_fields_and_only_argument_overrides() {
2996        let _env_lock = ENV_LOCK.lock().unwrap();
2997        let scratch = unique_temp_dir("bootstrap-loaded-fields");
2998        let file = scratch.join("subc.jsonc");
2999        std::fs::write(
3000            &file,
3001            br#"{"version":1,"modules":{},"scope_authority_owners":["file-owner"],"flow_scope_authority_owners":["flow-owner"]}"#,
3002        )
3003        .unwrap();
3004        let mut config = BootstrapConfig::new(scratch.join("connection.json"), 0)
3005            .with_daemon_config_source(file.clone(), None);
3006        config.defer_file_load = true;
3007        config.operator_timeout = Duration::from_secs(7);
3008        let selected = load_bootstrap_authority(config, None).unwrap();
3009        assert_eq!(
3010            selected.file_derived_test_probe,
3011            Some(vec!["file-owner".into()])
3012        );
3013        assert_eq!(selected.flow_scope_authority_owners, ["flow-owner"]);
3014        assert_eq!(selected.operator_timeout, Duration::from_secs(7));
3015        assert_eq!(selected.daemon_config_path, Some(file));
3016        assert_eq!(
3017            selected.connection_file_path,
3018            scratch.join("connection.json")
3019        );
3020    }
3021
3022    #[test]
3023    fn config_recovery_bootstrap_ignores_invalid_live_file_and_poisoned_settings() {
3024        let scratch = unique_temp_dir("recovery-bootstrap");
3025        let root = scratch.join("store");
3026        std::fs::create_dir_all(&root).unwrap();
3027        std::fs::write(
3028            root.join(crate::config_store::STORE_FILE),
3029            br#"{"format_version":999}"#,
3030        )
3031        .unwrap();
3032        let mut store = crate::config_store::ConfigStore::open_digest_only_for_tests(
3033            crate::config_store::StoreRoot::from_service_definition(root).unwrap(),
3034        );
3035        assert_eq!(
3036            store.status().state,
3037            crate::config_store::StoreState::StoreUnverified
3038        );
3039        let file = scratch.join("subc.jsonc");
3040        std::fs::write(&file, b"invalid live config").unwrap();
3041        let mut config = BootstrapConfig::new(scratch.join("connection.json"), 1)
3042            .with_daemon_config_source(file, Some(1))
3043            .with_scope_authority_owners(vec!["untrusted".into()])
3044            .with_reserved_capabilities(BTreeMap::from([("untrusted".into(), "untrusted".into())]));
3045        config.defer_file_load = true;
3046        config.file_derived_test_probe = Some(vec!["untrusted".into()]);
3047        let config = load_bootstrap_authority(config, Some(&mut store)).unwrap();
3048        assert_eq!(config.file_derived_test_probe, None);
3049        assert_eq!(config.port, DEFAULT_SUBC_PORT);
3050        assert!(config.configured_modules.is_empty());
3051        assert_eq!(
3052            config.scope_authority_owners,
3053            daemon_config::default_scope_authority_owners()
3054        );
3055        assert!(config.flow_scope_authority_owners.is_empty());
3056        assert!(config.reserved_capabilities.is_empty());
3057        assert_eq!(
3058            config.privileged_operator_prompt,
3059            daemon_config::PrivilegedOperatorPrompt::default()
3060        );
3061    }
3062
3063    /// An approved generation whose daemon bytes listen on `port`. Changing
3064    /// the port is a setting only bootstrap reads, so it waits for a restart.
3065    fn approved_port_entry(
3066        kind: crate::config_store::CommitKind,
3067        port: u16,
3068    ) -> crate::config_store::HistoryEntry {
3069        use subc_protocol::config::{ConfigLayer, ConfigLayerSnapshot};
3070        crate::config_store::HistoryEntry {
3071            generation: subc_config::Generation::new(
3072                0,
3073                subc_config::ApprovalChannel::OsPrompt,
3074                subc_config::raw_digest(b"approved-plan"),
3075                subc_config::InputVector::default(),
3076                subc_config::Changeset::new(),
3077            ),
3078            kind,
3079            approval_id: "approval".into(),
3080            outcome: "approved".into(),
3081            tuples: Default::default(),
3082            project_outcomes: Default::default(),
3083            configuration: Default::default(),
3084            delivery: Some(crate::config_store::DeliverySnapshot {
3085                daemon: Some(ConfigLayerSnapshot::file(
3086                    "subc",
3087                    ConfigLayer::User,
3088                    "/approved/subc.jsonc",
3089                    Some(format!(r#"{{"version":1,"port":{port},"modules":{{}}}}"#).into_bytes()),
3090                )),
3091                ..crate::config_store::DeliverySnapshot::default()
3092            }),
3093        }
3094    }
3095
3096    fn approve_port(
3097        store: &mut crate::config_store::ConfigStore,
3098        kind: crate::config_store::CommitKind,
3099        port: u16,
3100    ) {
3101        store
3102            .commit_generation(
3103                approved_port_entry(kind, port),
3104                Default::default(),
3105                Default::default(),
3106                1,
3107            )
3108            .unwrap();
3109    }
3110
3111    fn stamped_boot(
3112        scratch: &Path,
3113        store: &mut crate::config_store::ConfigStore,
3114    ) -> BootstrapConfig {
3115        let mut config = BootstrapConfig::new(scratch.join("connection.json"), 1)
3116            .with_daemon_config_source(scratch.join("subc.jsonc"), Some(1));
3117        config.defer_file_load = true;
3118        load_bootstrap_authority(config, Some(store)).unwrap()
3119    }
3120
3121    #[test]
3122    fn config_stamped_boot_uses_last_active_generation_until_restart_intent() {
3123        use crate::config_store::{CommitKind, ConfigStore, StoreRoot};
3124        let scratch = unique_temp_dir("stamped-boot-selection");
3125        let root = scratch.join("store");
3126        std::fs::create_dir_all(&root).unwrap();
3127        let open = || {
3128            ConfigStore::open_digest_only_for_tests(
3129                StoreRoot::from_service_definition(root.clone()).unwrap(),
3130            )
3131        };
3132        let mut store = open();
3133        approve_port(&mut store, CommitKind::Stamp, 41001);
3134        approve_port(&mut store, CommitKind::Approved, 41002);
3135        drop(store);
3136        let mut store = open();
3137        assert_eq!(
3138            stamped_boot(&scratch, &mut store).port,
3139            41001,
3140            "an ordinary start must not boot an approval still waiting for a daemon restart"
3141        );
3142        assert_eq!(store.assign_daemon_restart().unwrap(), Some(2));
3143        drop(store);
3144        let mut store = open();
3145        assert_eq!(stamped_boot(&scratch, &mut store).port, 41002);
3146    }
3147
3148    #[test]
3149    fn config_stamped_boot_enters_recovery_when_anchor_retry_fails_at_start() {
3150        use crate::config_store::{CommitKind, ConfigStore, StoreRoot, StoreState, TestStoreKey};
3151        let scratch = unique_temp_dir("stamped-boot-anchor-pending");
3152        let root = scratch.join("store");
3153        std::fs::create_dir_all(&root).unwrap();
3154        let key = TestStoreKey::default();
3155        let open = || {
3156            ConfigStore::open_sealed_for_tests(
3157                StoreRoot::from_service_definition(root.clone()).unwrap(),
3158                key.clone(),
3159            )
3160        };
3161        let mut store = open();
3162        approve_port(&mut store, CommitKind::Stamp, 41001);
3163        // Crash between publication and anchor: the bytes are renamed into
3164        // place but the anchor never catches up, and keeps failing at start.
3165        key.fail_anchor(true);
3166        assert!(store
3167            .commit_generation(
3168                approved_port_entry(CommitKind::Approved, 41001),
3169                Default::default(),
3170                Default::default(),
3171                2,
3172            )
3173            .is_err());
3174        drop(store);
3175        let mut store = open();
3176        let status = store.status();
3177        assert_eq!(status.state, StoreState::Stamped);
3178        assert!(status.anchor_pending);
3179        let config = stamped_boot(&scratch, &mut store);
3180        assert_eq!(config.port, DEFAULT_SUBC_PORT);
3181        assert!(config.configured_modules.is_empty());
3182        assert_eq!(store.status().state, StoreState::StoreUnverified);
3183    }
3184
3185    #[test]
3186    fn normalized_build_provenance_omits_unavailable_and_empty_values() {
3187        assert_eq!(normalized_build_provenance("unavailable"), None);
3188        assert_eq!(normalized_build_provenance(""), None);
3189    }
3190
3191    #[cfg(target_os = "linux")]
3192    fn current_cgroup_path_for_test() -> io::Result<PathBuf> {
3193        let cgroups = fs::read_to_string("/proc/self/cgroup")?;
3194        let relative = cgroups
3195            .lines()
3196            .find_map(|line| line.strip_prefix("0::"))
3197            .ok_or_else(|| {
3198                io::Error::new(io::ErrorKind::Unsupported, "cgroup v2 is unavailable")
3199            })?;
3200        Ok(Path::new("/sys/fs/cgroup").join(relative.trim_start_matches('/')))
3201    }
3202
3203    #[cfg(target_os = "linux")]
3204    fn module_cgroup_directories() -> io::Result<BTreeSet<OsString>> {
3205        let modules = current_cgroup_path_for_test()?.join("subc-modules");
3206        let entries = match fs::read_dir(modules) {
3207            Ok(entries) => entries,
3208            Err(error) if error.kind() == io::ErrorKind::NotFound => return Ok(BTreeSet::new()),
3209            Err(error) => return Err(error),
3210        };
3211        let mut directories = BTreeSet::new();
3212        for entry in entries {
3213            let entry = entry?;
3214            if entry.file_type()?.is_dir() {
3215                directories.insert(entry.file_name());
3216            }
3217        }
3218        Ok(directories)
3219    }
3220
3221    #[cfg(target_os = "linux")]
3222    async fn wait_for_path(path: &Path, task: &JoinHandle<Result<(), BootstrapError>>) {
3223        let deadline = tokio::time::Instant::now() + Duration::from_secs(5);
3224        while !path.exists() && tokio::time::Instant::now() < deadline {
3225            assert!(
3226                !task.is_finished(),
3227                "daemon exited before creating {}",
3228                path.display()
3229            );
3230            sleep(Duration::from_millis(10)).await;
3231        }
3232        assert!(path.exists(), "daemon did not create {}", path.display());
3233    }
3234
3235    /// An in-process daemon with the default (disabled) cgroup placement must
3236    /// leave the host's live module cgroup tree exactly as it found it.
3237    /// Red-checking this test (making it fail) creates a
3238    /// `cgroup-isolation-probe-*` directory in the live cgroup tree, which must be removed by hand.
3239    #[cfg(target_os = "linux")]
3240    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
3241    async fn run_with_config_does_not_reconcile_the_ambient_cgroup_by_default() {
3242        let temp = unique_temp_dir("bootstrap-cgroup-default-disabled");
3243        let module_id = format!("cgroup-isolation-probe-{}", process::id());
3244        let before = module_cgroup_directories().expect("read ambient module cgroups before boot");
3245        assert!(
3246            !before.contains(&OsString::from(&module_id)),
3247            "isolation probe cgroup already exists before this daemon starts"
3248        );
3249        let capture = temp.join("logs").join(format!("{module_id}.stderr.log"));
3250        let module = ConfiguredModule {
3251            script: None,
3252            carry_containment: false,
3253            module_id,
3254            program: PathBuf::from("sh"),
3255            args: vec!["-c".to_string(), "sleep 30".to_string()],
3256            env: Vec::new(),
3257            log: None,
3258            enabled: true,
3259            registration_channel: false,
3260            reserved: false,
3261            reserved_prefixes: Vec::new(),
3262            protocol: ModuleProtocol::None,
3263            overlap: Default::default(),
3264            health: HealthConfig::default(),
3265            drain_timeout_ms: None,
3266            register_timeout: crate::supervise::DEFAULT_REGISTER_TIMEOUT,
3267            route_bind_relay_timeout_ms: None,
3268            restart: RestartPolicy::default(),
3269        };
3270        let config = config_with_a_short_socket(BootstrapConfig::new(temp.join("c"), 0))
3271            .with_configured_modules([module])
3272            .with_capture_logs_dir(temp.join("logs"))
3273            .with_terminal_journal_path(temp.join("terminals.jsonl"));
3274        let task = tokio::spawn(run_with_config(config));
3275
3276        wait_for_path(&capture, &task).await;
3277        let after = module_cgroup_directories().expect("read ambient module cgroups after boot");
3278
3279        task.abort();
3280        assert!(task
3281            .await
3282            .expect_err("aborted daemon task must cancel")
3283            .is_cancelled());
3284        assert_eq!(
3285            before, after,
3286            "an in-process daemon must not create or reconcile ambient module cgroups"
3287        );
3288    }
3289
3290    #[cfg(target_os = "linux")]
3291    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
3292    async fn explicit_cgroup_root_is_prepared_inside_the_fixture_tree() {
3293        let temp = unique_temp_dir("bootstrap-cgroup-explicit-root");
3294        let cgroup_root = temp.join("cgroup");
3295        fs::create_dir(&cgroup_root).expect("create scratch cgroup root");
3296        fs::write(cgroup_root.join("cgroup.procs"), b"").expect("write scratch cgroup marker");
3297        let modules = cgroup_root.join("subc-modules");
3298        let config = config_with_a_short_socket(BootstrapConfig::new(temp.join("c"), 0))
3299            .with_cgroup_placement(CgroupPlacementConfig::Root(cgroup_root))
3300            .with_terminal_journal_path(temp.join("terminals.jsonl"));
3301        let task = tokio::spawn(run_with_config(config));
3302
3303        wait_for_path(&modules, &task).await;
3304
3305        task.abort();
3306        assert!(task
3307            .await
3308            .expect_err("aborted daemon task must cancel")
3309            .is_cancelled());
3310        assert!(
3311            fs::read_dir(&modules)
3312                .expect("read prepared modules directory")
3313                .next()
3314                .is_none(),
3315            "the delegation probe must clean up after itself"
3316        );
3317    }
3318
3319    struct EnvGuard {
3320        key: &'static str,
3321        previous: Option<OsString>,
3322    }
3323
3324    impl EnvGuard {
3325        fn set(key: &'static str, value: &Path) -> Self {
3326            let previous = env::var_os(key);
3327            env::set_var(key, value);
3328            Self { key, previous }
3329        }
3330
3331        fn set_str(key: &'static str, value: &str) -> Self {
3332            let previous = env::var_os(key);
3333            env::set_var(key, value);
3334            Self { key, previous }
3335        }
3336
3337        fn unset(key: &'static str) -> Self {
3338            let previous = env::var_os(key);
3339            env::remove_var(key);
3340            Self { key, previous }
3341        }
3342    }
3343
3344    impl Drop for EnvGuard {
3345        fn drop(&mut self) {
3346            match &self.previous {
3347                Some(value) => env::set_var(self.key, value),
3348                None => env::remove_var(self.key),
3349            }
3350        }
3351    }
3352
3353    fn unique_temp_dir(name: &str) -> ScratchDir {
3354        ScratchDir::new(name)
3355    }
3356
3357    fn temp_connection_file_path(name: &str) -> (ScratchDir, PathBuf) {
3358        let dir = unique_temp_dir(name);
3359        let path = dir.join("conn.json");
3360        (dir, path)
3361    }
3362
3363    fn auth_for(info: &ConnectionInfo) -> ServerAuth {
3364        ServerAuth::new(info.key.clone(), info.daemon_id, info.daemon_ver.clone())
3365    }
3366
3367    fn start_server(bound: BoundDaemon) -> JoinHandle<Result<(), ServerError>> {
3368        let auth = auth_for(&bound.connection_info);
3369        tokio::spawn(crate::server::serve_listeners(
3370            bound.listeners,
3371            Arc::new(Router::with_default_self_handler()),
3372            auth,
3373        ))
3374    }
3375
3376    fn expect_bound(outcome: Outcome) -> BoundDaemon {
3377        match outcome {
3378            Outcome::Bound(bound) => bound,
3379            Outcome::AlreadyRunning => panic!("fresh connection file unexpectedly had a daemon"),
3380        }
3381    }
3382
3383    async fn connect_from_info(conn: &ConnectionInfo) -> io::Result<TcpStream> {
3384        let endpoint = conn
3385            .endpoints
3386            .first()
3387            .expect("test connection file should have an endpoint");
3388        let ip: IpAddr = endpoint.host.parse().unwrap();
3389        TcpStream::connect(SocketAddr::new(ip, endpoint.port)).await
3390    }
3391
3392    fn make_connection_info(port: u16) -> ConnectionInfo {
3393        ConnectionInfo {
3394            schema: SCHEMA_VERSION,
3395            wire_version: Some(PROTOCOL_VERSION),
3396            endpoints: vec![Endpoint {
3397                host: "127.0.0.1".to_owned(),
3398                port,
3399            }],
3400            key: generate_key().unwrap(),
3401            daemon_id: generate_daemon_id().unwrap(),
3402            pid: process::id(),
3403            daemon_ver: "test-subc".to_owned(),
3404        }
3405    }
3406
3407    fn write_raw_owner_only_connection_file(path: &Path, contents: &[u8]) {
3408        fs::write(path, contents).unwrap();
3409        #[cfg(unix)]
3410        fs::set_permissions(path, fs::Permissions::from_mode(0o600)).unwrap();
3411    }
3412
3413    fn assert_owner_only_connection_file(path: &Path) {
3414        // `path` is only inspected on Unix (mode bits); on Windows the owner-only
3415        // guarantee comes from the inherited %TEMP% ACL, nothing to assert here.
3416        #[cfg(unix)]
3417        {
3418            let mode = fs::metadata(path).unwrap().permissions().mode() & 0o777;
3419            assert_eq!(mode, 0o600);
3420        }
3421        #[cfg(not(unix))]
3422        let _ = path;
3423    }
3424
3425    #[test]
3426    fn connection_file_path_source_is_xdg_runtime_dir_when_set() {
3427        let runtime_dir = OsString::from("/run/user/1000");
3428
3429        let (path, source) = connection_file_path_with_source(Some(runtime_dir), || {
3430            panic!("an explicit runtime directory needs no daemon run directory")
3431        });
3432
3433        assert_eq!(
3434            path,
3435            PathBuf::from("/run/user/1000").join(CONNECTION_FILE_NAME)
3436        );
3437        assert_eq!(source, ConnectionFileSource::XdgRuntimeDir);
3438    }
3439
3440    #[cfg(unix)]
3441    #[test]
3442    fn connection_file_path_uses_daemon_run_dir_without_xdg_runtime_dir() {
3443        for runtime_dir in [None, Some(OsString::new())] {
3444            let (path, source) = connection_file_path_with_source(runtime_dir, || {
3445                daemon_config::daemon_run_dir_from(PathBuf::from("/data/home"))
3446            });
3447
3448            assert_eq!(
3449                path,
3450                PathBuf::from("/data/home/cortexkit/run/subc-connection.json")
3451            );
3452            assert_eq!(source, ConnectionFileSource::DaemonRunDir);
3453        }
3454    }
3455
3456    #[cfg(unix)]
3457    #[test]
3458    fn connection_file_path_uses_temp_dir_with_relative_data_home() {
3459        let (path, source) = connection_file_path_with_source(None, || {
3460            daemon_config::daemon_run_dir_from(PathBuf::from("relative-data-home"))
3461        });
3462
3463        assert_eq!(
3464            path,
3465            env::temp_dir().join(format!("subc-{}.connection.json", user_connection_token()))
3466        );
3467        assert_eq!(source, ConnectionFileSource::TempDirFallback);
3468    }
3469
3470    #[cfg(unix)]
3471    #[tokio::test]
3472    async fn connection_file_path_creates_private_run_dir_before_start_lock() {
3473        use std::os::unix::fs::PermissionsExt;
3474
3475        let root = unique_temp_dir("connection-run-dir");
3476        let (path, source) = connection_file_path_with_source(None, || {
3477            daemon_config::daemon_run_dir_from(root.join("data"))
3478        });
3479        let parent = path.parent().unwrap();
3480        assert!(!parent.exists());
3481
3482        let config = BootstrapConfig::new(&path, 0).with_connection_file_source(source);
3483        let outcome = ensure_singleton_with_config(config).await.unwrap();
3484
3485        assert!(matches!(outcome, Outcome::Bound(_)));
3486        assert!(path.is_file());
3487        assert_eq!(
3488            fs::metadata(parent).unwrap().permissions().mode() & 0o777,
3489            0o700
3490        );
3491    }
3492
3493    /// Concurrent callers must derive one token. The former temp-file uid probe
3494    /// could fail transiently (same-tick name collision, fd exhaustion) and send
3495    /// the loser down the env-derived fallback with a different identity for the
3496    /// same user; this fence keeps identity independent of filesystem luck.
3497    #[test]
3498    fn user_connection_token_is_stable_under_concurrent_callers() {
3499        let expected = user_connection_token();
3500        let workers: Vec<_> = (0..32)
3501            .map(|_| {
3502                std::thread::spawn(|| (0..40).map(|_| user_connection_token()).collect::<Vec<_>>())
3503            })
3504            .collect();
3505        for worker in workers {
3506            for token in worker.join().expect("probe thread") {
3507                assert_eq!(token, expected, "token diverged under concurrent probes");
3508            }
3509        }
3510    }
3511
3512    #[cfg(not(unix))]
3513    #[test]
3514    fn connection_file_path_source_is_temp_dir_when_xdg_unset_or_empty() {
3515        for runtime_dir in [None, Some(OsString::new())] {
3516            let (path, source) = connection_file_path_with_source(runtime_dir, || {
3517                panic!("the daemon run directory is only checked on Unix")
3518            });
3519
3520            assert_eq!(
3521                path,
3522                env::temp_dir().join(format!("subc-{}.connection.json", user_connection_token()))
3523            );
3524            assert_eq!(source, ConnectionFileSource::TempDirFallback);
3525        }
3526    }
3527
3528    /// The shipped binary is the only caller that journals terminal exits into
3529    /// the real run directory, so its constructor must supply that path itself;
3530    /// the in-process default leaves it unset.
3531    #[test]
3532    fn daemon_binary_config_journals_and_captures_into_the_run_dir() {
3533        let _env_lock = ENV_LOCK.lock().unwrap();
3534        let root = unique_temp_dir("daemon-binary-config");
3535        let data_home = root.join("data");
3536        let _data = EnvGuard::set("XDG_DATA_HOME", &data_home);
3537        let _config = EnvGuard::set("XDG_CONFIG_HOME", &root.join("config"));
3538        let _port = EnvGuard::unset(SUBC_PORT_ENV);
3539
3540        let config = BootstrapConfig::from_env_for_daemon_binary().unwrap();
3541
3542        let run_dir = data_home.join("cortexkit").join("run");
3543        assert_eq!(
3544            config.terminal_journal_path,
3545            Some(run_dir.join("terminals.jsonl"))
3546        );
3547        assert_eq!(config.capture_logs_dir, Some(run_dir.join("logs")));
3548        assert_eq!(
3549            BootstrapConfig::new(root.join("connection.json"), 0).terminal_journal_path,
3550            None,
3551            "an in-process config must not journal anywhere unless asked to"
3552        );
3553    }
3554
3555    #[test]
3556    fn daemon_binary_config_refuses_a_relative_data_home() {
3557        let _env_lock = ENV_LOCK.lock().unwrap();
3558        let root = unique_temp_dir("daemon-binary-relative-data");
3559        let _data = EnvGuard::set_str("XDG_DATA_HOME", "relative-data-home");
3560        let _config = EnvGuard::set("XDG_CONFIG_HOME", &root.join("config"));
3561        let _port = EnvGuard::unset(SUBC_PORT_ENV);
3562
3563        let error = BootstrapConfig::from_env_for_daemon_binary()
3564            .expect_err("a relative data home must refuse the daemon binary's config");
3565        assert!(
3566            matches!(error, BootstrapError::RunDir(_)),
3567            "expected a run-directory refusal, got {error}"
3568        );
3569        assert!(error.to_string().contains("XDG_DATA_HOME"), "{error}");
3570    }
3571
3572    #[test]
3573    fn privileged_operator_prompt_is_loaded_by_both_bootstrap_config_paths() {
3574        let _env_lock = ENV_LOCK.lock().unwrap();
3575        let _port = EnvGuard::unset(SUBC_PORT_ENV);
3576        let (_dir, conn_path) = temp_connection_file_path("privileged-operator-prompt");
3577        let config_path = conn_path.with_file_name("subc.jsonc");
3578        for (doc, expected) in [
3579            (None, daemon_config::PrivilegedOperatorPrompt::Log),
3580            (
3581                Some(r#"{"version":1}"#),
3582                daemon_config::PrivilegedOperatorPrompt::Log,
3583            ),
3584            (
3585                Some(r#"{"version":1,"privileged_operator_prompt":"log"}"#),
3586                daemon_config::PrivilegedOperatorPrompt::Log,
3587            ),
3588            (
3589                Some(r#"{"version":1,"privileged_operator_prompt":"enforce"}"#),
3590                daemon_config::PrivilegedOperatorPrompt::Enforce,
3591            ),
3592        ] {
3593            if let Some(doc) = doc {
3594                fs::write(&config_path, doc).unwrap();
3595            }
3596            assert_eq!(
3597                BootstrapConfig::from_env_with_daemon_config_path(&config_path)
3598                    .unwrap()
3599                    .privileged_operator_prompt,
3600                expected
3601            );
3602            assert_eq!(
3603                BootstrapConfig::new(&conn_path, 0)
3604                    .with_daemon_config_path(&config_path)
3605                    .unwrap()
3606                    .privileged_operator_prompt,
3607                expected
3608            );
3609        }
3610    }
3611
3612    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
3613    async fn privileged_operator_prompt_is_snapshotted_by_running_daemon() {
3614        let dir = unique_temp_dir("privileged-operator-prompt-bootstrap");
3615        let connection_path = dir.join("connection.json");
3616        let config_path = dir.join("subc.jsonc");
3617        fs::write(
3618            &config_path,
3619            r#"{"version":1,"privileged_operator_prompt":"enforce"}"#,
3620        )
3621        .unwrap();
3622        let config = config_with_a_short_socket(BootstrapConfig::new(&connection_path, 0))
3623            .with_daemon_config_path(&config_path)
3624            .unwrap();
3625        let connection_path = config.connection_file_path.clone();
3626        let daemon = AbortOnDrop::new(tokio::spawn(run_with_config(config)));
3627        tokio::time::timeout(Duration::from_secs(5), async {
3628            while !connection_path.exists() {
3629                assert!(
3630                    !daemon.handle.is_finished(),
3631                    "daemon exited before publishing"
3632                );
3633                tokio::task::yield_now().await;
3634            }
3635        })
3636        .await
3637        .unwrap();
3638        let info = connection_file::read(&connection_path).unwrap();
3639        let mut client = connect_from_info(&info).await.unwrap();
3640        authenticate_client(&mut client, &info, Duration::from_secs(5))
3641            .await
3642            .unwrap();
3643        for (correlation, mode, expected) in [
3644            (1, "enforce", Vec::new()),
3645            (2, "log", vec!["privileged_operator_prompt"]),
3646            (3, "log", vec!["privileged_operator_prompt"]),
3647        ] {
3648            fs::write(
3649                &config_path,
3650                serde_json::json!({"version":1,"privileged_operator_prompt":mode}).to_string(),
3651            )
3652            .unwrap();
3653            let frame = crate::Frame::build(
3654                subc_protocol::FrameType::Request,
3655                subc_protocol::Flags::new(false, subc_protocol::Priority::Interactive, false),
3656                0,
3657                0,
3658                correlation,
3659                serde_json::to_vec(&subc_control::ClientControlRequest::SupervisorRescan {
3660                    preview: true,
3661                })
3662                .unwrap(),
3663            )
3664            .unwrap();
3665            crate::write_frame(&mut client, &frame).await.unwrap();
3666            let reply =
3667                tokio::time::timeout(Duration::from_secs(5), crate::read_frame(&mut client))
3668                    .await
3669                    .unwrap()
3670                    .unwrap()
3671                    .unwrap();
3672            assert_eq!(reply.header.ty, subc_protocol::FrameType::Response);
3673            assert_eq!(reply.header.corr, correlation);
3674            let subc_control::ClientControlResponse::SupervisorRescan { result } =
3675                serde_json::from_slice(&reply.body).unwrap()
3676            else {
3677                panic!("expected a rescan response");
3678            };
3679            assert_eq!(result.restart_required, expected);
3680        }
3681    }
3682
3683    #[test]
3684    fn configured_port_uses_default_config_and_env_override() {
3685        let _env_lock = ENV_LOCK.lock().unwrap();
3686        let (_dir, conn_path) = temp_connection_file_path("daemon-config-port");
3687        let config_path = conn_path.with_file_name("subc.jsonc");
3688
3689        let _port = EnvGuard::unset(SUBC_PORT_ENV);
3690        assert_eq!(
3691            BootstrapConfig::from_env_with_daemon_config_path(&config_path)
3692                .unwrap()
3693                .port,
3694            DEFAULT_SUBC_PORT
3695        );
3696
3697        fs::write(&config_path, r#"{ "version": 1, "port": 8123 }"#).unwrap();
3698        assert_eq!(
3699            BootstrapConfig::from_env_with_daemon_config_path(&config_path)
3700                .unwrap()
3701                .port,
3702            8123
3703        );
3704
3705        let _port = EnvGuard::set_str(SUBC_PORT_ENV, "9012");
3706        assert_eq!(
3707            BootstrapConfig::from_env_with_daemon_config_path(&config_path)
3708                .unwrap()
3709                .port,
3710            9012
3711        );
3712    }
3713
3714    #[tokio::test]
3715    async fn singleton_does_not_accept_a_peer_that_answers_once_then_exits() {
3716        let (_dir, path) = temp_connection_file_path("departing-peer");
3717        let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
3718        let info = make_connection_info(listener.local_addr().unwrap().port());
3719        write_connection_file(&path, &info, None).unwrap();
3720        let peer = tokio::spawn(async move {
3721            let (mut stream, _) = listener.accept().await.unwrap();
3722            subc_transport::authenticate_server(
3723                &mut stream,
3724                &info.key,
3725                &info.daemon_id,
3726                &info.daemon_ver,
3727                PROBE_AUTH_DEADLINE,
3728            )
3729            .await
3730            .unwrap();
3731        });
3732        let outcome = ensure_singleton(&path, 0).await.unwrap();
3733        peer.await.unwrap();
3734        assert!(
3735            matches!(outcome, Outcome::Bound(_)),
3736            "a departing peer is not AlreadyRunning"
3737        );
3738    }
3739
3740    #[tokio::test]
3741    async fn second_singleton_probe_against_served_tcp_daemon_reports_already_running() {
3742        let (_dir, path) = temp_connection_file_path("already-running");
3743
3744        let bound = expect_bound(ensure_singleton(&path, 0).await.unwrap());
3745        let server = start_server(bound);
3746
3747        let second = ensure_singleton(&path, 0).await.unwrap();
3748        assert!(matches!(second, Outcome::AlreadyRunning));
3749
3750        server.abort();
3751        let _ = server.await;
3752    }
3753
3754    #[tokio::test]
3755    async fn held_publication_lock_with_live_daemon_is_already_running() {
3756        let (_dir, path) = temp_connection_file_path("live-publication-lock");
3757        let config = BootstrapConfig::new(&path, 0);
3758        let mut bound = expect_bound(ensure_singleton_inner(config.clone(), false).await.unwrap());
3759        let publication = bound.publication_lock.take().unwrap();
3760        let info = bound.connection_info.clone();
3761        let server = start_server(bound);
3762
3763        // The peer was not yet published at the contender's first probe. It
3764        // must find the live peer after losing the lock to the first boot.
3765        let (contender, ()) = tokio::join!(ensure_singleton_inner(config, false), async {
3766            sleep(START_LOCK_RETRY_DELAY * 2).await;
3767            write_atomic(&path, &info).unwrap();
3768        });
3769        assert!(matches!(contender.unwrap(), Outcome::AlreadyRunning));
3770        assert!(matches!(
3771            FileExt::try_lock(&open_owner_only_lock(&start_lock_path(&path)).unwrap()),
3772            Err(TryLockError::WouldBlock)
3773        ));
3774        drop(publication);
3775        server.abort();
3776        let _ = server.await;
3777    }
3778
3779    #[tokio::test]
3780    async fn daemon_connection_file_publishes_protocol_wire_version() {
3781        let (_dir, path) = temp_connection_file_path("wire-version");
3782        let bound = expect_bound(ensure_singleton(&path, 0).await.unwrap());
3783        assert_eq!(bound.connection_info.wire_version, Some(PROTOCOL_VERSION));
3784        assert_eq!(
3785            connection_file::read(&path).unwrap().wire_version,
3786            Some(PROTOCOL_VERSION)
3787        );
3788
3789        drop(bound.listeners);
3790    }
3791
3792    #[tokio::test]
3793    async fn stale_unbound_connection_file_is_reclaimed() {
3794        let (_dir, path) = temp_connection_file_path("stale-reclaim");
3795        let stale = TcpListener::bind((Ipv4Addr::LOCALHOST, 0)).await.unwrap();
3796        let stale_port = stale.local_addr().unwrap().port();
3797        drop(stale);
3798        let stale_info = make_connection_info(stale_port);
3799        write_atomic(&path, &stale_info).unwrap();
3800
3801        let bound = expect_bound(ensure_singleton(&path, 0).await.unwrap());
3802        assert_ne!(bound.connection_info.key, stale_info.key);
3803        drop(bound.listeners);
3804    }
3805
3806    #[cfg(unix)]
3807    #[tokio::test]
3808    async fn ensure_singleton_reclaims_insecure_connection_file() {
3809        let (_dir, path) = temp_connection_file_path("insecure-reclaim");
3810        let stale = TcpListener::bind((Ipv4Addr::LOCALHOST, 0)).await.unwrap();
3811        let stale_port = stale.local_addr().unwrap().port();
3812        drop(stale);
3813        let stale_info = make_connection_info(stale_port);
3814        write_atomic(&path, &stale_info).unwrap();
3815        fs::set_permissions(&path, fs::Permissions::from_mode(0o644)).unwrap();
3816
3817        let bound = expect_bound(ensure_singleton(&path, 0).await.unwrap());
3818        assert_ne!(bound.connection_info.key, stale_info.key);
3819        assert_ne!(bound.connection_info.daemon_id, stale_info.daemon_id);
3820        assert_owner_only_connection_file(&path);
3821
3822        drop(bound.listeners);
3823    }
3824
3825    #[tokio::test]
3826    async fn ensure_singleton_reclaims_non_loopback_connection_file() {
3827        let (_dir, path) = temp_connection_file_path("non-loopback-reclaim");
3828        let mut stale_info = make_connection_info(8757);
3829        stale_info.endpoints = vec![Endpoint {
3830            host: "192.0.2.10".to_owned(),
3831            port: 8757,
3832        }];
3833        write_atomic(&path, &stale_info).unwrap();
3834
3835        let config = config_with_a_short_socket(BootstrapConfig::new(&path, 0));
3836        let bound = expect_bound(ensure_singleton_with_config(config).await.unwrap());
3837        assert_ne!(bound.connection_info.key, stale_info.key);
3838        assert_ne!(bound.connection_info.daemon_id, stale_info.daemon_id);
3839        assert!(bound
3840            .connection_info
3841            .endpoints
3842            .iter()
3843            .all(|endpoint| endpoint.host.parse::<IpAddr>().unwrap().is_loopback()));
3844        assert_owner_only_connection_file(&path);
3845
3846        drop(bound.listeners);
3847    }
3848
3849    #[tokio::test]
3850    async fn ensure_singleton_reclaims_invalid_connection_file_shapes() {
3851        let mut unsupported_schema = make_connection_info(8757);
3852        unsupported_schema.schema = SCHEMA_VERSION + 1;
3853
3854        let mut empty_endpoints = make_connection_info(8757);
3855        empty_endpoints.endpoints.clear();
3856
3857        let mut short_key = make_connection_info(8757);
3858        short_key.key = vec![0x5A; MIN_KEY_LEN - 1];
3859
3860        let cases = vec![
3861            (
3862                "unsupported-schema",
3863                serde_json::to_vec(&unsupported_schema).unwrap(),
3864                Some(unsupported_schema),
3865            ),
3866            (
3867                "empty-endpoints",
3868                serde_json::to_vec(&empty_endpoints).unwrap(),
3869                Some(empty_endpoints),
3870            ),
3871            (
3872                "short-key",
3873                serde_json::to_vec(&short_key).unwrap(),
3874                Some(short_key),
3875            ),
3876            ("invalid-json", b"{not valid connection json".to_vec(), None),
3877        ];
3878
3879        for (label, contents, old_info) in cases {
3880            let (_dir, path) = temp_connection_file_path(label);
3881            write_raw_owner_only_connection_file(&path, &contents);
3882
3883            let bound = expect_bound(ensure_singleton(&path, 0).await.unwrap());
3884            if let Some(old_info) = old_info {
3885                assert_ne!(bound.connection_info.key, old_info.key, "{label}");
3886                assert_ne!(
3887                    bound.connection_info.daemon_id, old_info.daemon_id,
3888                    "{label}"
3889                );
3890            }
3891            assert!(bound.connection_info.key.len() >= MIN_KEY_LEN, "{label}");
3892            assert_ne!(bound.connection_info.daemon_id, [0u8; 16], "{label}");
3893            assert_owner_only_connection_file(&path);
3894
3895            drop(bound.listeners);
3896        }
3897    }
3898
3899    #[tokio::test]
3900    async fn foreign_reused_port_connection_file_is_reclaimed_after_auth_probe_fails() {
3901        let (_dir, path) = temp_connection_file_path("foreign-reclaim");
3902        let foreign = TcpListener::bind((Ipv4Addr::LOCALHOST, 0)).await.unwrap();
3903        let foreign_port = foreign.local_addr().unwrap().port();
3904        write_atomic(&path, &make_connection_info(foreign_port)).unwrap();
3905        let foreign_task = tokio::spawn(async move {
3906            if let Ok((mut stream, _)) = foreign.accept().await {
3907                let mut buf = [0u8; 64];
3908                let _ = stream.read(&mut buf).await;
3909            }
3910        });
3911
3912        let bound = expect_bound(ensure_singleton(&path, 0).await.unwrap());
3913        assert!(bound
3914            .connection_info
3915            .endpoints
3916            .iter()
3917            .all(|endpoint| endpoint.port != foreign_port));
3918
3919        drop(bound.listeners);
3920        let _ = foreign_task.await;
3921    }
3922
3923    #[tokio::test]
3924    async fn stale_start_lock_file_is_reclaimable() {
3925        let (_dir, path) = temp_connection_file_path("start-lock-stale-file");
3926        let lock_path = start_lock_path(&path);
3927        drop(open_owner_only_lock(&lock_path).unwrap());
3928        assert!(lock_path.is_file());
3929
3930        let lock = StartLock::acquire(&path).await.unwrap();
3931        assert!(lock_path.is_file());
3932
3933        drop(lock);
3934        assert!(lock_path.is_file());
3935    }
3936
3937    #[tokio::test]
3938    async fn held_start_lock_blocks_second_acquire_until_release() {
3939        let (_dir, path) = temp_connection_file_path("start-lock-held");
3940        let lock_path = start_lock_path(&path);
3941        let first = StartLock::acquire(&path).await.unwrap();
3942
3943        let err = match StartLock::acquire(&path).await {
3944            Ok(_) => panic!("second acquire while held must stay busy"),
3945            Err(err) => err,
3946        };
3947        assert!(matches!(
3948            err,
3949            BootstrapError::StartLockBusy {
3950                ref path,
3951                attempts: START_LOCK_RETRIES,
3952            } if path == &lock_path
3953        ));
3954
3955        drop(first);
3956
3957        let second = StartLock::acquire(&path)
3958            .await
3959            .expect("released advisory lock should be reclaimable");
3960        drop(second);
3961    }
3962
3963    #[tokio::test]
3964    async fn bind_conflict_on_fixed_port_fails_loud_without_reselecting() {
3965        let (_dir, path) = temp_connection_file_path("bind-conflict");
3966        let occupied = TcpListener::bind((Ipv4Addr::LOCALHOST, 0)).await.unwrap();
3967        let occupied_port = occupied.local_addr().unwrap().port();
3968
3969        let err = ensure_singleton(&path, occupied_port).await.unwrap_err();
3970        assert!(matches!(
3971            err,
3972            BootstrapError::Bind { ref source, .. } if source.kind() == io::ErrorKind::AddrInUse
3973        ));
3974        assert!(err.to_string().contains("set the port in config"));
3975
3976        drop(occupied);
3977    }
3978
3979    #[tokio::test]
3980    async fn ephemeral_ipv6_collision_still_serves_ipv4() {
3981        let (listeners, endpoints) = bind_loopback_with(0, |port| async move {
3982            let occupied = TcpListener::bind((Ipv6Addr::LOCALHOST, port)).await?;
3983            let result = TcpListener::bind((Ipv6Addr::LOCALHOST, port)).await;
3984            drop(occupied);
3985            result
3986        })
3987        .await
3988        .expect("an incidental IPv6 collision must not prevent an ephemeral daemon from starting");
3989        assert_eq!(endpoints.len(), 1);
3990        assert_eq!(endpoints[0].host, "127.0.0.1");
3991        TcpStream::connect((Ipv4Addr::LOCALHOST, endpoints[0].port))
3992            .await
3993            .unwrap();
3994        drop(listeners);
3995    }
3996
3997    #[tokio::test]
3998    async fn unpublished_boot_holds_singleton_lock_until_publication() {
3999        let dir = ScratchDir::new("ul");
4000        let path = dir.join("c");
4001        let config = config_with_a_short_socket(BootstrapConfig::new(&path, 0));
4002        let bound = expect_bound(ensure_singleton_inner(config, false).await.unwrap());
4003        assert!(!path.exists());
4004        let contender = open_owner_only_lock(&start_lock_path(&path)).unwrap();
4005        assert!(
4006            matches!(FileExt::try_lock(&contender), Err(TryLockError::WouldBlock)),
4007            "an unpublished boot must keep its singleton claim"
4008        );
4009        drop(bound);
4010        FileExt::try_lock(&contender).unwrap();
4011    }
4012
4013    #[tokio::test]
4014    async fn start_lock_drop_releases_claim_with_a_shared_file_description() {
4015        let dir = ScratchDir::new("sl");
4016        let path = dir.join("c");
4017        let config = config_with_a_short_socket(BootstrapConfig::new(&path, 0));
4018        let bound = expect_bound(ensure_singleton_inner(config, false).await.unwrap());
4019        // try_clone shares the open file description just as fork does,
4020        // without relying on the timing of another test's child spawn.
4021        let inherited = bound
4022            .publication_lock
4023            .as_ref()
4024            .unwrap()
4025            ._file
4026            .try_clone()
4027            .unwrap();
4028        let contender = open_owner_only_lock(&start_lock_path(&path)).unwrap();
4029        assert!(matches!(
4030            FileExt::try_lock(&contender),
4031            Err(TryLockError::WouldBlock)
4032        ));
4033        drop(bound);
4034        FileExt::try_lock(&contender).expect("dropping bootstrap releases even an inherited lock");
4035        drop(inherited);
4036    }
4037
4038    #[tokio::test]
4039    async fn readiness_probe_requires_an_authenticating_server() {
4040        let dir = ScratchDir::new("unserved-readiness");
4041        let bound = expect_bound(
4042            ensure_singleton_inner(BootstrapConfig::new(dir.join("connection.json"), 0), false)
4043                .await
4044                .unwrap(),
4045        );
4046        assert!(matches!(
4047            verify_serving(&bound.connection_info).await,
4048            Err(BootstrapError::StartupNotServing)
4049        ));
4050    }
4051
4052    #[cfg(unix)]
4053    #[tokio::test]
4054    async fn orphan_sweep_finishes_before_connection_file_publication() {
4055        use crate::live_children::{ExecutableIdentity, LiveChild};
4056        let dir = ScratchDir::new("pas");
4057        // A one-letter connection file name, and no long socket path: the sweep
4058        // this test covers runs before the local endpoint is bound, so a longer
4059        // name would only add a way for the test to fail on something else.
4060        let path = dir.join("c");
4061        let record = dir.join("live-children.json");
4062        let ready = dir.join("ready");
4063        let mut child = std::process::Command::new("/bin/sh")
4064            .args([
4065                "-c",
4066                "trap '' TERM; : > \"$0\"; read -r _",
4067                ready.to_str().unwrap(),
4068            ])
4069            .stdin(std::process::Stdio::piped())
4070            .env("XDG_DATA_HOME", dir.path())
4071            .env("XDG_RUNTIME_DIR", dir.path())
4072            .env("XDG_CONFIG_HOME", dir.path())
4073            .spawn()
4074            .unwrap();
4075        timeout(Duration::from_secs(5), async {
4076            while !ready.exists() {
4077                sleep(Duration::from_millis(5)).await;
4078            }
4079        })
4080        .await
4081        .unwrap();
4082        let observed = subc_os::Process::open(child.id())
4083            .unwrap()
4084            .unwrap()
4085            .observe()
4086            .unwrap();
4087        crate::live_children::write_record(
4088            &record,
4089            &[LiveChild {
4090                container: None,
4091                module_id: "old-sleep".into(),
4092                pid: child.id(),
4093                protocol: subc_control::ModuleProtocol::None,
4094                start_time: Some(observed.start_time),
4095                executable: observed.executable.map(ExecutableIdentity::from),
4096                cgroup_name: None,
4097            }],
4098        )
4099        .unwrap();
4100        let config = config_with_a_short_socket(BootstrapConfig::new(&path, 0))
4101            .with_live_children_record(&record);
4102        let daemon = tokio::spawn(run_with_config(config));
4103        timeout(Duration::from_secs(5), async {
4104            while !path.exists() {
4105                sleep(Duration::from_millis(5)).await;
4106            }
4107        })
4108        .await
4109        .unwrap();
4110        assert!(path.exists());
4111        let ended = child.try_wait().unwrap().is_some();
4112        if !ended {
4113            child.kill().unwrap();
4114        }
4115        child.wait().unwrap();
4116        if ended {
4117            assert!(matches!(probe_existing(&path).await.unwrap(), Probe::Live));
4118        }
4119        daemon.abort();
4120        let _ = daemon.await;
4121        assert!(
4122            ended,
4123            "the published daemon must not still owe its orphan sweep"
4124        );
4125    }
4126
4127    /// Publishing the connection file fsyncs, which can take seconds on a busy
4128    /// disk, so the daemon must do it off the async worker thread. The hook
4129    /// blocks inside the write until another task on the same single-threaded
4130    /// runtime has run. Writing on the worker thread would starve that task: the
4131    /// hook then gives up after its deadline and the test fails, as it does if
4132    /// startup publishes without going through the hooked write at all.
4133    #[tokio::test(flavor = "current_thread")]
4134    async fn connection_file_publication_leaves_the_async_runtime_free() {
4135        use std::sync::atomic::{AtomicBool, Ordering};
4136
4137        let (_dir, path) = temp_connection_file_path("publish-off-runtime");
4138        let write_started = Arc::new(AtomicBool::new(false));
4139        let (progress_tx, progress_rx) = std::sync::mpsc::channel::<()>();
4140        let (verdict_tx, verdict_rx) = std::sync::mpsc::channel::<bool>();
4141        let hook_started = Arc::clone(&write_started);
4142        connection_file_write_hook::install(&path, move || {
4143            hook_started.store(true, Ordering::SeqCst);
4144            let progressed = progress_rx.recv_timeout(Duration::from_secs(5)).is_ok();
4145            let _ = verdict_tx.send(progressed);
4146        });
4147        // Signals only after the write has started, so a message can only come
4148        // from this task running while the write is still blocked.
4149        let ticker = tokio::spawn(async move {
4150            loop {
4151                if write_started.load(Ordering::SeqCst) {
4152                    let _ = progress_tx.send(());
4153                    return;
4154                }
4155                sleep(Duration::from_millis(5)).await;
4156            }
4157        });
4158
4159        let daemon = tokio::spawn(run_with_config(BootstrapConfig::new(&path, 0)));
4160        let published = timeout(Duration::from_secs(15), async {
4161            while !path.exists() && !daemon.is_finished() {
4162                sleep(Duration::from_millis(5)).await;
4163            }
4164        })
4165        .await;
4166        let daemon_exited = daemon.is_finished();
4167        daemon.abort();
4168        let daemon_result = daemon.await;
4169        ticker.abort();
4170
4171        assert!(
4172            published.is_ok() && !daemon_exited,
4173            "the daemon must start and publish its connection file: {daemon_result:?}"
4174        );
4175        match verdict_rx.try_recv() {
4176            Ok(true) => {}
4177            Ok(false) => panic!(
4178                "no other task on the runtime ran while the connection file was being written: the write is blocking the async worker thread"
4179            ),
4180            Err(_) => panic!("startup published the connection file without the hooked write"),
4181        }
4182    }
4183
4184    /// A write that never reports back must stop startup with an error naming
4185    /// the connection file, never be taken as published.
4186    #[tokio::test]
4187    async fn a_panicking_connection_file_write_fails_startup() {
4188        let (_dir, path) = temp_connection_file_path("publish-panics");
4189        connection_file_write_hook::install(&path, || {
4190            panic!("deliberate panic inside the connection-file write")
4191        });
4192
4193        let error = timeout(
4194            Duration::from_secs(15),
4195            run_with_config(BootstrapConfig::new(&path, 0)),
4196        )
4197        .await
4198        .expect("startup must end once the write task fails")
4199        .expect_err("startup must fail when the connection-file write panics");
4200
4201        assert!(
4202            matches!(&error, BootstrapError::ConnectionFileWrite { path: failed, .. } if failed == &path),
4203            "expected a connection-file write error, got {error:?}"
4204        );
4205        let message = error.to_string();
4206        assert!(message.contains(&path.display().to_string()), "{message}");
4207        assert!(message.contains("panicked"), "{message}");
4208        assert!(!path.exists(), "no connection file may be published");
4209    }
4210
4211    #[cfg(target_os = "macos")]
4212    #[test]
4213    fn nofile_raise_worker() {
4214        let Some(path) = std::env::var_os("SUBC_NOFILE_TEST_FILE") else {
4215            return;
4216        };
4217        let (_, hard) = rlimit::Resource::NOFILE.get().unwrap();
4218        rlimit::Resource::NOFILE.set(256, hard).unwrap();
4219        raise_nofile_limit_with_ceiling(Some(10240));
4220        std::fs::write(path, rlimit::Resource::NOFILE.get().unwrap().0.to_string()).unwrap();
4221    }
4222
4223    #[cfg(target_os = "macos")]
4224    #[test]
4225    fn macos_nofile_raise_clamps_to_kernel_ceiling() {
4226        let dir = ScratchDir::new("nofile-ceiling");
4227        let result = dir.join("soft");
4228        let status = std::process::Command::new(std::env::current_exe().unwrap())
4229            .args(["--exact", "bootstrap::tests::nofile_raise_worker"])
4230            .env("SUBC_NOFILE_TEST_FILE", &result)
4231            .env("XDG_DATA_HOME", dir.path())
4232            .env("XDG_RUNTIME_DIR", dir.path())
4233            .env("XDG_CONFIG_HOME", dir.path())
4234            .status()
4235            .unwrap();
4236        assert!(status.success());
4237        let soft: u64 = std::fs::read_to_string(result).unwrap().parse().unwrap();
4238        assert!(
4239            soft > 256 && soft <= 10240,
4240            "the inherited limit must be raised within the kernel ceiling; got {soft}"
4241        );
4242    }
4243
4244    #[tokio::test]
4245    async fn key_rotation_republishes_new_material_and_old_file_fails_auth() {
4246        let (_dir, path) = temp_connection_file_path("key-rotation");
4247        let first = expect_bound(ensure_singleton(&path, 0).await.unwrap());
4248        let old_info = first.connection_info.clone();
4249        let fixed_port = old_info.endpoints[0].port;
4250        drop(first.listeners);
4251
4252        let second = expect_bound(ensure_singleton(&path, fixed_port).await.unwrap());
4253        let new_info = second.connection_info.clone();
4254        assert_ne!(old_info.key, new_info.key);
4255        assert_ne!(old_info.daemon_id, new_info.daemon_id);
4256        let server = start_server(second);
4257
4258        let mut old_stream = connect_from_info(&old_info).await.unwrap();
4259        let old_auth = authenticate_client(&mut old_stream, &old_info, PROBE_AUTH_DEADLINE).await;
4260        assert!(
4261            old_auth.is_err(),
4262            "old key must not authenticate after restart"
4263        );
4264
4265        let reread = connection_file::read(&path).unwrap();
4266        let mut new_stream = connect_from_info(&reread).await.unwrap();
4267        authenticate_client(&mut new_stream, &reread, PROBE_AUTH_DEADLINE)
4268            .await
4269            .unwrap();
4270
4271        server.abort();
4272        let _ = server.await;
4273    }
4274
4275    #[cfg(unix)]
4276    #[tokio::test]
4277    async fn published_connection_file_permissions_are_owner_only() {
4278        let (_dir, path) = temp_connection_file_path("permissions");
4279        let bound = expect_bound(ensure_singleton(&path, 0).await.unwrap());
4280
4281        let mode = fs::metadata(&path).unwrap().permissions().mode() & 0o777;
4282        assert_eq!(mode, 0o600);
4283
4284        drop(bound.listeners);
4285    }
4286
4287    /// A config with the socket in `dir`'s own short subdirectory.
4288    ///
4289    /// A Unix socket path is limited to just over a hundred bytes, and this
4290    /// harness's temporary directories use nearly all of that, so a test that
4291    /// boots a real daemon passes a short directory and a one-letter connection
4292    /// file name; anything longer makes the bind refuse. On Windows there is no
4293    /// socket path to keep short, so the config is returned unchanged.
4294    fn config_with_a_short_socket(config: BootstrapConfig) -> BootstrapConfig {
4295        let dir = config
4296            .connection_file_path
4297            .parent()
4298            .map(Path::to_path_buf)
4299            .unwrap_or_else(|| PathBuf::from("."));
4300        #[cfg(unix)]
4301        let config = BootstrapConfig {
4302            connection_file_path: dir.join("c"),
4303            local_listener: LocalListenerConfig::in_socket_dir(dir.join("s")),
4304            ..config
4305        };
4306        #[cfg(not(unix))]
4307        let _ = dir;
4308        config
4309    }
4310
4311    /// The shipped binary puts the socket in its own run directory. The file is
4312    /// named from the connection file's path, so a restart finds it again.
4313    #[cfg(unix)]
4314    #[test]
4315    fn the_daemon_binary_puts_its_socket_in_the_run_directory() {
4316        let _env_lock = ENV_LOCK.lock().unwrap();
4317        let root = ScratchDir::new("binary-local-socket");
4318        let data_home = root.join("data");
4319        let _data = EnvGuard::set("XDG_DATA_HOME", &data_home);
4320        let _config = EnvGuard::set("XDG_CONFIG_HOME", &root.join("config"));
4321        let _port = EnvGuard::unset(SUBC_PORT_ENV);
4322
4323        let config = BootstrapConfig::from_env_for_daemon_binary().unwrap();
4324
4325        let run_dir = data_home.join("cortexkit").join("run");
4326        assert_eq!(
4327            config.local_listener.configured_dir(),
4328            Some(run_dir.as_path()),
4329            "the binary serves from its run directory"
4330        );
4331        let socket = local_listener::socket_path_for(Some(&run_dir), &config.connection_file_path)
4332            .expect("the binary config names a directory");
4333        assert_eq!(socket.parent().unwrap(), run_dir);
4334        assert_eq!(
4335            socket.file_name().unwrap().to_string_lossy(),
4336            "subc.sock",
4337            "a fixed name: the run directory belongs to one data home"
4338        );
4339    }
4340
4341    /// An in-process daemon that names no directory serves TCP only: it publishes
4342    /// no local endpoint, creates nothing under the data home, and says nothing is
4343    /// unavailable, because nothing was asked for.
4344    /// The environment lock covers only the setup: the daemon under test reads
4345    /// its data home from the process environment while it boots, and holding
4346    /// the lock across that await would block every other test that sets one.
4347    #[cfg(unix)]
4348    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
4349    async fn an_in_process_daemon_without_a_configured_directory_serves_no_local_endpoint() {
4350        let root = ScratchDir::new("in-process-no-local-socket");
4351        let data_home = root.join("data");
4352        fs::create_dir_all(&data_home).unwrap();
4353        let connection_path = root.join("c");
4354        let _data;
4355        let _config;
4356        let _port;
4357        {
4358            let _env_lock = ENV_LOCK.lock().unwrap();
4359            _data = EnvGuard::set("XDG_DATA_HOME", &data_home);
4360            _config = EnvGuard::set("XDG_CONFIG_HOME", &root.join("config"));
4361            _port = EnvGuard::unset(SUBC_PORT_ENV);
4362        }
4363
4364        let bound = expect_bound(ensure_singleton(&connection_path, 0).await.unwrap());
4365
4366        assert!(bound.local_endpoint.is_none());
4367        assert!(bound.local_endpoint_unavailable.is_none());
4368        let published = connection_file::read_with_local_endpoint(&connection_path).unwrap();
4369        assert!(published.local_endpoint.is_none());
4370        assert!(
4371            local_listener::socket_path_for(None, &connection_path).is_none(),
4372            "no configured directory, no socket"
4373        );
4374        let mut leftovers = Vec::new();
4375        let mut pending = vec![data_home.clone()];
4376        while let Some(dir) = pending.pop() {
4377            for entry in fs::read_dir(&dir).unwrap() {
4378                let entry = entry.unwrap();
4379                let path = entry.path();
4380                if entry.file_type().unwrap().is_dir() {
4381                    pending.push(path.clone());
4382                }
4383                if entry.file_name().to_string_lossy().ends_with(".sock") {
4384                    leftovers.push(path);
4385                }
4386            }
4387        }
4388        assert!(
4389            leftovers.is_empty(),
4390            "an in-process daemon must not create a socket in the data home: {leftovers:?}"
4391        );
4392    }
4393
4394    /// A local endpoint that cannot be bound does not stop the daemon: it keeps
4395    /// serving TCP, publishes no local endpoint, and reports the reason where an
4396    /// operator reads daemon facts. Every module stays up for a feature nothing
4397    /// has to use.
4398    #[cfg(unix)]
4399    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
4400    async fn a_daemon_whose_socket_path_is_too_long_still_serves_tcp() {
4401        let dir = ScratchDir::new("tcp-only");
4402        let canonical = std::fs::canonicalize(&dir).unwrap();
4403        let connection_path = canonical.join("c");
4404        // The socket directory is deep enough that the socket's path is over the
4405        // Unix socket limit, so binding it must fail.
4406        let deep = canonical.join("x".repeat(80));
4407        fs::create_dir(&deep).unwrap();
4408        fs::set_permissions(&deep, fs::Permissions::from_mode(0o700)).unwrap();
4409        let config =
4410            BootstrapConfig::new(&connection_path, 0).with_local_listener_socket_dir(&deep);
4411        let bound = expect_bound(ensure_singleton_with_config(config).await.unwrap());
4412        assert!(
4413            bound.local_endpoint.is_none(),
4414            "a socket that cannot be bound is not published"
4415        );
4416        assert!(
4417            bound
4418                .local_endpoint_unavailable
4419                .as_deref()
4420                .is_some_and(|reason| reason.contains("too long")),
4421            "{:?}",
4422            bound.local_endpoint_unavailable
4423        );
4424        let published = connection_file::read_with_local_endpoint(&connection_path).unwrap();
4425        assert!(published.local_endpoint.is_none());
4426        assert!(
4427            !published.info.endpoints.is_empty(),
4428            "TCP is still published"
4429        );
4430
4431        // The daemon serves TCP as usual.
4432        let server = start_server(bound);
4433        let info = connection_file::read(&connection_path).unwrap();
4434        let mut client = connect_from_info(&info).await.unwrap();
4435        authenticate_client(&mut client, &info, PROBE_AUTH_DEADLINE)
4436            .await
4437            .expect("a TCP client still completes the handshake");
4438        server.abort();
4439        let _ = server.await;
4440    }
4441
4442    /// The published file names the local endpoint the daemon actually serves,
4443    /// and a client that trusts the file completes the handshake over it.
4444    #[cfg(unix)]
4445    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
4446    async fn published_connection_file_names_the_served_local_endpoint() {
4447        let (_dir, path) = temp_connection_file_path("local-endpoint");
4448        // The socket goes in the system temporary directory rather than inside
4449        // the harness's own directory, whose long lockdown-sandbox path leaves
4450        // no room inside the Unix socket path limit.
4451        let short_socket_dir = std::env::temp_dir().join(format!("subc-bt-{}", std::process::id()));
4452        let config =
4453            BootstrapConfig::new(&path, 0).with_local_listener_socket_dir(&short_socket_dir);
4454        let bound = expect_bound(ensure_singleton_with_config(config).await.unwrap());
4455        let endpoint = connection_file::read_with_local_endpoint(&path)
4456            .unwrap()
4457            .local_endpoint
4458            .expect("the daemon serves a local endpoint, so the file names it");
4459        assert_eq!(Some(&endpoint), bound.local_endpoint.as_ref());
4460        let LocalEndpoint::Unix { path: socket_path } = &endpoint else {
4461            panic!("a Unix daemon publishes a socket path");
4462        };
4463        assert_eq!(socket_path.parent().unwrap(), short_socket_dir);
4464        assert_eq!(
4465            fs::metadata(socket_path).unwrap().permissions().mode() & 0o777,
4466            0o600
4467        );
4468
4469        let router = Arc::new(Router::with_default_self_handler());
4470        let auth = auth_for(&bound.connection_info);
4471        let server = tokio::spawn(serve_local_listener(
4472            bound.local_listener.expect("the local listener is bound"),
4473            router,
4474            auth,
4475        ));
4476        let mut client = tokio::net::UnixStream::connect(socket_path).await.unwrap();
4477        authenticate_client(&mut client, &bound.connection_info, Duration::from_secs(5))
4478            .await
4479            .expect("a socket client completes the same handshake as a TCP client");
4480
4481        server.abort();
4482        drop(bound.listeners);
4483    }
4484
4485    /// A configured directory that is not a directory refuses at bind rather
4486    /// than publishing an endpoint nothing serves.
4487    #[cfg(unix)]
4488    #[test]
4489    fn a_socket_directory_that_is_a_file_refuses() {
4490        let dir = ScratchDir::new("local-listener-file-as-dir");
4491        let file = dir.join("not-a-directory");
4492        fs::write(&file, b"x").unwrap();
4493        let error = local_listener::bind(
4494            &LocalListenerConfig::in_socket_dir(file),
4495            &dir.join("connection.json"),
4496        )
4497        .expect_err("a path that is not a directory cannot hold the socket");
4498        assert!(matches!(error, ServerError::LocalAccept { .. }), "{error}");
4499    }
4500
4501    /// The socket sits directly in the configured directory under one fixed
4502    /// name, and a directory that would put the path over the platform limit is
4503    /// refused rather than shortened around.
4504    #[cfg(unix)]
4505    #[test]
4506    fn the_socket_path_stays_within_the_unix_limit() {
4507        let run_dir = PathBuf::from("/tmp/short-run");
4508        assert!(
4509            local_listener::socket_path_for(None, &run_dir.join("one.json")).is_none(),
4510            "no configured directory means no socket"
4511        );
4512        let socket = local_listener::socket_path_for(Some(&run_dir), &run_dir.join("one.json"))
4513            .expect("a configured directory gets a socket");
4514        assert_eq!(socket, run_dir.join("subc.sock"));
4515        assert_eq!(
4516            socket,
4517            local_listener::socket_path_for(Some(&run_dir), &run_dir.join("two.json")).unwrap(),
4518            "the name does not come from the connection file"
4519        );
4520
4521        let deep = PathBuf::from(format!("/tmp/{}", "x".repeat(60)));
4522        let long = local_listener::socket_path_for(Some(&deep), &deep.join("conn.json"))
4523            .expect("a configured directory gets a socket");
4524        assert!(
4525            long.as_os_str().len() < 104,
4526            "{} is {} bytes",
4527            long.display(),
4528            long.as_os_str().len()
4529        );
4530    }
4531}