Skip to main content

subc_daemon/
bootstrap.rs

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