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