peat-protocol 0.9.0-rc.8

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
//! Command coordination and dissemination logic
//!
//! Manages command lifecycle: issuance, routing, acknowledgment, and status tracking.

use crate::command::conflict_resolver::{ConflictResolver, ConflictResult};
use crate::command::routing::{CommandRouter, TargetResolution};
use crate::command::timeout_manager::TimeoutManager;
use crate::command::CommandStorage;
use crate::Result;
use peat_schema::command::v1::{
    AckStatus, CommandAcknowledgment, CommandStatus, ConflictPolicy, HierarchicalCommand,
};
use std::collections::HashMap;
use std::sync::Arc;
use std::time::Duration;
use tokio::sync::RwLock;

/// Coordinates hierarchical command dissemination
pub struct CommandCoordinator {
    /// Node identifier
    node_id: String,

    /// Router for target resolution
    router: CommandRouter,

    /// Storage backend for command dissemination
    storage: Arc<dyn CommandStorage>,

    /// Active commands indexed by command_id (in-memory cache)
    active_commands: Arc<RwLock<HashMap<String, HierarchicalCommand>>>,

    /// Command acknowledgments indexed by (command_id, node_id) (in-memory cache)
    acknowledgments: Arc<RwLock<HashMap<(String, String), CommandAcknowledgment>>>,

    /// Command execution status (in-memory cache)
    command_status: Arc<RwLock<HashMap<String, CommandStatus>>>,

    /// Conflict resolution engine
    conflict_resolver: Arc<ConflictResolver>,

    /// Timeout management
    timeout_manager: Arc<TimeoutManager>,
}

impl CommandCoordinator {
    /// Create new command coordinator with storage backend
    pub fn new(
        squad_id: Option<String>,
        node_id: String,
        squad_members: Vec<String>,
        storage: Arc<dyn CommandStorage>,
    ) -> Self {
        let router = CommandRouter::new(node_id.clone(), squad_id, squad_members, None);

        Self {
            node_id,
            router,
            storage,
            active_commands: Arc::new(RwLock::new(HashMap::new())),
            acknowledgments: Arc::new(RwLock::new(HashMap::new())),
            command_status: Arc::new(RwLock::new(HashMap::new())),
            conflict_resolver: Arc::new(ConflictResolver::new()),
            timeout_manager: Arc::new(TimeoutManager::new()),
        }
    }

    /// Issue a command (originating from this node)
    pub async fn issue_command(&self, command: HierarchicalCommand) -> Result<()> {
        tracing::info!(
            "[{}] Issuing command: {} (priority: {})",
            self.node_id,
            command.command_id,
            command.priority
        );

        // 1. Check for conflicts
        let conflict_result = self.conflict_resolver.check_conflict(&command).await;
        if let ConflictResult::Conflict(existing) = conflict_result {
            let policy = ConflictPolicy::try_from(command.conflict_policy)
                .unwrap_or(ConflictPolicy::HighestPriorityWins);

            tracing::debug!(
                "[{}] Conflict detected for command {}, resolving with policy {:?}",
                self.node_id,
                command.command_id,
                policy
            );

            let mut all_commands = existing;
            all_commands.push(command.clone());

            let resolved = self.conflict_resolver.resolve(all_commands, policy)?;

            if resolved.command_id != command.command_id {
                tracing::warn!(
                    "[{}] Command {} rejected due to conflict (winner: {})",
                    self.node_id,
                    command.command_id,
                    resolved.command_id
                );
                return Err(crate::Error::Internal(
                    "Command rejected by conflict resolution policy".to_string(),
                ));
            }
        }

        // 2. Register for expiration tracking
        self.timeout_manager.register_expiration(&command).await?;

        // 3. Register with conflict resolver
        self.conflict_resolver.register_command(&command).await?;

        // 4. Store in active commands
        self.active_commands
            .write()
            .await
            .insert(command.command_id.clone(), command.clone());

        // 5. Create initial status
        let status = CommandStatus {
            command_id: command.command_id.clone(),
            state: 1, // PENDING
            acknowledgments: Vec::new(),
            last_updated: Some(peat_schema::common::v1::Timestamp {
                seconds: std::time::SystemTime::now()
                    .duration_since(std::time::UNIX_EPOCH)
                    .expect("system clock is before Unix epoch")
                    .as_secs(),
                nanos: 0,
            }),
        };

        self.command_status
            .write()
            .await
            .insert(command.command_id.clone(), status);

        // 6. Setup acknowledgment timeout if required
        if self.requires_acknowledgment(&command) {
            let targets = {
                let resolution = self.router.resolve_target(&command);
                self.router.get_routing_targets(&resolution)
            };

            if !targets.is_empty() {
                let ack_timeout = Duration::from_secs(30); // TODO: Make configurable
                self.timeout_manager
                    .register_ack_timeout(command.command_id.clone(), targets, ack_timeout)
                    .await?;
            }
        }

        // 7. Route command to targets
        self.route_command(&command).await?;

        Ok(())
    }

