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