clawft-kernel 0.8.3

WeftOS kernel: boot sequence, process table, service registry, and health subsystem
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
//! Configuration and secrets service (K5-G1).
//!
//! Provides [`ConfigService`] for runtime configuration management with
//! change notification, typed values, and encrypted secret storage. Backed
//! by in-memory stores (tree integration deferred to when `exochain`
//! feature is enabled).

use std::sync::atomic::{AtomicU64, Ordering};
use std::sync::{Arc, RwLock};

use async_trait::async_trait;
use chrono::{DateTime, Duration, Utc};
use dashmap::DashMap;
use serde::{Deserialize, Serialize};
use tracing::info;

use crate::error::KernelError;
use crate::health::HealthStatus;
use crate::process::Pid;
use crate::service::{ServiceType, SystemService};

#[cfg(feature = "exochain")]
use crate::chain::ChainManager;
#[cfg(feature = "exochain")]
use crate::gate::GateBackend;

// ---------------------------------------------------------------------------
// ConfigValue — typed configuration values
// ---------------------------------------------------------------------------

/// A typed configuration value.
#[non_exhaustive]
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub enum ConfigValue {
    /// Plain text.
    Text(String),
    /// 64-bit signed integer.
    Integer(i64),
    /// 64-bit floating point.
    Float(f64),
    /// Boolean flag.
    Boolean(bool),
    /// Arbitrary JSON blob.
    Json(serde_json::Value),
}

impl ConfigValue {
    /// Convert to a `serde_json::Value` representation.
    pub fn to_json(&self) -> serde_json::Value {
        match self {
            ConfigValue::Text(s) => serde_json::Value::String(s.clone()),
            ConfigValue::Integer(n) => serde_json::json!(n),
            ConfigValue::Float(f) => serde_json::json!(f),
            ConfigValue::Boolean(b) => serde_json::json!(b),
            ConfigValue::Json(v) => v.clone(),
        }
    }
}

// ---------------------------------------------------------------------------
// ConfigEntry
// ---------------------------------------------------------------------------

/// A stored configuration entry with metadata.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ConfigEntry {
    /// Configuration key.
    pub key: String,
    /// Configuration namespace.
    pub namespace: String,
    /// Typed value.
    pub value: ConfigValue,
    /// When the entry was last updated.
    pub updated_at: DateTime<Utc>,
}

// ---------------------------------------------------------------------------
// ConfigChange
// ---------------------------------------------------------------------------

/// A change notification for a configuration key.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ConfigChange {
    /// Configuration namespace.
    pub namespace: String,
    /// Configuration key.
    pub key: String,
    /// Previous value (if any).
    pub old_value: Option<serde_json::Value>,
    /// New value (if any -- `None` for deletions).
    pub new_value: Option<serde_json::Value>,
    /// PID of the process that made the change.
    pub changed_by: Pid,
    /// When the change occurred.
    pub timestamp: DateTime<Utc>,
}

// ---------------------------------------------------------------------------
// SecretRef
// ---------------------------------------------------------------------------

/// Metadata about a stored secret.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SecretRef {
    /// Secret namespace.
    pub namespace: String,
    /// Secret key.
    pub key: String,
    /// When the secret expires.
    pub expires_at: DateTime<Utc>,
    /// PIDs allowed to read this secret.
    pub scoped_to: Vec<Pid>,
}

// ---------------------------------------------------------------------------
// ConfigService
// ---------------------------------------------------------------------------

