clawft-types 0.6.4

Core types for the clawft AI assistant framework
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
//! Kernel configuration types.
//!
//! These types are defined in `clawft-types` so they can be embedded
//! in the root [`Config`](super::Config) without creating a circular
//! dependency with `clawft-kernel`.

use serde::{Deserialize, Serialize};

/// Default maximum number of concurrent processes.
fn default_max_processes() -> u32 {
    64
}

/// Default health check interval in seconds.
fn default_health_check_interval_secs() -> u64 {
    30
}

/// Kernel is enabled by default.
fn default_enabled() -> bool {
    true
}

/// Cluster networking configuration for distributed WeftOS nodes.
///
/// Controls the ruvector-powered clustering layer that coordinates
/// native nodes. Browser/edge nodes join via WebSocket to a
/// coordinator and do not need this configuration.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ClusterNetworkConfig {
    /// Number of replica copies for each shard (default: 3).
    #[serde(default = "default_replication_factor", alias = "replicationFactor")]
    pub replication_factor: usize,

    /// Total number of shards in the cluster (default: 64).
    #[serde(default = "default_shard_count", alias = "shardCount")]
    pub shard_count: u32,

    /// Interval between heartbeat checks in seconds (default: 5).
    #[serde(
        default = "default_cluster_heartbeat",
        alias = "heartbeatIntervalSecs"
    )]
    pub heartbeat_interval_secs: u64,

    /// Timeout before marking a node offline in seconds (default: 30).
    #[serde(default = "default_node_timeout", alias = "nodeTimeoutSecs")]
    pub node_timeout_secs: u64,

    /// Whether to enable DAG-based consensus (default: true).
    #[serde(default = "default_enable_consensus", alias = "enableConsensus")]
    pub enable_consensus: bool,

    /// Minimum nodes required for quorum (default: 2).
    #[serde(default = "default_min_quorum", alias = "minQuorumSize")]
    pub min_quorum_size: usize,

    /// Seed node addresses for discovery (coordinator addresses).
    #[serde(default, alias = "seedNodes")]
    pub seed_nodes: Vec<String>,

    /// Human-readable display name for this node.
    #[serde(default, alias = "nodeName")]
    pub node_name: Option<String>,
}

fn default_replication_factor() -> usize {
    3
}
fn default_shard_count() -> u32 {
    64
}
fn default_cluster_heartbeat() -> u64 {
    5
}
fn default_node_timeout() -> u64 {
    30
}
fn default_enable_consensus() -> bool {
    true
}
fn default_min_quorum() -> usize {
    2
}

impl Default for ClusterNetworkConfig {
    fn default() -> Self {
        Self {
            replication_factor: default_replication_factor(),
            shard_count: default_shard_count(),
            heartbeat_interval_secs: default_cluster_heartbeat(),
            node_timeout_secs: default_node_timeout(),
            enable_consensus: default_enable_consensus(),
            min_quorum_size: default_min_quorum(),
            seed_nodes: Vec::new(),
            node_name: None,
        }
    }
}

/// Kernel subsystem configuration.
///
/// Embedded in the root `Config` under the `kernel` key. All fields
/// have sensible defaults so that existing configuration files parse
/// without errors.
///
/// # Example JSON
///
/// ```json
/// {
///   "kernel": {
///     "enabled": false,
///     "max_processes": 128,
///     "health_check_interval_secs": 15
///   }
/// }
/// ```
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct KernelConfig {
    /// Whether the kernel subsystem is enabled.
    ///
    /// When `false`, kernel subsystems do not activate unless explicitly
    /// invoked via `weave kernel` CLI commands. Defaults to `true`.
    #[serde(default = "default_enabled")]
    pub enabled: bool,

    /// Maximum number of concurrent processes in the process table.
    #[serde(default = "default_max_processes", alias = "maxProcesses")]
    pub max_processes: u32,

    /// Interval (in seconds) between periodic health checks.
    #[serde(
        default = "default_health_check_interval_secs",
        alias = "healthCheckIntervalSecs"
    )]
    pub health_check_interval_secs: u64,

    /// Cluster networking configuration (native coordinator nodes).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub cluster: Option<ClusterNetworkConfig>,

    /// Local chain configuration (exochain feature).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub chain: Option<ChainConfig>,

    /// Resource tree configuration (exochain feature).
    #[serde(default, skip_serializing_if = "Option::is_none", alias = "resourceTree")]
    pub resource_tree: Option<ResourceTreeConfig>,

    /// Vector search backend configuration (ECC feature).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub vector: Option<VectorConfig>,

    /// Per-user profile namespace configuration.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub profiles: Option<ProfilesConfig>,

    /// Time-windowed pairing configuration.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub pairing: Option<PairingConfig>,
}

