aof-core 0.4.0-beta

Core types, traits, and abstractions for AOF 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
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
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
//! AgentFleet - Multi-agent coordination and orchestration
//!
//! AgentFleet provides Kubernetes-style configuration for managing groups
//! of agents with different coordination modes:
//! - Hierarchical: Manager agent coordinates workers
//! - Peer: All agents coordinate as equals
//! - Swarm: Dynamic self-organizing coordination
//! - Pipeline: Sequential handoff between agents
//! - Tiered: Tier-based parallel execution with consensus (for multi-model RCA)

use serde::{Deserialize, Serialize};
use std::collections::HashMap;

/// AgentFleet configuration (K8s-style)
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct AgentFleet {
    /// API version (e.g., "aof.dev/v1")
    #[serde(rename = "apiVersion")]
    pub api_version: String,

    /// Resource kind (always "AgentFleet")
    pub kind: String,

    /// Fleet metadata
    pub metadata: FleetMetadata,

    /// Fleet specification
    pub spec: FleetSpec,
}

/// Fleet metadata
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct FleetMetadata {
    /// Fleet name
    pub name: String,

    /// Namespace
    #[serde(default)]
    pub namespace: Option<String>,

    /// Labels for filtering
    #[serde(default)]
    pub labels: HashMap<String, String>,

    /// Annotations for metadata
    #[serde(default)]
    pub annotations: HashMap<String, String>,
}

/// Fleet specification
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct FleetSpec {
    /// Agent definitions in the fleet
    pub agents: Vec<FleetAgent>,

    /// Coordination configuration
    #[serde(default)]
    pub coordination: CoordinationConfig,

    /// Shared resources across agents
    #[serde(default)]
    pub shared: Option<SharedResources>,

    /// Communication patterns
    #[serde(default)]
    pub communication: Option<CommunicationConfig>,

    /// Scaling configuration
    #[serde(default)]
    pub scaling: Option<ScalingConfig>,
}

/// Agent definition within a fleet
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct FleetAgent {
    /// Agent name (unique within fleet)
    pub name: String,

    /// Path to agent configuration file
    #[serde(default)]
    pub config: Option<String>,

    /// Inline agent configuration
    #[serde(default)]
    pub spec: Option<FleetAgentSpec>,

    /// Number of agent replicas
    #[serde(default = "default_replicas")]
    pub replicas: u32,

    /// Role in the fleet
    #[serde(default)]
    pub role: AgentRole,

    /// Agent-specific labels
    #[serde(default)]
    pub labels: HashMap<String, String>,

    /// Tier number for tiered coordination mode (1 = first tier, 2 = second, etc.)
    /// Tier 1 agents run first, their results feed into tier 2, etc.
    /// If not specified, defaults to 1.
    #[serde(default)]
    pub tier: Option<u32>,

    /// Weight for weighted consensus voting (default: 1.0)
    #[serde(default)]
    pub weight: Option<f32>,
}

fn default_replicas() -> u32 {
    1
}

/// Inline agent specification (simplified)
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct FleetAgentSpec {
    /// Model to use
    pub model: String,

    /// Agent instructions/system prompt
    #[serde(default)]
    pub instructions: Option<String>,

    /// Tools available to this agent
    /// Supports both simple strings and qualified specs
    #[serde(default)]
    pub tools: Vec<crate::agent::ToolSpec>,

    /// MCP servers for this agent
    #[serde(default)]
    pub mcp_servers: Vec<crate::McpServerConfig>,

    /// Maximum iterations
    #[serde(default)]
    pub max_iterations: Option<u32>,

    /// Temperature for model
    #[serde(default)]
    pub temperature: Option<f32>,
}

/// Agent role within the fleet
#[derive(Debug, Clone, Copy, Serialize, Deserialize, Default, PartialEq, Eq)]
#[serde(rename_all = "lowercase")]
pub enum AgentRole {
    /// Regular worker agent
    #[default]
    Worker,
    /// Manager/coordinator agent
    Manager,
    /// Specialist agent for specific tasks
    Specialist,
    /// Validator/reviewer agent
    Validator,
}

/// Coordination configuration
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct CoordinationConfig {
    /// Coordination mode
    #[serde(default)]
    pub mode: CoordinationMode,

    /// Manager agent name (for hierarchical mode)
    #[serde(default)]
    pub manager: Option<String>,

    /// Task distribution strategy
    #[serde(default)]
    pub distribution: TaskDistribution,

    /// Consensus configuration (for peer/tiered mode)
    #[serde(default)]
    pub consensus: Option<ConsensusConfig>,

    /// Result aggregation strategy (for peer mode with complementary specialists)
    /// When set, peer mode will collect and merge ALL agent results instead of using consensus.
    /// Use this when agents provide complementary information (e.g., security + quality reviews)
    /// rather than competing perspectives.
    #[serde(default)]
    pub aggregation: Option<FinalAggregation>,

    /// Tiered execution configuration (for tiered mode)
    #[serde(default)]
    pub tiered: Option<TieredConfig>,

    /// Deep execution configuration (for deep mode)
    #[serde(default)]
    pub deep: Option<DeepConfig>,
}