/// Configuration and secrets service.
///
/// Stores configuration values at `/kernel/config/{namespace}/{key}` and
/// secrets at `/kernel/secrets/{namespace}/{key}` (encrypted at rest).
/// Supports change notification via subscriptions.
pub struct ConfigService {
    /// Config store: "namespace/key" -> value.
    configs: DashMap<String, serde_json::Value>,
    /// Typed config entries: "namespace/key" -> ConfigEntry.
    entries: DashMap<String, ConfigEntry>,
    /// Secret store: "namespace/key" -> encrypted bytes.
    secrets: DashMap<String, Vec<u8>>,
    /// Secret metadata: "namespace/key" -> SecretRef.
    secret_refs: DashMap<String, SecretRef>,
    /// Change subscribers: namespace -> list of subscription queues.
    subscribers: DashMap<String, Vec<Arc<RwLock<Vec<ConfigChange>>>>>,
    /// Encryption key (derived from genesis in production).
    encryption_key: [u8; 32],
    /// Change log for auditing.
    change_log: RwLock<Vec<ConfigChange>>,
    /// Total config sets.
    set_count: AtomicU64,
    /// ExoChain manager for event logging.
    #[cfg(feature = "exochain")]
    chain_manager: Option<Arc<ChainManager>>,
    /// Governance gate for access control.
    #[cfg(feature = "exochain")]
    governance_gate: Option<Arc<dyn GateBackend>>,
}

impl ConfigService {
    /// Create a new config service with a given encryption key.
    pub fn new(encryption_key: [u8; 32]) -> Self {
        Self {
            configs: DashMap::new(),
            entries: DashMap::new(),
            secrets: DashMap::new(),
            secret_refs: DashMap::new(),
            subscribers: DashMap::new(),
            encryption_key,
            change_log: RwLock::new(Vec::new()),
            set_count: AtomicU64::new(0),
            #[cfg(feature = "exochain")]
            chain_manager: None,
            #[cfg(feature = "exochain")]
            governance_gate: None,
        }
    }

    /// Create a config service with a default (zero) encryption key (testing).
    pub fn new_default() -> Self {
        Self::new([0u8; 32])
    }

    /// Set the chain manager for exochain event logging.
    #[cfg(feature = "exochain")]
    pub fn with_chain_manager(mut self, cm: Arc<ChainManager>) -> Self {
        self.chain_manager = Some(cm);
        self
    }

    /// Set the governance gate for access control.
    #[cfg(feature = "exochain")]
    pub fn with_governance_gate(mut self, gate: Arc<dyn GateBackend>) -> Self {
        self.governance_gate = Some(gate);
        self
    }

    // ── Config operations ─────────────────────────────────────────

    /// Set a configuration value.
    pub fn set(
        &self,
        namespace: &str,
        key: &str,
        value: serde_json::Value,
        changed_by: Pid,
    ) -> Result<(), KernelError> {
        // Governance gate: config changes are gated.
        #[cfg(feature = "exochain")]
        if let Some(ref gate) = self.governance_gate {
            use crate::gate::GateDecision;
            use crate::governance::{GateEffectKind, with_effect_context};
            let ctx = with_effect_context(
                serde_json::json!({
                    "namespace": namespace,
                    "key": key,
                    "changed_by": changed_by,
                }),
                &GateEffectKind::ConfigSet.effect_vector(),
            );
            let decision = gate.check("config-service", "config.set", &ctx);
            if let GateDecision::Deny { reason, .. } = decision {
                return Err(KernelError::GovernanceDenied(format!(
                    "config set denied: {reason}"
                )));
            }
        }

        let config_key = format!("{namespace}/{key}");
        let old_value = self.configs.get(&config_key).map(|v| v.value().clone());
        self.configs.insert(config_key, value.clone());

        let change = ConfigChange {
            namespace: namespace.to_string(),
            key: key.to_string(),
            old_value,
            new_value: Some(value),
            changed_by,
            timestamp: Utc::now(),
        };

        // Notify subscribers.
        self.notify_subscribers(namespace, &change);

        // Record in change log.
        if let Ok(mut log) = self.change_log.write() {
            log.push(change);
        }
        self.set_count.fetch_add(1, Ordering::Relaxed);

        #[cfg(feature = "exochain")]
        if let Some(ref cm) = self.chain_manager {
            cm.append(
                "config",
                crate::chain::EVENT_KIND_CONFIG_SET,
                Some(serde_json::json!({
                    "namespace": namespace,
                    "key": key,
                    "changed_by": changed_by,
                })),
            );
        }

        Ok(())
    }