impl Default for KernelConfig {
    fn default() -> Self {
        Self {
            enabled: true,
            max_processes: default_max_processes(),
            health_check_interval_secs: default_health_check_interval_secs(),
            cluster: None,
            chain: None,
            resource_tree: None,
            vector: None,
            profiles: None,
            pairing: None,
        }
    }
}

// ── Profile namespace configuration ─────────────────────────────────────

/// Per-user profile namespace configuration.
///
/// When enabled, each profile gets its own isolated vector storage
/// directory under `storage_path`.
///
/// # Example TOML
///
/// ```toml
/// [kernel.profiles]
/// enabled = true
/// storage_path = ".weftos/profiles"
/// default_profile = "default"
/// ```
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ProfilesConfig {
    /// Whether profile namespaces are enabled.
    #[serde(default = "default_profiles_enabled")]
    pub enabled: bool,

    /// Base directory for profile data.
    #[serde(default = "default_profiles_storage_path")]
    pub storage_path: String,

    /// Default profile to activate on boot.
    #[serde(default = "default_profile_name")]
    pub default_profile: String,
}

fn default_profiles_enabled() -> bool {
    true
}

fn default_profiles_storage_path() -> String {
    ".weftos/profiles".to_owned()
}

fn default_profile_name() -> String {
    "default".to_owned()
}

impl Default for ProfilesConfig {
    fn default() -> Self {
        Self {
            enabled: default_profiles_enabled(),
            storage_path: default_profiles_storage_path(),
            default_profile: default_profile_name(),
        }
    }
}

// ── Time-windowed pairing configuration ─────────────────────────────────

/// Configuration for time-windowed mesh pairing.
///
/// Controls where paired host data is persisted and the default
/// enrollment window duration.
///
/// # Example TOML
///
/// ```toml
/// [kernel.pairing]
/// persist_path = ".weftos/runtime/paired_hosts.json"
/// default_window_secs = 30
/// ```
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct PairingConfig {
    /// Path to the paired hosts persistence file.
    #[serde(default = "default_pairing_persist_path")]
    pub persist_path: String,

    /// Default enrollment window duration in seconds.
    #[serde(default = "default_pairing_window_secs")]
    pub default_window_secs: u64,
}

fn default_pairing_persist_path() -> String {
    ".weftos/runtime/paired_hosts.json".to_owned()
}

fn default_pairing_window_secs() -> u64 {
    30
}

impl Default for PairingConfig {
    fn default() -> Self {
        Self {
            persist_path: default_pairing_persist_path(),
            default_window_secs: default_pairing_window_secs(),
        }
    }
}

/// Local chain configuration.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ChainConfig {
    /// Whether the local chain is enabled.
    #[serde(default = "default_true")]
    pub enabled: bool,

    /// Maximum events before auto-checkpoint.
    #[serde(default = "default_checkpoint_interval", alias = "checkpointInterval")]
    pub checkpoint_interval: u64,

    /// Chain ID (0 = local node chain).
    #[serde(default)]
    pub chain_id: u32,

    /// Path to the chain checkpoint file for persistence across restarts.
    /// If `None`, defaults to `~/.clawft/chain/local.json`.
    #[serde(
        default,
        skip_serializing_if = "Option::is_none",
        alias = "checkpointPath"
    )]
    pub checkpoint_path: Option<String>,
}

