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    let (disk_status, disk_monitor_task) =
1485        crate::disk_monitor::spawn(daemon_config::default_data_home().join("cortexkit"));
1486    let _disk_monitor_task = AbortOnDrop::new(disk_monitor_task);
1487    #[cfg(feature = "test-support")]
1488    supervisor_handle.set_shutdown_intent_window(shutdown_intent_window);
1489    let connected_clients = ConnectedClients::new();
1490    #[cfg(any(target_os = "linux", target_os = "macos"))]
1491    let store_writer = opened_store.as_ref().and_then(|(_, lock)| {
1492        crate::control::upgrade_in_place::witness(
1493            crate::supervise::handover::LockRole::StoreWriter,
1494            lock.file(),
1495        )
1496        .ok()
1497    });
1498    let daemon_incarnation = format!(
1499        "{:032x}",
1500        u128::from_be_bytes(bound.connection_info.daemon_id)
1501    );
1502    let config_runtime = if let Some((store, writer_lock)) = opened_store {
1503        let path = daemon_config_path.clone().ok_or_else(|| {
1504            BootstrapError::ConfigStore(
1505                "an explicit daemon config path is required with a config store".into(),
1506            )
1507        })?;
1508        let config_home = daemon_config::default_config_home();
1509        let incarnation = daemon_incarnation.clone();
1510        let projects = Arc::new(
1511            crate::config_gate::project_registry::EntorhinalProjectRegistry::new(
1512                registry.clone(),
1513                forwarding.clone(),
1514            ),
1515        );
1516        Some(Arc::new(
1517            tokio::task::spawn_blocking(move || {
1518                crate::config_gate::runtime::RuntimeOwner::new(
1519                    incarnation,
1520                    store,
1521                    crate::config_gate::capture::ConfigCapturer {
1522                        daemon_path: path,
1523                        config_home,
1524                        projects,
1525                    },
1526                )
1527                .with_policy_root_data(daemon_config::default_data_home().join("cortexkit"))
1528                .with_settings_recovery_data(daemon_config::default_data_home().join("cortexkit"))
1529                .enable_project_settings()
1530                .retain_writer_lock(writer_lock)
1531                .map_err(io::Error::other)
1532            })
1533            .await
1534            .map_err(|e| BootstrapError::ConfigStore(e.to_string()))?
1535            .map_err(|e| BootstrapError::ConfigStore(e.to_string()))?,
1536        ))
1537    } else {
1538        None
1539    };
1540    let _config_plan_sweep = config_runtime.as_ref().map(|runtime| {
1541        let runtime = Arc::downgrade(runtime);
1542        AbortOnDrop::new(tokio::spawn(async move {
1543            let mut interval =
1544                tokio::time::interval(crate::config_gate::runtime::PLAN_SWEEP_INTERVAL);
1545            loop {
1546                interval.tick().await;
1547                let Some(runtime) = runtime.upgrade() else {
1548                    break;
1549                };
1550                match tokio::task::spawn_blocking(move || runtime.sweep_expired()).await {
1551                    Ok(Ok(())) => {}
1552                    result => tracing::warn!(?result, "configuration plan expiry sweep failed"),
1553                }
1554            }
1555        }))
1556    });
1557    let supervisor = Supervisor::new(Arc::clone(&registry), RestartPolicy::default())
1558        .with_process_liveness(process_liveness.clone())
1559        .with_forwarding(Arc::clone(&forwarding))
1560        .with_handle(supervisor_handle.clone())
1561        .with_connection_file_path(bound.connection_file_path.clone())
1562        .with_daemon_incarnation(daemon_incarnation.clone());
1563    let supervisor = match &config_runtime {
1564        Some(owner) => supervisor.with_config_runtime(owner.clone()),
1565        None => supervisor,
1566    };
1567    let supervisor = match privacy_trampoline {
1568        Some(path) => supervisor.with_privacy_trampoline(path),
1569        None => supervisor,
1570    };
1571    // ABSENT MEANS NO CAPTURE AND NO JOURNAL, NOT "THE REAL RUN DIRECTORY", and
1572    // the difference is a production-corruption hazard rather than a preference.
1573    // Both fields below follow the same rule: `None` for `capture_logs_dir`
1574    // means supervised output is not captured, and `None` for
1575    // `terminal_journal_path` means terminal history lives only in each
1576    // module's in-memory ring (`supervisor.terminals` still answers, with the
1577    // journal counters at zero).
1578    //
1579    // The terminal journal used to fall back to
1580    // `daemon_run_dir().join("terminals.jsonl")`, so an in-process test daemon
1581    // appended its fixture exits to the operator's journal, where they then
1582    // appeared in `ck module terminals`.
1583    //
1584    // The capture line used to be `unwrap_or_else(|| daemon_run_dir().join("logs"))`,
1585    // so ANY caller that did not set the field captured supervised children into
1586    // the operator's live `~/.local/share/cortexkit/run/logs/`. That is twelve
1587    // sibling repos whose integration tests boot an in-process daemon through
1588    // `run_with_config` -- none of which asked for it, and none of which can see
1589    // it from their side.
1590    //
1591    // Harmless while fixture module ids are fixture-shaped: this host carries 20
1592    // zero-byte files from subc's own tests (good-aft, missing-aft,
1593    // preview-consumer...). THE HAZARD IS A COLLISION. A fixture named "broca"
1594    // or "aft" appends to a PRODUCTION capture file that operators read
1595    // forensically and that placement gates count lines in -- with no residue to
1596    // notice, because the file legitimately exists and legitimately grows.
1597    //
1598    // Found by BROCA (2026-09-19) from the other side: their rigs spawn the
1599    // SHIPPED ck-subc and set XDG_CONFIG_HOME + XDG_RUNTIME_DIR but not
1600    // XDG_DATA_HOME, so every local rig run supervised a module named "broca"
1601    // and captured it into production's broca.stderr.log -- the same file I
1602    // count seal lines in before and after placing their binaries.
1603    //
1604    // The supervisor already treats `None` as no-capture and no-journal, so
1605    // this only removes invented defaults. The binary keeps capturing and
1606    // journaling via `BootstrapConfig::from_env_for_daemon_binary`.
1607
1608    // Keep both ledgers in the explicitly selected run directory. An embedded
1609    // daemon without a journal path must not write to the operator's live ledger.
1610    let activity_run_dir = terminal_journal_path
1611        .as_ref()
1612        .and_then(|path| path.parent())
1613        .map(Path::to_path_buf);
1614    let supervisor = match terminal_journal_path {
1615        Some(path) => supervisor.with_terminal_journal(path, daemon_incarnation.clone()),
1616        None => supervisor,
1617    };
1618    let supervisor = match capture_logs_dir {
1619        Some(dir) => supervisor.with_capture_logs_dir(dir),
1620        None => supervisor,
1621    };
1622    let supervisor = match &run_dir_lock {
1623        Some(owner) => supervisor.with_owned_live_children_record(owner, protected),
1624        None => supervisor,
1625    };
1626    #[cfg(target_os = "linux")]
1627    let supervisor = supervisor.with_cgroup_placement(cgroup_placement);
1628    // Collect per-module route.bind relay overrides BEFORE handing the
1629    // `configured_modules` vector to the supervisor (which only needs each
1630    // module's `drain_timeout_ms`). Each entry was filled in by parse-time
1631    // resolution (per-module > daemon-wide > absent), so modules with no
1632    // override are absent from this map and the daemon-wide default applies.
1633    let route_bind_relay_timeouts = configured_modules
1634        .iter()
1635        .filter_map(|module| {
1636            module
1637                .route_bind_relay_timeout_ms
1638                .map(|ms| (module.module_id.clone(), Duration::from_millis(ms)))
1639        })
1640        .collect::<std::collections::BTreeMap<_, _>>();
1641    let mut control = ControlHandler::with_forwarding(Arc::clone(&registry), forwarding)
1642        .with_daemon_version(bound.connection_info.daemon_ver.clone())
1643        .with_process_liveness(process_liveness)
1644        .with_supervisor(supervisor_handle.clone())
1645        // The same flag `begin_daemon_shutdown` sets below, so requirement
1646        // changes while modules exit during the shutdown log at INFO.
1647        .with_daemon_shutdown_flag(supervisor.daemon_shutdown_flag())
1648        .with_connected_clients(connected_clients.clone())
1649        .with_disk_status(disk_status)
1650        .with_local_endpoint_unavailable(bound.local_endpoint_unavailable.clone())
1651        .with_storage_config(storage_config)
1652        .with_machine_id(bound.machine_id.clone())
1653        .with_admission_facts_config(admission_facts.carrier_module_id, admission_facts.targets)
1654        .with_scope_authority_owners(scope_authority_owners)
1655        .with_flow_scope_authority_owners(flow_scope_authority_owners)
1656        .with_federated_scope_owner(federated_scope_owner)
1657        .with_privileged_operator_prompt(privileged_operator_prompt)
1658        .with_route_bind_relay_timeouts(route_bind_relay_timeouts)
1659        .with_daemon_provenance(
1660            bound.connection_info.pid,
1661            daemon_start_clock.started_at_ms(),
1662            std::env::current_exe().ok(),
1663            normalized_build_provenance(env!("SUBC_BUILD_GIT_SHA")),
1664            normalized_build_provenance(env!("SUBC_BUILD_LOCK_DIGEST")),
1665        )
1666        .with_daemon_start_clock(daemon_start_clock)
1667        .with_capability_config(
1668            configured_modules
1669                .iter()
1670                .map(|module| (module.module_id.clone(), module.enabled)),
1671            reserved_capabilities,
1672        );
1673    if let Some(run_dir) = activity_run_dir {
1674        control =
1675            control.with_activity_ledger_config(&run_dir, daemon_incarnation, activity_config);
1676    }
1677    let daemon_ready_runtime = config_runtime.clone();
1678    if let Some(runtime) = config_runtime {
1679        control = control.with_explicit_config_store(runtime);
1680    }
1681    #[cfg(feature = "test-support")]
1682    if config_test_seam::enabled() {
1683        control = control.with_config_os_prompt_policy_for_tests();
1684    }
1685    #[cfg(feature = "test-support")]
1686    if let Some(harness) = test_operator_app_harness {
1687        warn!(%harness, "test operator-app route stamp active");
1688        control.test_operator_app_harness = Some(harness);
1689    }
1690    if let Some(ms) = route_bind_relay_default_ms {
1691        // A daemon-wide config value overrides the built-in default; a
1692        // `None` here leaves the ControlHandler's 12s default in place.
1693        control = control.with_route_bind_relay_timeout(Duration::from_millis(ms));
1694    }
1695    if let Some(config_path) = daemon_config_path {
1696        control = control.with_supervisor_rescan(supervisor.clone(), config_path, configured_port);
1697        control = control.with_supervisor_rescan_entries(&configured_modules);
1698    }
1699    #[cfg(all(test, feature = "test-support"))]
1700    let control = if let Some(adapt) = test_control {
1701        // A test hook is not a substitute for the executable-name guard.
1702        let executable =
1703            std::env::current_exe().map_err(|e| BootstrapError::ConfigStore(e.to_string()))?;
1704        if !executable
1705            .file_name()
1706            .is_some_and(|name| name.to_string_lossy().starts_with("ckdev-"))
1707        {
1708            return Err(BootstrapError::ConfigStore(
1709                "test control requires a ckdev executable".into(),
1710            ));
1711        }
1712        adapt(control)
1713    } else {
1714        control
1715    };
1716    let tcp_listeners: Vec<_> = bound.listeners.into_iter().map(Arc::new).collect();
1717    #[cfg(any(target_os = "linux", target_os = "macos"))]
1718    let (control, upgrade_runtime, _run_dir_lock) = match (upgrade, run_dir_lock) {
1719        (Some(startup), Some(run_dir)) if bound.local_listener.is_some() => {
1720            let mut control = control;
1721            let runtime = Arc::new(
1722                crate::control::upgrade_in_place::Runtime::new(
1723                    startup.boot,
1724                    startup.required,
1725                    run_dir,
1726                    store_writer,
1727                    supervisor.retained_children(),
1728                    startup.hooks,
1729                )
1730                .with_listeners(&tcp_listeners),
1731            );
1732            control.upgrade = Some(runtime.clone());
1733            (control, Some(runtime), None)
1734        }
1735        (_, run_dir_lock) => (control, None, run_dir_lock),
1736    };
1737    let control = Arc::new(control);
1738    let router = Arc::new(Router::with_control_handler(Arc::clone(&control)));
1739    let auth = ServerAuth::new(
1740        bound.connection_info.key.clone(),
1741        bound.connection_info.daemon_id,
1742        bound.connection_info.daemon_ver.clone(),
1743    )
1744    .with_connected_clients(connected_clients);
1745
1746    // Discovery must expose every accepted configured module, including disabled
1747    // ones. Registration creates status handles but neither starts monitors
1748    // nor launches processes: children need the published file for `--subc`.
1749    let mut registered_modules = Vec::with_capacity(configured_modules.len());
1750    #[cfg(any(target_os = "linux", target_os = "macos"))]
1751    let mut registered_cohort = BTreeMap::new();
1752    for configured in configured_modules {
1753        let enabled = configured.enabled;
1754        let health = configured.health.clone();
1755        let module_id = configured.module_id.clone();
1756        #[cfg(any(target_os = "linux", target_os = "macos"))]
1757        let cohort_enabled = adoption
1758            .as_ref()
1759            .and_then(|plan| plan.enabled(&module_id, enabled));
1760        let registered = match supervisor.register_configured_with_health(
1761            configured.module_spec(),
1762            enabled,
1763            health.clone(),
1764            configured.drain_timeout_ms,
1765            configured.restart,
1766            configured.register_timeout,
1767        ) {
1768            Ok(registered) => registered,
1769            Err(err) => {
1770                error!(module_id = %module_id, error = %err, "failed to supervise configured module; continuing daemon startup");
1771                continue;
1772            }
1773        };
1774        // A relaxed threshold can silently outlive the temporary allowance
1775        // that required it, so report the extra tolerance on every boot.
1776        let default_threshold = HealthConfig::default().failure_threshold;
1777        if enabled && health.failure_threshold > default_threshold {
1778            warn!(
1779                module_id = %module_id,
1780                failure_threshold = health.failure_threshold,
1781                default_threshold,
1782                tolerance_secs = health.cadence.as_secs() * u64::from(health.failure_threshold),
1783                "health failure threshold is relaxed above the default; a wedged module stays unflagged for longer"
1784            );
1785        }
1786        info!(module_id = %module_id, enabled, "configured module registered");
1787        #[cfg(any(target_os = "linux", target_os = "macos"))]
1788        if let Some(effective) = cohort_enabled {
1789            registered_cohort.insert(module_id, (registered, effective));
1790            continue;
1791        }
1792        registered_modules.push(registered);
1793    }
1794    control.refresh_capability_requirements();
1795
1796    let publish = |lock| {
1797        publish_connection_file(
1798            &bound.connection_file_path,
1799            #[cfg(windows)]
1800            bound.connection_file_copy.as_deref(),
1801            &bound.connection_info,
1802            bound.local_endpoint.as_ref(),
1803            lock,
1804        )
1805    };
1806    #[cfg(any(target_os = "linux", target_os = "macos"))]
1807    let preparations = adoption
1808        .as_ref()
1809        .map(|plan| plan.stage_preparations(&supervisor_handle, &registered_cohort))
1810        .transpose()?
1811        .unwrap_or_default();
1812    #[cfg(any(target_os = "linux", target_os = "macos"))]
1813    let (resumed_listener, local_ready) = adoption
1814        .as_ref()
1815        .map(|plan| {
1816            let (ready, wait) = tokio::sync::oneshot::channel();
1817            (Some((plan.monotonic_ns, ready)), Some(wait))
1818        })
1819        .unwrap_or_default();
1820
1821    // The local endpoint is served beside TCP and answers the same handshake.
1822    // Only a carried child with a valid resume HELLO can register on it.
1823    let local_serve_task = bound.local_listener.map(|listener| {
1824        let router = router.clone();
1825        let auth = auth.clone();
1826        AbortOnDrop::new(tokio::spawn(async move {
1827            #[cfg(any(target_os = "linux", target_os = "macos"))]
1828            if let Some((sample, ready)) = resumed_listener {
1829                #[cfg(feature = "test-support")]
1830                if let Some(path) = local_listener_gate {
1831                    if let Err(error) =
1832                        crate::control::upgrade_in_place::wait_at_gate(&path, 1).await
1833                    {
1834                        warn!(%error, "could not wait at the resume local listener test gate");
1835                    }
1836                }
1837                return crate::server::serve_resumed_local_listener(
1838                    listener,
1839                    router,
1840                    auth,
1841                    move || {
1842                        resume::log_accept(sample);
1843                        let _ = ready.send(());
1844                    },
1845                )
1846                .await;
1847            }
1848            serve_local_listener(listener, router, auth).await
1849        }))
1850    });
1851    let mut serve_task = AbortOnDrop::new(tokio::spawn(serve_shared_listeners(
1852        tcp_listeners,
1853        router,
1854        auth,
1855    )));
1856    // On Unix the task is dropped below to stop accepting at shutdown. Windows
1857    // leaves it to the process exit; naming it keeps the binding uniform.
1858    #[cfg(windows)]
1859    let _local_serve_task = local_serve_task;
1860    // The connection file promises clients can authenticate immediately, even
1861    // while individual modules are still preparing to resume.
1862    verify_serving(&bound.connection_info).await?;
1863    #[cfg(any(target_os = "linux", target_os = "macos"))]
1864    if let Some(ready) = local_ready {
1865        timeout(PROBE_AUTH_DEADLINE, ready)
1866            .await
1867            .map_err(|_| BootstrapError::StartupNotServing)?
1868            .map_err(|_| BootstrapError::StartupNotServing)?;
1869    }
1870    let (published, lock) = publish(publication_lock.take()).await;
1871    published?;
1872    publication_lock = lock.flatten();
1873    #[cfg(any(target_os = "linux", target_os = "macos"))]
1874    let planned = if let Some(adoption) = adoption {
1875        if let Some(runtime) = &upgrade_runtime {
1876            if let Some(lock) = publication_lock.take() {
1877                runtime.retain_publication(lock);
1878            }
1879        }
1880        // A child being adopted may exit during installation and need a
1881        // replacement. Do not start these preparations before publishing.
1882        adoption
1883            .install(&supervisor, registered_cohort, preparations)
1884            .await?
1885    } else {
1886        Vec::new()
1887    };
1888    // Serving and discoverable: a daemon booted from a restart intent records
1889    // readiness, which makes that generation the daemon's active one. Without
1890    // this record the next start treats the warm-up as failed.
1891    if let Some(owner) = daemon_ready_runtime {
1892        if let Err(error) = owner.on_blocking(|owner| owner.record_daemon_ready()).await {
1893            warn!(%error, "daemon readiness was not recorded in the approved store");
1894        }
1895    }
1896    #[cfg(test)]
1897    startup_publication_hook::run(&bound.connection_file_path).await;
1898    #[cfg(not(any(target_os = "linux", target_os = "macos")))]
1899    drop(publication_lock);
1900    let _clock_step_task = AbortOnDrop::new(crate::watchdog::spawn_clock_step_monitor());
1901    let _stalled_cancel_task =
1902        AbortOnDrop::new(control.forwarding().spawn_stalled_cancel_monitor());
1903    // Off the startup path: it runs `systemctl`, and only ever logs.
1904    #[cfg(target_os = "linux")]
1905    let _kill_mode_check = AbortOnDrop::new(tokio::spawn(
1906        crate::systemd_kill_mode::warn_if_kill_mode_defeats_ordered_shutdown(),
1907    ));
1908    let _watchdog_task = AbortOnDrop::new(
1909        DaemonSelfWatchdog::new(
1910            bound.connection_info.clone(),
1911            bound.connection_file_path.clone(),
1912        )
1913        .with_config(watchdog_config)
1914        .spawn(),
1915    );
1916
1917    #[cfg(any(target_os = "linux", target_os = "macos"))]
1918    for (module, registered, enabled) in planned {
1919        if let Err(error) = supervisor
1920            .start_planned_after_upgrade(&module, registered, enabled)
1921            .await
1922        {
1923            error!(module_id = %module, %error, "failed to start a planned upgrade replacement");
1924        }
1925    }
1926    for registered in registered_modules {
1927        match supervisor
1928            .start_registered_configured_async(registered, None, true)
1929            .await
1930        {
1931            Ok(module) => {
1932                info!(module_id = %module.module_id(), "configured module supervised");
1933            }
1934            Err(err) => {
1935                error!(error = %err, "failed to start configured module; continuing daemon startup");
1936            }
1937        }
1938    }
1939
1940    control.refresh_capability_requirements();
1941    Arc::clone(&control).spawn_capability_deadline_loop();
1942    Arc::clone(&control).spawn_scope_expiry_loop();
1943    let _config_delivery_task = control.spawn_config_delivery_worker().map(AbortOnDrop::new);
1944    let _pending_settings_task = control
1945        .spawn_pending_settings_worker()
1946        .map(AbortOnDrop::new);
1947    control.spawn_resource_sampler();
1948    #[cfg(any(target_os = "linux", target_os = "macos"))]
1949    if let Some(runtime) = &upgrade_runtime {
1950        if let Some(lock) = publication_lock.take() {
1951            runtime.retain_publication(lock);
1952        }
1953    }
1954
1955    #[cfg(unix)]
1956    {
1957        tokio::select! {
1958            result = serve_task.join() => {
1959                return result.map_err(BootstrapError::ServeJoin)?.map_err(BootstrapError::Serve);
1960            }
1961            _ = terminate.recv() => {}
1962        }
1963        #[cfg(any(target_os = "linux", target_os = "macos"))]
1964        if let Some(runtime) = &upgrade_runtime {
1965            runtime.shutdown().await;
1966        }
1967        // First, before the notice, the drain, or any connection close: from
1968        // here on a module exit is recorded as `daemon_shutdown` and never
1969        // respawned. Also before allowing a second signal to cut the bounded
1970        // wait short, so the journal marker is queued first.
1971        supervisor.begin_daemon_shutdown();
1972        // Stop the self-watchdog before closing the listener. Its next tick would
1973        // connect to that listener, fail, and log an ERROR indistinguishable from
1974        // a wedged daemon, once for every interval a planned stop lasts.
1975        drop(_watchdog_task);
1976        // Dropping the listener stops new accepts, not established connections:
1977        // their detached tasks must remain live throughout notice and drain. The
1978        // local endpoint stops accepting the same way.
1979        drop(serve_task);
1980        drop(local_serve_task);
1981        let second_sigterm = async {
1982            terminate.recv().await;
1983            std::time::Instant::now()
1984        };
1985        tokio::pin!(second_sigterm);
1986        let mut escalation_started = tokio::select! {
1987            biased;
1988            at = second_sigterm.as_mut() => {
1989                info!("second SIGTERM: abandoning daemon shutdown wait");
1990                Some(at)
1991            }
1992            result = supervisor.drain_for_daemon_shutdown() => {
1993                if let Err(error) = result {
1994                    warn!(%error, "daemon shutdown drain failed; exiting anyway");
1995                }
1996                None
1997            }
1998        };
1999        // Supervised modules lead their own process groups, so a service
2000        // manager's kill of this process's group does not reach them. (A
2001        // systemd unit with KillMode=control-group kills by cgroup instead and
2002        // does reach them; see `systemd_kill_mode`.) The daemon ends them
2003        // itself: EOF (or SIGTERM for a protocol none child) first, then
2004        // signals at each child's own drain deadline.
2005        let already_escalated = escalation_started.is_some();
2006        supervisor
2007            .end_children_for_daemon_shutdown(already_escalated, async {
2008                if already_escalated {
2009                    std::future::pending::<()>().await;
2010                } else {
2011                    escalation_started = Some(second_sigterm.await);
2012                }
2013            })
2014            .await;
2015        if let Some(at) = escalation_started {
2016            info!(
2017                second_sigterm_elapsed_ms = at.elapsed().as_millis() as u64,
2018                "daemon shutdown wait ended after second SIGTERM"
2019            );
2020        }
2021        info!("daemon exiting: SIGTERM shutdown complete");
2022        Ok(())
2023    }
2024    #[cfg(not(unix))]
2025    serve_task
2026        .join()
2027        .await
2028        .map_err(BootstrapError::ServeJoin)?
2029        .map_err(BootstrapError::Serve)
2030}
2031
2032fn normalized_build_provenance(value: &str) -> Option<String> {
2033    match value.trim() {
2034        "" | "unavailable" => None,
2035        value => Some(value.to_string()),
2036    }
2037}
2038
2039/// Find an existing daemon or atomically bind loopback TCP for this daemon.
2040///
2041/// The algorithm is intentionally connect-first: an endpoint from the connection
2042/// file is treated as live only after the TCP+key server-proof authenticates for
2043/// that file's key and daemon_id. Stale or foreign connection files are reclaimed
2044/// only while holding the per-user start lock; the TCP port is never the
2045/// singleton primitive.
2046pub async fn ensure_singleton(
2047    connection_file_path: impl AsRef<Path>,
2048    port: u16,
2049) -> Result<Outcome, BootstrapError> {
2050    ensure_singleton_with_config(BootstrapConfig::new(connection_file_path.as_ref(), port)).await
2051}
2052
2053pub async fn ensure_singleton_with_config(
2054    config: BootstrapConfig,
2055) -> Result<Outcome, BootstrapError> {
2056    ensure_singleton_inner(config, true).await
2057}
2058
2059async fn ensure_singleton_inner(
2060    config: BootstrapConfig,
2061    publish: bool,
2062) -> Result<Outcome, BootstrapError> {
2063    let Some(lock) = singleton_start_lock(&config).await? else {
2064        return Ok(Outcome::AlreadyRunning);
2065    };
2066    ensure_singleton_with_start_lock(config, publish, lock).await
2067}
2068
2069async fn singleton_start_lock(
2070    config: &BootstrapConfig,
2071) -> Result<Option<StartLock>, BootstrapError> {
2072    let path = &config.connection_file_path;
2073    if stable_peer(path).await? {
2074        return Ok(None);
2075    }
2076
2077    #[cfg(unix)]
2078    if config.connection_file_source == ConnectionFileSource::DaemonRunDir {
2079        // The binary prepares the run directory for logging first. Embedded
2080        // daemons can reach the start lock before anything creates its parent.
2081        if let Some(parent) = path
2082            .parent()
2083            .filter(|p| !p.as_os_str().is_empty() && !p.exists())
2084        {
2085            daemon_config::ensure_directory_private(parent).map_err(|source| {
2086                BootstrapError::StartLockCreate {
2087                    path: start_lock_path(path),
2088                    source,
2089                }
2090            })?;
2091        }
2092    }
2093    let lock = match StartLock::acquire(path).await {
2094        Err(BootstrapError::StartLockBusy { .. }) if stable_peer(path).await? => return Ok(None),
2095        result => result?,
2096    };
2097
2098    // Re-probe after acquiring the start lock so a peer that won the race between
2099    // our first failed probe and the lock acquisition is observed instead of
2100    // overwritten.
2101    if stable_peer(path).await? {
2102        return Ok(None);
2103    }
2104    Ok(Some(lock))
2105}
2106
2107async fn ensure_singleton_with_start_lock(
2108    config: BootstrapConfig,
2109    publish: bool,
2110    lock: StartLock,
2111) -> Result<Outcome, BootstrapError> {
2112    // The held start lock and its peer check only rule out a daemon using this
2113    // connection file. A daemon started with another runtime directory but
2114    // the same data home shares the run directory while passing both, so the
2115    // run directory needs its own owner: refuse at once if a live daemon holds
2116    // it, before anything below reads or writes run or data-home state.
2117    let run_dir_lock = config
2118        .live_children_path
2119        .as_deref()
2120        .map(crate::run_dir_lock::RunDirLock::acquire)
2121        .transpose()?;
2122    #[cfg(any(target_os = "linux", target_os = "macos"))]
2123    if let Some(owner) = &run_dir_lock {
2124        resume::discard_leftover(owner);
2125    }
2126    bind_under_locks(
2127        config,
2128        publish,
2129        lock,
2130        run_dir_lock,
2131        #[cfg(any(target_os = "linux", target_os = "macos"))]
2132        None,
2133    )
2134    .await
2135}
2136
2137async fn bind_under_locks(
2138    config: BootstrapConfig,
2139    publish: bool,
2140    lock: StartLock,
2141    run_dir_lock: Option<crate::run_dir_lock::RunDirLock>,
2142    #[cfg(any(target_os = "linux", target_os = "macos"))] inherited_tcp: Option<
2143        Vec<std::net::TcpListener>,
2144    >,
2145) -> Result<Outcome, BootstrapError> {
2146    #[cfg(windows)]
2147    let copy_path = windows_connection_copy::resolve(&config);
2148    let path = config.connection_file_path;
2149    #[cfg(unix)]
2150    if config.connection_file_source == ConnectionFileSource::TempDirFallback {
2151        warn!(
2152            connection_file = %path.display(),
2153            reason = config.connection_file_source.reason(),
2154            "using the system temporary directory for the daemon connection file"
2155        );
2156    }
2157    remove_stale_connection_file_if_present(&path)?;
2158    #[cfg(windows)]
2159    let copy_path = windows_connection_copy::reclaim(&path, copy_path).await;
2160
2161    // Established under the start lock, and under the run-directory lock when
2162    // there is one, and before binding: a corrupt file stops boot before
2163    // anything is published, and two daemons racing to start cannot both mint.
2164    //
2165    // Minting a new machine id fsyncs its file, so loading or minting runs on
2166    // tokio's blocking pool. Both locks travel with that work, so neither is
2167    // released while a mint is in flight.
2168    let (machine_id, lock, run_dir_lock) = match config.machine_id_path {
2169        None => (None, lock, run_dir_lock),
2170        Some(machine_id_path) => {
2171            let task_path = machine_id_path.clone();
2172            match run_blocking_holding((lock, run_dir_lock), move || {
2173                crate::machine_id::load_or_mint(&task_path)
2174            })
2175            .await
2176            {
2177                Ok((Ok(id), (lock, run_dir_lock))) => (Some(id), lock, run_dir_lock),
2178                Ok((Err(error), _locks)) => return Err(BootstrapError::MachineId(error)),
2179                Err(join_error) => {
2180                    return Err(BootstrapError::MachineId(
2181                        crate::machine_id::MachineIdFileError::Write {
2182                            path: machine_id_path,
2183                            source: io::Error::other(describe_blocking_task_failure(
2184                                "loading or minting the machine id",
2185                                &join_error,
2186                            )),
2187                        },
2188                    ))
2189                }
2190            }
2191        }
2192    };
2193
2194    #[cfg(not(any(target_os = "linux", target_os = "macos")))]
2195    let (listeners, endpoints) = bind_loopback(config.port).await?;
2196    #[cfg(any(target_os = "linux", target_os = "macos"))]
2197    let (listeners, endpoints) = match inherited_tcp {
2198        None => bind_loopback(config.port).await?,
2199        Some(inherited) => {
2200            let mut listeners = Vec::with_capacity(inherited.len());
2201            let mut endpoints = Vec::with_capacity(inherited.len());
2202            for listener in inherited {
2203                let address = listener.local_addr().map_err(BootstrapError::Resume)?;
2204                listeners.push(TcpListener::from_std(listener).map_err(BootstrapError::Resume)?);
2205                endpoints.push(Endpoint {
2206                    host: address.ip().to_string(),
2207                    port: address.port(),
2208                });
2209            }
2210            (listeners, endpoints)
2211        }
2212    };
2213    // The local endpoint is an addition to the daemon, not a condition for it:
2214    // a bind failure leaves clients on TCP only, with the connection file naming
2215    // no local endpoint, and the reason reported by `server.describe`. A daemon
2216    // that refused to start would take every module down for a feature nothing
2217    // has to use yet.
2218    let (local_listener, local_endpoint, local_endpoint_unavailable) =
2219        if config.local_listener.configured_dir().is_some() {
2220            match local_listener::bind(&config.local_listener, &path) {
2221                Ok(local_listener) => {
2222                    let endpoint = local_listener.endpoint();
2223                    (Some(local_listener), Some(endpoint), None)
2224                }
2225                Err(error) => {
2226                    let reason = error.to_string();
2227                    warn!(
2228                        error = %reason,
2229                        "the local endpoint is unavailable; serving loopback TCP only"
2230                    );
2231                    (None, None, Some(reason))
2232                }
2233            }
2234        } else {
2235            (None, None, None)
2236        };
2237    let connection_info = ConnectionInfo {
2238        schema: SCHEMA_VERSION,
2239        wire_version: Some(PROTOCOL_VERSION),
2240        endpoints,
2241        key: generate_key().map_err(BootstrapError::GenerateConnectionFile)?,
2242        daemon_id: generate_daemon_id().map_err(BootstrapError::GenerateConnectionFile)?,
2243        pid: process::id(),
2244        daemon_ver: config.daemon_ver,
2245    };
2246
2247    // The low-level binding API historically publishes for callers that serve
2248    // these listeners themselves. The daemon entry point defers publication
2249    // until its own authentication server is running.
2250    let publication_lock = if publish {
2251        let (published, lock) = publish_connection_file(
2252            &path,
2253            #[cfg(windows)]
2254            copy_path.as_deref(),
2255            &connection_info,
2256            local_endpoint.as_ref(),
2257            lock,
2258        )
2259        .await;
2260        if let Err(error) = published {
2261            if let Some(local_listener) = local_listener.as_ref() {
2262                local_listener::release(local_listener);
2263            }
2264            drop(listeners);
2265            return Err(error);
2266        }
2267        drop(lock);
2268        None
2269    } else {
2270        Some(lock)
2271    };
2272
2273    Ok(Outcome::Bound(BoundDaemon {
2274        listeners,
2275        local_listener,
2276        local_endpoint,
2277        local_endpoint_unavailable,
2278        connection_info,
2279        connection_file_path: path,
2280        connection_file_source: config.connection_file_source,
2281        #[cfg(windows)]
2282        connection_file_copy: copy_path,
2283        machine_id,
2284        run_dir_lock,
2285        publication_lock,
2286    }))
2287}
2288
2289#[derive(Debug, Clone, Copy, PartialEq, Eq)]
2290enum Probe {
2291    Live,
2292    StaleOrAbsent,
2293}
2294
2295async fn stable_peer(path: &Path) -> Result<bool, BootstrapError> {
2296    if !matches!(probe_existing(path).await?, Probe::Live) {
2297        return Ok(false);
2298    }
2299    // A terminating peer can still authenticate while its listeners drain.
2300    // Require another proof after a short settling interval before reporting
2301    // a successful duplicate start. If the peer left, proceed with startup;
2302    // any remaining bind/ownership conflict is an error, not exit 0 (which
2303    // would suppress launchd's restart-on-failure policy).
2304    tokio::time::sleep(Duration::from_millis(1500)).await;
2305    Ok(matches!(probe_existing(path).await?, Probe::Live))
2306}
2307
2308async fn probe_existing(path: &Path) -> Result<Probe, BootstrapError> {
2309    let info = match connection_file::read(path) {
2310        Ok(info) => info,
2311        Err(source) if is_absent_or_stale_connection_file(&source) => {
2312            return Ok(Probe::StaleOrAbsent)
2313        }
2314        Err(source) => {
2315            return Err(BootstrapError::ConnectionFileRead {
2316                path: path.to_path_buf(),
2317                source,
2318            })
2319        }
2320    };
2321
2322    for endpoint in &info.endpoints {
2323        if matches!(probe_endpoint(&info, endpoint).await, Probe::Live) {
2324            return Ok(Probe::Live);
2325        }
2326    }
2327
2328    Ok(Probe::StaleOrAbsent)
2329}
2330
2331async fn probe_endpoint(info: &ConnectionInfo, endpoint: &Endpoint) -> Probe {
2332    let Ok(ip) = endpoint.host.parse::<IpAddr>() else {
2333        return Probe::StaleOrAbsent;
2334    };
2335    if !ip.is_loopback() {
2336        return Probe::StaleOrAbsent;
2337    }
2338    let addr = SocketAddr::new(ip, endpoint.port);
2339
2340    let mut stream = match timeout(CONNECT_TIMEOUT, TcpStream::connect(addr)).await {
2341        Ok(Ok(stream)) => stream,
2342        Ok(Err(_)) | Err(_) => return Probe::StaleOrAbsent,
2343    };
2344
2345    match authenticate_client(&mut stream, info, PROBE_AUTH_DEADLINE).await {
2346        Ok(()) => Probe::Live,
2347        Err(AuthError::DaemonIdMismatch)
2348        | Err(AuthError::InvalidServerProof)
2349        | Err(AuthError::UnexpectedEof { .. })
2350        | Err(AuthError::Timeout { .. })
2351        | Err(AuthError::JsonEncode { .. })
2352        | Err(AuthError::JsonDecode { .. })
2353        | Err(AuthError::Io { .. })
2354        | Err(AuthError::MessageTooLarge { .. })
2355        | Err(AuthError::KeyTooShort { .. })
2356        | Err(AuthError::Random(_))
2357        | Err(AuthError::InvalidClientAuth) => Probe::StaleOrAbsent,
2358    }
2359}
2360
2361async fn verify_serving(info: &ConnectionInfo) -> Result<(), BootstrapError> {
2362    // Scheduling a server task is not a readiness barrier. Authenticate once
2363    // against the mandatory IPv4 listener before exposing discovery to peers.
2364    // This uses the normal probe deadline, with no retries or widened budget.
2365    if let Some(endpoint) = info.endpoints.first() {
2366        if matches!(probe_endpoint(info, endpoint).await, Probe::Live) {
2367            return Ok(());
2368        }
2369    }
2370    Err(BootstrapError::StartupNotServing)
2371}
2372
2373/// Run blocking filesystem work (an fsync, a rename) on tokio's blocking-thread
2374/// pool rather than on the async worker thread that awaits it. On a slow or
2375/// busy disk an fsync can take seconds, and a runtime has few worker threads
2376/// (an in-process test daemon may share two with everything else), so doing it
2377/// inline stalls unrelated tasks for that long.
2378///
2379/// `guards` (lock handles) move into the blocking task and are handed back
2380/// with the work's result. If the awaiting future is dropped first, the work
2381/// still runs to completion on its thread and the guards are released only
2382/// after it ends, so a lock is never given up while the work it protects is
2383/// still writing.
2384///
2385/// `Err` means the task panicked, or was cancelled before it started because
2386/// the runtime is shutting down; the guards have then been released already.
2387async fn run_blocking_holding<G, T>(
2388    guards: G,
2389    work: impl FnOnce() -> T + Send + 'static,
2390) -> Result<(T, G), JoinError>
2391where
2392    G: Send + 'static,
2393    T: Send + 'static,
2394{
2395    tokio::task::spawn_blocking(move || {
2396        let output = work();
2397        (output, guards)
2398    })
2399    .await
2400}
2401
2402/// Explain, for a startup error, why blocking work produced no result.
2403fn describe_blocking_task_failure(work: &str, join_error: &JoinError) -> String {
2404    if join_error.is_panic() {
2405        format!("the background thread {work} panicked before finishing: {join_error}")
2406    } else {
2407        format!(
2408            "the background thread {work} was cancelled before finishing, because the async runtime is shutting down: {join_error}"
2409        )
2410    }
2411}
2412
2413/// Publish the connection file: owner-only permissions, written to a temporary
2414/// file, fsynced and renamed over `path` (all done by `write_atomic`). The
2415/// write runs on tokio's blocking pool through [`run_blocking_holding`], so the
2416/// fsync never holds an async worker thread.
2417///
2418/// `guard` is the singleton start lock (or whatever the caller must keep held
2419/// across publication); it is returned with the result. It comes back `None`
2420/// only when the write task panicked or was cancelled, in which case the
2421/// result is an error and the file must be treated as not published.
2422///
2423/// On Windows, `copy_path` asks for the profile copy as well. Its start lock is
2424/// taken before the primary write. Once `path` is written, an error returned
2425/// while preparing or writing the copy only logs a warning, and the result is
2426/// still success. The two writes share one blocking task but aren't one atomic
2427/// step, and a panic or cancellation of that task is still a publication
2428/// error.
2429async fn publish_connection_file<G: Send + 'static>(
2430    path: &Path,
2431    #[cfg(windows)] copy_path: Option<&Path>,
2432    info: &ConnectionInfo,
2433    local_endpoint: Option<&LocalEndpoint>,
2434    guard: G,
2435) -> (Result<(), BootstrapError>, Option<G>) {
2436    let task_path = path.to_path_buf();
2437    let task_info = info.clone();
2438    let task_endpoint = local_endpoint.cloned();
2439    #[cfg(windows)]
2440    let copy = windows_connection_copy::claim_for_publication(path, copy_path, info).await;
2441    let outcome = run_blocking_holding(guard, move || {
2442        write_connection_file(&task_path, &task_info, task_endpoint.as_ref())?;
2443        #[cfg(windows)]
2444        if let Some((copy_path, _lock)) = copy {
2445            if let Err(error) =
2446                write_connection_file(&copy_path, &task_info, task_endpoint.as_ref())
2447            {
2448                windows_connection_copy::warn_unavailable(&task_path, Some(&copy_path), &error);
2449            }
2450        }
2451        Ok(())
2452    })
2453    .await;
2454    match outcome {
2455        Ok((Ok(()), guard)) => (Ok(()), Some(guard)),
2456        Ok((Err(source), guard)) => (
2457            Err(BootstrapError::ConnectionFileWrite {
2458                path: path.to_path_buf(),
2459                source,
2460            }),
2461            Some(guard),
2462        ),
2463        Err(join_error) => (
2464            Err(BootstrapError::ConnectionFileWrite {
2465                path: path.to_path_buf(),
2466                source: ConnectionFileError::Io {
2467                    op: "write",
2468                    path: path.to_path_buf(),
2469                    source: io::Error::other(describe_blocking_task_failure(
2470                        "writing the connection file",
2471                        &join_error,
2472                    )),
2473                },
2474            }),
2475            None,
2476        ),
2477    }
2478}
2479
2480/// The synchronous connection-file write, including its fsync. Call it only
2481/// through [`publish_connection_file`], which keeps it off the async workers.
2482///
2483/// `local_endpoint` is written through subc-transport's endpoint-aware writer,
2484/// so the file carries `local_endpoint` when there is a local listener and is
2485/// byte-identical to before when there is none.
2486fn write_connection_file(
2487    path: &Path,
2488    info: &ConnectionInfo,
2489    local_endpoint: Option<&LocalEndpoint>,
2490) -> Result<(), ConnectionFileError> {
2491    #[cfg(test)]
2492    connection_file_write_hook::run(path);
2493    write_atomic_with_local_endpoint(path, info, local_endpoint)
2494}
2495
2496/// Lets a test run code inside the connection-file write, on whichever thread
2497/// performs it, for example to block there and check what else can still run.
2498#[cfg(test)]
2499mod connection_file_write_hook {
2500    use std::{
2501        path::{Path, PathBuf},
2502        sync::{Mutex, PoisonError},
2503    };
2504
2505    type Hook = Box<dyn FnOnce() + Send>;
2506
2507    /// Keyed by connection-file path, so a hook fires only for the test that
2508    /// installed it while other tests publish their own files in parallel.
2509    static HOOKS: Mutex<Vec<(PathBuf, Hook)>> = Mutex::new(Vec::new());
2510
2511    /// Run `hook` once, at the start of the next write of `path`.
2512    pub(super) fn install(path: &Path, hook: impl FnOnce() + Send + 'static) {
2513        HOOKS
2514            .lock()
2515            .unwrap_or_else(PoisonError::into_inner)
2516            .push((path.to_path_buf(), Box::new(hook)));
2517    }
2518
2519    pub(super) fn run(path: &Path) {
2520        let hook = {
2521            let mut hooks = HOOKS.lock().unwrap_or_else(PoisonError::into_inner);
2522            hooks
2523                .iter()
2524                .position(|(hooked, _)| hooked == path)
2525                .map(|index| hooks.swap_remove(index).1)
2526        };
2527        if let Some(hook) = hook {
2528            hook();
2529        }
2530    }
2531}
2532
2533/// A path-scoped barrier after publication and before any configured activation.
2534/// The async wait leaves the listeners free to answer discovery-time requests.
2535#[cfg(test)]
2536mod startup_publication_hook {
2537    use std::{
2538        path::{Path, PathBuf},
2539        sync::{Mutex, PoisonError},
2540    };
2541    use tokio::sync::oneshot;
2542
2543    type Barrier = (oneshot::Sender<()>, oneshot::Receiver<()>);
2544    static BARRIERS: Mutex<Vec<(PathBuf, Barrier)>> = Mutex::new(Vec::new());
2545
2546    pub(super) fn install(path: &Path) -> (oneshot::Receiver<()>, oneshot::Sender<()>) {
2547        let (entered_tx, entered_rx) = oneshot::channel();
2548        let (release_tx, release_rx) = oneshot::channel();
2549        BARRIERS
2550            .lock()
2551            .unwrap_or_else(PoisonError::into_inner)
2552            .push((path.to_path_buf(), (entered_tx, release_rx)));
2553        (entered_rx, release_tx)
2554    }
2555
2556    pub(super) async fn run(path: &Path) {
2557        let barrier = {
2558            let mut barriers = BARRIERS.lock().unwrap_or_else(PoisonError::into_inner);
2559            barriers
2560                .iter()
2561                .position(|(hooked, _)| hooked == path)
2562                .map(|index| barriers.swap_remove(index).1)
2563        };
2564        if let Some((entered, release)) = barrier {
2565            let _ = entered.send(());
2566            let _ = release.await;
2567        }
2568    }
2569}
2570
2571fn is_absent_or_stale_connection_file(err: &ConnectionFileError) -> bool {
2572    match err {
2573        ConnectionFileError::Io { source, .. } if source.kind() == io::ErrorKind::NotFound => true,
2574        ConnectionFileError::JsonRead { .. }
2575        | ConnectionFileError::UnsupportedSchema { .. }
2576        | ConnectionFileError::Invalid { .. }
2577        | ConnectionFileError::KeyTooShort { .. }
2578        // A live daemon always publishes the file owner-only (0600), so a file
2579        // with insecure permissions is never a daemon we should defer to: treat it
2580        // as stale and take over (which republishes a correct 0600 file).
2581        | ConnectionFileError::InsecurePermissions { .. } => true,
2582        ConnectionFileError::MissingParent { .. }
2583        | ConnectionFileError::MissingFileName { .. }
2584        // A writable ancestor is an operator misconfiguration, never evidence
2585        // about whether a daemon is live. Reclaiming the file would republish key
2586        // material into the same directory the refusal is about.
2587        | ConnectionFileError::InsecureParentDirectory { .. }
2588        | ConnectionFileError::Io { .. }
2589        | ConnectionFileError::JsonWrite { .. }
2590        | ConnectionFileError::Random(_)
2591        // A wire mismatch may identify a newer live daemon, so never reclaim its
2592        // connection file merely because this binary cannot speak its envelope.
2593        | ConnectionFileError::WireVersionMismatch { .. } => false,
2594    }
2595}
2596
2597fn remove_stale_connection_file_if_present(path: &Path) -> Result<(), BootstrapError> {
2598    match fs::remove_file(path) {
2599        Ok(()) => Ok(()),
2600        Err(err) if err.kind() == io::ErrorKind::NotFound => Ok(()),
2601        Err(source) => Err(BootstrapError::RemoveStale {
2602            path: path.to_path_buf(),
2603            source,
2604        }),
2605    }
2606}
2607
2608async fn bind_loopback(port: u16) -> Result<(Vec<TcpListener>, Vec<Endpoint>), BootstrapError> {
2609    bind_loopback_with(port, |port| TcpListener::bind((Ipv6Addr::LOCALHOST, port))).await
2610}
2611
2612async fn bind_loopback_with<F, Fut>(
2613    port: u16,
2614    mut bind_v6: F,
2615) -> Result<(Vec<TcpListener>, Vec<Endpoint>), BootstrapError>
2616where
2617    F: FnMut(u16) -> Fut,
2618    Fut: std::future::Future<Output = io::Result<TcpListener>>,
2619{
2620    let v4_host = Ipv4Addr::LOCALHOST;
2621    let v4 = TcpListener::bind((v4_host, port))
2622        .await
2623        .map_err(|source| BootstrapError::Bind {
2624            host: v4_host.to_string(),
2625            port,
2626            source,
2627        })?;
2628    let actual_port = v4
2629        .local_addr()
2630        .map_err(|source| BootstrapError::LocalAddr {
2631            host: v4_host.to_string(),
2632            source,
2633        })?
2634        .port();
2635
2636    let mut listeners = vec![v4];
2637    let mut endpoints = vec![Endpoint {
2638        host: v4_host.to_string(),
2639        port: actual_port,
2640    }];
2641
2642    let v6_host = Ipv6Addr::LOCALHOST;
2643    match bind_v6(actual_port).await {
2644        Ok(v6) => {
2645            listeners.push(v6);
2646            endpoints.push(Endpoint {
2647                host: v6_host.to_string(),
2648                port: actual_port,
2649            });
2650        }
2651        Err(err)
2652            if ipv6_loopback_unavailable(&err)
2653                || (port == 0 && err.kind() == io::ErrorKind::AddrInUse) =>
2654        {
2655            warn!(
2656                port = actual_port,
2657                error = %err,
2658                "IPv6 loopback unavailable; serving only IPv4 loopback"
2659            );
2660        }
2661        Err(source) => {
2662            drop(listeners);
2663            return Err(BootstrapError::Bind {
2664                host: v6_host.to_string(),
2665                port: actual_port,
2666                source,
2667            });
2668        }
2669    }
2670
2671    Ok((listeners, endpoints))
2672}
2673
2674fn ipv6_loopback_unavailable(err: &io::Error) -> bool {
2675    matches!(
2676        err.kind(),
2677        io::ErrorKind::AddrNotAvailable | io::ErrorKind::Unsupported
2678    ) || matches!(err.raw_os_error(), Some(47) | Some(49) | Some(97))
2679}
2680
2681struct AbortOnDrop<T> {
2682    handle: JoinHandle<T>,
2683}
2684
2685impl<T> AbortOnDrop<T> {
2686    fn new(handle: JoinHandle<T>) -> Self {
2687        Self { handle }
2688    }
2689
2690    async fn join(&mut self) -> Result<T, JoinError> {
2691        (&mut self.handle).await
2692    }
2693}
2694
2695impl<T> Drop for AbortOnDrop<T> {
2696    fn drop(&mut self) {
2697        if !self.handle.is_finished() {
2698            self.handle.abort();
2699        }
2700    }
2701}
2702
2703#[derive(Debug)]
2704pub(crate) struct StartLock {
2705    // Service boots keep the file holding the startup lock open for handover.
2706    _file: fs::File,
2707}
2708
2709impl Drop for StartLock {
2710    fn drop(&mut self) {
2711        // Closing alone leaves the lock held if a concurrent fork inherited
2712        // the open file description and has not exec'd yet. Unlock explicitly
2713        // so another daemon can start as soon as this owner releases the lock.
2714        if let Err(error) = FileExt::unlock(&self._file) {
2715            tracing::warn!(%error, "failed to release the singleton start lock");
2716        }
2717    }
2718}
2719
2720impl StartLock {
2721    #[cfg(any(target_os = "linux", target_os = "macos"))]
2722    pub(crate) fn file(&self) -> &fs::File {
2723        &self._file
2724    }
2725    async fn acquire(connection_file_path: &Path) -> Result<Self, BootstrapError> {
2726        let path = start_lock_path(connection_file_path);
2727        for _ in 0..START_LOCK_RETRIES {
2728            let file = match open_owner_only_lock(&path) {
2729                Ok(file) => file,
2730                Err(source) => return Err(BootstrapError::StartLockCreate { path, source }),
2731            };
2732            match FileExt::try_lock(&file) {
2733                Ok(()) => return Ok(Self { _file: file }),
2734                Err(TryLockError::WouldBlock) => sleep(START_LOCK_RETRY_DELAY).await,
2735                Err(TryLockError::Error(source)) => {
2736                    return Err(BootstrapError::StartLockCreate { path, source });
2737                }
2738            }
2739        }
2740
2741        Err(BootstrapError::StartLockBusy {
2742            path,
2743            attempts: START_LOCK_RETRIES,
2744        })
2745    }
2746}
2747
2748#[cfg(all(test, any(target_os = "linux", target_os = "macos")))]
2749pub(crate) async fn upgrade_runtime_for_test(
2750    root: &Path,
2751    supervisor: &Supervisor,
2752    executable: PathBuf,
2753) -> Arc<crate::control::upgrade_in_place::Runtime> {
2754    use crate::control::upgrade_in_place::{BootImage, Runtime};
2755
2756    let config = BootstrapConfig::new(root.join("connection.json"), 0);
2757    let run = crate::run_dir_lock::RunDirLock::acquire(&root.join("live-children.json")).unwrap();
2758    let publication = StartLock::acquire(&config.connection_file_path)
2759        .await
2760        .unwrap();
2761    #[cfg(target_os = "linux")]
2762    let image = fs::File::open("/proc/self/exe").unwrap();
2763    #[cfg(target_os = "macos")]
2764    let image = fs::File::open(&executable).unwrap();
2765    let boot = BootImage::capture(
2766        executable,
2767        Arc::new(image),
2768        "test".into(),
2769        None,
2770        None,
2771        &Default::default(),
2772    )
2773    .await
2774    .with_fixture_probe(root.join("must-not-exec"));
2775    boot.wait_for_digest().await.expect("fixture image hash");
2776    let runtime = Arc::new(Runtime::for_settings_cutover_test(
2777        boot,
2778        crate::supervise::handover::required_lock_roles(&config),
2779        run,
2780        supervisor.retained_children(),
2781    ));
2782    runtime.retain_publication(publication);
2783    runtime
2784}
2785
2786pub(crate) fn open_owner_only_lock(path: &Path) -> io::Result<fs::File> {
2787    let mut options = fs::OpenOptions::new();
2788    options.read(true).write(true).create(true);
2789    #[cfg(unix)]
2790    {
2791        use std::os::unix::fs::OpenOptionsExt;
2792        options.mode(0o600);
2793    }
2794    options.open(path)
2795}
2796
2797fn start_lock_path(connection_file_path: &Path) -> PathBuf {
2798    let file_name = connection_file_path
2799        .file_name()
2800        .map(|name| name.to_string_lossy())
2801        .unwrap_or_else(|| CONNECTION_FILE_NAME.into());
2802    let lock_name = format!("{file_name}.start-lock");
2803    connection_file_path
2804        .parent()
2805        .filter(|parent| !parent.as_os_str().is_empty())
2806        .unwrap_or_else(|| Path::new("."))
2807        .join(lock_name)
2808}
2809
2810/// Bootstrap-layer errors are deliberately typed so startup never panics for
2811/// ordinary daemon-discovery races or stale filesystem state.
2812#[derive(Debug)]
2813#[non_exhaustive]
2814pub enum BootstrapError {
2815    ConfigStore(String),
2816    #[cfg(any(target_os = "linux", target_os = "macos"))]
2817    Resume(io::Error),
2818    /// The bound server could not authenticate its own readiness probe.
2819    StartupNotServing,
2820    #[cfg(unix)]
2821    Signal(io::Error),
2822    InvalidPort {
2823        raw: String,
2824        source: std::num::ParseIntError,
2825    },
2826    ConnectionFileRead {
2827        path: PathBuf,
2828        source: ConnectionFileError,
2829    },
2830    ConnectionFileWrite {
2831        path: PathBuf,
2832        source: ConnectionFileError,
2833    },
2834    GenerateConnectionFile(ConnectionFileError),
2835    StartLockCreate {
2836        path: PathBuf,
2837        source: io::Error,
2838    },
2839    StartLockBusy {
2840        path: PathBuf,
2841        attempts: usize,
2842    },
2843    /// The run-directory lock file could not be created, opened or locked.
2844    RunDirLockCreate {
2845        path: PathBuf,
2846        source: io::Error,
2847    },
2848    /// Another live process, almost certainly a daemon started with a
2849    /// different runtime directory over the same data home, owns the run
2850    /// directory. The daemon does not start. `holder_pid` is read from the
2851    /// lock file when possible and is informational only.
2852    RunDirBusy {
2853        path: PathBuf,
2854        holder_pid: Option<u32>,
2855    },
2856    RemoveStale {
2857        path: PathBuf,
2858        source: io::Error,
2859    },
2860    Bind {
2861        host: String,
2862        port: u16,
2863        source: io::Error,
2864    },
2865    LocalAddr {
2866        host: String,
2867        source: io::Error,
2868    },
2869    DaemonConfig(DaemonConfigError),
2870    /// The machine id could not be established: its file is corrupt, unreadable
2871    /// or unwritable, or the data home is relative. The daemon does not start.
2872    MachineId(crate::machine_id::MachineIdFileError),
2873    /// The daemon run directory could not be resolved because the data home is
2874    /// relative. The daemon does not start.
2875    RunDir(daemon_config::DaemonRunDirError),
2876    Serve(ServerError),
2877    ServeJoin(tokio::task::JoinError),
2878}
2879
2880impl From<ServerError> for BootstrapError {
2881    fn from(error: ServerError) -> Self {
2882        Self::Serve(error)
2883    }
2884}
2885
2886impl fmt::Display for BootstrapError {
2887    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2888        match self {
2889            Self::ConfigStore(error) => write!(f, "configuration store startup refused: {error}"),
2890            #[cfg(any(target_os = "linux", target_os = "macos"))]
2891            Self::Resume(error) => write!(f, "daemon handover refused: {error}"),
2892            Self::StartupNotServing => write!(f, "bound daemon did not authenticate its readiness probe; connection file was not published"),
2893            #[cfg(unix)]
2894            Self::Signal(error) => write!(f, "failed to register SIGTERM handler: {error}"),
2895            Self::InvalidPort { raw, source } => {
2896                write!(f, "invalid {SUBC_PORT_ENV} value '{raw}': {source}")
2897            }
2898            Self::ConnectionFileRead { path, source } => write!(
2899                f,
2900                "failed to read connection file {}: {source}",
2901                path.display()
2902            ),
2903            Self::ConnectionFileWrite { path, source } => write!(
2904                f,
2905                "failed to publish connection file {}: {source}",
2906                path.display()
2907            ),
2908            Self::GenerateConnectionFile(err) => {
2909                write!(f, "failed to generate connection-file auth material: {err}")
2910            }
2911            Self::StartLockCreate { path, source } => {
2912                write!(
2913                    f,
2914                    "failed to create start lock {}: {source}",
2915                    path.display()
2916                )
2917            }
2918            Self::StartLockBusy { path, attempts } => write!(
2919                f,
2920                "start lock {} remained busy after {attempts} attempts",
2921                path.display()
2922            ),
2923            Self::RunDirLockCreate { path, source } => write!(
2924                f,
2925                "refusing to start: failed to lock run directory via {}: {source}",
2926                path.display()
2927            ),
2928            Self::RunDirBusy { path, holder_pid } => {
2929                write!(
2930                    f,
2931                    "refusing to start: run directory lock {} is held by another daemon",
2932                    path.display()
2933                )?;
2934                if let Some(pid) = holder_pid {
2935                    write!(f, " (pid {pid})")?;
2936                }
2937                write!(
2938                    f,
2939                    "; a live daemon owns this data home's run state (typically one started with a different XDG_RUNTIME_DIR)"
2940                )
2941            }
2942            Self::RemoveStale { path, source } => write!(
2943                f,
2944                "failed to remove stale connection file {}: {source}",
2945                path.display()
2946            ),
2947            Self::Bind { host, port, source } if source.kind() == io::ErrorKind::AddrInUse => {
2948                write!(
2949                    f,
2950                    "port {port} in use on loopback {host}: {source}; set the port in config"
2951                )
2952            }
2953            Self::Bind { host, port, source } => {
2954                write!(f, "failed to bind loopback TCP {host}:{port}: {source}")
2955            }
2956            Self::LocalAddr { host, source } => {
2957                write!(f, "failed to read local address for {host}: {source}")
2958            }
2959            Self::DaemonConfig(err) => write!(f, "failed to load daemon config: {err}"),
2960            Self::MachineId(err) => write!(f, "refusing to start: {err}"),
2961            Self::RunDir(err) => write!(f, "refusing to start: {err}"),
2962            Self::Serve(err) => write!(f, "daemon server failed: {err}"),
2963            Self::ServeJoin(err) => write!(f, "daemon server task failed: {err}"),
2964        }
2965    }
2966}
2967
2968impl Error for BootstrapError {
2969    fn source(&self) -> Option<&(dyn Error + 'static)> {
2970        match self {
2971            Self::ConfigStore(_) => None,
2972            #[cfg(any(target_os = "linux", target_os = "macos"))]
2973            Self::Resume(source) => Some(source),
2974            Self::StartupNotServing => None,
2975            #[cfg(unix)]
2976            Self::Signal(source) => Some(source),
2977            Self::InvalidPort { source, .. } => Some(source),
2978            Self::ConnectionFileRead { source, .. }
2979            | Self::ConnectionFileWrite { source, .. }
2980            | Self::GenerateConnectionFile(source) => Some(source),
2981            Self::StartLockCreate { source, .. }
2982            | Self::RunDirLockCreate { source, .. }
2983            | Self::RemoveStale { source, .. }
2984            | Self::Bind { source, .. }
2985            | Self::LocalAddr { source, .. } => Some(source),
2986            Self::DaemonConfig(err) => Some(err),
2987            Self::MachineId(err) => Some(err),
2988            Self::RunDir(err) => Some(err),
2989            Self::Serve(err) => Some(err),
2990            Self::ServeJoin(err) => Some(err),
2991            Self::StartLockBusy { .. } | Self::RunDirBusy { .. } => None,
2992        }
2993    }
2994}
2995
2996#[cfg(all(test, feature = "test-support", unix))]
2997#[path = "bootstrap_recovery_tests.rs"]
2998mod recovery_tests;
2999
3000#[cfg(test)]
3001mod tests {
3002    mod activity {
3003        include!("activity_bootstrap_tests.rs");
3004    }
3005    mod startup_order {
3006        include!("startup_order_tests.rs");
3007    }
3008    use super::*;
3009    use crate::server::ServerAuth;
3010    use cortexkit_test_support::ScratchDir;
3011    #[cfg(target_os = "linux")]
3012    use std::collections::BTreeSet;
3013    use std::sync::Mutex;
3014    #[cfg(target_os = "linux")]
3015    use subc_control::ModuleProtocol;
3016    use subc_transport::{write_atomic, MIN_KEY_LEN};
3017    use tokio::io::AsyncReadExt;
3018    use tokio::task::JoinHandle;
3019
3020    #[cfg(unix)]
3021    use std::os::unix::fs::PermissionsExt;
3022
3023    static ENV_LOCK: Mutex<()> = Mutex::new(());
3024
3025    #[test]
3026    fn normalized_build_provenance_preserves_real_values() {
3027        assert_eq!(normalized_build_provenance("abc"), Some("abc".to_string()));
3028    }
3029
3030    #[test]
3031    fn config_recovery_bootstrap_preserves_all_loaded_fields_and_only_argument_overrides() {
3032        let _env_lock = ENV_LOCK.lock().unwrap();
3033        let scratch = unique_temp_dir("bootstrap-loaded-fields");
3034        let file = scratch.join("subc.jsonc");
3035        std::fs::write(
3036            &file,
3037            br#"{"version":1,"modules":{},"scope_authority_owners":["file-owner"],"flow_scope_authority_owners":["flow-owner"]}"#,
3038        )
3039        .unwrap();
3040        let mut config = BootstrapConfig::new(scratch.join("connection.json"), 0)
3041            .with_daemon_config_source(file.clone(), None);
3042        config.defer_file_load = true;
3043        config.operator_timeout = Duration::from_secs(7);
3044        let selected = load_bootstrap_authority(config, None).unwrap();
3045        assert_eq!(
3046            selected.file_derived_test_probe,
3047            Some(vec!["file-owner".into()])
3048        );
3049        assert_eq!(selected.flow_scope_authority_owners, ["flow-owner"]);
3050        assert_eq!(selected.operator_timeout, Duration::from_secs(7));
3051        assert_eq!(selected.daemon_config_path, Some(file));
3052        assert_eq!(
3053            selected.connection_file_path,
3054            scratch.join("connection.json")
3055        );
3056    }
3057
3058    #[test]
3059    fn config_recovery_bootstrap_ignores_invalid_live_file_and_poisoned_settings() {
3060        let scratch = unique_temp_dir("recovery-bootstrap");
3061        let root = scratch.join("store");
3062        std::fs::create_dir_all(&root).unwrap();
3063        std::fs::write(
3064            root.join(crate::config_store::STORE_FILE),
3065            br#"{"format_version":999}"#,
3066        )
3067        .unwrap();
3068        let mut store = crate::config_store::ConfigStore::open_digest_only_for_tests(
3069            crate::config_store::StoreRoot::from_service_definition(root).unwrap(),
3070        );
3071        assert_eq!(
3072            store.status().state,
3073            crate::config_store::StoreState::StoreUnverified
3074        );
3075        let file = scratch.join("subc.jsonc");
3076        std::fs::write(&file, b"invalid live config").unwrap();
3077        let mut config = BootstrapConfig::new(scratch.join("connection.json"), 1)
3078            .with_daemon_config_source(file, Some(1))
3079            .with_scope_authority_owners(vec!["untrusted".into()])
3080            .with_reserved_capabilities(BTreeMap::from([("untrusted".into(), "untrusted".into())]));
3081        config.defer_file_load = true;
3082        config.file_derived_test_probe = Some(vec!["untrusted".into()]);
3083        let config = load_bootstrap_authority(config, Some(&mut store)).unwrap();
3084        assert_eq!(config.file_derived_test_probe, None);
3085        assert_eq!(config.port, DEFAULT_SUBC_PORT);
3086        assert!(config.configured_modules.is_empty());
3087        assert_eq!(
3088            config.scope_authority_owners,
3089            daemon_config::default_scope_authority_owners()
3090        );
3091        assert!(config.flow_scope_authority_owners.is_empty());
3092        assert!(config.reserved_capabilities.is_empty());
3093        assert_eq!(
3094            config.privileged_operator_prompt,
3095            daemon_config::PrivilegedOperatorPrompt::default()
3096        );
3097    }
3098
3099    /// An approved generation whose daemon bytes listen on `port`. Changing
3100    /// the port is a setting only bootstrap reads, so it waits for a restart.
3101    fn approved_port_entry(
3102        kind: crate::config_store::CommitKind,
3103        port: u16,
3104    ) -> crate::config_store::HistoryEntry {
3105        use subc_protocol::config::{ConfigLayer, ConfigLayerSnapshot};
3106        crate::config_store::HistoryEntry {
3107            generation: subc_config::Generation::new(
3108                0,
3109                subc_config::ApprovalChannel::OsPrompt,
3110                subc_config::raw_digest(b"approved-plan"),
3111                subc_config::InputVector::default(),
3112                subc_config::Changeset::new(),
3113            ),
3114            kind,
3115            approval_id: "approval".into(),
3116            outcome: "approved".into(),
3117            tuples: Default::default(),
3118            project_outcomes: Default::default(),
3119            configuration: Default::default(),
3120            delivery: Some(crate::config_store::DeliverySnapshot {
3121                daemon: Some(ConfigLayerSnapshot::file(
3122                    "subc",
3123                    ConfigLayer::User,
3124                    "/approved/subc.jsonc",
3125                    Some(format!(r#"{{"version":1,"port":{port},"modules":{{}}}}"#).into_bytes()),
3126                )),
3127                ..crate::config_store::DeliverySnapshot::default()
3128            }),
3129        }
3130    }
3131
3132    fn approve_port(
3133        store: &mut crate::config_store::ConfigStore,
3134        kind: crate::config_store::CommitKind,
3135        port: u16,
3136    ) {
3137        store
3138            .commit_generation(
3139                approved_port_entry(kind, port),
3140                Default::default(),
3141                Default::default(),
3142                1,
3143            )
3144            .unwrap();
3145    }
3146
3147    fn stamped_boot(
3148        scratch: &Path,
3149        store: &mut crate::config_store::ConfigStore,
3150    ) -> BootstrapConfig {
3151        let mut config = BootstrapConfig::new(scratch.join("connection.json"), 1)
3152            .with_daemon_config_source(scratch.join("subc.jsonc"), Some(1));
3153        config.defer_file_load = true;
3154        load_bootstrap_authority(config, Some(store)).unwrap()
3155    }
3156
3157    #[test]
3158    fn config_stamped_boot_uses_last_active_generation_until_restart_intent() {
3159        use crate::config_store::{CommitKind, ConfigStore, StoreRoot};
3160        let scratch = unique_temp_dir("stamped-boot-selection");
3161        let root = scratch.join("store");
3162        std::fs::create_dir_all(&root).unwrap();
3163        let open = || {
3164            ConfigStore::open_digest_only_for_tests(
3165                StoreRoot::from_service_definition(root.clone()).unwrap(),
3166            )
3167        };
3168        let mut store = open();
3169        approve_port(&mut store, CommitKind::Stamp, 41001);
3170        approve_port(&mut store, CommitKind::Approved, 41002);
3171        drop(store);
3172        let mut store = open();
3173        assert_eq!(
3174            stamped_boot(&scratch, &mut store).port,
3175            41001,
3176            "an ordinary start must not boot an approval still waiting for a daemon restart"
3177        );
3178        assert_eq!(store.assign_daemon_restart().unwrap(), Some(2));
3179        drop(store);
3180        let mut store = open();
3181        assert_eq!(stamped_boot(&scratch, &mut store).port, 41002);
3182    }
3183
3184    #[test]
3185    fn config_stamped_boot_enters_recovery_when_anchor_retry_fails_at_start() {
3186        use crate::config_store::{CommitKind, ConfigStore, StoreRoot, StoreState, TestStoreKey};
3187        let scratch = unique_temp_dir("stamped-boot-anchor-pending");
3188        let root = scratch.join("store");
3189        std::fs::create_dir_all(&root).unwrap();
3190        let key = TestStoreKey::default();
3191        let open = || {
3192            ConfigStore::open_sealed_for_tests(
3193                StoreRoot::from_service_definition(root.clone()).unwrap(),
3194                key.clone(),
3195            )
3196        };
3197        let mut store = open();
3198        approve_port(&mut store, CommitKind::Stamp, 41001);
3199        // Crash between publication and anchor: the bytes are renamed into
3200        // place but the anchor never catches up, and keeps failing at start.
3201        key.fail_anchor(true);
3202        assert!(store
3203            .commit_generation(
3204                approved_port_entry(CommitKind::Approved, 41001),
3205                Default::default(),
3206                Default::default(),
3207                2,
3208            )
3209            .is_err());
3210        drop(store);
3211        let mut store = open();
3212        let status = store.status();
3213        assert_eq!(status.state, StoreState::Stamped);
3214        assert!(status.anchor_pending);
3215        let config = stamped_boot(&scratch, &mut store);
3216        assert_eq!(config.port, DEFAULT_SUBC_PORT);
3217        assert!(config.configured_modules.is_empty());
3218        assert_eq!(store.status().state, StoreState::StoreUnverified);
3219    }
3220
3221    #[test]
3222    fn normalized_build_provenance_omits_unavailable_and_empty_values() {
3223        assert_eq!(normalized_build_provenance("unavailable"), None);
3224        assert_eq!(normalized_build_provenance(""), None);
3225    }
3226
3227    #[cfg(target_os = "linux")]
3228    fn current_cgroup_path_for_test() -> io::Result<PathBuf> {
3229        let cgroups = fs::read_to_string("/proc/self/cgroup")?;
3230        let relative = cgroups
3231            .lines()
3232            .find_map(|line| line.strip_prefix("0::"))
3233            .ok_or_else(|| {
3234                io::Error::new(io::ErrorKind::Unsupported, "cgroup v2 is unavailable")
3235            })?;
3236        Ok(Path::new("/sys/fs/cgroup").join(relative.trim_start_matches('/')))
3237    }
3238
3239    #[cfg(target_os = "linux")]
3240    fn module_cgroup_directories() -> io::Result<BTreeSet<OsString>> {
3241        let modules = current_cgroup_path_for_test()?.join("subc-modules");
3242        let entries = match fs::read_dir(modules) {
3243            Ok(entries) => entries,
3244            Err(error) if error.kind() == io::ErrorKind::NotFound => return Ok(BTreeSet::new()),
3245            Err(error) => return Err(error),
3246        };
3247        let mut directories = BTreeSet::new();
3248        for entry in entries {
3249            let entry = entry?;
3250            if entry.file_type()?.is_dir() {
3251                directories.insert(entry.file_name());
3252            }
3253        }
3254        Ok(directories)
3255    }
3256
3257    #[cfg(target_os = "linux")]
3258    async fn wait_for_path(path: &Path, task: &JoinHandle<Result<(), BootstrapError>>) {
3259        let deadline = tokio::time::Instant::now() + Duration::from_secs(5);
3260        while !path.exists() && tokio::time::Instant::now() < deadline {
3261            assert!(
3262                !task.is_finished(),
3263                "daemon exited before creating {}",
3264                path.display()
3265            );
3266            sleep(Duration::from_millis(10)).await;
3267        }
3268        assert!(path.exists(), "daemon did not create {}", path.display());
3269    }
3270
3271    /// An in-process daemon with the default (disabled) cgroup placement must
3272    /// leave the host's live module cgroup tree exactly as it found it.
3273    /// Red-checking this test (making it fail) creates a
3274    /// `cgroup-isolation-probe-*` directory in the live cgroup tree, which must be removed by hand.
3275    #[cfg(target_os = "linux")]
3276    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
3277    async fn run_with_config_does_not_reconcile_the_ambient_cgroup_by_default() {
3278        let temp = unique_temp_dir("bootstrap-cgroup-default-disabled");
3279        let module_id = format!("cgroup-isolation-probe-{}", process::id());
3280        let before = module_cgroup_directories().expect("read ambient module cgroups before boot");
3281        assert!(
3282            !before.contains(&OsString::from(&module_id)),
3283            "isolation probe cgroup already exists before this daemon starts"
3284        );
3285        let capture = temp.join("logs").join(format!("{module_id}.stderr.log"));
3286        let module = ConfiguredModule {
3287            script: None,
3288            carry_containment: false,
3289            module_id,
3290            program: PathBuf::from("sh"),
3291            args: vec!["-c".to_string(), "sleep 30".to_string()],
3292            env: Vec::new(),
3293            log: None,
3294            enabled: true,
3295            registration_channel: false,
3296            reserved: false,
3297            reserved_prefixes: Vec::new(),
3298            protocol: ModuleProtocol::None,
3299            overlap: Default::default(),
3300            health: HealthConfig::default(),
3301            drain_timeout_ms: None,
3302            register_timeout: crate::supervise::DEFAULT_REGISTER_TIMEOUT,
3303            route_bind_relay_timeout_ms: None,
3304            restart: RestartPolicy::default(),
3305        };
3306        let config = config_with_a_short_socket(BootstrapConfig::new(temp.join("c"), 0))
3307            .with_configured_modules([module])
3308            .with_capture_logs_dir(temp.join("logs"))
3309            .with_terminal_journal_path(temp.join("terminals.jsonl"));
3310        let task = tokio::spawn(run_with_config(config));
3311
3312        wait_for_path(&capture, &task).await;
3313        let after = module_cgroup_directories().expect("read ambient module cgroups after boot");
3314
3315        task.abort();
3316        assert!(task
3317            .await
3318            .expect_err("aborted daemon task must cancel")
3319            .is_cancelled());
3320        assert_eq!(
3321            before, after,
3322            "an in-process daemon must not create or reconcile ambient module cgroups"
3323        );
3324    }
3325
3326    #[cfg(target_os = "linux")]
3327    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
3328    async fn explicit_cgroup_root_is_prepared_inside_the_fixture_tree() {
3329        let temp = unique_temp_dir("bootstrap-cgroup-explicit-root");
3330        let cgroup_root = temp.join("cgroup");
3331        fs::create_dir(&cgroup_root).expect("create scratch cgroup root");
3332        fs::write(cgroup_root.join("cgroup.procs"), b"").expect("write scratch cgroup marker");
3333        let modules = cgroup_root.join("subc-modules");
3334        let config = config_with_a_short_socket(BootstrapConfig::new(temp.join("c"), 0))
3335            .with_cgroup_placement(CgroupPlacementConfig::Root(cgroup_root))
3336            .with_terminal_journal_path(temp.join("terminals.jsonl"));
3337        let task = tokio::spawn(run_with_config(config));
3338
3339        wait_for_path(&modules, &task).await;
3340
3341        task.abort();
3342        assert!(task
3343            .await
3344            .expect_err("aborted daemon task must cancel")
3345            .is_cancelled());
3346        assert!(
3347            fs::read_dir(&modules)
3348                .expect("read prepared modules directory")
3349                .next()
3350                .is_none(),
3351            "the delegation probe must clean up after itself"
3352        );
3353    }
3354
3355    struct EnvGuard {
3356        key: &'static str,
3357        previous: Option<OsString>,
3358    }
3359
3360    impl EnvGuard {
3361        fn set(key: &'static str, value: &Path) -> Self {
3362            let previous = env::var_os(key);
3363            env::set_var(key, value);
3364            Self { key, previous }
3365        }
3366
3367        fn set_str(key: &'static str, value: &str) -> Self {
3368            let previous = env::var_os(key);
3369            env::set_var(key, value);
3370            Self { key, previous }
3371        }
3372
3373        fn unset(key: &'static str) -> Self {
3374            let previous = env::var_os(key);
3375            env::remove_var(key);
3376            Self { key, previous }
3377        }
3378    }
3379
3380    impl Drop for EnvGuard {
3381        fn drop(&mut self) {
3382            match &self.previous {
3383                Some(value) => env::set_var(self.key, value),
3384                None => env::remove_var(self.key),
3385            }
3386        }
3387    }
3388
3389    fn unique_temp_dir(name: &str) -> ScratchDir {
3390        ScratchDir::new(name)
3391    }
3392
3393    fn temp_connection_file_path(name: &str) -> (ScratchDir, PathBuf) {
3394        let dir = unique_temp_dir(name);
3395        let path = dir.join("conn.json");
3396        (dir, path)
3397    }
3398
3399    fn auth_for(info: &ConnectionInfo) -> ServerAuth {
3400        ServerAuth::new(info.key.clone(), info.daemon_id, info.daemon_ver.clone())
3401    }
3402
3403    fn start_server(bound: BoundDaemon) -> JoinHandle<Result<(), ServerError>> {
3404        let auth = auth_for(&bound.connection_info);
3405        tokio::spawn(crate::server::serve_listeners(
3406            bound.listeners,
3407            Arc::new(Router::with_default_self_handler()),
3408            auth,
3409        ))
3410    }
3411
3412    fn expect_bound(outcome: Outcome) -> BoundDaemon {
3413        match outcome {
3414            Outcome::Bound(bound) => bound,
3415            Outcome::AlreadyRunning => panic!("fresh connection file unexpectedly had a daemon"),
3416        }
3417    }
3418
3419    async fn connect_from_info(conn: &ConnectionInfo) -> io::Result<TcpStream> {
3420        let endpoint = conn
3421            .endpoints
3422            .first()
3423            .expect("test connection file should have an endpoint");
3424        let ip: IpAddr = endpoint.host.parse().unwrap();
3425        TcpStream::connect(SocketAddr::new(ip, endpoint.port)).await
3426    }
3427
3428    fn make_connection_info(port: u16) -> ConnectionInfo {
3429        ConnectionInfo {
3430            schema: SCHEMA_VERSION,
3431            wire_version: Some(PROTOCOL_VERSION),
3432            endpoints: vec![Endpoint {
3433                host: "127.0.0.1".to_owned(),
3434                port,
3435            }],
3436            key: generate_key().unwrap(),
3437            daemon_id: generate_daemon_id().unwrap(),
3438            pid: process::id(),
3439            daemon_ver: "test-subc".to_owned(),
3440        }
3441    }
3442
3443    fn write_raw_owner_only_connection_file(path: &Path, contents: &[u8]) {
3444        fs::write(path, contents).unwrap();
3445        #[cfg(unix)]
3446        fs::set_permissions(path, fs::Permissions::from_mode(0o600)).unwrap();
3447    }
3448
3449    fn assert_owner_only_connection_file(path: &Path) {
3450        // `path` is only inspected on Unix (mode bits); on Windows the owner-only
3451        // guarantee comes from the inherited %TEMP% ACL, nothing to assert here.
3452        #[cfg(unix)]
3453        {
3454            let mode = fs::metadata(path).unwrap().permissions().mode() & 0o777;
3455            assert_eq!(mode, 0o600);
3456        }
3457        #[cfg(not(unix))]
3458        let _ = path;
3459    }
3460
3461    #[test]
3462    fn connection_file_path_source_is_xdg_runtime_dir_when_set() {
3463        let runtime_dir = OsString::from("/run/user/1000");
3464
3465        let (path, source) = connection_file_path_with_source(Some(runtime_dir), || {
3466            panic!("an explicit runtime directory needs no daemon run directory")
3467        });
3468
3469        assert_eq!(
3470            path,
3471            PathBuf::from("/run/user/1000").join(CONNECTION_FILE_NAME)
3472        );
3473        assert_eq!(source, ConnectionFileSource::XdgRuntimeDir);
3474    }
3475
3476    #[cfg(unix)]
3477    #[test]
3478    fn connection_file_path_uses_daemon_run_dir_without_xdg_runtime_dir() {
3479        for runtime_dir in [None, Some(OsString::new())] {
3480            let (path, source) = connection_file_path_with_source(runtime_dir, || {
3481                daemon_config::daemon_run_dir_from(PathBuf::from("/data/home"))
3482            });
3483
3484            assert_eq!(
3485                path,
3486                PathBuf::from("/data/home/cortexkit/run/subc-connection.json")
3487            );
3488            assert_eq!(source, ConnectionFileSource::DaemonRunDir);
3489        }
3490    }
3491
3492    #[cfg(unix)]
3493    #[test]
3494    fn connection_file_path_uses_temp_dir_with_relative_data_home() {
3495        let (path, source) = connection_file_path_with_source(None, || {
3496            daemon_config::daemon_run_dir_from(PathBuf::from("relative-data-home"))
3497        });
3498
3499        assert_eq!(
3500            path,
3501            env::temp_dir().join(format!("subc-{}.connection.json", user_connection_token()))
3502        );
3503        assert_eq!(source, ConnectionFileSource::TempDirFallback);
3504    }
3505
3506    #[cfg(unix)]
3507    #[tokio::test]
3508    async fn connection_file_path_creates_private_run_dir_before_start_lock() {
3509        use std::os::unix::fs::PermissionsExt;
3510
3511        let root = unique_temp_dir("connection-run-dir");
3512        let (path, source) = connection_file_path_with_source(None, || {
3513            daemon_config::daemon_run_dir_from(root.join("data"))
3514        });
3515        let parent = path.parent().unwrap();
3516        assert!(!parent.exists());
3517
3518        let config = BootstrapConfig::new(&path, 0).with_connection_file_source(source);
3519        let outcome = ensure_singleton_with_config(config).await.unwrap();
3520
3521        assert!(matches!(outcome, Outcome::Bound(_)));
3522        assert!(path.is_file());
3523        assert_eq!(
3524            fs::metadata(parent).unwrap().permissions().mode() & 0o777,
3525            0o700
3526        );
3527    }
3528
3529    /// Concurrent callers must derive one token. The former temp-file uid probe
3530    /// could fail transiently (same-tick name collision, fd exhaustion) and send
3531    /// the loser down the env-derived fallback with a different identity for the
3532    /// same user; this fence keeps identity independent of filesystem luck.
3533    #[test]
3534    fn user_connection_token_is_stable_under_concurrent_callers() {
3535        let expected = user_connection_token();
3536        let workers: Vec<_> = (0..32)
3537            .map(|_| {
3538                std::thread::spawn(|| (0..40).map(|_| user_connection_token()).collect::<Vec<_>>())
3539            })
3540            .collect();
3541        for worker in workers {
3542            for token in worker.join().expect("probe thread") {
3543                assert_eq!(token, expected, "token diverged under concurrent probes");
3544            }
3545        }
3546    }
3547
3548    #[cfg(not(unix))]
3549    #[test]
3550    fn connection_file_path_source_is_temp_dir_when_xdg_unset_or_empty() {
3551        for runtime_dir in [None, Some(OsString::new())] {
3552            let (path, source) = connection_file_path_with_source(runtime_dir, || {
3553                panic!("the daemon run directory is only checked on Unix")
3554            });
3555
3556            assert_eq!(
3557                path,
3558                env::temp_dir().join(format!("subc-{}.connection.json", user_connection_token()))
3559            );
3560            assert_eq!(source, ConnectionFileSource::TempDirFallback);
3561        }
3562    }
3563
3564    /// The shipped binary is the only caller that journals terminal exits into
3565    /// the real run directory, so its constructor must supply that path itself;
3566    /// the in-process default leaves it unset.
3567    #[test]
3568    fn daemon_binary_config_journals_and_captures_into_the_run_dir() {
3569        let _env_lock = ENV_LOCK.lock().unwrap();
3570        let root = unique_temp_dir("daemon-binary-config");
3571        let data_home = root.join("data");
3572        let _data = EnvGuard::set("XDG_DATA_HOME", &data_home);
3573        let _config = EnvGuard::set("XDG_CONFIG_HOME", &root.join("config"));
3574        let _port = EnvGuard::unset(SUBC_PORT_ENV);
3575
3576        let config = BootstrapConfig::from_env_for_daemon_binary().unwrap();
3577
3578        let run_dir = data_home.join("cortexkit").join("run");
3579        assert_eq!(
3580            config.terminal_journal_path,
3581            Some(run_dir.join("terminals.jsonl"))
3582        );
3583        assert_eq!(config.capture_logs_dir, Some(run_dir.join("logs")));
3584        assert_eq!(
3585            BootstrapConfig::new(root.join("connection.json"), 0).terminal_journal_path,
3586            None,
3587            "an in-process config must not journal anywhere unless asked to"
3588        );
3589    }
3590
3591    #[test]
3592    fn daemon_binary_config_refuses_a_relative_data_home() {
3593        let _env_lock = ENV_LOCK.lock().unwrap();
3594        let root = unique_temp_dir("daemon-binary-relative-data");
3595        let _data = EnvGuard::set_str("XDG_DATA_HOME", "relative-data-home");
3596        let _config = EnvGuard::set("XDG_CONFIG_HOME", &root.join("config"));
3597        let _port = EnvGuard::unset(SUBC_PORT_ENV);
3598
3599        let error = BootstrapConfig::from_env_for_daemon_binary()
3600            .expect_err("a relative data home must refuse the daemon binary's config");
3601        assert!(
3602            matches!(error, BootstrapError::RunDir(_)),
3603            "expected a run-directory refusal, got {error}"
3604        );
3605        assert!(error.to_string().contains("XDG_DATA_HOME"), "{error}");
3606    }
3607
3608    #[test]
3609    fn privileged_operator_prompt_is_loaded_by_both_bootstrap_config_paths() {
3610        let _env_lock = ENV_LOCK.lock().unwrap();
3611        let _port = EnvGuard::unset(SUBC_PORT_ENV);
3612        let (_dir, conn_path) = temp_connection_file_path("privileged-operator-prompt");
3613        let config_path = conn_path.with_file_name("subc.jsonc");
3614        for (doc, expected) in [
3615            (None, daemon_config::PrivilegedOperatorPrompt::Log),
3616            (
3617                Some(r#"{"version":1}"#),
3618                daemon_config::PrivilegedOperatorPrompt::Log,
3619            ),
3620            (
3621                Some(r#"{"version":1,"privileged_operator_prompt":"log"}"#),
3622                daemon_config::PrivilegedOperatorPrompt::Log,
3623            ),
3624            (
3625                Some(r#"{"version":1,"privileged_operator_prompt":"enforce"}"#),
3626                daemon_config::PrivilegedOperatorPrompt::Enforce,
3627            ),
3628        ] {
3629            if let Some(doc) = doc {
3630                fs::write(&config_path, doc).unwrap();
3631            }
3632            assert_eq!(
3633                BootstrapConfig::from_env_with_daemon_config_path(&config_path)
3634                    .unwrap()
3635                    .privileged_operator_prompt,
3636                expected
3637            );
3638            assert_eq!(
3639                BootstrapConfig::new(&conn_path, 0)
3640                    .with_daemon_config_path(&config_path)
3641                    .unwrap()
3642                    .privileged_operator_prompt,
3643                expected
3644            );
3645        }
3646    }
3647
3648    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
3649    async fn privileged_operator_prompt_is_snapshotted_by_running_daemon() {
3650        let dir = unique_temp_dir("privileged-operator-prompt-bootstrap");
3651        let connection_path = dir.join("connection.json");
3652        let config_path = dir.join("subc.jsonc");
3653        fs::write(
3654            &config_path,
3655            r#"{"version":1,"privileged_operator_prompt":"enforce"}"#,
3656        )
3657        .unwrap();
3658        let config = config_with_a_short_socket(BootstrapConfig::new(&connection_path, 0))
3659            .with_daemon_config_path(&config_path)
3660            .unwrap();
3661        let connection_path = config.connection_file_path.clone();
3662        let daemon = AbortOnDrop::new(tokio::spawn(run_with_config(config)));
3663        tokio::time::timeout(Duration::from_secs(5), async {
3664            while !connection_path.exists() {
3665                assert!(
3666                    !daemon.handle.is_finished(),
3667                    "daemon exited before publishing"
3668                );
3669                tokio::task::yield_now().await;
3670            }
3671        })
3672        .await
3673        .unwrap();
3674        let info = connection_file::read(&connection_path).unwrap();
3675        let mut client = connect_from_info(&info).await.unwrap();
3676        authenticate_client(&mut client, &info, Duration::from_secs(5))
3677            .await
3678            .unwrap();
3679        for (correlation, mode, expected) in [
3680            (1, "enforce", Vec::new()),
3681            (2, "log", vec!["privileged_operator_prompt"]),
3682            (3, "log", vec!["privileged_operator_prompt"]),
3683        ] {
3684            fs::write(
3685                &config_path,
3686                serde_json::json!({"version":1,"privileged_operator_prompt":mode}).to_string(),
3687            )
3688            .unwrap();
3689            let frame = crate::Frame::build(
3690                subc_protocol::FrameType::Request,
3691                subc_protocol::Flags::new(false, subc_protocol::Priority::Interactive, false),
3692                0,
3693                0,
3694                correlation,
3695                serde_json::to_vec(&subc_control::ClientControlRequest::SupervisorRescan {
3696                    preview: true,
3697                })
3698                .unwrap(),
3699            )
3700            .unwrap();
3701            crate::write_frame(&mut client, &frame).await.unwrap();
3702            let reply =
3703                tokio::time::timeout(Duration::from_secs(5), crate::read_frame(&mut client))
3704                    .await
3705                    .unwrap()
3706                    .unwrap()
3707                    .unwrap();
3708            assert_eq!(reply.header.ty, subc_protocol::FrameType::Response);
3709            assert_eq!(reply.header.corr, correlation);
3710            let subc_control::ClientControlResponse::SupervisorRescan { result } =
3711                serde_json::from_slice(&reply.body).unwrap()
3712            else {
3713                panic!("expected a rescan response");
3714            };
3715            assert_eq!(result.restart_required, expected);
3716        }
3717    }
3718
3719    #[test]
3720    fn configured_port_uses_default_config_and_env_override() {
3721        let _env_lock = ENV_LOCK.lock().unwrap();
3722        let (_dir, conn_path) = temp_connection_file_path("daemon-config-port");
3723        let config_path = conn_path.with_file_name("subc.jsonc");
3724
3725        let _port = EnvGuard::unset(SUBC_PORT_ENV);
3726        assert_eq!(
3727            BootstrapConfig::from_env_with_daemon_config_path(&config_path)
3728                .unwrap()
3729                .port,
3730            DEFAULT_SUBC_PORT
3731        );
3732
3733        fs::write(&config_path, r#"{ "version": 1, "port": 8123 }"#).unwrap();
3734        assert_eq!(
3735            BootstrapConfig::from_env_with_daemon_config_path(&config_path)
3736                .unwrap()
3737                .port,
3738            8123
3739        );
3740
3741        let _port = EnvGuard::set_str(SUBC_PORT_ENV, "9012");
3742        assert_eq!(
3743            BootstrapConfig::from_env_with_daemon_config_path(&config_path)
3744                .unwrap()
3745                .port,
3746            9012
3747        );
3748    }
3749
3750    #[tokio::test]
3751    async fn singleton_does_not_accept_a_peer_that_answers_once_then_exits() {
3752        let (_dir, path) = temp_connection_file_path("departing-peer");
3753        let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
3754        let info = make_connection_info(listener.local_addr().unwrap().port());
3755        write_connection_file(&path, &info, None).unwrap();
3756        let peer = tokio::spawn(async move {
3757            let (mut stream, _) = listener.accept().await.unwrap();
3758            subc_transport::authenticate_server(
3759                &mut stream,
3760                &info.key,
3761                &info.daemon_id,
3762                &info.daemon_ver,
3763                PROBE_AUTH_DEADLINE,
3764            )
3765            .await
3766            .unwrap();
3767        });
3768        let outcome = ensure_singleton(&path, 0).await.unwrap();
3769        peer.await.unwrap();
3770        assert!(
3771            matches!(outcome, Outcome::Bound(_)),
3772            "a departing peer is not AlreadyRunning"
3773        );
3774    }
3775
3776    #[tokio::test]
3777    async fn second_singleton_probe_against_served_tcp_daemon_reports_already_running() {
3778        let (_dir, path) = temp_connection_file_path("already-running");
3779
3780        let bound = expect_bound(ensure_singleton(&path, 0).await.unwrap());
3781        let server = start_server(bound);
3782
3783        let second = ensure_singleton(&path, 0).await.unwrap();
3784        assert!(matches!(second, Outcome::AlreadyRunning));
3785
3786        server.abort();
3787        let _ = server.await;
3788    }
3789
3790    #[tokio::test]
3791    async fn held_publication_lock_with_live_daemon_is_already_running() {
3792        let (_dir, path) = temp_connection_file_path("live-publication-lock");
3793        let config = BootstrapConfig::new(&path, 0);
3794        let mut bound = expect_bound(ensure_singleton_inner(config.clone(), false).await.unwrap());
3795        let publication = bound.publication_lock.take().unwrap();
3796        let info = bound.connection_info.clone();
3797        let server = start_server(bound);
3798
3799        // The peer was not yet published at the contender's first probe. It
3800        // must find the live peer after losing the lock to the first boot.
3801        let (contender, ()) = tokio::join!(ensure_singleton_inner(config, false), async {
3802            sleep(START_LOCK_RETRY_DELAY * 2).await;
3803            write_atomic(&path, &info).unwrap();
3804        });
3805        assert!(matches!(contender.unwrap(), Outcome::AlreadyRunning));
3806        assert!(matches!(
3807            FileExt::try_lock(&open_owner_only_lock(&start_lock_path(&path)).unwrap()),
3808            Err(TryLockError::WouldBlock)
3809        ));
3810        drop(publication);
3811        server.abort();
3812        let _ = server.await;
3813    }
3814
3815    #[tokio::test]
3816    async fn daemon_connection_file_publishes_protocol_wire_version() {
3817        let (_dir, path) = temp_connection_file_path("wire-version");
3818        let bound = expect_bound(ensure_singleton(&path, 0).await.unwrap());
3819        assert_eq!(bound.connection_info.wire_version, Some(PROTOCOL_VERSION));
3820        assert_eq!(
3821            connection_file::read(&path).unwrap().wire_version,
3822            Some(PROTOCOL_VERSION)
3823        );
3824
3825        drop(bound.listeners);
3826    }
3827
3828    #[tokio::test]
3829    async fn stale_unbound_connection_file_is_reclaimed() {
3830        let (_dir, path) = temp_connection_file_path("stale-reclaim");
3831        let stale = TcpListener::bind((Ipv4Addr::LOCALHOST, 0)).await.unwrap();
3832        let stale_port = stale.local_addr().unwrap().port();
3833        drop(stale);
3834        let stale_info = make_connection_info(stale_port);
3835        write_atomic(&path, &stale_info).unwrap();
3836
3837        let bound = expect_bound(ensure_singleton(&path, 0).await.unwrap());
3838        assert_ne!(bound.connection_info.key, stale_info.key);
3839        drop(bound.listeners);
3840    }
3841
3842    #[cfg(unix)]
3843    #[tokio::test]
3844    async fn ensure_singleton_reclaims_insecure_connection_file() {
3845        let (_dir, path) = temp_connection_file_path("insecure-reclaim");
3846        let stale = TcpListener::bind((Ipv4Addr::LOCALHOST, 0)).await.unwrap();
3847        let stale_port = stale.local_addr().unwrap().port();
3848        drop(stale);
3849        let stale_info = make_connection_info(stale_port);
3850        write_atomic(&path, &stale_info).unwrap();
3851        fs::set_permissions(&path, fs::Permissions::from_mode(0o644)).unwrap();
3852
3853        let bound = expect_bound(ensure_singleton(&path, 0).await.unwrap());
3854        assert_ne!(bound.connection_info.key, stale_info.key);
3855        assert_ne!(bound.connection_info.daemon_id, stale_info.daemon_id);
3856        assert_owner_only_connection_file(&path);
3857
3858        drop(bound.listeners);
3859    }
3860
3861    #[tokio::test]
3862    async fn ensure_singleton_reclaims_non_loopback_connection_file() {
3863        let (_dir, path) = temp_connection_file_path("non-loopback-reclaim");
3864        let mut stale_info = make_connection_info(8757);
3865        stale_info.endpoints = vec![Endpoint {
3866            host: "192.0.2.10".to_owned(),
3867            port: 8757,
3868        }];
3869        write_atomic(&path, &stale_info).unwrap();
3870
3871        let config = config_with_a_short_socket(BootstrapConfig::new(&path, 0));
3872        let bound = expect_bound(ensure_singleton_with_config(config).await.unwrap());
3873        assert_ne!(bound.connection_info.key, stale_info.key);
3874        assert_ne!(bound.connection_info.daemon_id, stale_info.daemon_id);
3875        assert!(bound
3876            .connection_info
3877            .endpoints
3878            .iter()
3879            .all(|endpoint| endpoint.host.parse::<IpAddr>().unwrap().is_loopback()));
3880        assert_owner_only_connection_file(&path);
3881
3882        drop(bound.listeners);
3883    }
3884
3885    #[tokio::test]
3886    async fn ensure_singleton_reclaims_invalid_connection_file_shapes() {
3887        let mut unsupported_schema = make_connection_info(8757);
3888        unsupported_schema.schema = SCHEMA_VERSION + 1;
3889
3890        let mut empty_endpoints = make_connection_info(8757);
3891        empty_endpoints.endpoints.clear();
3892
3893        let mut short_key = make_connection_info(8757);
3894        short_key.key = vec![0x5A; MIN_KEY_LEN - 1];
3895
3896        let cases = vec![
3897            (
3898                "unsupported-schema",
3899                serde_json::to_vec(&unsupported_schema).unwrap(),
3900                Some(unsupported_schema),
3901            ),
3902            (
3903                "empty-endpoints",
3904                serde_json::to_vec(&empty_endpoints).unwrap(),
3905                Some(empty_endpoints),
3906            ),
3907            (
3908                "short-key",
3909                serde_json::to_vec(&short_key).unwrap(),
3910                Some(short_key),
3911            ),
3912            ("invalid-json", b"{not valid connection json".to_vec(), None),
3913        ];
3914
3915        for (label, contents, old_info) in cases {
3916            let (_dir, path) = temp_connection_file_path(label);
3917            write_raw_owner_only_connection_file(&path, &contents);
3918
3919            let bound = expect_bound(ensure_singleton(&path, 0).await.unwrap());
3920            if let Some(old_info) = old_info {
3921                assert_ne!(bound.connection_info.key, old_info.key, "{label}");
3922                assert_ne!(
3923                    bound.connection_info.daemon_id, old_info.daemon_id,
3924                    "{label}"
3925                );
3926            }
3927            assert!(bound.connection_info.key.len() >= MIN_KEY_LEN, "{label}");
3928            assert_ne!(bound.connection_info.daemon_id, [0u8; 16], "{label}");
3929            assert_owner_only_connection_file(&path);
3930
3931            drop(bound.listeners);
3932        }
3933    }
3934
3935    #[tokio::test]
3936    async fn foreign_reused_port_connection_file_is_reclaimed_after_auth_probe_fails() {
3937        let (_dir, path) = temp_connection_file_path("foreign-reclaim");
3938        let foreign = TcpListener::bind((Ipv4Addr::LOCALHOST, 0)).await.unwrap();
3939        let foreign_port = foreign.local_addr().unwrap().port();
3940        write_atomic(&path, &make_connection_info(foreign_port)).unwrap();
3941        let foreign_task = tokio::spawn(async move {
3942            if let Ok((mut stream, _)) = foreign.accept().await {
3943                let mut buf = [0u8; 64];
3944                let _ = stream.read(&mut buf).await;
3945            }
3946        });
3947
3948        let bound = expect_bound(ensure_singleton(&path, 0).await.unwrap());
3949        assert!(bound
3950            .connection_info
3951            .endpoints
3952            .iter()
3953            .all(|endpoint| endpoint.port != foreign_port));
3954
3955        drop(bound.listeners);
3956        let _ = foreign_task.await;
3957    }
3958
3959    #[tokio::test]
3960    async fn stale_start_lock_file_is_reclaimable() {
3961        let (_dir, path) = temp_connection_file_path("start-lock-stale-file");
3962        let lock_path = start_lock_path(&path);
3963        drop(open_owner_only_lock(&lock_path).unwrap());
3964        assert!(lock_path.is_file());
3965
3966        let lock = StartLock::acquire(&path).await.unwrap();
3967        assert!(lock_path.is_file());
3968
3969        drop(lock);
3970        assert!(lock_path.is_file());
3971    }
3972
3973    #[tokio::test]
3974    async fn held_start_lock_blocks_second_acquire_until_release() {
3975        let (_dir, path) = temp_connection_file_path("start-lock-held");
3976        let lock_path = start_lock_path(&path);
3977        let first = StartLock::acquire(&path).await.unwrap();
3978
3979        let err = match StartLock::acquire(&path).await {
3980            Ok(_) => panic!("second acquire while held must stay busy"),
3981            Err(err) => err,
3982        };
3983        assert!(matches!(
3984            err,
3985            BootstrapError::StartLockBusy {
3986                ref path,
3987                attempts: START_LOCK_RETRIES,
3988            } if path == &lock_path
3989        ));
3990
3991        drop(first);
3992
3993        let second = StartLock::acquire(&path)
3994            .await
3995            .expect("released advisory lock should be reclaimable");
3996        drop(second);
3997    }
3998
3999    #[tokio::test]
4000    async fn bind_conflict_on_fixed_port_fails_loud_without_reselecting() {
4001        let (_dir, path) = temp_connection_file_path("bind-conflict");
4002        let occupied = TcpListener::bind((Ipv4Addr::LOCALHOST, 0)).await.unwrap();
4003        let occupied_port = occupied.local_addr().unwrap().port();
4004
4005        let err = ensure_singleton(&path, occupied_port).await.unwrap_err();
4006        assert!(matches!(
4007            err,
4008            BootstrapError::Bind { ref source, .. } if source.kind() == io::ErrorKind::AddrInUse
4009        ));
4010        assert!(err.to_string().contains("set the port in config"));
4011
4012        drop(occupied);
4013    }
4014
4015    #[tokio::test]
4016    async fn ephemeral_ipv6_collision_still_serves_ipv4() {
4017        let (listeners, endpoints) = bind_loopback_with(0, |port| async move {
4018            let occupied = TcpListener::bind((Ipv6Addr::LOCALHOST, port)).await?;
4019            let result = TcpListener::bind((Ipv6Addr::LOCALHOST, port)).await;
4020            drop(occupied);
4021            result
4022        })
4023        .await
4024        .expect("an incidental IPv6 collision must not prevent an ephemeral daemon from starting");
4025        assert_eq!(endpoints.len(), 1);
4026        assert_eq!(endpoints[0].host, "127.0.0.1");
4027        TcpStream::connect((Ipv4Addr::LOCALHOST, endpoints[0].port))
4028            .await
4029            .unwrap();
4030        drop(listeners);
4031    }
4032
4033    #[tokio::test]
4034    async fn unpublished_boot_holds_singleton_lock_until_publication() {
4035        let dir = ScratchDir::new("ul");
4036        let path = dir.join("c");
4037        let config = config_with_a_short_socket(BootstrapConfig::new(&path, 0));
4038        let bound = expect_bound(ensure_singleton_inner(config, false).await.unwrap());
4039        assert!(!path.exists());
4040        let contender = open_owner_only_lock(&start_lock_path(&path)).unwrap();
4041        assert!(
4042            matches!(FileExt::try_lock(&contender), Err(TryLockError::WouldBlock)),
4043            "an unpublished boot must keep its singleton claim"
4044        );
4045        drop(bound);
4046        FileExt::try_lock(&contender).unwrap();
4047    }
4048
4049    #[tokio::test]
4050    async fn start_lock_drop_releases_claim_with_a_shared_file_description() {
4051        let dir = ScratchDir::new("sl");
4052        let path = dir.join("c");
4053        let config = config_with_a_short_socket(BootstrapConfig::new(&path, 0));
4054        let bound = expect_bound(ensure_singleton_inner(config, false).await.unwrap());
4055        // try_clone shares the open file description just as fork does,
4056        // without relying on the timing of another test's child spawn.
4057        let inherited = bound
4058            .publication_lock
4059            .as_ref()
4060            .unwrap()
4061            ._file
4062            .try_clone()
4063            .unwrap();
4064        let contender = open_owner_only_lock(&start_lock_path(&path)).unwrap();
4065        assert!(matches!(
4066            FileExt::try_lock(&contender),
4067            Err(TryLockError::WouldBlock)
4068        ));
4069        drop(bound);
4070        FileExt::try_lock(&contender).expect("dropping bootstrap releases even an inherited lock");
4071        drop(inherited);
4072    }
4073
4074    #[tokio::test]
4075    async fn readiness_probe_requires_an_authenticating_server() {
4076        let dir = ScratchDir::new("unserved-readiness");
4077        let bound = expect_bound(
4078            ensure_singleton_inner(BootstrapConfig::new(dir.join("connection.json"), 0), false)
4079                .await
4080                .unwrap(),
4081        );
4082        assert!(matches!(
4083            verify_serving(&bound.connection_info).await,
4084            Err(BootstrapError::StartupNotServing)
4085        ));
4086    }
4087
4088    #[cfg(unix)]
4089    #[tokio::test]
4090    async fn orphan_sweep_finishes_before_connection_file_publication() {
4091        use crate::live_children::{ExecutableIdentity, LiveChild};
4092        let dir = ScratchDir::new("pas");
4093        // A one-letter connection file name, and no long socket path: the sweep
4094        // this test covers runs before the local endpoint is bound, so a longer
4095        // name would only add a way for the test to fail on something else.
4096        let path = dir.join("c");
4097        let record = dir.join("live-children.json");
4098        let ready = dir.join("ready");
4099        let mut child = std::process::Command::new("/bin/sh")
4100            .args([
4101                "-c",
4102                "trap '' TERM; : > \"$0\"; read -r _",
4103                ready.to_str().unwrap(),
4104            ])
4105            .stdin(std::process::Stdio::piped())
4106            .env("XDG_DATA_HOME", dir.path())
4107            .env("XDG_RUNTIME_DIR", dir.path())
4108            .env("XDG_CONFIG_HOME", dir.path())
4109            .spawn()
4110            .unwrap();
4111        timeout(Duration::from_secs(5), async {
4112            while !ready.exists() {
4113                sleep(Duration::from_millis(5)).await;
4114            }
4115        })
4116        .await
4117        .unwrap();
4118        let observed = subc_os::Process::open(child.id())
4119            .unwrap()
4120            .unwrap()
4121            .observe()
4122            .unwrap();
4123        crate::live_children::write_record(
4124            &record,
4125            &[LiveChild {
4126                container: None,
4127                module_id: "old-sleep".into(),
4128                pid: child.id(),
4129                protocol: subc_control::ModuleProtocol::None,
4130                start_time: Some(observed.start_time),
4131                executable: observed.executable.map(ExecutableIdentity::from),
4132                cgroup_name: None,
4133            }],
4134        )
4135        .unwrap();
4136        let config = config_with_a_short_socket(BootstrapConfig::new(&path, 0))
4137            .with_live_children_record(&record);
4138        let daemon = tokio::spawn(run_with_config(config));
4139        timeout(Duration::from_secs(5), async {
4140            while !path.exists() {
4141                sleep(Duration::from_millis(5)).await;
4142            }
4143        })
4144        .await
4145        .unwrap();
4146        assert!(path.exists());
4147        let ended = child.try_wait().unwrap().is_some();
4148        if !ended {
4149            child.kill().unwrap();
4150        }
4151        child.wait().unwrap();
4152        if ended {
4153            assert!(matches!(probe_existing(&path).await.unwrap(), Probe::Live));
4154        }
4155        daemon.abort();
4156        let _ = daemon.await;
4157        assert!(
4158            ended,
4159            "the published daemon must not still owe its orphan sweep"
4160        );
4161    }
4162
4163    /// Publishing the connection file fsyncs, which can take seconds on a busy
4164    /// disk, so the daemon must do it off the async worker thread. The hook
4165    /// blocks inside the write until another task on the same single-threaded
4166    /// runtime has run. Writing on the worker thread would starve that task: the
4167    /// hook then gives up after its deadline and the test fails, as it does if
4168    /// startup publishes without going through the hooked write at all.
4169    #[tokio::test(flavor = "current_thread")]
4170    async fn connection_file_publication_leaves_the_async_runtime_free() {
4171        use std::sync::atomic::{AtomicBool, Ordering};
4172
4173        let (_dir, path) = temp_connection_file_path("publish-off-runtime");
4174        let write_started = Arc::new(AtomicBool::new(false));
4175        let (progress_tx, progress_rx) = std::sync::mpsc::channel::<()>();
4176        let (verdict_tx, verdict_rx) = std::sync::mpsc::channel::<bool>();
4177        let hook_started = Arc::clone(&write_started);
4178        connection_file_write_hook::install(&path, move || {
4179            hook_started.store(true, Ordering::SeqCst);
4180            let progressed = progress_rx.recv_timeout(Duration::from_secs(5)).is_ok();
4181            let _ = verdict_tx.send(progressed);
4182        });
4183        // Signals only after the write has started, so a message can only come
4184        // from this task running while the write is still blocked.
4185        let ticker = tokio::spawn(async move {
4186            loop {
4187                if write_started.load(Ordering::SeqCst) {
4188                    let _ = progress_tx.send(());
4189                    return;
4190                }
4191                sleep(Duration::from_millis(5)).await;
4192            }
4193        });
4194
4195        let daemon = tokio::spawn(run_with_config(BootstrapConfig::new(&path, 0)));
4196        let published = timeout(Duration::from_secs(15), async {
4197            while !path.exists() && !daemon.is_finished() {
4198                sleep(Duration::from_millis(5)).await;
4199            }
4200        })
4201        .await;
4202        let daemon_exited = daemon.is_finished();
4203        daemon.abort();
4204        let daemon_result = daemon.await;
4205        ticker.abort();
4206
4207        assert!(
4208            published.is_ok() && !daemon_exited,
4209            "the daemon must start and publish its connection file: {daemon_result:?}"
4210        );
4211        match verdict_rx.try_recv() {
4212            Ok(true) => {}
4213            Ok(false) => panic!(
4214                "no other task on the runtime ran while the connection file was being written: the write is blocking the async worker thread"
4215            ),
4216            Err(_) => panic!("startup published the connection file without the hooked write"),
4217        }
4218    }
4219
4220    /// A write that never reports back must stop startup with an error naming
4221    /// the connection file, never be taken as published.
4222    #[tokio::test]
4223    async fn a_panicking_connection_file_write_fails_startup() {
4224        let (_dir, path) = temp_connection_file_path("publish-panics");
4225        connection_file_write_hook::install(&path, || {
4226            panic!("deliberate panic inside the connection-file write")
4227        });
4228
4229        let error = timeout(
4230            Duration::from_secs(15),
4231            run_with_config(BootstrapConfig::new(&path, 0)),
4232        )
4233        .await
4234        .expect("startup must end once the write task fails")
4235        .expect_err("startup must fail when the connection-file write panics");
4236
4237        assert!(
4238            matches!(&error, BootstrapError::ConnectionFileWrite { path: failed, .. } if failed == &path),
4239            "expected a connection-file write error, got {error:?}"
4240        );
4241        let message = error.to_string();
4242        assert!(message.contains(&path.display().to_string()), "{message}");
4243        assert!(message.contains("panicked"), "{message}");
4244        assert!(!path.exists(), "no connection file may be published");
4245    }
4246
4247    #[cfg(target_os = "macos")]
4248    #[test]
4249    fn nofile_raise_worker() {
4250        let Some(path) = std::env::var_os("SUBC_NOFILE_TEST_FILE") else {
4251            return;
4252        };
4253        let (_, hard) = rlimit::Resource::NOFILE.get().unwrap();
4254        rlimit::Resource::NOFILE.set(256, hard).unwrap();
4255        raise_nofile_limit_with_ceiling(Some(10240));
4256        std::fs::write(path, rlimit::Resource::NOFILE.get().unwrap().0.to_string()).unwrap();
4257    }
4258
4259    #[cfg(target_os = "macos")]
4260    #[test]
4261    fn macos_nofile_raise_clamps_to_kernel_ceiling() {
4262        let dir = ScratchDir::new("nofile-ceiling");
4263        let result = dir.join("soft");
4264        let status = std::process::Command::new(std::env::current_exe().unwrap())
4265            .args(["--exact", "bootstrap::tests::nofile_raise_worker"])
4266            .env("SUBC_NOFILE_TEST_FILE", &result)
4267            .env("XDG_DATA_HOME", dir.path())
4268            .env("XDG_RUNTIME_DIR", dir.path())
4269            .env("XDG_CONFIG_HOME", dir.path())
4270            .status()
4271            .unwrap();
4272        assert!(status.success());
4273        let soft: u64 = std::fs::read_to_string(result).unwrap().parse().unwrap();
4274        assert!(
4275            soft > 256 && soft <= 10240,
4276            "the inherited limit must be raised within the kernel ceiling; got {soft}"
4277        );
4278    }
4279
4280    #[tokio::test]
4281    async fn key_rotation_republishes_new_material_and_old_file_fails_auth() {
4282        let (_dir, path) = temp_connection_file_path("key-rotation");
4283        let first = expect_bound(ensure_singleton(&path, 0).await.unwrap());
4284        let old_info = first.connection_info.clone();
4285        let fixed_port = old_info.endpoints[0].port;
4286        drop(first.listeners);
4287
4288        let second = expect_bound(ensure_singleton(&path, fixed_port).await.unwrap());
4289        let new_info = second.connection_info.clone();
4290        assert_ne!(old_info.key, new_info.key);
4291        assert_ne!(old_info.daemon_id, new_info.daemon_id);
4292        let server = start_server(second);
4293
4294        let mut old_stream = connect_from_info(&old_info).await.unwrap();
4295        let old_auth = authenticate_client(&mut old_stream, &old_info, PROBE_AUTH_DEADLINE).await;
4296        assert!(
4297            old_auth.is_err(),
4298            "old key must not authenticate after restart"
4299        );
4300
4301        let reread = connection_file::read(&path).unwrap();
4302        let mut new_stream = connect_from_info(&reread).await.unwrap();
4303        authenticate_client(&mut new_stream, &reread, PROBE_AUTH_DEADLINE)
4304            .await
4305            .unwrap();
4306
4307        server.abort();
4308        let _ = server.await;
4309    }
4310
4311    #[cfg(unix)]
4312    #[tokio::test]
4313    async fn published_connection_file_permissions_are_owner_only() {
4314        let (_dir, path) = temp_connection_file_path("permissions");
4315        let bound = expect_bound(ensure_singleton(&path, 0).await.unwrap());
4316
4317        let mode = fs::metadata(&path).unwrap().permissions().mode() & 0o777;
4318        assert_eq!(mode, 0o600);
4319
4320        drop(bound.listeners);
4321    }
4322
4323    /// A config with the socket in `dir`'s own short subdirectory.
4324    ///
4325    /// A Unix socket path is limited to just over a hundred bytes, and this
4326    /// harness's temporary directories use nearly all of that, so a test that
4327    /// boots a real daemon passes a short directory and a one-letter connection
4328    /// file name; anything longer makes the bind refuse. On Windows there is no
4329    /// socket path to keep short, so the config is returned unchanged.
4330    fn config_with_a_short_socket(config: BootstrapConfig) -> BootstrapConfig {
4331        let dir = config
4332            .connection_file_path
4333            .parent()
4334            .map(Path::to_path_buf)
4335            .unwrap_or_else(|| PathBuf::from("."));
4336        #[cfg(unix)]
4337        let config = BootstrapConfig {
4338            connection_file_path: dir.join("c"),
4339            local_listener: LocalListenerConfig::in_socket_dir(dir.join("s")),
4340            ..config
4341        };
4342        #[cfg(not(unix))]
4343        let _ = dir;
4344        config
4345    }
4346
4347    /// The shipped binary puts the socket in its own run directory. The file is
4348    /// named from the connection file's path, so a restart finds it again.
4349    #[cfg(unix)]
4350    #[test]
4351    fn the_daemon_binary_puts_its_socket_in_the_run_directory() {
4352        let _env_lock = ENV_LOCK.lock().unwrap();
4353        let root = ScratchDir::new("binary-local-socket");
4354        let data_home = root.join("data");
4355        let _data = EnvGuard::set("XDG_DATA_HOME", &data_home);
4356        let _config = EnvGuard::set("XDG_CONFIG_HOME", &root.join("config"));
4357        let _port = EnvGuard::unset(SUBC_PORT_ENV);
4358
4359        let config = BootstrapConfig::from_env_for_daemon_binary().unwrap();
4360
4361        let run_dir = data_home.join("cortexkit").join("run");
4362        assert_eq!(
4363            config.local_listener.configured_dir(),
4364            Some(run_dir.as_path()),
4365            "the binary serves from its run directory"
4366        );
4367        let socket = local_listener::socket_path_for(Some(&run_dir), &config.connection_file_path)
4368            .expect("the binary config names a directory");
4369        assert_eq!(socket.parent().unwrap(), run_dir);
4370        assert_eq!(
4371            socket.file_name().unwrap().to_string_lossy(),
4372            "subc.sock",
4373            "a fixed name: the run directory belongs to one data home"
4374        );
4375    }
4376
4377    /// An in-process daemon that names no directory serves TCP only: it publishes
4378    /// no local endpoint, creates nothing under the data home, and says nothing is
4379    /// unavailable, because nothing was asked for.
4380    /// The environment lock covers only the setup: the daemon under test reads
4381    /// its data home from the process environment while it boots, and holding
4382    /// the lock across that await would block every other test that sets one.
4383    #[cfg(unix)]
4384    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
4385    async fn an_in_process_daemon_without_a_configured_directory_serves_no_local_endpoint() {
4386        let root = ScratchDir::new("in-process-no-local-socket");
4387        let data_home = root.join("data");
4388        fs::create_dir_all(&data_home).unwrap();
4389        let connection_path = root.join("c");
4390        let _data;
4391        let _config;
4392        let _port;
4393        {
4394            let _env_lock = ENV_LOCK.lock().unwrap();
4395            _data = EnvGuard::set("XDG_DATA_HOME", &data_home);
4396            _config = EnvGuard::set("XDG_CONFIG_HOME", &root.join("config"));
4397            _port = EnvGuard::unset(SUBC_PORT_ENV);
4398        }
4399
4400        let bound = expect_bound(ensure_singleton(&connection_path, 0).await.unwrap());
4401
4402        assert!(bound.local_endpoint.is_none());
4403        assert!(bound.local_endpoint_unavailable.is_none());
4404        let published = connection_file::read_with_local_endpoint(&connection_path).unwrap();
4405        assert!(published.local_endpoint.is_none());
4406        assert!(
4407            local_listener::socket_path_for(None, &connection_path).is_none(),
4408            "no configured directory, no socket"
4409        );
4410        let mut leftovers = Vec::new();
4411        let mut pending = vec![data_home.clone()];
4412        while let Some(dir) = pending.pop() {
4413            for entry in fs::read_dir(&dir).unwrap() {
4414                let entry = entry.unwrap();
4415                let path = entry.path();
4416                if entry.file_type().unwrap().is_dir() {
4417                    pending.push(path.clone());
4418                }
4419                if entry.file_name().to_string_lossy().ends_with(".sock") {
4420                    leftovers.push(path);
4421                }
4422            }
4423        }
4424        assert!(
4425            leftovers.is_empty(),
4426            "an in-process daemon must not create a socket in the data home: {leftovers:?}"
4427        );
4428    }
4429
4430    /// A local endpoint that cannot be bound does not stop the daemon: it keeps
4431    /// serving TCP, publishes no local endpoint, and reports the reason where an
4432    /// operator reads daemon facts. Every module stays up for a feature nothing
4433    /// has to use.
4434    #[cfg(unix)]
4435    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
4436    async fn a_daemon_whose_socket_path_is_too_long_still_serves_tcp() {
4437        let dir = ScratchDir::new("tcp-only");
4438        let canonical = std::fs::canonicalize(&dir).unwrap();
4439        let connection_path = canonical.join("c");
4440        // The socket directory is deep enough that the socket's path is over the
4441        // Unix socket limit, so binding it must fail.
4442        let deep = canonical.join("x".repeat(80));
4443        fs::create_dir(&deep).unwrap();
4444        fs::set_permissions(&deep, fs::Permissions::from_mode(0o700)).unwrap();
4445        let config =
4446            BootstrapConfig::new(&connection_path, 0).with_local_listener_socket_dir(&deep);
4447        let bound = expect_bound(ensure_singleton_with_config(config).await.unwrap());
4448        assert!(
4449            bound.local_endpoint.is_none(),
4450            "a socket that cannot be bound is not published"
4451        );
4452        assert!(
4453            bound
4454                .local_endpoint_unavailable
4455                .as_deref()
4456                .is_some_and(|reason| reason.contains("too long")),
4457            "{:?}",
4458            bound.local_endpoint_unavailable
4459        );
4460        let published = connection_file::read_with_local_endpoint(&connection_path).unwrap();
4461        assert!(published.local_endpoint.is_none());
4462        assert!(
4463            !published.info.endpoints.is_empty(),
4464            "TCP is still published"
4465        );
4466
4467        // The daemon serves TCP as usual.
4468        let server = start_server(bound);
4469        let info = connection_file::read(&connection_path).unwrap();
4470        let mut client = connect_from_info(&info).await.unwrap();
4471        authenticate_client(&mut client, &info, PROBE_AUTH_DEADLINE)
4472            .await
4473            .expect("a TCP client still completes the handshake");
4474        server.abort();
4475        let _ = server.await;
4476    }
4477
4478    /// The published file names the local endpoint the daemon actually serves,
4479    /// and a client that trusts the file completes the handshake over it.
4480    #[cfg(unix)]
4481    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
4482    async fn published_connection_file_names_the_served_local_endpoint() {
4483        let (_dir, path) = temp_connection_file_path("local-endpoint");
4484        // The socket goes in the system temporary directory rather than inside
4485        // the harness's own directory, whose long lockdown-sandbox path leaves
4486        // no room inside the Unix socket path limit.
4487        let short_socket_dir = std::env::temp_dir().join(format!("subc-bt-{}", std::process::id()));
4488        let config =
4489            BootstrapConfig::new(&path, 0).with_local_listener_socket_dir(&short_socket_dir);
4490        let bound = expect_bound(ensure_singleton_with_config(config).await.unwrap());
4491        let endpoint = connection_file::read_with_local_endpoint(&path)
4492            .unwrap()
4493            .local_endpoint
4494            .expect("the daemon serves a local endpoint, so the file names it");
4495        assert_eq!(Some(&endpoint), bound.local_endpoint.as_ref());
4496        let LocalEndpoint::Unix { path: socket_path } = &endpoint else {
4497            panic!("a Unix daemon publishes a socket path");
4498        };
4499        assert_eq!(socket_path.parent().unwrap(), short_socket_dir);
4500        assert_eq!(
4501            fs::metadata(socket_path).unwrap().permissions().mode() & 0o777,
4502            0o600
4503        );
4504
4505        let router = Arc::new(Router::with_default_self_handler());
4506        let auth = auth_for(&bound.connection_info);
4507        let server = tokio::spawn(serve_local_listener(
4508            bound.local_listener.expect("the local listener is bound"),
4509            router,
4510            auth,
4511        ));
4512        let mut client = tokio::net::UnixStream::connect(socket_path).await.unwrap();
4513        authenticate_client(&mut client, &bound.connection_info, Duration::from_secs(5))
4514            .await
4515            .expect("a socket client completes the same handshake as a TCP client");
4516
4517        server.abort();
4518        drop(bound.listeners);
4519    }
4520
4521    /// A configured directory that is not a directory refuses at bind rather
4522    /// than publishing an endpoint nothing serves.
4523    #[cfg(unix)]
4524    #[test]
4525    fn a_socket_directory_that_is_a_file_refuses() {
4526        let dir = ScratchDir::new("local-listener-file-as-dir");
4527        let file = dir.join("not-a-directory");
4528        fs::write(&file, b"x").unwrap();
4529        let error = local_listener::bind(
4530            &LocalListenerConfig::in_socket_dir(file),
4531            &dir.join("connection.json"),
4532        )
4533        .expect_err("a path that is not a directory cannot hold the socket");
4534        assert!(matches!(error, ServerError::LocalAccept { .. }), "{error}");
4535    }
4536
4537    /// The socket sits directly in the configured directory under one fixed
4538    /// name, and a directory that would put the path over the platform limit is
4539    /// refused rather than shortened around.
4540    #[cfg(unix)]
4541    #[test]
4542    fn the_socket_path_stays_within_the_unix_limit() {
4543        let run_dir = PathBuf::from("/tmp/short-run");
4544        assert!(
4545            local_listener::socket_path_for(None, &run_dir.join("one.json")).is_none(),
4546            "no configured directory means no socket"
4547        );
4548        let socket = local_listener::socket_path_for(Some(&run_dir), &run_dir.join("one.json"))
4549            .expect("a configured directory gets a socket");
4550        assert_eq!(socket, run_dir.join("subc.sock"));
4551        assert_eq!(
4552            socket,
4553            local_listener::socket_path_for(Some(&run_dir), &run_dir.join("two.json")).unwrap(),
4554            "the name does not come from the connection file"
4555        );
4556
4557        let deep = PathBuf::from(format!("/tmp/{}", "x".repeat(60)));
4558        let long = local_listener::socket_path_for(Some(&deep), &deep.join("conn.json"))
4559            .expect("a configured directory gets a socket");
4560        assert!(
4561            long.as_os_str().len() < 104,
4562            "{} is {} bytes",
4563            long.display(),
4564            long.as_os_str().len()
4565        );
4566    }
4567}