    /// Get a configuration value.
    pub fn get(&self, namespace: &str, key: &str) -> Option<serde_json::Value> {
        let config_key = format!("{namespace}/{key}");
        self.configs.get(&config_key).map(|v| v.value().clone())
    }

    /// Delete a configuration value.
    pub fn delete(&self, namespace: &str, key: &str, changed_by: Pid) -> Result<(), KernelError> {
        // Governance gate: config deletion is gated.
        #[cfg(feature = "exochain")]
        if let Some(ref gate) = self.governance_gate {
            use crate::gate::GateDecision;
            use crate::governance::{GateEffectKind, with_effect_context};
            let ctx = with_effect_context(
                serde_json::json!({
                    "namespace": namespace,
                    "key": key,
                    "changed_by": changed_by,
                }),
                &GateEffectKind::ConfigDelete.effect_vector(),
            );
            let decision = gate.check("config-service", "config.delete", &ctx);
            if let GateDecision::Deny { reason, .. } = decision {
                return Err(KernelError::GovernanceDenied(format!(
                    "config delete denied: {reason}"
                )));
            }
        }

        let config_key = format!("{namespace}/{key}");
        let old_value = self.configs.remove(&config_key).map(|(_, v)| v);

        let change = ConfigChange {
            namespace: namespace.to_string(),
            key: key.to_string(),
            old_value,
            new_value: None,
            changed_by,
            timestamp: Utc::now(),
        };
        self.notify_subscribers(namespace, &change);

        #[cfg(feature = "exochain")]
        if let Some(ref cm) = self.chain_manager {
            cm.append(
                "config",
                crate::chain::EVENT_KIND_CONFIG_DELETE,
                Some(serde_json::json!({
                    "namespace": namespace,
                    "key": key,
                    "changed_by": changed_by,
                })),
            );
        }

        Ok(())
    }

    /// List all config keys in a namespace.
    pub fn list_keys(&self, namespace: &str) -> Vec<String> {
        let prefix = format!("{namespace}/");
        self.configs
            .iter()
            .filter(|e| e.key().starts_with(&prefix))
            .map(|e| e.key()[prefix.len()..].to_string())
            .collect()
    }

    // ── Typed config operations ──────────────────────────────────

    /// Store a typed configuration value.
    pub fn set_typed(
        &self,
        namespace: &str,
        key: &str,
        value: ConfigValue,
        changed_by: Pid,
    ) -> Result<(), KernelError> {
        let config_key = format!("{namespace}/{key}");
        let json_value = value.to_json();

        // Also store in the legacy JSON map for backward compatibility.
        let old_value = self.configs.get(&config_key).map(|v| v.value().clone());
        self.configs.insert(config_key.clone(), json_value.clone());

        let entry = ConfigEntry {
            key: key.to_string(),
            namespace: namespace.to_string(),
            value,
            updated_at: Utc::now(),
        };
        self.entries.insert(config_key, entry);

        let change = ConfigChange {
            namespace: namespace.to_string(),
            key: key.to_string(),
            old_value,
            new_value: Some(json_value),
            changed_by,
            timestamp: Utc::now(),
        };
        self.notify_subscribers(namespace, &change);

        if let Ok(mut log) = self.change_log.write() {
            log.push(change);
        }
        self.set_count.fetch_add(1, Ordering::Relaxed);
        Ok(())
    }

    /// Retrieve a typed configuration entry.
    pub fn get_typed(&self, namespace: &str, key: &str) -> Option<ConfigEntry> {
        let config_key = format!("{namespace}/{key}");
        self.entries.get(&config_key).map(|e| e.value().clone())
    }

    /// List all typed entries in a namespace.
    pub fn list(&self, namespace: &str) -> Vec<ConfigEntry> {
        let prefix = format!("{namespace}/");
        self.entries
            .iter()
            .filter(|e| e.key().starts_with(&prefix))
            .map(|e| e.value().clone())
            .collect()
    }