fn default_true() -> bool {
    true
}
fn default_checkpoint_interval() -> u64 {
    1000
}

impl Default for ChainConfig {
    fn default() -> Self {
        Self {
            enabled: true,
            checkpoint_interval: default_checkpoint_interval(),
            chain_id: 0,
            checkpoint_path: None,
        }
    }
}

impl ChainConfig {
    /// Returns the effective checkpoint path.
    ///
    /// If `checkpoint_path` is set, returns it. Otherwise falls back to
    /// `~/.clawft/chain.json` (requires the `native` feature for `dirs`).
    pub fn effective_checkpoint_path(&self) -> Option<String> {
        if self.checkpoint_path.is_some() {
            return self.checkpoint_path.clone();
        }
        #[cfg(feature = "native")]
        {
            dirs::home_dir().map(|h| {
                h.join(".clawft")
                    .join("chain.json")
                    .to_string_lossy()
                    .into_owned()
            })
        }
        #[cfg(not(feature = "native"))]
        {
            None
        }
    }
}

/// Resource tree configuration.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ResourceTreeConfig {
    /// Whether the resource tree is enabled.
    #[serde(default = "default_true_rt")]
    pub enabled: bool,

    /// Path to checkpoint file (None = in-memory only).
    #[serde(
        default,
        skip_serializing_if = "Option::is_none",
        alias = "checkpointPath"
    )]
    pub checkpoint_path: Option<String>,
}

fn default_true_rt() -> bool {
    true
}

impl Default for ResourceTreeConfig {
    fn default() -> Self {
        Self {
            enabled: true,
            checkpoint_path: None,
        }
    }
}

// ── Vector search backend configuration ──────────────────────────────────

/// Which vector search backend to use.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Default)]
#[serde(rename_all = "lowercase")]
pub enum VectorBackendKind {
    /// In-memory HNSW (default, fast, suitable for <1M vectors).
    #[default]
    Hnsw,
    /// SSD-backed DiskANN (large scale, 1M+ vectors).
    DiskAnn,
    /// Hot HNSW cache + cold DiskANN store.
    Hybrid,
}

/// HNSW-specific vector configuration.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct VectorHnswConfig {
    /// ef_construction parameter for index building.
    #[serde(default = "default_ef_construction")]
    pub ef_construction: usize,

    /// Number of bi-directional links per node (M parameter).
    #[serde(default = "default_m")]
    pub m: usize,

    /// Maximum number of elements the index can hold.
    #[serde(default = "default_max_elements")]
    pub max_elements: usize,
}

fn default_ef_construction() -> usize {
    200
}
fn default_m() -> usize {
    16
}
fn default_max_elements() -> usize {
    100_000
}

impl Default for VectorHnswConfig {
    fn default() -> Self {
        Self {
            ef_construction: default_ef_construction(),
            m: default_m(),
            max_elements: default_max_elements(),
        }
    }
}

/// DiskANN-specific vector configuration.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct VectorDiskAnnConfig {
    /// Maximum number of points the index can hold.
    #[serde(default = "default_diskann_max_points")]
    pub max_points: usize,

    /// Vector dimensionality.
    #[serde(default = "default_diskann_dimensions")]
    pub dimensions: usize,

    /// Number of neighbors per node in the DiskANN graph.
    #[serde(default = "default_diskann_num_neighbors")]
    pub num_neighbors: usize,

    /// Size of the search candidate list.
    #[serde(default = "default_diskann_search_list_size")]
    pub search_list_size: usize,

    /// Directory path for SSD-backed data files.
    #[serde(default = "default_diskann_data_path")]
    pub data_path: String,

    /// Whether to use product quantization for compression.
    #[serde(default = "default_diskann_use_pq")]
    pub use_pq: bool,

    /// Number of PQ sub-quantizer chunks.
    #[serde(default = "default_diskann_pq_num_chunks")]
    pub pq_num_chunks: usize,
}

