peat-protocol 0.9.0-rc.6

Peat Coordination Protocol — hierarchical capability composition over CRDTs for heterogeneous mesh networks
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
//! Capability-based queries for platform and squad discovery
//!
//! Implements the capability query system for finding nodes and squads
//! based on required capabilities during the bootstrap phase.
//!
//! # Architecture
//!
//! The capability query system allows C2 or nodes to discover other entities
//! based on capability requirements:
//!
//! ## Query Types
//!
//! - **Type-based**: Find entities with specific capability types (Sensor, Compute, etc.)
//! - **Confidence-based**: Filter by minimum confidence thresholds
//! - **Combination queries**: Require multiple capabilities (AND logic)
//! - **Ranked results**: Score and rank matches by relevance
//!
//! ## Use Cases
//!
//! - **Mission planning**: Find nodes with required sensor capabilities
//! - **Cell formation**: Form cells with complementary capabilities
//! - **Resource discovery**: Locate available compute/comms resources
//! - **Redundancy**: Find backup nodes with similar capabilities
//!
//! ## Example
//!
//! ```rust,ignore
//! // Find nodes with sensor AND communication capabilities
//! let query = CapabilityQuery::builder()
//!     .require_type(CapabilityType::Sensor)
//!     .require_type(CapabilityType::Communication)
//!     .min_confidence(0.8)
//!     .build();
//!
//! let matches = engine.query_platforms(&query, &nodes)?;
//! ```

use crate::models::{cell::CellState, node::NodeConfig, Capability, CapabilityExt, CapabilityType};
use serde::{Deserialize, Serialize};
use std::collections::HashMap;

/// Capability query for finding nodes or squads
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct CapabilityQuery {
    /// Required capability types (AND logic - all must be present)
    pub required_types: Vec<CapabilityType>,
    /// Optional capability types (OR logic - any can be present for bonus score)
    pub optional_types: Vec<CapabilityType>,
    /// Minimum confidence threshold (0.0 - 1.0)
    pub min_confidence: f32,
    /// Minimum number of total capabilities
    pub min_capability_count: Option<usize>,
    /// Maximum results to return
    pub limit: Option<usize>,
}

impl CapabilityQuery {
    /// Create a new query builder
    pub fn builder() -> CapabilityQueryBuilder {
        CapabilityQueryBuilder::new()
    }

    /// Check if a set of capabilities satisfies this query
    pub fn matches(&self, capabilities: &[Capability]) -> bool {
        // Check minimum capability count
        if let Some(min_count) = self.min_capability_count {
            if capabilities.len() < min_count {
                return false;
            }
        }

        // Check all required types are present with sufficient confidence
        for required_type in &self.required_types {
            let has_type = capabilities.iter().any(|cap| {
                cap.get_capability_type() == *required_type && cap.confidence >= self.min_confidence
            });

            if !has_type {
                return false;
            }
        }

        true
    }

    /// Calculate a relevance score for a set of capabilities (0.0 - 1.0)
    ///
    /// Score components:
    /// - Required types: 0.6 weight (normalized by count)
    /// - Optional types: 0.3 weight (normalized by count)
    /// - Average confidence: 0.1 weight
    pub fn score(&self, capabilities: &[Capability]) -> f32 {
        if capabilities.is_empty() {
            return 0.0;
        }

        let mut score = 0.0;

        // Required types score (60% weight)
        if !self.required_types.is_empty() {
            let required_score: f32 = self
                .required_types
                .iter()
                .map(|req_type| {
                    capabilities
                        .iter()
                        .filter(|cap| cap.get_capability_type() == *req_type)
                        .map(|cap| cap.confidence)
                        .max_by(|a, b| a.partial_cmp(b).unwrap())
                        .unwrap_or(0.0)
                })
                .sum::<f32>()
                / self.required_types.len() as f32;

            score += required_score * 0.6;
        } else {
            // If no required types, give full weight
            score += 0.6;
        }

        // Optional types score (30% weight)
        if !self.optional_types.is_empty() {
            let optional_score: f32 = self
                .optional_types
                .iter()
                .map(|opt_type| {
                    capabilities
                        .iter()
                        .filter(|cap| cap.get_capability_type() == *opt_type)
                        .map(|cap| cap.confidence)
                        .max_by(|a, b| a.partial_cmp(b).unwrap())
                        .unwrap_or(0.0)
                })
                .sum::<f32>()
                / self.optional_types.len() as f32;

            score += optional_score * 0.3;
        } else {
            score += 0.3;
        }

        // Average confidence score (10% weight)
        let avg_confidence: f32 =
            capabilities.iter().map(|cap| cap.confidence).sum::<f32>() / capabilities.len() as f32;
        score += avg_confidence * 0.1;

        score.clamp(0.0, 1.0)
    }
}