    /// Delete a typed configuration entry. Returns `true` if it existed.
    ///
    /// # Errors
    ///
    /// Returns `KernelError::GovernanceDenied` if the governance gate
    /// rejects the deletion (only when the `exochain` feature is enabled
    /// and a gate is attached).
    pub fn delete_typed(
        &self,
        namespace: &str,
        key: &str,
        changed_by: Pid,
    ) -> Result<bool, KernelError> {
        // Governance gate: typed config deletion is gated.
        #[cfg(feature = "exochain")]
        if let Some(ref gate) = self.governance_gate {
            use crate::gate::GateDecision;
            use crate::governance::{GateEffectKind, with_effect_context};
            let ctx = with_effect_context(
                serde_json::json!({
                    "namespace": namespace,
                    "key": key,
                    "changed_by": changed_by,
                }),
                &GateEffectKind::ConfigDelete.effect_vector(),
            );
            let decision = gate.check("config-service", "config.delete_typed", &ctx);
            if let GateDecision::Deny { reason, .. } = decision {
                return Err(KernelError::GovernanceDenied(format!(
                    "config delete_typed denied: {reason}"
                )));
            }
        }

        let config_key = format!("{namespace}/{key}");
        let removed = self.entries.remove(&config_key).is_some();
        // Also remove from legacy store.
        let old_value = self.configs.remove(&config_key).map(|(_, v)| v);

        let change = ConfigChange {
            namespace: namespace.to_string(),
            key: key.to_string(),
            old_value,
            new_value: None,
            changed_by,
            timestamp: Utc::now(),
        };
        self.notify_subscribers(namespace, &change);
        Ok(removed)
    }

    // ── Subscription ──────────────────────────────────────────────

    /// Subscribe to changes in a namespace.
    ///
    /// Returns a shared reference to the change queue. Callers can read
    /// accumulated changes from the returned `Arc<RwLock<Vec<ConfigChange>>>`.
    pub fn subscribe(&self, namespace: &str) -> Arc<RwLock<Vec<ConfigChange>>> {
        let queue = Arc::new(RwLock::new(Vec::new()));
        self.subscribers
            .entry(namespace.to_string())
            .or_default()
            .push(queue.clone());
        queue
    }

    /// Notify all subscribers for a namespace.
    fn notify_subscribers(&self, namespace: &str, change: &ConfigChange) {
        if let Some(mut subs) = self.subscribers.get_mut(namespace) {
            subs.retain(|queue| {
                if let Ok(mut q) = queue.write() {
                    q.push(change.clone());
                    true
                } else {
                    false // remove dead subscribers
                }
            });
        }
    }

    // ── Secret operations ─────────────────────────────────────────

    /// Store an encrypted secret.
    pub fn set_secret(
        &self,
        namespace: &str,
        key: &str,
        value: &[u8],
        scoped_to: Vec<Pid>,
    ) -> Result<(), KernelError> {
        // Governance gate: secret storage is a critical action.
        #[cfg(feature = "exochain")]
        if let Some(ref gate) = self.governance_gate {
            use crate::gate::GateDecision;
            use crate::governance::{GateEffectKind, with_effect_context};
            let ctx = with_effect_context(
                serde_json::json!({
                    "namespace": namespace,
                    "key": key,
                }),
                &GateEffectKind::ConfigSecretSet.effect_vector(),
            );
            let decision = gate.check("config-service", "config.secret.set", &ctx);
            if let GateDecision::Deny { reason, .. } = decision {
                return Err(KernelError::GovernanceDenied(format!(
                    "secret set denied: {reason}"
                )));
            }
        }

        let secret_key = format!("{namespace}/{key}");

        // Simple XOR encryption (production would use AEAD).
        let encrypted = self.xor_encrypt(value);
        self.secrets.insert(secret_key.clone(), encrypted);

        let secret_ref = SecretRef {
            namespace: namespace.to_string(),
            key: key.to_string(),
            expires_at: Utc::now() + Duration::hours(24),
            scoped_to,
        };
        self.secret_refs.insert(secret_key, secret_ref);

        #[cfg(feature = "exochain")]
        if let Some(ref cm) = self.chain_manager {
            cm.append(
                "config",
                crate::chain::EVENT_KIND_CONFIG_SECRET_SET,
                Some(serde_json::json!({
                    "namespace": namespace,
                    "key": key,
                })),
            );
        }

        Ok(())
    }

