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