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