fn default_diskann_max_points() -> usize {
    10_000_000
}
fn default_diskann_dimensions() -> usize {
    384
}
fn default_diskann_num_neighbors() -> usize {
    64
}
fn default_diskann_search_list_size() -> usize {
    100
}
fn default_diskann_data_path() -> String {
    ".weftos/diskann".to_owned()
}
fn default_diskann_use_pq() -> bool {
    true
}
fn default_diskann_pq_num_chunks() -> usize {
    48
}

impl Default for VectorDiskAnnConfig {
    fn default() -> Self {
        Self {
            max_points: default_diskann_max_points(),
            dimensions: default_diskann_dimensions(),
            num_neighbors: default_diskann_num_neighbors(),
            search_list_size: default_diskann_search_list_size(),
            data_path: default_diskann_data_path(),
            use_pq: default_diskann_use_pq(),
            pq_num_chunks: default_diskann_pq_num_chunks(),
        }
    }
}

/// Eviction policy for the hybrid backend's hot tier.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Default)]
#[serde(rename_all = "lowercase")]
pub enum VectorEvictionPolicy {
    /// Least Recently Used.
    #[default]
    Lru,
}

/// Hybrid backend-specific configuration.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct VectorHybridConfig {
    /// Maximum number of vectors in the hot (HNSW) tier.
    #[serde(default = "default_hybrid_hot_capacity")]
    pub hot_capacity: usize,

    /// Access count threshold before a cold vector is promoted to hot.
    #[serde(default = "default_hybrid_promotion_threshold")]
    pub promotion_threshold: u32,

    /// Eviction policy when the hot tier is full.
    #[serde(default)]
    pub eviction_policy: VectorEvictionPolicy,
}

fn default_hybrid_hot_capacity() -> usize {
    50_000
}
fn default_hybrid_promotion_threshold() -> u32 {
    3
}

impl Default for VectorHybridConfig {
    fn default() -> Self {
        Self {
            hot_capacity: default_hybrid_hot_capacity(),
            promotion_threshold: default_hybrid_promotion_threshold(),
            eviction_policy: VectorEvictionPolicy::default(),
        }
    }
}

/// Unified vector search backend configuration.
///
/// Controls which backend is used for the ECC cognitive substrate's
/// vector search layer.
///
/// # Example TOML
///
/// ```toml
/// [kernel.vector]
/// backend = "hybrid"
///
/// [kernel.vector.hnsw]
/// ef_construction = 200
/// max_elements = 100000
///
/// [kernel.vector.diskann]
/// max_points = 10000000
/// data_path = ".weftos/diskann"
///
/// [kernel.vector.hybrid]
/// hot_capacity = 50000
/// promotion_threshold = 3
/// ```
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct VectorConfig {
    /// Which backend to use.
    #[serde(default)]
    pub backend: VectorBackendKind,

    /// HNSW-specific settings.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub hnsw: Option<VectorHnswConfig>,

    /// DiskANN-specific settings.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub diskann: Option<VectorDiskAnnConfig>,

    /// Hybrid-specific settings.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub hybrid: Option<VectorHybridConfig>,
}