/// Configuration for tiered coordination mode
#[derive(Debug, Clone, Serialize, Deserialize, Default)]
pub struct TieredConfig {
    /// Per-tier consensus configuration
    /// Key: tier number (as string), Value: consensus config for that tier
    #[serde(default)]
    pub tier_consensus: HashMap<String, ConsensusConfig>,

    /// Whether to pass all tier results to next tier or just the consensus result
    #[serde(default)]
    pub pass_all_results: bool,

    /// Final tier aggregation strategy
    #[serde(default)]
    pub final_aggregation: FinalAggregation,
}

/// Configuration for deep coordination mode (iterative planning + execution)
///
/// # Example
/// ```yaml
/// coordination:
///   mode: deep
///   deep:
///     max_iterations: 10
///     planning: true
///     memory: true
/// ```
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct DeepConfig {
    /// Maximum iterations before stopping (safety limit)
    #[serde(default = "default_max_iterations")]
    pub max_iterations: u32,

    /// Enable planning phase (LLM generates investigation steps)
    #[serde(default = "default_true")]
    pub planning: bool,

    /// Enable memory persistence across iterations
    #[serde(default = "default_true")]
    pub memory: bool,

    /// Model to use for planning (defaults to fleet's model)
    #[serde(default)]
    pub planner_model: Option<String>,

    /// System prompt for the planning phase
    #[serde(default)]
    pub planner_prompt: Option<String>,

    /// System prompt for the synthesis phase
    #[serde(default)]
    pub synthesizer_prompt: Option<String>,
}

fn default_max_iterations() -> u32 {
    10
}

fn default_true() -> bool {
    true
}

impl Default for DeepConfig {
    fn default() -> Self {
        Self {
            max_iterations: default_max_iterations(),
            planning: default_true(),
            memory: default_true(),
            planner_model: None,
            planner_prompt: None,
            synthesizer_prompt: None,
        }
    }
}

/// How to aggregate results from the final tier
#[derive(Debug, Clone, Copy, Serialize, Deserialize, Default, PartialEq, Eq)]
#[serde(rename_all = "snake_case")]
pub enum FinalAggregation {
    /// Use consensus algorithm to pick best result
    #[default]
    Consensus,
    /// Merge all results into combined output
    Merge,
    /// Use manager agent to synthesize final result
    ManagerSynthesis,
}

impl Default for CoordinationConfig {
    fn default() -> Self {
        Self {
            mode: CoordinationMode::Peer,
            manager: None,
            distribution: TaskDistribution::RoundRobin,
            consensus: None,
            aggregation: None,
            tiered: None,
            deep: None,
        }
    }
}

/// Coordination mode for the fleet
///
/// Choose the mode that best fits your use case:
/// - **Peer**: All agents work on the same task in parallel. Results can be combined via
///   consensus (competing perspectives) or aggregation (complementary specialists).
///   Best for code review, multi-expert analysis, RCA.
/// - **Hierarchical**: Manager delegates to workers, aggregates results. Best for
///   complex multi-step tasks with oversight.
/// - **Pipeline**: Sequential handoff between agents. Best for workflows where
///   each stage transforms data for the next.
/// - **Swarm**: Self-organizing dynamic coordination. Best for large-scale
///   parallel processing with adaptive load balancing.
/// - **Tiered**: Tier-based parallel execution with consensus. Best for multi-model
///   RCA where cheap data-collectors feed reasoning models.
/// - **Deep**: Iterative planning and execution loop. Best for complex investigations
///   that require multi-step reasoning with re-planning based on findings.
#[derive(Debug, Clone, Copy, Serialize, Deserialize, Default, PartialEq, Eq)]
#[serde(rename_all = "lowercase")]
pub enum CoordinationMode {
    /// Hierarchical: Manager coordinates workers
    Hierarchical,
    /// Peer-to-peer: Agents coordinate as equals
    #[default]
    Peer,
    /// Swarm: Self-organizing dynamic coordination
    Swarm,
    /// Pipeline: Sequential handoff between agents
    Pipeline,
    /// Tiered: Tier-based parallel execution with consensus
    /// Agents are grouped by tier (e.g., tier 1 = data collectors, tier 2 = reasoners)
    /// Each tier runs in parallel, results flow to next tier
    Tiered,
    /// Deep: Iterative planning and execution loop (like Claude Code)
    /// Plans investigation steps, executes iteratively, re-plans based on findings
    Deep,
}

/// Task distribution strategy
#[derive(Debug, Clone, Copy, Serialize, Deserialize, Default, PartialEq, Eq)]
#[serde(rename_all = "kebab-case")]
pub enum TaskDistribution {
    /// Round-robin distribution
    #[default]
    RoundRobin,
    /// Least-loaded agent gets the task
    LeastLoaded,
    /// Random distribution
    Random,
    /// Skill-based routing (agents with matching skills)
    SkillBased,
    /// Sticky routing (same task types go to same agent)
    Sticky,
}