    /// Receive a command (from higher echelon)
    pub async fn receive_command(&self, command: HierarchicalCommand) -> Result<()> {
        tracing::info!(
            "[{}] Received command: {} from {}",
            self.node_id,
            command.command_id,
            command.originator_id
        );

        // Resolve target
        let resolution = self.router.resolve_target(&command);

        match resolution {
            TargetResolution::Self_ => {
                // Command targets this node - execute it
                self.execute_command(&command).await?;

                // Send acknowledgment if required
                if self.requires_acknowledgment(&command) {
                    self.send_acknowledgment(&command, AckStatus::AckReceived as i32)
                        .await?;
                }
            }

            TargetResolution::Subordinates(_) | TargetResolution::AllSquadMembers(_) => {
                // Command targets subordinates - route it
                self.route_command(&command).await?;
            }

            TargetResolution::NotApplicable => {
                tracing::debug!(
                    "[{}] Command {} not applicable to this node",
                    self.node_id,
                    command.command_id
                );
            }
        }

        Ok(())
    }

    /// Route command to subordinate nodes
    async fn route_command(&self, command: &HierarchicalCommand) -> Result<()> {
        let resolution = self.router.resolve_target(command);

        if !self.router.should_route(&resolution) {
            return Ok(());
        }

        let targets = self.router.get_routing_targets(&resolution);

        tracing::info!(
            "[{}] Routing command {} to {} nodes",
            self.node_id,
            command.command_id,
            targets.len()
        );

        // Publish command to storage for dissemination
        let doc_id = self.storage.publish_command(command).await?;

        tracing::debug!(
            "[{}] Published command {} to storage (doc_id: {})",
            self.node_id,
            command.command_id,
            doc_id
        );

        for target_id in &targets {
            tracing::debug!(
                "[{}] → Routing command {} to {}",
                self.node_id,
                command.command_id,
                target_id
            );
        }

        Ok(())
    }

    /// Execute a command locally
    async fn execute_command(&self, command: &HierarchicalCommand) -> Result<()> {
        tracing::info!(
            "[{}] Executing command: {}",
            self.node_id,
            command.command_id
        );

        // Update status to EXECUTING
        let mut status_map = self.command_status.write().await;
        if let Some(status) = status_map.get_mut(&command.command_id) {
            status.state = 2; // EXECUTING
        } else {
            status_map.insert(
                command.command_id.clone(),
                CommandStatus {
                    command_id: command.command_id.clone(),
                    state: 2, // EXECUTING
                    acknowledgments: Vec::new(),
                    last_updated: Some(peat_schema::common::v1::Timestamp {
                        seconds: std::time::SystemTime::now()
                            .duration_since(std::time::UNIX_EPOCH)
                            .expect("system clock is before Unix epoch")
                            .as_secs(),
                        nanos: 0,
                    }),
                },
            );
        }

        // TODO: Actual command execution logic based on command_type
        // For now, just mark as completed
        tokio::time::sleep(tokio::time::Duration::from_millis(100)).await;

        // Update status to COMPLETED
        if let Some(status) = status_map.get_mut(&command.command_id) {
            status.state = 3; // COMPLETED
        }

        tracing::info!(
            "[{}] ✓ Completed command: {}",
            self.node_id,
            command.command_id
        );

        Ok(())
    }