impl Default for VectorConfig {
    fn default() -> Self {
        Self {
            backend: VectorBackendKind::default(),
            hnsw: None,
            diskann: None,
            hybrid: None,
        }
    }
}

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

    #[test]
    fn default_kernel_config() {
        let cfg = KernelConfig::default();
        assert!(cfg.enabled);
        assert_eq!(cfg.max_processes, 64);
        assert_eq!(cfg.health_check_interval_secs, 30);
    }

    #[test]
    fn deserialize_empty() {
        let cfg: KernelConfig = serde_json::from_str("{}").unwrap();
        assert!(cfg.enabled);
        assert_eq!(cfg.max_processes, 64);
    }

    #[test]
    fn deserialize_camel_case() {
        let json = r#"{"maxProcesses": 128, "healthCheckIntervalSecs": 15}"#;
        let cfg: KernelConfig = serde_json::from_str(json).unwrap();
        assert_eq!(cfg.max_processes, 128);
        assert_eq!(cfg.health_check_interval_secs, 15);
    }

    #[test]
    fn serde_roundtrip() {
        let cfg = KernelConfig {
            enabled: true,
            max_processes: 256,
            health_check_interval_secs: 10,
            cluster: None,
            chain: None,
            resource_tree: None,
            vector: None,
            profiles: None,
            pairing: None,
        };
        let json = serde_json::to_string(&cfg).unwrap();
        let restored: KernelConfig = serde_json::from_str(&json).unwrap();
        assert_eq!(restored.enabled, cfg.enabled);
        assert_eq!(restored.max_processes, cfg.max_processes);
    }

    #[test]
    fn profiles_config_defaults() {
        let cfg = ProfilesConfig::default();
        assert!(cfg.enabled);
        assert_eq!(cfg.storage_path, ".weftos/profiles");
        assert_eq!(cfg.default_profile, "default");
    }

    #[test]
    fn profiles_config_deserialize() {
        let json = r#"{"enabled": false, "storage_path": "/tmp/profiles", "default_profile": "admin"}"#;
        let cfg: ProfilesConfig = serde_json::from_str(json).unwrap();
        assert!(!cfg.enabled);
        assert_eq!(cfg.storage_path, "/tmp/profiles");
        assert_eq!(cfg.default_profile, "admin");
    }

    #[test]
    fn pairing_config_defaults() {
        let cfg = PairingConfig::default();
        assert_eq!(cfg.persist_path, ".weftos/runtime/paired_hosts.json");
        assert_eq!(cfg.default_window_secs, 30);
    }

    #[test]
    fn pairing_config_deserialize() {
        let json = r#"{"persist_path": "/opt/pairing.json", "default_window_secs": 60}"#;
        let cfg: PairingConfig = serde_json::from_str(json).unwrap();
        assert_eq!(cfg.persist_path, "/opt/pairing.json");
        assert_eq!(cfg.default_window_secs, 60);
    }

    #[test]
    fn kernel_config_with_profiles_and_pairing() {
        let json = r#"{"profiles": {"enabled": true}, "pairing": {"default_window_secs": 45}}"#;
        let cfg: KernelConfig = serde_json::from_str(json).unwrap();
        assert!(cfg.profiles.is_some());
        assert!(cfg.profiles.unwrap().enabled);
        assert!(cfg.pairing.is_some());
        assert_eq!(cfg.pairing.unwrap().default_window_secs, 45);
    }

    #[test]
    fn vector_config_defaults() {
        let cfg = VectorConfig::default();
        assert_eq!(cfg.backend, VectorBackendKind::Hnsw);
        assert!(cfg.hnsw.is_none());
        assert!(cfg.diskann.is_none());
        assert!(cfg.hybrid.is_none());
    }

    #[test]
    fn vector_config_deserialize_hybrid() {
        let json = r#"{"backend": "hybrid", "hybrid": {"hot_capacity": 1000, "promotion_threshold": 5}}"#;
        let cfg: VectorConfig = serde_json::from_str(json).unwrap();
        assert_eq!(cfg.backend, VectorBackendKind::Hybrid);
        let h = cfg.hybrid.unwrap();
        assert_eq!(h.hot_capacity, 1000);
        assert_eq!(h.promotion_threshold, 5);
    }

    #[test]
    fn vector_config_deserialize_diskann() {
        let json = r#"{"backend": "diskann", "diskann": {"max_points": 5000000}}"#;
        let cfg: VectorConfig = serde_json::from_str(json).unwrap();
        assert_eq!(cfg.backend, VectorBackendKind::DiskAnn);
        let d = cfg.diskann.unwrap();
        assert_eq!(d.max_points, 5_000_000);
    }

    #[test]
    fn kernel_config_with_vector() {
        let json = r#"{"vector": {"backend": "hnsw"}}"#;
        let cfg: KernelConfig = serde_json::from_str(json).unwrap();
        assert!(cfg.vector.is_some());
        assert_eq!(cfg.vector.unwrap().backend, VectorBackendKind::Hnsw);
    }
}