/// Consensus configuration for peer/tiered coordination
///
/// # Example
/// ```yaml
/// consensus:
///   algorithm: weighted
///   min_votes: 2
///   timeout_ms: 60000
///   allow_partial: true
///   weights:
///     senior-reviewer: 2.0
///     junior-reviewer: 1.0
///   min_confidence: 0.7
/// ```
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ConsensusConfig {
    /// Consensus algorithm
    #[serde(default)]
    pub algorithm: ConsensusAlgorithm,

    /// Minimum votes required for consensus
    #[serde(default)]
    pub min_votes: Option<u32>,

    /// Timeout for reaching consensus (milliseconds)
    #[serde(default)]
    pub timeout_ms: Option<u64>,

    /// Allow partial consensus if timeout reached
    #[serde(default)]
    pub allow_partial: bool,

    /// Per-agent weights for weighted voting
    /// Key: agent name, Value: weight (default 1.0)
    #[serde(default)]
    pub weights: HashMap<String, f32>,

    /// Minimum confidence threshold (0.0-1.0)
    /// Below this threshold, result is flagged for human review
    #[serde(default)]
    pub min_confidence: Option<f32>,
}

/// Consensus algorithm type
///
/// Choose based on your requirements:
/// - **Majority**: >50% agreement wins. Fast, tolerates outliers.
/// - **Unanimous**: 100% agreement required. High confidence, may timeout.
/// - **Weighted**: Per-agent weights (senior reviewers count more). Balanced expertise.
/// - **FirstWins**: First response wins. Fastest, no consensus overhead.
/// - **HumanReview**: Flags for human operator decision. High-stakes scenarios.
#[derive(Debug, Clone, Copy, Serialize, Deserialize, Default, PartialEq, Eq)]
#[serde(rename_all = "snake_case")]
pub enum ConsensusAlgorithm {
    /// Simple majority voting (>50% agreement)
    #[default]
    Majority,
    /// Unanimous agreement required (100%)
    Unanimous,
    /// Weighted voting based on agent weights
    Weighted,
    /// First response wins (no consensus)
    FirstWins,
    /// Flags result for human operator review
    HumanReview,
}

/// Shared resources configuration
#[derive(Debug, Clone, Serialize, Deserialize, Default)]
pub struct SharedResources {
    /// Shared memory configuration
    #[serde(default)]
    pub memory: Option<SharedMemoryConfig>,

    /// Shared tools available to all agents
    #[serde(default)]
    pub tools: Vec<SharedToolConfig>,

    /// Shared knowledge base
    #[serde(default)]
    pub knowledge: Option<SharedKnowledgeConfig>,
}

/// Shared memory configuration
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SharedMemoryConfig {
    /// Memory backend type
    #[serde(rename = "type")]
    pub memory_type: SharedMemoryType,

    /// Connection URL
    #[serde(default)]
    pub url: Option<String>,

    /// Memory namespace/prefix
    #[serde(default)]
    pub namespace: Option<String>,

    /// TTL for memory entries (seconds)
    #[serde(default)]
    pub ttl: Option<u64>,
}

/// Shared memory backend type
#[derive(Debug, Clone, Copy, Serialize, Deserialize, Default, PartialEq, Eq)]
#[serde(rename_all = "lowercase")]
pub enum SharedMemoryType {
    /// In-memory (single process)
    #[default]
    InMemory,
    /// Redis backend
    Redis,
    /// SQLite backend
    Sqlite,
    /// PostgreSQL backend
    Postgres,
}

/// Shared tool configuration
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SharedToolConfig {
    /// MCP server reference
    #[serde(rename = "mcp-server")]
    pub mcp_server: Option<String>,

    /// Built-in tool name
    pub tool: Option<String>,

    /// Tool configuration
    #[serde(default)]
    pub config: HashMap<String, serde_json::Value>,
}

/// Shared knowledge configuration
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SharedKnowledgeConfig {
    /// Knowledge base type
    #[serde(rename = "type")]
    pub kb_type: String,

    /// Source path or URL
    pub source: String,

    /// Additional configuration
    #[serde(default)]
    pub config: HashMap<String, serde_json::Value>,
}

/// Communication configuration
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct CommunicationConfig {
    /// Message passing pattern
    #[serde(default)]
    pub pattern: MessagePattern,

    /// Message queue configuration
    #[serde(default)]
    pub queue: Option<QueueConfig>,

    /// Broadcast configuration
    #[serde(default)]
    pub broadcast: Option<BroadcastConfig>,
}

/// Message passing pattern
#[derive(Debug, Clone, Copy, Serialize, Deserialize, Default, PartialEq, Eq)]
#[serde(rename_all = "kebab-case")]
pub enum MessagePattern {
    /// Direct point-to-point messaging
    #[default]
    Direct,
    /// Publish-subscribe pattern
    PubSub,
    /// Request-reply pattern
    RequestReply,
    /// Broadcast to all agents
    Broadcast,
}