/// Builder for creating capability queries
#[derive(Debug, Default)]
pub struct CapabilityQueryBuilder {
    required_types: Vec<CapabilityType>,
    optional_types: Vec<CapabilityType>,
    min_confidence: f32,
    min_capability_count: Option<usize>,
    limit: Option<usize>,
}

impl CapabilityQueryBuilder {
    /// Create a new query builder
    pub fn new() -> Self {
        Self {
            min_confidence: 0.0,
            ..Default::default()
        }
    }

    /// Add a required capability type
    pub fn require_type(mut self, capability_type: CapabilityType) -> Self {
        self.required_types.push(capability_type);
        self
    }

    /// Add an optional capability type
    pub fn prefer_type(mut self, capability_type: CapabilityType) -> Self {
        self.optional_types.push(capability_type);
        self
    }

    /// Set minimum confidence threshold
    pub fn min_confidence(mut self, min_confidence: f32) -> Self {
        self.min_confidence = min_confidence.clamp(0.0, 1.0);
        self
    }

    /// Set minimum capability count
    pub fn min_capability_count(mut self, count: usize) -> Self {
        self.min_capability_count = Some(count);
        self
    }

    /// Set maximum results limit
    pub fn limit(mut self, limit: usize) -> Self {
        self.limit = Some(limit);
        self
    }

    /// Build the query
    pub fn build(self) -> CapabilityQuery {
        CapabilityQuery {
            required_types: self.required_types,
            optional_types: self.optional_types,
            min_confidence: self.min_confidence,
            min_capability_count: self.min_capability_count,
            limit: self.limit,
        }
    }
}

/// Result of a capability query with score
#[derive(Debug, Clone)]
pub struct QueryMatch<T> {
    /// The matched entity (platform or squad)
    pub entity: T,
    /// Relevance score (0.0 - 1.0)
    pub score: f32,
}

/// Capability query engine for finding nodes and squads
pub struct CapabilityQueryEngine;

impl CapabilityQueryEngine {
    /// Create a new query engine
    pub fn new() -> Self {
        Self
    }

    /// Query nodes by capabilities
    pub fn query_platforms(
        &self,
        query: &CapabilityQuery,
        nodes: &[NodeConfig],
    ) -> Vec<QueryMatch<NodeConfig>> {
        let mut matches: Vec<QueryMatch<NodeConfig>> = nodes
            .iter()
            .filter(|node| query.matches(&node.capabilities))
            .map(|node| QueryMatch {
                score: query.score(&node.capabilities),
                entity: node.clone(),
            })
            .collect();

        // Sort by score descending
        matches.sort_by(|a, b| b.score.partial_cmp(&a.score).unwrap());

        // Apply limit if specified
        if let Some(limit) = query.limit {
            matches.truncate(limit);
        }

        matches
    }

    /// Query cells by capabilities
    pub fn query_squads(
        &self,
        query: &CapabilityQuery,
        squads: &[CellState],
    ) -> Vec<QueryMatch<CellState>> {
        let mut matches: Vec<QueryMatch<CellState>> = squads
            .iter()
            .filter(|squad| query.matches(&squad.capabilities))
            .map(|squad| QueryMatch {
                score: query.score(&squad.capabilities),
                entity: squad.clone(),
            })
            .collect();

        // Sort by score descending
        matches.sort_by(|a, b| b.score.partial_cmp(&a.score).unwrap());

        // Apply limit if specified
        if let Some(limit) = query.limit {
            matches.truncate(limit);
        }

        matches
    }

    /// Get capability statistics for a set of platforms
    pub fn platform_capability_stats(
        &self,
        nodes: &[NodeConfig],
    ) -> HashMap<CapabilityType, CapabilityStats> {
        let mut stats: HashMap<CapabilityType, Vec<f32>> = HashMap::new();

        for node in nodes {
            for capability in &node.capabilities {
                stats
                    .entry(capability.get_capability_type())
                    .or_default()
                    .push(capability.confidence);
            }
        }

        stats
            .into_iter()
            .map(|(cap_type, confidences)| {
                (cap_type, CapabilityStats::from_confidences(&confidences))
            })
            .collect()
    }
}