    /// Check if command requires acknowledgment
    fn requires_acknowledgment(&self, command: &HierarchicalCommand) -> bool {
        // Check acknowledgment_policy
        // 0 = UNSPECIFIED, 1 = NONE, 2 = RECEIVED_ONLY, 3 = COMPLETED_ONLY, 4 = BOTH
        command.acknowledgment_policy > 1
    }

    /// Send acknowledgment for a command
    async fn send_acknowledgment(&self, command: &HierarchicalCommand, status: i32) -> Result<()> {
        let ack = CommandAcknowledgment {
            command_id: command.command_id.clone(),
            node_id: self.node_id.clone(),
            status,
            reason: None,
            timestamp: Some(peat_schema::common::v1::Timestamp {
                seconds: std::time::SystemTime::now()
                    .duration_since(std::time::UNIX_EPOCH)
                    .expect("system clock is before Unix epoch")
                    .as_secs(),
                nanos: 0,
            }),
        };

        tracing::debug!(
            "[{}] Sending ACK for command {} with status {}",
            self.node_id,
            command.command_id,
            status
        );

        // Publish acknowledgment to storage
        let doc_id = self.storage.publish_acknowledgment(&ack).await?;

        tracing::debug!(
            "[{}] Published acknowledgment for command {} to storage (doc_id: {})",
            self.node_id,
            command.command_id,
            doc_id
        );

        // Store acknowledgment in local cache
        self.acknowledgments
            .write()
            .await
            .insert((command.command_id.clone(), self.node_id.clone()), ack);

        // Record acknowledgment in timeout manager
        let all_received = self
            .timeout_manager
            .record_ack(&command.command_id, &self.node_id)
            .await;

        if all_received {
            tracing::debug!(
                "[{}] All acknowledgments received for command {}",
                self.node_id,
                command.command_id
            );
            // Clean up timeout tracking
            self.timeout_manager
                .unregister_ack_timeout(&command.command_id)
                .await?;
        }

        Ok(())
    }

    /// Get command status
    pub async fn get_command_status(&self, command_id: &str) -> Option<CommandStatus> {
        self.command_status.read().await.get(command_id).cloned()
    }

    /// Get all acknowledgments for a command
    pub async fn get_command_acknowledgments(
        &self,
        command_id: &str,
    ) -> Vec<CommandAcknowledgment> {
        self.acknowledgments
            .read()
            .await
            .iter()
            .filter(|((cmd_id, _), _)| cmd_id == command_id)
            .map(|(_, ack)| ack.clone())
            .collect()
    }

