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