    /// Retrieve a secret (decrypted). Checks PID authorization and expiry.
    pub fn get_secret(
        &self,
        namespace: &str,
        key: &str,
        requester_pid: Pid,
    ) -> Result<Vec<u8>, KernelError> {
        let secret_key = format!("{namespace}/{key}");

        let secret_ref = self
            .secret_refs
            .get(&secret_key)
            .ok_or_else(|| KernelError::Service("secret not found".into()))?;

        // Check authorization.
        if !secret_ref.scoped_to.is_empty() && !secret_ref.scoped_to.contains(&requester_pid) {
            return Err(KernelError::CapabilityDenied {
                pid: requester_pid,
                action: "read_secret".into(),
                reason: format!(
                    "PID {} not authorized for secret {secret_key}",
                    requester_pid
                ),
            });
        }

        // Check expiry.
        if Utc::now() > secret_ref.expires_at {
            return Err(KernelError::Service("secret expired".into()));
        }

        let encrypted = self
            .secrets
            .get(&secret_key)
            .ok_or_else(|| KernelError::Service("secret data missing".into()))?;

        Ok(self.xor_decrypt(&encrypted))
    }

    /// Simple XOR encryption with the key (for testing; production uses AEAD).
    fn xor_encrypt(&self, data: &[u8]) -> Vec<u8> {
        data.iter()
            .enumerate()
            .map(|(i, b)| b ^ self.encryption_key[i % 32])
            .collect()
    }

    /// Decrypt XOR-encrypted data.
    fn xor_decrypt(&self, data: &[u8]) -> Vec<u8> {
        // XOR is symmetric.
        self.xor_encrypt(data)
    }

    /// Get the change log (for auditing).
    pub fn change_log(&self) -> Vec<ConfigChange> {
        self.change_log
            .read()
            .map(|l| l.clone())
            .unwrap_or_default()
    }

    /// Total number of config sets performed.
    pub fn set_count(&self) -> u64 {
        self.set_count.load(Ordering::Relaxed)
    }
}

#[async_trait]
impl SystemService for ConfigService {
    fn name(&self) -> &str {
        "config-service"
    }

    fn service_type(&self) -> ServiceType {
        ServiceType::Core
    }

    async fn start(&self) -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
        info!("config service started");
        Ok(())
    }

    async fn stop(&self) -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
        info!(
            configs = self.configs.len(),
            secrets = self.secrets.len(),
            "config service stopped"
        );
        Ok(())
    }

    async fn health_check(&self) -> HealthStatus {
        HealthStatus::Healthy
    }
}

// ── Tests ─────────────────────────────────────────────────────────────────

#[cfg(test)]
mod tests {
    use super::*;

    fn pid(n: u64) -> Pid {
        n
    }

    #[test]
    fn set_and_get_config() {
        let svc = ConfigService::new_default();
        svc.set("app", "timeout", serde_json::json!(30), pid(1))
            .unwrap();
        let val = svc.get("app", "timeout").unwrap();
        assert_eq!(val, serde_json::json!(30));
    }

    #[test]
    fn get_nonexistent_returns_none() {
        let svc = ConfigService::new_default();
        assert!(svc.get("app", "missing").is_none());
    }

    #[test]
    fn delete_config() {
        let svc = ConfigService::new_default();
        svc.set("app", "key", serde_json::json!("val"), pid(1))
            .unwrap();
        svc.delete("app", "key", pid(1)).unwrap();
        assert!(svc.get("app", "key").is_none());
    }

    #[test]
    fn list_keys_in_namespace() {
        let svc = ConfigService::new_default();
        svc.set("ns", "a", serde_json::json!(1), pid(1)).unwrap();
        svc.set("ns", "b", serde_json::json!(2), pid(1)).unwrap();
        svc.set("other", "c", serde_json::json!(3), pid(1)).unwrap();
        let mut keys = svc.list_keys("ns");
        keys.sort();
        assert_eq!(keys, vec!["a", "b"]);
    }

