Skip to main content

subc_daemon/
daemon_config.rs

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