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