    #[test]
    fn config_change_notification() {
        let svc = ConfigService::new_default();
        let sub = svc.subscribe("watch");
        svc.set("watch", "flag", serde_json::json!(true), pid(1))
            .unwrap();
        let changes = sub.read().unwrap();
        assert_eq!(changes.len(), 1);
        assert_eq!(changes[0].key, "flag");
        assert_eq!(changes[0].new_value, Some(serde_json::json!(true)));
    }

    #[test]
    fn config_change_includes_old_value() {
        let svc = ConfigService::new_default();
        let sub = svc.subscribe("ver");
        svc.set("ver", "v", serde_json::json!(1), pid(1)).unwrap();
        svc.set("ver", "v", serde_json::json!(2), pid(1)).unwrap();
        let changes = sub.read().unwrap();
        assert_eq!(changes.len(), 2);
        assert_eq!(changes[1].old_value, Some(serde_json::json!(1)));
        assert_eq!(changes[1].new_value, Some(serde_json::json!(2)));
    }

    #[test]
    fn secret_set_and_get() {
        let key = [0xAB; 32];
        let svc = ConfigService::new(key);
        svc.set_secret("creds", "api_key", b"secret123", vec![pid(1)])
            .unwrap();
        let val = svc.get_secret("creds", "api_key", pid(1)).unwrap();
        assert_eq!(val, b"secret123");
    }

    #[test]
    fn secret_encrypted_at_rest() {
        let key = [0xAB; 32];
        let svc = ConfigService::new(key);
        svc.set_secret("creds", "pass", b"plaintext", vec![pid(1)])
            .unwrap();
        // Verify stored data is not plaintext.
        let stored = svc.secrets.get("creds/pass").unwrap();
        assert_ne!(stored.as_slice(), b"plaintext");
    }

    #[test]
    fn unauthorized_pid_cannot_read_secret() {
        let svc = ConfigService::new_default();
        svc.set_secret("creds", "key", b"val", vec![pid(1)])
            .unwrap();
        let result = svc.get_secret("creds", "key", pid(99));
        assert!(result.is_err());
        let err = result.unwrap_err().to_string();
        assert!(
            err.contains("denied") || err.contains("authorized"),
            "got: {err}"
        );
    }

    #[test]
    fn empty_scope_allows_any_pid() {
        let svc = ConfigService::new_default();
        svc.set_secret("open", "key", b"val", vec![]).unwrap();
        let val = svc.get_secret("open", "key", pid(42)).unwrap();
        assert_eq!(val, b"val");
    }

    #[test]
    fn change_log_recorded() {
        let svc = ConfigService::new_default();
        svc.set("ns", "k", serde_json::json!("v"), pid(1)).unwrap();
        let log = svc.change_log();
        assert_eq!(log.len(), 1);
        assert_eq!(log[0].namespace, "ns");
    }

    #[tokio::test]
    async fn system_service_impl() {
        let svc = ConfigService::new_default();
        assert_eq!(svc.name(), "config-service");
        assert_eq!(svc.service_type(), ServiceType::Core);
        svc.start().await.unwrap();
        assert_eq!(svc.health_check().await, HealthStatus::Healthy);
        svc.stop().await.unwrap();
    }

    // ── Typed config value tests ─────────────────────────────────

    #[test]
    fn typed_set_get_roundtrip() {
        let svc = ConfigService::new_default();
        svc.set_typed("app", "name", ConfigValue::Text("myapp".into()), pid(1))
            .unwrap();
        let entry = svc.get_typed("app", "name").unwrap();
        assert_eq!(entry.value, ConfigValue::Text("myapp".into()));
        assert_eq!(entry.namespace, "app");
        assert_eq!(entry.key, "name");
    }

    #[test]
    fn typed_get_nonexistent_returns_none() {
        let svc = ConfigService::new_default();
        assert!(svc.get_typed("app", "missing").is_none());
    }