    /// Check if command has been acknowledged by all targets
    pub async fn is_command_acknowledged(&self, command_id: &str) -> bool {
        let command = match self.active_commands.read().await.get(command_id) {
            Some(cmd) => cmd.clone(),
            None => return false,
        };

        let resolution = self.router.resolve_target(&command);
        let targets = self.router.get_routing_targets(&resolution);

        if targets.is_empty() {
            return true;
        }

        let acks = self.get_command_acknowledgments(command_id).await;
        let acked_nodes: std::collections::HashSet<String> =
            acks.iter().map(|a| a.node_id.clone()).collect();

        targets.iter().all(|t| acked_nodes.contains(t))
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::command::ObserverHandle;
    use peat_schema::command::v1::{command_target::Scope, CommandTarget};

    // Mock storage for unit tests
    struct MockStorage;

    #[async_trait::async_trait]
    impl CommandStorage for MockStorage {
        async fn publish_command(&self, _command: &HierarchicalCommand) -> crate::Result<String> {
            Ok("mock-doc-id".to_string())
        }

        async fn get_command(
            &self,
            _command_id: &str,
        ) -> crate::Result<Option<HierarchicalCommand>> {
            Ok(None)
        }

        async fn query_commands_by_target(
            &self,
            _target_id: &str,
        ) -> crate::Result<Vec<HierarchicalCommand>> {
            Ok(Vec::new())
        }

        async fn delete_command(&self, _command_id: &str) -> crate::Result<()> {
            Ok(())
        }

        async fn publish_acknowledgment(
            &self,
            _ack: &CommandAcknowledgment,
        ) -> crate::Result<String> {
            Ok("mock-ack-id".to_string())
        }

        async fn get_acknowledgments(
            &self,
            _command_id: &str,
        ) -> crate::Result<Vec<CommandAcknowledgment>> {
            Ok(Vec::new())
        }

        async fn update_command_status(&self, _status: &CommandStatus) -> crate::Result<()> {
            Ok(())
        }

        async fn get_command_status(
            &self,
            _command_id: &str,
        ) -> crate::Result<Option<CommandStatus>> {
            Ok(None)
        }

        async fn observe_commands(
            &self,
            _node_id: &str,
            _callback: Box<
                dyn Fn(
                        HierarchicalCommand,
                    )
                        -> std::pin::Pin<Box<dyn std::future::Future<Output = ()> + Send>>
                    + Send
                    + Sync,
            >,
        ) -> crate::Result<ObserverHandle> {
            Ok(ObserverHandle::new(()))
        }

        async fn observe_acknowledgments(
            &self,
            _issuer_id: &str,
            _callback: Box<
                dyn Fn(
                        CommandAcknowledgment,
                    )
                        -> std::pin::Pin<Box<dyn std::future::Future<Output = ()> + Send>>
                    + Send
                    + Sync,
            >,
        ) -> crate::Result<ObserverHandle> {
            Ok(ObserverHandle::new(()))
        }
    }

    #[tokio::test]
    async fn test_issue_command() {
        let storage = Arc::new(MockStorage);
        let coordinator = CommandCoordinator::new(
            Some("squad-alpha".to_string()),
            "node-1".to_string(),
            vec!["node-1".to_string(), "node-2".to_string()],
            storage,
        );

        let command = HierarchicalCommand {
            command_id: "cmd-001".to_string(),
            originator_id: "node-1".to_string(),
            target: Some(CommandTarget {
                scope: Scope::Individual as i32,
                target_ids: vec!["node-2".to_string()],
            }),
            priority: 5,
            acknowledgment_policy: 2, // RECEIVED_ONLY
            ..Default::default()
        };

        coordinator.issue_command(command.clone()).await.unwrap();

        let status = coordinator.get_command_status("cmd-001").await;
        assert!(status.is_some());
        assert_eq!(status.unwrap().state, 1); // PENDING
    }

    #[tokio::test]
    async fn test_receive_and_execute_command() {
        let storage = Arc::new(MockStorage);
        let coordinator = CommandCoordinator::new(
            Some("squad-alpha".to_string()),
            "node-1".to_string(),
            vec!["node-1".to_string(), "node-2".to_string()],
            storage,
        );

        let command = HierarchicalCommand {
            command_id: "cmd-002".to_string(),
            originator_id: "node-leader".to_string(),
            target: Some(CommandTarget {
                scope: Scope::Individual as i32,
                target_ids: vec!["node-1".to_string()],
            }),
            priority: 5,
            acknowledgment_policy: 4, // BOTH
            ..Default::default()
        };

        coordinator.receive_command(command).await.unwrap();

        // Wait for execution
        tokio::time::sleep(tokio::time::Duration::from_millis(200)).await;

        let status = coordinator.get_command_status("cmd-002").await;
        assert!(status.is_some());
        assert_eq!(status.unwrap().state, 3); // COMPLETED
    }

    #[tokio::test]
    async fn test_acknowledgment_tracking() {
        let storage = Arc::new(MockStorage);
        let coordinator = CommandCoordinator::new(
            Some("squad-alpha".to_string()),
            "node-1".to_string(),
            vec!["node-1".to_string(), "node-2".to_string()],
            storage,
        );

        let command = HierarchicalCommand {
            command_id: "cmd-003".to_string(),
            originator_id: "node-1".to_string(),
            target: Some(CommandTarget {
                scope: Scope::Individual as i32,
                target_ids: vec!["node-1".to_string()],
            }),
            priority: 5,
            acknowledgment_policy: 2, // RECEIVED_ONLY
            ..Default::default()
        };

        coordinator.receive_command(command).await.unwrap();

        let acks = coordinator.get_command_acknowledgments("cmd-003").await;
        assert!(!acks.is_empty());
        assert_eq!(acks[0].node_id, "node-1");
    }
}