impl Default for CapabilityQueryEngine {
    fn default() -> Self {
        Self::new()
    }
}

/// Statistical summary of capability distribution
#[derive(Debug, Clone)]
pub struct CapabilityStats {
    /// Total count of this capability type
    pub count: usize,
    /// Average confidence
    pub avg_confidence: f32,
    /// Minimum confidence
    pub min_confidence: f32,
    /// Maximum confidence
    pub max_confidence: f32,
}

impl CapabilityStats {
    /// Calculate statistics from confidence values
    pub fn from_confidences(confidences: &[f32]) -> Self {
        let count = confidences.len();
        let sum: f32 = confidences.iter().sum();
        let avg_confidence = if count > 0 { sum / count as f32 } else { 0.0 };

        let min_confidence = confidences
            .iter()
            .copied()
            .min_by(|a, b| a.partial_cmp(b).unwrap())
            .unwrap_or(0.0);

        let max_confidence = confidences
            .iter()
            .copied()
            .max_by(|a, b| a.partial_cmp(b).unwrap())
            .unwrap_or(0.0);

        Self {
            count,
            avg_confidence,
            min_confidence,
            max_confidence,
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::models::{CapabilityExt, NodeConfigExt};

    fn create_test_capability(id: &str, cap_type: CapabilityType, confidence: f32) -> Capability {
        Capability::new(
            id.to_string(),
            format!("{:?} capability", cap_type),
            cap_type,
            confidence,
        )
    }

    fn create_test_platform(
        id: &str,
        platform_type: &str,
        capabilities: Vec<Capability>,
    ) -> NodeConfig {
        let mut platform = NodeConfig::new(platform_type.to_string());
        platform.id = id.to_string();
        for cap in capabilities {
            platform.add_capability(cap);
        }
        platform
    }

    #[test]
    fn test_query_builder() {
        let query = CapabilityQuery::builder()
            .require_type(CapabilityType::Sensor)
            .require_type(CapabilityType::Communication)
            .min_confidence(0.8)
            .limit(10)
            .build();

        assert_eq!(query.required_types.len(), 2);
        assert_eq!(query.min_confidence, 0.8);
        assert_eq!(query.limit, Some(10));
    }

    #[test]
    fn test_query_matches_required_types() {
        let query = CapabilityQuery::builder()
            .require_type(CapabilityType::Sensor)
            .require_type(CapabilityType::Communication)
            .min_confidence(0.7)
            .build();

        // Node with both required capabilities
        let caps1 = vec![
            create_test_capability("sensor1", CapabilityType::Sensor, 0.9),
            create_test_capability("comms1", CapabilityType::Communication, 0.8),
        ];
        assert!(query.matches(&caps1));

        // Node missing one required capability
        let caps2 = vec![create_test_capability(
            "sensor1",
            CapabilityType::Sensor,
            0.9,
        )];
        assert!(!query.matches(&caps2));

        // Node with low confidence
        let caps3 = vec![
            create_test_capability("sensor1", CapabilityType::Sensor, 0.9),
            create_test_capability("comms1", CapabilityType::Communication, 0.5),
        ];
        assert!(!query.matches(&caps3));
    }

    #[test]
    fn test_query_matches_min_capability_count() {
        let query = CapabilityQuery::builder().min_capability_count(3).build();

        let caps1 = vec![
            create_test_capability("sensor1", CapabilityType::Sensor, 0.9),
            create_test_capability("comms1", CapabilityType::Communication, 0.8),
            create_test_capability("compute1", CapabilityType::Compute, 0.7),
        ];
        assert!(query.matches(&caps1));

        let caps2 = vec![
            create_test_capability("sensor1", CapabilityType::Sensor, 0.9),
            create_test_capability("comms1", CapabilityType::Communication, 0.8),
        ];
        assert!(!query.matches(&caps2));
    }

    #[test]
    fn test_query_scoring() {
        let query = CapabilityQuery::builder()
            .require_type(CapabilityType::Sensor)
            .prefer_type(CapabilityType::Communication)
            .build();

        // Node with both required and optional
        let caps1 = vec![
            create_test_capability("sensor1", CapabilityType::Sensor, 0.9),
            create_test_capability("comms1", CapabilityType::Communication, 0.8),
        ];
        let score1 = query.score(&caps1);

        // Node with only required
        let caps2 = vec![create_test_capability(
            "sensor1",
            CapabilityType::Sensor,
            0.9,
        )];
        let score2 = query.score(&caps2);

        // First platform should score higher
        assert!(score1 > score2);
        assert!(score1 <= 1.0);
        assert!(score2 > 0.0);
    }

    #[test]
    fn test_query_engine_platforms() {
        let engine = CapabilityQueryEngine::new();

        let nodes = vec![
            create_test_platform(
                "platform1",
                "UAV",
                vec![
                    create_test_capability("sensor1", CapabilityType::Sensor, 0.9),
                    create_test_capability("comms1", CapabilityType::Communication, 0.8),
                ],
            ),
            create_test_platform(
                "platform2",
                "UAV",
                vec![create_test_capability(
                    "sensor2",
                    CapabilityType::Sensor,
                    0.7,
                )],
            ),
            create_test_platform(
                "platform3",
                "UAV",
                vec![
                    create_test_capability("sensor3", CapabilityType::Sensor, 0.95),
                    create_test_capability("comms3", CapabilityType::Communication, 0.9),
                    create_test_capability("compute3", CapabilityType::Compute, 0.85),
                ],
            ),
        ];

        let query = CapabilityQuery::builder()
            .require_type(CapabilityType::Sensor)
            .prefer_type(CapabilityType::Communication)
            .min_confidence(0.7)
            .build();

        let matches = engine.query_platforms(&query, &nodes);

        // All nodes have sensor capability
        assert_eq!(matches.len(), 3);

        // platform3 should score highest (has all capabilities with high confidence)
        assert_eq!(matches[0].entity.id, "platform3");
        assert!(matches[0].score > matches[1].score);
    }

    #[test]
    fn test_query_engine_limit() {
        let engine = CapabilityQueryEngine::new();

        let nodes = vec![
            create_test_platform(
                "platform1",
                "UAV",
                vec![create_test_capability(
                    "sensor1",
                    CapabilityType::Sensor,
                    0.9,
                )],
            ),
            create_test_platform(
                "platform2",
                "UAV",
                vec![create_test_capability(
                    "sensor2",
                    CapabilityType::Sensor,
                    0.8,
                )],
            ),
            create_test_platform(
                "platform3",
                "UAV",
                vec![create_test_capability(
                    "sensor3",
                    CapabilityType::Sensor,
                    0.7,
                )],
            ),
        ];

        let query = CapabilityQuery::builder()
            .require_type(CapabilityType::Sensor)
            .limit(2)
            .build();

        let matches = engine.query_platforms(&query, &nodes);

        assert_eq!(matches.len(), 2);
        // Should return top 2 by score
        assert!(matches[0].score >= matches[1].score);
    }

    #[test]
    fn test_capability_stats() {
        let engine = CapabilityQueryEngine::new();

        let nodes = vec![
            create_test_platform(
                "platform1",
                "UAV",
                vec![
                    create_test_capability("sensor1", CapabilityType::Sensor, 0.9),
                    create_test_capability("comms1", CapabilityType::Communication, 0.8),
                ],
            ),
            create_test_platform(
                "platform2",
                "UAV",
                vec![
                    create_test_capability("sensor2", CapabilityType::Sensor, 0.7),
                    create_test_capability("compute2", CapabilityType::Compute, 0.85),
                ],
            ),
        ];

        let stats = engine.platform_capability_stats(&nodes);

        assert_eq!(stats.len(), 3);
        assert_eq!(stats.get(&CapabilityType::Sensor).unwrap().count, 2);
        assert_eq!(stats.get(&CapabilityType::Communication).unwrap().count, 1);
        assert_eq!(stats.get(&CapabilityType::Compute).unwrap().count, 1);

        let sensor_stats = stats.get(&CapabilityType::Sensor).unwrap();
        assert_eq!(sensor_stats.min_confidence, 0.7);
        assert_eq!(sensor_stats.max_confidence, 0.9);
        assert!((sensor_stats.avg_confidence - 0.8).abs() < 0.01);
    }

    #[test]
    fn test_empty_query() {
        let query = CapabilityQuery::builder().build();

        let caps = vec![
            create_test_capability("sensor1", CapabilityType::Sensor, 0.9),
            create_test_capability("comms1", CapabilityType::Communication, 0.8),
        ];

        // Empty query should match any platform
        assert!(query.matches(&caps));
        // Score should be non-zero
        assert!(query.score(&caps) > 0.0);
    }
}