/// Queue configuration
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct QueueConfig {
    /// Queue type
    #[serde(rename = "type")]
    pub queue_type: String,

    /// Connection URL
    pub url: String,

    /// Queue name
    pub name: String,
}

/// Broadcast configuration
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct BroadcastConfig {
    /// Broadcast channel name
    pub channel: String,

    /// Include sender in broadcast
    #[serde(default)]
    pub include_sender: bool,
}

/// Scaling configuration
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ScalingConfig {
    /// Minimum replicas
    #[serde(default)]
    pub min_replicas: Option<u32>,

    /// Maximum replicas
    #[serde(default)]
    pub max_replicas: Option<u32>,

    /// Auto-scaling enabled
    #[serde(default)]
    pub auto_scale: bool,

    /// Scaling metrics
    #[serde(default)]
    pub metrics: Vec<ScalingMetric>,
}

/// Scaling metric
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ScalingMetric {
    /// Metric name
    pub name: String,

    /// Target value
    pub target: f64,

    /// Metric type
    #[serde(rename = "type")]
    pub metric_type: String,
}

/// Fleet runtime state
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct FleetState {
    /// Fleet name
    pub fleet_name: String,

    /// Fleet status
    pub status: FleetStatus,

    /// Agent instances
    pub agents: HashMap<String, AgentInstanceState>,

    /// Active tasks
    pub active_tasks: Vec<FleetTask>,

    /// Completed tasks
    pub completed_tasks: Vec<FleetTask>,

    /// Fleet metrics
    pub metrics: FleetMetrics,

    /// Start time
    pub started_at: Option<chrono::DateTime<chrono::Utc>>,
}

impl FleetState {
    /// Create new fleet state
    pub fn new(fleet_name: &str) -> Self {
        Self {
            fleet_name: fleet_name.to_string(),
            status: FleetStatus::Initializing,
            agents: HashMap::new(),
            active_tasks: Vec::new(),
            completed_tasks: Vec::new(),
            metrics: FleetMetrics::default(),
            started_at: None,
        }
    }
}

/// Fleet status
#[derive(Debug, Clone, Copy, Serialize, Deserialize, Default, PartialEq, Eq)]
#[serde(rename_all = "lowercase")]
pub enum FleetStatus {
    /// Fleet is initializing
    #[default]
    Initializing,
    /// Fleet is ready and idle
    Ready,
    /// Fleet is actively processing tasks
    Active,
    /// Fleet is paused
    Paused,
    /// Fleet has failed
    Failed,
    /// Fleet is shutting down
    ShuttingDown,
}

/// Agent instance state
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct AgentInstanceState {
    /// Instance ID
    pub instance_id: String,

    /// Agent name from fleet config
    pub agent_name: String,

    /// Replica index
    pub replica_index: u32,

    /// Instance status
    pub status: AgentInstanceStatus,

    /// Current task (if any)
    pub current_task: Option<String>,

    /// Tasks processed count
    pub tasks_processed: u64,

    /// Last activity timestamp
    pub last_activity: Option<chrono::DateTime<chrono::Utc>>,
}

/// Agent instance status
#[derive(Debug, Clone, Copy, Serialize, Deserialize, Default, PartialEq, Eq)]
#[serde(rename_all = "lowercase")]
pub enum AgentInstanceStatus {
    /// Instance is starting
    #[default]
    Starting,
    /// Instance is idle and ready
    Idle,
    /// Instance is processing a task
    Busy,
    /// Instance has failed
    Failed,
    /// Instance is stopped
    Stopped,
}

/// Fleet task
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct FleetTask {
    /// Task ID
    pub task_id: String,

    /// Task input
    pub input: serde_json::Value,

    /// Assigned agent instance
    pub assigned_to: Option<String>,

    /// Task status
    pub status: FleetTaskStatus,

    /// Task result (if completed)
    pub result: Option<serde_json::Value>,

    /// Error (if failed)
    pub error: Option<String>,

    /// Created timestamp
    pub created_at: chrono::DateTime<chrono::Utc>,

    /// Started timestamp
    pub started_at: Option<chrono::DateTime<chrono::Utc>>,

    /// Completed timestamp
    pub completed_at: Option<chrono::DateTime<chrono::Utc>>,
}

/// Fleet task status
#[derive(Debug, Clone, Copy, Serialize, Deserialize, Default, PartialEq, Eq)]
#[serde(rename_all = "lowercase")]
pub enum FleetTaskStatus {
    /// Task is pending assignment
    #[default]
    Pending,
    /// Task is assigned to an agent
    Assigned,
    /// Task is being processed
    Running,
    /// Task completed successfully
    Completed,
    /// Task failed
    Failed,
    /// Task was cancelled
    Cancelled,
}

