Skip to main content

subc_daemon/
daemon_config.rs

1use std::{
2    collections::BTreeMap,
3    env,
4    error::Error,
5    ffi::OsString,
6    fmt, fs, io,
7    path::{Path, PathBuf},
8    time::Duration,
9};
10
11pub use crate::activity::ActivityConfig;
12use cortexkit_log::Retention;
13use serde::Deserialize;
14use subc_control::ModuleProtocol;
15use subc_jsonc::jsonc_to_json;
16use subc_protocol::manifest::is_valid_capability_identifier;
17
18use crate::{
19    supervise::{ModuleOverlap, SUBC_SPAWN_ROLE_ENV},
20    HealthAction, HealthConfig, ModuleSpec, RestartPolicy,
21};
22
23const DAEMON_CONFIG_RELATIVE_PATH: &str = "cortexkit/subc.jsonc";
24const SUPPORTED_CONFIG_VERSION: u32 = 1;
25pub(crate) const CK_LOG_ENV: &str = "CK_LOG";
26pub(crate) const CAPTURE_MAX_FILE_MB_ENV: &str = "__SUBC_CAPTURE_LOG_MAX_FILE_MB";
27pub(crate) const CAPTURE_KEEP_ENV: &str = "__SUBC_CAPTURE_LOG_KEEP";
28pub(crate) const CAPTURE_MAX_AGE_DAYS_ENV: &str = "__SUBC_CAPTURE_LOG_MAX_AGE_DAYS";
29/// The child's own segment retention, read by `cortexkit_log::Config::from_env`.
30/// Unlike the `__SUBC_CAPTURE_*` names above these are a real child-process
31/// contract and are spawned into the environment.
32pub(crate) const CHILD_LOG_MAX_AGE_DAYS_ENV: &str = "CK_LOG_MAX_AGE_DAYS";
33pub(crate) const CHILD_LOG_ALARM_SEGMENT_MB_ENV: &str = "CK_LOG_ALARM_SEGMENT_MB";
34
35/// Top-level daemon config sections that rescan cannot apply. The daemon
36/// snapshots these sections at start and reports later rescan changes as
37/// `restart_required`. Setup also uses this set, when it observes the system
38/// before writing config (a dry run included): it lists the dotted keys core
39/// setup would write, treating a missing config file as empty so every
40/// desired key counts as pending, and, when the daemon is live, flags each key
41/// whose top-level section is one of these (`restart_required_from_pending_keys`
42/// in subc-core). It cannot ask the daemon instead, because the new sections
43/// are not on disk yet. Match this enum
44/// exhaustively so a new section cannot be added without a comparison.
45/// Per-module `health` (including `health.http`, cadence and deadline) is not
46/// in this set: rescan applies it live without a module restart. Launch-spec
47/// fields such as `protocol` take effect at the next spawn instead.
48#[derive(Clone, Copy, Debug, Eq, PartialEq)]
49pub enum RestartRequiredSection {
50    Port,
51    Storage,
52    AdmissionFactsCarrierModuleId,
53    AdmissionFactsTargets,
54    ScopeAuthorityOwners,
55    FederatedScopeOwner,
56    PrivilegedOperatorPrompt,
57}
58
59impl RestartRequiredSection {
60    pub const ALL: [Self; 7] = [
61        Self::Port,
62        Self::Storage,
63        Self::AdmissionFactsCarrierModuleId,
64        Self::AdmissionFactsTargets,
65        Self::ScopeAuthorityOwners,
66        Self::FederatedScopeOwner,
67        Self::PrivilegedOperatorPrompt,
68    ];
69
70    pub const fn label(self) -> &'static str {
71        match self {
72            Self::Port => "port",
73            Self::Storage => "storage",
74            Self::AdmissionFactsCarrierModuleId => "admission_facts_carrier_module_id",
75            Self::AdmissionFactsTargets => "admission_facts_targets",
76            Self::ScopeAuthorityOwners => "scope_authority_owners",
77            Self::FederatedScopeOwner => "federated_scope_owner",
78            Self::PrivilegedOperatorPrompt => "privileged_operator_prompt",
79        }
80    }
81}
82
83/// Whether privileged client operations are only logged or require operator approval.
84#[derive(Clone, Copy, Debug, Default, Deserialize, Eq, PartialEq)]
85#[serde(rename_all = "lowercase")]
86pub enum PrivilegedOperatorPrompt {
87    #[default]
88    Log,
89    Enforce,
90}
91
92/// `scope_authority_owners` when the config does not set it: the session
93/// runtime, the same module that carries admission facts today.
94pub fn default_scope_authority_owners() -> Vec<String> {
95    vec!["prefrontal-core".to_string()]
96}
97
98pub fn default_federated_scope_owner() -> String {
99    "callosum".to_string()
100}
101
102/// Refused at parse time by both layers (daemon-wide and per-module) — `0`
103/// would turn every affected bind into an instant failure, which is not a
104/// posture anyone deliberately configures. The asymmetry with
105/// `drain_timeout_ms` (which accepts `0` as a legitimate "tear down now")
106/// is intentional: drain `0` is an *action* an operator takes during a
107/// wedge bounce; bind `0` is a typo wearing a config key. Operators who
108/// want a module unreachable should use `enabled: false` instead.
109///
110/// The per-module variant prefixes the offending module id before this
111/// message — see `parse_doc`.
112const ROUTE_BIND_RELAY_ZERO_MESSAGE: &str = "route_bind_relay_timeout_ms must be greater than 0 (a zero budget fails every bind to the module; to make a module unreachable use enabled: false)";
113
114/// Refused at parse time because a zero window and a large one are different
115/// settings that look alike in a diff. The crash budget counts restarts inside
116/// `window_secs`; with `0`, no restart is ever inside it, so the cap can never
117/// be reached and the module restarts forever. That is a real posture, but it
118/// is "unlimited restarts", and anyone choosing it must say so by name rather
119/// than by writing a zero that reads like "no delay".
120const RESTART_WINDOW_ZERO_MESSAGE: &str = "restart.window_secs must be greater than 0 (a zero window holds no crash, so the budget can never be spent; for effectively unlimited restarts set a deliberately large window_secs, and to stop restarting entirely set restart.max_restarts: 0)";
121
122/// Logging policy parsed from `subc.jsonc`.
123///
124/// `retention` is the rename-rotating policy for the daemon's per-child
125/// stderr CAPTURE file (single writer). The daemon's own log and every module's
126/// log are date segments under fleet-logging r2, which never rotate; for those
127/// only `retention.max_age_days` applies, plus `alarm_segment_mb`.
128#[derive(Debug, Clone, PartialEq, Eq)]
129pub struct LoggingConfig {
130    pub level: String,
131    /// Per-logger levels. Keys are logger names; a key with no dot is taken
132    /// as a COMPONENT of the module it is configured on (`perf` on synapse is
133    /// `synapse.perf`), so an operator's `subc.jsonc` reads naturally. See
134    /// [`LoggingConfig::filter_spec`].
135    pub tags: BTreeMap<String, String>,
136    pub retention: Retention,
137    /// Segment size at which the writer alarms (never truncates).
138    pub alarm_segment_mb: u32,
139}
140
141impl LoggingConfig {
142    /// The `CK_LOG` value for `module_id`. Logger names in `CK_LOG` are
143    /// absolute (`synapse.perf=info`), while the config block is written per
144    /// module, so a dotless key is prefixed with the module id here. A key
145    /// that already starts with `<module_id>.` or contains a dot is passed
146    /// verbatim; a key equal to the module id is the root and is also
147    /// verbatim. Without this a config `tags: { perf: debug }` would emit
148    /// `perf=debug`, which matches no logger on the r2 hierarchy and silently
149    /// does nothing.
150    pub fn filter_spec(&self, module_id: &str) -> String {
151        let mut directives = vec![self.level.clone()];
152        directives.extend(self.tags.iter().map(|(logger, level)| {
153            if logger == module_id || logger.contains('.') {
154                format!("{logger}={level}")
155            } else {
156                format!("{module_id}.{logger}={level}")
157            }
158        }));
159        directives.join(",")
160    }
161
162    pub fn segment_retention(&self) -> cortexkit_log::SegmentRetention {
163        cortexkit_log::SegmentRetention {
164            max_age_days: self.retention.max_age_days,
165            alarm_segment_mb: self.alarm_segment_mb,
166        }
167    }
168}
169
170#[derive(Debug, Clone, PartialEq, Eq)]
171pub struct DaemonConfig {
172    pub path: PathBuf,
173    pub port: Option<u16>,
174    /// Restart-required: rescan must not change the policy that guards rescan itself.
175    pub privileged_operator_prompt: PrivilegedOperatorPrompt,
176    /// Daemon-wide default drain budget (ms) for module teardown: how long a
177    /// drain waits for already-dispatched requests to finalize. `None` uses
178    /// the built-in default (30s). Per-module `drain_timeout_ms` overrides.
179    pub drain_timeout_ms: Option<u64>,
180    /// Daemon-wide default route.bind relay budget (ms): how long the daemon
181    /// waits for the target module to acknowledge a relayed `route.bind` before
182    /// reporting `module_timeout`. `None` uses the built-in default (12s, set
183    /// in `control::DEFAULT_ROUTE_BIND_RELAY_TIMEOUT`). Per-module
184    /// `route_bind_relay_timeout_ms` overrides. `0` is refused at parse time
185    /// (a zero budget fails every bind; use `enabled: false` to make a
186    /// module unreachable) — this is deliberately asymmetric with
187    /// `drain_timeout_ms`, where `0` is the sanctioned "tear down now".
188    pub route_bind_relay_timeout_ms: Option<u64>,
189    pub modules: Vec<ConfiguredModule>,
190    /// Central storage policy: the single backend choice all managed modules use.
191    /// `None` when the config has no `storage` section (no managed storage).
192    pub storage: Option<StorageConfig>,
193    /// Exact module id whose reserved process may carry admission facts.
194    pub admission_facts_carrier_module_id: Option<String>,
195    /// Exact target module ids that may receive facts from the configured carrier.
196    pub admission_facts_targets: Option<Vec<String>>,
197    /// Module ids whose scopes may set the attributes that grant authority
198    /// (`agent_id`, `delegates`), and whose scopes are stamped
199    /// `owner_authorized`. Restart-required: a change reaching a running daemon
200    /// would leave live routes holding an `owner_authorized` stamp the owner no
201    /// longer has, and a restart closes every route.
202    pub scope_authority_owners: Vec<String>,
203    /// Exact reserved module id allowed to own federated scopes. Restart-required.
204    pub federated_scope_owner: String,
205    /// Capability names reserved to one module id. The binding may name a module
206    /// that is not configured yet so an operator can reserve an interface before
207    /// installing its provider.
208    pub reserved_capabilities: BTreeMap<String, String>,
209}
210
211/// Central storage configuration: one backend for every managed module. subc
212/// resolves this into a per-module storage descriptor and delivers it in the
213/// module's HELLO_ACK; the module opens it via the shared store library.
214#[derive(Debug, Clone, PartialEq, Eq)]
215pub enum StorageConfig {
216    /// Each module gets its own sqlite file under `data_home`.
217    Sqlite { data_home: PathBuf },
218}
219
220impl StorageConfig {
221    /// Resolve this central policy into a module's storage descriptor: the opaque
222    /// JSON delivered in `HELLO_ACK.storage`. The shape matches
223    /// `cortexkit_store_types::StorageDescriptor` (subc constructs it by hand to
224    /// avoid a database-library dependency in the thin daemon). The module
225    /// deserializes it into that type and hands it to `cortexkit-store`.
226    ///
227    /// THE DESCRIPTOR IS ADVISORY, NOT BINDING, and the daemon has no way to
228    /// tell whether a module consumed it. A module that opens its store BEFORE
229    /// connecting -- building its own descriptor from an environment variable --
230    /// never reads this at all, and nothing on the wire reports that.
231    ///
232    /// Two consequences worth knowing before reasoning from a store path:
233    ///
234    /// * A store at the path below does NOT prove the descriptor arrived or was
235    ///   keyed correctly; a self-keying module can land on the same path by
236    ///   agreeing with the convention rather than by consuming the descriptor.
237    ///   Any test asserting "the store landed under MODULE_ID" proves the
238    ///   daemon's half only for modules that derive the path from the id they
239    ///   claimed.
240    /// * Where a self-keying module disagrees, BOTH paths can exist. Observed on
241    ///   the live box: astrocyte is handed a data dir already ending in
242    ///   `cortexkit/astrocyte` and appends the same suffix again, so its real
243    ///   store sits nested while an empty file remains at the path this function
244    ///   names -- and a reader inspecting that directory would reasonably
245    ///   conclude the module has an empty store.
246    pub fn descriptor_for(&self, module_id: &str) -> serde_json::Value {
247        match self {
248            // Path convention mirrors cortexkit_store_types::sqlite_store_path:
249            // <data_home>/cortexkit/<module_id>/store.db. One database per module;
250            // a project-scoped module partitions its own rows internally.
251            //
252            // Build the path with forward slashes (NOT PathBuf::join, which inserts
253            // backslashes on Windows) so the delivered wire descriptor is identical
254            // cross-platform and byte-matches the store-types helper. Forward-slash
255            // paths are accepted by sqlite on every platform.
256            StorageConfig::Sqlite { data_home } => {
257                let data_home = data_home.to_string_lossy();
258                let path = format!(
259                    "{}/cortexkit/{module_id}/store.db",
260                    data_home.trim_end_matches('/')
261                );
262                serde_json::json!({
263                    "module_id": module_id,
264                    "storage_namespace": "default",
265                    "isolation": { "kind": "module" },
266                    "backend": { "backend": "sqlite", "path": path },
267                })
268            }
269        }
270    }
271}
272
273#[derive(Debug, Clone, PartialEq, Eq)]
274pub struct ConfiguredModule {
275    pub module_id: String,
276    pub program: PathBuf,
277    pub args: Vec<String>,
278    pub env: Vec<(String, String)>,
279    /// Effective module logging policy. An absent module block inherits the
280    /// daemon-wide logging block; when neither exists this stays absent so
281    /// `CK_LOG` is genuinely absent from the service-manager-minimal child env.
282    pub log: Option<LoggingConfig>,
283    pub enabled: bool,
284    /// Approved support for the inherited registration channel. Absence is false;
285    /// protocol-none children do not need a registration channel.
286    pub registration_channel: bool,
287    /// When true, only the daemon-spawned process for this `module_id` may register
288    /// it: subc injects a one-time launch nonce on spawn and rejects any HELLO for
289    /// this id whose nonce does not match. Protects security-boundary modules (e.g.
290    /// the credential vault) from being impersonated by another key-holder while the
291    /// real process is down or restarting. Defaults to false.
292    pub reserved: bool,
293    /// Namespace prefixes owned by this reserved, supervised module. A HELLO for a
294    /// module id under one of these prefixes must echo this owner module's current
295    /// spawn nonce.
296    pub reserved_prefixes: Vec<String>,
297    /// Which wire protocol this module speaks, as declared. Absent in config
298    /// means `Subc`, which is what every module written before this key meant.
299    pub protocol: ModuleProtocol,
300    /// Whether a second process of this module may run beside the first, which
301    /// a blue/green swap does. Absent in config means exclusive.
302    pub overlap: ModuleOverlap,
303    /// Keep the current process container across module restarts. The value is
304    /// fixed when a fresh container starts, not when an existing one is replaced.
305    pub carry_containment: bool,
306    pub health: HealthConfig,
307    /// Effective drain budget (ms) for this module's teardown, already resolved
308    /// against the daemon-wide default at parse time. `None` = built-in default.
309    pub drain_timeout_ms: Option<u64>,
310    /// First-HELLO budget for ordinary spawns. Resolved when supervision starts,
311    /// like the restart policy; reload and swap use their own readiness budgets.
312    pub register_timeout: Duration,
313    /// Effective route.bind relay budget (ms) for this module, already resolved
314    /// against the daemon-wide default at parse time. `None` = built-in default
315    /// (12s). A `0` is refused at parse time at both layers — see
316    /// `DaemonConfig::route_bind_relay_timeout_ms` and `ROUTE_BIND_RELAY_ZERO_MESSAGE`.
317    pub route_bind_relay_timeout_ms: Option<u64>,
318    /// This module's crash-restart budget, fully resolved at parse time: every
319    /// absent key of the optional `restart` block falls back to the supervisor
320    /// default (3 restarts per 600s, 100ms base backoff, 30s maximum backoff).
321    /// Stored resolved rather than as an `Option` so no later layer has to
322    /// re-derive the defaults and get them subtly different.
323    ///
324    /// Read when a module STARTS being supervised (daemon start, or a rescan
325    /// that adds the module). Like `drain_timeout_ms`, an edit to this block for
326    /// an already-running module is not part of the rescan diff, so it takes
327    /// effect on the next daemon start rather than immediately. With approved-
328    /// store authority, approved generations reconcile it live on a separate path.
329    pub restart: RestartPolicy,
330}
331
332impl ConfiguredModule {
333    pub fn module_spec(&self) -> ModuleSpec {
334        let mut env = self.env.clone();
335        if let Some(log) = &self.log {
336            env.retain(|(key, _)| {
337                key != CK_LOG_ENV
338                    && key != CAPTURE_MAX_FILE_MB_ENV
339                    && key != CAPTURE_KEEP_ENV
340                    && key != CAPTURE_MAX_AGE_DAYS_ENV
341            });
342            env.retain(|(key, _)| {
343                key != CHILD_LOG_MAX_AGE_DAYS_ENV && key != CHILD_LOG_ALARM_SEGMENT_MB_ENV
344            });
345            env.push((CK_LOG_ENV.to_string(), log.filter_spec(&self.module_id)));
346            env.push((
347                CHILD_LOG_MAX_AGE_DAYS_ENV.to_string(),
348                log.retention.max_age_days.to_string(),
349            ));
350            env.push((
351                CHILD_LOG_ALARM_SEGMENT_MB_ENV.to_string(),
352                log.alarm_segment_mb.to_string(),
353            ));
354            // The capture file's own rotation policy. These private entries are
355            // supervisor metadata and are removed before spawn: the child never
356            // sees them, and the capture sink reads them back at spawn time.
357            env.push((
358                CAPTURE_MAX_FILE_MB_ENV.to_string(),
359                log.retention.max_file_mb.to_string(),
360            ));
361            env.push((CAPTURE_KEEP_ENV.to_string(), log.retention.keep.to_string()));
362            env.push((
363                CAPTURE_MAX_AGE_DAYS_ENV.to_string(),
364                log.retention.max_age_days.to_string(),
365            ));
366        }
367        ModuleSpec {
368            module_id: self.module_id.clone(),
369            program: self.program.clone(),
370            args: self.args.clone(),
371            env,
372            reserved: self.reserved,
373            reserved_prefixes: self.reserved_prefixes.clone(),
374            protocol: self.protocol,
375            overlap: self.overlap,
376            carry_containment: self.carry_containment,
377        }
378    }
379}
380
381#[derive(Debug)]
382pub enum DaemonConfigError {
383    Read {
384        path: PathBuf,
385        source: io::Error,
386    },
387    InvalidJsonc {
388        path: PathBuf,
389        message: String,
390    },
391    InvalidJson {
392        path: PathBuf,
393        source: serde_json::Error,
394    },
395    UnsupportedVersion {
396        path: PathBuf,
397        version: u32,
398    },
399    InvalidValue {
400        path: PathBuf,
401        message: String,
402    },
403}
404
405#[derive(Debug, Deserialize)]
406struct RawDaemonConfig {
407    version: u32,
408    #[serde(default)]
409    activity: ActivityConfig,
410    #[serde(default)]
411    port: Option<u16>,
412    #[serde(default)]
413    privileged_operator_prompt: PrivilegedOperatorPrompt,
414    #[serde(default)]
415    drain_timeout_ms: Option<u64>,
416    #[serde(default)]
417    route_bind_relay_timeout_ms: Option<u64>,
418    #[serde(default)]
419    log: Option<RawLoggingConfig>,
420    #[serde(default)]
421    modules: BTreeMap<String, RawModuleConfig>,
422    #[serde(default)]
423    storage: Option<RawStorageConfig>,
424    #[serde(default)]
425    admission_facts_carrier_module_id: Option<String>,
426    #[serde(default)]
427    admission_facts_targets: Option<Vec<String>>,
428    #[serde(default)]
429    scope_authority_owners: Option<Vec<String>>,
430    #[serde(default = "default_federated_scope_owner")]
431    federated_scope_owner: String,
432    #[serde(default)]
433    reserved_capabilities: BTreeMap<String, String>,
434}
435
436#[derive(Debug, Deserialize)]
437#[serde(tag = "backend", rename_all = "snake_case")]
438enum RawStorageConfig {
439    Sqlite {
440        /// Where per-module sqlite files live. Defaults to the platform data home
441        /// (`$XDG_DATA_HOME`, else `~/.local/share`) when omitted.
442        #[serde(default)]
443        data_home: Option<PathBuf>,
444    },
445}
446
447#[derive(Debug, Deserialize)]
448struct RawModuleConfig {
449    program: PathBuf,
450    #[serde(default)]
451    args: Vec<String>,
452    #[serde(default)]
453    env: BTreeMap<String, String>,
454    #[serde(default)]
455    log: Option<RawLoggingConfig>,
456    #[serde(default = "default_enabled")]
457    enabled: bool,
458    #[serde(default)]
459    registration_channel: bool,
460    #[serde(default)]
461    reserved: bool,
462    // Unknown module keys remain ignored. Retain them only to warn about the
463    // retired nonce switch for one release, including an explicitly null value.
464    #[serde(flatten)]
465    ignored: BTreeMap<String, serde_json::Value>,
466    #[serde(default)]
467    reserved_prefixes: Vec<String>,
468    /// Read as a raw string rather than a serde enum so an unusable value is
469    /// refused as an `InvalidValue` naming the module and the value the operator
470    /// typed, instead of a serde variant error that names neither.
471    #[serde(default)]
472    protocol: Option<String>,
473    /// Read as a raw string for the same reason as `protocol`.
474    #[serde(default)]
475    overlap: Option<String>,
476    #[serde(default)]
477    carry_containment: bool,
478    #[serde(default)]
479    health: Option<RawHealthConfig>,
480    #[serde(default)]
481    drain_timeout_ms: Option<u64>,
482    #[serde(default)]
483    register_timeout_s: Option<u64>,
484    #[serde(default)]
485    route_bind_relay_timeout_ms: Option<u64>,
486    #[serde(default)]
487    restart: Option<RawRestartConfig>,
488}
489
490#[derive(Debug, Clone, Deserialize)]
491struct RawLoggingConfig {
492    #[serde(default)]
493    level: Option<String>,
494    #[serde(default)]
495    tags: BTreeMap<String, String>,
496    #[serde(default)]
497    alarm_segment_mb: Option<u32>,
498    #[serde(default)]
499    max_file_mb: Option<u32>,
500    #[serde(default)]
501    keep: Option<u8>,
502    #[serde(default)]
503    max_age_days: Option<u32>,
504}
505
506#[derive(Debug, Deserialize)]
507struct RawRestartConfig {
508    #[serde(default)]
509    max_restarts: Option<u32>,
510    #[serde(default)]
511    window_secs: Option<u64>,
512    #[serde(default)]
513    backoff_ms: Option<u64>,
514    #[serde(default)]
515    max_backoff_ms: Option<u64>,
516}
517
518#[derive(Debug, Deserialize)]
519struct RawHealthConfig {
520    #[serde(default)]
521    http: Option<String>,
522    #[serde(default)]
523    cadence_ms: Option<u64>,
524    #[serde(default)]
525    deadline_ms: Option<u64>,
526    #[serde(default)]
527    failure_threshold: Option<u32>,
528    #[serde(default)]
529    on_degraded: Option<RawHealthAction>,
530    #[serde(default)]
531    on_failing: Option<RawHealthAction>,
532    #[serde(default)]
533    critical: bool,
534}
535
536#[derive(Debug, Deserialize)]
537#[serde(rename_all = "snake_case")]
538enum RawHealthAction {
539    Report,
540    Restart,
541    Alert,
542}
543
544pub fn default_config_path() -> PathBuf {
545    default_config_home().join(DAEMON_CONFIG_RELATIVE_PATH)
546}
547
548/// The XDG-style CONFIG HOME (`~/.config`, `%APPDATA%`), with no `cortexkit/`
549/// tail. This is the AUTHORITY for every module that resolves its own config
550/// file: mirrors (`cortexkit-store-types::resolve_config_home`, and any module
551/// still carrying a hand copy of this ladder) assert against
552/// `tests/golden/config_home_resolution.json` and may not diverge. It is split
553/// from `default_config_path` so the mirror and the daemon share one ladder
554/// rather than one ladder plus a tail that each copy re-appends differently --
555/// the daemon appends `cortexkit/subc.jsonc`, a module appends
556/// `cortexkit/<its file>`, and a copy that bakes the tail in cannot be reused.
557///
558/// Resolution: `XDG_CONFIG_HOME` → `APPDATA` (Windows) → `USERPROFILE` +
559/// `AppData\Roaming` (Windows) → `HOME/.config` → `.config` relative.
560/// Empty values count as unset. Mirrors the data-home ladder exactly except for
561/// the per-platform tails (`.local/share` there, `.config` here).
562///
563/// A RELATIVE result means one of two things and the resolver does not say
564/// which: no home variable was set (the final rung), or `XDG_CONFIG_HOME` was
565/// itself relative (honoured as-is, golden-pinned). Either way the path resolves
566/// against the caller's cwd, which is a true answer about a directory nobody
567/// chose. Callers that must be fail-closed check `is_absolute()` and refuse;
568/// the daemon does so for the storage descriptor it serves (`parse_doc`).
569pub fn default_config_home() -> PathBuf {
570    if let Some(config_home) = non_empty_os_var("XDG_CONFIG_HOME") {
571        return PathBuf::from(config_home);
572    }
573
574    #[cfg(windows)]
575    {
576        if let Some(app_data) = non_empty_os_var("APPDATA") {
577            return PathBuf::from(app_data);
578        }
579        if let Some(user_profile) = non_empty_os_var("USERPROFILE") {
580            return PathBuf::from(user_profile).join("AppData").join("Roaming");
581        }
582    }
583
584    if let Some(home) = non_empty_os_var("HOME") {
585        return PathBuf::from(home).join(".config");
586    }
587
588    PathBuf::from(".config")
589}
590
591pub fn load(path: impl AsRef<Path>) -> Result<Option<DaemonConfig>, DaemonConfigError> {
592    let path = path.as_ref();
593    let Some(doc) = read_config_doc(path)? else {
594        return Ok(None);
595    };
596    parse_doc(&doc, path).map(Some)
597}
598
599/// Load module configuration and activity retention from the same document.
600/// Reading once prevents an edit between reads from mixing two configurations
601/// during rescan, without adding fields to the public `DaemonConfig` struct.
602pub fn load_with_activity(
603    path: impl AsRef<Path>,
604) -> Result<Option<(DaemonConfig, ActivityConfig)>, DaemonConfigError> {
605    let path = path.as_ref();
606    let Some(doc) = read_config_doc(path)? else {
607        return Ok(None);
608    };
609    parse_doc_with_activity(&doc, path).map(Some)
610}
611
612/// Parse configuration text with the loader [`load_with_activity`] uses, as if
613/// it had been read from `path`. `path` only names the file in errors. Used to
614/// check text that has not been written yet, so the check and the later read
615/// of the file cannot apply different rules.
616pub fn parse_with_activity(
617    doc: &str,
618    path: impl AsRef<Path>,
619) -> Result<(DaemonConfig, ActivityConfig), DaemonConfigError> {
620    parse_doc_with_activity(doc, path.as_ref())
621}
622
623/// Loads only the daemon-wide logging block for tracing initialization.
624///
625/// The daemon installs its global subscriber before bootstrap parses the full
626/// configuration. A malformed full config is still reported by bootstrap after
627/// the file sink is live; this early read only chooses its filter and retention.
628pub fn load_logging(path: impl AsRef<Path>) -> Result<Option<LoggingConfig>, DaemonConfigError> {
629    let path = path.as_ref();
630    let Some(doc) = read_config_doc(path)? else {
631        return Ok(None);
632    };
633    let json = jsonc_to_json(&doc).map_err(|message| DaemonConfigError::InvalidJsonc {
634        path: path.to_path_buf(),
635        message,
636    })?;
637    let raw: RawDaemonConfig =
638        serde_json::from_str(&json).map_err(|source| DaemonConfigError::InvalidJson {
639            path: path.to_path_buf(),
640            source,
641        })?;
642    if raw.version != SUPPORTED_CONFIG_VERSION {
643        return Err(DaemonConfigError::UnsupportedVersion {
644            path: path.to_path_buf(),
645            version: raw.version,
646        });
647    }
648    raw.log
649        .map(|log| parse_logging_config(log, path, "daemon log"))
650        .transpose()
651}
652
653/// Create the daemon run directory at 0700 if absent, and tighten it if wider.
654///
655/// WHY A SEPARATE STEP RATHER THAN A MODE ON THE CREATOR. Several things create
656/// this directory and none of them owns it: the log sink's `create_dir_all`
657/// (0777 & ~umask, so 0755 on a default desk), the terminal journal, and the
658/// connection-file writer -- which DOES build its parents at 0700, but returns
659/// early when the directory already exists, because an existing directory keeps
660/// its mode. So the first creator to run decides the mode for every later one,
661/// and on this fleet that was the log sink.
662///
663/// WHAT THE BIT COSTS, stated so nobody over- or under-reads it: the connection
664/// secret inside is written 0600 and was never readable by another account. A
665/// world-listable run directory leaks the MAP -- which modules are live and what
666/// their connection files are named -- not the key. It is worth closing anyway
667/// because the map is reconnaissance and costs nothing to withhold. (Found by
668/// prefrontal's campaign-rig isolation probe, 2026-09-20, on a real desk.)
669///
670/// TIGHTENING IS BEST-EFFORT AND NEVER FATAL. The daemon does not own every
671/// deployment: a directory it cannot chmod belongs to someone else, and refusing
672/// to boot over a permission bit would trade a reconnaissance leak for an
673/// outage. The caller logs what it could not do.
674///
675/// A run directory that cannot be resolved (see [`daemon_run_dir`]) is reported
676/// as an `InvalidInput` I/O error rather than created under the working
677/// directory.
678pub fn ensure_daemon_run_dir_private() -> Result<PathBuf, io::Error> {
679    let path = daemon_run_dir()
680        .map_err(|error| io::Error::new(io::ErrorKind::InvalidInput, error.to_string()))?;
681    ensure_directory_private(&path)?;
682    Ok(path)
683}
684
685/// The policy half, taking the directory so a test drives a real one without
686/// touching the process environment (this crate forbids unsafe, and `set_var` is
687/// unsafe in this edition -- which is the better outcome: the seam is a parameter
688/// rather than a global the test has to fight).
689#[cfg(unix)]
690fn ensure_directory_private(path: &Path) -> Result<(), io::Error> {
691    use std::os::unix::fs::{DirBuilderExt, PermissionsExt};
692
693    if !path.exists() {
694        fs::DirBuilder::new()
695            .recursive(true)
696            .mode(0o700)
697            .create(path)?;
698        return Ok(());
699    }
700    let mode = fs::metadata(path)?.permissions().mode() & 0o777;
701    if mode & 0o077 != 0 {
702        fs::set_permissions(path, fs::Permissions::from_mode(0o700))?;
703    }
704    Ok(())
705}
706
707/// A redirected run directory must not inherit access for other users. Windows
708/// receives a protected DACL at creation and narrows existing inherited grants.
709#[cfg(windows)]
710fn ensure_directory_private(path: &Path) -> Result<(), io::Error> {
711    subc_os::windows_acl::create_private_dir(path)
712}
713
714#[cfg(not(any(unix, windows)))]
715fn ensure_directory_private(path: &Path) -> Result<(), io::Error> {
716    if !path.exists() {
717        fs::create_dir_all(path)?;
718    }
719    Ok(())
720}
721
722/// Existing per-user daemon run directory (`<data-home>/cortexkit/run`).
723///
724/// Refuses a relative data home (HOME and XDG_DATA_HOME both unset, or a
725/// relative XDG_DATA_HOME) instead of resolving it against the working
726/// directory. Resolving it there once wrote a stray `.local/` tree into a crate
727/// directory and dirtied a release build: the run directory holds the
728/// connection file, the terminal journal and the daemon's logs, so it must not
729/// depend on where a process happened to be started. The storage data home is
730/// refused at config parse for the same reason.
731pub fn daemon_run_dir() -> Result<PathBuf, DaemonRunDirError> {
732    daemon_run_dir_from(default_data_home())
733}
734
735/// The policy half of [`daemon_run_dir`], taking the data home as a parameter so
736/// a test can drive both outcomes without touching the process environment.
737fn daemon_run_dir_from(data_home: PathBuf) -> Result<PathBuf, DaemonRunDirError> {
738    if !data_home.is_absolute() {
739        return Err(DaemonRunDirError::RelativeDataHome { data_home });
740    }
741    Ok(data_home.join("cortexkit").join("run"))
742}
743
744/// Why the daemon run directory could not be resolved.
745#[derive(Debug, Clone, PartialEq, Eq)]
746pub enum DaemonRunDirError {
747    /// The data home resolved to a relative path, which would place the run
748    /// directory under whatever directory the process was started from.
749    RelativeDataHome { data_home: PathBuf },
750}
751
752impl fmt::Display for DaemonRunDirError {
753    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
754        match self {
755            Self::RelativeDataHome { data_home } => write!(
756                f,
757                "cannot resolve the daemon run directory: the data home `{}` is relative, \
758                 so it would land under the current working directory; {}",
759                data_home.display(),
760                DATA_HOME_REMEDY
761            ),
762        }
763    }
764}
765
766impl std::error::Error for DaemonRunDirError {}
767
768/// Which environment variables make the data home absolute on this platform.
769#[cfg(windows)]
770const DATA_HOME_REMEDY: &str =
771    "set XDG_DATA_HOME to an absolute path, or set APPDATA, USERPROFILE or HOME";
772#[cfg(not(windows))]
773const DATA_HOME_REMEDY: &str = "set XDG_DATA_HOME to an absolute path, or set HOME";
774
775fn read_config_doc(path: &Path) -> Result<Option<String>, DaemonConfigError> {
776    match fs::read_to_string(path) {
777        Ok(doc) => Ok(Some(doc)),
778        Err(source) if source.kind() == io::ErrorKind::NotFound => Ok(None),
779        Err(source) => Err(DaemonConfigError::Read {
780            path: path.to_path_buf(),
781            source,
782        }),
783    }
784}
785
786fn parse_doc(doc: &str, path: &Path) -> Result<DaemonConfig, DaemonConfigError> {
787    parse_doc_with_activity(doc, path).map(|(config, _)| config)
788}
789
790fn parse_doc_with_activity(
791    doc: &str,
792    path: &Path,
793) -> Result<(DaemonConfig, ActivityConfig), DaemonConfigError> {
794    let json = jsonc_to_json(doc).map_err(|message| DaemonConfigError::InvalidJsonc {
795        path: path.to_path_buf(),
796        message,
797    })?;
798    let raw: RawDaemonConfig =
799        serde_json::from_str(&json).map_err(|source| DaemonConfigError::InvalidJson {
800            path: path.to_path_buf(),
801            source,
802        })?;
803
804    if raw.version != SUPPORTED_CONFIG_VERSION {
805        return Err(DaemonConfigError::UnsupportedVersion {
806            path: path.to_path_buf(),
807            version: raw.version,
808        });
809    }
810
811    let daemon_logging = raw
812        .log
813        .map(|log| parse_logging_config(log, path, "daemon log"))
814        .transpose()?;
815    let default_drain_timeout_ms = raw.drain_timeout_ms;
816    // `0` here would turn every bind to a slow module into an instant failure;
817    // "off is not a budget" so refuse the key at parse time. Operators who
818    // want a module unreachable should use `enabled: false` instead. The
819    // check is per-layer (daemon-wide + per-module) because either alone
820    // poisons every affected bind.
821    let default_route_bind_relay_timeout_ms = match raw.route_bind_relay_timeout_ms {
822        Some(0) => {
823            return Err(DaemonConfigError::InvalidValue {
824                path: path.to_path_buf(),
825                message: ROUTE_BIND_RELAY_ZERO_MESSAGE.to_string(),
826            });
827        }
828        Some(value) => Some(value),
829        None => None,
830    };
831    let modules = raw
832        .modules
833        .into_iter()
834        .map(|(module_id, module)| {
835            let protocol = parse_module_protocol(module.protocol.as_deref(), path, &module_id)?;
836            let health = module
837                .health
838                .map(|health| parse_health_config(health, path, &module_id, protocol))
839                .transpose()?
840                .unwrap_or_default();
841            if let Err(reason) = crate::registry::module_id_path_hazard(&module_id) {
842                return Err(DaemonConfigError::InvalidValue {
843                    path: path.to_path_buf(),
844                    message: format!(
845                        "module id '{}' is not usable as a path component ({reason}): \
846                         the daemon derives each module's store path from its id",
847                        module_id.escape_debug()
848                    ),
849                });
850            }
851            // Same rejection at the per-module layer. `Some(0)` from a module
852            // is refused even when the daemon-wide value is also Some(0): the
853            // failure must name the offending module id so the operator can
854            // locate it in the file.
855            let per_module_route_bind_relay_timeout_ms = match module.route_bind_relay_timeout_ms {
856                Some(0) => {
857                    return Err(DaemonConfigError::InvalidValue {
858                        path: path.to_path_buf(),
859                        message: format!(
860                            "module '{module_id}' {ROUTE_BIND_RELAY_ZERO_MESSAGE}",
861                            module_id = module_id.escape_debug()
862                        ),
863                    });
864                }
865                Some(value) => Some(value),
866                None => default_route_bind_relay_timeout_ms,
867            };
868            // Through the daemon's log, not stderr: under launchd or systemd the
869            // daemon's stderr is usually discarded, so a warning written there is
870            // one no operator reads. The daemon installs its logger before it
871            // loads the full config, so this lands in run/logs/subc.<date>.log.
872            if module.ignored.contains_key("launch_nonce_env") {
873                tracing::warn!(
874                    module_id = %module_id.escape_debug(),
875                    "launch_nonce_env is deprecated and ignored; nonce delivery is determined by the platform"
876                );
877            }
878            let overlap = parse_module_overlap(module.overlap.as_deref(), path, &module_id)?;
879            if module.carry_containment && overlap == ModuleOverlap::Safe {
880                return Err(DaemonConfigError::InvalidValue {
881                    path: path.to_path_buf(),
882                    message: format!(
883                        "module '{}' sets carry_containment: true with overlap: \"safe\"; carried containment does not support overlapping instances",
884                        module_id.escape_debug()
885                    ),
886                });
887            }
888            // The spawn role is set by the supervisor on a swap candidate and
889            // nowhere else; a configured value would put the long swap warm-up
890            // budget on every plain restart, where callers wait on it.
891            if module.env.contains_key(SUBC_SPAWN_ROLE_ENV) {
892                return Err(DaemonConfigError::InvalidValue {
893                    path: path.to_path_buf(),
894                    message: format!(
895                        "module '{module_id}' sets {SUBC_SPAWN_ROLE_ENV} in env; that variable is set by the supervisor on a swap candidate only and cannot be configured",
896                        module_id = module_id.escape_debug()
897                    ),
898                });
899            }
900            // A reserved module is one only the daemon-spawned process may
901            // REGISTER as, enforced by matching a launch nonce in its HELLO. A
902            // module that speaks no subc wire sends no HELLO, so the gate has
903            // nothing to check and the pairing states an intent the daemon
904            // cannot carry out. Refusing at parse is better than accepting a
905            // security-looking declaration that protects nothing.
906            if protocol == ModuleProtocol::None && module.reserved {
907                return Err(DaemonConfigError::InvalidValue {
908                    path: path.to_path_buf(),
909                    message: format!(
910                        "module '{module_id}' sets reserved: true with protocol: \"none\"; \
911                         reserved is enforced on the module's HELLO and a protocol: \"none\" \
912                         module never registers, so the reservation could never be checked",
913                        module_id = module_id.escape_debug()
914                    ),
915                });
916            }
917            let restart = parse_restart_config(module.restart, path, &module_id)?;
918            let register_timeout_s = module
919                .register_timeout_s
920                .unwrap_or(crate::supervise::DEFAULT_REGISTER_TIMEOUT.as_secs());
921            if !(10..=3600).contains(&register_timeout_s) {
922                return Err(DaemonConfigError::InvalidValue {
923                    path: path.to_path_buf(),
924                    message: format!(
925                        "module '{module_id}' register_timeout_s must be an integer from 10 to 3600"
926                    ),
927                });
928            }
929            let log = module
930                .log
931                .map(|log| parse_logging_config(log, path, &format!("module '{module_id}' log")))
932                .transpose()?
933                .or_else(|| daemon_logging.clone());
934            Ok(ConfiguredModule {
935                module_id,
936                program: module.program,
937                args: module.args,
938                env: module.env.into_iter().collect(),
939                log,
940                enabled: module.enabled,
941                registration_channel: module.registration_channel,
942                reserved: module.reserved,
943                reserved_prefixes: module.reserved_prefixes,
944                protocol,
945                overlap,
946                carry_containment: module.carry_containment,
947                health,
948                // Per-module wins; the daemon-wide value is the fallback. `0` is
949                // legitimate ("never wait"), so this is `.or`, not `filter+or`.
950                drain_timeout_ms: module.drain_timeout_ms.or(default_drain_timeout_ms),
951                register_timeout: Duration::from_secs(register_timeout_s),
952                // Same shape as drain: an explicit per-module value wins over
953                // the daemon-wide default. A `0` here is rejected above
954                // (see "off is not a budget"), so `None` means "use the
955                // daemon-wide value" and `Some(value > 0)` means "use this".
956                route_bind_relay_timeout_ms: per_module_route_bind_relay_timeout_ms,
957                restart,
958            })
959        })
960        .collect::<Result<Vec<_>, DaemonConfigError>>()?;
961
962    validate_reserved_prefixes(&modules, path)?;
963    validate_reserved_capabilities(&raw.reserved_capabilities, path)?;
964    validate_admission_facts_config(
965        &modules,
966        raw.admission_facts_carrier_module_id.as_deref(),
967        raw.admission_facts_targets.as_deref(),
968        path,
969    )?;
970    let scope_authority_owners = raw
971        .scope_authority_owners
972        .unwrap_or_else(default_scope_authority_owners);
973    subc_protocol::manifest::validate_module_id(&raw.federated_scope_owner).map_err(|error| {
974        DaemonConfigError::InvalidValue {
975            path: path.to_path_buf(),
976            message: format!("federated_scope_owner: {error}"),
977        }
978    })?;
979    if scope_authority_owners.iter().any(|owner| owner.is_empty()) {
980        return Err(DaemonConfigError::InvalidValue {
981            path: path.to_path_buf(),
982            message: "scope_authority_owners must not contain empty module ids".to_string(),
983        });
984    }
985
986    let storage = raw
987        .storage
988        .map(|s| match s {
989            RawStorageConfig::Sqlite { data_home } => {
990                let data_home = data_home.unwrap_or_else(default_data_home);
991                // A relative data home is served to every module in its storage
992                // descriptor and resolves against each module's own cwd, so one
993                // daemon would hand out N different directories while every
994                // module's gate stays green. The resolver returns a relative
995                // path when no home variable is set (golden-pinned) or when an
996                // operator set XDG_DATA_HOME to one; both are refused here rather
997                // than in the resolver, because the resolver's contract is shared
998                // with modules that may legitimately tolerate it.
999                if !data_home.is_absolute() {
1000                    return Err(DaemonConfigError::InvalidValue {
1001                        path: path.to_path_buf(),
1002                        message: format!(
1003                            "storage data home resolved to the relative path {} \
1004                             (no absolute XDG_DATA_HOME, APPDATA, USERPROFILE, or HOME \
1005                             in the daemon's environment); refusing to serve a \
1006                             cwd-relative storage descriptor to modules. Set \
1007                             XDG_DATA_HOME or HOME to an absolute path, or set \
1008                             storage.data_home in this file.",
1009                            data_home.display()
1010                        ),
1011                    });
1012                }
1013                Ok(StorageConfig::Sqlite { data_home })
1014            }
1015        })
1016        .transpose()?;
1017
1018    if raw.activity.max_age_days == 0 || raw.activity.max_total_mb == 0 {
1019        return Err(DaemonConfigError::InvalidValue {
1020            path: path.to_path_buf(),
1021            message: "activity.max_age_days and activity.max_total_mb must be positive".into(),
1022        });
1023    }
1024    Ok((
1025        DaemonConfig {
1026            path: path.to_path_buf(),
1027            port: raw.port,
1028            privileged_operator_prompt: raw.privileged_operator_prompt,
1029            drain_timeout_ms: default_drain_timeout_ms,
1030            route_bind_relay_timeout_ms: default_route_bind_relay_timeout_ms,
1031            modules,
1032            storage,
1033            admission_facts_carrier_module_id: raw.admission_facts_carrier_module_id,
1034            admission_facts_targets: raw.admission_facts_targets,
1035            scope_authority_owners,
1036            federated_scope_owner: raw.federated_scope_owner,
1037            reserved_capabilities: raw.reserved_capabilities,
1038        },
1039        raw.activity,
1040    ))
1041}
1042
1043fn parse_logging_config(
1044    raw: RawLoggingConfig,
1045    path: &Path,
1046    owner: &str,
1047) -> Result<LoggingConfig, DaemonConfigError> {
1048    fn valid_level(level: &str) -> bool {
1049        matches!(level, "off" | "error" | "warn" | "info" | "debug" | "trace")
1050    }
1051
1052    let level = raw.level.unwrap_or_else(|| "info".to_string());
1053    if !valid_level(&level) {
1054        return Err(DaemonConfigError::InvalidValue {
1055            path: path.to_path_buf(),
1056            message: format!(
1057                "{owner}.level must be one of off, error, warn, info, debug, trace; got {level:?}"
1058            ),
1059        });
1060    }
1061    for (tag, tag_level) in &raw.tags {
1062        // A logger name is dotted segments of [a-z][a-z0-9-]*: the same
1063        // grammar cortexkit-log renders and filters on. Anything else would
1064        // pass through CK_LOG and be refused there, one process away from the
1065        // config that caused it.
1066        let well_formed = !tag.is_empty()
1067            && tag.split('.').all(|segment| {
1068                let mut chars = segment.chars();
1069                matches!(chars.next(), Some('a'..='z'))
1070                    && chars.all(|c| matches!(c, 'a'..='z' | '0'..='9' | '-'))
1071            });
1072        if !well_formed {
1073            return Err(DaemonConfigError::InvalidValue {
1074                path: path.to_path_buf(),
1075                message: format!(
1076                    "{owner}.tags key {tag:?} is not a logger name (dotted segments of [a-z][a-z0-9-]*)"
1077                ),
1078            });
1079        }
1080        if !valid_level(tag_level) {
1081            return Err(DaemonConfigError::InvalidValue {
1082                path: path.to_path_buf(),
1083                message: format!(
1084                    "{owner}.tags.{tag} must be one of off, error, warn, info, debug, trace; got {tag_level:?}"
1085                ),
1086            });
1087        }
1088    }
1089
1090    let defaults = Retention::default();
1091    let retention = Retention {
1092        max_file_mb: raw.max_file_mb.unwrap_or(defaults.max_file_mb),
1093        keep: raw.keep.unwrap_or(defaults.keep),
1094        max_age_days: raw.max_age_days.unwrap_or(defaults.max_age_days),
1095    };
1096    if retention.max_file_mb == 0 {
1097        return Err(DaemonConfigError::InvalidValue {
1098            path: path.to_path_buf(),
1099            message: format!("{owner}.max_file_mb must be greater than 0"),
1100        });
1101    }
1102
1103    let alarm_segment_mb = raw
1104        .alarm_segment_mb
1105        .unwrap_or(cortexkit_log::SegmentRetention::default().alarm_segment_mb);
1106    if alarm_segment_mb == 0 {
1107        return Err(DaemonConfigError::InvalidValue {
1108            path: path.to_path_buf(),
1109            message: format!("{owner}.alarm_segment_mb must be greater than 0"),
1110        });
1111    }
1112
1113    Ok(LoggingConfig {
1114        level,
1115        tags: raw.tags,
1116        retention,
1117        alarm_segment_mb,
1118    })
1119}
1120
1121/// Resolve a module's declared `protocol` key.
1122///
1123/// Absent and `"subc"` are the SAME answer on purpose: a config written before
1124/// this key existed meant "a subc module", so there is no third state for
1125/// "unspecified" to drift into. Anything else is refused with the value quoted,
1126/// because the alternative -- falling back to `subc` for a typo like `"non"` --
1127/// silently restores the exact supervision behaviour the operator was trying to
1128/// turn off.
1129fn parse_module_protocol(
1130    raw: Option<&str>,
1131    path: &Path,
1132    module_id: &str,
1133) -> Result<ModuleProtocol, DaemonConfigError> {
1134    match raw {
1135        None | Some("subc") => Ok(ModuleProtocol::Subc),
1136        Some("none") => Ok(ModuleProtocol::None),
1137        // `{other:?}` quotes and escapes the operator's own bytes, so a value
1138        // carrying control characters cannot rewrite the terminal of whoever
1139        // reads the refusal.
1140        Some(other) => Err(DaemonConfigError::InvalidValue {
1141            path: path.to_path_buf(),
1142            message: format!(
1143                "module '{module_id}' declares protocol {other:?}; supported values are \
1144                 \"subc\" (the default when the key is absent) and \"none\"",
1145                module_id = module_id.escape_debug(),
1146            ),
1147        }),
1148    }
1149}
1150
1151/// Resolve a module's declared `overlap` key. Absent means `"exclusive"`,
1152/// and an unknown value is refused rather than read as either: a typo that
1153/// became `"safe"` would let a swap run two processes on a single-writer store.
1154fn parse_module_overlap(
1155    raw: Option<&str>,
1156    path: &Path,
1157    module_id: &str,
1158) -> Result<ModuleOverlap, DaemonConfigError> {
1159    match raw {
1160        None | Some("exclusive") => Ok(ModuleOverlap::Exclusive),
1161        Some("safe") => Ok(ModuleOverlap::Safe),
1162        Some(other) => Err(DaemonConfigError::InvalidValue {
1163            path: path.to_path_buf(),
1164            message: format!(
1165                "module '{module_id}' declares overlap {other:?}; supported values are \
1166                 \"exclusive\" (the default when the key is absent) and \"safe\"",
1167                module_id = module_id.escape_debug(),
1168            ),
1169        }),
1170    }
1171}
1172
1173fn validate_reserved_capabilities(
1174    bindings: &BTreeMap<String, String>,
1175    path: &Path,
1176) -> Result<(), DaemonConfigError> {
1177    for (capability, module_id) in bindings {
1178        if !is_valid_capability_identifier(capability) {
1179            return Err(DaemonConfigError::InvalidValue {
1180                path: path.to_path_buf(),
1181                message: format!(
1182                    "reserved_capabilities key {:?} is not a valid capability identifier",
1183                    capability
1184                ),
1185            });
1186        }
1187        if module_id.trim().is_empty() {
1188            return Err(DaemonConfigError::InvalidValue {
1189                path: path.to_path_buf(),
1190                message: format!(
1191                    "reserved_capabilities binding for {:?} has an empty module id",
1192                    capability
1193                ),
1194            });
1195        }
1196        if let Err(reason) = crate::registry::module_id_path_hazard(module_id) {
1197            return Err(DaemonConfigError::InvalidValue {
1198                path: path.to_path_buf(),
1199                message: format!(
1200                    "reserved_capabilities binding for {:?} has an unusable module id {:?}: {reason}",
1201                    capability, module_id
1202                ),
1203            });
1204        }
1205    }
1206    Ok(())
1207}
1208
1209fn validate_admission_facts_config(
1210    modules: &[ConfiguredModule],
1211    carrier_module_id: Option<&str>,
1212    targets: Option<&[String]>,
1213    path: &Path,
1214) -> Result<(), DaemonConfigError> {
1215    let Some(carrier_module_id) = carrier_module_id else {
1216        return Ok(());
1217    };
1218
1219    let Some(carrier) = modules
1220        .iter()
1221        .find(|module| module.module_id == carrier_module_id)
1222    else {
1223        return Err(DaemonConfigError::InvalidValue {
1224            path: path.to_path_buf(),
1225            message: format!(
1226                "admission_facts_carrier_module_id '{carrier_module_id}' must name a configured module"
1227            ),
1228        });
1229    };
1230    if !carrier.enabled || !carrier.reserved {
1231        return Err(DaemonConfigError::InvalidValue {
1232            path: path.to_path_buf(),
1233            message: format!(
1234                "admission_facts_carrier_module_id '{carrier_module_id}' must name an enabled reserved module"
1235            ),
1236        });
1237    }
1238
1239    let Some(targets) = targets else {
1240        return Err(DaemonConfigError::InvalidValue {
1241            path: path.to_path_buf(),
1242            message: "admission_facts_targets must be present when an admission facts carrier is configured".to_string(),
1243        });
1244    };
1245    if targets.is_empty() || targets.iter().any(String::is_empty) {
1246        return Err(DaemonConfigError::InvalidValue {
1247            path: path.to_path_buf(),
1248            message:
1249                "admission_facts_targets must be non-empty and must not contain empty module ids"
1250                    .to_string(),
1251        });
1252    }
1253
1254    Ok(())
1255}
1256
1257fn default_enabled() -> bool {
1258    true
1259}
1260
1261fn validate_reserved_prefixes(
1262    modules: &[ConfiguredModule],
1263    path: &Path,
1264) -> Result<(), DaemonConfigError> {
1265    for module in modules {
1266        if module.reserved_prefixes.is_empty() {
1267            continue;
1268        }
1269        if !module.reserved {
1270            return Err(DaemonConfigError::InvalidValue {
1271                path: path.to_path_buf(),
1272                message: format!(
1273                    "module '{}' reserved_prefixes require reserved=true so the owner is spawn-nonce protected",
1274                    module.module_id
1275                ),
1276            });
1277        }
1278        for prefix in &module.reserved_prefixes {
1279            if !prefix.ends_with(':') {
1280                return Err(DaemonConfigError::InvalidValue {
1281                    path: path.to_path_buf(),
1282                    message: format!(
1283                        "module '{}' reserved prefix '{}' must end with ':'",
1284                        module.module_id, prefix
1285                    ),
1286                });
1287            }
1288        }
1289    }
1290
1291    for module in modules {
1292        for prefix in &module.reserved_prefixes {
1293            if let Some(colliding) = modules
1294                .iter()
1295                .find(|candidate| candidate.module_id.starts_with(prefix))
1296            {
1297                return Err(DaemonConfigError::InvalidValue {
1298                    path: path.to_path_buf(),
1299                    message: format!(
1300                        "reserved prefix '{}' owned by '{}' collides with configured module id '{}'",
1301                        prefix, module.module_id, colliding.module_id
1302                    ),
1303                });
1304            }
1305        }
1306    }
1307
1308    for (left_index, left) in modules.iter().enumerate() {
1309        for right in modules.iter().skip(left_index + 1) {
1310            if left.module_id == right.module_id {
1311                continue;
1312            }
1313            for left_prefix in &left.reserved_prefixes {
1314                for right_prefix in &right.reserved_prefixes {
1315                    if left_prefix.starts_with(right_prefix)
1316                        || right_prefix.starts_with(left_prefix)
1317                    {
1318                        return Err(DaemonConfigError::InvalidValue {
1319                            path: path.to_path_buf(),
1320                            message: format!(
1321                                "reserved prefixes '{}' owned by '{}' and '{}' owned by '{}' overlap",
1322                                left_prefix, left.module_id, right_prefix, right.module_id
1323                            ),
1324                        });
1325                    }
1326                }
1327            }
1328        }
1329    }
1330
1331    Ok(())
1332}
1333
1334fn parse_health_config(
1335    raw: RawHealthConfig,
1336    path: &Path,
1337    module_id: &str,
1338    protocol: ModuleProtocol,
1339) -> Result<HealthConfig, DaemonConfigError> {
1340    if let Some(url) = raw.http.as_deref() {
1341        let reason = if protocol != ModuleProtocol::None {
1342            Some("is valid only for protocol: \"none\" modules".to_string())
1343        } else {
1344            crate::supervise::parse_http_probe_url(url).err()
1345        };
1346        if let Some(reason) = reason {
1347            return Err(DaemonConfigError::InvalidValue {
1348                path: path.to_path_buf(),
1349                message: format!("module '{module_id}' health.http {reason}"),
1350            });
1351        }
1352    }
1353    let defaults = HealthConfig::default();
1354    let cadence = positive_millis(
1355        raw.cadence_ms,
1356        defaults.cadence,
1357        path,
1358        module_id,
1359        "cadence_ms",
1360    )?;
1361    let deadline = positive_millis(
1362        raw.deadline_ms,
1363        defaults.deadline,
1364        path,
1365        module_id,
1366        "deadline_ms",
1367    )?;
1368    let failure_threshold = match raw.failure_threshold {
1369        Some(0) => {
1370            return Err(DaemonConfigError::InvalidValue {
1371                path: path.to_path_buf(),
1372                message: format!("module '{module_id}' health.failure_threshold must be positive"),
1373            })
1374        }
1375        Some(value) => value,
1376        None => defaults.failure_threshold,
1377    };
1378
1379    Ok(HealthConfig {
1380        http: raw.http,
1381        cadence,
1382        deadline,
1383        failure_threshold,
1384        on_degraded: match raw.on_degraded {
1385            Some(RawHealthAction::Restart) => {
1386                return Err(DaemonConfigError::InvalidValue {
1387                    path: path.to_path_buf(),
1388                    message: format!(
1389                        "module '{module_id}' health.on_degraded may not be 'restart': a degraded module is slow-but-moving, so restarting it converts transient load into an outage. Use 'report' or 'alert' (Health-Path v2: only total wreckage or reported-unresponsiveness restarts)."
1390                    ),
1391                });
1392            }
1393            Some(action) => health_action(action),
1394            None => defaults.on_degraded,
1395        },
1396        on_failing: raw
1397            .on_failing
1398            .map(health_action)
1399            .unwrap_or(defaults.on_failing),
1400        critical: raw.critical,
1401    })
1402}
1403
1404/// Resolve one module's `restart` block against the supervisor defaults.
1405///
1406/// Every key is optional and independent: a config that sets only
1407/// `window_secs` keeps the default cap and backoff, and a config with no
1408/// `restart` block at all gets exactly the policy the daemon used before the
1409/// block existed.
1410fn parse_restart_config(
1411    raw: Option<RawRestartConfig>,
1412    path: &Path,
1413    module_id: &str,
1414) -> Result<RestartPolicy, DaemonConfigError> {
1415    let defaults = RestartPolicy::default();
1416    let Some(raw) = raw else {
1417        return Ok(defaults);
1418    };
1419
1420    let window = match raw.window_secs {
1421        Some(0) => {
1422            return Err(DaemonConfigError::InvalidValue {
1423                path: path.to_path_buf(),
1424                message: format!(
1425                    "module '{module_id}' {RESTART_WINDOW_ZERO_MESSAGE}",
1426                    module_id = module_id.escape_debug()
1427                ),
1428            });
1429        }
1430        Some(secs) => Duration::from_secs(secs),
1431        None => defaults.window,
1432    };
1433    let backoff = raw
1434        .backoff_ms
1435        .map(Duration::from_millis)
1436        .unwrap_or(defaults.backoff);
1437    let max_backoff = raw
1438        .max_backoff_ms
1439        .map(Duration::from_millis)
1440        .unwrap_or(defaults.max_backoff);
1441    if max_backoff < backoff {
1442        return Err(DaemonConfigError::InvalidValue {
1443            path: path.to_path_buf(),
1444            message: format!(
1445                "module '{}' restart.max_backoff_ms must be greater than or equal to restart.backoff_ms (max_backoff_ms={max_backoff:?}, backoff_ms={backoff:?})",
1446                module_id.escape_debug()
1447            ),
1448        });
1449    }
1450
1451    Ok(RestartPolicy {
1452        // `0` is a deliberate posture here ("never replace this module"), unlike
1453        // the window, so it is accepted as written.
1454        max_restarts: raw.max_restarts.unwrap_or(defaults.max_restarts),
1455        backoff,
1456        max_backoff,
1457        window,
1458    })
1459}
1460
1461fn positive_millis(
1462    value: Option<u64>,
1463    default: std::time::Duration,
1464    path: &Path,
1465    module_id: &str,
1466    field: &str,
1467) -> Result<std::time::Duration, DaemonConfigError> {
1468    match value {
1469        Some(0) => Err(DaemonConfigError::InvalidValue {
1470            path: path.to_path_buf(),
1471            message: format!("module '{module_id}' health.{field} must be positive"),
1472        }),
1473        Some(value) => Ok(std::time::Duration::from_millis(value)),
1474        None => Ok(default),
1475    }
1476}
1477
1478fn health_action(action: RawHealthAction) -> HealthAction {
1479    match action {
1480        RawHealthAction::Report => HealthAction::Report,
1481        RawHealthAction::Restart => HealthAction::Restart,
1482        RawHealthAction::Alert => HealthAction::Alert,
1483    }
1484}
1485
1486/// Platform data home for per-module storage: `$XDG_DATA_HOME`, else
1487/// `~/.local/share` (or the Windows roaming app data), else a relative fallback.
1488pub(crate) fn default_data_home() -> PathBuf {
1489    if let Some(data_home) = non_empty_os_var("XDG_DATA_HOME") {
1490        return PathBuf::from(data_home);
1491    }
1492
1493    #[cfg(windows)]
1494    {
1495        if let Some(app_data) = non_empty_os_var("APPDATA") {
1496            return PathBuf::from(app_data);
1497        }
1498        if let Some(user_profile) = non_empty_os_var("USERPROFILE") {
1499            return PathBuf::from(user_profile).join("AppData").join("Roaming");
1500        }
1501    }
1502
1503    if let Some(home) = non_empty_os_var("HOME") {
1504        return PathBuf::from(home).join(".local").join("share");
1505    }
1506
1507    PathBuf::from(".local").join("share")
1508}
1509
1510fn non_empty_os_var(key: &str) -> Option<OsString> {
1511    let value = env::var_os(key)?;
1512    if value.is_empty() {
1513        None
1514    } else {
1515        Some(value)
1516    }
1517}
1518
1519impl fmt::Display for DaemonConfigError {
1520    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1521        match self {
1522            Self::Read { path, source } => {
1523                write!(f, "failed to read daemon config {}: {source}", path.display())
1524            }
1525            Self::InvalidJsonc { path, message } => {
1526                write!(f, "invalid JSONC in daemon config {}: {message}", path.display())
1527            }
1528            Self::InvalidJson { path, source } => {
1529                write!(f, "invalid daemon config {}: {source}", path.display())
1530            }
1531            Self::UnsupportedVersion { path, version } => write!(
1532                f,
1533                "invalid daemon config {}: version {version} is unsupported (expected {SUPPORTED_CONFIG_VERSION})",
1534                path.display()
1535            ),
1536            Self::InvalidValue { path, message } => {
1537                write!(f, "invalid daemon config {}: {message}", path.display())
1538            }
1539        }
1540    }
1541}
1542
1543impl Error for DaemonConfigError {
1544    fn source(&self) -> Option<&(dyn Error + 'static)> {
1545        match self {
1546            Self::Read { source, .. } => Some(source),
1547            Self::InvalidJson { source, .. } => Some(source),
1548            Self::InvalidJsonc { .. }
1549            | Self::UnsupportedVersion { .. }
1550            | Self::InvalidValue { .. } => None,
1551        }
1552    }
1553}
1554
1555#[cfg(all(test, windows))]
1556mod windows_run_dir_privacy_tests {
1557    use super::ensure_directory_private;
1558    use cortexkit_test_support::ScratchDir;
1559    use subc_os::windows_acl::test_support::{
1560        assert_dacl_owner_only, assert_owner_only, grant_everyone,
1561    };
1562
1563    #[test]
1564    fn windows_run_dir_has_exact_protected_dacl_at_creation() {
1565        let root = ScratchDir::new("windows-run-dir-create");
1566        grant_everyone(root.path());
1567        let path = root.join("run");
1568        ensure_directory_private(&path).unwrap();
1569        assert_owner_only(&path, true, true);
1570    }
1571
1572    #[test]
1573    fn windows_run_dir_narrows_existing_inherited_descendants() {
1574        let root = ScratchDir::new("windows-run-dir-existing");
1575        grant_everyone(root.path());
1576        let path = root.join("run");
1577        std::fs::create_dir(&path).unwrap();
1578        let child = path.join("old.log");
1579        std::fs::write(&child, b"old log").unwrap();
1580        ensure_directory_private(&path).unwrap();
1581        // The folder and the file both existed before narrowing, so only their
1582        // access lists change; an elevated test runner owns them as Administrators.
1583        assert_dacl_owner_only(&path, true, true);
1584        assert_dacl_owner_only(&child, false, false);
1585    }
1586}
1587
1588#[cfg(all(test, unix))]
1589mod run_dir_privacy_tests {
1590    use cortexkit_test_support::ScratchDir;
1591    use std::fs;
1592    use std::os::unix::fs::PermissionsExt;
1593
1594    /// Both arms of the thing that actually bit: a directory this code CREATES,
1595    /// and one it INHERITS from another creator. The second is the real case --
1596    /// every desk in the fleet already had a 0755 run directory made by the log
1597    /// sink, so a fix that only sets the mode at creation would have changed
1598    /// nothing anywhere it mattered.
1599    #[test]
1600    fn run_dir_is_created_private_and_an_inherited_wide_one_is_tightened() {
1601        let temp = ScratchDir::new("subc-run-dir-privacy");
1602        let created = temp.path().join("cortexkit").join("run");
1603        super::ensure_directory_private(&created).expect("create run dir");
1604        let mode = fs::metadata(&created)
1605            .expect("stat created")
1606            .permissions()
1607            .mode()
1608            & 0o777;
1609        assert_eq!(
1610            mode, 0o700,
1611            "observable a run directory this code creates must be 0700, got {mode:o}"
1612        );
1613
1614        // Now the inherited case: widen it the way create_dir_all would have.
1615        fs::set_permissions(&created, fs::Permissions::from_mode(0o755)).expect("widen");
1616        let widened = fs::metadata(&created)
1617            .expect("stat widened")
1618            .permissions()
1619            .mode()
1620            & 0o777;
1621        assert_eq!(
1622            widened, 0o755,
1623            "observable the fixture must actually be wide before the tighten"
1624        );
1625
1626        super::ensure_directory_private(&created).expect("tighten run dir");
1627        let mode = fs::metadata(&created)
1628            .expect("stat tightened")
1629            .permissions()
1630            .mode()
1631            & 0o777;
1632        assert_eq!(
1633            mode, 0o700,
1634            "observable an inherited group- or world-readable run directory must be tightened to 0700, got {mode:o}"
1635        );
1636    }
1637}
1638
1639#[cfg(test)]
1640mod tests {
1641    use super::*;
1642
1643    /// The golden fixture is the CONTRACT for data-home resolution: mirror
1644    /// implementations (cortexkit-store-types `resolve_data_home`,
1645    /// @cortexkit/store `resolveDataHome`) assert against the same rows, so a
1646    /// rule change here that skips the fixture breaks THIS test rather than
1647    /// silently splitting a module's self-resolved path from the descriptor
1648    /// the daemon serves (the CKCRED Windows divergence, 2026-08).
1649    /// Env-mutating tests share this lock: cargo runs tests on multiple
1650    /// threads and the four data-home variables are process-global.
1651    static ENV_LOCK: std::sync::Mutex<()> = std::sync::Mutex::new(());
1652
1653    /// A path that is absolute on the platform running the test. `/data` is
1654    /// relative on Windows (no drive letter), which is not a bug in the resolver
1655    /// but a bug in a test that assumes POSIX absoluteness -- the relative-home
1656    /// refusal exposed three such tests on the Windows leg.
1657    fn abs(posix: &str) -> PathBuf {
1658        if cfg!(windows) {
1659            PathBuf::from(format!("C:{}", posix.replace('/', "\\")))
1660        } else {
1661            PathBuf::from(posix)
1662        }
1663    }
1664
1665    #[test]
1666    fn default_data_home_matches_golden_fixture() {
1667        let _g = ENV_LOCK.lock().unwrap_or_else(|p| p.into_inner());
1668        let doc: serde_json::Value =
1669            serde_json::from_str(include_str!("../tests/golden/data_home_resolution.json"))
1670                .expect("golden parses");
1671        let vars = ["XDG_DATA_HOME", "APPDATA", "USERPROFILE", "HOME"];
1672        let saved: Vec<(&str, Option<std::ffi::OsString>)> =
1673            vars.iter().map(|v| (*v, env::var_os(v))).collect();
1674        let platform_matches =
1675            |p: &str| p == "any" || p == if cfg!(windows) { "windows" } else { "unix" };
1676
1677        let mut ran = 0usize;
1678        for case in doc["cases"].as_array().expect("cases array") {
1679            let name = case["name"].as_str().expect("name");
1680            if !platform_matches(case["platform"].as_str().expect("platform")) {
1681                continue;
1682            }
1683            for v in vars {
1684                env::remove_var(v);
1685            }
1686            for (k, v) in case["env"].as_object().expect("env map") {
1687                env::set_var(k, v.as_str().expect("env value"));
1688            }
1689            let got = default_data_home();
1690            assert_eq!(
1691                got.to_string_lossy(),
1692                case["expect"].as_str().expect("expect"),
1693                "golden case '{name}' diverged"
1694            );
1695            ran += 1;
1696        }
1697        // Vacuity floor: 'any' rows plus this platform's rows must both run.
1698        assert!(
1699            ran >= 6,
1700            "only {ran} golden cases ran; fixture or filter broken"
1701        );
1702
1703        for (k, v) in saved {
1704            match v {
1705                Some(val) => env::set_var(k, val),
1706                None => env::remove_var(k),
1707            }
1708        }
1709    }
1710
1711    /// A relative data home is what `default_data_home` returns when HOME and
1712    /// XDG_DATA_HOME are both unset (the golden fixture pins `.local/share`), or
1713    /// when XDG_DATA_HOME itself is relative. Either must be refused, never
1714    /// joined onto the working directory.
1715    #[test]
1716    fn daemon_run_dir_refuses_a_relative_data_home_and_names_the_variables() {
1717        for data_home in [PathBuf::from(".local/share"), PathBuf::from("relative-xdg")] {
1718            let error = daemon_run_dir_from(data_home.clone())
1719                .expect_err("a relative data home must be refused");
1720            assert_eq!(
1721                error,
1722                DaemonRunDirError::RelativeDataHome {
1723                    data_home: data_home.clone()
1724                }
1725            );
1726            let message = error.to_string();
1727            assert!(
1728                message.contains("XDG_DATA_HOME") && message.contains("HOME"),
1729                "the refusal must name the variables to set: {message}"
1730            );
1731        }
1732    }
1733
1734    #[test]
1735    fn daemon_run_dir_under_an_absolute_data_home_is_cortexkit_run() {
1736        let data_home = env::temp_dir().join("subc-run-dir-probe").join("data");
1737        assert!(data_home.is_absolute());
1738        assert_eq!(
1739            daemon_run_dir_from(data_home.clone()),
1740            Ok(data_home.join("cortexkit").join("run"))
1741        );
1742    }
1743
1744    /// Same harness as the data-home golden, over the config-home ladder. The two
1745    /// fixtures share a row shape on purpose: a divergence between the ladders
1746    /// (one honouring a variable the other does not) is exactly the class that
1747    /// produced the doubled-path store defect, and a shared harness makes it
1748    /// visible as a fixture diff rather than as a runtime surprise.
1749    #[test]
1750    fn default_config_home_matches_golden_fixture() {
1751        let _g = ENV_LOCK.lock().unwrap_or_else(|p| p.into_inner());
1752        let doc: serde_json::Value =
1753            serde_json::from_str(include_str!("../tests/golden/config_home_resolution.json"))
1754                .expect("golden parses");
1755        let vars = ["XDG_CONFIG_HOME", "APPDATA", "USERPROFILE", "HOME"];
1756        let saved: Vec<(&str, Option<std::ffi::OsString>)> =
1757            vars.iter().map(|v| (*v, env::var_os(v))).collect();
1758        let platform_matches =
1759            |p: &str| p == "any" || p == if cfg!(windows) { "windows" } else { "unix" };
1760
1761        let mut ran = 0usize;
1762        for case in doc["cases"].as_array().expect("cases array") {
1763            let name = case["name"].as_str().expect("name");
1764            if !platform_matches(case["platform"].as_str().expect("platform")) {
1765                continue;
1766            }
1767            for v in vars {
1768                env::remove_var(v);
1769            }
1770            for (k, v) in case["env"].as_object().expect("env map") {
1771                env::set_var(k, v.as_str().expect("env value"));
1772            }
1773            let got = default_config_home();
1774            assert_eq!(
1775                got.to_string_lossy(),
1776                case["expect"].as_str().expect("expect"),
1777                "golden case '{name}' diverged"
1778            );
1779            ran += 1;
1780        }
1781        assert!(
1782            ran >= 6,
1783            "only {ran} golden cases ran; fixture or filter broken"
1784        );
1785
1786        for (k, v) in saved {
1787            match v {
1788                Some(val) => env::set_var(k, val),
1789                None => env::remove_var(k),
1790            }
1791        }
1792    }
1793
1794    /// A relative storage data home is refused at parse rather than served.
1795    /// Both ways a relative path arises are covered: an explicit relative
1796    /// `storage.data_home` in the file, and the resolver's own fall-through when
1797    /// no home variable is set. The control proves the guard is on the VALUE and
1798    /// not on the presence of the key: the same document with an absolute home
1799    /// parses.
1800    #[test]
1801    fn relative_storage_data_home_is_refused_at_parse() {
1802        let _g = ENV_LOCK.lock().unwrap_or_else(|p| p.into_inner());
1803        let path = Path::new("/golden/subc.jsonc");
1804
1805        // Arm 1: explicit relative value in the file.
1806        let doc =
1807            r#"{ "version": 1, "storage": { "backend": "sqlite", "data_home": "relative/home" } }"#;
1808        let err = parse_doc(doc, path).expect_err("relative data_home must refuse");
1809        assert!(
1810            matches!(&err, DaemonConfigError::InvalidValue { message, .. }
1811                if message.contains("relative path relative/home")),
1812            "wrong refusal: {err:?}"
1813        );
1814
1815        // Arm 2: the resolver's fall-through, with every home variable cleared.
1816        let vars = ["XDG_DATA_HOME", "APPDATA", "USERPROFILE", "HOME"];
1817        let saved: Vec<(&str, Option<std::ffi::OsString>)> =
1818            vars.iter().map(|v| (*v, env::var_os(v))).collect();
1819        for v in vars {
1820            env::remove_var(v);
1821        }
1822        let doc = r#"{ "version": 1, "storage": { "backend": "sqlite" } }"#;
1823        let err = parse_doc(doc, path).expect_err("no home in env must refuse");
1824        assert!(
1825            matches!(&err, DaemonConfigError::InvalidValue { message, .. }
1826                if message.contains("no absolute XDG_DATA_HOME")),
1827            "wrong refusal: {err:?}"
1828        );
1829
1830        // Control: an absolute value parses -- the guard is on the value. The
1831        // path must be absolute ON THIS PLATFORM; `/abs/home` is relative on
1832        // Windows and would make the control refuse for the wrong reason.
1833        let want = abs("/abs/home");
1834        let doc = format!(
1835            r#"{{ "version": 1, "storage": {{ "backend": "sqlite", "data_home": {} }} }}"#,
1836            serde_json::to_string(&want).expect("json path")
1837        );
1838        let cfg = parse_doc(&doc, path).expect("absolute data_home parses");
1839        assert!(matches!(
1840            cfg.storage,
1841            Some(StorageConfig::Sqlite { ref data_home }) if *data_home == want
1842        ));
1843
1844        for (k, v) in saved {
1845            match v {
1846                Some(val) => env::set_var(k, val),
1847                None => env::remove_var(k),
1848            }
1849        }
1850    }
1851
1852    #[test]
1853    fn restart_required_sections_are_the_rescan_cannot_apply_set() {
1854        assert_eq!(
1855            RestartRequiredSection::ALL.map(RestartRequiredSection::label),
1856            [
1857                "port",
1858                "storage",
1859                "admission_facts_carrier_module_id",
1860                "admission_facts_targets",
1861                "scope_authority_owners",
1862                "federated_scope_owner",
1863                "privileged_operator_prompt",
1864            ]
1865        );
1866    }
1867
1868    #[test]
1869    fn privileged_operator_prompt_defaults_to_log_and_accepts_both_modes() {
1870        let path = Path::new("/tmp/subc.jsonc");
1871        let config = parse_doc(r#"{"version":1}"#, path).unwrap();
1872        assert_eq!(
1873            config.privileged_operator_prompt,
1874            PrivilegedOperatorPrompt::Log
1875        );
1876        for (value, expected) in [
1877            ("log", PrivilegedOperatorPrompt::Log),
1878            ("enforce", PrivilegedOperatorPrompt::Enforce),
1879        ] {
1880            let config = parse_doc(
1881                &format!(r#"{{"version":1,"privileged_operator_prompt":"{value}"}}"#),
1882                path,
1883            )
1884            .unwrap();
1885            assert_eq!(config.privileged_operator_prompt, expected);
1886        }
1887    }
1888
1889    #[test]
1890    fn privileged_operator_prompt_refuses_unknown_values_and_wrong_types() {
1891        let path = Path::new("/tmp/subc.jsonc");
1892        for value in [r#""unknown""#, r#""Enforce""#, "null", "true", "1", "{}"] {
1893            let error = parse_doc(
1894                &format!(r#"{{"version":1,"privileged_operator_prompt":{value}}}"#),
1895                path,
1896            )
1897            .unwrap_err();
1898            assert!(matches!(error, DaemonConfigError::InvalidJson { .. }));
1899        }
1900    }
1901
1902    #[test]
1903    fn scope_authority_owners_defaults_to_the_session_runtime() {
1904        let config = parse_doc(r#"{ "version": 1 }"#, Path::new("/tmp/subc.jsonc")).unwrap();
1905        assert_eq!(config.scope_authority_owners, vec!["prefrontal-core"]);
1906    }
1907
1908    #[test]
1909    fn federated_scope_owner_defaults_and_is_validated_and_restart_required() {
1910        let config = parse_doc(r#"{ "version": 1 }"#, Path::new("/fixture/subc.jsonc")).unwrap();
1911        assert_eq!(config.federated_scope_owner, "callosum");
1912        assert!(!config
1913            .scope_authority_owners
1914            .contains(&config.federated_scope_owner));
1915        let configured = parse_doc(
1916            r#"{ "version": 1, "federated_scope_owner": "peer-carrier" }"#,
1917            Path::new("/fixture/subc.jsonc"),
1918        )
1919        .unwrap();
1920        assert_eq!(configured.federated_scope_owner, "peer-carrier");
1921        assert!(RestartRequiredSection::ALL.contains(&RestartRequiredSection::FederatedScopeOwner));
1922        for invalid in ["", "..", "a/b", "a\\b"] {
1923            let body = serde_json::json!({"version": 1, "federated_scope_owner": invalid});
1924            assert!(
1925                parse_doc(&body.to_string(), Path::new("/fixture/subc.jsonc"))
1926                    .unwrap_err()
1927                    .to_string()
1928                    .contains("federated_scope_owner")
1929            );
1930        }
1931    }
1932
1933    #[test]
1934    fn scope_authority_owners_is_read_when_set_and_refuses_an_empty_id() {
1935        let config = parse_doc(
1936            r#"{ "version": 1, "scope_authority_owners": ["a", "b"] }"#,
1937            Path::new("/tmp/subc.jsonc"),
1938        )
1939        .unwrap();
1940        assert_eq!(config.scope_authority_owners, vec!["a", "b"]);
1941        // An explicit empty list is a real posture (no owner may set gated
1942        // attributes), distinct from an absent key.
1943        let config = parse_doc(
1944            r#"{ "version": 1, "scope_authority_owners": [] }"#,
1945            Path::new("/tmp/subc.jsonc"),
1946        )
1947        .unwrap();
1948        assert!(config.scope_authority_owners.is_empty());
1949        let error = parse_doc(
1950            r#"{ "version": 1, "scope_authority_owners": [""] }"#,
1951            Path::new("/tmp/subc.jsonc"),
1952        )
1953        .expect_err("an empty module id is refused");
1954        assert!(
1955            error.to_string().contains("scope_authority_owners"),
1956            "{error}"
1957        );
1958    }
1959
1960    #[test]
1961    fn no_storage_section_yields_none() {
1962        let config = parse_doc(
1963            r#"{ "version": 1, "modules": {} }"#,
1964            Path::new("/tmp/subc.jsonc"),
1965        )
1966        .expect("parse");
1967        assert_eq!(config.storage, None);
1968    }
1969
1970    #[test]
1971    fn sqlite_storage_parses_with_explicit_data_home() {
1972        let config = parse_doc(
1973            &format!(
1974                r#"{{ "version": 1, "storage": {{ "backend": "sqlite", "data_home": {} }} }}"#,
1975                serde_json::to_string(&abs("/data")).expect("json path")
1976            ),
1977            Path::new("/tmp/subc.jsonc"),
1978        )
1979        .expect("parse");
1980        assert_eq!(
1981            config.storage,
1982            Some(StorageConfig::Sqlite {
1983                data_home: abs("/data")
1984            })
1985        );
1986    }
1987
1988    #[test]
1989    fn sqlite_storage_defaults_data_home_when_omitted() {
1990        // With no data_home, it falls back to the platform data home (here forced
1991        // via XDG_DATA_HOME so the test is deterministic).
1992        // Mutating the environment is a process-wide side effect; every test
1993        // reading or writing the data-home variables serializes on ENV_LOCK
1994        // (the golden-fixture test above mutates all four variables).
1995        let _g = ENV_LOCK.lock().unwrap_or_else(|p| p.into_inner());
1996        std::env::set_var("XDG_DATA_HOME", abs("/forced/data/home"));
1997        let config = parse_doc(
1998            r#"{ "version": 1, "storage": { "backend": "sqlite" } }"#,
1999            Path::new("/tmp/subc.jsonc"),
2000        )
2001        .expect("parse");
2002        std::env::remove_var("XDG_DATA_HOME");
2003        assert_eq!(
2004            config.storage,
2005            Some(StorageConfig::Sqlite {
2006                data_home: abs("/forced/data/home")
2007            })
2008        );
2009    }
2010
2011    #[test]
2012    fn descriptor_for_matches_store_types_shape() {
2013        // The opaque descriptor subc delivers must match the
2014        // cortexkit_store_types::StorageDescriptor JSON shape exactly (path
2015        // convention <data_home>/cortexkit/<module>/store.db, one db per module).
2016        let cfg = StorageConfig::Sqlite {
2017            data_home: PathBuf::from("/data"),
2018        };
2019        let descriptor = cfg.descriptor_for("alfonso-routing");
2020        assert_eq!(
2021            descriptor,
2022            serde_json::json!({
2023                "module_id": "alfonso-routing",
2024                "storage_namespace": "default",
2025                "isolation": { "kind": "module" },
2026                "backend": {
2027                    "backend": "sqlite",
2028                    "path": "/data/cortexkit/alfonso-routing/store.db"
2029                }
2030            })
2031        );
2032    }
2033
2034    #[test]
2035    fn path_hazard_module_id_refuses_config_parse() {
2036        let path = Path::new("/tmp/subc.jsonc");
2037        let err = parse_doc(
2038            r#"{ "version": 1, "modules": { "../escape": { "program": "x" } } }"#,
2039            path,
2040        )
2041        .expect_err("separator-bearing module id must refuse");
2042        let text = format!("{err}");
2043        assert!(
2044            text.contains("not usable as a path component"),
2045            "refusal must name the hazard: {text}"
2046        );
2047    }
2048
2049    #[test]
2050    fn drain_timeout_resolves_module_over_daemon_over_absent() {
2051        let path = Path::new("/tmp/subc.jsonc");
2052        let config = parse_doc(
2053            r#"
2054            {
2055              "version": 1,
2056              "drain_timeout_ms": 45000,
2057              "modules": {
2058                "fast": { "program": "fast", "drain_timeout_ms": 0 },
2059                "slow": { "program": "slow", "drain_timeout_ms": 120000 },
2060                "inherits": { "program": "inherits" }
2061              }
2062            }
2063            "#,
2064            path,
2065        )
2066        .unwrap();
2067        let by_id = |id: &str| {
2068            config
2069                .modules
2070                .iter()
2071                .find(|m| m.module_id == id)
2072                .unwrap()
2073                .drain_timeout_ms
2074        };
2075        // Per-module wins, INCLUDING an explicit 0 ("never wait") -- the case a
2076        // truthiness-shaped resolution would silently replace with the default.
2077        assert_eq!(by_id("fast"), Some(0));
2078        assert_eq!(by_id("slow"), Some(120_000));
2079        // No per-module value: the daemon-wide default flows in at parse time.
2080        assert_eq!(by_id("inherits"), Some(45_000));
2081        assert_eq!(config.drain_timeout_ms, Some(45_000));
2082    }
2083
2084    #[test]
2085    fn drain_timeout_absent_everywhere_stays_none_for_builtin_default() {
2086        let path = Path::new("/tmp/subc.jsonc");
2087        let config = parse_doc(
2088            r#"{ "version": 1, "modules": { "m": { "program": "m" } } }"#,
2089            path,
2090        )
2091        .unwrap();
2092        // None here is load-bearing: it means "use the compiled default", so a
2093        // future default bump reaches every unconfigured module without a
2094        // config migration.
2095        assert_eq!(config.modules[0].drain_timeout_ms, None);
2096        assert_eq!(config.drain_timeout_ms, None);
2097    }
2098
2099    #[test]
2100    fn route_bind_relay_timeout_resolves_module_over_daemon_over_absent() {
2101        // Precedence still holds for valid non-zero values. `0` at either
2102        // layer is rejected by `route_bind_relay_timeout_zero_at_daemon_layer_is_refused`
2103        // and `route_bind_relay_timeout_zero_at_module_layer_is_refused` below
2104        // — the asymmetry is deliberate (drain `0` is still accepted; see
2105        // `drain_timeout_zero_still_parses_for_wedge_bounces`).
2106        let path = Path::new("/tmp/subc.jsonc");
2107        let config = parse_doc(
2108            r#"
2109            {
2110              "version": 1,
2111              "route_bind_relay_timeout_ms": 30000,
2112              "modules": {
2113                "tight": { "program": "tight", "route_bind_relay_timeout_ms": 5000 },
2114                "loose": { "program": "loose", "route_bind_relay_timeout_ms": 60000 },
2115                "inherits": { "program": "inherits" }
2116              }
2117            }
2118            "#,
2119            path,
2120        )
2121        .unwrap();
2122        let by_id = |id: &str| {
2123            config
2124                .modules
2125                .iter()
2126                .find(|m| m.module_id == id)
2127                .unwrap()
2128                .route_bind_relay_timeout_ms
2129        };
2130        // Per-module wins for every non-zero value.
2131        assert_eq!(by_id("tight"), Some(5_000));
2132        assert_eq!(by_id("loose"), Some(60_000));
2133        // No per-module value: the daemon-wide default flows in at parse time.
2134        assert_eq!(by_id("inherits"), Some(30_000));
2135        assert_eq!(config.route_bind_relay_timeout_ms, Some(30_000));
2136    }
2137
2138    #[test]
2139    fn log_tag_keys_must_be_logger_names_and_the_error_names_the_key() {
2140        let path = Path::new("/tmp/subc.jsonc");
2141        for bad in ["Perf", "a b", "perf.", ".perf", "gc..walk", "a=b"] {
2142            let doc = format!(
2143                r#"{{ "version": 1, "modules": {{ "m": {{ "program": "m", "log": {{ "tags": {{ "{bad}": "debug" }} }} }} }} }}"#
2144            );
2145            let err = parse_doc(&doc, path).expect_err(bad);
2146            let text = format!("{err}");
2147            assert!(
2148                text.contains(&format!("{bad:?}")),
2149                "must name the key: {text}"
2150            );
2151            assert!(
2152                text.contains("logger name"),
2153                "must say what a key is: {text}"
2154            );
2155        }
2156        // Control: dotted, hyphenated, root-equal keys are all fine.
2157        let ok = parse_doc(
2158            r#"{ "version": 1, "modules": { "m": { "program": "m", "log": { "tags": { "perf": "debug", "gc.walk": "trace", "m": "error", "a-b": "info" } } } } }"#,
2159            path,
2160        );
2161        assert!(ok.is_ok(), "{ok:?}");
2162    }
2163
2164    #[test]
2165    fn log_filter_spec_prefixes_bare_keys_with_the_module_and_passes_absolute_ones() {
2166        let path = Path::new("/tmp/subc.jsonc");
2167        let config = parse_doc(
2168            r#"{ "version": 1, "modules": { "synapse": { "program": "s", "log": { "level": "warn", "tags": { "perf": "debug", "gc.walk": "trace", "synapse": "error", "other.x": "info" } } } } }"#,
2169            path,
2170        )
2171        .unwrap();
2172        let log = config.modules[0].log.as_ref().unwrap();
2173        // BTreeMap order: gc.walk, other.x, perf, synapse.
2174        assert_eq!(
2175            log.filter_spec("synapse"),
2176            "warn,gc.walk=trace,other.x=info,synapse.perf=debug,synapse=error"
2177        );
2178    }
2179
2180    #[test]
2181    fn log_alarm_segment_mb_defaults_to_the_crate_default_and_refuses_zero() {
2182        let path = Path::new("/tmp/subc.jsonc");
2183        let config = parse_doc(
2184            r#"{ "version": 1, "modules": { "m": { "program": "m", "log": { "level": "info" } } } }"#,
2185            path,
2186        )
2187        .unwrap();
2188        assert_eq!(
2189            config.modules[0].log.as_ref().unwrap().alarm_segment_mb,
2190            cortexkit_log::SegmentRetention::default().alarm_segment_mb
2191        );
2192        let err = parse_doc(
2193            r#"{ "version": 1, "modules": { "m": { "program": "m", "log": { "alarm_segment_mb": 0 } } } }"#,
2194            path,
2195        )
2196        .expect_err("zero alarm must refuse");
2197        assert!(format!("{err}").contains("alarm_segment_mb"));
2198    }
2199
2200    #[test]
2201    fn route_bind_relay_timeout_zero_at_daemon_layer_is_refused() {
2202        let path = Path::new("/tmp/subc.jsonc");
2203        let err = parse_doc(
2204            r#"
2205            {
2206              "version": 1,
2207              "route_bind_relay_timeout_ms": 0,
2208              "modules": { "m": { "program": "m" } }
2209            }
2210            "#,
2211            path,
2212        )
2213        .expect_err("a daemon-wide zero budget must refuse parse");
2214        let text = format!("{err}");
2215        assert!(
2216            text.contains("route_bind_relay_timeout_ms"),
2217            "error must name the offending key: {text}"
2218        );
2219        assert!(
2220            text.contains("enabled: false"),
2221            "error must name the remedy (enable false): {text}"
2222        );
2223    }
2224
2225    #[test]
2226    fn route_bind_relay_timeout_zero_at_module_layer_is_refused() {
2227        let path = Path::new("/tmp/subc.jsonc");
2228        let err = parse_doc(
2229            r#"
2230            {
2231              "version": 1,
2232              "modules": {
2233                "good": { "program": "good" },
2234                "broken": { "program": "broken", "route_bind_relay_timeout_ms": 0 }
2235              }
2236            }
2237            "#,
2238            path,
2239        )
2240        .expect_err("a per-module zero budget must refuse parse");
2241        let text = format!("{err}");
2242        assert!(
2243            text.contains("route_bind_relay_timeout_ms"),
2244            "error must name the offending key: {text}"
2245        );
2246        assert!(
2247            text.contains("broken"),
2248            "error must name the offending module id: {text}"
2249        );
2250        assert!(
2251            text.contains("enabled: false"),
2252            "error must name the remedy (enable false): {text}"
2253        );
2254    }
2255
2256    #[test]
2257    fn drain_timeout_zero_still_parses_for_wedge_bounces() {
2258        // The asymmetry guard: `drain_timeout_ms: 0` is the sanctioned "tear
2259        // down now" used during a wedge bounce and MUST keep parsing. Anyone
2260        // later tempted to "fix the inconsistency" between drain and bind by
2261        // rejecting drain `0` too will break the wedge-bounce path; this
2262        // test names that contract explicitly.
2263        let path = Path::new("/tmp/subc.jsonc");
2264        let config = parse_doc(
2265            r#"
2266            {
2267              "version": 1,
2268              "drain_timeout_ms": 0,
2269              "modules": {
2270                "wedge": { "program": "wedge", "drain_timeout_ms": 0 }
2271              }
2272            }
2273            "#,
2274            path,
2275        )
2276        .expect("drain_timeout_ms: 0 must still parse; wedge-bounce uses it");
2277        let wedge = config
2278            .modules
2279            .iter()
2280            .find(|m| m.module_id == "wedge")
2281            .unwrap();
2282        assert_eq!(wedge.drain_timeout_ms, Some(0));
2283        assert_eq!(config.drain_timeout_ms, Some(0));
2284    }
2285
2286    #[test]
2287    fn route_bind_relay_timeout_absent_everywhere_stays_none_for_builtin_default() {
2288        // Backward-compatibility guard: a config that does not mention
2289        // `route_bind_relay_timeout_ms` at all (the shape every pre-#38 daemon
2290        // shipped) parses to `None` on both layers, so the bind path keeps
2291        // its compiled 12s default.
2292        let path = Path::new("/tmp/subc.jsonc");
2293        let config = parse_doc(
2294            r#"{ "version": 1, "modules": { "m": { "program": "m" } } }"#,
2295            path,
2296        )
2297        .unwrap();
2298        assert_eq!(config.modules[0].route_bind_relay_timeout_ms, None);
2299        assert_eq!(config.route_bind_relay_timeout_ms, None);
2300    }
2301
2302    /// The shape every config in the field has today: no `restart` block at
2303    /// all. It must keep parsing, and it must land on the exact policy the
2304    /// daemon used before the block existed -- all three numbers asserted, so
2305    /// that quietly changing one is a failing test rather than a fleet-wide
2306    /// behaviour change nobody configured.
2307    #[test]
2308    fn a_config_without_a_restart_block_keeps_the_supervisor_defaults() {
2309        let path = Path::new("/tmp/subc.jsonc");
2310        let config = parse_doc(
2311            r#"{ "version": 1, "modules": { "m": { "program": "m" } } }"#,
2312            path,
2313        )
2314        .unwrap();
2315        assert_eq!(config.modules[0].restart.max_restarts, 3);
2316        assert_eq!(config.modules[0].restart.window, Duration::from_secs(600));
2317        assert_eq!(
2318            config.modules[0].restart.backoff,
2319            Duration::from_millis(100)
2320        );
2321        assert_eq!(
2322            config.modules[0].restart.max_backoff,
2323            Duration::from_secs(30)
2324        );
2325    }
2326
2327    #[test]
2328    fn register_timeout_config_accepts_bounds_and_rejects_outside_them() {
2329        let path = Path::new("subc.jsonc");
2330        for seconds in [10, 3600] {
2331            let doc = format!(
2332                r#"{{"version":1,"modules":{{"m":{{"program":"m","register_timeout_s":{seconds}}}}}}}"#
2333            );
2334            let config = parse_doc(&doc, path).unwrap();
2335            assert_eq!(
2336                config.modules[0].register_timeout,
2337                Duration::from_secs(seconds)
2338            );
2339        }
2340        for value in ["9", "3601"] {
2341            let doc = format!(
2342                r#"{{"version":1,"modules":{{"m":{{"program":"m","register_timeout_s":{value}}}}}}}"#
2343            );
2344            let error = parse_doc(&doc, path).unwrap_err().to_string();
2345            assert!(error.contains("register_timeout_s"), "{value}: {error}");
2346        }
2347        let config = parse_doc(r#"{"version":1,"modules":{"m":{"program":"m"}}}"#, path).unwrap();
2348        assert_eq!(config.modules[0].register_timeout, Duration::from_secs(120));
2349    }
2350
2351    #[test]
2352    fn a_restart_block_resolves_each_key_independently() {
2353        let path = Path::new("/tmp/subc.jsonc");
2354        let config = parse_doc(
2355            r#"
2356            {
2357              "version": 1,
2358              "modules": {
2359                "all": {
2360                  "program": "all",
2361                  "restart": { "max_restarts": 5, "window_secs": 60, "backoff_ms": 250, "max_backoff_ms": 5000 }
2362                },
2363                "window-only": {
2364                  "program": "window-only",
2365                  "restart": { "window_secs": 7200 }
2366                },
2367                "never": {
2368                  "program": "never",
2369                  "restart": { "max_restarts": 0 }
2370                }
2371              }
2372            }
2373            "#,
2374            path,
2375        )
2376        .unwrap();
2377        let by_id = |id: &str| {
2378            config
2379                .modules
2380                .iter()
2381                .find(|m| m.module_id == id)
2382                .unwrap()
2383                .restart
2384        };
2385
2386        let all = by_id("all");
2387        assert_eq!(all.max_restarts, 5);
2388        assert_eq!(all.window, Duration::from_secs(60));
2389        assert_eq!(all.backoff, Duration::from_millis(250));
2390        assert_eq!(all.max_backoff, Duration::from_secs(5));
2391
2392        // A module that only widens its window keeps the default cap and
2393        // backoff: the keys do not travel as a set.
2394        let window_only = by_id("window-only");
2395        assert_eq!(window_only.max_restarts, 3);
2396        assert_eq!(window_only.window, Duration::from_secs(7_200));
2397        assert_eq!(window_only.backoff, Duration::from_millis(100));
2398        assert_eq!(window_only.max_backoff, Duration::from_secs(30));
2399
2400        // `max_restarts: 0` is a posture, not a mistake: never replace this
2401        // module. Unlike a zero window, it is accepted as written.
2402        assert_eq!(by_id("never").max_restarts, 0);
2403    }
2404
2405    /// A zero window makes the budget unspendable, which is the opposite of a
2406    /// tight limit and looks almost identical in a diff. Refuse it by name so
2407    /// the operator writes what they meant.
2408    #[test]
2409    fn restart_window_zero_is_refused_by_name() {
2410        let path = Path::new("/tmp/subc.jsonc");
2411        let err = parse_doc(
2412            r#"
2413            {
2414              "version": 1,
2415              "modules": {
2416                "good": { "program": "good" },
2417                "broken": { "program": "broken", "restart": { "window_secs": 0 } }
2418              }
2419            }
2420            "#,
2421            path,
2422        )
2423        .expect_err("a zero crash window must refuse parse");
2424        assert!(
2425            matches!(err, DaemonConfigError::InvalidValue { .. }),
2426            "a zero window is an invalid value, not a parse failure: {err:?}"
2427        );
2428        let text = format!("{err}");
2429        assert!(
2430            text.contains("restart.window_secs"),
2431            "error must name the offending key: {text}"
2432        );
2433        assert!(
2434            text.contains("broken"),
2435            "error must name the offending module id: {text}"
2436        );
2437        assert!(
2438            text.contains("max_restarts: 0"),
2439            "error must name the setting that actually stops restarts: {text}"
2440        );
2441    }
2442
2443    #[test]
2444    fn restart_max_backoff_below_backoff_is_refused_by_name() {
2445        let path = Path::new("/tmp/subc.jsonc");
2446        let err = parse_doc(
2447            r#"
2448            {
2449              "version": 1,
2450              "modules": {
2451                "broken": {
2452                  "program": "broken",
2453                  "restart": { "backoff_ms": 1000, "max_backoff_ms": 999 }
2454                }
2455              }
2456            }
2457            "#,
2458            path,
2459        )
2460        .expect_err("a maximum below the base backoff must refuse parse");
2461        assert!(
2462            matches!(err, DaemonConfigError::InvalidValue { .. }),
2463            "an invalid restart bound must be an InvalidValue: {err:?}"
2464        );
2465        let text = format!("{err}");
2466        assert!(
2467            text.contains("restart.max_backoff_ms"),
2468            "error must name max_backoff_ms: {text}"
2469        );
2470        assert!(
2471            text.contains("restart.backoff_ms"),
2472            "error must name backoff_ms: {text}"
2473        );
2474        assert!(
2475            text.contains("broken"),
2476            "error must name the offending module id: {text}"
2477        );
2478    }
2479
2480    #[test]
2481    fn parse_jsonc_defaults_and_ignores_unknown_fields() {
2482        let path = Path::new("/tmp/subc.jsonc");
2483        let config = parse_doc(
2484            r#"
2485            {
2486              // forward-compatible root field
2487              "version": 1,
2488              "unknown": { "ignored": true },
2489              "modules": {
2490                "aft": {
2491                  "program": "aft",
2492                  "args": ["module",],
2493                  "env": { "A": "B", },
2494                  "future": 42,
2495                },
2496                "disabled": { "program": "disabled", "enabled": false }
2497              },
2498            }
2499            "#,
2500            path,
2501        )
2502        .unwrap();
2503
2504        assert_eq!(config.port, None);
2505        assert_eq!(config.modules.len(), 2);
2506        assert_eq!(config.modules[0].module_id, "aft");
2507        assert_eq!(config.modules[0].program, PathBuf::from("aft"));
2508        assert_eq!(config.modules[0].args, ["module"]);
2509        assert_eq!(config.modules[0].env, [("A".to_string(), "B".to_string())]);
2510        assert!(config.modules[0].enabled);
2511        assert!(config.modules[0].reserved_prefixes.is_empty());
2512        assert_eq!(config.modules[0].health, HealthConfig::default());
2513        assert!(!config.modules[1].enabled);
2514    }
2515
2516    #[test]
2517    fn reserved_capabilities_accept_unknown_bound_modules_and_refuse_bad_identifiers() {
2518        let path = Path::new("/tmp/subc.jsonc");
2519        let config = parse_doc(
2520            r#"{
2521                "version": 1,
2522                "reserved_capabilities": {
2523                    "credentials-provider/v1": "future-vault"
2524                },
2525                "modules": {}
2526            }"#,
2527            path,
2528        )
2529        .expect("a binding may predate its provider installation");
2530        assert_eq!(
2531            config.reserved_capabilities,
2532            BTreeMap::from([(
2533                "credentials-provider/v1".to_string(),
2534                "future-vault".to_string()
2535            )])
2536        );
2537
2538        let error = parse_doc(
2539            r#"{
2540                "version": 1,
2541                "reserved_capabilities": { "Credentials/v1": "vault" },
2542                "modules": {}
2543            }"#,
2544            path,
2545        )
2546        .expect_err("reserved capabilities use the capability identifier grammar");
2547        assert!(error.to_string().contains("reserved_capabilities key"));
2548    }
2549
2550    #[test]
2551    fn retired_launch_nonce_env_is_ignored_for_any_value() {
2552        let parse = |field: &str| {
2553            parse_doc(
2554                &format!(r#"{{"version":1,"modules":{{"probe":{{"program":"probe"{field}}}}}}}"#),
2555                Path::new("subc.jsonc"),
2556            )
2557            .unwrap()
2558            .modules
2559            .remove(0)
2560            .module_spec()
2561        };
2562        for value in ["true", "false", "null", "0", "\"false\"", "[]", "{}"] {
2563            assert_eq!(
2564                parse(""),
2565                parse(&format!(",\"launch_nonce_env\":{value}")),
2566                "the retired key must not change the launch spec or require a restart"
2567            );
2568        }
2569    }
2570
2571    /// An old config and an explicit `subc` declaration must normalize identically
2572    /// so adding the protocol key does not silently change existing modules.
2573    #[test]
2574    fn an_absent_protocol_key_and_an_explicit_subc_are_the_same_module() {
2575        let parse = |module_body: &str| {
2576            parse_doc(
2577                &format!(
2578                    r#"{{
2579                      "version": 1,
2580                      "modules": {{ "aft": {{ "program": "aft"{module_body} }} }}
2581                    }}"#
2582                ),
2583                Path::new("subc.jsonc"),
2584            )
2585            .expect("module parses")
2586            .modules
2587            .remove(0)
2588        };
2589
2590        let absent = parse("");
2591        let explicit = parse(r#", "protocol": "subc""#);
2592        let none = parse(r#", "protocol": "none""#);
2593
2594        assert_eq!(absent.protocol, ModuleProtocol::Subc);
2595        assert_eq!(explicit.protocol, ModuleProtocol::Subc);
2596        assert_eq!(
2597            absent, explicit,
2598            "an absent protocol key must produce exactly the module an explicit subc does"
2599        );
2600        assert_eq!(none.protocol, ModuleProtocol::None);
2601        // The declaration has to survive into what the supervisor is handed;
2602        // parsing it into a field nothing reads would leave every behaviour
2603        // gated on it unreachable.
2604        assert_eq!(none.module_spec().protocol, ModuleProtocol::None);
2605    }
2606
2607    /// `overlap` defaults to exclusive, `"safe"` opts in and reaches the spec
2608    /// the supervisor is handed, and anything else is refused rather than read
2609    /// as either value.
2610    #[test]
2611    fn overlap_defaults_to_exclusive_and_only_safe_opts_in() {
2612        let parse = |module_body: &str| {
2613            parse_doc(
2614                &format!(
2615                    r#"{{
2616                      "version": 1,
2617                      "modules": {{ "aft": {{ "program": "aft"{module_body} }} }}
2618                    }}"#
2619                ),
2620                Path::new("subc.jsonc"),
2621            )
2622        };
2623
2624        let absent = parse("").unwrap().modules.remove(0);
2625        assert_eq!(absent.overlap, ModuleOverlap::Exclusive);
2626        assert_eq!(absent.module_spec().overlap, ModuleOverlap::Exclusive);
2627        let safe = parse(r#", "overlap": "safe""#).unwrap().modules.remove(0);
2628        assert_eq!(safe.module_spec().overlap, ModuleOverlap::Safe);
2629        let typo = parse(r#", "overlap": "sfae""#).expect_err("an unknown overlap is refused");
2630        assert!(typo.to_string().contains("sfae"), "{typo}");
2631    }
2632
2633    #[test]
2634    fn carry_containment_defaults_off_and_refuses_overlap() {
2635        let parse = |module_body: &str| {
2636            parse_doc(
2637                &format!(
2638                    r#"{{
2639                      "version": 1,
2640                      "modules": {{ "worker": {{ "program": "worker"{module_body} }} }}
2641                    }}"#
2642                ),
2643                Path::new("subc.jsonc"),
2644            )
2645        };
2646
2647        let absent = parse("").unwrap().modules.remove(0);
2648        let explicit_off = parse(r#", "carry_containment": false"#)
2649            .unwrap()
2650            .modules
2651            .remove(0);
2652        assert_eq!(absent, explicit_off);
2653        assert!(!absent.module_spec().carry_containment);
2654        let carried = parse(r#", "carry_containment": true"#)
2655            .unwrap()
2656            .modules
2657            .remove(0);
2658        assert!(carried.module_spec().carry_containment);
2659        let error = parse(r#", "carry_containment": true, "overlap": "safe""#)
2660            .expect_err("a carried container cannot have overlapping leaders");
2661        let message = error.to_string();
2662        assert!(message.contains("worker"), "{message}");
2663        assert!(message.contains("carry_containment"), "{message}");
2664        assert!(message.contains("overlap"), "{message}");
2665    }
2666
2667    /// The spawn role is the supervisor's to set on a swap candidate. A
2668    /// configured value would reach every plain spawn and make the module pick
2669    /// its long swap warm-up budget while callers wait on a restart.
2670    #[test]
2671    fn the_spawn_role_is_refused_as_a_configured_env_key() {
2672        let error = parse_doc(
2673            r#"{
2674              "version": 1,
2675              "modules": { "aft": { "program": "aft", "env": { "SUBC_SPAWN_ROLE": "swap_candidate" } } }
2676            }"#,
2677            Path::new("subc.jsonc"),
2678        )
2679        .expect_err("SUBC_SPAWN_ROLE must not be configurable");
2680        assert!(
2681            matches!(error, DaemonConfigError::InvalidValue { .. }),
2682            "expected InvalidValue, got {error:?}"
2683        );
2684        assert!(error.to_string().contains("SUBC_SPAWN_ROLE"), "{error}");
2685    }
2686
2687    /// An unusable value is refused WITH THE VALUE IN THE MESSAGE. Falling back
2688    /// to `subc` on a typo would restore the exact supervision the operator was
2689    /// trying to turn off -- health probing, restart-on-silence, SIGKILL
2690    /// teardown -- and the config file would still read as if it had been
2691    /// applied.
2692    #[test]
2693    fn an_unsupported_protocol_value_is_refused_by_name() {
2694        let error = parse_doc(
2695            r#"{
2696              "version": 1,
2697              "modules": { "nats": { "program": "nats-server", "protocol": "grpc" } }
2698            }"#,
2699            Path::new("subc.jsonc"),
2700        )
2701        .expect_err("an unknown protocol must not fall back to a default");
2702
2703        assert!(
2704            matches!(error, DaemonConfigError::InvalidValue { .. }),
2705            "expected InvalidValue, got {error:?}"
2706        );
2707        let message = error.to_string();
2708        assert!(
2709            message.contains("grpc"),
2710            "the refusal must name the offending value: {message}"
2711        );
2712        assert!(
2713            message.contains("nats"),
2714            "the refusal must name the module so it can be found in the file: {message}"
2715        );
2716    }
2717
2718    /// `reserved` is enforced on a module's HELLO. A module that speaks no subc
2719    /// wire never sends one, so the pair declares a protection that could never
2720    /// be applied -- worse than no protection, because the config file states it.
2721    #[test]
2722    fn reserved_true_with_protocol_none_is_refused_with_the_reason() {
2723        let error = parse_doc(
2724            r#"{
2725              "version": 1,
2726              "modules": {
2727                "nats": { "program": "nats-server", "protocol": "none", "reserved": true }
2728              }
2729            }"#,
2730            Path::new("subc.jsonc"),
2731        )
2732        .expect_err("a reservation that can never be checked must not parse");
2733
2734        assert!(
2735            matches!(error, DaemonConfigError::InvalidValue { .. }),
2736            "expected InvalidValue, got {error:?}"
2737        );
2738        let message = error.to_string();
2739        assert!(
2740            message.contains("nats") && message.contains("reserved"),
2741            "the refusal must name the module and the offending key: {message}"
2742        );
2743        assert!(
2744            message.contains("HELLO") || message.contains("never registers"),
2745            "the refusal must say WHY the pair cannot work: {message}"
2746        );
2747    }
2748
2749    #[test]
2750    fn reserved_prefixes_parse_for_reserved_modules() {
2751        let config = parse_doc(
2752            r#"
2753            {
2754              "version": 1,
2755              "modules": {
2756                "federation": {
2757                  "program": "fed",
2758                  "reserved": true,
2759                  "reserved_prefixes": ["fed:"]
2760                }
2761              }
2762            }
2763            "#,
2764            Path::new("subc.jsonc"),
2765        )
2766        .unwrap();
2767
2768        assert_eq!(config.modules[0].reserved_prefixes, ["fed:".to_string()]);
2769    }
2770
2771    #[test]
2772    fn reserved_prefixes_reject_bad_boundaries_and_owners() {
2773        let missing_delimiter = parse_doc(
2774            r#"{
2775              "version": 1,
2776              "modules": {
2777                "federation": { "program": "fed", "reserved": true, "reserved_prefixes": ["fed"] }
2778              }
2779            }"#,
2780            Path::new("subc.jsonc"),
2781        )
2782        .unwrap_err();
2783        assert!(matches!(
2784            missing_delimiter,
2785            DaemonConfigError::InvalidValue { .. }
2786        ));
2787
2788        let non_reserved_owner = parse_doc(
2789            r#"{
2790              "version": 1,
2791              "modules": {
2792                "federation": { "program": "fed", "reserved_prefixes": ["fed:"] }
2793              }
2794            }"#,
2795            Path::new("subc.jsonc"),
2796        )
2797        .unwrap_err();
2798        assert!(matches!(
2799            non_reserved_owner,
2800            DaemonConfigError::InvalidValue { .. }
2801        ));
2802    }
2803
2804    #[test]
2805    fn reserved_prefixes_reject_cross_owner_overlap_and_exact_id_collisions() {
2806        let overlap = parse_doc(
2807            r#"{
2808              "version": 1,
2809              "modules": {
2810                "fed-owner": { "program": "fed", "reserved": true, "reserved_prefixes": ["fed:"] },
2811                "sub-owner": { "program": "fed-sub", "reserved": true, "reserved_prefixes": ["fed:sub:"] }
2812              }
2813            }"#,
2814            Path::new("subc.jsonc"),
2815        )
2816        .unwrap_err();
2817        assert!(matches!(overlap, DaemonConfigError::InvalidValue { .. }));
2818
2819        let exact_collision = parse_doc(
2820            r#"{
2821              "version": 1,
2822              "modules": {
2823                "federation": { "program": "fed", "reserved": true, "reserved_prefixes": ["fed:"] },
2824                "fed:special": { "program": "special" }
2825              }
2826            }"#,
2827            Path::new("subc.jsonc"),
2828        )
2829        .unwrap_err();
2830        assert!(matches!(
2831            exact_collision,
2832            DaemonConfigError::InvalidValue { .. }
2833        ));
2834    }
2835
2836    #[test]
2837    fn health_config_parses_and_ignores_unknown_fields() {
2838        let config = parse_doc(
2839            r#"
2840            {
2841              "version": 1,
2842              "modules": {
2843                "aft": {
2844                  "program": "aft",
2845                  "health": {
2846                    "cadence_ms": 100,
2847                    "deadline_ms": 20,
2848                    "failure_threshold": 2,
2849                    "on_degraded": "report",
2850                    "on_failing": "restart",
2851                    "critical": true,
2852                    "future": "ignored"
2853                  }
2854                }
2855              }
2856            }
2857            "#,
2858            Path::new("subc.jsonc"),
2859        )
2860        .unwrap();
2861
2862        let health = &config.modules[0].health;
2863        assert_eq!(health.cadence, std::time::Duration::from_millis(100));
2864        assert_eq!(health.deadline, std::time::Duration::from_millis(20));
2865        assert_eq!(health.failure_threshold, 2);
2866        assert_eq!(health.on_degraded, HealthAction::Report);
2867        assert_eq!(health.on_failing, HealthAction::Restart);
2868        assert!(health.critical);
2869    }
2870
2871    #[test]
2872    fn http_health_refuses_non_loopback_https_and_wire_modules() {
2873        for (protocol, url) in [
2874            ("none", "http://example.com/healthz"),
2875            ("none", "https://127.0.0.1/healthz"),
2876            ("subc", "http://127.0.0.1/healthz"),
2877        ] {
2878            let doc = serde_json::json!({"version": 1, "modules": {"bus": {
2879                "program": "nats-server", "protocol": protocol, "health": {"http": url}
2880            }}})
2881            .to_string();
2882            let error = parse_doc(&doc, Path::new("test.jsonc"))
2883                .unwrap_err()
2884                .to_string();
2885            assert!(
2886                error.contains("bus") && error.contains("health.http"),
2887                "{error}"
2888            );
2889        }
2890    }
2891
2892    #[test]
2893    fn health_config_rejects_bad_enum_and_non_positive_numbers() {
2894        let bad_enum = parse_doc(
2895            r#"{
2896              "version": 1,
2897              "modules": { "aft": { "program": "aft", "health": { "on_failing": "page" } } }
2898            }"#,
2899            Path::new("subc.jsonc"),
2900        )
2901        .unwrap_err();
2902        assert!(matches!(bad_enum, DaemonConfigError::InvalidJson { .. }));
2903
2904        let zero = parse_doc(
2905            r#"{
2906              "version": 1,
2907              "modules": { "aft": { "program": "aft", "health": { "cadence_ms": 0 } } }
2908            }"#,
2909            Path::new("subc.jsonc"),
2910        )
2911        .unwrap_err();
2912        assert!(matches!(zero, DaemonConfigError::InvalidValue { .. }));
2913    }
2914
2915    #[test]
2916    fn admission_facts_carrier_requires_non_empty_targets() {
2917        let missing_targets = parse_doc(
2918            r#"{
2919              "version": 1,
2920              "admission_facts_carrier_module_id": "fed",
2921              "modules": { "fed": { "program": "fed", "reserved": true } }
2922            }"#,
2923            Path::new("subc.jsonc"),
2924        )
2925        .unwrap_err();
2926        // Pin the message, not just the variant. Every rule in this validator
2927        // returns InvalidValue, and the guard below rejects an empty list -- so
2928        // a change that turned a missing list into an empty one would still be
2929        // refused, by a different rule, and a variant-only assertion could not
2930        // tell the two apart.
2931        assert!(
2932            matches!(&missing_targets, DaemonConfigError::InvalidValue { message, .. }
2933                if message.contains("must be present")),
2934            "expected the presence rule, got: {missing_targets:?}"
2935        );
2936
2937        let empty_targets = parse_doc(
2938            r#"{
2939              "version": 1,
2940              "admission_facts_carrier_module_id": "fed",
2941              "admission_facts_targets": [""],
2942              "modules": { "fed": { "program": "fed", "reserved": true } }
2943            }"#,
2944            Path::new("subc.jsonc"),
2945        )
2946        .unwrap_err();
2947        assert!(
2948            matches!(&empty_targets, DaemonConfigError::InvalidValue { message, .. }
2949                if message.contains("must be non-empty")),
2950            "expected the non-empty rule, got: {empty_targets:?}"
2951        );
2952    }
2953
2954    #[test]
2955    fn admission_facts_carrier_must_be_enabled_reserved_and_configured() {
2956        for module in [
2957            r#"{ "program": "fed", "enabled": false, "reserved": true }"#,
2958            r#"{ "program": "fed", "enabled": true, "reserved": false }"#,
2959        ] {
2960            let doc = format!(
2961                r#"{{
2962                  "version": 1,
2963                  "admission_facts_carrier_module_id": "fed",
2964                  "admission_facts_targets": ["target"],
2965                  "modules": {{ "fed": {module}, "target": {{ "program": "target" }} }}
2966                }}"#
2967            );
2968            let err = parse_doc(&doc, Path::new("subc.jsonc")).unwrap_err();
2969            // Pin which refusal fired. Both inputs are also missing nothing
2970            // else, so without this the neighbouring "must name a configured
2971            // module" rule would satisfy the assertion if this one were removed.
2972            assert!(
2973                matches!(&err, DaemonConfigError::InvalidValue { message, .. }
2974                    if message.contains("enabled reserved module")),
2975                "expected the enabled-and-reserved rule, got: {err:?}"
2976            );
2977        }
2978
2979        let absent = parse_doc(
2980            r#"{
2981              "version": 1,
2982              "admission_facts_carrier_module_id": "missing",
2983              "admission_facts_targets": ["target"],
2984              "modules": { "target": { "program": "target" } }
2985            }"#,
2986            Path::new("subc.jsonc"),
2987        )
2988        .unwrap_err();
2989        assert!(
2990            matches!(&absent, DaemonConfigError::InvalidValue { message, .. }
2991                if message.contains("must name a configured module")),
2992            "expected the configured-module rule, got: {absent:?}"
2993        );
2994    }
2995
2996    #[test]
2997    fn reject_unsupported_version() {
2998        let err = parse_doc(
2999            r#"{ "version": 2, "modules": {} }"#,
3000            Path::new("subc.jsonc"),
3001        )
3002        .unwrap_err();
3003        assert!(matches!(
3004            err,
3005            DaemonConfigError::UnsupportedVersion { version: 2, .. }
3006        ));
3007    }
3008
3009    #[test]
3010    fn reject_unterminated_block_comment() {
3011        let err = parse_doc(r#"{ "version": 1, /*"#, Path::new("subc.jsonc")).unwrap_err();
3012        assert!(matches!(err, DaemonConfigError::InvalidJsonc { .. }));
3013    }
3014}
3015
3016#[cfg(test)]
3017mod activity_config_tests {
3018    use super::*;
3019
3020    #[test]
3021    fn activity_config_defaults_partial_overrides_and_positive_bounds() {
3022        let path = Path::new("subc.jsonc");
3023        let default = parse_doc_with_activity(r#"{"version":1,"modules":{}}"#, path).unwrap();
3024        assert_eq!(
3025            default.1,
3026            ActivityConfig {
3027                max_age_days: 30,
3028                max_total_mb: 64
3029            }
3030        );
3031        let changed = parse_doc_with_activity(
3032            r#"{"version":1,"activity":{"max_age_days":7,"max_total_mb":8}}"#,
3033            path,
3034        )
3035        .unwrap();
3036        assert_eq!(
3037            changed.1,
3038            ActivityConfig {
3039                max_age_days: 7,
3040                max_total_mb: 8
3041            }
3042        );
3043        let partial =
3044            parse_doc_with_activity(r#"{"version":1,"activity":{"max_age_days":7}}"#, path)
3045                .unwrap();
3046        assert_eq!(
3047            partial.1,
3048            ActivityConfig {
3049                max_age_days: 7,
3050                max_total_mb: 64
3051            }
3052        );
3053        for doc in [
3054            r#"{"version":1,"activity":{"max_age_days":0}}"#,
3055            r#"{"version":1,"activity":{"max_total_mb":0}}"#,
3056        ] {
3057            assert!(parse_doc(doc, path).is_err());
3058        }
3059        assert!(!RestartRequiredSection::ALL
3060            .iter()
3061            .any(|section| section.label() == "activity"));
3062    }
3063}
3064
3065#[cfg(test)]
3066mod registration_declaration_tests {
3067    use super::*;
3068    #[test]
3069    fn registration_declaration_config_bool_is_optional_and_typed() {
3070        let parse = |field: &str| {
3071            parse_doc(
3072                &format!(r#"{{"version":1,"modules":{{"worker":{{"program":"worker"{field}}}}}}}"#),
3073                Path::new("subc.jsonc"),
3074            )
3075        };
3076        assert!(!parse("").unwrap().modules[0].registration_channel);
3077        assert!(
3078            !parse(r#", "registration_channel":false"#).unwrap().modules[0].registration_channel
3079        );
3080        assert!(parse(r#", "registration_channel":true"#).unwrap().modules[0].registration_channel);
3081        assert!(parse(r#", "registration_channel":"true""#).is_err());
3082    }
3083}