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