/// Fleet metrics
#[derive(Debug, Clone, Serialize, Deserialize, Default)]
pub struct FleetMetrics {
    /// Total tasks submitted
    pub total_tasks: u64,

    /// Completed tasks
    pub completed_tasks: u64,

    /// Failed tasks
    pub failed_tasks: u64,

    /// Average task duration (ms)
    pub avg_task_duration_ms: f64,

    /// Active agent count
    pub active_agents: u32,

    /// Total agent count
    pub total_agents: u32,

    /// Messages exchanged between agents
    pub messages_exchanged: u64,

    /// Consensus rounds (for peer mode)
    pub consensus_rounds: u64,
}

impl AgentFleet {
    /// Load fleet from YAML file
    pub fn from_yaml(yaml: &str) -> Result<Self, crate::AofError> {
        serde_yaml::from_str(yaml).map_err(|e| crate::AofError::config(format!("Failed to parse fleet YAML: {}", e)))
    }

    /// Load fleet from file
    pub fn from_file(path: &str) -> Result<Self, crate::AofError> {
        let content = std::fs::read_to_string(path)
            .map_err(|e| crate::AofError::config(format!("Failed to read fleet file: {}", e)))?;
        Self::from_yaml(&content)
    }

    /// Get agent by name
    pub fn get_agent(&self, name: &str) -> Option<&FleetAgent> {
        self.spec.agents.iter().find(|a| a.name == name)
    }

    /// Get all agents with a specific role
    pub fn get_agents_by_role(&self, role: AgentRole) -> Vec<&FleetAgent> {
        self.spec.agents.iter().filter(|a| a.role == role).collect()
    }

    /// Get the manager agent (for hierarchical mode)
    pub fn get_manager(&self) -> Option<&FleetAgent> {
        if let Some(ref manager_name) = self.spec.coordination.manager {
            self.get_agent(manager_name)
        } else {
            self.get_agents_by_role(AgentRole::Manager).first().copied()
        }
    }

    /// Total replica count across all agents
    pub fn total_replicas(&self) -> u32 {
        self.spec.agents.iter().map(|a| a.replicas).sum()
    }

    /// Validate fleet configuration
    pub fn validate(&self) -> Result<(), crate::AofError> {
        // Check for duplicate agent names
        let mut names = std::collections::HashSet::new();
        for agent in &self.spec.agents {
            if !names.insert(&agent.name) {
                return Err(crate::AofError::config(format!(
                    "Duplicate agent name in fleet: {}",
                    agent.name
                )));
            }
        }

        // Validate hierarchical mode has a manager
        if self.spec.coordination.mode == CoordinationMode::Hierarchical {
            if self.get_manager().is_none() {
                return Err(crate::AofError::config(
                    "Hierarchical mode requires a manager agent".to_string(),
                ));
            }
        }

        // Validate tiered mode has agents with tier assignments
        if self.spec.coordination.mode == CoordinationMode::Tiered {
            let tiers = self.get_tiers();
            if tiers.is_empty() {
                return Err(crate::AofError::config(
                    "Tiered mode requires at least one agent with a tier assignment".to_string(),
                ));
            }
            // Ensure we have at least 2 tiers for meaningful tiered execution
            if tiers.len() < 2 {
                // This is a warning, not an error - single tier still works
                tracing::warn!(
                    "Tiered mode with only one tier ({}) - consider using peer mode instead",
                    tiers[0]
                );
            }
        }

        // Validate agent configurations
        for agent in &self.spec.agents {
            if agent.config.is_none() && agent.spec.is_none() {
                return Err(crate::AofError::config(format!(
                    "Agent '{}' must have either 'config' or 'spec' defined",
                    agent.name
                )));
            }
        }

        Ok(())
    }

    /// Get unique tiers in the fleet (sorted ascending)
    pub fn get_tiers(&self) -> Vec<u32> {
        let mut tiers: Vec<u32> = self
            .spec
            .agents
            .iter()
            .map(|a| a.tier.unwrap_or(1))
            .collect::<std::collections::HashSet<_>>()
            .into_iter()
            .collect();
        tiers.sort();
        tiers
    }

    /// Get agents for a specific tier
    pub fn get_agents_by_tier(&self, tier: u32) -> Vec<&FleetAgent> {
        self.spec
            .agents
            .iter()
            .filter(|a| a.tier.unwrap_or(1) == tier)
            .collect()
    }