    #[test]
    fn typed_list_returns_all_in_namespace() {
        let svc = ConfigService::new_default();
        svc.set_typed("db", "host", ConfigValue::Text("localhost".into()), pid(1))
            .unwrap();
        svc.set_typed("db", "port", ConfigValue::Integer(5432), pid(1))
            .unwrap();
        svc.set_typed("cache", "ttl", ConfigValue::Integer(60), pid(1))
            .unwrap();

        let mut entries = svc.list("db");
        entries.sort_by(|a, b| a.key.cmp(&b.key));
        assert_eq!(entries.len(), 2);
        assert_eq!(entries[0].key, "host");
        assert_eq!(entries[1].key, "port");
    }

    #[test]
    fn typed_delete_removes_entry() {
        let svc = ConfigService::new_default();
        svc.set_typed("ns", "k", ConfigValue::Boolean(true), pid(1))
            .unwrap();
        assert!(svc.delete_typed("ns", "k", pid(1)).unwrap());
        assert!(svc.get_typed("ns", "k").is_none());
        // Second delete returns false.
        assert!(!svc.delete_typed("ns", "k", pid(1)).unwrap());
    }

    #[test]
    fn typed_subscribe_receives_change_notification() {
        let svc = ConfigService::new_default();
        let sub = svc.subscribe("typed-ns");
        svc.set_typed("typed-ns", "flag", ConfigValue::Boolean(true), pid(1))
            .unwrap();
        let changes = sub.read().unwrap();
        assert_eq!(changes.len(), 1);
        assert_eq!(changes[0].key, "flag");
        assert_eq!(changes[0].new_value, Some(serde_json::json!(true)));
    }

    #[test]
    fn typed_set_updates_existing_value() {
        let svc = ConfigService::new_default();
        svc.set_typed("app", "level", ConfigValue::Integer(1), pid(1))
            .unwrap();
        svc.set_typed("app", "level", ConfigValue::Integer(2), pid(1))
            .unwrap();
        let entry = svc.get_typed("app", "level").unwrap();
        assert_eq!(entry.value, ConfigValue::Integer(2));
    }

    #[test]
    fn typed_namespace_isolation() {
        let svc = ConfigService::new_default();
        svc.set_typed("alpha", "key", ConfigValue::Text("a".into()), pid(1))
            .unwrap();
        svc.set_typed("beta", "key", ConfigValue::Text("b".into()), pid(1))
            .unwrap();

        let a = svc.get_typed("alpha", "key").unwrap();
        let b = svc.get_typed("beta", "key").unwrap();
        assert_eq!(a.value, ConfigValue::Text("a".into()));
        assert_eq!(b.value, ConfigValue::Text("b".into()));

        // list returns only matching namespace.
        assert_eq!(svc.list("alpha").len(), 1);
        assert_eq!(svc.list("beta").len(), 1);
        assert_eq!(svc.list("gamma").len(), 0);
    }

    #[test]
    fn typed_all_value_variants() {
        let svc = ConfigService::new_default();

        svc.set_typed("t", "text", ConfigValue::Text("hello".into()), pid(1))
            .unwrap();
        svc.set_typed("t", "int", ConfigValue::Integer(42), pid(1))
            .unwrap();
        svc.set_typed("t", "float", ConfigValue::Float(2.5), pid(1))
            .unwrap();
        svc.set_typed("t", "bool", ConfigValue::Boolean(false), pid(1))
            .unwrap();
        svc.set_typed(
            "t",
            "json",
            ConfigValue::Json(serde_json::json!({"a": 1})),
            pid(1),
        )
        .unwrap();

        assert_eq!(
            svc.get_typed("t", "text").unwrap().value,
            ConfigValue::Text("hello".into())
        );
        assert_eq!(
            svc.get_typed("t", "int").unwrap().value,
            ConfigValue::Integer(42)
        );
        assert_eq!(
            svc.get_typed("t", "float").unwrap().value,
            ConfigValue::Float(2.5)
        );
        assert_eq!(
            svc.get_typed("t", "bool").unwrap().value,
            ConfigValue::Boolean(false)
        );
        assert_eq!(
            svc.get_typed("t", "json").unwrap().value,
            ConfigValue::Json(serde_json::json!({"a": 1}))
        );
    }
}