Skip to main content

subc_daemon/
bootstrap.rs

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