    /// Get agent weight (for weighted consensus)
    pub fn get_agent_weight(&self, agent_name: &str) -> f32 {
        // First check agent-level weight
        if let Some(agent) = self.get_agent(agent_name) {
            if let Some(weight) = agent.weight {
                return weight;
            }
        }
        // Then check consensus config weights
        if let Some(ref consensus) = self.spec.coordination.consensus {
            if let Some(weight) = consensus.weights.get(agent_name) {
                return *weight;
            }
        }
        // Default weight
        1.0
    }
}

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

    #[test]
    fn test_parse_fleet_yaml() {
        let yaml = r#"
apiVersion: aof.dev/v1
kind: AgentFleet
metadata:
  name: incident-team
  labels:
    team: sre
spec:
  agents:
    - name: detector
      config: ./agents/detector.yaml
      replicas: 2
      role: worker
    - name: analyzer
      config: ./agents/analyzer.yaml
      replicas: 1
      role: specialist
    - name: coordinator
      config: ./agents/coordinator.yaml
      replicas: 1
      role: manager
  coordination:
    mode: hierarchical
    manager: coordinator
    distribution: skill-based
  shared:
    memory:
      type: redis
      url: redis://localhost:6379
    tools:
      - mcp-server: kubectl-ai
"#;

        let fleet = AgentFleet::from_yaml(yaml).unwrap();
        assert_eq!(fleet.metadata.name, "incident-team");
        assert_eq!(fleet.spec.agents.len(), 3);
        assert_eq!(fleet.spec.coordination.mode, CoordinationMode::Hierarchical);
        assert_eq!(fleet.total_replicas(), 4);

        let manager = fleet.get_manager().unwrap();
        assert_eq!(manager.name, "coordinator");
    }

    #[test]
    fn test_peer_mode_fleet() {
        let yaml = r#"
apiVersion: aof.dev/v1
kind: AgentFleet
metadata:
  name: review-team
spec:
  agents:
    - name: reviewer-1
      config: ./reviewer.yaml
    - name: reviewer-2
      config: ./reviewer.yaml
    - name: reviewer-3
      config: ./reviewer.yaml
  coordination:
    mode: peer
    distribution: round-robin
    consensus:
      algorithm: majority
      minVotes: 2
"#;

        let fleet = AgentFleet::from_yaml(yaml).unwrap();
        assert_eq!(fleet.spec.coordination.mode, CoordinationMode::Peer);
        assert!(fleet.spec.coordination.consensus.is_some());
    }

    #[test]
    fn test_fleet_validation() {
        // Valid fleet
        let yaml = r#"
apiVersion: aof.dev/v1
kind: AgentFleet
metadata:
  name: test-fleet
spec:
  agents:
    - name: agent-1
      config: ./agent.yaml
"#;
        let fleet = AgentFleet::from_yaml(yaml).unwrap();
        assert!(fleet.validate().is_ok());

        // Invalid: hierarchical without manager
        let yaml = r#"
apiVersion: aof.dev/v1
kind: AgentFleet
metadata:
  name: test-fleet
spec:
  agents:
    - name: agent-1
      config: ./agent.yaml
  coordination:
    mode: hierarchical
"#;
        let fleet = AgentFleet::from_yaml(yaml).unwrap();
        assert!(fleet.validate().is_err());
    }

    #[test]
    fn test_fleet_state() {
        let mut state = FleetState::new("test-fleet");
        assert_eq!(state.status, FleetStatus::Initializing);

        state.status = FleetStatus::Ready;
        state.metrics.total_agents = 3;
        state.metrics.active_agents = 3;

        assert_eq!(state.metrics.total_agents, 3);
    }

    #[test]
    fn test_tiered_mode_fleet() {
        let yaml = r#"
apiVersion: aof.dev/v1
kind: AgentFleet
metadata:
  name: rca-team
spec:
  agents:
    # Tier 1: Data collectors (cheap models)
    - name: loki-collector
      config: ./agents/loki.yaml
      tier: 1
    - name: prometheus-collector
      config: ./agents/prometheus.yaml
      tier: 1
    - name: k8s-collector
      config: ./agents/k8s.yaml
      tier: 1
    # Tier 2: Reasoning models
    - name: claude-analyzer
      config: ./agents/claude.yaml
      tier: 2
      weight: 2.0
    - name: gemini-analyzer
      config: ./agents/gemini.yaml
      tier: 2
    # Tier 3: Synthesizer
    - name: rca-coordinator
      config: ./agents/coordinator.yaml
      tier: 3
      role: manager
  coordination:
    mode: tiered
    consensus:
      algorithm: weighted
      min_votes: 2
      min_confidence: 0.7
    tiered:
      pass_all_results: true
      final_aggregation: manager_synthesis
"#;

        let fleet = AgentFleet::from_yaml(yaml).unwrap();
        assert_eq!(fleet.metadata.name, "rca-team");
        assert_eq!(fleet.spec.coordination.mode, CoordinationMode::Tiered);

        // Test tier detection
        let tiers = fleet.get_tiers();
        assert_eq!(tiers, vec![1, 2, 3]);

        // Test agents by tier
        let tier1_agents = fleet.get_agents_by_tier(1);
        assert_eq!(tier1_agents.len(), 3);

        let tier2_agents = fleet.get_agents_by_tier(2);
        assert_eq!(tier2_agents.len(), 2);

        let tier3_agents = fleet.get_agents_by_tier(3);
        assert_eq!(tier3_agents.len(), 1);

        // Test agent weights
        assert_eq!(fleet.get_agent_weight("claude-analyzer"), 2.0);
        assert_eq!(fleet.get_agent_weight("gemini-analyzer"), 1.0); // default

        // Validate configuration
        assert!(fleet.validate().is_ok());
    }

    #[test]
    fn test_consensus_algorithms() {
        // Test all consensus algorithm variants parse correctly
        let algorithms = vec![
            ("majority", ConsensusAlgorithm::Majority),
            ("unanimous", ConsensusAlgorithm::Unanimous),
            ("weighted", ConsensusAlgorithm::Weighted),
            ("first_wins", ConsensusAlgorithm::FirstWins),
            ("human_review", ConsensusAlgorithm::HumanReview),
        ];

        for (yaml_value, expected) in algorithms {
            let yaml = format!(r#"
apiVersion: aof.dev/v1
kind: AgentFleet
metadata:
  name: test
spec:
  agents:
    - name: agent-1
      config: ./agent.yaml
  coordination:
    mode: peer
    consensus:
      algorithm: {}
"#, yaml_value);

            let fleet = AgentFleet::from_yaml(&yaml).unwrap();
            assert_eq!(
                fleet.spec.coordination.consensus.as_ref().unwrap().algorithm,
                expected,
                "Failed for algorithm: {}",
                yaml_value
            );
        }
    }

    #[test]
    fn test_weighted_consensus_config() {
        let yaml = r#"
apiVersion: aof.dev/v1
kind: AgentFleet
metadata:
  name: weighted-team
spec:
  agents:
    - name: senior-reviewer
      config: ./reviewer.yaml
      weight: 2.0
    - name: junior-reviewer
      config: ./reviewer.yaml
  coordination:
    mode: peer
    consensus:
      algorithm: weighted
      min_votes: 2
      min_confidence: 0.8
      weights:
        senior-reviewer: 2.0
        junior-reviewer: 1.0
"#;

        let fleet = AgentFleet::from_yaml(yaml).unwrap();
        let consensus = fleet.spec.coordination.consensus.as_ref().unwrap();

        assert_eq!(consensus.algorithm, ConsensusAlgorithm::Weighted);
        assert_eq!(consensus.min_votes, Some(2));
        assert_eq!(consensus.min_confidence, Some(0.8));
        assert_eq!(consensus.weights.get("senior-reviewer"), Some(&2.0));
        assert_eq!(consensus.weights.get("junior-reviewer"), Some(&1.0));

        // Test weight lookup via fleet method
        assert_eq!(fleet.get_agent_weight("senior-reviewer"), 2.0);
    }

    #[test]
    fn test_human_review_consensus() {
        let yaml = r#"
apiVersion: aof.dev/v1
kind: AgentFleet
metadata:
  name: critical-review
spec:
  agents:
    - name: analyzer-1
      config: ./analyzer.yaml
    - name: analyzer-2
      config: ./analyzer.yaml
  coordination:
    mode: peer
    consensus:
      algorithm: human_review
      timeout_ms: 300000
      min_confidence: 0.9
"#;

        let fleet = AgentFleet::from_yaml(yaml).unwrap();
        let consensus = fleet.spec.coordination.consensus.as_ref().unwrap();

        assert_eq!(consensus.algorithm, ConsensusAlgorithm::HumanReview);
        assert_eq!(consensus.timeout_ms, Some(300000));
        assert_eq!(consensus.min_confidence, Some(0.9));
    }

    #[test]
    fn test_all_coordination_modes() {
        let modes = vec![
            ("peer", CoordinationMode::Peer),
            ("hierarchical", CoordinationMode::Hierarchical),
            ("pipeline", CoordinationMode::Pipeline),
            ("swarm", CoordinationMode::Swarm),
            ("tiered", CoordinationMode::Tiered),
            ("deep", CoordinationMode::Deep),
        ];

        for (yaml_value, expected) in modes {
            let yaml = format!(r#"
apiVersion: aof.dev/v1
kind: AgentFleet
metadata:
  name: test
spec:
  agents:
    - name: agent-1
      config: ./agent.yaml
      role: manager
      tier: 1
    - name: agent-2
      config: ./agent.yaml
      tier: 2
  coordination:
    mode: {}
    manager: agent-1
"#, yaml_value);

            let fleet = AgentFleet::from_yaml(&yaml).unwrap();
            assert_eq!(
                fleet.spec.coordination.mode,
                expected,
                "Failed for mode: {}",
                yaml_value
            );
        }
    }

    #[test]
    fn test_tiered_config() {
        let yaml = r#"
apiVersion: aof.dev/v1
kind: AgentFleet
metadata:
  name: tiered-team
spec:
  agents:
    - name: collector
      config: ./collector.yaml
      tier: 1
    - name: reasoner
      config: ./reasoner.yaml
      tier: 2
  coordination:
    mode: tiered
    tiered:
      pass_all_results: true
      final_aggregation: merge
      tier_consensus:
        "1":
          algorithm: first_wins
        "2":
          algorithm: majority
          min_votes: 1
"#;

        let fleet = AgentFleet::from_yaml(yaml).unwrap();
        let tiered = fleet.spec.coordination.tiered.as_ref().unwrap();

        assert!(tiered.pass_all_results);
        assert_eq!(tiered.final_aggregation, FinalAggregation::Merge);

        let tier1_consensus = tiered.tier_consensus.get("1").unwrap();
        assert_eq!(tier1_consensus.algorithm, ConsensusAlgorithm::FirstWins);

        let tier2_consensus = tiered.tier_consensus.get("2").unwrap();
        assert_eq!(tier2_consensus.algorithm, ConsensusAlgorithm::Majority);
    }

    #[test]
    fn test_final_aggregation_modes() {
        let modes = vec![
            ("consensus", FinalAggregation::Consensus),
            ("merge", FinalAggregation::Merge),
            ("manager_synthesis", FinalAggregation::ManagerSynthesis),
        ];

        for (yaml_value, expected) in modes {
            let yaml = format!(r#"
apiVersion: aof.dev/v1
kind: AgentFleet
metadata:
  name: test
spec:
  agents:
    - name: agent-1
      config: ./agent.yaml
      tier: 1
    - name: agent-2
      config: ./agent.yaml
      tier: 2
  coordination:
    mode: tiered
    tiered:
      final_aggregation: {}
"#, yaml_value);

            let fleet = AgentFleet::from_yaml(&yaml).unwrap();
            let tiered = fleet.spec.coordination.tiered.as_ref().unwrap();
            assert_eq!(
                tiered.final_aggregation,
                expected,
                "Failed for aggregation: {}",
                yaml_value
            );
        }
    }

    #[test]
    fn test_existing_simple_fleet_unchanged() {
        // Ensure existing simple fleet configurations still work
        let yaml = r#"
apiVersion: aof.dev/v1
kind: AgentFleet
metadata:
  name: simple-fleet
spec:
  agents:
    - name: worker
      config: ./worker.yaml
"#;

        let fleet = AgentFleet::from_yaml(yaml).unwrap();
        assert_eq!(fleet.spec.coordination.mode, CoordinationMode::Peer); // default
        assert!(fleet.validate().is_ok());
    }

    #[test]
    fn test_pipeline_mode_unchanged() {
        let yaml = r#"
apiVersion: aof.dev/v1
kind: AgentFleet
metadata:
  name: pipeline-fleet
spec:
  agents:
    - name: stage1
      config: ./stage1.yaml
    - name: stage2
      config: ./stage2.yaml
    - name: stage3
      config: ./stage3.yaml
  coordination:
    mode: pipeline
"#;

        let fleet = AgentFleet::from_yaml(yaml).unwrap();
        assert_eq!(fleet.spec.coordination.mode, CoordinationMode::Pipeline);
        assert!(fleet.validate().is_ok());
    }

    #[test]
    fn test_deep_mode_config() {
        let yaml = r#"
apiVersion: aof.dev/v1
kind: AgentFleet
metadata:
  name: deep-fleet
spec:
  agents:
    - name: investigator
      spec:
        model: openai:gpt-4
        instructions: "Deep investigator"
        tools: []
  coordination:
    mode: deep
    deep:
      max_iterations: 15
      planning: true
      memory: true
      planner_model: anthropic:claude-sonnet-4
      planner_prompt: "Generate investigation steps."
      synthesizer_prompt: "Synthesize findings into a report."
"#;

        let fleet = AgentFleet::from_yaml(yaml).unwrap();
        assert_eq!(fleet.spec.coordination.mode, CoordinationMode::Deep);

        let deep_config = fleet.spec.coordination.deep.as_ref().unwrap();
        assert_eq!(deep_config.max_iterations, 15);
        assert!(deep_config.planning);
        assert!(deep_config.memory);
        assert_eq!(deep_config.planner_model.as_deref(), Some("anthropic:claude-sonnet-4"));
        assert!(deep_config.planner_prompt.is_some());
        assert!(deep_config.synthesizer_prompt.is_some());
    }

    #[test]
    fn test_deep_mode_defaults() {
        let yaml = r#"
apiVersion: aof.dev/v1
kind: AgentFleet
metadata:
  name: deep-fleet-defaults
spec:
  agents:
    - name: agent
      config: ./agent.yaml
  coordination:
    mode: deep
"#;

        let fleet = AgentFleet::from_yaml(yaml).unwrap();
        assert_eq!(fleet.spec.coordination.mode, CoordinationMode::Deep);

        // Deep config should have defaults when not specified
        let deep_config = fleet.spec.coordination.deep.unwrap_or_default();
        assert_eq!(deep_config.max_iterations, 10); // default
        assert!(deep_config.planning); // default true
        assert!(deep_config.memory); // default true
        assert!(deep_config.planner_model.is_none());
        assert!(deep_config.planner_prompt.is_none());
        assert!(deep_config.synthesizer_prompt.is_none());
    }
}